code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
/* Copyright (C) 2001 artofcode LLC. All rights reserved.
This software is provided AS-IS with no warranty, either express or
implied.
This software is distributed under license and may not be copied,
modified or distributed except as expressly authorized under the terms
of the license contained in the file LICENSE in this distribution.
For more information about licensing, please refer to
http://www.ghostscript.com/licensing/. For information on
commercial licensing, go to http://www.artifex.com/licensing/ or
contact Artifex Software, Inc., 101 Lucas Valley Road #110,
San Rafael, CA 94903, U.S.A., +1(415)492-9861.
*/
/* $Id: gp_stdia.c,v 1.5 2002/02/21 22:24:52 giles Exp $ */
/* Read stdin on platforms that support unbuffered read. */
/* We want unbuffered for console input and pipes. */
#include "stdio_.h"
#include "time_.h"
#include "unistd_.h"
#include "gx.h"
#include "gp.h"
/* Read bytes from stdin, unbuffered if possible. */
int gp_stdin_read(char *buf, int len, int interactive, FILE *f)
{
return read(fileno(f), buf, len);
}
| Java |
## Copyright (C) 2007-2012 Red Hat, Inc., Bryn M. Reeves <bmr@redhat.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.
from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin
class SysVIPC(Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin):
"""SysV IPC related information
"""
plugin_name = "sysvipc"
def setup(self):
self.add_copy_specs([
"/proc/sysvipc/msg",
"/proc/sysvipc/sem",
"/proc/sysvipc/shm"
])
self.add_cmd_output("ipcs")
# vim: et ts=4 sw=4
| Java |
/* This file was generated by SableCC (http://www.sablecc.org/). */
package se.sics.kola.node;
import se.sics.kola.analysis.*;
@SuppressWarnings("nls")
public final class AClassFieldAccess extends PFieldAccess
{
private PClassName _className_;
private TIdentifier _identifier_;
public AClassFieldAccess()
{
// Constructor
}
public AClassFieldAccess(
@SuppressWarnings("hiding") PClassName _className_,
@SuppressWarnings("hiding") TIdentifier _identifier_)
{
// Constructor
setClassName(_className_);
setIdentifier(_identifier_);
}
@Override
public Object clone()
{
return new AClassFieldAccess(
cloneNode(this._className_),
cloneNode(this._identifier_));
}
@Override
public void apply(Switch sw)
{
((Analysis) sw).caseAClassFieldAccess(this);
}
public PClassName getClassName()
{
return this._className_;
}
public void setClassName(PClassName node)
{
if(this._className_ != null)
{
this._className_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._className_ = node;
}
public TIdentifier getIdentifier()
{
return this._identifier_;
}
public void setIdentifier(TIdentifier node)
{
if(this._identifier_ != null)
{
this._identifier_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._identifier_ = node;
}
@Override
public String toString()
{
return ""
+ toString(this._className_)
+ toString(this._identifier_);
}
@Override
void removeChild(@SuppressWarnings("unused") Node child)
{
// Remove child
if(this._className_ == child)
{
this._className_ = null;
return;
}
if(this._identifier_ == child)
{
this._identifier_ = null;
return;
}
throw new RuntimeException("Not a child.");
}
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._className_ == oldChild)
{
setClassName((PClassName) newChild);
return;
}
if(this._identifier_ == oldChild)
{
setIdentifier((TIdentifier) newChild);
return;
}
throw new RuntimeException("Not a child.");
}
}
| Java |
package com.pingdynasty.blipbox;
import java.util.Map;
import java.util.HashMap;
import javax.sound.midi.*;
import com.pingdynasty.midi.ScaleMapper;
import org.apache.log4j.Logger;
public class MidiOutputEventHandler extends MultiModeKeyPressManager {
private static final Logger log = Logger.getLogger(MidiOutputEventHandler.class);
private static final int OCTAVE_SHIFT = 6;
private MidiPlayer midiPlayer;
private int lastNote = 0;
public class MidiConfigurationMode extends ConfigurationMode {
private ScaleMapper mapper;
private int basenote = 40;
public MidiConfigurationMode(String name, String follow){
super(name, follow);
mapper = new ScaleMapper();
mapper.setScale("Mixolydian Mode");
// setScale("Chromatic Scale");
// setScale("C Major");
// setScale("Dorian Mode");
}
public ScaleMapper getScaleMapper(){
return mapper;
}
public int getBaseNote(){
return basenote;
}
public void setBaseNote(int basenote){
this.basenote = basenote;
}
}
public ConfigurationMode createConfigurationMode(String mode, String follow){
return new MidiConfigurationMode(mode, follow);
}
public ScaleMapper getScaleMapper(){
MidiConfigurationMode mode = (MidiConfigurationMode)getCurrentConfigurationMode();
return mode.getScaleMapper();
}
public ScaleMapper getScaleMapper(String mode){
MidiConfigurationMode config = (MidiConfigurationMode)getConfigurationMode(mode);
return config.getScaleMapper();
}
public int getBaseNote(){
MidiConfigurationMode mode = (MidiConfigurationMode)getCurrentConfigurationMode();
return mode.getBaseNote();
}
public void setBaseNote(int basenote){
MidiConfigurationMode mode = (MidiConfigurationMode)getCurrentConfigurationMode();
mode.setBaseNote(basenote);
}
public void setBaseNote(String modename, int basenote){
MidiConfigurationMode mode = (MidiConfigurationMode)getConfigurationMode(modename);
mode.setBaseNote(basenote);
}
public void holdOff(){
super.holdOff();
sendMidiNoteOff(lastNote);
}
public void init(){
super.init();
setSensorEventHandler("Cross", SensorType.BUTTON2_SENSOR, new OctaveShiftUpEventHandler());
setSensorEventHandler("Cross", SensorType.BUTTON3_SENSOR, new OctaveShiftDownEventHandler());
setSensorEventHandler("Criss", SensorType.BUTTON2_SENSOR, new OctaveShiftUpEventHandler());
setSensorEventHandler("Criss", SensorType.BUTTON3_SENSOR, new OctaveShiftDownEventHandler());
}
public class OctaveShiftUpEventHandler implements SensorEventHandler {
public void sensorChange(SensorDefinition sensor){
if(sensor.value != 0){
int basenote = getBaseNote();
log.debug("octave up");
basenote += OCTAVE_SHIFT;
if(basenote + OCTAVE_SHIFT <= 127)
setBaseNote(basenote);
log.debug("new basenote "+basenote);
}
}
}
public class OctaveShiftDownEventHandler implements SensorEventHandler {
public void sensorChange(SensorDefinition sensor){
if(sensor.value != 0){
int basenote = getBaseNote();
log.debug("octave down");
basenote -= OCTAVE_SHIFT;
if(basenote > 0)
setBaseNote(basenote);
log.debug("new basenote "+basenote);
}
}
}
public class BaseNoteChangeEventHandler implements SensorEventHandler {
private int min, max;
public BaseNoteChangeEventHandler(){
this(0, 127);
}
public BaseNoteChangeEventHandler(int min, int max){
this.min = min;
this.max = max;
}
public void sensorChange(SensorDefinition sensor){
int basenote = sensor.scale(min, max);
log.debug("basenote: "+basenote);
setBaseNote(basenote);
}
}
public class ScaleChangeEventHandler implements SensorEventHandler {
public void sensorChange(SensorDefinition sensor){
ScaleMapper mapper = getScaleMapper();
int val = sensor.scale(mapper.getScaleNames().length);
if(val < mapper.getScaleNames().length){
mapper.setScale(val);
log.debug("set scale "+mapper.getScaleNames()[val]);
}
}
}
public class ControlChangeEventHandler implements SensorEventHandler {
private int from;
private int to;
private int cc;
public ControlChangeEventHandler(int cc){
this(cc, 0, 127);
}
public ControlChangeEventHandler(int cc, int from, int to){
this.from = from;
this.to = to;
this.cc = cc;
}
public void sensorChange(SensorDefinition sensor){
int val = sensor.scale(from, to);
sendMidiCC(cc, val);
}
}
public class NonRegisteredParameterEventHandler implements SensorEventHandler {
private int from;
private int to;
private int cc;
public NonRegisteredParameterEventHandler(int cc, int from, int to){
this.from = from;
this.to = to;
this.cc = cc;
}
public void sensorChange(SensorDefinition sensor){
int val = sensor.scale(from, to);
sendMidiNRPN(cc, val);
}
}
public class PitchBendEventHandler implements SensorEventHandler {
private int from;
private int to;
public PitchBendEventHandler(){
this(-8191, 8192);
}
public PitchBendEventHandler(int from, int to){
this.from = from;
this.to = to;
}
public void sensorChange(SensorDefinition sensor){
int val = sensor.scale(from, to);
sendMidiPitchBend(val);
}
}
public class NotePlayer implements KeyEventHandler {
private int lastnote;
public void sensorChange(SensorDefinition sensor){}
protected int getVelocity(int row){
// int velocity = ((row+1)*127/8);
// int velocity = (row*127/8)+1;
int velocity = ((row+1)*127/9);
return velocity;
}
public void keyDown(int col, int row){
lastNote = getScaleMapper().getNote(col+getBaseNote());
sendMidiNoteOn(lastNote, getVelocity(row));
}
public void keyUp(int col, int row){
sendMidiNoteOff(lastNote);
}
public void keyChange(int oldCol, int oldRow, int newCol, int newRow){
int newNote = getScaleMapper().getNote(newCol+getBaseNote());
if(newNote != lastNote){
sendMidiNoteOff(lastNote);
sendMidiNoteOn(newNote, getVelocity(newRow));
}
lastNote = newNote;
}
}
public MidiOutputEventHandler(BlipBox sender){
super(sender);
}
public void configureControlChange(String mode, SensorType type, int channel, int cc, int min, int max){
log.debug("Setting "+mode+":"+type+" to CC "+cc+" ("+min+"-"+max+")");
setSensorEventHandler(mode, type, new ControlChangeEventHandler(cc, min, max));
}
public void configureNRPN(String mode, SensorType type, int channel, int cc, int min, int max){
log.debug("Setting "+mode+":"+type+" to NRPN "+cc+" ("+min+"-"+max+")");
setSensorEventHandler(mode, type, new NonRegisteredParameterEventHandler(cc, min, max));
}
public void configurePitchBend(String mode, SensorType type, int channel, int min, int max){
setSensorEventHandler(mode, type, new PitchBendEventHandler(min, max));
}
public void configureBaseNoteChange(String mode, SensorType type, int min, int max){
log.debug("Setting "+mode+":"+type+" to control base note");
setSensorEventHandler(mode, type, new BaseNoteChangeEventHandler(min, max));
}
public void configureScaleChange(String mode, SensorType type){
log.debug("Setting "+mode+":"+type+" to control scale changes");
setSensorEventHandler(mode, type, new ScaleChangeEventHandler());
}
public void configureNotePlayer(String mode, boolean notes, boolean pb, boolean at){
log.debug("Setting "+mode+" mode to play notes ("+notes+") pitch bend ("+pb+") aftertouch ("+at+")");
if(notes){
setKeyEventHandler(mode, new NotePlayer());
}else{
setKeyEventHandler(mode, null);
}
// todo: honour pb and at
}
// public String[] getScaleNames(){
// return mapper.getScaleNames();
// }
// public void setScale(int index){
// mapper.setScale(index);
// }
public String getCurrentScale(){
ScaleMapper mapper = getScaleMapper();
return mapper.getScaleNames()[mapper.getScaleIndex()];
}
public void setMidiPlayer(MidiPlayer midiPlayer){
this.midiPlayer = midiPlayer;
}
public void sendMidiNoteOn(int note, int velocity){
log.debug("note on:\t "+note+"\t "+velocity);
if(note > 127 || note < 0){
log.error("MIDI note on "+note+"/"+velocity+" value out of range");
return;
}
if(velocity > 127 || velocity < 0){
log.error("MIDI note on "+note+"/"+velocity+" value out of range");
velocity = velocity < 0 ? 0 : 127;
}
try {
if(midiPlayer != null)
midiPlayer.noteOn(note, velocity);
}catch(Exception exc){
log.error(exc, exc);
}
}
public void sendMidiNoteOff(int note){
// note = mapper.getNote(note);
log.debug("note off:\t "+note);
if(note > 127 || note < 0){
log.error("MIDI note off "+note+" value out of range");
return;
}
try {
if(midiPlayer != null)
midiPlayer.noteOff(note);
}catch(Exception exc){
log.error(exc, exc);
}
}
public void sendMidiNRPN(int parameter, int value){
// log.debug("nrpn ("+parameter+") :\t "+value);
sendMidiCC(99, 3);
sendMidiCC(98, parameter & 0x7f); // NRPN LSB
sendMidiCC(6, value);
// sendMidiCC(99, parameter >> 7); // NRPN MSB
// sendMidiCC(98, parameter & 0x7f); // NRPN LSB
// sendMidiCC(6, value >> 7); // Data Entry MSB
// if((value & 0x7f) != 0)
// sendMidiCC(38, value & 0x7f); // Data Entry LSB
}
public void sendMidiCC(int cc, int value){
// log.debug("midi cc:\t "+cc+"\t "+value);
if(value > 127 || value < 0){
log.error("MIDI CC "+cc+" value out of range: "+value);
return;
}
try {
if(midiPlayer != null)
midiPlayer.controlChange(cc, value);
}catch(Exception exc){
log.error(exc, exc);
}
}
public void sendMidiPitchBend(int degree){
// send midi pitch bend in the range -8192 to 8191 inclusive
if(degree < -8192 || degree > 8191){
log.error("MIDI pitch bend value out of range: "+degree);
return;
}
// setPitchBend() expects a value in the range 0 to 16383
degree += 8192;
try {
if(midiPlayer != null)
midiPlayer.pitchBend(degree);
}catch(Exception exc){
log.error(exc, exc);
}
}
public void setChannel(int channel){
midiPlayer.setChannel(channel);
}
public class SensitiveNotePlayer implements KeyEventHandler {
private int lastnote;
private int velocity;
// todo : velocity could be set by row rather than sensor position
public void sensorChange(SensorDefinition sensor){
velocity = sensor.scale(127);
}
public void keyDown(int col, int row){
lastNote = getScaleMapper().getNote(col+getBaseNote());
sendMidiNoteOn(lastNote, velocity);
}
public void keyUp(int col, int row){
sendMidiNoteOff(lastNote);
}
public void keyChange(int oldCol, int oldRow, int newCol, int newRow){
int newNote = getScaleMapper().getNote(newCol+getBaseNote());
if(newNote != lastNote){
sendMidiNoteOff(lastNote);
sendMidiNoteOn(newNote, velocity);
// }else{
// // todo: aftertouch, bend
}
lastNote = newNote;
}
}
} | Java |
/*
* Copyright 2004-2007 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 4853450
* @summary EnumType tests
* @library ../../lib
* @compile -source 1.5 EnumTyp.java
* @run main EnumTyp
*/
import java.util.*;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;
public class EnumTyp extends Tester {
public static void main(String[] args) {
(new EnumTyp()).run();
}
// Declarations used by tests
enum Suit {
CIVIL,
CRIMINAL
}
private Suit s;
private EnumType e; // an enum type
protected void init() {
e = (EnumType) getField("s").getType();
}
// TypeMirror methods
@Test(result="enum")
Collection<String> accept() {
final Collection<String> res = new ArrayList<String>();
e.accept(new SimpleTypeVisitor() {
public void visitTypeMirror(TypeMirror t) {
res.add("type");
}
public void visitReferenceType(ReferenceType t) {
res.add("ref type");
}
public void visitClassType(ClassType t) {
res.add("class");
}
public void visitEnumType(EnumType t) {
res.add("enum");
}
public void visitInterfaceType(InterfaceType t) {
res.add("interface");
}
});
return res;
}
// EnumType method
@Test(result="EnumTyp.Suit")
EnumDeclaration getDeclaration() {
return e.getDeclaration();
}
}
| Java |
/*----------------------------------------------------------------------------
* U S B - K e r n e l
*----------------------------------------------------------------------------
* Name: usbreg_STM32F10x.h
* Purpose: USB Hardware Layer Definitions for ST STM32F10x
* Version: V1.20
*----------------------------------------------------------------------------
* This file is part of the uVision/ARM development tools.
* This software may only be used under the terms of a valid, current,
* end user licence from KEIL for a compatible version of KEIL software
* development tools. Nothing else gives you the right to use this software.
*
* This software is supplied "AS IS" without warranties of any kind.
*
* Copyright (c) 2009-2011 Keil - An ARM Company. All rights reserved.
*----------------------------------------------------------------------------*/
#ifndef __USBREG_STM32F10x_H
#define __USBREG_STM32F10x_H
#define REG(x) (*((volatile unsigned int *)(x)))
#define USB_BASE_ADDR 0x40005C00 /* USB Registers Base Address */
#define USB_PMA_ADDR 0x40006000 /* USB Packet Memory Area Address */
/* Common Registers */
#define CNTR REG(USB_BASE_ADDR + 0x40) /* Control Register */
#define ISTR REG(USB_BASE_ADDR + 0x44) /* Interrupt Status Register */
#define FNR REG(USB_BASE_ADDR + 0x48) /* Frame Number Register */
#define DADDR REG(USB_BASE_ADDR + 0x4C) /* Device Address Register */
#define BTABLE REG(USB_BASE_ADDR + 0x50) /* Buffer Table Address Register */
/* CNTR: Control Register Bit Definitions */
#define CNTR_CTRM 0x8000 /* Correct Transfer Interrupt Mask */
#define CNTR_PMAOVRM 0x4000 /* Packet Memory Aerea Over/underrun Interrupt Mask */
#define CNTR_ERRM 0x2000 /* Error Interrupt Mask */
#define CNTR_WKUPM 0x1000 /* Wake-up Interrupt Mask */
#define CNTR_SUSPM 0x0800 /* Suspend Mode Interrupt Mask */
#define CNTR_RESETM 0x0400 /* USB Reset Interrupt Mask */
#define CNTR_SOFM 0x0200 /* Start of Frame Interrupt Mask */
#define CNTR_ESOFM 0x0100 /* Expected Start of Frame Interrupt Mask */
#define CNTR_RESUME 0x0010 /* Resume Request */
#define CNTR_FSUSP 0x0008 /* Force Suspend */
#define CNTR_LPMODE 0x0004 /* Low-power Mode */
#define CNTR_PDWN 0x0002 /* Power Down */
#define CNTR_FRES 0x0001 /* Force USB Reset */
/* ISTR: Interrupt Status Register Bit Definitions */
#define ISTR_CTR 0x8000 /* Correct Transfer */
#define ISTR_PMAOVR 0x4000 /* Packet Memory Aerea Over/underrun */
#define ISTR_ERR 0x2000 /* Error */
#define ISTR_WKUP 0x1000 /* Wake-up */
#define ISTR_SUSP 0x0800 /* Suspend Mode */
#define ISTR_RESET 0x0400 /* USB Reset */
#define ISTR_SOF 0x0200 /* Start of Frame */
#define ISTR_ESOF 0x0100 /* Expected Start of Frame */
#define ISTR_DIR 0x0010 /* Direction of Transaction */
#define ISTR_EP_ID 0x000F /* EndPoint Identifier */
/* FNR: Frame Number Register Bit Definitions */
#define FNR_RXDP 0x8000 /* D+ Data Line Status */
#define FNR_RXDM 0x4000 /* D- Data Line Status */
#define FNR_LCK 0x2000 /* Locked */
#define FNR_LSOF 0x1800 /* Lost SOF */
#define FNR_FN 0x07FF /* Frame Number */
/* DADDR: Device Address Register Bit Definitions */
#define DADDR_EF 0x0080 /* Enable Function */
#define DADDR_ADD 0x007F /* Device Address */
/* EndPoint Registers */
#define EPxREG(x) REG(USB_BASE_ADDR + 4*(x))
/* EPxREG: EndPoint Registers Bit Definitions */
#define EP_CTR_RX 0x8000 /* Correct RX Transfer */
#define EP_DTOG_RX 0x4000 /* RX Data Toggle */
#define EP_STAT_RX 0x3000 /* RX Status */
#define EP_SETUP 0x0800 /* EndPoint Setup */
#define EP_TYPE 0x0600 /* EndPoint Type */
#define EP_KIND 0x0100 /* EndPoint Kind */
#define EP_CTR_TX 0x0080 /* Correct TX Transfer */
#define EP_DTOG_TX 0x0040 /* TX Data Toggle */
#define EP_STAT_TX 0x0030 /* TX Status */
#define EP_EA 0x000F /* EndPoint Address */
/* EndPoint Register Mask (No Toggle Fields) */
#define EP_MASK (EP_CTR_RX|EP_SETUP|EP_TYPE|EP_KIND|EP_CTR_TX|EP_EA)
/* EP_TYPE: EndPoint Types */
#define EP_BULK 0x0000 /* BULK EndPoint */
#define EP_CONTROL 0x0200 /* CONTROL EndPoint */
#define EP_ISOCHRONOUS 0x0400 /* ISOCHRONOUS EndPoint */
#define EP_INTERRUPT 0x0600 /* INTERRUPT EndPoint */
/* EP_KIND: EndPoint Kind */
#define EP_DBL_BUF EP_KIND /* Double Buffer for Bulk Endpoint */
#define EP_STATUS_OUT EP_KIND /* Status Out for Control Endpoint */
/* EP_STAT_TX: TX Status */
#define EP_TX_DIS 0x0000 /* Disabled */
#define EP_TX_STALL 0x0010 /* Stalled */
#define EP_TX_NAK 0x0020 /* NAKed */
#define EP_TX_VALID 0x0030 /* Valid */
/* EP_STAT_RX: RX Status */
#define EP_RX_DIS 0x0000 /* Disabled */
#define EP_RX_STALL 0x1000 /* Stalled */
#define EP_RX_NAK 0x2000 /* NAKed */
#define EP_RX_VALID 0x3000 /* Valid */
/* Endpoint Buffer Descriptor */
typedef struct _EP_BUF_DSCR {
U32 ADDR_TX;
U32 COUNT_TX;
U32 ADDR_RX;
U32 COUNT_RX;
} EP_BUF_DSCR;
#define EP_ADDR_MASK 0xFFFE /* Address Mask */
#define EP_COUNT_MASK 0x03FF /* Count Mask */
#endif /* __USBREG_STM32F10x_H */
| Java |
/* Qualcomm Crypto Engine driver.
*
* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) "QCE50: %s: " fmt, __func__
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mod_devicetable.h>
#include <linux/device.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/dma-mapping.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <linux/delay.h>
#include <linux/crypto.h>
#include <linux/qcedev.h>
#include <linux/bitops.h>
#include <crypto/hash.h>
#include <crypto/sha.h>
#include <mach/dma.h>
#include <mach/clk.h>
#include <mach/socinfo.h>
#include <mach/qcrypto.h>
#include "qce.h"
#include "qce50.h"
#include "qcryptohw_50.h"
#define CRYPTO_CONFIG_RESET 0xE001F
#define QCE_MAX_NUM_DSCR 0x500
#define QCE_SECTOR_SIZE 0x200
static DEFINE_MUTEX(bam_register_cnt);
struct bam_registration_info {
uint32_t handle;
uint32_t cnt;
};
static struct bam_registration_info bam_registry;
static bool ce_bam_registered;
/*
* CE HW device structure.
* Each engine has an instance of the structure.
* Each engine can only handle one crypto operation at one time. It is up to
* the sw above to ensure single threading of operation on an engine.
*/
struct qce_device {
struct device *pdev; /* Handle to platform_device structure */
unsigned char *coh_vmem; /* Allocated coherent virtual memory */
dma_addr_t coh_pmem; /* Allocated coherent physical memory */
int memsize; /* Memory allocated */
int is_shared; /* CE HW is shared */
bool support_cmd_dscr;
bool support_hw_key;
void __iomem *iobase; /* Virtual io base of CE HW */
unsigned int phy_iobase; /* Physical io base of CE HW */
struct clk *ce_core_src_clk; /* Handle to CE src clk*/
struct clk *ce_core_clk; /* Handle to CE clk */
struct clk *ce_clk; /* Handle to CE clk */
struct clk *ce_bus_clk; /* Handle to CE AXI clk*/
qce_comp_func_ptr_t qce_cb; /* qce callback function pointer */
int assoc_nents;
int ivsize;
int authsize;
int src_nents;
int dst_nents;
dma_addr_t phy_iv_in;
unsigned char dec_iv[16];
int dir;
void *areq;
enum qce_cipher_mode_enum mode;
struct qce_ce_cfg_reg_setting reg;
struct ce_sps_data ce_sps;
};
/* Standard initialization vector for SHA-1, source: FIPS 180-2 */
static uint32_t _std_init_vector_sha1[] = {
0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0
};
/* Standard initialization vector for SHA-256, source: FIPS 180-2 */
static uint32_t _std_init_vector_sha256[] = {
0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,
0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19
};
static void _byte_stream_to_net_words(uint32_t *iv, unsigned char *b,
unsigned int len)
{
unsigned n;
n = len / sizeof(uint32_t) ;
for (; n > 0; n--) {
*iv = ((*b << 24) & 0xff000000) |
(((*(b+1)) << 16) & 0xff0000) |
(((*(b+2)) << 8) & 0xff00) |
(*(b+3) & 0xff);
b += sizeof(uint32_t);
iv++;
}
n = len % sizeof(uint32_t);
if (n == 3) {
*iv = ((*b << 24) & 0xff000000) |
(((*(b+1)) << 16) & 0xff0000) |
(((*(b+2)) << 8) & 0xff00) ;
} else if (n == 2) {
*iv = ((*b << 24) & 0xff000000) |
(((*(b+1)) << 16) & 0xff0000) ;
} else if (n == 1) {
*iv = ((*b << 24) & 0xff000000) ;
}
}
static void _byte_stream_swap_to_net_words(uint32_t *iv, unsigned char *b,
unsigned int len)
{
unsigned i, j;
unsigned char swap_iv[AES_IV_LENGTH];
memset(swap_iv, 0, AES_IV_LENGTH);
for (i = (AES_IV_LENGTH-len), j = len-1; i < AES_IV_LENGTH; i++, j--)
swap_iv[i] = b[j];
_byte_stream_to_net_words(iv, swap_iv, AES_IV_LENGTH);
}
static int count_sg(struct scatterlist *sg, int nbytes)
{
int i;
for (i = 0; nbytes > 0; i++, sg = scatterwalk_sg_next(sg))
nbytes -= sg->length;
return i;
}
static int qce_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
enum dma_data_direction direction)
{
int i;
for (i = 0; i < nents; ++i) {
dma_map_sg(dev, sg, 1, direction);
sg = scatterwalk_sg_next(sg);
}
return nents;
}
static int qce_dma_unmap_sg(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction direction)
{
int i;
for (i = 0; i < nents; ++i) {
dma_unmap_sg(dev, sg, 1, direction);
sg = scatterwalk_sg_next(sg);
}
return nents;
}
static int _probe_ce_engine(struct qce_device *pce_dev)
{
unsigned int rev;
unsigned int maj_rev, min_rev, step_rev;
rev = readl_relaxed(pce_dev->iobase + CRYPTO_VERSION_REG);
mb();
maj_rev = (rev & CRYPTO_CORE_MAJOR_REV_MASK) >> CRYPTO_CORE_MAJOR_REV;
min_rev = (rev & CRYPTO_CORE_MINOR_REV_MASK) >> CRYPTO_CORE_MINOR_REV;
step_rev = (rev & CRYPTO_CORE_STEP_REV_MASK) >> CRYPTO_CORE_STEP_REV;
if (maj_rev != 0x05) {
pr_err("Unknown Qualcomm crypto device at 0x%x, rev %d.%d.%d\n",
pce_dev->phy_iobase, maj_rev, min_rev, step_rev);
return -EIO;
};
pce_dev->ce_sps.minor_version = min_rev;
dev_info(pce_dev->pdev, "Qualcomm Crypto %d.%d.%d device found @0x%x\n",
maj_rev, min_rev, step_rev, pce_dev->phy_iobase);
pce_dev->ce_sps.ce_burst_size = MAX_CE_BAM_BURST_SIZE;
dev_info(pce_dev->pdev,
"IO base, CE = 0x%x\n, "
"Consumer (IN) PIPE %d, "
"Producer (OUT) PIPE %d\n"
"IO base BAM = 0x%x\n"
"BAM IRQ %d\n",
(uint32_t) pce_dev->iobase,
pce_dev->ce_sps.dest_pipe_index,
pce_dev->ce_sps.src_pipe_index,
(uint32_t)pce_dev->ce_sps.bam_iobase,
pce_dev->ce_sps.bam_irq);
return 0;
};
static int _ce_get_hash_cmdlistinfo(struct qce_device *pce_dev,
struct qce_sha_req *sreq,
struct qce_cmdlist_info **cmdplistinfo)
{
struct qce_cmdlistptr_ops *cmdlistptr = &pce_dev->ce_sps.cmdlistptr;
switch (sreq->alg) {
case QCE_HASH_SHA1:
*cmdplistinfo = &cmdlistptr->auth_sha1;
break;
case QCE_HASH_SHA256:
*cmdplistinfo = &cmdlistptr->auth_sha256;
break;
case QCE_HASH_SHA1_HMAC:
*cmdplistinfo = &cmdlistptr->auth_sha1_hmac;
break;
case QCE_HASH_SHA256_HMAC:
*cmdplistinfo = &cmdlistptr->auth_sha256_hmac;
break;
case QCE_HASH_AES_CMAC:
if (sreq->authklen == AES128_KEY_SIZE)
*cmdplistinfo = &cmdlistptr->auth_aes_128_cmac;
else
*cmdplistinfo = &cmdlistptr->auth_aes_256_cmac;
break;
default:
break;
}
return 0;
}
static int _ce_setup_hash(struct qce_device *pce_dev,
struct qce_sha_req *sreq,
struct qce_cmdlist_info *cmdlistinfo)
{
uint32_t auth32[SHA256_DIGEST_SIZE / sizeof(uint32_t)];
uint32_t diglen;
int i;
uint32_t mackey32[SHA_HMAC_KEY_SIZE/sizeof(uint32_t)] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
bool sha1 = false;
struct sps_command_element *pce = NULL;
if ((sreq->alg == QCE_HASH_SHA1_HMAC) ||
(sreq->alg == QCE_HASH_SHA256_HMAC) ||
(sreq->alg == QCE_HASH_AES_CMAC)) {
uint32_t authk_size_in_word = sreq->authklen/sizeof(uint32_t);
_byte_stream_to_net_words(mackey32, sreq->authkey,
sreq->authklen);
/* check for null key. If null, use hw key*/
for (i = 0; i < authk_size_in_word; i++) {
if (mackey32[i] != 0)
break;
}
pce = cmdlistinfo->go_proc;
if (i == authk_size_in_word) {
pce->addr = (uint32_t)(CRYPTO_GOPROC_QC_KEY_REG +
pce_dev->phy_iobase);
} else {
pce->addr = (uint32_t)(CRYPTO_GOPROC_REG +
pce_dev->phy_iobase);
pce = cmdlistinfo->auth_key;
for (i = 0; i < authk_size_in_word; i++, pce++)
pce->data = mackey32[i];
}
}
if (sreq->alg == QCE_HASH_AES_CMAC)
goto go_proc;
/* if not the last, the size has to be on the block boundary */
if (sreq->last_blk == 0 && (sreq->size % SHA256_BLOCK_SIZE))
return -EIO;
switch (sreq->alg) {
case QCE_HASH_SHA1:
case QCE_HASH_SHA1_HMAC:
diglen = SHA1_DIGEST_SIZE;
sha1 = true;
break;
case QCE_HASH_SHA256:
case QCE_HASH_SHA256_HMAC:
diglen = SHA256_DIGEST_SIZE;
break;
default:
return -EINVAL;
}
/* write 20/32 bytes, 5/8 words into auth_iv for SHA1/SHA256 */
if (sreq->first_blk) {
if (sha1) {
for (i = 0; i < 5; i++)
auth32[i] = _std_init_vector_sha1[i];
} else {
for (i = 0; i < 8; i++)
auth32[i] = _std_init_vector_sha256[i];
}
} else {
_byte_stream_to_net_words(auth32, sreq->digest, diglen);
}
pce = cmdlistinfo->auth_iv;
for (i = 0; i < 5; i++, pce++)
pce->data = auth32[i];
if ((sreq->alg == QCE_HASH_SHA256) ||
(sreq->alg == QCE_HASH_SHA256_HMAC)) {
for (i = 5; i < 8; i++, pce++)
pce->data = auth32[i];
}
/* write auth_bytecnt 0/1, start with 0 */
pce = cmdlistinfo->auth_bytecount;
for (i = 0; i < 2; i++, pce++)
pce->data = sreq->auth_data[i];
/* Set/reset last bit in CFG register */
pce = cmdlistinfo->auth_seg_cfg;
if (sreq->last_blk)
pce->data |= 1 << CRYPTO_LAST;
else
pce->data &= ~(1 << CRYPTO_LAST);
if (sreq->first_blk)
pce->data |= 1 << CRYPTO_FIRST;
else
pce->data &= ~(1 << CRYPTO_FIRST);
go_proc:
/* write auth seg size */
pce = cmdlistinfo->auth_seg_size;
pce->data = sreq->size;
pce = cmdlistinfo->encr_seg_cfg;
pce->data = 0;
/* write auth seg size start*/
pce = cmdlistinfo->auth_seg_start;
pce->data = 0;
/* write seg size */
pce = cmdlistinfo->seg_size;
pce->data = sreq->size;
return 0;
}
static struct qce_cmdlist_info *_ce_get_aead_cmdlistinfo(
struct qce_device *pce_dev, struct qce_req *creq)
{
switch (creq->alg) {
case CIPHER_ALG_DES:
switch (creq->mode) {
case QCE_MODE_ECB:
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_ecb_des;
break;
case QCE_MODE_CBC:
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_cbc_des;
break;
default:
return NULL;
}
break;
case CIPHER_ALG_3DES:
switch (creq->mode) {
case QCE_MODE_ECB:
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_ecb_3des;
break;
case QCE_MODE_CBC:
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_cbc_3des;
break;
default:
return NULL;
}
break;
case CIPHER_ALG_AES:
switch (creq->mode) {
case QCE_MODE_ECB:
if (creq->encklen == AES128_KEY_SIZE)
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_ecb_aes_128;
else if (creq->encklen == AES256_KEY_SIZE)
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_ecb_aes_256;
else
return NULL;
break;
case QCE_MODE_CBC:
if (creq->encklen == AES128_KEY_SIZE)
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_cbc_aes_128;
else if (creq->encklen == AES256_KEY_SIZE)
return &pce_dev->ce_sps.
cmdlistptr.aead_hmac_sha1_cbc_aes_256;
else
return NULL;
break;
default:
return NULL;
}
break;
default:
return NULL;
}
return NULL;
}
static int _ce_setup_aead(struct qce_device *pce_dev, struct qce_req *q_req,
uint32_t totallen_in, uint32_t coffset,
struct qce_cmdlist_info *cmdlistinfo)
{
int32_t authk_size_in_word = q_req->authklen/sizeof(uint32_t);
int i;
uint32_t mackey32[SHA_HMAC_KEY_SIZE/sizeof(uint32_t)] = {0};
struct sps_command_element *pce;
uint32_t a_cfg;
uint32_t enckey32[(MAX_CIPHER_KEY_SIZE*2)/sizeof(uint32_t)] = {0};
uint32_t enciv32[MAX_IV_LENGTH/sizeof(uint32_t)] = {0};
uint32_t enck_size_in_word = 0;
uint32_t enciv_in_word;
uint32_t key_size;
uint32_t encr_cfg = 0;
uint32_t ivsize = q_req->ivsize;
key_size = q_req->encklen;
enck_size_in_word = key_size/sizeof(uint32_t);
switch (q_req->alg) {
case CIPHER_ALG_DES:
enciv_in_word = 2;
break;
case CIPHER_ALG_3DES:
enciv_in_word = 2;
break;
case CIPHER_ALG_AES:
if ((key_size != AES128_KEY_SIZE) &&
(key_size != AES256_KEY_SIZE))
return -EINVAL;
enciv_in_word = 4;
break;
default:
return -EINVAL;
}
switch (q_req->mode) {
case QCE_MODE_ECB:
case QCE_MODE_CBC:
case QCE_MODE_CTR:
pce_dev->mode = q_req->mode;
break;
default:
return -EINVAL;
}
if (q_req->mode != QCE_MODE_ECB) {
_byte_stream_to_net_words(enciv32, q_req->iv, ivsize);
pce = cmdlistinfo->encr_cntr_iv;
for (i = 0; i < enciv_in_word; i++, pce++)
pce->data = enciv32[i];
}
/*
* write encr key
* do not use hw key or pipe key
*/
_byte_stream_to_net_words(enckey32, q_req->enckey, key_size);
pce = cmdlistinfo->encr_key;
for (i = 0; i < enck_size_in_word; i++, pce++)
pce->data = enckey32[i];
/* write encr seg cfg */
pce = cmdlistinfo->encr_seg_cfg;
encr_cfg = pce->data;
if (q_req->dir == QCE_ENCRYPT)
encr_cfg |= (1 << CRYPTO_ENCODE);
else
encr_cfg &= ~(1 << CRYPTO_ENCODE);
pce->data = encr_cfg;
/* we only support sha1-hmac at this point */
_byte_stream_to_net_words(mackey32, q_req->authkey,
q_req->authklen);
pce = cmdlistinfo->auth_key;
for (i = 0; i < authk_size_in_word; i++, pce++)
pce->data = mackey32[i];
pce = cmdlistinfo->auth_iv;
for (i = 0; i < 5; i++, pce++)
pce->data = _std_init_vector_sha1[i];
/* write auth_bytecnt 0/1, start with 0 */
pce = cmdlistinfo->auth_bytecount;
for (i = 0; i < 2; i++, pce++)
pce->data = 0;
pce = cmdlistinfo->auth_seg_cfg;
a_cfg = pce->data;
a_cfg &= ~(CRYPTO_AUTH_POS_MASK);
if (q_req->dir == QCE_ENCRYPT)
a_cfg |= (CRYPTO_AUTH_POS_AFTER << CRYPTO_AUTH_POS);
else
a_cfg |= (CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
pce->data = a_cfg;
/* write auth seg size */
pce = cmdlistinfo->auth_seg_size;
pce->data = totallen_in;
/* write auth seg size start*/
pce = cmdlistinfo->auth_seg_start;
pce->data = 0;
/* write seg size */
pce = cmdlistinfo->seg_size;
pce->data = totallen_in;
/* write encr seg size */
pce = cmdlistinfo->encr_seg_size;
pce->data = q_req->cryptlen;
/* write encr seg start */
pce = cmdlistinfo->encr_seg_start;
pce->data = (coffset & 0xffff);
return 0;
};
static int _ce_get_cipher_cmdlistinfo(struct qce_device *pce_dev,
struct qce_req *creq,
struct qce_cmdlist_info **cmdlistinfo)
{
struct qce_cmdlistptr_ops *cmdlistptr = &pce_dev->ce_sps.cmdlistptr;
if (creq->alg != CIPHER_ALG_AES) {
switch (creq->alg) {
case CIPHER_ALG_DES:
if (creq->mode == QCE_MODE_ECB)
*cmdlistinfo = &cmdlistptr->cipher_des_ecb;
else
*cmdlistinfo = &cmdlistptr->cipher_des_cbc;
break;
case CIPHER_ALG_3DES:
if (creq->mode == QCE_MODE_ECB)
*cmdlistinfo =
&cmdlistptr->cipher_3des_ecb;
else
*cmdlistinfo =
&cmdlistptr->cipher_3des_cbc;
break;
default:
break;
}
} else {
switch (creq->mode) {
case QCE_MODE_ECB:
if (creq->encklen == AES128_KEY_SIZE)
*cmdlistinfo = &cmdlistptr->cipher_aes_128_ecb;
else
*cmdlistinfo = &cmdlistptr->cipher_aes_256_ecb;
break;
case QCE_MODE_CBC:
case QCE_MODE_CTR:
if (creq->encklen == AES128_KEY_SIZE)
*cmdlistinfo =
&cmdlistptr->cipher_aes_128_cbc_ctr;
else
*cmdlistinfo =
&cmdlistptr->cipher_aes_256_cbc_ctr;
break;
case QCE_MODE_XTS:
if (creq->encklen/2 == AES128_KEY_SIZE)
*cmdlistinfo = &cmdlistptr->cipher_aes_128_xts;
else
*cmdlistinfo = &cmdlistptr->cipher_aes_256_xts;
break;
case QCE_MODE_CCM:
if (creq->encklen == AES128_KEY_SIZE)
*cmdlistinfo = &cmdlistptr->aead_aes_128_ccm;
else
*cmdlistinfo = &cmdlistptr->aead_aes_256_ccm;
break;
default:
break;
}
}
return 0;
}
static int _ce_setup_cipher(struct qce_device *pce_dev, struct qce_req *creq,
uint32_t totallen_in, uint32_t coffset,
struct qce_cmdlist_info *cmdlistinfo)
{
uint32_t enckey32[(MAX_CIPHER_KEY_SIZE * 2)/sizeof(uint32_t)] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
uint32_t enciv32[MAX_IV_LENGTH / sizeof(uint32_t)] = {
0, 0, 0, 0};
uint32_t enck_size_in_word = 0;
uint32_t key_size;
bool use_hw_key = false;
bool use_pipe_key = false;
uint32_t encr_cfg = 0;
uint32_t ivsize = creq->ivsize;
int i;
struct sps_command_element *pce = NULL;
if (creq->mode == QCE_MODE_XTS)
key_size = creq->encklen/2;
else
key_size = creq->encklen;
pce = cmdlistinfo->go_proc;
if ((creq->flags & QCRYPTO_CTX_USE_HW_KEY) == QCRYPTO_CTX_USE_HW_KEY) {
use_hw_key = true;
} else {
if ((creq->flags & QCRYPTO_CTX_USE_PIPE_KEY) ==
QCRYPTO_CTX_USE_PIPE_KEY)
use_pipe_key = true;
}
pce = cmdlistinfo->go_proc;
if (use_hw_key == true)
pce->addr = (uint32_t)(CRYPTO_GOPROC_QC_KEY_REG +
pce_dev->phy_iobase);
else
pce->addr = (uint32_t)(CRYPTO_GOPROC_REG +
pce_dev->phy_iobase);
if ((use_pipe_key == false) && (use_hw_key == false)) {
_byte_stream_to_net_words(enckey32, creq->enckey, key_size);
enck_size_in_word = key_size/sizeof(uint32_t);
}
if ((creq->op == QCE_REQ_AEAD) && (creq->mode == QCE_MODE_CCM)) {
uint32_t authklen32 = creq->encklen/sizeof(uint32_t);
uint32_t noncelen32 = MAX_NONCE/sizeof(uint32_t);
uint32_t nonce32[MAX_NONCE/sizeof(uint32_t)] = {0, 0, 0, 0};
uint32_t auth_cfg = 0;
/* write nonce */
_byte_stream_to_net_words(nonce32, creq->nonce, MAX_NONCE);
pce = cmdlistinfo->auth_nonce_info;
for (i = 0; i < noncelen32; i++, pce++)
pce->data = nonce32[i];
if (creq->authklen == AES128_KEY_SIZE)
auth_cfg = pce_dev->reg.auth_cfg_aes_ccm_128;
else {
if (creq->authklen == AES256_KEY_SIZE)
auth_cfg = pce_dev->reg.auth_cfg_aes_ccm_256;
}
if (creq->dir == QCE_ENCRYPT)
auth_cfg |= (CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
else
auth_cfg |= (CRYPTO_AUTH_POS_AFTER << CRYPTO_AUTH_POS);
auth_cfg |= ((creq->authsize - 1) << CRYPTO_AUTH_SIZE);
if (use_hw_key == true) {
auth_cfg |= (1 << CRYPTO_USE_HW_KEY_AUTH);
} else {
auth_cfg &= ~(1 << CRYPTO_USE_HW_KEY_AUTH);
/* write auth key */
pce = cmdlistinfo->auth_key;
for (i = 0; i < authklen32; i++, pce++)
pce->data = enckey32[i];
}
pce = cmdlistinfo->auth_seg_cfg;
pce->data = auth_cfg;
pce = cmdlistinfo->auth_seg_size;
if (creq->dir == QCE_ENCRYPT)
pce->data = totallen_in;
else
pce->data = totallen_in - creq->authsize;
pce = cmdlistinfo->auth_seg_start;
pce->data = 0;
} else {
if (creq->op != QCE_REQ_AEAD) {
pce = cmdlistinfo->auth_seg_cfg;
pce->data = 0;
}
}
switch (creq->mode) {
case QCE_MODE_ECB:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ecb_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_ecb_256;
break;
case QCE_MODE_CBC:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_cbc_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_cbc_256;
break;
case QCE_MODE_XTS:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_xts_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_xts_256;
break;
case QCE_MODE_CCM:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ccm_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_ccm_256;
encr_cfg |= (CRYPTO_ENCR_MODE_CCM << CRYPTO_ENCR_MODE) |
(CRYPTO_LAST_CCM_XFR << CRYPTO_LAST_CCM);
break;
case QCE_MODE_CTR:
default:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ctr_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_ctr_256;
break;
}
pce_dev->mode = creq->mode;
switch (creq->alg) {
case CIPHER_ALG_DES:
if (creq->mode != QCE_MODE_ECB) {
_byte_stream_to_net_words(enciv32, creq->iv, ivsize);
pce = cmdlistinfo->encr_cntr_iv;
pce->data = enciv32[0];
pce++;
pce->data = enciv32[1];
}
if (use_hw_key == false) {
pce = cmdlistinfo->encr_key;
pce->data = enckey32[0];
pce++;
pce->data = enckey32[1];
}
break;
case CIPHER_ALG_3DES:
if (creq->mode != QCE_MODE_ECB) {
_byte_stream_to_net_words(enciv32, creq->iv, ivsize);
pce = cmdlistinfo->encr_cntr_iv;
pce->data = enciv32[0];
pce++;
pce->data = enciv32[1];
}
if (use_hw_key == false) {
/* write encr key */
pce = cmdlistinfo->encr_key;
for (i = 0; i < 6; i++, pce++)
pce->data = enckey32[i];
}
break;
case CIPHER_ALG_AES:
default:
if (creq->mode == QCE_MODE_XTS) {
uint32_t xtskey32[MAX_CIPHER_KEY_SIZE/sizeof(uint32_t)]
= {0, 0, 0, 0, 0, 0, 0, 0};
uint32_t xtsklen =
creq->encklen/(2 * sizeof(uint32_t));
if ((use_hw_key == false) && (use_pipe_key == false)) {
_byte_stream_to_net_words(xtskey32,
(creq->enckey + creq->encklen/2),
creq->encklen/2);
/* write xts encr key */
pce = cmdlistinfo->encr_xts_key;
for (i = 0; i < xtsklen; i++, pce++)
pce->data = xtskey32[i];
}
/* write xts du size */
pce = cmdlistinfo->encr_xts_du_size;
if (!(creq->flags & QCRYPTO_CTX_XTS_MASK))
pce->data = creq->cryptlen;
else
pce->data = min((unsigned int)QCE_SECTOR_SIZE,
creq->cryptlen);
}
if (creq->mode != QCE_MODE_ECB) {
if (creq->mode == QCE_MODE_XTS)
_byte_stream_swap_to_net_words(enciv32,
creq->iv, ivsize);
else
_byte_stream_to_net_words(enciv32, creq->iv,
ivsize);
/* write encr cntr iv */
pce = cmdlistinfo->encr_cntr_iv;
for (i = 0; i < 4; i++, pce++)
pce->data = enciv32[i];
if (creq->mode == QCE_MODE_CCM) {
/* write cntr iv for ccm */
pce = cmdlistinfo->encr_ccm_cntr_iv;
for (i = 0; i < 4; i++, pce++)
pce->data = enciv32[i];
/* update cntr_iv[3] by one */
pce = cmdlistinfo->encr_cntr_iv;
pce += 3;
pce->data += 1;
}
}
if (creq->op == QCE_REQ_ABLK_CIPHER_NO_KEY) {
encr_cfg |= (CRYPTO_ENCR_KEY_SZ_AES128 <<
CRYPTO_ENCR_KEY_SZ);
} else {
if (use_hw_key == false) {
/* write encr key */
pce = cmdlistinfo->encr_key;
for (i = 0; i < enck_size_in_word; i++, pce++)
pce->data = enckey32[i];
}
} /* else of if (creq->op == QCE_REQ_ABLK_CIPHER_NO_KEY) */
break;
} /* end of switch (creq->mode) */
if (use_pipe_key)
encr_cfg |= (CRYPTO_USE_PIPE_KEY_ENCR_ENABLED
<< CRYPTO_USE_PIPE_KEY_ENCR);
/* write encr seg cfg */
pce = cmdlistinfo->encr_seg_cfg;
if ((creq->alg == CIPHER_ALG_DES) || (creq->alg == CIPHER_ALG_3DES)) {
if (creq->dir == QCE_ENCRYPT)
pce->data |= (1 << CRYPTO_ENCODE);
else
pce->data &= ~(1 << CRYPTO_ENCODE);
encr_cfg = pce->data;
} else {
encr_cfg |=
((creq->dir == QCE_ENCRYPT) ? 1 : 0) << CRYPTO_ENCODE;
}
if (use_hw_key == true)
encr_cfg |= (CRYPTO_USE_HW_KEY << CRYPTO_USE_HW_KEY_ENCR);
else
encr_cfg &= ~(CRYPTO_USE_HW_KEY << CRYPTO_USE_HW_KEY_ENCR);
pce->data = encr_cfg;
/* write encr seg size */
pce = cmdlistinfo->encr_seg_size;
if ((creq->mode == QCE_MODE_CCM) && (creq->dir == QCE_DECRYPT))
pce->data = (creq->cryptlen + creq->authsize);
else
pce->data = creq->cryptlen;
/* write encr seg start */
pce = cmdlistinfo->encr_seg_start;
pce->data = (coffset & 0xffff);
/* write seg size */
pce = cmdlistinfo->seg_size;
pce->data = totallen_in;
return 0;
};
static int _ce_setup_hash_direct(struct qce_device *pce_dev,
struct qce_sha_req *sreq)
{
uint32_t auth32[SHA256_DIGEST_SIZE / sizeof(uint32_t)];
uint32_t diglen;
bool use_hw_key = false;
int i;
uint32_t mackey32[SHA_HMAC_KEY_SIZE/sizeof(uint32_t)] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
bool sha1 = false;
uint32_t auth_cfg = 0;
/* clear status */
writel_relaxed(0, pce_dev->iobase + CRYPTO_STATUS_REG);
writel_relaxed(pce_dev->reg.crypto_cfg_be, (pce_dev->iobase +
CRYPTO_CONFIG_REG));
/*
* Ensure previous instructions (setting the CONFIG register)
* was completed before issuing starting to set other config register
* This is to ensure the configurations are done in correct endian-ness
* as set in the CONFIG registers
*/
mb();
if (sreq->alg == QCE_HASH_AES_CMAC) {
/* write seg_cfg */
writel_relaxed(0, pce_dev->iobase + CRYPTO_AUTH_SEG_CFG_REG);
/* write seg_cfg */
writel_relaxed(0, pce_dev->iobase + CRYPTO_ENCR_SEG_CFG_REG);
/* write seg_cfg */
writel_relaxed(0, pce_dev->iobase + CRYPTO_ENCR_SEG_SIZE_REG);
/* Clear auth_ivn, auth_keyn registers */
for (i = 0; i < 16; i++) {
writel_relaxed(0, (pce_dev->iobase +
(CRYPTO_AUTH_IV0_REG + i*sizeof(uint32_t))));
writel_relaxed(0, (pce_dev->iobase +
(CRYPTO_AUTH_KEY0_REG + i*sizeof(uint32_t))));
}
/* write auth_bytecnt 0/1/2/3, start with 0 */
for (i = 0; i < 4; i++)
writel_relaxed(0, pce_dev->iobase +
CRYPTO_AUTH_BYTECNT0_REG +
i * sizeof(uint32_t));
if (sreq->authklen == AES128_KEY_SIZE)
auth_cfg = pce_dev->reg.auth_cfg_cmac_128;
else
auth_cfg = pce_dev->reg.auth_cfg_cmac_256;
}
if ((sreq->alg == QCE_HASH_SHA1_HMAC) ||
(sreq->alg == QCE_HASH_SHA256_HMAC) ||
(sreq->alg == QCE_HASH_AES_CMAC)) {
uint32_t authk_size_in_word = sreq->authklen/sizeof(uint32_t);
_byte_stream_to_net_words(mackey32, sreq->authkey,
sreq->authklen);
/* check for null key. If null, use hw key*/
for (i = 0; i < authk_size_in_word; i++) {
if (mackey32[i] != 0)
break;
}
if (i == authk_size_in_word)
use_hw_key = true;
else
/* Clear auth_ivn, auth_keyn registers */
for (i = 0; i < authk_size_in_word; i++)
writel_relaxed(mackey32[i], (pce_dev->iobase +
(CRYPTO_AUTH_KEY0_REG +
i*sizeof(uint32_t))));
}
if (sreq->alg == QCE_HASH_AES_CMAC)
goto go_proc;
/* if not the last, the size has to be on the block boundary */
if (sreq->last_blk == 0 && (sreq->size % SHA256_BLOCK_SIZE))
return -EIO;
switch (sreq->alg) {
case QCE_HASH_SHA1:
auth_cfg = pce_dev->reg.auth_cfg_sha1;
diglen = SHA1_DIGEST_SIZE;
sha1 = true;
break;
case QCE_HASH_SHA1_HMAC:
auth_cfg = pce_dev->reg.auth_cfg_hmac_sha1;
diglen = SHA1_DIGEST_SIZE;
sha1 = true;
break;
case QCE_HASH_SHA256:
auth_cfg = pce_dev->reg.auth_cfg_sha256;
diglen = SHA256_DIGEST_SIZE;
break;
case QCE_HASH_SHA256_HMAC:
auth_cfg = pce_dev->reg.auth_cfg_hmac_sha256;
diglen = SHA256_DIGEST_SIZE;
break;
default:
return -EINVAL;
}
/* write 20/32 bytes, 5/8 words into auth_iv for SHA1/SHA256 */
if (sreq->first_blk) {
if (sha1) {
for (i = 0; i < 5; i++)
auth32[i] = _std_init_vector_sha1[i];
} else {
for (i = 0; i < 8; i++)
auth32[i] = _std_init_vector_sha256[i];
}
} else {
_byte_stream_to_net_words(auth32, sreq->digest, diglen);
}
/* Set auth_ivn, auth_keyn registers */
for (i = 0; i < 5; i++)
writel_relaxed(auth32[i], (pce_dev->iobase +
(CRYPTO_AUTH_IV0_REG + i*sizeof(uint32_t))));
if ((sreq->alg == QCE_HASH_SHA256) ||
(sreq->alg == QCE_HASH_SHA256_HMAC)) {
for (i = 5; i < 8; i++)
writel_relaxed(auth32[i], (pce_dev->iobase +
(CRYPTO_AUTH_IV0_REG + i*sizeof(uint32_t))));
}
/* write auth_bytecnt 0/1/2/3, start with 0 */
for (i = 0; i < 2; i++)
writel_relaxed(sreq->auth_data[i], pce_dev->iobase +
CRYPTO_AUTH_BYTECNT0_REG +
i * sizeof(uint32_t));
/* Set/reset last bit in CFG register */
if (sreq->last_blk)
auth_cfg |= 1 << CRYPTO_LAST;
else
auth_cfg &= ~(1 << CRYPTO_LAST);
if (sreq->first_blk)
auth_cfg |= 1 << CRYPTO_FIRST;
else
auth_cfg &= ~(1 << CRYPTO_FIRST);
go_proc:
/* write seg_cfg */
writel_relaxed(auth_cfg, pce_dev->iobase + CRYPTO_AUTH_SEG_CFG_REG);
/* write auth seg_size */
writel_relaxed(sreq->size, pce_dev->iobase + CRYPTO_AUTH_SEG_SIZE_REG);
/* write auth_seg_start */
writel_relaxed(0, pce_dev->iobase + CRYPTO_AUTH_SEG_START_REG);
/* reset encr seg_cfg */
writel_relaxed(0, pce_dev->iobase + CRYPTO_ENCR_SEG_CFG_REG);
/* write seg_size */
writel_relaxed(sreq->size, pce_dev->iobase + CRYPTO_SEG_SIZE_REG);
writel_relaxed(pce_dev->reg.crypto_cfg_le, (pce_dev->iobase +
CRYPTO_CONFIG_REG));
/* issue go to crypto */
if (use_hw_key == false)
writel_relaxed(((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
pce_dev->iobase + CRYPTO_GOPROC_REG);
else
writel_relaxed(((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
pce_dev->iobase + CRYPTO_GOPROC_QC_KEY_REG);
/*
* Ensure previous instructions (setting the GO register)
* was completed before issuing a DMA transfer request
*/
mb();
return 0;
}
static int _ce_setup_aead_direct(struct qce_device *pce_dev,
struct qce_req *q_req, uint32_t totallen_in, uint32_t coffset)
{
int32_t authk_size_in_word = q_req->authklen/sizeof(uint32_t);
int i;
uint32_t mackey32[SHA_HMAC_KEY_SIZE/sizeof(uint32_t)] = {0};
uint32_t a_cfg;
uint32_t enckey32[(MAX_CIPHER_KEY_SIZE*2)/sizeof(uint32_t)] = {0};
uint32_t enciv32[MAX_IV_LENGTH/sizeof(uint32_t)] = {0};
uint32_t enck_size_in_word = 0;
uint32_t enciv_in_word;
uint32_t key_size;
uint32_t ivsize = q_req->ivsize;
uint32_t encr_cfg;
/* clear status */
writel_relaxed(0, pce_dev->iobase + CRYPTO_STATUS_REG);
writel_relaxed(pce_dev->reg.crypto_cfg_be, (pce_dev->iobase +
CRYPTO_CONFIG_REG));
/*
* Ensure previous instructions (setting the CONFIG register)
* was completed before issuing starting to set other config register
* This is to ensure the configurations are done in correct endian-ness
* as set in the CONFIG registers
*/
mb();
key_size = q_req->encklen;
enck_size_in_word = key_size/sizeof(uint32_t);
switch (q_req->alg) {
case CIPHER_ALG_DES:
switch (q_req->mode) {
case QCE_MODE_ECB:
encr_cfg = pce_dev->reg.encr_cfg_des_ecb;
break;
case QCE_MODE_CBC:
encr_cfg = pce_dev->reg.encr_cfg_des_cbc;
break;
default:
return -EINVAL;
}
enciv_in_word = 2;
break;
case CIPHER_ALG_3DES:
switch (q_req->mode) {
case QCE_MODE_ECB:
encr_cfg = pce_dev->reg.encr_cfg_3des_ecb;
break;
case QCE_MODE_CBC:
encr_cfg = pce_dev->reg.encr_cfg_3des_cbc;
break;
default:
return -EINVAL;
}
enciv_in_word = 2;
break;
case CIPHER_ALG_AES:
switch (q_req->mode) {
case QCE_MODE_ECB:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ecb_128;
else if (key_size == AES256_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ecb_256;
else
return -EINVAL;
break;
case QCE_MODE_CBC:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_cbc_128;
else if (key_size == AES256_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_cbc_256;
else
return -EINVAL;
break;
default:
return -EINVAL;
}
enciv_in_word = 4;
break;
default:
return -EINVAL;
}
pce_dev->mode = q_req->mode;
/* write CNTR0_IV0_REG */
if (q_req->mode != QCE_MODE_ECB) {
_byte_stream_to_net_words(enciv32, q_req->iv, ivsize);
for (i = 0; i < enciv_in_word; i++)
writel_relaxed(enciv32[i], pce_dev->iobase +
(CRYPTO_CNTR0_IV0_REG + i * sizeof(uint32_t)));
}
/*
* write encr key
* do not use hw key or pipe key
*/
_byte_stream_to_net_words(enckey32, q_req->enckey, key_size);
for (i = 0; i < enck_size_in_word; i++)
writel_relaxed(enckey32[i], pce_dev->iobase +
(CRYPTO_ENCR_KEY0_REG + i * sizeof(uint32_t)));
/* write encr seg cfg */
if (q_req->dir == QCE_ENCRYPT)
encr_cfg |= (1 << CRYPTO_ENCODE);
writel_relaxed(encr_cfg, pce_dev->iobase + CRYPTO_ENCR_SEG_CFG_REG);
/* we only support sha1-hmac at this point */
_byte_stream_to_net_words(mackey32, q_req->authkey,
q_req->authklen);
for (i = 0; i < authk_size_in_word; i++)
writel_relaxed(mackey32[i], pce_dev->iobase +
(CRYPTO_AUTH_KEY0_REG + i * sizeof(uint32_t)));
for (i = 0; i < 5; i++)
writel_relaxed(_std_init_vector_sha1[i], pce_dev->iobase +
(CRYPTO_AUTH_IV0_REG + i * sizeof(uint32_t)));
/* write auth_bytecnt 0/1, start with 0 */
writel_relaxed(0, pce_dev->iobase + CRYPTO_AUTH_BYTECNT0_REG);
writel_relaxed(0, pce_dev->iobase + CRYPTO_AUTH_BYTECNT1_REG);
/* write encr seg size */
writel_relaxed(q_req->cryptlen, pce_dev->iobase +
CRYPTO_ENCR_SEG_SIZE_REG);
/* write encr start */
writel_relaxed(coffset & 0xffff, pce_dev->iobase +
CRYPTO_ENCR_SEG_START_REG);
a_cfg = (CRYPTO_AUTH_MODE_HMAC << CRYPTO_AUTH_MODE) |
(CRYPTO_AUTH_SIZE_SHA1 << CRYPTO_AUTH_SIZE) |
(1 << CRYPTO_LAST) | (1 << CRYPTO_FIRST) |
(CRYPTO_AUTH_ALG_SHA << CRYPTO_AUTH_ALG);
if (q_req->dir == QCE_ENCRYPT)
a_cfg |= (CRYPTO_AUTH_POS_AFTER << CRYPTO_AUTH_POS);
else
a_cfg |= (CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
/* write auth seg_cfg */
writel_relaxed(a_cfg, pce_dev->iobase + CRYPTO_AUTH_SEG_CFG_REG);
/* write auth seg_size */
writel_relaxed(totallen_in, pce_dev->iobase + CRYPTO_AUTH_SEG_SIZE_REG);
/* write auth_seg_start */
writel_relaxed(0, pce_dev->iobase + CRYPTO_AUTH_SEG_START_REG);
/* write seg_size */
writel_relaxed(totallen_in, pce_dev->iobase + CRYPTO_SEG_SIZE_REG);
writel_relaxed(pce_dev->reg.crypto_cfg_le, (pce_dev->iobase +
CRYPTO_CONFIG_REG));
/* issue go to crypto */
writel_relaxed(((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
pce_dev->iobase + CRYPTO_GOPROC_REG);
/*
* Ensure previous instructions (setting the GO register)
* was completed before issuing a DMA transfer request
*/
mb();
return 0;
};
static int _ce_setup_cipher_direct(struct qce_device *pce_dev,
struct qce_req *creq, uint32_t totallen_in, uint32_t coffset)
{
uint32_t enckey32[(MAX_CIPHER_KEY_SIZE * 2)/sizeof(uint32_t)] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
uint32_t enciv32[MAX_IV_LENGTH / sizeof(uint32_t)] = {
0, 0, 0, 0};
uint32_t enck_size_in_word = 0;
uint32_t key_size;
bool use_hw_key = false;
bool use_pipe_key = false;
uint32_t encr_cfg = 0;
uint32_t ivsize = creq->ivsize;
int i;
/* clear status */
writel_relaxed(0, pce_dev->iobase + CRYPTO_STATUS_REG);
writel_relaxed(pce_dev->reg.crypto_cfg_be, (pce_dev->iobase +
CRYPTO_CONFIG_REG));
/*
* Ensure previous instructions (setting the CONFIG register)
* was completed before issuing starting to set other config register
* This is to ensure the configurations are done in correct endian-ness
* as set in the CONFIG registers
*/
mb();
if (creq->mode == QCE_MODE_XTS)
key_size = creq->encklen/2;
else
key_size = creq->encklen;
if ((creq->flags & QCRYPTO_CTX_USE_HW_KEY) == QCRYPTO_CTX_USE_HW_KEY) {
use_hw_key = true;
} else {
if ((creq->flags & QCRYPTO_CTX_USE_PIPE_KEY) ==
QCRYPTO_CTX_USE_PIPE_KEY)
use_pipe_key = true;
}
if ((use_pipe_key == false) && (use_hw_key == false)) {
_byte_stream_to_net_words(enckey32, creq->enckey, key_size);
enck_size_in_word = key_size/sizeof(uint32_t);
}
if ((creq->op == QCE_REQ_AEAD) && (creq->mode == QCE_MODE_CCM)) {
uint32_t authklen32 = creq->encklen/sizeof(uint32_t);
uint32_t noncelen32 = MAX_NONCE/sizeof(uint32_t);
uint32_t nonce32[MAX_NONCE/sizeof(uint32_t)] = {0, 0, 0, 0};
uint32_t auth_cfg = 0;
/* Clear auth_ivn, auth_keyn registers */
for (i = 0; i < 16; i++) {
writel_relaxed(0, (pce_dev->iobase +
(CRYPTO_AUTH_IV0_REG + i*sizeof(uint32_t))));
writel_relaxed(0, (pce_dev->iobase +
(CRYPTO_AUTH_KEY0_REG + i*sizeof(uint32_t))));
}
/* write auth_bytecnt 0/1/2/3, start with 0 */
for (i = 0; i < 4; i++)
writel_relaxed(0, pce_dev->iobase +
CRYPTO_AUTH_BYTECNT0_REG +
i * sizeof(uint32_t));
/* write nonce */
_byte_stream_to_net_words(nonce32, creq->nonce, MAX_NONCE);
for (i = 0; i < noncelen32; i++)
writel_relaxed(nonce32[i], pce_dev->iobase +
CRYPTO_AUTH_INFO_NONCE0_REG +
(i*sizeof(uint32_t)));
if (creq->authklen == AES128_KEY_SIZE)
auth_cfg = pce_dev->reg.auth_cfg_aes_ccm_128;
else {
if (creq->authklen == AES256_KEY_SIZE)
auth_cfg = pce_dev->reg.auth_cfg_aes_ccm_256;
}
if (creq->dir == QCE_ENCRYPT)
auth_cfg |= (CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
else
auth_cfg |= (CRYPTO_AUTH_POS_AFTER << CRYPTO_AUTH_POS);
auth_cfg |= ((creq->authsize - 1) << CRYPTO_AUTH_SIZE);
if (use_hw_key == true) {
auth_cfg |= (1 << CRYPTO_USE_HW_KEY_AUTH);
} else {
auth_cfg &= ~(1 << CRYPTO_USE_HW_KEY_AUTH);
/* write auth key */
for (i = 0; i < authklen32; i++)
writel_relaxed(enckey32[i], pce_dev->iobase +
CRYPTO_AUTH_KEY0_REG + (i*sizeof(uint32_t)));
}
writel_relaxed(auth_cfg, pce_dev->iobase +
CRYPTO_AUTH_SEG_CFG_REG);
if (creq->dir == QCE_ENCRYPT)
writel_relaxed(totallen_in, pce_dev->iobase +
CRYPTO_AUTH_SEG_SIZE_REG);
else
writel_relaxed((totallen_in - creq->authsize),
pce_dev->iobase + CRYPTO_AUTH_SEG_SIZE_REG);
writel_relaxed(0, pce_dev->iobase + CRYPTO_AUTH_SEG_START_REG);
} else {
if (creq->op != QCE_REQ_AEAD)
writel_relaxed(0, pce_dev->iobase +
CRYPTO_AUTH_SEG_CFG_REG);
}
/*
* Ensure previous instructions (write to all AUTH registers)
* was completed before accessing a register that is not in
* in the same 1K range.
*/
mb();
switch (creq->mode) {
case QCE_MODE_ECB:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ecb_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_ecb_256;
break;
case QCE_MODE_CBC:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_cbc_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_cbc_256;
break;
case QCE_MODE_XTS:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_xts_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_xts_256;
break;
case QCE_MODE_CCM:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ccm_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_ccm_256;
break;
case QCE_MODE_CTR:
default:
if (key_size == AES128_KEY_SIZE)
encr_cfg = pce_dev->reg.encr_cfg_aes_ctr_128;
else
encr_cfg = pce_dev->reg.encr_cfg_aes_ctr_256;
break;
}
pce_dev->mode = creq->mode;
switch (creq->alg) {
case CIPHER_ALG_DES:
if (creq->mode != QCE_MODE_ECB) {
encr_cfg = pce_dev->reg.encr_cfg_des_cbc;
_byte_stream_to_net_words(enciv32, creq->iv, ivsize);
writel_relaxed(enciv32[0], pce_dev->iobase +
CRYPTO_CNTR0_IV0_REG);
writel_relaxed(enciv32[1], pce_dev->iobase +
CRYPTO_CNTR1_IV1_REG);
} else {
encr_cfg = pce_dev->reg.encr_cfg_des_ecb;
}
if (use_hw_key == false) {
writel_relaxed(enckey32[0], pce_dev->iobase +
CRYPTO_ENCR_KEY0_REG);
writel_relaxed(enckey32[1], pce_dev->iobase +
CRYPTO_ENCR_KEY1_REG);
}
break;
case CIPHER_ALG_3DES:
if (creq->mode != QCE_MODE_ECB) {
_byte_stream_to_net_words(enciv32, creq->iv, ivsize);
writel_relaxed(enciv32[0], pce_dev->iobase +
CRYPTO_CNTR0_IV0_REG);
writel_relaxed(enciv32[1], pce_dev->iobase +
CRYPTO_CNTR1_IV1_REG);
encr_cfg = pce_dev->reg.encr_cfg_3des_cbc;
} else {
encr_cfg = pce_dev->reg.encr_cfg_3des_ecb;
}
if (use_hw_key == false) {
/* write encr key */
for (i = 0; i < 6; i++)
writel_relaxed(enckey32[0], (pce_dev->iobase +
(CRYPTO_ENCR_KEY0_REG + i * sizeof(uint32_t))));
}
break;
case CIPHER_ALG_AES:
default:
if (creq->mode == QCE_MODE_XTS) {
uint32_t xtskey32[MAX_CIPHER_KEY_SIZE/sizeof(uint32_t)]
= {0, 0, 0, 0, 0, 0, 0, 0};
uint32_t xtsklen =
creq->encklen/(2 * sizeof(uint32_t));
if ((use_hw_key == false) && (use_pipe_key == false)) {
_byte_stream_to_net_words(xtskey32,
(creq->enckey + creq->encklen/2),
creq->encklen/2);
/* write xts encr key */
for (i = 0; i < xtsklen; i++)
writel_relaxed(xtskey32[i],
pce_dev->iobase +
CRYPTO_ENCR_XTS_KEY0_REG +
(i * sizeof(uint32_t)));
}
/* write xts du size */
if (use_pipe_key == true)
writel_relaxed(min((uint32_t)QCE_SECTOR_SIZE,
creq->cryptlen),
pce_dev->iobase +
CRYPTO_ENCR_XTS_DU_SIZE_REG);
else
writel_relaxed(creq->cryptlen ,
pce_dev->iobase +
CRYPTO_ENCR_XTS_DU_SIZE_REG);
}
if (creq->mode != QCE_MODE_ECB) {
if (creq->mode == QCE_MODE_XTS)
_byte_stream_swap_to_net_words(enciv32,
creq->iv, ivsize);
else
_byte_stream_to_net_words(enciv32, creq->iv,
ivsize);
/* write encr cntr iv */
for (i = 0; i <= 3; i++)
writel_relaxed(enciv32[i], pce_dev->iobase +
CRYPTO_CNTR0_IV0_REG +
(i * sizeof(uint32_t)));
if (creq->mode == QCE_MODE_CCM) {
/* write cntr iv for ccm */
for (i = 0; i <= 3; i++)
writel_relaxed(enciv32[i],
pce_dev->iobase +
CRYPTO_ENCR_CCM_INT_CNTR0_REG +
(i * sizeof(uint32_t)));
/* update cntr_iv[3] by one */
writel_relaxed((enciv32[3] + 1),
pce_dev->iobase +
CRYPTO_CNTR0_IV0_REG +
(3 * sizeof(uint32_t)));
}
}
if (creq->op == QCE_REQ_ABLK_CIPHER_NO_KEY) {
encr_cfg |= (CRYPTO_ENCR_KEY_SZ_AES128 <<
CRYPTO_ENCR_KEY_SZ);
} else {
if ((use_hw_key == false) && (use_pipe_key == false)) {
for (i = 0; i < enck_size_in_word; i++)
writel_relaxed(enckey32[i],
pce_dev->iobase +
CRYPTO_ENCR_KEY0_REG +
(i * sizeof(uint32_t)));
}
} /* else of if (creq->op == QCE_REQ_ABLK_CIPHER_NO_KEY) */
break;
} /* end of switch (creq->mode) */
if (use_pipe_key)
encr_cfg |= (CRYPTO_USE_PIPE_KEY_ENCR_ENABLED
<< CRYPTO_USE_PIPE_KEY_ENCR);
/* write encr seg cfg */
encr_cfg |= ((creq->dir == QCE_ENCRYPT) ? 1 : 0) << CRYPTO_ENCODE;
if (use_hw_key == true)
encr_cfg |= (CRYPTO_USE_HW_KEY << CRYPTO_USE_HW_KEY_ENCR);
else
encr_cfg &= ~(CRYPTO_USE_HW_KEY << CRYPTO_USE_HW_KEY_ENCR);
/* write encr seg cfg */
writel_relaxed(encr_cfg, pce_dev->iobase + CRYPTO_ENCR_SEG_CFG_REG);
/* write encr seg size */
if ((creq->mode == QCE_MODE_CCM) && (creq->dir == QCE_DECRYPT))
writel_relaxed((creq->cryptlen + creq->authsize),
pce_dev->iobase + CRYPTO_ENCR_SEG_SIZE_REG);
else
writel_relaxed(creq->cryptlen,
pce_dev->iobase + CRYPTO_ENCR_SEG_SIZE_REG);
/* write encr seg start */
writel_relaxed((coffset & 0xffff),
pce_dev->iobase + CRYPTO_ENCR_SEG_START_REG);
/* write encr seg start */
writel_relaxed(0xffffffff,
pce_dev->iobase + CRYPTO_CNTR_MASK_REG);
/* write seg size */
writel_relaxed(totallen_in, pce_dev->iobase + CRYPTO_SEG_SIZE_REG);
writel_relaxed(pce_dev->reg.crypto_cfg_le, (pce_dev->iobase +
CRYPTO_CONFIG_REG));
/* issue go to crypto */
if (use_hw_key == false)
writel_relaxed(((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
pce_dev->iobase + CRYPTO_GOPROC_REG);
else
writel_relaxed(((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
pce_dev->iobase + CRYPTO_GOPROC_QC_KEY_REG);
/*
* Ensure previous instructions (setting the GO register)
* was completed before issuing a DMA transfer request
*/
mb();
return 0;
};
static int _qce_unlock_other_pipes(struct qce_device *pce_dev)
{
int rc = 0;
if (pce_dev->support_cmd_dscr == false)
return rc;
pce_dev->ce_sps.consumer.event.callback = NULL;
rc = sps_transfer_one(pce_dev->ce_sps.consumer.pipe,
GET_PHYS_ADDR(pce_dev->ce_sps.cmdlistptr.unlock_all_pipes.cmdlist),
0, NULL, (SPS_IOVEC_FLAG_CMD | SPS_IOVEC_FLAG_UNLOCK));
if (rc) {
pr_err("sps_xfr_one() fail rc=%d", rc);
rc = -EINVAL;
}
return rc;
}
static int _aead_complete(struct qce_device *pce_dev)
{
struct aead_request *areq;
unsigned char mac[SHA256_DIGEST_SIZE];
uint32_t status;
int32_t result_status;
areq = (struct aead_request *) pce_dev->areq;
if (areq->src != areq->dst) {
qce_dma_unmap_sg(pce_dev->pdev, areq->dst, pce_dev->dst_nents,
DMA_FROM_DEVICE);
}
qce_dma_unmap_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
(areq->src == areq->dst) ? DMA_BIDIRECTIONAL :
DMA_TO_DEVICE);
qce_dma_unmap_sg(pce_dev->pdev, areq->assoc, pce_dev->assoc_nents,
DMA_TO_DEVICE);
/* check MAC */
memcpy(mac, (char *)(&pce_dev->ce_sps.result->auth_iv[0]),
SHA256_DIGEST_SIZE);
/* read status before unlock */
status = readl_relaxed(pce_dev->iobase + CRYPTO_STATUS_REG);
if (_qce_unlock_other_pipes(pce_dev))
return -EINVAL;
/*
* Don't use result dump status. The operation may not
* be complete.
* Instead, use the status we just read of device.
* In case, we need to use result_status from result
* dump the result_status needs to be byte swapped,
* since we set the device to little endian.
*/
result_status = 0;
pce_dev->ce_sps.result->status = 0;
if (status & ((1 << CRYPTO_SW_ERR) | (1 << CRYPTO_AXI_ERR)
| (1 << CRYPTO_HSD_ERR))) {
pr_err("aead operation error. Status %x\n", status);
result_status = -ENXIO;
} else if (pce_dev->ce_sps.consumer_status |
pce_dev->ce_sps.producer_status) {
pr_err("aead sps operation error. sps status %x %x\n",
pce_dev->ce_sps.consumer_status,
pce_dev->ce_sps.producer_status);
result_status = -ENXIO;
} else if ((status & (1 << CRYPTO_OPERATION_DONE)) == 0) {
pr_err("aead operation not done? Status %x, sps status %x %x\n",
status,
pce_dev->ce_sps.consumer_status,
pce_dev->ce_sps.producer_status);
result_status = -ENXIO;
}
if (pce_dev->mode == QCE_MODE_CCM) {
if (result_status == 0 && (status & (1 << CRYPTO_MAC_FAILED)))
result_status = -EBADMSG;
pce_dev->qce_cb(areq, mac, NULL, result_status);
} else {
uint32_t ivsize = 0;
struct crypto_aead *aead;
unsigned char iv[NUM_OF_CRYPTO_CNTR_IV_REG * CRYPTO_REG_SIZE];
aead = crypto_aead_reqtfm(areq);
ivsize = crypto_aead_ivsize(aead);
if (pce_dev->ce_sps.minor_version != 0)
dma_unmap_single(pce_dev->pdev, pce_dev->phy_iv_in,
ivsize, DMA_TO_DEVICE);
memcpy(iv, (char *)(pce_dev->ce_sps.result->encr_cntr_iv),
sizeof(iv));
pce_dev->qce_cb(areq, mac, iv, result_status);
}
return 0;
};
static int _sha_complete(struct qce_device *pce_dev)
{
struct ahash_request *areq;
unsigned char digest[SHA256_DIGEST_SIZE];
uint32_t bytecount32[2];
int32_t result_status = pce_dev->ce_sps.result->status;
uint32_t status;
areq = (struct ahash_request *) pce_dev->areq;
qce_dma_unmap_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
DMA_TO_DEVICE);
memcpy(digest, (char *)(&pce_dev->ce_sps.result->auth_iv[0]),
SHA256_DIGEST_SIZE);
_byte_stream_to_net_words(bytecount32,
(unsigned char *)pce_dev->ce_sps.result->auth_byte_count,
2 * CRYPTO_REG_SIZE);
/* read status before unlock */
status = readl_relaxed(pce_dev->iobase + CRYPTO_STATUS_REG);
if (_qce_unlock_other_pipes(pce_dev))
return -EINVAL;
/*
* Don't use result dump status. The operation may not be complete.
* Instead, use the status we just read of device.
* In case, we need to use result_status from result
* dump the result_status needs to be byte swapped,
* since we set the device to little endian.
*/
if (status & ((1 << CRYPTO_SW_ERR) | (1 << CRYPTO_AXI_ERR)
| (1 << CRYPTO_HSD_ERR))) {
pr_err("sha operation error. Status %x\n", status);
result_status = -ENXIO;
} else if (pce_dev->ce_sps.consumer_status) {
pr_err("sha sps operation error. sps status %x\n",
pce_dev->ce_sps.consumer_status);
result_status = -ENXIO;
} else if ((status & (1 << CRYPTO_OPERATION_DONE)) == 0) {
pr_err("sha operation not done? Status %x, sps status %x\n",
status, pce_dev->ce_sps.consumer_status);
result_status = -ENXIO;
} else {
result_status = 0;
}
pce_dev->qce_cb(areq, digest, (char *)bytecount32,
result_status);
return 0;
};
static int _ablk_cipher_complete(struct qce_device *pce_dev)
{
struct ablkcipher_request *areq;
unsigned char iv[NUM_OF_CRYPTO_CNTR_IV_REG * CRYPTO_REG_SIZE];
uint32_t status;
int32_t result_status;
areq = (struct ablkcipher_request *) pce_dev->areq;
if (areq->src != areq->dst) {
qce_dma_unmap_sg(pce_dev->pdev, areq->dst,
pce_dev->dst_nents, DMA_FROM_DEVICE);
}
qce_dma_unmap_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
(areq->src == areq->dst) ? DMA_BIDIRECTIONAL :
DMA_TO_DEVICE);
/* read status before unlock */
status = readl_relaxed(pce_dev->iobase + CRYPTO_STATUS_REG);
if (_qce_unlock_other_pipes(pce_dev))
return -EINVAL;
/*
* Don't use result dump status. The operation may not be complete.
* Instead, use the status we just read of device.
* In case, we need to use result_status from result
* dump the result_status needs to be byte swapped,
* since we set the device to little endian.
*/
if (status & ((1 << CRYPTO_SW_ERR) | (1 << CRYPTO_AXI_ERR)
| (1 << CRYPTO_HSD_ERR))) {
pr_err("ablk_cipher operation error. Status %x\n",
status);
result_status = -ENXIO;
} else if (pce_dev->ce_sps.consumer_status |
pce_dev->ce_sps.producer_status) {
pr_err("ablk_cipher sps operation error. sps status %x %x\n",
pce_dev->ce_sps.consumer_status,
pce_dev->ce_sps.producer_status);
result_status = -ENXIO;
} else if ((status & (1 << CRYPTO_OPERATION_DONE)) == 0) {
pr_err("ablk_cipher operation not done? Status %x, sps status %x %x\n",
status,
pce_dev->ce_sps.consumer_status,
pce_dev->ce_sps.producer_status);
result_status = -ENXIO;
} else {
result_status = 0;
}
if (pce_dev->mode == QCE_MODE_ECB) {
pce_dev->qce_cb(areq, NULL, NULL,
pce_dev->ce_sps.consumer_status |
result_status);
} else {
if (pce_dev->ce_sps.minor_version == 0) {
if (pce_dev->mode == QCE_MODE_CBC) {
if (pce_dev->dir == QCE_DECRYPT)
memcpy(iv, (char *)pce_dev->dec_iv,
sizeof(iv));
else
memcpy(iv, (unsigned char *)
(sg_virt(areq->src) +
areq->src->length - 16),
sizeof(iv));
}
if ((pce_dev->mode == QCE_MODE_CTR) ||
(pce_dev->mode == QCE_MODE_XTS)) {
uint32_t num_blk = 0;
uint32_t cntr_iv3 = 0;
unsigned long long cntr_iv64 = 0;
unsigned char *b = (unsigned char *)(&cntr_iv3);
memcpy(iv, areq->info, sizeof(iv));
if (pce_dev->mode != QCE_MODE_XTS)
num_blk = areq->nbytes/16;
else
num_blk = 1;
cntr_iv3 = ((*(iv + 12) << 24) & 0xff000000) |
(((*(iv + 13)) << 16) & 0xff0000) |
(((*(iv + 14)) << 8) & 0xff00) |
(*(iv + 15) & 0xff);
cntr_iv64 =
(((unsigned long long)cntr_iv3 &
(unsigned long long)0xFFFFFFFFULL) +
(unsigned long long)num_blk) %
(unsigned long long)(0x100000000ULL);
cntr_iv3 = (u32)(cntr_iv64 & 0xFFFFFFFF);
*(iv + 15) = (char)(*b);
*(iv + 14) = (char)(*(b + 1));
*(iv + 13) = (char)(*(b + 2));
*(iv + 12) = (char)(*(b + 3));
}
} else {
memcpy(iv,
(char *)(pce_dev->ce_sps.result->encr_cntr_iv),
sizeof(iv));
}
pce_dev->qce_cb(areq, NULL, iv, result_status);
}
return 0;
};
#ifdef QCE_DEBUG
static void _qce_dump_descr_fifos(struct qce_device *pce_dev)
{
int i, j, ents;
struct sps_iovec *iovec = pce_dev->ce_sps.in_transfer.iovec;
uint32_t cmd_flags = SPS_IOVEC_FLAG_CMD;
printk(KERN_INFO "==============================================\n");
printk(KERN_INFO "CONSUMER (TX/IN/DEST) PIPE DESCRIPTOR\n");
printk(KERN_INFO "==============================================\n");
for (i = 0; i < pce_dev->ce_sps.in_transfer.iovec_count; i++) {
printk(KERN_INFO " [%d] addr=0x%x size=0x%x flags=0x%x\n", i,
iovec->addr, iovec->size, iovec->flags);
if (iovec->flags & cmd_flags) {
struct sps_command_element *pced;
pced = (struct sps_command_element *)
(GET_VIRT_ADDR(iovec->addr));
ents = iovec->size/(sizeof(struct sps_command_element));
for (j = 0; j < ents; j++) {
printk(KERN_INFO " [%d] [0x%x] 0x%x\n", j,
pced->addr, pced->data);
pced++;
}
}
iovec++;
}
printk(KERN_INFO "==============================================\n");
printk(KERN_INFO "PRODUCER (RX/OUT/SRC) PIPE DESCRIPTOR\n");
printk(KERN_INFO "==============================================\n");
iovec = pce_dev->ce_sps.out_transfer.iovec;
for (i = 0; i < pce_dev->ce_sps.out_transfer.iovec_count; i++) {
printk(KERN_INFO " [%d] addr=0x%x size=0x%x flags=0x%x\n", i,
iovec->addr, iovec->size, iovec->flags);
iovec++;
}
}
#else
static void _qce_dump_descr_fifos(struct qce_device *pce_dev)
{
}
#endif
static void _qce_dump_descr_fifos_fail(struct qce_device *pce_dev)
{
int i, j, ents;
struct sps_iovec *iovec = pce_dev->ce_sps.in_transfer.iovec;
uint32_t cmd_flags = SPS_IOVEC_FLAG_CMD;
printk(KERN_INFO "==============================================\n");
printk(KERN_INFO "CONSUMER (TX/IN/DEST) PIPE DESCRIPTOR\n");
printk(KERN_INFO "==============================================\n");
for (i = 0; i < pce_dev->ce_sps.in_transfer.iovec_count; i++) {
printk(KERN_INFO " [%d] addr=0x%x size=0x%x flags=0x%x\n", i,
iovec->addr, iovec->size, iovec->flags);
if (iovec->flags & cmd_flags) {
struct sps_command_element *pced;
pced = (struct sps_command_element *)
(GET_VIRT_ADDR(iovec->addr));
ents = iovec->size/(sizeof(struct sps_command_element));
for (j = 0; j < ents; j++) {
printk(KERN_INFO " [%d] [0x%x] 0x%x\n", j,
pced->addr, pced->data);
pced++;
}
}
iovec++;
}
printk(KERN_INFO "==============================================\n");
printk(KERN_INFO "PRODUCER (RX/OUT/SRC) PIPE DESCRIPTOR\n");
printk(KERN_INFO "==============================================\n");
iovec = pce_dev->ce_sps.out_transfer.iovec;
for (i = 0; i < pce_dev->ce_sps.out_transfer.iovec_count; i++) {
printk(KERN_INFO " [%d] addr=0x%x size=0x%x flags=0x%x\n", i,
iovec->addr, iovec->size, iovec->flags);
iovec++;
}
}
static void _qce_sps_iovec_count_init(struct qce_device *pce_dev)
{
pce_dev->ce_sps.in_transfer.iovec_count = 0;
pce_dev->ce_sps.out_transfer.iovec_count = 0;
}
static void _qce_set_flag(struct sps_transfer *sps_bam_pipe, uint32_t flag)
{
struct sps_iovec *iovec = sps_bam_pipe->iovec +
(sps_bam_pipe->iovec_count - 1);
iovec->flags |= flag;
}
static int _qce_sps_add_data(uint32_t addr, uint32_t len,
struct sps_transfer *sps_bam_pipe)
{
struct sps_iovec *iovec = sps_bam_pipe->iovec +
sps_bam_pipe->iovec_count;
if (sps_bam_pipe->iovec_count == QCE_MAX_NUM_DSCR) {
pr_err("Num of descrptor %d exceed max (%d)",
sps_bam_pipe->iovec_count, (uint32_t)QCE_MAX_NUM_DSCR);
return -ENOMEM;
}
if (len) {
iovec->size = len;
iovec->addr = addr;
iovec->flags = 0;
sps_bam_pipe->iovec_count++;
}
return 0;
}
static int _qce_sps_add_sg_data(struct qce_device *pce_dev,
struct scatterlist *sg_src, uint32_t nbytes,
struct sps_transfer *sps_bam_pipe)
{
uint32_t addr, data_cnt, len;
struct sps_iovec *iovec = sps_bam_pipe->iovec +
sps_bam_pipe->iovec_count;
while (nbytes > 0) {
len = min(nbytes, sg_dma_len(sg_src));
nbytes -= len;
addr = sg_dma_address(sg_src);
if (pce_dev->ce_sps.minor_version == 0)
len = ALIGN(len, pce_dev->ce_sps.ce_burst_size);
while (len > 0) {
if (sps_bam_pipe->iovec_count == QCE_MAX_NUM_DSCR) {
pr_err("Num of descrptor %d exceed max (%d)",
sps_bam_pipe->iovec_count,
(uint32_t)QCE_MAX_NUM_DSCR);
return -ENOMEM;
}
if (len > SPS_MAX_PKT_SIZE) {
data_cnt = SPS_MAX_PKT_SIZE;
iovec->size = data_cnt;
iovec->addr = addr;
iovec->flags = 0;
} else {
data_cnt = len;
iovec->size = data_cnt;
iovec->addr = addr;
iovec->flags = 0;
}
iovec++;
sps_bam_pipe->iovec_count++;
addr += data_cnt;
len -= data_cnt;
}
sg_src = scatterwalk_sg_next(sg_src);
}
return 0;
}
static int _qce_sps_add_cmd(struct qce_device *pce_dev, uint32_t flag,
struct qce_cmdlist_info *cmdptr,
struct sps_transfer *sps_bam_pipe)
{
struct sps_iovec *iovec = sps_bam_pipe->iovec +
sps_bam_pipe->iovec_count;
iovec->size = cmdptr->size;
iovec->addr = GET_PHYS_ADDR(cmdptr->cmdlist);
iovec->flags = SPS_IOVEC_FLAG_CMD | flag;
sps_bam_pipe->iovec_count++;
return 0;
}
static int _qce_sps_transfer(struct qce_device *pce_dev)
{
int rc = 0;
_qce_dump_descr_fifos(pce_dev);
rc = sps_transfer(pce_dev->ce_sps.consumer.pipe,
&pce_dev->ce_sps.in_transfer);
if (rc) {
pr_err("sps_xfr() fail (consumer pipe=0x%x) rc = %d,",
(u32)pce_dev->ce_sps.consumer.pipe, rc);
_qce_dump_descr_fifos_fail(pce_dev);
return rc;
}
rc = sps_transfer(pce_dev->ce_sps.producer.pipe,
&pce_dev->ce_sps.out_transfer);
if (rc) {
pr_err("sps_xfr() fail (producer pipe=0x%x) rc = %d,",
(u32)pce_dev->ce_sps.producer.pipe, rc);
return rc;
}
return rc;
}
/**
* Allocate and Connect a CE peripheral's SPS endpoint
*
* This function allocates endpoint context and
* connect it with memory endpoint by calling
* appropriate SPS driver APIs.
*
* Also registers a SPS callback function with
* SPS driver
*
* This function should only be called once typically
* during driver probe.
*
* @pce_dev - Pointer to qce_device structure
* @ep - Pointer to sps endpoint data structure
* @is_produce - 1 means Producer endpoint
* 0 means Consumer endpoint
*
* @return - 0 if successful else negative value.
*
*/
static int qce_sps_init_ep_conn(struct qce_device *pce_dev,
struct qce_sps_ep_conn_data *ep,
bool is_producer)
{
int rc = 0;
struct sps_pipe *sps_pipe_info;
struct sps_connect *sps_connect_info = &ep->connect;
struct sps_register_event *sps_event = &ep->event;
/* Allocate endpoint context */
sps_pipe_info = sps_alloc_endpoint();
if (!sps_pipe_info) {
pr_err("sps_alloc_endpoint() failed!!! is_producer=%d",
is_producer);
rc = -ENOMEM;
goto out;
}
/* Now save the sps pipe handle */
ep->pipe = sps_pipe_info;
/* Get default connection configuration for an endpoint */
rc = sps_get_config(sps_pipe_info, sps_connect_info);
if (rc) {
pr_err("sps_get_config() fail pipe_handle=0x%x, rc = %d\n",
(u32)sps_pipe_info, rc);
goto get_config_err;
}
/* Modify the default connection configuration */
if (is_producer) {
/*
* For CE producer transfer, source should be
* CE peripheral where as destination should
* be system memory.
*/
sps_connect_info->source = pce_dev->ce_sps.bam_handle;
sps_connect_info->destination = SPS_DEV_HANDLE_MEM;
/* Producer pipe will handle this connection */
sps_connect_info->mode = SPS_MODE_SRC;
sps_connect_info->options =
SPS_O_AUTO_ENABLE | SPS_O_DESC_DONE;
} else {
/* For CE consumer transfer, source should be
* system memory where as destination should
* CE peripheral
*/
sps_connect_info->source = SPS_DEV_HANDLE_MEM;
sps_connect_info->destination = pce_dev->ce_sps.bam_handle;
sps_connect_info->mode = SPS_MODE_DEST;
sps_connect_info->options =
SPS_O_AUTO_ENABLE | SPS_O_EOT;
}
/* Producer pipe index */
sps_connect_info->src_pipe_index = pce_dev->ce_sps.src_pipe_index;
/* Consumer pipe index */
sps_connect_info->dest_pipe_index = pce_dev->ce_sps.dest_pipe_index;
/* Set pipe group */
sps_connect_info->lock_group = pce_dev->ce_sps.pipe_pair_index;
sps_connect_info->event_thresh = 0x10;
/*
* Max. no of scatter/gather buffers that can
* be passed by block layer = 32 (NR_SG).
* Each BAM descritor needs 64 bits (8 bytes).
* One BAM descriptor is required per buffer transfer.
* So we would require total 256 (32 * 8) bytes of descriptor FIFO.
* But due to HW limitation we need to allocate atleast one extra
* descriptor memory (256 bytes + 8 bytes). But in order to be
* in power of 2, we are allocating 512 bytes of memory.
*/
sps_connect_info->desc.size = QCE_MAX_NUM_DSCR *
sizeof(struct sps_iovec);
sps_connect_info->desc.base = dma_alloc_coherent(pce_dev->pdev,
sps_connect_info->desc.size,
&sps_connect_info->desc.phys_base,
GFP_KERNEL);
if (sps_connect_info->desc.base == NULL) {
rc = -ENOMEM;
pr_err("Can not allocate coherent memory for sps data\n");
goto get_config_err;
}
memset(sps_connect_info->desc.base, 0x00, sps_connect_info->desc.size);
/* Establish connection between peripheral and memory endpoint */
rc = sps_connect(sps_pipe_info, sps_connect_info);
if (rc) {
pr_err("sps_connect() fail pipe_handle=0x%x, rc = %d\n",
(u32)sps_pipe_info, rc);
goto sps_connect_err;
}
sps_event->mode = SPS_TRIGGER_CALLBACK;
if (is_producer)
sps_event->options = SPS_O_EOT | SPS_O_DESC_DONE;
else
sps_event->options = SPS_O_EOT;
sps_event->xfer_done = NULL;
sps_event->user = (void *)pce_dev;
pr_debug("success, %s : pipe_handle=0x%x, desc fifo base (phy) = 0x%x\n",
is_producer ? "PRODUCER(RX/OUT)" : "CONSUMER(TX/IN)",
(u32)sps_pipe_info, sps_connect_info->desc.phys_base);
goto out;
sps_connect_err:
dma_free_coherent(pce_dev->pdev,
sps_connect_info->desc.size,
sps_connect_info->desc.base,
sps_connect_info->desc.phys_base);
get_config_err:
sps_free_endpoint(sps_pipe_info);
out:
return rc;
}
/**
* Disconnect and Deallocate a CE peripheral's SPS endpoint
*
* This function disconnect endpoint and deallocates
* endpoint context.
*
* This function should only be called once typically
* during driver remove.
*
* @pce_dev - Pointer to qce_device structure
* @ep - Pointer to sps endpoint data structure
*
*/
static void qce_sps_exit_ep_conn(struct qce_device *pce_dev,
struct qce_sps_ep_conn_data *ep)
{
struct sps_pipe *sps_pipe_info = ep->pipe;
struct sps_connect *sps_connect_info = &ep->connect;
sps_disconnect(sps_pipe_info);
dma_free_coherent(pce_dev->pdev,
sps_connect_info->desc.size,
sps_connect_info->desc.base,
sps_connect_info->desc.phys_base);
sps_free_endpoint(sps_pipe_info);
}
/**
* Initialize SPS HW connected with CE core
*
* This function register BAM HW resources with
* SPS driver and then initialize 2 SPS endpoints
*
* This function should only be called once typically
* during driver probe.
*
* @pce_dev - Pointer to qce_device structure
*
* @return - 0 if successful else negative value.
*
*/
static int qce_sps_init(struct qce_device *pce_dev)
{
int rc = 0;
struct sps_bam_props bam = {0};
bool register_bam = false;
bam.phys_addr = pce_dev->ce_sps.bam_mem;
bam.virt_addr = pce_dev->ce_sps.bam_iobase;
/*
* This event thresold value is only significant for BAM-to-BAM
* transfer. It's ignored for BAM-to-System mode transfer.
*/
bam.event_threshold = 0x10; /* Pipe event threshold */
/*
* This threshold controls when the BAM publish
* the descriptor size on the sideband interface.
* SPS HW will only be used when
* data transfer size > 64 bytes.
*/
bam.summing_threshold = 64;
/* SPS driver wll handle the crypto BAM IRQ */
bam.irq = (u32)pce_dev->ce_sps.bam_irq;
/*
* Set flag to indicate BAM global device control is managed
* remotely.
*/
if ((pce_dev->support_cmd_dscr == false) || (pce_dev->is_shared))
bam.manage = SPS_BAM_MGR_DEVICE_REMOTE;
else
bam.manage = SPS_BAM_MGR_LOCAL;
bam.ee = 1;
pr_debug("bam physical base=0x%x\n", (u32)bam.phys_addr);
pr_debug("bam virtual base=0x%x\n", (u32)bam.virt_addr);
mutex_lock(&bam_register_cnt);
if (ce_bam_registered == false) {
bam_registry.handle = 0;
bam_registry.cnt = 0;
}
if ((bam_registry.handle == 0) && (bam_registry.cnt == 0)) {
/* Register CE Peripheral BAM device to SPS driver */
rc = sps_register_bam_device(&bam, &bam_registry.handle);
if (rc) {
mutex_unlock(&bam_register_cnt);
pr_err("sps_register_bam_device() failed! err=%d", rc);
return -EIO;
}
bam_registry.cnt++;
register_bam = true;
ce_bam_registered = true;
} else {
bam_registry.cnt++;
}
mutex_unlock(&bam_register_cnt);
pce_dev->ce_sps.bam_handle = bam_registry.handle;
pr_debug("BAM device registered. bam_handle=0x%x",
pce_dev->ce_sps.bam_handle);
rc = qce_sps_init_ep_conn(pce_dev, &pce_dev->ce_sps.producer, true);
if (rc)
goto sps_connect_producer_err;
rc = qce_sps_init_ep_conn(pce_dev, &pce_dev->ce_sps.consumer, false);
if (rc)
goto sps_connect_consumer_err;
pce_dev->ce_sps.out_transfer.user = pce_dev->ce_sps.producer.pipe;
pce_dev->ce_sps.in_transfer.user = pce_dev->ce_sps.consumer.pipe;
pr_info(" Qualcomm MSM CE-BAM at 0x%016llx irq %d\n",
(unsigned long long)pce_dev->ce_sps.bam_mem,
(unsigned int)pce_dev->ce_sps.bam_irq);
return rc;
sps_connect_consumer_err:
qce_sps_exit_ep_conn(pce_dev, &pce_dev->ce_sps.producer);
sps_connect_producer_err:
if (register_bam) {
mutex_lock(&bam_register_cnt);
sps_deregister_bam_device(pce_dev->ce_sps.bam_handle);
ce_bam_registered = false;
bam_registry.handle = 0;
bam_registry.cnt = 0;
mutex_unlock(&bam_register_cnt);
}
return rc;
}
/**
* De-initialize SPS HW connected with CE core
*
* This function deinitialize SPS endpoints and then
* deregisters BAM resources from SPS driver.
*
* This function should only be called once typically
* during driver remove.
*
* @pce_dev - Pointer to qce_device structure
*
*/
static void qce_sps_exit(struct qce_device *pce_dev)
{
qce_sps_exit_ep_conn(pce_dev, &pce_dev->ce_sps.consumer);
qce_sps_exit_ep_conn(pce_dev, &pce_dev->ce_sps.producer);
mutex_lock(&bam_register_cnt);
if ((bam_registry.handle != 0) && (bam_registry.cnt == 1)) {
sps_deregister_bam_device(pce_dev->ce_sps.bam_handle);
bam_registry.cnt = 0;
bam_registry.handle = 0;
}
if ((bam_registry.handle != 0) && (bam_registry.cnt > 1))
bam_registry.cnt--;
mutex_unlock(&bam_register_cnt);
iounmap(pce_dev->ce_sps.bam_iobase);
}
static void _aead_sps_producer_callback(struct sps_event_notify *notify)
{
struct qce_device *pce_dev = (struct qce_device *)
((struct sps_event_notify *)notify)->user;
pce_dev->ce_sps.notify = *notify;
pr_debug("sps ev_id=%d, addr=0x%x, size=0x%x, flags=0x%x\n",
notify->event_id,
notify->data.transfer.iovec.addr,
notify->data.transfer.iovec.size,
notify->data.transfer.iovec.flags);
if (pce_dev->ce_sps.producer_state == QCE_PIPE_STATE_COMP) {
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_IDLE;
/* done */
_aead_complete(pce_dev);
} else {
int rc = 0;
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_COMP;
pce_dev->ce_sps.out_transfer.iovec_count = 0;
_qce_sps_add_data(GET_PHYS_ADDR(pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer);
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
rc = sps_transfer(pce_dev->ce_sps.producer.pipe,
&pce_dev->ce_sps.out_transfer);
if (rc) {
pr_err("sps_xfr() fail (producer pipe=0x%x) rc = %d,",
(u32)pce_dev->ce_sps.producer.pipe, rc);
}
}
};
static void _sha_sps_producer_callback(struct sps_event_notify *notify)
{
struct qce_device *pce_dev = (struct qce_device *)
((struct sps_event_notify *)notify)->user;
pce_dev->ce_sps.notify = *notify;
pr_debug("sps ev_id=%d, addr=0x%x, size=0x%x, flags=0x%x\n",
notify->event_id,
notify->data.transfer.iovec.addr,
notify->data.transfer.iovec.size,
notify->data.transfer.iovec.flags);
/* done */
_sha_complete(pce_dev);
};
static void _ablk_cipher_sps_producer_callback(struct sps_event_notify *notify)
{
struct qce_device *pce_dev = (struct qce_device *)
((struct sps_event_notify *)notify)->user;
pce_dev->ce_sps.notify = *notify;
pr_debug("sps ev_id=%d, addr=0x%x, size=0x%x, flags=0x%x\n",
notify->event_id,
notify->data.transfer.iovec.addr,
notify->data.transfer.iovec.size,
notify->data.transfer.iovec.flags);
if (pce_dev->ce_sps.producer_state == QCE_PIPE_STATE_COMP) {
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_IDLE;
/* done */
_ablk_cipher_complete(pce_dev);
} else {
int rc = 0;
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_COMP;
pce_dev->ce_sps.out_transfer.iovec_count = 0;
_qce_sps_add_data(GET_PHYS_ADDR(pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer);
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
rc = sps_transfer(pce_dev->ce_sps.producer.pipe,
&pce_dev->ce_sps.out_transfer);
if (rc) {
pr_err("sps_xfr() fail (producer pipe=0x%x) rc = %d,",
(u32)pce_dev->ce_sps.producer.pipe, rc);
}
}
};
static void qce_add_cmd_element(struct qce_device *pdev,
struct sps_command_element **cmd_ptr, u32 addr,
u32 data, struct sps_command_element **populate)
{
(*cmd_ptr)->addr = (uint32_t)(addr + pdev->phy_iobase);
(*cmd_ptr)->data = data;
(*cmd_ptr)->mask = 0xFFFFFFFF;
if (populate != NULL)
*populate = *cmd_ptr;
(*cmd_ptr)++ ;
}
static int _setup_cipher_aes_cmdlistptrs(struct qce_device *pdev,
unsigned char **pvaddr, enum qce_cipher_mode_enum mode,
bool key_128)
{
struct sps_command_element *ce_vaddr;
uint32_t ce_vaddr_start;
struct qce_cmdlistptr_ops *cmdlistptr = &pdev->ce_sps.cmdlistptr;
struct qce_cmdlist_info *pcl_info = NULL;
int i = 0;
uint32_t encr_cfg = 0;
uint32_t key_reg = 0;
uint32_t xts_key_reg = 0;
uint32_t iv_reg = 0;
*pvaddr = (unsigned char *) ALIGN(((unsigned int)(*pvaddr)),
pdev->ce_sps.ce_burst_size);
ce_vaddr = (struct sps_command_element *)(*pvaddr);
ce_vaddr_start = (uint32_t)(*pvaddr);
/*
* Designate chunks of the allocated memory to various
* command list pointers related to AES cipher operations defined
* in ce_cmdlistptrs_ops structure.
*/
switch (mode) {
case QCE_MODE_CBC:
case QCE_MODE_CTR:
if (key_128 == true) {
cmdlistptr->cipher_aes_128_cbc_ctr.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_aes_128_cbc_ctr);
if (mode == QCE_MODE_CBC)
encr_cfg = pdev->reg.encr_cfg_aes_cbc_128;
else
encr_cfg = pdev->reg.encr_cfg_aes_ctr_128;
iv_reg = 4;
key_reg = 4;
xts_key_reg = 0;
} else {
cmdlistptr->cipher_aes_256_cbc_ctr.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_aes_256_cbc_ctr);
if (mode == QCE_MODE_CBC)
encr_cfg = pdev->reg.encr_cfg_aes_cbc_256;
else
encr_cfg = pdev->reg.encr_cfg_aes_ctr_256;
iv_reg = 4;
key_reg = 8;
xts_key_reg = 0;
}
break;
case QCE_MODE_ECB:
if (key_128 == true) {
cmdlistptr->cipher_aes_128_ecb.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_aes_128_ecb);
encr_cfg = pdev->reg.encr_cfg_aes_ecb_128;
iv_reg = 0;
key_reg = 4;
xts_key_reg = 0;
} else {
cmdlistptr->cipher_aes_256_ecb.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_aes_256_ecb);
encr_cfg = pdev->reg.encr_cfg_aes_ecb_256;
iv_reg = 0;
key_reg = 8;
xts_key_reg = 0;
}
break;
case QCE_MODE_XTS:
if (key_128 == true) {
cmdlistptr->cipher_aes_128_xts.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_aes_128_xts);
encr_cfg = pdev->reg.encr_cfg_aes_xts_128;
iv_reg = 4;
key_reg = 4;
xts_key_reg = 4;
} else {
cmdlistptr->cipher_aes_256_xts.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_aes_256_xts);
encr_cfg = pdev->reg.encr_cfg_aes_xts_256;
iv_reg = 4;
key_reg = 8;
xts_key_reg = 8;
}
break;
default:
pr_err("Unknown mode of operation %d received, exiting now\n",
mode);
return -EINVAL;
break;
}
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG, 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_SEG_SIZE_REG, 0,
&pcl_info->seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_CFG_REG, encr_cfg,
&pcl_info->encr_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_SIZE_REG, 0,
&pcl_info->encr_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_START_REG, 0,
&pcl_info->encr_seg_start);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CNTR_MASK_REG,
(uint32_t)0xffffffff, &pcl_info->encr_mask);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_CFG_REG, 0,
&pcl_info->auth_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_KEY0_REG, 0,
&pcl_info->encr_key);
for (i = 1; i < key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_ENCR_KEY0_REG + i * sizeof(uint32_t)),
0, NULL);
if (xts_key_reg) {
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_XTS_KEY0_REG,
0, &pcl_info->encr_xts_key);
for (i = 1; i < xts_key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_ENCR_XTS_KEY0_REG +
i * sizeof(uint32_t)), 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr,
CRYPTO_ENCR_XTS_DU_SIZE_REG, 0,
&pcl_info->encr_xts_du_size);
}
if (iv_reg) {
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CNTR0_IV0_REG, 0,
&pcl_info->encr_cntr_iv);
for (i = 1; i < iv_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_CNTR0_IV0_REG + i * sizeof(uint32_t)),
0, NULL);
}
/* Add dummy to align size to burst-size multiple */
if (mode == QCE_MODE_XTS) {
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_SIZE_REG,
0, &pcl_info->auth_seg_size);
} else {
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_SIZE_REG,
0, &pcl_info->auth_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_START_REG,
0, &pcl_info->auth_seg_size);
}
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_le, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_GOPROC_REG,
((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
&pcl_info->go_proc);
pcl_info->size = (uint32_t)ce_vaddr - (uint32_t)ce_vaddr_start;
*pvaddr = (unsigned char *) ce_vaddr;
return 0;
}
static int _setup_cipher_des_cmdlistptrs(struct qce_device *pdev,
unsigned char **pvaddr, enum qce_cipher_alg_enum alg,
bool mode_cbc)
{
struct sps_command_element *ce_vaddr;
uint32_t ce_vaddr_start;
struct qce_cmdlistptr_ops *cmdlistptr = &pdev->ce_sps.cmdlistptr;
struct qce_cmdlist_info *pcl_info = NULL;
int i = 0;
uint32_t encr_cfg = 0;
uint32_t key_reg = 0;
uint32_t iv_reg = 0;
*pvaddr = (unsigned char *) ALIGN(((unsigned int)(*pvaddr)),
pdev->ce_sps.ce_burst_size);
ce_vaddr = (struct sps_command_element *)(*pvaddr);
ce_vaddr_start = (uint32_t)(*pvaddr);
/*
* Designate chunks of the allocated memory to various
* command list pointers related to cipher operations defined
* in ce_cmdlistptrs_ops structure.
*/
switch (alg) {
case CIPHER_ALG_DES:
if (mode_cbc) {
cmdlistptr->cipher_des_cbc.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_des_cbc);
encr_cfg = pdev->reg.encr_cfg_des_cbc;
iv_reg = 2;
key_reg = 2;
} else {
cmdlistptr->cipher_des_ecb.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_des_ecb);
encr_cfg = pdev->reg.encr_cfg_des_ecb;
iv_reg = 0;
key_reg = 2;
}
break;
case CIPHER_ALG_3DES:
if (mode_cbc) {
cmdlistptr->cipher_3des_cbc.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_3des_cbc);
encr_cfg = pdev->reg.encr_cfg_3des_cbc;
iv_reg = 2;
key_reg = 6;
} else {
cmdlistptr->cipher_3des_ecb.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->cipher_3des_ecb);
encr_cfg = pdev->reg.encr_cfg_3des_ecb;
iv_reg = 0;
key_reg = 6;
}
break;
default:
pr_err("Unknown algorithms %d received, exiting now\n", alg);
return -EINVAL;
break;
}
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG, 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_SEG_SIZE_REG, 0,
&pcl_info->seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_CFG_REG, encr_cfg,
&pcl_info->encr_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_SIZE_REG, 0,
&pcl_info->encr_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_START_REG, 0,
&pcl_info->encr_seg_start);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_CFG_REG, 0,
&pcl_info->auth_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_KEY0_REG, 0,
&pcl_info->encr_key);
for (i = 1; i < key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_ENCR_KEY0_REG + i * sizeof(uint32_t)),
0, NULL);
if (iv_reg) {
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CNTR0_IV0_REG, 0,
&pcl_info->encr_cntr_iv);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CNTR1_IV1_REG, 0,
NULL);
}
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_le, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_GOPROC_REG,
((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
&pcl_info->go_proc);
pcl_info->size = (uint32_t)ce_vaddr - (uint32_t)ce_vaddr_start;
*pvaddr = (unsigned char *) ce_vaddr;
return 0;
}
static int _setup_auth_cmdlistptrs(struct qce_device *pdev,
unsigned char **pvaddr, enum qce_hash_alg_enum alg,
bool key_128)
{
struct sps_command_element *ce_vaddr;
uint32_t ce_vaddr_start;
struct qce_cmdlistptr_ops *cmdlistptr = &pdev->ce_sps.cmdlistptr;
struct qce_cmdlist_info *pcl_info = NULL;
int i = 0;
uint32_t key_reg = 0;
uint32_t auth_cfg = 0;
uint32_t iv_reg = 0;
*pvaddr = (unsigned char *) ALIGN(((unsigned int)(*pvaddr)),
pdev->ce_sps.ce_burst_size);
ce_vaddr_start = (uint32_t)(*pvaddr);
ce_vaddr = (struct sps_command_element *)(*pvaddr);
/*
* Designate chunks of the allocated memory to various
* command list pointers related to authentication operations
* defined in ce_cmdlistptrs_ops structure.
*/
switch (alg) {
case QCE_HASH_SHA1:
cmdlistptr->auth_sha1.cmdlist = (uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->auth_sha1);
auth_cfg = pdev->reg.auth_cfg_sha1;
iv_reg = 5;
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG,
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
break;
case QCE_HASH_SHA256:
cmdlistptr->auth_sha256.cmdlist = (uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->auth_sha256);
auth_cfg = pdev->reg.auth_cfg_sha256;
iv_reg = 8;
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG,
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
/* 1 dummy write */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_SIZE_REG,
0, NULL);
break;
case QCE_HASH_SHA1_HMAC:
cmdlistptr->auth_sha1_hmac.cmdlist = (uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->auth_sha1_hmac);
auth_cfg = pdev->reg.auth_cfg_hmac_sha1;
key_reg = 16;
iv_reg = 5;
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG,
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
break;
case QCE_HASH_SHA256_HMAC:
cmdlistptr->auth_sha256_hmac.cmdlist = (uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->auth_sha256_hmac);
auth_cfg = pdev->reg.auth_cfg_hmac_sha256;
key_reg = 16;
iv_reg = 8;
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG, 0,
NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
/* 1 dummy write */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_SIZE_REG,
0, NULL);
break;
case QCE_HASH_AES_CMAC:
if (key_128 == true) {
cmdlistptr->auth_aes_128_cmac.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->auth_aes_128_cmac);
auth_cfg = pdev->reg.auth_cfg_cmac_128;
key_reg = 4;
} else {
cmdlistptr->auth_aes_256_cmac.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->auth_aes_256_cmac);
auth_cfg = pdev->reg.auth_cfg_cmac_256;
key_reg = 8;
}
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG, 0,
NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
/* 1 dummy write */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_SIZE_REG,
0, NULL);
break;
default:
pr_err("Unknown algorithms %d received, exiting now\n", alg);
return -EINVAL;
break;
}
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_SEG_SIZE_REG, 0,
&pcl_info->seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_CFG_REG, 0,
&pcl_info->encr_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_CFG_REG,
auth_cfg, &pcl_info->auth_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_SIZE_REG, 0,
&pcl_info->auth_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_START_REG, 0,
&pcl_info->auth_seg_start);
if (alg == QCE_HASH_AES_CMAC) {
/* reset auth iv, bytecount and key registers */
for (i = 0; i < 16; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_IV0_REG + i * sizeof(uint32_t)),
0, NULL);
for (i = 0; i < 16; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_KEY0_REG + i*sizeof(uint32_t)),
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_BYTECNT0_REG,
0, NULL);
} else {
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_IV0_REG, 0,
&pcl_info->auth_iv);
for (i = 1; i < iv_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_IV0_REG + i*sizeof(uint32_t)),
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_BYTECNT0_REG,
0, &pcl_info->auth_bytecount);
}
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_BYTECNT1_REG, 0, NULL);
if (key_reg) {
qce_add_cmd_element(pdev, &ce_vaddr,
CRYPTO_AUTH_KEY0_REG, 0, &pcl_info->auth_key);
for (i = 1; i < key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_KEY0_REG + i*sizeof(uint32_t)),
0, NULL);
}
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_le, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_GOPROC_REG,
((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
&pcl_info->go_proc);
pcl_info->size = (uint32_t)ce_vaddr - (uint32_t)ce_vaddr_start;
*pvaddr = (unsigned char *) ce_vaddr;
return 0;
}
static int _setup_aead_cmdlistptrs(struct qce_device *pdev,
unsigned char **pvaddr,
uint32_t alg,
uint32_t mode,
uint32_t key_size)
{
struct sps_command_element *ce_vaddr;
uint32_t ce_vaddr_start;
struct qce_cmdlistptr_ops *cmdlistptr = &pdev->ce_sps.cmdlistptr;
struct qce_cmdlist_info *pcl_info = NULL;
uint32_t key_reg;
uint32_t iv_reg;
uint32_t i;
uint32_t enciv_in_word;
uint32_t encr_cfg;
*pvaddr = (unsigned char *) ALIGN(((unsigned int)(*pvaddr)),
pdev->ce_sps.ce_burst_size);
ce_vaddr_start = (uint32_t)(*pvaddr);
ce_vaddr = (struct sps_command_element *)(*pvaddr);
switch (alg) {
case CIPHER_ALG_DES:
switch (mode) {
case QCE_MODE_ECB:
cmdlistptr->aead_hmac_sha1_ecb_des.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->aead_hmac_sha1_ecb_des);
encr_cfg = pdev->reg.encr_cfg_des_ecb;
break;
case QCE_MODE_CBC:
cmdlistptr->aead_hmac_sha1_cbc_des.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->aead_hmac_sha1_cbc_des);
encr_cfg = pdev->reg.encr_cfg_des_cbc;
break;
default:
return -EINVAL;
};
enciv_in_word = 2;
break;
case CIPHER_ALG_3DES:
switch (mode) {
case QCE_MODE_ECB:
cmdlistptr->aead_hmac_sha1_ecb_3des.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->aead_hmac_sha1_ecb_3des);
encr_cfg = pdev->reg.encr_cfg_3des_ecb;
break;
case QCE_MODE_CBC:
cmdlistptr->aead_hmac_sha1_cbc_3des.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->aead_hmac_sha1_cbc_3des);
encr_cfg = pdev->reg.encr_cfg_3des_cbc;
break;
default:
return -EINVAL;
};
enciv_in_word = 2;
break;
case CIPHER_ALG_AES:
switch (mode) {
case QCE_MODE_ECB:
if (key_size == AES128_KEY_SIZE) {
cmdlistptr->aead_hmac_sha1_ecb_aes_128.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->
aead_hmac_sha1_ecb_aes_128);
encr_cfg = pdev->reg.encr_cfg_aes_ecb_128;
} else if (key_size == AES256_KEY_SIZE) {
cmdlistptr->aead_hmac_sha1_ecb_aes_256.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->
aead_hmac_sha1_ecb_aes_256);
encr_cfg = pdev->reg.encr_cfg_aes_ecb_256;
} else {
return -EINVAL;
}
break;
case QCE_MODE_CBC:
if (key_size == AES128_KEY_SIZE) {
cmdlistptr->aead_hmac_sha1_cbc_aes_128.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->
aead_hmac_sha1_cbc_aes_128);
encr_cfg = pdev->reg.encr_cfg_aes_cbc_128;
} else if (key_size == AES256_KEY_SIZE) {
cmdlistptr->aead_hmac_sha1_cbc_aes_256.cmdlist =
(uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->
aead_hmac_sha1_cbc_aes_256);
encr_cfg = pdev->reg.encr_cfg_aes_cbc_256;
} else {
return -EINVAL;
}
break;
default:
return -EINVAL;
};
enciv_in_word = 4;
break;
default:
return -EINVAL;
};
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG, 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
key_reg = key_size/sizeof(uint32_t);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_KEY0_REG, 0,
&pcl_info->encr_key);
for (i = 1; i < key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_ENCR_KEY0_REG + i * sizeof(uint32_t)),
0, NULL);
if (mode != QCE_MODE_ECB) {
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CNTR0_IV0_REG, 0,
&pcl_info->encr_cntr_iv);
for (i = 1; i < enciv_in_word; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_CNTR0_IV0_REG + i * sizeof(uint32_t)),
0, NULL);
};
iv_reg = 5;
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_IV0_REG, 0,
&pcl_info->auth_iv);
for (i = 1; i < iv_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_IV0_REG + i*sizeof(uint32_t)),
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_BYTECNT0_REG,
0, &pcl_info->auth_bytecount);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_BYTECNT1_REG, 0, NULL);
key_reg = SHA_HMAC_KEY_SIZE/sizeof(uint32_t);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_KEY0_REG, 0,
&pcl_info->auth_key);
for (i = 1; i < key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_KEY0_REG + i*sizeof(uint32_t)), 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_SEG_SIZE_REG, 0,
&pcl_info->seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_CFG_REG, encr_cfg,
&pcl_info->encr_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_SIZE_REG, 0,
&pcl_info->encr_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_START_REG, 0,
&pcl_info->encr_seg_start);
qce_add_cmd_element(
pdev,
&ce_vaddr,
CRYPTO_AUTH_SEG_CFG_REG,
pdev->reg.auth_cfg_aead_sha1_hmac,
&pcl_info->auth_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_SIZE_REG, 0,
&pcl_info->auth_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_START_REG, 0,
&pcl_info->auth_seg_start);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_le, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_GOPROC_REG,
((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
&pcl_info->go_proc);
pcl_info->size = (uint32_t)ce_vaddr - (uint32_t)ce_vaddr_start;
*pvaddr = (unsigned char *) ce_vaddr;
return 0;
}
static int _setup_aead_ccm_cmdlistptrs(struct qce_device *pdev,
unsigned char **pvaddr, bool key_128)
{
struct sps_command_element *ce_vaddr;
uint32_t ce_vaddr_start;
struct qce_cmdlistptr_ops *cmdlistptr = &pdev->ce_sps.cmdlistptr;
struct qce_cmdlist_info *pcl_info = NULL;
int i = 0;
uint32_t encr_cfg = 0;
uint32_t auth_cfg = 0;
uint32_t key_reg = 0;
*pvaddr = (unsigned char *) ALIGN(((unsigned int)(*pvaddr)),
pdev->ce_sps.ce_burst_size);
ce_vaddr_start = (uint32_t)(*pvaddr);
ce_vaddr = (struct sps_command_element *)(*pvaddr);
/*
* Designate chunks of the allocated memory to various
* command list pointers related to aead operations
* defined in ce_cmdlistptrs_ops structure.
*/
if (key_128 == true) {
cmdlistptr->aead_aes_128_ccm.cmdlist = (uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->aead_aes_128_ccm);
auth_cfg = pdev->reg.auth_cfg_aes_ccm_128;
encr_cfg = pdev->reg.encr_cfg_aes_ccm_128;
key_reg = 4;
} else {
cmdlistptr->aead_aes_256_ccm.cmdlist = (uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->aead_aes_256_ccm);
auth_cfg = pdev->reg.auth_cfg_aes_ccm_256;
encr_cfg = pdev->reg.encr_cfg_aes_ccm_256;
key_reg = 8;
}
/* clear status register */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_STATUS_REG, 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_be, &pcl_info->crypto_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_CFG_REG, 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_START_REG, 0,
NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_SEG_SIZE_REG, 0,
&pcl_info->seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_CFG_REG,
encr_cfg, &pcl_info->encr_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_SIZE_REG, 0,
&pcl_info->encr_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_SEG_START_REG, 0,
&pcl_info->encr_seg_start);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CNTR_MASK_REG,
(uint32_t)0xffffffff, &pcl_info->encr_mask);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_CFG_REG,
auth_cfg, &pcl_info->auth_seg_cfg);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_SIZE_REG, 0,
&pcl_info->auth_seg_size);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_SEG_START_REG, 0,
&pcl_info->auth_seg_start);
/* reset auth iv, bytecount and key registers */
for (i = 0; i < 8; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_IV0_REG + i * sizeof(uint32_t)),
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_BYTECNT0_REG,
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_BYTECNT1_REG,
0, NULL);
for (i = 0; i < 16; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_KEY0_REG + i * sizeof(uint32_t)),
0, NULL);
/* set auth key */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_KEY0_REG, 0,
&pcl_info->auth_key);
for (i = 1; i < key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_KEY0_REG + i * sizeof(uint32_t)),
0, NULL);
/* set NONCE info */
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_AUTH_INFO_NONCE0_REG, 0,
&pcl_info->auth_nonce_info);
for (i = 1; i < 4; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_AUTH_INFO_NONCE0_REG +
i * sizeof(uint32_t)), 0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_KEY0_REG, 0,
&pcl_info->encr_key);
for (i = 1; i < key_reg; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_ENCR_KEY0_REG + i * sizeof(uint32_t)),
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CNTR0_IV0_REG, 0,
&pcl_info->encr_cntr_iv);
for (i = 1; i < 4; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_CNTR0_IV0_REG + i * sizeof(uint32_t)),
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_ENCR_CCM_INT_CNTR0_REG, 0,
&pcl_info->encr_ccm_cntr_iv);
for (i = 1; i < 4; i++)
qce_add_cmd_element(pdev, &ce_vaddr,
(CRYPTO_ENCR_CCM_INT_CNTR0_REG + i * sizeof(uint32_t)),
0, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
pdev->reg.crypto_cfg_le, NULL);
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_GOPROC_REG,
((1 << CRYPTO_GO) | (1 << CRYPTO_RESULTS_DUMP)),
&pcl_info->go_proc);
pcl_info->size = (uint32_t)ce_vaddr - (uint32_t)ce_vaddr_start;
*pvaddr = (unsigned char *) ce_vaddr;
return 0;
}
static int _setup_unlock_pipe_cmdlistptrs(struct qce_device *pdev,
unsigned char **pvaddr)
{
struct sps_command_element *ce_vaddr;
uint32_t ce_vaddr_start = (uint32_t)(*pvaddr);
struct qce_cmdlistptr_ops *cmdlistptr = &pdev->ce_sps.cmdlistptr;
struct qce_cmdlist_info *pcl_info = NULL;
*pvaddr = (unsigned char *) ALIGN(((unsigned int)(*pvaddr)),
pdev->ce_sps.ce_burst_size);
ce_vaddr = (struct sps_command_element *)(*pvaddr);
cmdlistptr->unlock_all_pipes.cmdlist = (uint32_t)ce_vaddr;
pcl_info = &(cmdlistptr->unlock_all_pipes);
/*
* Designate chunks of the allocated memory to command list
* to unlock pipes.
*/
qce_add_cmd_element(pdev, &ce_vaddr, CRYPTO_CONFIG_REG,
CRYPTO_CONFIG_RESET, NULL);
pcl_info->size = (uint32_t)ce_vaddr - (uint32_t)ce_vaddr_start;
*pvaddr = (unsigned char *) ce_vaddr;
return 0;
}
static int qce_setup_cmdlistptrs(struct qce_device *pdev,
unsigned char **pvaddr)
{
struct sps_command_element *ce_vaddr =
(struct sps_command_element *)(*pvaddr);
/*
* Designate chunks of the allocated memory to various
* command list pointers related to operations defined
* in ce_cmdlistptrs_ops structure.
*/
ce_vaddr =
(struct sps_command_element *) ALIGN(((unsigned int) ce_vaddr),
pdev->ce_sps.ce_burst_size);
*pvaddr = (unsigned char *) ce_vaddr;
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_CBC, true);
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_CTR, true);
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_ECB, true);
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_XTS, true);
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_CBC, false);
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_CTR, false);
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_ECB, false);
_setup_cipher_aes_cmdlistptrs(pdev, pvaddr, QCE_MODE_XTS, false);
_setup_cipher_des_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_DES, true);
_setup_cipher_des_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_DES, false);
_setup_cipher_des_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_3DES, true);
_setup_cipher_des_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_3DES, false);
_setup_auth_cmdlistptrs(pdev, pvaddr, QCE_HASH_SHA1, false);
_setup_auth_cmdlistptrs(pdev, pvaddr, QCE_HASH_SHA256, false);
_setup_auth_cmdlistptrs(pdev, pvaddr, QCE_HASH_SHA1_HMAC, false);
_setup_auth_cmdlistptrs(pdev, pvaddr, QCE_HASH_SHA256_HMAC, false);
_setup_auth_cmdlistptrs(pdev, pvaddr, QCE_HASH_AES_CMAC, true);
_setup_auth_cmdlistptrs(pdev, pvaddr, QCE_HASH_AES_CMAC, false);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_DES, QCE_MODE_CBC,
DES_KEY_SIZE);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_DES, QCE_MODE_ECB,
DES_KEY_SIZE);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_3DES, QCE_MODE_CBC,
DES3_EDE_KEY_SIZE);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_3DES, QCE_MODE_ECB,
DES3_EDE_KEY_SIZE);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_AES, QCE_MODE_CBC,
AES128_KEY_SIZE);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_AES, QCE_MODE_ECB,
AES128_KEY_SIZE);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_AES, QCE_MODE_CBC,
AES256_KEY_SIZE);
_setup_aead_cmdlistptrs(pdev, pvaddr, CIPHER_ALG_AES, QCE_MODE_ECB,
AES256_KEY_SIZE);
_setup_aead_ccm_cmdlistptrs(pdev, pvaddr, true);
_setup_aead_ccm_cmdlistptrs(pdev, pvaddr, false);
_setup_unlock_pipe_cmdlistptrs(pdev, pvaddr);
return 0;
}
static int qce_setup_ce_sps_data(struct qce_device *pce_dev)
{
unsigned char *vaddr;
vaddr = pce_dev->coh_vmem;
vaddr = (unsigned char *) ALIGN(((unsigned int)vaddr),
pce_dev->ce_sps.ce_burst_size);
/* Allow for 256 descriptor (cmd and data) entries per pipe */
pce_dev->ce_sps.in_transfer.iovec = (struct sps_iovec *)vaddr;
pce_dev->ce_sps.in_transfer.iovec_phys =
(uint32_t)GET_PHYS_ADDR(vaddr);
vaddr += QCE_MAX_NUM_DSCR * sizeof(struct sps_iovec);
pce_dev->ce_sps.out_transfer.iovec = (struct sps_iovec *)vaddr;
pce_dev->ce_sps.out_transfer.iovec_phys =
(uint32_t)GET_PHYS_ADDR(vaddr);
vaddr += QCE_MAX_NUM_DSCR * sizeof(struct sps_iovec);
if (pce_dev->support_cmd_dscr)
qce_setup_cmdlistptrs(pce_dev, &vaddr);
vaddr = (unsigned char *) ALIGN(((unsigned int)vaddr),
pce_dev->ce_sps.ce_burst_size);
pce_dev->ce_sps.result_dump = (uint32_t)vaddr;
pce_dev->ce_sps.result = (struct ce_result_dump_format *)vaddr;
vaddr += CRYPTO_RESULT_DUMP_SIZE;
pce_dev->ce_sps.ignore_buffer = (uint32_t)vaddr;
vaddr += pce_dev->ce_sps.ce_burst_size * 2;
if ((vaddr - pce_dev->coh_vmem) > pce_dev->memsize)
panic("qce50: Not enough coherent memory. Allocate %x , need %x",
pce_dev->memsize, vaddr - pce_dev->coh_vmem);
return 0;
}
static int qce_init_ce_cfg_val(struct qce_device *pce_dev)
{
uint32_t beats = (pce_dev->ce_sps.ce_burst_size >> 3) - 1;
uint32_t pipe_pair = pce_dev->ce_sps.pipe_pair_index;
pce_dev->reg.crypto_cfg_be = (beats << CRYPTO_REQ_SIZE) |
BIT(CRYPTO_MASK_DOUT_INTR) | BIT(CRYPTO_MASK_DIN_INTR) |
BIT(CRYPTO_MASK_OP_DONE_INTR) | (0 << CRYPTO_HIGH_SPD_EN_N) |
(pipe_pair << CRYPTO_PIPE_SET_SELECT);
pce_dev->reg.crypto_cfg_le =
(pce_dev->reg.crypto_cfg_be | CRYPTO_LITTLE_ENDIAN_MASK);
/* Initialize encr_cfg register for AES alg */
pce_dev->reg.encr_cfg_aes_cbc_128 =
(CRYPTO_ENCR_KEY_SZ_AES128 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CBC << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_cbc_256 =
(CRYPTO_ENCR_KEY_SZ_AES256 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CBC << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_ctr_128 =
(CRYPTO_ENCR_KEY_SZ_AES128 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CTR << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_ctr_256 =
(CRYPTO_ENCR_KEY_SZ_AES256 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CTR << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_xts_128 =
(CRYPTO_ENCR_KEY_SZ_AES128 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_XTS << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_xts_256 =
(CRYPTO_ENCR_KEY_SZ_AES256 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_XTS << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_ecb_128 =
(CRYPTO_ENCR_KEY_SZ_AES128 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_ECB << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_ecb_256 =
(CRYPTO_ENCR_KEY_SZ_AES256 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_ECB << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_aes_ccm_128 =
(CRYPTO_ENCR_KEY_SZ_AES128 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CCM << CRYPTO_ENCR_MODE)|
(CRYPTO_LAST_CCM_XFR << CRYPTO_LAST_CCM);
pce_dev->reg.encr_cfg_aes_ccm_256 =
(CRYPTO_ENCR_KEY_SZ_AES256 << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_AES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CCM << CRYPTO_ENCR_MODE) |
(CRYPTO_LAST_CCM_XFR << CRYPTO_LAST_CCM);
/* Initialize encr_cfg register for DES alg */
pce_dev->reg.encr_cfg_des_ecb =
(CRYPTO_ENCR_KEY_SZ_DES << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_DES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_ECB << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_des_cbc =
(CRYPTO_ENCR_KEY_SZ_DES << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_DES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CBC << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_3des_ecb =
(CRYPTO_ENCR_KEY_SZ_3DES << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_DES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_ECB << CRYPTO_ENCR_MODE);
pce_dev->reg.encr_cfg_3des_cbc =
(CRYPTO_ENCR_KEY_SZ_3DES << CRYPTO_ENCR_KEY_SZ) |
(CRYPTO_ENCR_ALG_DES << CRYPTO_ENCR_ALG) |
(CRYPTO_ENCR_MODE_CBC << CRYPTO_ENCR_MODE);
/* Initialize auth_cfg register for CMAC alg */
pce_dev->reg.auth_cfg_cmac_128 =
(1 << CRYPTO_LAST) | (1 << CRYPTO_FIRST) |
(CRYPTO_AUTH_MODE_CMAC << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_ENUM_16_BYTES << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_AES << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_KEY_SZ_AES128 << CRYPTO_AUTH_KEY_SIZE);
pce_dev->reg.auth_cfg_cmac_256 =
(1 << CRYPTO_LAST) | (1 << CRYPTO_FIRST) |
(CRYPTO_AUTH_MODE_CMAC << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_ENUM_16_BYTES << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_AES << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_KEY_SZ_AES256 << CRYPTO_AUTH_KEY_SIZE);
/* Initialize auth_cfg register for HMAC alg */
pce_dev->reg.auth_cfg_hmac_sha1 =
(CRYPTO_AUTH_MODE_HMAC << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_SHA1 << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_SHA << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
pce_dev->reg.auth_cfg_hmac_sha256 =
(CRYPTO_AUTH_MODE_HMAC << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_SHA256 << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_SHA << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
/* Initialize auth_cfg register for SHA1/256 alg */
pce_dev->reg.auth_cfg_sha1 =
(CRYPTO_AUTH_MODE_HASH << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_SHA1 << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_SHA << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
pce_dev->reg.auth_cfg_sha256 =
(CRYPTO_AUTH_MODE_HASH << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_SHA256 << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_SHA << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_POS_BEFORE << CRYPTO_AUTH_POS);
/* Initialize auth_cfg register for AEAD alg */
pce_dev->reg.auth_cfg_aead_sha1_hmac =
(CRYPTO_AUTH_MODE_HMAC << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_SHA1 << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_SHA << CRYPTO_AUTH_ALG) |
(1 << CRYPTO_LAST) | (1 << CRYPTO_FIRST);
pce_dev->reg.auth_cfg_aead_sha256_hmac =
(CRYPTO_AUTH_MODE_HMAC << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_SIZE_SHA256 << CRYPTO_AUTH_SIZE) |
(CRYPTO_AUTH_ALG_SHA << CRYPTO_AUTH_ALG) |
(1 << CRYPTO_LAST) | (1 << CRYPTO_FIRST);
pce_dev->reg.auth_cfg_aes_ccm_128 =
(1 << CRYPTO_LAST) | (1 << CRYPTO_FIRST) |
(CRYPTO_AUTH_MODE_CCM << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_ALG_AES << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_KEY_SZ_AES128 << CRYPTO_AUTH_KEY_SIZE) |
((MAX_NONCE/sizeof(uint32_t)) << CRYPTO_AUTH_NONCE_NUM_WORDS);
pce_dev->reg.auth_cfg_aes_ccm_128 &= ~(1 << CRYPTO_USE_HW_KEY_AUTH);
pce_dev->reg.auth_cfg_aes_ccm_256 =
(1 << CRYPTO_LAST) | (1 << CRYPTO_FIRST) |
(CRYPTO_AUTH_MODE_CCM << CRYPTO_AUTH_MODE)|
(CRYPTO_AUTH_ALG_AES << CRYPTO_AUTH_ALG) |
(CRYPTO_AUTH_KEY_SZ_AES256 << CRYPTO_AUTH_KEY_SIZE) |
((MAX_NONCE/sizeof(uint32_t)) << CRYPTO_AUTH_NONCE_NUM_WORDS);
pce_dev->reg.auth_cfg_aes_ccm_256 &= ~(1 << CRYPTO_USE_HW_KEY_AUTH);
return 0;
}
static int _qce_aead_ccm_req(void *handle, struct qce_req *q_req)
{
struct qce_device *pce_dev = (struct qce_device *) handle;
struct aead_request *areq = (struct aead_request *) q_req->areq;
uint32_t authsize = q_req->authsize;
uint32_t totallen_in, out_len;
uint32_t hw_pad_out = 0;
int rc = 0;
int ce_burst_size;
struct qce_cmdlist_info *cmdlistinfo = NULL;
ce_burst_size = pce_dev->ce_sps.ce_burst_size;
totallen_in = areq->cryptlen + areq->assoclen;
if (q_req->dir == QCE_ENCRYPT) {
q_req->cryptlen = areq->cryptlen;
out_len = areq->cryptlen + authsize;
hw_pad_out = ALIGN(authsize, ce_burst_size) - authsize;
} else {
q_req->cryptlen = areq->cryptlen - authsize;
out_len = q_req->cryptlen;
hw_pad_out = authsize;
}
if (pce_dev->ce_sps.minor_version == 0) {
/*
* For crypto 5.0 that has burst size alignment requirement
* for data descritpor,
* the agent above(qcrypto) prepares the src scatter list with
* memory starting with associated data, followed by
* data stream to be ciphered.
* The destination scatter list is pointing to the same
* data area as source.
*/
pce_dev->src_nents = count_sg(areq->src, totallen_in);
} else {
pce_dev->src_nents = count_sg(areq->src, areq->cryptlen);
}
pce_dev->assoc_nents = count_sg(areq->assoc, areq->assoclen);
pce_dev->authsize = q_req->authsize;
/* associated data input */
qce_dma_map_sg(pce_dev->pdev, areq->assoc, pce_dev->assoc_nents,
DMA_TO_DEVICE);
/* cipher input */
qce_dma_map_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
(areq->src == areq->dst) ? DMA_BIDIRECTIONAL :
DMA_TO_DEVICE);
/* cipher + mac output for encryption */
if (areq->src != areq->dst) {
if (pce_dev->ce_sps.minor_version == 0)
/*
* The destination scatter list is pointing to the same
* data area as src.
* Note, the associated data will be pass-through
* at the begining of destination area.
*/
pce_dev->dst_nents = count_sg(areq->dst,
out_len + areq->assoclen);
else
pce_dev->dst_nents = count_sg(areq->dst, out_len);
qce_dma_map_sg(pce_dev->pdev, areq->dst, pce_dev->dst_nents,
DMA_FROM_DEVICE);
} else {
pce_dev->dst_nents = pce_dev->src_nents;
}
if (pce_dev->support_cmd_dscr) {
_ce_get_cipher_cmdlistinfo(pce_dev, q_req, &cmdlistinfo);
/* set up crypto device */
rc = _ce_setup_cipher(pce_dev, q_req, totallen_in,
areq->assoclen, cmdlistinfo);
} else {
/* set up crypto device */
rc = _ce_setup_cipher_direct(pce_dev, q_req, totallen_in,
areq->assoclen);
}
if (rc < 0)
goto bad;
/* setup for callback, and issue command to bam */
pce_dev->areq = q_req->areq;
pce_dev->qce_cb = q_req->qce_cb;
/* Register callback event for EOT (End of transfer) event. */
pce_dev->ce_sps.producer.event.callback = _aead_sps_producer_callback;
pce_dev->ce_sps.producer.event.options = SPS_O_DESC_DONE;
rc = sps_register_event(pce_dev->ce_sps.producer.pipe,
&pce_dev->ce_sps.producer.event);
if (rc) {
pr_err("Producer callback registration failed rc = %d\n", rc);
goto bad;
}
_qce_sps_iovec_count_init(pce_dev);
if (pce_dev->support_cmd_dscr)
_qce_sps_add_cmd(pce_dev, SPS_IOVEC_FLAG_LOCK, cmdlistinfo,
&pce_dev->ce_sps.in_transfer);
if (pce_dev->ce_sps.minor_version == 0) {
if (_qce_sps_add_sg_data(pce_dev, areq->src, totallen_in,
&pce_dev->ce_sps.in_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.in_transfer,
SPS_IOVEC_FLAG_EOT|SPS_IOVEC_FLAG_NWD);
/*
* The destination data should be big enough to
* include CCM padding.
*/
if (_qce_sps_add_sg_data(pce_dev, areq->dst, out_len +
areq->assoclen + hw_pad_out,
&pce_dev->ce_sps.out_transfer))
goto bad;
if (totallen_in > SPS_MAX_PKT_SIZE) {
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer.event.options =
SPS_O_DESC_DONE;
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_IDLE;
} else {
if (_qce_sps_add_data(GET_PHYS_ADDR(
pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_COMP;
}
} else {
if (_qce_sps_add_sg_data(pce_dev, areq->assoc, areq->assoclen,
&pce_dev->ce_sps.in_transfer))
goto bad;
if (_qce_sps_add_sg_data(pce_dev, areq->src, areq->cryptlen,
&pce_dev->ce_sps.in_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.in_transfer,
SPS_IOVEC_FLAG_EOT|SPS_IOVEC_FLAG_NWD);
/* Pass through to ignore associated data*/
if (_qce_sps_add_data(
GET_PHYS_ADDR(pce_dev->ce_sps.ignore_buffer),
areq->assoclen,
&pce_dev->ce_sps.out_transfer))
goto bad;
if (_qce_sps_add_sg_data(pce_dev, areq->dst, out_len,
&pce_dev->ce_sps.out_transfer))
goto bad;
/* Pass through to ignore hw_pad (padding of the MAC data) */
if (_qce_sps_add_data(
GET_PHYS_ADDR(pce_dev->ce_sps.ignore_buffer),
hw_pad_out, &pce_dev->ce_sps.out_transfer))
goto bad;
if (totallen_in > SPS_MAX_PKT_SIZE) {
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_IDLE;
} else {
if (_qce_sps_add_data(
GET_PHYS_ADDR(pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_COMP;
}
}
rc = _qce_sps_transfer(pce_dev);
if (rc)
goto bad;
return 0;
bad:
if (pce_dev->assoc_nents) {
qce_dma_unmap_sg(pce_dev->pdev, areq->assoc,
pce_dev->assoc_nents, DMA_TO_DEVICE);
}
if (pce_dev->src_nents) {
qce_dma_unmap_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
(areq->src == areq->dst) ? DMA_BIDIRECTIONAL :
DMA_TO_DEVICE);
}
if (areq->src != areq->dst) {
qce_dma_unmap_sg(pce_dev->pdev, areq->dst, pce_dev->dst_nents,
DMA_FROM_DEVICE);
}
return rc;
}
int qce_aead_req(void *handle, struct qce_req *q_req)
{
struct qce_device *pce_dev;
struct aead_request *areq;
uint32_t authsize;
struct crypto_aead *aead;
uint32_t ivsize;
uint32_t totallen;
int rc;
struct qce_cmdlist_info *cmdlistinfo = NULL;
if (q_req->mode == QCE_MODE_CCM)
return _qce_aead_ccm_req(handle, q_req);
pce_dev = (struct qce_device *) handle;
areq = (struct aead_request *) q_req->areq;
aead = crypto_aead_reqtfm(areq);
ivsize = crypto_aead_ivsize(aead);
q_req->ivsize = ivsize;
authsize = q_req->authsize;
if (q_req->dir == QCE_ENCRYPT)
q_req->cryptlen = areq->cryptlen;
else
q_req->cryptlen = areq->cryptlen - authsize;
totallen = q_req->cryptlen + areq->assoclen + ivsize;
if (pce_dev->support_cmd_dscr) {
cmdlistinfo = _ce_get_aead_cmdlistinfo(pce_dev, q_req);
if (cmdlistinfo == NULL) {
pr_err("Unsupported aead ciphering algorithm %d, mode %d, ciphering key length %d, auth digest size %d\n",
q_req->alg, q_req->mode, q_req->encklen,
q_req->authsize);
return -EINVAL;
}
/* set up crypto device */
rc = _ce_setup_aead(pce_dev, q_req, totallen,
areq->assoclen + ivsize, cmdlistinfo);
if (rc < 0)
return -EINVAL;
};
pce_dev->assoc_nents = count_sg(areq->assoc, areq->assoclen);
if (pce_dev->ce_sps.minor_version == 0) {
/*
* For crypto 5.0 that has burst size alignment requirement
* for data descritpor,
* the agent above(qcrypto) prepares the src scatter list with
* memory starting with associated data, followed by
* iv, and data stream to be ciphered.
*/
pce_dev->src_nents = count_sg(areq->src, totallen);
} else {
pce_dev->src_nents = count_sg(areq->src, q_req->cryptlen);
};
pce_dev->ivsize = q_req->ivsize;
pce_dev->authsize = q_req->authsize;
pce_dev->phy_iv_in = 0;
/* associated data input */
qce_dma_map_sg(pce_dev->pdev, areq->assoc, pce_dev->assoc_nents,
DMA_TO_DEVICE);
/* cipher input */
qce_dma_map_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
(areq->src == areq->dst) ? DMA_BIDIRECTIONAL :
DMA_TO_DEVICE);
/* cipher + mac output for encryption */
if (areq->src != areq->dst) {
if (pce_dev->ce_sps.minor_version == 0)
/*
* The destination scatter list is pointing to the same
* data area as source.
*/
pce_dev->dst_nents = count_sg(areq->dst, totallen);
else
pce_dev->dst_nents = count_sg(areq->dst,
q_req->cryptlen);
qce_dma_map_sg(pce_dev->pdev, areq->dst, pce_dev->dst_nents,
DMA_FROM_DEVICE);
}
/* cipher iv for input */
if (pce_dev->ce_sps.minor_version != 0)
pce_dev->phy_iv_in = dma_map_single(pce_dev->pdev, q_req->iv,
ivsize, DMA_TO_DEVICE);
/* setup for callback, and issue command to bam */
pce_dev->areq = q_req->areq;
pce_dev->qce_cb = q_req->qce_cb;
/* Register callback event for EOT (End of transfer) event. */
pce_dev->ce_sps.producer.event.callback = _aead_sps_producer_callback;
pce_dev->ce_sps.producer.event.options = SPS_O_DESC_DONE;
rc = sps_register_event(pce_dev->ce_sps.producer.pipe,
&pce_dev->ce_sps.producer.event);
if (rc) {
pr_err("Producer callback registration failed rc = %d\n", rc);
goto bad;
}
_qce_sps_iovec_count_init(pce_dev);
if (pce_dev->support_cmd_dscr) {
_qce_sps_add_cmd(pce_dev, SPS_IOVEC_FLAG_LOCK, cmdlistinfo,
&pce_dev->ce_sps.in_transfer);
} else {
rc = _ce_setup_aead_direct(pce_dev, q_req, totallen,
areq->assoclen + ivsize);
if (rc)
goto bad;
}
if (pce_dev->ce_sps.minor_version == 0) {
if (_qce_sps_add_sg_data(pce_dev, areq->src, totallen,
&pce_dev->ce_sps.in_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.in_transfer,
SPS_IOVEC_FLAG_EOT|SPS_IOVEC_FLAG_NWD);
if (_qce_sps_add_sg_data(pce_dev, areq->dst, totallen,
&pce_dev->ce_sps.out_transfer))
goto bad;
if (totallen > SPS_MAX_PKT_SIZE) {
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer.event.options =
SPS_O_DESC_DONE;
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_IDLE;
} else {
if (_qce_sps_add_data(GET_PHYS_ADDR(
pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_COMP;
}
} else {
if (_qce_sps_add_sg_data(pce_dev, areq->assoc, areq->assoclen,
&pce_dev->ce_sps.in_transfer))
goto bad;
if (_qce_sps_add_data((uint32_t)pce_dev->phy_iv_in, ivsize,
&pce_dev->ce_sps.in_transfer))
goto bad;
if (_qce_sps_add_sg_data(pce_dev, areq->src, areq->cryptlen,
&pce_dev->ce_sps.in_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.in_transfer,
SPS_IOVEC_FLAG_EOT|SPS_IOVEC_FLAG_NWD);
/* Pass through to ignore associated + iv data*/
if (_qce_sps_add_data(
GET_PHYS_ADDR(pce_dev->ce_sps.ignore_buffer),
(ivsize + areq->assoclen),
&pce_dev->ce_sps.out_transfer))
goto bad;
if (_qce_sps_add_sg_data(pce_dev, areq->dst, areq->cryptlen,
&pce_dev->ce_sps.out_transfer))
goto bad;
if (totallen > SPS_MAX_PKT_SIZE) {
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_IDLE;
} else {
if (_qce_sps_add_data(
GET_PHYS_ADDR(pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_COMP;
}
}
rc = _qce_sps_transfer(pce_dev);
if (rc)
goto bad;
return 0;
bad:
if (pce_dev->assoc_nents) {
qce_dma_unmap_sg(pce_dev->pdev, areq->assoc,
pce_dev->assoc_nents, DMA_TO_DEVICE);
}
if (pce_dev->src_nents) {
qce_dma_unmap_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
(areq->src == areq->dst) ? DMA_BIDIRECTIONAL :
DMA_TO_DEVICE);
}
if (areq->src != areq->dst) {
qce_dma_unmap_sg(pce_dev->pdev, areq->dst, pce_dev->dst_nents,
DMA_FROM_DEVICE);
}
if (pce_dev->phy_iv_in) {
dma_unmap_single(pce_dev->pdev, pce_dev->phy_iv_in,
ivsize, DMA_TO_DEVICE);
}
return rc;
}
EXPORT_SYMBOL(qce_aead_req);
int qce_ablk_cipher_req(void *handle, struct qce_req *c_req)
{
int rc = 0;
struct qce_device *pce_dev = (struct qce_device *) handle;
struct ablkcipher_request *areq = (struct ablkcipher_request *)
c_req->areq;
struct qce_cmdlist_info *cmdlistinfo = NULL;
pce_dev->src_nents = 0;
pce_dev->dst_nents = 0;
/* cipher input */
pce_dev->src_nents = count_sg(areq->src, areq->nbytes);
qce_dma_map_sg(pce_dev->pdev, areq->src, pce_dev->src_nents,
(areq->src == areq->dst) ? DMA_BIDIRECTIONAL :
DMA_TO_DEVICE);
/* cipher output */
if (areq->src != areq->dst) {
pce_dev->dst_nents = count_sg(areq->dst, areq->nbytes);
qce_dma_map_sg(pce_dev->pdev, areq->dst,
pce_dev->dst_nents, DMA_FROM_DEVICE);
} else {
pce_dev->dst_nents = pce_dev->src_nents;
}
pce_dev->dir = c_req->dir;
if ((pce_dev->ce_sps.minor_version == 0) && (c_req->dir == QCE_DECRYPT)
&& (c_req->mode == QCE_MODE_CBC)) {
memcpy(pce_dev->dec_iv, (unsigned char *)sg_virt(areq->src) +
areq->src->length - 16,
NUM_OF_CRYPTO_CNTR_IV_REG * CRYPTO_REG_SIZE);
}
/* set up crypto device */
if (pce_dev->support_cmd_dscr) {
_ce_get_cipher_cmdlistinfo(pce_dev, c_req, &cmdlistinfo);
rc = _ce_setup_cipher(pce_dev, c_req, areq->nbytes, 0,
cmdlistinfo);
} else {
rc = _ce_setup_cipher_direct(pce_dev, c_req, areq->nbytes, 0);
}
if (rc < 0)
goto bad;
/* setup for client callback, and issue command to BAM */
pce_dev->areq = areq;
pce_dev->qce_cb = c_req->qce_cb;
/* Register callback event for EOT (End of transfer) event. */
pce_dev->ce_sps.producer.event.callback =
_ablk_cipher_sps_producer_callback;
pce_dev->ce_sps.producer.event.options = SPS_O_DESC_DONE;
rc = sps_register_event(pce_dev->ce_sps.producer.pipe,
&pce_dev->ce_sps.producer.event);
if (rc) {
pr_err("Producer callback registration failed rc = %d\n", rc);
goto bad;
}
_qce_sps_iovec_count_init(pce_dev);
if (pce_dev->support_cmd_dscr)
_qce_sps_add_cmd(pce_dev, SPS_IOVEC_FLAG_LOCK, cmdlistinfo,
&pce_dev->ce_sps.in_transfer);
if (_qce_sps_add_sg_data(pce_dev, areq->src, areq->nbytes,
&pce_dev->ce_sps.in_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.in_transfer,
SPS_IOVEC_FLAG_EOT|SPS_IOVEC_FLAG_NWD);
if (_qce_sps_add_sg_data(pce_dev, areq->dst, areq->nbytes,
&pce_dev->ce_sps.out_transfer))
goto bad;
if (areq->nbytes > SPS_MAX_PKT_SIZE) {
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_IDLE;
} else {
pce_dev->ce_sps.producer_state = QCE_PIPE_STATE_COMP;
if (_qce_sps_add_data(
GET_PHYS_ADDR(pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.out_transfer,
SPS_IOVEC_FLAG_INT);
}
rc = _qce_sps_transfer(pce_dev);
if (rc)
goto bad;
return 0;
bad:
if (areq->src != areq->dst) {
if (pce_dev->dst_nents) {
qce_dma_unmap_sg(pce_dev->pdev, areq->dst,
pce_dev->dst_nents, DMA_FROM_DEVICE);
}
}
if (pce_dev->src_nents) {
qce_dma_unmap_sg(pce_dev->pdev, areq->src,
pce_dev->src_nents,
(areq->src == areq->dst) ?
DMA_BIDIRECTIONAL : DMA_TO_DEVICE);
}
return rc;
}
EXPORT_SYMBOL(qce_ablk_cipher_req);
int qce_process_sha_req(void *handle, struct qce_sha_req *sreq)
{
struct qce_device *pce_dev = (struct qce_device *) handle;
int rc;
struct ahash_request *areq = (struct ahash_request *)sreq->areq;
struct qce_cmdlist_info *cmdlistinfo = NULL;
pce_dev->src_nents = count_sg(sreq->src, sreq->size);
qce_dma_map_sg(pce_dev->pdev, sreq->src, pce_dev->src_nents,
DMA_TO_DEVICE);
if (pce_dev->support_cmd_dscr) {
_ce_get_hash_cmdlistinfo(pce_dev, sreq, &cmdlistinfo);
rc = _ce_setup_hash(pce_dev, sreq, cmdlistinfo);
} else {
rc = _ce_setup_hash_direct(pce_dev, sreq);
}
if (rc < 0)
goto bad;
pce_dev->areq = areq;
pce_dev->qce_cb = sreq->qce_cb;
/* Register callback event for EOT (End of transfer) event. */
pce_dev->ce_sps.producer.event.callback = _sha_sps_producer_callback;
pce_dev->ce_sps.producer.event.options = SPS_O_DESC_DONE;
rc = sps_register_event(pce_dev->ce_sps.producer.pipe,
&pce_dev->ce_sps.producer.event);
if (rc) {
pr_err("Producer callback registration failed rc = %d\n", rc);
goto bad;
}
_qce_sps_iovec_count_init(pce_dev);
if (pce_dev->support_cmd_dscr)
_qce_sps_add_cmd(pce_dev, SPS_IOVEC_FLAG_LOCK, cmdlistinfo,
&pce_dev->ce_sps.in_transfer);
if (_qce_sps_add_sg_data(pce_dev, areq->src, areq->nbytes,
&pce_dev->ce_sps.in_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.in_transfer,
SPS_IOVEC_FLAG_EOT|SPS_IOVEC_FLAG_NWD);
if (_qce_sps_add_data(GET_PHYS_ADDR(pce_dev->ce_sps.result_dump),
CRYPTO_RESULT_DUMP_SIZE,
&pce_dev->ce_sps.out_transfer))
goto bad;
_qce_set_flag(&pce_dev->ce_sps.out_transfer, SPS_IOVEC_FLAG_INT);
rc = _qce_sps_transfer(pce_dev);
if (rc)
goto bad;
return 0;
bad:
if (pce_dev->src_nents) {
qce_dma_unmap_sg(pce_dev->pdev, sreq->src,
pce_dev->src_nents, DMA_TO_DEVICE);
}
return rc;
}
EXPORT_SYMBOL(qce_process_sha_req);
static int __qce_get_device_tree_data(struct platform_device *pdev,
struct qce_device *pce_dev)
{
struct resource *resource;
int rc = 0;
pce_dev->is_shared = of_property_read_bool((&pdev->dev)->of_node,
"qcom,ce-hw-shared");
pce_dev->support_hw_key = of_property_read_bool((&pdev->dev)->of_node,
"qcom,ce-hw-key");
if (of_property_read_u32((&pdev->dev)->of_node,
"qcom,bam-pipe-pair",
&pce_dev->ce_sps.pipe_pair_index)) {
pr_err("Fail to get bam pipe pair information.\n");
return -EINVAL;
} else {
pr_warn("bam_pipe_pair=0x%x", pce_dev->ce_sps.pipe_pair_index);
}
pce_dev->ce_sps.dest_pipe_index = 2 * pce_dev->ce_sps.pipe_pair_index;
pce_dev->ce_sps.src_pipe_index = pce_dev->ce_sps.dest_pipe_index + 1;
resource = platform_get_resource_byname(pdev, IORESOURCE_MEM,
"crypto-base");
if (resource) {
pce_dev->phy_iobase = resource->start;
pce_dev->iobase = ioremap_nocache(resource->start,
resource_size(resource));
if (!pce_dev->iobase) {
pr_err("Can not map CRYPTO io memory\n");
return -ENOMEM;
}
} else {
pr_err("CRYPTO HW mem unavailable.\n");
return -ENODEV;
}
pr_warn("ce_phy_reg_base=0x%x ", pce_dev->phy_iobase);
pr_warn("ce_virt_reg_base=0x%x\n", (uint32_t)pce_dev->iobase);
resource = platform_get_resource_byname(pdev, IORESOURCE_MEM,
"crypto-bam-base");
if (resource) {
pce_dev->ce_sps.bam_mem = resource->start;
pce_dev->ce_sps.bam_iobase = ioremap_nocache(resource->start,
resource_size(resource));
if (!pce_dev->ce_sps.bam_iobase) {
rc = -ENOMEM;
pr_err("Can not map BAM io memory\n");
goto err_getting_bam_info;
}
} else {
pr_err("CRYPTO BAM mem unavailable.\n");
rc = -ENODEV;
goto err_getting_bam_info;
}
pr_warn("ce_bam_phy_reg_base=0x%x ", pce_dev->ce_sps.bam_mem);
pr_warn("ce_bam_virt_reg_base=0x%x\n",
(uint32_t)pce_dev->ce_sps.bam_iobase);
resource = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (resource) {
pce_dev->ce_sps.bam_irq = resource->start;
pr_warn("CRYPTO BAM IRQ = %d.\n", pce_dev->ce_sps.bam_irq);
} else {
pr_err("CRYPTO BAM IRQ unavailable.\n");
goto err_dev;
}
return rc;
err_dev:
if (pce_dev->ce_sps.bam_iobase)
iounmap(pce_dev->ce_sps.bam_iobase);
err_getting_bam_info:
if (pce_dev->iobase)
iounmap(pce_dev->iobase);
return rc;
}
static int __qce_init_clk(struct qce_device *pce_dev)
{
int rc = 0;
struct clk *ce_core_clk;
struct clk *ce_clk;
struct clk *ce_core_src_clk;
struct clk *ce_bus_clk;
/* Get CE3 src core clk. */
ce_core_src_clk = clk_get(pce_dev->pdev, "core_clk_src");
if (!IS_ERR(ce_core_src_clk)) {
pce_dev->ce_core_src_clk = ce_core_src_clk;
/* Set the core src clk @100Mhz */
rc = clk_set_rate(pce_dev->ce_core_src_clk, 100000000);
if (rc) {
clk_put(pce_dev->ce_core_src_clk);
pce_dev->ce_core_src_clk = NULL;
pr_err("Unable to set the core src clk @100Mhz.\n");
goto err_clk;
}
} else {
pr_warn("Unable to get CE core src clk, set to NULL\n");
pce_dev->ce_core_src_clk = NULL;
}
/* Get CE core clk */
ce_core_clk = clk_get(pce_dev->pdev, "core_clk");
if (IS_ERR(ce_core_clk)) {
rc = PTR_ERR(ce_core_clk);
pr_err("Unable to get CE core clk\n");
if (pce_dev->ce_core_src_clk != NULL)
clk_put(pce_dev->ce_core_src_clk);
goto err_clk;
}
pce_dev->ce_core_clk = ce_core_clk;
/* Get CE Interface clk */
ce_clk = clk_get(pce_dev->pdev, "iface_clk");
if (IS_ERR(ce_clk)) {
rc = PTR_ERR(ce_clk);
pr_err("Unable to get CE interface clk\n");
if (pce_dev->ce_core_src_clk != NULL)
clk_put(pce_dev->ce_core_src_clk);
clk_put(pce_dev->ce_core_clk);
goto err_clk;
}
pce_dev->ce_clk = ce_clk;
/* Get CE AXI clk */
ce_bus_clk = clk_get(pce_dev->pdev, "bus_clk");
if (IS_ERR(ce_bus_clk)) {
rc = PTR_ERR(ce_bus_clk);
pr_err("Unable to get CE BUS interface clk\n");
if (pce_dev->ce_core_src_clk != NULL)
clk_put(pce_dev->ce_core_src_clk);
clk_put(pce_dev->ce_core_clk);
clk_put(pce_dev->ce_clk);
goto err_clk;
}
pce_dev->ce_bus_clk = ce_bus_clk;
err_clk:
if (rc)
pr_err("Unable to init CE clks, rc = %d\n", rc);
return rc;
}
static void __qce_deinit_clk(struct qce_device *pce_dev)
{
if (pce_dev->ce_clk != NULL) {
clk_put(pce_dev->ce_clk);
pce_dev->ce_clk = NULL;
}
if (pce_dev->ce_core_clk != NULL) {
clk_put(pce_dev->ce_core_clk);
pce_dev->ce_core_clk = NULL;
}
if (pce_dev->ce_bus_clk != NULL) {
clk_put(pce_dev->ce_bus_clk);
pce_dev->ce_bus_clk = NULL;
}
if (pce_dev->ce_core_src_clk != NULL) {
clk_put(pce_dev->ce_core_src_clk);
pce_dev->ce_core_src_clk = NULL;
}
}
int qce_enable_clk(void *handle)
{
struct qce_device *pce_dev = (struct qce_device *) handle;
int rc = 0;
/* Enable CE core clk */
if (pce_dev->ce_core_clk != NULL) {
rc = clk_prepare_enable(pce_dev->ce_core_clk);
if (rc) {
pr_err("Unable to enable/prepare CE core clk\n");
return rc;
}
}
/* Enable CE clk */
if (pce_dev->ce_clk != NULL) {
rc = clk_prepare_enable(pce_dev->ce_clk);
if (rc) {
pr_err("Unable to enable/prepare CE iface clk\n");
clk_disable_unprepare(pce_dev->ce_core_clk);
return rc;
}
}
/* Enable AXI clk */
if (pce_dev->ce_bus_clk != NULL) {
rc = clk_prepare_enable(pce_dev->ce_bus_clk);
if (rc) {
pr_err("Unable to enable/prepare CE BUS clk\n");
clk_disable_unprepare(pce_dev->ce_clk);
clk_disable_unprepare(pce_dev->ce_core_clk);
return rc;
}
}
return rc;
}
EXPORT_SYMBOL(qce_enable_clk);
int qce_disable_clk(void *handle)
{
struct qce_device *pce_dev = (struct qce_device *) handle;
int rc = 0;
if (pce_dev->ce_clk != NULL)
clk_disable_unprepare(pce_dev->ce_clk);
if (pce_dev->ce_core_clk != NULL)
clk_disable_unprepare(pce_dev->ce_core_clk);
if (pce_dev->ce_bus_clk != NULL)
clk_disable_unprepare(pce_dev->ce_bus_clk);
return rc;
}
EXPORT_SYMBOL(qce_disable_clk);
/* crypto engine open function. */
void *qce_open(struct platform_device *pdev, int *rc)
{
struct qce_device *pce_dev;
uint32_t bam_cfg = 0 ;
pce_dev = kzalloc(sizeof(struct qce_device), GFP_KERNEL);
if (!pce_dev) {
*rc = -ENOMEM;
pr_err("Can not allocate memory: %d\n", *rc);
return NULL;
}
pce_dev->pdev = &pdev->dev;
if (pdev->dev.of_node) {
*rc = __qce_get_device_tree_data(pdev, pce_dev);
if (*rc)
goto err_pce_dev;
} else {
*rc = -EINVAL;
pr_err("Device Node not found.\n");
goto err_pce_dev;
}
pce_dev->memsize = 9 * PAGE_SIZE;
pce_dev->coh_vmem = dma_alloc_coherent(pce_dev->pdev,
pce_dev->memsize, &pce_dev->coh_pmem, GFP_KERNEL);
if (pce_dev->coh_vmem == NULL) {
*rc = -ENOMEM;
pr_err("Can not allocate coherent memory for sps data\n");
goto err_iobase;
}
*rc = __qce_init_clk(pce_dev);
if (*rc)
goto err_mem;
*rc = qce_enable_clk(pce_dev);
if (*rc)
goto err;
if (_probe_ce_engine(pce_dev)) {
*rc = -ENXIO;
goto err;
}
*rc = 0;
bam_cfg = readl_relaxed(pce_dev->ce_sps.bam_iobase +
CRYPTO_BAM_CNFG_BITS_REG);
pce_dev->support_cmd_dscr = (bam_cfg & CRYPTO_BAM_CD_ENABLE_MASK) ?
true : false;
qce_init_ce_cfg_val(pce_dev);
qce_setup_ce_sps_data(pce_dev);
qce_sps_init(pce_dev);
qce_disable_clk(pce_dev);
return pce_dev;
err:
__qce_deinit_clk(pce_dev);
err_mem:
if (pce_dev->coh_vmem)
dma_free_coherent(pce_dev->pdev, pce_dev->memsize,
pce_dev->coh_vmem, pce_dev->coh_pmem);
err_iobase:
if (pce_dev->ce_sps.bam_iobase)
iounmap(pce_dev->ce_sps.bam_iobase);
if (pce_dev->iobase)
iounmap(pce_dev->iobase);
err_pce_dev:
kfree(pce_dev);
return NULL;
}
EXPORT_SYMBOL(qce_open);
/* crypto engine close function. */
int qce_close(void *handle)
{
struct qce_device *pce_dev = (struct qce_device *) handle;
if (handle == NULL)
return -ENODEV;
qce_enable_clk(pce_dev);
qce_sps_exit(pce_dev);
if (pce_dev->iobase)
iounmap(pce_dev->iobase);
if (pce_dev->coh_vmem)
dma_free_coherent(pce_dev->pdev, pce_dev->memsize,
pce_dev->coh_vmem, pce_dev->coh_pmem);
qce_disable_clk(pce_dev);
__qce_deinit_clk(pce_dev);
kfree(handle);
return 0;
}
EXPORT_SYMBOL(qce_close);
int qce_hw_support(void *handle, struct ce_hw_support *ce_support)
{
struct qce_device *pce_dev = (struct qce_device *)handle;
if (ce_support == NULL)
return -EINVAL;
ce_support->sha1_hmac_20 = false;
ce_support->sha1_hmac = false;
ce_support->sha256_hmac = false;
ce_support->sha_hmac = true;
ce_support->cmac = true;
ce_support->aes_key_192 = false;
ce_support->aes_xts = true;
ce_support->ota = false;
ce_support->bam = true;
ce_support->is_shared = (pce_dev->is_shared == 1) ? true : false;
ce_support->hw_key = pce_dev->support_hw_key;
ce_support->aes_ccm = true;
if (pce_dev->ce_sps.minor_version)
ce_support->aligned_only = false;
else
ce_support->aligned_only = true;
return 0;
}
EXPORT_SYMBOL(qce_hw_support);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Crypto Engine driver");
| Java |
package org.zanata.dao;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.zanata.model.HAccount;
import org.zanata.model.HAccountRole;
import org.zanata.model.HProject;
@Name("accountRoleDAO")
@AutoCreate
@Scope(ScopeType.STATELESS)
public class AccountRoleDAO extends AbstractDAOImpl<HAccountRole, Integer> {
public AccountRoleDAO() {
super(HAccountRole.class);
}
public AccountRoleDAO(Session session) {
super(HAccountRole.class, session);
}
public boolean roleExists(String role) {
return findByName(role) != null;
}
public HAccountRole findByName(String roleName) {
Criteria cr = getSession().createCriteria(HAccountRole.class);
cr.add(Restrictions.eq("name", roleName));
cr.setCacheable(true).setComment("AccountRoleDAO.findByName");
return (HAccountRole) cr.uniqueResult();
}
public HAccountRole create(String roleName, HAccountRole.RoleType type,
String... includesRoles) {
HAccountRole role = new HAccountRole();
role.setName(roleName);
role.setRoleType(type);
for (String includeRole : includesRoles) {
Set<HAccountRole> groups = role.getGroups();
if (groups == null) {
groups = new HashSet<HAccountRole>();
role.setGroups(groups);
}
groups.add(findByName(includeRole));
}
makePersistent(role);
return role;
}
public HAccountRole updateIncludeRoles(String roleName,
String... includesRoles) {
HAccountRole role = findByName(roleName);
for (String includeRole : includesRoles) {
Set<HAccountRole> groups = role.getGroups();
if (groups == null) {
groups = new HashSet<HAccountRole>();
role.setGroups(groups);
}
groups.add(findByName(includeRole));
}
makePersistent(role);
return role;
}
public List<HAccount> listMembers(String roleName) {
HAccountRole role = findByName(roleName);
return listMembers(role);
}
@SuppressWarnings("unchecked")
public List<HAccount> listMembers(HAccountRole role) {
Query query =
getSession()
.createQuery(
"from HAccount account where :role member of account.roles");
query.setParameter("role", role);
query.setComment("AccountRoleDAO.listMembers");
return query.list();
}
public Collection<HAccountRole> getByProject(HProject project) {
return getSession()
.createQuery(
"select p.allowedRoles from HProject p where p = :project")
.setParameter("project", project)
.setComment("AccountRoleDAO.getByProject").list();
}
}
| Java |
/*
Copyright (C) 2009 - 2015 by Yurii Chernyi <terraninfo@terraninfo.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 as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* Formula debugger - implementation
* */
#include "formula_debugger.hpp"
#include "formula.hpp"
#include "formula_function.hpp"
#include "game_display.hpp"
#include "log.hpp"
#include "resources.hpp"
#include "gui/dialogs/formula_debugger.hpp"
#include "gui/widgets/settings.hpp"
#include <boost/lexical_cast.hpp>
static lg::log_domain log_formula_debugger("ai/debug/formula");
#define DBG_FDB LOG_STREAM(debug, log_formula_debugger)
#define LOG_FDB LOG_STREAM(info, log_formula_debugger)
#define WRN_FDB LOG_STREAM(warn, log_formula_debugger)
#define ERR_FDB LOG_STREAM(err, log_formula_debugger)
namespace game_logic {
debug_info::debug_info(int arg_number, int counter, int level, const std::string &name, const std::string &str, const variant &value, bool evaluated)
: arg_number_(arg_number), counter_(counter), level_(level), name_(name), str_(str), value_(value), evaluated_(evaluated)
{
}
debug_info::~debug_info()
{
}
int debug_info::level() const
{
return level_;
}
const std::string& debug_info::name() const
{
return name_;
}
int debug_info::counter() const
{
return counter_;
}
const variant& debug_info::value() const
{
return value_;
}
void debug_info::set_value(const variant &value)
{
value_ = value;
}
bool debug_info::evaluated() const
{
return evaluated_;
}
void debug_info::set_evaluated(bool evaluated)
{
evaluated_ = evaluated;
}
const std::string& debug_info::str() const
{
return str_;
}
formula_debugger::formula_debugger()
: call_stack_(), counter_(0), current_breakpoint_(), breakpoints_(), execution_trace_(),arg_number_extra_debug_info(-1), f_name_extra_debug_info("")
{
add_breakpoint_step_into();
add_breakpoint_continue_to_end();
}
formula_debugger::~formula_debugger()
{
}
static void msg(const char *act, debug_info &i, const char *to="", const char *result = "")
{
DBG_FDB << "#" << i.counter() << act << std::endl <<" \""<< i.name().c_str() << "\"='" << i.str().c_str() << "' " << to << result << std::endl;
}
void formula_debugger::add_debug_info(int arg_number, const char *f_name)
{
arg_number_extra_debug_info = arg_number;
f_name_extra_debug_info = f_name;
}
const std::deque<debug_info>& formula_debugger::get_call_stack() const
{
return call_stack_;
}
const breakpoint_ptr formula_debugger::get_current_breakpoint() const
{
return current_breakpoint_;
}
const std::deque<debug_info>& formula_debugger::get_execution_trace() const
{
return execution_trace_;
}
void formula_debugger::check_breakpoints()
{
for( std::deque< breakpoint_ptr >::iterator b = breakpoints_.begin(); b!= breakpoints_.end(); ++b) {
if ((*b)->is_break_now()){
current_breakpoint_ = (*b);
show_gui();
current_breakpoint_ = breakpoint_ptr();
if ((*b)->is_one_time_only()) {
breakpoints_.erase(b);
}
break;
}
}
}
void formula_debugger::show_gui()
{
if (resources::screen == NULL) {
WRN_FDB << "do not showing debug window due to NULL gui" << std::endl;
return;
}
if (gui2::new_widgets) {
gui2::tformula_debugger debug_dialog(*this);
debug_dialog.show(resources::screen->video());
} else {
WRN_FDB << "do not showing debug window due to disabled --new-widgets"<< std::endl;
}
}
void formula_debugger::call_stack_push(const std::string &str)
{
call_stack_.push_back(debug_info(arg_number_extra_debug_info,counter_++,call_stack_.size(),f_name_extra_debug_info,str,variant(),false));
arg_number_extra_debug_info = -1;
f_name_extra_debug_info = "";
execution_trace_.push_back(call_stack_.back());
}
void formula_debugger::call_stack_pop()
{
execution_trace_.push_back(call_stack_.back());
call_stack_.pop_back();
}
void formula_debugger::call_stack_set_evaluated(bool evaluated)
{
call_stack_.back().set_evaluated(evaluated);
}
void formula_debugger::call_stack_set_value(const variant &v)
{
call_stack_.back().set_value(v);
}
variant formula_debugger::evaluate_arg_callback(const formula_expression &expression, const formula_callable &variables)
{
call_stack_push(expression.str());
check_breakpoints();
msg(" evaluating expression: ",call_stack_.back());
variant v = expression.execute(variables,this);
call_stack_set_value(v);
call_stack_set_evaluated(true);
msg(" evaluated expression: ",call_stack_.back()," to ",v.to_debug_string(NULL,true).c_str());
check_breakpoints();
call_stack_pop();
return v;
}
variant formula_debugger::evaluate_formula_callback(const formula &f, const formula_callable &variables)
{
call_stack_push(f.str());
check_breakpoints();
msg(" evaluating formula: ",call_stack_.back());
variant v = f.execute(variables,this);
call_stack_set_value(v);
call_stack_set_evaluated(true);
msg(" evaluated formula: ",call_stack_.back()," to ",v.to_debug_string(NULL,true).c_str());
check_breakpoints();
call_stack_pop();
return v;
}
variant formula_debugger::evaluate_formula_callback(const formula &f)
{
call_stack_push(f.str());
check_breakpoints();
msg(" evaluating formula without variables: ",call_stack_.back());
variant v = f.execute(this);
call_stack_set_value(v);
call_stack_set_evaluated(true);
msg(" evaluated formula without variables: ",call_stack_.back()," to ",v.to_debug_string(NULL,true).c_str());
check_breakpoints();
call_stack_pop();
return v;
}
base_breakpoint::base_breakpoint(formula_debugger &fdb, const std::string &name, bool one_time_only)
: fdb_(fdb), name_(name), one_time_only_(one_time_only)
{
}
base_breakpoint::~base_breakpoint()
{
}
bool base_breakpoint::is_one_time_only() const
{
return one_time_only_;
}
const std::string& base_breakpoint::name() const
{
return name_;
}
class end_breakpoint : public base_breakpoint {
public:
end_breakpoint(formula_debugger &fdb)
: base_breakpoint(fdb,"End", true)
{
}
virtual ~end_breakpoint()
{
}
virtual bool is_break_now() const
{
const std::deque<debug_info> &call_stack = fdb_.get_call_stack();
if ((call_stack.size() == 1) && (call_stack[0].evaluated()) ) {
return true;
}
return false;
}
};
class step_in_breakpoint : public base_breakpoint {
public:
step_in_breakpoint(formula_debugger &fdb)
: base_breakpoint(fdb,"Step",true)
{
}
virtual ~step_in_breakpoint()
{
}
virtual bool is_break_now() const
{
const std::deque<debug_info> &call_stack = fdb_.get_call_stack();
if (call_stack.empty() || call_stack.back().evaluated()) {
return false;
}
return true;
}
};
class step_out_breakpoint : public base_breakpoint {
public:
step_out_breakpoint(formula_debugger &fdb)
: base_breakpoint(fdb,"Step out",true), level_(fdb.get_call_stack().size()-1)
{
}
virtual ~step_out_breakpoint()
{
}
virtual bool is_break_now() const
{
const std::deque<debug_info> &call_stack = fdb_.get_call_stack();
if (call_stack.empty() || call_stack.back().evaluated()) {
return false;
}
if (call_stack.size() == level_) {
return true;
}
return false;
}
private:
size_t level_;
};
class next_breakpoint : public base_breakpoint {
public:
next_breakpoint(formula_debugger &fdb)
: base_breakpoint(fdb,"Next",true), level_(fdb.get_call_stack().size())
{
}
virtual ~next_breakpoint()
{
}
virtual bool is_break_now() const
{
const std::deque<debug_info> &call_stack = fdb_.get_call_stack();
if (call_stack.empty() || call_stack.back().evaluated()) {
return false;
}
if (call_stack.size() == level_) {
return true;
}
return false;
}
private:
size_t level_;
};
void formula_debugger::add_breakpoint_continue_to_end()
{
breakpoints_.push_back(breakpoint_ptr(new end_breakpoint(*this)));
LOG_FDB << "added 'end' breakpoint"<< std::endl;
}
void formula_debugger::add_breakpoint_step_into()
{
breakpoints_.push_back(breakpoint_ptr(new step_in_breakpoint(*this)));
LOG_FDB << "added 'step into' breakpoint"<< std::endl;
}
void formula_debugger::add_breakpoint_step_out()
{
breakpoints_.push_back(breakpoint_ptr(new step_out_breakpoint(*this)));
LOG_FDB << "added 'step out' breakpoint"<< std::endl;
}
void formula_debugger::add_breakpoint_next()
{
breakpoints_.push_back(breakpoint_ptr(new next_breakpoint(*this)));
LOG_FDB << "added 'next' breakpoint"<< std::endl;
}
} // end of namespace game_logic
| Java |
#include "botpch.h"
#include "../../playerbot.h"
#include "BuyAction.h"
#include "../ItemVisitors.h"
#include "../values/ItemCountValue.h"
using namespace ai;
bool BuyAction::Execute(Event event)
{
string link = event.getParam();
ItemIds itemIds = chat->parseItems(link);
if (itemIds.empty())
return false;
Player* master = GetMaster();
if (!master)
return false;
ObjectGuid vendorguid = master->GetSelectionGuid();
if (!vendorguid)
return false;
Creature *pCreature = bot->GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
if (!pCreature)
{
ai->TellMaster("Cannot talk to vendor");
return false;
}
VendorItemData const* tItems = pCreature->GetVendorItems();
if (!tItems)
{
ai->TellMaster("This vendor has no items");
return false;
}
for (ItemIds::iterator i = itemIds.begin(); i != itemIds.end(); i++)
{
for (uint32 slot = 0; slot < tItems->GetItemCount(); slot++)
{
if (tItems->GetItem(slot)->item == *i)
{
bot->BuyItemFromVendor(vendorguid, *i, 1, NULL_BAG, NULL_SLOT);
ai->TellMaster("Bought item");
}
}
}
return true;
}
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language;?>" >
<?php
/* @package mx_joomla121 Template
* @author mixwebtemplates http://www.mixwebtemplates.com
* @copyright Copyright (c) 2006 - 2012 mixwebtemplates. All rights reserved
*/
defined( '_JEXEC' ) or die( 'Restricted access' );
if(!defined('DS')){define('DS',DIRECTORY_SEPARATOR);}
$tcParams = '';
include_once(dirname(__FILE__).DS.'tclibs'.DS.'head.php');
include_once(dirname(__FILE__).DS.'tclibs'.DS.'settings.php');
$tcParams .= '<body id="tc">';
$tcParams .= TCShowModule('adverts', 'mx_xhtml', 'container');
$tcParams .= '<div id="mx_wrapper" class="mx_wrapper">';
$tcParams .= TCShowModule('header', 'mx_xhtml', 'container');
$tcParams .= '<jdoc:include type="modules" name="sign_in" />';
include_once(dirname(__FILE__).DS.'tclibs'.DS.'slider.php');
include_once(dirname(__FILE__).DS.'tclibs'.DS.'social.php');
$tcParams .= TCShowModule('slider', 'mx_xhtml', 'container');
$tcParams .= TCShowModule('top', 'mx_xhtml', 'container');
$tcParams .= TCShowModule('info', 'mx_xhtml', 'container');
$tcParams .= '<section class="mx_wrapper_info mx_section">'
.'<div class="container mx_group"><jdoc:include type="modules" name="search_jobs_box" />'
// .'<div><jdoc:include type="modules" name="test1" /></div>'
.'</div></section>';
//Latest Jobs blocks
$tcParams .= '<div class="row"><jdoc:include type="modules" name="latest_jobs" /></div>'
;
//Slide top
$tcParams .= '<section class="mx_wrapper_top mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="top_slide" />'
.'</div></section>';
//very maintop content block
$tcParams .= '<section class="mx_wrapper_maintop mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="top_block" />'
.'</div></section>';
$tcParams .= TCShowModule('maintop', 'mx_xhtml', 'container');
$tcParams .= '<main class="mx_main container clearfix">'.$component.'</main>';
$tcParams .= TCShowModule('mainbottom', 'mx_xhtml', 'container').
TCShowModule('feature', 'mx_xhtml', 'container').
TCShowModule('bottom', 'mx_xhtml', 'container').
TCShowModule('footer', 'mx_xhtml', 'container');
//Advise widget
$tcParams .= '<div class="row">'
.'<jdoc:include type="modules" name="advise-widget" />'
.'</div>';
//Resume nav bar
$tcParams .= '<div class="mod-content clearfix">'
.'<jdoc:include type="modules" name="Create_ResumeNavBar" />'
.'</div>';
//Feature blocks
$tcParams .= '<section class="mx_wrapper_feature mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="feature-1" />'
.'</div></section>';
//Footer blocks
$tcParams .= '<section class="mx_wrapper_bottom mx_section">'
.'<div class="container mx_group">'
.'<jdoc:include type="modules" name="footer_block" />'
.'</div></section>';
$tcParams .= '<footer class="mx_wrapper_copyright mx_section">'.
'<div class="container clearfix">'.
'<div class="col-md-12">'.($copyright ? '<div style="padding:10px;">'.$cpright.' </div>' : ''). /* You CAN NOT remove (or unreadable) this without mixwebtemplates.com permission */ //'<div style="padding-bottom:10px; text-align:right; ">Designed by <a href="http://www.mixwebtemplates.com/" title="Visit mixwebtemplates.com!" target="blank">mixwebtemplates.com</a></div>'.
'</div>'.
'</div>'.
'</footer>';
$tcParams .='</div>';
include_once(dirname(__FILE__).DS.'tclibs'.DS.'debug.php');
$tcParams .='</body>';
$tcParams .='</html>';
echo $tcParams;
?> | Java |
/*
* main.cpp
*
* Created on: 30 Xan, 2015
* Author: marcos
*/
#include "common.h"
extern "C" {
#include "perm.h"
}
/**
* \brief Print application help
*/
void printHelp() {
cout << "diffExprpermutation: Find differentially expressed genes from a set of control and cases samples using a permutation strategy." << endl;
cout << "diffExprPermutation -f input [--c1 condition1 --c2 condition2 -n permutations -H stopHits -s statistic] -o outFile" << endl;
cout << "Inputs:" << endl;
cout << " -f input Space separated table. Format: sampleName group lib.size norm.factors gene1 gene2 ... geneN" << endl;
cout << "Outputs:" << endl;
cout << " -o outFile Output file name" << endl;
cout << "Options:" << endl;
cout << " --c1 condition1 Condition that determine one of two groups [default: case]" << endl;
cout << " --c2 condition2 Condition that determine other group [default: control]" << endl;
cout << " -s statistic Statistic to compute pvalue median|perc25|perc75|x [default: median]" << endl;
cout << " -p percentile mode Mode for selection of percentile auto|linear|nearest [default: auto]" << endl;
cout << " -t n_threads Number of threads [default: 1]" << endl;
}
/**
* \brief Check Arguments
* \param string fileInput - Name input file
* \param string outFile - Name output file
* \param unsigned int chunks - Number of chunks to create
* \param string condition1 - First condition group. Usually case.
* \param string condition1 - Second condition group. Usually control.
*/
inline bool argumentChecking(const string &fileInput,
const string &outFile,
const string &condition1,
const string &condition2)
{
bool bWrong = false;
if (fileInput.empty())
{
cout << "Sorry!! No input file was specified!!" << endl;
return true;
}
if (outFile.empty())
{
cout << "Sorry!! No output file was specified!!" << endl;
return true;
}
if (condition1.empty())
{
cout << "Sorry!! Condition group 1 is empty!!" << endl;
return true;
}
if (condition2.empty())
{
cout << "Sorry!! Condition group 2 is empty!!" << endl;
return true;
}
return bWrong;
}
int main(int argc, char **argv)
{
string fileInput = "";
string outFile = "";
string condition1 = "case";
string condition2 = "control";
string percentile_mode = "auto";
cp_mode pc_mode = AUTO;
int n_threads = 1;
string statistic = "median";
double fStatisticValue = 0;
bool doMedian = true;
vector<Gene> vGenes; // vector of genes where each gene has a vector of sampleGenes, each sampleGene contains sample name expression value and group
/**
* BRACA1 -> A,true,0.75
* -> B,false,0.85
* ...
* BRACA2 -> A,true,0.15
* -> B,false,0.20
* ...
*/
// 1.Process parameters
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "-f") == 0)
{
fileInput = argv[++i];
}
else if (strcmp(argv[i], "-o") == 0)
{
outFile = argv[++i];
}
else if (strcmp(argv[i], "--c1") == 0)
{
condition1 = argv[++i];
}
else if (strcmp(argv[i], "--c2") == 0)
{
condition2 = argv[++i];
}
else if (strcmp(argv[i], "-s") == 0)
{
statistic = argv[++i];
}
else if (strcmp(argv[i], "-p") == 0)
{
percentile_mode = argv[++i];
}
else if (strcmp(argv[i], "-t") == 0)
{
n_threads = atoi(argv[++i]);
if (n_threads < 1) n_threads = 1;
}
else if (strcmp(argv[i],"-h") == 0)
{
printHelp();
return 0;
}
}
// Check Arguments
if(argumentChecking(fileInput, outFile, condition1, condition2))
{
return -1;
}
// Updates statistic
string headerOutput = "gene\tdiff_median\tmedianCase\tmedianControl\tfold_change\tmedian_pv\tmedian_pv_fdr";
if (statistic.compare("perc25") == 0)
{
fStatisticValue = 25.0;
doMedian = false;
headerOutput = "gene\tdiff_lowerq\tlowerqCase\tlowerqControl\tfold_change\tlowerq_pv\tlowerq_pv_fdr";
}
else if (statistic.compare("perc75") == 0)
{
fStatisticValue = 75.0;
doMedian = false;
headerOutput = "gene\tdiff_UpQ\tupperqCase\tupperqControl\tfold_change\tupperq_pv\tupper_pv_fdr";
}
else
{
char *p;
double x = strtod(statistic.c_str(), &p);
if (x > 0.0 && x < 100.0)
{
fStatisticValue = x;
doMedian = false;
ostringstream s;
s << "gene\tdiff_" << x << "%\t" << x << "\%_Case\t" << x << "\%_Control\tfold_change\t" << x << "\%_pv\t" << x << "\%_pv_fdr";
headerOutput = s.str();
}
}
if (percentile_mode.compare("auto") == 0) pc_mode = AUTO;
else if (percentile_mode.compare("linear") == 0) pc_mode = LINEAR_INTERPOLATION;
else if (percentile_mode.compare("nearest") == 0) pc_mode = NEAREST_RANK;
else
{
cerr << "Percentile mode '" << percentile_mode << "' not recognized" << endl;
return -1;
}
// Parsing Input file
if (!loadFileInfo(fileInput, vGenes, condition1, condition2))
{
cerr << "Sorry!! Can not open file " << fileInput << endl;
return -1;
}
// Allocate and make C structure for permutation routine
struct perm_data pdata;
pdata.n_cases = vGenes.begin()->nCases;
pdata.n_controls = vGenes.begin()->nControls;
int n_samples = pdata.n_cases + pdata.n_controls;
pdata.n_var = vGenes.size();
pdata.data = (float *)malloc(sizeof(float) * pdata.n_var * (4 + n_samples));
pdata.fold_change = pdata.data + pdata.n_var * n_samples;
pdata.pc_cases = pdata.fold_change + pdata.n_var;
pdata.pc_controls = pdata.pc_cases + pdata.n_var;
pdata.pc_diff = pdata.pc_controls + pdata.n_var;
pdata.grp = (group *)malloc(sizeof(group) * n_samples);
pdata.p_values = (double *)malloc(sizeof(double) * pdata.n_var);
// Copy expression data
float *tp = pdata.data;
for (vector<Gene>::iterator gene_it = vGenes.begin(); gene_it != vGenes.end(); ++gene_it)
{
for (vector<SampleGene>::const_iterator iter = gene_it->vGeneValues.begin();iter != gene_it->vGeneValues.end(); ++iter)
{
(*tp++) = (float)iter->expressionValue;
}
}
// Copy group information
int ix = 0;
for (vector<bool>::const_iterator iter = vGenes.begin()->vGroup.begin(); iter != vGenes.begin()->vGroup.end(); ++iter)
{
pdata.grp[ix++] = *iter ? CASE : CONTROL;
}
// Calculate exact permutation p-values
check_percentile(doMedian ? 50.0 : fStatisticValue, pc_mode, n_threads,&pdata);
vector<double> vPvalues;
int i = 0;
for (vector<Gene>::iterator iter = vGenes.begin(); iter != vGenes.end(); ++iter)
{
// Copy results from pdata struture
(*iter).originalDiff = (double)pdata.pc_diff[i];
(*iter).originalMedianCases = (double)pdata.pc_cases[i];
(*iter).originalMedianControl = (double)pdata.pc_controls[i];
(*iter).foldChange = pdata.fold_change[i];
(*iter).pValue = pdata.p_values[i];
// Add pvalue to a vector of pvalues for being correcte by FDR
vPvalues.push_back((*iter).pValue);
i++;
}
vector<double> correctedPvalues;
correct_pvalues_fdr(vPvalues, correctedPvalues);
// Print to file
std::ofstream outfile(outFile.c_str(), std::ofstream::out);
// Header File
outfile << headerOutput << endl;
vector<double>::const_iterator iterCorrected = correctedPvalues.begin();
outfile.precision(15);
for (vector<Gene>::const_iterator iter = vGenes.begin(); iter != vGenes.end();++iter)
{
outfile << (*iter).geneName << "\t" << (*iter).originalDiff << "\t" << (*iter).originalMedianCases;
outfile << "\t" << (*iter).originalMedianControl << "\t" << (*iter).foldChange << "\t" << (*iter).pValue << "\t" << (*iterCorrected) << endl;
++iterCorrected;
}
free(pdata.grp);
free(pdata.data);
free(pdata.p_values);
outfile.close();
return 0;
}
| Java |
//
// iTermBoxDrawingBezierCurveFactory.h
// iTerm2
//
// Created by George Nachman on 7/15/16.
//
//
#import <Cocoa/Cocoa.h>
@interface iTermBoxDrawingBezierCurveFactory : NSObject
+ (NSCharacterSet *)boxDrawingCharactersWithBezierPaths;
+ (NSArray<NSBezierPath *> *)bezierPathsForBoxDrawingCode:(unichar)code
cellSize:(NSSize)cellSize
scale:(CGFloat)scale;
@end
| Java |
/* Remove some alpha blended PNGs to avoid problems with antiquated IE <= 6. It doesn't look much different unless you look closely. */
div.post-content, span.post-frame-top, span.post-frame-bottom { background-image: url(images/post-ie.png);height:1px; overflow:visible}
div.widget-center, span.widget-top, span.widget-bottom { background-image: url(images/widget-ie.png);height:1px; overflow:visible}
div.post-body img { margin: 0 5px}
div.post-footer {height: 1px; overflow: visible}
/*
Some crude fixes for ie5.5 to get it to a useable state, not going to worry about 5.5 beyond this.
*/
body.ie5 div.widget-centre, body.ie55 div.widget-centre{ width: 290px}
body.ie5 div.container, body.ie55 div.container{ margin-left: 20px;} /* As ie55 won't centre the container on the page I'll move it a small amount away from the edge. */
body.ie5 div#comments-block, body.ie55 div#comments-block{width:543px} | Java |
#ifndef _LINUX_PRIO_HEAP_H
#define _LINUX_PRIO_HEAP_H
#include <linux/gfp.h>
struct ptr_heap {
void **ptrs;
int max;
int size;
int (*gt)(void *, void *);
};
extern int heap_init(struct ptr_heap *heap, size_t size, gfp_t gfp_mask,
int (*gt)(void *, void *));
void heap_free(struct ptr_heap *heap);
extern void *heap_insert(struct ptr_heap *heap, void *p);
#endif
| Java |
bjxypingjiao
============
滨江学院评教系统
| Java |
<?php
include_once '../libs/Connection.php';
include_once '../libs/tree_editor.php';
class tree_performance extends tree_editor{
public function __construct(){
parent::__construct();
if(!isset($_POST['action'])){
header("content-type:text/xml;charset=UTF-8");
if(isset($_GET['refresh'])){
$refresh = $_GET['refresh'];
}else{
$refresh = false;
}
echo ($this->getXml($_GET['id'],$_GET['autoload'],$refresh));
}else{
$this->db->query("START TRANSACTION");
$response = "";
$response = $this->parseRequest();
$this->db->query("COMMIT");
echo json_encode($response);
}
}
public function getXmlTree($id=0,$rf,$autoload = true){
$xml = '<tree id="'.$id.'">';
$xml .= $this->getXmlMyPerformanceAuto($id,$rf,$autoload);
$xml .= '</tree>';
return $xml;
}
/********* Top level *****************/
protected function getXmlMyPerformanceAuto($id,$rf,$autoload){
if($autoload=='false'){
$xml = '<item child="1" text="My Studygroups" id="mystg" im1="folder_open.png" im2="folder_closed.png">';
$xml .= $this->getItemLoad(0,"mystg",$rf,false);
$xml .= '</item>';
}else{
if($id == "0"){
$xml = '<item child="1" text="My Studygroups" id="mystg" im1="folder_open.png" im2="folder_closed.png">';
}else{
$xml .= $this->getItemLoad(0,$id,$rf,true);
$xml .= '</item>';
}
}
return $xml;
}
protected function getChildItems($type){
$items = array();
switch ($type) {
case 'studygroup':
$items[] = array('table' => 'performance',
'id' => 'performance',
'pid' => 'studygroup_id',
);
break;
case 'mystg':
$items[] = array('table' => 'studygroups',
'id' => 'studygroup',
'pid' => 'mystg',
);
break;
default:
break;
}
return $items;
}
public function getTableInfoFromType($type){
switch ($type) {
case 'studygroup':
$table = "studygroups";
$id_name = "studygroup";
break;
case 'mystg':
$table = "mystg";
$id_name = "mystg";
break;
case 'performance':
$table = "performance";
$id_name = "performance";
break;
default:
break;
}
return array('table' => $table, 'id_name' => $id_name);
}
public function addPerformanceItem($item){
switch($item){
case "performance":
$values = array(
'studygroup_id' => $_POST["id"],
'public' => 1
);
break;
}
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->addItem($itemInfo['table'],$values,$item);
return $response;
}
public function addNotPublicPerformanceItem($item){
switch($item){
case "performance":
$values = array(
'studygroup_id' => $_POST["id"],
'public' => 0
);
break;
}
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->addItem($itemInfo['table'],$values,$item);
return $response;
}
public function deletePerformanceItem($id,$item){
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->removeItem($id,$itemInfo['table'],$itemInfo['id_name']);
return $response;
}
public function sharePerformanceItem($id,$item){
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->shareItem($id,$itemInfo['table'],$itemInfo['id_name']);
return $response;
}
public function privatePerformanceItem($id,$item){
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->privateItem($id,$itemInfo['table'],$itemInfo['id_name']);
return $response;
}
public function duplicatePerformanceItem($id,$item){
$itemInfo = $this->getTableInfoFromType($item);
$response = $this->duplicateItem($id,$itemInfo['table'],$itemInfo['id_name']);
return $response;
}
public function movePerformanceItem($ids,$item,$sid,$lid,$par){
$itemInfo = $this->getTableInfoFromType($item);
switch($item){
case "performance":
$parents = array(
'studygroup_id' => $_POST['studygroup']
);
break;
}
$response = $this->setParent($sid,$parents,$lid,$itemInfo['id_name'],$itemInfo['table']);
return $response;
}
public function moveDublPerformanceItem($ids,$item,$sid,$lid,$par){
$itemInfo = $this->getTableInfoFromType($item);
switch($item){
case "assignment":
$parents = array(
'studygroup_id' => $_POST['studygroup']
);
break;
}
$response = $this->duplicatePerformanceItem($sid,$item);
$response = $this->setParent($response['id'],$parents,$lid,$itemInfo['id_name'],$itemInfo['table']);
return $response;
}
public function getPerformanceInfo($id){
$result = $this->db->query("
SELECT perf.title_en as title_p, stg.title_en as title_g
FROM performance perf
inner join studygroups stg on perf.studygroup_id=stg.studygroup_id
where perf.performance_id=$id
");
while($row = mysql_fetch_assoc($result)){
$name = $row['title_p'];
$studygroup = $row['title_g'];
}
return array(
"name" => $name,
"studygroup" => $studygroup
);
}
public function getPerformanceDescroption($id){
$description = "";
$notes = "";
$result = $this->db->query("SELECT content_en,owner_notes FROM performance WHERE performance_id=$id LIMIT 1");
while($row = mysql_fetch_assoc($result)){
$description = $row['content_en'];
$notes = $row['owner_notes'];
}
return array('content' => $description,'notes' => $notes);
}
public function putPerformanceDescription($id,$content,$notes){
$result = $this->db->query("UPDATE performance SET content_en='$content',owner_notes='$notes' WHERE performance_id=$id");
return array('update' => true);
}
function parseRequest(){
if(isset($_POST['action'])){
$action = $_POST['action'];
$act = explode("_", $action);
$id = $_POST['id'];
$response = "";
$id = $_POST['id'];
$name = $_POST['name'];
$type = $_POST['node'];
$ids = explode(",", $_POST['ids']);
$par = explode('_', $_POST['tid']);
$sid = $_POST['sid'];
$lid = $_POST['lid'];
$content = $_POST['content'];
$notes = $_POST['notes'];
$description = $_POST['description'];
switch($act[0]){
case "new":
$response = $this->addPerformanceItem($act[1]);
break;
case "delete":
$response = $this->deletePerformanceItem($id,$act[1]);
break;
case "duplicate":
$response = $this->duplicatePerformanceItem($id,$act[1]);
break;
case "rename":
$table = $this->getTableInfoFromType($type);
$response = $this->rename($id,$name,$table['table'],$table['id_name']);
break;
case "move":
$response = $this->movePerformanceItem($ids,$act[1],$sid,$lid,$par);
break;
case "movedupl":
$response = $this->moveDublPerformanceItem($ids,$act[1],$sid,$lid,$par);
break;
case "getassignment":
$response = $this->getAssignmentContent($id);
$response["info"] = $this->getAssignmentInfo($id);
break;
case "putassignment":
$response = $this->putAssignmentContent($id,$content,$notes);
break;
case "share":
$response = $this->sharePerformanceItem($id,$act[1]);
break;
case "private":
$response = $this->privatePerformanceItem($id,$act[1]);
break;
case "getassessperformance":
$response = $this->getPerformanceDescroption($id);
$response["info"] = $this->getPerformanceInfo($id);
$response["info"]["view_assessments"] = dlang("header_asignment_view_performance","View Performance");
$response["info"]["assessment_image"] = "dhtmlx/dhtmlxTree/codebase/imgs/csh_schoolmule/performance.png";
break;
case "getperformance":
$response = $this->getPerformanceDescroption($id);
$response["info"] = $this->getPerformanceInfo($id);
$response["info"]["view_assessments"] = "View Assessments";
$response["info"]["assessment_image"] = "dhtmlx/dhtmlxTree/codebase/imgs/csh_schoolmule/assessment.png";
break;
case "putperformance":
$response = $this->putPerformanceDescription($id,$_POST['content'],$_POST['notes']);
break;
case "newnotpublic":
$response = $this->addNotPublicPerformanceItem($act[1]);
}
return $response;
}else{
return false;
}
}
}
?> | Java |
package imageresizerforandroid;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.swing.ImageIcon;
/**
*
* @author fonter
*/
public class ImageContainer {
private final BufferedImage image;
private ImageIcon cache;
private final File file;
public ImageContainer (BufferedImage image, File file) {
this.image = image;
this.file = file;
}
public String getNormalizeName () {
String name = file.getName();
int pos = name.lastIndexOf(".");
if (pos > 0) {
return name.substring(0, pos);
}
return name;
}
public ImageIcon getCache () {
return cache;
}
public File getFile () {
return file;
}
public BufferedImage getImage () {
return image;
}
public void setCache (ImageIcon cache) {
this.cache = cache;
}
public boolean isCacheCreate () {
return cache != null;
}
}
| Java |
from buildbot.status.web.auth import IAuth
class Authz(object):
"""Decide who can do what."""
knownActions = [
# If you add a new action here, be sure to also update the documentation
# at docs/cfg-statustargets.texinfo
'gracefulShutdown',
'forceBuild',
'forceAllBuilds',
'pingBuilder',
'stopBuild',
'stopAllBuilds',
'cancelPendingBuild',
]
def __init__(self,
default_action=False,
auth=None,
**kwargs):
self.auth = auth
if auth:
assert IAuth.providedBy(auth)
self.config = dict( (a, default_action) for a in self.knownActions )
for act in self.knownActions:
if act in kwargs:
self.config[act] = kwargs[act]
del kwargs[act]
if kwargs:
raise ValueError("unknown authorization action(s) " + ", ".join(kwargs.keys()))
def advertiseAction(self, action):
"""Should the web interface even show the form for ACTION?"""
if action not in self.knownActions:
raise KeyError("unknown action")
cfg = self.config.get(action, False)
if cfg:
return True
return False
def needAuthForm(self, action):
"""Does this action require an authentication form?"""
if action not in self.knownActions:
raise KeyError("unknown action")
cfg = self.config.get(action, False)
if cfg == 'auth' or callable(cfg):
return True
return False
def actionAllowed(self, action, request, *args):
"""Is this ACTION allowed, given this http REQUEST?"""
if action not in self.knownActions:
raise KeyError("unknown action")
cfg = self.config.get(action, False)
if cfg:
if cfg == 'auth' or callable(cfg):
if not self.auth:
return False
user = request.args.get("username", ["<unknown>"])[0]
passwd = request.args.get("passwd", ["<no-password>"])[0]
if user == "<unknown>" or passwd == "<no-password>":
return False
if self.auth.authenticate(user, passwd):
if callable(cfg) and not cfg(user, *args):
return False
return True
return False
else:
return True # anyone can do this..
| Java |
#! /usr/bin/env python
# encoding: UTF-8
'''give access permission for files in this folder'''
| Java |
## IGSuite 4.0.1
## Procedure: SpreadsheetWriteExcelUtility.pm
## Last update: 01/07/2010
#############################################################################
# IGSuite 4.0.1 - Provides an Office Suite by simple web interface #
# Copyright (C) 2002 Dante Ortolani [LucaS] #
# #
# This program is free software; you can redistribute it and/or #
# modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation; either version 2 #
# of the License, or (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software Foundation, #
# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #
#############################################################################
package Spreadsheet::WriteExcel::Utility;
###############################################################################
#
# Utility - Helper functions for Spreadsheet::WriteExcel.
#
# Copyright 2000-2008, John McNamara, jmcnamara@cpan.org
#
#
use Exporter;
use strict;
use autouse 'Date::Calc' => qw(Delta_DHMS Decode_Date_EU Decode_Date_US);
use autouse 'Date::Manip' => qw(ParseDate Date_Init);
# Do all of the export preparation
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
# Row and column functions
my @rowcol = qw(
xl_rowcol_to_cell
xl_cell_to_rowcol
xl_inc_row
xl_dec_row
xl_inc_col
xl_dec_col
);
# Date and Time functions
my @dates = qw(
xl_date_list
xl_date_1904
xl_parse_time
xl_parse_date
xl_parse_date_init
xl_decode_date_EU
xl_decode_date_US
);
@ISA = qw(Exporter);
@EXPORT_OK = ();
@EXPORT = (@rowcol, @dates);
%EXPORT_TAGS = (
rowcol => \@rowcol,
dates => \@dates
);
$VERSION = '2.20';
=head1 NAME
Utility - Helper functions for Spreadsheet::WriteExcel.
=head1 VERSION
This document refers to version 0.03 of Spreadsheet::WriteExcel::Utility, released March, 2002.
=head1 SYNOPSIS
Functions to help with some common tasks when using Spreadsheet::WriteExcel.
These functions mainly relate to dealing with rows and columns in A1 notation and to handling dates and times.
use Spreadsheet::WriteExcel::Utility; # Import everything
($row, $col) = xl_cell_to_rowcol('C2'); # (1, 2)
$str = xl_rowcol_to_cell(1, 2); # C2
$str = xl_inc_col('Z1' ); # AA1
$str = xl_dec_col('AA1' ); # Z1
$date = xl_date_list(2002, 1, 1); # 37257
$date = xl_parse_date("11 July 1997"); # 35622
$time = xl_parse_time('3:21:36 PM'); # 0.64
$date = xl_decode_date_EU("13 May 2002"); # 37389
=head1 DESCRIPTION
This module provides a set of functions to help with some common tasks encountered when using the Spreadsheet::WriteExcel module. The two main categories of function are:
Row and column functions: these are used to deal with Excel's A1 representation of cells. The functions in this category are:
xl_rowcol_to_cell
xl_cell_to_rowcol
xl_inc_row
xl_dec_row
xl_inc_col
xl_dec_col
Date and Time functions: these are used to convert dates and times to the numeric format used by Excel. The functions in this category are:
xl_date_list
xl_date_1904
xl_parse_time
xl_parse_date
xl_parse_date_init
xl_decode_date_EU
xl_decode_date_US
All of these functions are exported by default. However, you can use import lists if you wish to limit the functions that are imported:
use Spreadsheet::WriteExcel::Utility; # Import everything
use Spreadsheet::WriteExcel::Utility qw(xl_date_list); # xl_date_list only
use Spreadsheet::WriteExcel::Utility qw(:rowcol); # Row/col functions
use Spreadsheet::WriteExcel::Utility qw(:dates); # Date functions
=head1 ROW AND COLUMN FUNCTIONS
Spreadsheet::WriteExcel supports two forms of notation to designate the position of cells: Row-column notation and A1 notation.
Row-column notation uses a zero based index for both row and column while A1 notation uses the standard Excel alphanumeric sequence of column letter and 1-based row. Columns range from A to IV i.e. 0 to 255, rows range from 1 to 16384 in Excel 5 and 65536 in Excel 97. For example:
(0, 0) # The top left cell in row-column notation.
('A1') # The top left cell in A1 notation.
(1999, 29) # Row-column notation.
('AD2000') # The same cell in A1 notation.
Row-column notation is useful if you are referring to cells programmatically:
for my $i (0 .. 9) {
$worksheet->write($i, 0, 'Hello'); # Cells A1 to A10
}
A1 notation is useful for setting up a worksheet manually and for working with formulas:
$worksheet->write('H1', 200);
$worksheet->write('H2', '=H7+1');
The functions in the following sections can be used for dealing with A1 notation, for example:
($row, $col) = xl_cell_to_rowcol('C2'); # (1, 2)
$str = xl_rowcol_to_cell(1, 2); # C2
Cell references in Excel can be either relative or absolute. Absolute references are prefixed by the dollar symbol as shown below:
A1 # Column and row are relative
$A1 # Column is absolute and row is relative
A$1 # Column is relative and row is absolute
$A$1 # Column and row are absolute
An absolute reference only has an effect if the cell is copied. Refer to the Excel documentation for further details. All of the following functions support absolute references.
=cut
###############################################################################
###############################################################################
=head2 xl_rowcol_to_cell($row, $col, $row_absolute, $col_absolute)
Parameters: $row: Integer
$col: Integer
$row_absolute: Boolean (1/0) [optional, default is 0]
$col_absolute: Boolean (1/0) [optional, default is 0]
Returns: A string in A1 cell notation
This function converts a zero based row and column cell reference to a A1 style string:
$str = xl_rowcol_to_cell(0, 0); # A1
$str = xl_rowcol_to_cell(0, 1); # B1
$str = xl_rowcol_to_cell(1, 0); # A2
The optional parameters C<$row_absolute> and C<$col_absolute> can be used to indicate if the row or column is absolute:
$str = xl_rowcol_to_cell(0, 0, 0, 1); # $A1
$str = xl_rowcol_to_cell(0, 0, 1, 0); # A$1
$str = xl_rowcol_to_cell(0, 0, 1, 1); # $A$1
See L<ROW AND COLUMN FUNCTIONS> for an explanation of absolute cell references.
=cut
###############################################################################
#
# xl_rowcol_to_cell($row, $col, $row_absolute, $col_absolute)
#
sub xl_rowcol_to_cell {
my $row = $_[0];
my $col = $_[1];
my $row_abs = $_[2] ? '$' : '';
my $col_abs = $_[3] ? '$' : '';
my $int = int ($col / 26);
my $frac = $col % 26;
my $chr1 =''; # Most significant character in AA1
if ($int > 0) {
$chr1 = chr( ord('A') + $int -1 );
}
my $chr2 = chr( ord('A') + $frac );
# Zero index to 1-index
$row++;
return $col_abs . $chr1 . $chr2 . $row_abs. $row;
}
###############################################################################
###############################################################################
=head2 xl_cell_to_rowcol($string)
Parameters: $string String in A1 format
Returns: List ($row, $col)
This function converts an Excel cell reference in A1 notation to a zero based row and column. The function will also handle Excel's absolute, C<$>, cell notation.
my ($row, $col) = xl_cell_to_rowcol('A1'); # (0, 0)
my ($row, $col) = xl_cell_to_rowcol('B1'); # (0, 1)
my ($row, $col) = xl_cell_to_rowcol('C2'); # (1, 2)
my ($row, $col) = xl_cell_to_rowcol('$C2' ); # (1, 2)
my ($row, $col) = xl_cell_to_rowcol('C$2' ); # (1, 2)
my ($row, $col) = xl_cell_to_rowcol('$C$2'); # (1, 2)
=cut
###############################################################################
#
# xl_cell_to_rowcol($string)
#
# Returns: ($row, $col, $row_absolute, $col_absolute)
#
# The $row_absolute and $col_absolute parameters aren't documented because they
# mainly used internally and aren't very useful to the user.
#
sub xl_cell_to_rowcol {
my $cell = shift;
$cell =~ /(\$?)([A-I]?[A-Z])(\$?)(\d+)/;
my $col_abs = $1 eq "" ? 0 : 1;
my $col = $2;
my $row_abs = $3 eq "" ? 0 : 1;
my $row = $4;
# Convert base26 column string to number
# All your Base are belong to us.
my @chars = split //, $col;
my $expn = 0;
$col = 0;
while (@chars) {
my $char = pop(@chars); # LS char first
$col += (ord($char) -ord('A') +1) * (26**$expn);
$expn++;
}
# Convert 1-index to zero-index
$row--;
$col--;
return $row, $col, $row_abs, $col_abs;
}
###############################################################################
###############################################################################
=head2 xl_inc_row($string)
Parameters: $string, a string in A1 format
Returns: Incremented string in A1 format
This functions takes a cell reference string in A1 notation and increments the row. The function will also handle Excel's absolute, C<$>, cell notation:
my $str = xl_inc_row('A1' ); # A2
my $str = xl_inc_row('B$2' ); # B$3
my $str = xl_inc_row('$C3' ); # $C4
my $str = xl_inc_row('$D$4'); # $D$5
=cut
###############################################################################
#
# xl_inc_row($string)
#
sub xl_inc_row {
my $cell = shift;
my ($row, $col, $row_abs, $col_abs) = xl_cell_to_rowcol($cell);
return xl_rowcol_to_cell(++$row, $col, $row_abs, $col_abs);
}
###############################################################################
###############################################################################
=head2 xl_dec_row($string)
Parameters: $string, a string in A1 format
Returns: Decremented string in A1 format
This functions takes a cell reference string in A1 notation and decrements the row. The function will also handle Excel's absolute, C<$>, cell notation:
my $str = xl_dec_row('A2' ); # A1
my $str = xl_dec_row('B$3' ); # B$2
my $str = xl_dec_row('$C4' ); # $C3
my $str = xl_dec_row('$D$5'); # $D$4
=cut
###############################################################################
#
# xl_dec_row($string)
#
# Decrements the row number of an Excel cell reference in A1 notation.
# For example C4 to C3
#
# Returns: a cell reference string.
#
sub xl_dec_row {
my $cell = shift;
my ($row, $col, $row_abs, $col_abs) = xl_cell_to_rowcol($cell);
return xl_rowcol_to_cell(--$row, $col, $row_abs, $col_abs);
}
###############################################################################
###############################################################################
=head2 xl_inc_col($string)
Parameters: $string, a string in A1 format
Returns: Incremented string in A1 format
This functions takes a cell reference string in A1 notation and increments the column. The function will also handle Excel's absolute, C<$>, cell notation:
my $str = xl_inc_col('A1' ); # B1
my $str = xl_inc_col('Z1' ); # AA1
my $str = xl_inc_col('$B1' ); # $C1
my $str = xl_inc_col('$D$5'); # $E$5
=cut
###############################################################################
#
# xl_inc_col($string)
#
# Increments the column number of an Excel cell reference in A1 notation.
# For example C3 to D3
#
# Returns: a cell reference string.
#
sub xl_inc_col {
my $cell = shift;
my ($row, $col, $row_abs, $col_abs) = xl_cell_to_rowcol($cell);
return xl_rowcol_to_cell($row, ++$col, $row_abs, $col_abs);
}
###############################################################################
###############################################################################
=head2 xl_dec_col($string)
Parameters: $string, a string in A1 format
Returns: Decremented string in A1 format
This functions takes a cell reference string in A1 notation and decrements the column. The function will also handle Excel's absolute, C<$>, cell notation:
my $str = xl_dec_col('B1' ); # A1
my $str = xl_dec_col('AA1' ); # Z1
my $str = xl_dec_col('$C1' ); # $B1
my $str = xl_dec_col('$E$5'); # $D$5
=cut
###############################################################################
#
# xl_dec_col($string)
#
sub xl_dec_col {
my $cell = shift;
my ($row, $col, $row_abs, $col_abs) = xl_cell_to_rowcol($cell);
return xl_rowcol_to_cell($row, --$col, $row_abs, $col_abs);
}
=head1 TIME AND DATE FUNCTIONS
Dates and times in Excel are represented by real numbers, for example "Jan 1 2001 12:30 AM" is represented by the number 36892.521.
The integer part of the number stores the number of days since the epoch and the fractional part stores the percentage of the day in seconds.
The epoch can be either 1900 or 1904. Excel for Windows uses 1900 and Excel for Macintosh uses 1904. The epochs are:
1900: 0 January 1900 i.e. 31 December 1899
1904: 1 January 1904
Excel on Windows and the Macintosh will convert automatically between one system and the other. By default Spreadsheet::WriteExcel uses the 1900 format. To use the 1904 epoch you must use the C<set_1904()> workbook method, see the Spreadsheet::WriteExcel documentation.
There are two things to note about the 1900 date format. The first is that the epoch starts on 0 January 1900. The second is that the year 1900 is erroneously but deliberately treated as a leap year. Therefore you must add an extra day to dates after 28 February 1900. The functions in the following section will deal with these issues automatically. The reason for this anomaly is explained at http://support.microsoft.com/support/kb/articles/Q181/3/70.asp
Note, a date or time in Excel is like any other number. To display the number as a date you must apply a number format to it: Refer to the C<set_num_format()> method in the Spreadsheet::WriteExcel documentation:
$date = xl_date_list(2001, 1, 1, 12, 30);
$format->set_num_format('mmm d yyyy hh:mm AM/PM');
$worksheet->write('A1', $date , $format); # Jan 1 2001 12:30 AM
To use these functions you must install the C<Date::Manip> and C<Date::Calc> modules. See L<REQUIREMENTS> and the individual requirements of each functions.
See also the DateTime::Format::Excel module,http://search.cpan.org/search?dist=DateTime-Format-Excel which is part of the DateTime project and which deals specifically with converting dates and times to and from Excel's format.
=cut
###############################################################################
###############################################################################
=head2 xl_date_list($years, $months, $days, $hours, $minutes, $seconds)
Parameters: $years: Integer
$months: Integer [optional, default is 1]
$days: Integer [optional, default is 1]
$hours: Integer [optional, default is 0]
$minutes: Integer [optional, default is 0]
$seconds: Float [optional, default is 0]
Returns: A number that represents an Excel date
or undef for an invalid date.
Requires: Date::Calc
This function converts an array of data into a number that represents an Excel date. All of the parameters are optional except for C<$years>.
$date1 = xl_date_list(2002, 1, 2); # 2 Jan 2002
$date2 = xl_date_list(2002, 1, 2, 12); # 2 Jan 2002 12:00 pm
$date3 = xl_date_list(2002, 1, 2, 12, 30); # 2 Jan 2002 12:30 pm
$date4 = xl_date_list(2002, 1, 2, 12, 30, 45); # 2 Jan 2002 12:30:45 pm
This function can be used in conjunction with functions that parse date and time strings. In fact it is used in most of the following functions.
=cut
###############################################################################
#
# xl_date_list($years, $months, $days, $hours, $minutes, $seconds)
#
sub xl_date_list {
return undef unless @_;
my $years = $_[0];
my $months = $_[1] || 1;
my $days = $_[2] || 1;
my $hours = $_[3] || 0;
my $minutes = $_[4] || 0;
my $seconds = $_[5] || 0;
my @date = ($years, $months, $days, $hours, $minutes, $seconds);
my @epoch = (1899, 12, 31, 0, 0, 0);
($days, $hours, $minutes, $seconds) = Delta_DHMS(@epoch, @date);
my $date = $days + ($hours*3600 +$minutes*60 +$seconds)/(24*60*60);
# Add a day for Excel's missing leap day in 1900
$date++ if ($date > 59);
return $date;
}
###############################################################################
###############################################################################
=head2 xl_parse_time($string)
Parameters: $string, a textual representation of a time
Returns: A number that represents an Excel time
or undef for an invalid time.
This function converts a time string into a number that represents an Excel time. The following time formats are valid:
hh:mm [AM|PM]
hh:mm [AM|PM]
hh:mm:ss [AM|PM]
hh:mm:ss.ss [AM|PM]
The meridian, AM or PM, is optional and case insensitive. A 24 hour time is assumed if the meridian is omitted
$time1 = xl_parse_time('12:18');
$time2 = xl_parse_time('12:18:14');
$time3 = xl_parse_time('12:18:14 AM');
$time4 = xl_parse_time('1:18:14 AM');
Time in Excel is expressed as a fraction of the day in seconds. Therefore you can calculate an Excel time as follows:
$time = ($hours*3600 +$minutes*60 +$seconds)/(24*60*60);
=cut
###############################################################################
#
# xl_parse_time($string)
#
sub xl_parse_time {
my $time = shift;
if ($time =~ /(\d{1,2}):(\d\d):?((?:\d\d)(?:\.\d+)?)?(?:\s+)?(am|pm)?/i) {
my $hours = $1;
my $minutes = $2;
my $seconds = $3 || 0;
my $meridian = lc($4) || '';
# Normalise midnight and midday
$hours = 0 if ($hours == 12 && $meridian ne '');
# Add 12 hours to the pm times. Note: 12.00 pm has been set to 0.00.
$hours += 12 if $meridian eq 'pm';
# Calculate the time as a fraction of 24 hours in seconds
return ($hours*3600 +$minutes*60 +$seconds)/(24*60*60);
}
else {
return undef; # Not a valid time string
}
}
###############################################################################
###############################################################################
=head2 xl_parse_date($string)
Parameters: $string, a textual representation of a date and time
Returns: A number that represents an Excel date
or undef for an invalid date.
Requires: Date::Manip and Date::Calc
This function converts a date and time string into a number that represents an Excel date.
The parsing is performed using the C<ParseDate()> function of the Date::Manip module. Refer to the Date::Manip documentation for further information about the date and time formats that can be parsed. In order to use this function you will probably have to initialise some Date::Manip variables via the C<xl_parse_date_init()> function, see below.
xl_parse_date_init("TZ=GMT","DateFormat=non-US");
$date1 = xl_parse_date("11/7/97");
$date2 = xl_parse_date("Friday 11 July 1997");
$date3 = xl_parse_date("10:30 AM Friday 11 July 1997");
$date4 = xl_parse_date("Today");
$date5 = xl_parse_date("Yesterday");
Note, if you parse a string that represents a time but not a date this function will add the current date. If you want the time without the date you can do something like the following:
$time = xl_parse_date("10:30 AM");
$time -= int($time);
=cut
###############################################################################
#
# xl_parse_date($string)
#
sub xl_parse_date {
my $date = ParseDate($_[0]);
return undef unless defined $date;
# Unpack the return value from ParseDate()
my ($years, $months, $days, $hours, undef, $minutes, undef, $seconds) =
unpack("A4 A2 A2 A2 C A2 C A2", $date);
# Convert to Excel date
return xl_date_list($years, $months, $days, $hours, $minutes, $seconds);
}
###############################################################################
###############################################################################
=head2 xl_parse_date_init("variable=value", ...)
Parameters: A list of Date::Manip variable strings
Returns: A list of all the Date::Manip strings
Requires: Date::Manip
This function is used to initialise variables required by the Date::Manip module. You should call this function before calling C<xl_parse_date()>. It need only be called once.
This function is a thin wrapper for the C<Date::Manip::Date_Init()> function. You can use C<Date_Init()> directly if you wish. Refer to the Date::Manip documentation for further information.
xl_parse_date_init("TZ=MST","DateFormat=US");
$date1 = xl_parse_date("11/7/97"); # November 7th 1997
xl_parse_date_init("TZ=GMT","DateFormat=non-US");
$date1 = xl_parse_date("11/7/97"); # July 11th 1997
=cut
###############################################################################
#
# xl_parse_date_init("variable=value", ...)
#
sub xl_parse_date_init {
Date_Init(@_); # How lazy is that.
}
###############################################################################
###############################################################################
=head2 xl_decode_date_EU($string)
Parameters: $string, a textual representation of a date and time
Returns: A number that represents an Excel date
or undef for an invalid date.
Requires: Date::Calc
This function converts a date and time string into a number that represents an Excel date.
The date parsing is performed using the C<Decode_Date_EU()> function of the Date::Calc module. Refer to the Date::Calc for further information about the date formats that can be parsed. Also note the following from the Date::Calc documentation:
"If the year is given as one or two digits only (i.e., if the year is less than 100), it is mapped to the window 1970 -2069 as follows":
0 E<lt>= $year E<lt> 70 ==> $year += 2000;
70 E<lt>= $year E<lt> 100 ==> $year += 1900;
The time portion of the string is parsed using the C<xl_parse_time()> function described above.
Note: the EU in the function name means that a European date format is assumed if it is not clear from the string. See the first example below.
$date1 = xl_decode_date_EU("11/7/97"); #11 July 1997
$date2 = xl_decode_date_EU("Sat 12 Sept 1998");
$date3 = xl_decode_date_EU("4:30 AM Sat 12 Sept 1998");
=cut
###############################################################################
#
# xl_decode_date_EU($string)
#
sub xl_decode_date_EU {
return undef unless @_;
my $date = shift;
my @date;
my $time = 0;
# Remove and decode the time portion of the string
if ($date =~ s/(\d{1,2}:\d\d:?(\d\d(\.\d+)?)?(\s+)?(am|pm)?)//i) {
$time = xl_parse_time($1);
return undef unless defined $time;
}
# Return if the string is now blank, i.e. it contained a time only.
return $time if $date =~ /^\s*$/;
# Decode the date portion of the string
@date = Decode_Date_EU($date);
return undef unless @date;
return xl_date_list(@date) + $time;
}
###############################################################################
###############################################################################
=head2 xl_decode_date_US($string)
Parameters: $string, a textual representation of a date and time
Returns: A number that represents an Excel date
or undef for an invalid date.
Requires: Date::Calc
This function converts a date and time string into a number that represents an Excel date.
The date parsing is performed using the C<Decode_Date_US()> function of the Date::Calc module. Refer to the Date::Calc for further information about the date formats that can be parsed. Also note the following from the Date::Calc documentation:
"If the year is given as one or two digits only (i.e., if the year is less than 100), it is mapped to the window 1970 -2069 as follows":
0 <= $year < 70 ==> $year += 2000;
70 <= $year < 100 ==> $year += 1900;
The time portion of the string is parsed using the C<xl_parse_time()> function described above.
Note: the US in the function name means that an American date format is assumed if it is not clear from the string. See the first example below.
$date1 = xl_decode_date_US("11/7/97"); # 7 November 1997
$date2 = xl_decode_date_US("12 Sept Saturday 1998");
$date3 = xl_decode_date_US("4:30 AM 12 Sept Sat 1998");
=cut
###############################################################################
#
# xl_decode_date_US($string)
#
sub xl_decode_date_US {
return undef unless @_;
my $date = shift;
my @date;
my $time = 0;
# Remove and decode the time portion of the string
if ($date =~ s/(\d{1,2}:\d\d:?(\d\d(\.\d+)?)?(\s+)?(am|pm)?)//i) {
$time = xl_parse_time($1);
return undef unless defined $time;
}
# Return if the string is now blank, i.e. it contained a time only.
return $time if $date =~ /^\s*$/;
# Decode the date portion of the string
@date = Decode_Date_US($date);
return undef unless @date;
return xl_date_list(@date) + $time;
}
###############################################################################
###############################################################################
=head2 xl_date_1904($date)
Parameters: $date, an Excel date with a 1900 epoch
Returns: an Excel date with a 1904 epoch or zero if
the $date is before 1904
This function converts an Excel date based on the 1900 epoch into a date based on the 1904 epoch.
$date1 = xl_date_list(2002, 1, 13); # 13 Jan 2002, 1900 epoch
$date2 = xl_date_1904($date1); # 13 Jan 2002, 1904 epoch
See also the C<set_1904()> workbook method in the Spreadsheet::WriteExcel documentation.
=cut
###############################################################################
#
# xl_decode_date_US($string)
#
sub xl_date_1904 {
my $date = $_[0] || 0;
if ($date < 1462) {
# before 1904
$date = 0;
}
else {
$date -= 1462;
}
return $date;
}
=head1 REQUIREMENTS
The date and time functions require functions from the C<Date::Manip> and C<Date::Calc> modules. The required functions are "autoused" from these modules so that you do not have to install them unless you wish to use the date and time routines. Therefore it is possible to use the row and column functions without having C<Date::Manip> and C<Date::Calc> installed.
For more information about "autousing" refer to the documentation on the C<autouse> pragma.
=head1 BUGS
When using the autoused functions from C<Date::Manip> and C<Date::Calc> on Perl 5.6.0 with C<-w> you will get a warning like this:
"Subroutine xxx redefined ..."
The current workaround for this is to put C<use warnings;> near the beginning of your program.
=head1 AUTHOR
John McNamara jmcnamara@cpan.org
=head1 COPYRIGHT
© MM-MMVIII, John McNamara.
All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.
=cut
1;
__END__
| Java |
<?php
/**
* Helpers for handling timezone based event datetimes.
*
* In our timezone logic, the term "local" refers to the locality of an event
* rather than the local WordPress timezone.
*/
class E_Register_NowTimezones {
const SITE_TIMEZONE = 'site';
const EVENT_TIMEZONE = 'event';
/**
* Container for reusable DateTimeZone objects.
*
* @var array
*/
protected static $timezones = array();
public static function init() {
self::invalidate_caches();
}
/**
* Clear any cached timezone-related values when appropriate.
*
* Currently we are concerned only with the site timezone abbreviation.
*/
protected static function invalidate_caches() {
add_filter( 'pre_update_option_gmt_offset', array( __CLASS__, 'clear_site_timezone_abbr' ) );
add_filter( 'pre_update_option_timezone_string', array( __CLASS__, 'clear_site_timezone_abbr' ) );
}
/**
* Wipe the cached site timezone abbreviation, if set.
*
* @param mixed $option_val (passed through without modification)
*
* @return mixed
*/
public static function clear_site_timezone_abbr( $option_val ) {
delete_transient( 'tribe_events_wp_timezone_abbr' );
return $option_val;
}
/**
* Returns the current site-wide timezone string.
*
* Based on the core WP code found in wp-admin/options-general.php.
*
* @return string
*/
public static function wp_timezone_string() {
$current_offset = get_option( 'gmt_offset' );
$tzstring = get_option( 'timezone_string' );
// Return the timezone string if already set
if ( ! empty( $tzstring ) ) {
return $tzstring;
}
// Otherwise return the UTC offset
if ( 0 == $current_offset ) {
return 'UTC+0';
} elseif ( $current_offset < 0 ) {
return 'UTC' . $current_offset;
}
return 'UTC+' . $current_offset;
}
/**
* Returns the current site-wide timezone string abbreviation, if it can be
* determined or falls back on the full timezone string/offset text.
*
* @param string $date
*
* @return string
*/
public static function wp_timezone_abbr( $date ) {
$abbr = get_transient( 'tribe_events_wp_timezone_abbr' );
if ( empty( $abbr ) ) {
$timezone_string = self::wp_timezone_string();
$abbr = self::abbr( $date, $timezone_string );
set_transient( 'tribe_events_wp_timezone_abbr', $abbr );
}
return empty( $abbr )
? $timezone_string
: $abbr;
}
/**
* Helper function to retrieve the timezone string for a given UTC offset
*
* This is a close copy of WooCommerce's wc_timezone_string() method
*
* @param string $offset UTC offset
*
* @return string
*/
public static function generate_timezone_string_from_utc_offset( $offset ) {
if ( ! self::is_utc_offset( $offset ) ) {
return $offset;
}
// ensure we have the minutes on the offset
if ( ! strpos( $offset, ':' ) ) {
$offset .= ':00';
}
$offset = str_replace( 'UTC', '', $offset );
list( $hours, $minutes ) = explode( ':', $offset );
$seconds = $hours * 60 * 60 + $minutes * 60;
// attempt to guess the timezone string from the UTC offset
$timezone = timezone_name_from_abbr( '', $seconds, 0 );
if ( false === $timezone ) {
$is_dst = date( 'I' );
foreach ( timezone_abbreviations_list() as $abbr ) {
foreach ( $abbr as $city ) {
if (
$city['dst'] == $is_dst
&& $city['offset'] == $seconds
) {
return $city['timezone_id'];
}
}
}
// fallback to UTC
return 'UTC';
}
return $timezone;
}
/**
* Tried to convert the provided $datetime to UTC from the timezone represented by $tzstring.
*
* Though the usual range of formats are allowed, $datetime ordinarily ought to be something
* like the "Y-m-d H:i:s" format (ie, no timezone information). If it itself contains timezone
* data, the results may be unexpected.
*
* In those cases where the conversion fails to take place, the $datetime string will be
* returned untouched.
*
* @param string $datetime
* @param string $tzstring
*
* @return string
*/
public static function to_utc( $datetime, $tzstring ) {
if ( self::is_utc_offset( $tzstring ) ) {
return self::apply_offset( $datetime, $tzstring, true );
}
try {
$local = self::get_timezone( $tzstring );
$utc = self::get_timezone( 'UTC' );
$datetime = date_create( $datetime, $local )->setTimezone( $utc );
return $datetime->format( E_Register_NowDate_Utils::DBDATETIMEFORMAT );
}
catch ( Exception $e ) {
return $datetime;
}
}
/**
* Tries to convert the provided $datetime to the timezone represented by $tzstring.
*
* This is the sister function of self::to_utc() - please review the docs for that method
* for more information.
*
* @param string $datetime
* @param string $tzstring
*
* @return string
*/
public static function to_tz( $datetime, $tzstring ) {
if ( self::is_utc_offset( $tzstring ) ) {
return self::apply_offset( $datetime, $tzstring );
}
try {
$local = self::get_timezone( $tzstring );
$utc = self::get_timezone( 'UTC' );
$datetime = date_create( $datetime, $utc )->setTimezone( $local );
return $datetime->format( E_Register_NowDate_Utils::DBDATETIMEFORMAT );
}
catch ( Exception $e ) {
return $datetime;
}
}
/**
* Tests to see if the timezone string is a UTC offset, ie "UTC+2".
*
* @param string $timezone
*
* @return bool
*/
public static function is_utc_offset( $timezone ) {
$timezone = trim( $timezone );
return ( 0 === strpos( $timezone, 'UTC' ) && strlen( $timezone ) > 3 );
}
/**
* @param string $datetime
* @param mixed $offset (string or numeric offset)
* @param bool $invert = false
*
* @return string
*/
public static function apply_offset( $datetime, $offset, $invert = false ) {
// Normalize
$offset = strtolower( trim( $offset ) );
// Strip any leading "utc" text if set
if ( 0 === strpos( $offset, 'utc' ) ) {
$offset = substr( $offset, 3 );
}
// It's possible no adjustment will be needed
if ( 0 === $offset ) {
return $datetime;
}
// Convert the offset to minutes for easier handling of fractional offsets
$offset = (int) ( $offset * 60 );
// Invert the offset? Useful for stripping an offset that has already been applied
if ( $invert ) {
$offset *= -1;
}
try {
if ( $offset > 0 ) $offset = '+' . $offset;
$offset = $offset . ' minutes';
$datetime = date_create( $datetime )->modify( $offset );
return $datetime->format( E_Register_NowDate_Utils::DBDATETIMEFORMAT );
}
catch ( Exception $e ) {
return $datetime;
}
}
/**
* Accepts a unix timestamp and adjusts it so that when it is used to consitute
* a new datetime string, that string reflects the designated timezone.
*
* @param string $unix_timestamp
* @param string $tzstring
*
* @return string
*/
public static function adjust_timestamp( $unix_timestamp, $tzstring ) {
try {
$local = self::get_timezone( $tzstring );
$datetime = date_create_from_format( 'U', $unix_timestamp )->format( E_Register_NowDate_Utils::DBDATETIMEFORMAT );
return date_create_from_format( 'Y-m-d H:i:s', $datetime, $local )->getTimestamp();
}
catch( Exception $e ) {
return $unix_timestamp;
}
}
/**
* Returns a DateTimeZone object matching the representation in $tzstring where
* possible, or else representing UTC (or, in the worst case, false).
*
* If optional parameter $with_fallback is true, which is the default, then in
* the event it cannot find/create the desired timezone it will try to return the
* UTC DateTimeZone before bailing.
*
* @param string $tzstring
* @param bool $with_fallback = true
*
* @return DateTimeZone|false
*/
public static function get_timezone( $tzstring, $with_fallback = true ) {
if ( isset( self::$timezones[ $tzstring ] ) ) {
return self::$timezones[ $tzstring ];
}
try {
self::$timezones[ $tzstring ] = new DateTimeZone( $tzstring );
return self::$timezones[ $tzstring ];
}
catch ( Exception $e ) {
if ( $with_fallback ) {
return self::get_timezone( 'UTC', true );
}
}
return false;
}
/**
* Returns a string representing the timezone/offset currently desired for
* the display of dates and times.
*
* @return string
*/
public static function mode() {
$mode = self::EVENT_TIMEZONE;
if ( 'site' === tribe_get_option( 'tribe_events_timezone_mode' ) ) {
$mode = self::SITE_TIMEZONE;
}
return apply_filters( 'tribe_events_current_display_timezone', $mode );
}
/**
* Confirms if the current timezone mode matches the $possible_mode.
*
* @param string $possible_mode
*
* @return bool
*/
public static function is_mode( $possible_mode ) {
return $possible_mode === self::mode();
}
/**
* Attempts to provide the correct timezone abbreviation for the provided timezone string
* on the date given (and so should account for daylight saving time, etc).
*
* @param string $date
* @param string $timezone_string
*
* @return string
*/
public static function abbr( $date, $timezone_string ) {
try {
return date_create( $date, new DateTimeZone( $timezone_string ) )->format( 'T' );
}
catch ( Exception $e ) {
return '';
}
}
}
| Java |
/*****************************************************************************
* Copyright (C) 2009 by Peter Penz <peter.penz@gmx.at> *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License version 2 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* 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. *
*****************************************************************************/
#ifndef KEDIT_TAGS_DIALOG_H
#define KEDIT_TAGS_DIALOG_H
#include <kdialog.h>
#include <Nepomuk2/Tag>
class KLineEdit;
class QListWidget;
class QListWidgetItem;
class QPushButton;
class QTimer;
/**
* @brief Dialog to edit a list of Nepomuk tags.
*
* It is possible for the user to add existing tags,
* create new tags or to remove tags.
*
* @see KMetaDataConfigurationDialog
*/
class KEditTagsDialog : public KDialog
{
Q_OBJECT
public:
KEditTagsDialog(const QList<Nepomuk2::Tag>& tags,
QWidget* parent = 0,
Qt::WFlags flags = 0);
virtual ~KEditTagsDialog();
QList<Nepomuk2::Tag> tags() const;
virtual bool eventFilter(QObject* watched, QEvent* event);
protected slots:
virtual void slotButtonClicked(int button);
private slots:
void slotTextEdited(const QString& text);
void slotItemEntered(QListWidgetItem* item);
void showDeleteButton();
void deleteTag();
private:
void loadTags();
void removeNewTagItem();
private:
QList<Nepomuk2::Tag> m_tags;
QListWidget* m_tagsList;
QListWidgetItem* m_newTagItem;
QListWidgetItem* m_autoCheckedItem;
QListWidgetItem* m_deleteCandidate;
KLineEdit* m_newTagEdit;
QPushButton* m_deleteButton;
QTimer* m_deleteButtonTimer;
};
#endif
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>»ÆÊ¯ÓÎÏ·ÖÐÐÄÏÂÔØ</title>
<meta name="keywords" content="»ÆÊ¯,ÓÎÏ·ÖÐÐÄ,ÏÂÔØ,»ÆÊ¯,ÓÎÏ·ÖÐÐÄ,µ±µØ,ÆåÅÆÓÎÏ·,ƽ̨," />
<meta name="description" content="»ÆÊ¯ÓÎÏ·ÖÐÐÄÊÇ»ÆÊ¯µ±µØµÄÆåÅÆÓÎϷƽ̨£¬¸Ãƽ̨¾ßÓÐŨÓôµÄµØ·½ÌØÉ«£¬£¬ÔÚÕâÀï¿ÉÒÔÏÖ³¡ÊÓÆµ£¬µ±µØµÄÅóÓÑϲ»¶ÍæµÄ²Ð¼²¶·µØÖ÷ÓÎÏ·£¬»ÆÊ¯Â齫ÓÎÏ·»ÆÊ¯ÓÎÏ·ÖÐÐͼÓУ¬ÁíÍâΪÄú»ÆÊ¯ÓÎÏ·»¹Óи÷ÖÖ½±Æ·Å¶£¡ »ÆÊ¯ÓÎÏ· »ÆÊ¯ÓÎÏ·ÖÐÐÄ »ÆÊ¯ÓÎÏ·´óÌüÏÂÔØ »ÆÊ¯ÓÎÏ·ÖÐÐÄÊǺÜ" />
<LINK rel=stylesheet type=text/css href="/qipai/templets/default/style/style.css">
<LINK rel=stylesheet type=text/css href="/qipai/templets/default/style/p.css">
<BODY>
<DIV class=top>
<DIV class=c_960>
<DIV class=top-nav><SPAN>Hi£¬»¶ÓÀ´µ½789ÓÎÏ·ÖÐÐÄ£¡</SPAN></DIV>
<DIV><!-- logo -->
<DIV style="POSITION: relative" class=logo><A
href="/"></A></DIV>
<DIV class=nav>
<UL>
<LI><a href="/">ÍøÕ¾Ê×Ò³</a></LI>
<LI class=gap></LI>
<LI><a href="/qipai/qpplat/">ÓÎϷƽ̨</a></LI>
<LI class=gap></LI>
<LI><a href="/kefuzhongxin/">¿Í·þÖÐÐÄ</a></LI>
<LI class=gap></LI>
<LI><a href="/youxijieshao/">ÓÎÏ·½éÉÜ</a></LI>
<LI class=gap></LI>
<LI><a href="/Download/">ÏÂÔØÖÐÐÄ</a></LI>
<LI class=gap></LI></UL></DIV><!-- µ¼º½À¸½áÊø --></DIV></DIV></DIV>
<div style="BORDER: #cdcdcd 1px solid; margin-top:10px; width:960px; margin:5px auto"><a href="/Download/"><img src="/qipai/templets/default/images/960X424.jpg" width="960" height="424"></a></div>
<div class="main">
<DIV id=p_con><!--Ò³Ãæ×ó²à²¿·Ö ¿ªÊ¼ -->
<DIV class=p_l>
<DIV class=location><IMG src="/qipai/templets/default/images/flag.png" width=16 height=16>
µ±Ç°Î»ÖÃ:</strong> <a href="/">Ö÷Ò³</a> ><a href='/qipai/qpplat/'>ÆåÅÆÓÎϷƽ̨</a> > </DIV>
<DIV id=pnlContent>
<H1 class=que-title>»ÆÊ¯ÓÎÏ·ÖÐÐÄÏÂÔØ</H1>
<DIV class=que-date> <span>ʱ¼ä:</span>2014-02-21 14:31<span>À´Ô´:</span><a href="http://www.789game.com/">789gameÆåÅÆÓÎÏ·ÖÐÐÄ</a>
<span>×÷Õß:</span>admin <span>µã»÷:</span>
<script src="/qipai/plus/count.php?view=yes&aid=70&mid=1" type='text/javascript' language="javascript"></script>
´Î</DIV>
<DIV class=que-content>
<p>
»ÆÊ¯ÓÎÏ·ÖÐÐÄÊÇ»ÆÊ¯µ±µØµÄÆåÅÆÓÎϷƽ̨£¬¸Ãƽ̨¾ßÓÐŨÓôµÄµØ·½ÌØÉ«£¬£¬ÔÚÕâÀï¿ÉÒÔÏÖ³¡ÊÓÆµ£¬µ±µØµÄÅóÓÑϲ»¶ÍæµÄ²Ð¼²¶·µØÖ÷ÓÎÏ·£¬»ÆÊ¯Â齫ÓÎÏ·»ÆÊ¯ÓÎÏ·ÖÐÐͼÓУ¬ÁíÍâΪÄú»ÆÊ¯ÓÎÏ·»¹Óи÷ÖÖ½±Æ·Å¶£¡</p>
<p>
<strong>»ÆÊ¯ÓÎÏ·</strong></p>
<p>
<strong>»ÆÊ¯ÓÎÏ·ÖÐÐÄ</strong></p>
<p>
<strong>»ÆÊ¯ÓÎÏ·´óÌüÏÂÔØ</strong></p>
<p>
»ÆÊ¯ÓÎÏ·ÖÐÐÄÊǺÜÊÜÓû§»¶ÓµÄ£¬»ÆÊ¯ÓÎÏ·ÖÐÐÄÊǶ¨ÆÚÌṩÉý¼¶£¬°üÀ¨Æ·ËĹú¾üÆå£¬ÏóÆå£¬ºÍÆäËûÁ÷ÐеÄÓÎÏ·Ãâ·ÑÏÂÔØ£¬Ï£Íû»ÆÊ¯ÆåÅÆÓÎÏ·ÄÜÔö¼ÓÄúµÄÉú»îÀÖȤÈÃÄúÍæµÄÓä¿ì£¡</p>
</DIV>
<DIV class=pre-nex>ÉÏһƪ£º<a href='/qipai/qpplat/69.html'>¡¾¾©¶¼ÆåÅÆ¡¿¾©¶¼ÆåÅÆ¹ÙÍø_¾©¶¼ÆåÅÆÏÂÔØ</a> ÏÂÒ»Ìõ£ºÏÂһƪ£º<a href='/qipai/qpplat/71.html'>Ì콡ÆåÅÆ¹Ù·½ÍøÕ¾-´óÁ¬Ì콡ÆåÅÆÏÂÔØ</a> </DIV></DIV>
</DIV>
<DIV class=p_r_xiazai><DIV class=r_ad>
<DIV class=dl_client_v2>
<A style="BACKGROUND-POSITION: 22px -536px" class=client_dl title=ÏÂÔØ¿Í»§¶Ë
rel=nofollow href="/Download/"></A><A class="reg reg_fadein" title=×¢²áÕ˺Å
rel=nofollow href="/Download/"></A>
<A class=demo title=ÓÎÏ·ÊÔÍæ rel=nofollow href="/Download/"></A></DIV></DIV></div>
<DIV class=p_r>
<DL class=box_dl>
<DT>×îÐÂÎÄÕÂ</DT><DD><a href="/qipai/qpplat/136.html">ÒâȤÆåÅÆÓÎÏ·´óÌü¹Ù·½ÍøÕ¾-ÒâȤ</a> </DD>
<DD><a href="/qipai/qpplat/135.html">¿À³ÆåÅÆÓÎÏ·ÖÐÐÄ-¿À³ÆåÅÆÓÎÏ·</a> </DD>
<DD><a href="/qipai/qpplat/134.html">ÁúÓòÆåÅÆÓÎÏ·ÖÐÐÄ-ÁúÓòÆåÅÆ´óÌü</a> </DD>
<DD><a href="/qipai/qpplat/133.html">ÃûÊ˹ú¼ÊÆåÅÆÓÎÏ·¹Ù·½ÍøÕ¾-ÃûÊË</a> </DD>
<DD><a href="/qipai/qpplat/132.html">ÆåÀÖ°ÉÆåÅÆÓÎϷƽ̨-ÆåÀÖ°ÉÓÎÏ·</a> </DD>
<DD><a href="/qipai/qpplat/131.html">ɽˮÆåÅÆÓÎÏ·ÖÐÐÄ-ÖÛɽɽˮÆåÅÆ</a> </DD>
<DD><a href="/qipai/qpplat/130.html">ºã·áÆåÅÆÓÎÏ·´óÌü-ºã·áÆåÅÆ¹Ù·½</a> </DD>
<DD><a href="/qipai/qpplat/129.html">ÓÀºêÆåÅÆÓÎÏ·´óÌü-ÓÀºêÆåÅÆ¹Ù·½</a> </DD>
<DD><a href="/qipai/qpplat/128.html">½ðÀöÆåÅÆÓÎÏ·ÖÐÐĹÙÍø-½ðÀöÆåÅÆ</a> </DD>
<DD><a href="/qipai/qpplat/127.html">ÌìºãÆåÅÆÓÎÏ·ÖÐÐĹÙÍø-ÌìºãÆåÅÆ</a> </DD>
</DL>
<DL class=box_dl>
<DT>×îÈÈÎÄÕÂ</DT>
<DD><a href="/qipai/qpplat/17.html">°²»Õ±ß·æÓÎÏ·¶·µØÖ÷</a> </DD>
<DD><a href="/qipai/qpplat/67.html">6603ÆåÅÆÓÎÏ·ÖÐÐÄ-6603ÆåÅÆ´óÌü</a> </DD>
<DD><a href="/qipai/qpplat/126.html">3171ÓÎÏ·ÖÐÐÄ-3171ÓÎÏ·´óÌü¹Ù·½</a> </DD>
<DD><a href="/qipai/qpplat/89.html">·çÀ×ÓÎÏ·´óÌüÏÂÔØ</a> </DD>
<DD><a href="/qipai/qpplat/117.html">898ÆåÅÆÓÎÏ·´óÌüÏÂÔØ-¿ìÀÖÖ®¶¼Æå</a> </DD>
<DD><a href="/qipai/qpplat/94.html">»ªÏÄÆåÅÆÓÎÏ·´óÌü</a> </DD>
<DD><a href="/qipai/qpplat/112.html">66ÓÎÏ·ÖÐÐÄ-66ÆåÅÆ´óÌü¹Ù·½ÍøÕ¾</a> </DD>
<DD><a href="/qipai/qpplat/121.html">sosoÆåÅÆÓÎÏ·ÖÐÐÄ¡ªÓÎÏ·´óÌüÏÂÔØ</a> </DD>
<DD><a href="/qipai/qpplat/122.html">ÑÇÐÄÆåÅÆÓÎÏ·ÖÐÐÄ-ÑÇÐÄÆåÅÆ¹Ù·½</a> </DD>
<DD><a href="/qipai/qpplat/56.html">89ÆåÅÆÓÎÏ·¹Ù·½ÍøÕ¾-89ÆåÅÆ´óÌü</a> </DD>
</DL><DIV class=tags>
<DL class=box_dl>
<DT>ÓÎÏ·½éÉÜ</DT>
<DIV class=tags>
<A href="/youxijieshao/xiuxianleiyouxi/55.html">½ð²õ²¶Óã</A>
<A href="/youxijieshao/paileiyouxi/65.html">²¶ÓãÓÎÏ·</A>
<A href="/youxijieshao/paileiyouxi/60.html">ÖÁ×ð¶·Å£</A>
<A href="/youxijieshao/paileiyouxi/64.html">ţţÓÎÏ·</A>
<A href="/youxijieshao/shoujileiyouxi/63.html">¿¨ÎåÐÇ</A>
<A href="/youxijieshao/paileiyouxi/61.html">»¶ÀÖ¶·µØÖ÷</A>
<A href="/youxijieshao/paileiyouxi/58.html">¶þÈ˶·Å£</A>
<A href="/youxijieshao/paileiyouxi/58.html">ͬ±Èţţ</A>
<A href="/youxijieshao/xiuxianleiyouxi/57.html">·è¿ñÈü³µ</A>
<A href="/youxijieshao/xiuxianleiyouxi/56.html">·è¿ñ30Ãë³µ</A>
<A href="/youxijieshao/xiuxianleiyouxi/54.html">Îò¿ÕÄÔº£</A>
<A href="/youxijieshao/xiuxianleiyouxi/54.html">´óÉùÄÔº£</A>
<A href="/youxijieshao/xiuxianleiyouxi/50.html">ÀîåÓÅüÓã</A>
<A href="/youxijieshao/paileiyouxi/49.html">·ÉÇÝ×ßÊÞ</A>
<A href="/youxijieshao/paileiyouxi/51.html">¶·µØÖ÷</A>
</DIV></DL></DIV>
</DIV>
</DIV><!--Ò³ÃæÓҲಿ·Ö ½áÊø --></DIV>
</DIV>
<DIV class=footer>
µÖÖÆ²»Á¼ÓÎÏ· ¾Ü¾øµÁ°æÓÎÏ· ×¢Òâ×ÔÎÒ±£»¤ ½÷·ÀÊÜÆÉϵ± ÊʶÈÓÎÏ·ÒæÄÔ ³ÁÃÔÓÎÏ·ÉËÉí ºÏÀí°²ÅÅʱ¼ä ÏíÊܽ¡¿µÉú»î <BR>
789ÓÎÏ·ÖÐÐÄ Ô¥ICP±¸12014032ºÅ-1
±¸°¸ÎĺÅ:ÎÄÍøÓα¸×Ö[2011]C-CBG002ºÅ<BR>¿Í·þQQ£º4000371814 ¿Í·þÈÈÏߣº4000371814 <script type="text/javascript">
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3Fde6684532de22a1b45cd44b14141ff07' type='text/javascript'%3E%3C/script%3E"));
</script><script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_5813709'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s23.cnzz.com/stat.php%3Fid%3D5813709%26show%3Dpic' type='text/javascript'%3E%3C/script%3E"));</script>
</DIV>
</BODY></HTML>
| Java |
using UnityEngine;
using System.Collections;
public class EndScreenController : ScreenController {
public UnityEngine.UI.Text winnerText;
public UnityEngine.UI.Text player1Text;
public UnityEngine.UI.Text player2Text;
public UnityEngine.UI.Text nextLeftPlayers;
public UnityEngine.UI.Text nextRightPlayers;
protected override void OnActivation() {
gameObject.SetActive(true);
winnerText.text = "...";
player1Text.text = "...";
player2Text.text = "...";
nextLeftPlayers.text = "...";
nextRightPlayers.text = "...";
int matchId = eventInfo.matchId;
StartCoroutine (DownloadMatchInfo (matchId));
}
protected override void OnDeactivation() {
}
protected override void OnMatchInfoDownloaded (MatchInfo matchInfo) {
if (matchInfo.state != "OK") {
int matchId = eventInfo.matchId;
StartCoroutine (DownloadMatchInfo (matchId));
return;
}
Bot winner = matchInfo.GetWinner();
if (winner == null) {
winnerText.text = "Draw!";
Bot[] bots = matchInfo.bots;
player1Text.text = createText (bots[0].name, -1);
player2Text.text = createText (bots[1].name, -1);
} else {
winnerText.text = winner.name + " wins!";
Bot looser = matchInfo.GetLooser ();
player1Text.text = createText (winner.name, 3);
player2Text.text = createText (looser.name, 0);
}
int tournamentId = matchInfo.tournamentId;
StartCoroutine(DownloadUpcomingMatches(tournamentId));
}
protected override void OnUpcomingMatchesDownloaded(UpcomingMatches upcomingMatches) {
Match[] matches = upcomingMatches.matches;
nextLeftPlayers.text = "";
nextRightPlayers.text = "";
for (int i = 0; i < 3 && i < matches.Length; i++) {
Match match = matches [i];
string botNameLeft = match.bots [0];
string botNameRight = match.bots [1];
if (i > 0) {
nextLeftPlayers.text += "\n";
nextRightPlayers.text += "\n";
}
nextLeftPlayers.text += botNameLeft;
nextRightPlayers.text += botNameRight;
}
}
private string createText(string botName, int pts) {
string sign = pts >= 0 ? "+" : "";
return botName + "\n" + sign + pts + " pts";
}
}
| Java |
package fortesting;
import java.io.IOException;
public class RunTransformTim {
/**
* Loads data into appropriate tables (assumes scheme already created)
*
* This will import the tables from my CSVs, which I have on dropbox. Let me
* (Tim) know if you need the CSVs No guarantee that it works on CSVs
* generated differently
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// String host = "127.0.0.1";
String host = "52.32.209.104";
// String keyspace = "new";
String keyspace = "main";
String year = "2012";
// if an error occurs during upload of first CSV, use
// GetLastRow.getLastEntry() to find its
// npi value and use that as start. This will not work in other CSVs
// unless the last npi
// added is greater than the largest npi in all previously loaded CSVs
String start = "";
TransformTim t = new TransformTim();
t.injest(host, keyspace, "CSV/MedicareA2012.csv", year, start);
t.injest(host, keyspace, "CSV/MedicareB2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareC2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareD2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareEG2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareHJ2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareKL2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareMN2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareOQ2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareR2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareS2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareTX2012.csv", year, "");
t.injest(host, keyspace, "CSV/MedicareYZ2012.csv", year, "");
}
}
| Java |
/*
* Open Firm Accounting
* A double-entry accounting application for professional services.
*
* Copyright (C) 2014-2020 Pierre Wieser (see AUTHORS)
*
* Open Firm Accounting 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.
*
* Open Firm Accounting 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 Open Firm Accounting; see the file COPYING. If not,
* see <http://www.gnu.org/licenses/>.
*
* Authors:
* Pierre Wieser <pwieser@trychlos.org>
*/
#ifndef __OPENBOOK_API_OFO_BASE_H__
#define __OPENBOOK_API_OFO_BASE_H__
/**
* SECTION: ofobase
* @title: ofoBase
* @short_description: #ofoBase class definition.
* @include: openbook/ofo-base.h
*
* The ofoBase class is the class base for application objects.
*
* Properties:
* - ofo-base-getter:
* a #ofaIGetter instance;
* no default, will be %NULL if has not been previously set.
*/
#include "api/ofa-box.h"
#include "api/ofa-idbconnect-def.h"
#include "api/ofa-igetter-def.h"
#include "api/ofo-base-def.h"
G_BEGIN_DECLS
#define OFO_TYPE_BASE ( ofo_base_get_type())
#define OFO_BASE( object ) ( G_TYPE_CHECK_INSTANCE_CAST( object, OFO_TYPE_BASE, ofoBase ))
#define OFO_BASE_CLASS( klass ) ( G_TYPE_CHECK_CLASS_CAST( klass, OFO_TYPE_BASE, ofoBaseClass ))
#define OFO_IS_BASE( object ) ( G_TYPE_CHECK_INSTANCE_TYPE( object, OFO_TYPE_BASE ))
#define OFO_IS_BASE_CLASS( klass ) ( G_TYPE_CHECK_CLASS_TYPE(( klass ), OFO_TYPE_BASE ))
#define OFO_BASE_GET_CLASS( object ) ( G_TYPE_INSTANCE_GET_CLASS(( object ), OFO_TYPE_BASE, ofoBaseClass ))
#if 0
typedef struct _ofoBaseProtected ofoBaseProtected;
typedef struct {
/*< public members >*/
GObject parent;
/*< protected members >*/
ofoBaseProtected *prot;
}
ofoBase;
typedef struct {
/*< public members >*/
GObjectClass parent;
}
ofoBaseClass;
#endif
/**
* ofo_base_getter:
* @C: the class radical (e.g. 'ACCOUNT')
* @V: the variable name (e.g. 'account')
* @T: the type of required data (e.g. 'amount')
* @R: the returned data if %NULL or an error occured (e.g. '0')
* @I: the identifier of the required field (e.g. 'ACC_DEB_AMOUNT')
*
* A convenience macro to get the value of an identified field from an
* #ofoBase object.
*/
#define ofo_base_getter(C,V,T,R,I) \
g_return_val_if_fail((V) && OFO_IS_ ## C(V),(R)); \
g_return_val_if_fail( !OFO_BASE(V)->prot->dispose_has_run, (R)); \
if( !ofa_box_is_set( OFO_BASE(V)->prot->fields,(I))) return(R); \
return(ofa_box_get_ ## T(OFO_BASE(V)->prot->fields,(I)))
/**
* ofo_base_setter:
* @C: the class mnemonic (e.g. 'ACCOUNT')
* @V: the variable name (e.g. 'account')
* @T: the type of required data (e.g. 'amount')
* @I: the identifier of the required field (e.g. 'ACC_DEB_AMOUNT')
* @D: the data value to be set
*
* A convenience macro to set the value of an identified field from an
* #ofoBase object.
*/
#define ofo_base_setter(C,V,T,I,D) \
g_return_if_fail((V) && OFO_IS_ ## C(V)); \
g_return_if_fail( !OFO_BASE(V)->prot->dispose_has_run ); \
ofa_box_set_ ## T(OFO_BASE(V)->prot->fields,(I),(D))
/**
* Identifier unset value
*/
#define OFO_BASE_UNSET_ID -1
GType ofo_base_get_type ( void ) G_GNUC_CONST;
GList *ofo_base_init_fields_list( const ofsBoxDef *defs );
GList *ofo_base_load_dataset ( const ofsBoxDef *defs,
const gchar *from,
GType type,
ofaIGetter *getter );
GList *ofo_base_load_rows ( const ofsBoxDef *defs,
const ofaIDBConnect *connect,
const gchar *from );
ofaIGetter *ofo_base_get_getter ( ofoBase *base );
G_END_DECLS
#endif /* __OPENBOOK_API_OFO_BASE_H__ */
| Java |
package edu.cmu.cs.cimds.geogame.client.ui;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import edu.cmu.cs.cimds.geogame.client.model.dto.ItemDTO;
public class InventoryGrid extends Grid {
// public static final String MONEY_ICON_FILENAME = "coinbag.jpg";
public static final String BLANK_ICON_FILENAME = "blank.png";
private int numCells;
private VerticalPanel[] blanks;
private List<ItemDTO> inventory = new ArrayList<ItemDTO>();
private ItemImageCreator imageCreator;
private String imageWidth = null;
public InventoryGrid(int numRows, int numColumns) {
super(numRows, numColumns);
this.numCells = numRows * numColumns;
this.blanks = new VerticalPanel[this.numCells];
for(int i=0;i<numCells;i++) {
this.blanks[i] = new VerticalPanel();
this.blanks[i].add(new Image(BLANK_ICON_FILENAME));
this.setWidget(i, this.blanks[i]);
}
this.clearContent();
}
public InventoryGrid(int numRows, int numColumns, ItemImageCreator imageCreator) {
this(numRows, numColumns);
this.imageCreator = imageCreator;
}
public List<ItemDTO> getInventory() { return inventory; }
public void setInventory(List<ItemDTO> inventory) { this.inventory = inventory; }
// public void setInventory(List<ItemTypeDTO> inventory) {
// this.inventory = new ArrayList<ItemTypeDTO>();
// for(ItemTypeDTO itemType : inventory) {
// Item dummyItem = new Item();
// dummyItem.setItemType(itemType);
// this.inventory.add(dummyItem);
// }
// }
public ItemImageCreator getImageCreator() { return imageCreator; }
public void setImageCreator(ItemImageCreator imageCreator) { this.imageCreator = imageCreator; }
public void setImageWidth(String imageWidth) { this.imageWidth = imageWidth; }
public void setWidget(int numCell, Widget w) {
// if(numCell >= this.numCells) {
// throw new IndexOutOfBoundsException();
// }
super.setWidget((int)Math.floor(numCell/this.numColumns), numCell%this.numColumns, w);
}
public void clearContent() {
for(int i=0;i<numCells;i++) {
this.setWidget(i, this.blanks[i]);
}
}
public void refresh() {
this.clearContent();
Collections.sort(this.inventory);
for(int i=0;i<this.inventory.size();i++) {
final ItemDTO item = this.inventory.get(i);
Image image = this.imageCreator.createImage(item);
if(this.imageWidth!=null) {
image.setWidth(this.imageWidth);
}
//Label descriptionLabel = new Label(item.getItemType().getName() + " - " + item.getItemType().getBasePrice() + "G", true);
VerticalPanel itemPanel = new VerticalPanel();
itemPanel.add(image);
//itemPanel.add(descriptionLabel);
this.setWidget(i, itemPanel);
}
}
} | Java |
<?php
/**
* @package phposm
* @copyright Copyright (C) 2015 Wene - ssm2017 Binder ( S.Massiaux ). All rights reserved.
* @link https://github.com/ssm2017/phposm
* @license GNU/GPL, http://www.gnu.org/licenses/gpl-2.0.html
* Phposm is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*/
function createArchiveUrl($file_path)
{
logWrite('[archive] createArchiveUrl called');
// check if file exists
if (!is_file($file_path))
{
logWrite('[archive] file not found : '. $file_path);
return False;
}
// parse the path
$splitted = explode('/', $file_path);
if ($splitted[1] != 'home' || $splitted[3] != 'opensimulator' or ($splitted[4] != 'iar' && $splitted[4] != 'oar'))
{
logWrite('[archive] wrong file path : '. $file_path);
return False;
}
$username = $splitted[2];
$archive_type = $splitted[4];
$expiration = time() + 300;
$url = '/archive?q='. $archive_type. '/'. $username. '/'. md5($expiration. ':'. $GLOBALS['config']['password']). '/'. $expiration. '/'. $splitted[5];
return $url;
}
function parseArchiveUrl($url)
{
logWrite('[archive] parseArchiveUrl called');
$splitted = explode('/', $url);
if ($splitted[1] != 'archive' || ($splitted[2] != 'oar' && $splitted[2] != 'iar'))
{
logWrite('[archive] wrong url : '. $url);
return Null;
}
$filename = $splitted[6];
$username = $splitted[3];
// check expiration
$expiration = $splitted[5];
$now = time();
if ($now > $expiration)
{
logWrite('[archive] url expired : '. $url);
return Null;
}
// check password
if ($splitted[4] != md5($expiration. ':'. $GLOBALS['config']['password']))
{
logWrite('[archive] wrong password');
return Null;
}
// check if file exists
$file_path = '/home/'. $username. '/opensimulator/'. $splitted[2]. '/'. $filename;
if (!is_file($file_path))
{
logWrite('[archive] file not found');
return Null;
}
return $file_path;
}
| Java |
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
Sig="/home/dai/tmp/Assignment#3/Size/Signature/BatchProcessing.m"
Rect="/home/dai/tmp/Assignment#3/Size/Rectangle/BatchProcessing.sh"
Eva="/home/dai/tmp/Assignment#3/Size/Evaluation/BatchProcessing.m"
MatlabExe="/opt/Matlab2013/bin/matlab"
${MatlabExe} -nodesktop -nosplash -r "run ${Sig};quit"
sh ${Rect}
${MatlabExe} -nodesktop -nosplash -r "run ${Eva};quit"
| Java |
<?php
/**
* NoNumber Framework Helper File: Assignments: Tags
*
* @package NoNumber Framework
* @version 14.9.9
*
* @author Peter van Westen <peter@nonumber.nl>
* @link http://www.nonumber.nl
* @copyright Copyright © 2014 NoNumber All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
defined('_JEXEC') or die;
/**
* Assignments: Tags
*/
class NNFrameworkAssignmentsTags
{
function passTags(&$parent, &$params, $selection = array(), $assignment = 'all', $article = 0)
{
$is_content = in_array($parent->params->option, array('com_content', 'com_flexicontent'));
if (!$is_content)
{
return $parent->pass(0, $assignment);
}
$is_item = in_array($parent->params->view, array('', 'article', 'item'));
$is_category = in_array($parent->params->view, array('category'));
if ($is_item)
{
$prefix = 'com_content.article';
}
else if ($is_category)
{
$prefix = 'com_content.category';
}
else
{
return $parent->pass(0, $assignment);
}
// Load the tags.
$parent->q->clear()
->select($parent->db->quoteName('t.id'))
->from('#__tags AS t')
->join(
'INNER', '#__contentitem_tag_map AS m'
. ' ON m.tag_id = t.id'
. ' AND m.type_alias = ' . $parent->db->quote($prefix)
. ' AND m.content_item_id IN ( ' . $parent->params->id . ')'
);
$parent->db->setQuery($parent->q);
$tags = $parent->db->loadColumn();
if (empty($tags))
{
return $parent->pass(0, $assignment);
}
$pass = 0;
foreach ($tags as $tag)
{
$pass = in_array($tag, $selection);
if ($pass && $params->inc_children == 2)
{
$pass = 0;
}
else if (!$pass && $params->inc_children)
{
$parentids = self::getParentIds($parent, $tag);
$parentids = array_diff($parentids, array('1'));
foreach ($parentids as $id)
{
if (in_array($id, $selection))
{
$pass = 1;
break;
}
}
unset($parentids);
}
}
return $parent->pass($pass, $assignment);
}
function getParentIds(&$parent, $id = 0)
{
return $parent->getParentIds($id, 'tags');
}
}
| Java |
/* GStreamer
* Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
* 2005 Wim Taymans <wim@fluendo.com>
*
* gstaudiosink.c: simple audio sink base class
*
* 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.
*/
/**
* SECTION:gstaudiosink
* @short_description: Simple base class for audio sinks
* @see_also: #GstAudioBaseSink, #GstAudioRingBuffer, #GstAudioSink.
*
* This is the most simple base class for audio sinks that only requires
* subclasses to implement a set of simple functions:
*
* <variablelist>
* <varlistentry>
* <term>open()</term>
* <listitem><para>Open the device.</para></listitem>
* </varlistentry>
* <varlistentry>
* <term>prepare()</term>
* <listitem><para>Configure the device with the specified format.</para></listitem>
* </varlistentry>
* <varlistentry>
* <term>write()</term>
* <listitem><para>Write samples to the device.</para></listitem>
* </varlistentry>
* <varlistentry>
* <term>reset()</term>
* <listitem><para>Unblock writes and flush the device.</para></listitem>
* </varlistentry>
* <varlistentry>
* <term>delay()</term>
* <listitem><para>Get the number of samples written but not yet played
* by the device.</para></listitem>
* </varlistentry>
* <varlistentry>
* <term>unprepare()</term>
* <listitem><para>Undo operations done by prepare.</para></listitem>
* </varlistentry>
* <varlistentry>
* <term>close()</term>
* <listitem><para>Close the device.</para></listitem>
* </varlistentry>
* </variablelist>
*
* All scheduling of samples and timestamps is done in this base class
* together with #GstAudioBaseSink using a default implementation of a
* #GstAudioRingBuffer that uses threads.
*/
#include <string.h>
#include <gst/audio/audio.h>
#include "gstaudiosink.h"
GST_DEBUG_CATEGORY_STATIC (gst_audio_sink_debug);
#define GST_CAT_DEFAULT gst_audio_sink_debug
#define GST_TYPE_AUDIO_SINK_RING_BUFFER \
(gst_audio_sink_ring_buffer_get_type())
#define GST_AUDIO_SINK_RING_BUFFER(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_AUDIO_SINK_RING_BUFFER,GstAudioSinkRingBuffer))
#define GST_AUDIO_SINK_RING_BUFFER_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_AUDIO_SINK_RING_BUFFER,GstAudioSinkRingBufferClass))
#define GST_AUDIO_SINK_RING_BUFFER_GET_CLASS(obj) \
(G_TYPE_INSTANCE_GET_CLASS ((obj), GST_TYPE_AUDIO_SINK_RING_BUFFER, GstAudioSinkRingBufferClass))
#define GST_AUDIO_SINK_RING_BUFFER_CAST(obj) \
((GstAudioSinkRingBuffer *)obj)
#define GST_IS_AUDIO_SINK_RING_BUFFER(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_AUDIO_SINK_RING_BUFFER))
#define GST_IS_AUDIO_SINK_RING_BUFFER_CLASS(klass)\
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_AUDIO_SINK_RING_BUFFER))
typedef struct _GstAudioSinkRingBuffer GstAudioSinkRingBuffer;
typedef struct _GstAudioSinkRingBufferClass GstAudioSinkRingBufferClass;
#define GST_AUDIO_SINK_RING_BUFFER_GET_COND(buf) (&(((GstAudioSinkRingBuffer *)buf)->cond))
#define GST_AUDIO_SINK_RING_BUFFER_WAIT(buf) (g_cond_wait (GST_AUDIO_SINK_RING_BUFFER_GET_COND (buf), GST_OBJECT_GET_LOCK (buf)))
#define GST_AUDIO_SINK_RING_BUFFER_SIGNAL(buf) (g_cond_signal (GST_AUDIO_SINK_RING_BUFFER_GET_COND (buf)))
#define GST_AUDIO_SINK_RING_BUFFER_BROADCAST(buf)(g_cond_broadcast (GST_AUDIO_SINK_RING_BUFFER_GET_COND (buf)))
struct _GstAudioSinkRingBuffer
{
GstAudioRingBuffer object;
gboolean running;
gint queuedseg;
GCond cond;
};
struct _GstAudioSinkRingBufferClass
{
GstAudioRingBufferClass parent_class;
};
static void gst_audio_sink_ring_buffer_class_init (GstAudioSinkRingBufferClass *
klass);
static void gst_audio_sink_ring_buffer_init (GstAudioSinkRingBuffer *
ringbuffer, GstAudioSinkRingBufferClass * klass);
static void gst_audio_sink_ring_buffer_dispose (GObject * object);
static void gst_audio_sink_ring_buffer_finalize (GObject * object);
static GstAudioRingBufferClass *ring_parent_class = NULL;
static gboolean gst_audio_sink_ring_buffer_open_device (GstAudioRingBuffer *
buf);
static gboolean gst_audio_sink_ring_buffer_close_device (GstAudioRingBuffer *
buf);
static gboolean gst_audio_sink_ring_buffer_acquire (GstAudioRingBuffer * buf,
GstAudioRingBufferSpec * spec);
static gboolean gst_audio_sink_ring_buffer_release (GstAudioRingBuffer * buf);
static gboolean gst_audio_sink_ring_buffer_start (GstAudioRingBuffer * buf);
static gboolean gst_audio_sink_ring_buffer_pause (GstAudioRingBuffer * buf);
static gboolean gst_audio_sink_ring_buffer_stop (GstAudioRingBuffer * buf);
static guint gst_audio_sink_ring_buffer_delay (GstAudioRingBuffer * buf);
static gboolean gst_audio_sink_ring_buffer_activate (GstAudioRingBuffer * buf,
gboolean active);
/* ringbuffer abstract base class */
static GType
gst_audio_sink_ring_buffer_get_type (void)
{
static GType ringbuffer_type = 0;
if (!ringbuffer_type) {
static const GTypeInfo ringbuffer_info = {
sizeof (GstAudioSinkRingBufferClass),
NULL,
NULL,
(GClassInitFunc) gst_audio_sink_ring_buffer_class_init,
NULL,
NULL,
sizeof (GstAudioSinkRingBuffer),
0,
(GInstanceInitFunc) gst_audio_sink_ring_buffer_init,
NULL
};
ringbuffer_type =
g_type_register_static (GST_TYPE_AUDIO_RING_BUFFER,
"GstAudioSinkRingBuffer", &ringbuffer_info, 0);
}
return ringbuffer_type;
}
static void
gst_audio_sink_ring_buffer_class_init (GstAudioSinkRingBufferClass * klass)
{
GObjectClass *gobject_class;
GstAudioRingBufferClass *gstringbuffer_class;
gobject_class = (GObjectClass *) klass;
gstringbuffer_class = (GstAudioRingBufferClass *) klass;
ring_parent_class = g_type_class_peek_parent (klass);
gobject_class->dispose = gst_audio_sink_ring_buffer_dispose;
gobject_class->finalize = gst_audio_sink_ring_buffer_finalize;
gstringbuffer_class->open_device =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_open_device);
gstringbuffer_class->close_device =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_close_device);
gstringbuffer_class->acquire =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_acquire);
gstringbuffer_class->release =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_release);
gstringbuffer_class->start =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_start);
gstringbuffer_class->pause =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_pause);
gstringbuffer_class->resume =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_start);
gstringbuffer_class->stop =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_stop);
gstringbuffer_class->delay =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_delay);
gstringbuffer_class->activate =
GST_DEBUG_FUNCPTR (gst_audio_sink_ring_buffer_activate);
}
typedef gint (*WriteFunc) (GstAudioSink * sink, gpointer data, guint length);
/* this internal thread does nothing else but write samples to the audio device.
* It will write each segment in the ringbuffer and will update the play
* pointer.
* The start/stop methods control the thread.
*/
static void
audioringbuffer_thread_func (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
GstAudioSinkRingBuffer *abuf = GST_AUDIO_SINK_RING_BUFFER_CAST (buf);
WriteFunc writefunc;
GstMessage *message;
GValue val = { 0 };
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
GST_DEBUG_OBJECT (sink, "enter thread");
GST_OBJECT_LOCK (abuf);
GST_DEBUG_OBJECT (sink, "signal wait");
GST_AUDIO_SINK_RING_BUFFER_SIGNAL (buf);
GST_OBJECT_UNLOCK (abuf);
writefunc = csink->write;
if (writefunc == NULL)
goto no_function;
message = gst_message_new_stream_status (GST_OBJECT_CAST (buf),
GST_STREAM_STATUS_TYPE_ENTER, GST_ELEMENT_CAST (sink));
g_value_init (&val, GST_TYPE_G_THREAD);
g_value_set_boxed (&val, sink->thread);
gst_message_set_stream_status_object (message, &val);
g_value_unset (&val);
GST_DEBUG_OBJECT (sink, "posting ENTER stream status");
gst_element_post_message (GST_ELEMENT_CAST (sink), message);
while (TRUE) {
gint left, len;
guint8 *readptr;
gint readseg;
/* buffer must be started */
if (gst_audio_ring_buffer_prepare_read (buf, &readseg, &readptr, &len)) {
gint written;
left = len;
do {
written = writefunc (sink, readptr, left);
GST_LOG_OBJECT (sink, "transfered %d bytes of %d from segment %d",
written, left, readseg);
if (written < 0 || written > left) {
/* might not be critical, it e.g. happens when aborting playback */
GST_WARNING_OBJECT (sink,
"error writing data in %s (reason: %s), skipping segment (left: %d, written: %d)",
GST_DEBUG_FUNCPTR_NAME (writefunc),
(errno > 1 ? g_strerror (errno) : "unknown"), left, written);
break;
}
left -= written;
readptr += written;
} while (left > 0);
/* clear written samples */
gst_audio_ring_buffer_clear (buf, readseg);
/* we wrote one segment */
gst_audio_ring_buffer_advance (buf, 1);
} else {
GST_OBJECT_LOCK (abuf);
if (!abuf->running)
goto stop_running;
if (G_UNLIKELY (g_atomic_int_get (&buf->state) ==
GST_AUDIO_RING_BUFFER_STATE_STARTED)) {
GST_OBJECT_UNLOCK (abuf);
continue;
}
GST_DEBUG_OBJECT (sink, "signal wait");
GST_AUDIO_SINK_RING_BUFFER_SIGNAL (buf);
GST_DEBUG_OBJECT (sink, "wait for action");
GST_AUDIO_SINK_RING_BUFFER_WAIT (buf);
GST_DEBUG_OBJECT (sink, "got signal");
if (!abuf->running)
goto stop_running;
GST_DEBUG_OBJECT (sink, "continue running");
GST_OBJECT_UNLOCK (abuf);
}
}
/* Will never be reached */
g_assert_not_reached ();
return;
/* ERROR */
no_function:
{
GST_DEBUG_OBJECT (sink, "no write function, exit thread");
return;
}
stop_running:
{
GST_OBJECT_UNLOCK (abuf);
GST_DEBUG_OBJECT (sink, "stop running, exit thread");
message = gst_message_new_stream_status (GST_OBJECT_CAST (buf),
GST_STREAM_STATUS_TYPE_LEAVE, GST_ELEMENT_CAST (sink));
g_value_init (&val, GST_TYPE_G_THREAD);
g_value_set_boxed (&val, sink->thread);
gst_message_set_stream_status_object (message, &val);
g_value_unset (&val);
GST_DEBUG_OBJECT (sink, "posting LEAVE stream status");
gst_element_post_message (GST_ELEMENT_CAST (sink), message);
return;
}
}
static void
gst_audio_sink_ring_buffer_init (GstAudioSinkRingBuffer * ringbuffer,
GstAudioSinkRingBufferClass * g_class)
{
ringbuffer->running = FALSE;
ringbuffer->queuedseg = 0;
g_cond_init (&ringbuffer->cond);
}
static void
gst_audio_sink_ring_buffer_dispose (GObject * object)
{
G_OBJECT_CLASS (ring_parent_class)->dispose (object);
}
static void
gst_audio_sink_ring_buffer_finalize (GObject * object)
{
GstAudioSinkRingBuffer *ringbuffer = GST_AUDIO_SINK_RING_BUFFER_CAST (object);
g_cond_clear (&ringbuffer->cond);
G_OBJECT_CLASS (ring_parent_class)->finalize (object);
}
static gboolean
gst_audio_sink_ring_buffer_open_device (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
gboolean result = TRUE;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
if (csink->open)
result = csink->open (sink);
if (!result)
goto could_not_open;
return result;
could_not_open:
{
GST_DEBUG_OBJECT (sink, "could not open device");
return FALSE;
}
}
static gboolean
gst_audio_sink_ring_buffer_close_device (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
gboolean result = TRUE;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
if (csink->close)
result = csink->close (sink);
if (!result)
goto could_not_close;
return result;
could_not_close:
{
GST_DEBUG_OBJECT (sink, "could not close device");
return FALSE;
}
}
static gboolean
gst_audio_sink_ring_buffer_acquire (GstAudioRingBuffer * buf,
GstAudioRingBufferSpec * spec)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
gboolean result = FALSE;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
if (csink->prepare)
result = csink->prepare (sink, spec);
if (!result)
goto could_not_prepare;
/* set latency to one more segment as we need some headroom */
spec->seglatency = spec->segtotal + 1;
buf->size = spec->segtotal * spec->segsize;
buf->memory = g_malloc (buf->size);
if (buf->spec.type == GST_AUDIO_RING_BUFFER_FORMAT_TYPE_RAW) {
gst_audio_format_fill_silence (buf->spec.info.finfo, buf->memory,
buf->size);
} else {
/* FIXME, non-raw formats get 0 as the empty sample */
memset (buf->memory, 0, buf->size);
}
return TRUE;
/* ERRORS */
could_not_prepare:
{
GST_DEBUG_OBJECT (sink, "could not prepare device");
return FALSE;
}
}
static gboolean
gst_audio_sink_ring_buffer_activate (GstAudioRingBuffer * buf, gboolean active)
{
GstAudioSink *sink;
GstAudioSinkRingBuffer *abuf;
GError *error = NULL;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
abuf = GST_AUDIO_SINK_RING_BUFFER_CAST (buf);
if (active) {
abuf->running = TRUE;
GST_DEBUG_OBJECT (sink, "starting thread");
sink->thread = g_thread_try_new ("audiosink-ringbuffer",
(GThreadFunc) audioringbuffer_thread_func, buf, &error);
if (!sink->thread || error != NULL)
goto thread_failed;
GST_DEBUG_OBJECT (sink, "waiting for thread");
/* the object lock is taken */
GST_AUDIO_SINK_RING_BUFFER_WAIT (buf);
GST_DEBUG_OBJECT (sink, "thread is started");
} else {
abuf->running = FALSE;
GST_DEBUG_OBJECT (sink, "signal wait");
GST_AUDIO_SINK_RING_BUFFER_SIGNAL (buf);
GST_OBJECT_UNLOCK (buf);
/* join the thread */
g_thread_join (sink->thread);
GST_OBJECT_LOCK (buf);
}
return TRUE;
/* ERRORS */
thread_failed:
{
if (error)
GST_ERROR_OBJECT (sink, "could not create thread %s", error->message);
else
GST_ERROR_OBJECT (sink, "could not create thread for unknown reason");
g_clear_error (&error);
return FALSE;
}
}
/* function is called with LOCK */
static gboolean
gst_audio_sink_ring_buffer_release (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
gboolean result = FALSE;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
/* free the buffer */
g_free (buf->memory);
buf->memory = NULL;
if (csink->unprepare)
result = csink->unprepare (sink);
if (!result)
goto could_not_unprepare;
GST_DEBUG_OBJECT (sink, "unprepared");
return result;
could_not_unprepare:
{
GST_DEBUG_OBJECT (sink, "could not unprepare device");
return FALSE;
}
}
static gboolean
gst_audio_sink_ring_buffer_start (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
GST_DEBUG_OBJECT (sink, "start, sending signal");
GST_AUDIO_SINK_RING_BUFFER_SIGNAL (buf);
return TRUE;
}
static gboolean
gst_audio_sink_ring_buffer_pause (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
/* unblock any pending writes to the audio device */
if (csink->reset) {
GST_DEBUG_OBJECT (sink, "reset...");
csink->reset (sink);
GST_DEBUG_OBJECT (sink, "reset done");
}
return TRUE;
}
static gboolean
gst_audio_sink_ring_buffer_stop (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
/* unblock any pending writes to the audio device */
if (csink->reset) {
GST_DEBUG_OBJECT (sink, "reset...");
csink->reset (sink);
GST_DEBUG_OBJECT (sink, "reset done");
}
#if 0
if (abuf->running) {
GST_DEBUG_OBJECT (sink, "stop, waiting...");
GST_AUDIO_SINK_RING_BUFFER_WAIT (buf);
GST_DEBUG_OBJECT (sink, "stopped");
}
#endif
return TRUE;
}
static guint
gst_audio_sink_ring_buffer_delay (GstAudioRingBuffer * buf)
{
GstAudioSink *sink;
GstAudioSinkClass *csink;
guint res = 0;
sink = GST_AUDIO_SINK (GST_OBJECT_PARENT (buf));
csink = GST_AUDIO_SINK_GET_CLASS (sink);
if (csink->delay)
res = csink->delay (sink);
return res;
}
/* AudioSink signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
ARG_0,
};
#define _do_init \
GST_DEBUG_CATEGORY_INIT (gst_audio_sink_debug, "audiosink", 0, "audiosink element");
#define gst_audio_sink_parent_class parent_class
G_DEFINE_TYPE_WITH_CODE (GstAudioSink, gst_audio_sink,
GST_TYPE_AUDIO_BASE_SINK, _do_init);
static GstAudioRingBuffer *gst_audio_sink_create_ringbuffer (GstAudioBaseSink *
sink);
static void
gst_audio_sink_class_init (GstAudioSinkClass * klass)
{
GstAudioBaseSinkClass *gstaudiobasesink_class;
gstaudiobasesink_class = (GstAudioBaseSinkClass *) klass;
gstaudiobasesink_class->create_ringbuffer =
GST_DEBUG_FUNCPTR (gst_audio_sink_create_ringbuffer);
g_type_class_ref (GST_TYPE_AUDIO_SINK_RING_BUFFER);
}
static void
gst_audio_sink_init (GstAudioSink * audiosink)
{
}
static GstAudioRingBuffer *
gst_audio_sink_create_ringbuffer (GstAudioBaseSink * sink)
{
GstAudioRingBuffer *buffer;
GST_DEBUG_OBJECT (sink, "creating ringbuffer");
buffer = g_object_new (GST_TYPE_AUDIO_SINK_RING_BUFFER, NULL);
GST_DEBUG_OBJECT (sink, "created ringbuffer @%p", buffer);
return buffer;
}
| Java |
/**
@file TextOutput.cpp
@maintainer Morgan McGuire, http://graphics.cs.williams.edu
@created 2004-06-21
@edited 2010-03-14
Copyright 2000-2010, Morgan McGuire.
All rights reserved.
*/
#include "G3D/TextOutput.h"
#include "G3D/Log.h"
#include "G3D/fileutils.h"
#include "G3D/FileSystem.h"
namespace G3D {
TextOutput::TextOutput(const TextOutput::Settings& opt) :
startingNewLine(true),
currentColumn(0),
inDQuote(false),
filename(""),
indentLevel(0)
{
setOptions(opt);
}
TextOutput::TextOutput(const std::string& fil, const TextOutput::Settings& opt) :
startingNewLine(true),
currentColumn(0),
inDQuote(false),
filename(fil),
indentLevel(0)
{
setOptions(opt);
}
void TextOutput::setIndentLevel(int i) {
indentLevel = i;
// If there were more pops than pushes, don't let that take us below 0 indent.
// Don't ever indent more than the number of columns.
indentSpaces =
iClamp(option.spacesPerIndent * indentLevel,
0,
option.numColumns - 1);
}
void TextOutput::setOptions(const Settings& _opt) {
option = _opt;
debugAssert(option.numColumns > 1);
setIndentLevel(indentLevel);
newline = (option.newlineStyle == Settings::NEWLINE_WINDOWS) ? "\r\n" : "\n";
}
void TextOutput::pushIndent() {
setIndentLevel(indentLevel + 1);
}
void TextOutput::popIndent() {
setIndentLevel(indentLevel - 1);
}
static std::string escape(const std::string& string) {
std::string result = "";
for (std::string::size_type i = 0; i < string.length(); ++i) {
char c = string.at(i);
switch (c) {
case '\0':
result += "\\0";
break;
case '\r':
result += "\\r";
break;
case '\n':
result += "\\n";
break;
case '\t':
result += "\\t";
break;
case '\\':
result += "\\\\";
break;
default:
result += c;
}
}
return result;
}
void TextOutput::writeString(const std::string& string) {
// Convert special characters to escape sequences
this->printf("\"%s\"", escape(string).c_str());
}
void TextOutput::writeBoolean(bool b) {
this->printf("%s ", b ? option.trueSymbol.c_str() : option.falseSymbol.c_str());
}
void TextOutput::writeNumber(double n) {
this->printf("%f ", n);
}
void TextOutput::writeNumber(int n) {
this->printf("%d ", n);
}
void TextOutput::writeSymbol(const std::string& string) {
if (string.size() > 0) {
// TODO: check for legal symbols?
this->printf("%s ", string.c_str());
}
}
void TextOutput::writeSymbols(
const std::string& a,
const std::string& b,
const std::string& c,
const std::string& d,
const std::string& e,
const std::string& f) {
writeSymbol(a);
writeSymbol(b);
writeSymbol(c);
writeSymbol(d);
writeSymbol(e);
writeSymbol(f);
}
void TextOutput::printf(const std::string formatString, ...) {
va_list argList;
va_start(argList, formatString);
this->vprintf(formatString.c_str(), argList);
va_end(argList);
}
void TextOutput::printf(const char* formatString, ...) {
va_list argList;
va_start(argList, formatString);
this->vprintf(formatString, argList);
va_end(argList);
}
void TextOutput::convertNewlines(const std::string& in, std::string& out) {
// TODO: can be significantly optimized in cases where
// single characters are copied in order by walking through
// the array and copying substrings as needed.
if (option.convertNewlines) {
out = "";
for (uint32 i = 0; i < in.size(); ++i) {
if (in[i] == '\n') {
// Unix newline
out += newline;
} else if ((in[i] == '\r') && (i + 1 < in.size()) && (in[i + 1] == '\n')) {
// Windows newline
out += newline;
++i;
} else {
out += in[i];
}
}
} else {
out = in;
}
}
void TextOutput::writeNewline() {
for (uint32 i = 0; i < newline.size(); ++i) {
indentAppend(newline[i]);
}
}
void TextOutput::writeNewlines(int numLines) {
for (int i = 0; i < numLines; ++i) {
writeNewline();
}
}
void TextOutput::wordWrapIndentAppend(const std::string& str) {
// TODO: keep track of the last space character we saw so we don't
// have to always search.
if ((option.wordWrap == Settings::WRAP_NONE) ||
(currentColumn + (int)str.size() <= option.numColumns)) {
// No word-wrapping is needed
// Add one character at a time.
// TODO: optimize for strings without newlines to add multiple
// characters.
for (uint32 i = 0; i < str.size(); ++i) {
indentAppend(str[i]);
}
return;
}
// Number of columns to wrap against
int cols = option.numColumns - indentSpaces;
// Copy forward until we exceed the column size,
// and then back up and try to insert newlines as needed.
for (uint32 i = 0; i < str.size(); ++i) {
indentAppend(str[i]);
if ((str[i] == '\r') && (i + 1 < str.size()) && (str[i + 1] == '\n')) {
// \r\n, we need to hit the \n to enter word wrapping.
++i;
indentAppend(str[i]);
}
if (currentColumn >= cols) {
debugAssertM(str[i] != '\n' && str[i] != '\r',
"Should never enter word-wrapping on a newline character");
// True when we're allowed to treat a space as a space.
bool unquotedSpace = option.allowWordWrapInsideDoubleQuotes || ! inDQuote;
// Cases:
//
// 1. Currently in a series of spaces that ends with a newline
// strip all spaces and let the newline
// flow through.
//
// 2. Currently in a series of spaces that does not end with a newline
// strip all spaces and replace them with single newline
//
// 3. Not in a series of spaces
// search backwards for a space, then execute case 2.
// Index of most recent space
uint32 lastSpace = data.size() - 1;
// How far back we had to look for a space
uint32 k = 0;
uint32 maxLookBackward = currentColumn - indentSpaces;
// Search backwards (from current character), looking for a space.
while ((k < maxLookBackward) &&
(lastSpace > 0) &&
(! ((data[lastSpace] == ' ') && unquotedSpace))) {
--lastSpace;
++k;
if ((data[lastSpace] == '\"') && !option.allowWordWrapInsideDoubleQuotes) {
unquotedSpace = ! unquotedSpace;
}
}
if (k == maxLookBackward) {
// We couldn't find a series of spaces
if (option.wordWrap == Settings::WRAP_ALWAYS) {
// Strip the last character we wrote, force a newline,
// and replace the last character;
data.pop();
writeNewline();
indentAppend(str[i]);
} else {
// Must be Settings::WRAP_WITHOUT_BREAKING
//
// Don't write the newline; we'll come back to
// the word wrap code after writing another character
}
} else {
// We found a series of spaces. If they continue
// to the new string, strip spaces off both. Otherwise
// strip spaces from data only and insert a newline.
// Find the start of the spaces. firstSpace is the index of the
// first non-space, looking backwards from lastSpace.
uint32 firstSpace = lastSpace;
while ((k < maxLookBackward) &&
(firstSpace > 0) &&
(data[firstSpace] == ' ')) {
--firstSpace;
++k;
}
if (k == maxLookBackward) {
++firstSpace;
}
if (lastSpace == (uint32)data.size() - 1) {
// Spaces continued up to the new string
data.resize(firstSpace + 1);
writeNewline();
// Delete the spaces from the new string
while ((i < str.size() - 1) && (str[i + 1] == ' ')) {
++i;
}
} else {
// Spaces were somewhere in the middle of the old string.
// replace them with a newline.
// Copy over the characters that should be saved
Array<char> temp;
for (uint32 j = lastSpace + 1; j < (uint32)data.size(); ++j) {
char c = data[j];
if (c == '\"') {
// Undo changes to quoting (they will be re-done
// when we paste these characters back on).
inDQuote = !inDQuote;
}
temp.append(c);
}
// Remove those characters and replace with a newline.
data.resize(firstSpace + 1);
writeNewline();
// Write them back
for (uint32 j = 0; j < (uint32)temp.size(); ++j) {
indentAppend(temp[j]);
}
// We are now free to continue adding from the
// new string, which may or may not begin with spaces.
} // if spaces included new string
} // if hit indent
} // if line exceeded
} // iterate over str
}
void TextOutput::indentAppend(char c) {
if (startingNewLine) {
for (int j = 0; j < indentSpaces; ++j) {
data.push(' ');
}
startingNewLine = false;
currentColumn = indentSpaces;
}
data.push(c);
// Don't increment the column count on return character
// newline is taken care of below.
if (c != '\r') {
++currentColumn;
}
if (c == '\"') {
inDQuote = ! inDQuote;
}
startingNewLine = (c == '\n');
if (startingNewLine) {
currentColumn = 0;
}
}
void TextOutput::vprintf(const char* formatString, va_list argPtr) {
std::string str = vformat(formatString, argPtr);
std::string clean;
convertNewlines(str, clean);
wordWrapIndentAppend(clean);
}
void TextOutput::commit(bool flush) {
std::string p = filenamePath(filename);
if (! FileSystem::exists(p, false)) {
FileSystem::createDirectory(p);
}
FILE* f = FileSystem::fopen(filename.c_str(), "wb");
debugAssertM(f, "Could not open \"" + filename + "\"");
fwrite(data.getCArray(), 1, data.size(), f);
if (flush) {
fflush(f);
}
FileSystem::fclose(f);
}
void TextOutput::commitString(std::string& out) {
// Null terminate
data.push('\0');
out = data.getCArray();
data.pop();
}
std::string TextOutput::commitString() {
std::string str;
commitString(str);
return str;
}
/////////////////////////////////////////////////////////////////////
void serialize(const float& b, TextOutput& to) {
to.writeNumber(b);
}
void serialize(const bool& b, TextOutput& to) {
to.writeSymbol(b ? "true" : "false");
}
void serialize(const int& b, TextOutput& to) {
to.writeNumber(b);
}
void serialize(const uint8& b, TextOutput& to) {
to.writeNumber(b);
}
void serialize(const double& b, TextOutput& to) {
to.writeNumber(b);
}
}
| Java |
/*
* kernel/workqueue.c - generic async execution with shared worker pool
*
* Copyright (C) 2002 Ingo Molnar
*
* Derived from the taskqueue/keventd code by:
* David Woodhouse <dwmw2@infradead.org>
* Andrew Morton
* Kai Petzke <wpp@marie.physik.tu-berlin.de>
* Theodore Ts'o <tytso@mit.edu>
*
* Made to use alloc_percpu by Christoph Lameter.
*
* Copyright (C) 2010 SUSE Linux Products GmbH
* Copyright (C) 2010 Tejun Heo <tj@kernel.org>
*
* This is the generic async execution mechanism. Work items as are
* executed in process context. The worker pool is shared and
* automatically managed. There is one worker pool for each CPU and
* one extra for works which are better served by workers which are
* not bound to any specific CPU.
*
* Please read Documentation/workqueue.txt for details.
*/
#include <linux/export.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/signal.h>
#include <linux/completion.h>
#include <linux/workqueue.h>
#include <linux/slab.h>
#include <linux/cpu.h>
#include <linux/notifier.h>
#include <linux/kthread.h>
#include <linux/hardirq.h>
#include <linux/mempolicy.h>
#include <linux/freezer.h>
#include <linux/kallsyms.h>
#include <linux/debug_locks.h>
#include <linux/lockdep.h>
#include <linux/idr.h>
#include <linux/bug.h>
#include <linux/module.h>
#include "workqueue_sched.h"
enum {
/* global_cwq flags */
GCWQ_DISASSOCIATED = 1 << 0, /* cpu can't serve workers */
GCWQ_FREEZING = 1 << 1, /* freeze in progress */
/* pool flags */
POOL_MANAGE_WORKERS = 1 << 0, /* need to manage workers */
POOL_MANAGING_WORKERS = 1 << 1, /* managing workers */
/* worker flags */
WORKER_STARTED = 1 << 0, /* started */
WORKER_DIE = 1 << 1, /* die die die */
WORKER_IDLE = 1 << 2, /* is idle */
WORKER_PREP = 1 << 3, /* preparing to run works */
WORKER_ROGUE = 1 << 4, /* not bound to any cpu */
WORKER_REBIND = 1 << 5, /* mom is home, come back */
WORKER_CPU_INTENSIVE = 1 << 6, /* cpu intensive */
WORKER_UNBOUND = 1 << 7, /* worker is unbound */
WORKER_NOT_RUNNING = WORKER_PREP | WORKER_ROGUE | WORKER_REBIND |
WORKER_CPU_INTENSIVE | WORKER_UNBOUND,
/* gcwq->trustee_state */
TRUSTEE_START = 0, /* start */
TRUSTEE_IN_CHARGE = 1, /* trustee in charge of gcwq */
TRUSTEE_BUTCHER = 2, /* butcher workers */
TRUSTEE_RELEASE = 3, /* release workers */
TRUSTEE_DONE = 4, /* trustee is done */
NR_WORKER_POOLS = 2, /* # worker pools per gcwq */
BUSY_WORKER_HASH_ORDER = 6, /* 64 pointers */
BUSY_WORKER_HASH_SIZE = 1 << BUSY_WORKER_HASH_ORDER,
BUSY_WORKER_HASH_MASK = BUSY_WORKER_HASH_SIZE - 1,
MAX_IDLE_WORKERS_RATIO = 4, /* 1/4 of busy can be idle */
IDLE_WORKER_TIMEOUT = 300 * HZ, /* keep idle ones for 5 mins */
MAYDAY_INITIAL_TIMEOUT = HZ / 100 >= 2 ? HZ / 100 : 2,
/* call for help after 10ms
(min two ticks) */
MAYDAY_INTERVAL = HZ / 10, /* and then every 100ms */
CREATE_COOLDOWN = HZ, /* time to breath after fail */
TRUSTEE_COOLDOWN = HZ / 10, /* for trustee draining */
/*
* Rescue workers are used only on emergencies and shared by
* all cpus. Give -20.
*/
RESCUER_NICE_LEVEL = -20,
HIGHPRI_NICE_LEVEL = -20,
};
/*
* Structure fields follow one of the following exclusion rules.
*
* I: Modifiable by initialization/destruction paths and read-only for
* everyone else.
*
* P: Preemption protected. Disabling preemption is enough and should
* only be modified and accessed from the local cpu.
*
* L: gcwq->lock protected. Access with gcwq->lock held.
*
* X: During normal operation, modification requires gcwq->lock and
* should be done only from local cpu. Either disabling preemption
* on local cpu or grabbing gcwq->lock is enough for read access.
* If GCWQ_DISASSOCIATED is set, it's identical to L.
*
* F: wq->flush_mutex protected.
*
* W: workqueue_lock protected.
*/
struct global_cwq;
struct worker_pool;
/*
* The poor guys doing the actual heavy lifting. All on-duty workers
* are either serving the manager role, on idle list or on busy hash.
*/
struct worker {
/* on idle list while idle, on busy hash table while busy */
union {
struct list_head entry; /* L: while idle */
struct hlist_node hentry; /* L: while busy */
};
struct work_struct *current_work; /* L: work being processed */
struct cpu_workqueue_struct *current_cwq; /* L: current_work's cwq */
struct list_head scheduled; /* L: scheduled works */
struct task_struct *task; /* I: worker task */
struct worker_pool *pool; /* I: the associated pool */
/* 64 bytes boundary on 64bit, 32 on 32bit */
unsigned long last_active; /* L: last active timestamp */
unsigned int flags; /* X: flags */
int id; /* I: worker id */
struct work_struct rebind_work; /* L: rebind worker to cpu */
};
struct worker_pool {
struct global_cwq *gcwq; /* I: the owning gcwq */
unsigned int flags; /* X: flags */
struct list_head worklist; /* L: list of pending works */
int nr_workers; /* L: total number of workers */
int nr_idle; /* L: currently idle ones */
struct list_head idle_list; /* X: list of idle workers */
struct timer_list idle_timer; /* L: worker idle timeout */
struct timer_list mayday_timer; /* L: SOS timer for workers */
struct ida worker_ida; /* L: for worker IDs */
struct worker *first_idle; /* L: first idle worker */
};
/*
* Global per-cpu workqueue. There's one and only one for each cpu
* and all works are queued and processed here regardless of their
* target workqueues.
*/
struct global_cwq {
spinlock_t lock; /* the gcwq lock */
unsigned int cpu; /* I: the associated cpu */
unsigned int flags; /* L: GCWQ_* flags */
/* workers are chained either in busy_hash or pool idle_list */
struct hlist_head busy_hash[BUSY_WORKER_HASH_SIZE];
/* L: hash of busy workers */
struct worker_pool pools[2]; /* normal and highpri pools */
struct task_struct *trustee; /* L: for gcwq shutdown */
unsigned int trustee_state; /* L: trustee state */
wait_queue_head_t trustee_wait; /* trustee wait */
} ____cacheline_aligned_in_smp;
/*
* The per-CPU workqueue. The lower WORK_STRUCT_FLAG_BITS of
* work_struct->data are used for flags and thus cwqs need to be
* aligned at two's power of the number of flag bits.
*/
struct cpu_workqueue_struct {
struct worker_pool *pool; /* I: the associated pool */
struct workqueue_struct *wq; /* I: the owning workqueue */
int work_color; /* L: current color */
int flush_color; /* L: flushing color */
int nr_in_flight[WORK_NR_COLORS];
/* L: nr of in_flight works */
int nr_active; /* L: nr of active works */
int max_active; /* L: max active works */
struct list_head delayed_works; /* L: delayed works */
};
/*
* Structure used to wait for workqueue flush.
*/
struct wq_flusher {
struct list_head list; /* F: list of flushers */
int flush_color; /* F: flush color waiting for */
struct completion done; /* flush completion */
};
/*
* All cpumasks are assumed to be always set on UP and thus can't be
* used to determine whether there's something to be done.
*/
#ifdef CONFIG_SMP
typedef cpumask_var_t mayday_mask_t;
#define mayday_test_and_set_cpu(cpu, mask) \
cpumask_test_and_set_cpu((cpu), (mask))
#define mayday_clear_cpu(cpu, mask) cpumask_clear_cpu((cpu), (mask))
#define for_each_mayday_cpu(cpu, mask) for_each_cpu((cpu), (mask))
#define alloc_mayday_mask(maskp, gfp) zalloc_cpumask_var((maskp), (gfp))
#define free_mayday_mask(mask) free_cpumask_var((mask))
#else
typedef unsigned long mayday_mask_t;
#define mayday_test_and_set_cpu(cpu, mask) test_and_set_bit(0, &(mask))
#define mayday_clear_cpu(cpu, mask) clear_bit(0, &(mask))
#define for_each_mayday_cpu(cpu, mask) if ((cpu) = 0, (mask))
#define alloc_mayday_mask(maskp, gfp) true
#define free_mayday_mask(mask) do { } while (0)
#endif
/*
* The externally visible workqueue abstraction is an array of
* per-CPU workqueues:
*/
struct workqueue_struct {
unsigned int flags; /* W: WQ_* flags */
union {
struct cpu_workqueue_struct __percpu *pcpu;
struct cpu_workqueue_struct *single;
unsigned long v;
} cpu_wq; /* I: cwq's */
struct list_head list; /* W: list of all workqueues */
struct mutex flush_mutex; /* protects wq flushing */
int work_color; /* F: current work color */
int flush_color; /* F: current flush color */
atomic_t nr_cwqs_to_flush; /* flush in progress */
struct wq_flusher *first_flusher; /* F: first flusher */
struct list_head flusher_queue; /* F: flush waiters */
struct list_head flusher_overflow; /* F: flush overflow list */
mayday_mask_t mayday_mask; /* cpus requesting rescue */
struct worker *rescuer; /* I: rescue worker */
int nr_drainers; /* W: drain in progress */
int saved_max_active; /* W: saved cwq max_active */
#ifdef CONFIG_LOCKDEP
struct lockdep_map lockdep_map;
#endif
char name[]; /* I: workqueue name */
};
/* see the comment above the definition of WQ_POWER_EFFICIENT */
#ifdef CONFIG_WQ_POWER_EFFICIENT_DEFAULT
static bool wq_power_efficient = true;
#else
static bool wq_power_efficient;
#endif
module_param_named(power_efficient, wq_power_efficient, bool, 0444);
struct workqueue_struct *system_wq __read_mostly;
struct workqueue_struct *system_long_wq __read_mostly;
struct workqueue_struct *system_nrt_wq __read_mostly;
struct workqueue_struct *system_unbound_wq __read_mostly;
struct workqueue_struct *system_freezable_wq __read_mostly;
struct workqueue_struct *system_nrt_freezable_wq __read_mostly;
struct workqueue_struct *system_power_efficient_wq __read_mostly;
struct workqueue_struct *system_freezable_power_efficient_wq __read_mostly;
EXPORT_SYMBOL_GPL(system_wq);
EXPORT_SYMBOL_GPL(system_long_wq);
EXPORT_SYMBOL_GPL(system_nrt_wq);
EXPORT_SYMBOL_GPL(system_unbound_wq);
EXPORT_SYMBOL_GPL(system_freezable_wq);
EXPORT_SYMBOL_GPL(system_nrt_freezable_wq);
EXPORT_SYMBOL_GPL(system_power_efficient_wq);
EXPORT_SYMBOL_GPL(system_freezable_power_efficient_wq);
#define CREATE_TRACE_POINTS
#include <trace/events/workqueue.h>
#define for_each_worker_pool(pool, gcwq) \
for ((pool) = &(gcwq)->pools[0]; \
(pool) < &(gcwq)->pools[NR_WORKER_POOLS]; (pool)++)
#define for_each_busy_worker(worker, i, pos, gcwq) \
for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++) \
hlist_for_each_entry(worker, pos, &gcwq->busy_hash[i], hentry)
static inline int __next_gcwq_cpu(int cpu, const struct cpumask *mask,
unsigned int sw)
{
if (cpu < nr_cpu_ids) {
if (sw & 1) {
cpu = cpumask_next(cpu, mask);
if (cpu < nr_cpu_ids)
return cpu;
}
if (sw & 2)
return WORK_CPU_UNBOUND;
}
return WORK_CPU_NONE;
}
static inline int __next_wq_cpu(int cpu, const struct cpumask *mask,
struct workqueue_struct *wq)
{
return __next_gcwq_cpu(cpu, mask, !(wq->flags & WQ_UNBOUND) ? 1 : 2);
}
/*
* CPU iterators
*
* An extra gcwq is defined for an invalid cpu number
* (WORK_CPU_UNBOUND) to host workqueues which are not bound to any
* specific CPU. The following iterators are similar to
* for_each_*_cpu() iterators but also considers the unbound gcwq.
*
* for_each_gcwq_cpu() : possible CPUs + WORK_CPU_UNBOUND
* for_each_online_gcwq_cpu() : online CPUs + WORK_CPU_UNBOUND
* for_each_cwq_cpu() : possible CPUs for bound workqueues,
* WORK_CPU_UNBOUND for unbound workqueues
*/
#define for_each_gcwq_cpu(cpu) \
for ((cpu) = __next_gcwq_cpu(-1, cpu_possible_mask, 3); \
(cpu) < WORK_CPU_NONE; \
(cpu) = __next_gcwq_cpu((cpu), cpu_possible_mask, 3))
#define for_each_online_gcwq_cpu(cpu) \
for ((cpu) = __next_gcwq_cpu(-1, cpu_online_mask, 3); \
(cpu) < WORK_CPU_NONE; \
(cpu) = __next_gcwq_cpu((cpu), cpu_online_mask, 3))
#define for_each_cwq_cpu(cpu, wq) \
for ((cpu) = __next_wq_cpu(-1, cpu_possible_mask, (wq)); \
(cpu) < WORK_CPU_NONE; \
(cpu) = __next_wq_cpu((cpu), cpu_possible_mask, (wq)))
#ifdef CONFIG_DEBUG_OBJECTS_WORK
static struct debug_obj_descr work_debug_descr;
static void *work_debug_hint(void *addr)
{
return ((struct work_struct *) addr)->func;
}
/*
* fixup_init is called when:
* - an active object is initialized
*/
static int work_fixup_init(void *addr, enum debug_obj_state state)
{
struct work_struct *work = addr;
switch (state) {
case ODEBUG_STATE_ACTIVE:
cancel_work_sync(work);
debug_object_init(work, &work_debug_descr);
return 1;
default:
return 0;
}
}
/*
* fixup_activate is called when:
* - an active object is activated
* - an unknown object is activated (might be a statically initialized object)
*/
static int work_fixup_activate(void *addr, enum debug_obj_state state)
{
struct work_struct *work = addr;
switch (state) {
case ODEBUG_STATE_NOTAVAILABLE:
/*
* This is not really a fixup. The work struct was
* statically initialized. We just make sure that it
* is tracked in the object tracker.
*/
if (test_bit(WORK_STRUCT_STATIC_BIT, work_data_bits(work))) {
debug_object_init(work, &work_debug_descr);
debug_object_activate(work, &work_debug_descr);
return 0;
}
WARN_ON_ONCE(1);
return 0;
case ODEBUG_STATE_ACTIVE:
WARN_ON(1);
default:
return 0;
}
}
/*
* fixup_free is called when:
* - an active object is freed
*/
static int work_fixup_free(void *addr, enum debug_obj_state state)
{
struct work_struct *work = addr;
switch (state) {
case ODEBUG_STATE_ACTIVE:
cancel_work_sync(work);
debug_object_free(work, &work_debug_descr);
return 1;
default:
return 0;
}
}
static struct debug_obj_descr work_debug_descr = {
.name = "work_struct",
.debug_hint = work_debug_hint,
.fixup_init = work_fixup_init,
.fixup_activate = work_fixup_activate,
.fixup_free = work_fixup_free,
};
static inline void debug_work_activate(struct work_struct *work)
{
debug_object_activate(work, &work_debug_descr);
}
static inline void debug_work_deactivate(struct work_struct *work)
{
debug_object_deactivate(work, &work_debug_descr);
}
void __init_work(struct work_struct *work, int onstack)
{
if (onstack)
debug_object_init_on_stack(work, &work_debug_descr);
else
debug_object_init(work, &work_debug_descr);
}
EXPORT_SYMBOL_GPL(__init_work);
void destroy_work_on_stack(struct work_struct *work)
{
debug_object_free(work, &work_debug_descr);
}
EXPORT_SYMBOL_GPL(destroy_work_on_stack);
#else
static inline void debug_work_activate(struct work_struct *work) { }
static inline void debug_work_deactivate(struct work_struct *work) { }
#endif
/* Serializes the accesses to the list of workqueues. */
static DEFINE_SPINLOCK(workqueue_lock);
static LIST_HEAD(workqueues);
static bool workqueue_freezing; /* W: have wqs started freezing? */
/*
* The almighty global cpu workqueues. nr_running is the only field
* which is expected to be used frequently by other cpus via
* try_to_wake_up(). Put it in a separate cacheline.
*/
static DEFINE_PER_CPU(struct global_cwq, global_cwq);
static DEFINE_PER_CPU_SHARED_ALIGNED(atomic_t, pool_nr_running[NR_WORKER_POOLS]);
/*
* Global cpu workqueue and nr_running counter for unbound gcwq. The
* gcwq is always online, has GCWQ_DISASSOCIATED set, and all its
* workers have WORKER_UNBOUND set.
*/
static struct global_cwq unbound_global_cwq;
static atomic_t unbound_pool_nr_running[NR_WORKER_POOLS] = {
[0 ... NR_WORKER_POOLS - 1] = ATOMIC_INIT(0), /* always 0 */
};
static int worker_thread(void *__worker);
static int worker_pool_pri(struct worker_pool *pool)
{
return pool - pool->gcwq->pools;
}
static struct global_cwq *get_gcwq(unsigned int cpu)
{
if (cpu != WORK_CPU_UNBOUND)
return &per_cpu(global_cwq, cpu);
else
return &unbound_global_cwq;
}
static atomic_t *get_pool_nr_running(struct worker_pool *pool)
{
int cpu = pool->gcwq->cpu;
int idx = worker_pool_pri(pool);
if (cpu != WORK_CPU_UNBOUND)
return &per_cpu(pool_nr_running, cpu)[idx];
else
return &unbound_pool_nr_running[idx];
}
static struct cpu_workqueue_struct *get_cwq(unsigned int cpu,
struct workqueue_struct *wq)
{
if (!(wq->flags & WQ_UNBOUND)) {
if (likely(cpu < nr_cpu_ids))
return per_cpu_ptr(wq->cpu_wq.pcpu, cpu);
} else if (likely(cpu == WORK_CPU_UNBOUND))
return wq->cpu_wq.single;
return NULL;
}
static unsigned int work_color_to_flags(int color)
{
return color << WORK_STRUCT_COLOR_SHIFT;
}
static int get_work_color(struct work_struct *work)
{
return (*work_data_bits(work) >> WORK_STRUCT_COLOR_SHIFT) &
((1 << WORK_STRUCT_COLOR_BITS) - 1);
}
static int work_next_color(int color)
{
return (color + 1) % WORK_NR_COLORS;
}
/*
* A work's data points to the cwq with WORK_STRUCT_CWQ set while the
* work is on queue. Once execution starts, WORK_STRUCT_CWQ is
* cleared and the work data contains the cpu number it was last on.
*
* set_work_{cwq|cpu}() and clear_work_data() can be used to set the
* cwq, cpu or clear work->data. These functions should only be
* called while the work is owned - ie. while the PENDING bit is set.
*
* get_work_[g]cwq() can be used to obtain the gcwq or cwq
* corresponding to a work. gcwq is available once the work has been
* queued anywhere after initialization. cwq is available only from
* queueing until execution starts.
*/
static inline void set_work_data(struct work_struct *work, unsigned long data,
unsigned long flags)
{
BUG_ON(!work_pending(work));
atomic_long_set(&work->data, data | flags | work_static(work));
}
static void set_work_cwq(struct work_struct *work,
struct cpu_workqueue_struct *cwq,
unsigned long extra_flags)
{
set_work_data(work, (unsigned long)cwq,
WORK_STRUCT_PENDING | WORK_STRUCT_CWQ | extra_flags);
}
static void set_work_cpu(struct work_struct *work, unsigned int cpu)
{
set_work_data(work, cpu << WORK_STRUCT_FLAG_BITS, WORK_STRUCT_PENDING);
}
static void clear_work_data(struct work_struct *work)
{
set_work_data(work, WORK_STRUCT_NO_CPU, 0);
}
static struct cpu_workqueue_struct *get_work_cwq(struct work_struct *work)
{
unsigned long data = atomic_long_read(&work->data);
if (data & WORK_STRUCT_CWQ)
return (void *)(data & WORK_STRUCT_WQ_DATA_MASK);
else
return NULL;
}
static struct global_cwq *get_work_gcwq(struct work_struct *work)
{
unsigned long data = atomic_long_read(&work->data);
unsigned int cpu;
if (data & WORK_STRUCT_CWQ)
return ((struct cpu_workqueue_struct *)
(data & WORK_STRUCT_WQ_DATA_MASK))->pool->gcwq;
cpu = data >> WORK_STRUCT_FLAG_BITS;
if (cpu == WORK_CPU_NONE)
return NULL;
BUG_ON(cpu >= nr_cpu_ids && cpu != WORK_CPU_UNBOUND);
return get_gcwq(cpu);
}
/*
* Policy functions. These define the policies on how the global worker
* pools are managed. Unless noted otherwise, these functions assume that
* they're being called with gcwq->lock held.
*/
static bool __need_more_worker(struct worker_pool *pool)
{
return !atomic_read(get_pool_nr_running(pool));
}
/*
* Need to wake up a worker? Called from anything but currently
* running workers.
*
* Note that, because unbound workers never contribute to nr_running, this
* function will always return %true for unbound gcwq as long as the
* worklist isn't empty.
*/
static bool need_more_worker(struct worker_pool *pool)
{
return !list_empty(&pool->worklist) && __need_more_worker(pool);
}
/* Can I start working? Called from busy but !running workers. */
static bool may_start_working(struct worker_pool *pool)
{
return pool->nr_idle;
}
/* Do I need to keep working? Called from currently running workers. */
static bool keep_working(struct worker_pool *pool)
{
atomic_t *nr_running = get_pool_nr_running(pool);
return !list_empty(&pool->worklist) && atomic_read(nr_running) <= 1;
}
/* Do we need a new worker? Called from manager. */
static bool need_to_create_worker(struct worker_pool *pool)
{
return need_more_worker(pool) && !may_start_working(pool);
}
/* Do I need to be the manager? */
static bool need_to_manage_workers(struct worker_pool *pool)
{
return need_to_create_worker(pool) ||
(pool->flags & POOL_MANAGE_WORKERS);
}
/* Do we have too many workers and should some go away? */
static bool too_many_workers(struct worker_pool *pool)
{
bool managing = pool->flags & POOL_MANAGING_WORKERS;
int nr_idle = pool->nr_idle + managing; /* manager is considered idle */
int nr_busy = pool->nr_workers - nr_idle;
return nr_idle > 2 && (nr_idle - 2) * MAX_IDLE_WORKERS_RATIO >= nr_busy;
}
/*
* Wake up functions.
*/
/* Return the first worker. Safe with preemption disabled */
static struct worker *first_worker(struct worker_pool *pool)
{
if (unlikely(list_empty(&pool->idle_list)))
return NULL;
return list_first_entry(&pool->idle_list, struct worker, entry);
}
/**
* wake_up_worker - wake up an idle worker
* @pool: worker pool to wake worker from
*
* Wake up the first idle worker of @pool.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*/
static void wake_up_worker(struct worker_pool *pool)
{
struct worker *worker = first_worker(pool);
if (likely(worker))
wake_up_process(worker->task);
}
/**
* wq_worker_waking_up - a worker is waking up
* @task: task waking up
* @cpu: CPU @task is waking up to
*
* This function is called during try_to_wake_up() when a worker is
* being awoken.
*
* CONTEXT:
* spin_lock_irq(rq->lock)
*/
void wq_worker_waking_up(struct task_struct *task, unsigned int cpu)
{
struct worker *worker = kthread_data(task);
if (!(worker->flags & WORKER_NOT_RUNNING))
atomic_inc(get_pool_nr_running(worker->pool));
}
/**
* wq_worker_sleeping - a worker is going to sleep
* @task: task going to sleep
* @cpu: CPU in question, must be the current CPU number
*
* This function is called during schedule() when a busy worker is
* going to sleep. Worker on the same cpu can be woken up by
* returning pointer to its task.
*
* CONTEXT:
* spin_lock_irq(rq->lock)
*
* RETURNS:
* Worker task on @cpu to wake up, %NULL if none.
*/
struct task_struct *wq_worker_sleeping(struct task_struct *task,
unsigned int cpu)
{
struct worker *worker = kthread_data(task), *to_wakeup = NULL;
struct worker_pool *pool = worker->pool;
atomic_t *nr_running = get_pool_nr_running(pool);
if (worker->flags & WORKER_NOT_RUNNING)
return NULL;
/* this can only happen on the local cpu */
BUG_ON(cpu != raw_smp_processor_id());
/*
* The counterpart of the following dec_and_test, implied mb,
* worklist not empty test sequence is in insert_work().
* Please read comment there.
*
* NOT_RUNNING is clear. This means that trustee is not in
* charge and we're running on the local cpu w/ rq lock held
* and preemption disabled, which in turn means that none else
* could be manipulating idle_list, so dereferencing idle_list
* without gcwq lock is safe.
*/
if (atomic_dec_and_test(nr_running) && !list_empty(&pool->worklist))
to_wakeup = first_worker(pool);
return to_wakeup ? to_wakeup->task : NULL;
}
/**
* worker_set_flags - set worker flags and adjust nr_running accordingly
* @worker: self
* @flags: flags to set
* @wakeup: wakeup an idle worker if necessary
*
* Set @flags in @worker->flags and adjust nr_running accordingly. If
* nr_running becomes zero and @wakeup is %true, an idle worker is
* woken up.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock)
*/
static inline void worker_set_flags(struct worker *worker, unsigned int flags,
bool wakeup)
{
struct worker_pool *pool = worker->pool;
WARN_ON_ONCE(worker->task != current);
/*
* If transitioning into NOT_RUNNING, adjust nr_running and
* wake up an idle worker as necessary if requested by
* @wakeup.
*/
if ((flags & WORKER_NOT_RUNNING) &&
!(worker->flags & WORKER_NOT_RUNNING)) {
atomic_t *nr_running = get_pool_nr_running(pool);
if (wakeup) {
if (atomic_dec_and_test(nr_running) &&
!list_empty(&pool->worklist))
wake_up_worker(pool);
} else
atomic_dec(nr_running);
}
worker->flags |= flags;
}
/**
* worker_clr_flags - clear worker flags and adjust nr_running accordingly
* @worker: self
* @flags: flags to clear
*
* Clear @flags in @worker->flags and adjust nr_running accordingly.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock)
*/
static inline void worker_clr_flags(struct worker *worker, unsigned int flags)
{
struct worker_pool *pool = worker->pool;
unsigned int oflags = worker->flags;
WARN_ON_ONCE(worker->task != current);
worker->flags &= ~flags;
/*
* If transitioning out of NOT_RUNNING, increment nr_running. Note
* that the nested NOT_RUNNING is not a noop. NOT_RUNNING is mask
* of multiple flags, not a single flag.
*/
if ((flags & WORKER_NOT_RUNNING) && (oflags & WORKER_NOT_RUNNING))
if (!(worker->flags & WORKER_NOT_RUNNING))
atomic_inc(get_pool_nr_running(pool));
}
/**
* busy_worker_head - return the busy hash head for a work
* @gcwq: gcwq of interest
* @work: work to be hashed
*
* Return hash head of @gcwq for @work.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*
* RETURNS:
* Pointer to the hash head.
*/
static struct hlist_head *busy_worker_head(struct global_cwq *gcwq,
struct work_struct *work)
{
const int base_shift = ilog2(sizeof(struct work_struct));
unsigned long v = (unsigned long)work;
/* simple shift and fold hash, do we need something better? */
v >>= base_shift;
v += v >> BUSY_WORKER_HASH_ORDER;
v &= BUSY_WORKER_HASH_MASK;
return &gcwq->busy_hash[v];
}
/**
* __find_worker_executing_work - find worker which is executing a work
* @gcwq: gcwq of interest
* @bwh: hash head as returned by busy_worker_head()
* @work: work to find worker for
*
* Find a worker which is executing @work on @gcwq. @bwh should be
* the hash head obtained by calling busy_worker_head() with the same
* work.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*
* RETURNS:
* Pointer to worker which is executing @work if found, NULL
* otherwise.
*/
static struct worker *__find_worker_executing_work(struct global_cwq *gcwq,
struct hlist_head *bwh,
struct work_struct *work)
{
struct worker *worker;
struct hlist_node *tmp;
hlist_for_each_entry(worker, tmp, bwh, hentry)
if (worker->current_work == work)
return worker;
return NULL;
}
/**
* find_worker_executing_work - find worker which is executing a work
* @gcwq: gcwq of interest
* @work: work to find worker for
*
* Find a worker which is executing @work on @gcwq. This function is
* identical to __find_worker_executing_work() except that this
* function calculates @bwh itself.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*
* RETURNS:
* Pointer to worker which is executing @work if found, NULL
* otherwise.
*/
static struct worker *find_worker_executing_work(struct global_cwq *gcwq,
struct work_struct *work)
{
return __find_worker_executing_work(gcwq, busy_worker_head(gcwq, work),
work);
}
/**
* insert_work - insert a work into gcwq
* @cwq: cwq @work belongs to
* @work: work to insert
* @head: insertion point
* @extra_flags: extra WORK_STRUCT_* flags to set
*
* Insert @work which belongs to @cwq into @gcwq after @head.
* @extra_flags is or'd to work_struct flags.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*/
static void insert_work(struct cpu_workqueue_struct *cwq,
struct work_struct *work, struct list_head *head,
unsigned int extra_flags)
{
struct worker_pool *pool = cwq->pool;
/* we own @work, set data and link */
set_work_cwq(work, cwq, extra_flags);
/*
* Ensure that we get the right work->data if we see the
* result of list_add() below, see try_to_grab_pending().
*/
smp_wmb();
list_add_tail(&work->entry, head);
/*
* Ensure either worker_sched_deactivated() sees the above
* list_add_tail() or we see zero nr_running to avoid workers
* lying around lazily while there are works to be processed.
*/
smp_mb();
if (__need_more_worker(pool))
wake_up_worker(pool);
}
/*
* Test whether @work is being queued from another work executing on the
* same workqueue. This is rather expensive and should only be used from
* cold paths.
*/
static bool is_chained_work(struct workqueue_struct *wq)
{
unsigned long flags;
unsigned int cpu;
for_each_gcwq_cpu(cpu) {
struct global_cwq *gcwq = get_gcwq(cpu);
struct worker *worker;
struct hlist_node *pos;
int i;
spin_lock_irqsave(&gcwq->lock, flags);
for_each_busy_worker(worker, i, pos, gcwq) {
if (worker->task != current)
continue;
spin_unlock_irqrestore(&gcwq->lock, flags);
/*
* I'm @worker, no locking necessary. See if @work
* is headed to the same workqueue.
*/
return worker->current_cwq->wq == wq;
}
spin_unlock_irqrestore(&gcwq->lock, flags);
}
return false;
}
static void __queue_work(unsigned int cpu, struct workqueue_struct *wq,
struct work_struct *work)
{
struct global_cwq *gcwq;
struct cpu_workqueue_struct *cwq;
struct list_head *worklist;
unsigned int work_flags;
unsigned long flags;
debug_work_activate(work);
/* if dying, only works from the same workqueue are allowed */
if (unlikely(wq->flags & WQ_DRAINING) &&
WARN_ON_ONCE(!is_chained_work(wq)))
return;
/* determine gcwq to use */
if (!(wq->flags & WQ_UNBOUND)) {
struct global_cwq *last_gcwq;
if (unlikely(cpu == WORK_CPU_UNBOUND))
cpu = raw_smp_processor_id();
/*
* It's multi cpu. If @wq is non-reentrant and @work
* was previously on a different cpu, it might still
* be running there, in which case the work needs to
* be queued on that cpu to guarantee non-reentrance.
*/
gcwq = get_gcwq(cpu);
if (wq->flags & WQ_NON_REENTRANT &&
(last_gcwq = get_work_gcwq(work)) && last_gcwq != gcwq) {
struct worker *worker;
spin_lock_irqsave(&last_gcwq->lock, flags);
worker = find_worker_executing_work(last_gcwq, work);
if (worker && worker->current_cwq->wq == wq)
gcwq = last_gcwq;
else {
/* meh... not running there, queue here */
spin_unlock_irqrestore(&last_gcwq->lock, flags);
spin_lock_irqsave(&gcwq->lock, flags);
}
} else
spin_lock_irqsave(&gcwq->lock, flags);
} else {
gcwq = get_gcwq(WORK_CPU_UNBOUND);
spin_lock_irqsave(&gcwq->lock, flags);
}
/* gcwq determined, get cwq and queue */
cwq = get_cwq(gcwq->cpu, wq);
trace_workqueue_queue_work(cpu, cwq, work);
BUG_ON(!list_empty(&work->entry));
cwq->nr_in_flight[cwq->work_color]++;
work_flags = work_color_to_flags(cwq->work_color);
if (likely(cwq->nr_active < cwq->max_active)) {
trace_workqueue_activate_work(work);
cwq->nr_active++;
worklist = &cwq->pool->worklist;
} else {
work_flags |= WORK_STRUCT_DELAYED;
worklist = &cwq->delayed_works;
}
insert_work(cwq, work, worklist, work_flags);
spin_unlock_irqrestore(&gcwq->lock, flags);
}
/**
* queue_work - queue work on a workqueue
* @wq: workqueue to use
* @work: work to queue
*
* Returns 0 if @work was already on a queue, non-zero otherwise.
*
* We queue the work to the CPU on which it was submitted, but if the CPU dies
* it can be processed by another CPU.
*/
int queue_work(struct workqueue_struct *wq, struct work_struct *work)
{
int ret;
ret = queue_work_on(get_cpu(), wq, work);
put_cpu();
return ret;
}
EXPORT_SYMBOL_GPL(queue_work);
/**
* queue_work_on - queue work on specific cpu
* @cpu: CPU number to execute work on
* @wq: workqueue to use
* @work: work to queue
*
* Returns 0 if @work was already on a queue, non-zero otherwise.
*
* We queue the work to a specific CPU, the caller must ensure it
* can't go away.
*/
int
queue_work_on(int cpu, struct workqueue_struct *wq, struct work_struct *work)
{
int ret = 0;
if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
__queue_work(cpu, wq, work);
ret = 1;
}
return ret;
}
EXPORT_SYMBOL_GPL(queue_work_on);
static void delayed_work_timer_fn(unsigned long __data)
{
struct delayed_work *dwork = (struct delayed_work *)__data;
struct cpu_workqueue_struct *cwq = get_work_cwq(&dwork->work);
__queue_work(smp_processor_id(), cwq->wq, &dwork->work);
}
/**
* queue_delayed_work - queue work on a workqueue after delay
* @wq: workqueue to use
* @dwork: delayable work to queue
* @delay: number of jiffies to wait before queueing
*
* Returns 0 if @work was already on a queue, non-zero otherwise.
*/
int queue_delayed_work(struct workqueue_struct *wq,
struct delayed_work *dwork, unsigned long delay)
{
if (delay == 0)
return queue_work(wq, &dwork->work);
return queue_delayed_work_on(-1, wq, dwork, delay);
}
EXPORT_SYMBOL_GPL(queue_delayed_work);
/**
* queue_delayed_work_on - queue work on specific CPU after delay
* @cpu: CPU number to execute work on
* @wq: workqueue to use
* @dwork: work to queue
* @delay: number of jiffies to wait before queueing
*
* Returns 0 if @work was already on a queue, non-zero otherwise.
*/
int queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
struct delayed_work *dwork, unsigned long delay)
{
int ret = 0;
struct timer_list *timer = &dwork->timer;
struct work_struct *work = &dwork->work;
if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) {
unsigned int lcpu;
BUG_ON(timer_pending(timer));
BUG_ON(!list_empty(&work->entry));
timer_stats_timer_set_start_info(&dwork->timer);
/*
* This stores cwq for the moment, for the timer_fn.
* Note that the work's gcwq is preserved to allow
* reentrance detection for delayed works.
*/
if (!(wq->flags & WQ_UNBOUND)) {
struct global_cwq *gcwq = get_work_gcwq(work);
if (gcwq && gcwq->cpu != WORK_CPU_UNBOUND)
lcpu = gcwq->cpu;
else
lcpu = raw_smp_processor_id();
} else
lcpu = WORK_CPU_UNBOUND;
set_work_cwq(work, get_cwq(lcpu, wq), 0);
timer->expires = jiffies + delay;
timer->data = (unsigned long)dwork;
timer->function = delayed_work_timer_fn;
if (unlikely(cpu >= 0))
add_timer_on(timer, cpu);
else
add_timer(timer);
ret = 1;
}
return ret;
}
EXPORT_SYMBOL_GPL(queue_delayed_work_on);
/**
* worker_enter_idle - enter idle state
* @worker: worker which is entering idle state
*
* @worker is entering idle state. Update stats and idle timer if
* necessary.
*
* LOCKING:
* spin_lock_irq(gcwq->lock).
*/
static void worker_enter_idle(struct worker *worker)
{
struct worker_pool *pool = worker->pool;
struct global_cwq *gcwq = pool->gcwq;
BUG_ON(worker->flags & WORKER_IDLE);
BUG_ON(!list_empty(&worker->entry) &&
(worker->hentry.next || worker->hentry.pprev));
/* can't use worker_set_flags(), also called from start_worker() */
worker->flags |= WORKER_IDLE;
pool->nr_idle++;
worker->last_active = jiffies;
/* idle_list is LIFO */
list_add(&worker->entry, &pool->idle_list);
if (likely(!(worker->flags & WORKER_ROGUE))) {
if (too_many_workers(pool) && !timer_pending(&pool->idle_timer))
mod_timer(&pool->idle_timer,
jiffies + IDLE_WORKER_TIMEOUT);
} else
wake_up_all(&gcwq->trustee_wait);
/*
* Sanity check nr_running. Because trustee releases gcwq->lock
* between setting %WORKER_ROGUE and zapping nr_running, the
* warning may trigger spuriously. Check iff trustee is idle.
*/
WARN_ON_ONCE(gcwq->trustee_state == TRUSTEE_DONE &&
pool->nr_workers == pool->nr_idle &&
atomic_read(get_pool_nr_running(pool)));
}
/**
* worker_leave_idle - leave idle state
* @worker: worker which is leaving idle state
*
* @worker is leaving idle state. Update stats.
*
* LOCKING:
* spin_lock_irq(gcwq->lock).
*/
static void worker_leave_idle(struct worker *worker)
{
struct worker_pool *pool = worker->pool;
BUG_ON(!(worker->flags & WORKER_IDLE));
worker_clr_flags(worker, WORKER_IDLE);
pool->nr_idle--;
list_del_init(&worker->entry);
}
/**
* worker_maybe_bind_and_lock - bind worker to its cpu if possible and lock gcwq
* @worker: self
*
* Works which are scheduled while the cpu is online must at least be
* scheduled to a worker which is bound to the cpu so that if they are
* flushed from cpu callbacks while cpu is going down, they are
* guaranteed to execute on the cpu.
*
* This function is to be used by rogue workers and rescuers to bind
* themselves to the target cpu and may race with cpu going down or
* coming online. kthread_bind() can't be used because it may put the
* worker to already dead cpu and set_cpus_allowed_ptr() can't be used
* verbatim as it's best effort and blocking and gcwq may be
* [dis]associated in the meantime.
*
* This function tries set_cpus_allowed() and locks gcwq and verifies
* the binding against GCWQ_DISASSOCIATED which is set during
* CPU_DYING and cleared during CPU_ONLINE, so if the worker enters
* idle state or fetches works without dropping lock, it can guarantee
* the scheduling requirement described in the first paragraph.
*
* CONTEXT:
* Might sleep. Called without any lock but returns with gcwq->lock
* held.
*
* RETURNS:
* %true if the associated gcwq is online (@worker is successfully
* bound), %false if offline.
*/
static bool worker_maybe_bind_and_lock(struct worker *worker)
__acquires(&gcwq->lock)
{
struct global_cwq *gcwq = worker->pool->gcwq;
struct task_struct *task = worker->task;
while (true) {
/*
* The following call may fail, succeed or succeed
* without actually migrating the task to the cpu if
* it races with cpu hotunplug operation. Verify
* against GCWQ_DISASSOCIATED.
*/
if (!(gcwq->flags & GCWQ_DISASSOCIATED))
set_cpus_allowed_ptr(task, get_cpu_mask(gcwq->cpu));
spin_lock_irq(&gcwq->lock);
if (gcwq->flags & GCWQ_DISASSOCIATED)
return false;
if (task_cpu(task) == gcwq->cpu &&
cpumask_equal(¤t->cpus_allowed,
get_cpu_mask(gcwq->cpu)))
return true;
spin_unlock_irq(&gcwq->lock);
/*
* We've raced with CPU hot[un]plug. Give it a breather
* and retry migration. cond_resched() is required here;
* otherwise, we might deadlock against cpu_stop trying to
* bring down the CPU on non-preemptive kernel.
*/
cpu_relax();
cond_resched();
}
}
/*
* Function for worker->rebind_work used to rebind rogue busy workers
* to the associated cpu which is coming back online. This is
* scheduled by cpu up but can race with other cpu hotplug operations
* and may be executed twice without intervening cpu down.
*/
static void worker_rebind_fn(struct work_struct *work)
{
struct worker *worker = container_of(work, struct worker, rebind_work);
struct global_cwq *gcwq = worker->pool->gcwq;
if (worker_maybe_bind_and_lock(worker))
worker_clr_flags(worker, WORKER_REBIND);
spin_unlock_irq(&gcwq->lock);
}
static struct worker *alloc_worker(void)
{
struct worker *worker;
worker = kzalloc(sizeof(*worker), GFP_KERNEL);
if (worker) {
INIT_LIST_HEAD(&worker->entry);
INIT_LIST_HEAD(&worker->scheduled);
INIT_WORK(&worker->rebind_work, worker_rebind_fn);
/* on creation a worker is in !idle && prep state */
worker->flags = WORKER_PREP;
}
return worker;
}
/**
* create_worker - create a new workqueue worker
* @pool: pool the new worker will belong to
* @bind: whether to set affinity to @cpu or not
*
* Create a new worker which is bound to @pool. The returned worker
* can be started by calling start_worker() or destroyed using
* destroy_worker().
*
* CONTEXT:
* Might sleep. Does GFP_KERNEL allocations.
*
* RETURNS:
* Pointer to the newly created worker.
*/
static struct worker *create_worker(struct worker_pool *pool, bool bind)
{
struct global_cwq *gcwq = pool->gcwq;
bool on_unbound_cpu = gcwq->cpu == WORK_CPU_UNBOUND;
const char *pri = worker_pool_pri(pool) ? "H" : "";
struct worker *worker = NULL;
int id = -1;
spin_lock_irq(&gcwq->lock);
while (ida_get_new(&pool->worker_ida, &id)) {
spin_unlock_irq(&gcwq->lock);
if (!ida_pre_get(&pool->worker_ida, GFP_KERNEL))
goto fail;
spin_lock_irq(&gcwq->lock);
}
spin_unlock_irq(&gcwq->lock);
worker = alloc_worker();
if (!worker)
goto fail;
worker->pool = pool;
worker->id = id;
if (!on_unbound_cpu)
worker->task = kthread_create_on_node(worker_thread,
worker, cpu_to_node(gcwq->cpu),
"kworker/%u:%d%s", gcwq->cpu, id, pri);
else
worker->task = kthread_create(worker_thread, worker,
"kworker/u:%d%s", id, pri);
if (IS_ERR(worker->task))
goto fail;
if (worker_pool_pri(pool))
set_user_nice(worker->task, HIGHPRI_NICE_LEVEL);
/*
* A rogue worker will become a regular one if CPU comes
* online later on. Make sure every worker has
* PF_THREAD_BOUND set.
*/
if (bind && !on_unbound_cpu)
kthread_bind(worker->task, gcwq->cpu);
else {
worker->task->flags |= PF_THREAD_BOUND;
if (on_unbound_cpu)
worker->flags |= WORKER_UNBOUND;
}
return worker;
fail:
if (id >= 0) {
spin_lock_irq(&gcwq->lock);
ida_remove(&pool->worker_ida, id);
spin_unlock_irq(&gcwq->lock);
}
kfree(worker);
return NULL;
}
/**
* start_worker - start a newly created worker
* @worker: worker to start
*
* Make the gcwq aware of @worker and start it.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*/
static void start_worker(struct worker *worker)
{
worker->flags |= WORKER_STARTED;
worker->pool->nr_workers++;
worker_enter_idle(worker);
wake_up_process(worker->task);
}
/**
* destroy_worker - destroy a workqueue worker
* @worker: worker to be destroyed
*
* Destroy @worker and adjust @gcwq stats accordingly.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock) which is released and regrabbed.
*/
static void destroy_worker(struct worker *worker)
{
struct worker_pool *pool = worker->pool;
struct global_cwq *gcwq = pool->gcwq;
int id = worker->id;
/* sanity check frenzy */
BUG_ON(worker->current_work);
BUG_ON(!list_empty(&worker->scheduled));
if (worker->flags & WORKER_STARTED)
pool->nr_workers--;
if (worker->flags & WORKER_IDLE)
pool->nr_idle--;
list_del_init(&worker->entry);
worker->flags |= WORKER_DIE;
spin_unlock_irq(&gcwq->lock);
kthread_stop(worker->task);
kfree(worker);
spin_lock_irq(&gcwq->lock);
ida_remove(&pool->worker_ida, id);
}
static void idle_worker_timeout(unsigned long __pool)
{
struct worker_pool *pool = (void *)__pool;
struct global_cwq *gcwq = pool->gcwq;
spin_lock_irq(&gcwq->lock);
if (too_many_workers(pool)) {
struct worker *worker;
unsigned long expires;
/* idle_list is kept in LIFO order, check the last one */
worker = list_entry(pool->idle_list.prev, struct worker, entry);
expires = worker->last_active + IDLE_WORKER_TIMEOUT;
if (time_before(jiffies, expires))
mod_timer(&pool->idle_timer, expires);
else {
/* it's been idle for too long, wake up manager */
pool->flags |= POOL_MANAGE_WORKERS;
wake_up_worker(pool);
}
}
spin_unlock_irq(&gcwq->lock);
}
static bool send_mayday(struct work_struct *work)
{
struct cpu_workqueue_struct *cwq = get_work_cwq(work);
struct workqueue_struct *wq = cwq->wq;
unsigned int cpu;
if (!(wq->flags & WQ_RESCUER))
return false;
/* mayday mayday mayday */
cpu = cwq->pool->gcwq->cpu;
/* WORK_CPU_UNBOUND can't be set in cpumask, use cpu 0 instead */
if (cpu == WORK_CPU_UNBOUND)
cpu = 0;
if (!mayday_test_and_set_cpu(cpu, wq->mayday_mask))
wake_up_process(wq->rescuer->task);
return true;
}
static void gcwq_mayday_timeout(unsigned long __pool)
{
struct worker_pool *pool = (void *)__pool;
struct global_cwq *gcwq = pool->gcwq;
struct work_struct *work;
spin_lock_irq(&gcwq->lock);
if (need_to_create_worker(pool)) {
/*
* We've been trying to create a new worker but
* haven't been successful. We might be hitting an
* allocation deadlock. Send distress signals to
* rescuers.
*/
list_for_each_entry(work, &pool->worklist, entry)
send_mayday(work);
}
spin_unlock_irq(&gcwq->lock);
mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INTERVAL);
}
/**
* maybe_create_worker - create a new worker if necessary
* @pool: pool to create a new worker for
*
* Create a new worker for @pool if necessary. @pool is guaranteed to
* have at least one idle worker on return from this function. If
* creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
* sent to all rescuers with works scheduled on @pool to resolve
* possible allocation deadlock.
*
* On return, need_to_create_worker() is guaranteed to be false and
* may_start_working() true.
*
* LOCKING:
* spin_lock_irq(gcwq->lock) which may be released and regrabbed
* multiple times. Does GFP_KERNEL allocations. Called only from
* manager.
*
* RETURNS:
* false if no action was taken and gcwq->lock stayed locked, true
* otherwise.
*/
static bool maybe_create_worker(struct worker_pool *pool)
__releases(&gcwq->lock)
__acquires(&gcwq->lock)
{
struct global_cwq *gcwq = pool->gcwq;
if (!need_to_create_worker(pool))
return false;
restart:
spin_unlock_irq(&gcwq->lock);
/* if we don't make progress in MAYDAY_INITIAL_TIMEOUT, call for help */
mod_timer(&pool->mayday_timer, jiffies + MAYDAY_INITIAL_TIMEOUT);
while (true) {
struct worker *worker;
worker = create_worker(pool, true);
if (worker) {
del_timer_sync(&pool->mayday_timer);
spin_lock_irq(&gcwq->lock);
start_worker(worker);
BUG_ON(need_to_create_worker(pool));
return true;
}
if (!need_to_create_worker(pool))
break;
__set_current_state(TASK_INTERRUPTIBLE);
schedule_timeout(CREATE_COOLDOWN);
if (!need_to_create_worker(pool))
break;
}
del_timer_sync(&pool->mayday_timer);
spin_lock_irq(&gcwq->lock);
if (need_to_create_worker(pool))
goto restart;
return true;
}
/**
* maybe_destroy_worker - destroy workers which have been idle for a while
* @pool: pool to destroy workers for
*
* Destroy @pool workers which have been idle for longer than
* IDLE_WORKER_TIMEOUT.
*
* LOCKING:
* spin_lock_irq(gcwq->lock) which may be released and regrabbed
* multiple times. Called only from manager.
*
* RETURNS:
* false if no action was taken and gcwq->lock stayed locked, true
* otherwise.
*/
static bool maybe_destroy_workers(struct worker_pool *pool)
{
bool ret = false;
while (too_many_workers(pool)) {
struct worker *worker;
unsigned long expires;
worker = list_entry(pool->idle_list.prev, struct worker, entry);
expires = worker->last_active + IDLE_WORKER_TIMEOUT;
if (time_before(jiffies, expires)) {
mod_timer(&pool->idle_timer, expires);
break;
}
destroy_worker(worker);
ret = true;
}
return ret;
}
/**
* manage_workers - manage worker pool
* @worker: self
*
* Assume the manager role and manage gcwq worker pool @worker belongs
* to. At any given time, there can be only zero or one manager per
* gcwq. The exclusion is handled automatically by this function.
*
* The caller can safely start processing works on false return. On
* true return, it's guaranteed that need_to_create_worker() is false
* and may_start_working() is true.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock) which may be released and regrabbed
* multiple times. Does GFP_KERNEL allocations.
*
* RETURNS:
* false if no action was taken and gcwq->lock stayed locked, true if
* some action was taken.
*/
static bool manage_workers(struct worker *worker)
{
struct worker_pool *pool = worker->pool;
struct global_cwq *gcwq = pool->gcwq;
bool ret = false;
if (pool->flags & POOL_MANAGING_WORKERS)
return ret;
pool->flags &= ~POOL_MANAGE_WORKERS;
pool->flags |= POOL_MANAGING_WORKERS;
/*
* Destroy and then create so that may_start_working() is true
* on return.
*/
ret |= maybe_destroy_workers(pool);
ret |= maybe_create_worker(pool);
pool->flags &= ~POOL_MANAGING_WORKERS;
/*
* The trustee might be waiting to take over the manager
* position, tell it we're done.
*/
if (unlikely(gcwq->trustee))
wake_up_all(&gcwq->trustee_wait);
return ret;
}
/**
* move_linked_works - move linked works to a list
* @work: start of series of works to be scheduled
* @head: target list to append @work to
* @nextp: out paramter for nested worklist walking
*
* Schedule linked works starting from @work to @head. Work series to
* be scheduled starts at @work and includes any consecutive work with
* WORK_STRUCT_LINKED set in its predecessor.
*
* If @nextp is not NULL, it's updated to point to the next work of
* the last scheduled work. This allows move_linked_works() to be
* nested inside outer list_for_each_entry_safe().
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*/
static void move_linked_works(struct work_struct *work, struct list_head *head,
struct work_struct **nextp)
{
struct work_struct *n;
/*
* Linked worklist will always end before the end of the list,
* use NULL for list head.
*/
list_for_each_entry_safe_from(work, n, NULL, entry) {
list_move_tail(&work->entry, head);
if (!(*work_data_bits(work) & WORK_STRUCT_LINKED))
break;
}
/*
* If we're already inside safe list traversal and have moved
* multiple works to the scheduled queue, the next position
* needs to be updated.
*/
if (nextp)
*nextp = n;
}
static void cwq_activate_first_delayed(struct cpu_workqueue_struct *cwq)
{
struct work_struct *work = list_first_entry(&cwq->delayed_works,
struct work_struct, entry);
trace_workqueue_activate_work(work);
move_linked_works(work, &cwq->pool->worklist, NULL);
__clear_bit(WORK_STRUCT_DELAYED_BIT, work_data_bits(work));
cwq->nr_active++;
}
/**
* cwq_dec_nr_in_flight - decrement cwq's nr_in_flight
* @cwq: cwq of interest
* @color: color of work which left the queue
* @delayed: for a delayed work
*
* A work either has completed or is removed from pending queue,
* decrement nr_in_flight of its cwq and handle workqueue flushing.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*/
static void cwq_dec_nr_in_flight(struct cpu_workqueue_struct *cwq, int color,
bool delayed)
{
/* ignore uncolored works */
if (color == WORK_NO_COLOR)
return;
cwq->nr_in_flight[color]--;
if (!delayed) {
cwq->nr_active--;
if (!list_empty(&cwq->delayed_works)) {
/* one down, submit a delayed one */
if (cwq->nr_active < cwq->max_active)
cwq_activate_first_delayed(cwq);
}
}
/* is flush in progress and are we at the flushing tip? */
if (likely(cwq->flush_color != color))
return;
/* are there still in-flight works? */
if (cwq->nr_in_flight[color])
return;
/* this cwq is done, clear flush_color */
cwq->flush_color = -1;
/*
* If this was the last cwq, wake up the first flusher. It
* will handle the rest.
*/
if (atomic_dec_and_test(&cwq->wq->nr_cwqs_to_flush))
complete(&cwq->wq->first_flusher->done);
}
/**
* process_one_work - process single work
* @worker: self
* @work: work to process
*
* Process @work. This function contains all the logics necessary to
* process a single work including synchronization against and
* interaction with other workers on the same cpu, queueing and
* flushing. As long as context requirement is met, any worker can
* call this function to process a work.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock) which is released and regrabbed.
*/
static void process_one_work(struct worker *worker, struct work_struct *work)
__releases(&gcwq->lock)
__acquires(&gcwq->lock)
{
struct cpu_workqueue_struct *cwq = get_work_cwq(work);
struct worker_pool *pool = worker->pool;
struct global_cwq *gcwq = pool->gcwq;
struct hlist_head *bwh = busy_worker_head(gcwq, work);
bool cpu_intensive = cwq->wq->flags & WQ_CPU_INTENSIVE;
work_func_t f = work->func;
int work_color;
struct worker *collision;
#ifdef CONFIG_LOCKDEP
/*
* It is permissible to free the struct work_struct from
* inside the function that is called from it, this we need to
* take into account for lockdep too. To avoid bogus "held
* lock freed" warnings as well as problems when looking into
* work->lockdep_map, make a copy and use that here.
*/
struct lockdep_map lockdep_map = work->lockdep_map;
#endif
/*
* A single work shouldn't be executed concurrently by
* multiple workers on a single cpu. Check whether anyone is
* already processing the work. If so, defer the work to the
* currently executing one.
*/
collision = __find_worker_executing_work(gcwq, bwh, work);
if (unlikely(collision)) {
move_linked_works(work, &collision->scheduled, NULL);
return;
}
/* claim and process */
debug_work_deactivate(work);
hlist_add_head(&worker->hentry, bwh);
worker->current_work = work;
worker->current_cwq = cwq;
work_color = get_work_color(work);
/* record the current cpu number in the work data and dequeue */
set_work_cpu(work, gcwq->cpu);
list_del_init(&work->entry);
/*
* CPU intensive works don't participate in concurrency
* management. They're the scheduler's responsibility.
*/
if (unlikely(cpu_intensive))
worker_set_flags(worker, WORKER_CPU_INTENSIVE, true);
/*
* Unbound gcwq isn't concurrency managed and work items should be
* executed ASAP. Wake up another worker if necessary.
*/
if ((worker->flags & WORKER_UNBOUND) && need_more_worker(pool))
wake_up_worker(pool);
spin_unlock_irq(&gcwq->lock);
work_clear_pending(work);
lock_map_acquire_read(&cwq->wq->lockdep_map);
lock_map_acquire(&lockdep_map);
trace_workqueue_execute_start(work);
f(work);
/*
* While we must be careful to not use "work" after this, the trace
* point will only record its address.
*/
trace_workqueue_execute_end(work);
lock_map_release(&lockdep_map);
lock_map_release(&cwq->wq->lockdep_map);
if (unlikely(in_atomic() || lockdep_depth(current) > 0)) {
printk(KERN_ERR "BUG: workqueue leaked lock or atomic: "
"%s/0x%08x/%d\n",
current->comm, preempt_count(), task_pid_nr(current));
printk(KERN_ERR " last function: ");
print_symbol("%s\n", (unsigned long)f);
debug_show_held_locks(current);
BUG_ON(PANIC_CORRUPTION);
dump_stack();
}
spin_lock_irq(&gcwq->lock);
/* clear cpu intensive status */
if (unlikely(cpu_intensive))
worker_clr_flags(worker, WORKER_CPU_INTENSIVE);
/* we're done with it, release */
hlist_del_init(&worker->hentry);
worker->current_work = NULL;
worker->current_cwq = NULL;
cwq_dec_nr_in_flight(cwq, work_color, false);
}
/**
* process_scheduled_works - process scheduled works
* @worker: self
*
* Process all scheduled works. Please note that the scheduled list
* may change while processing a work, so this function repeatedly
* fetches a work from the top and executes it.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock) which may be released and regrabbed
* multiple times.
*/
static void process_scheduled_works(struct worker *worker)
{
while (!list_empty(&worker->scheduled)) {
struct work_struct *work = list_first_entry(&worker->scheduled,
struct work_struct, entry);
process_one_work(worker, work);
}
}
/**
* worker_thread - the worker thread function
* @__worker: self
*
* The gcwq worker thread function. There's a single dynamic pool of
* these per each cpu. These workers process all works regardless of
* their specific target workqueue. The only exception is works which
* belong to workqueues with a rescuer which will be explained in
* rescuer_thread().
*/
static int worker_thread(void *__worker)
{
struct worker *worker = __worker;
struct worker_pool *pool = worker->pool;
struct global_cwq *gcwq = pool->gcwq;
/* tell the scheduler that this is a workqueue worker */
worker->task->flags |= PF_WQ_WORKER;
woke_up:
spin_lock_irq(&gcwq->lock);
/* DIE can be set only while we're idle, checking here is enough */
if (worker->flags & WORKER_DIE) {
spin_unlock_irq(&gcwq->lock);
worker->task->flags &= ~PF_WQ_WORKER;
return 0;
}
worker_leave_idle(worker);
recheck:
/* no more worker necessary? */
if (!need_more_worker(pool))
goto sleep;
/* do we need to manage? */
if (unlikely(!may_start_working(pool)) && manage_workers(worker))
goto recheck;
/*
* ->scheduled list can only be filled while a worker is
* preparing to process a work or actually processing it.
* Make sure nobody diddled with it while I was sleeping.
*/
BUG_ON(!list_empty(&worker->scheduled));
/*
* When control reaches this point, we're guaranteed to have
* at least one idle worker or that someone else has already
* assumed the manager role.
*/
worker_clr_flags(worker, WORKER_PREP);
do {
struct work_struct *work =
list_first_entry(&pool->worklist,
struct work_struct, entry);
if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) {
/* optimization path, not strictly necessary */
process_one_work(worker, work);
if (unlikely(!list_empty(&worker->scheduled)))
process_scheduled_works(worker);
} else {
move_linked_works(work, &worker->scheduled, NULL);
process_scheduled_works(worker);
}
} while (keep_working(pool));
worker_set_flags(worker, WORKER_PREP, false);
sleep:
if (unlikely(need_to_manage_workers(pool)) && manage_workers(worker))
goto recheck;
/*
* gcwq->lock is held and there's no work to process and no
* need to manage, sleep. Workers are woken up only while
* holding gcwq->lock or from local cpu, so setting the
* current state before releasing gcwq->lock is enough to
* prevent losing any event.
*/
worker_enter_idle(worker);
__set_current_state(TASK_INTERRUPTIBLE);
spin_unlock_irq(&gcwq->lock);
schedule();
goto woke_up;
}
/**
* rescuer_thread - the rescuer thread function
* @__wq: the associated workqueue
*
* Workqueue rescuer thread function. There's one rescuer for each
* workqueue which has WQ_RESCUER set.
*
* Regular work processing on a gcwq may block trying to create a new
* worker which uses GFP_KERNEL allocation which has slight chance of
* developing into deadlock if some works currently on the same queue
* need to be processed to satisfy the GFP_KERNEL allocation. This is
* the problem rescuer solves.
*
* When such condition is possible, the gcwq summons rescuers of all
* workqueues which have works queued on the gcwq and let them process
* those works so that forward progress can be guaranteed.
*
* This should happen rarely.
*/
static int rescuer_thread(void *__wq)
{
struct workqueue_struct *wq = __wq;
struct worker *rescuer = wq->rescuer;
struct list_head *scheduled = &rescuer->scheduled;
bool is_unbound = wq->flags & WQ_UNBOUND;
unsigned int cpu;
set_user_nice(current, RESCUER_NICE_LEVEL);
repeat:
set_current_state(TASK_INTERRUPTIBLE);
if (kthread_should_stop())
return 0;
/*
* See whether any cpu is asking for help. Unbounded
* workqueues use cpu 0 in mayday_mask for CPU_UNBOUND.
*/
for_each_mayday_cpu(cpu, wq->mayday_mask) {
unsigned int tcpu = is_unbound ? WORK_CPU_UNBOUND : cpu;
struct cpu_workqueue_struct *cwq = get_cwq(tcpu, wq);
struct worker_pool *pool = cwq->pool;
struct global_cwq *gcwq = pool->gcwq;
struct work_struct *work, *n;
__set_current_state(TASK_RUNNING);
mayday_clear_cpu(cpu, wq->mayday_mask);
/* migrate to the target cpu if possible */
rescuer->pool = pool;
worker_maybe_bind_and_lock(rescuer);
/*
* Slurp in all works issued via this workqueue and
* process'em.
*/
BUG_ON(!list_empty(&rescuer->scheduled));
list_for_each_entry_safe(work, n, &pool->worklist, entry)
if (get_work_cwq(work) == cwq)
move_linked_works(work, scheduled, &n);
process_scheduled_works(rescuer);
/*
* Leave this gcwq. If keep_working() is %true, notify a
* regular worker; otherwise, we end up with 0 concurrency
* and stalling the execution.
*/
if (keep_working(pool))
wake_up_worker(pool);
spin_unlock_irq(&gcwq->lock);
}
schedule();
goto repeat;
}
struct wq_barrier {
struct work_struct work;
struct completion done;
};
static void wq_barrier_func(struct work_struct *work)
{
struct wq_barrier *barr = container_of(work, struct wq_barrier, work);
complete(&barr->done);
}
/**
* insert_wq_barrier - insert a barrier work
* @cwq: cwq to insert barrier into
* @barr: wq_barrier to insert
* @target: target work to attach @barr to
* @worker: worker currently executing @target, NULL if @target is not executing
*
* @barr is linked to @target such that @barr is completed only after
* @target finishes execution. Please note that the ordering
* guarantee is observed only with respect to @target and on the local
* cpu.
*
* Currently, a queued barrier can't be canceled. This is because
* try_to_grab_pending() can't determine whether the work to be
* grabbed is at the head of the queue and thus can't clear LINKED
* flag of the previous work while there must be a valid next work
* after a work with LINKED flag set.
*
* Note that when @worker is non-NULL, @target may be modified
* underneath us, so we can't reliably determine cwq from @target.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock).
*/
static void insert_wq_barrier(struct cpu_workqueue_struct *cwq,
struct wq_barrier *barr,
struct work_struct *target, struct worker *worker)
{
struct list_head *head;
unsigned int linked = 0;
/*
* debugobject calls are safe here even with gcwq->lock locked
* as we know for sure that this will not trigger any of the
* checks and call back into the fixup functions where we
* might deadlock.
*/
INIT_WORK_ONSTACK(&barr->work, wq_barrier_func);
__set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(&barr->work));
init_completion(&barr->done);
/*
* If @target is currently being executed, schedule the
* barrier to the worker; otherwise, put it after @target.
*/
if (worker)
head = worker->scheduled.next;
else {
unsigned long *bits = work_data_bits(target);
head = target->entry.next;
/* there can already be other linked works, inherit and set */
linked = *bits & WORK_STRUCT_LINKED;
__set_bit(WORK_STRUCT_LINKED_BIT, bits);
}
debug_work_activate(&barr->work);
insert_work(cwq, &barr->work, head,
work_color_to_flags(WORK_NO_COLOR) | linked);
}
/**
* flush_workqueue_prep_cwqs - prepare cwqs for workqueue flushing
* @wq: workqueue being flushed
* @flush_color: new flush color, < 0 for no-op
* @work_color: new work color, < 0 for no-op
*
* Prepare cwqs for workqueue flushing.
*
* If @flush_color is non-negative, flush_color on all cwqs should be
* -1. If no cwq has in-flight commands at the specified color, all
* cwq->flush_color's stay at -1 and %false is returned. If any cwq
* has in flight commands, its cwq->flush_color is set to
* @flush_color, @wq->nr_cwqs_to_flush is updated accordingly, cwq
* wakeup logic is armed and %true is returned.
*
* The caller should have initialized @wq->first_flusher prior to
* calling this function with non-negative @flush_color. If
* @flush_color is negative, no flush color update is done and %false
* is returned.
*
* If @work_color is non-negative, all cwqs should have the same
* work_color which is previous to @work_color and all will be
* advanced to @work_color.
*
* CONTEXT:
* mutex_lock(wq->flush_mutex).
*
* RETURNS:
* %true if @flush_color >= 0 and there's something to flush. %false
* otherwise.
*/
static bool flush_workqueue_prep_cwqs(struct workqueue_struct *wq,
int flush_color, int work_color)
{
bool wait = false;
unsigned int cpu;
if (flush_color >= 0) {
BUG_ON(atomic_read(&wq->nr_cwqs_to_flush));
atomic_set(&wq->nr_cwqs_to_flush, 1);
}
for_each_cwq_cpu(cpu, wq) {
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
struct global_cwq *gcwq = cwq->pool->gcwq;
spin_lock_irq(&gcwq->lock);
if (flush_color >= 0) {
BUG_ON(cwq->flush_color != -1);
if (cwq->nr_in_flight[flush_color]) {
cwq->flush_color = flush_color;
atomic_inc(&wq->nr_cwqs_to_flush);
wait = true;
}
}
if (work_color >= 0) {
BUG_ON(work_color != work_next_color(cwq->work_color));
cwq->work_color = work_color;
}
spin_unlock_irq(&gcwq->lock);
}
if (flush_color >= 0 && atomic_dec_and_test(&wq->nr_cwqs_to_flush))
complete(&wq->first_flusher->done);
return wait;
}
/**
* flush_workqueue - ensure that any scheduled work has run to completion.
* @wq: workqueue to flush
*
* Forces execution of the workqueue and blocks until its completion.
* This is typically used in driver shutdown handlers.
*
* We sleep until all works which were queued on entry have been handled,
* but we are not livelocked by new incoming ones.
*/
void flush_workqueue(struct workqueue_struct *wq)
{
struct wq_flusher this_flusher = {
.list = LIST_HEAD_INIT(this_flusher.list),
.flush_color = -1,
.done = COMPLETION_INITIALIZER_ONSTACK(this_flusher.done),
};
int next_color;
lock_map_acquire(&wq->lockdep_map);
lock_map_release(&wq->lockdep_map);
mutex_lock(&wq->flush_mutex);
/*
* Start-to-wait phase
*/
next_color = work_next_color(wq->work_color);
if (next_color != wq->flush_color) {
/*
* Color space is not full. The current work_color
* becomes our flush_color and work_color is advanced
* by one.
*/
BUG_ON(!list_empty(&wq->flusher_overflow));
this_flusher.flush_color = wq->work_color;
wq->work_color = next_color;
if (!wq->first_flusher) {
/* no flush in progress, become the first flusher */
BUG_ON(wq->flush_color != this_flusher.flush_color);
wq->first_flusher = &this_flusher;
if (!flush_workqueue_prep_cwqs(wq, wq->flush_color,
wq->work_color)) {
/* nothing to flush, done */
wq->flush_color = next_color;
wq->first_flusher = NULL;
goto out_unlock;
}
} else {
/* wait in queue */
BUG_ON(wq->flush_color == this_flusher.flush_color);
list_add_tail(&this_flusher.list, &wq->flusher_queue);
flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
}
} else {
/*
* Oops, color space is full, wait on overflow queue.
* The next flush completion will assign us
* flush_color and transfer to flusher_queue.
*/
list_add_tail(&this_flusher.list, &wq->flusher_overflow);
}
mutex_unlock(&wq->flush_mutex);
wait_for_completion(&this_flusher.done);
/*
* Wake-up-and-cascade phase
*
* First flushers are responsible for cascading flushes and
* handling overflow. Non-first flushers can simply return.
*/
if (wq->first_flusher != &this_flusher)
return;
mutex_lock(&wq->flush_mutex);
/* we might have raced, check again with mutex held */
if (wq->first_flusher != &this_flusher)
goto out_unlock;
wq->first_flusher = NULL;
BUG_ON(!list_empty(&this_flusher.list));
BUG_ON(wq->flush_color != this_flusher.flush_color);
while (true) {
struct wq_flusher *next, *tmp;
/* complete all the flushers sharing the current flush color */
list_for_each_entry_safe(next, tmp, &wq->flusher_queue, list) {
if (next->flush_color != wq->flush_color)
break;
list_del_init(&next->list);
complete(&next->done);
}
BUG_ON(!list_empty(&wq->flusher_overflow) &&
wq->flush_color != work_next_color(wq->work_color));
/* this flush_color is finished, advance by one */
wq->flush_color = work_next_color(wq->flush_color);
/* one color has been freed, handle overflow queue */
if (!list_empty(&wq->flusher_overflow)) {
/*
* Assign the same color to all overflowed
* flushers, advance work_color and append to
* flusher_queue. This is the start-to-wait
* phase for these overflowed flushers.
*/
list_for_each_entry(tmp, &wq->flusher_overflow, list)
tmp->flush_color = wq->work_color;
wq->work_color = work_next_color(wq->work_color);
list_splice_tail_init(&wq->flusher_overflow,
&wq->flusher_queue);
flush_workqueue_prep_cwqs(wq, -1, wq->work_color);
}
if (list_empty(&wq->flusher_queue)) {
BUG_ON(wq->flush_color != wq->work_color);
break;
}
/*
* Need to flush more colors. Make the next flusher
* the new first flusher and arm cwqs.
*/
BUG_ON(wq->flush_color == wq->work_color);
BUG_ON(wq->flush_color != next->flush_color);
list_del_init(&next->list);
wq->first_flusher = next;
if (flush_workqueue_prep_cwqs(wq, wq->flush_color, -1))
break;
/*
* Meh... this color is already done, clear first
* flusher and repeat cascading.
*/
wq->first_flusher = NULL;
}
out_unlock:
mutex_unlock(&wq->flush_mutex);
}
EXPORT_SYMBOL_GPL(flush_workqueue);
/**
* drain_workqueue - drain a workqueue
* @wq: workqueue to drain
*
* Wait until the workqueue becomes empty. While draining is in progress,
* only chain queueing is allowed. IOW, only currently pending or running
* work items on @wq can queue further work items on it. @wq is flushed
* repeatedly until it becomes empty. The number of flushing is detemined
* by the depth of chaining and should be relatively short. Whine if it
* takes too long.
*/
void drain_workqueue(struct workqueue_struct *wq)
{
unsigned int flush_cnt = 0;
unsigned int cpu;
/*
* __queue_work() needs to test whether there are drainers, is much
* hotter than drain_workqueue() and already looks at @wq->flags.
* Use WQ_DRAINING so that queue doesn't have to check nr_drainers.
*/
spin_lock(&workqueue_lock);
if (!wq->nr_drainers++)
wq->flags |= WQ_DRAINING;
spin_unlock(&workqueue_lock);
reflush:
flush_workqueue(wq);
for_each_cwq_cpu(cpu, wq) {
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
bool drained;
spin_lock_irq(&cwq->pool->gcwq->lock);
drained = !cwq->nr_active && list_empty(&cwq->delayed_works);
spin_unlock_irq(&cwq->pool->gcwq->lock);
if (drained)
continue;
if (++flush_cnt == 10 ||
(flush_cnt % 100 == 0 && flush_cnt <= 1000))
pr_warning("workqueue %s: flush on destruction isn't complete after %u tries\n",
wq->name, flush_cnt);
goto reflush;
}
spin_lock(&workqueue_lock);
if (!--wq->nr_drainers)
wq->flags &= ~WQ_DRAINING;
spin_unlock(&workqueue_lock);
}
EXPORT_SYMBOL_GPL(drain_workqueue);
static bool start_flush_work(struct work_struct *work, struct wq_barrier *barr,
bool wait_executing)
{
struct worker *worker = NULL;
struct global_cwq *gcwq;
struct cpu_workqueue_struct *cwq;
might_sleep();
gcwq = get_work_gcwq(work);
if (!gcwq)
return false;
spin_lock_irq(&gcwq->lock);
if (!list_empty(&work->entry)) {
/*
* See the comment near try_to_grab_pending()->smp_rmb().
* If it was re-queued to a different gcwq under us, we
* are not going to wait.
*/
smp_rmb();
cwq = get_work_cwq(work);
if (unlikely(!cwq || gcwq != cwq->pool->gcwq))
goto already_gone;
} else if (wait_executing) {
worker = find_worker_executing_work(gcwq, work);
if (!worker)
goto already_gone;
cwq = worker->current_cwq;
} else
goto already_gone;
insert_wq_barrier(cwq, barr, work, worker);
spin_unlock_irq(&gcwq->lock);
/*
* If @max_active is 1 or rescuer is in use, flushing another work
* item on the same workqueue may lead to deadlock. Make sure the
* flusher is not running on the same workqueue by verifying write
* access.
*/
if (cwq->wq->saved_max_active == 1 || cwq->wq->flags & WQ_RESCUER)
lock_map_acquire(&cwq->wq->lockdep_map);
else
lock_map_acquire_read(&cwq->wq->lockdep_map);
lock_map_release(&cwq->wq->lockdep_map);
return true;
already_gone:
spin_unlock_irq(&gcwq->lock);
return false;
}
/**
* flush_work - wait for a work to finish executing the last queueing instance
* @work: the work to flush
*
* Wait until @work has finished execution. This function considers
* only the last queueing instance of @work. If @work has been
* enqueued across different CPUs on a non-reentrant workqueue or on
* multiple workqueues, @work might still be executing on return on
* some of the CPUs from earlier queueing.
*
* If @work was queued only on a non-reentrant, ordered or unbound
* workqueue, @work is guaranteed to be idle on return if it hasn't
* been requeued since flush started.
*
* RETURNS:
* %true if flush_work() waited for the work to finish execution,
* %false if it was already idle.
*/
bool flush_work(struct work_struct *work)
{
struct wq_barrier barr;
if (start_flush_work(work, &barr, true)) {
wait_for_completion(&barr.done);
destroy_work_on_stack(&barr.work);
return true;
} else
return false;
}
EXPORT_SYMBOL_GPL(flush_work);
static bool wait_on_cpu_work(struct global_cwq *gcwq, struct work_struct *work)
{
struct wq_barrier barr;
struct worker *worker;
spin_lock_irq(&gcwq->lock);
worker = find_worker_executing_work(gcwq, work);
if (unlikely(worker))
insert_wq_barrier(worker->current_cwq, &barr, work, worker);
spin_unlock_irq(&gcwq->lock);
if (unlikely(worker)) {
wait_for_completion(&barr.done);
destroy_work_on_stack(&barr.work);
return true;
} else
return false;
}
static bool wait_on_work(struct work_struct *work)
{
bool ret = false;
int cpu;
might_sleep();
lock_map_acquire(&work->lockdep_map);
lock_map_release(&work->lockdep_map);
for_each_gcwq_cpu(cpu)
ret |= wait_on_cpu_work(get_gcwq(cpu), work);
return ret;
}
/**
* flush_work_sync - wait until a work has finished execution
* @work: the work to flush
*
* Wait until @work has finished execution. On return, it's
* guaranteed that all queueing instances of @work which happened
* before this function is called are finished. In other words, if
* @work hasn't been requeued since this function was called, @work is
* guaranteed to be idle on return.
*
* RETURNS:
* %true if flush_work_sync() waited for the work to finish execution,
* %false if it was already idle.
*/
bool flush_work_sync(struct work_struct *work)
{
struct wq_barrier barr;
bool pending, waited;
/* we'll wait for executions separately, queue barr only if pending */
pending = start_flush_work(work, &barr, false);
/* wait for executions to finish */
waited = wait_on_work(work);
/* wait for the pending one */
if (pending) {
wait_for_completion(&barr.done);
destroy_work_on_stack(&barr.work);
}
return pending || waited;
}
EXPORT_SYMBOL_GPL(flush_work_sync);
/*
* Upon a successful return (>= 0), the caller "owns" WORK_STRUCT_PENDING bit,
* so this work can't be re-armed in any way.
*/
static int try_to_grab_pending(struct work_struct *work)
{
struct global_cwq *gcwq;
int ret = -1;
if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work)))
return 0;
/*
* The queueing is in progress, or it is already queued. Try to
* steal it from ->worklist without clearing WORK_STRUCT_PENDING.
*/
gcwq = get_work_gcwq(work);
if (!gcwq)
return ret;
spin_lock_irq(&gcwq->lock);
if (!list_empty(&work->entry)) {
/*
* This work is queued, but perhaps we locked the wrong gcwq.
* In that case we must see the new value after rmb(), see
* insert_work()->wmb().
*/
smp_rmb();
if (gcwq == get_work_gcwq(work)) {
debug_work_deactivate(work);
list_del_init(&work->entry);
cwq_dec_nr_in_flight(get_work_cwq(work),
get_work_color(work),
*work_data_bits(work) & WORK_STRUCT_DELAYED);
ret = 1;
}
}
spin_unlock_irq(&gcwq->lock);
return ret;
}
static bool __cancel_work_timer(struct work_struct *work,
struct timer_list* timer)
{
int ret;
do {
ret = (timer && likely(del_timer(timer)));
if (!ret)
ret = try_to_grab_pending(work);
wait_on_work(work);
} while (unlikely(ret < 0));
clear_work_data(work);
return ret;
}
/**
* cancel_work_sync - cancel a work and wait for it to finish
* @work: the work to cancel
*
* Cancel @work and wait for its execution to finish. This function
* can be used even if the work re-queues itself or migrates to
* another workqueue. On return from this function, @work is
* guaranteed to be not pending or executing on any CPU.
*
* cancel_work_sync(&delayed_work->work) must not be used for
* delayed_work's. Use cancel_delayed_work_sync() instead.
*
* The caller must ensure that the workqueue on which @work was last
* queued can't be destroyed before this function returns.
*
* RETURNS:
* %true if @work was pending, %false otherwise.
*/
bool cancel_work_sync(struct work_struct *work)
{
return __cancel_work_timer(work, NULL);
}
EXPORT_SYMBOL_GPL(cancel_work_sync);
/**
* flush_delayed_work - wait for a dwork to finish executing the last queueing
* @dwork: the delayed work to flush
*
* Delayed timer is cancelled and the pending work is queued for
* immediate execution. Like flush_work(), this function only
* considers the last queueing instance of @dwork.
*
* RETURNS:
* %true if flush_work() waited for the work to finish execution,
* %false if it was already idle.
*/
bool flush_delayed_work(struct delayed_work *dwork)
{
if (del_timer_sync(&dwork->timer))
__queue_work(raw_smp_processor_id(),
get_work_cwq(&dwork->work)->wq, &dwork->work);
return flush_work(&dwork->work);
}
EXPORT_SYMBOL(flush_delayed_work);
/**
* flush_delayed_work_sync - wait for a dwork to finish
* @dwork: the delayed work to flush
*
* Delayed timer is cancelled and the pending work is queued for
* execution immediately. Other than timer handling, its behavior
* is identical to flush_work_sync().
*
* RETURNS:
* %true if flush_work_sync() waited for the work to finish execution,
* %false if it was already idle.
*/
bool flush_delayed_work_sync(struct delayed_work *dwork)
{
if (del_timer_sync(&dwork->timer))
__queue_work(raw_smp_processor_id(),
get_work_cwq(&dwork->work)->wq, &dwork->work);
return flush_work_sync(&dwork->work);
}
EXPORT_SYMBOL(flush_delayed_work_sync);
/**
* cancel_delayed_work_sync - cancel a delayed work and wait for it to finish
* @dwork: the delayed work cancel
*
* This is cancel_work_sync() for delayed works.
*
* RETURNS:
* %true if @dwork was pending, %false otherwise.
*/
bool cancel_delayed_work_sync(struct delayed_work *dwork)
{
return __cancel_work_timer(&dwork->work, &dwork->timer);
}
EXPORT_SYMBOL(cancel_delayed_work_sync);
/**
* schedule_work - put work task in global workqueue
* @work: job to be done
*
* Returns zero if @work was already on the kernel-global workqueue and
* non-zero otherwise.
*
* This puts a job in the kernel-global workqueue if it was not already
* queued and leaves it in the same position on the kernel-global
* workqueue otherwise.
*/
int schedule_work(struct work_struct *work)
{
return queue_work(system_wq, work);
}
EXPORT_SYMBOL(schedule_work);
/*
* schedule_work_on - put work task on a specific cpu
* @cpu: cpu to put the work task on
* @work: job to be done
*
* This puts a job on a specific cpu
*/
int schedule_work_on(int cpu, struct work_struct *work)
{
return queue_work_on(cpu, system_wq, work);
}
EXPORT_SYMBOL(schedule_work_on);
/**
* schedule_delayed_work - put work task in global workqueue after delay
* @dwork: job to be done
* @delay: number of jiffies to wait or 0 for immediate execution
*
* After waiting for a given time this puts a job in the kernel-global
* workqueue.
*/
int schedule_delayed_work(struct delayed_work *dwork,
unsigned long delay)
{
return queue_delayed_work(system_wq, dwork, delay);
}
EXPORT_SYMBOL(schedule_delayed_work);
/**
* schedule_delayed_work_on - queue work in global workqueue on CPU after delay
* @cpu: cpu to use
* @dwork: job to be done
* @delay: number of jiffies to wait
*
* After waiting for a given time this puts a job in the kernel-global
* workqueue on the specified CPU.
*/
int schedule_delayed_work_on(int cpu,
struct delayed_work *dwork, unsigned long delay)
{
return queue_delayed_work_on(cpu, system_wq, dwork, delay);
}
EXPORT_SYMBOL(schedule_delayed_work_on);
/**
* schedule_on_each_cpu - execute a function synchronously on each online CPU
* @func: the function to call
*
* schedule_on_each_cpu() executes @func on each online CPU using the
* system workqueue and blocks until all CPUs have completed.
* schedule_on_each_cpu() is very slow.
*
* RETURNS:
* 0 on success, -errno on failure.
*/
int schedule_on_each_cpu(work_func_t func)
{
int cpu;
struct work_struct __percpu *works;
works = alloc_percpu(struct work_struct);
if (!works)
return -ENOMEM;
get_online_cpus();
for_each_online_cpu(cpu) {
struct work_struct *work = per_cpu_ptr(works, cpu);
INIT_WORK(work, func);
schedule_work_on(cpu, work);
}
for_each_online_cpu(cpu)
flush_work(per_cpu_ptr(works, cpu));
put_online_cpus();
free_percpu(works);
return 0;
}
/**
* flush_scheduled_work - ensure that any scheduled work has run to completion.
*
* Forces execution of the kernel-global workqueue and blocks until its
* completion.
*
* Think twice before calling this function! It's very easy to get into
* trouble if you don't take great care. Either of the following situations
* will lead to deadlock:
*
* One of the work items currently on the workqueue needs to acquire
* a lock held by your code or its caller.
*
* Your code is running in the context of a work routine.
*
* They will be detected by lockdep when they occur, but the first might not
* occur very often. It depends on what work items are on the workqueue and
* what locks they need, which you have no control over.
*
* In most situations flushing the entire workqueue is overkill; you merely
* need to know that a particular work item isn't queued and isn't running.
* In such cases you should use cancel_delayed_work_sync() or
* cancel_work_sync() instead.
*/
void flush_scheduled_work(void)
{
flush_workqueue(system_wq);
}
EXPORT_SYMBOL(flush_scheduled_work);
/**
* execute_in_process_context - reliably execute the routine with user context
* @fn: the function to execute
* @ew: guaranteed storage for the execute work structure (must
* be available when the work executes)
*
* Executes the function immediately if process context is available,
* otherwise schedules the function for delayed execution.
*
* Returns: 0 - function was executed
* 1 - function was scheduled for execution
*/
int execute_in_process_context(work_func_t fn, struct execute_work *ew)
{
if (!in_interrupt()) {
fn(&ew->work);
return 0;
}
INIT_WORK(&ew->work, fn);
schedule_work(&ew->work);
return 1;
}
EXPORT_SYMBOL_GPL(execute_in_process_context);
int keventd_up(void)
{
return system_wq != NULL;
}
static int alloc_cwqs(struct workqueue_struct *wq)
{
/*
* cwqs are forced aligned according to WORK_STRUCT_FLAG_BITS.
* Make sure that the alignment isn't lower than that of
* unsigned long long.
*/
const size_t size = sizeof(struct cpu_workqueue_struct);
const size_t align = max_t(size_t, 1 << WORK_STRUCT_FLAG_BITS,
__alignof__(unsigned long long));
if (!(wq->flags & WQ_UNBOUND))
wq->cpu_wq.pcpu = __alloc_percpu(size, align);
else {
void *ptr;
/*
* Allocate enough room to align cwq and put an extra
* pointer at the end pointing back to the originally
* allocated pointer which will be used for free.
*/
ptr = kzalloc(size + align + sizeof(void *), GFP_KERNEL);
if (ptr) {
wq->cpu_wq.single = PTR_ALIGN(ptr, align);
*(void **)(wq->cpu_wq.single + 1) = ptr;
}
}
/* just in case, make sure it's actually aligned */
BUG_ON(!IS_ALIGNED(wq->cpu_wq.v, align));
return wq->cpu_wq.v ? 0 : -ENOMEM;
}
static void free_cwqs(struct workqueue_struct *wq)
{
if (!(wq->flags & WQ_UNBOUND))
free_percpu(wq->cpu_wq.pcpu);
else if (wq->cpu_wq.single) {
/* the pointer to free is stored right after the cwq */
kfree(*(void **)(wq->cpu_wq.single + 1));
}
}
static int wq_clamp_max_active(int max_active, unsigned int flags,
const char *name)
{
int lim = flags & WQ_UNBOUND ? WQ_UNBOUND_MAX_ACTIVE : WQ_MAX_ACTIVE;
if (max_active < 1 || max_active > lim)
printk(KERN_WARNING "workqueue: max_active %d requested for %s "
"is out of range, clamping between %d and %d\n",
max_active, name, 1, lim);
return clamp_val(max_active, 1, lim);
}
struct workqueue_struct *__alloc_workqueue_key(const char *fmt,
unsigned int flags,
int max_active,
struct lock_class_key *key,
const char *lock_name, ...)
{
va_list args, args1;
struct workqueue_struct *wq;
unsigned int cpu;
size_t namelen;
/* determine namelen, allocate wq and format name */
va_start(args, lock_name);
va_copy(args1, args);
namelen = vsnprintf(NULL, 0, fmt, args) + 1;
wq = kzalloc(sizeof(*wq) + namelen, GFP_KERNEL);
if (!wq)
goto err;
vsnprintf(wq->name, namelen, fmt, args1);
va_end(args);
va_end(args1);
/* see the comment above the definition of WQ_POWER_EFFICIENT */
if ((flags & WQ_POWER_EFFICIENT) && wq_power_efficient)
flags |= WQ_UNBOUND;
/*
* Workqueues which may be used during memory reclaim should
* have a rescuer to guarantee forward progress.
*/
if (flags & WQ_MEM_RECLAIM)
flags |= WQ_RESCUER;
max_active = max_active ?: WQ_DFL_ACTIVE;
max_active = wq_clamp_max_active(max_active, flags, wq->name);
/* init wq */
wq->flags = flags;
wq->saved_max_active = max_active;
mutex_init(&wq->flush_mutex);
atomic_set(&wq->nr_cwqs_to_flush, 0);
INIT_LIST_HEAD(&wq->flusher_queue);
INIT_LIST_HEAD(&wq->flusher_overflow);
lockdep_init_map(&wq->lockdep_map, lock_name, key, 0);
INIT_LIST_HEAD(&wq->list);
if (alloc_cwqs(wq) < 0)
goto err;
for_each_cwq_cpu(cpu, wq) {
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
struct global_cwq *gcwq = get_gcwq(cpu);
int pool_idx = (bool)(flags & WQ_HIGHPRI);
BUG_ON((unsigned long)cwq & WORK_STRUCT_FLAG_MASK);
cwq->pool = &gcwq->pools[pool_idx];
cwq->wq = wq;
cwq->flush_color = -1;
cwq->max_active = max_active;
INIT_LIST_HEAD(&cwq->delayed_works);
}
if (flags & WQ_RESCUER) {
struct worker *rescuer;
if (!alloc_mayday_mask(&wq->mayday_mask, GFP_KERNEL))
goto err;
wq->rescuer = rescuer = alloc_worker();
if (!rescuer)
goto err;
rescuer->task = kthread_create(rescuer_thread, wq, "%s",
wq->name);
if (IS_ERR(rescuer->task))
goto err;
rescuer->task->flags |= PF_THREAD_BOUND;
wake_up_process(rescuer->task);
}
/*
* workqueue_lock protects global freeze state and workqueues
* list. Grab it, set max_active accordingly and add the new
* workqueue to workqueues list.
*/
spin_lock(&workqueue_lock);
if (workqueue_freezing && wq->flags & WQ_FREEZABLE)
for_each_cwq_cpu(cpu, wq)
get_cwq(cpu, wq)->max_active = 0;
list_add(&wq->list, &workqueues);
spin_unlock(&workqueue_lock);
return wq;
err:
if (wq) {
free_cwqs(wq);
free_mayday_mask(wq->mayday_mask);
kfree(wq->rescuer);
kfree(wq);
}
return NULL;
}
EXPORT_SYMBOL_GPL(__alloc_workqueue_key);
/**
* destroy_workqueue - safely terminate a workqueue
* @wq: target workqueue
*
* Safely destroy a workqueue. All work currently pending will be done first.
*/
void destroy_workqueue(struct workqueue_struct *wq)
{
unsigned int cpu;
/* drain it before proceeding with destruction */
drain_workqueue(wq);
/*
* wq list is used to freeze wq, remove from list after
* flushing is complete in case freeze races us.
*/
spin_lock(&workqueue_lock);
list_del(&wq->list);
spin_unlock(&workqueue_lock);
/* sanity check */
for_each_cwq_cpu(cpu, wq) {
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
int i;
for (i = 0; i < WORK_NR_COLORS; i++)
BUG_ON(cwq->nr_in_flight[i]);
BUG_ON(cwq->nr_active);
BUG_ON(!list_empty(&cwq->delayed_works));
}
if (wq->flags & WQ_RESCUER) {
kthread_stop(wq->rescuer->task);
free_mayday_mask(wq->mayday_mask);
kfree(wq->rescuer);
}
free_cwqs(wq);
kfree(wq);
}
EXPORT_SYMBOL_GPL(destroy_workqueue);
/**
* workqueue_set_max_active - adjust max_active of a workqueue
* @wq: target workqueue
* @max_active: new max_active value.
*
* Set max_active of @wq to @max_active.
*
* CONTEXT:
* Don't call from IRQ context.
*/
void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
{
unsigned int cpu;
max_active = wq_clamp_max_active(max_active, wq->flags, wq->name);
spin_lock(&workqueue_lock);
wq->saved_max_active = max_active;
for_each_cwq_cpu(cpu, wq) {
struct global_cwq *gcwq = get_gcwq(cpu);
spin_lock_irq(&gcwq->lock);
if (!(wq->flags & WQ_FREEZABLE) ||
!(gcwq->flags & GCWQ_FREEZING))
get_cwq(gcwq->cpu, wq)->max_active = max_active;
spin_unlock_irq(&gcwq->lock);
}
spin_unlock(&workqueue_lock);
}
EXPORT_SYMBOL_GPL(workqueue_set_max_active);
/**
* workqueue_congested - test whether a workqueue is congested
* @cpu: CPU in question
* @wq: target workqueue
*
* Test whether @wq's cpu workqueue for @cpu is congested. There is
* no synchronization around this function and the test result is
* unreliable and only useful as advisory hints or for debugging.
*
* RETURNS:
* %true if congested, %false otherwise.
*/
bool workqueue_congested(unsigned int cpu, struct workqueue_struct *wq)
{
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
return !list_empty(&cwq->delayed_works);
}
EXPORT_SYMBOL_GPL(workqueue_congested);
/**
* work_cpu - return the last known associated cpu for @work
* @work: the work of interest
*
* RETURNS:
* CPU number if @work was ever queued. WORK_CPU_NONE otherwise.
*/
unsigned int work_cpu(struct work_struct *work)
{
struct global_cwq *gcwq = get_work_gcwq(work);
return gcwq ? gcwq->cpu : WORK_CPU_NONE;
}
EXPORT_SYMBOL_GPL(work_cpu);
/**
* work_busy - test whether a work is currently pending or running
* @work: the work to be tested
*
* Test whether @work is currently pending or running. There is no
* synchronization around this function and the test result is
* unreliable and only useful as advisory hints or for debugging.
* Especially for reentrant wqs, the pending state might hide the
* running state.
*
* RETURNS:
* OR'd bitmask of WORK_BUSY_* bits.
*/
unsigned int work_busy(struct work_struct *work)
{
struct global_cwq *gcwq = get_work_gcwq(work);
unsigned long flags;
unsigned int ret = 0;
if (!gcwq)
return false;
spin_lock_irqsave(&gcwq->lock, flags);
if (work_pending(work))
ret |= WORK_BUSY_PENDING;
if (find_worker_executing_work(gcwq, work))
ret |= WORK_BUSY_RUNNING;
spin_unlock_irqrestore(&gcwq->lock, flags);
return ret;
}
EXPORT_SYMBOL_GPL(work_busy);
/*
* CPU hotplug.
*
* There are two challenges in supporting CPU hotplug. Firstly, there
* are a lot of assumptions on strong associations among work, cwq and
* gcwq which make migrating pending and scheduled works very
* difficult to implement without impacting hot paths. Secondly,
* gcwqs serve mix of short, long and very long running works making
* blocked draining impractical.
*
* This is solved by allowing a gcwq to be detached from CPU, running
* it with unbound (rogue) workers and allowing it to be reattached
* later if the cpu comes back online. A separate thread is created
* to govern a gcwq in such state and is called the trustee of the
* gcwq.
*
* Trustee states and their descriptions.
*
* START Command state used on startup. On CPU_DOWN_PREPARE, a
* new trustee is started with this state.
*
* IN_CHARGE Once started, trustee will enter this state after
* assuming the manager role and making all existing
* workers rogue. DOWN_PREPARE waits for trustee to
* enter this state. After reaching IN_CHARGE, trustee
* tries to execute the pending worklist until it's empty
* and the state is set to BUTCHER, or the state is set
* to RELEASE.
*
* BUTCHER Command state which is set by the cpu callback after
* the cpu has went down. Once this state is set trustee
* knows that there will be no new works on the worklist
* and once the worklist is empty it can proceed to
* killing idle workers.
*
* RELEASE Command state which is set by the cpu callback if the
* cpu down has been canceled or it has come online
* again. After recognizing this state, trustee stops
* trying to drain or butcher and clears ROGUE, rebinds
* all remaining workers back to the cpu and releases
* manager role.
*
* DONE Trustee will enter this state after BUTCHER or RELEASE
* is complete.
*
* trustee CPU draining
* took over down complete
* START -----------> IN_CHARGE -----------> BUTCHER -----------> DONE
* | | ^
* | CPU is back online v return workers |
* ----------------> RELEASE --------------
*/
/**
* trustee_wait_event_timeout - timed event wait for trustee
* @cond: condition to wait for
* @timeout: timeout in jiffies
*
* wait_event_timeout() for trustee to use. Handles locking and
* checks for RELEASE request.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock) which may be released and regrabbed
* multiple times. To be used by trustee.
*
* RETURNS:
* Positive indicating left time if @cond is satisfied, 0 if timed
* out, -1 if canceled.
*/
#define trustee_wait_event_timeout(cond, timeout) ({ \
long __ret = (timeout); \
while (!((cond) || (gcwq->trustee_state == TRUSTEE_RELEASE)) && \
__ret) { \
spin_unlock_irq(&gcwq->lock); \
__wait_event_timeout(gcwq->trustee_wait, (cond) || \
(gcwq->trustee_state == TRUSTEE_RELEASE), \
__ret); \
spin_lock_irq(&gcwq->lock); \
} \
gcwq->trustee_state == TRUSTEE_RELEASE ? -1 : (__ret); \
})
/**
* trustee_wait_event - event wait for trustee
* @cond: condition to wait for
*
* wait_event() for trustee to use. Automatically handles locking and
* checks for CANCEL request.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock) which may be released and regrabbed
* multiple times. To be used by trustee.
*
* RETURNS:
* 0 if @cond is satisfied, -1 if canceled.
*/
#define trustee_wait_event(cond) ({ \
long __ret1; \
__ret1 = trustee_wait_event_timeout(cond, MAX_SCHEDULE_TIMEOUT);\
__ret1 < 0 ? -1 : 0; \
})
static bool gcwq_is_managing_workers(struct global_cwq *gcwq)
{
struct worker_pool *pool;
for_each_worker_pool(pool, gcwq)
if (pool->flags & POOL_MANAGING_WORKERS)
return true;
return false;
}
static bool gcwq_has_idle_workers(struct global_cwq *gcwq)
{
struct worker_pool *pool;
for_each_worker_pool(pool, gcwq)
if (!list_empty(&pool->idle_list))
return true;
return false;
}
static int __cpuinit trustee_thread(void *__gcwq)
{
struct global_cwq *gcwq = __gcwq;
struct worker_pool *pool;
struct worker *worker;
struct work_struct *work;
struct hlist_node *pos;
long rc;
int i;
BUG_ON(gcwq->cpu != smp_processor_id());
spin_lock_irq(&gcwq->lock);
/*
* Claim the manager position and make all workers rogue.
* Trustee must be bound to the target cpu and can't be
* cancelled.
*/
BUG_ON(gcwq->cpu != smp_processor_id());
rc = trustee_wait_event(!gcwq_is_managing_workers(gcwq));
BUG_ON(rc < 0);
for_each_worker_pool(pool, gcwq) {
pool->flags |= POOL_MANAGING_WORKERS;
list_for_each_entry(worker, &pool->idle_list, entry)
worker->flags |= WORKER_ROGUE;
}
for_each_busy_worker(worker, i, pos, gcwq)
worker->flags |= WORKER_ROGUE;
/*
* Call schedule() so that we cross rq->lock and thus can
* guarantee sched callbacks see the rogue flag. This is
* necessary as scheduler callbacks may be invoked from other
* cpus.
*/
spin_unlock_irq(&gcwq->lock);
schedule();
spin_lock_irq(&gcwq->lock);
/*
* Sched callbacks are disabled now. Zap nr_running. After
* this, nr_running stays zero and need_more_worker() and
* keep_working() are always true as long as the worklist is
* not empty.
*/
for_each_worker_pool(pool, gcwq)
atomic_set(get_pool_nr_running(pool), 0);
spin_unlock_irq(&gcwq->lock);
for_each_worker_pool(pool, gcwq)
del_timer_sync(&pool->idle_timer);
spin_lock_irq(&gcwq->lock);
/*
* We're now in charge. Notify and proceed to drain. We need
* to keep the gcwq running during the whole CPU down
* procedure as other cpu hotunplug callbacks may need to
* flush currently running tasks.
*/
gcwq->trustee_state = TRUSTEE_IN_CHARGE;
wake_up_all(&gcwq->trustee_wait);
/*
* The original cpu is in the process of dying and may go away
* anytime now. When that happens, we and all workers would
* be migrated to other cpus. Try draining any left work. We
* want to get it over with ASAP - spam rescuers, wake up as
* many idlers as necessary and create new ones till the
* worklist is empty. Note that if the gcwq is frozen, there
* may be frozen works in freezable cwqs. Don't declare
* completion while frozen.
*/
while (true) {
bool busy = false;
for_each_worker_pool(pool, gcwq)
busy |= pool->nr_workers != pool->nr_idle;
if (!busy && !(gcwq->flags & GCWQ_FREEZING) &&
gcwq->trustee_state != TRUSTEE_IN_CHARGE)
break;
for_each_worker_pool(pool, gcwq) {
int nr_works = 0;
list_for_each_entry(work, &pool->worklist, entry) {
send_mayday(work);
nr_works++;
}
list_for_each_entry(worker, &pool->idle_list, entry) {
if (!nr_works--)
break;
wake_up_process(worker->task);
}
if (need_to_create_worker(pool)) {
spin_unlock_irq(&gcwq->lock);
worker = create_worker(pool, false);
spin_lock_irq(&gcwq->lock);
if (worker) {
worker->flags |= WORKER_ROGUE;
start_worker(worker);
}
}
}
/* give a breather */
if (trustee_wait_event_timeout(false, TRUSTEE_COOLDOWN) < 0)
break;
}
/*
* Either all works have been scheduled and cpu is down, or
* cpu down has already been canceled. Wait for and butcher
* all workers till we're canceled.
*/
do {
rc = trustee_wait_event(gcwq_has_idle_workers(gcwq));
i = 0;
for_each_worker_pool(pool, gcwq) {
while (!list_empty(&pool->idle_list)) {
worker = list_first_entry(&pool->idle_list,
struct worker, entry);
destroy_worker(worker);
}
i |= pool->nr_workers;
}
} while (i && rc >= 0);
/*
* At this point, either draining has completed and no worker
* is left, or cpu down has been canceled or the cpu is being
* brought back up. There shouldn't be any idle one left.
* Tell the remaining busy ones to rebind once it finishes the
* currently scheduled works by scheduling the rebind_work.
*/
for_each_worker_pool(pool, gcwq)
WARN_ON(!list_empty(&pool->idle_list));
for_each_busy_worker(worker, i, pos, gcwq) {
struct work_struct *rebind_work = &worker->rebind_work;
/*
* Rebind_work may race with future cpu hotplug
* operations. Use a separate flag to mark that
* rebinding is scheduled.
*/
worker->flags |= WORKER_REBIND;
worker->flags &= ~WORKER_ROGUE;
/* queue rebind_work, wq doesn't matter, use the default one */
if (test_and_set_bit(WORK_STRUCT_PENDING_BIT,
work_data_bits(rebind_work)))
continue;
debug_work_activate(rebind_work);
insert_work(get_cwq(gcwq->cpu, system_wq), rebind_work,
worker->scheduled.next,
work_color_to_flags(WORK_NO_COLOR));
}
/* relinquish manager role */
for_each_worker_pool(pool, gcwq)
pool->flags &= ~POOL_MANAGING_WORKERS;
/* notify completion */
gcwq->trustee = NULL;
gcwq->trustee_state = TRUSTEE_DONE;
wake_up_all(&gcwq->trustee_wait);
spin_unlock_irq(&gcwq->lock);
return 0;
}
/**
* wait_trustee_state - wait for trustee to enter the specified state
* @gcwq: gcwq the trustee of interest belongs to
* @state: target state to wait for
*
* Wait for the trustee to reach @state. DONE is already matched.
*
* CONTEXT:
* spin_lock_irq(gcwq->lock) which may be released and regrabbed
* multiple times. To be used by cpu_callback.
*/
static void __cpuinit wait_trustee_state(struct global_cwq *gcwq, int state)
__releases(&gcwq->lock)
__acquires(&gcwq->lock)
{
if (!(gcwq->trustee_state == state ||
gcwq->trustee_state == TRUSTEE_DONE)) {
spin_unlock_irq(&gcwq->lock);
__wait_event(gcwq->trustee_wait,
gcwq->trustee_state == state ||
gcwq->trustee_state == TRUSTEE_DONE);
spin_lock_irq(&gcwq->lock);
}
}
static int __devinit workqueue_cpu_callback(struct notifier_block *nfb,
unsigned long action,
void *hcpu)
{
unsigned int cpu = (unsigned long)hcpu;
struct global_cwq *gcwq = get_gcwq(cpu);
struct task_struct *new_trustee = NULL;
struct worker *new_workers[NR_WORKER_POOLS] = { };
struct worker_pool *pool;
unsigned long flags;
int i;
action &= ~CPU_TASKS_FROZEN;
switch (action) {
case CPU_DOWN_PREPARE:
new_trustee = kthread_create(trustee_thread, gcwq,
"workqueue_trustee/%d\n", cpu);
if (IS_ERR(new_trustee))
return notifier_from_errno(PTR_ERR(new_trustee));
kthread_bind(new_trustee, cpu);
/* fall through */
case CPU_UP_PREPARE:
i = 0;
for_each_worker_pool(pool, gcwq) {
BUG_ON(pool->first_idle);
new_workers[i] = create_worker(pool, false);
if (!new_workers[i++])
goto err_destroy;
}
}
/* some are called w/ irq disabled, don't disturb irq status */
spin_lock_irqsave(&gcwq->lock, flags);
switch (action) {
case CPU_DOWN_PREPARE:
/* initialize trustee and tell it to acquire the gcwq */
BUG_ON(gcwq->trustee || gcwq->trustee_state != TRUSTEE_DONE);
gcwq->trustee = new_trustee;
gcwq->trustee_state = TRUSTEE_START;
wake_up_process(gcwq->trustee);
wait_trustee_state(gcwq, TRUSTEE_IN_CHARGE);
/* fall through */
case CPU_UP_PREPARE:
i = 0;
for_each_worker_pool(pool, gcwq) {
BUG_ON(pool->first_idle);
pool->first_idle = new_workers[i++];
}
break;
case CPU_DYING:
/*
* Before this, the trustee and all workers except for
* the ones which are still executing works from
* before the last CPU down must be on the cpu. After
* this, they'll all be diasporas.
*/
gcwq->flags |= GCWQ_DISASSOCIATED;
break;
case CPU_POST_DEAD:
gcwq->trustee_state = TRUSTEE_BUTCHER;
/* fall through */
case CPU_UP_CANCELED:
for_each_worker_pool(pool, gcwq) {
destroy_worker(pool->first_idle);
pool->first_idle = NULL;
}
break;
case CPU_DOWN_FAILED:
case CPU_ONLINE:
gcwq->flags &= ~GCWQ_DISASSOCIATED;
if (gcwq->trustee_state != TRUSTEE_DONE) {
gcwq->trustee_state = TRUSTEE_RELEASE;
wake_up_process(gcwq->trustee);
wait_trustee_state(gcwq, TRUSTEE_DONE);
}
/*
* Trustee is done and there might be no worker left.
* Put the first_idle in and request a real manager to
* take a look.
*/
for_each_worker_pool(pool, gcwq) {
spin_unlock_irq(&gcwq->lock);
kthread_bind(pool->first_idle->task, cpu);
spin_lock_irq(&gcwq->lock);
pool->flags |= POOL_MANAGE_WORKERS;
start_worker(pool->first_idle);
pool->first_idle = NULL;
}
break;
}
spin_unlock_irqrestore(&gcwq->lock, flags);
return notifier_from_errno(0);
err_destroy:
if (new_trustee)
kthread_stop(new_trustee);
spin_lock_irqsave(&gcwq->lock, flags);
for (i = 0; i < NR_WORKER_POOLS; i++)
if (new_workers[i])
destroy_worker(new_workers[i]);
spin_unlock_irqrestore(&gcwq->lock, flags);
return NOTIFY_BAD;
}
#ifdef CONFIG_SMP
struct work_for_cpu {
struct completion completion;
long (*fn)(void *);
void *arg;
long ret;
};
static int do_work_for_cpu(void *_wfc)
{
struct work_for_cpu *wfc = _wfc;
wfc->ret = wfc->fn(wfc->arg);
complete(&wfc->completion);
return 0;
}
/**
* work_on_cpu - run a function in user context on a particular cpu
* @cpu: the cpu to run on
* @fn: the function to run
* @arg: the function arg
*
* This will return the value @fn returns.
* It is up to the caller to ensure that the cpu doesn't go offline.
* The caller must not hold any locks which would prevent @fn from completing.
*/
long work_on_cpu(unsigned int cpu, long (*fn)(void *), void *arg)
{
struct task_struct *sub_thread;
struct work_for_cpu wfc = {
.completion = COMPLETION_INITIALIZER_ONSTACK(wfc.completion),
.fn = fn,
.arg = arg,
};
sub_thread = kthread_create(do_work_for_cpu, &wfc, "work_for_cpu");
if (IS_ERR(sub_thread))
return PTR_ERR(sub_thread);
kthread_bind(sub_thread, cpu);
wake_up_process(sub_thread);
wait_for_completion(&wfc.completion);
return wfc.ret;
}
EXPORT_SYMBOL_GPL(work_on_cpu);
#endif /* CONFIG_SMP */
#ifdef CONFIG_FREEZER
/**
* freeze_workqueues_begin - begin freezing workqueues
*
* Start freezing workqueues. After this function returns, all freezable
* workqueues will queue new works to their frozen_works list instead of
* gcwq->worklist.
*
* CONTEXT:
* Grabs and releases workqueue_lock and gcwq->lock's.
*/
void freeze_workqueues_begin(void)
{
unsigned int cpu;
spin_lock(&workqueue_lock);
BUG_ON(workqueue_freezing);
workqueue_freezing = true;
for_each_gcwq_cpu(cpu) {
struct global_cwq *gcwq = get_gcwq(cpu);
struct workqueue_struct *wq;
spin_lock_irq(&gcwq->lock);
BUG_ON(gcwq->flags & GCWQ_FREEZING);
gcwq->flags |= GCWQ_FREEZING;
list_for_each_entry(wq, &workqueues, list) {
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
if (cwq && wq->flags & WQ_FREEZABLE)
cwq->max_active = 0;
}
spin_unlock_irq(&gcwq->lock);
}
spin_unlock(&workqueue_lock);
}
/**
* freeze_workqueues_busy - are freezable workqueues still busy?
*
* Check whether freezing is complete. This function must be called
* between freeze_workqueues_begin() and thaw_workqueues().
*
* CONTEXT:
* Grabs and releases workqueue_lock.
*
* RETURNS:
* %true if some freezable workqueues are still busy. %false if freezing
* is complete.
*/
bool freeze_workqueues_busy(void)
{
unsigned int cpu;
bool busy = false;
spin_lock(&workqueue_lock);
BUG_ON(!workqueue_freezing);
for_each_gcwq_cpu(cpu) {
struct workqueue_struct *wq;
/*
* nr_active is monotonically decreasing. It's safe
* to peek without lock.
*/
list_for_each_entry(wq, &workqueues, list) {
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
if (!cwq || !(wq->flags & WQ_FREEZABLE))
continue;
BUG_ON(cwq->nr_active < 0);
if (cwq->nr_active) {
busy = true;
goto out_unlock;
}
}
}
out_unlock:
spin_unlock(&workqueue_lock);
return busy;
}
/**
* thaw_workqueues - thaw workqueues
*
* Thaw workqueues. Normal queueing is restored and all collected
* frozen works are transferred to their respective gcwq worklists.
*
* CONTEXT:
* Grabs and releases workqueue_lock and gcwq->lock's.
*/
void thaw_workqueues(void)
{
unsigned int cpu;
spin_lock(&workqueue_lock);
if (!workqueue_freezing)
goto out_unlock;
for_each_gcwq_cpu(cpu) {
struct global_cwq *gcwq = get_gcwq(cpu);
struct worker_pool *pool;
struct workqueue_struct *wq;
spin_lock_irq(&gcwq->lock);
BUG_ON(!(gcwq->flags & GCWQ_FREEZING));
gcwq->flags &= ~GCWQ_FREEZING;
list_for_each_entry(wq, &workqueues, list) {
struct cpu_workqueue_struct *cwq = get_cwq(cpu, wq);
if (!cwq || !(wq->flags & WQ_FREEZABLE))
continue;
/* restore max_active and repopulate worklist */
cwq->max_active = wq->saved_max_active;
while (!list_empty(&cwq->delayed_works) &&
cwq->nr_active < cwq->max_active)
cwq_activate_first_delayed(cwq);
}
for_each_worker_pool(pool, gcwq)
wake_up_worker(pool);
spin_unlock_irq(&gcwq->lock);
}
workqueue_freezing = false;
out_unlock:
spin_unlock(&workqueue_lock);
}
#endif /* CONFIG_FREEZER */
static int __init init_workqueues(void)
{
unsigned int cpu;
int i;
cpu_notifier(workqueue_cpu_callback, CPU_PRI_WORKQUEUE);
/* initialize gcwqs */
for_each_gcwq_cpu(cpu) {
struct global_cwq *gcwq = get_gcwq(cpu);
struct worker_pool *pool;
spin_lock_init(&gcwq->lock);
gcwq->cpu = cpu;
gcwq->flags |= GCWQ_DISASSOCIATED;
for (i = 0; i < BUSY_WORKER_HASH_SIZE; i++)
INIT_HLIST_HEAD(&gcwq->busy_hash[i]);
for_each_worker_pool(pool, gcwq) {
pool->gcwq = gcwq;
INIT_LIST_HEAD(&pool->worklist);
INIT_LIST_HEAD(&pool->idle_list);
init_timer_deferrable(&pool->idle_timer);
pool->idle_timer.function = idle_worker_timeout;
pool->idle_timer.data = (unsigned long)pool;
setup_timer(&pool->mayday_timer, gcwq_mayday_timeout,
(unsigned long)pool);
ida_init(&pool->worker_ida);
}
gcwq->trustee_state = TRUSTEE_DONE;
init_waitqueue_head(&gcwq->trustee_wait);
}
/* create the initial worker */
for_each_online_gcwq_cpu(cpu) {
struct global_cwq *gcwq = get_gcwq(cpu);
struct worker_pool *pool;
if (cpu != WORK_CPU_UNBOUND)
gcwq->flags &= ~GCWQ_DISASSOCIATED;
for_each_worker_pool(pool, gcwq) {
struct worker *worker;
worker = create_worker(pool, true);
BUG_ON(!worker);
spin_lock_irq(&gcwq->lock);
start_worker(worker);
spin_unlock_irq(&gcwq->lock);
}
}
system_wq = alloc_workqueue("events", 0, 0);
system_long_wq = alloc_workqueue("events_long", 0, 0);
system_nrt_wq = alloc_workqueue("events_nrt", WQ_NON_REENTRANT, 0);
system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND,
WQ_UNBOUND_MAX_ACTIVE);
system_freezable_wq = alloc_workqueue("events_freezable",
WQ_FREEZABLE, 0);
system_nrt_freezable_wq = alloc_workqueue("events_nrt_freezable",
WQ_NON_REENTRANT | WQ_FREEZABLE, 0);
system_power_efficient_wq = alloc_workqueue("events_power_efficient",
WQ_POWER_EFFICIENT, 0);
system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient",
WQ_FREEZABLE | WQ_POWER_EFFICIENT,
0);
BUG_ON(!system_wq || !system_long_wq || !system_nrt_wq ||
!system_unbound_wq || !system_freezable_wq ||
!system_nrt_freezable_wq ||
!system_power_efficient_wq ||
!system_freezable_power_efficient_wq);
return 0;
}
early_initcall(init_workqueues);
| Java |
/**
* @version 1.0.0
* @package YPR - YouTube Playlist Reader
* @author Fotis Evangelou - http://nuevvo.gr
* @copyright Copyright (c) 2010 - 2012 Nuevvo Webware Ltd. All rights reserved.
* @license GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
*/
ul.yprList {list-style:none;padding:8px 0;margin:0;}
ul.yprList li {float:left;width:310px;padding:5px;margin:0;text-align:center;}
ul.yprList li img {display:block;border:5px solid #ccc;width:300px;height:auto;}
| Java |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- Taken from from http://easy-code.ru/lesson/formatting-numeric-output-java -->
<!-- Edited by Dushen Alexey on 05.08.2014 https://github.com/blacky0x0/java-docs-ru -->
<title>Formatting Numeric Print Output (The Java™ Tutorials >
Learning the Java Language > Numbers and Strings)
</title>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<meta name="description" content="This beginner Java tutorial describes fundamentals of programming in the Java programming language" />
<meta name="keywords" content="java programming, learn java, java sample code, java objects, java classes, java inheritance, interfaces, variables, arrays, data types, operators, control flow, number, string" />
<style type="text/css">
.FigureCaption {
margin-left: 1in;
margin-right: 1in;
font-family: sans-serif;
font-size: smaller;
text-align: justify;
}
#TopBar_bl {
background: url(../../images/java_bar_bl.gif) 0 100% no-repeat;
width: 100%;
height: 60px;
}
#TopBar_br {
background: url(../../images/java_bar_br.gif) 100% 100% no-repeat;
width: 100%;
height: 60px;
}
#TopBar_tl {
background: url(../../images/java_bar_tl.gif) 0 0 no-repeat;
width: 100%;
height: 60px;
}
#TopBar_tr {
background: url(../../images/java_bar_tr.gif) 100% 0 no-repeat;
width: 100%;
height: 60px;
}
#TopBar {
background: #35556B url(../../images/java_bar.gif);
margin: 10px 10px 0 10px;
height:60px;
min-width:700px;
color: white;
font-family: sans-serif;
font-weight: bold;
}
@media print {
#BreadCrumbs, #Download {
display: none;
}
}
#TopBar_right {
line-height: 14px;
float: right;
padding-top: 2px;
padding-right: 30px;
text-align: left;
}
@media print {
#TopBar_right {
display: none;
}
}
#TopBar_right a {
font-size: 12px;
margin: 3px;
padding: 0;
}
#TopBar a:visited, #TopBar a:link {
color: white;
text-decoration: none;
}
#TopBar a:hover, #TopBar a:active {
background-color: white;
color: #35556B;
}
#BreadCrumbs {
padding: 4px 5px 0.5em 0;
font-family: sans-serif;
float: right;
}
#BreadCrumbs a {
color: blue;
}
#BreadCrumbs a:visited, #BreadCrumbs a:link {
text-decoration: none;
}
#BreadCrumbs a:hover, #BreadCrumbs a:active {
text-decoration: underline;
}
#PageTitle {
margin: 0 5px 0.5em 0;
color: #F90000;
}
#PageContent{
margin: 0 5px 0 20px;
}
.LeftBar_shown {
width: 13em;
float: left;
margin-left: 10px;
margin-top: 4px;
margin-bottom: 2em;
margin-right: 10px;
}
@media print {
.LeftBar_shown {
display: none;
}
}
.LeftBar_hidden {
display: none;
}
#Footer {
padding-top: 10px;
padding-left: 10px;
margin-right: 10px;
}
.footertext {
font-size: 10px;
font-family: sans-serif;
margin-top: 1px;
}
#Footer2 {
padding-top: 10px;
padding-left: 10px;
margin-right: 10px;
}
.NavBit {
padding: 4px 5px 0.5em 0;
font-family: sans-serif;
}
@media print {
.NavBit {
display: none;
}
}
#TagNotes {
text-align: right;
}
@media print {
#TagNotes a:visited, #TagNotes a:link {
color: #35556B;
text-decoration: none;
}
}
#Contents a, .NavBit a, #TagNotes a {
color: blue
}
#TagNotes a:visited, #TagNotes a:link,
#Contents a:visited, #Contents a:link,
.NavBit a:visited, .NavBit a:link {
text-decoration: none;
}
#TagNotes a:hover, #TagNotes a:active,
#Contents a:hover, #Contents a:active,
.NavBit a:hover, .NavBit a:active {
text-decoration: underline;
}
#Contents {
float: left;
font-family: sans-serif;
}
@media print {
#Contents {
display: none;
}
}
@media screen {
div.PrintHeaders {
display: none;
}
}
.linkLESSON, .nolinkLESSON {
margin-left: 0.5em;
text-indent: -0.5em
}
.linkAHEAD, .nolinkAHEAD, .linkQUESTIONS, .nolinkQUESTIONS {
margin-left: 1.5em;
text-indent: -0.5em
}
.linkBHEAD, .nolinkBHEAD {
margin-left: 2.5em;
text-indent: -0.5em
}
.linkCHEAD, .nolinkCHEAD {
margin-left: 3.5em;
text-indent: -0.5em
}
.nolinkLESSON, .nolinkAHEAD, .nolinkBHEAD, .nolinkCHEAD,
.nolinkQUESTIONS {
font-weight: bold;
color: #F90000;
}
.MainFlow_indented {
margin-right: 10px;
margin-left: 15em;
margin-bottom: 2em;
}
.MainFlow_wide {
margin-right: 10px;
margin-left: 10px;
margin-bottom: 2em;
}
@media print {
.MainFlow_indented, .MainFlow_wide {
padding-top: 0;
margin-top: 10px;
margin-right: 10px;
margin-left: 0;
}
}
h1, h2, h3, h4, h5 {
color: #F90000;
font-family: sans-serif;
}
h1 {
font-weight: bold;
font-size: 20px;
}
h2 {
font-weight: bold;
font-size: 17px;
}
h3 {
font-weight: bold;
font-size: 14px;
}
h4 {
font-size: 15px;
}
h5 {
font-size: 12px;
}
#ToggleLeft {
display: none;
}
.note {
margin: 0 30px 0px 30px;
}
.codeblock {
margin: 0 30px 0px 30px;
}
.tocli {
list-style-type:none;
}
</style>
<script type="text/javascript">
/* <![CDATA[ */
function leftBar() {
var nameq = 'tutorial_showLeftBar='
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookieString = cookies[i];
while (cookieString.charAt(0) == ' ') {
cookieString = cookieString.substring(1, cookieString.length);
}
if (cookieString.indexOf(nameq) == 0) {
cookieValue = cookieString.substring(nameq.length,
cookieString.length);
return cookieValue == 'yes';
}
}
return true;
}
function showLeft(b) {
var contents = document.getElementById("LeftBar");
var main = document.getElementById("MainFlow");
var toggle = document.getElementById("ToggleLeft");
if (b) {
contents.className = "LeftBar_shown";
main.className = "MainFlow_indented";
toggle.innerHTML = "Hide TOC";
document.cookie = 'tutorial_showLeftBar=yes; path=/';
} else {
contents.className = "LeftBar_hidden";
main.className = "MainFlow_wide";
toggle.innerHTML = "Show the TOC";
document.cookie = 'tutorial_showLeftBar=no; path=/';
}
}
function toggleLeft() {
showLeft(document.getElementById("LeftBar").className ==
"LeftBar_hidden");
document.getElementById("ToggleLeft").blur();
}
function load() {
showLeft(leftBar());
document.getElementById("ToggleLeft").style.display="inline";
}
function showCode(displayCodePage, codePath) {
var codePathEls = codePath.split("/");
var currDocPathEls = location.href.split("/");
//alert ("codePathEls = " + codePathEls + "\n" + "currDocPathEls = " + currDocPathEls);
currDocPathEls.pop(); // remove file name at the end
while (codePathEls.length > 0) {
if (codePathEls[0] == "..") {
codePathEls.shift();
currDocPathEls.pop();
} else {
break;
}
}
var fullCodePath = currDocPathEls.join("/") + "/" + codePathEls.join("/");
//alert ("fullCodePath = " + fullCodePath );
if (codePath.indexOf(".java") != -1 || codePath.indexOf(".jnlp") != -1) {
window.location.href = displayCodePage + "?code=" + encodeURI(fullCodePath);
} else {
window.location.href = fullCodePath;
}
}
/* ]]> */
</script>
</head>
<body onload="load()">
<noscript>
A browser with JavaScript enabled is required for this page to operate properly.
</noscript>
<div id="TopBar"> <div id="TopBar_tr"> <div id="TopBar_tl"> <div id="TopBar_br"> <div id="TopBar_bl">
<div id="TopBar_right">
<a target="_blank"
href="http://www.oracle.com/technetwork/java/javase/downloads/java-se-7-tutorial-2012-02-28-1536013.html">Download Ebooks</a><br />
<a target="_blank"
href="http://www.oracle.com/technetwork/java/javase/downloads/index.html">Download JDK</a>
<br />
<a href="../../search.html" target="_blank">Search Java Tutorials</a>
<br />
<a href="javascript:toggleLeft()"
id="ToggleLeft">Hide TOC</a>
</div>
</div> </div> </div> </div> </div>
<div class="PrintHeaders">
<b>Курс:</b> Изучение языка Java
<br /><b>Урок:</b> Числа и строки
<br /><b>Section:</b> Numbers
</div>
<div id="LeftBar" class="LeftBar_shown">
<div id="Contents">
<div class="linkLESSON"><a href="index.html">Числа и строки</a></div>
<div class="linkAHEAD"><a href="numbers.html">Числа</a></div>
<div class="linkBHEAD"><a href="numberclasses.html">Классы чисел</a></div>
<div class="nolinkBHEAD">Форматирование вывода</div>
<div class="linkBHEAD"><a href="beyondmath.html">Beyond Basic Arithmetic</a></div>
<div class="linkBHEAD"><a href="numbersummary.html">Summary of Numbers</a></div>
<div class="linkQUESTIONS"><a href="QandE/numbers-questions.html">Вопросы и упражнения</a></div>
<div class="linkAHEAD"><a href="characters.html">Characters</a></div>
<div class="linkAHEAD"><a href="strings.html">Строки</a></div>
<div class="linkBHEAD"><a href="converting.html">Converting Between Numbers and Strings</a></div>
<div class="linkBHEAD"><a href="manipstrings.html">Работа со строками</a></div>
<div class="linkBHEAD"><a href="comparestrings.html">Сравнение строк и частей строк</a></div>
<div class="linkBHEAD"><a href="buffers.html">Класс StringBuilder</a></div>
<div class="linkBHEAD"><a href="stringsummary.html">Summary of Characters and Strings</a></div>
<div class="linkAHEAD"><a href="autoboxing.html">Autoboxing and Unboxing</a></div>
<div class="linkQUESTIONS"><a href="QandE/characters-questions.html">Вопросы и упражнения</a></div>
</div>
</div>
<div id="MainFlow" class="MainFlow_indented">
<span id="BreadCrumbs">
<a href="../../index.html" target="_top">Home Page</a>
>
<a href="../index.html" target="_top">Изучение языка Java</a>
>
<a href="index.html" target="_top">Числа и строки</a>
</span>
<div class="NavBit">
<a target="_top" href="numberclasses.html">« Previous</a> • <a target="_top" href="../TOC.html">Trail</a> • <a target="_top" href="beyondmath.html">Next »</a>
</div>
<div id="PageTitle"><h1>Форматирование вывода</h1></div>
<div id="PageContent">
<!-- Formatting Numeric Print Output -->
<p>
Earlier you saw the use of the <code>print</code> and <code>println</code> methods for printing strings to standard output (<code>System.out</code>).
Since all numbers can be converted to strings (as you will see later in this
lesson),
you can use these methods to print out an arbitrary mixture of strings and numbers.
The Java programming language has other methods, however, that allow you to exercise much more control over your print output when numbers are included.</p>
<h2>Методы printf и format</h2>
<p>
Пакет <code>java.io</code> содержит
класс
<code>PrintStream</code>, у которого есть специальные методы <code>format</code> и <code>printf</code> для форматирования.
Эти методы эквивалентны друг другу и
их можно использовать вместо <code>print</code> и <code>println</code>.
Хорошо знакомая конструкция <code>System.out</code> является объектом класса <code>PrintStream</code>,
поэтому в любом участке кода можно спокойно заменить методы <code>print</code> и <code>println</code> на
<code>format</code> или <code>printf</code>.
Например:
</p>
<div class="codeblock"><pre>
System.out.format(.....);
</pre></div>
<p>
Синтаксис этих методов класса
<a class="APILink" target="_blank" href="http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html"><code>java.io.PrintStream</code> </a>
одинаков:
</p>
<div class="codeblock"><pre>
public PrintStream format(String format, Object... args)
</pre></div>
<p>
где <code>format</code> - это строка, определяющая шаблон, согласно которому будет происходить форматирование, а
<code>args</code> - это список переменных для печати по заданному шаблону
(запись <code>Object... args</code> определяет переменное количество аргументов). Простой пример:
</p>
<div class="codeblock"><pre>
System.out.format("The value of " + "the float variable is " +
"%f, while the value of the " + "integer variable is %d, " +
"and the string is %s", floatVar, intVar, stringVar);
</pre></div>
<p>
Строка <code>format</code> содержит простой текст и специальные <em>форматирующие символы</em>,
используемые при форматировании списка объектов второго параметра <code>args</code>.
Эти символы начинаются со знака процента (%) и заканчиваются <i>конвертором</i> - символом,
который определяет тип переменной для форматирования.
Между знаком процента (%) и конвертером можно указать дополнительные флаги и спецификаторы.
Полное описание конвертеров, флагов и спецификаторов можно посмотреть по ссылке
<a class="APILink" target="_blank" href="http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html">
<code>java.util.Formatter</code></a>.
Пример:
</p>
<p>
Простенький пример:
</p>
<div class="codeblock"><pre>
int i = 461012;
System.out.format("The value of i is: %d%n", i);
</pre></div>
<p>
Спецификатор <code>%d</code> указывает на то, что переменная должна быть целым числом.
<code>%n</code> - платформенно-независимый символ перевода строки.
Вывод будет следующим:</p>
<div class="codeblock"><pre>
The value of i is: 461012
</pre></div>
<p>
Чтобы вывод соответствовал <s>региональным стандартам определенного языка</s> следует использовать
перегруженные версии методов <code>printf</code> и <code>format</code>, которые имеют следующий синтаксис:
</p>
<div class="codeblock"><pre>
public PrintStream printf(Locale l, String format, Object... args)
public PrintStream format(Locale l, String format, Object... args)
</pre></div>
<p>
Например, в качестве разделителя целой и дробной частей числа с плавающей точкой во Французской системе используется запятая,
в то время как в Английской используется точка:</p>
<div class="codeblock"><pre>
System.out.format(Locale.FRANCE,
"The value of the float " + "variable is %f, while the " +
"value of the integer variable " + "is %d, and the string is %s%n",
floatVar, intVar, stringVar);
</pre></div>
<h2>Пример</h2>
<p>
В таблице перечислены некоторые конвертеры и флаги, которые были использованы в программе <code>TestFormat.java</code>
</p>
<table width="70%" border="1" cellpadding="4" cellspacing="3"
summary="Converters and flags that are used in the sample program TestFormat.java">
<caption style="font-weight: bold">Конвертеры и флаги, использованные в <code>TestFormat.java</code></caption>
<tr>
<th id="h1" width="10%">Конвертер</th>
<th id="h2" width="10%">Флаг</th>
<th id="h3" width="50%">Описание</th>
</tr>
<tr>
<td headers="h1">d</td>
<td headers="h2"> </td>
<td headers="h3">
Десятичное целое
</td>
</tr>
<tr>
<td headers="h1">f</td>
<td headers="h2"> </td>
<td headers="h3">
Число с плавающей точкой (float)
</td>
</tr>
<tr>
<td headers="h1">n</td>
<td headers="h2"> </td>
<td headers="h3">
Символ новой строки в зависимости от платформы, на которой запущена программа.
Старайтесь всегда использовать <code>%n</code>, а не <code>\n</code>
</td>
</tr>
<tr>
<td headers="h1">tB</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время—полное название месяца в зависимости от языка
</td>
</tr>
<tr>
<td headers="h1">td, te</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время — 2 цифры дня месяца. td - с ведущими нулями, te - без
</td>
</tr>
<tr>
<td headers="h1">ty, tY</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время —ty = год из 2-х цифр, tY = год из 4-х цифр
</td>
</tr>
<tr>
<td headers="h1">tl</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время— часы в 12-ти часовом формате
</td>
</tr>
<tr>
<td headers="h1">tM</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время— минуты из 2-х цифр с ведущими нулями
</td>
</tr>
<tr>
<td headers="h1">tp</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время — am/pm в зависимости от языка (в нижнем регистре)
</td>
</tr>
<tr>
<td headers="h1">tm</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время — месяц из 2-х цифр с ведущими нулями
</td>
</tr>
<tr>
<td headers="h1">tD</td>
<td headers="h2"> </td>
<td headers="h3">
Дата и время — дата в формате %tm%td%ty
</td>
</tr>
<tr>
<td headers="h1"> </td>
<td headers="h2">08</td>
<td headers="h3">
Восемь символов в ширину, дозаполняя ведущими нулями по необходимости
</td>
</tr>
<tr>
<td headers="h1"> </td>
<td headers="h2">+</td>
<td headers="h3">
Включить знак (положительный или отрицательный)
</td>
</tr>
<tr>
<td headers="h1"> </td>
<td headers="h2">,</td>
<td headers="h3">
Включить специфичную для каждой локали группировку символов
</td>
</tr>
<tr>
<td headers="h1"> </td>
<td headers="h2">-</td>
<td headers="h3">
Выравнивание по левому краю
</td>
</tr>
<tr>
<td headers="h1"> </td>
<td headers="h2">.3</td>
<td headers="h3">
Три символа после десятичного разделителя
</td>
</tr>
<tr>
<td headers="h1"> </td>
<td headers="h2">10.3</td>
<td headers="h3">
Десять символов в ширину, выравнивание по правому краю, три символа после десятичного разделителя
</td>
</tr>
</table>
<p>
В программе показаны несколько примеров форматирования с использованием метода <code>format</code>.
Вывод показан в комментариях:</p>
<div class="codeblock"><pre>
import java.util.Calendar;
import java.util.Locale;
public class TestFormat {
public static void main(String[] args) {
long n = 461012;
System.out.format("%d%n", n); // --> "461012"
System.out.format("%08d%n", n); // --> "00461012"
System.out.format("%+8d%n", n); // --> " +461012"
System.out.format("%,8d%n", n); // --> " 461,012"
System.out.format("%+,8d%n%n", n); // --> "+461,012"
double pi = Math.PI;
System.out.format("%f%n", pi); // --> "3.141593"
System.out.format("%.3f%n", pi); // --> "3.142"
System.out.format("%10.3f%n", pi); // --> " 3.142"
System.out.format("%-10.3f%n", pi); // --> "3.142"
System.out.format(Locale.FRANCE,
"%-10.4f%n%n", pi); // --> "3,1416"
Calendar c = Calendar.getInstance();
System.out.format("%tB %te, %tY%n", c, c, c); // --> "May 29, 2006"
System.out.format("%tl:%tM %tp%n", c, c, c); // --> "2:34 am"
System.out.format("%tD%n", c); // --> "05/29/06"
}
}
</pre></div>
<div class="note"><hr /><strong>Примечание:</strong>
в этой главе показаны основы работы с методами <code>format</code> и <code>printf</code>.
Более подробно о форматировании рассказано в главе, посвященной
<a class="TutorialLink" target="_top" href="../../essential/io/formatting.html"><code>основам ввода/вывода</code></a>.<br />
О создании строк при помощи метода <code>String.format</code> рассказано в главе, посвященной
<a class="TutorialLink" target="_top" href="strings.html">строкам</a>.
<hr /></div>
<h2>Класс DecimalFormat</h2>
<p>
You can use the
<a class="APILink" target="_blank" href="http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html"><code>java.text.DecimalFormat</code> </a> class to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator.
<code>DecimalFormat</code> offers a great deal of flexibility in the formatting of numbers, but it can make your code more complex.</p>
<p>
The example that follows creates a <code>DecimalFormat</code> object, <code>myFormatter</code>, by passing a pattern string to the <code>DecimalFormat</code> constructor.
The <code>format()</code> method, which <code>DecimalFormat</code> inherits from <code>NumberFormat</code>, is then invoked by <code>myFormatter</code>—it accepts a <code>double</code> value as an argument and returns the formatted number in a string:</p>
<p>
Here is a sample program that illustrates the use of <code>DecimalFormat</code>:</p>
<div class="codeblock"><pre>
import java.text.*;
public class DecimalFormatDemo {
static public void customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
}
static public void main(String[] args) {
customFormat("###,###.###", 123456.789);
customFormat("###.##", 123456.789);
customFormat("000000.000", 123.78);
customFormat("$###,###.###", 12345.67);
}
}
</pre></div>
<p>
Вывод будет следующим:</p>
<div class="codeblock"><pre>
123456.789 ###,###.### 123,456.789
123456.789 ###.## 123456.79
123.78 000000.000 000123.780
12345.67 $###,###.### $12,345.67
</pre></div>
<p>
В таблице даны пояснения к каждой выведенной строке:
</p>
<table width="100%" border="1" cellpadding="4" cellspacing="3" summary="DecimalFormatDemo.java output">
<caption style="font-weight: normal">Вывод <code>DecimalFormat.java</code></caption>
<tr>
<th id="h101">Значение</th>
<th id="h102">Шаблон</th>
<th id="h103">Вывод</th>
<th id="h104">Пояснение</th>
</tr>
<tr>
<td headers="h101">123456.789</td>
<td headers="h102">###,###.###</td>
<td headers="h103">123,456.789</td>
<td headers="h104">Знак решетки (в Англии # является знаком фунта - 'pound sign') обозначает цифру,
а точка и запятая являются символами-заполнителями. Первый из которых - это десятичный разделитель,
а второй служит для группировки чисел.
</td>
</tr>
<tr>
<td headers="h101">123456.789</td>
<td headers="h102">###.##</td>
<td headers="h103">123456.79</td>
<td headers="h104">
В дробной части используемого значения указаны три цифры, а в шаблоне для дробной части используется только два разряда.
В этому случает метод <code>format</code> сделает необходимое округление.
</td>
</tr>
<tr>
<td headers="h101">123.78</td>
<td headers="h102">000000.000</td>
<td headers="h103">000123.780</td>
<td headers="h104">
Символ 0 можно использовать вместо знака решетки (или знак фунта - #), тогда форматируемое число будет дополнено нулями в начале и конце.
</td>
</tr>
<tr>
<td headers="h101">12345.67</td>
<td headers="h102">$###,###.###</td>
<td headers="h103">$12,345.67</td>
<td headers="h104">Первым знаком в шаблоне идет знак доллара ($).
Обратите внимание на то, что он выводится перед цифрами.
</td>
</tr>
</table>
</div>
<div class="NavBit">
<a target="_top" href="numberclasses.html">« Previous</a>
•
<a target="_top" href="../TOC.html">Trail</a>
•
<a target="_top" href="beyondmath.html">Next »</a>
</div>
</div>
<div id="Footer2">
<hr />
<div id="TagNotes">
<p class="footertext">Problems with the examples? Try <a target="_blank"
href="../../information/run-examples.html">Compiling and Running
the Examples: FAQs</a>.
<br />
Complaints? Compliments? Suggestions? <a target="_blank"
href="http://docs.oracle.com/javase/feedback.html">Give
us your feedback</a>.
</p>
</div>
<div id="Footer">
<p class="footertext"><a name="license_info">Your use of this</a> page and all the material on pages under "The Java Tutorials" banner
is subject to these <a href="../../information/cpyr.html">legal notices</a>.
</p>
<table border="0" cellspacing="0" cellpadding="5" summary="">
<tr>
<td width="20%">
<table width="100%" border="0" cellspacing="0" cellpadding="5">
<tr>
<td headers="h201" align="center"><img id="duke" src="../../images/DukeWave.gif" width="55" height="55" alt="duke image" /></td>
<td headers="h202" align="left" valign="middle"><img id="oracle" src="../../images/logo_oracle_footer.gif" width="100" height="29" alt="Oracle logo" /></td>
</tr>
</table>
</td>
<td width="55%" valign="middle" align="center">
<p class="footertext"><a href="http://www.oracle.com/us/corporate/index.html">About Oracle</a> | <a href="http://www.oracle.com/technology/index.html">Oracle Technology Network</a> | <a href="http://www.oracle.com/us/legal/terms/index.html">Terms of Use</a></p>
</td>
<td width="25%" valign="middle" align="right">
<p class="footertext">Copyright © 1995, 2012 Oracle and/or its affiliates.
All rights reserved.</p>
</td>
</tr>
</table>
</div>
</div>
<div class="PrintHeaders">
<b>Previous page:</b> The Numbers Classes
<br /><b>Next page:</b> Beyond Basic Arithmetic
</div>
</body>
</html>
| Java |
## Xrt3d.pm is a sub-module of Graph.pm. It has all the subroutines
## needed for the Xrt3d part of the package.
##
## $Id: Xrt3d.pm,v 1.30 2006/06/07 21:09:33 emile Exp $ $Name: $
##
## This software product is developed by Michael Young and David Moore,
## and copyrighted(C) 1998 by the University of California, San Diego
## (UCSD), with all rights reserved. UCSD administers the CAIDA grant,
## NCR-9711092, under which part of this code was developed.
##
## There is no charge for this software. You can redistribute it and/or
## modify it under the terms of the GNU General Public License, v. 2 dated
## June 1991 which is incorporated by reference herein. This software is
## distributed WITHOUT ANY WARRANTY, IMPLIED OR EXPRESS, OF MERCHANTABILITY
## OR FITNESS FOR A PARTICULAR PURPOSE or that the use of it will not
## infringe on any third party's intellectual property rights.
##
## You should have received a copy of the GNU GPL along with this program.
##
##
## IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY
## PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
## DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS
## SOFTWARE, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF
## THE POSSIBILITY OF SUCH DAMAGE.
##
## THE SOFTWARE PROVIDED HEREIN IS ON AN "AS IS" BASIS, AND THE
## UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE,
## SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. THE UNIVERSITY
## OF CALIFORNIA MAKES NO REPRESENTATIONS AND EXTENDS NO WARRANTIES
## OF ANY KIND, EITHER IMPLIED OR EXPRESS, INCLUDING, BUT NOT LIMITED
## TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
## PARTICULAR PURPOSE, OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE
## ANY PATENT, TRADEMARK OR OTHER RIGHTS.
##
##
## Contact: graph-dev@caida.org
##
##
package Chart::Graph::Xrt3d;
use Exporter ();
@ISA = qw(Exporter);
@EXPORT = qw();
@EXPORT_OK = qw(&xrt3d);
use FileHandle; # to create generic filehandles
use Carp; # for carp() and croak()
use Chart::Graph::Utils qw(:UTILS); # get global subs and variables
use Chart::Graph::XrtUtils qw(:UTILS);
$cvs_Id = '$Id: Xrt3d.pm,v 1.30 2006/06/07 21:09:33 emile Exp $';
$cvs_Author = '$Author: emile $';
$cvs_Name = '$Name: $';
$cvs_Revision = '$Revision: 1.30 $';
$VERSION = 3.2;
use strict;
#
# xrt graphing package
#
my %def_xrt_global_opts; # xrt specific globals
%def_xrt_global_opts = (
"output file" => "untitled-xrt3d.gif",
"output type" => "gif",
"x-axis title" => "x-axis",
"y-axis title" => "y-axis",
"z-axis title" => "z-axis",
"x-min" => "0",
"y-min" => "0",
"x-step" => "1",
"y-step" => "1",
"x-ticks" => undef,
"y-ticks" => undef,
"header" => ["header"],
"footer" => ["footer"],
);
#
#
# Subroutine: xrt()
#
# Description: this is the main function you will be calling from
# our scripts. please see
# www.caida.org/Tools/Graph/ for a full description
# and how-to of this subroutine
#
sub xrt3d {
my $user_global_opts_ref = shift;
my $data_set_ref = shift;
my $matrix_data_ref;
my $data_filename;
my (%global_opts);
# variables to be written to the command file
my ($plot_file, $x_axis, $y_axis, $z_axis, $x_step, $y_step);
my ($x_min, $y_min, $x_ticks, $y_ticks, $header, $footer);
my ($x_cnt, $y_cnt, $hdr_cnt, $ftr_cnt);
my ($output_file);
if (@_) {
carp 'Too many arguments. Usage: xrt3d(\%options, \@data_set)';
return 0;
}
_make_tmpdir("_Xrt3d_");
# set paths for external programs
if (not _set_xrtpaths("xrt3d")) {
_cleanup_tmpdir();
return 0;
}
# check first arg for hash
if (ref($user_global_opts_ref) ne "HASH") {
carp "Global options must be a hash.";
_cleanup_tmpdir();
return 0;
}
# call to combine user options with default options
%global_opts = _mesh_opts($user_global_opts_ref, \%def_xrt_global_opts);
# check for values in command file
while (my ($key, $value) = each %global_opts) {
if ($key eq "output file") {
$output_file = $value;
unless (defined $global_opts{"output type"}) {
carp "Must have an output type defined";
_cleanup_tmpdir();
return 0;
}
}
# If the file is PostScript ... what XRT makes is PostScript
if ($global_opts{"output type"} eq "ps") {
$plot_file = _make_tmpfile("plot", "ps");
}
# For all raster formats XRT starts out with
# X-Windows XWD format.
elsif (($global_opts{"output type"} eq "gif") or
($global_opts{"output type"} eq "xwd") or
($global_opts{"output type"} eq "png") or
($global_opts{"output type"} eq "jpg")
) {
$plot_file = _make_tmpfile("plot", "xwd");
} else {
# Default is XWD
carp "Unknown output type, defaulting to xwd";
$plot_file = _make_tmpfile("plot", "xwd");
}
if ($key eq "x-axis title") {
if(defined($value)) {
$x_axis = $value;
}
}
if ($key eq "y-axis title") {
if(defined($value)) {
$y_axis = $value;
}
}
if ($key eq "z-axis title") {
if(defined($value)) {
$z_axis = $value;
}
}
if ($key eq "x-min") {
if(defined($value)) {
$x_min = $value;
}
}
if ($key eq "y-min") {
if(defined($value)) {
$y_min = $value;
}
}
if ($key eq "x-step") {
if(defined($value)) {
$x_step = $value;
}
}
if ($key eq "y-step") {
if(defined($value)) {
$y_step = $value;
}
}
if ($key eq "x-ticks") {
if(defined($value)) {
$x_ticks = $value;
}
}
if ($key eq "y-ticks") {
if(defined($value)) {
$y_ticks = $value;
}
}
if ($key eq "header") {
if(defined($value)) {
$header = $value;
}
}
if ($key eq "footer") {
if(defined($value)) {
$footer = $value;
}
}
}
# Extract options for data.
my $data_opts = shift @{$data_set_ref};
while (my ($key, $value) = each %{$data_opts}) {
if ($key eq "type") {
if ($value eq "matrix") {
$matrix_data_ref = $data_set_ref;
}
elsif ($value eq "file") {
$data_filename = pop @{$data_set_ref};
} else {
carp "Unsupported or unknown format for data";
}
}
}
# because xrt allows multiline headers
# get the length of the header array
# each line of the header is one index
# in the array
$hdr_cnt = $#{$global_opts{"header"}} + 1;
$ftr_cnt = $#{$global_opts{"footer"}} + 1;
if (defined($matrix_data_ref)) {
# get the number of columns and number of rows
# and verify that each row has same number of
# columns
$x_cnt = $#{$matrix_data_ref} + 1;
my $tmp = $#{$matrix_data_ref->[0]} + 1;
foreach my $i (@{$matrix_data_ref}) {
if ($tmp != $#{$i} + 1) {
carp "each row must have the same number of columns";
_cleanup_tmpdir();
return 0;
}
}
$y_cnt = $tmp;
# verify that number of tick marks == corresponds
# to that of xy matrix. One tick mark for every x
# y.
if (not _verify_ticks($x_cnt, $global_opts{"x-ticks"})) {
_cleanup_tmpdir();
return 0;
}
if (not _verify_ticks($y_cnt, $global_opts{"y-ticks"})) {
_cleanup_tmpdir();
return 0;
}
} else {
# XXX
# Poor man's hack to compute rows and columns in data file. This will
# make a second pass through file, but is probably faster than doing it
# in Perl.
my ($lead, $words, $bytes);
($lead, $x_cnt, $words, $bytes) = split(/\D+/, `wc $data_filename`);
if (($x_cnt > 0) and ($words > 0)) {
$x_cnt++;
$y_cnt = $words/$x_cnt;
} else {
$x_cnt = 0;
$y_cnt = 0;
carp "Cannot compute number of rows and/or columns in file data";
}
}
##
## print command file using this format
##
# output.file
# x_min (normally 0)
# y_min (normally 0)
# x_step (normally 1)
# y_step (normally 1)
# x_cnt (number of rows of input)
# y_cnt (number of columns of input)
# data11 data12 data13 data14 .... (x by y matrix of doubles)
# data21 data22 data23 ....
# .
# .
# .
# datax1 datax2 ... dataxy
# Number of header lines (multiple header lines available)
# header1
# header2
# ...
# Number of header lines (multiple header lines available)
# foot1
# foot2
# ...
# Title of x-axis
# Title of y-axis
# Title of z-axis
# xlabel0 (x_cnt number of labels for ticks along x-axis)
# ...
# xlabelx
# ylabel0 (y_cnt number of labels for ticks along y-axis)
# ...
# ylabely
# create command file and open file handle
my $command_file = _make_tmpfile("command");
my $handle = new FileHandle;
if (not $handle->open(">$command_file")) {
carp "could not open $command_file";
_cleanup_tmpdir();
return 0;
}
print $handle "$plot_file\n";
print $handle "$x_min\n";
print $handle "$y_min\n";
print $handle "$x_step\n";
print $handle "$y_step\n";
print $handle "$x_cnt\n";
print $handle "$y_cnt\n";
if (defined($matrix_data_ref)) {
_print_matrix($handle, @{$matrix_data_ref});
} else {
_transfer_file($handle, $data_filename)
}
print $handle "$hdr_cnt\n";
_print_array($handle, @{$header});
print $handle "$ftr_cnt\n";
_print_array($handle, @{$footer});
print $handle "$x_axis\n";
print $handle "$y_axis\n";
print $handle "$z_axis\n";
_print_array($handle, @{$x_ticks});
_print_array($handle, @{$y_ticks});
$handle->close();
# call xrt and convert file to gif
if (not _exec_xrt3d($command_file)) {
_cleanup_tmpdir();
return 0;
}
my $graph_format = $global_opts{"output type"};
if ($graph_format eq "ps") {
if (not _chk_status(system("cp $plot_file $output_file"))) {
_cleanup_tmpdir();
return 0;
}
} elsif ($graph_format eq "xwd") {
if (not _chk_status(system("cp $plot_file $output_file"))) {
_cleanup_tmpdir();
return 0;
}
} else {
if(not _convert_raster($graph_format, $plot_file, $output_file)) {
_cleanup_tmpdir();
return 0;
}
}
_cleanup_tmpdir();
return 1;
}
1;
__END__
=head1 NAME
Chart::Graph::Xrt3d
=head1 SYNOPSIS
#Include module
use Chart::Graph::Xrt3d qw(xrt3d);
# Function call
xrt3d(\%options,
\@data_set
);
=head1 DESCRIPTION
This module is unmaintained, it worked with Sitraka's XRT, and hasn't been
tested against newer versions.
Sitraka (now Quest) makes a number of graphics packages for UNIX systems. XRT is
a Motif-based commercial software product that has been adapted by
CAIDA using a combination of C drivers and Perl function I<xrt3d()>.
The Perl function I<xrt3d()> provides access to the three dimensional
graphing capabilities of XRT from Perl. To access the two dimensional
graphing using XRT, use I<xrt2d()> also supplied in the
I<Chart::Graph> package.
=head1 ARGUMENTS
The options to I<xrt3d()> are listed below. Additional control over the
resulting graph is possible by using the XRT application itself once
the graph has been created.
+--------------------------------------------------------------------------+
| OPTIONS |
+----------------+--------------------------+------------------------------+
| Name | Options | Default |
|"output file" | (set your own) | "untitled-xrt3d.gif" |
|"output type" | "ps","xwd", "png", "jpg"| "xwd" |
|"x-axis title" | (set your own) | "x-axis" |
|"y-axis title" | (set your own) | "y-axis" |
|"z-axis title" | (set your own) | "z-axis" |
|"x-min" | "0" or "1"(normally 0) | "0" |
|"y-min" | "0" or "1"(normally 0) | "0" |
|"x-step" | "0" or "1"(normally 1) | "1" |
|"y-step" | "0" or "1"(normally 1) | "1" |
|"x-ticks" | (set your own) | none |
|"y-ticks" | (set your own) | none |
|"header" | (set your own) | Array ref of "header" text |
|"footer" | (set your own) | Array ref of "footer" text |
+----------------+--------------------------+------------------------------+
The I<xrt3d> function only accepts data in one of two forms. The
choices are: either C<[\%data1_opts, \@data_matrix]> or
C<[\%data1_opts, "filename"]> The data options are listed below.
+--------------------------------------------------------------------------+
| DATA OPTIONS |
+----------------+--------------------------+------------------------------+
| Name | Options | Default |
+----------------+--------------------------+------------------------------+
| "type" | Data format: "matrix" or | none |
| | "file" | |
+----------------+--------------------------+------------------------------+
=head2 DETAILS ON GRAPHICS CONVERTER OPTIONS
The xrt package supports only two graphics formats internally:
Postscript and the X windows format XWD. Additional raster graphics
formats are supported with Chart::Graph by using one of two graphics
converter packages: I<Imagemagick> and I<Netpbm>.
If you need to install a converter package,I<Imagemagick>
I<http://www.imagemagick.org/> is probably preferable
simply for its comparatively simplicity. It uses one program
I<convert> for all of it's conversion needs, so it is easy to manage
and simple for Chart::Graph to use. Many UNIX systems come with some
collection of the I<Netpbm> utilities already installed, thus users
may be able to start using Chart::Graph without adding any additional
converters. Alas, it is unlikely any distributions would include all
the converters for the newest graphics formats used by Chart::Graph.
In that case it may still preferable to use I<Imagemagick> simply for
the sake of avoiding installing over 80 utilities that come with
current distributions of I<Netpbm>. For more information on the
current distribution of I<Netpbm> go to the current website at:
I<http://netpbm.sourceforge.net/>
The xrt package also allows for multiple header and footers with each
graph. As a result, instead of just the usual string, an array
reference containing the multiple strings for the header and footer
text.
=head1 EXAMPLES
The following four examples show Chart::Graph::Xrt3d in different roles
and producing different styles of output.
=head2 EXAMPLE: STOCK PRICES FOR JOE'S RESTAURANT
The first example creates a three dimensional bar chart of
fictitious stock data that is displayed in the graphic file
F<xrt3d-1.gif>. Note that I<xrt3d()> uses the older gif file format,
but can use others as noted above if you have the available converters
provided.
#make sure to include Chart::Graph
use Chart::Graph::Xrt3d qw(xrt3d);
#using a 3 by 6 matrix for the data set
xrt3d({"output file" => "xrt3d-1.gif",
"output type" => "gif",
"header" =>
["Stock prices for Joe's restaurant chain",
"Compiled from local records"
],
"footer" =>
["Joe's Restaurant"],
"y-ticks"=>["Jan/Feb", "Mar/Apr", "May/Jun", "Jul/Aug",
"Sep/Oct", "Nov/Dec"],
"x-axis title" => "Years monitored",
"y-axis title" => "Month's tracked",
"z-axis title" => "Stock prices",
},
[{"type" => "matrix"},
["4", "5", "3", "6", "6", "5"],
["8", "13", "20", "45", "100", "110" ],
["70", "45", "10", "5", "4", "3"]])
=for html
<p><center><img src="http://www.caida.org/tools/utilities/graphing/xrt3d-1.jpg"></center></p>
<p><center><em>xrt3d-1.jpg</em></center></p>
=head2 EXAMPLE: EARLY GROWTH OF THE INTERNET
The following example creates a three dimensional bar chart of data
collected on the early growth of the Internet (URL and corporate
source included on graph.) The result in this case is display in one
of the newest graphics formats the PNG format: F<xrt3d-2.png>.
#make sure to include Chart::Graph
use Chart::Graph::Xrt3d qw(xrt3d);
xrt3d({"output file" => "xrt3d-2.png",
"output type" => "png",
"header" =>
["Growth of Early Internet",
"(according to Internet Wizards - http://www.nw.com/)",
],
"footer" =>
["http://www.mit.edu/people/mkgray/net/internet-growth-raw-data.html"],
"y-ticks"=>["Jan 93", "Apr 93", "Jul 93",
"Oct 93", "Jan 94", "Jul 94",
"Oct 94", "Jan 95", "Jul 95",
"Jan 96"
],
"x-ticks"=>["Hosts", "Domains", "Replied to Ping"],},
[{"type" => "matrix"},
["1.3e6", "1.5e6", "1.8e6", "2.1e6", "2.2e6", "3.2e6",
"3.9e6","4.9e6", "6.6e6", "9.5e6"
],
["21000","22000", "26000", "28000", "30000", "46000",
"56000", "71000", "120000", "240000"
],
["NA", "0.4e6", "NA", "0.5e6", "0.6e6", "0.7e6",
"1.0e6", "1.0e6", "1.1e6", "1.7e6"
]
]
);
=for html
<p><center><img src="http://www.caida.org/tools/utilities/graphing/xrt3d-2.png"></center></p>
<p><center><em>xrt3d-2.png</em></center></p>
=head2 EXAMPLE: USING A DATA FILE FOR INPUT
The next example uses a file instead of a array for it's data source.
The file is listed below the Perl code.
#make sure to include Chart::Graph
use Chart::Graph::Xrt3d qw(xrt3d);
if (xrt3d({"output file" => "xrt3d-3.gif",
"output type" => "gif",
"x-ticks"=>["a", "b", "c"],
"y-ticks"=>["w", "x", "y", "z"],},
[{"type" => "file"},
"xrt3d_data.txt"])) {
print "ok\n";
} else {
print "not ok\n";
}
The data file used in the above example is as follows.
10 15 23 10
4 13 35 45
29 15 64 24
=for html
<p><center><img src="http://www.caida.org/tools/utilities/graphing/xrt3d-3.gif"></center></p>
<p><center><em>xrt3d-3.gif</em></center></p>
=head1 MORE INFO
For more information on XRT:
http://www.quest.com/xrt_pds/
=head1 CONTACT
Send email to graph-dev@caida.org is you have problems, questions,
or comments. To subscribe to the mailing list send mail to
graph-dev-request@caida.org with a body of "subscribe your@email.com"
=head1 AUTHOR
CAIDA Perl development team (cpan@caida.org)
=cut
| Java |
package mx.gob.sct.utic.mimappir.admseg.postgreSQL.services;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import mx.gob.sct.utic.mimappir.admseg.postgreSQL.model.SEGUSUARIO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
/**
* A custom service for retrieving users from a custom datasource, such as a
* database.
* <p>
* This custom service must implement Spring's {@link UserDetailsService}
*/
@Transactional(value="transactionManager_ADMSEG_POSGIS",readOnly=true)
public class CustomUserDetailsService implements UserDetailsService{
private SEGUSUARIO_Service SEGUSUARIO_Service;
//private UserDAO userDAO2 = new UserDAO();
/**
* Retrieves a user record containing the user's credentials and access.
*/
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
// Declare a null Spring User
UserDetails user = null;
try {
// Search database for a user that matches the specified username
// You can provide a custom DAO to access your persistence layer
// Or use JDBC to access your database
// DbUser is our custom domain user. This is not the same as
// Spring's User
List<SEGUSUARIO> registros = SEGUSUARIO_Service.getUsuario(username);
//List<SEGUSUARIO> registros = SEGUSUARIO_Service.getUsuariosList();
Iterator<SEGUSUARIO> it = registros.iterator();
SEGUSUARIO dbUser = null;
while(it.hasNext()){
dbUser = it.next();
}
// Populate the Spring User object with details from the dbUser
// Here we just pass the username, password, and access level
// getAuthorities() will translate the access level to the correct
// role type
user = new User(dbUser.getCUSUARIO(), dbUser.getCPASSWORD(), true, true,
true, true, getAuthorities(0));
} catch (Exception e) {
throw new UsernameNotFoundException("Error in retrieving user");
}
// Return user to Spring for processing.
// Take note we're not the one evaluating whether this user is
// authenticated or valid
// We just merely retrieve a user that matches the specified username
return user;
}
/**
* Retrieves the correct ROLE type depending on the access level, where
* access level is an Integer. Basically, this interprets the access value
* whether it's for a regular user or admin.
*
* @param access
* an integer value representing the access of the user
* @return collection of granted authorities
*/
public Collection<GrantedAuthority> getAuthorities(Integer access) {
// Create a list of grants for this user
List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);
// All users are granted with ROLE_USER access
// Therefore this user gets a ROLE_USER by default
authList.add(new GrantedAuthorityImpl("ROLE_USER"));
// Check if this user has admin access
// We interpret Integer(1) as an admin user
if (access.compareTo(1) == 0) {
// User has admin access
authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
}
// Return list of granted authorities
return authList;
}
@Autowired
public void setMenuService(SEGUSUARIO_Service service) {
this.SEGUSUARIO_Service = service;
}
} | Java |
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>translate.storage.pypo</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="translate-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http://translate.sourceforge.net/wiki/toolkit/index">Translate Toolkit</a></th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="translate-module.html">Package translate</a> ::
<a href="translate.storage-module.html">Package storage</a> ::
Module pypo
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="translate.storage.pypo-module.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== MODULE DESCRIPTION ==================== -->
<h1 class="epydoc">Module pypo</h1><p class="nomargin-top"><span class="codelink"><a href="translate.storage.pypo-pysrc.html">source code</a></span></p>
<p>classes that hold units of .po files (pounit) or entire files (pofile)
gettext-style .po (or .pot) files are used in translations for KDE et al
(see kbabel)</p>
<!-- ==================== CLASSES ==================== -->
<a name="section-Classes"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Classes</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Classes"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="translate.storage.pypo.pounit-class.html" class="summary-name">pounit</a>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="translate.storage.pypo.pofile-class.html" class="summary-name">pofile</a><br />
A .po file containing various units
</td>
</tr>
</table>
<!-- ==================== FUNCTIONS ==================== -->
<a name="section-Functions"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Functions</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Functions"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="translate.storage.pypo-module.html#escapeforpo" class="summary-sig-name">escapeforpo</a>(<span class="summary-sig-arg">line</span>)</span><br />
Escapes a line for po format.</td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#escapeforpo">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="unescapehandler"></a><span class="summary-sig-name">unescapehandler</span>(<span class="summary-sig-arg">escape</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#unescapehandler">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="wrapline"></a><span class="summary-sig-name">wrapline</span>(<span class="summary-sig-arg">line</span>)</span><br />
Wrap text for po files.</td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#wrapline">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="quoteforpo"></a><span class="summary-sig-name">quoteforpo</span>(<span class="summary-sig-arg">text</span>)</span><br />
quotes the given text for a PO file, returning quoted and escaped
lines</td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#quoteforpo">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="translate.storage.pypo-module.html#extractpoline" class="summary-sig-name">extractpoline</a>(<span class="summary-sig-arg">line</span>)</span><br />
Remove quote and unescape line from po file.</td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#extractpoline">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="unquotefrompo"></a><span class="summary-sig-name">unquotefrompo</span>(<span class="summary-sig-arg">postr</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#unquotefrompo">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="is_null"></a><span class="summary-sig-name">is_null</span>(<span class="summary-sig-arg">lst</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#is_null">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="extractstr"></a><span class="summary-sig-name">extractstr</span>(<span class="summary-sig-arg">string</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="translate.storage.pypo-pysrc.html#extractstr">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- ==================== VARIABLES ==================== -->
<a name="section-Variables"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Variables</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Variables"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="lsep"></a><span class="summary-name">lsep</span> = <code title=""\n#: "">"\n#: "</code><br />
Seperator for #: entries
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="translate.storage.pypo-module.html#po_unescape_map" class="summary-name">po_unescape_map</a> = <code title="{"\\r": "\r", "\\t": "\t", '\\"': '"', '\\n': '\n', '\\\\': '\\'}">{"\\r": "\r", "\\t": "\t", '\\"': '"', '\\n'<code class="variable-ellipsis">...</code></code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="translate.storage.pypo-module.html#po_escape_map" class="summary-name">po_escape_map</a> = <code title="dict([(value, key) for(key, value) in po_unescape_map.items()])">dict([(value, key) for(key, value) in po_unesc<code class="variable-ellipsis">...</code></code>
</td>
</tr>
</table>
<p class="indent-wrapped-lines"><b>Imports:</b>
<span title="copy">copy</span>,
<span title="cStringIO">cStringIO</span>,
<span title="re">re</span>,
<span title="translate.lang.data">data</span>,
<a href="translate.misc.multistring.multistring-class.html" title="translate.misc.multistring.multistring">multistring</a>,
<a href="translate.misc.quote-module.html" title="translate.misc.quote">quote</a>,
<a href="translate.misc.textwrap-module.html" title="translate.misc.textwrap">textwrap</a>,
<a href="translate.storage.pocommon-module.html" title="translate.storage.pocommon">pocommon</a>,
<a href="translate.storage.base-module.html" title="translate.storage.base">base</a>,
<a href="translate.storage.poparser-module.html" title="translate.storage.poparser">poparser</a>,
<a href="translate.storage.pocommon-module.html#encodingToUse" title="translate.storage.pocommon.encodingToUse">encodingToUse</a>
</p><br />
<!-- ==================== FUNCTION DETAILS ==================== -->
<a name="section-FunctionDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Function Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-FunctionDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="escapeforpo"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">escapeforpo</span>(<span class="sig-arg">line</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="translate.storage.pypo-pysrc.html#escapeforpo">source code</a></span>
</td>
</tr></table>
<p>Escapes a line for po format. assumes no occurs in the line.</p>
<dl class="fields">
<dt>Parameters:</dt>
<dd><ul class="nomargin-top">
<li><strong class="pname"><code>line</code></strong> - unescaped text</li>
</ul></dd>
</dl>
</td></tr></table>
</div>
<a name="extractpoline"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">extractpoline</span>(<span class="sig-arg">line</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="translate.storage.pypo-pysrc.html#extractpoline">source code</a></span>
</td>
</tr></table>
<p>Remove quote and unescape line from po file.</p>
<dl class="fields">
<dt>Parameters:</dt>
<dd><ul class="nomargin-top">
<li><strong class="pname"><code>line</code></strong> - a quoted line from a po file (msgid or msgstr)</li>
</ul></dd>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== VARIABLES DETAILS ==================== -->
<a name="section-VariablesDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Variables Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-VariablesDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="po_unescape_map"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">po_unescape_map</h3>
<dl class="fields">
</dl>
<dl class="fields">
<dt>Value:</dt>
<dd><table><tr><td><pre class="variable">
{"\\r": "\r", "\\t": "\t", '\\"': '"', '\\n': '\n', '\\\\': '\\'}
</pre></td></tr></table>
</dd>
</dl>
</td></tr></table>
</div>
<a name="po_escape_map"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<h3 class="epydoc">po_escape_map</h3>
<dl class="fields">
</dl>
<dl class="fields">
<dt>Value:</dt>
<dd><table><tr><td><pre class="variable">
dict([(value, key) for(key, value) in po_unescape_map.items()])
</pre></td></tr></table>
</dd>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="translate-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http://translate.sourceforge.net/wiki/toolkit/index">Translate Toolkit</a></th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Tue Apr 12 18:11:55 2011
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
| Java |
/*
* (C) 2007-2010 Taobao Inc.
*
* 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.
*
*
* Version: $Id$
*
* Authors:
* duolong <duolong@taobao.com>
*
*/
#ifndef TBNET_SERVERSOCKET_H_
#define TBNET_SERVERSOCKET_H_
namespace tbnet {
class ServerSocket : public Socket {
public:
/*
* ¹¹Ô캯Êý
*/
ServerSocket();
/*
* acceptÒ»¸öеÄÁ¬½Ó
*
* @return Ò»¸öSocket
*/
Socket* accept();
/*
* ´ò¿ª¼àÌý
*
* @return ÊÇ·ñ³É¹¦
*/
bool listen();
private:
int _backLog; // backlog
};
}
#endif /*SERVERSOCKET_H_*/
| Java |
<?php
/* core/themes/classy/templates/views/views-view-grid.html.twig */
class __TwigTemplate_b1b5e6a9a8cd209497117279c69ebc6612c8c2cb7794b0f45dd07835addb061c extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$tags = array("set" => 28, "if" => 35, "for" => 56);
$filters = array();
$functions = array();
try {
$this->env->getExtension('Twig_Extension_Sandbox')->checkSecurity(
array('set', 'if', 'for'),
array(),
array()
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setSourceContext($this->getSourceContext());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 28
$context["classes"] = array(0 => "views-view-grid", 1 => $this->getAttribute( // line 30
(isset($context["options"]) ? $context["options"] : null), "alignment", array()), 2 => ("cols-" . $this->getAttribute( // line 31
(isset($context["options"]) ? $context["options"] : null), "columns", array())), 3 => "clearfix");
// line 35
if ($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "row_class_default", array())) {
// line 36
echo " ";
// line 37
$context["row_classes"] = array(0 => "views-row", 1 => ((($this->getAttribute( // line 39
(isset($context["options"]) ? $context["options"] : null), "alignment", array()) == "horizontal")) ? ("clearfix") : ("")));
}
// line 43
if ($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "col_class_default", array())) {
// line 44
echo " ";
// line 45
$context["col_classes"] = array(0 => "views-col", 1 => ((($this->getAttribute( // line 47
(isset($context["options"]) ? $context["options"] : null), "alignment", array()) == "vertical")) ? ("clearfix") : ("")));
}
// line 51
if ((isset($context["title"]) ? $context["title"] : null)) {
// line 52
echo " <h3>";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, (isset($context["title"]) ? $context["title"] : null), "html", null, true));
echo "</h3>
";
}
// line 54
echo "<div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => (isset($context["classes"]) ? $context["classes"] : null)), "method"), "html", null, true));
echo ">
";
// line 55
if (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "alignment", array()) == "horizontal")) {
// line 56
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable((isset($context["items"]) ? $context["items"] : null));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["row"]) {
// line 57
echo " <div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["row"], "attributes", array()), "addClass", array(0 => (isset($context["row_classes"]) ? $context["row_classes"] : null), 1 => (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "row_class_default", array())) ? (("row-" . $this->getAttribute($context["loop"], "index", array()))) : (""))), "method"), "html", null, true));
echo ">
";
// line 58
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($context["row"], "content", array()));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["column"]) {
// line 59
echo " <div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["column"], "attributes", array()), "addClass", array(0 => (isset($context["col_classes"]) ? $context["col_classes"] : null), 1 => (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "col_class_default", array())) ? (("col-" . $this->getAttribute($context["loop"], "index", array()))) : (""))), "method"), "html", null, true));
echo ">
";
// line 60
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($context["column"], "content", array()), "html", null, true));
echo "
</div>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['column'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 63
echo " </div>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['row'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 65
echo " ";
} else {
// line 66
echo " ";
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable((isset($context["items"]) ? $context["items"] : null));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["column"]) {
// line 67
echo " <div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["column"], "attributes", array()), "addClass", array(0 => (isset($context["col_classes"]) ? $context["col_classes"] : null), 1 => (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "col_class_default", array())) ? (("col-" . $this->getAttribute($context["loop"], "index", array()))) : (""))), "method"), "html", null, true));
echo ">
";
// line 68
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($context["column"], "content", array()));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["row"]) {
// line 69
echo " <div";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["row"], "attributes", array()), "addClass", array(0 => (isset($context["row_classes"]) ? $context["row_classes"] : null), 1 => (($this->getAttribute((isset($context["options"]) ? $context["options"] : null), "row_class_default", array())) ? (("row-" . $this->getAttribute($context["loop"], "index", array()))) : (""))), "method"), "html", null, true));
echo ">
";
// line 70
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($context["row"], "content", array()), "html", null, true));
echo "
</div>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['row'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 73
echo " </div>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['column'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 75
echo " ";
}
// line 76
echo "</div>
";
}
public function getTemplateName()
{
return "core/themes/classy/templates/views/views-view-grid.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 238 => 76, 235 => 75, 220 => 73, 203 => 70, 198 => 69, 181 => 68, 176 => 67, 158 => 66, 155 => 65, 140 => 63, 123 => 60, 118 => 59, 101 => 58, 96 => 57, 78 => 56, 76 => 55, 71 => 54, 65 => 52, 63 => 51, 60 => 47, 59 => 45, 57 => 44, 55 => 43, 52 => 39, 51 => 37, 49 => 36, 47 => 35, 45 => 31, 44 => 30, 43 => 28,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("{#
/**
* @file
* Theme override for views to display rows in a grid.
*
* Available variables:
* - attributes: HTML attributes for the wrapping element.
* - title: The title of this group of rows.
* - view: The view object.
* - rows: The rendered view results.
* - options: The view plugin style options.
* - row_class_default: A flag indicating whether default classes should be
* used on rows.
* - col_class_default: A flag indicating whether default classes should be
* used on columns.
* - items: A list of grid items. Each item contains a list of rows or columns.
* The order in what comes first (row or column) depends on which alignment
* type is chosen (horizontal or vertical).
* - attributes: HTML attributes for each row or column.
* - content: A list of columns or rows. Each row or column contains:
* - attributes: HTML attributes for each row or column.
* - content: The row or column contents.
*
* @see template_preprocess_views_view_grid()
*/
#}
{%
set classes = [
'views-view-grid',
options.alignment,
'cols-' ~ options.columns,
'clearfix',
]
%}
{% if options.row_class_default %}
{%
set row_classes = [
'views-row',
options.alignment == 'horizontal' ? 'clearfix',
]
%}
{% endif %}
{% if options.col_class_default %}
{%
set col_classes = [
'views-col',
options.alignment == 'vertical' ? 'clearfix',
]
%}
{% endif %}
{% if title %}
<h3>{{ title }}</h3>
{% endif %}
<div{{ attributes.addClass(classes) }}>
{% if options.alignment == 'horizontal' %}
{% for row in items %}
<div{{ row.attributes.addClass(row_classes, options.row_class_default ? 'row-' ~ loop.index) }}>
{% for column in row.content %}
<div{{ column.attributes.addClass(col_classes, options.col_class_default ? 'col-' ~ loop.index) }}>
{{ column.content }}
</div>
{% endfor %}
</div>
{% endfor %}
{% else %}
{% for column in items %}
<div{{ column.attributes.addClass(col_classes, options.col_class_default ? 'col-' ~ loop.index) }}>
{% for row in column.content %}
<div{{ row.attributes.addClass(row_classes, options.row_class_default ? 'row-' ~ loop.index) }}>
{{ row.content }}
</div>
{% endfor %}
</div>
{% endfor %}
{% endif %}
</div>
", "core/themes/classy/templates/views/views-view-grid.html.twig", "/mnt/jeet/www/local/chipc/core/themes/classy/templates/views/views-view-grid.html.twig");
}
}
| Java |
<?php
/**
* @version $Id: joocmavatar.php 48 2010-02-08 22:15:48Z sterob $
* @package Joo!CM
* @copyright Copyright (C) 2007-2010 Joo!BB Project. All rights reserved.
* @license GNU/GPL. Please see license.php in Joo!CM directory
* for copyright notices and details.
* Joo!CM is free software. This version may have been NOT modified.
*/
/**
* Joocm Avatar Table Class
*
* @package Joo!CM
*/
class JTableJoocmAvatar extends JTable {
/** @var int Unique id*/
var $id = null;
/** @var string */
var $avatar_file = null;
/** @var int */
var $published = null;
/** @var int */
var $checked_out = null;
/** @var datetime */
var $checked_out_time = null;
/** @var int */
var $id_user = null;
/**
* @param database A database connector object
*/
function __construct(&$db) {
parent::__construct('#__joocm_avatars', 'id', $db);
}
}
?> | Java |
# This Makefile is for the VFS dumper extension to perl.
#
# It was generated automatically by MakeMaker version
# 7.0401 (Revision: 70401) from the contents of
# Makefile.PL. Don't edit this file, edit Makefile.PL instead.
#
# ANY CHANGES MADE HERE WILL BE LOST!
#
# MakeMaker ARGV: ()
#
# MakeMaker Parameters:
# BUILD_REQUIRES => { }
# CONFIGURE_REQUIRES => { }
# NAME => q[VFS dumper]
# PREREQ_PM => { }
# TEST_REQUIRES => { }
# VERSION_FROM => q[bin/vfs_dumper.pl]
# --- MakeMaker post_initialize section:
# --- MakeMaker const_config section:
# These definitions are from config.sh (via /usr/lib/i386-linux-gnu/perl/5.22/Config.pm).
# They may have been overridden via Makefile.PL or on the command line.
AR = ar
CC = i686-linux-gnu-gcc
CCCDLFLAGS = -fPIC
CCDLFLAGS = -Wl,-E
DLEXT = so
DLSRC = dl_dlopen.xs
EXE_EXT =
FULL_AR = /usr/bin/ar
LD = i686-linux-gnu-gcc
LDDLFLAGS = -shared -L/usr/local/lib -fstack-protector-strong
LDFLAGS = -fstack-protector-strong -L/usr/local/lib
LIBC = libc-2.21.so
LIB_EXT = .a
OBJ_EXT = .o
OSNAME = linux
OSVERS = 3.16.0
RANLIB = :
SITELIBEXP = /usr/local/share/perl/5.22.1
SITEARCHEXP = /usr/local/lib/i386-linux-gnu/perl/5.22.1
SO = so
VENDORARCHEXP = /usr/lib/i386-linux-gnu/perl5/5.22
VENDORLIBEXP = /usr/share/perl5
# --- MakeMaker constants section:
AR_STATIC_ARGS = cr
DIRFILESEP = /
DFSEP = $(DIRFILESEP)
NAME = VFS dumper
NAME_SYM = VFS_dumper
VERSION = 1
VERSION_MACRO = VERSION
VERSION_SYM = 1
DEFINE_VERSION = -D$(VERSION_MACRO)=\"$(VERSION)\"
XS_VERSION = 1
XS_VERSION_MACRO = XS_VERSION
XS_DEFINE_VERSION = -D$(XS_VERSION_MACRO)=\"$(XS_VERSION)\"
INST_ARCHLIB = blib/arch
INST_SCRIPT = blib/script
INST_BIN = blib/bin
INST_LIB = blib/lib
INST_MAN1DIR = blib/man1
INST_MAN3DIR = blib/man3
MAN1EXT = 1p
MAN3EXT = 3pm
INSTALLDIRS = site
INSTALL_BASE = /home/popyan/perl5
DESTDIR =
PREFIX = $(INSTALL_BASE)
INSTALLPRIVLIB = $(INSTALL_BASE)/lib/perl5
DESTINSTALLPRIVLIB = $(DESTDIR)$(INSTALLPRIVLIB)
INSTALLSITELIB = $(INSTALL_BASE)/lib/perl5
DESTINSTALLSITELIB = $(DESTDIR)$(INSTALLSITELIB)
INSTALLVENDORLIB = $(INSTALL_BASE)/lib/perl5
DESTINSTALLVENDORLIB = $(DESTDIR)$(INSTALLVENDORLIB)
INSTALLARCHLIB = $(INSTALL_BASE)/lib/perl5/i686-linux-gnu-thread-multi-64int
DESTINSTALLARCHLIB = $(DESTDIR)$(INSTALLARCHLIB)
INSTALLSITEARCH = $(INSTALL_BASE)/lib/perl5/i686-linux-gnu-thread-multi-64int
DESTINSTALLSITEARCH = $(DESTDIR)$(INSTALLSITEARCH)
INSTALLVENDORARCH = $(INSTALL_BASE)/lib/perl5/i686-linux-gnu-thread-multi-64int
DESTINSTALLVENDORARCH = $(DESTDIR)$(INSTALLVENDORARCH)
INSTALLBIN = $(INSTALL_BASE)/bin
DESTINSTALLBIN = $(DESTDIR)$(INSTALLBIN)
INSTALLSITEBIN = $(INSTALL_BASE)/bin
DESTINSTALLSITEBIN = $(DESTDIR)$(INSTALLSITEBIN)
INSTALLVENDORBIN = $(INSTALL_BASE)/bin
DESTINSTALLVENDORBIN = $(DESTDIR)$(INSTALLVENDORBIN)
INSTALLSCRIPT = $(INSTALL_BASE)/bin
DESTINSTALLSCRIPT = $(DESTDIR)$(INSTALLSCRIPT)
INSTALLSITESCRIPT = $(INSTALL_BASE)/bin
DESTINSTALLSITESCRIPT = $(DESTDIR)$(INSTALLSITESCRIPT)
INSTALLVENDORSCRIPT = $(INSTALL_BASE)/bin
DESTINSTALLVENDORSCRIPT = $(DESTDIR)$(INSTALLVENDORSCRIPT)
INSTALLMAN1DIR = $(INSTALL_BASE)/man/man1
DESTINSTALLMAN1DIR = $(DESTDIR)$(INSTALLMAN1DIR)
INSTALLSITEMAN1DIR = $(INSTALL_BASE)/man/man1
DESTINSTALLSITEMAN1DIR = $(DESTDIR)$(INSTALLSITEMAN1DIR)
INSTALLVENDORMAN1DIR = $(INSTALL_BASE)/man/man1
DESTINSTALLVENDORMAN1DIR = $(DESTDIR)$(INSTALLVENDORMAN1DIR)
INSTALLMAN3DIR = $(INSTALL_BASE)/man/man3
DESTINSTALLMAN3DIR = $(DESTDIR)$(INSTALLMAN3DIR)
INSTALLSITEMAN3DIR = $(INSTALL_BASE)/man/man3
DESTINSTALLSITEMAN3DIR = $(DESTDIR)$(INSTALLSITEMAN3DIR)
INSTALLVENDORMAN3DIR = $(INSTALL_BASE)/man/man3
DESTINSTALLVENDORMAN3DIR = $(DESTDIR)$(INSTALLVENDORMAN3DIR)
PERL_LIB = /usr/share/perl/5.22
PERL_ARCHLIB = /usr/lib/i386-linux-gnu/perl/5.22
PERL_ARCHLIBDEP = /usr/lib/i386-linux-gnu/perl/5.22
LIBPERL_A = libperl.a
FIRST_MAKEFILE = Makefile
MAKEFILE_OLD = Makefile.old
MAKE_APERL_FILE = Makefile.aperl
PERLMAINCC = $(CC)
PERL_INC = /usr/lib/i386-linux-gnu/perl/5.22/CORE
PERL_INCDEP = /usr/lib/i386-linux-gnu/perl/5.22/CORE
PERL = "/usr/bin/perl"
FULLPERL = "/usr/bin/perl"
ABSPERL = $(PERL)
PERLRUN = $(PERL)
FULLPERLRUN = $(FULLPERL)
ABSPERLRUN = $(ABSPERL)
PERLRUNINST = $(PERLRUN) "-I$(INST_ARCHLIB)" "-I$(INST_LIB)"
FULLPERLRUNINST = $(FULLPERLRUN) "-I$(INST_ARCHLIB)" "-I$(INST_LIB)"
ABSPERLRUNINST = $(ABSPERLRUN) "-I$(INST_ARCHLIB)" "-I$(INST_LIB)"
PERL_CORE = 0
PERM_DIR = 755
PERM_RW = 644
PERM_RWX = 755
MAKEMAKER = /usr/share/perl/5.22/ExtUtils/MakeMaker.pm
MM_VERSION = 7.0401
MM_REVISION = 70401
# FULLEXT = Pathname for extension directory (eg Foo/Bar/Oracle).
# BASEEXT = Basename part of FULLEXT. May be just equal FULLEXT. (eg Oracle)
# PARENT_NAME = NAME without BASEEXT and no trailing :: (eg Foo::Bar)
# DLBASE = Basename part of dynamic library. May be just equal BASEEXT.
MAKE = make
FULLEXT = VFS dumper
BASEEXT = dumper
PARENT_NAME =
DLBASE = $(BASEEXT)
VERSION_FROM = bin/vfs_dumper.pl
OBJECT =
LDFROM = $(OBJECT)
LINKTYPE = dynamic
BOOTDEP =
# Handy lists of source code files:
XS_FILES =
C_FILES =
O_FILES =
H_FILES =
MAN1PODS =
MAN3PODS = lib/VFS.pm
# Where is the Config information that we are using/depend on
CONFIGDEP = $(PERL_ARCHLIBDEP)$(DFSEP)Config.pm $(PERL_INCDEP)$(DFSEP)config.h
# Where to build things
INST_LIBDIR = $(INST_LIB)
INST_ARCHLIBDIR = $(INST_ARCHLIB)
INST_AUTODIR = $(INST_LIB)/auto/$(FULLEXT)
INST_ARCHAUTODIR = $(INST_ARCHLIB)/auto/$(FULLEXT)
INST_STATIC =
INST_DYNAMIC =
INST_BOOT =
# Extra linker info
EXPORT_LIST =
PERL_ARCHIVE =
PERL_ARCHIVEDEP =
PERL_ARCHIVE_AFTER =
TO_INST_PM = lib/VFS.pm
PM_TO_BLIB = lib/VFS.pm \
blib/lib/VFS.pm
# --- MakeMaker platform_constants section:
MM_Unix_VERSION = 7.0401
PERL_MALLOC_DEF = -DPERL_EXTMALLOC_DEF -Dmalloc=Perl_malloc -Dfree=Perl_mfree -Drealloc=Perl_realloc -Dcalloc=Perl_calloc
# --- MakeMaker tool_autosplit section:
# Usage: $(AUTOSPLITFILE) FileToSplit AutoDirToSplitInto
AUTOSPLITFILE = $(ABSPERLRUN) -e 'use AutoSplit; autosplit($$$$ARGV[0], $$$$ARGV[1], 0, 1, 1)' --
# --- MakeMaker tool_xsubpp section:
# --- MakeMaker tools_other section:
SHELL = /bin/sh
CHMOD = chmod
CP = cp
MV = mv
NOOP = $(TRUE)
NOECHO = @
RM_F = rm -f
RM_RF = rm -rf
TEST_F = test -f
TOUCH = touch
UMASK_NULL = umask 0
DEV_NULL = > /dev/null 2>&1
MKPATH = $(ABSPERLRUN) -MExtUtils::Command -e 'mkpath' --
EQUALIZE_TIMESTAMP = $(ABSPERLRUN) -MExtUtils::Command -e 'eqtime' --
FALSE = false
TRUE = true
ECHO = echo
ECHO_N = echo -n
UNINST = 0
VERBINST = 0
MOD_INSTALL = $(ABSPERLRUN) -MExtUtils::Install -e 'install([ from_to => {@ARGV}, verbose => '\''$(VERBINST)'\'', uninstall_shadows => '\''$(UNINST)'\'', dir_mode => '\''$(PERM_DIR)'\'' ]);' --
DOC_INSTALL = $(ABSPERLRUN) -MExtUtils::Command::MM -e 'perllocal_install' --
UNINSTALL = $(ABSPERLRUN) -MExtUtils::Command::MM -e 'uninstall' --
WARN_IF_OLD_PACKLIST = $(ABSPERLRUN) -MExtUtils::Command::MM -e 'warn_if_old_packlist' --
MACROSTART =
MACROEND =
USEMAKEFILE = -f
FIXIN = $(ABSPERLRUN) -MExtUtils::MY -e 'MY->fixin(shift)' --
CP_NONEMPTY = $(ABSPERLRUN) -MExtUtils::Command::MM -e 'cp_nonempty' --
# --- MakeMaker makemakerdflt section:
makemakerdflt : all
$(NOECHO) $(NOOP)
# --- MakeMaker dist section:
TAR = tar
TARFLAGS = cvf
ZIP = zip
ZIPFLAGS = -r
COMPRESS = gzip --best
SUFFIX = .gz
SHAR = shar
PREOP = $(NOECHO) $(NOOP)
POSTOP = $(NOECHO) $(NOOP)
TO_UNIX = $(NOECHO) $(NOOP)
CI = ci -u
RCS_LABEL = rcs -Nv$(VERSION_SYM): -q
DIST_CP = best
DIST_DEFAULT = tardist
DISTNAME = VFS dumper
DISTVNAME = VFS dumper-1
# --- MakeMaker macro section:
# --- MakeMaker depend section:
# --- MakeMaker cflags section:
# --- MakeMaker const_loadlibs section:
# --- MakeMaker const_cccmd section:
# --- MakeMaker post_constants section:
# --- MakeMaker pasthru section:
PASTHRU = LIBPERL_A="$(LIBPERL_A)"\
LINKTYPE="$(LINKTYPE)"\
LD="$(LD)"\
PREFIX="$(PREFIX)"\
INSTALL_BASE="$(INSTALL_BASE)"
# --- MakeMaker special_targets section:
.SUFFIXES : .xs .c .C .cpp .i .s .cxx .cc $(OBJ_EXT)
.PHONY: all config static dynamic test linkext manifest blibdirs clean realclean disttest distdir
# --- MakeMaker c_o section:
# --- MakeMaker xs_c section:
# --- MakeMaker xs_o section:
# --- MakeMaker top_targets section:
all :: pure_all manifypods
$(NOECHO) $(NOOP)
pure_all :: config pm_to_blib subdirs linkext
$(NOECHO) $(NOOP)
subdirs :: $(MYEXTLIB)
$(NOECHO) $(NOOP)
config :: $(FIRST_MAKEFILE) blibdirs
$(NOECHO) $(NOOP)
help :
perldoc ExtUtils::MakeMaker
# --- MakeMaker blibdirs section:
blibdirs : $(INST_LIBDIR)$(DFSEP).exists $(INST_ARCHLIB)$(DFSEP).exists $(INST_AUTODIR)$(DFSEP).exists $(INST_ARCHAUTODIR)$(DFSEP).exists $(INST_BIN)$(DFSEP).exists $(INST_SCRIPT)$(DFSEP).exists $(INST_MAN1DIR)$(DFSEP).exists $(INST_MAN3DIR)$(DFSEP).exists
$(NOECHO) $(NOOP)
# Backwards compat with 6.18 through 6.25
blibdirs.ts : blibdirs
$(NOECHO) $(NOOP)
$(INST_LIBDIR)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_LIBDIR)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_LIBDIR)
$(NOECHO) $(TOUCH) $(INST_LIBDIR)$(DFSEP).exists
$(INST_ARCHLIB)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_ARCHLIB)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_ARCHLIB)
$(NOECHO) $(TOUCH) $(INST_ARCHLIB)$(DFSEP).exists
$(INST_AUTODIR)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_AUTODIR)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_AUTODIR)
$(NOECHO) $(TOUCH) $(INST_AUTODIR)$(DFSEP).exists
$(INST_ARCHAUTODIR)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_ARCHAUTODIR)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_ARCHAUTODIR)
$(NOECHO) $(TOUCH) $(INST_ARCHAUTODIR)$(DFSEP).exists
$(INST_BIN)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_BIN)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_BIN)
$(NOECHO) $(TOUCH) $(INST_BIN)$(DFSEP).exists
$(INST_SCRIPT)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_SCRIPT)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_SCRIPT)
$(NOECHO) $(TOUCH) $(INST_SCRIPT)$(DFSEP).exists
$(INST_MAN1DIR)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_MAN1DIR)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_MAN1DIR)
$(NOECHO) $(TOUCH) $(INST_MAN1DIR)$(DFSEP).exists
$(INST_MAN3DIR)$(DFSEP).exists :: Makefile.PL
$(NOECHO) $(MKPATH) $(INST_MAN3DIR)
$(NOECHO) $(CHMOD) $(PERM_DIR) $(INST_MAN3DIR)
$(NOECHO) $(TOUCH) $(INST_MAN3DIR)$(DFSEP).exists
# --- MakeMaker linkext section:
linkext :: $(LINKTYPE)
$(NOECHO) $(NOOP)
# --- MakeMaker dlsyms section:
# --- MakeMaker dynamic_bs section:
BOOTSTRAP =
# --- MakeMaker dynamic section:
dynamic :: $(FIRST_MAKEFILE) $(BOOTSTRAP) $(INST_DYNAMIC)
$(NOECHO) $(NOOP)
# --- MakeMaker dynamic_lib section:
# --- MakeMaker static section:
## $(INST_PM) has been moved to the all: target.
## It remains here for awhile to allow for old usage: "make static"
static :: $(FIRST_MAKEFILE) $(INST_STATIC)
$(NOECHO) $(NOOP)
# --- MakeMaker static_lib section:
# --- MakeMaker manifypods section:
POD2MAN_EXE = $(PERLRUN) "-MExtUtils::Command::MM" -e pod2man "--"
POD2MAN = $(POD2MAN_EXE)
manifypods : pure_all \
lib/VFS.pm
$(NOECHO) $(POD2MAN) --section=$(MAN3EXT) --perm_rw=$(PERM_RW) -u \
lib/VFS.pm $(INST_MAN3DIR)/VFS.$(MAN3EXT)
# --- MakeMaker processPL section:
# --- MakeMaker installbin section:
# --- MakeMaker subdirs section:
# none
# --- MakeMaker clean_subdirs section:
clean_subdirs :
$(NOECHO) $(NOOP)
# --- MakeMaker clean section:
# Delete temporary files but do not touch installed files. We don't delete
# the Makefile here so a later make realclean still has a makefile to use.
clean :: clean_subdirs
- $(RM_F) \
$(BASEEXT).bso $(BASEEXT).def \
$(BASEEXT).exp $(BASEEXT).x \
$(BOOTSTRAP) $(INST_ARCHAUTODIR)/extralibs.all \
$(INST_ARCHAUTODIR)/extralibs.ld $(MAKE_APERL_FILE) \
*$(LIB_EXT) *$(OBJ_EXT) \
*perl.core MYMETA.json \
MYMETA.yml blibdirs.ts \
core core.*perl.*.? \
core.[0-9] core.[0-9][0-9] \
core.[0-9][0-9][0-9] core.[0-9][0-9][0-9][0-9] \
core.[0-9][0-9][0-9][0-9][0-9] lib$(BASEEXT).def \
mon.out perl \
perl$(EXE_EXT) perl.exe \
perlmain.c pm_to_blib \
pm_to_blib.ts so_locations \
tmon.out
- $(RM_RF) \
blib
$(NOECHO) $(RM_F) $(MAKEFILE_OLD)
- $(MV) $(FIRST_MAKEFILE) $(MAKEFILE_OLD) $(DEV_NULL)
# --- MakeMaker realclean_subdirs section:
realclean_subdirs :
$(NOECHO) $(NOOP)
# --- MakeMaker realclean section:
# Delete temporary files (via clean) and also delete dist files
realclean purge :: clean realclean_subdirs
- $(RM_F) \
$(FIRST_MAKEFILE) $(MAKEFILE_OLD)
- $(RM_RF) \
$(DISTVNAME)
# --- MakeMaker metafile section:
metafile : create_distdir
$(NOECHO) $(ECHO) Generating META.yml
$(NOECHO) $(ECHO) '---' > META_new.yml
$(NOECHO) $(ECHO) 'abstract: unknown' >> META_new.yml
$(NOECHO) $(ECHO) 'author:' >> META_new.yml
$(NOECHO) $(ECHO) ' - unknown' >> META_new.yml
$(NOECHO) $(ECHO) 'build_requires:' >> META_new.yml
$(NOECHO) $(ECHO) ' ExtUtils::MakeMaker: '\''0'\''' >> META_new.yml
$(NOECHO) $(ECHO) 'configure_requires:' >> META_new.yml
$(NOECHO) $(ECHO) ' ExtUtils::MakeMaker: '\''0'\''' >> META_new.yml
$(NOECHO) $(ECHO) 'dynamic_config: 1' >> META_new.yml
$(NOECHO) $(ECHO) 'generated_by: '\''ExtUtils::MakeMaker version 7.0401, CPAN::Meta::Converter version 2.150001'\''' >> META_new.yml
$(NOECHO) $(ECHO) 'license: unknown' >> META_new.yml
$(NOECHO) $(ECHO) 'meta-spec:' >> META_new.yml
$(NOECHO) $(ECHO) ' url: http://module-build.sourceforge.net/META-spec-v1.4.html' >> META_new.yml
$(NOECHO) $(ECHO) ' version: '\''1.4'\''' >> META_new.yml
$(NOECHO) $(ECHO) 'name: '\''VFS dumper'\''' >> META_new.yml
$(NOECHO) $(ECHO) 'no_index:' >> META_new.yml
$(NOECHO) $(ECHO) ' directory:' >> META_new.yml
$(NOECHO) $(ECHO) ' - t' >> META_new.yml
$(NOECHO) $(ECHO) ' - inc' >> META_new.yml
$(NOECHO) $(ECHO) 'requires: {}' >> META_new.yml
$(NOECHO) $(ECHO) 'version: 1' >> META_new.yml
-$(NOECHO) $(MV) META_new.yml $(DISTVNAME)/META.yml
$(NOECHO) $(ECHO) Generating META.json
$(NOECHO) $(ECHO) '{' > META_new.json
$(NOECHO) $(ECHO) ' "abstract" : "unknown",' >> META_new.json
$(NOECHO) $(ECHO) ' "author" : [' >> META_new.json
$(NOECHO) $(ECHO) ' "unknown"' >> META_new.json
$(NOECHO) $(ECHO) ' ],' >> META_new.json
$(NOECHO) $(ECHO) ' "dynamic_config" : 1,' >> META_new.json
$(NOECHO) $(ECHO) ' "generated_by" : "ExtUtils::MakeMaker version 7.0401, CPAN::Meta::Converter version 2.150001",' >> META_new.json
$(NOECHO) $(ECHO) ' "license" : [' >> META_new.json
$(NOECHO) $(ECHO) ' "unknown"' >> META_new.json
$(NOECHO) $(ECHO) ' ],' >> META_new.json
$(NOECHO) $(ECHO) ' "meta-spec" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec",' >> META_new.json
$(NOECHO) $(ECHO) ' "version" : "2"' >> META_new.json
$(NOECHO) $(ECHO) ' },' >> META_new.json
$(NOECHO) $(ECHO) ' "name" : "VFS dumper",' >> META_new.json
$(NOECHO) $(ECHO) ' "no_index" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "directory" : [' >> META_new.json
$(NOECHO) $(ECHO) ' "t",' >> META_new.json
$(NOECHO) $(ECHO) ' "inc"' >> META_new.json
$(NOECHO) $(ECHO) ' ]' >> META_new.json
$(NOECHO) $(ECHO) ' },' >> META_new.json
$(NOECHO) $(ECHO) ' "prereqs" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "build" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "requires" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "ExtUtils::MakeMaker" : "0"' >> META_new.json
$(NOECHO) $(ECHO) ' }' >> META_new.json
$(NOECHO) $(ECHO) ' },' >> META_new.json
$(NOECHO) $(ECHO) ' "configure" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "requires" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "ExtUtils::MakeMaker" : "0"' >> META_new.json
$(NOECHO) $(ECHO) ' }' >> META_new.json
$(NOECHO) $(ECHO) ' },' >> META_new.json
$(NOECHO) $(ECHO) ' "runtime" : {' >> META_new.json
$(NOECHO) $(ECHO) ' "requires" : {}' >> META_new.json
$(NOECHO) $(ECHO) ' }' >> META_new.json
$(NOECHO) $(ECHO) ' },' >> META_new.json
$(NOECHO) $(ECHO) ' "release_status" : "stable",' >> META_new.json
$(NOECHO) $(ECHO) ' "version" : 1' >> META_new.json
$(NOECHO) $(ECHO) '}' >> META_new.json
-$(NOECHO) $(MV) META_new.json $(DISTVNAME)/META.json
# --- MakeMaker signature section:
signature :
cpansign -s
# --- MakeMaker dist_basics section:
distclean :: realclean distcheck
$(NOECHO) $(NOOP)
distcheck :
$(PERLRUN) "-MExtUtils::Manifest=fullcheck" -e fullcheck
skipcheck :
$(PERLRUN) "-MExtUtils::Manifest=skipcheck" -e skipcheck
manifest :
$(PERLRUN) "-MExtUtils::Manifest=mkmanifest" -e mkmanifest
veryclean : realclean
$(RM_F) *~ */*~ *.orig */*.orig *.bak */*.bak *.old */*.old
# --- MakeMaker dist_core section:
dist : $(DIST_DEFAULT) $(FIRST_MAKEFILE)
$(NOECHO) $(ABSPERLRUN) -l -e 'print '\''Warning: Makefile possibly out of date with $(VERSION_FROM)'\''' \
-e ' if -e '\''$(VERSION_FROM)'\'' and -M '\''$(VERSION_FROM)'\'' < -M '\''$(FIRST_MAKEFILE)'\'';' --
tardist : $(DISTVNAME).tar$(SUFFIX)
$(NOECHO) $(NOOP)
uutardist : $(DISTVNAME).tar$(SUFFIX)
uuencode $(DISTVNAME).tar$(SUFFIX) $(DISTVNAME).tar$(SUFFIX) > $(DISTVNAME).tar$(SUFFIX)_uu
$(NOECHO) $(ECHO) 'Created $(DISTVNAME).tar$(SUFFIX)_uu'
$(DISTVNAME).tar$(SUFFIX) : distdir
$(PREOP)
$(TO_UNIX)
$(TAR) $(TARFLAGS) $(DISTVNAME).tar $(DISTVNAME)
$(RM_RF) $(DISTVNAME)
$(COMPRESS) $(DISTVNAME).tar
$(NOECHO) $(ECHO) 'Created $(DISTVNAME).tar$(SUFFIX)'
$(POSTOP)
zipdist : $(DISTVNAME).zip
$(NOECHO) $(NOOP)
$(DISTVNAME).zip : distdir
$(PREOP)
$(ZIP) $(ZIPFLAGS) $(DISTVNAME).zip $(DISTVNAME)
$(RM_RF) $(DISTVNAME)
$(NOECHO) $(ECHO) 'Created $(DISTVNAME).zip'
$(POSTOP)
shdist : distdir
$(PREOP)
$(SHAR) $(DISTVNAME) > $(DISTVNAME).shar
$(RM_RF) $(DISTVNAME)
$(NOECHO) $(ECHO) 'Created $(DISTVNAME).shar'
$(POSTOP)
# --- MakeMaker distdir section:
create_distdir :
$(RM_RF) $(DISTVNAME)
$(PERLRUN) "-MExtUtils::Manifest=manicopy,maniread" \
-e "manicopy(maniread(),'$(DISTVNAME)', '$(DIST_CP)');"
distdir : create_distdir distmeta
$(NOECHO) $(NOOP)
# --- MakeMaker dist_test section:
disttest : distdir
cd $(DISTVNAME) && $(ABSPERLRUN) Makefile.PL
cd $(DISTVNAME) && $(MAKE) $(PASTHRU)
cd $(DISTVNAME) && $(MAKE) test $(PASTHRU)
# --- MakeMaker dist_ci section:
ci :
$(PERLRUN) "-MExtUtils::Manifest=maniread" \
-e "@all = keys %{ maniread() };" \
-e "print(qq{Executing $(CI) @all\n}); system(qq{$(CI) @all});" \
-e "print(qq{Executing $(RCS_LABEL) ...\n}); system(qq{$(RCS_LABEL) @all});"
# --- MakeMaker distmeta section:
distmeta : create_distdir metafile
$(NOECHO) cd $(DISTVNAME) && $(ABSPERLRUN) -MExtUtils::Manifest=maniadd -e 'exit unless -e q{META.yml};' \
-e 'eval { maniadd({q{META.yml} => q{Module YAML meta-data (added by MakeMaker)}}) }' \
-e ' or print "Could not add META.yml to MANIFEST: $$$${'\''@'\''}\n"' --
$(NOECHO) cd $(DISTVNAME) && $(ABSPERLRUN) -MExtUtils::Manifest=maniadd -e 'exit unless -f q{META.json};' \
-e 'eval { maniadd({q{META.json} => q{Module JSON meta-data (added by MakeMaker)}}) }' \
-e ' or print "Could not add META.json to MANIFEST: $$$${'\''@'\''}\n"' --
# --- MakeMaker distsignature section:
distsignature : create_distdir
$(NOECHO) cd $(DISTVNAME) && $(ABSPERLRUN) -MExtUtils::Manifest=maniadd -e 'eval { maniadd({q{SIGNATURE} => q{Public-key signature (added by MakeMaker)}}) }' \
-e ' or print "Could not add SIGNATURE to MANIFEST: $$$${'\''@'\''}\n"' --
$(NOECHO) cd $(DISTVNAME) && $(TOUCH) SIGNATURE
cd $(DISTVNAME) && cpansign -s
# --- MakeMaker install section:
install :: pure_install doc_install
$(NOECHO) $(NOOP)
install_perl :: pure_perl_install doc_perl_install
$(NOECHO) $(NOOP)
install_site :: pure_site_install doc_site_install
$(NOECHO) $(NOOP)
install_vendor :: pure_vendor_install doc_vendor_install
$(NOECHO) $(NOOP)
pure_install :: pure_$(INSTALLDIRS)_install
$(NOECHO) $(NOOP)
doc_install :: doc_$(INSTALLDIRS)_install
$(NOECHO) $(NOOP)
pure__install : pure_site_install
$(NOECHO) $(ECHO) INSTALLDIRS not defined, defaulting to INSTALLDIRS=site
doc__install : doc_site_install
$(NOECHO) $(ECHO) INSTALLDIRS not defined, defaulting to INSTALLDIRS=site
pure_perl_install :: all
$(NOECHO) umask 022; $(MOD_INSTALL) \
"$(INST_LIB)" "$(DESTINSTALLPRIVLIB)" \
"$(INST_ARCHLIB)" "$(DESTINSTALLARCHLIB)" \
"$(INST_BIN)" "$(DESTINSTALLBIN)" \
"$(INST_SCRIPT)" "$(DESTINSTALLSCRIPT)" \
"$(INST_MAN1DIR)" "$(DESTINSTALLMAN1DIR)" \
"$(INST_MAN3DIR)" "$(DESTINSTALLMAN3DIR)"
$(NOECHO) $(WARN_IF_OLD_PACKLIST) \
"$(SITEARCHEXP)/auto/$(FULLEXT)"
pure_site_install :: all
$(NOECHO) umask 02; $(MOD_INSTALL) \
read "$(SITEARCHEXP)/auto/$(FULLEXT)/.packlist" \
write "$(DESTINSTALLSITEARCH)/auto/$(FULLEXT)/.packlist" \
"$(INST_LIB)" "$(DESTINSTALLSITELIB)" \
"$(INST_ARCHLIB)" "$(DESTINSTALLSITEARCH)" \
"$(INST_BIN)" "$(DESTINSTALLSITEBIN)" \
"$(INST_SCRIPT)" "$(DESTINSTALLSITESCRIPT)" \
"$(INST_MAN1DIR)" "$(DESTINSTALLSITEMAN1DIR)" \
"$(INST_MAN3DIR)" "$(DESTINSTALLSITEMAN3DIR)"
$(NOECHO) $(WARN_IF_OLD_PACKLIST) \
"$(PERL_ARCHLIB)/auto/$(FULLEXT)"
pure_vendor_install :: all
$(NOECHO) umask 022; $(MOD_INSTALL) \
"$(INST_LIB)" "$(DESTINSTALLVENDORLIB)" \
"$(INST_ARCHLIB)" "$(DESTINSTALLVENDORARCH)" \
"$(INST_BIN)" "$(DESTINSTALLVENDORBIN)" \
"$(INST_SCRIPT)" "$(DESTINSTALLVENDORSCRIPT)" \
"$(INST_MAN1DIR)" "$(DESTINSTALLVENDORMAN1DIR)" \
"$(INST_MAN3DIR)" "$(DESTINSTALLVENDORMAN3DIR)"
doc_perl_install :: all
doc_site_install :: all
$(NOECHO) $(ECHO) Appending installation info to "$(DESTINSTALLSITEARCH)/perllocal.pod"
-$(NOECHO) umask 02; $(MKPATH) "$(DESTINSTALLSITEARCH)"
-$(NOECHO) umask 02; $(DOC_INSTALL) \
"Module" "$(NAME)" \
"installed into" $(INSTALLSITELIB) \
LINKTYPE "$(LINKTYPE)" \
VERSION "$(VERSION)" \
EXE_FILES "$(EXE_FILES)" \
>> "$(DESTINSTALLSITEARCH)/perllocal.pod"
doc_vendor_install :: all
uninstall :: uninstall_from_$(INSTALLDIRS)dirs
$(NOECHO) $(NOOP)
uninstall_from_perldirs ::
uninstall_from_sitedirs ::
$(NOECHO) $(UNINSTALL) "$(SITEARCHEXP)/auto/$(FULLEXT)/.packlist"
uninstall_from_vendordirs ::
# --- MakeMaker force section:
# Phony target to force checking subdirectories.
FORCE :
$(NOECHO) $(NOOP)
# --- MakeMaker perldepend section:
# --- MakeMaker makefile section:
# We take a very conservative approach here, but it's worth it.
# We move Makefile to Makefile.old here to avoid gnu make looping.
$(FIRST_MAKEFILE) : Makefile.PL $(CONFIGDEP)
$(NOECHO) $(ECHO) "Makefile out-of-date with respect to $?"
$(NOECHO) $(ECHO) "Cleaning current config before rebuilding Makefile..."
-$(NOECHO) $(RM_F) $(MAKEFILE_OLD)
-$(NOECHO) $(MV) $(FIRST_MAKEFILE) $(MAKEFILE_OLD)
- $(MAKE) $(USEMAKEFILE) $(MAKEFILE_OLD) clean $(DEV_NULL)
$(PERLRUN) Makefile.PL
$(NOECHO) $(ECHO) "==> Your Makefile has been rebuilt. <=="
$(NOECHO) $(ECHO) "==> Please rerun the $(MAKE) command. <=="
$(FALSE)
# --- MakeMaker staticmake section:
# --- MakeMaker makeaperl section ---
MAP_TARGET = perl
FULLPERL = "/usr/bin/perl"
$(MAP_TARGET) :: static $(MAKE_APERL_FILE)
$(MAKE) $(USEMAKEFILE) $(MAKE_APERL_FILE) $@
$(MAKE_APERL_FILE) : $(FIRST_MAKEFILE) pm_to_blib
$(NOECHO) $(ECHO) Writing \"$(MAKE_APERL_FILE)\" for this $(MAP_TARGET)
$(NOECHO) $(PERLRUNINST) \
Makefile.PL DIR="" \
MAKEFILE=$(MAKE_APERL_FILE) LINKTYPE=static \
MAKEAPERL=1 NORECURS=1 CCCDLFLAGS=
# --- MakeMaker test section:
TEST_VERBOSE=0
TEST_TYPE=test_$(LINKTYPE)
TEST_FILE = test.pl
TEST_FILES = t/*.t
TESTDB_SW = -d
testdb :: testdb_$(LINKTYPE)
test :: $(TEST_TYPE) subdirs-test
subdirs-test ::
$(NOECHO) $(NOOP)
test_dynamic :: pure_all
PERL_DL_NONLAZY=1 $(FULLPERLRUN) "-MExtUtils::Command::MM" "-MTest::Harness" "-e" "undef *Test::Harness::Switches; test_harness($(TEST_VERBOSE), '$(INST_LIB)', '$(INST_ARCHLIB)')" $(TEST_FILES)
testdb_dynamic :: pure_all
PERL_DL_NONLAZY=1 $(FULLPERLRUN) $(TESTDB_SW) "-I$(INST_LIB)" "-I$(INST_ARCHLIB)" $(TEST_FILE)
test_ : test_dynamic
test_static :: test_dynamic
testdb_static :: testdb_dynamic
# --- MakeMaker ppd section:
# Creates a PPD (Perl Package Description) for a binary distribution.
ppd :
$(NOECHO) $(ECHO) '<SOFTPKG NAME="$(DISTNAME)" VERSION="$(VERSION)">' > $(DISTNAME).ppd
$(NOECHO) $(ECHO) ' <ABSTRACT></ABSTRACT>' >> $(DISTNAME).ppd
$(NOECHO) $(ECHO) ' <AUTHOR></AUTHOR>' >> $(DISTNAME).ppd
$(NOECHO) $(ECHO) ' <IMPLEMENTATION>' >> $(DISTNAME).ppd
$(NOECHO) $(ECHO) ' <ARCHITECTURE NAME="i686-linux-gnu-thread-multi-64int-5.22" />' >> $(DISTNAME).ppd
$(NOECHO) $(ECHO) ' <CODEBASE HREF="" />' >> $(DISTNAME).ppd
$(NOECHO) $(ECHO) ' </IMPLEMENTATION>' >> $(DISTNAME).ppd
$(NOECHO) $(ECHO) '</SOFTPKG>' >> $(DISTNAME).ppd
# --- MakeMaker pm_to_blib section:
pm_to_blib : $(FIRST_MAKEFILE) $(TO_INST_PM)
$(NOECHO) $(ABSPERLRUN) -MExtUtils::Install -e 'pm_to_blib({@ARGV}, '\''$(INST_LIB)/auto'\'', q[$(PM_FILTER)], '\''$(PERM_DIR)'\'')' -- \
lib/VFS.pm blib/lib/VFS.pm
$(NOECHO) $(TOUCH) pm_to_blib
# --- MakeMaker selfdocument section:
# --- MakeMaker postamble section:
# End.
| Java |
package org.ljc.adoptojdk.class_name;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ResolveSimpleNameClassName {
private Collection<String> packages = null;
public Collection<String> getPackages() {
Set<String> returnPackages = new HashSet<String>();
for (Package aPackage : Package.getPackages()) {
returnPackages.add(aPackage.getName());
}
return returnPackages;
}
public List<String> getFullyQualifiedNames(String simpleName) {
if (this.packages == null) {
this.packages = getPackages();
}
List<String> fqns = new ArrayList<String>();
for (String aPackage : packages) {
try {
String fqn = aPackage + "." + simpleName;
Class.forName(fqn);
fqns.add(fqn);
} catch (Exception e) {
// Ignore
}
}
return fqns;
}
}
| Java |
/*!
* Bootstrap v3.2.0 (http://getbootstrap.com)
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
/*! normalize.css v3.0.1 | MIT License | git.io/normalize */
html {
font-family: sans-serif;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
body {
margin: 0;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {
display: block;
}
audio,
canvas,
progress,
video {
display: inline-block;
vertical-align: baseline;
}
audio:not([controls]) {
display: none;
height: 0;
}
[hidden],
template {
display: none;
}
a {
background: transparent;
}
a:active,
a:hover {
outline: 0;
}
abbr[title] {
border-bottom: 1px dotted;
}
b,
strong {
font-weight: bold;
}
dfn {
font-style: italic;
}
h1 {
margin: .67em 0;
font-size: 2em;
}
mark {
color: #000;
background: #ff0;
}
small {
font-size: 80%;
}
sub,
sup {
position: relative;
font-size: 75%;
line-height: 0;
vertical-align: baseline;
}
sup {
top: -.5em;
}
sub {
bottom: -.25em;
}
img {
border: 0;
}
svg:not(:root) {
overflow: hidden;
}
figure {
margin: 1em 40px;
}
hr {
height: 0;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
pre {
overflow: auto;
}
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
button,
input,
optgroup,
select,
textarea {
margin: 0;
font: inherit;
color: inherit;
}
button {
overflow: visible;
}
button,
select {
text-transform: none;
}
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button;
cursor: pointer;
}
button[disabled],
html input[disabled] {
cursor: default;
}
button::-moz-focus-inner,
input::-moz-focus-inner {
padding: 0;
border: 0;
}
input {
line-height: normal;
}
input[type="checkbox"],
input[type="radio"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 0;
}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
input[type="search"] {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
-webkit-appearance: textfield;
}
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
fieldset {
padding: .35em .625em .75em;
margin: 0 2px;
border: 1px solid #c0c0c0;
}
legend {
padding: 0;
border: 0;
}
textarea {
overflow: auto;
}
optgroup {
font-weight: bold;
}
table {
border-spacing: 0;
border-collapse: collapse;
}
td,
th {
padding: 0;
}
@media print {
* {
color: #000 !important;
text-shadow: none !important;
background: transparent !important;
-webkit-box-shadow: none !important;
box-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
a[href^="javascript:"]:after,
a[href^="#"]:after {
content: "";
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
thead {
display: table-header-group;
}
tr,
img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
select {
background: #fff !important;
}
.navbar {
display: none;
}
.table td,
.table th {
background-color: #fff !important;
}
.btn > .caret,
.dropup > .btn > .caret {
border-top-color: #000 !important;
}
.label {
border: 1px solid #000;
}
.table {
border-collapse: collapse !important;
}
.table-bordered th,
.table-bordered td {
border: 1px solid #ddd !important;
}
}
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}
.glyphicon {
position: relative;
top: 1px;
display: inline-block;
font-family: 'Glyphicons Halflings';
font-style: normal;
font-weight: normal;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.glyphicon-asterisk:before {
content: "\2a";
}
.glyphicon-plus:before {
content: "\2b";
}
.glyphicon-euro:before {
content: "\20ac";
}
.glyphicon-minus:before {
content: "\2212";
}
.glyphicon-cloud:before {
content: "\2601";
}
.glyphicon-envelope:before {
content: "\2709";
}
.glyphicon-pencil:before {
content: "\270f";
}
.glyphicon-glass:before {
content: "\e001";
}
.glyphicon-music:before {
content: "\e002";
}
.glyphicon-search:before {
content: "\e003";
}
.glyphicon-heart:before {
content: "\e005";
}
.glyphicon-star:before {
content: "\e006";
}
.glyphicon-star-empty:before {
content: "\e007";
}
.glyphicon-user:before {
content: "\e008";
}
.glyphicon-film:before {
content: "\e009";
}
.glyphicon-th-large:before {
content: "\e010";
}
.glyphicon-th:before {
content: "\e011";
}
.glyphicon-th-list:before {
content: "\e012";
}
.glyphicon-ok:before {
content: "\e013";
}
.glyphicon-remove:before {
content: "\e014";
}
.glyphicon-zoom-in:before {
content: "\e015";
}
.glyphicon-zoom-out:before {
content: "\e016";
}
.glyphicon-off:before {
content: "\e017";
}
.glyphicon-signal:before {
content: "\e018";
}
.glyphicon-cog:before {
content: "\e019";
}
.glyphicon-trash:before {
content: "\e020";
}
.glyphicon-home:before {
content: "\e021";
}
.glyphicon-file:before {
content: "\e022";
}
.glyphicon-time:before {
content: "\e023";
}
.glyphicon-road:before {
content: "\e024";
}
.glyphicon-download-alt:before {
content: "\e025";
}
.glyphicon-download:before {
content: "\e026";
}
.glyphicon-upload:before {
content: "\e027";
}
.glyphicon-inbox:before {
content: "\e028";
}
.glyphicon-play-circle:before {
content: "\e029";
}
.glyphicon-repeat:before {
content: "\e030";
}
.glyphicon-refresh:before {
content: "\e031";
}
.glyphicon-list-alt:before {
content: "\e032";
}
.glyphicon-lock:before {
content: "\e033";
}
.glyphicon-flag:before {
content: "\e034";
}
.glyphicon-headphones:before {
content: "\e035";
}
.glyphicon-volume-off:before {
content: "\e036";
}
.glyphicon-volume-down:before {
content: "\e037";
}
.glyphicon-volume-up:before {
content: "\e038";
}
.glyphicon-qrcode:before {
content: "\e039";
}
.glyphicon-barcode:before {
content: "\e040";
}
.glyphicon-tag:before {
content: "\e041";
}
.glyphicon-tags:before {
content: "\e042";
}
.glyphicon-book:before {
content: "\e043";
}
.glyphicon-bookmark:before {
content: "\e044";
}
.glyphicon-print:before {
content: "\e045";
}
.glyphicon-camera:before {
content: "\e046";
}
.glyphicon-font:before {
content: "\e047";
}
.glyphicon-bold:before {
content: "\e048";
}
.glyphicon-italic:before {
content: "\e049";
}
.glyphicon-text-height:before {
content: "\e050";
}
.glyphicon-text-width:before {
content: "\e051";
}
.glyphicon-align-left:before {
content: "\e052";
}
.glyphicon-align-center:before {
content: "\e053";
}
.glyphicon-align-right:before {
content: "\e054";
}
.glyphicon-align-justify:before {
content: "\e055";
}
.glyphicon-list:before {
content: "\e056";
}
.glyphicon-indent-left:before {
content: "\e057";
}
.glyphicon-indent-right:before {
content: "\e058";
}
.glyphicon-facetime-video:before {
content: "\e059";
}
.glyphicon-picture:before {
content: "\e060";
}
.glyphicon-map-marker:before {
content: "\e062";
}
.glyphicon-adjust:before {
content: "\e063";
}
.glyphicon-tint:before {
content: "\e064";
}
.glyphicon-edit:before {
content: "\e065";
}
.glyphicon-share:before {
content: "\e066";
}
.glyphicon-check:before {
content: "\e067";
}
.glyphicon-move:before {
content: "\e068";
}
.glyphicon-step-backward:before {
content: "\e069";
}
.glyphicon-fast-backward:before {
content: "\e070";
}
.glyphicon-backward:before {
content: "\e071";
}
.glyphicon-play:before {
content: "\e072";
}
.glyphicon-pause:before {
content: "\e073";
}
.glyphicon-stop:before {
content: "\e074";
}
.glyphicon-forward:before {
content: "\e075";
}
.glyphicon-fast-forward:before {
content: "\e076";
}
.glyphicon-step-forward:before {
content: "\e077";
}
.glyphicon-eject:before {
content: "\e078";
}
.glyphicon-chevron-left:before {
content: "\e079";
}
.glyphicon-chevron-right:before {
content: "\e080";
}
.glyphicon-plus-sign:before {
content: "\e081";
}
.glyphicon-minus-sign:before {
content: "\e082";
}
.glyphicon-remove-sign:before {
content: "\e083";
}
.glyphicon-ok-sign:before {
content: "\e084";
}
.glyphicon-question-sign:before {
content: "\e085";
}
.glyphicon-info-sign:before {
content: "\e086";
}
.glyphicon-screenshot:before {
content: "\e087";
}
.glyphicon-remove-circle:before {
content: "\e088";
}
.glyphicon-ok-circle:before {
content: "\e089";
}
.glyphicon-ban-circle:before {
content: "\e090";
}
.glyphicon-arrow-left:before {
content: "\e091";
}
.glyphicon-arrow-right:before {
content: "\e092";
}
.glyphicon-arrow-up:before {
content: "\e093";
}
.glyphicon-arrow-down:before {
content: "\e094";
}
.glyphicon-share-alt:before {
content: "\e095";
}
.glyphicon-resize-full:before {
content: "\e096";
}
.glyphicon-resize-small:before {
content: "\e097";
}
.glyphicon-exclamation-sign:before {
content: "\e101";
}
.glyphicon-gift:before {
content: "\e102";
}
.glyphicon-leaf:before {
content: "\e103";
}
.glyphicon-fire:before {
content: "\e104";
}
.glyphicon-eye-open:before {
content: "\e105";
}
.glyphicon-eye-close:before {
content: "\e106";
}
.glyphicon-warning-sign:before {
content: "\e107";
}
.glyphicon-plane:before {
content: "\e108";
}
.glyphicon-calendar:before {
content: "\e109";
}
.glyphicon-random:before {
content: "\e110";
}
.glyphicon-comment:before {
content: "\e111";
}
.glyphicon-magnet:before {
content: "\e112";
}
.glyphicon-chevron-up:before {
content: "\e113";
}
.glyphicon-chevron-down:before {
content: "\e114";
}
.glyphicon-retweet:before {
content: "\e115";
}
.glyphicon-shopping-cart:before {
content: "\e116";
}
.glyphicon-folder-close:before {
content: "\e117";
}
.glyphicon-folder-open:before {
content: "\e118";
}
.glyphicon-resize-vertical:before {
content: "\e119";
}
.glyphicon-resize-horizontal:before {
content: "\e120";
}
.glyphicon-hdd:before {
content: "\e121";
}
.glyphicon-bullhorn:before {
content: "\e122";
}
.glyphicon-bell:before {
content: "\e123";
}
.glyphicon-certificate:before {
content: "\e124";
}
.glyphicon-thumbs-up:before {
content: "\e125";
}
.glyphicon-thumbs-down:before {
content: "\e126";
}
.glyphicon-hand-right:before {
content: "\e127";
}
.glyphicon-hand-left:before {
content: "\e128";
}
.glyphicon-hand-up:before {
content: "\e129";
}
.glyphicon-hand-down:before {
content: "\e130";
}
.glyphicon-circle-arrow-right:before {
content: "\e131";
}
.glyphicon-circle-arrow-left:before {
content: "\e132";
}
.glyphicon-circle-arrow-up:before {
content: "\e133";
}
.glyphicon-circle-arrow-down:before {
content: "\e134";
}
.glyphicon-globe:before {
content: "\e135";
}
.glyphicon-wrench:before {
content: "\e136";
}
.glyphicon-tasks:before {
content: "\e137";
}
.glyphicon-filter:before {
content: "\e138";
}
.glyphicon-briefcase:before {
content: "\e139";
}
.glyphicon-fullscreen:before {
content: "\e140";
}
.glyphicon-dashboard:before {
content: "\e141";
}
.glyphicon-paperclip:before {
content: "\e142";
}
.glyphicon-heart-empty:before {
content: "\e143";
}
.glyphicon-link:before {
content: "\e144";
}
.glyphicon-phone:before {
content: "\e145";
}
.glyphicon-pushpin:before {
content: "\e146";
}
.glyphicon-usd:before {
content: "\e148";
}
.glyphicon-gbp:before {
content: "\e149";
}
.glyphicon-sort:before {
content: "\e150";
}
.glyphicon-sort-by-alphabet:before {
content: "\e151";
}
.glyphicon-sort-by-alphabet-alt:before {
content: "\e152";
}
.glyphicon-sort-by-order:before {
content: "\e153";
}
.glyphicon-sort-by-order-alt:before {
content: "\e154";
}
.glyphicon-sort-by-attributes:before {
content: "\e155";
}
.glyphicon-sort-by-attributes-alt:before {
content: "\e156";
}
.glyphicon-unchecked:before {
content: "\e157";
}
.glyphicon-expand:before {
content: "\e158";
}
.glyphicon-collapse-down:before {
content: "\e159";
}
.glyphicon-collapse-up:before {
content: "\e160";
}
.glyphicon-log-in:before {
content: "\e161";
}
.glyphicon-flash:before {
content: "\e162";
}
.glyphicon-log-out:before {
content: "\e163";
}
.glyphicon-new-window:before {
content: "\e164";
}
.glyphicon-record:before {
content: "\e165";
}
.glyphicon-save:before {
content: "\e166";
}
.glyphicon-open:before {
content: "\e167";
}
.glyphicon-saved:before {
content: "\e168";
}
.glyphicon-import:before {
content: "\e169";
}
.glyphicon-export:before {
content: "\e170";
}
.glyphicon-send:before {
content: "\e171";
}
.glyphicon-floppy-disk:before {
content: "\e172";
}
.glyphicon-floppy-saved:before {
content: "\e173";
}
.glyphicon-floppy-remove:before {
content: "\e174";
}
.glyphicon-floppy-save:before {
content: "\e175";
}
.glyphicon-floppy-open:before {
content: "\e176";
}
.glyphicon-credit-card:before {
content: "\e177";
}
.glyphicon-transfer:before {
content: "\e178";
}
.glyphicon-cutlery:before {
content: "\e179";
}
.glyphicon-header:before {
content: "\e180";
}
.glyphicon-compressed:before {
content: "\e181";
}
.glyphicon-earphone:before {
content: "\e182";
}
.glyphicon-phone-alt:before {
content: "\e183";
}
.glyphicon-tower:before {
content: "\e184";
}
.glyphicon-stats:before {
content: "\e185";
}
.glyphicon-sd-video:before {
content: "\e186";
}
.glyphicon-hd-video:before {
content: "\e187";
}
.glyphicon-subtitles:before {
content: "\e188";
}
.glyphicon-sound-stereo:before {
content: "\e189";
}
.glyphicon-sound-dolby:before {
content: "\e190";
}
.glyphicon-sound-5-1:before {
content: "\e191";
}
.glyphicon-sound-6-1:before {
content: "\e192";
}
.glyphicon-sound-7-1:before {
content: "\e193";
}
.glyphicon-copyright-mark:before {
content: "\e194";
}
.glyphicon-registration-mark:before {
content: "\e195";
}
.glyphicon-cloud-download:before {
content: "\e197";
}
.glyphicon-cloud-upload:before {
content: "\e198";
}
.glyphicon-tree-conifer:before {
content: "\e199";
}
.glyphicon-tree-deciduous:before {
content: "\e200";
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html {
font-size: 10px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.42857143;
color: #333;
background-color: #fff;
}
input,
button,
select,
textarea {
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
a {
color: #428bca;
text-decoration: none;
}
a:hover,
a:focus {
color: #2a6496;
text-decoration: underline;
}
a:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
figure {
margin: 0;
}
img {
vertical-align: middle;
}
.img-responsive,
.thumbnail > img,
.thumbnail a > img,
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
display: block;
width: 100% \9;
max-width: 100%;
height: auto;
}
.img-rounded {
border-radius: 6px;
}
.img-thumbnail {
display: inline-block;
width: 100% \9;
max-width: 100%;
height: auto;
padding: 4px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
-webkit-transition: all .2s ease-in-out;
-o-transition: all .2s ease-in-out;
transition: all .2s ease-in-out;
}
.img-circle {
border-radius: 50%;
}
hr {
margin-top: 20px;
margin-bottom: 20px;
border: 0;
border-top: 1px solid #eee;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
.sr-only-focusable:active,
.sr-only-focusable:focus {
position: static;
width: auto;
height: auto;
margin: 0;
overflow: visible;
clip: auto;
}
h1,
h2,
h3,
h4,
h5,
h6,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {
font-family: inherit;
font-weight: 500;
line-height: 1.1;
color: inherit;
}
h1 small,
h2 small,
h3 small,
h4 small,
h5 small,
h6 small,
.h1 small,
.h2 small,
.h3 small,
.h4 small,
.h5 small,
.h6 small,
h1 .small,
h2 .small,
h3 .small,
h4 .small,
h5 .small,
h6 .small,
.h1 .small,
.h2 .small,
.h3 .small,
.h4 .small,
.h5 .small,
.h6 .small {
font-weight: normal;
line-height: 1;
color: #777;
}
h1,
.h1,
h2,
.h2,
h3,
.h3 {
margin-top: 20px;
margin-bottom: 10px;
}
h1 small,
.h1 small,
h2 small,
.h2 small,
h3 small,
.h3 small,
h1 .small,
.h1 .small,
h2 .small,
.h2 .small,
h3 .small,
.h3 .small {
font-size: 65%;
}
h4,
.h4,
h5,
.h5,
h6,
.h6 {
margin-top: 10px;
margin-bottom: 10px;
}
h4 small,
.h4 small,
h5 small,
.h5 small,
h6 small,
.h6 small,
h4 .small,
.h4 .small,
h5 .small,
.h5 .small,
h6 .small,
.h6 .small {
font-size: 75%;
}
h1,
.h1 {
font-size: 36px;
}
h2,
.h2 {
font-size: 30px;
}
h3,
.h3 {
font-size: 24px;
}
h4,
.h4 {
font-size: 18px;
}
h5,
.h5 {
font-size: 14px;
}
h6,
.h6 {
font-size: 12px;
}
p {
margin: 0 0 10px;
}
.lead {
margin-bottom: 20px;
font-size: 16px;
font-weight: 300;
line-height: 1.4;
}
@media (min-width: 768px) {
.lead {
font-size: 21px;
}
}
small,
.small {
font-size: 85%;
}
cite {
font-style: normal;
}
mark,
.mark {
padding: .2em;
background-color: #fcf8e3;
}
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
.text-justify {
text-align: justify;
}
.text-nowrap {
white-space: nowrap;
}
.text-lowercase {
text-transform: lowercase;
}
.text-uppercase {
text-transform: uppercase;
}
.text-capitalize {
text-transform: capitalize;
}
.text-muted {
color: #777;
}
.text-primary {
color: #428bca;
}
a.text-primary:hover {
color: #3071a9;
}
.text-success {
color: #3c763d;
}
a.text-success:hover {
color: #2b542c;
}
.text-info {
color: #31708f;
}
a.text-info:hover {
color: #245269;
}
.text-warning {
color: #8a6d3b;
}
a.text-warning:hover {
color: #66512c;
}
.text-danger {
color: #a94442;
}
a.text-danger:hover {
color: #843534;
}
.bg-primary {
color: #fff;
background-color: #428bca;
}
a.bg-primary:hover {
background-color: #3071a9;
}
.bg-success {
background-color: #dff0d8;
}
a.bg-success:hover {
background-color: #c1e2b3;
}
.bg-info {
background-color: #d9edf7;
}
a.bg-info:hover {
background-color: #afd9ee;
}
.bg-warning {
background-color: #fcf8e3;
}
a.bg-warning:hover {
background-color: #f7ecb5;
}
.bg-danger {
background-color: #f2dede;
}
a.bg-danger:hover {
background-color: #e4b9b9;
}
.page-header {
padding-bottom: 9px;
margin: 40px 0 20px;
border-bottom: 1px solid #eee;
}
ul,
ol {
margin-top: 0;
margin-bottom: 10px;
}
ul ul,
ol ul,
ul ol,
ol ol {
margin-bottom: 0;
}
.list-unstyled {
padding-left: 0;
list-style: none;
}
.list-inline {
padding-left: 0;
margin-left: -5px;
list-style: none;
}
.list-inline > li {
display: inline-block;
padding-right: 5px;
padding-left: 5px;
}
dl {
margin-top: 0;
margin-bottom: 20px;
}
dt,
dd {
line-height: 1.42857143;
}
dt {
font-weight: bold;
}
dd {
margin-left: 0;
}
@media (min-width: 768px) {
.dl-horizontal dt {
float: left;
width: 160px;
overflow: hidden;
clear: left;
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
}
.dl-horizontal dd {
margin-left: 180px;
}
}
abbr[title],
abbr[data-original-title] {
cursor: help;
border-bottom: 1px dotted #777;
}
.initialism {
font-size: 90%;
text-transform: uppercase;
}
blockquote {
padding: 10px 20px;
margin: 0 0 20px;
font-size: 17.5px;
border-left: 5px solid #eee;
}
blockquote p:last-child,
blockquote ul:last-child,
blockquote ol:last-child {
margin-bottom: 0;
}
blockquote footer,
blockquote small,
blockquote .small {
display: block;
font-size: 80%;
line-height: 1.42857143;
color: #777;
}
blockquote footer:before,
blockquote small:before,
blockquote .small:before {
content: '\2014 \00A0';
}
.blockquote-reverse,
blockquote.pull-right {
padding-right: 15px;
padding-left: 0;
text-align: right;
border-right: 5px solid #eee;
border-left: 0;
}
.blockquote-reverse footer:before,
blockquote.pull-right footer:before,
.blockquote-reverse small:before,
blockquote.pull-right small:before,
.blockquote-reverse .small:before,
blockquote.pull-right .small:before {
content: '';
}
.blockquote-reverse footer:after,
blockquote.pull-right footer:after,
.blockquote-reverse small:after,
blockquote.pull-right small:after,
.blockquote-reverse .small:after,
blockquote.pull-right .small:after {
content: '\00A0 \2014';
}
blockquote:before,
blockquote:after {
content: "";
}
address {
margin-bottom: 20px;
font-style: normal;
line-height: 1.42857143;
}
code,
kbd,
pre,
samp {
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
}
code {
padding: 2px 4px;
font-size: 90%;
color: #c7254e;
background-color: #f9f2f4;
border-radius: 4px;
}
kbd {
padding: 2px 4px;
font-size: 90%;
color: #fff;
background-color: #333;
border-radius: 3px;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25);
}
kbd kbd {
padding: 0;
font-size: 100%;
-webkit-box-shadow: none;
box-shadow: none;
}
pre {
display: block;
padding: 9.5px;
margin: 0 0 10px;
font-size: 13px;
line-height: 1.42857143;
color: #333;
word-break: break-all;
word-wrap: break-word;
background-color: #f5f5f5;
border: 1px solid #ccc;
border-radius: 4px;
}
pre code {
padding: 0;
font-size: inherit;
color: inherit;
white-space: pre-wrap;
background-color: transparent;
border-radius: 0;
}
.pre-scrollable {
max-height: 340px;
overflow-y: scroll;
}
.container {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
}
@media (min-width: 768px) {
.container {
width: 750px;
}
}
@media (min-width: 992px) {
.container {
width: 970px;
}
}
@media (min-width: 1200px) {
.container {
width: 1170px;
}
}
.container-fluid {
padding-right: 6px;
padding-left: 6px;
margin-right: auto;
margin-left: auto;
}
.row {
margin-right: -6px;
margin-left: -6px;
}
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
position: relative;
min-height: 1px;
padding-right: 6px;
padding-left: 6px;
}
.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 {
float: left;
}
.col-xs-12 {
width: 100%;
}
.col-xs-11 {
width: 91.66666667%;
}
.col-xs-10 {
width: 83.33333333%;
}
.col-xs-9 {
width: 75%;
}
.col-xs-8 {
width: 66.66666667%;
}
.col-xs-7 {
width: 58.33333333%;
}
.col-xs-6 {
width: 50%;
}
.col-xs-5 {
width: 41.66666667%;
}
.col-xs-4 {
width: 33.33333333%;
}
.col-xs-3 {
width: 25%;
}
.col-xs-2 {
width: 16.66666667%;
}
.col-xs-1 {
width: 8.33333333%;
}
.col-xs-pull-12 {
right: 100%;
}
.col-xs-pull-11 {
right: 91.66666667%;
}
.col-xs-pull-10 {
right: 83.33333333%;
}
.col-xs-pull-9 {
right: 75%;
}
.col-xs-pull-8 {
right: 66.66666667%;
}
.col-xs-pull-7 {
right: 58.33333333%;
}
.col-xs-pull-6 {
right: 50%;
}
.col-xs-pull-5 {
right: 41.66666667%;
}
.col-xs-pull-4 {
right: 33.33333333%;
}
.col-xs-pull-3 {
right: 25%;
}
.col-xs-pull-2 {
right: 16.66666667%;
}
.col-xs-pull-1 {
right: 8.33333333%;
}
.col-xs-pull-0 {
right: auto;
}
.col-xs-push-12 {
left: 100%;
}
.col-xs-push-11 {
left: 91.66666667%;
}
.col-xs-push-10 {
left: 83.33333333%;
}
.col-xs-push-9 {
left: 75%;
}
.col-xs-push-8 {
left: 66.66666667%;
}
.col-xs-push-7 {
left: 58.33333333%;
}
.col-xs-push-6 {
left: 50%;
}
.col-xs-push-5 {
left: 41.66666667%;
}
.col-xs-push-4 {
left: 33.33333333%;
}
.col-xs-push-3 {
left: 25%;
}
.col-xs-push-2 {
left: 16.66666667%;
}
.col-xs-push-1 {
left: 8.33333333%;
}
.col-xs-push-0 {
left: auto;
}
.col-xs-offset-12 {
margin-left: 100%;
}
.col-xs-offset-11 {
margin-left: 91.66666667%;
}
.col-xs-offset-10 {
margin-left: 83.33333333%;
}
.col-xs-offset-9 {
margin-left: 75%;
}
.col-xs-offset-8 {
margin-left: 66.66666667%;
}
.col-xs-offset-7 {
margin-left: 58.33333333%;
}
.col-xs-offset-6 {
margin-left: 50%;
}
.col-xs-offset-5 {
margin-left: 41.66666667%;
}
.col-xs-offset-4 {
margin-left: 33.33333333%;
}
.col-xs-offset-3 {
margin-left: 25%;
}
.col-xs-offset-2 {
margin-left: 16.66666667%;
}
.col-xs-offset-1 {
margin-left: 8.33333333%;
}
.col-xs-offset-0 {
margin-left: 0;
}
@media (min-width: 768px) {
.col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {
float: left;
}
.col-sm-12 {
width: 100%;
}
.col-sm-11 {
width: 91.66666667%;
}
.col-sm-10 {
width: 83.33333333%;
}
.col-sm-9 {
width: 75%;
}
.col-sm-8 {
width: 66.66666667%;
}
.col-sm-7 {
width: 58.33333333%;
}
.col-sm-6 {
width: 50%;
}
.col-sm-5 {
width: 41.66666667%;
}
.col-sm-4 {
width: 33.33333333%;
}
.col-sm-3 {
width: 25%;
}
.col-sm-2 {
width: 16.66666667%;
}
.col-sm-1 {
width: 8.33333333%;
}
.col-sm-pull-12 {
right: 100%;
}
.col-sm-pull-11 {
right: 91.66666667%;
}
.col-sm-pull-10 {
right: 83.33333333%;
}
.col-sm-pull-9 {
right: 75%;
}
.col-sm-pull-8 {
right: 66.66666667%;
}
.col-sm-pull-7 {
right: 58.33333333%;
}
.col-sm-pull-6 {
right: 50%;
}
.col-sm-pull-5 {
right: 41.66666667%;
}
.col-sm-pull-4 {
right: 33.33333333%;
}
.col-sm-pull-3 {
right: 25%;
}
.col-sm-pull-2 {
right: 16.66666667%;
}
.col-sm-pull-1 {
right: 8.33333333%;
}
.col-sm-pull-0 {
right: auto;
}
.col-sm-push-12 {
left: 100%;
}
.col-sm-push-11 {
left: 91.66666667%;
}
.col-sm-push-10 {
left: 83.33333333%;
}
.col-sm-push-9 {
left: 75%;
}
.col-sm-push-8 {
left: 66.66666667%;
}
.col-sm-push-7 {
left: 58.33333333%;
}
.col-sm-push-6 {
left: 50%;
}
.col-sm-push-5 {
left: 41.66666667%;
}
.col-sm-push-4 {
left: 33.33333333%;
}
.col-sm-push-3 {
left: 25%;
}
.col-sm-push-2 {
left: 16.66666667%;
}
.col-sm-push-1 {
left: 8.33333333%;
}
.col-sm-push-0 {
left: auto;
}
.col-sm-offset-12 {
margin-left: 100%;
}
.col-sm-offset-11 {
margin-left: 91.66666667%;
}
.col-sm-offset-10 {
margin-left: 83.33333333%;
}
.col-sm-offset-9 {
margin-left: 75%;
}
.col-sm-offset-8 {
margin-left: 66.66666667%;
}
.col-sm-offset-7 {
margin-left: 58.33333333%;
}
.col-sm-offset-6 {
margin-left: 50%;
}
.col-sm-offset-5 {
margin-left: 41.66666667%;
}
.col-sm-offset-4 {
margin-left: 33.33333333%;
}
.col-sm-offset-3 {
margin-left: 25%;
}
.col-sm-offset-2 {
margin-left: 16.66666667%;
}
.col-sm-offset-1 {
margin-left: 8.33333333%;
}
.col-sm-offset-0 {
margin-left: 0;
}
}
@media (min-width: 992px) {
.col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
float: left;
}
.col-md-12 {
width: 100%;
}
.col-md-11 {
width: 91.66666667%;
}
.col-md-10 {
width: 83.33333333%;
}
.col-md-9 {
width: 75%;
}
.col-md-8 {
width: 66.66666667%;
}
.col-md-7 {
width: 58.33333333%;
}
.col-md-6 {
width: 50%;
}
.col-md-5 {
width: 41.66666667%;
}
.col-md-4 {
width: 33.33333333%;
}
.col-md-3 {
width: 25%;
}
.col-md-2 {
width: 16.66666667%;
}
.col-md-1 {
width: 8.33333333%;
}
.col-md-pull-12 {
right: 100%;
}
.col-md-pull-11 {
right: 91.66666667%;
}
.col-md-pull-10 {
right: 83.33333333%;
}
.col-md-pull-9 {
right: 75%;
}
.col-md-pull-8 {
right: 66.66666667%;
}
.col-md-pull-7 {
right: 58.33333333%;
}
.col-md-pull-6 {
right: 50%;
}
.col-md-pull-5 {
right: 41.66666667%;
}
.col-md-pull-4 {
right: 33.33333333%;
}
.col-md-pull-3 {
right: 25%;
}
.col-md-pull-2 {
right: 16.66666667%;
}
.col-md-pull-1 {
right: 8.33333333%;
}
.col-md-pull-0 {
right: auto;
}
.col-md-push-12 {
left: 100%;
}
.col-md-push-11 {
left: 91.66666667%;
}
.col-md-push-10 {
left: 83.33333333%;
}
.col-md-push-9 {
left: 75%;
}
.col-md-push-8 {
left: 66.66666667%;
}
.col-md-push-7 {
left: 58.33333333%;
}
.col-md-push-6 {
left: 50%;
}
.col-md-push-5 {
left: 41.66666667%;
}
.col-md-push-4 {
left: 33.33333333%;
}
.col-md-push-3 {
left: 25%;
}
.col-md-push-2 {
left: 16.66666667%;
}
.col-md-push-1 {
left: 8.33333333%;
}
.col-md-push-0 {
left: auto;
}
.col-md-offset-12 {
margin-left: 100%;
}
.col-md-offset-11 {
margin-left: 91.66666667%;
}
.col-md-offset-10 {
margin-left: 83.33333333%;
}
.col-md-offset-9 {
margin-left: 75%;
}
.col-md-offset-8 {
margin-left: 66.66666667%;
}
.col-md-offset-7 {
margin-left: 58.33333333%;
}
.col-md-offset-6 {
margin-left: 50%;
}
.col-md-offset-5 {
margin-left: 41.66666667%;
}
.col-md-offset-4 {
margin-left: 33.33333333%;
}
.col-md-offset-3 {
margin-left: 25%;
}
.col-md-offset-2 {
margin-left: 16.66666667%;
}
.col-md-offset-1 {
margin-left: 8.33333333%;
}
.col-md-offset-0 {
margin-left: 0;
}
}
@media (min-width: 1200px) {
.col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 {
float: left;
}
.col-lg-12 {
width: 100%;
}
.col-lg-11 {
width: 91.66666667%;
}
.col-lg-10 {
width: 83.33333333%;
}
.col-lg-9 {
width: 75%;
}
.col-lg-8 {
width: 66.66666667%;
}
.col-lg-7 {
width: 58.33333333%;
}
.col-lg-6 {
width: 50%;
}
.col-lg-5 {
width: 41.66666667%;
}
.col-lg-4 {
width: 33.33333333%;
}
.col-lg-3 {
width: 25%;
}
.col-lg-2 {
width: 16.66666667%;
}
.col-lg-1 {
width: 8.33333333%;
}
.col-lg-pull-12 {
right: 100%;
}
.col-lg-pull-11 {
right: 91.66666667%;
}
.col-lg-pull-10 {
right: 83.33333333%;
}
.col-lg-pull-9 {
right: 75%;
}
.col-lg-pull-8 {
right: 66.66666667%;
}
.col-lg-pull-7 {
right: 58.33333333%;
}
.col-lg-pull-6 {
right: 50%;
}
.col-lg-pull-5 {
right: 41.66666667%;
}
.col-lg-pull-4 {
right: 33.33333333%;
}
.col-lg-pull-3 {
right: 25%;
}
.col-lg-pull-2 {
right: 16.66666667%;
}
.col-lg-pull-1 {
right: 8.33333333%;
}
.col-lg-pull-0 {
right: auto;
}
.col-lg-push-12 {
left: 100%;
}
.col-lg-push-11 {
left: 91.66666667%;
}
.col-lg-push-10 {
left: 83.33333333%;
}
.col-lg-push-9 {
left: 75%;
}
.col-lg-push-8 {
left: 66.66666667%;
}
.col-lg-push-7 {
left: 58.33333333%;
}
.col-lg-push-6 {
left: 50%;
}
.col-lg-push-5 {
left: 41.66666667%;
}
.col-lg-push-4 {
left: 33.33333333%;
}
.col-lg-push-3 {
left: 25%;
}
.col-lg-push-2 {
left: 16.66666667%;
}
.col-lg-push-1 {
left: 8.33333333%;
}
.col-lg-push-0 {
left: auto;
}
.col-lg-offset-12 {
margin-left: 100%;
}
.col-lg-offset-11 {
margin-left: 91.66666667%;
}
.col-lg-offset-10 {
margin-left: 83.33333333%;
}
.col-lg-offset-9 {
margin-left: 75%;
}
.col-lg-offset-8 {
margin-left: 66.66666667%;
}
.col-lg-offset-7 {
margin-left: 58.33333333%;
}
.col-lg-offset-6 {
margin-left: 50%;
}
.col-lg-offset-5 {
margin-left: 41.66666667%;
}
.col-lg-offset-4 {
margin-left: 33.33333333%;
}
.col-lg-offset-3 {
margin-left: 25%;
}
.col-lg-offset-2 {
margin-left: 16.66666667%;
}
.col-lg-offset-1 {
margin-left: 8.33333333%;
}
.col-lg-offset-0 {
margin-left: 0;
}
}
table {
background-color: transparent;
}
th {
text-align: left;
}
.table {
width: 100%;
max-width: 100%;
margin-bottom: 20px;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
padding: 8px;
line-height: 1.42857143;
vertical-align: top;
border-top: 1px solid #ddd;
}
.table > thead > tr > th {
vertical-align: bottom;
border-bottom: 2px solid #ddd;
}
.table > caption + thead > tr:first-child > th,
.table > colgroup + thead > tr:first-child > th,
.table > thead:first-child > tr:first-child > th,
.table > caption + thead > tr:first-child > td,
.table > colgroup + thead > tr:first-child > td,
.table > thead:first-child > tr:first-child > td {
border-top: 0;
}
.table > tbody + tbody {
border-top: 2px solid #ddd;
}
.table .table {
background-color: #fff;
}
.table-condensed > thead > tr > th,
.table-condensed > tbody > tr > th,
.table-condensed > tfoot > tr > th,
.table-condensed > thead > tr > td,
.table-condensed > tbody > tr > td,
.table-condensed > tfoot > tr > td {
padding: 5px;
}
.table-bordered {
border: 1px solid #ddd;
}
.table-bordered > thead > tr > th,
.table-bordered > tbody > tr > th,
.table-bordered > tfoot > tr > th,
.table-bordered > thead > tr > td,
.table-bordered > tbody > tr > td,
.table-bordered > tfoot > tr > td {
border: 1px solid #ddd;
}
.table-bordered > thead > tr > th,
.table-bordered > thead > tr > td {
border-bottom-width: 2px;
}
.table-striped > tbody > tr:nth-child(odd) > td,
.table-striped > tbody > tr:nth-child(odd) > th {
background-color: #f9f9f9;
}
.table-hover > tbody > tr:hover > td,
.table-hover > tbody > tr:hover > th {
background-color: #f5f5f5;
}
table col[class*="col-"] {
position: static;
display: table-column;
float: none;
}
table td[class*="col-"],
table th[class*="col-"] {
position: static;
display: table-cell;
float: none;
}
.table > thead > tr > td.active,
.table > tbody > tr > td.active,
.table > tfoot > tr > td.active,
.table > thead > tr > th.active,
.table > tbody > tr > th.active,
.table > tfoot > tr > th.active,
.table > thead > tr.active > td,
.table > tbody > tr.active > td,
.table > tfoot > tr.active > td,
.table > thead > tr.active > th,
.table > tbody > tr.active > th,
.table > tfoot > tr.active > th {
background-color: #f5f5f5;
}
.table-hover > tbody > tr > td.active:hover,
.table-hover > tbody > tr > th.active:hover,
.table-hover > tbody > tr.active:hover > td,
.table-hover > tbody > tr:hover > .active,
.table-hover > tbody > tr.active:hover > th {
background-color: #e8e8e8;
}
.table > thead > tr > td.success,
.table > tbody > tr > td.success,
.table > tfoot > tr > td.success,
.table > thead > tr > th.success,
.table > tbody > tr > th.success,
.table > tfoot > tr > th.success,
.table > thead > tr.success > td,
.table > tbody > tr.success > td,
.table > tfoot > tr.success > td,
.table > thead > tr.success > th,
.table > tbody > tr.success > th,
.table > tfoot > tr.success > th {
background-color: #dff0d8;
}
.table-hover > tbody > tr > td.success:hover,
.table-hover > tbody > tr > th.success:hover,
.table-hover > tbody > tr.success:hover > td,
.table-hover > tbody > tr:hover > .success,
.table-hover > tbody > tr.success:hover > th {
background-color: #d0e9c6;
}
.table > thead > tr > td.info,
.table > tbody > tr > td.info,
.table > tfoot > tr > td.info,
.table > thead > tr > th.info,
.table > tbody > tr > th.info,
.table > tfoot > tr > th.info,
.table > thead > tr.info > td,
.table > tbody > tr.info > td,
.table > tfoot > tr.info > td,
.table > thead > tr.info > th,
.table > tbody > tr.info > th,
.table > tfoot > tr.info > th {
background-color: #d9edf7;
}
.table-hover > tbody > tr > td.info:hover,
.table-hover > tbody > tr > th.info:hover,
.table-hover > tbody > tr.info:hover > td,
.table-hover > tbody > tr:hover > .info,
.table-hover > tbody > tr.info:hover > th {
background-color: #c4e3f3;
}
.table > thead > tr > td.warning,
.table > tbody > tr > td.warning,
.table > tfoot > tr > td.warning,
.table > thead > tr > th.warning,
.table > tbody > tr > th.warning,
.table > tfoot > tr > th.warning,
.table > thead > tr.warning > td,
.table > tbody > tr.warning > td,
.table > tfoot > tr.warning > td,
.table > thead > tr.warning > th,
.table > tbody > tr.warning > th,
.table > tfoot > tr.warning > th {
background-color: #fcf8e3;
}
.table-hover > tbody > tr > td.warning:hover,
.table-hover > tbody > tr > th.warning:hover,
.table-hover > tbody > tr.warning:hover > td,
.table-hover > tbody > tr:hover > .warning,
.table-hover > tbody > tr.warning:hover > th {
background-color: #faf2cc;
}
.table > thead > tr > td.danger,
.table > tbody > tr > td.danger,
.table > tfoot > tr > td.danger,
.table > thead > tr > th.danger,
.table > tbody > tr > th.danger,
.table > tfoot > tr > th.danger,
.table > thead > tr.danger > td,
.table > tbody > tr.danger > td,
.table > tfoot > tr.danger > td,
.table > thead > tr.danger > th,
.table > tbody > tr.danger > th,
.table > tfoot > tr.danger > th {
background-color: #f2dede;
}
.table-hover > tbody > tr > td.danger:hover,
.table-hover > tbody > tr > th.danger:hover,
.table-hover > tbody > tr.danger:hover > td,
.table-hover > tbody > tr:hover > .danger,
.table-hover > tbody > tr.danger:hover > th {
background-color: #ebcccc;
}
@media screen and (max-width: 767px) {
.table-responsive {
width: 100%;
margin-bottom: 15px;
overflow-x: auto;
overflow-y: hidden;
-webkit-overflow-scrolling: touch;
-ms-overflow-style: -ms-autohiding-scrollbar;
border: 1px solid #ddd;
}
.table-responsive > .table {
margin-bottom: 0;
}
.table-responsive > .table > thead > tr > th,
.table-responsive > .table > tbody > tr > th,
.table-responsive > .table > tfoot > tr > th,
.table-responsive > .table > thead > tr > td,
.table-responsive > .table > tbody > tr > td,
.table-responsive > .table > tfoot > tr > td {
white-space: nowrap;
}
.table-responsive > .table-bordered {
border: 0;
}
.table-responsive > .table-bordered > thead > tr > th:first-child,
.table-responsive > .table-bordered > tbody > tr > th:first-child,
.table-responsive > .table-bordered > tfoot > tr > th:first-child,
.table-responsive > .table-bordered > thead > tr > td:first-child,
.table-responsive > .table-bordered > tbody > tr > td:first-child,
.table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.table-responsive > .table-bordered > thead > tr > th:last-child,
.table-responsive > .table-bordered > tbody > tr > th:last-child,
.table-responsive > .table-bordered > tfoot > tr > th:last-child,
.table-responsive > .table-bordered > thead > tr > td:last-child,
.table-responsive > .table-bordered > tbody > tr > td:last-child,
.table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.table-responsive > .table-bordered > tbody > tr:last-child > th,
.table-responsive > .table-bordered > tfoot > tr:last-child > th,
.table-responsive > .table-bordered > tbody > tr:last-child > td,
.table-responsive > .table-bordered > tfoot > tr:last-child > td {
border-bottom: 0;
}
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
display: block;
width: 100%;
padding: 0;
margin-bottom: 20px;
font-size: 21px;
line-height: inherit;
color: #333;
border: 0;
border-bottom: 1px solid #e5e5e5;
}
label {
display: inline-block;
max-width: 100%;
margin-bottom: 5px;
font-weight: bold;
}
input[type="search"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
input[type="radio"],
input[type="checkbox"] {
margin: 4px 0 0;
margin-top: 1px \9;
line-height: normal;
}
input[type="file"] {
display: block;
}
input[type="range"] {
display: block;
width: 100%;
}
select[multiple],
select[size] {
height: auto;
}
input[type="file"]:focus,
input[type="radio"]:focus,
input[type="checkbox"]:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
output {
display: block;
padding-top: 7px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
}
.form-control {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
.form-control:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6);
}
.form-control::-moz-placeholder {
color: #777;
opacity: 1;
}
.form-control:-ms-input-placeholder {
color: #777;
}
.form-control::-webkit-input-placeholder {
color: #777;
}
.form-control[disabled],
.form-control[readonly],
fieldset[disabled] .form-control {
cursor: not-allowed;
background-color: #eee;
opacity: 1;
}
textarea.form-control {
height: auto;
}
input[type="search"] {
-webkit-appearance: none;
}
input[type="date"],
input[type="time"],
input[type="datetime-local"],
input[type="month"] {
line-height: 34px;
line-height: 1.42857143 \0;
}
input[type="date"].input-sm,
input[type="time"].input-sm,
input[type="datetime-local"].input-sm,
input[type="month"].input-sm {
line-height: 30px;
}
input[type="date"].input-lg,
input[type="time"].input-lg,
input[type="datetime-local"].input-lg,
input[type="month"].input-lg {
line-height: 46px;
}
.form-group {
margin-bottom: 15px;
}
.radio,
.checkbox {
position: relative;
display: block;
min-height: 20px;
margin-top: 10px;
margin-bottom: 10px;
}
.radio label,
.checkbox label {
padding-left: 20px;
margin-bottom: 0;
font-weight: normal;
cursor: pointer;
}
.radio input[type="radio"],
.radio-inline input[type="radio"],
.checkbox input[type="checkbox"],
.checkbox-inline input[type="checkbox"] {
position: absolute;
margin-top: 4px \9;
margin-left: -20px;
}
.radio + .radio,
.checkbox + .checkbox {
margin-top: -5px;
}
.radio-inline,
.checkbox-inline {
display: inline-block;
padding-left: 20px;
margin-bottom: 0;
font-weight: normal;
vertical-align: middle;
cursor: pointer;
}
.radio-inline + .radio-inline,
.checkbox-inline + .checkbox-inline {
margin-top: 0;
margin-left: 10px;
}
input[type="radio"][disabled],
input[type="checkbox"][disabled],
input[type="radio"].disabled,
input[type="checkbox"].disabled,
fieldset[disabled] input[type="radio"],
fieldset[disabled] input[type="checkbox"] {
cursor: not-allowed;
}
.radio-inline.disabled,
.checkbox-inline.disabled,
fieldset[disabled] .radio-inline,
fieldset[disabled] .checkbox-inline {
cursor: not-allowed;
}
.radio.disabled label,
.checkbox.disabled label,
fieldset[disabled] .radio label,
fieldset[disabled] .checkbox label {
cursor: not-allowed;
}
.form-control-static {
padding-top: 7px;
padding-bottom: 7px;
margin-bottom: 0;
}
.form-control-static.input-lg,
.form-control-static.input-sm {
padding-right: 0;
padding-left: 0;
}
.input-sm,
.form-horizontal .form-group-sm .form-control {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
select.input-sm {
height: 30px;
line-height: 30px;
}
textarea.input-sm,
select[multiple].input-sm {
height: auto;
}
.input-lg,
.form-horizontal .form-group-lg .form-control {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 6px;
}
select.input-lg {
height: 46px;
line-height: 46px;
}
textarea.input-lg,
select[multiple].input-lg {
height: auto;
}
.has-feedback {
position: relative;
}
.has-feedback .form-control {
padding-right: 42.5px;
}
.form-control-feedback {
position: absolute;
top: 25px;
right: 0;
z-index: 2;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
}
.input-lg + .form-control-feedback {
width: 46px;
height: 46px;
line-height: 46px;
}
.input-sm + .form-control-feedback {
width: 30px;
height: 30px;
line-height: 30px;
}
.has-success .help-block,
.has-success .control-label,
.has-success .radio,
.has-success .checkbox,
.has-success .radio-inline,
.has-success .checkbox-inline {
color: #3c763d;
}
.has-success .form-control {
border-color: #3c763d;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-success .form-control:focus {
border-color: #2b542c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168;
}
.has-success .input-group-addon {
color: #3c763d;
background-color: #dff0d8;
border-color: #3c763d;
}
.has-success .form-control-feedback {
color: #3c763d;
}
.has-warning .help-block,
.has-warning .control-label,
.has-warning .radio,
.has-warning .checkbox,
.has-warning .radio-inline,
.has-warning .checkbox-inline {
color: #8a6d3b;
}
.has-warning .form-control {
border-color: #8a6d3b;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-warning .form-control:focus {
border-color: #66512c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b;
}
.has-warning .input-group-addon {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #8a6d3b;
}
.has-warning .form-control-feedback {
color: #8a6d3b;
}
.has-error .help-block,
.has-error .control-label,
.has-error .radio,
.has-error .checkbox,
.has-error .radio-inline,
.has-error .checkbox-inline {
color: #a94442;
}
.has-error .form-control {
border-color: #a94442;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.has-error .form-control:focus {
border-color: #843534;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
}
.has-error .input-group-addon {
color: #a94442;
background-color: #f2dede;
border-color: #a94442;
}
.has-error .form-control-feedback {
color: #a94442;
}
.has-feedback label.sr-only ~ .form-control-feedback {
top: 0;
}
.help-block {
display: block;
margin-top: 5px;
margin-bottom: 10px;
color: #737373;
}
@media (min-width: 768px) {
.form-inline .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.form-inline .input-group {
display: inline-table;
vertical-align: middle;
}
.form-inline .input-group .input-group-addon,
.form-inline .input-group .input-group-btn,
.form-inline .input-group .form-control {
width: auto;
}
.form-inline .input-group > .form-control {
width: 100%;
}
.form-inline .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio,
.form-inline .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio label,
.form-inline .checkbox label {
padding-left: 0;
}
.form-inline .radio input[type="radio"],
.form-inline .checkbox input[type="checkbox"] {
position: relative;
margin-left: 0;
}
.form-inline .has-feedback .form-control-feedback {
top: 0;
}
}
.form-horizontal .radio,
.form-horizontal .checkbox,
.form-horizontal .radio-inline,
.form-horizontal .checkbox-inline {
padding-top: 7px;
margin-top: 0;
margin-bottom: 0;
}
.form-horizontal .radio,
.form-horizontal .checkbox {
min-height: 27px;
}
.form-horizontal .form-group {
margin-right: -15px;
margin-left: -15px;
}
@media (min-width: 768px) {
.form-horizontal .control-label {
padding-top: 7px;
margin-bottom: 0;
text-align: right;
}
}
.form-horizontal .has-feedback .form-control-feedback {
top: 0;
right: 15px;
}
@media (min-width: 768px) {
.form-horizontal .form-group-lg .control-label {
padding-top: 14.3px;
}
}
@media (min-width: 768px) {
.form-horizontal .form-group-sm .control-label {
padding-top: 6px;
}
}
.btn {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: normal;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
.btn:focus,
.btn:active:focus,
.btn.active:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
.btn:hover,
.btn:focus {
color: #333;
text-decoration: none;
}
.btn:active,
.btn.active {
background-image: none;
outline: 0;
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
}
.btn.disabled,
.btn[disabled],
fieldset[disabled] .btn {
pointer-events: none;
cursor: not-allowed;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
opacity: .65;
}
.btn-default {
color: #333;
background-color: #fff;
border-color: #ccc;
}
.btn-default:hover,
.btn-default:focus,
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
color: #333;
background-color: #e6e6e6;
border-color: #adadad;
}
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
background-image: none;
}
.btn-default.disabled,
.btn-default[disabled],
fieldset[disabled] .btn-default,
.btn-default.disabled:hover,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default:hover,
.btn-default.disabled:focus,
.btn-default[disabled]:focus,
fieldset[disabled] .btn-default:focus,
.btn-default.disabled:active,
.btn-default[disabled]:active,
fieldset[disabled] .btn-default:active,
.btn-default.disabled.active,
.btn-default[disabled].active,
fieldset[disabled] .btn-default.active {
background-color: #fff;
border-color: #ccc;
}
.btn-default .badge {
color: #fff;
background-color: #333;
}
.btn-primary {
color: #fff;
background-color: #428bca;
border-color: #357ebd;
}
.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
color: #fff;
background-color: #3071a9;
border-color: #285e8e;
}
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
background-image: none;
}
.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
background-color: #428bca;
border-color: #357ebd;
}
.btn-primary .badge {
color: #428bca;
background-color: #fff;
}
.btn-success {
color: #fff;
background-color: #5cb85c;
border-color: #4cae4c;
}
.btn-success:hover,
.btn-success:focus,
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
color: #fff;
background-color: #449d44;
border-color: #398439;
}
.btn-success:active,
.btn-success.active,
.open > .dropdown-toggle.btn-success {
background-image: none;
}
.btn-success.disabled,
.btn-success[disabled],
fieldset[disabled] .btn-success,
.btn-success.disabled:hover,
.btn-success[disabled]:hover,
fieldset[disabled] .btn-success:hover,
.btn-success.disabled:focus,
.btn-success[disabled]:focus,
fieldset[disabled] .btn-success:focus,
.btn-success.disabled:active,
.btn-success[disabled]:active,
fieldset[disabled] .btn-success:active,
.btn-success.disabled.active,
.btn-success[disabled].active,
fieldset[disabled] .btn-success.active {
background-color: #5cb85c;
border-color: #4cae4c;
}
.btn-success .badge {
color: #5cb85c;
background-color: #fff;
}
.btn-info {
color: #fff;
background-color: #5bc0de;
border-color: #46b8da;
}
.btn-info:hover,
.btn-info:focus,
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
color: #fff;
background-color: #31b0d5;
border-color: #269abc;
}
.btn-info:active,
.btn-info.active,
.open > .dropdown-toggle.btn-info {
background-image: none;
}
.btn-info.disabled,
.btn-info[disabled],
fieldset[disabled] .btn-info,
.btn-info.disabled:hover,
.btn-info[disabled]:hover,
fieldset[disabled] .btn-info:hover,
.btn-info.disabled:focus,
.btn-info[disabled]:focus,
fieldset[disabled] .btn-info:focus,
.btn-info.disabled:active,
.btn-info[disabled]:active,
fieldset[disabled] .btn-info:active,
.btn-info.disabled.active,
.btn-info[disabled].active,
fieldset[disabled] .btn-info.active {
background-color: #5bc0de;
border-color: #46b8da;
}
.btn-info .badge {
color: #5bc0de;
background-color: #fff;
}
.btn-warning {
color: #fff;
background-color: #f0ad4e;
border-color: #eea236;
}
.btn-warning:hover,
.btn-warning:focus,
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
color: #fff;
background-color: #ec971f;
border-color: #d58512;
}
.btn-warning:active,
.btn-warning.active,
.open > .dropdown-toggle.btn-warning {
background-image: none;
}
.btn-warning.disabled,
.btn-warning[disabled],
fieldset[disabled] .btn-warning,
.btn-warning.disabled:hover,
.btn-warning[disabled]:hover,
fieldset[disabled] .btn-warning:hover,
.btn-warning.disabled:focus,
.btn-warning[disabled]:focus,
fieldset[disabled] .btn-warning:focus,
.btn-warning.disabled:active,
.btn-warning[disabled]:active,
fieldset[disabled] .btn-warning:active,
.btn-warning.disabled.active,
.btn-warning[disabled].active,
fieldset[disabled] .btn-warning.active {
background-color: #f0ad4e;
border-color: #eea236;
}
.btn-warning .badge {
color: #f0ad4e;
background-color: #fff;
}
.btn-danger {
color: #fff;
background-color: #d9534f;
border-color: #d43f3a;
}
.btn-danger:hover,
.btn-danger:focus,
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
color: #fff;
background-color: #c9302c;
border-color: #ac2925;
}
.btn-danger:active,
.btn-danger.active,
.open > .dropdown-toggle.btn-danger {
background-image: none;
}
.btn-danger.disabled,
.btn-danger[disabled],
fieldset[disabled] .btn-danger,
.btn-danger.disabled:hover,
.btn-danger[disabled]:hover,
fieldset[disabled] .btn-danger:hover,
.btn-danger.disabled:focus,
.btn-danger[disabled]:focus,
fieldset[disabled] .btn-danger:focus,
.btn-danger.disabled:active,
.btn-danger[disabled]:active,
fieldset[disabled] .btn-danger:active,
.btn-danger.disabled.active,
.btn-danger[disabled].active,
fieldset[disabled] .btn-danger.active {
background-color: #d9534f;
border-color: #d43f3a;
}
.btn-danger .badge {
color: #d9534f;
background-color: #fff;
}
.btn-link {
font-weight: normal;
color: #428bca;
cursor: pointer;
border-radius: 0;
}
.btn-link,
.btn-link:active,
.btn-link[disabled],
fieldset[disabled] .btn-link {
background-color: transparent;
-webkit-box-shadow: none;
box-shadow: none;
}
.btn-link,
.btn-link:hover,
.btn-link:focus,
.btn-link:active {
border-color: transparent;
}
.btn-link:hover,
.btn-link:focus {
color: #2a6496;
text-decoration: underline;
background-color: transparent;
}
.btn-link[disabled]:hover,
fieldset[disabled] .btn-link:hover,
.btn-link[disabled]:focus,
fieldset[disabled] .btn-link:focus {
color: #777;
text-decoration: none;
}
.btn-lg,
.btn-group-lg > .btn {
padding: 10px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 6px;
}
.btn-sm,
.btn-group-sm > .btn {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.btn-xs,
.btn-group-xs > .btn {
padding: 1px 5px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.btn-block {
display: block;
width: 100%;
}
.btn-block + .btn-block {
margin-top: 5px;
}
input[type="submit"].btn-block,
input[type="reset"].btn-block,
input[type="button"].btn-block {
width: 100%;
}
.fade {
opacity: 0;
-webkit-transition: opacity .15s linear;
-o-transition: opacity .15s linear;
transition: opacity .15s linear;
}
.fade.in {
opacity: 1;
}
.collapse {
display: none;
}
.collapse.in {
display: block;
}
tr.collapse.in {
display: table-row;
}
tbody.collapse.in {
display: table-row-group;
}
.collapsing {
position: relative;
height: 0;
overflow: hidden;
-webkit-transition: height .35s ease;
-o-transition: height .35s ease;
transition: height .35s ease;
}
.caret {
display: inline-block;
width: 0;
height: 0;
margin-left: 2px;
vertical-align: middle;
border-top: 4px solid;
border-right: 4px solid transparent;
border-left: 4px solid transparent;
}
.dropdown {
position: relative;
}
.dropdown-toggle:focus {
outline: 0;
}
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
font-size: 14px;
text-align: left;
list-style: none;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
box-shadow: 0 6px 12px rgba(0, 0, 0, .175);
}
.dropdown-menu.pull-right {
right: 0;
left: auto;
}
.dropdown-menu .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.dropdown-menu > li > a {
display: block;
padding: 3px 20px;
clear: both;
font-weight: normal;
line-height: 1.42857143;
color: #333;
white-space: nowrap;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
color: #262626;
text-decoration: none;
background-color: #f5f5f5;
}
.dropdown-menu > .active > a,
.dropdown-menu > .active > a:hover,
.dropdown-menu > .active > a:focus {
color: #fff;
text-decoration: none;
background-color: #428bca;
outline: 0;
}
.dropdown-menu > .disabled > a,
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
color: #777;
}
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
text-decoration: none;
cursor: not-allowed;
background-color: transparent;
background-image: none;
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
}
.open > .dropdown-menu {
display: block;
}
.open > a {
outline: 0;
}
.dropdown-menu-right {
right: 0;
left: auto;
}
.dropdown-menu-left {
right: auto;
left: 0;
}
.dropdown-header {
display: block;
padding: 3px 20px;
font-size: 12px;
line-height: 1.42857143;
color: #777;
white-space: nowrap;
}
.dropdown-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 990;
}
.pull-right > .dropdown-menu {
right: 0;
left: auto;
}
.dropup .caret,
.navbar-fixed-bottom .dropdown .caret {
content: "";
border-top: 0;
border-bottom: 4px solid;
}
.dropup .dropdown-menu,
.navbar-fixed-bottom .dropdown .dropdown-menu {
top: auto;
bottom: 100%;
margin-bottom: 1px;
}
@media (min-width: 768px) {
.navbar-right .dropdown-menu {
right: 0;
left: auto;
}
.navbar-right .dropdown-menu-left {
right: auto;
left: 0;
}
}
.btn-group,
.btn-group-vertical {
position: relative;
display: inline-block;
vertical-align: middle;
}
.btn-group > .btn,
.btn-group-vertical > .btn {
position: relative;
float: left;
}
.btn-group > .btn:hover,
.btn-group-vertical > .btn:hover,
.btn-group > .btn:focus,
.btn-group-vertical > .btn:focus,
.btn-group > .btn:active,
.btn-group-vertical > .btn:active,
.btn-group > .btn.active,
.btn-group-vertical > .btn.active {
z-index: 2;
}
.btn-group > .btn:focus,
.btn-group-vertical > .btn:focus {
outline: 0;
}
.btn-group .btn + .btn,
.btn-group .btn + .btn-group,
.btn-group .btn-group + .btn,
.btn-group .btn-group + .btn-group {
margin-left: -1px;
}
.btn-toolbar {
margin-left: -5px;
}
.btn-toolbar .btn-group,
.btn-toolbar .input-group {
float: left;
}
.btn-toolbar > .btn,
.btn-toolbar > .btn-group,
.btn-toolbar > .input-group {
margin-left: 5px;
}
.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
border-radius: 0;
}
.btn-group > .btn:first-child {
margin-left: 0;
}
.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.btn-group > .btn:last-child:not(:first-child),
.btn-group > .dropdown-toggle:not(:first-child) {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group > .btn-group {
float: left;
}
.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group > .btn-group:first-child > .btn:last-child,
.btn-group > .btn-group:first-child > .dropdown-toggle {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.btn-group > .btn-group:last-child > .btn:first-child {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group .dropdown-toggle:active,
.btn-group.open .dropdown-toggle {
outline: 0;
}
.btn-group > .btn + .dropdown-toggle {
padding-right: 8px;
padding-left: 8px;
}
.btn-group > .btn-lg + .dropdown-toggle {
padding-right: 12px;
padding-left: 12px;
}
.btn-group.open .dropdown-toggle {
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
}
.btn-group.open .dropdown-toggle.btn-link {
-webkit-box-shadow: none;
box-shadow: none;
}
.btn .caret {
margin-left: 0;
}
.btn-lg .caret {
border-width: 5px 5px 0;
border-bottom-width: 0;
}
.dropup .btn-lg .caret {
border-width: 0 5px 5px;
}
.btn-group-vertical > .btn,
.btn-group-vertical > .btn-group,
.btn-group-vertical > .btn-group > .btn {
display: block;
float: none;
width: 100%;
max-width: 100%;
}
.btn-group-vertical > .btn-group > .btn {
float: none;
}
.btn-group-vertical > .btn + .btn,
.btn-group-vertical > .btn + .btn-group,
.btn-group-vertical > .btn-group + .btn,
.btn-group-vertical > .btn-group + .btn-group {
margin-top: -1px;
margin-left: 0;
}
.btn-group-vertical > .btn:not(:first-child):not(:last-child) {
border-radius: 0;
}
.btn-group-vertical > .btn:first-child:not(:last-child) {
border-top-right-radius: 4px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn:last-child:not(:first-child) {
border-top-left-radius: 0;
border-top-right-radius: 0;
border-bottom-left-radius: 4px;
}
.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child,
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.btn-group-justified {
display: table;
width: 100%;
table-layout: fixed;
border-collapse: separate;
}
.btn-group-justified > .btn,
.btn-group-justified > .btn-group {
display: table-cell;
float: none;
width: 1%;
}
.btn-group-justified > .btn-group .btn {
width: 100%;
}
.btn-group-justified > .btn-group .dropdown-menu {
left: auto;
}
[data-toggle="buttons"] > .btn > input[type="radio"],
[data-toggle="buttons"] > .btn > input[type="checkbox"] {
position: absolute;
z-index: -1;
filter: alpha(opacity=0);
opacity: 0;
}
.input-group {
position: relative;
display: table;
border-collapse: separate;
}
.input-group[class*="col-"] {
float: none;
padding-right: 0;
padding-left: 0;
}
.input-group .form-control {
position: relative;
z-index: 2;
float: left;
width: 100%;
margin-bottom: 0;
}
.input-group-lg > .form-control,
.input-group-lg > .input-group-addon,
.input-group-lg > .input-group-btn > .btn {
height: 46px;
padding: 10px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 6px;
}
select.input-group-lg > .form-control,
select.input-group-lg > .input-group-addon,
select.input-group-lg > .input-group-btn > .btn {
height: 46px;
line-height: 46px;
}
textarea.input-group-lg > .form-control,
textarea.input-group-lg > .input-group-addon,
textarea.input-group-lg > .input-group-btn > .btn,
select[multiple].input-group-lg > .form-control,
select[multiple].input-group-lg > .input-group-addon,
select[multiple].input-group-lg > .input-group-btn > .btn {
height: auto;
}
.input-group-sm > .form-control,
.input-group-sm > .input-group-addon,
.input-group-sm > .input-group-btn > .btn {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
select.input-group-sm > .form-control,
select.input-group-sm > .input-group-addon,
select.input-group-sm > .input-group-btn > .btn {
height: 30px;
line-height: 30px;
}
textarea.input-group-sm > .form-control,
textarea.input-group-sm > .input-group-addon,
textarea.input-group-sm > .input-group-btn > .btn,
select[multiple].input-group-sm > .form-control,
select[multiple].input-group-sm > .input-group-addon,
select[multiple].input-group-sm > .input-group-btn > .btn {
height: auto;
}
.input-group-addon,
.input-group-btn,
.input-group .form-control {
display: table-cell;
}
.input-group-addon:not(:first-child):not(:last-child),
.input-group-btn:not(:first-child):not(:last-child),
.input-group .form-control:not(:first-child):not(:last-child) {
border-radius: 0;
}
.input-group-addon,
.input-group-btn {
width: 1%;
white-space: nowrap;
vertical-align: middle;
}
.input-group-addon {
padding: 6px 12px;
font-size: 14px;
font-weight: normal;
line-height: 1;
color: #555;
text-align: center;
background-color: #eee;
border: 1px solid #ccc;
border-radius: 4px;
}
.input-group-addon.input-sm {
padding: 5px 10px;
font-size: 12px;
border-radius: 3px;
}
.input-group-addon.input-lg {
padding: 10px 16px;
font-size: 18px;
border-radius: 6px;
}
.input-group-addon input[type="radio"],
.input-group-addon input[type="checkbox"] {
margin-top: 0;
}
.input-group .form-control:first-child,
.input-group-addon:first-child,
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group > .btn,
.input-group-btn:first-child > .dropdown-toggle,
.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),
.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.input-group-addon:first-child {
border-right: 0;
}
.input-group .form-control:last-child,
.input-group-addon:last-child,
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group > .btn,
.input-group-btn:last-child > .dropdown-toggle,
.input-group-btn:first-child > .btn:not(:first-child),
.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.input-group-addon:last-child {
border-left: 0;
}
.input-group-btn {
position: relative;
font-size: 0;
white-space: nowrap;
}
.input-group-btn > .btn {
position: relative;
}
.input-group-btn > .btn + .btn {
margin-left: -1px;
}
.input-group-btn > .btn:hover,
.input-group-btn > .btn:focus,
.input-group-btn > .btn:active {
z-index: 2;
}
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group {
margin-right: -1px;
}
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group {
margin-left: -1px;
}
.nav {
padding-left: 0;
margin-bottom: 0;
list-style: none;
}
.nav > li {
position: relative;
display: block;
}
.nav > li > a {
position: relative;
display: block;
padding: 10px 15px;
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: #eee;
}
.nav > li.disabled > a {
color: #777;
}
.nav > li.disabled > a:hover,
.nav > li.disabled > a:focus {
color: #777;
text-decoration: none;
cursor: not-allowed;
background-color: transparent;
}
.nav .open > a,
.nav .open > a:hover,
.nav .open > a:focus {
background-color: #eee;
border-color: #428bca;
}
.nav .nav-divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.nav > li > a > img {
max-width: none;
}
.nav-tabs {
border-bottom: 1px solid #ddd;
}
.nav-tabs > li {
float: left;
margin-bottom: -1px;
}
.nav-tabs > li > a {
margin-right: 2px;
line-height: 1.42857143;
border: 1px solid transparent;
border-radius: 4px 4px 0 0;
}
.nav-tabs > li > a:hover {
border-color: #eee #eee #ddd;
}
.nav-tabs > li.active > a,
.nav-tabs > li.active > a:hover,
.nav-tabs > li.active > a:focus {
color: #555;
cursor: default;
background-color: #fff;
border: 1px solid #ddd;
border-bottom-color: transparent;
}
.nav-tabs.nav-justified {
width: 100%;
border-bottom: 0;
}
.nav-tabs.nav-justified > li {
float: none;
}
.nav-tabs.nav-justified > li > a {
margin-bottom: 5px;
text-align: center;
}
.nav-tabs.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-tabs.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs.nav-justified > li > a {
margin-right: 0;
border-radius: 4px;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border: 1px solid #ddd;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li > a {
border-bottom: 1px solid #ddd;
border-radius: 4px 4px 0 0;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border-bottom-color: #fff;
}
}
.nav-pills > li {
float: left;
}
.nav-pills > li > a {
border-radius: 4px;
}
.nav-pills > li + li {
margin-left: 2px;
}
.nav-pills > li.active > a,
.nav-pills > li.active > a:hover,
.nav-pills > li.active > a:focus {
color: #fff;
background-color: #428bca;
}
.nav-stacked > li {
float: none;
}
.nav-stacked > li + li {
margin-top: 2px;
margin-left: 0;
}
.nav-justified {
width: 100%;
}
.nav-justified > li {
float: none;
}
.nav-justified > li > a {
margin-bottom: 5px;
text-align: center;
}
.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs-justified {
border-bottom: 0;
}
.nav-tabs-justified > li > a {
margin-right: 0;
border-radius: 4px;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border: 1px solid #ddd;
}
@media (min-width: 768px) {
.nav-tabs-justified > li > a {
border-bottom: 1px solid #ddd;
border-radius: 4px 4px 0 0;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border-bottom-color: #fff;
}
}
.tab-content > .tab-pane {
display: none;
}
.tab-content > .active {
display: block;
}
.nav-tabs .dropdown-menu {
margin-top: -1px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.navbar {
position: relative;
min-height: 50px;
margin-bottom: 20px;
border: 1px solid transparent;
}
@media (min-width: 768px) {
.navbar {
border-radius: 4px;
}
}
@media (min-width: 768px) {
.navbar-header {
float: left;
}
}
.navbar-collapse {
padding-right: 15px;
padding-left: 15px;
overflow-x: visible;
-webkit-overflow-scrolling: touch;
border-top: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1);
}
.navbar-collapse.in {
overflow-y: auto;
}
@media (min-width: 768px) {
.navbar-collapse {
width: auto;
border-top: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-collapse.collapse {
display: block !important;
height: auto !important;
padding-bottom: 0;
overflow: visible !important;
}
.navbar-collapse.in {
overflow-y: visible;
}
.navbar-fixed-top .navbar-collapse,
.navbar-static-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
padding-right: 0;
padding-left: 0;
}
}
.navbar-fixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 340px;
}
@media (max-width: 480px) and (orientation: landscape) {
.navbar-fixed-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
max-height: 200px;
}
}
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: -15px;
margin-left: -15px;
}
@media (min-width: 768px) {
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: 0;
margin-left: 0;
}
}
.navbar-static-top {
z-index: 1000;
border-width: 0 0 1px;
}
@media (min-width: 768px) {
.navbar-static-top {
border-radius: 0;
}
}
.navbar-fixed-top,
.navbar-fixed-bottom {
position: fixed;
right: 0;
left: 0;
z-index: 1030;
-webkit-transform: translate3d(0, 0, 0);
-o-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
@media (min-width: 768px) {
.navbar-fixed-top,
.navbar-fixed-bottom {
border-radius: 0;
}
}
.navbar-fixed-top {
top: 0;
border-width: 0 0 1px;
}
.navbar-fixed-bottom {
bottom: 0;
margin-bottom: 0;
border-width: 1px 0 0;
}
.navbar-brand {
float: left;
height: 50px;
padding: 15px 15px;
font-size: 18px;
line-height: 20px;
}
.navbar-brand:hover,
.navbar-brand:focus {
text-decoration: none;
}
@media (min-width: 768px) {
.navbar > .container .navbar-brand,
.navbar > .container-fluid .navbar-brand {
margin-left: -15px;
}
}
.navbar-toggle {
position: relative;
float: right;
padding: 9px 10px;
margin-top: 8px;
margin-right: 15px;
margin-bottom: 8px;
background-color: transparent;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
.navbar-toggle:focus {
outline: 0;
}
.navbar-toggle .icon-bar {
display: block;
width: 22px;
height: 2px;
border-radius: 1px;
}
.navbar-toggle .icon-bar + .icon-bar {
margin-top: 4px;
}
@media (min-width: 768px) {
.navbar-toggle {
display: none;
}
}
.navbar-nav {
margin: 7.5px -15px;
}
.navbar-nav > li > a {
padding-top: 10px;
padding-bottom: 10px;
line-height: 20px;
}
@media (max-width: 767px) {
.navbar-nav .open .dropdown-menu {
position: static;
float: none;
width: auto;
margin-top: 0;
background-color: transparent;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-nav .open .dropdown-menu > li > a,
.navbar-nav .open .dropdown-menu .dropdown-header {
padding: 5px 15px 5px 25px;
}
.navbar-nav .open .dropdown-menu > li > a {
line-height: 20px;
}
.navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-nav .open .dropdown-menu > li > a:focus {
background-image: none;
}
}
@media (min-width: 768px) {
.navbar-nav {
float: left;
margin: 0;
}
.navbar-nav > li {
float: left;
}
.navbar-nav > li > a {
padding-top: 15px;
padding-bottom: 15px;
}
.navbar-nav.navbar-right:last-child {
margin-right: -15px;
}
}
@media (min-width: 768px) {
.navbar-left {
float: left !important;
}
.navbar-right {
float: right !important;
}
}
.navbar-form {
padding: 10px 15px;
margin-top: 8px;
margin-right: -15px;
margin-bottom: 8px;
margin-left: -15px;
border-top: 1px solid transparent;
border-bottom: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1);
}
@media (min-width: 768px) {
.navbar-form .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.navbar-form .input-group {
display: inline-table;
vertical-align: middle;
}
.navbar-form .input-group .input-group-addon,
.navbar-form .input-group .input-group-btn,
.navbar-form .input-group .form-control {
width: auto;
}
.navbar-form .input-group > .form-control {
width: 100%;
}
.navbar-form .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio,
.navbar-form .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio label,
.navbar-form .checkbox label {
padding-left: 0;
}
.navbar-form .radio input[type="radio"],
.navbar-form .checkbox input[type="checkbox"] {
position: relative;
margin-left: 0;
}
.navbar-form .has-feedback .form-control-feedback {
top: 0;
}
}
@media (max-width: 767px) {
.navbar-form .form-group {
margin-bottom: 5px;
}
}
@media (min-width: 768px) {
.navbar-form {
width: auto;
padding-top: 0;
padding-bottom: 0;
margin-right: 0;
margin-left: 0;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-form.navbar-right:last-child {
margin-right: -15px;
}
}
.navbar-nav > li > .dropdown-menu {
margin-top: 0;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.navbar-btn {
margin-top: 8px;
margin-bottom: 8px;
}
.navbar-btn.btn-sm {
margin-top: 10px;
margin-bottom: 10px;
}
.navbar-btn.btn-xs {
margin-top: 14px;
margin-bottom: 14px;
}
.navbar-text {
margin-top: 15px;
margin-bottom: 15px;
}
@media (min-width: 768px) {
.navbar-text {
float: left;
margin-right: 15px;
margin-left: 15px;
}
.navbar-text.navbar-right:last-child {
margin-right: 0;
}
}
.navbar-default {
background-color: #f8f8f8;
border-color: #e7e7e7;
}
.navbar-default .navbar-brand {
color: #777;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
color: #5e5e5e;
background-color: transparent;
}
.navbar-default .navbar-text {
color: #777;
}
.navbar-default .navbar-nav > li > a {
color: #777;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
color: #333;
background-color: transparent;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #555;
background-color: #e7e7e7;
}
.navbar-default .navbar-nav > .disabled > a,
.navbar-default .navbar-nav > .disabled > a:hover,
.navbar-default .navbar-nav > .disabled > a:focus {
color: #ccc;
background-color: transparent;
}
.navbar-default .navbar-toggle {
border-color: #ddd;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
background-color: #ddd;
}
.navbar-default .navbar-toggle .icon-bar {
background-color: #888;
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
border-color: #e7e7e7;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
color: #555;
background-color: #e7e7e7;
}
@media (max-width: 767px) {
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
color: #777;
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
color: #333;
background-color: transparent;
}
.navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #555;
background-color: #e7e7e7;
}
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #ccc;
background-color: transparent;
}
}
.navbar-default .navbar-link {
color: #777;
}
.navbar-default .navbar-link:hover {
color: #333;
}
.navbar-default .btn-link {
color: #777;
}
.navbar-default .btn-link:hover,
.navbar-default .btn-link:focus {
color: #333;
}
.navbar-default .btn-link[disabled]:hover,
fieldset[disabled] .navbar-default .btn-link:hover,
.navbar-default .btn-link[disabled]:focus,
fieldset[disabled] .navbar-default .btn-link:focus {
color: #ccc;
}
.navbar-inverse {
background-color: #222;
border-color: #080808;
}
.navbar-inverse .navbar-brand {
color: #777;
}
.navbar-inverse .navbar-brand:hover,
.navbar-inverse .navbar-brand:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-text {
color: #777;
}
.navbar-inverse .navbar-nav > li > a {
color: #777;
}
.navbar-inverse .navbar-nav > li > a:hover,
.navbar-inverse .navbar-nav > li > a:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-nav > .active > a,
.navbar-inverse .navbar-nav > .active > a:hover,
.navbar-inverse .navbar-nav > .active > a:focus {
color: #fff;
background-color: #080808;
}
.navbar-inverse .navbar-nav > .disabled > a,
.navbar-inverse .navbar-nav > .disabled > a:hover,
.navbar-inverse .navbar-nav > .disabled > a:focus {
color: #444;
background-color: transparent;
}
.navbar-inverse .navbar-toggle {
border-color: #333;
}
.navbar-inverse .navbar-toggle:hover,
.navbar-inverse .navbar-toggle:focus {
background-color: #333;
}
.navbar-inverse .navbar-toggle .icon-bar {
background-color: #fff;
}
.navbar-inverse .navbar-collapse,
.navbar-inverse .navbar-form {
border-color: #101010;
}
.navbar-inverse .navbar-nav > .open > a,
.navbar-inverse .navbar-nav > .open > a:hover,
.navbar-inverse .navbar-nav > .open > a:focus {
color: #fff;
background-color: #080808;
}
@media (max-width: 767px) {
.navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {
border-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu .divider {
background-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a {
color: #777;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {
color: #fff;
background-color: transparent;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #fff;
background-color: #080808;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #444;
background-color: transparent;
}
}
.navbar-inverse .navbar-link {
color: #777;
}
.navbar-inverse .navbar-link:hover {
color: #fff;
}
.navbar-inverse .btn-link {
color: #777;
}
.navbar-inverse .btn-link:hover,
.navbar-inverse .btn-link:focus {
color: #fff;
}
.navbar-inverse .btn-link[disabled]:hover,
fieldset[disabled] .navbar-inverse .btn-link:hover,
.navbar-inverse .btn-link[disabled]:focus,
fieldset[disabled] .navbar-inverse .btn-link:focus {
color: #444;
}
.breadcrumb {
padding: 8px 15px;
margin-bottom: 20px;
list-style: none;
background-color: #f5f5f5;
border-radius: 4px;
}
.breadcrumb > li {
display: inline-block;
}
.breadcrumb > li + li:before {
padding: 0 5px;
color: #ccc;
content: "/\00a0";
}
.breadcrumb > .active {
color: #777;
}
.pagination {
display: inline-block;
padding-left: 0;
margin: 20px 0;
border-radius: 4px;
}
.pagination > li {
display: inline;
}
.pagination > li > a,
.pagination > li > span {
position: relative;
float: left;
padding: 6px 12px;
margin-left: -1px;
line-height: 1.42857143;
color: #428bca;
text-decoration: none;
background-color: #fff;
border: 1px solid #ddd;
}
.pagination > li:first-child > a,
.pagination > li:first-child > span {
margin-left: 0;
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
}
.pagination > li:last-child > a,
.pagination > li:last-child > span {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.pagination > li > a:hover,
.pagination > li > span:hover,
.pagination > li > a:focus,
.pagination > li > span:focus {
color: #2a6496;
background-color: #eee;
border-color: #ddd;
}
.pagination > .active > a,
.pagination > .active > span,
.pagination > .active > a:hover,
.pagination > .active > span:hover,
.pagination > .active > a:focus,
.pagination > .active > span:focus {
z-index: 2;
color: #fff;
cursor: default;
background-color: #428bca;
border-color: #428bca;
}
.pagination > .disabled > span,
.pagination > .disabled > span:hover,
.pagination > .disabled > span:focus,
.pagination > .disabled > a,
.pagination > .disabled > a:hover,
.pagination > .disabled > a:focus {
color: #777;
cursor: not-allowed;
background-color: #fff;
border-color: #ddd;
}
.pagination-lg > li > a,
.pagination-lg > li > span {
padding: 10px 16px;
font-size: 18px;
}
.pagination-lg > li:first-child > a,
.pagination-lg > li:first-child > span {
border-top-left-radius: 6px;
border-bottom-left-radius: 6px;
}
.pagination-lg > li:last-child > a,
.pagination-lg > li:last-child > span {
border-top-right-radius: 6px;
border-bottom-right-radius: 6px;
}
.pagination-sm > li > a,
.pagination-sm > li > span {
padding: 5px 10px;
font-size: 12px;
}
.pagination-sm > li:first-child > a,
.pagination-sm > li:first-child > span {
border-top-left-radius: 3px;
border-bottom-left-radius: 3px;
}
.pagination-sm > li:last-child > a,
.pagination-sm > li:last-child > span {
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
}
.pager {
padding-left: 0;
margin: 20px 0;
text-align: center;
list-style: none;
}
.pager li {
display: inline;
}
.pager li > a,
.pager li > span {
display: inline-block;
padding: 5px 14px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 15px;
}
.pager li > a:hover,
.pager li > a:focus {
text-decoration: none;
background-color: #eee;
}
.pager .next > a,
.pager .next > span {
float: right;
}
.pager .previous > a,
.pager .previous > span {
float: left;
}
.pager .disabled > a,
.pager .disabled > a:hover,
.pager .disabled > a:focus,
.pager .disabled > span {
color: #777;
cursor: not-allowed;
background-color: #fff;
}
.label {
display: inline;
padding: .2em .6em .3em;
font-size: 75%;
font-weight: bold;
line-height: 1;
color: #fff;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: .25em;
}
a.label:hover,
a.label:focus {
color: #fff;
text-decoration: none;
cursor: pointer;
}
.label:empty {
display: none;
}
.btn .label {
position: relative;
top: -1px;
}
.label-default {
background-color: #777;
}
.label-default[href]:hover,
.label-default[href]:focus {
background-color: #5e5e5e;
}
.label-primary {
background-color: #428bca;
}
.label-primary[href]:hover,
.label-primary[href]:focus {
background-color: #3071a9;
}
.label-success {
background-color: #5cb85c;
}
.label-success[href]:hover,
.label-success[href]:focus {
background-color: #449d44;
}
.label-info {
background-color: #5bc0de;
}
.label-info[href]:hover,
.label-info[href]:focus {
background-color: #31b0d5;
}
.label-warning {
background-color: #f0ad4e;
}
.label-warning[href]:hover,
.label-warning[href]:focus {
background-color: #ec971f;
}
.label-danger {
background-color: #d9534f;
}
.label-danger[href]:hover,
.label-danger[href]:focus {
background-color: #c9302c;
}
.badge {
display: inline-block;
min-width: 10px;
padding: 3px 7px;
font-size: 12px;
font-weight: bold;
line-height: 1;
color: #fff;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
background-color: #777;
border-radius: 10px;
}
.badge:empty {
display: none;
}
.btn .badge {
position: relative;
top: -1px;
}
.btn-xs .badge {
top: 0;
padding: 1px 5px;
}
a.badge:hover,
a.badge:focus {
color: #fff;
text-decoration: none;
cursor: pointer;
}
a.list-group-item.active > .badge,
.nav-pills > .active > a > .badge {
color: #428bca;
background-color: #fff;
}
.nav-pills > li > a > .badge {
margin-left: 3px;
}
.jumbotron {
padding: 30px;
margin-bottom: 30px;
color: inherit;
background-color: #eee;
}
.jumbotron h1,
.jumbotron .h1 {
color: inherit;
}
.jumbotron p {
margin-bottom: 15px;
font-size: 21px;
font-weight: 200;
}
.jumbotron > hr {
border-top-color: #d5d5d5;
}
.container .jumbotron {
border-radius: 6px;
}
.jumbotron .container {
max-width: 100%;
}
@media screen and (min-width: 768px) {
.jumbotron {
padding-top: 48px;
padding-bottom: 48px;
}
.container .jumbotron {
padding-right: 60px;
padding-left: 60px;
}
.jumbotron h1,
.jumbotron .h1 {
font-size: 63px;
}
}
.thumbnail {
display: block;
padding: 4px;
margin-bottom: 20px;
line-height: 1.42857143;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
-webkit-transition: all .2s ease-in-out;
-o-transition: all .2s ease-in-out;
transition: all .2s ease-in-out;
}
.thumbnail > img,
.thumbnail a > img {
margin-right: auto;
margin-left: auto;
}
a.thumbnail:hover,
a.thumbnail:focus,
a.thumbnail.active {
border-color: #428bca;
}
.thumbnail .caption {
padding: 9px;
color: #333;
}
.alert {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
}
.alert h4 {
margin-top: 0;
color: inherit;
}
.alert .alert-link {
font-weight: bold;
}
.alert > p,
.alert > ul {
margin-bottom: 0;
}
.alert > p + p {
margin-top: 5px;
}
.alert-dismissable,
.alert-dismissible {
padding-right: 35px;
}
.alert-dismissable .close,
.alert-dismissible .close {
position: relative;
top: -2px;
right: -21px;
color: inherit;
}
.alert-success {
color: #3c763d;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.alert-success hr {
border-top-color: #c9e2b3;
}
.alert-success .alert-link {
color: #2b542c;
}
.alert-info {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
.alert-info hr {
border-top-color: #a6e1ec;
}
.alert-info .alert-link {
color: #245269;
}
.alert-warning {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc;
}
.alert-warning hr {
border-top-color: #f7e1b5;
}
.alert-warning .alert-link {
color: #66512c;
}
.alert-danger {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.alert-danger hr {
border-top-color: #e4b9c0;
}
.alert-danger .alert-link {
color: #843534;
}
@-webkit-keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
@-o-keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
@keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
.progress {
height: 20px;
margin-bottom: 20px;
overflow: hidden;
background-color: #f5f5f5;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
}
.progress-bar {
float: left;
width: 0;
height: 100%;
font-size: 12px;
line-height: 20px;
color: #fff;
text-align: center;
background-color: #428bca;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15);
-webkit-transition: width .6s ease;
-o-transition: width .6s ease;
transition: width .6s ease;
}
.progress-striped .progress-bar,
.progress-bar-striped {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
-webkit-background-size: 40px 40px;
background-size: 40px 40px;
}
.progress.active .progress-bar,
.progress-bar.active {
-webkit-animation: progress-bar-stripes 2s linear infinite;
-o-animation: progress-bar-stripes 2s linear infinite;
animation: progress-bar-stripes 2s linear infinite;
}
.progress-bar[aria-valuenow="1"],
.progress-bar[aria-valuenow="2"] {
min-width: 30px;
}
.progress-bar[aria-valuenow="0"] {
min-width: 30px;
color: #777;
background-color: transparent;
background-image: none;
-webkit-box-shadow: none;
box-shadow: none;
}
.progress-bar-success {
background-color: #5cb85c;
}
.progress-striped .progress-bar-success {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.progress-bar-info {
background-color: #5bc0de;
}
.progress-striped .progress-bar-info {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.progress-bar-warning {
background-color: #f0ad4e;
}
.progress-striped .progress-bar-warning {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.progress-bar-danger {
background-color: #d9534f;
}
.progress-striped .progress-bar-danger {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent);
}
.media,
.media-body {
overflow: hidden;
zoom: 1;
}
.media,
.media .media {
margin-top: 15px;
}
.media:first-child {
margin-top: 0;
}
.media-object {
display: block;
}
.media-heading {
margin: 0 0 5px;
}
.media > .pull-left {
margin-right: 10px;
}
.media > .pull-right {
margin-left: 10px;
}
.media-list {
padding-left: 0;
list-style: none;
}
.list-group {
padding-left: 0;
margin-bottom: 20px;
}
.list-group-item {
position: relative;
display: block;
padding: 10px 15px;
margin-bottom: -1px;
background-color: #fff;
border: 1px solid #ddd;
}
.list-group-item:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.list-group-item:last-child {
margin-bottom: 0;
border-bottom-right-radius: 4px;
border-bottom-left-radius: 4px;
}
.list-group-item > .badge {
float: right;
}
.list-group-item > .badge + .badge {
margin-right: 5px;
}
a.list-group-item {
color: #555;
}
a.list-group-item .list-group-item-heading {
color: #333;
}
a.list-group-item:hover,
a.list-group-item:focus {
color: #555;
text-decoration: none;
background-color: #f5f5f5;
}
.list-group-item.disabled,
.list-group-item.disabled:hover,
.list-group-item.disabled:focus {
color: #777;
background-color: #eee;
}
.list-group-item.disabled .list-group-item-heading,
.list-group-item.disabled:hover .list-group-item-heading,
.list-group-item.disabled:focus .list-group-item-heading {
color: inherit;
}
.list-group-item.disabled .list-group-item-text,
.list-group-item.disabled:hover .list-group-item-text,
.list-group-item.disabled:focus .list-group-item-text {
color: #777;
}
.list-group-item.active,
.list-group-item.active:hover,
.list-group-item.active:focus {
z-index: 2;
color: #fff;
background-color: #428bca;
border-color: #428bca;
}
.list-group-item.active .list-group-item-heading,
.list-group-item.active:hover .list-group-item-heading,
.list-group-item.active:focus .list-group-item-heading,
.list-group-item.active .list-group-item-heading > small,
.list-group-item.active:hover .list-group-item-heading > small,
.list-group-item.active:focus .list-group-item-heading > small,
.list-group-item.active .list-group-item-heading > .small,
.list-group-item.active:hover .list-group-item-heading > .small,
.list-group-item.active:focus .list-group-item-heading > .small {
color: inherit;
}
.list-group-item.active .list-group-item-text,
.list-group-item.active:hover .list-group-item-text,
.list-group-item.active:focus .list-group-item-text {
color: #e1edf7;
}
.list-group-item-success {
color: #3c763d;
background-color: #dff0d8;
}
a.list-group-item-success {
color: #3c763d;
}
a.list-group-item-success .list-group-item-heading {
color: inherit;
}
a.list-group-item-success:hover,
a.list-group-item-success:focus {
color: #3c763d;
background-color: #d0e9c6;
}
a.list-group-item-success.active,
a.list-group-item-success.active:hover,
a.list-group-item-success.active:focus {
color: #fff;
background-color: #3c763d;
border-color: #3c763d;
}
.list-group-item-info {
color: #31708f;
background-color: #d9edf7;
}
a.list-group-item-info {
color: #31708f;
}
a.list-group-item-info .list-group-item-heading {
color: inherit;
}
a.list-group-item-info:hover,
a.list-group-item-info:focus {
color: #31708f;
background-color: #c4e3f3;
}
a.list-group-item-info.active,
a.list-group-item-info.active:hover,
a.list-group-item-info.active:focus {
color: #fff;
background-color: #31708f;
border-color: #31708f;
}
.list-group-item-warning {
color: #8a6d3b;
background-color: #fcf8e3;
}
a.list-group-item-warning {
color: #8a6d3b;
}
a.list-group-item-warning .list-group-item-heading {
color: inherit;
}
a.list-group-item-warning:hover,
a.list-group-item-warning:focus {
color: #8a6d3b;
background-color: #faf2cc;
}
a.list-group-item-warning.active,
a.list-group-item-warning.active:hover,
a.list-group-item-warning.active:focus {
color: #fff;
background-color: #8a6d3b;
border-color: #8a6d3b;
}
.list-group-item-danger {
color: #a94442;
background-color: #f2dede;
}
a.list-group-item-danger {
color: #a94442;
}
a.list-group-item-danger .list-group-item-heading {
color: inherit;
}
a.list-group-item-danger:hover,
a.list-group-item-danger:focus {
color: #a94442;
background-color: #ebcccc;
}
a.list-group-item-danger.active,
a.list-group-item-danger.active:hover,
a.list-group-item-danger.active:focus {
color: #fff;
background-color: #a94442;
border-color: #a94442;
}
.list-group-item-heading {
margin-top: 0;
margin-bottom: 5px;
}
.list-group-item-text {
margin-bottom: 0;
line-height: 1.3;
}
.panel {
margin-bottom: 20px;
background-color: #fff;
border: 1px solid transparent;
border-radius: 4px;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
box-shadow: 0 1px 1px rgba(0, 0, 0, .05);
}
.panel-body {
padding: 15px;
}
.panel-heading {
padding: 10px 15px;
border-bottom: 1px solid transparent;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel-heading > .dropdown .dropdown-toggle {
color: inherit;
}
.panel-title {
margin-top: 0;
margin-bottom: 0;
font-size: 16px;
color: inherit;
}
.panel-title > a {
color: inherit;
}
.panel-footer {
padding: 10px 15px;
background-color: #f5f5f5;
border-top: 1px solid #ddd;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .list-group {
margin-bottom: 0;
}
.panel > .list-group .list-group-item {
border-width: 1px 0;
border-radius: 0;
}
.panel > .list-group:first-child .list-group-item:first-child {
border-top: 0;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel > .list-group:last-child .list-group-item:last-child {
border-bottom: 0;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel-heading + .list-group .list-group-item:first-child {
border-top-width: 0;
}
.list-group + .panel-footer {
border-top-width: 0;
}
.panel > .table,
.panel > .table-responsive > .table,
.panel > .panel-collapse > .table {
margin-bottom: 0;
}
.panel > .table:first-child,
.panel > .table-responsive:first-child > .table:first-child {
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child {
border-top-left-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child {
border-top-right-radius: 3px;
}
.panel > .table:last-child,
.panel > .table-responsive:last-child > .table:last-child {
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child {
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child {
border-bottom-right-radius: 3px;
}
.panel > .panel-body + .table,
.panel > .panel-body + .table-responsive {
border-top: 1px solid #ddd;
}
.panel > .table > tbody:first-child > tr:first-child th,
.panel > .table > tbody:first-child > tr:first-child td {
border-top: 0;
}
.panel > .table-bordered,
.panel > .table-responsive > .table-bordered {
border: 0;
}
.panel > .table-bordered > thead > tr > th:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:first-child,
.panel > .table-bordered > tbody > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child,
.panel > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-bordered > thead > tr > td:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:first-child,
.panel > .table-bordered > tbody > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child,
.panel > .table-bordered > tfoot > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.panel > .table-bordered > thead > tr > th:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:last-child,
.panel > .table-bordered > tbody > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child,
.panel > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-bordered > thead > tr > td:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:last-child,
.panel > .table-bordered > tbody > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child,
.panel > .table-bordered > tfoot > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.panel > .table-bordered > thead > tr:first-child > td,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > td,
.panel > .table-bordered > tbody > tr:first-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > td,
.panel > .table-bordered > thead > tr:first-child > th,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > th,
.panel > .table-bordered > tbody > tr:first-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > th {
border-bottom: 0;
}
.panel > .table-bordered > tbody > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td,
.panel > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-bordered > tbody > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th,
.panel > .table-bordered > tfoot > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th {
border-bottom: 0;
}
.panel > .table-responsive {
margin-bottom: 0;
border: 0;
}
.panel-group {
margin-bottom: 20px;
}
.panel-group .panel {
margin-bottom: 0;
border-radius: 4px;
}
.panel-group .panel + .panel {
margin-top: 5px;
}
.panel-group .panel-heading {
border-bottom: 0;
}
.panel-group .panel-heading + .panel-collapse > .panel-body {
border-top: 1px solid #ddd;
}
.panel-group .panel-footer {
border-top: 0;
}
.panel-group .panel-footer + .panel-collapse .panel-body {
border-bottom: 1px solid #ddd;
}
.panel-default {
border-color: #ddd;
}
.panel-default > .panel-heading {
color: #333;
background-color: #f5f5f5;
border-color: #ddd;
}
.panel-default > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #ddd;
}
.panel-default > .panel-heading .badge {
color: #f5f5f5;
background-color: #333;
}
.panel-default > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #ddd;
}
.panel-primary {
border-color: #428bca;
}
.panel-primary > .panel-heading {
color: #fff;
background-color: #428bca;
border-color: #428bca;
}
.panel-primary > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #428bca;
}
.panel-primary > .panel-heading .badge {
color: #428bca;
background-color: #fff;
}
.panel-primary > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #428bca;
}
.panel-success {
border-color: #d6e9c6;
}
.panel-success > .panel-heading {
color: #3c763d;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.panel-success > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #d6e9c6;
}
.panel-success > .panel-heading .badge {
color: #dff0d8;
background-color: #3c763d;
}
.panel-success > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #d6e9c6;
}
.panel-info {
border-color: #bce8f1;
}
.panel-info > .panel-heading {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
.panel-info > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #bce8f1;
}
.panel-info > .panel-heading .badge {
color: #d9edf7;
background-color: #31708f;
}
.panel-info > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #bce8f1;
}
.panel-warning {
border-color: #faebcc;
}
.panel-warning > .panel-heading {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc;
}
.panel-warning > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #faebcc;
}
.panel-warning > .panel-heading .badge {
color: #fcf8e3;
background-color: #8a6d3b;
}
.panel-warning > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #faebcc;
}
.panel-danger {
border-color: #ebccd1;
}
.panel-danger > .panel-heading {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.panel-danger > .panel-heading + .panel-collapse > .panel-body {
border-top-color: #ebccd1;
}
.panel-danger > .panel-heading .badge {
color: #f2dede;
background-color: #a94442;
}
.panel-danger > .panel-footer + .panel-collapse > .panel-body {
border-bottom-color: #ebccd1;
}
.embed-responsive {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
.embed-responsive .embed-responsive-item,
.embed-responsive iframe,
.embed-responsive embed,
.embed-responsive object {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
.embed-responsive.embed-responsive-16by9 {
padding-bottom: 56.25%;
}
.embed-responsive.embed-responsive-4by3 {
padding-bottom: 75%;
}
.well {
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
background-color: #f5f5f5;
border: 1px solid #e3e3e3;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
}
.well blockquote {
border-color: #ddd;
border-color: rgba(0, 0, 0, .15);
}
.well-lg {
padding: 24px;
border-radius: 6px;
}
.well-sm {
padding: 9px;
border-radius: 3px;
}
.close {
float: right;
font-size: 21px;
font-weight: bold;
line-height: 1;
color: #000;
text-shadow: 0 1px 0 #fff;
filter: alpha(opacity=20);
opacity: .2;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
filter: alpha(opacity=50);
opacity: .5;
}
button.close {
-webkit-appearance: none;
padding: 0;
cursor: pointer;
background: transparent;
border: 0;
}
.modal-open {
overflow: hidden;
}
.modal {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1050;
display: none;
overflow: hidden;
-webkit-overflow-scrolling: touch;
outline: 0;
}
.modal.fade .modal-dialog {
-webkit-transition: -webkit-transform .3s ease-out;
-o-transition: -o-transform .3s ease-out;
transition: transform .3s ease-out;
-webkit-transform: translate3d(0, -25%, 0);
-o-transform: translate3d(0, -25%, 0);
transform: translate3d(0, -25%, 0);
}
.modal.in .modal-dialog {
-webkit-transform: translate3d(0, 0, 0);
-o-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
.modal-open .modal {
overflow-x: hidden;
overflow-y: auto;
}
.modal-dialog {
position: relative;
width: auto;
margin: 10px;
}
.modal-content {
position: relative;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #999;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: 6px;
outline: 0;
-webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
}
.modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1040;
background-color: #000;
}
.modal-backdrop.fade {
filter: alpha(opacity=0);
opacity: 0;
}
.modal-backdrop.in {
filter: alpha(opacity=50);
opacity: .5;
}
.modal-header {
min-height: 16.42857143px;
padding: 15px;
border-bottom: 1px solid #e5e5e5;
}
.modal-header .close {
margin-top: -2px;
}
.modal-title {
margin: 0;
line-height: 1.42857143;
}
.modal-body {
position: relative;
padding: 15px;
}
.modal-footer {
padding: 15px;
text-align: right;
border-top: 1px solid #e5e5e5;
}
.modal-footer .btn + .btn {
margin-bottom: 0;
margin-left: 5px;
}
.modal-footer .btn-group .btn + .btn {
margin-left: -1px;
}
.modal-footer .btn-block + .btn-block {
margin-left: 0;
}
.modal-scrollbar-measure {
position: absolute;
top: -9999px;
width: 50px;
height: 50px;
overflow: scroll;
}
@media (min-width: 768px) {
.modal-dialog {
width: 600px;
margin: 30px auto;
}
.modal-content {
-webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
}
.modal-sm {
width: 300px;
}
}
@media (min-width: 992px) {
.modal-lg {
width: 900px;
}
}
.tooltip {
position: absolute;
z-index: 1070;
display: block;
font-size: 12px;
line-height: 1.4;
visibility: visible;
filter: alpha(opacity=0);
opacity: 0;
}
.tooltip.in {
filter: alpha(opacity=90);
opacity: .9;
}
.tooltip.top {
padding: 5px 0;
margin-top: -3px;
}
.tooltip.right {
padding: 0 5px;
margin-left: 3px;
}
.tooltip.bottom {
padding: 5px 0;
margin-top: 3px;
}
.tooltip.left {
padding: 0 5px;
margin-left: -3px;
}
.tooltip-inner {
max-width: 200px;
padding: 3px 8px;
color: #fff;
text-align: center;
text-decoration: none;
background-color: #000;
border-radius: 4px;
}
.tooltip-arrow {
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.tooltip.top .tooltip-arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.top-left .tooltip-arrow {
bottom: 0;
left: 5px;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.top-right .tooltip-arrow {
right: 5px;
bottom: 0;
border-width: 5px 5px 0;
border-top-color: #000;
}
.tooltip.right .tooltip-arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-width: 5px 5px 5px 0;
border-right-color: #000;
}
.tooltip.left .tooltip-arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-width: 5px 0 5px 5px;
border-left-color: #000;
}
.tooltip.bottom .tooltip-arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.tooltip.bottom-left .tooltip-arrow {
top: 0;
left: 5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.tooltip.bottom-right .tooltip-arrow {
top: 0;
right: 5px;
border-width: 0 5px 5px;
border-bottom-color: #000;
}
.popover {
position: absolute;
top: 0;
left: 0;
z-index: 1060;
display: none;
max-width: 276px;
padding: 1px;
text-align: left;
white-space: normal;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: 6px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
}
.popover.top {
margin-top: -10px;
}
.popover.right {
margin-left: 10px;
}
.popover.bottom {
margin-top: 10px;
}
.popover.left {
margin-left: -10px;
}
.popover-title {
padding: 8px 14px;
margin: 0;
font-size: 14px;
font-weight: normal;
line-height: 18px;
background-color: #f7f7f7;
border-bottom: 1px solid #ebebeb;
border-radius: 5px 5px 0 0;
}
.popover-content {
padding: 9px 14px;
}
.popover > .arrow,
.popover > .arrow:after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.popover > .arrow {
border-width: 11px;
}
.popover > .arrow:after {
content: "";
border-width: 10px;
}
.popover.top > .arrow {
bottom: -11px;
left: 50%;
margin-left: -11px;
border-top-color: #999;
border-top-color: rgba(0, 0, 0, .25);
border-bottom-width: 0;
}
.popover.top > .arrow:after {
bottom: 1px;
margin-left: -10px;
content: " ";
border-top-color: #fff;
border-bottom-width: 0;
}
.popover.right > .arrow {
top: 50%;
left: -11px;
margin-top: -11px;
border-right-color: #999;
border-right-color: rgba(0, 0, 0, .25);
border-left-width: 0;
}
.popover.right > .arrow:after {
bottom: -10px;
left: 1px;
content: " ";
border-right-color: #fff;
border-left-width: 0;
}
.popover.bottom > .arrow {
top: -11px;
left: 50%;
margin-left: -11px;
border-top-width: 0;
border-bottom-color: #999;
border-bottom-color: rgba(0, 0, 0, .25);
}
.popover.bottom > .arrow:after {
top: 1px;
margin-left: -10px;
content: " ";
border-top-width: 0;
border-bottom-color: #fff;
}
.popover.left > .arrow {
top: 50%;
right: -11px;
margin-top: -11px;
border-right-width: 0;
border-left-color: #999;
border-left-color: rgba(0, 0, 0, .25);
}
.popover.left > .arrow:after {
right: 1px;
bottom: -10px;
content: " ";
border-right-width: 0;
border-left-color: #fff;
}
.carousel {
position: relative;
}
.carousel-inner {
position: relative;
width: 100%;
overflow: hidden;
}
.carousel-inner > .item {
position: relative;
display: none;
-webkit-transition: .6s ease-in-out left;
-o-transition: .6s ease-in-out left;
transition: .6s ease-in-out left;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
line-height: 1;
}
.carousel-inner > .active,
.carousel-inner > .next,
.carousel-inner > .prev {
display: block;
}
.carousel-inner > .active {
left: 0;
}
.carousel-inner > .next,
.carousel-inner > .prev {
position: absolute;
top: 0;
width: 100%;
}
.carousel-inner > .next {
left: 100%;
}
.carousel-inner > .prev {
left: -100%;
}
.carousel-inner > .next.left,
.carousel-inner > .prev.right {
left: 0;
}
.carousel-inner > .active.left {
left: -100%;
}
.carousel-inner > .active.right {
left: 100%;
}
.carousel-control {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 15%;
font-size: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
filter: alpha(opacity=50);
opacity: .5;
}
.carousel-control.left {
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001)));
background-image: linear-gradient(to right, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
background-repeat: repeat-x;
}
.carousel-control.right {
right: 0;
left: auto;
background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
background-image: -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5)));
background-image: linear-gradient(to right, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
background-repeat: repeat-x;
}
.carousel-control:hover,
.carousel-control:focus {
color: #fff;
text-decoration: none;
filter: alpha(opacity=90);
outline: 0;
opacity: .9;
}
.carousel-control .icon-prev,
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right {
position: absolute;
top: 50%;
z-index: 5;
display: inline-block;
}
.carousel-control .icon-prev,
.carousel-control .glyphicon-chevron-left {
left: 50%;
margin-left: -10px;
}
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-right {
right: 50%;
margin-right: -10px;
}
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 20px;
height: 20px;
margin-top: -10px;
font-family: serif;
}
.carousel-control .icon-prev:before {
content: '\2039';
}
.carousel-control .icon-next:before {
content: '\203a';
}
.carousel-indicators {
position: absolute;
bottom: 10px;
left: 50%;
z-index: 15;
width: 60%;
padding-left: 0;
margin-left: -30%;
text-align: center;
list-style: none;
}
.carousel-indicators li {
display: inline-block;
width: 10px;
height: 10px;
margin: 1px;
text-indent: -999px;
cursor: pointer;
background-color: #000 \9;
background-color: rgba(0, 0, 0, 0);
border: 1px solid #fff;
border-radius: 10px;
}
.carousel-indicators .active {
width: 12px;
height: 12px;
margin: 0;
background-color: #fff;
}
.carousel-caption {
position: absolute;
right: 15%;
bottom: 20px;
left: 15%;
z-index: 10;
padding-top: 20px;
padding-bottom: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
}
.carousel-caption .btn {
text-shadow: none;
}
@media screen and (min-width: 768px) {
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 30px;
height: 30px;
margin-top: -15px;
font-size: 30px;
}
.carousel-control .glyphicon-chevron-left,
.carousel-control .icon-prev {
margin-left: -15px;
}
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-next {
margin-right: -15px;
}
.carousel-caption {
right: 20%;
left: 20%;
padding-bottom: 30px;
}
.carousel-indicators {
bottom: 20px;
}
}
.clearfix:before,
.clearfix:after,
.dl-horizontal dd:before,
.dl-horizontal dd:after,
.container:before,
.container:after,
.container-fluid:before,
.container-fluid:after,
.row:before,
.row:after,
.form-horizontal .form-group:before,
.form-horizontal .form-group:after,
.btn-toolbar:before,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:before,
.btn-group-vertical > .btn-group:after,
.nav:before,
.nav:after,
.navbar:before,
.navbar:after,
.navbar-header:before,
.navbar-header:after,
.navbar-collapse:before,
.navbar-collapse:after,
.pager:before,
.pager:after,
.panel-body:before,
.panel-body:after,
.modal-footer:before,
.modal-footer:after {
display: table;
content: " ";
}
.clearfix:after,
.dl-horizontal dd:after,
.container:after,
.container-fluid:after,
.row:after,
.form-horizontal .form-group:after,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:after,
.nav:after,
.navbar:after,
.navbar-header:after,
.navbar-collapse:after,
.pager:after,
.panel-body:after,
.modal-footer:after {
clear: both;
}
.center-block {
display: block;
margin-right: auto;
margin-left: auto;
}
.pull-right {
float: right !important;
}
.pull-left {
float: left !important;
}
.hide {
display: none !important;
}
.show {
display: block !important;
}
.invisible {
visibility: hidden;
}
.text-hide {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
.hidden {
display: none !important;
visibility: hidden !important;
}
.affix {
position: fixed;
-webkit-transform: translate3d(0, 0, 0);
-o-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
@-ms-viewport {
width: device-width;
}
.visible-xs,
.visible-sm,
.visible-md,
.visible-lg {
display: none !important;
}
.visible-xs-block,
.visible-xs-inline,
.visible-xs-inline-block,
.visible-sm-block,
.visible-sm-inline,
.visible-sm-inline-block,
.visible-md-block,
.visible-md-inline,
.visible-md-inline-block,
.visible-lg-block,
.visible-lg-inline,
.visible-lg-inline-block {
display: none !important;
}
@media (max-width: 767px) {
.visible-xs {
display: block !important;
}
table.visible-xs {
display: table;
}
tr.visible-xs {
display: table-row !important;
}
th.visible-xs,
td.visible-xs {
display: table-cell !important;
}
}
@media (max-width: 767px) {
.visible-xs-block {
display: block !important;
}
}
@media (max-width: 767px) {
.visible-xs-inline {
display: inline !important;
}
}
@media (max-width: 767px) {
.visible-xs-inline-block {
display: inline-block !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm {
display: block !important;
}
table.visible-sm {
display: table;
}
tr.visible-sm {
display: table-row !important;
}
th.visible-sm,
td.visible-sm {
display: table-cell !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-block {
display: block !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-inline {
display: inline !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-inline-block {
display: inline-block !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md {
display: block !important;
}
table.visible-md {
display: table;
}
tr.visible-md {
display: table-row !important;
}
th.visible-md,
td.visible-md {
display: table-cell !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-block {
display: block !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-inline {
display: inline !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md-inline-block {
display: inline-block !important;
}
}
@media (min-width: 1200px) {
.visible-lg {
display: block !important;
}
table.visible-lg {
display: table;
}
tr.visible-lg {
display: table-row !important;
}
th.visible-lg,
td.visible-lg {
display: table-cell !important;
}
}
@media (min-width: 1200px) {
.visible-lg-block {
display: block !important;
}
}
@media (min-width: 1200px) {
.visible-lg-inline {
display: inline !important;
}
}
@media (min-width: 1200px) {
.visible-lg-inline-block {
display: inline-block !important;
}
}
@media (max-width: 767px) {
.hidden-xs {
display: none !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.hidden-sm {
display: none !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.hidden-md {
display: none !important;
}
}
@media (min-width: 1200px) {
.hidden-lg {
display: none !important;
}
}
.visible-print {
display: none !important;
}
@media print {
.visible-print {
display: block !important;
}
table.visible-print {
display: table;
}
tr.visible-print {
display: table-row !important;
}
th.visible-print,
td.visible-print {
display: table-cell !important;
}
}
.visible-print-block {
display: none !important;
}
@media print {
.visible-print-block {
display: block !important;
}
}
.visible-print-inline {
display: none !important;
}
@media print {
.visible-print-inline {
display: inline !important;
}
}
.visible-print-inline-block {
display: none !important;
}
@media print {
.visible-print-inline-block {
display: inline-block !important;
}
}
@media print {
.hidden-print {
display: none !important;
}
}
/*# sourceMappingURL=bootstrap.css.map */
| Java |
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# **********************************************************************
import os, sys, traceback
import Ice, AllTests
def test(b):
if not b:
raise RuntimeError('test assertion failed')
def usage(n):
sys.stderr.write("Usage: " + n + " port...\n")
def run(args, communicator):
ports = []
for arg in args[1:]:
if arg[0] == '-':
sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n")
usage(args[0])
return False
ports.append(int(arg))
if len(ports) == 0:
sys.stderr.write(args[0] + ": no ports specified\n")
usage(args[0])
return False
try:
AllTests.allTests(communicator, ports)
except:
traceback.print_exc()
test(False)
return True
try:
initData = Ice.InitializationData()
initData.properties = Ice.createProperties(sys.argv)
#
# This test aborts servers, so we don't want warnings.
#
initData.properties.setProperty('Ice.Warn.Connections', '0')
communicator = Ice.initialize(sys.argv, initData)
status = run(sys.argv, communicator)
except:
traceback.print_exc()
status = False
if communicator:
try:
communicator.destroy()
except:
traceback.print_exc()
status = False
sys.exit(not status)
| Java |
/*
* Copyright (C) 2000 Matthias Elter <elter@kde.org>
* Copyright (C) 2001-2002 Raffaele Sandrini <sandrini@kde.org)
* Copyright (C) 2003 Waldo Bastian <bastian@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <unistd.h>
#include <tqcstring.h>
#include <tqcursor.h>
#include <tqdatastream.h>
#include <tqdir.h>
#include <tqdragobject.h>
#include <tqfileinfo.h>
#include <tqheader.h>
#include <tqpainter.h>
#include <tqpopupmenu.h>
#include <tqregexp.h>
#include <tqstringlist.h>
#include <tdeglobal.h>
#include <kstandarddirs.h>
#include <kinputdialog.h>
#include <tdelocale.h>
#include <ksimpleconfig.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kdesktopfile.h>
#include <tdeaction.h>
#include <tdemessagebox.h>
#include <tdeapplication.h>
#include <kservice.h>
#include <kservicegroup.h>
#include <tdemultipledrag.h>
#include <kurldrag.h>
#include "treeview.h"
#include "treeview.moc"
#include "khotkeys.h"
#include "menufile.h"
#include "menuinfo.h"
#define MOVE_FOLDER 'M'
#define COPY_FOLDER 'C'
#define MOVE_FILE 'm'
#define COPY_FILE 'c'
#define COPY_SEPARATOR 'S'
TreeItem::TreeItem(TQListViewItem *parent, TQListViewItem *after, const TQString& menuId, bool __init)
:TQListViewItem(parent, after), _hidden(false), _init(__init), _layoutDirty(false), _menuId(menuId),
m_folderInfo(0), m_entryInfo(0) {}
TreeItem::TreeItem(TQListView *parent, TQListViewItem *after, const TQString& menuId, bool __init)
: TQListViewItem(parent, after), _hidden(false), _init(__init), _layoutDirty(false), _menuId(menuId),
m_folderInfo(0), m_entryInfo(0) {}
void TreeItem::setName(const TQString &name)
{
_name = name;
update();
}
void TreeItem::setHidden(bool b)
{
if (_hidden == b) return;
_hidden = b;
update();
}
void TreeItem::update()
{
TQString s = _name;
if (_hidden)
s += i18n(" [Hidden]");
setText(0, s);
}
void TreeItem::setOpen(bool o)
{
if (o)
load();
TQListViewItem::setOpen(o);
}
void TreeItem::load()
{
if (m_folderInfo && !_init)
{
_init = true;
TreeView *tv = static_cast<TreeView *>(listView());
tv->fillBranch(m_folderInfo, this);
}
}
void TreeItem::paintCell ( TQPainter * p, const TQColorGroup & cg, int column, int width, int align )
{
TQListViewItem::paintCell(p, cg, column, width, align);
if (!m_folderInfo && !m_entryInfo)
{
// Draw Separator
int h = (height() / 2) -1;
if (isSelected())
p->setPen( cg.highlightedText() );
else
p->setPen( cg.text() );
p->drawLine(0, h,
width, h);
}
}
void TreeItem::setup()
{
TQListViewItem::setup();
if (!m_folderInfo && !m_entryInfo)
setHeight(8);
}
static TQPixmap appIcon(const TQString &iconName)
{
TQPixmap normal = TDEGlobal::iconLoader()->loadIcon(iconName, TDEIcon::Small, 0, TDEIcon::DefaultState, 0L, true);
// make sure they are not larger than 20x20
if (normal.width() > 20 || normal.height() > 20)
{
TQImage tmp = normal.convertToImage();
tmp = tmp.smoothScale(20, 20);
normal.convertFromImage(tmp);
}
return normal;
}
TreeView::TreeView( bool controlCenter, TDEActionCollection *ac, TQWidget *parent, const char *name )
: TDEListView(parent, name), m_ac(ac), m_rmb(0), m_clipboard(0),
m_clipboardFolderInfo(0), m_clipboardEntryInfo(0),
m_controlCenter(controlCenter), m_layoutDirty(false)
{
setFrameStyle(TQFrame::WinPanel | TQFrame::Sunken);
setAllColumnsShowFocus(true);
setRootIsDecorated(true);
setSorting(-1);
setAcceptDrops(true);
setDropVisualizer(true);
setDragEnabled(true);
setMinimumWidth(240);
addColumn("");
header()->hide();
connect(this, TQT_SIGNAL(dropped(TQDropEvent*, TQListViewItem*, TQListViewItem*)),
TQT_SLOT(slotDropped(TQDropEvent*, TQListViewItem*, TQListViewItem*)));
connect(this, TQT_SIGNAL(clicked( TQListViewItem* )),
TQT_SLOT(itemSelected( TQListViewItem* )));
connect(this,TQT_SIGNAL(selectionChanged ( TQListViewItem * )),
TQT_SLOT(itemSelected( TQListViewItem* )));
connect(this, TQT_SIGNAL(rightButtonPressed(TQListViewItem*, const TQPoint&, int)),
TQT_SLOT(slotRMBPressed(TQListViewItem*, const TQPoint&)));
// connect actions
connect(m_ac->action("newitem"), TQT_SIGNAL(activated()), TQT_SLOT(newitem()));
connect(m_ac->action("newsubmenu"), TQT_SIGNAL(activated()), TQT_SLOT(newsubmenu()));
if (m_ac->action("newsep"))
connect(m_ac->action("newsep"), TQT_SIGNAL(activated()), TQT_SLOT(newsep()));
m_menuFile = new MenuFile( locateLocal("xdgconf-menu", "applications-tdemenuedit.menu"));
m_rootFolder = new MenuFolderInfo;
m_separator = new MenuSeparatorInfo;
m_drag = 0;
// Read menu format configuration information
TDESharedConfig::Ptr pConfig = TDESharedConfig::openConfig("kickerrc");
pConfig->setGroup("menus");
m_detailedMenuEntries = pConfig->readBoolEntry("DetailedMenuEntries",true);
if (m_detailedMenuEntries)
{
m_detailedEntriesNamesFirst = pConfig->readBoolEntry("DetailedEntriesNamesFirst",false);
}
}
TreeView::~TreeView() {
cleanupClipboard();
delete m_rootFolder;
delete m_separator;
}
void TreeView::setViewMode(bool showHidden)
{
delete m_rmb;
// setup rmb menu
m_rmb = new TQPopupMenu(this);
TDEAction *action;
action = m_ac->action("edit_cut");
if(action) {
action->plug(m_rmb);
action->setEnabled(false);
connect(action, TQT_SIGNAL(activated()), TQT_SLOT(cut()));
}
action = m_ac->action("edit_copy");
if(action) {
action->plug(m_rmb);
action->setEnabled(false);
connect(action, TQT_SIGNAL(activated()), TQT_SLOT(copy()));
}
action = m_ac->action("edit_paste");
if(action) {
action->plug(m_rmb);
action->setEnabled(false);
connect(action, TQT_SIGNAL(activated()), TQT_SLOT(paste()));
}
m_rmb->insertSeparator();
action = m_ac->action("delete");
if(action) {
action->plug(m_rmb);
action->setEnabled(false);
connect(action, TQT_SIGNAL(activated()), TQT_SLOT(del()));
}
m_rmb->insertSeparator();
if(m_ac->action("newitem"))
m_ac->action("newitem")->plug(m_rmb);
if(m_ac->action("newsubmenu"))
m_ac->action("newsubmenu")->plug(m_rmb);
if(m_ac->action("newsep"))
m_ac->action("newsep")->plug(m_rmb);
m_showHidden = showHidden;
readMenuFolderInfo();
fill();
}
void TreeView::readMenuFolderInfo(MenuFolderInfo *folderInfo, KServiceGroup::Ptr folder, const TQString &prefix)
{
if (!folderInfo)
{
folderInfo = m_rootFolder;
if (m_controlCenter)
folder = KServiceGroup::baseGroup("settings");
else
folder = KServiceGroup::root();
}
if (!folder || !folder->isValid())
return;
folderInfo->caption = folder->caption();
folderInfo->comment = folder->comment();
// Item names may contain ampersands. To avoid them being converted
// to accelerators, replace them with two ampersands.
folderInfo->hidden = folder->noDisplay();
folderInfo->directoryFile = folder->directoryEntryPath();
folderInfo->icon = folder->icon();
TQString id = folder->relPath();
int i = id.findRev('/', -2);
id = id.mid(i+1);
folderInfo->id = id;
folderInfo->fullId = prefix + id;
KServiceGroup::List list = folder->entries(true, !m_showHidden, true, m_detailedMenuEntries && !m_detailedEntriesNamesFirst);
for(KServiceGroup::List::ConstIterator it = list.begin();
it != list.end(); ++it)
{
KSycocaEntry * e = *it;
if (e->isType(KST_KServiceGroup))
{
KServiceGroup::Ptr g(static_cast<KServiceGroup *>(e));
MenuFolderInfo *subFolderInfo = new MenuFolderInfo();
readMenuFolderInfo(subFolderInfo, g, folderInfo->fullId);
folderInfo->add(subFolderInfo, true);
}
else if (e->isType(KST_KService))
{
folderInfo->add(new MenuEntryInfo(static_cast<KService *>(e)), true);
}
else if (e->isType(KST_KServiceSeparator))
{
folderInfo->add(m_separator, true);
}
}
}
void TreeView::fill()
{
TQApplication::setOverrideCursor(Qt::WaitCursor);
clear();
fillBranch(m_rootFolder, 0);
TQApplication::restoreOverrideCursor();
}
TQString TreeView::findName(KDesktopFile *df, bool deleted)
{
TQString name = df->readName();
if (deleted)
{
if (name == "empty")
name = TQString::null;
if (name.isEmpty())
{
TQString file = df->fileName();
TQString res = df->resource();
bool isLocal = true;
TQStringList files = TDEGlobal::dirs()->findAllResources(res.latin1(), file);
for(TQStringList::ConstIterator it = files.begin();
it != files.end();
++it)
{
if (isLocal)
{
isLocal = false;
continue;
}
KDesktopFile df2(*it);
name = df2.readName();
if (!name.isEmpty() && (name != "empty"))
return name;
}
}
}
return name;
}
TreeItem *TreeView::createTreeItem(TreeItem *parent, TQListViewItem *after, MenuFolderInfo *folderInfo, bool _init)
{
TreeItem *item;
if (parent == 0)
item = new TreeItem(this, after, TQString::null, _init);
else
item = new TreeItem(parent, after, TQString::null, _init);
item->setMenuFolderInfo(folderInfo);
item->setName(folderInfo->caption);
item->setPixmap(0, appIcon(folderInfo->icon));
item->setDirectoryPath(folderInfo->fullId);
item->setHidden(folderInfo->hidden);
item->setExpandable(true);
return item;
}
TreeItem *TreeView::createTreeItem(TreeItem *parent, TQListViewItem *after, MenuEntryInfo *entryInfo, bool _init)
{
bool hidden = entryInfo->hidden;
TreeItem* item;
if (parent == 0)
item = new TreeItem(this, after, entryInfo->menuId(), _init);
else
item = new TreeItem(parent, after, entryInfo->menuId(),_init);
QString name;
if (m_detailedMenuEntries && entryInfo->description.length() != 0)
{
if (m_detailedEntriesNamesFirst)
{
name = entryInfo->caption + " (" + entryInfo->description + ")";
}
else
{
name = entryInfo->description + " (" + entryInfo->caption + ")";
}
}
else
{
name = entryInfo->caption;
}
item->setMenuEntryInfo(entryInfo);
item->setName(name);
item->setPixmap(0, appIcon(entryInfo->icon));
item->setHidden(hidden);
return item;
}
TreeItem *TreeView::createTreeItem(TreeItem *parent, TQListViewItem *after, MenuSeparatorInfo *, bool _init)
{
TreeItem* item;
if (parent == 0)
item = new TreeItem(this, after, TQString::null, _init);
else
item = new TreeItem(parent, after, TQString::null,_init);
return item;
}
void TreeView::fillBranch(MenuFolderInfo *folderInfo, TreeItem *parent)
{
TQString relPath = parent ? parent->directory() : TQString::null;
TQPtrListIterator<MenuInfo> it( folderInfo->initialLayout );
TreeItem *after = 0;
for (MenuInfo *info; (info = it.current()); ++it)
{
MenuEntryInfo *entry = dynamic_cast<MenuEntryInfo*>(info);
if (entry)
{
after = createTreeItem(parent, after, entry);
continue;
}
MenuFolderInfo *subFolder = dynamic_cast<MenuFolderInfo*>(info);
if (subFolder)
{
after = createTreeItem(parent, after, subFolder);
continue;
}
MenuSeparatorInfo *separator = dynamic_cast<MenuSeparatorInfo*>(info);
if (separator)
{
after = createTreeItem(parent, after, separator);
continue;
}
}
}
void TreeView::closeAllItems(TQListViewItem *item)
{
if (!item) return;
while(item)
{
item->setOpen(false);
closeAllItems(item->firstChild());
item = item->nextSibling();
}
}
void TreeView::selectMenu(const TQString &menu)
{
closeAllItems(firstChild());
if (menu.length() <= 1)
{
setCurrentItem(firstChild());
clearSelection();
return; // Root menu
}
TQString restMenu = menu.mid(1);
if (!restMenu.endsWith("/"))
restMenu += "/";
TreeItem *item = 0;
do
{
int i = restMenu.find("/");
TQString subMenu = restMenu.left(i+1);
restMenu = restMenu.mid(i+1);
item = (TreeItem*)(item ? item->firstChild() : firstChild());
while(item)
{
MenuFolderInfo *folderInfo = item->folderInfo();
if (folderInfo && (folderInfo->id == subMenu))
{
item->setOpen(true);
break;
}
item = (TreeItem*) item->nextSibling();
}
}
while( item && !restMenu.isEmpty());
if (item)
{
setCurrentItem(item);
ensureItemVisible(item);
}
}
void TreeView::selectMenuEntry(const TQString &menuEntry)
{
TreeItem *item = (TreeItem *) selectedItem();
if (!item)
{
item = (TreeItem *) currentItem();
while (item && item->isDirectory())
item = (TreeItem*) item->nextSibling();
}
else
item = (TreeItem *) item->firstChild();
while(item)
{
MenuEntryInfo *entry = item->entryInfo();
if (entry && (entry->menuId() == menuEntry))
{
setCurrentItem(item);
ensureItemVisible(item);
return;
}
item = (TreeItem*) item->nextSibling();
}
}
void TreeView::itemSelected(TQListViewItem *item)
{
TreeItem *_item = (TreeItem*)item;
bool selected = false;
bool dselected = false;
if (_item) {
selected = true;
dselected = _item->isHidden();
}
m_ac->action("edit_cut")->setEnabled(selected);
m_ac->action("edit_copy")->setEnabled(selected);
if (m_ac->action("delete"))
m_ac->action("delete")->setEnabled(selected && !dselected);
if(!item)
{
emit disableAction();
return;
}
if (_item->isDirectory())
emit entrySelected(_item->folderInfo());
else
emit entrySelected(_item->entryInfo());
}
void TreeView::currentChanged(MenuFolderInfo *folderInfo)
{
TreeItem *item = (TreeItem*)selectedItem();
if (item == 0) return;
if (folderInfo == 0) return;
item->setName(folderInfo->caption);
item->setPixmap(0, appIcon(folderInfo->icon));
}
void TreeView::currentChanged(MenuEntryInfo *entryInfo)
{
TreeItem *item = (TreeItem*)selectedItem();
if (item == 0) return;
if (entryInfo == 0) return;
QString name;
if (m_detailedMenuEntries && entryInfo->description.length() != 0)
{
if (m_detailedEntriesNamesFirst)
{
name = entryInfo->caption + " (" + entryInfo->description + ")";
}
else
{
name = entryInfo->description + " (" + entryInfo->caption + ")";
}
}
else
{
name = entryInfo->caption;
}
item->setName(name);
item->setPixmap(0, appIcon(entryInfo->icon));
}
TQStringList TreeView::fileList(const TQString& rPath)
{
TQString relativePath = rPath;
// truncate "/.directory"
int pos = relativePath.findRev("/.directory");
if (pos > 0) relativePath.truncate(pos);
TQStringList filelist;
// loop through all resource dirs and build a file list
TQStringList resdirlist = TDEGlobal::dirs()->resourceDirs("apps");
for (TQStringList::ConstIterator it = resdirlist.begin(); it != resdirlist.end(); ++it)
{
TQDir dir((*it) + "/" + relativePath);
if(!dir.exists()) continue;
dir.setFilter(TQDir::Files);
dir.setNameFilter("*.desktop;*.kdelnk");
// build a list of files
TQStringList files = dir.entryList();
for (TQStringList::ConstIterator it = files.begin(); it != files.end(); ++it) {
// does not work?!
//if (filelist.contains(*it)) continue;
if (relativePath.isEmpty()) {
filelist.remove(*it); // hack
filelist.append(*it);
}
else {
filelist.remove(relativePath + "/" + *it); //hack
filelist.append(relativePath + "/" + *it);
}
}
}
return filelist;
}
TQStringList TreeView::dirList(const TQString& rPath)
{
TQString relativePath = rPath;
// truncate "/.directory"
int pos = relativePath.findRev("/.directory");
if (pos > 0) relativePath.truncate(pos);
TQStringList dirlist;
// loop through all resource dirs and build a subdir list
TQStringList resdirlist = TDEGlobal::dirs()->resourceDirs("apps");
for (TQStringList::ConstIterator it = resdirlist.begin(); it != resdirlist.end(); ++it)
{
TQDir dir((*it) + "/" + relativePath);
if(!dir.exists()) continue;
dir.setFilter(TQDir::Dirs);
// build a list of subdirs
TQStringList subdirs = dir.entryList();
for (TQStringList::ConstIterator it = subdirs.begin(); it != subdirs.end(); ++it) {
if ((*it) == "." || (*it) == "..") continue;
// does not work?!
// if (dirlist.contains(*it)) continue;
if (relativePath.isEmpty()) {
dirlist.remove(*it); //hack
dirlist.append(*it);
}
else {
dirlist.remove(relativePath + "/" + *it); //hack
dirlist.append(relativePath + "/" + *it);
}
}
}
return dirlist;
}
bool TreeView::acceptDrag(TQDropEvent* e) const
{
if (e->provides("application/x-kmenuedit-internal") &&
(e->source() == const_cast<TreeView *>(this)))
return true;
KURL::List urls;
if (KURLDrag::decode(e, urls) && (urls.count() == 1) &&
urls[0].isLocalFile() && urls[0].path().endsWith(".desktop"))
return true;
return false;
}
static TQString createDesktopFile(const TQString &file, TQString *menuId, TQStringList *excludeList)
{
TQString base = file.mid(file.findRev('/')+1);
base = base.left(base.findRev('.'));
TQRegExp r("(.*)(?=-\\d+)");
base = (r.search(base) > -1) ? r.cap(1) : base;
TQString result = KService::newServicePath(true, base, menuId, excludeList);
excludeList->append(*menuId);
// Todo for Undo-support: Undo menuId allocation:
return result;
}
static KDesktopFile *copyDesktopFile(MenuEntryInfo *entryInfo, TQString *menuId, TQStringList *excludeList)
{
TQString result = createDesktopFile(entryInfo->file(), menuId, excludeList);
KDesktopFile *df = entryInfo->desktopFile()->copyTo(result);
df->deleteEntry("Categories"); // Don't set any categories!
return df;
}
static TQString createDirectoryFile(const TQString &file, TQStringList *excludeList)
{
TQString base = file.mid(file.findRev('/')+1);
base = base.left(base.findRev('.'));
TQString result;
int i = 1;
while(true)
{
if (i == 1)
result = base + ".directory";
else
result = base + TQString("-%1.directory").arg(i);
if (!excludeList->contains(result))
{
if (locate("xdgdata-dirs", result).isEmpty())
break;
}
i++;
}
excludeList->append(result);
result = locateLocal("xdgdata-dirs", result);
return result;
}
void TreeView::slotDropped (TQDropEvent * e, TQListViewItem *parent, TQListViewItem*after)
{
if(!e) return;
// get destination folder
TreeItem *parentItem = static_cast<TreeItem*>(parent);
TQString folder = parentItem ? parentItem->directory() : TQString::null;
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
if (e->source() != this)
{
// External drop
KURL::List urls;
if (!KURLDrag::decode(e, urls) || (urls.count() != 1) || !urls[0].isLocalFile())
return;
TQString path = urls[0].path();
if (!path.endsWith(".desktop"))
return;
TQString menuId;
TQString result = createDesktopFile(path, &menuId, &m_newMenuIds);
KDesktopFile orig_df(path);
KDesktopFile *df = orig_df.copyTo(result);
df->deleteEntry("Categories"); // Don't set any categories!
KService *s = new KService(df);
s->setMenuId(menuId);
MenuEntryInfo *entryInfo = new MenuEntryInfo(s, df);
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption, oldCaption);
entryInfo->setCaption(newCaption);
// Add file to menu
// m_menuFile->addEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::ADD_ENTRY, folder, menuId);
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(entryInfo);
TreeItem *newItem = createTreeItem(parentItem, after, entryInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
m_drag = 0;
setLayoutDirty(parentItem);
return;
}
// is there content in the clipboard?
if (!m_drag) return;
if (m_dragItem == after) return; // Nothing to do
int command = m_drag;
if (command == MOVE_FOLDER)
{
MenuFolderInfo *folderInfo = m_dragInfo;
if (e->action() == TQDropEvent::Copy)
{
// Ugh.. this is hard :)
// * Create new .directory file
// Add
}
else
{
TreeItem *tmpItem = static_cast<TreeItem*>(parentItem);
while ( tmpItem )
{
if ( tmpItem == m_dragItem )
{
m_drag = 0;
return;
}
tmpItem = static_cast<TreeItem*>(tmpItem->parent() );
}
// Remove MenuFolderInfo
TreeItem *oldParentItem = static_cast<TreeItem*>(m_dragItem->parent());
MenuFolderInfo *oldParentFolderInfo = oldParentItem ? oldParentItem->folderInfo() : m_rootFolder;
oldParentFolderInfo->take(folderInfo);
// Move menu
TQString oldFolder = folderInfo->fullId;
TQString folderName = folderInfo->id;
TQString newFolder = m_menuFile->uniqueMenuName(folder, folderName, parentFolderInfo->existingMenuIds());
folderInfo->id = newFolder;
// Add file to menu
//m_menuFile->moveMenu(oldFolder, folder + newFolder);
m_menuFile->pushAction(MenuFile::MOVE_MENU, oldFolder, folder + newFolder);
// Make sure caption is unique
TQString newCaption = parentFolderInfo->uniqueMenuCaption(folderInfo->caption);
if (newCaption != folderInfo->caption)
{
folderInfo->setCaption(newCaption);
}
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
folderInfo->updateFullId(parentFolderInfo->fullId);
folderInfo->setInUse(true);
parentFolderInfo->add(folderInfo);
if ((parentItem != oldParentItem) || !after)
{
if (oldParentItem)
oldParentItem->takeItem(m_dragItem);
else
takeItem(m_dragItem);
if (parentItem)
parentItem->insertItem(m_dragItem);
else
insertItem(m_dragItem);
}
m_dragItem->moveItem(after);
m_dragItem->setName(folderInfo->caption);
m_dragItem->setDirectoryPath(folderInfo->fullId);
setSelected(m_dragItem, true);
itemSelected(m_dragItem);
}
}
else if (command == MOVE_FILE)
{
MenuEntryInfo *entryInfo = m_dragItem->entryInfo();
TQString menuId = entryInfo->menuId();
if (e->action() == TQDropEvent::Copy)
{
// Need to copy file and then add it
KDesktopFile *df = copyDesktopFile(entryInfo, &menuId, &m_newMenuIds); // Duplicate
//UNDO-ACTION: NEW_MENU_ID (menuId)
KService *s = new KService(df);
s->setMenuId(menuId);
entryInfo = new MenuEntryInfo(s, df);
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption, oldCaption);
entryInfo->setCaption(newCaption);
}
else
{
del(m_dragItem, false);
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption);
entryInfo->setCaption(newCaption);
entryInfo->setInUse(true);
}
// Add file to menu
// m_menuFile->addEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::ADD_ENTRY, folder, menuId);
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(entryInfo);
TreeItem *newItem = createTreeItem(parentItem, after, entryInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
}
else if (command == COPY_SEPARATOR)
{
if (e->action() != TQDropEvent::Copy)
del(m_dragItem, false);
TreeItem *newItem = createTreeItem(parentItem, after, m_separator, true);
setSelected ( newItem, true);
itemSelected( newItem);
}
else
{
// Error
}
m_drag = 0;
setLayoutDirty(parentItem);
}
void TreeView::startDrag()
{
TQDragObject *drag = dragObject();
if (!drag)
return;
drag->dragMove();
}
TQDragObject *TreeView::dragObject()
{
m_dragPath = TQString::null;
TreeItem *item = (TreeItem*)selectedItem();
if(item == 0) return 0;
KMultipleDrag *drag = new KMultipleDrag( this );
if (item->isDirectory())
{
m_drag = MOVE_FOLDER;
m_dragInfo = item->folderInfo();
m_dragItem = item;
}
else if (item->isEntry())
{
m_drag = MOVE_FILE;
m_dragInfo = 0;
m_dragItem = item;
TQString menuId = item->menuId();
m_dragPath = item->entryInfo()->service->desktopEntryPath();
if (!m_dragPath.isEmpty())
m_dragPath = locate("apps", m_dragPath);
if (!m_dragPath.isEmpty())
{
KURL url;
url.setPath(m_dragPath);
drag->addDragObject( new KURLDrag(url, 0));
}
}
else
{
m_drag = COPY_SEPARATOR;
m_dragInfo = 0;
m_dragItem = item;
}
drag->addDragObject( new TQStoredDrag("application/x-kmenuedit-internal", 0));
if ( item->pixmap(0) )
drag->setPixmap(*item->pixmap(0));
return drag;
}
void TreeView::slotRMBPressed(TQListViewItem*, const TQPoint& p)
{
TreeItem *item = (TreeItem*)selectedItem();
if(item == 0) return;
if(m_rmb) m_rmb->exec(p);
}
void TreeView::newsubmenu()
{
TreeItem *parentItem = 0;
TreeItem *item = (TreeItem*)selectedItem();
bool ok;
TQString caption = KInputDialog::getText( i18n( "New Submenu" ),
i18n( "Submenu name:" ), TQString::null, &ok, this );
if (!ok) return;
TQString file = caption;
file.replace('/', '-');
file = createDirectoryFile(file, &m_newDirectoryList); // Create
// get destination folder
TQString folder;
if(!item)
{
parentItem = 0;
folder = TQString::null;
}
else if(item->isDirectory())
{
parentItem = item;
item = 0;
folder = parentItem->directory();
}
else
{
parentItem = static_cast<TreeItem*>(item->parent());
folder = parentItem ? parentItem->directory() : TQString::null;
}
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
MenuFolderInfo *folderInfo = new MenuFolderInfo();
folderInfo->caption = parentFolderInfo->uniqueMenuCaption(caption);
folderInfo->id = m_menuFile->uniqueMenuName(folder, caption, parentFolderInfo->existingMenuIds());
folderInfo->directoryFile = file;
folderInfo->icon = "package";
folderInfo->hidden = false;
folderInfo->setDirty();
KDesktopFile *df = new KDesktopFile(file);
df->writeEntry("Name", folderInfo->caption);
df->writeEntry("Icon", folderInfo->icon);
df->sync();
delete df;
// Add file to menu
// m_menuFile->addMenu(folder + folderInfo->id, file);
m_menuFile->pushAction(MenuFile::ADD_MENU, folder + folderInfo->id, file);
folderInfo->fullId = parentFolderInfo->fullId + folderInfo->id;
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(folderInfo);
TreeItem *newItem = createTreeItem(parentItem, item, folderInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
setLayoutDirty(parentItem);
}
void TreeView::newitem()
{
TreeItem *parentItem = 0;
TreeItem *item = (TreeItem*)selectedItem();
bool ok;
TQString caption = KInputDialog::getText( i18n( "New Item" ),
i18n( "Item name:" ), TQString::null, &ok, this );
if (!ok) return;
TQString menuId;
TQString file = caption;
file.replace('/', '-');
file = createDesktopFile(file, &menuId, &m_newMenuIds); // Create
KDesktopFile *df = new KDesktopFile(file);
df->writeEntry("Name", caption);
df->writeEntry("Type", "Application");
// get destination folder
TQString folder;
if(!item)
{
parentItem = 0;
folder = TQString::null;
}
else if(item->isDirectory())
{
parentItem = item;
item = 0;
folder = parentItem->directory();
}
else
{
parentItem = static_cast<TreeItem*>(item->parent());
folder = parentItem ? parentItem->directory() : TQString::null;
}
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
// Add file to menu
// m_menuFile->addEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::ADD_ENTRY, folder, menuId);
KService *s = new KService(df);
s->setMenuId(menuId);
MenuEntryInfo *entryInfo = new MenuEntryInfo(s, df);
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(entryInfo);
TreeItem *newItem = createTreeItem(parentItem, item, entryInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
setLayoutDirty(parentItem);
}
void TreeView::newsep()
{
TreeItem *parentItem = 0;
TreeItem *item = (TreeItem*)selectedItem();
if(!item)
{
parentItem = 0;
}
else if(item->isDirectory())
{
parentItem = item;
item = 0;
}
else
{
parentItem = static_cast<TreeItem*>(item->parent());
}
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
TreeItem *newItem = createTreeItem(parentItem, item, m_separator, true);
setSelected ( newItem, true);
itemSelected( newItem);
setLayoutDirty(parentItem);
}
void TreeView::cut()
{
copy( true );
m_ac->action("edit_cut")->setEnabled(false);
m_ac->action("edit_copy")->setEnabled(false);
m_ac->action("delete")->setEnabled(false);
// Select new current item
setSelected( currentItem(), true );
// Switch the UI to show that item
itemSelected( selectedItem() );
}
void TreeView::copy()
{
copy( false );
}
void TreeView::copy( bool cutting )
{
TreeItem *item = (TreeItem*)selectedItem();
// nil selected? -> nil to copy
if (item == 0) return;
if (cutting)
setLayoutDirty((TreeItem*)item->parent());
// clean up old stuff
cleanupClipboard();
// is item a folder or a file?
if(item->isDirectory())
{
TQString folder = item->directory();
if (cutting)
{
// Place in clipboard
m_clipboard = MOVE_FOLDER;
m_clipboardFolderInfo = item->folderInfo();
del(item, false);
}
else
{
// Place in clipboard
m_clipboard = COPY_FOLDER;
m_clipboardFolderInfo = item->folderInfo();
}
}
else if (item->isEntry())
{
if (cutting)
{
// Place in clipboard
m_clipboard = MOVE_FILE;
m_clipboardEntryInfo = item->entryInfo();
del(item, false);
}
else
{
// Place in clipboard
m_clipboard = COPY_FILE;
m_clipboardEntryInfo = item->entryInfo();
}
}
else
{
// Place in clipboard
m_clipboard = COPY_SEPARATOR;
if (cutting)
del(item, false);
}
m_ac->action("edit_paste")->setEnabled(true);
}
void TreeView::paste()
{
TreeItem *parentItem = 0;
TreeItem *item = (TreeItem*)selectedItem();
// nil selected? -> nil to paste to
if (item == 0) return;
// is there content in the clipboard?
if (!m_clipboard) return;
// get destination folder
TQString folder;
if(item->isDirectory())
{
parentItem = item;
item = 0;
folder = parentItem->directory();
}
else
{
parentItem = static_cast<TreeItem*>(item->parent());
folder = parentItem ? parentItem->directory() : TQString::null;
}
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
int command = m_clipboard;
if ((command == COPY_FOLDER) || (command == MOVE_FOLDER))
{
MenuFolderInfo *folderInfo = m_clipboardFolderInfo;
if (command == COPY_FOLDER)
{
// Ugh.. this is hard :)
// * Create new .directory file
// Add
}
else if (command == MOVE_FOLDER)
{
// Move menu
TQString oldFolder = folderInfo->fullId;
TQString folderName = folderInfo->id;
TQString newFolder = m_menuFile->uniqueMenuName(folder, folderName, parentFolderInfo->existingMenuIds());
folderInfo->id = newFolder;
// Add file to menu
// m_menuFile->moveMenu(oldFolder, folder + newFolder);
m_menuFile->pushAction(MenuFile::MOVE_MENU, oldFolder, folder + newFolder);
// Make sure caption is unique
TQString newCaption = parentFolderInfo->uniqueMenuCaption(folderInfo->caption);
if (newCaption != folderInfo->caption)
{
folderInfo->setCaption(newCaption);
}
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
folderInfo->fullId = parentFolderInfo->fullId + folderInfo->id;
folderInfo->setInUse(true);
parentFolderInfo->add(folderInfo);
TreeItem *newItem = createTreeItem(parentItem, item, folderInfo);
setSelected ( newItem, true);
itemSelected( newItem);
}
m_clipboard = COPY_FOLDER; // Next one copies.
}
else if ((command == COPY_FILE) || (command == MOVE_FILE))
{
MenuEntryInfo *entryInfo = m_clipboardEntryInfo;
TQString menuId;
if (command == COPY_FILE)
{
// Need to copy file and then add it
KDesktopFile *df = copyDesktopFile(entryInfo, &menuId, &m_newMenuIds); // Duplicate
KService *s = new KService(df);
s->setMenuId(menuId);
entryInfo = new MenuEntryInfo(s, df);
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption, oldCaption);
entryInfo->setCaption(newCaption);
}
else if (command == MOVE_FILE)
{
menuId = entryInfo->menuId();
m_clipboard = COPY_FILE; // Next one copies.
TQString oldCaption = entryInfo->caption;
TQString newCaption = parentFolderInfo->uniqueItemCaption(oldCaption);
entryInfo->setCaption(newCaption);
entryInfo->setInUse(true);
}
// Add file to menu
// m_menuFile->addEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::ADD_ENTRY, folder, menuId);
// create the TreeItem
if(parentItem)
parentItem->setOpen(true);
// update fileInfo data
parentFolderInfo->add(entryInfo);
TreeItem *newItem = createTreeItem(parentItem, item, entryInfo, true);
setSelected ( newItem, true);
itemSelected( newItem);
}
else
{
// create separator
if(parentItem)
parentItem->setOpen(true);
TreeItem *newItem = createTreeItem(parentItem, item, m_separator, true);
setSelected ( newItem, true);
itemSelected( newItem);
}
setLayoutDirty(parentItem);
}
void TreeView::del()
{
TreeItem *item = (TreeItem*)selectedItem();
// nil selected? -> nil to delete
if (item == 0) return;
del(item, true);
m_ac->action("edit_cut")->setEnabled(false);
m_ac->action("edit_copy")->setEnabled(false);
m_ac->action("delete")->setEnabled(false);
// Select new current item
setSelected( currentItem(), true );
// Switch the UI to show that item
itemSelected( selectedItem() );
}
void TreeView::del(TreeItem *item, bool deleteInfo)
{
TreeItem *parentItem = static_cast<TreeItem*>(item->parent());
// is file a .directory or a .desktop file
if(item->isDirectory())
{
MenuFolderInfo *folderInfo = item->folderInfo();
// Remove MenuFolderInfo
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
parentFolderInfo->take(folderInfo);
folderInfo->setInUse(false);
if (m_clipboard == COPY_FOLDER && (m_clipboardFolderInfo == folderInfo))
{
// Copy + Del == Cut
m_clipboard = MOVE_FOLDER; // Clipboard now owns folderInfo
}
else
{
if (folderInfo->takeRecursive(m_clipboardFolderInfo))
m_clipboard = MOVE_FOLDER; // Clipboard now owns m_clipboardFolderInfo
if (deleteInfo)
delete folderInfo; // Delete folderInfo
}
// Remove from menu
// m_menuFile->removeMenu(item->directory());
m_menuFile->pushAction(MenuFile::REMOVE_MENU, item->directory(), TQString::null);
// Remove tree item
delete item;
}
else if (item->isEntry())
{
MenuEntryInfo *entryInfo = item->entryInfo();
TQString menuId = entryInfo->menuId();
// Remove MenuFolderInfo
MenuFolderInfo *parentFolderInfo = parentItem ? parentItem->folderInfo() : m_rootFolder;
parentFolderInfo->take(entryInfo);
entryInfo->setInUse(false);
if (m_clipboard == COPY_FILE && (m_clipboardEntryInfo == entryInfo))
{
// Copy + Del == Cut
m_clipboard = MOVE_FILE; // Clipboard now owns entryInfo
}
else
{
if (deleteInfo)
delete entryInfo; // Delete entryInfo
}
// Remove from menu
TQString folder = parentItem ? parentItem->directory() : TQString::null;
// m_menuFile->removeEntry(folder, menuId);
m_menuFile->pushAction(MenuFile::REMOVE_ENTRY, folder, menuId);
// Remove tree item
delete item;
}
else
{
// Remove separator
delete item;
}
setLayoutDirty(parentItem);
}
void TreeView::cleanupClipboard() {
if (m_clipboard == MOVE_FOLDER)
delete m_clipboardFolderInfo;
m_clipboardFolderInfo = 0;
if (m_clipboard == MOVE_FILE)
delete m_clipboardEntryInfo;
m_clipboardEntryInfo = 0;
m_clipboard = 0;
}
static TQStringList extractLayout(TreeItem *item)
{
bool firstFolder = true;
bool firstEntry = true;
TQStringList layout;
for(;item; item = static_cast<TreeItem*>(item->nextSibling()))
{
if (item->isDirectory())
{
if (firstFolder)
{
firstFolder = false;
layout << ":M"; // Add new folders here...
}
layout << (item->folderInfo()->id);
}
else if (item->isEntry())
{
if (firstEntry)
{
firstEntry = false;
layout << ":F"; // Add new entries here...
}
layout << (item->entryInfo()->menuId());
}
else
{
layout << ":S";
}
}
return layout;
}
TQStringList TreeItem::layout()
{
TQStringList layout = extractLayout(static_cast<TreeItem*>(firstChild()));
_layoutDirty = false;
return layout;
}
void TreeView::saveLayout()
{
if (m_layoutDirty)
{
TQStringList layout = extractLayout(static_cast<TreeItem*>(firstChild()));
m_menuFile->setLayout(m_rootFolder->fullId, layout);
m_layoutDirty = false;
}
TQPtrList<TQListViewItem> lst;
TQListViewItemIterator it( this );
while ( it.current() ) {
TreeItem *item = static_cast<TreeItem*>(it.current());
if ( item->isLayoutDirty() )
{
m_menuFile->setLayout(item->folderInfo()->fullId, item->layout());
}
++it;
}
}
bool TreeView::save()
{
saveLayout();
m_rootFolder->save(m_menuFile);
bool success = m_menuFile->performAllActions();
m_newMenuIds.clear();
m_newDirectoryList.clear();
if (success)
{
KService::rebuildKSycoca(this);
}
else
{
KMessageBox::sorry(this, "<qt>"+i18n("Menu changes could not be saved because of the following problem:")+"<br><br>"+
m_menuFile->error()+"</qt>");
}
return success;
}
void TreeView::setLayoutDirty(TreeItem *parentItem)
{
if (parentItem)
parentItem->setLayoutDirty();
else
m_layoutDirty = true;
}
bool TreeView::isLayoutDirty()
{
TQPtrList<TQListViewItem> lst;
TQListViewItemIterator it( this );
while ( it.current() ) {
if ( static_cast<TreeItem*>(it.current())->isLayoutDirty() )
return true;
++it;
}
return false;
}
bool TreeView::dirty()
{
return m_layoutDirty || m_rootFolder->hasDirt() || m_menuFile->dirty() || isLayoutDirty();
}
void TreeView::findServiceShortcut(const TDEShortcut&cut, KService::Ptr &service)
{
service = m_rootFolder->findServiceShortcut(cut);
}
| Java |
/*
* Copyright (C) Dag Henning Liodden Sørbø <daghenning@lioddensorbo.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, see <http://www.gnu.org/licenses/>.
*/
#include "drawingview.h"
#include <QApplication>
#include "randomgenerator.h"
#include "drawingcontroller.h"
#include "drawingsetupcontroller.h"
#include "lotwindow.h"
#include "app.h"
#include <QLibraryInfo>
#include <QTranslator>
#include "color.h"
#include "settingshandler.h"
#include "selectlanguagedialog.h"
#include "updatereminder.h"
#include "updateview.h"
#include "i18n.h"
bool setLanguageToSystemLanguage() {
QString langCountry = QLocale().system().name();
QString lang = langCountry.left(2);
if (lang == "nb" || lang == "nn") {
lang = "no";
}
bool langIsSupported = false;
for (int i = 0; i < NUM_LANGUAGES; ++i) {
if (LANGUAGES[i][1] == lang) {
langIsSupported = true;
}
}
if (langIsSupported) {
SettingsHandler::setLanguage(lang);
}
return langIsSupported;
}
int setupLanguage(QApplication& app) {
if (!SettingsHandler::hasLanguage()) {
bool ok = setLanguageToSystemLanguage();
if (!ok) {
SelectLanguageDialog dialog;
if (dialog.exec() == QDialog::Rejected) {
return -1;
}
}
}
QString language = SettingsHandler::language();
if (language != "en") {
QTranslator* translator = new QTranslator();
QString filename = QString(language).append(".qm");
translator->load(filename, ":/app/translations");
app.installTranslator(translator);
}
return 0;
}
int main(int argc, char *argv[])
{
RandomGenerator::init();
qRegisterMetaTypeStreamOperators<Color>("Color");
QApplication app(argc, argv);
app.setApplicationName(APPLICATION_NAME);
app.setApplicationDisplayName(APPLICATION_NAME);
app.setApplicationVersion(APPLICATION_VERSION);
app.setOrganizationName(ORG_NAME);
app.setOrganizationDomain(ORG_DOMAIN);
QIcon icon(":/gui/icons/lots.svg");
app.setWindowIcon(icon);
#ifdef Q_OS_MAC
app.setAttribute(Qt::AA_DontShowIconsInMenus, true);
#endif
SettingsHandler::initialize(ORG_NAME, APPLICATION_NAME);
if (int res = setupLanguage(app) != 0) {
return res;
}
DrawingSetupController setupController;
DrawingSetupDialog setupDialog(&setupController);
DrawingController controller;
DrawingView drawingView(&controller, &setupDialog);
controller.setDrawingView(&drawingView);
UpdateView updateView(&setupDialog);
UpdateReminder reminder([&](UpdateInfo info) {
if (!info.hasError && info.hasUpdate) {
updateView.setUpdateInfo(info);
updateView.show();
}
});
if (!SettingsHandler::autoUpdatesDisabled()) {
reminder.checkForUpdate();
}
return app.exec();
}
| Java |
#include "../comedidev.h"
#include "comedi_pci.h"
#include "8255.h"
#define PCI_VENDOR_ID_CB 0x1307 /* PCI vendor number of ComputerBoards */
#define EEPROM_SIZE 128 /* number of entries in eeprom */
#define MAX_AO_CHANNELS 8 /* maximum number of ao channels for supported boards */
/* PCI-DDA base addresses */
#define DIGITALIO_BADRINDEX 2
/* DIGITAL I/O is pci_dev->resource[2] */
#define DIGITALIO_SIZE 8
/* DIGITAL I/O uses 8 I/O port addresses */
#define DAC_BADRINDEX 3
/* DAC is pci_dev->resource[3] */
/* Digital I/O registers */
#define PORT1A 0 /* PORT 1A DATA */
#define PORT1B 1 /* PORT 1B DATA */
#define PORT1C 2 /* PORT 1C DATA */
#define CONTROL1 3 /* CONTROL REGISTER 1 */
#define PORT2A 4 /* PORT 2A DATA */
#define PORT2B 5 /* PORT 2B DATA */
#define PORT2C 6 /* PORT 2C DATA */
#define CONTROL2 7 /* CONTROL REGISTER 2 */
/* DAC registers */
#define DACONTROL 0 /* D/A CONTROL REGISTER */
#define SU 0000001 /* Simultaneous update enabled */
#define NOSU 0000000 /* Simultaneous update disabled */
#define ENABLEDAC 0000002 /* Enable specified DAC */
#define DISABLEDAC 0000000 /* Disable specified DAC */
#define RANGE2V5 0000000 /* 2.5V */
#define RANGE5V 0000200 /* 5V */
#define RANGE10V 0000300 /* 10V */
#define UNIP 0000400 /* Unipolar outputs */
#define BIP 0000000 /* Bipolar outputs */
#define DACALIBRATION1 4 /* D/A CALIBRATION REGISTER 1 */
/* write bits */
#define SERIAL_IN_BIT 0x1 /* serial data input for eeprom, caldacs, reference dac */
#define CAL_CHANNEL_MASK (0x7 << 1)
#define CAL_CHANNEL_BITS(channel) (((channel) << 1) & CAL_CHANNEL_MASK)
/* read bits */
#define CAL_COUNTER_MASK 0x1f
#define CAL_COUNTER_OVERFLOW_BIT 0x20 /* calibration counter overflow status bit */
#define AO_BELOW_REF_BIT 0x40 /* analog output is less than reference dac voltage */
#define SERIAL_OUT_BIT 0x80 /* serial data out, for reading from eeprom */
#define DACALIBRATION2 6 /* D/A CALIBRATION REGISTER 2 */
#define SELECT_EEPROM_BIT 0x1 /* send serial data in to eeprom */
#define DESELECT_REF_DAC_BIT 0x2 /* don't send serial data to MAX542 reference dac */
#define DESELECT_CALDAC_BIT(n) (0x4 << (n)) /* don't send serial data to caldac n */
#define DUMMY_BIT 0x40 /* manual says to set this bit with no explanation */
#define DADATA 8 /* FIRST D/A DATA REGISTER (0) */
static const struct comedi_lrange cb_pcidda_ranges = {
6,
{
BIP_RANGE(10),
BIP_RANGE(5),
BIP_RANGE(2.5),
UNI_RANGE(10),
UNI_RANGE(5),
UNI_RANGE(2.5),
}
};
struct cb_pcidda_board {
const char *name;
char status; /* Driver status: */
/*
* 0 - tested
* 1 - manual read, not tested
* 2 - manual not read
*/
unsigned short device_id;
int ao_chans;
int ao_bits;
const struct comedi_lrange *ranges;
};
static const struct cb_pcidda_board cb_pcidda_boards[] = {
{
.name = "pci-dda02/12",
.status = 1,
.device_id = 0x20,
.ao_chans = 2,
.ao_bits = 12,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda04/12",
.status = 1,
.device_id = 0x21,
.ao_chans = 4,
.ao_bits = 12,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda08/12",
.status = 0,
.device_id = 0x22,
.ao_chans = 8,
.ao_bits = 12,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda02/16",
.status = 2,
.device_id = 0x23,
.ao_chans = 2,
.ao_bits = 16,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda04/16",
.status = 2,
.device_id = 0x24,
.ao_chans = 4,
.ao_bits = 16,
.ranges = &cb_pcidda_ranges,
},
{
.name = "pci-dda08/16",
.status = 0,
.device_id = 0x25,
.ao_chans = 8,
.ao_bits = 16,
.ranges = &cb_pcidda_ranges,
},
};
static DEFINE_PCI_DEVICE_TABLE(cb_pcidda_pci_table) = {
{
PCI_VENDOR_ID_CB, 0x0020, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0021, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0022, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0023, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0024, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_CB, 0x0025, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
0}
};
MODULE_DEVICE_TABLE(pci, cb_pcidda_pci_table);
#define thisboard ((const struct cb_pcidda_board *)dev->board_ptr)
struct cb_pcidda_private {
int data;
/* would be useful for a PCI device */
struct pci_dev *pci_dev;
unsigned long digitalio;
unsigned long dac;
/* unsigned long control_status; */
/* unsigned long adc_fifo; */
unsigned int dac_cal1_bits; /* bits last written to da calibration register 1 */
unsigned int ao_range[MAX_AO_CHANNELS]; /* current range settings for output channels */
u16 eeprom_data[EEPROM_SIZE]; /* software copy of board's eeprom */
};
#define devpriv ((struct cb_pcidda_private *)dev->private)
static int cb_pcidda_attach(struct comedi_device *dev,
struct comedi_devconfig *it);
static int cb_pcidda_detach(struct comedi_device *dev);
/* static int cb_pcidda_ai_rinsn(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data); */
static int cb_pcidda_ao_winsn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
/* static int cb_pcidda_ai_cmd(struct comedi_device *dev, struct *comedi_subdevice *s);*/
/* static int cb_pcidda_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_cmd *cmd); */
/* static int cb_pcidda_ns_to_timer(unsigned int *ns,int *round); */
static unsigned int cb_pcidda_serial_in(struct comedi_device *dev);
static void cb_pcidda_serial_out(struct comedi_device *dev, unsigned int value,
unsigned int num_bits);
static unsigned int cb_pcidda_read_eeprom(struct comedi_device *dev,
unsigned int address);
static void cb_pcidda_calibrate(struct comedi_device *dev, unsigned int channel,
unsigned int range);
static struct comedi_driver driver_cb_pcidda = {
.driver_name = "cb_pcidda",
.module = THIS_MODULE,
.attach = cb_pcidda_attach,
.detach = cb_pcidda_detach,
};
static int cb_pcidda_attach(struct comedi_device *dev,
struct comedi_devconfig *it)
{
struct comedi_subdevice *s;
struct pci_dev *pcidev;
int index;
printk("comedi%d: cb_pcidda: ", dev->minor);
if (alloc_private(dev, sizeof(struct cb_pcidda_private)) < 0)
return -ENOMEM;
printk("\n");
for (pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, NULL);
pcidev != NULL;
pcidev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pcidev)) {
if (pcidev->vendor == PCI_VENDOR_ID_CB) {
if (it->options[0] || it->options[1]) {
if (pcidev->bus->number != it->options[0] ||
PCI_SLOT(pcidev->devfn) != it->options[1]) {
continue;
}
}
for (index = 0; index < ARRAY_SIZE(cb_pcidda_boards); index++) {
if (cb_pcidda_boards[index].device_id ==
pcidev->device) {
goto found;
}
}
}
}
if (!pcidev) {
printk
("Not a ComputerBoards/MeasurementComputing card on requested position\n");
return -EIO;
}
found:
devpriv->pci_dev = pcidev;
dev->board_ptr = cb_pcidda_boards + index;
/* "thisboard" macro can be used from here. */
printk("Found %s at requested position\n", thisboard->name);
/*
* Enable PCI device and request regions.
*/
if (comedi_pci_enable(pcidev, thisboard->name)) {
printk
("cb_pcidda: failed to enable PCI device and request regions\n");
return -EIO;
}
devpriv->digitalio =
pci_resource_start(devpriv->pci_dev, DIGITALIO_BADRINDEX);
devpriv->dac = pci_resource_start(devpriv->pci_dev, DAC_BADRINDEX);
if (thisboard->status == 2)
printk
("WARNING: DRIVER FOR THIS BOARD NOT CHECKED WITH MANUAL. "
"WORKS ASSUMING FULL COMPATIBILITY WITH PCI-DDA08/12. "
"PLEASE REPORT USAGE TO <ivanmr@altavista.com>.\n");
dev->board_name = thisboard->name;
if (alloc_subdevices(dev, 3) < 0)
return -ENOMEM;
s = dev->subdevices + 0;
/* analog output subdevice */
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITABLE;
s->n_chan = thisboard->ao_chans;
s->maxdata = (1 << thisboard->ao_bits) - 1;
s->range_table = thisboard->ranges;
s->insn_write = cb_pcidda_ao_winsn;
/* s->subdev_flags |= SDF_CMD_READ; */
/* s->do_cmd = cb_pcidda_ai_cmd; */
/* s->do_cmdtest = cb_pcidda_ai_cmdtest; */
/* two 8255 digital io subdevices */
s = dev->subdevices + 1;
subdev_8255_init(dev, s, NULL, devpriv->digitalio);
s = dev->subdevices + 2;
subdev_8255_init(dev, s, NULL, devpriv->digitalio + PORT2A);
printk(" eeprom:");
for (index = 0; index < EEPROM_SIZE; index++) {
devpriv->eeprom_data[index] = cb_pcidda_read_eeprom(dev, index);
printk(" %i:0x%x ", index, devpriv->eeprom_data[index]);
}
printk("\n");
/* set calibrations dacs */
for (index = 0; index < thisboard->ao_chans; index++)
cb_pcidda_calibrate(dev, index, devpriv->ao_range[index]);
return 1;
}
static int cb_pcidda_detach(struct comedi_device *dev)
{
if (devpriv) {
if (devpriv->pci_dev) {
if (devpriv->dac)
comedi_pci_disable(devpriv->pci_dev);
pci_dev_put(devpriv->pci_dev);
}
}
/* cleanup 8255 */
if (dev->subdevices) {
subdev_8255_cleanup(dev, dev->subdevices + 1);
subdev_8255_cleanup(dev, dev->subdevices + 2);
}
printk("comedi%d: cb_pcidda: remove\n", dev->minor);
return 0;
}
#if 0
static int cb_pcidda_ai_cmd(struct comedi_device *dev,
struct comedi_subdevice *s)
{
printk("cb_pcidda_ai_cmd\n");
printk("subdev: %d\n", cmd->subdev);
printk("flags: %d\n", cmd->flags);
printk("start_src: %d\n", cmd->start_src);
printk("start_arg: %d\n", cmd->start_arg);
printk("scan_begin_src: %d\n", cmd->scan_begin_src);
printk("convert_src: %d\n", cmd->convert_src);
printk("convert_arg: %d\n", cmd->convert_arg);
printk("scan_end_src: %d\n", cmd->scan_end_src);
printk("scan_end_arg: %d\n", cmd->scan_end_arg);
printk("stop_src: %d\n", cmd->stop_src);
printk("stop_arg: %d\n", cmd->stop_arg);
printk("chanlist_len: %d\n", cmd->chanlist_len);
}
#endif
#if 0
static int cb_pcidda_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
int err = 0;
int tmp;
/* cmdtest tests a particular command to see if it is valid.
* Using the cmdtest ioctl, a user can create a valid cmd
* and then have it executes by the cmd ioctl.
*
* cmdtest returns 1,2,3,4 or 0, depending on which tests
* the command passes. */
/* step 1: make sure trigger sources are trivially valid */
tmp = cmd->start_src;
cmd->start_src &= TRIG_NOW;
if (!cmd->start_src || tmp != cmd->start_src)
err++;
tmp = cmd->scan_begin_src;
cmd->scan_begin_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
err++;
tmp = cmd->convert_src;
cmd->convert_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->convert_src || tmp != cmd->convert_src)
err++;
tmp = cmd->scan_end_src;
cmd->scan_end_src &= TRIG_COUNT;
if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
err++;
tmp = cmd->stop_src;
cmd->stop_src &= TRIG_COUNT | TRIG_NONE;
if (!cmd->stop_src || tmp != cmd->stop_src)
err++;
if (err)
return 1;
/* step 2: make sure trigger sources are unique and mutually compatible */
/* note that mutual compatibility is not an issue here */
if (cmd->scan_begin_src != TRIG_TIMER
&& cmd->scan_begin_src != TRIG_EXT)
err++;
if (cmd->convert_src != TRIG_TIMER && cmd->convert_src != TRIG_EXT)
err++;
if (cmd->stop_src != TRIG_TIMER && cmd->stop_src != TRIG_EXT)
err++;
if (err)
return 2;
/* step 3: make sure arguments are trivially compatible */
if (cmd->start_arg != 0) {
cmd->start_arg = 0;
err++;
}
#define MAX_SPEED 10000 /* in nanoseconds */
#define MIN_SPEED 1000000000 /* in nanoseconds */
if (cmd->scan_begin_src == TRIG_TIMER) {
if (cmd->scan_begin_arg < MAX_SPEED) {
cmd->scan_begin_arg = MAX_SPEED;
err++;
}
if (cmd->scan_begin_arg > MIN_SPEED) {
cmd->scan_begin_arg = MIN_SPEED;
err++;
}
} else {
/* external trigger */
/* should be level/edge, hi/lo specification here */
/* should specify multiple external triggers */
if (cmd->scan_begin_arg > 9) {
cmd->scan_begin_arg = 9;
err++;
}
}
if (cmd->convert_src == TRIG_TIMER) {
if (cmd->convert_arg < MAX_SPEED) {
cmd->convert_arg = MAX_SPEED;
err++;
}
if (cmd->convert_arg > MIN_SPEED) {
cmd->convert_arg = MIN_SPEED;
err++;
}
} else {
/* external trigger */
/* see above */
if (cmd->convert_arg > 9) {
cmd->convert_arg = 9;
err++;
}
}
if (cmd->scan_end_arg != cmd->chanlist_len) {
cmd->scan_end_arg = cmd->chanlist_len;
err++;
}
if (cmd->stop_src == TRIG_COUNT) {
if (cmd->stop_arg > 0x00ffffff) {
cmd->stop_arg = 0x00ffffff;
err++;
}
} else {
/* TRIG_NONE */
if (cmd->stop_arg != 0) {
cmd->stop_arg = 0;
err++;
}
}
if (err)
return 3;
/* step 4: fix up any arguments */
if (cmd->scan_begin_src == TRIG_TIMER) {
tmp = cmd->scan_begin_arg;
cb_pcidda_ns_to_timer(&cmd->scan_begin_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->scan_begin_arg)
err++;
}
if (cmd->convert_src == TRIG_TIMER) {
tmp = cmd->convert_arg;
cb_pcidda_ns_to_timer(&cmd->convert_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->convert_arg)
err++;
if (cmd->scan_begin_src == TRIG_TIMER &&
cmd->scan_begin_arg <
cmd->convert_arg * cmd->scan_end_arg) {
cmd->scan_begin_arg =
cmd->convert_arg * cmd->scan_end_arg;
err++;
}
}
if (err)
return 4;
return 0;
}
#endif
#if 0
static int cb_pcidda_ns_to_timer(unsigned int *ns, int round)
{
/* trivial timer */
return *ns;
}
#endif
static int cb_pcidda_ao_winsn(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
unsigned int command;
unsigned int channel, range;
channel = CR_CHAN(insn->chanspec);
range = CR_RANGE(insn->chanspec);
/* adjust calibration dacs if range has changed */
if (range != devpriv->ao_range[channel])
cb_pcidda_calibrate(dev, channel, range);
/* output channel configuration */
command = NOSU | ENABLEDAC;
/* output channel range */
switch (range) {
case 0:
command |= BIP | RANGE10V;
break;
case 1:
command |= BIP | RANGE5V;
break;
case 2:
command |= BIP | RANGE2V5;
break;
case 3:
command |= UNIP | RANGE10V;
break;
case 4:
command |= UNIP | RANGE5V;
break;
case 5:
command |= UNIP | RANGE2V5;
break;
};
/* output channel specification */
command |= channel << 2;
outw(command, devpriv->dac + DACONTROL);
/* write data */
outw(data[0], devpriv->dac + DADATA + channel * 2);
/* return the number of samples read/written */
return 1;
}
/* lowlevel read from eeprom */
static unsigned int cb_pcidda_serial_in(struct comedi_device *dev)
{
unsigned int value = 0;
int i;
const int value_width = 16; /* number of bits wide values are */
for (i = 1; i <= value_width; i++) {
/* read bits most significant bit first */
if (inw_p(devpriv->dac + DACALIBRATION1) & SERIAL_OUT_BIT)
value |= 1 << (value_width - i);
}
return value;
}
/* lowlevel write to eeprom/dac */
static void cb_pcidda_serial_out(struct comedi_device *dev, unsigned int value,
unsigned int num_bits)
{
int i;
for (i = 1; i <= num_bits; i++) {
/* send bits most significant bit first */
if (value & (1 << (num_bits - i)))
devpriv->dac_cal1_bits |= SERIAL_IN_BIT;
else
devpriv->dac_cal1_bits &= ~SERIAL_IN_BIT;
outw_p(devpriv->dac_cal1_bits, devpriv->dac + DACALIBRATION1);
}
}
/* reads a 16 bit value from board's eeprom */
static unsigned int cb_pcidda_read_eeprom(struct comedi_device *dev,
unsigned int address)
{
unsigned int i;
unsigned int cal2_bits;
unsigned int value;
const int max_num_caldacs = 4; /* one caldac for every two dac channels */
const int read_instruction = 0x6; /* bits to send to tell eeprom we want to read */
const int instruction_length = 3;
const int address_length = 8;
/* send serial output stream to eeprom */
cal2_bits = SELECT_EEPROM_BIT | DESELECT_REF_DAC_BIT | DUMMY_BIT;
/* deactivate caldacs (one caldac for every two channels) */
for (i = 0; i < max_num_caldacs; i++)
cal2_bits |= DESELECT_CALDAC_BIT(i);
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
/* tell eeprom we want to read */
cb_pcidda_serial_out(dev, read_instruction, instruction_length);
/* send address we want to read from */
cb_pcidda_serial_out(dev, address, address_length);
value = cb_pcidda_serial_in(dev);
/* deactivate eeprom */
cal2_bits &= ~SELECT_EEPROM_BIT;
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
return value;
}
/* writes to 8 bit calibration dacs */
static void cb_pcidda_write_caldac(struct comedi_device *dev,
unsigned int caldac, unsigned int channel,
unsigned int value)
{
unsigned int cal2_bits;
unsigned int i;
const int num_channel_bits = 3; /* caldacs use 3 bit channel specification */
const int num_caldac_bits = 8; /* 8 bit calibration dacs */
const int max_num_caldacs = 4; /* one caldac for every two dac channels */
/* write 3 bit channel */
cb_pcidda_serial_out(dev, channel, num_channel_bits);
/* write 8 bit caldac value */
cb_pcidda_serial_out(dev, value, num_caldac_bits);
cal2_bits = DESELECT_REF_DAC_BIT | DUMMY_BIT;
/* deactivate caldacs (one caldac for every two channels) */
for (i = 0; i < max_num_caldacs; i++)
cal2_bits |= DESELECT_CALDAC_BIT(i);
/* activate the caldac we want */
cal2_bits &= ~DESELECT_CALDAC_BIT(caldac);
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
/* deactivate caldac */
cal2_bits |= DESELECT_CALDAC_BIT(caldac);
outw_p(cal2_bits, devpriv->dac + DACALIBRATION2);
}
/* returns caldac that calibrates given analog out channel */
static unsigned int caldac_number(unsigned int channel)
{
return channel / 2;
}
/* returns caldac channel that provides fine gain for given ao channel */
static unsigned int fine_gain_channel(unsigned int ao_channel)
{
return 4 * (ao_channel % 2);
}
/* returns caldac channel that provides coarse gain for given ao channel */
static unsigned int coarse_gain_channel(unsigned int ao_channel)
{
return 1 + 4 * (ao_channel % 2);
}
/* returns caldac channel that provides coarse offset for given ao channel */
static unsigned int coarse_offset_channel(unsigned int ao_channel)
{
return 2 + 4 * (ao_channel % 2);
}
/* returns caldac channel that provides fine offset for given ao channel */
static unsigned int fine_offset_channel(unsigned int ao_channel)
{
return 3 + 4 * (ao_channel % 2);
}
/* returns eeprom address that provides offset for given ao channel and range */
static unsigned int offset_eeprom_address(unsigned int ao_channel,
unsigned int range)
{
return 0x7 + 2 * range + 12 * ao_channel;
}
/* returns eeprom address that provides gain calibration for given ao channel and range */
static unsigned int gain_eeprom_address(unsigned int ao_channel,
unsigned int range)
{
return 0x8 + 2 * range + 12 * ao_channel;
}
/* returns upper byte of eeprom entry, which gives the coarse adjustment values */
static unsigned int eeprom_coarse_byte(unsigned int word)
{
return (word >> 8) & 0xff;
}
/* returns lower byte of eeprom entry, which gives the fine adjustment values */
static unsigned int eeprom_fine_byte(unsigned int word)
{
return word & 0xff;
}
/* set caldacs to eeprom values for given channel and range */
static void cb_pcidda_calibrate(struct comedi_device *dev, unsigned int channel,
unsigned int range)
{
unsigned int coarse_offset, fine_offset, coarse_gain, fine_gain;
/* remember range so we can tell when we need to readjust calibration */
devpriv->ao_range[channel] = range;
/* get values from eeprom data */
coarse_offset =
eeprom_coarse_byte(devpriv->eeprom_data
[offset_eeprom_address(channel, range)]);
fine_offset =
eeprom_fine_byte(devpriv->eeprom_data
[offset_eeprom_address(channel, range)]);
coarse_gain =
eeprom_coarse_byte(devpriv->eeprom_data
[gain_eeprom_address(channel, range)]);
fine_gain =
eeprom_fine_byte(devpriv->eeprom_data
[gain_eeprom_address(channel, range)]);
/* set caldacs */
cb_pcidda_write_caldac(dev, caldac_number(channel),
coarse_offset_channel(channel), coarse_offset);
cb_pcidda_write_caldac(dev, caldac_number(channel),
fine_offset_channel(channel), fine_offset);
cb_pcidda_write_caldac(dev, caldac_number(channel),
coarse_gain_channel(channel), coarse_gain);
cb_pcidda_write_caldac(dev, caldac_number(channel),
fine_gain_channel(channel), fine_gain);
}
COMEDI_PCI_INITCLEANUP(driver_cb_pcidda, cb_pcidda_pci_table);
| Java |
#ifndef SCSI_TRANSPORT_SRP_H
#define SCSI_TRANSPORT_SRP_H
#include <linux/transport_class.h>
#include <linux/types.h>
#include <linux/mutex.h>
#define SRP_RPORT_ROLE_INITIATOR 0
#define SRP_RPORT_ROLE_TARGET 1
struct srp_rport_identifiers {
u8 port_id[16];
u8 roles;
};
struct srp_rport {
struct device dev;
u8 port_id[16];
u8 roles;
};
struct srp_function_template {
/* for target drivers */
int (* tsk_mgmt_response)(struct Scsi_Host *, u64, u64, int);
int (* it_nexus_response)(struct Scsi_Host *, u64, int);
};
extern struct scsi_transport_template *
srp_attach_transport(struct srp_function_template *);
extern void srp_release_transport(struct scsi_transport_template *);
extern struct srp_rport *srp_rport_add(struct Scsi_Host *,
struct srp_rport_identifiers *);
extern void srp_rport_del(struct srp_rport *);
extern void srp_remove_host(struct Scsi_Host *);
#endif
| Java |
/** ======================================================================== */
/** */
/** @copyright Copyright (c) 2010-2015, S2S s.r.l. */
/** @license http://www.gnu.org/licenses/gpl-2.0.html GNU Public License v.2 */
/** @version 6.0 */
/** This file is part of SdS - Sistema della Sicurezza . */
/** SdS - Sistema della Sicurezza 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. */
/** SdS - Sistema della Sicurezza 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 SdS - Sistema della Sicurezza . If not, see <http://www.gnu.org/licenses/gpl-2.0.html> GNU Public License v.2 */
/** */
/** ======================================================================== */
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.apconsulting.luna.ejb.Corsi;
/**
*
* @author Dario
*/
public class MaterialeCorso_View implements java.io.Serializable {
public long COD_DOC;
public String TIT_DOC;
public java.sql.Date DAT_REV_DOC;
public String RSP_DOC;
public String NOME_FILE;
}
| Java |
/*
* Copyright (C) 2014-2017 StormCore
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellAuraEffects.h"
#include "SpellScript.h"
#include "vault_of_archavon.h"
enum Events
{
// Koralon
EVENT_BURNING_BREATH = 1,
EVENT_BURNING_FURY = 2,
EVENT_FLAME_CINDER = 3,
EVENT_METEOR_FISTS = 4,
// Flame Warder
EVENT_FW_LAVA_BIRST = 5,
EVENT_FW_METEOR_FISTS = 6
};
enum Spells
{
// Spells Koralon
SPELL_BURNING_BREATH = 66665,
SPELL_BURNING_FURY = 66721,
SPELL_FLAME_CINDER_A = 66684,
SPELL_FLAME_CINDER_B = 66681, // don't know the real relation to SPELL_FLAME_CINDER_A atm.
SPELL_METEOR_FISTS = 66725,
SPELL_METEOR_FISTS_DAMAGE = 66765,
// Spells Flame Warder
SPELL_FW_LAVA_BIRST = 66813,
SPELL_FW_METEOR_FISTS = 66808,
SPELL_FW_METEOR_FISTS_DAMAGE = 66809
};
class boss_koralon : public CreatureScript
{
public:
boss_koralon() : CreatureScript("boss_koralon") { }
struct boss_koralonAI : public BossAI
{
boss_koralonAI(Creature* creature) : BossAI(creature, DATA_KORALON)
{
}
void EnterCombat(Unit* /*who*/) override
{
DoCast(me, SPELL_BURNING_FURY);
events.ScheduleEvent(EVENT_BURNING_FURY, 20000); /// @todo check timer
events.ScheduleEvent(EVENT_BURNING_BREATH, 15000); // 1st after 15sec, then every 45sec
events.ScheduleEvent(EVENT_METEOR_FISTS, 75000); // 1st after 75sec, then every 45sec
events.ScheduleEvent(EVENT_FLAME_CINDER, 30000); /// @todo check timer
_EnterCombat();
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_BURNING_FURY:
DoCast(me, SPELL_BURNING_FURY);
events.ScheduleEvent(EVENT_BURNING_FURY, 20000);
break;
case EVENT_BURNING_BREATH:
DoCast(me, SPELL_BURNING_BREATH);
events.ScheduleEvent(EVENT_BURNING_BREATH, 45000);
break;
case EVENT_METEOR_FISTS:
DoCast(me, SPELL_METEOR_FISTS);
events.ScheduleEvent(EVENT_METEOR_FISTS, 45000);
break;
case EVENT_FLAME_CINDER:
DoCast(me, SPELL_FLAME_CINDER_A);
events.ScheduleEvent(EVENT_FLAME_CINDER, 30000);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_koralonAI(creature);
}
};
/*######
## Npc Flame Warder
######*/
class npc_flame_warder : public CreatureScript
{
public:
npc_flame_warder() : CreatureScript("npc_flame_warder") { }
struct npc_flame_warderAI : public ScriptedAI
{
npc_flame_warderAI(Creature* creature) : ScriptedAI(creature)
{
}
void Reset() override
{
events.Reset();
}
void EnterCombat(Unit* /*who*/) override
{
DoZoneInCombat();
events.ScheduleEvent(EVENT_FW_LAVA_BIRST, 5000);
events.ScheduleEvent(EVENT_FW_METEOR_FISTS, 10000);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_FW_LAVA_BIRST:
DoCastVictim(SPELL_FW_LAVA_BIRST);
events.ScheduleEvent(EVENT_FW_LAVA_BIRST, 15000);
break;
case EVENT_FW_METEOR_FISTS:
DoCast(me, SPELL_FW_METEOR_FISTS);
events.ScheduleEvent(EVENT_FW_METEOR_FISTS, 20000);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
EventMap events;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_flame_warderAI(creature);
}
};
class spell_koralon_meteor_fists : public SpellScriptLoader
{
public:
spell_koralon_meteor_fists() : SpellScriptLoader("spell_koralon_meteor_fists") { }
class spell_koralon_meteor_fists_AuraScript : public AuraScript
{
PrepareAuraScript(spell_koralon_meteor_fists_AuraScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_METEOR_FISTS_DAMAGE))
return false;
return true;
}
void TriggerFists(AuraEffect const* aurEff, ProcEventInfo& eventInfo)
{
PreventDefaultAction();
GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_METEOR_FISTS_DAMAGE, true, NULL, aurEff);
}
void Register() override
{
OnEffectProc += AuraEffectProcFn(spell_koralon_meteor_fists_AuraScript::TriggerFists, EFFECT_0, SPELL_AURA_DUMMY);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_koralon_meteor_fists_AuraScript();
}
};
class spell_koralon_meteor_fists_damage : public SpellScriptLoader
{
public:
spell_koralon_meteor_fists_damage() : SpellScriptLoader("spell_koralon_meteor_fists_damage") { }
class spell_koralon_meteor_fists_damage_SpellScript : public SpellScript
{
PrepareSpellScript(spell_koralon_meteor_fists_damage_SpellScript);
public:
spell_koralon_meteor_fists_damage_SpellScript()
{
_chainTargets = 0;
}
private:
void FilterTargets(std::list<WorldObject*>& targets)
{
_chainTargets = targets.size();
}
void CalculateSplitDamage()
{
if (_chainTargets)
SetHitDamage(GetHitDamage() / (_chainTargets + 1));
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_koralon_meteor_fists_damage_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_TARGET_ENEMY);
OnHit += SpellHitFn(spell_koralon_meteor_fists_damage_SpellScript::CalculateSplitDamage);
}
private:
uint8 _chainTargets;
};
SpellScript* GetSpellScript() const override
{
return new spell_koralon_meteor_fists_damage_SpellScript();
}
};
class spell_flame_warder_meteor_fists : public SpellScriptLoader
{
public:
spell_flame_warder_meteor_fists() : SpellScriptLoader("spell_flame_warder_meteor_fists") { }
class spell_flame_warder_meteor_fists_AuraScript : public AuraScript
{
PrepareAuraScript(spell_flame_warder_meteor_fists_AuraScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
if (!sSpellMgr->GetSpellInfo(SPELL_FW_METEOR_FISTS_DAMAGE))
return false;
return true;
}
void TriggerFists(AuraEffect const* aurEff, ProcEventInfo& eventInfo)
{
PreventDefaultAction();
GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_FW_METEOR_FISTS_DAMAGE, true, NULL, aurEff);
}
void Register() override
{
OnEffectProc += AuraEffectProcFn(spell_flame_warder_meteor_fists_AuraScript::TriggerFists, EFFECT_0, SPELL_AURA_DUMMY);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_flame_warder_meteor_fists_AuraScript();
}
};
void AddSC_boss_koralon()
{
new boss_koralon();
new npc_flame_warder();
new spell_koralon_meteor_fists();
new spell_koralon_meteor_fists_damage();
new spell_flame_warder_meteor_fists();
}
| Java |
<?php
/**
* @version SEBLOD 3.x Core ~ $Id: version.php sebastienheraud $
* @package SEBLOD (App Builder & CCK) // SEBLOD nano (Form Builder)
* @url http://www.seblod.com
* @editor Octopoos - www.octopoos.com
* @copyright Copyright (C) 2009 - 2016 SEBLOD. All Rights Reserved.
* @license GNU General Public License version 2 or later; see _LICENSE.php
**/
defined( '_JEXEC' ) or die;
require_once JPATH_COMPONENT.'/helpers/helper_version.php';
// Model
class CCKModelVersion extends JCckBaseLegacyModelAdmin
{
protected $text_prefix = 'COM_CCK';
protected $vName = 'version';
// populateState
protected function populateState()
{
$app = JFactory::getApplication( 'administrator' );
$pk = $app->input->getInt( 'id', 0 );
$this->setState( 'version.id', $pk );
}
// getForm
public function getForm( $data = array(), $loadData = true )
{
$form = $this->loadForm( CCK_COM.'.'.$this->vName, $this->vName, array( 'control' => 'jform', 'load_data' => $loadData ) );
if ( empty( $form ) ) {
return false;
}
return $form;
}
// getItem
public function getItem( $pk = null )
{
if ( $item = parent::getItem( $pk ) ) {
//
}
return $item;
}
// getTable
public function getTable( $type = 'Version', $prefix = CCK_TABLE, $config = array() )
{
return JTable::getInstance( $type, $prefix, $config );
}
// loadFormData
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState( CCK_COM.'.edit.'.$this->vName.'.data', array() );
if ( empty( $data ) ) {
$data = $this->getItem();
}
return $data;
}
// -------- -------- -------- -------- -------- -------- -------- -------- // Store
// prepareData
protected function prepareData()
{
$data = JRequest::get( 'post' );
return $data;
}
// revert
public function revert( $pk, $type )
{
$db = $this->getDbo();
$table = $this->getTable();
if ( !$pk || !$type ) {
return false;
}
$table->load( $pk );
if ( JCck::getConfig_Param( 'version_revert', 1 ) == 1 ) {
Helper_Version::createVersion( $type, $table->e_id, JText::sprintf( 'COM_CCK_VERSION_AUTO_BEFORE_REVERT', $table->e_version ) );
}
$row = JTable::getInstance( $type, 'CCK_Table' );
$row->load( $table->e_id );
$core = JCckDev::fromJSON( $table->e_core );
if ( isset( $row->asset_id ) && $row->asset_id && isset( $core['rules'] ) ) {
JCckDatabase::execute( 'UPDATE #__assets SET rules = "'.$db->escape( $core['rules'] ).'" WHERE id = '.(int)$row->asset_id );
}
// More
if ( $type == 'search' ) {
$clients = array( 1=>'search', 2=>'filter', 3=>'list', 4=>'item', 5=>'order' );
} else {
$clients = array( 1=>'admin', 2=>'site', 3=>'intro', 4=>'content' );
}
foreach ( $clients as $i=>$client ) {
$name = 'e_more'.$i;
$this->_revert_more( $type, $client, $table->e_id, $table->{$name} );
}
// Override
if ( $row->version && ( $row->version != $table->e_version ) ) {
$core['version'] = ++$row->version;
}
$core['checked_out'] = 0;
$core['checked_out_time'] = '0000-00-00 00:00:00';
$row->bind( $core );
$row->check();
$row->store();
return true;
}
// _revert_more
public function _revert_more( $type, $client, $pk, $json )
{
$data = json_decode( $json );
$table = JCckTableBatch::getInstance( '#__cck_core_'.$type.'_field' );
$table->delete( $type.'id = '.$pk.' AND client = "'.$client.'"' );
$table->save( $data->fields, array(), array(), array( 'markup'=>'', 'restriction'=>'', 'restriction_options'=>'' ) );
$table = JCckTableBatch::getInstance( '#__cck_core_'.$type.'_position' );
$table->delete( $type.'id = '.$pk.' AND client = "'.$client.'"' );
$table->save( $data->positions );
}
}
?> | Java |
<!DOCTYPE html>
<!--[if IE 7]>
<html class="ie ie7" lang="en-US" prefix="og: http://ogp.me/ns#">
<![endif]-->
<!--[if IE 8]>
<html class="ie ie8" lang="en-US" prefix="og: http://ogp.me/ns#">
<![endif]-->
<!--[if !(IE 7) | !(IE 8) ]><!-->
<html lang="en-US" prefix="og: http://ogp.me/ns#">
<!--<![endif]-->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Page Not Found | Team California Baseball</title>
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="http://teamcalbaseball.com/xmlrpc.php">
<!--[if lt IE 9]>
<script src="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/js/html5.js"></script>
<![endif]-->
<!-- This site is optimized with the Yoast WordPress SEO plugin v1.4.24 - http://yoast.com/wordpress/seo/ -->
<meta property="og:locale" content="en_US" />
<meta property="og:type" content="website" />
<meta property="og:title" content="Page Not Found - Team California Baseball" />
<meta property="og:site_name" content="Team California Baseball" />
<!-- / Yoast WordPress SEO plugin. -->
<link rel="alternate" type="application/rss+xml" title="Team California Baseball » Feed" href="http://teamcalbaseball.com/feed/" />
<link rel="alternate" type="application/rss+xml" title="Team California Baseball » Comments Feed" href="http://teamcalbaseball.com/comments/feed/" />
<link rel='stylesheet' id='contact-form-7-css' href='http://teamcalbaseball.com/wp-content/plugins/contact-form-7/includes/css/styles.css?ver=3.7' type='text/css' media='all' />
<link rel='stylesheet' id='symple_shortcode_styles-css' href='http://teamcalbaseball.com/wp-content/plugins/symple-shortcodes/includes/css/symple_shortcodes_styles.css?ver=3.8.1' type='text/css' media='all' />
<link rel='stylesheet' id='twentyfourteen-lato-css' href='//fonts.googleapis.com/css?family=Lato%3A300%2C400%2C700%2C900%2C300italic%2C400italic%2C700italic' type='text/css' media='all' />
<link rel='stylesheet' id='genericons-css' href='http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/genericons/genericons.css?ver=3.0.2' type='text/css' media='all' />
<link rel='stylesheet' id='twentyfourteen-style-css' href='http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/style.css?ver=3.8.1' type='text/css' media='all' />
<!--[if lt IE 9]>
<link rel='stylesheet' id='twentyfourteen-ie-css' href='http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/css/ie.css?ver=20131205' type='text/css' media='all' />
<![endif]-->
<script type='text/javascript' src='http://teamcalbaseball.com/wp-includes/js/jquery/jquery.js?ver=1.10.2'></script>
<script type='text/javascript' src='http://teamcalbaseball.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1'></script>
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://teamcalbaseball.com/xmlrpc.php?rsd" />
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://teamcalbaseball.com/wp-includes/wlwmanifest.xml" />
<meta name="generator" content="WordPress 3.8.1" />
<style>span>iframe{
max-width:none !important;
}
</style>
<link rel="stylesheet" href="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/styles/fonts.css" type="text/css">
<link rel="stylesheet" href="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/styles/jquery.bxslider.css" type="text/css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
<link rel="stylesheet/less" href="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/less/tcb.less" type="text/css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<script src="http://cdn.kendostatic.com/2013.3.1119/js/kendo.web.min.js"></script>
<script src="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/js/less-1.6.1.min.js"></script>
<script src="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/js/jquery.bxslider.min.js"></script>
<script src="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/js/jquery.marquee.min.js"></script>
<script>
$(document).ready(function() {
$('.marquee').marquee({
duration: 10000,
pauseOnHover: true,
});
$('.sponsors').bxSlider({
minSlides: 4,
slideWidth: 210,
});
});
</script>
</head>
<body class="error404 masthead-fixed full-width footer-widgets">
<div class="container">
<header>
<div class="pageTitle">
<h1>Team California Baseball</h1>
</div>
<div id="headerImage"><img src="/wp-content/themes/teamcalbaseball/images/headerImage2.png"></div>
<div class="twitterLink"><a href="https://twitter.com/teamcalbaseball" target="_blank"><img src="/wp-content/themes/teamcalbaseball/images/twitterLink.png"></a></div>
</header>
<section id="ticker">
<div class="row">
<div class="col-lg-12">
<div class="marquee">
<div class="playerScroll">
<a href="http://www.cuieagles.com/sport/0/1.php" target="_blank"><p>MIKE MARTINEZ</p>
<p>2014 - EASTLAKE HS</p>
<p>PITCHER/1ST BASE</p>
<p>CONCORDIA UNIVERSITY</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.nevadawolfpack.com/sports/m-basebl/unv-m-basebl-body.html" target="_blank"><p>JORDAN PEARCE</p>
<p>2014 - EL CAMINO HS</p>
<p>3RD BASE</p>
<p>UNIVERSITY OF NEVADA RENO</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.baylorbears.com/sports/m-basebl/" target="_blank"><p>HUDSON PEARSON</p>
<p>2014 - EASTLAKE HS</p>
<p>PITCHER</p>
<p>BAYLOR UNIVERSITY</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.usfdons.com/index.aspx?path=baseball" target="_blank"><p>AARON PING</p>
<p>2014 - PATRICK HENRY HS</p>
<p>INFIELD</p>
<p>UNIVERSITY OF SAN FRANCISCO</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.oit.edu/athletics/mens-sports/baseball" target="_blank"><p>JOHN SCHULZ</p>
<p>2014 - CALVARY CHRISTIAN HS</p>
<p>PITCHER</p>
<p>OREGON INSTITUTE OF TECHNOLOGY</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.gomatadors.com/sports/m-basebl/index" target="_blank"><p>DREW WESTON</p>
<p>2014 - SAN MARCOS HS</p>
<p>PITCHER</p>
<p>CAL STATE NORTHRIDGE</p>
</div>
<div class="playerScroll">
<a href="http://goaztecs.cstv.com/sports/m-basebl/sdsu-m-basebl-body.html" target="_blank"><p>MATT WEZNIAK</p>
<p>2014 CARLSBAD HS</p>
<p>INFIELD</p>
<p>SAN DIEGO STATE UNIVERSITY</p>
</a>
</div> <div class="playerScroll">
<a href="http://www.hokiesports.com/baseball/players/anderson_nick.html" target="_blank"><p>NICK ANDERSON</p>
<p>2013 - CARLSBAD HS</p>
<p>OUTFIELD</p>
<p>VIRGINIA TECH</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.milb.com/milb/stats/stats.jsp?sid=milb&t=p_pbp&pid=641334" target="_blank"><p>MATT BALL</p>
<p>2013 - BONITA VISTA HS</p>
<p>PITCHER - LONG BEACH STATE</p>
<p>DRAFTED 10TH RD CHICAGO WHITE SOX (SIGNED)</p>
</a>
</div>
<div class="playerScroll">
<a href="http://goaztecs.cstv.com/sports/m-basebl/mtt/andrew_brown_865856.html" target="_blank"><p>ANDY BROWN</p>
<p>2013 - THE ROCK ACADEMY HS</p>
<p>SHORTSTOP</p>
<p>SAN DIEGO STATE UNIVERSITY</p></a>
</div>
<div class="playerScroll">
<a href="http://www.csusmcougars.com/roster.aspx?rp_id=2240" target="_blank"><p>NOAH BUCHANAN</p>
<p>2013 - GROSSMONT HS</p>
<p>OUTFIELD</p>
<p>CAL STATE SAN MARCOS</p>
</a>
</div>
<div class="playerScroll">
<a href="http://usdtoreros.cstv.com/sports/m-basebl/mtt/cj_burdick_881275.html" target="_blank"><p>CJ BURDICK</p>
<p>2013 - SERRA HS</p>
<p>PITCHER</p>
<p>UNIVERSITY OF SAN DIEGO</p>
</a>
</div>
<div class="playerScroll">
<a href="http://rccathletics.com/sports/bsb/2013-14/bios/devries_josh_gh7b" target="_blank"><p>JOSH DEVRIES</p>
<p>2013 - CAPISTRANO VALLEY HS</p>
<p>PITCHER</p>
<p>RIVERSIDE COMMUNITY COLLEGE</p></a>
</div>
<div class="playerScroll">
<a href="http://www.gostanford.com/ViewArticle.dbml?ATCLID=209370499&DB_OEM_ID=30600" target="_blank"><p>TOMMY EDMAN</p>
<p>2013 - LJCDS</p>
<p>SHORTSTOP</p>
<p>STANFORD UNIVERSITY</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.sgucavaliers.com/roster/11/3/1481.php" target="_blank"><p>DAVID FLORES</p>
<p>2013 - CALVARY CHRISTIAN HS</p>
<p>PITCHER</p>
<p>ST. GREGORY'S UNIVERSITY</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.plnusealions.com/roster.aspx?rp_id=1721&path=baseball" target="_blank"><p>RYAN GARCIA</p>
<p>2013 - EL CAMINO HS</p>
<p>1ST BASE</p>
<p>POINT LOMA NAZARENE UNIVERSITY</p>
</a>
</a>
</div>
<div class="playerScroll">
<a href="http://www.ucirvinesports.com/sports/m-basebl/2013-14/bios/guenette_alex_8xac" target="_blank"><p>ALEX GUENETTE</p>
<p>2013 - LJCDS</p>
<p>CATCHER</p>
<p>UC IRVINE</p>
</a>
</div>
<div class="playerScroll">
<a href="http://utahutes.cstv.com/sports/m-basebl/mtt/dustin_hughes_863278.html" target="_blank"><p>DUSTIN HUGHES</p>
<p>2013 - LJCDS</p>
<p>PITCHER</p>
<p>UNIVERSITY OF UTAH</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.plnusealions.com/roster.aspx?rp_id=1723" target="_blank"><p>MATT JERVIS</p>
<p>2013 - RANCHO BERNARDO HS</p>
<p>SHORTSTOP</p>
<p>POINT LOMA NAZARENE UNIVERSITY</p>
</a>
</div>
<div class="playerScroll">
<a href="https://www.gopoly.com/sports/bsb/2013-14/bios/lee_slater_sppl" target="_blank"><p>SLATER LEE</p>
<p>2013 - CARLSBAD HS</p>
<p>PITCHER</p>
<p>CAL POLY SAN LUIS OBISPO</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.cmsathletics.org/sports/bsb/2013-14/bios/l-esperance_james_b8gw" target="_blank"><p>JAMES L'ESPERANCE</p>
<p>2013 - EASTLAKE HS</p>
<p>OUTFIELD</p>
<p>CLAREMONT COLLEGE</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.centralaz.edu/home/athletics/teams/baseball.htm" target="_blank"><p>DEANDRE SIMPSON</p>
<p>2013 - THE ROCK ACADEMY HS</p>
<p>PITCHER</p>
<p>CENTRAL ARIZONA COMMUNITY COLLEGE</p>
</a>
</div>
<div class="playerScroll">
<a href="http://gocugo.com/roster.aspx?path=baseball&rp_id=1637" target="_blank"><p>ADAM TAYLOR</p>
<p>2013 - THE ROCK ACADEMY HS</p>
<p>UTILITY</p>
<p>CONCORDIA UNIVERSITY</p>
</a>
</div>
<div class="playerScroll">
<a href="https://www.masters.edu/athletics/menssports/baseball/roster.aspx" target="_blank"><p>CALEB WHITLEY</p>
<p>2013 - CALVARY CHRISTIAN HS</p>
<p>CATCHER</p>
<p>MASTERS COLLEGE</p>
</a>
</div>
<div class="playerScroll">
<a target="_blank" href="http://www.milb.com/milb/stats/stats.jsp?sid=milb&t=p_pbp&pid=622049"><p>SAM AYALA</p>
<p>2012 - LJCDS</p>
<p>CATCHER - UC SANTA BARBARA</p>
<p>DRAFTED 17TH RD CHICAGO WHITE SOX (SIGNED)</p></a>
</div>
<div class="playerScroll">
<a href="http://webapps.westmont.edu/cgi-bin/WebObjects/sportsData.woa/1/wo/DGQb83Mwxqlz2zv1jiywTw/0.1.2.1.18.24.2.0.0" target="_blank"><p>RUSSELL HARMENING</p>
<p>2012 - CALVARY CHRISTIAN HS</p>
<p>PITCHER</p>
<p>WESTMONT COLLEGE</p>
</a>
</div>
<div class="playerScroll">
<a href="https://www.masters.edu/athletics/menssports/baseball/roster.aspx" target="_blank"><p>COLLIN NYENHUIS</p>
<p>2012 - VISTA HS</p>
<p>3RD BASE</p>
<p>MASTERS COLLEGE</p>
</a>
</div>
<div class="playerScroll">
<a href="http://www.sdmesa.edu/students/athletics/sports/baseball/roster/" target="_blank"><p>KYLE HARRIS</p>
<p>2012 - CHRISTIAN HS</p>
<p>OUTFIELD</p>
<p>MESA COLLEGE</p>
</a>
</div>
</div>
<!-- <div class="popout">
<a class="button" href="#" onclick="javascript:void window.open('http://harrisonschaen.com/teamcalbaseball/ticker/','tickerWindow','width=990,height=110,toolbar=0,menubar=0,location=0,status=0,scrollbars=0,resizable=0,left=0,top=0');return false;">
Popout
</a>
</div>-->
</div>
</div>
</section>
<nav id="primary-navigation" class="site-navigation primary-navigation tcbNav" role="navigation">
<a class="screen-reader-text skip-link" href="#content">Skip to content</a>
<div class="menu-main-menu-container"><ul id="menu-main-menu" class="nav-menu tcbNav"><li id="menu-item-32" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-32"><a href="/">Home</a></li>
<li id="menu-item-252" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-252"><a href="#">About</a>
<ul class="sub-menu">
<li id="menu-item-205" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-205"><a href="http://teamcalbaseball.com/about/">Mission Statement</a></li>
<li id="menu-item-125" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-125"><a href="http://teamcalbaseball.com/about/staff/">Staff</a></li>
<li id="menu-item-101" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-101"><a href="http://teamcalbaseball.com/about/partners/">Partners</a></li>
<li id="menu-item-102" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-102"><a href="http://teamcalbaseball.com/about/resources/">Resources</a></li>
</ul>
</li>
<li id="menu-item-72" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-72"><a href="http://teamcalbaseball.com/alumni/">Alumni</a></li>
<li id="menu-item-74" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-74"><a href="http://teamcalbaseball.com/events/">Events</a>
<ul class="sub-menu">
<li id="menu-item-130" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-130"><a href="http://teamcalbaseball.com/events/tournaments/">Tournaments</a></li>
<li id="menu-item-129" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-129"><a href="http://teamcalbaseball.com/events/showcases/">Showcases</a></li>
<li id="menu-item-127" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-127"><a href="http://teamcalbaseball.com/events/college-team-camps/">College Team Camps</a></li>
<li id="menu-item-128" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-128"><a href="http://teamcalbaseball.com/events/perfect-game-so-cal-league/">Perfect Game Socal League</a></li>
</ul>
</li>
<li id="menu-item-132" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-132"><a href="http://teamcalbaseball.com/prospects/">Prospects</a>
<ul class="sub-menu">
<li id="menu-item-161" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-161"><a target="_blank" href="http://web1.ncaa.org/ECWR2/NCAA_EMS/NCAA_EMS.html#">Clearinghouse</a></li>
</ul>
</li>
<li id="menu-item-251" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-251"><a href="#">Teams</a>
<ul class="sub-menu">
<li id="menu-item-80" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-80"><a href="http://teamcalbaseball.com/teams/san-diego/">San Diego</a></li>
<li id="menu-item-79" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-79"><a href="http://teamcalbaseball.com/teams/orange-county/">Orange County</a></li>
<li id="menu-item-78" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-78"><a href="http://teamcalbaseball.com/teams/los-angeles/">Los Angeles</a></li>
<li id="menu-item-81" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-81"><a href="http://teamcalbaseball.com/teams/valley/">Valley</a></li>
</ul>
</li>
<li id="menu-item-131" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-131"><a href="http://teamcalbaseball.com/perfect-game-all-tournament-teams/">Perfect Game All-Tournament Teams</a></li>
<li id="menu-item-406" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-406"><a href="http://teamcalbaseball.com/schedule/">Schedule</a>
<ul class="sub-menu">
<li id="menu-item-408" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-408"><a href="http://teamcalbaseball.com/schedule/workout/">Workout</a></li>
<li id="menu-item-407" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-407"><a target="_blank" href="http://teamcalbaseball.com/schedule/game/">Game</a></li>
</ul>
</li>
<li id="menu-item-76" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-76"><a href="http://teamcalbaseball.com/team-store/">Team Store</a></li>
<li id="menu-item-73" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-73"><a href="http://teamcalbaseball.com/contact/">Contact</a></li>
</ul></div> </nav>
<article id="tcbPage">
<section>
<header class="page-header">
<h1 class="page-title">Not Found</h1>
</header>
<div class="page-content">
<p>It looks like nothing was found at this location. Maybe try a search?</p>
<form role="search" method="get" class="search-form" action="http://teamcalbaseball.com/">
<label>
<span class="screen-reader-text">Search for:</span>
<input type="search" class="search-field" placeholder="Search …" value="" name="s" title="Search for:" />
</label>
<input type="submit" class="search-submit" value="Search" />
</form> </div><!-- .page-content -->
</section><!-- #content -->
</article><!-- #primary -->
<footer id="colophon" class="site-footer container" role="contentinfo">
<div class="row">
<div class="col-lg-12">
<div class="foot pull-left"><img src="http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/images/tcblogo.png"></div>
<div class="foot pull-left"><h2><a href="/teamcalbaseball/">Home</h2><h2><a href="/teamcalbaseball/about">About</a></h2><ul><li><a href="/teamcalbaseball/about/">Mission</a></li><li><a href="/teamcalbaseball/about/staff">Staff</a></li><li><a href="/teamcalbaseball/about/partners">Partners</a></li><li><a href="/teamcalbaseball/about/resources">Resources</a></li></ul><h2><a href="/teamcalbaseball/alumni">Alumni</a></h2></div>
<div class="foot pull-left"><h2><a href="/teamcalbaseball/events/">Events</a></h2><h2>Teams</h2><ul><li><a href="/teamcalbaseball/teams/san-diego/">San Diego</a></li><li><a href="/teamcalbaseball/teams/orange-county/">Orange County</a></li><li><a href="/teamcalbaseball/teams/los-angeles/">Los Angeles</a></li><li><a href="/teamcalbaseball/teams/valley/">Valley</a></li></ul></div>
<div class="foot pull-left"><h2><a href="/teamcalbaseball/contact/">Contact</a></h2><ul><li><p>Team California Baseball</p><p>PO Box 131406<p>(760) 994-9114</p><p>teamcalbaseball.com</p><p class="designedBy"><a href="http://www.harrisonschaen.com" alt="Designed and Developed by Harrison Schaen">Site by Harrison Schaen</a></p></div>
</div>
</div>
</footer><!-- #colophon -->
</div><!-- end Container-->
<script type='text/javascript' src='http://teamcalbaseball.com/wp-content/plugins/contact-form-7/includes/js/jquery.form.min.js?ver=3.48.0-2013.12.28'></script>
<script type='text/javascript'>
/* <![CDATA[ */
var _wpcf7 = {"loaderUrl":"http:\/\/teamcalbaseball.com\/wp-content\/plugins\/contact-form-7\/images\/ajax-loader.gif","sending":"Sending ...","cached":"1"};
/* ]]> */
</script>
<script type='text/javascript' src='http://teamcalbaseball.com/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=3.7'></script>
<script type='text/javascript' src='http://teamcalbaseball.com/wp-includes/js/jquery/jquery.masonry.min.js?ver=2.1.05'></script>
<script type='text/javascript' src='http://teamcalbaseball.com/wp-content/themes/teamcalbaseball/js/functions.js?ver=20131209'></script>
</body>
</html>
<!-- Dynamic page generated in 0.129 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2014-02-22 09:52:28 -->
<!-- Compression = gzip -->
<!-- super cache --> | Java |
/*
How would you design a stack which, in addition to push and pop, also has a function min
which returns the minimum element? Push, pop and min should all operate in O(1) time.
*/
#include <stdio.h>
#include <map>
using namespace std;
#define N 500
typedef struct Stack
{
int top;
int min;
int value[N];
map<int, int> minTr;
}Stack;
void init(Stack& s)
{
s.top = 0;
s.min = 1 << 30;
}
void push(Stack& s, int val)
{
if(s.top >= N)
{
printf("overflow!\n");
return;
}
s.value[s.top] = val;
if(val < s.min)
{
s.minTr.insert(pair<int, int>(s.top, val));
s.min = val;
}
s.top++;
}
int pop(Stack& s)
{
if(s.top <= 0)
{
printf("Stack is empty!\n");
return 0;
}
s.top--;
int e = s.value[s.top];
if(e == s.min)
{
int ind = s.minTr.rbegin()->first;
if(ind == s.top)
{
s.minTr.erase(s.top);
if(s.minTr.empty())
s.min = 1 << 30;
else
s.min = s.minTr.rbegin()->second;
}
}
return e;
}
int minEle(Stack s)
{
if(s.top == 0)
{
printf("Stack is empty!\n");
return 0;
}
return s.min;
}
void createStack(Stack& s, int *a, int n)
{
for (int i = 0; i < 9; ++i)
{
push(s, a[i]);
//printf("%d %d\n", a[i], minEle(s));
}
}
void popEmpty(Stack s)
{
//printf("hello\n");
while(s.top > 0)
{
int e = pop(s);
printf("%d %d\n", e, s.min);
}
}
int main()
{
int a[9] = {3, 4, 5, 2, 6, 8, 1, 1, 4};
Stack s;
init(s);
createStack(s, a, 9);
popEmpty(s);
return 0;
} | Java |
/**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2022 MaNGOS <https://getmangos.eu>
*
* 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
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
#include "Common.h"
#include "Language.h"
#include "Database/DatabaseEnv.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "Opcodes.h"
#include "Log.h"
#include "ObjectMgr.h"
#include "SpellMgr.h"
#include "Player.h"
#include "GossipDef.h"
#include "UpdateMask.h"
#include "ScriptMgr.h"
#include "Creature.h"
#include "Pet.h"
#include "Guild.h"
#include "GuildMgr.h"
#include "Chat.h"
#include "Item.h"
#ifdef ENABLE_ELUNA
#include "LuaEngine.h"
#endif /* ENABLE_ELUNA */
enum StableResultCode
{
STABLE_ERR_MONEY = 0x01, // "you don't have enough money"
STABLE_ERR_STABLE = 0x06, // currently used in most fail cases
STABLE_SUCCESS_STABLE = 0x08, // stable success
STABLE_SUCCESS_UNSTABLE = 0x09, // unstable/swap success
STABLE_SUCCESS_BUY_SLOT = 0x0A, // buy slot success
STABLE_ERR_EXOTIC = 0x0C, // "you are unable to control exotic creatures"
};
void WorldSession::HandleTabardVendorActivateOpcode(WorldPacket& recv_data)
{
ObjectGuid guid;
recv_data >> guid;
Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TABARDDESIGNER);
if (!unit)
{
DEBUG_LOG("WORLD: HandleTabardVendorActivateOpcode - %s not found or you can't interact with him.", guid.GetString().c_str());
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
SendTabardVendorActivate(guid);
}
void WorldSession::SendTabardVendorActivate(ObjectGuid guid)
{
WorldPacket data(MSG_TABARDVENDOR_ACTIVATE, 8);
data << ObjectGuid(guid);
SendPacket(&data);
}
void WorldSession::HandleBankerActivateOpcode(WorldPacket& recv_data)
{
ObjectGuid guid;
DEBUG_LOG("WORLD: Received opcode CMSG_BANKER_ACTIVATE");
recv_data >> guid;
if (!CheckBanker(guid))
{
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
SendShowBank(guid);
}
void WorldSession::SendShowBank(ObjectGuid guid)
{
WorldPacket data(SMSG_SHOW_BANK, 8);
data << ObjectGuid(guid);
SendPacket(&data);
}
void WorldSession::HandleTrainerListOpcode(WorldPacket& recv_data)
{
ObjectGuid guid;
recv_data >> guid;
SendTrainerList(guid);
}
void WorldSession::SendTrainerList(ObjectGuid guid)
{
std::string str = GetMangosString(LANG_NPC_TAINER_HELLO);
SendTrainerList(guid, str);
}
static void SendTrainerSpellHelper(WorldPacket& data, TrainerSpell const* tSpell, TrainerSpellState state, float fDiscountMod, bool can_learn_primary_prof, uint32 reqLevel)
{
bool primary_prof_first_rank = sSpellMgr.IsPrimaryProfessionFirstRankSpell(tSpell->learnedSpell);
SpellChainNode const* chain_node = sSpellMgr.GetSpellChainNode(tSpell->learnedSpell);
data << uint32(tSpell->spell); // learned spell (or cast-spell in profession case)
data << uint8(state == TRAINER_SPELL_GREEN_DISABLED ? TRAINER_SPELL_GREEN : state);
data << uint32(floor(tSpell->spellCost * fDiscountMod));
data << uint32(primary_prof_first_rank && can_learn_primary_prof ? 1 : 0);
// primary prof. learn confirmation dialog
data << uint32(primary_prof_first_rank ? 1 : 0); // must be equal prev. field to have learn button in enabled state
data << uint8(reqLevel);
data << uint32(tSpell->reqSkill);
data << uint32(tSpell->reqSkillValue);
data << uint32(!tSpell->IsCastable() && chain_node ? (chain_node->prev ? chain_node->prev : chain_node->req) : 0);
data << uint32(!tSpell->IsCastable() && chain_node && chain_node->prev ? chain_node->req : 0);
data << uint32(0);
}
void WorldSession::SendTrainerList(ObjectGuid guid, const std::string& strTitle)
{
DEBUG_LOG("WORLD: SendTrainerList");
Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TRAINER);
if (!unit)
{
DEBUG_LOG("WORLD: SendTrainerList - %s not found or you can't interact with him.", guid.GetString().c_str());
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
// trainer list loaded at check;
if (!unit->IsTrainerOf(_player, true))
{
return;
}
CreatureInfo const* ci = unit->GetCreatureInfo();
if (!ci)
{
return;
}
TrainerSpellData const* cSpells = unit->GetTrainerSpells();
TrainerSpellData const* tSpells = unit->GetTrainerTemplateSpells();
if (!cSpells && !tSpells)
{
DEBUG_LOG("WORLD: SendTrainerList - Training spells not found for %s", guid.GetString().c_str());
return;
}
uint32 maxcount = (cSpells ? cSpells->spellList.size() : 0) + (tSpells ? tSpells->spellList.size() : 0);
uint32 trainer_type = cSpells && cSpells->trainerType ? cSpells->trainerType : (tSpells ? tSpells->trainerType : 0);
WorldPacket data(SMSG_TRAINER_LIST, 8 + 4 + 4 + maxcount * 38 + strTitle.size() + 1);
data << ObjectGuid(guid);
data << uint32(trainer_type);
size_t count_pos = data.wpos();
data << uint32(maxcount);
// reputation discount
float fDiscountMod = _player->GetReputationPriceDiscount(unit);
bool can_learn_primary_prof = GetPlayer()->GetFreePrimaryProfessionPoints() > 0;
uint32 count = 0;
if (cSpells)
{
for (TrainerSpellMap::const_iterator itr = cSpells->spellList.begin(); itr != cSpells->spellList.end(); ++itr)
{
TrainerSpell const* tSpell = &itr->second;
uint32 reqLevel = 0;
if (!_player->IsSpellFitByClassAndRace(tSpell->learnedSpell, &reqLevel))
{
continue;
}
reqLevel = tSpell->isProvidedReqLevel ? tSpell->reqLevel : std::max(reqLevel, tSpell->reqLevel);
TrainerSpellState state = _player->GetTrainerSpellState(tSpell, reqLevel);
SendTrainerSpellHelper(data, tSpell, state, fDiscountMod, can_learn_primary_prof, reqLevel);
++count;
}
}
if (tSpells)
{
for (TrainerSpellMap::const_iterator itr = tSpells->spellList.begin(); itr != tSpells->spellList.end(); ++itr)
{
TrainerSpell const* tSpell = &itr->second;
uint32 reqLevel = 0;
if (!_player->IsSpellFitByClassAndRace(tSpell->learnedSpell, &reqLevel))
{
continue;
}
reqLevel = tSpell->isProvidedReqLevel ? tSpell->reqLevel : std::max(reqLevel, tSpell->reqLevel);
TrainerSpellState state = _player->GetTrainerSpellState(tSpell, reqLevel);
SendTrainerSpellHelper(data, tSpell, state, fDiscountMod, can_learn_primary_prof, reqLevel);
++count;
}
}
data << strTitle;
data.put<uint32>(count_pos, count);
SendPacket(&data);
}
void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket& recv_data)
{
ObjectGuid guid;
uint32 spellId = 0;
recv_data >> guid >> spellId;
DEBUG_LOG("WORLD: Received opcode CMSG_TRAINER_BUY_SPELL Trainer: %s, learn spell id is: %u", guid.GetString().c_str(), spellId);
Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TRAINER);
if (!unit)
{
DEBUG_LOG("WORLD: HandleTrainerBuySpellOpcode - %s not found or you can't interact with him.", guid.GetString().c_str());
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
if (!unit->IsTrainerOf(_player, true))
{
return;
}
// check present spell in trainer spell list
TrainerSpellData const* cSpells = unit->GetTrainerSpells();
TrainerSpellData const* tSpells = unit->GetTrainerTemplateSpells();
if (!cSpells && !tSpells)
{
return;
}
// Try find spell in npc_trainer
TrainerSpell const* trainer_spell = cSpells ? cSpells->Find(spellId) : NULL;
// Not found, try find in npc_trainer_template
if (!trainer_spell && tSpells)
{
trainer_spell = tSpells->Find(spellId);
}
// Not found anywhere, cheating?
if (!trainer_spell)
{
return;
}
// can't be learn, cheat? Or double learn with lags...
uint32 reqLevel = 0;
if (!_player->IsSpellFitByClassAndRace(trainer_spell->learnedSpell, &reqLevel))
{
return;
}
reqLevel = trainer_spell->isProvidedReqLevel ? trainer_spell->reqLevel : std::max(reqLevel, trainer_spell->reqLevel);
if (_player->GetTrainerSpellState(trainer_spell, reqLevel) != TRAINER_SPELL_GREEN)
{
return;
}
// apply reputation discount
uint32 nSpellCost = uint32(floor(trainer_spell->spellCost * _player->GetReputationPriceDiscount(unit)));
// check money requirement
if (_player->GetMoney() < nSpellCost)
{
return;
}
_player->ModifyMoney(-int32(nSpellCost));
SendPlaySpellVisual(guid, 0xB3); // visual effect on trainer
WorldPacket data(SMSG_PLAY_SPELL_IMPACT, 8 + 4); // visual effect on player
data << _player->GetObjectGuid();
data << uint32(0x016A); // index from SpellVisualKit.dbc
SendPacket(&data);
// learn explicitly or cast explicitly
// TODO - Are these spells really cast correctly this way?
if (trainer_spell->IsCastable())
{
_player->CastSpell(_player, trainer_spell->spell, true);
}
else
{
_player->learnSpell(spellId, false);
}
data.Initialize(SMSG_TRAINER_BUY_SUCCEEDED, 12);
data << ObjectGuid(guid);
data << uint32(spellId); // should be same as in packet from client
SendPacket(&data);
}
void WorldSession::HandleGossipHelloOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_GOSSIP_HELLO");
ObjectGuid guid;
recv_data >> guid;
Creature* pCreature = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_NONE);
if (!pCreature)
{
DEBUG_LOG("WORLD: HandleGossipHelloOpcode - %s not found or you can't interact with him.", guid.GetString().c_str());
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
pCreature->StopMoving();
if (pCreature->IsSpiritGuide())
{
pCreature->SendAreaSpiritHealerQueryOpcode(_player);
}
if (!sScriptMgr.OnGossipHello(_player, pCreature))
{
_player->PrepareGossipMenu(pCreature, pCreature->GetCreatureInfo()->GossipMenuId);
_player->SendPreparedGossip(pCreature);
}
}
void WorldSession::HandleGossipSelectOptionOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: CMSG_GOSSIP_SELECT_OPTION");
uint32 gossipListId;
uint32 menuId;
ObjectGuid guid;
std::string code;
recv_data >> guid >> menuId >> gossipListId;
if (_player->PlayerTalkClass->GossipOptionCoded(gossipListId))
{
recv_data >> code;
DEBUG_LOG("Gossip code: %s", code.c_str());
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
uint32 sender = _player->PlayerTalkClass->GossipOptionSender(gossipListId);
uint32 action = _player->PlayerTalkClass->GossipOptionAction(gossipListId);
if (guid.IsAnyTypeCreature())
{
Creature* pCreature = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_NONE);
if (!pCreature)
{
DEBUG_LOG("WORLD: HandleGossipSelectOptionOpcode - %s not found or you can't interact with it.", guid.GetString().c_str());
return;
}
if (!sScriptMgr.OnGossipSelect(_player, pCreature, sender, action, code.empty() ? NULL : code.c_str()))
{
_player->OnGossipSelect(pCreature, gossipListId, menuId);
}
}
else if (guid.IsGameObject())
{
GameObject* pGo = GetPlayer()->GetGameObjectIfCanInteractWith(guid);
if (!pGo)
{
DEBUG_LOG("WORLD: HandleGossipSelectOptionOpcode - %s not found or you can't interact with it.", guid.GetString().c_str());
return;
}
if (!sScriptMgr.OnGossipSelect(_player, pGo, sender, action, code.empty() ? NULL : code.c_str()))
{
_player->OnGossipSelect(pGo, gossipListId, menuId);
}
}
else if (guid.IsItem())
{
Item* item = GetPlayer()->GetItemByGuid(guid);
if (!item)
{
DEBUG_LOG("WORLD: HandleGossipSelectOptionOpcode - %s not found or you can't interact with it.", guid.GetString().c_str());
return;
}
if (!sScriptMgr.OnGossipSelect(_player, item, sender, action, code.empty() ? NULL : code.c_str()))
{
DEBUG_LOG("WORLD: HandleGossipSelectOptionOpcode - item script for %s not found or you can't interact with it.", item->GetProto()->Name1);
return;
}
// Used by Eluna
#ifdef ENABLE_ELUNA
sEluna->HandleGossipSelectOption(GetPlayer(), item, GetPlayer()->PlayerTalkClass->GossipOptionSender(gossipListId), GetPlayer()->PlayerTalkClass->GossipOptionAction(gossipListId), code);
#endif /* ENABLE_ELUNA */
}
else if (guid.IsPlayer())
{
if (GetPlayer()->GetGUIDLow() != guid || GetPlayer()->PlayerTalkClass->GetGossipMenu().GetMenuId() != menuId)
{
DEBUG_LOG("WORLD: HandleGossipSelectOptionOpcode - %s not found or you can't interact with it.", guid.GetString().c_str());
return;
}
// Used by Eluna
#ifdef ENABLE_ELUNA
sEluna->HandleGossipSelectOption(GetPlayer(), menuId, GetPlayer()->PlayerTalkClass->GossipOptionSender(gossipListId), GetPlayer()->PlayerTalkClass->GossipOptionAction(gossipListId), code);
#endif /* ENABLE_ELUNA */
}
}
void WorldSession::HandleSpiritHealerActivateOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: CMSG_SPIRIT_HEALER_ACTIVATE");
ObjectGuid guid;
recv_data >> guid;
Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_SPIRITHEALER);
if (!unit)
{
DEBUG_LOG("WORLD: HandleSpiritHealerActivateOpcode - %s not found or you can't interact with him.", guid.GetString().c_str());
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
SendSpiritResurrect();
}
void WorldSession::SendSpiritResurrect()
{
_player->ResurrectPlayer(0.5f, true);
_player->DurabilityLossAll(0.25f, true);
// get corpse nearest graveyard
WorldSafeLocsEntry const* corpseGrave = NULL;
Corpse* corpse = _player->GetCorpse();
if (corpse)
corpseGrave = sObjectMgr.GetClosestGraveYard(
corpse->GetPositionX(), corpse->GetPositionY(), corpse->GetPositionZ(), corpse->GetMapId(), _player->GetTeam());
// now can spawn bones
_player->SpawnCorpseBones();
// teleport to nearest from corpse graveyard, if different from nearest to player ghost
if (corpseGrave)
{
WorldSafeLocsEntry const* ghostGrave = sObjectMgr.GetClosestGraveYard(
_player->GetPositionX(), _player->GetPositionY(), _player->GetPositionZ(), _player->GetMapId(), _player->GetTeam());
if (corpseGrave != ghostGrave)
{
_player->TeleportTo(corpseGrave->map_id, corpseGrave->x, corpseGrave->y, corpseGrave->z, _player->GetOrientation());
}
// or update at original position
else
{
_player->GetCamera().UpdateVisibilityForOwner();
_player->UpdateObjectVisibility();
}
}
// or update at original position
else
{
_player->GetCamera().UpdateVisibilityForOwner();
_player->UpdateObjectVisibility();
}
}
void WorldSession::HandleBinderActivateOpcode(WorldPacket& recv_data)
{
ObjectGuid npcGuid;
recv_data >> npcGuid;
if (!GetPlayer()->IsInWorld() || !GetPlayer()->IsAlive())
{
return;
}
Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(npcGuid, UNIT_NPC_FLAG_INNKEEPER);
if (!unit)
{
DEBUG_LOG("WORLD: HandleBinderActivateOpcode - %s not found or you can't interact with him.", npcGuid.GetString().c_str());
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
SendBindPoint(unit);
}
void WorldSession::SendBindPoint(Creature* npc)
{
// prevent set homebind to instances in any case
if (GetPlayer()->GetMap()->Instanceable())
{
return;
}
// send spell for bind 3286 bind magic
npc->CastSpell(_player, 3286, true); // Bind
WorldPacket data(SMSG_TRAINER_BUY_SUCCEEDED, (8 + 4));
data << npc->GetObjectGuid();
data << uint32(3286); // Bind
SendPacket(&data);
_player->PlayerTalkClass->CloseGossip();
}
void WorldSession::HandleListStabledPetsOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Recv MSG_LIST_STABLED_PETS");
ObjectGuid npcGUID;
recv_data >> npcGUID;
if (!CheckStableMaster(npcGUID))
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
SendStablePet(npcGUID);
}
void WorldSession::SendStablePet(ObjectGuid guid)
{
DEBUG_LOG("WORLD: Recv MSG_LIST_STABLED_PETS Send.");
WorldPacket data(MSG_LIST_STABLED_PETS, 200); // guess size
data << guid;
Pet* pet = _player->GetPet();
size_t wpos = data.wpos();
data << uint8(0); // place holder for slot show number
data << uint8(GetPlayer()->m_stableSlots);
uint8 num = 0; // counter for place holder
// not let move dead pet in slot
if (pet && pet->IsAlive() && pet->getPetType() == HUNTER_PET)
{
data << uint32(pet->GetCharmInfo()->GetPetNumber());
data << uint32(pet->GetEntry());
data << uint32(pet->getLevel());
data << pet->GetName(); // petname
data << uint8(1); // 1 = current, 2/3 = in stable (any from 4,5,... create problems with proper show)
++num;
}
// 0 1 2 3 4
QueryResult* result = CharacterDatabase.PQuery("SELECT `owner`, `id`, `entry`, `level`, `name` FROM `character_pet` WHERE `owner` = '%u' AND `slot` >= '%u' AND `slot` <= '%u' ORDER BY `slot`",
_player->GetGUIDLow(), PET_SAVE_FIRST_STABLE_SLOT, PET_SAVE_LAST_STABLE_SLOT);
if (result)
{
do
{
Field* fields = result->Fetch();
data << uint32(fields[1].GetUInt32()); // petnumber
data << uint32(fields[2].GetUInt32()); // creature entry
data << uint32(fields[3].GetUInt32()); // level
data << fields[4].GetString(); // name
data << uint8(2); // 1 = current, 2/3 = in stable (any from 4,5,... create problems with proper show)
++num;
}
while (result->NextRow());
delete result;
}
data.put<uint8>(wpos, num); // set real data to placeholder
SendPacket(&data);
}
void WorldSession::SendStableResult(uint8 res)
{
WorldPacket data(SMSG_STABLE_RESULT, 1);
data << uint8(res);
SendPacket(&data);
}
bool WorldSession::CheckStableMaster(ObjectGuid guid)
{
// spell case or GM
if (guid == GetPlayer()->GetObjectGuid())
{
// command case will return only if player have real access to command
if (!GetPlayer()->HasAuraType(SPELL_AURA_OPEN_STABLE) && !ChatHandler(GetPlayer()).FindCommand("stable"))
{
DEBUG_LOG("%s attempt open stable in cheating way.", guid.GetString().c_str());
return false;
}
}
// stable master case
else
{
if (!GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_STABLEMASTER))
{
DEBUG_LOG("Stablemaster %s not found or you can't interact with him.", guid.GetString().c_str());
return false;
}
}
return true;
}
void WorldSession::HandleStablePet(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Recv CMSG_STABLE_PET");
ObjectGuid npcGUID;
recv_data >> npcGUID;
if (!GetPlayer()->IsAlive())
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
if (!CheckStableMaster(npcGUID))
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
Pet* pet = _player->GetPet();
// can't place in stable dead pet
if (!pet || !pet->IsAlive() || pet->getPetType() != HUNTER_PET)
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
uint32 free_slot = 1;
QueryResult* result = CharacterDatabase.PQuery("SELECT `owner`,`slot`,`id` FROM `character_pet` WHERE `owner` = '%u' AND `slot` >= '%u' AND `slot` <= '%u' ORDER BY `slot`",
_player->GetGUIDLow(), PET_SAVE_FIRST_STABLE_SLOT, PET_SAVE_LAST_STABLE_SLOT);
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 slot = fields[1].GetUInt32();
// slots ordered in query, and if not equal then free
if (slot != free_slot)
{
break;
}
// this slot not free, skip
++free_slot;
}
while (result->NextRow());
delete result;
}
if (free_slot > 0 && free_slot <= GetPlayer()->m_stableSlots)
{
pet->Unsummon(PetSaveMode(free_slot), _player);
SendStableResult(STABLE_SUCCESS_STABLE);
}
else
{
SendStableResult(STABLE_ERR_STABLE);
}
}
void WorldSession::HandleUnstablePet(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Recv CMSG_UNSTABLE_PET.");
ObjectGuid npcGUID;
uint32 petnumber;
recv_data >> npcGUID >> petnumber;
if (!CheckStableMaster(npcGUID))
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
uint32 creature_id = 0;
{
QueryResult* result = CharacterDatabase.PQuery("SELECT `entry` FROM `character_pet` WHERE `owner` = '%u' AND `id` = '%u' AND `slot` >='%u' AND `slot` <= '%u'",
_player->GetGUIDLow(), petnumber, PET_SAVE_FIRST_STABLE_SLOT, PET_SAVE_LAST_STABLE_SLOT);
if (result)
{
Field* fields = result->Fetch();
creature_id = fields[0].GetUInt32();
delete result;
}
}
if (!creature_id)
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
CreatureInfo const* creatureInfo = ObjectMgr::GetCreatureTemplate(creature_id);
if (!creatureInfo || !creatureInfo->isTameable(_player->CanTameExoticPets()))
{
// if problem in exotic pet
if (creatureInfo && creatureInfo->isTameable(true))
{
SendStableResult(STABLE_ERR_EXOTIC);
}
else
{
SendStableResult(STABLE_ERR_STABLE);
}
return;
}
Pet* pet = _player->GetPet();
if (pet && pet->IsAlive())
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
// delete dead pet
if (pet)
{
pet->Unsummon(PET_SAVE_AS_DELETED, _player);
}
Pet* newpet = new Pet(HUNTER_PET);
if (!newpet->LoadPetFromDB(_player, creature_id, petnumber))
{
delete newpet;
newpet = NULL;
SendStableResult(STABLE_ERR_STABLE);
return;
}
SendStableResult(STABLE_SUCCESS_UNSTABLE);
}
void WorldSession::HandleBuyStableSlot(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Recv CMSG_BUY_STABLE_SLOT.");
ObjectGuid npcGUID;
recv_data >> npcGUID;
if (!CheckStableMaster(npcGUID))
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
if (GetPlayer()->m_stableSlots < MAX_PET_STABLES)
{
StableSlotPricesEntry const* SlotPrice = sStableSlotPricesStore.LookupEntry(GetPlayer()->m_stableSlots + 1);
if (_player->GetMoney() >= SlotPrice->Price)
{
++GetPlayer()->m_stableSlots;
_player->ModifyMoney(-int32(SlotPrice->Price));
SendStableResult(STABLE_SUCCESS_BUY_SLOT);
}
else
{
SendStableResult(STABLE_ERR_MONEY);
}
}
else
{
SendStableResult(STABLE_ERR_STABLE);
}
}
void WorldSession::HandleStableRevivePet(WorldPacket& /* recv_data */)
{
DEBUG_LOG("HandleStableRevivePet: Not implemented");
}
void WorldSession::HandleStableSwapPet(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Recv CMSG_STABLE_SWAP_PET.");
ObjectGuid npcGUID;
uint32 pet_number;
recv_data >> npcGUID >> pet_number;
if (!CheckStableMaster(npcGUID))
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
Pet* pet = _player->GetPet();
if (!pet || pet->getPetType() != HUNTER_PET)
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
// find swapped pet slot in stable
QueryResult* result = CharacterDatabase.PQuery("SELECT `slot`,`entry` FROM `character_pet` WHERE `owner` = '%u' AND `id` = '%u'",
_player->GetGUIDLow(), pet_number);
if (!result)
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
Field* fields = result->Fetch();
uint32 slot = fields[0].GetUInt32();
uint32 creature_id = fields[1].GetUInt32();
delete result;
if (!creature_id)
{
SendStableResult(STABLE_ERR_STABLE);
return;
}
CreatureInfo const* creatureInfo = ObjectMgr::GetCreatureTemplate(creature_id);
if (!creatureInfo || !creatureInfo->isTameable(_player->CanTameExoticPets()))
{
// if problem in exotic pet
if (creatureInfo && creatureInfo->isTameable(true))
{
SendStableResult(STABLE_ERR_EXOTIC);
}
else
{
SendStableResult(STABLE_ERR_STABLE);
}
return;
}
// move alive pet to slot or delete dead pet
pet->Unsummon(pet->IsAlive() ? PetSaveMode(slot) : PET_SAVE_AS_DELETED, _player);
// summon unstabled pet
Pet* newpet = new Pet;
if (!newpet->LoadPetFromDB(_player, creature_id, pet_number))
{
delete newpet;
SendStableResult(STABLE_ERR_STABLE);
}
else
{
SendStableResult(STABLE_SUCCESS_UNSTABLE);
}
}
void WorldSession::HandleRepairItemOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: CMSG_REPAIR_ITEM");
ObjectGuid npcGuid;
ObjectGuid itemGuid;
uint8 guildBank; // new in 2.3.2, bool that means from guild bank money
recv_data >> npcGuid >> itemGuid >> guildBank;
Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(npcGuid, UNIT_NPC_FLAG_REPAIR);
if (!unit)
{
DEBUG_LOG("WORLD: HandleRepairItemOpcode - %s not found or you can't interact with him.", npcGuid.GetString().c_str());
return;
}
// remove fake death
if (GetPlayer()->hasUnitState(UNIT_STAT_DIED))
{
GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
}
// reputation discount
float discountMod = _player->GetReputationPriceDiscount(unit);
uint32 TotalCost = 0;
if (itemGuid)
{
DEBUG_LOG("ITEM: %s repair of %s", npcGuid.GetString().c_str(), itemGuid.GetString().c_str());
Item* item = _player->GetItemByGuid(itemGuid);
if (item)
{
TotalCost = _player->DurabilityRepair(item->GetPos(), true, discountMod, (guildBank > 0));
}
}
else
{
DEBUG_LOG("ITEM: %s repair all items", npcGuid.GetString().c_str());
TotalCost = _player->DurabilityRepairAll(true, discountMod, (guildBank > 0));
}
if (guildBank)
{
uint32 GuildId = _player->GetGuildId();
if (!GuildId)
{
return;
}
Guild* pGuild = sGuildMgr.GetGuildById(GuildId);
if (!pGuild)
{
return;
}
pGuild->LogBankEvent(GUILD_BANK_LOG_REPAIR_MONEY, 0, _player->GetGUIDLow(), TotalCost);
pGuild->SendMoneyInfo(this, _player->GetGUIDLow());
}
}
| Java |
<?php
/* TwigBundle:Exception:exception_full.html.twig */
class __TwigTemplate_12d6106874fca48a5e6b4ba3ab89b6fc520d1b724c37c5efb25ee5ce99e9e8da extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("TwigBundle::layout.html.twig");
$this->blocks = array(
'head' => array($this, 'block_head'),
'title' => array($this, 'block_title'),
'body' => array($this, 'block_body'),
);
}
protected function doGetParent(array $context)
{
return "TwigBundle::layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_head($context, array $blocks = array())
{
// line 4
echo " <link href=\"";
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/framework/css/exception.css"), "html", null, true);
echo "\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />
";
}
// line 7
public function block_title($context, array $blocks = array())
{
// line 8
echo " ";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "message"), "html", null, true);
echo " (";
echo twig_escape_filter($this->env, (isset($context["status_code"]) ? $context["status_code"] : $this->getContext($context, "status_code")), "html", null, true);
echo " ";
echo twig_escape_filter($this->env, (isset($context["status_text"]) ? $context["status_text"] : $this->getContext($context, "status_text")), "html", null, true);
echo ")
";
}
// line 11
public function block_body($context, array $blocks = array())
{
// line 12
echo " ";
$this->env->loadTemplate("TwigBundle:Exception:exception.html.twig")->display($context);
}
public function getTemplateName()
{
return "TwigBundle:Exception:exception_full.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 57 => 12, 54 => 11, 43 => 8, 40 => 7, 33 => 4, 30 => 3,);
}
}
| Java |
local assets=
{
Asset("ANIM", "anim/gold_nugget.zip"),
}
local function shine(inst)
inst.task = nil
inst.AnimState:PlayAnimation("sparkle")
inst.AnimState:PushAnimation("idle")
inst.task = inst:DoTaskInTime(4+math.random()*5, function() shine(inst) end)
end
local function fn(Sim)
local inst = CreateEntity()
inst.entity:AddTransform()
inst.entity:AddAnimState()
inst.entity:AddSoundEmitter()
inst.entity:AddPhysics()
MakeInventoryPhysics(inst)
inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
inst.AnimState:SetBank("goldnugget")
inst.AnimState:SetBuild("gold_nugget")
inst.AnimState:PlayAnimation("idle")
inst:AddComponent("edible")
inst.components.edible.foodtype = "ELEMENTAL"
inst.components.edible.hungervalue = 2
inst:AddComponent("tradable")
inst:AddComponent("inspectable")
inst:AddComponent("stackable")
inst:AddComponent("inventoryitem")
inst:AddComponent("bait")
inst:AddTag("molebait")
shine(inst)
return inst
end
return Prefab( "common/inventory/goldnugget", fn, assets)
| Java |
module.exports = {
dist: {
options: {
plugin_slug: 'simple-user-adding',
svn_user: 'wearerequired',
build_dir: 'release/svn/',
assets_dir: 'assets/'
}
}
};
| Java |
/*
* This file is part of the coreboot project.
*
* Copyright (C) 2008 VIA Technologies, Inc.
* (Written by Aaron Lwe <aaron.lwe@gmail.com> for VIA)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <stdint.h>
#include <device/pci_def.h>
#include <device/pci_ids.h>
#include <arch/io.h>
#include <device/pnp_def.h>
#include <console/console.h>
#include <lib.h>
#include <northbridge/via/cn700/raminit.h>
#include <cpu/x86/bist.h>
#include <delay.h>
#include "southbridge/via/vt8237r/early_smbus.c"
#include "southbridge/via/vt8237r/early_serial.c"
#include <spd.h>
static inline int spd_read_byte(unsigned device, unsigned address)
{
return smbus_read_byte(device, address);
}
#include "northbridge/via/cn700/raminit.c"
static void enable_mainboard_devices(void)
{
device_t dev;
dev = pci_locate_device(PCI_ID(PCI_VENDOR_ID_VIA,
PCI_DEVICE_ID_VIA_VT8237R_LPC), 0);
if (dev == PCI_DEV_INVALID)
die("Southbridge not found!!!\n");
/* bit=0 means enable function (per CX700 datasheet)
* 5 16.1 USB 2
* 4 16.0 USB 1
* 3 15.0 SATA and PATA
* 2 16.2 USB 3
* 1 16.4 USB EHCI
*/
pci_write_config8(dev, 0x50, 0x80);
/* bit=1 means enable internal function (per CX700 datasheet)
* 3 Internal RTC
* 2 Internal PS2 Mouse
* 1 Internal KBC Configuration
* 0 Internal Keyboard Controller
*/
pci_write_config8(dev, 0x51, 0x1d);
}
static const struct mem_controller ctrl = {
.d0f0 = 0x0000,
.d0f2 = 0x2000,
.d0f3 = 0x3000,
.d0f4 = 0x4000,
.d0f7 = 0x7000,
.d1f0 = 0x8000,
.channel0 = { DIMM0 },
};
#include <cpu/intel/romstage.h>
void main(unsigned long bist)
{
/* Enable multifunction for northbridge. */
pci_write_config8(ctrl.d0f0, 0x4f, 0x01);
enable_vt8237r_serial();
console_init();
enable_smbus();
smbus_fixup(&ctrl);
report_bist_failure(bist);
enable_mainboard_devices();
ddr_ram_setup(&ctrl);
}
| Java |
<?php
class ezxpdfpreview
{
function ezxpdfpreview()
{
$this->Operators = array( 'pdfpreview' );
}
/*!
\return an array with the template operator name.
*/
function operatorList()
{
return $this->Operators;
}
/*!
\return true to tell the template engine that the parameter list exists per operator type,
this is needed for operator classes that have multiple operators.
*/
function namedParameterPerOperator()
{
return true;
}
/*!
See eZTemplateOperator::namedParameterList
*/
function namedParameterList()
{
return array( 'pdfpreview' => array(
'width' => array( 'type' => 'integer', 'required' => true ),
'height' => array( 'type' => 'integer', 'required' => true ),
'attribute_id' => array( 'type' => 'integer', 'required' => true),
'attribute_version' => array( 'type' => 'integer', 'required' => true),
'page' => array( 'type' => 'integer', 'required' => false, 'default' => 1)
)
);
}
/*!
Executes the PHP function for the operator cleanup and modifies \a $operatorValue.
*/
function modify( &$tpl, &$operatorName, &$operatorParameters, &$rootNamespace, &$currentNamespace, &$operatorValue, &$namedParameters )
{
$ini = eZINI::instance();
$contentId = $operatorValue;
$width = (int)$namedParameters['width'];
$height = (int)$namedParameters['height'];
$container = ezpKernel::instance()->getServiceContainer();
$pdfPreview = $container->get( 'xrow_pdf_preview' );
$operatorValue = $pdfPreview->preview($contentId, $width, $height);
}
function previewRetrieve( $file, $mtime, $args )
{
//do nothing
}
function previewGenerate( $file, $args )
{
extract( $args );
$pdffile->fetch(true);
$cmd = "convert " . eZSys::escapeShellArgument( $pdf_file_path . "[" . $page . "]" ) . " " . " -alpha remove -resize " . eZSys::escapeShellArgument( $width . "x" . $height ) . " " . eZSys::escapeShellArgument( $cacheImageFilePath );
$out = shell_exec( $cmd );
$fileHandler = eZClusterFileHandler::instance();
$fileHandler->fileStore( $cacheImageFilePath, 'pdfpreview', false );
eZDebug::writeDebug( $cmd, "pdfpreview" );
if ( $out )
{
eZDebug::writeDebug( $out, "pdfpreview" );
}
//return values for the storecache function
return array( 'content' => $cacheImageFilePath,
'scope' => 'pdfpreview',
'store' => true );
}
}
?>
| Java |
return {
amazons_woodcutter = {},
}
| Java |
<?php
/*
* Copyright (C) 2015 andi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace ErsBase\View\Helper;
use Zend\View\Helper\AbstractHelper;
#use Zend\View\HelperPluginManager as ServiceManager;
use Zend\Session\Container;
class Session extends AbstractHelper {
#protected $serviceManager;
/*public function __construct(ServiceManager $serviceManager) {
$this->serviceManager = $serviceManager;
}*/
public function __invoke() {
$container = new Container('ers');
return $container;
}
} | Java |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2018-2020 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2020 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 Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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.features.kafka.producer;
import java.io.IOException;
import java.time.Duration;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.function.Consumer;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.errors.TimeoutException;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.opennms.core.ipc.common.kafka.Utils;
import org.opennms.features.kafka.producer.datasync.KafkaAlarmDataSync;
import org.opennms.features.kafka.producer.model.OpennmsModelProtos;
import org.opennms.features.situationfeedback.api.AlarmFeedback;
import org.opennms.features.situationfeedback.api.AlarmFeedbackListener;
import org.opennms.netmgt.alarmd.api.AlarmCallbackStateTracker;
import org.opennms.netmgt.alarmd.api.AlarmLifecycleListener;
import org.opennms.netmgt.events.api.EventListener;
import org.opennms.netmgt.events.api.EventSubscriptionService;
import org.opennms.netmgt.events.api.ThreadAwareEventListener;
import org.opennms.netmgt.events.api.model.IEvent;
import org.opennms.netmgt.model.OnmsAlarm;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyConsumer;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyDao;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyEdge;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyMessage;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyMessage.TopologyMessageStatus;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyProtocol;
import org.opennms.netmgt.topologies.service.api.OnmsTopologyVertex;
import org.opennms.netmgt.topologies.service.api.TopologyVisitor;
import org.opennms.netmgt.xml.event.Event;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.swrve.ratelimitedlogger.RateLimitedLog;
public class OpennmsKafkaProducer implements AlarmLifecycleListener, EventListener, AlarmFeedbackListener, OnmsTopologyConsumer, ThreadAwareEventListener {
private static final Logger LOG = LoggerFactory.getLogger(OpennmsKafkaProducer.class);
private static final RateLimitedLog RATE_LIMITED_LOGGER = RateLimitedLog
.withRateLimit(LOG)
.maxRate(5).every(Duration.ofSeconds(30))
.build();
public static final String KAFKA_CLIENT_PID = "org.opennms.features.kafka.producer.client";
private static final ExpressionParser SPEL_PARSER = new SpelExpressionParser();
private final ThreadFactory nodeUpdateThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("kafka-producer-node-update-%d")
.build();
private final ProtobufMapper protobufMapper;
private final NodeCache nodeCache;
private final ConfigurationAdmin configAdmin;
private final EventSubscriptionService eventSubscriptionService;
private KafkaAlarmDataSync dataSync;
private String eventTopic;
private String alarmTopic;
private String nodeTopic;
private String alarmFeedbackTopic;
private String topologyVertexTopic;
private String topologyEdgeTopic;
private boolean forwardEvents;
private boolean forwardAlarms;
private boolean forwardAlarmFeedback;
private boolean suppressIncrementalAlarms;
private boolean forwardNodes;
private Expression eventFilterExpression;
private Expression alarmFilterExpression;
private final CountDownLatch forwardedEvent = new CountDownLatch(1);
private final CountDownLatch forwardedAlarm = new CountDownLatch(1);
private final CountDownLatch forwardedNode = new CountDownLatch(1);
private final CountDownLatch forwardedAlarmFeedback = new CountDownLatch(1);
private final CountDownLatch forwardedTopologyVertexMessage = new CountDownLatch(1);
private final CountDownLatch forwardedTopologyEdgeMessage = new CountDownLatch(1);
private KafkaProducer<byte[], byte[]> producer;
private final Map<String, OpennmsModelProtos.Alarm> outstandingAlarms = new ConcurrentHashMap<>();
private final AlarmEqualityChecker alarmEqualityChecker =
AlarmEqualityChecker.with(AlarmEqualityChecker.Exclusions::defaultExclusions);
private final AlarmCallbackStateTracker stateTracker = new AlarmCallbackStateTracker();
private final OnmsTopologyDao topologyDao;
private int kafkaSendQueueCapacity;
private BlockingDeque<KafkaRecord> kafkaSendDeque;
private final ExecutorService kafkaSendQueueExecutor =
Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "KafkaSendQueueProcessor"));
private final ExecutorService nodeUpdateExecutor;
private String encoding = "UTF8";
private int numEventListenerThreads = 4;
public OpennmsKafkaProducer(ProtobufMapper protobufMapper, NodeCache nodeCache,
ConfigurationAdmin configAdmin, EventSubscriptionService eventSubscriptionService,
OnmsTopologyDao topologyDao, int nodeAsyncUpdateThreads) {
this.protobufMapper = Objects.requireNonNull(protobufMapper);
this.nodeCache = Objects.requireNonNull(nodeCache);
this.configAdmin = Objects.requireNonNull(configAdmin);
this.eventSubscriptionService = Objects.requireNonNull(eventSubscriptionService);
this.topologyDao = Objects.requireNonNull(topologyDao);
this.nodeUpdateExecutor = Executors.newFixedThreadPool(nodeAsyncUpdateThreads, nodeUpdateThreadFactory);
}
public void init() throws IOException {
// Create the Kafka producer
final Properties producerConfig = new Properties();
final Dictionary<String, Object> properties = configAdmin.getConfiguration(KAFKA_CLIENT_PID).getProperties();
if (properties != null) {
final Enumeration<String> keys = properties.keys();
while (keys.hasMoreElements()) {
final String key = keys.nextElement();
producerConfig.put(key, properties.get(key));
}
}
// Overwrite the serializers, since we rely on these
producerConfig.put("key.serializer", ByteArraySerializer.class.getCanonicalName());
producerConfig.put("value.serializer", ByteArraySerializer.class.getCanonicalName());
// Class-loader hack for accessing the kafka classes when initializing producer.
producer = Utils.runWithGivenClassLoader(() -> new KafkaProducer<>(producerConfig), KafkaProducer.class.getClassLoader());
// Start processing records that have been queued for sending
if (kafkaSendQueueCapacity <= 0) {
kafkaSendQueueCapacity = 1000;
LOG.info("Defaulted the 'kafkaSendQueueCapacity' to 1000 since no property was set");
}
kafkaSendDeque = new LinkedBlockingDeque<>(kafkaSendQueueCapacity);
kafkaSendQueueExecutor.execute(this::processKafkaSendQueue);
if (forwardEvents) {
eventSubscriptionService.addEventListener(this);
}
topologyDao.subscribe(this);
}
public void destroy() {
kafkaSendQueueExecutor.shutdownNow();
nodeUpdateExecutor.shutdownNow();
if (producer != null) {
producer.close();
producer = null;
}
if (forwardEvents) {
eventSubscriptionService.removeEventListener(this);
}
topologyDao.unsubscribe(this);
}
private void forwardTopologyMessage(OnmsTopologyMessage message) {
if (message.getProtocol() == null) {
LOG.error("forwardTopologyMessage: null protocol");
return;
}
if (message.getMessagestatus() == null) {
LOG.error("forwardTopologyMessage: null status");
return;
}
if (message.getMessagebody() == null) {
LOG.error("forwardTopologyMessage: null message");
return;
}
if (message.getMessagestatus() == TopologyMessageStatus.DELETE) {
message.getMessagebody().accept(new DeletingVisitor(message));
} else {
message.getMessagebody().accept(new UpdatingVisitor(message));
}
}
private void forwardTopologyEdgeMessage(byte[] refid, byte[] message) {
sendRecord(() -> {
return new ProducerRecord<>(topologyEdgeTopic, refid, message);
}, recordMetadata -> {
// We've got an ACK from the server that the event was forwarded
// Let other threads know when we've successfully forwarded an event
forwardedTopologyEdgeMessage.countDown();
});
}
private void forwardEvent(Event event) {
boolean shouldForwardEvent = true;
// Filtering
if (eventFilterExpression != null) {
try {
shouldForwardEvent = eventFilterExpression.getValue(event, Boolean.class);
} catch (Exception e) {
LOG.error("Event filter '{}' failed to return a result for event: {}. The event will be forwarded anyways.",
eventFilterExpression.getExpressionString(), event.toStringSimple(), e);
}
}
if (!shouldForwardEvent) {
if (LOG.isTraceEnabled()) {
LOG.trace("Event {} not forwarded due to event filter: {}",
event.toStringSimple(), eventFilterExpression.getExpressionString());
}
return;
}
// Node handling
if (forwardNodes && event.getNodeid() != null && event.getNodeid() != 0) {
updateNodeAsynchronously(event.getNodeid());
}
// Forward!
sendRecord(() -> {
final OpennmsModelProtos.Event mappedEvent = protobufMapper.toEvent(event).build();
LOG.debug("Sending event with UEI: {}", mappedEvent.getUei());
return new ProducerRecord<>(eventTopic, mappedEvent.toByteArray());
}, recordMetadata -> {
// We've got an ACK from the server that the event was forwarded
// Let other threads know when we've successfully forwarded an event
forwardedEvent.countDown();
});
}
public boolean shouldForwardAlarm(OnmsAlarm alarm) {
if (alarmFilterExpression != null) {
// The expression is not necessarily thread safe
synchronized (this) {
try {
final boolean shouldForwardAlarm = alarmFilterExpression.getValue(alarm, Boolean.class);
if (LOG.isTraceEnabled()) {
LOG.trace("Alarm {} not forwarded due to event filter: {}",
alarm, alarmFilterExpression.getExpressionString());
}
return shouldForwardAlarm;
} catch (Exception e) {
LOG.error("Alarm filter '{}' failed to return a result for event: {}. The alarm will be forwarded anyways.",
alarmFilterExpression.getExpressionString(), alarm, e);
}
}
}
return true;
}
private boolean isIncrementalAlarm(String reductionKey, OnmsAlarm alarm) {
OpennmsModelProtos.Alarm existingAlarm = outstandingAlarms.get(reductionKey);
return existingAlarm != null && alarmEqualityChecker.equalsExcludingOnFirst(protobufMapper.toAlarm(alarm),
existingAlarm);
}
private void recordIncrementalAlarm(String reductionKey, OnmsAlarm alarm) {
// Apply the excluded fields when putting to the map so we do not have to perform this calculation
// on each equality check
outstandingAlarms.put(reductionKey,
AlarmEqualityChecker.Exclusions.defaultExclusions(protobufMapper.toAlarm(alarm)).build());
}
private void updateAlarm(String reductionKey, OnmsAlarm alarm) {
// Always push null records, no good way to perform filtering on these
if (alarm == null) {
// The alarm has been deleted so we shouldn't track it in the map of outstanding alarms any longer
outstandingAlarms.remove(reductionKey);
// The alarm was deleted, push a null record to the reduction key
sendRecord(() -> {
LOG.debug("Deleting alarm with reduction key: {}", reductionKey);
return new ProducerRecord<>(alarmTopic, reductionKey.getBytes(encoding), null);
}, recordMetadata -> {
// We've got an ACK from the server that the alarm was forwarded
// Let other threads know when we've successfully forwarded an alarm
forwardedAlarm.countDown();
});
return;
}
// Filtering
if (!shouldForwardAlarm(alarm)) {
return;
}
if (suppressIncrementalAlarms && isIncrementalAlarm(reductionKey, alarm)) {
return;
}
// Node handling
if (forwardNodes && alarm.getNodeId() != null) {
updateNodeAsynchronously(alarm.getNodeId());
}
// Forward!
sendRecord(() -> {
final OpennmsModelProtos.Alarm mappedAlarm = protobufMapper.toAlarm(alarm).build();
LOG.debug("Sending alarm with reduction key: {}", reductionKey);
if (suppressIncrementalAlarms) {
recordIncrementalAlarm(reductionKey, alarm);
}
return new ProducerRecord<>(alarmTopic, reductionKey.getBytes(encoding), mappedAlarm.toByteArray());
}, recordMetadata -> {
// We've got an ACK from the server that the alarm was forwarded
// Let other threads know when we've successfully forwarded an alarm
forwardedAlarm.countDown();
});
}
private void updateNodeAsynchronously(long nodeId) {
// Updating node asynchronously will unblock event consumption.
nodeUpdateExecutor.execute(() -> {
maybeUpdateNode(nodeId);
});
}
private void maybeUpdateNode(long nodeId) {
nodeCache.triggerIfNeeded(nodeId, (node) -> {
final String nodeCriteria;
if (node != null && node.getForeignSource() != null && node.getForeignId() != null) {
nodeCriteria = String.format("%s:%s", node.getForeignSource(), node.getForeignId());
} else {
nodeCriteria = Long.toString(nodeId);
}
if (node == null) {
// The node was deleted, push a null record
sendRecord(() -> {
LOG.debug("Deleting node with criteria: {}", nodeCriteria);
return new ProducerRecord<>(nodeTopic, nodeCriteria.getBytes(encoding), null);
});
return;
}
sendRecord(() -> {
final OpennmsModelProtos.Node mappedNode = protobufMapper.toNode(node).build();
LOG.debug("Sending node with criteria: {}", nodeCriteria);
return new ProducerRecord<>(nodeTopic, nodeCriteria.getBytes(encoding), mappedNode.toByteArray());
}, recordMetadata -> {
// We've got an ACK from the server that the node was forwarded
// Let other threads know when we've successfully forwarded a node
forwardedNode.countDown();
});
});
}
private void sendRecord(Callable<ProducerRecord<byte[], byte[]>> callable) {
sendRecord(callable, null);
}
private void sendRecord(Callable<ProducerRecord<byte[], byte[]>> callable, Consumer<RecordMetadata> callback) {
if (producer == null) {
return;
}
final ProducerRecord<byte[], byte[]> record;
try {
record = callable.call();
} catch (Exception e) {
// Propagate
throw new RuntimeException(e);
}
// Rather than attempt to send, we instead queue the record to avoid blocking since KafkaProducer's send()
// method can block if Kafka is not available when metadata is attempted to be retrieved
// Any offer that fails due to capacity overflow will simply be dropped and will have to wait until the next
// sync to be processed so this is just a best effort attempt
if (!kafkaSendDeque.offer(new KafkaRecord(record, callback))) {
RATE_LIMITED_LOGGER.warn("Dropped a Kafka record due to queue capacity being full.");
}
}
private void processKafkaSendQueue() {
//noinspection InfiniteLoopStatement
while (true) {
try {
KafkaRecord kafkaRecord = kafkaSendDeque.take();
ProducerRecord<byte[], byte[]> producerRecord = kafkaRecord.getProducerRecord();
Consumer<RecordMetadata> consumer = kafkaRecord.getConsumer();
try {
producer.send(producerRecord, (recordMetadata, e) -> {
if (e != null) {
LOG.warn("Failed to send record to producer: {}.", producerRecord, e);
if (e instanceof TimeoutException) {
// If Kafka is Offline, buffer the record again for events.
// This is best effort to keep the order although in-flight elements may still miss the order.
if (producerRecord != null &&
this.eventTopic.equalsIgnoreCase(producerRecord.topic())) {
if(!kafkaSendDeque.offerFirst(kafkaRecord)) {
RATE_LIMITED_LOGGER.warn("Dropped a Kafka record due to queue capacity being full.");
}
}
}
return;
}
if (consumer != null) {
consumer.accept(recordMetadata);
}
});
} catch (RuntimeException e) {
LOG.warn("Failed to send record to producer: {}.", producerRecord, e);
}
} catch (InterruptedException ignore) {
break;
}
}
}
@Override
public void handleAlarmSnapshot(List<OnmsAlarm> alarms) {
if (!forwardAlarms || dataSync == null) {
// Ignore
return;
}
dataSync.handleAlarmSnapshot(alarms);
}
@Override
public void preHandleAlarmSnapshot() {
stateTracker.startTrackingAlarms();
}
@Override
public void postHandleAlarmSnapshot() {
stateTracker.resetStateAndStopTrackingAlarms();
}
@Override
public void handleNewOrUpdatedAlarm(OnmsAlarm alarm) {
if (!forwardAlarms) {
// Ignore
return;
}
updateAlarm(alarm.getReductionKey(), alarm);
stateTracker.trackNewOrUpdatedAlarm(alarm.getId(), alarm.getReductionKey());
}
@Override
public void handleDeletedAlarm(int alarmId, String reductionKey) {
if (!forwardAlarms) {
// Ignore
return;
}
handleDeletedAlarm(reductionKey);
stateTracker.trackDeletedAlarm(alarmId, reductionKey);
}
private void handleDeletedAlarm(String reductionKey) {
updateAlarm(reductionKey, null);
}
@Override
public String getName() {
return OpennmsKafkaProducer.class.getName();
}
@Override
public void onEvent(IEvent event) {
forwardEvent(Event.copyFrom(event));
}
@Override
public Set<OnmsTopologyProtocol> getProtocols() {
return Collections.singleton(OnmsTopologyProtocol.allProtocols());
}
@Override
public void consume(OnmsTopologyMessage message) {
forwardTopologyMessage(message);
}
public void setTopologyVertexTopic(String topologyVertexTopic) {
this.topologyVertexTopic = topologyVertexTopic;
}
public void setTopologyEdgeTopic(String topologyEdgeTopic) {
this.topologyEdgeTopic = topologyEdgeTopic;
}
public void setEventTopic(String eventTopic) {
this.eventTopic = eventTopic;
forwardEvents = !Strings.isNullOrEmpty(eventTopic);
}
public void setAlarmTopic(String alarmTopic) {
this.alarmTopic = alarmTopic;
forwardAlarms = !Strings.isNullOrEmpty(alarmTopic);
}
public void setNodeTopic(String nodeTopic) {
this.nodeTopic = nodeTopic;
forwardNodes = !Strings.isNullOrEmpty(nodeTopic);
}
public void setAlarmFeedbackTopic(String alarmFeedbackTopic) {
this.alarmFeedbackTopic = alarmFeedbackTopic;
forwardAlarmFeedback = !Strings.isNullOrEmpty(alarmFeedbackTopic);
}
public void setEventFilter(String eventFilter) {
if (Strings.isNullOrEmpty(eventFilter)) {
eventFilterExpression = null;
} else {
eventFilterExpression = SPEL_PARSER.parseExpression(eventFilter);
}
}
public void setAlarmFilter(String alarmFilter) {
if (Strings.isNullOrEmpty(alarmFilter)) {
alarmFilterExpression = null;
} else {
alarmFilterExpression = SPEL_PARSER.parseExpression(alarmFilter);
}
}
public OpennmsKafkaProducer setDataSync(KafkaAlarmDataSync dataSync) {
this.dataSync = dataSync;
return this;
}
@Override
public void handleAlarmFeedback(List<AlarmFeedback> alarmFeedback) {
if (!forwardAlarmFeedback) {
return;
}
// NOTE: This will currently block while waiting for Kafka metadata if Kafka is not available.
alarmFeedback.forEach(feedback -> sendRecord(() -> {
LOG.debug("Sending alarm feedback with key: {}", feedback.getAlarmKey());
return new ProducerRecord<>(alarmFeedbackTopic, feedback.getAlarmKey().getBytes(encoding),
protobufMapper.toAlarmFeedback(feedback).build().toByteArray());
}, recordMetadata -> {
// We've got an ACK from the server that the alarm feedback was forwarded
// Let other threads know when we've successfully forwarded an alarm feedback
forwardedAlarmFeedback.countDown();
}));
}
public boolean isForwardingAlarms() {
return forwardAlarms;
}
public CountDownLatch getEventForwardedLatch() {
return forwardedEvent;
}
public CountDownLatch getAlarmForwardedLatch() {
return forwardedAlarm;
}
public CountDownLatch getNodeForwardedLatch() {
return forwardedNode;
}
public CountDownLatch getAlarmFeedbackForwardedLatch() {
return forwardedAlarmFeedback;
}
public void setSuppressIncrementalAlarms(boolean suppressIncrementalAlarms) {
this.suppressIncrementalAlarms = suppressIncrementalAlarms;
}
@VisibleForTesting
KafkaAlarmDataSync getDataSync() {
return dataSync;
}
public AlarmCallbackStateTracker getAlarmCallbackStateTracker() {
return stateTracker;
}
public void setKafkaSendQueueCapacity(int kafkaSendQueueCapacity) {
this.kafkaSendQueueCapacity = kafkaSendQueueCapacity;
}
@Override
public int getNumThreads() {
return numEventListenerThreads;
}
private static final class KafkaRecord {
private final ProducerRecord<byte[], byte[]> producerRecord;
private final Consumer<RecordMetadata> consumer;
KafkaRecord(ProducerRecord<byte[], byte[]> producerRecord, Consumer<RecordMetadata> consumer) {
this.producerRecord = producerRecord;
this.consumer = consumer;
}
ProducerRecord<byte[], byte[]> getProducerRecord() {
return producerRecord;
}
Consumer<RecordMetadata> getConsumer() {
return consumer;
}
}
public CountDownLatch getForwardedTopologyVertexMessage() {
return forwardedTopologyVertexMessage;
}
public CountDownLatch getForwardedTopologyEdgeMessage() {
return forwardedTopologyEdgeMessage;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public int getNumEventListenerThreads() {
return numEventListenerThreads;
}
public void setNumEventListenerThreads(int numEventListenerThreads) {
this.numEventListenerThreads = numEventListenerThreads;
}
private class TopologyVisitorImpl implements TopologyVisitor {
final OnmsTopologyMessage onmsTopologyMessage;
TopologyVisitorImpl(OnmsTopologyMessage onmsTopologyMessage) {
this.onmsTopologyMessage = Objects.requireNonNull(onmsTopologyMessage);
}
byte[] getKeyForEdge(OnmsTopologyEdge edge) {
Objects.requireNonNull(onmsTopologyMessage);
return String.format("topology:%s:%s", onmsTopologyMessage.getProtocol().getId(), edge.getId()).getBytes();
}
}
private class DeletingVisitor extends TopologyVisitorImpl {
DeletingVisitor(OnmsTopologyMessage topologyMessage) {
super(topologyMessage);
}
@Override
public void visit(OnmsTopologyEdge edge) {
forwardTopologyEdgeMessage(getKeyForEdge(edge), null);
}
}
private class UpdatingVisitor extends TopologyVisitorImpl {
UpdatingVisitor(OnmsTopologyMessage onmsTopologyMessage) {
super(onmsTopologyMessage);
}
@Override
public void visit(OnmsTopologyVertex vertex) {
// Node handling
if (forwardNodes && vertex.getNodeid() != null) {
updateNodeAsynchronously(vertex.getNodeid());
}
}
@Override
public void visit(OnmsTopologyEdge edge) {
Objects.requireNonNull(onmsTopologyMessage);
final OpennmsModelProtos.TopologyEdge mappedTopoMsg =
protobufMapper.toEdgeTopologyMessage(onmsTopologyMessage.getProtocol(), edge);
forwardTopologyEdgeMessage(getKeyForEdge(edge), mappedTopoMsg.toByteArray());
}
}
}
| Java |
/*
* This file Copyright (C) Mnemosyne LLC
*
* This file is licensed by the GPL version 2. Works owned by the
* Transmission project are granted a special exemption to clause 2 (b)
* so that the bulk of its code can remain under the MIT license.
* This exemption does not extend to derived works not owned by
* the Transmission project.
*
* $Id$
*/
#ifndef GTR_UTIL_H
#define GTR_UTIL_H
#include <sys/types.h>
#include <glib.h>
#include <gtk/gtk.h>
#include <libtransmission/transmission.h>
extern const int mem_K;
extern const char * mem_K_str;
extern const char * mem_M_str;
extern const char * mem_G_str;
extern const char * mem_T_str;
extern const int disk_K;
extern const char * disk_K_str;
extern const char * disk_M_str;
extern const char * disk_G_str;
extern const char * disk_T_str;
extern const int speed_K;
extern const char * speed_K_str;
extern const char * speed_M_str;
extern const char * speed_G_str;
extern const char * speed_T_str;
/* macro to shut up "unused parameter" warnings */
#ifndef UNUSED
#define UNUSED G_GNUC_UNUSED
#endif
enum
{
GTR_UNICODE_UP,
GTR_UNICODE_DOWN,
GTR_UNICODE_INF,
GTR_UNICODE_BULLET
};
const char * gtr_get_unicode_string (int);
/* return a percent formatted string of either x.xx, xx.x or xxx */
char* tr_strlpercent (char * buf, double x, size_t buflen);
/* return a human-readable string for the size given in bytes. */
char* tr_strlsize (char * buf, guint64 size, size_t buflen);
/* return a human-readable string for the given ratio. */
char* tr_strlratio (char * buf, double ratio, size_t buflen);
/* return a human-readable string for the time given in seconds. */
char* tr_strltime (char * buf, int secs, size_t buflen);
/***
****
***/
/* http://www.legaltorrents.com/some/announce/url --> legaltorrents.com */
void gtr_get_host_from_url (char * buf, size_t buflen, const char * url);
gboolean gtr_is_magnet_link (const char * str);
gboolean gtr_is_hex_hashcode (const char * str);
/***
****
***/
void gtr_open_uri (const char * uri);
void gtr_open_file (const char * path);
const char* gtr_get_help_uri (void);
/***
****
***/
/* backwards-compatible wrapper around gtk_widget_set_visible () */
void gtr_widget_set_visible (GtkWidget *, gboolean);
void gtr_dialog_set_content (GtkDialog * dialog, GtkWidget * content);
/***
****
***/
GtkWidget * gtr_priority_combo_new (void);
#define gtr_priority_combo_get_value(w) gtr_combo_box_get_active_enum (w)
#define gtr_priority_combo_set_value(w,val) gtr_combo_box_set_active_enum (w,val)
GtkWidget * gtr_combo_box_new_enum (const char * text_1, ...);
int gtr_combo_box_get_active_enum (GtkComboBox *);
void gtr_combo_box_set_active_enum (GtkComboBox *, int value);
/***
****
***/
void gtr_unrecognized_url_dialog (GtkWidget * parent, const char * url);
void gtr_http_failure_dialog (GtkWidget * parent, const char * url, long response_code);
void gtr_add_torrent_error_dialog (GtkWidget * window_or_child,
int err,
const char * filename);
/* pop up the context menu if a user right-clicks.
if the row they right-click on isn't selected, select it. */
gboolean on_tree_view_button_pressed (GtkWidget * view,
GdkEventButton * event,
gpointer unused);
/* if the click didn't specify a row, clear the selection */
gboolean on_tree_view_button_released (GtkWidget * view,
GdkEventButton * event,
gpointer unused);
/* move a file to the trashcan if GIO is available; otherwise, delete it */
int gtr_file_trash_or_remove (const char * filename);
void gtr_paste_clipboard_url_into_entry (GtkWidget * entry);
/* Only call gtk_label_set_text () if the new text differs from the old.
* This prevents the label from having to recalculate its size
* and prevents selected text in the label from being deselected */
void gtr_label_set_text (GtkLabel * lb, const char * text);
#endif /* GTR_UTIL_H */
| Java |
/**
* The routes worker process
*
* This worker process gets the app routes by running the application dynamically
* on the server, then stores the publicly exposed routes in an intermediate format
* (just the url paths) in Redis.
* From there, the paths are used by the live app for serving /sitemap.xml and /robots.txt requests.
* The paths are also used by downstream worker processes (snapshots) to produce the site's html snapshots
* for _escaped_fragment_ requests.
*
* Run this worker anytime the app menu has changed and needs to be refreshed.
*
* PATH and NODE_ENV have to set in the environment before running this.
* PATH has to include phantomjs bin
*/
var phantom = require("node-phantom");
var urlm = require("url");
var redis = require("../../../helpers/redis");
var configLib = require("../../../config");
var config = configLib.create();
// Write the appRoutes to Redis
function writeAppRoutes(appRoutes) {
// remove pattern routes, and prepend /
appRoutes = appRoutes.filter(function(appRoute) {
return !/[*\(\:]/.test(appRoute);
}).map(function(appRoute) {
return "/"+appRoute;
});
if (appRoutes.length > 0) {
var redisClient = redis.client();
redisClient.set(config.keys.routes, appRoutes, function(err) {
if (err) {
console.error("failed to store the routes for "+config.keys.routes);
} else {
console.log("successfully stored "+appRoutes.length+" routes in "+config.keys.routes);
}
redisClient.quit();
});
} else {
console.error("no routes found for "+config.app.hostname);
}
}
// Start up phantom, wait for the page, get the appRoutes
function routes(urlPath, timeout) {
var url = urlm.format({
protocol: "http",
hostname: config.app.hostname,
port: config.app.port || 80,
pathname: urlPath
});
phantom.create(function(err, ph) {
return ph.createPage(function(err, page) {
return page.open(url, function(err, status) {
if (status !== "success") {
console.error("Unable to load page " + url);
ph.exit();
} else {
setTimeout(function() {
return page.evaluate(function() {
return window.wpspa.appRoutes;
}, function(err, result) {
if (err) {
console.error("failed to get appRoutes");
} else {
writeAppRoutes(Object.keys(result));
}
ph.exit();
});
}, timeout);
}
});
});
});
}
module.exports = {
routes: routes
}; | Java |
/*
* Vulcan Build Manager
* Copyright (C) 2005-2012 Chris Eldredge
*
* 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.
*/
package net.sourceforge.vulcan.subversion;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import net.sourceforge.vulcan.RepositoryAdaptor;
import net.sourceforge.vulcan.StateManager;
import net.sourceforge.vulcan.core.BuildDetailCallback;
import net.sourceforge.vulcan.core.support.FileSystem;
import net.sourceforge.vulcan.core.support.FileSystemImpl;
import net.sourceforge.vulcan.core.support.RepositoryUtils;
import net.sourceforge.vulcan.dto.ChangeLogDto;
import net.sourceforge.vulcan.dto.ChangeSetDto;
import net.sourceforge.vulcan.dto.PathModification;
import net.sourceforge.vulcan.dto.ProjectConfigDto;
import net.sourceforge.vulcan.dto.ProjectStatusDto;
import net.sourceforge.vulcan.dto.RepositoryTagDto;
import net.sourceforge.vulcan.dto.RevisionTokenDto;
import net.sourceforge.vulcan.exception.ConfigException;
import net.sourceforge.vulcan.exception.RepositoryException;
import net.sourceforge.vulcan.integration.support.PluginSupport;
import net.sourceforge.vulcan.subversion.dto.CheckoutDepth;
import net.sourceforge.vulcan.subversion.dto.SparseCheckoutDto;
import net.sourceforge.vulcan.subversion.dto.SubversionConfigDto;
import net.sourceforge.vulcan.subversion.dto.SubversionProjectConfigDto;
import net.sourceforge.vulcan.subversion.dto.SubversionRepositoryProfileDto;
import org.apache.commons.lang.StringUtils;
import org.tigris.subversion.javahl.ClientException;
import org.tigris.subversion.javahl.Notify2;
import org.tigris.subversion.javahl.NotifyAction;
import org.tigris.subversion.javahl.NotifyInformation;
import org.tigris.subversion.javahl.PromptUserPassword2;
import org.tigris.subversion.javahl.PromptUserPassword3;
import org.tigris.subversion.javahl.Revision;
import org.tigris.subversion.javahl.SVNClient;
import org.tmatesoft.svn.core.ISVNLogEntryHandler;
import org.tmatesoft.svn.core.SVNCancelException;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNLogEntryPath;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNProperties;
import org.tmatesoft.svn.core.SVNPropertyValue;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.wc.ISVNEventHandler;
import org.tmatesoft.svn.core.wc.SVNDiffClient;
import org.tmatesoft.svn.core.wc.SVNEvent;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.wc.SVNPropertyData;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNWCClient;
public class SubversionRepositoryAdaptor extends SubversionSupport implements RepositoryAdaptor {
private final EventHandler eventHandler = new EventHandler();
private final ProjectConfigDto projectConfig;
private final String projectName;
private final Map<String, Long> byteCounters;
final LineOfDevelopment lineOfDevelopment = new LineOfDevelopment();
final SVNClient client = new SVNClient();
private long revision = -1;
private long diffStartRevision = -1;
private final StateManager stateManager;
private FileSystem fileSystem = new FileSystemImpl();
private List<ChangeSetDto> changeSets;
boolean canceling = false;
public SubversionRepositoryAdaptor(SubversionConfigDto globalConfig, ProjectConfigDto projectConfig, SubversionProjectConfigDto config, StateManager stateManager) throws ConfigException {
this(globalConfig, projectConfig, config, stateManager, true);
}
protected SubversionRepositoryAdaptor(SubversionConfigDto globalConfig, ProjectConfigDto projectConfig, SubversionProjectConfigDto config, StateManager stateManager, boolean init) throws ConfigException {
this(
globalConfig,
projectConfig,
config,
stateManager,
init,
getSelectedEnvironment(
globalConfig.getProfiles(),
config.getRepositoryProfile(),
"svn.profile.missing"));
}
protected SubversionRepositoryAdaptor(SubversionConfigDto globalConfig, ProjectConfigDto projectConfig, SubversionProjectConfigDto config, StateManager stateManager, boolean init, SubversionRepositoryProfileDto profile) throws ConfigException {
this(
globalConfig,
projectConfig,
config,
stateManager,
profile,
createRepository(profile, init));
}
protected SubversionRepositoryAdaptor(SubversionConfigDto globalConfig, ProjectConfigDto projectConfig, SubversionProjectConfigDto config, StateManager stateManager, final SubversionRepositoryProfileDto profile, SVNRepository svnRepository) throws ConfigException {
super(config, profile, svnRepository);
this.stateManager = stateManager;
this.projectConfig = projectConfig;
this.projectName = projectConfig.getName();
if (globalConfig != null) {
this.byteCounters = globalConfig.getWorkingCopyByteCounts();
} else {
this.byteCounters = Collections.emptyMap();
}
lineOfDevelopment.setPath(config.getPath());
lineOfDevelopment.setRepositoryRoot(profile.getRootUrl());
lineOfDevelopment.setTagFolderNames(new HashSet<String>(Arrays.asList(globalConfig.getTagFolderNames())));
client.notification2(eventHandler);
if (StringUtils.isNotBlank(profile.getUsername())) {
client.setPrompt(new PromptUserPassword3() {
public String getUsername() {
return profile.getUsername();
}
public String getPassword() {
return profile.getPassword();
}
public boolean prompt(String arg0, String arg1) {
return true;
}
public boolean prompt(String arg0, String arg1, boolean arg2) {
return true;
}
public boolean userAllowedSave() {
return false;
}
public int askTrustSSLServer(String arg0, boolean arg1) {
return PromptUserPassword2.AcceptTemporary;
}
public String askQuestion(String arg0, String arg1,
boolean arg2, boolean arg3) {
throw new UnsupportedOperationException();
}
public String askQuestion(String arg0, String arg1, boolean arg2) {
throw new UnsupportedOperationException();
}
public boolean askYesNo(String arg0, String arg1, boolean arg2) {
throw new UnsupportedOperationException();
}
});
}
}
public boolean hasIncomingChanges(ProjectStatusDto previousStatus) throws RepositoryException {
RevisionTokenDto rev = previousStatus.getRevision();
if (rev == null) {
rev = previousStatus.getLastKnownRevision();
}
if (rev == null) {
return true;
}
return getLatestRevision(rev).getRevisionNum() > rev.getRevisionNum();
}
public void prepareRepository(BuildDetailCallback buildDetailCallback) throws RepositoryException, InterruptedException {
}
public RevisionTokenDto getLatestRevision(RevisionTokenDto previousRevision) throws RepositoryException {
final String path = lineOfDevelopment.getComputedRelativePath();
SVNDirEntry info;
try {
info = svnRepository.info(path, revision);
} catch (SVNException e) {
throw new RepositoryException(e);
}
if (info == null) {
throw new RepositoryException("svn.path.not.exist", null, path);
}
final long lastChangedRevision = info.getRevision();
/*
* Get the revision of the newest log entry for this path.
* See Issue 95 (http://code.google.com/p/vulcan/issues/detail?id=95).
*/
final long mostRecentLogRevision = getMostRecentLogRevision(lastChangedRevision);
revision = mostRecentLogRevision;
if (config.getCheckoutDepth() == CheckoutDepth.Infinity || previousRevision == null) {
return new RevisionTokenDto(revision, "r" + revision);
}
/* Issue 151 (http://code.google.com/p/vulcan/issues/detail?id=151):
* Need to filter out irrelevant commits from sparse working copy.
*/
try {
getChangeLog(previousRevision, new RevisionTokenDto(revision), null);
if (changeSets.size() > 0) {
String label = changeSets.get(changeSets.size()-1).getRevisionLabel();
revision = Long.valueOf(label.substring(1));
} else {
// No commit logs matched means we're effectively at the old revision.
// Need to check if the old revision exists on this path in case we're building
// from a different branch/tag.
try {
info = svnRepository.info(path, previousRevision.getRevisionNum());
} catch (SVNException e) {
throw new RepositoryException(e);
}
if (info != null) {
revision = previousRevision.getRevisionNum();
} else {
// Path doesn't exist at that revision. Use most recent commit
// even though it didn't match our sparse working copy.
revision = mostRecentLogRevision;
}
}
} catch (RepositoryException e) {
// Probably the path does not exist at the previousRevision.
revision = mostRecentLogRevision;
changeSets = null;
}
return new RevisionTokenDto(revision, "r" + revision);
}
public void createPristineWorkingCopy(BuildDetailCallback buildDetailCallback) throws RepositoryException {
final File absolutePath = new File(projectConfig.getWorkDir()).getAbsoluteFile();
new RepositoryUtils(fileSystem).createOrCleanWorkingCopy(absolutePath, buildDetailCallback);
synchronized (byteCounters) {
if (byteCounters.containsKey(projectName)) {
eventHandler.setPreviousFileCount(byteCounters.get(projectName).longValue());
}
}
eventHandler.setBuildDetailCallback(buildDetailCallback);
final Revision svnRev = Revision.getInstance(revision);
final boolean ignoreExternals = false;
final boolean allowUnverObstructions = false;
try {
client.checkout(
getCompleteSVNURL().toString(),
absolutePath.toString(),
svnRev,
svnRev,
config.getCheckoutDepth().getId(),
ignoreExternals,
allowUnverObstructions
);
configureBugtraqIfNecessary(absolutePath);
} catch (ClientException e) {
if (!canceling) {
throw new RepositoryException(e);
}
} catch (SVNException e) {
throw new RepositoryException(e);
}
final boolean depthIsSticky = true;
for (SparseCheckoutDto folder : config.getFolders()) {
sparseUpdate(folder, absolutePath, svnRev, ignoreExternals,
allowUnverObstructions, depthIsSticky);
}
synchronized (byteCounters) {
byteCounters.put(projectName, eventHandler.getFileCount());
}
}
void sparseUpdate(SparseCheckoutDto folder,
File workingCopyRootPath, final Revision svnRev,
final boolean ignoreExternals,
final boolean allowUnverObstructions, final boolean depthIsSticky)
throws RepositoryException {
final File dir = new File(workingCopyRootPath, folder.getDirectoryName());
final File parentDir = dir.getParentFile();
if (!parentDir.exists()) {
final SparseCheckoutDto parentFolder = new SparseCheckoutDto();
parentFolder.setDirectoryName(new File(folder.getDirectoryName()).getParent());
parentFolder.setCheckoutDepth(CheckoutDepth.Empty);
sparseUpdate(parentFolder, workingCopyRootPath, svnRev, ignoreExternals, allowUnverObstructions, depthIsSticky);
}
final String path = dir.toString();
try {
client.update(path, svnRev, folder.getCheckoutDepth().getId(), depthIsSticky, ignoreExternals, allowUnverObstructions);
} catch (ClientException e) {
if (!canceling) {
throw new RepositoryException("svn.sparse.checkout.error", e, folder.getDirectoryName());
}
}
}
public void updateWorkingCopy(BuildDetailCallback buildDetailCallback) throws RepositoryException {
final File absolutePath = new File(projectConfig.getWorkDir()).getAbsoluteFile();
try {
final Revision svnRev = Revision.getInstance(revision);
final boolean depthIsSticky = false;
final boolean ignoreExternals = false;
final boolean allowUnverObstructions = false;
client.update(absolutePath.toString(), svnRev, SVNDepth.UNKNOWN.getId(), depthIsSticky, ignoreExternals, allowUnverObstructions);
} catch (ClientException e) {
if (!canceling) {
throw new RepositoryException(e);
}
throw new RepositoryException(e);
}
}
public boolean isWorkingCopy() {
try {
if (client.info(new File(projectConfig.getWorkDir()).getAbsolutePath()) != null) {
return true;
}
} catch (ClientException ignore) {
}
return false;
}
public ChangeLogDto getChangeLog(RevisionTokenDto first, RevisionTokenDto last, OutputStream diffOutputStream) throws RepositoryException {
final SVNRevision r1 = SVNRevision.create(first.getRevisionNum().longValue());
final SVNRevision r2 = SVNRevision.create(last.getRevisionNum().longValue());
if (changeSets == null) {
changeSets = fetchChangeSets(r1, r2);
if (this.config.getCheckoutDepth() != CheckoutDepth.Infinity) {
final SparseChangeLogFilter filter = new SparseChangeLogFilter(this.config, this.lineOfDevelopment);
filter.removeIrrelevantChangeSets(changeSets);
}
}
if (diffOutputStream != null) {
fetchDifferences(SVNRevision.create(diffStartRevision), r2, diffOutputStream);
}
final ChangeLogDto changeLog = new ChangeLogDto();
changeLog.setChangeSets(changeSets);
return changeLog;
}
@SuppressWarnings("unchecked")
public List<RepositoryTagDto> getAvailableTagsAndBranches() throws RepositoryException {
final String projectRoot = lineOfDevelopment.getComputedTagRoot();
final List<RepositoryTagDto> tags = new ArrayList<RepositoryTagDto>();
final RepositoryTagDto trunkTag = new RepositoryTagDto();
trunkTag.setDescription("trunk");
trunkTag.setName("trunk");
tags.add(trunkTag);
try {
final Collection<SVNDirEntry> entries = svnRepository.getDir(projectRoot, -1, null, (Collection<?>) null);
for (SVNDirEntry entry : entries) {
final String folderName = entry.getName();
if (entry.getKind() == SVNNodeKind.DIR && lineOfDevelopment.isTag(folderName)) {
addTags(projectRoot, folderName, tags);
}
}
} catch (SVNException e) {
throw new RepositoryException(e);
}
Collections.sort(tags, new Comparator<RepositoryTagDto>() {
public int compare(RepositoryTagDto t1, RepositoryTagDto t2) {
return t1.getName().compareTo(t2.getName());
}
});
return tags;
}
public String getRepositoryUrl() {
try {
return getCompleteSVNURL().toString();
} catch (SVNException e) {
throw new RuntimeException(e);
}
}
public String getTagOrBranch() {
return lineOfDevelopment.getComputedTagName();
}
public void setTagOrBranch(String tagName) {
lineOfDevelopment.setAlternateTagName(tagName);
}
protected long getMostRecentLogRevision(final long lastChangedRevision) throws RepositoryException {
final long[] commitRev = new long[1];
commitRev[0] = -1;
final SVNLogClient logClient = new SVNLogClient(
svnRepository.getAuthenticationManager(), options);
final ISVNLogEntryHandler handler = new ISVNLogEntryHandler() {
public void handleLogEntry(SVNLogEntry logEntry) throws SVNException {
commitRev[0] = logEntry.getRevision();
}
};
try {
logClient.doLog(SVNURL.parseURIEncoded(profile.getRootUrl()),
new String[] {lineOfDevelopment.getComputedRelativePath()},
SVNRevision.HEAD, SVNRevision.HEAD, SVNRevision.create(lastChangedRevision),
true, false, 1, handler);
} catch (SVNException e) {
throw new RepositoryException(e);
}
// If for some reason there were zero log entries, default to Last Changed Revision.
if (commitRev[0] < 0) {
commitRev[0] = lastChangedRevision;
}
return commitRev[0];
}
protected List<ChangeSetDto> fetchChangeSets(final SVNRevision r1, final SVNRevision r2) throws RepositoryException {
final SVNLogClient logClient = new SVNLogClient(svnRepository.getAuthenticationManager(), options);
logClient.setEventHandler(eventHandler);
final List<ChangeSetDto> changeSets = new ArrayList<ChangeSetDto>();
diffStartRevision = r2.getNumber();
final ISVNLogEntryHandler handler = new ISVNLogEntryHandler() {
@SuppressWarnings("unchecked")
public void handleLogEntry(SVNLogEntry logEntry) {
final long logEntryRevision = logEntry.getRevision();
if (diffStartRevision > logEntryRevision) {
diffStartRevision = logEntryRevision;
}
if (logEntryRevision == r1.getNumber()) {
/* The log message for r1 is in the previous build report. Don't include it twice. */
return;
}
final ChangeSetDto changeSet = new ChangeSetDto();
changeSet.setRevisionLabel("r" + logEntryRevision);
changeSet.setAuthorName(logEntry.getAuthor());
changeSet.setMessage(logEntry.getMessage());
changeSet.setTimestamp(new Date(logEntry.getDate().getTime()));
final Collection<SVNLogEntryPath> paths = ((Map<String, SVNLogEntryPath>) logEntry.getChangedPaths()).values();
for (SVNLogEntryPath path : paths) {
changeSet.addModifiedPath(path.getPath(), toPathModification(path.getType()));
}
changeSets.add(changeSet);
}
private PathModification toPathModification(char type) {
switch(type) {
case SVNLogEntryPath.TYPE_ADDED:
return PathModification.Add;
case SVNLogEntryPath.TYPE_DELETED:
return PathModification.Remove;
case SVNLogEntryPath.TYPE_REPLACED:
case SVNLogEntryPath.TYPE_MODIFIED:
return PathModification.Modify;
}
return null;
}
};
try {
logClient.doLog(
SVNURL.parseURIEncoded(profile.getRootUrl()),
new String[] {lineOfDevelopment.getComputedRelativePath()},
r1, r1, r2,
true,
true,
0,
handler);
} catch (SVNCancelException e) {
} catch (SVNException e) {
if (isFatal(e)) {
throw new RepositoryException(e);
}
}
return changeSets;
}
protected void fetchDifferences(final SVNRevision r1, final SVNRevision r2, OutputStream os) throws RepositoryException {
final SVNDiffClient diffClient = new SVNDiffClient(svnRepository.getAuthenticationManager(), options);
diffClient.setEventHandler(eventHandler);
try {
diffClient.doDiff(getCompleteSVNURL(), r1, r1, r2, SVNDepth.INFINITY, true, os);
os.close();
} catch (SVNCancelException e) {
} catch (SVNException e) {
if (e.getErrorMessage().getErrorCode() == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
// This usually happens when building from a different branch or tag that
// does not share ancestry with the previous build.
log.info("Failed to obtain diff of revisions r"
+ r1.getNumber() + ":" + r2.getNumber(), e);
} else {
throw new RepositoryException(e);
}
} catch (IOException e) {
throw new RepositoryException(e);
}
}
protected SVNURL getCompleteSVNURL() throws SVNException {
return SVNURL.parseURIEncoded(lineOfDevelopment.getAbsoluteUrl());
}
@SuppressWarnings("unchecked")
private void addTags(String projectRoot, String folderName, List<RepositoryTagDto> tags) throws SVNException {
final String path = projectRoot + "/" + folderName;
final Collection<SVNDirEntry> entries = svnRepository.getDir(path, -1, null, (Collection<?>) null);
for (SVNDirEntry entry : entries) {
final String tagName = entry.getName();
if (entry.getKind() == SVNNodeKind.DIR) {
RepositoryTagDto tag = new RepositoryTagDto();
tag.setName(folderName + "/" + tagName);
tag.setDescription(tag.getName());
tags.add(tag);
}
}
}
private void configureBugtraqIfNecessary(File absolutePath) throws SVNException {
if (!this.config.isObtainBugtraqProperties()) {
return;
}
final ProjectConfigDto orig = stateManager.getProjectConfig(projectName);
final SVNWCClient client = new SVNWCClient(svnRepository.getAuthenticationManager(), options);
final SVNProperties bugtraqProps = new SVNProperties();
getWorkingCopyProperty(client, absolutePath, BUGTRAQ_URL, bugtraqProps);
getWorkingCopyProperty(client, absolutePath, BUGTRAQ_MESSAGE, bugtraqProps);
getWorkingCopyProperty(client, absolutePath, BUGTRAQ_LOGREGEX, bugtraqProps);
final ProjectConfigDto projectConfig = (ProjectConfigDto) orig.copy();
configureBugtraq(projectConfig, bugtraqProps);
if (!orig.equals(projectConfig)) {
try {
log.info("Updating bugtraq information for project " + projectName);
stateManager.updateProjectConfig(projectName, projectConfig, false);
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
}
}
private void getWorkingCopyProperty(final SVNWCClient client, File absolutePath, String propName, final SVNProperties bugtraqProps) throws SVNException {
SVNPropertyData prop;
prop = client.doGetProperty(absolutePath, propName, SVNRevision.BASE, SVNRevision.BASE);
bugtraqProps.put(propName, getValueIfNotNull(prop));
}
protected String getValueIfNotNull(SVNPropertyData prop) {
if (prop != null) {
final SVNPropertyValue value = prop.getValue();
if (value.isString()) {
return value.getString();
}
return SVNPropertyValue.getPropertyAsString(value);
}
return StringUtils.EMPTY;
}
private class EventHandler implements ISVNEventHandler, Notify2 {
private long previousFileCount = -1;
private long fileCount = 0;
private BuildDetailCallback buildDetailCallback;
public void onNotify(NotifyInformation info) {
if (info.getAction() == NotifyAction.update_add) {
fileCount++;
PluginSupport.setWorkingCopyProgress(buildDetailCallback, fileCount, previousFileCount, ProgressUnit.Files);
} else if (info.getAction() == NotifyAction.skip) {
log.warn("Skipping missing target: " + info.getPath());
}
if (Thread.interrupted()) {
try {
client.cancelOperation();
canceling = true;
} catch (ClientException e) {
log.error("Error canceling svn operation", e);
}
}
}
public void handleEvent(SVNEvent event, double progress) throws SVNException {
}
public void checkCancelled() throws SVNCancelException {
if (Thread.interrupted()) {
throw new SVNCancelException();
}
}
void setBuildDetailCallback(BuildDetailCallback buildDetailCallback) {
this.buildDetailCallback = buildDetailCallback;
}
long getFileCount() {
return fileCount;
}
void setPreviousFileCount(long previousByteCount) {
this.previousFileCount = previousByteCount;
}
}
}
| Java |
.CODE
__exec_payload PROC x:QWORD
mov rax, x
call QWORD PTR[rax]
ret
__exec_payload ENDP
END
| Java |
/* dia -- an diagram creation/manipulation program
* Copyright (C) 1998 Alexander Larsson
*
* dia_svg.c -- Refactoring by Hans Breuer from :
*
* Custom Objects -- objects defined in XML rather than C.
* Copyright (C) 1999 James Henstridge.
*
* 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 "config.h"
#include <string.h>
#include <stdlib.h>
#include <pango/pango-attributes.h>
#include "dia_svg.h"
/**
* SECTION:dia_svg
* @title: Dia SVG
* @short_description: A set of function helping to read and write SVG with Dia
*
* The Dia application supports various variants of SVG. There are
* at least two importers of SVG dialects, namely \ref Shapes and
* the standard SVG importer \ref Plugins. Both are using theses
* services to a large extend, but they are also doing there own
* thing regarding the SVG dialect interpretation.
*/
/*!
* A global variable to be accessed by "currentColor"
*/
static int _current_color = 0xFF000000;
/*!
* \brief Initialize a style object from another style object or defaults.
* @param gs An SVG style object to initialize.
* @param parent_style An SVG style object to copy values from, or NULL,
* in which case defaults will be used.
* \ingroup DiaSvg
*/
void
dia_svg_style_init(DiaSvgStyle *gs, DiaSvgStyle *parent_style)
{
g_return_if_fail (gs);
gs->stroke = parent_style ? parent_style->stroke : DIA_SVG_COLOUR_DEFAULT;
gs->stroke_opacity = parent_style ? parent_style->stroke_opacity : 1.0;
gs->line_width = parent_style ? parent_style->line_width : 0.0;
gs->linestyle = parent_style ? parent_style->linestyle : DIA_LINE_STYLE_SOLID;
gs->dashlength = parent_style ? parent_style->dashlength : 1;
/* http://www.w3.org/TR/SVG/painting.html#FillProperty - default black
* but we still have to see the difference
*/
gs->fill = parent_style ? parent_style->fill : DIA_SVG_COLOUR_DEFAULT;
gs->fill_opacity = parent_style ? parent_style->fill_opacity : 1.0;
gs->linecap = parent_style ? parent_style->linecap : DIA_LINE_CAPS_DEFAULT;
gs->linejoin = parent_style ? parent_style->linejoin : DIA_LINE_JOIN_DEFAULT;
gs->linestyle = parent_style ? parent_style->linestyle : DIA_LINE_STYLE_DEFAULT;
gs->font = (parent_style && parent_style->font) ? g_object_ref (parent_style->font) : NULL;
gs->font_height = parent_style ? parent_style->font_height : 0.8;
gs->alignment = parent_style ? parent_style->alignment : DIA_ALIGN_LEFT;
gs->stop_color = parent_style ? parent_style->stop_color : 0x000000; /* default black */
gs->stop_opacity = parent_style ? parent_style->stop_opacity : 1.0;
}
/*!
* \brief Copy style values from one SVG style object to another.
* @param dest SVG style object to copy to.
* @param src SVG style object to copy from.
* \ingroup DiaSvg
*/
void
dia_svg_style_copy(DiaSvgStyle *dest, DiaSvgStyle *src)
{
g_return_if_fail (dest && src);
dest->stroke = src->stroke;
dest->stroke_opacity = src->stroke_opacity;
dest->line_width = src->line_width;
dest->linestyle = src->linestyle;
dest->dashlength = src->dashlength;
dest->fill = src->fill;
dest->fill_opacity = src->fill_opacity;
g_clear_object (&dest->font);
dest->font = src->font ? g_object_ref (src->font) : NULL;
dest->font_height = src->font_height;
dest->alignment = src->alignment;
dest->stop_color = src->stop_color;
dest->stop_opacity = src->stop_opacity;
}
static const struct _SvgNamedColor {
const gint value;
const char *name;
} _svg_named_colors [] = {
/* complete list copied from sodipodi source */
{ 0xF0F8FF, "aliceblue" },
{ 0xFAEBD7, "antiquewhite" },
{ 0x00FFFF, "aqua" },
{ 0x7FFFD4, "aquamarine" },
{ 0xF0FFFF, "azure" },
{ 0xF5F5DC, "beige" },
{ 0xFFE4C4, "bisque" },
{ 0x000000, "black" },
{ 0xFFEBCD, "blanchedalmond" },
{ 0x0000FF, "blue" },
{ 0x8A2BE2, "blueviolet" },
{ 0xA52A2A, "brown" },
{ 0xDEB887, "burlywood" },
{ 0x5F9EA0, "cadetblue" },
{ 0x7FFF00, "chartreuse" },
{ 0xD2691E, "chocolate" },
{ 0xFF7F50, "coral" },
{ 0x6495ED, "cornflowerblue" },
{ 0xFFF8DC, "cornsilk" },
{ 0xDC143C, "crimson" },
{ 0x00FFFF, "cyan" },
{ 0x00008B, "darkblue" },
{ 0x008B8B, "darkcyan" },
{ 0xB8860B, "darkgoldenrod" },
{ 0xA9A9A9, "darkgray" },
{ 0x006400, "darkgreen" },
{ 0xA9A9A9, "darkgrey" },
{ 0xBDB76B, "darkkhaki" },
{ 0x8B008B, "darkmagenta" },
{ 0x556B2F, "darkolivegreen" },
{ 0xFF8C00, "darkorange" },
{ 0x9932CC, "darkorchid" },
{ 0x8B0000, "darkred" },
{ 0xE9967A, "darksalmon" },
{ 0x8FBC8F, "darkseagreen" },
{ 0x483D8B, "darkslateblue" },
{ 0x2F4F4F, "darkslategray" },
{ 0x2F4F4F, "darkslategrey" },
{ 0x00CED1, "darkturquoise" },
{ 0x9400D3, "darkviolet" },
{ 0xFF1493, "deeppink" },
{ 0x00BFFF, "deepskyblue" },
{ 0x696969, "dimgray" },
{ 0x696969, "dimgrey" },
{ 0x1E90FF, "dodgerblue" },
{ 0xB22222, "firebrick" },
{ 0xFFFAF0, "floralwhite" },
{ 0x228B22, "forestgreen" },
{ 0xFF00FF, "fuchsia" },
{ 0xDCDCDC, "gainsboro" },
{ 0xF8F8FF, "ghostwhite" },
{ 0xFFD700, "gold" },
{ 0xDAA520, "goldenrod" },
{ 0x808080, "gray" },
{ 0x008000, "green" },
{ 0xADFF2F, "greenyellow" },
{ 0x808080, "grey" },
{ 0xF0FFF0, "honeydew" },
{ 0xFF69B4, "hotpink" },
{ 0xCD5C5C, "indianred" },
{ 0x4B0082, "indigo" },
{ 0xFFFFF0, "ivory" },
{ 0xF0E68C, "khaki" },
{ 0xE6E6FA, "lavender" },
{ 0xFFF0F5, "lavenderblush" },
{ 0x7CFC00, "lawngreen" },
{ 0xFFFACD, "lemonchiffon" },
{ 0xADD8E6, "lightblue" },
{ 0xF08080, "lightcoral" },
{ 0xE0FFFF, "lightcyan" },
{ 0xFAFAD2, "lightgoldenrodyellow" },
{ 0xD3D3D3, "lightgray" },
{ 0x90EE90, "lightgreen" },
{ 0xD3D3D3, "lightgrey" },
{ 0xFFB6C1, "lightpink" },
{ 0xFFA07A, "lightsalmon" },
{ 0x20B2AA, "lightseagreen" },
{ 0x87CEFA, "lightskyblue" },
{ 0x778899, "lightslategray" },
{ 0x778899, "lightslategrey" },
{ 0xB0C4DE, "lightsteelblue" },
{ 0xFFFFE0, "lightyellow" },
{ 0x00FF00, "lime" },
{ 0x32CD32, "limegreen" },
{ 0xFAF0E6, "linen" },
{ 0xFF00FF, "magenta" },
{ 0x800000, "maroon" },
{ 0x66CDAA, "mediumaquamarine" },
{ 0x0000CD, "mediumblue" },
{ 0xBA55D3, "mediumorchid" },
{ 0x9370DB, "mediumpurple" },
{ 0x3CB371, "mediumseagreen" },
{ 0x7B68EE, "mediumslateblue" },
{ 0x00FA9A, "mediumspringgreen" },
{ 0x48D1CC, "mediumturquoise" },
{ 0xC71585, "mediumvioletred" },
{ 0x191970, "midnightblue" },
{ 0xF5FFFA, "mintcream" },
{ 0xFFE4E1, "mistyrose" },
{ 0xFFE4B5, "moccasin" },
{ 0xFFDEAD, "navajowhite" },
{ 0x000080, "navy" },
{ 0xFDF5E6, "oldlace" },
{ 0x808000, "olive" },
{ 0x6B8E23, "olivedrab" },
{ 0xFFA500, "orange" },
{ 0xFF4500, "orangered" },
{ 0xDA70D6, "orchid" },
{ 0xEEE8AA, "palegoldenrod" },
{ 0x98FB98, "palegreen" },
{ 0xAFEEEE, "paleturquoise" },
{ 0xDB7093, "palevioletred" },
{ 0xFFEFD5, "papayawhip" },
{ 0xFFDAB9, "peachpuff" },
{ 0xCD853F, "peru" },
{ 0xFFC0CB, "pink" },
{ 0xDDA0DD, "plum" },
{ 0xB0E0E6, "powderblue" },
{ 0x800080, "purple" },
{ 0xFF0000, "red" },
{ 0xBC8F8F, "rosybrown" },
{ 0x4169E1, "royalblue" },
{ 0x8B4513, "saddlebrown" },
{ 0xFA8072, "salmon" },
{ 0xF4A460, "sandybrown" },
{ 0x2E8B57, "seagreen" },
{ 0xFFF5EE, "seashell" },
{ 0xA0522D, "sienna" },
{ 0xC0C0C0, "silver" },
{ 0x87CEEB, "skyblue" },
{ 0x6A5ACD, "slateblue" },
{ 0x708090, "slategray" },
{ 0x708090, "slategrey" },
{ 0xFFFAFA, "snow" },
{ 0x00FF7F, "springgreen" },
{ 0x4682B4, "steelblue" },
{ 0xD2B48C, "tan" },
{ 0x008080, "teal" },
{ 0xD8BFD8, "thistle" },
{ 0xFF6347, "tomato" },
{ 0x40E0D0, "turquoise" },
{ 0xEE82EE, "violet" },
{ 0xF5DEB3, "wheat" },
{ 0xFFFFFF, "white" },
{ 0xF5F5F5, "whitesmoke" },
{ 0xFFFF00, "yellow" },
{ 0x9ACD32, "yellowgreen" }
};
static int
_cmp_color (const void *key, const void *elem)
{
const char *a = key;
const struct _SvgNamedColor *color = elem;
return strcmp (a, color->name);
}
/*!
* \brief Get an SVG color value by name
*
* The list of named SVG tiny colors has only 17 entries according to
* http://www.w3.org/TR/CSS21/syndata.html#color-units
* Still pango_color_parse() does not support seven of them including
* 'white'. This function supports all of them.
* Against the SVG full specification (and the SVG Test Suite) pango's
* long list is still missing colors, e.g. crimson. So this function is
* using a supposed to be complete internal list.
*
* \ingroup DiaSvg
*/
static gboolean
svg_named_color (const char *name, gint32 *color)
{
const struct _SvgNamedColor *elem;
g_return_val_if_fail (name != NULL && color != NULL, FALSE);
elem = bsearch (name, _svg_named_colors,
G_N_ELEMENTS(_svg_named_colors), sizeof(_svg_named_colors[0]),
_cmp_color);
if (elem) {
*color = elem->value;
return TRUE;
}
return FALSE;
}
/*!
* \brief Parse an SVG color description.
*
* @param color A place to store the color information (0RGB)
* @param str An SVG color description string to parse.
* @return TRUE if parsing was successful.
*
* This function is rather tolerant compared to the SVG specification.
* It supports special names like 'fg', 'bg', 'foregroumd', 'background';
* three numeric representations: '\#FF0000', 'rgb(1.0,0.0,0.0), 'rgb(100%,0%,0%)'
* and named colors from two domains: SVG and Pango.
*
* \note Shouldn't we use an actual Dia Color object as return value?
* Would require that the DiaSvgStyle object uses that, too. If we did that,
* we could even return the color object directly, and we would be able to use
* >8 bits per channel.
* But we would not be able to handle named colors anymore ...
*
* \ingroup DiaSvg
*/
static gboolean
_parse_color(gint32 *color, const char *str)
{
if (str[0] == '#') {
char *endp = NULL;
guint32 val = strtol(str+1, &endp, 16);
if (endp - (str + 1) > 3) /* no 16-bit color here */
*color = val & 0xffffff;
else /* weak estimation: Pango is reusing bits to fill */
*color = ((0xF & val)<<4) | ((0xF0 & val)<<8) | (((0xF00 & val)>>4)<<16);
} else if (0 == strncmp(str, "none", 4))
*color = DIA_SVG_COLOUR_NONE;
else if (0 == strncmp(str, "foreground", 10) || 0 == strncmp(str, "fg", 2) ||
0 == strncmp(str, "inverse", 7))
*color = DIA_SVG_COLOUR_FOREGROUND;
else if (0 == strncmp(str, "background", 10) || 0 == strncmp(str, "bg", 2) ||
0 == strncmp(str, "default", 7))
*color = DIA_SVG_COLOUR_BACKGROUND;
else if (0 == strcmp(str, "text"))
*color = DIA_SVG_COLOUR_TEXT;
else if (0 == strcmp(str, "currentColor"))
*color = _current_color;
else if (0 == strncmp(str, "rgb(", 4)) {
int r = 0, g = 0, b = 0;
if (3 == sscanf (str+4, "%d,%d,%d", &r, &g, &b)) {
/* Set alpha to 1.0 */
*color = ((0xFF<<24) & 0xFF000000) | ((r<<16) & 0xFF0000) | ((g<<8) & 0xFF00) | (b & 0xFF);
} else if (strchr (str+4, '%')) {
/* e.g. cairo uses percent values */
char **vals = g_strsplit (str+4, "%,", -1);
int i;
*color = 0xFF000000;
for (i = 0; vals[i] && i < 3; ++i)
*color |= ((int)(((255 * g_ascii_strtod(vals[i], NULL)) / 100))<<(16-(8*i)));
g_strfreev (vals);
} else {
return FALSE;
}
} else if (0 == strncmp(str, "rgba(", 5)) {
int r = 0, g = 0, b = 0, a = 0;
if (4 == sscanf (str+4, "%d,%d,%d,%d", &r, &g, &b, &a))
*color = ((a<<24) & 0xFF000000) | ((r<<16) & 0xFF0000) | ((g<<8) & 0xFF00) | (b & 0xFF);
else
return FALSE;
} else {
char* se = strchr (str, ';');
if (!se) /* style might have trailign space */
se = strchr (str, ' ');
if (!se) {
return svg_named_color (str, color);
} else {
/* need to make a copy of the color only */
gboolean ret;
char *sc = g_strndup (str, se - str);
ret = svg_named_color (sc, color);
g_clear_pointer (&sc, g_free);
return ret;
}
}
return TRUE;
}
/*!
* \brief Convert a string to a color
*
* SVG spec also allows 'inherit' as color value, which leads
* to false here. Should still mostly work because the color
* is supposed to be initialized before.
*
* \ingroup DiaSvg
*/
gboolean
dia_svg_parse_color (const char *str, Color *color)
{
gint32 c;
gboolean ret = _parse_color (&c, str);
if (ret) {
color->red = ((c & 0xff0000) >> 16) / 255.0;
color->green = ((c & 0x00ff00) >> 8) / 255.0;
color->blue = (c & 0x0000ff) / 255.0;
color->alpha = 1.0;
}
return ret;
}
enum
{
FONT_NAME_LENGTH_MAX = 40
};
static void
_parse_dasharray (DiaSvgStyle *s, double user_scale, char *str, char **end)
{
char *ptr;
/* by also splitting on ';' we can also parse the continued style string */
char **dashes = g_regex_split_simple ("[\\s,;]+", (char *) str, 0, 0);
int n = 0;
double dl;
s->dashlength = g_ascii_strtod(str, &ptr);
if (s->dashlength <= 0.0) {
/* e.g. "none" */
s->linestyle = DIA_LINE_STYLE_SOLID;
} else if (user_scale > 0) {
s->dashlength /= user_scale;
}
if (s->dashlength) { /* at least one value */
while (dashes[n] && g_ascii_strtod (dashes[n], NULL) > 0) {
++n; /* Dia can not do arbitrary length, the number of dashes gives the style */
}
}
if (n > 0) {
s->dashlength = g_ascii_strtod (dashes[0], NULL);
}
if (user_scale > 0) {
s->dashlength /= user_scale;
}
switch (n) {
case 0:
s->linestyle = DIA_LINE_STYLE_SOLID;
break;
case 1:
s->linestyle = DIA_LINE_STYLE_DASHED;
break;
case 2:
dl = g_ascii_strtod (dashes[1], NULL);
if (user_scale > 0) {
dl /= user_scale;
}
if (dl < s->line_width || dl > s->dashlength) {
/* the difference is arbitrary */
s->linestyle = DIA_LINE_STYLE_DOTTED;
s->dashlength *= 10.0; /* dot = 10% of len */
} else {
s->linestyle = DIA_LINE_STYLE_DASHED;
}
break;
case 4:
s->linestyle = DIA_LINE_STYLE_DASH_DOT;
break;
default :
/* If an odd number of values is provided, then the list of values is repeated to
* yield an even number of values. Thus, stroke-dasharray: 5,3,2 is equivalent to
* stroke-dasharray: 5,3,2,5,3,2.
*/
case 6:
s->linestyle = DIA_LINE_STYLE_DASH_DOT_DOT;
break;
}
g_strfreev (dashes);
if (end)
*end = ptr;
}
static void
_parse_linejoin (DiaSvgStyle *s, const char *val)
{
if (!strncmp (val, "miter", 5)) {
s->linejoin = DIA_LINE_JOIN_MITER;
} else if (!strncmp (val, "round", 5)) {
s->linejoin = DIA_LINE_JOIN_ROUND;
} else if (!strncmp (val, "bevel", 5)) {
s->linejoin = DIA_LINE_JOIN_BEVEL;
} else if (!strncmp (val, "default", 7)) {
s->linejoin = DIA_LINE_JOIN_DEFAULT;
}
}
static void
_parse_linecap (DiaSvgStyle *s, const char *val)
{
if (!strncmp(val, "butt", 4))
s->linecap = DIA_LINE_CAPS_BUTT;
else if (!strncmp(val, "round", 5))
s->linecap = DIA_LINE_CAPS_ROUND;
else if (!strncmp(val, "square", 6) || !strncmp(val, "projecting", 10))
s->linecap = DIA_LINE_CAPS_PROJECTING;
else if (!strncmp(val, "default", 7))
s->linecap = DIA_LINE_CAPS_DEFAULT;
}
/*!
* \brief Given any of the three parameters adjust the font
* @param s Dia SVG style to modify
* @param family comma-separated list of family names
* @param style font slant string
* @param weight font weight string
*/
static void
_style_adjust_font (DiaSvgStyle *s, const char *family, const char *style, const char *weight)
{
g_clear_object (&s->font);
/* given font_height is bogus, especially if not given at all
* or without unit ... see bug 665648 about invalid CSS
*/
s->font = dia_font_new_from_style (DIA_FONT_SANS, s->font_height > 0 ? s->font_height : 1.0);
if (family) {
/* SVG allows a list of families here, also there is some strange formatting
* seen, like 'Arial'. If the given family name can not be resolved by
* Pango it complaints loudly with g_warning().
*/
char **families = g_strsplit (family, ",", -1);
int i = 0;
gboolean found = FALSE;
while (!found && families[i]) {
const char *chomped = g_strchomp (g_strdelimit (families[i], "'", ' '));
PangoFont *loaded;
dia_font_set_any_family(s->font, chomped);
loaded = pango_context_load_font (dia_font_get_context (),
dia_font_get_description (s->font));
if (loaded) {
g_clear_object (&loaded);
found = TRUE;
}
++i;
}
if (!found) {
dia_font_set_any_family (s->font, "sans");
}
g_strfreev (families);
}
if (style) {
dia_font_set_slant_from_string (s->font, style);
}
if (weight) {
dia_font_set_weight_from_string (s->font, weight);
}
}
static void
_parse_text_align (DiaSvgStyle *s, const char *ptr)
{
if (!strncmp (ptr, "start", 5)) {
s->alignment = DIA_ALIGN_LEFT;
} else if (!strncmp (ptr, "end", 3)) {
s->alignment = DIA_ALIGN_RIGHT;
} else if (!strncmp (ptr, "middle", 6)) {
s->alignment = DIA_ALIGN_CENTRE;
}
}
/*!
* \brief Parse SVG/CSS style string
*
* Parse as much information from the given style string as Dia can handle.
* There are still known limitations:
* - does not follow references to somewhere inside or outside the string
* (e.g. url(...), color and currentColor)
* - font parsing should be extended to support lists of fonts somehow
*
* \ingroup DiaSvg
*/
void
dia_svg_parse_style_string (DiaSvgStyle *s, double user_scale, const char *str)
{
int i = 0;
char *ptr = (char *) str;
char *family = NULL, *style = NULL, *weight = NULL;
while (ptr[0] != '\0') {
/* skip white space at start */
while (ptr[0] != '\0' && g_ascii_isspace(ptr[0])) ptr++;
if (ptr[0] == '\0') break;
if (!strncmp("font-family:", ptr, 12)) {
ptr += 12;
while ((ptr[0] != '\0') && g_ascii_isspace(ptr[0])) ptr++;
i = 0;
while (ptr[i] != '\0' && ptr[i] != ';') ++i;
/* with i==0 we fall back to 'sans' too */
if (strncmp (ptr, "sanserif", i) == 0 || strncmp (ptr, "sans-serif", i) == 0)
family = g_strdup ("sans"); /* special name adaption */
else
family = i > 0 ? g_strndup(ptr, i) : NULL;
ptr += i;
} else if (!strncmp("font-weight:", ptr, 12)) {
ptr += 12;
while ((ptr[0] != '\0') && g_ascii_isspace(ptr[0])) ptr++;
i = 0;
while (ptr[i] != '\0' && ptr[i] != ';') ++i;
weight = i > 0 ? g_strndup (ptr, i) : NULL;
ptr += i;
} else if (!strncmp("font-style:", ptr, 11)) {
ptr += 11;
while ((ptr[0] != '\0') && g_ascii_isspace(ptr[0])) ptr++;
i = 0;
while (ptr[i] != '\0' && ptr[i] != ';') ++i;
style = i > 0 ? g_strndup(ptr, i) : NULL;
ptr += i;
} else if (!strncmp("font-size:", ptr, 10)) {
ptr += 10;
while ((ptr[0] != '\0') && g_ascii_isspace(ptr[0])) ptr++;
i = 0;
while (ptr[i] != '\0' && ptr[i] != ';') ++i;
s->font_height = g_ascii_strtod(ptr, NULL);
ptr += i;
if (user_scale > 0)
s->font_height /= user_scale;
} else if (!strncmp("text-anchor:", ptr, 12)) {
ptr += 12;
while ((ptr[0] != '\0') && g_ascii_isspace(ptr[0])) ptr++;
_parse_text_align(s, ptr);
} else if (!strncmp("stroke-width:", ptr, 13)) {
ptr += 13;
s->line_width = g_ascii_strtod(ptr, &ptr);
if (user_scale > 0)
s->line_width /= user_scale;
} else if (!strncmp("stroke:", ptr, 7)) {
ptr += 7;
while ((ptr[0] != '\0') && g_ascii_isspace(ptr[0])) ptr++;
if (ptr[0] == '\0') break;
if (!_parse_color (&s->stroke, ptr))
s->stroke = DIA_SVG_COLOUR_NONE;
} else if (!strncmp("stroke-opacity:", ptr, 15)) {
ptr += 15;
s->stroke_opacity = g_ascii_strtod(ptr, &ptr);
} else if (!strncmp("fill:", ptr, 5)) {
ptr += 5;
while (ptr[0] != '\0' && g_ascii_isspace(ptr[0])) ptr++;
if (ptr[0] == '\0') break;
if (!_parse_color (&s->fill, ptr))
s->fill = DIA_SVG_COLOUR_NONE;
} else if (!strncmp("fill-opacity:", ptr, 13)) {
ptr += 13;
s->fill_opacity = g_ascii_strtod(ptr, &ptr);
} else if (!strncmp("stop-color:", ptr, 11)) {
ptr += 11;
while (ptr[0] != '\0' && g_ascii_isspace(ptr[0])) ptr++;
if (ptr[0] == '\0') break;
if (!_parse_color (&s->stop_color, ptr))
s->stop_color = DIA_SVG_COLOUR_NONE;
} else if (!strncmp("stop-opacity:", ptr, 13)) {
ptr += 13;
s->stop_opacity = g_ascii_strtod(ptr, &ptr);
} else if (!strncmp("opacity", ptr, 7)) {
double opacity;
ptr += 7;
opacity = g_ascii_strtod(ptr, &ptr);
/* multiplicative effect of opacity */
s->stroke_opacity *= opacity;
s->fill_opacity *= opacity;
} else if (!strncmp("stroke-linecap:", ptr, 15)) {
ptr += 15;
while (ptr[0] != '\0' && g_ascii_isspace(ptr[0])) ptr++;
if (ptr[0] == '\0') break;
_parse_linecap (s, ptr);
} else if (!strncmp("stroke-linejoin:", ptr, 16)) {
ptr += 16;
while (ptr[0] != '\0' && g_ascii_isspace(ptr[0])) ptr++;
if (ptr[0] == '\0') break;
_parse_linejoin (s, ptr);
} else if (!strncmp("stroke-pattern:", ptr, 15)) {
/* Apparently not an offical SVG style attribute, but
* referenced in custom-shapes document. So we continue
* supporting it (read only).
*/
ptr += 15;
while (ptr[0] != '\0' && g_ascii_isspace(ptr[0])) ptr++;
if (ptr[0] == '\0') break;
if (!strncmp (ptr, "solid", 5)) {
s->linestyle = DIA_LINE_STYLE_SOLID;
} else if (!strncmp (ptr, "dashed", 6)) {
s->linestyle = DIA_LINE_STYLE_DASHED;
} else if (!strncmp (ptr, "dash-dot", 8)) {
s->linestyle = DIA_LINE_STYLE_DASH_DOT;
} else if (!strncmp (ptr, "dash-dot-dot", 12)) {
s->linestyle = DIA_LINE_STYLE_DASH_DOT_DOT;
} else if (!strncmp (ptr, "dotted", 6)) {
s->linestyle = DIA_LINE_STYLE_DOTTED;
} else if (!strncmp (ptr, "default", 7)) {
s->linestyle = DIA_LINE_STYLE_DEFAULT;
}
/* XXX: deal with a real pattern */
} else if (!strncmp ("stroke-dashlength:", ptr, 18)) {
ptr += 18;
while (ptr[0] != '\0' && g_ascii_isspace(ptr[0])) ptr++;
if (ptr[0] == '\0') break;
if (!strncmp(ptr, "default", 7))
s->dashlength = 1.0;
else {
s->dashlength = g_ascii_strtod(ptr, &ptr);
if (user_scale > 0)
s->dashlength /= user_scale;
}
} else if (!strncmp ("stroke-dasharray:", ptr, 17)) {
s->linestyle = DIA_LINE_STYLE_DASHED;
ptr += 17;
while (ptr[0] != '\0' && g_ascii_isspace(ptr[0])) ptr++;
if (ptr[0] == '\0') break;
if (!strncmp(ptr, "default", 7))
s->dashlength = 1.0;
else
_parse_dasharray (s, user_scale, ptr, &ptr);
}
/* skip up to the next attribute */
while (ptr[0] != '\0' && ptr[0] != ';' && ptr[0] != '\n') ptr++;
if (ptr[0] != '\0') ptr++;
}
if (family || style || weight) {
_style_adjust_font (s, family, style, weight);
g_clear_pointer (&family, g_free);
g_clear_pointer (&style, g_free);
g_clear_pointer (&weight, g_free);
}
}
/*!
* \brief Parse SVG style properties
*
* This function not only parses the style attribute of the given node
* it also extracts some of the style properties directly.
* @param node An XML node to parse a style from.
* @param s The SVG style object to fill out. This should previously be
* initialized to some default values.
* @param user_scale if >0 scalable values (font-size, stroke-width, ...)
* are divided by this, otherwise ignored
*
* \ingroup DiaSvg
*/
void
dia_svg_parse_style (xmlNodePtr node, DiaSvgStyle *s, double user_scale)
{
xmlChar *str;
str = xmlGetProp(node, (const xmlChar *)"style");
if (str) {
dia_svg_parse_style_string (s, user_scale, (char *)str);
xmlFree(str);
}
/* ugly svg variations, it is allowed to give style properties without
* the style attribute, i.e. direct attributes
*/
str = xmlGetProp(node, (const xmlChar *)"color");
if (str) {
int c;
if (_parse_color (&c, (char *) str))
_current_color = c;
xmlFree(str);
}
str = xmlGetProp(node, (const xmlChar *)"opacity");
if (str) {
double opacity = g_ascii_strtod ((char *) str, NULL);
/* multiplicative effect of opacity */
s->stroke_opacity *= opacity;
s->fill_opacity *= opacity;
xmlFree(str);
}
str = xmlGetProp(node, (const xmlChar *)"stop-color");
if (str) {
if (!_parse_color (&s->stop_color, (char *) str) && strcmp ((const char *) str, "inherit") != 0)
s->stop_color = DIA_SVG_COLOUR_NONE;
xmlFree(str);
}
str = xmlGetProp(node, (const xmlChar *)"stop-opacity");
if (str) {
s->stop_opacity = g_ascii_strtod((char *) str, NULL);
xmlFree(str);
}
str = xmlGetProp(node, (const xmlChar *)"fill");
if (str) {
if (!_parse_color (&s->fill, (char *) str) && strcmp ((const char *) str, "inherit") != 0)
s->fill = DIA_SVG_COLOUR_NONE;
xmlFree(str);
}
str = xmlGetProp(node, (const xmlChar *)"fill-opacity");
if (str) {
s->fill_opacity = g_ascii_strtod((char *) str, NULL);
xmlFree(str);
}
str = xmlGetProp(node, (const xmlChar *)"stroke");
if (str) {
if (!_parse_color (&s->stroke, (char *) str) && strcmp ((const char *) str, "inherit") != 0)
s->stroke = DIA_SVG_COLOUR_NONE;
xmlFree(str);
}
str = xmlGetProp(node, (const xmlChar *)"stroke-opacity");
if (str) {
s->stroke_opacity = g_ascii_strtod((char *) str, NULL);
xmlFree(str);
}
str = xmlGetProp(node, (const xmlChar *)"stroke-width");
if (str) {
s->line_width = g_ascii_strtod((char *) str, NULL);
xmlFree(str);
if (user_scale > 0)
s->line_width /= user_scale;
}
str = xmlGetProp(node, (const xmlChar *)"stroke-dasharray");
if (str) {
if (strcmp ((const char *)str, "inherit") != 0)
_parse_dasharray (s, user_scale, (char *)str, NULL);
xmlFree(str);
}
str = xmlGetProp(node, (const xmlChar *)"stroke-linejoin");
if (str) {
if (strcmp ((const char *)str, "inherit") != 0)
_parse_linejoin (s, (char *)str);
xmlFree(str);
}
str = xmlGetProp(node, (const xmlChar *)"stroke-linecap");
if (str) {
if (strcmp ((const char *)str, "inherit") != 0)
_parse_linecap (s, (char *)str);
xmlFree(str);
}
/* text-props, again ;( */
str = xmlGetProp(node, (const xmlChar *)"font-size");
if (str) {
/* for inherit we just leave the original value,
* should be initialized by parent style already
*/
if (strcmp ((const char *)str, "inherit") != 0) {
s->font_height = g_ascii_strtod ((char *)str, NULL);
if (user_scale > 0)
s->font_height /= user_scale;
}
xmlFree(str);
}
str = xmlGetProp(node, (const xmlChar *)"text-anchor");
if (str) {
_parse_text_align (s, (const char*) str);
xmlFree(str);
}
{
xmlChar *family = xmlGetProp(node, (const xmlChar *)"font-family");
xmlChar *slant = xmlGetProp(node, (const xmlChar *)"font-style");
xmlChar *weight = xmlGetProp(node, (const xmlChar *)"font-weight");
if (family || slant || weight) {
_style_adjust_font (s, (char *)family, (char *)slant, (char *)weight);
if (family)
xmlFree(family);
if (slant)
xmlFree(slant);
if (weight)
xmlFree(weight);
}
}
}
/**
* _path_arc_segment:
* @points: destination array of #BezPoint
* @xc: center x
* @yc: center y
* @th0: first angle
* @th1: second angle
* @rx: radius x
* @ry: radius y
* @x_axis_rotation: rotation of the axis
* @last_p2: the resulting current point
*
* Parse a SVG description of an arc segment.
*
* Code stolen from (and adapted)
* http://www.inkscape.org/doc/doxygen/html/svg-path_8cpp.php#a7
* which may have got it from rsvg, hope it is correct ;)
*
* If you want the description of the algorithm read the SVG specs:
* http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands
*/
static void
_path_arc_segment (GArray *points,
double xc,
double yc,
double th0,
double th1,
double rx,
double ry,
double x_axis_rotation,
Point *last_p2)
{
BezPoint bez;
double sin_th, cos_th;
double a00, a01, a10, a11;
double x1, y1, x2, y2, x3, y3;
double t;
double th_half;
sin_th = sin (x_axis_rotation * (M_PI / 180.0));
cos_th = cos (x_axis_rotation * (M_PI / 180.0));
/* inverse transform compared with rsvg_path_arc */
a00 = cos_th * rx;
a01 = -sin_th * ry;
a10 = sin_th * rx;
a11 = cos_th * ry;
th_half = 0.5 * (th1 - th0);
t = (8.0 / 3.0) * sin(th_half * 0.5) * sin(th_half * 0.5) / sin(th_half);
x1 = xc + cos (th0) - t * sin (th0);
y1 = yc + sin (th0) + t * cos (th0);
x3 = xc + cos (th1);
y3 = yc + sin (th1);
x2 = x3 + t * sin (th1);
y2 = y3 - t * cos (th1);
bez.type = BEZ_CURVE_TO;
bez.p1.x = a00 * x1 + a01 * y1;
bez.p1.y = a10 * x1 + a11 * y1;
bez.p2.x = a00 * x2 + a01 * y2;
bez.p2.y = a10 * x2 + a11 * y2;
bez.p3.x = a00 * x3 + a01 * y3;
bez.p3.y = a10 * x3 + a11 * y3;
*last_p2 = bez.p2;
g_array_append_val(points, bez);
}
/*
* Parse an SVG description of a full arc.
*/
static void
_path_arc (GArray *points,
double cpx,
double cpy,
double rx,
double ry,
double x_axis_rotation,
int large_arc_flag,
int sweep_flag,
double x,
double y,
Point *last_p2)
{
double sin_th, cos_th;
double a00, a01, a10, a11;
double x0, y0, x1, y1, xc, yc;
double d, sfactor, sfactor_sq;
double th0, th1, th_arc;
double px, py, pl;
int i, n_segs;
sin_th = sin (x_axis_rotation * (M_PI / 180.0));
cos_th = cos (x_axis_rotation * (M_PI / 180.0));
/*
* Correction of out-of-range radii as described in Appendix F.6.6:
*
* 1. Ensure radii are non-zero (Done?).
* 2. Ensure that radii are positive.
* 3. Ensure that radii are large enough.
*/
if(rx < 0.0) rx = -rx;
if(ry < 0.0) ry = -ry;
px = cos_th * (cpx - x) * 0.5 + sin_th * (cpy - y) * 0.5;
py = cos_th * (cpy - y) * 0.5 - sin_th * (cpx - x) * 0.5;
pl = (px * px) / (rx * rx) + (py * py) / (ry * ry);
if(pl > 1.0)
{
pl = sqrt(pl);
rx *= pl;
ry *= pl;
}
/* Proceed with computations as described in Appendix F.6.5 */
a00 = cos_th / rx;
a01 = sin_th / rx;
a10 = -sin_th / ry;
a11 = cos_th / ry;
x0 = a00 * cpx + a01 * cpy;
y0 = a10 * cpx + a11 * cpy;
x1 = a00 * x + a01 * y;
y1 = a10 * x + a11 * y;
/* (x0, y0) is current point in transformed coordinate space.
(x1, y1) is new point in transformed coordinate space.
The arc fits a unit-radius circle in this space.
*/
d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0);
sfactor_sq = 1.0 / d - 0.25;
if (sfactor_sq < 0) sfactor_sq = 0;
sfactor = sqrt (sfactor_sq);
if (sweep_flag == large_arc_flag) sfactor = -sfactor;
xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0);
yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0);
/* (xc, yc) is center of the circle. */
th0 = atan2 (y0 - yc, x0 - xc);
th1 = atan2 (y1 - yc, x1 - xc);
th_arc = th1 - th0;
if (th_arc < 0 && sweep_flag)
th_arc += 2 * M_PI;
else if (th_arc > 0 && !sweep_flag)
th_arc -= 2 * M_PI;
n_segs = (int) ceil (fabs (th_arc / (M_PI * 0.5 + 0.001)));
for (i = 0; i < n_segs; i++) {
_path_arc_segment(points, xc, yc,
th0 + i * th_arc / n_segs,
th0 + (i + 1) * th_arc / n_segs,
rx, ry, x_axis_rotation,
last_p2);
}
}
/* routine to chomp off the start of the string */
#define path_chomp(path) while (path[0]!='\0'&&strchr(" \t\n\r,", path[0])) path++
/**
* dia_svg_parse_path:
* @path_str: A string describing an SVG path.
* @unparsed: The position in @path_str where parsing ended, or %NULL if
* the string was completely parsed. This should be used for
* calling the function until it is fully parsed.
* @closed: Whether the path was closed.
* @current_point: to retain it over splitting
*
* Takes SVG path content and converts it in an array of BezPoint.
*
* SVG pathes can contain multiple MOVE_TO commands while Dia's bezier
* object can only contain one so you may need to call this function
* multiple times.
*
* @bug This function is way too long (324 lines). So dont touch it. please!
* Shouldn't we try to turn straight lines, simple arc, polylines and
* zigzaglines into their appropriate objects? Could either be done by
* returning an object or by having functions that try parsing as
* specific simple paths.
* NOPE: Dia is capable to handle beziers and the file has given us some so
* WHY should be break it in to pieces ???
*
* Returns: %TRUE if there is any useful data in parsed to points
*/
gboolean
dia_svg_parse_path (GArray *points,
const char *path_str,
char **unparsed,
gboolean *closed,
Point *current_point)
{
enum {
PATH_MOVE, PATH_LINE, PATH_HLINE, PATH_VLINE, PATH_CURVE,
PATH_SMOOTHCURVE, PATH_QUBICCURVE, PATH_TTQCURVE,
PATH_ARC, PATH_CLOSE, PATH_END } last_type = PATH_MOVE;
Point last_open = {0.0, 0.0};
Point last_point = {0.0, 0.0};
Point last_control = {0.0, 0.0};
gboolean last_relative = FALSE;
BezPoint bez = { 0, };
char *path = (char *)path_str;
gboolean need_next_element = FALSE;
/* we can grow the same array in multiple steps */
gsize points_at_start = points->len;
*closed = FALSE;
*unparsed = NULL;
/* when splitting into pieces, we have to maintain current_point accross them */
if (current_point)
last_point = *current_point;
path_chomp(path);
while (path[0] != '\0') {
#ifdef DEBUG_CUSTOM
g_printerr ("Path: %s\n", path);
#endif
/* check for a new command */
switch (path[0]) {
case 'M':
if (points->len - points_at_start > 0) {
need_next_element = TRUE;
goto MORETOPARSE;
}
path++;
path_chomp(path);
last_type = PATH_MOVE;
last_relative = FALSE;
break;
case 'm':
if (points->len - points_at_start > 0) {
need_next_element = TRUE;
goto MORETOPARSE;
}
path++;
path_chomp(path);
last_type = PATH_MOVE;
last_relative = TRUE;
break;
case 'L':
path++;
path_chomp(path);
last_type = PATH_LINE;
last_relative = FALSE;
break;
case 'l':
path++;
path_chomp(path);
last_type = PATH_LINE;
last_relative = TRUE;
break;
case 'H':
path++;
path_chomp(path);
last_type = PATH_HLINE;
last_relative = FALSE;
break;
case 'h':
path++;
path_chomp(path);
last_type = PATH_HLINE;
last_relative = TRUE;
break;
case 'V':
path++;
path_chomp(path);
last_type = PATH_VLINE;
last_relative = FALSE;
break;
case 'v':
path++;
path_chomp(path);
last_type = PATH_VLINE;
last_relative = TRUE;
break;
case 'C':
path++;
path_chomp(path);
last_type = PATH_CURVE;
last_relative = FALSE;
break;
case 'c':
path++;
path_chomp(path);
last_type = PATH_CURVE;
last_relative = TRUE;
break;
case 'S':
path++;
path_chomp(path);
last_type = PATH_SMOOTHCURVE;
last_relative = FALSE;
break;
case 's':
path++;
path_chomp(path);
last_type = PATH_SMOOTHCURVE;
last_relative = TRUE;
break;
case 'q':
path++;
path_chomp(path);
last_type = PATH_QUBICCURVE;
last_relative = TRUE;
break;
case 'Q':
path++;
path_chomp(path);
last_type = PATH_QUBICCURVE;
last_relative = FALSE;
break;
case 't':
path++;
path_chomp(path);
last_type = PATH_TTQCURVE;
last_relative = TRUE;
break;
case 'T':
path++;
path_chomp(path);
last_type = PATH_TTQCURVE;
last_relative = FALSE;
break;
case 'Z':
case 'z':
path++;
path_chomp(path);
last_type = PATH_CLOSE;
last_relative = FALSE;
break;
case 'A':
path++;
path_chomp(path);
last_type = PATH_ARC;
last_relative = FALSE;
break;
case 'a':
path++;
path_chomp(path);
last_type = PATH_ARC;
last_relative = TRUE;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
case '+':
case '-':
if (last_type == PATH_CLOSE) {
g_warning("parse_path: argument given for implicite close path");
/* consume one number so we don't fall into an infinite loop */
while (path != NULL && strchr("0123456789.+-", path[0])) path++;
path_chomp(path);
*closed = TRUE;
need_next_element = TRUE;
goto MORETOPARSE;
}
break;
default:
g_warning("unsupported path code '%c'", path[0]);
last_type = PATH_END;
path++;
path_chomp(path);
break;
}
/* actually parse the path component */
switch (last_type) {
case PATH_MOVE:
if (points->len - points_at_start > 1) {
g_warning ("Only first point should be 'move'");
}
bez.type = BEZ_MOVE_TO;
bez.p1.x = g_ascii_strtod (path, &path);
path_chomp (path);
bez.p1.y = g_ascii_strtod (path, &path);
path_chomp (path);
if (last_relative) {
bez.p1.x += last_point.x;
bez.p1.y += last_point.y;
}
last_point = bez.p1;
last_control = bez.p1;
last_open = bez.p1;
if (points->len - points_at_start == 1) {
/* stupid svg, but we can handle it */
g_array_index (points, BezPoint, 0) = bez;
} else {
g_array_append_val (points, bez);
}
/* [SVG11 8.3.2] If a moveto is followed by multiple pairs of coordinates,
* the subsequent pairs are treated as implicit lineto commands
*/
last_type = PATH_LINE;
break;
case PATH_LINE:
bez.type = BEZ_LINE_TO;
bez.p1.x = g_ascii_strtod (path, &path);
path_chomp (path);
bez.p1.y = g_ascii_strtod (path, &path);
path_chomp (path);
if (last_relative) {
bez.p1.x += last_point.x;
bez.p1.y += last_point.y;
}
/* Strictly speeaking it should not be necessary to assign the other
* two points. But it helps hiding a serious limitation with the
* standard bezier serialization, namely only saving one move-to
* and the rest as curve-to */
#define INIT_LINE_TO_AS_CURVE_TO bez.p3 = bez.p1; bez.p2 = last_point
INIT_LINE_TO_AS_CURVE_TO;
last_point = bez.p1;
last_control = bez.p1;
g_array_append_val (points, bez);
break;
case PATH_HLINE:
bez.type = BEZ_LINE_TO;
bez.p1.x = g_ascii_strtod (path, &path);
path_chomp (path);
bez.p1.y = last_point.y;
if (last_relative) {
bez.p1.x += last_point.x;
}
INIT_LINE_TO_AS_CURVE_TO;
last_point = bez.p1;
last_control = bez.p1;
g_array_append_val (points, bez);
break;
case PATH_VLINE:
bez.type = BEZ_LINE_TO;
bez.p1.x = last_point.x;
bez.p1.y = g_ascii_strtod (path, &path);
path_chomp (path);
if (last_relative) {
bez.p1.y += last_point.y;
}
INIT_LINE_TO_AS_CURVE_TO;
#undef INIT_LINE_TO_AS_CURVE_TO
last_point = bez.p1;
last_control = bez.p1;
g_array_append_val (points, bez);
break;
case PATH_CURVE:
bez.type = BEZ_CURVE_TO;
bez.p1.x = g_ascii_strtod (path, &path);
path_chomp (path);
bez.p1.y = g_ascii_strtod (path, &path);
path_chomp (path);
bez.p2.x = g_ascii_strtod (path, &path);
path_chomp (path);
bez.p2.y = g_ascii_strtod (path, &path);
path_chomp (path);
bez.p3.x = g_ascii_strtod (path, &path);
path_chomp (path);
bez.p3.y = g_ascii_strtod (path, &path);
path_chomp (path);
if (last_relative) {
bez.p1.x += last_point.x;
bez.p1.y += last_point.y;
bez.p2.x += last_point.x;
bez.p2.y += last_point.y;
bez.p3.x += last_point.x;
bez.p3.y += last_point.y;
}
last_point = bez.p3;
last_control = bez.p2;
g_array_append_val (points, bez);
break;
case PATH_SMOOTHCURVE:
bez.type = BEZ_CURVE_TO;
bez.p1.x = 2 * last_point.x - last_control.x;
bez.p1.y = 2 * last_point.y - last_control.y;
bez.p2.x = g_ascii_strtod (path, &path);
path_chomp (path);
bez.p2.y = g_ascii_strtod (path, &path);
path_chomp (path);
bez.p3.x = g_ascii_strtod (path, &path);
path_chomp (path);
bez.p3.y = g_ascii_strtod (path, &path);
path_chomp (path);
if (last_relative) {
bez.p2.x += last_point.x;
bez.p2.y += last_point.y;
bez.p3.x += last_point.x;
bez.p3.y += last_point.y;
}
last_point = bez.p3;
last_control = bez.p2;
g_array_append_val (points, bez);
break;
case PATH_QUBICCURVE: {
/* raise quadratic bezier to cubic (copied from librsvg) */
double x1, y1;
x1 = g_ascii_strtod (path, &path);
path_chomp (path);
y1 = g_ascii_strtod (path, &path);
path_chomp (path);
if (last_relative) {
x1 += last_point.x;
y1 += last_point.y;
}
bez.type = BEZ_CURVE_TO;
bez.p1.x = (last_point.x + 2 * x1) * (1.0 / 3.0);
bez.p1.y = (last_point.y + 2 * y1) * (1.0 / 3.0);
bez.p3.x = g_ascii_strtod (path, &path);
path_chomp (path);
bez.p3.y = g_ascii_strtod (path, &path);
path_chomp (path);
if (last_relative) {
bez.p3.x += last_point.x;
bez.p3.y += last_point.y;
}
bez.p2.x = (bez.p3.x + 2 * x1) * (1.0 / 3.0);
bez.p2.y = (bez.p3.y + 2 * y1) * (1.0 / 3.0);
last_point = bez.p3;
last_control.x = x1;
last_control.y = y1;
g_array_append_val (points, bez);
}
break;
case PATH_TTQCURVE:
{
/* Truetype quadratic bezier curveto */
double xc, yc; /* quadratic control point */
xc = 2 * last_point.x - last_control.x;
yc = 2 * last_point.y - last_control.y;
/* generate a quadratic bezier with control point = xc, yc */
bez.type = BEZ_CURVE_TO;
bez.p1.x = (last_point.x + 2 * xc) * (1.0 / 3.0);
bez.p1.y = (last_point.y + 2 * yc) * (1.0 / 3.0);
bez.p3.x = g_ascii_strtod (path, &path);
path_chomp (path);
bez.p3.y = g_ascii_strtod (path, &path);
path_chomp (path);
if (last_relative) {
bez.p3.x += last_point.x;
bez.p3.y += last_point.y;
}
bez.p2.x = (bez.p3.x + 2 * xc) * (1.0 / 3.0);
bez.p2.y = (bez.p3.y + 2 * yc) * (1.0 / 3.0);
last_point = bez.p3;
last_control.x = xc;
last_control.y = yc;
g_array_append_val (points, bez);
}
break;
case PATH_ARC:
{
double rx, ry;
double xrot;
int largearc, sweep;
Point dest, dest_c;
dest_c.x=0;
dest_c.y=0;
rx = g_ascii_strtod (path, &path);
path_chomp (path);
ry = g_ascii_strtod (path, &path);
path_chomp (path);
#if 1 /* ok if it is all properly separated */
xrot = g_ascii_strtod (path, &path);
path_chomp (path);
largearc = (int) g_ascii_strtod (path, &path);
path_chomp (path);
sweep = (int) g_ascii_strtod (path, &path);
path_chomp (path);
#else
/* Actually three flags, which might not be properly separated,
* but even with this paths-data-20-f.svg does not work. IMHO the
* test case is seriously borked and can only pass if parsing
* the arc is tweaked against the test. In other words that test
* looks like it is built against one specific implementation.
* Inkscape and librsvg fail, Firefox pass.
*/
xrot = path[0] == '0' ? 0.0 : 1.0; ++path;
path_chomp(path);
largearc = path[0] == '0' ? 0 : 1; ++path;
path_chomp(path);
sweep = path[0] == '0' ? 0 : 1; ++path;
path_chomp(path);
#endif
dest.x = g_ascii_strtod (path, &path);
path_chomp (path);
dest.y = g_ascii_strtod (path, &path);
path_chomp (path);
if (last_relative) {
dest.x += last_point.x;
dest.y += last_point.y;
}
/* avoid matherr with bogus values - just ignore them
* does happen e.g. with 'Chem-Widgets - clamp-large'
*/
if (last_point.x != dest.x || last_point.y != dest.y) {
_path_arc (points, last_point.x, last_point.y,
rx, ry, xrot, largearc, sweep, dest.x, dest.y,
&dest_c);
}
last_point = dest;
last_control = dest_c;
}
break;
case PATH_CLOSE:
/* close the path with a line - second condition to ignore single close */
if (!*closed && (points->len != points_at_start)) {
const BezPoint *bpe = &g_array_index (points, BezPoint, points->len-1);
/* if the last point already meets the first point dont add it again */
const Point pte = bpe->type == BEZ_CURVE_TO ? bpe->p3 : bpe->p1;
if (pte.x != last_open.x || pte.y != last_open.y) {
bez.type = BEZ_LINE_TO;
bez.p1 = last_open;
g_array_append_val (points, bez);
}
last_point = last_open;
}
*closed = TRUE;
need_next_element = TRUE;
break;
case PATH_END:
while (*path != '\0') {
path++;
}
need_next_element = FALSE;
break;
default:
g_return_val_if_reached (FALSE);
}
/* get rid of any ignorable characters */
path_chomp (path);
MORETOPARSE:
if (need_next_element) {
/* check if there really is more to be parsed */
if (path[0] != 0) {
*unparsed = path;
} else {
*unparsed = NULL;
}
break; /* while */
}
}
/* avoid returning an array with only one point (I'd say the exporter
* producing such is rather broken, but *our* bezier creation code
* would crash on it.
*/
if (points->len < 2) {
g_array_set_size (points, 0);
}
if (current_point) {
*current_point = last_point;
}
return (points->len > 1);
}
static gboolean
_parse_transform (const char *trans, graphene_matrix_t *m, double scale)
{
char **list;
char *p = strchr (trans, '(');
int i = 0;
while ( (*trans != '\0')
&& (*trans == ' ' || *trans == ',' || *trans == '\t' ||
*trans == '\n' || *trans == '\r')) {
++trans; /* skip whitespace */
}
if (!p || !*trans) {
return FALSE; /* silently fail */
}
list = g_regex_split_simple ("[\\s,]+", p + 1, 0, 0);
if (strncmp (trans, "matrix", 6) == 0) {
float xx = 0, yx = 0, xy = 0, yy = 0, x0 = 0, y0 = 0;
if (list[i]) {
xx = g_ascii_strtod (list[i], NULL);
++i;
}
if (list[i]) {
yx = g_ascii_strtod (list[i], NULL);
++i;
}
if (list[i]) {
xy = g_ascii_strtod (list[i], NULL);
++i;
}
if (list[i]) {
yy = g_ascii_strtod (list[i], NULL);
++i;
}
if (list[i]) {
x0 = g_ascii_strtod (list[i], NULL);
++i;
}
if (list[i]) {
y0 = g_ascii_strtod (list[i], NULL);
++i;
}
graphene_matrix_init_from_2d (m, xx, yx, xy, yy, x0 / scale, y0 / scale);
} else if (strncmp (trans, "translate", 9) == 0) {
double x0 = 0, y0 = 0;
if (list[i]) {
x0 = g_ascii_strtod (list[i], NULL);
++i;
}
if (list[i]) {
y0 = g_ascii_strtod (list[i], NULL);
++i;
}
graphene_matrix_init_translate (m, &GRAPHENE_POINT3D_INIT (x0 / scale, y0 / scale, 0));
} else if (strncmp (trans, "scale", 5) == 0) {
double xx = 0, yy = 0;
if (list[i]) {
xx = g_ascii_strtod (list[i], NULL);
++i;
}
if (list[i]) {
yy = g_ascii_strtod (list[i], NULL);
++i;
} else {
yy = xx;
}
graphene_matrix_init_scale (m, xx, yy, 1.0);
} else if (strncmp (trans, "rotate", 6) == 0) {
double angle = 0;
double cx = 0, cy = 0;
if (list[i]) {
angle = g_ascii_strtod (list[i], NULL);
++i;
} else {
g_warning ("transform=rotate no angle?");
}
/* FIXME: check with real world data, I'm uncertain */
/* rotate around the given offset */
if (list[i]) {
graphene_point3d_t point;
cx = g_ascii_strtod (list[i], NULL);
++i;
if (list[i]) {
cy = g_ascii_strtod (list[i], NULL);
++i;
} else {
cy = 0.0; /* if offsets don't come in pairs */
}
/* translate by -cx,-cy */
graphene_point3d_init (&point, -(cx / scale), -(cy / scale), 0);
graphene_matrix_init_translate (m, &point);
/* rotate by angle */
graphene_matrix_rotate_z (m, angle);
/* translate by cx,cy */
graphene_point3d_init (&point, cx / scale, cy / scale, 0);
graphene_matrix_translate (m, &point);
} else {
graphene_matrix_init_rotate (m, angle, graphene_vec3_z_axis ());
}
} else if (strncmp (trans, "skewX", 5) == 0) {
float skew = 0;
if (list[i]) {
skew = g_ascii_strtod (list[i], NULL);
}
graphene_matrix_init_skew (m, DIA_RADIANS (skew), 0);
} else if (strncmp (trans, "skewY", 5) == 0) {
float skew = 0;
if (list[i]) {
skew = g_ascii_strtod (list[i], NULL);
}
graphene_matrix_init_skew (m, 0, DIA_RADIANS (skew));
} else {
g_warning ("SVG: %s?", trans);
return FALSE;
}
g_clear_pointer (&list, g_strfreev);
return TRUE;
}
graphene_matrix_t *
dia_svg_parse_transform (const char *trans, double scale)
{
graphene_matrix_t *m = NULL;
char **transforms = g_regex_split_simple ("\\)", trans, 0, 0);
int i = 0;
/* go through the list of transformations - not that one would be enough ;) */
while (transforms[i]) {
graphene_matrix_t mat;
if (_parse_transform (transforms[i], &mat, scale)) {
if (!m) {
m = graphene_matrix_alloc ();
graphene_matrix_init_from_matrix (m, &mat);
} else {
graphene_matrix_multiply (m, &mat, m);
}
}
++i;
}
g_clear_pointer (&transforms, g_strfreev);
return m;
}
char *
dia_svg_from_matrix (const graphene_matrix_t *matrix, double scale)
{
/* transform="matrix(1,0,0,1,0,0)" */
char buf[G_ASCII_DTOSTR_BUF_SIZE];
GString *sm = g_string_new ("matrix(");
char *s;
g_ascii_formatd (buf,
sizeof (buf),
"%g",
graphene_matrix_get_value (matrix, 0, 0));
g_string_append (sm, buf);
g_string_append (sm, ",");
g_ascii_formatd (buf,
sizeof (buf),
"%g",
graphene_matrix_get_value (matrix, 0, 1));
g_string_append (sm, buf);
g_string_append (sm, ",");
g_ascii_formatd (buf,
sizeof (buf),
"%g",
graphene_matrix_get_value (matrix, 1, 0));
g_string_append (sm, buf);
g_string_append (sm, ",");
g_ascii_formatd (buf,
sizeof (buf),
"%g",
graphene_matrix_get_value (matrix, 1, 1));
g_string_append (sm, buf);
g_string_append (sm, ",");
g_ascii_formatd (buf,
sizeof (buf),
"%g",
graphene_matrix_get_x_translation (matrix) * scale);
g_string_append (sm, buf);
g_string_append (sm, ",");
g_ascii_formatd (buf,
sizeof (buf),
"%g",
graphene_matrix_get_y_translation (matrix) * scale);
g_string_append (sm, buf);
g_string_append (sm, ")");
s = sm->str;
g_string_free (sm, FALSE);
return s;
}
| Java |
/*
* Copyright (c) 2011, 2013, 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.
*/
#ifndef GLASS_WINDOW_H
#define GLASS_WINDOW_H
#include <gtk/gtk.h>
#include <X11/Xlib.h>
#include <jni.h>
#include <set>
#include <vector>
#include "glass_view.h"
enum WindowFrameType {
TITLED,
UNTITLED,
TRANSPARENT
};
enum WindowType {
NORMAL,
UTILITY,
POPUP
};
enum request_type {
REQUEST_NONE,
REQUEST_RESIZABLE,
REQUEST_NOT_RESIZABLE
};
struct WindowFrameExtents {
int top;
int left;
int bottom;
int right;
};
static const guint MOUSE_BUTTONS_MASK = (guint) (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK | GDK_BUTTON3_MASK);
enum BoundsType {
BOUNDSTYPE_CONTENT,
BOUNDSTYPE_WINDOW
};
struct WindowGeometry {
WindowGeometry(): final_width(), final_height(),
refx(), refy(), gravity_x(), gravity_y(), current_width(), current_height(), extents() {}
// estimate of the final width the window will get after all pending
// configure requests are processed by the window manager
struct {
int value;
BoundsType type;
} final_width;
struct {
int value;
BoundsType type;
} final_height;
float refx;
float refy;
float gravity_x;
float gravity_y;
// the last width which was configured or obtained from configure
// notification
int current_width;
// the last height which was configured or obtained from configure
// notification
int current_height;
WindowFrameExtents extents;
};
class WindowContextChild;
class WindowContextTop;
class WindowContext {
public:
virtual bool isEnabled() = 0;
virtual bool hasIME() = 0;
virtual bool filterIME(GdkEvent *) = 0;
virtual void enableOrResetIME() = 0;
virtual void disableIME() = 0;
virtual void paint(void* data, jint width, jint height) = 0;
virtual WindowFrameExtents get_frame_extents() = 0;
virtual void enter_fullscreen() = 0;
virtual void exit_fullscreen() = 0;
virtual void show_or_hide_children(bool) = 0;
virtual void set_visible(bool) = 0;
virtual bool is_visible() = 0;
virtual void set_bounds(int, int, bool, bool, int, int, int, int) = 0;
virtual void set_resizable(bool) = 0;
virtual void request_focus() = 0;
virtual void set_focusable(bool)= 0;
virtual bool grab_focus() = 0;
virtual bool grab_mouse_drag_focus() = 0;
virtual void ungrab_focus() = 0;
virtual void ungrab_mouse_drag_focus() = 0;
virtual void set_title(const char*) = 0;
virtual void set_alpha(double) = 0;
virtual void set_enabled(bool) = 0;
virtual void set_minimum_size(int, int) = 0;
virtual void set_maximum_size(int, int) = 0;
virtual void set_minimized(bool) = 0;
virtual void set_maximized(bool) = 0;
virtual void set_icon(GdkPixbuf*) = 0;
virtual void restack(bool) = 0;
virtual void set_cursor(GdkCursor*) = 0;
virtual void set_modal(bool, WindowContext* parent = NULL) = 0;
virtual void set_gravity(float, float) = 0;
virtual void set_level(int) = 0;
virtual void set_background(float, float, float) = 0;
virtual void process_property_notify(GdkEventProperty*) = 0;
virtual void process_configure(GdkEventConfigure*) = 0;
virtual void process_map() = 0;
virtual void process_focus(GdkEventFocus*) = 0;
virtual void process_destroy() = 0;
virtual void process_delete() = 0;
virtual void process_expose(GdkEventExpose*) = 0;
virtual void process_mouse_button(GdkEventButton*) = 0;
virtual void process_mouse_motion(GdkEventMotion*) = 0;
virtual void process_mouse_scroll(GdkEventScroll*) = 0;
virtual void process_mouse_cross(GdkEventCrossing*) = 0;
virtual void process_key(GdkEventKey*) = 0;
virtual void process_state(GdkEventWindowState*) = 0;
virtual void notify_state(jint) = 0;
virtual void add_child(WindowContextTop* child) = 0;
virtual void remove_child(WindowContextTop* child) = 0;
virtual bool set_view(jobject) = 0;
virtual GdkWindow *get_gdk_window() = 0;
virtual GtkWindow *get_gtk_window() = 0;
virtual jobject get_jview() = 0;
virtual jobject get_jwindow() = 0;
virtual int getEmbeddedX() = 0;
virtual int getEmbeddedY() = 0;
virtual void increment_events_counter() = 0;
virtual void decrement_events_counter() = 0;
virtual size_t get_events_count() = 0;
virtual bool is_dead() = 0;
virtual ~WindowContext() {}
};
class WindowContextBase: public WindowContext {
std::set<WindowContextTop*> children;
struct _XIM{
XIM im;
XIC ic;
bool enabled;
} xim;
size_t events_processing_cnt;
bool can_be_deleted;
protected:
jobject jwindow;
jobject jview;
GtkWidget* gtk_widget;
GdkWindow* gdk_window;
bool is_iconified;
bool is_maximized;
bool is_mouse_entered;
/*
* sm_grab_window points to WindowContext holding a mouse grab.
* It is mostly used for popup windows.
*/
static WindowContext* sm_grab_window;
/*
* sm_mouse_drag_window points to a WindowContext from which a mouse drag started.
* This WindowContext holding a mouse grab during this drag. After releasing
* all mouse buttons sm_mouse_drag_window becomes NULL and sm_grab_window's
* mouse grab should be restored if present.
*
* This is done in order to mimic Windows behavior:
* All mouse events should be delivered to a window from which mouse drag
* started, until all mouse buttons released. No mouse ENTER/EXIT events
* should be reported during this drag.
*/
static WindowContext* sm_mouse_drag_window;
public:
bool isEnabled();
bool hasIME();
bool filterIME(GdkEvent *);
void enableOrResetIME();
void disableIME();
void paint(void*, jint, jint);
GdkWindow *get_gdk_window();
jobject get_jwindow();
jobject get_jview();
void add_child(WindowContextTop*);
void remove_child(WindowContextTop*);
void show_or_hide_children(bool);
void reparent_children(WindowContext* parent);
void set_visible(bool);
bool is_visible();
bool set_view(jobject);
bool grab_focus();
bool grab_mouse_drag_focus();
void ungrab_focus();
void ungrab_mouse_drag_focus();
void set_cursor(GdkCursor*);
void set_level(int) {}
void set_background(float, float, float);
void process_map() {}
void process_focus(GdkEventFocus*);
void process_destroy();
void process_delete();
void process_expose(GdkEventExpose*);
void process_mouse_button(GdkEventButton*);
void process_mouse_motion(GdkEventMotion*);
void process_mouse_scroll(GdkEventScroll*);
void process_mouse_cross(GdkEventCrossing*);
void process_key(GdkEventKey*);
void process_state(GdkEventWindowState*);
void notify_state(jint);
int getEmbeddedX() { return 0; }
int getEmbeddedY() { return 0; }
void increment_events_counter();
void decrement_events_counter();
size_t get_events_count();
bool is_dead();
~WindowContextBase();
protected:
virtual void applyShapeMask(void*, uint width, uint height) = 0;
private:
bool im_filter_keypress(GdkEventKey*);
};
class WindowContextPlug: public WindowContextBase {
WindowContext* parent;
public:
bool set_view(jobject);
void set_bounds(int, int, bool, bool, int, int, int, int);
//WindowFrameExtents get_frame_extents() { return WindowFrameExtents{0, 0, 0, 0}; };
WindowFrameExtents get_frame_extents() { WindowFrameExtents ext = {0, 0, 0, 0}; return ext;}
void enter_fullscreen() {}
void exit_fullscreen() {}
void set_resizable(bool) {}
void request_focus() {}
void set_focusable(bool) {}
void set_title(const char*) {}
void set_alpha(double) {}
void set_enabled(bool) {}
void set_minimum_size(int, int) {}
void set_maximum_size(int, int) {}
void set_minimized(bool) {}
void set_maximized(bool) {}
void set_icon(GdkPixbuf*) {}
void restack(bool) {}
void set_modal(bool, WindowContext*) {}
void set_gravity(float, float) {}
void process_property_notify(GdkEventProperty*) {}
void process_configure(GdkEventConfigure*);
void process_gtk_configure(GdkEventConfigure*);
void applyShapeMask(void*, uint width, uint height) {}
GtkWindow *get_gtk_window(); // TODO, get window from parent
WindowContextPlug(jobject, void*);
GtkWidget* gtk_container;
std::vector<WindowContextChild *> embedded_children;
private:
//HACK: remove once set_bounds is implemented correctly
void window_configure(XWindowChanges *, unsigned int);
WindowContextPlug(WindowContextPlug&);
WindowContextPlug& operator= (const WindowContextPlug&);
};
class WindowContextChild: public WindowContextBase {
WindowContextPlug* parent;
WindowContextTop* full_screen_window;
GlassView* view; // not null while in Full Screen
public:
void process_mouse_button(GdkEventButton*);
bool set_view(jobject);
void set_bounds(int, int, bool, bool, int, int, int, int);
//WindowFrameExtents get_frame_extents() { return WindowFrameExtents{0, 0, 0, 0}; };
WindowFrameExtents get_frame_extents() { WindowFrameExtents ext = {0, 0, 0, 0}; return ext;}
void enter_fullscreen();
void exit_fullscreen();
void set_resizable(bool) {}
void request_focus() {}
void set_focusable(bool) {}
void set_title(const char*) {}
void set_alpha(double) {}
void set_enabled(bool) {}
void set_minimum_size(int, int) {}
void set_maximum_size(int, int) {}
void set_minimized(bool) {}
void set_maximized(bool) {}
void set_icon(GdkPixbuf*) {}
void restack(bool);
void set_modal(bool, WindowContext*) {}
void set_gravity(float, float) {}
void process_property_notify(GdkEventProperty*) {}
void process_configure(GdkEventConfigure*);
void process_destroy();
void set_visible(bool visible);
int getEmbeddedX();
int getEmbeddedY();
void applyShapeMask(void*, uint width, uint height) {}
GtkWindow *get_gtk_window(); // TODO, get window from parent
WindowContextChild(jobject, void*, GtkWidget *parent_widget, WindowContextPlug *parent_context);
private:
WindowContextChild(WindowContextChild&);
WindowContextChild& operator= (const WindowContextChild&);
};
class WindowContextTop: public WindowContextBase {
jlong screen;
WindowFrameType frame_type;
struct WindowContext *owner;
WindowGeometry geometry;
int stale_config_notifications;
struct _Resizable{// we can't use set/get gtk_window_resizable function
_Resizable(): request(REQUEST_NONE), value(true), prev(false),
minw(-1), minh(-1), maxw(-1), maxh(-1){}
request_type request; //request for future setResizable
bool value; //actual value of resizable for a window
bool prev; //former resizable value (used in setEnabled for parents of modal window)
int minw, minh, maxw, maxh; //minimum and maximum window width/height;
} resizable;
bool frame_extents_initialized;
bool map_received;
bool location_assigned;
bool size_assigned;
public:
WindowContextTop(jobject, WindowContext*, long, WindowFrameType, WindowType);
void process_map();
void process_property_notify(GdkEventProperty*);
void process_configure(GdkEventConfigure*);
void process_destroy();
void process_net_wm_property();
WindowFrameExtents get_frame_extents();
void set_minimized(bool);
void set_maximized(bool);
void set_bounds(int, int, bool, bool, int, int, int, int);
void set_resizable(bool);
void request_focus();
void set_focusable(bool);
void set_title(const char*);
void set_alpha(double);
void set_enabled(bool);
void set_minimum_size(int, int);
void set_maximum_size(int, int);
void set_icon(GdkPixbuf*);
void restack(bool);
void set_modal(bool, WindowContext* parent = NULL);
void set_gravity(float, float);
void set_level(int);
void set_visible(bool);
void enter_fullscreen();
void exit_fullscreen();
void set_owner(WindowContext*);
GtkWindow *get_gtk_window();
void detach_from_java();
protected:
void applyShapeMask(void*, uint width, uint height);
private:
bool get_frame_extents_property(int *, int *, int *, int *);
void request_frame_extents();
void initialize_frame_extents();
void window_configure(XWindowChanges *, unsigned int);
void update_window_constraints();
void set_window_resizable(bool, bool);
WindowContextTop(WindowContextTop&);
WindowContextTop& operator= (const WindowContextTop&);
};
void destroy_and_delete_ctx(WindowContext* ctx);
class EventsCounterHelper {
private:
WindowContext* ctx;
public:
explicit EventsCounterHelper(WindowContext* context) {
ctx = context;
ctx->increment_events_counter();
}
~EventsCounterHelper() {
ctx->decrement_events_counter();
if (ctx->is_dead() && ctx->get_events_count() == 0) {
delete ctx;
}
ctx = NULL;
}
};
#endif /* GLASS_WINDOW_H */
| Java |
#region Using directives
using System;
using System.Collections;
using System.Data;
using UFSoft.UBF.UI.MD.Runtime;
using UFSoft.UBF.UI.MD.Runtime.Implement;
#endregion
namespace DocumentTypeRef
{ public partial class DocumentTypeRefModel
{
//初始化UIMODEL之后的方法
public override void AfterInitModel()
{
//this.Views[0].Fields[0].DefaultValue = thsi.co
}
//UIModel提交保存之前的校验操作.
public override void OnValidate()
{
base.OnValidate() ;
OnValidate_DefualtImpl();
//your coustom code ...
}
}
} | Java |
<?php
//------------------------------------------------------------------------------------------------------------------
// SKY HIGH CMS - Sky High Software Custom Content Management System - http://www.skyhighsoftware.com
// Copyright (C) 2008 - 2010 Sky High Software. All Rights Reserved.
// Permission to use and modify this software is for a single website installation as per written agreement.
//
// DO NOT DISTRIBUTE OR COPY this software to any additional purpose, websites, or hosting. If the original website
// is move to new hosting, this software may also be moved to new location.
//
// IN NO EVENT SHALL SKY HIGH SOFTWARE BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, OR INCIDENTAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING FROM USE OF THIS SOFTWARE.
//
// THIS SOFTWARE IS PROVIDED "AS IS". SKY HIGH SOFTWARE HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
// ENHANCEMENTS, OR MODIFICATIONS BEYOND THAT SPECIFICALLY AGREED TO IN SEPARATE WRITTEN AGREEMENT.
//------------------------------------------------------------------------------------------------------------------
?>
<tr><td colspan="3" height="20" class="pageEditBars"> SERVICES</td></tr>
<tr>
<td valign="top" ><div align="right">Service</div></td>
<td colspan="2"><input name="sub_title" type="text" id="sub_title" size="50" maxlength="100" value="<?php echo $sub_title; ?>"/></td>
</tr>
<tr>
<td valign="top" ><div align="right">Pricing</div></td>
<td colspan="2">
<?php
$oFCKeditor = new FCKeditor('other') ;
$oFCKeditor->BasePath = 'fckeditor/'; // is the default value.
$oFCKeditor->Value = $other;
$oFCKeditor->ToolbarSet = $EDITOR_TOOLBAR;
$oFCKeditor->Height = 70;
$oFCKeditor->Create() ;
?>
</td>
</tr>
<tr>
<td valign="top" ><div align="right">Related Services</div></td>
<td colspan="2"><?php
$oFCKeditor = new FCKeditor('other2') ;
$oFCKeditor->BasePath = 'fckeditor/'; // is the default value.
$oFCKeditor->Value = $other2;
//$oFCKeditor->ToolbarSet = $EDITOR_TOOLBAR;
$oFCKeditor->Height = 240;
$oFCKeditor->Create() ;
?></td>
</tr>
<tr>
<td valign="top" ><div align="right">Quote</div></td>
<td colspan="2">
<?php
$oFCKeditor = new FCKeditor('other5') ;
$oFCKeditor->BasePath = 'fckeditor/'; // is the default value.
$oFCKeditor->Value = $other5;
$oFCKeditor->ToolbarSet = $EDITOR_TOOLBAR;
$oFCKeditor->Height = 140;
$oFCKeditor->Create() ;
?>
</td>
</tr>
<?php include("page_edit_image_inc.php"); ?> | Java |
<?php
/**
* The template for displaying Comments.
*
* The area of the page that contains both current comments
* and the comment form. The actual display of comments is
* handled by a callback to hoshin_comment which is
* located in the functions.php file.
*
* @package WordPress
* @subpackage Twenty_Ten
* @since Twenty Ten 1.0
*/
?>
<div id="comments" class="comments">
<?php if ( post_password_required() ) : ?>
<p class="nopassword"><?php _e( 'This post is password protected. Enter the password to view any comments.', 'hoshin' ); ?></p>
</div><!-- #comments -->
<?php
/* Stop the rest of comments.php from being processed,
* but don't kill the script entirely -- we still have
* to fully load the template.
*/
return;
endif;
?>
<?php
// You can start editing here -- including this comment!
?>
<?php if ( have_comments() ) : ?>
<h3 class="comments-title"><?php
printf( _n( 'One Response to %2$s', '%1$s Responses to %2$s', get_comments_number(), 'hoshin' ),
number_format_i18n( get_comments_number() ), '<em>' . get_the_title() . '</em>' );
?></h3>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // Are there comments to navigate through? ?>
<div class="navigation">
<div class="nav-previous"><?php previous_comments_link( __( '<span class="meta-nav">←</span> Older Comments', 'hoshin' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments <span class="meta-nav">→</span>', 'hoshin' ) ); ?></div>
</div> <!-- .navigation -->
<?php endif; // check for comment navigation ?>
<ol class="commentlist">
<?php
/* Loop through and list the comments. Tell wp_list_comments()
* to use hoshin_comment() to format the comments.
* If you want to overload this in a child theme then you can
* define hoshin_comment() and that will be used instead.
* See hoshin_comment() in hoshin/functions.php for more.
*/
wp_list_comments( array( 'callback' => 'hoshin_comment' ) );
?>
</ol>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // Are there comments to navigate through? ?>
<div class="navigation">
<div class="nav-previous"><?php previous_comments_link( __( '<span class="meta-nav">←</span> Older Comments', 'hoshin' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments <span class="meta-nav">→</span>', 'hoshin' ) ); ?></div>
</div><!-- .navigation -->
<?php endif; // check for comment navigation ?>
<?php else : // or, if we don't have comments:
/* If there are no comments and comments are closed,
* let's leave a little note, shall we?
*/
if ( ! comments_open() ) :
?>
<p class="nocomments"><?php _e( 'Comments are closed.', 'hoshin' ); ?></p>
<?php endif; // end ! comments_open() ?>
<?php endif; // end have_comments() ?>
<?php comment_form(); ?>
</div><!-- #comments -->
| Java |
/* $Id: capi.h,v 1.1.1.1 2010/03/11 21:10:39 kris Exp $
*
* CAPI 2.0 Interface for Linux
*
* Copyright 1997 by Carsten Paeth (calle@calle.in-berlin.de)
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#ifndef __LINUX_CAPI_H__
#define __LINUX_CAPI_H__
#include <asm/types.h>
#include <linux/ioctl.h>
#ifndef __KERNEL__
#include <linux/kernelcapi.h>
#endif
/*
* CAPI_REGISTER
*/
typedef struct capi_register_params { /* CAPI_REGISTER */
__u32 level3cnt; /* No. of simulatneous user data connections */
__u32 datablkcnt; /* No. of buffered data messages */
__u32 datablklen; /* Size of buffered data messages */
} capi_register_params;
#define CAPI_REGISTER _IOW('C',0x01,struct capi_register_params)
/*
* CAPI_GET_MANUFACTURER
*/
#define CAPI_MANUFACTURER_LEN 64
#define CAPI_GET_MANUFACTURER _IOWR('C',0x06,int) /* broken: wanted size 64 (CAPI_MANUFACTURER_LEN) */
/*
* CAPI_GET_VERSION
*/
typedef struct capi_version {
__u32 majorversion;
__u32 minorversion;
__u32 majormanuversion;
__u32 minormanuversion;
} capi_version;
#define CAPI_GET_VERSION _IOWR('C',0x07,struct capi_version)
/*
* CAPI_GET_SERIAL
*/
#define CAPI_SERIAL_LEN 8
#define CAPI_GET_SERIAL _IOWR('C',0x08,int) /* broken: wanted size 8 (CAPI_SERIAL_LEN) */
/*
* CAPI_GET_PROFILE
*/
typedef struct capi_profile {
__u16 ncontroller; /* number of installed controller */
__u16 nbchannel; /* number of B-Channels */
__u32 goptions; /* global options */
__u32 support1; /* B1 protocols support */
__u32 support2; /* B2 protocols support */
__u32 support3; /* B3 protocols support */
__u32 reserved[6]; /* reserved */
__u32 manu[5]; /* manufacturer specific information */
} capi_profile;
#define CAPI_GET_PROFILE _IOWR('C',0x09,struct capi_profile)
typedef struct capi_manufacturer_cmd {
unsigned long cmd;
void __user *data;
} capi_manufacturer_cmd;
/*
* CAPI_MANUFACTURER_CMD
*/
#define CAPI_MANUFACTURER_CMD _IOWR('C',0x20, struct capi_manufacturer_cmd)
/*
* CAPI_GET_ERRCODE
* capi errcode is set, * if read, write, or ioctl returns EIO,
* ioctl returns errcode directly, and in arg, if != 0
*/
#define CAPI_GET_ERRCODE _IOR('C',0x21, __u16)
/*
* CAPI_INSTALLED
*/
#define CAPI_INSTALLED _IOR('C',0x22, __u16)
/*
* member contr is input for
* CAPI_GET_MANUFACTURER, CAPI_VERSION, CAPI_GET_SERIAL
* and CAPI_GET_PROFILE
*/
typedef union capi_ioctl_struct {
__u32 contr;
capi_register_params rparams;
__u8 manufacturer[CAPI_MANUFACTURER_LEN];
capi_version version;
__u8 serial[CAPI_SERIAL_LEN];
capi_profile profile;
capi_manufacturer_cmd cmd;
__u16 errcode;
} capi_ioctl_struct;
/*
* Middleware extension
*/
#define CAPIFLAG_HIGHJACKING 0x0001
#define CAPI_GET_FLAGS _IOR('C',0x23, unsigned)
#define CAPI_SET_FLAGS _IOR('C',0x24, unsigned)
#define CAPI_CLR_FLAGS _IOR('C',0x25, unsigned)
#define CAPI_NCCI_OPENCOUNT _IOR('C',0x26, unsigned)
#define CAPI_NCCI_GETUNIT _IOR('C',0x27, unsigned)
#endif /* __LINUX_CAPI_H__ */
| Java |
/* This program was written with lots of love under the GPL by Jonathan
* Blandford <jrb@gnome.org>
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
#include <gio/gio.h>
#include <gdk/gdkx.h>
#include <X11/Xatom.h>
#include <glib/gi18n.h>
#include <gdk/gdkkeysyms.h>
#if GTK_CHECK_VERSION (3, 0, 0)
#include <gdk/gdkkeysyms-compat.h>
#endif
#include "wm-common.h"
#include "capplet-util.h"
#include "eggcellrendererkeys.h"
#include "activate-settings-daemon.h"
#include "dconf-util.h"
#define GSETTINGS_KEYBINDINGS_DIR "/org/mate/desktop/keybindings/"
#define CUSTOM_KEYBINDING_SCHEMA "org.mate.control-center.keybinding"
#define MAX_ELEMENTS_BEFORE_SCROLLING 10
#define MAX_CUSTOM_SHORTCUTS 1000
#define RESPONSE_ADD 0
#define RESPONSE_REMOVE 1
typedef struct {
/* The untranslated name, combine with ->package to translate */
char *name;
/* The gettext package to use to translate the section title */
char *package;
/* Name of the window manager the keys would apply to */
char *wm_name;
/* The GSettings schema for the whole file */
char *schema;
/* an array of KeyListEntry */
GArray *entries;
} KeyList;
typedef enum {
COMPARISON_NONE = 0,
COMPARISON_GT,
COMPARISON_LT,
COMPARISON_EQ
} Comparison;
typedef struct
{
char *gsettings_path;
char *schema;
char *name;
int value;
char *value_schema; /* gsettings schema for key/value */
char *value_key;
char *description;
char *description_key;
char *cmd_key;
Comparison comparison;
} KeyListEntry;
enum
{
DESCRIPTION_COLUMN,
KEYENTRY_COLUMN,
N_COLUMNS
};
typedef struct
{
GSettings *settings;
char *gsettings_path;
char *gsettings_key;
guint keyval;
guint keycode;
EggVirtualModifierType mask;
gboolean editable;
GtkTreeModel *model;
char *description;
char *desc_gsettings_key;
gboolean desc_editable;
char *command;
char *cmd_gsettings_key;
gboolean cmd_editable;
gulong gsettings_cnxn;
gulong gsettings_cnxn_desc;
gulong gsettings_cnxn_cmd;
} KeyEntry;
static gboolean block_accels = FALSE;
static GtkWidget *custom_shortcut_dialog = NULL;
static GtkWidget *custom_shortcut_name_entry = NULL;
static GtkWidget *custom_shortcut_command_entry = NULL;
static GtkWidget* _gtk_builder_get_widget(GtkBuilder* builder, const gchar* name)
{
return GTK_WIDGET (gtk_builder_get_object (builder, name));
}
static GtkBuilder *
create_builder (void)
{
GtkBuilder *builder = gtk_builder_new();
GError *error = NULL;
static const gchar *uifile = MATECC_UI_DIR "/mate-keybinding-properties.ui";
if (gtk_builder_add_from_file (builder, uifile, &error) == 0) {
g_warning ("Could not load UI: %s", error->message);
g_error_free (error);
g_object_unref (builder);
builder = NULL;
}
return builder;
}
static char* binding_name(guint keyval, guint keycode, EggVirtualModifierType mask, gboolean translate)
{
if (keyval != 0 || keycode != 0)
{
if (translate)
{
return egg_virtual_accelerator_label (keyval, keycode, mask);
}
else
{
return egg_virtual_accelerator_name (keyval, keycode, mask);
}
}
else
{
return g_strdup (translate ? _("Disabled") : "");
}
}
static gboolean
binding_from_string (const char *str,
guint *accelerator_key,
guint *keycode,
EggVirtualModifierType *accelerator_mods)
{
g_return_val_if_fail (accelerator_key != NULL, FALSE);
if (str == NULL || strcmp (str, "disabled") == 0)
{
*accelerator_key = 0;
*keycode = 0;
*accelerator_mods = 0;
return TRUE;
}
egg_accelerator_parse_virtual (str, accelerator_key, keycode, accelerator_mods);
if (*accelerator_key == 0)
return FALSE;
else
return TRUE;
}
static void
accel_set_func (GtkTreeViewColumn *tree_column,
GtkCellRenderer *cell,
GtkTreeModel *model,
GtkTreeIter *iter,
gpointer data)
{
KeyEntry *key_entry;
gtk_tree_model_get (model, iter,
KEYENTRY_COLUMN, &key_entry,
-1);
if (key_entry == NULL)
g_object_set (cell,
"visible", FALSE,
NULL);
else if (! key_entry->editable)
g_object_set (cell,
"visible", TRUE,
"editable", FALSE,
"accel_key", key_entry->keyval,
"accel_mask", key_entry->mask,
"keycode", key_entry->keycode,
"style", PANGO_STYLE_ITALIC,
NULL);
else
g_object_set (cell,
"visible", TRUE,
"editable", TRUE,
"accel_key", key_entry->keyval,
"accel_mask", key_entry->mask,
"keycode", key_entry->keycode,
"style", PANGO_STYLE_NORMAL,
NULL);
}
static void
description_set_func (GtkTreeViewColumn *tree_column,
GtkCellRenderer *cell,
GtkTreeModel *model,
GtkTreeIter *iter,
gpointer data)
{
KeyEntry *key_entry;
gtk_tree_model_get (model, iter,
KEYENTRY_COLUMN, &key_entry,
-1);
if (key_entry != NULL)
g_object_set (cell,
"editable", FALSE,
"text", key_entry->description != NULL ?
key_entry->description : _("<Unknown Action>"),
NULL);
else
g_object_set (cell,
"editable", FALSE, NULL);
}
static gboolean
keybinding_key_changed_foreach (GtkTreeModel *model,
GtkTreePath *path,
GtkTreeIter *iter,
gpointer user_data)
{
KeyEntry *key_entry;
KeyEntry *tmp_key_entry;
key_entry = (KeyEntry *)user_data;
gtk_tree_model_get (key_entry->model, iter,
KEYENTRY_COLUMN, &tmp_key_entry,
-1);
if (key_entry == tmp_key_entry)
{
gtk_tree_model_row_changed (key_entry->model, path, iter);
return TRUE;
}
return FALSE;
}
static void
keybinding_key_changed (GSettings *settings,
gchar *key,
KeyEntry *key_entry)
{
gchar *key_value;
key_value = g_settings_get_string (settings, key);
binding_from_string (key_value, &key_entry->keyval, &key_entry->keycode, &key_entry->mask);
key_entry->editable = g_settings_is_writable (settings, key);
/* update the model */
gtk_tree_model_foreach (key_entry->model, keybinding_key_changed_foreach, key_entry);
}
static void
keybinding_description_changed (GSettings *settings,
gchar *key,
KeyEntry *key_entry)
{
gchar *key_value;
key_value = g_settings_get_string (settings, key);
g_free (key_entry->description);
key_entry->description = key_value ? g_strdup (key_value) : NULL;
g_free (key_value);
key_entry->desc_editable = g_settings_is_writable (settings, key);
/* update the model */
gtk_tree_model_foreach (key_entry->model, keybinding_key_changed_foreach, key_entry);
}
static void
keybinding_command_changed (GSettings *settings,
gchar *key,
KeyEntry *key_entry)
{
gchar *key_value;
key_value = g_settings_get_string (settings, key);
g_free (key_entry->command);
key_entry->command = key_value ? g_strdup (key_value) : NULL;
key_entry->cmd_editable = g_settings_is_writable (settings, key);
g_free (key_value);
/* update the model */
gtk_tree_model_foreach (key_entry->model, keybinding_key_changed_foreach, key_entry);
}
static int
keyentry_sort_func (GtkTreeModel *model,
GtkTreeIter *a,
GtkTreeIter *b,
gpointer user_data)
{
KeyEntry *key_entry_a;
KeyEntry *key_entry_b;
int retval;
key_entry_a = NULL;
gtk_tree_model_get (model, a,
KEYENTRY_COLUMN, &key_entry_a,
-1);
key_entry_b = NULL;
gtk_tree_model_get (model, b,
KEYENTRY_COLUMN, &key_entry_b,
-1);
if (key_entry_a && key_entry_b)
{
if ((key_entry_a->keyval || key_entry_a->keycode) &&
(key_entry_b->keyval || key_entry_b->keycode))
{
gchar *name_a, *name_b;
name_a = binding_name (key_entry_a->keyval,
key_entry_a->keycode,
key_entry_a->mask,
TRUE);
name_b = binding_name (key_entry_b->keyval,
key_entry_b->keycode,
key_entry_b->mask,
TRUE);
retval = g_utf8_collate (name_a, name_b);
g_free (name_a);
g_free (name_b);
}
else if (key_entry_a->keyval || key_entry_a->keycode)
retval = -1;
else if (key_entry_b->keyval || key_entry_b->keycode)
retval = 1;
else
retval = 0;
}
else if (key_entry_a)
retval = -1;
else if (key_entry_b)
retval = 1;
else
retval = 0;
return retval;
}
static void
clear_old_model (GtkBuilder *builder)
{
GtkWidget *tree_view;
GtkWidget *actions_swindow;
GtkTreeModel *model;
tree_view = _gtk_builder_get_widget (builder, "shortcut_treeview");
model = gtk_tree_view_get_model (GTK_TREE_VIEW (tree_view));
if (model == NULL)
{
/* create a new model */
model = (GtkTreeModel *) gtk_tree_store_new (N_COLUMNS, G_TYPE_STRING, G_TYPE_POINTER);
gtk_tree_sortable_set_sort_func (GTK_TREE_SORTABLE (model),
KEYENTRY_COLUMN,
keyentry_sort_func,
NULL, NULL);
gtk_tree_view_set_model (GTK_TREE_VIEW (tree_view), model);
g_object_unref (model);
}
else
{
/* clear the existing model */
gboolean valid;
GtkTreeIter iter;
KeyEntry *key_entry;
for (valid = gtk_tree_model_get_iter_first (model, &iter);
valid;
valid = gtk_tree_model_iter_next (model, &iter))
{
gtk_tree_model_get (model, &iter,
KEYENTRY_COLUMN, &key_entry,
-1);
if (key_entry != NULL)
{
g_signal_handler_disconnect (key_entry->settings, key_entry->gsettings_cnxn);
if (key_entry->gsettings_cnxn_desc != 0)
g_signal_handler_disconnect (key_entry->settings, key_entry->gsettings_cnxn_desc);
if (key_entry->gsettings_cnxn_cmd != 0)
g_signal_handler_disconnect (key_entry->settings, key_entry->gsettings_cnxn_cmd);
g_object_unref (key_entry->settings);
if (key_entry->gsettings_path)
g_free (key_entry->gsettings_path);
g_free (key_entry->gsettings_key);
g_free (key_entry->description);
g_free (key_entry->desc_gsettings_key);
g_free (key_entry->command);
g_free (key_entry->cmd_gsettings_key);
g_free (key_entry);
}
}
gtk_tree_store_clear (GTK_TREE_STORE (model));
}
actions_swindow = _gtk_builder_get_widget (builder, "actions_swindow");
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (actions_swindow),
GTK_POLICY_NEVER, GTK_POLICY_NEVER);
gtk_widget_set_size_request (actions_swindow, -1, -1);
}
typedef struct {
const char *key;
const char *path;
const char *schema;
gboolean found;
} KeyMatchData;
static gboolean key_match(GtkTreeModel* model, GtkTreePath* path, GtkTreeIter* iter, gpointer data)
{
KeyMatchData* match_data = data;
KeyEntry* element = NULL;
gchar *element_schema = NULL;
gchar *element_path = NULL;
gtk_tree_model_get(model, iter,
KEYENTRY_COLUMN, &element,
-1);
if (element && element->settings && G_IS_SETTINGS(element->settings))
{
g_object_get (element->settings, "schema-id", &element_schema, NULL);
g_object_get (element->settings, "path", &element_path, NULL);
}
if (element && g_strcmp0(element->gsettings_key, match_data->key) == 0
&& g_strcmp0(element_schema, match_data->schema) == 0
&& g_strcmp0(element_path, match_data->path) == 0)
{
match_data->found = TRUE;
return TRUE;
}
return FALSE;
}
static gboolean key_is_already_shown(GtkTreeModel* model, const KeyListEntry* entry)
{
KeyMatchData data;
data.key = entry->name;
data.schema = entry->schema;
data.path = entry->gsettings_path;
data.found = FALSE;
gtk_tree_model_foreach(model, key_match, &data);
return data.found;
}
static gboolean should_show_key(const KeyListEntry* entry)
{
GSettings *settings;
int value;
if (entry->comparison == COMPARISON_NONE)
{
return TRUE;
}
g_return_val_if_fail(entry->value_key != NULL, FALSE);
g_return_val_if_fail(entry->value_schema != NULL, FALSE);
settings = g_settings_new (entry->value_schema);
value = g_settings_get_int (settings, entry->value_key);
g_object_unref (settings);
switch (entry->comparison)
{
case COMPARISON_NONE:
/* For compiler warnings */
g_assert_not_reached ();
return FALSE;
case COMPARISON_GT:
if (value > entry->value)
{
return TRUE;
}
break;
case COMPARISON_LT:
if (value < entry->value)
{
return TRUE;
}
break;
case COMPARISON_EQ:
if (value == entry->value)
{
return TRUE;
}
break;
}
return FALSE;
}
static gboolean
count_rows_foreach (GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer data)
{
gint *rows = data;
(*rows)++;
return FALSE;
}
static void
ensure_scrollbar (GtkBuilder *builder, int i)
{
if (i == MAX_ELEMENTS_BEFORE_SCROLLING)
{
GtkRequisition rectangle;
GObject *actions_swindow = gtk_builder_get_object (builder,
"actions_swindow");
GtkWidget *treeview = _gtk_builder_get_widget (builder,
"shortcut_treeview");
gtk_widget_ensure_style (treeview);
gtk_widget_size_request (treeview, &rectangle);
gtk_widget_set_size_request (treeview, -1, rectangle.height);
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (actions_swindow),
GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
}
}
static void
find_section (GtkTreeModel *model,
GtkTreeIter *iter,
const char *title)
{
gboolean success;
success = gtk_tree_model_get_iter_first (model, iter);
while (success)
{
char *description = NULL;
gtk_tree_model_get (model, iter,
DESCRIPTION_COLUMN, &description,
-1);
if (g_strcmp0 (description, title) == 0)
return;
success = gtk_tree_model_iter_next (model, iter);
}
gtk_tree_store_append (GTK_TREE_STORE (model), iter, NULL);
gtk_tree_store_set (GTK_TREE_STORE (model), iter,
DESCRIPTION_COLUMN, title,
-1);
}
static void
append_keys_to_tree (GtkBuilder *builder,
const gchar *title,
const gchar *schema,
const gchar *package,
const KeyListEntry *keys_list)
{
GtkTreeIter parent_iter, iter;
GtkTreeModel *model;
gint i, j;
model = gtk_tree_view_get_model (GTK_TREE_VIEW (gtk_builder_get_object (builder, "shortcut_treeview")));
/* Try to find a section parent iter, if it already exists */
find_section (model, &iter, title);
parent_iter = iter;
i = 0;
gtk_tree_model_foreach (model, count_rows_foreach, &i);
/* If the header we just added is the MAX_ELEMENTS_BEFORE_SCROLLING th,
* then we need to scroll now */
ensure_scrollbar (builder, i - 1);
for (j = 0; keys_list[j].name != NULL; j++)
{
GSettings *settings = NULL;
gchar *settings_path;
KeyEntry *key_entry;
const gchar *key_string;
gchar *key_value;
gchar *description;
gchar *command;
if (!should_show_key (&keys_list[j]))
continue;
if (key_is_already_shown (model, &keys_list[j]))
continue;
key_string = keys_list[j].name;
if (keys_list[j].gsettings_path != NULL)
{
settings = g_settings_new_with_path (schema, keys_list[j].gsettings_path);
settings_path = g_strdup(keys_list[j].gsettings_path);
}
else
{
settings = g_settings_new (schema);
settings_path = NULL;
}
if (keys_list[j].description_key != NULL)
{
/* it's a custom shortcut, so description is in gsettings */
description = g_settings_get_string (settings, keys_list[j].description_key);
}
else
{
/* it's from keyfile, so description need to be translated */
description = keys_list[j].description;
if (package)
{
bind_textdomain_codeset (package, "UTF-8");
description = dgettext (package, description);
}
else
{
description = _(description);
}
}
if (description == NULL)
{
/* Only print a warning for keys that should have a schema */
if (keys_list[j].description_key == NULL)
g_warning ("No description for key '%s'", key_string);
}
if (keys_list[j].cmd_key != NULL)
{
command = g_settings_get_string (settings, keys_list[j].cmd_key);
}
else
{
command = NULL;
}
key_entry = g_new0 (KeyEntry, 1);
key_entry->settings = settings;
key_entry->gsettings_path = settings_path;
key_entry->gsettings_key = g_strdup (key_string);
key_entry->editable = g_settings_is_writable (settings, key_string);
key_entry->model = model;
key_entry->description = description;
key_entry->command = command;
if (keys_list[j].description_key != NULL)
{
key_entry->desc_gsettings_key = g_strdup (keys_list[j].description_key);
key_entry->desc_editable = g_settings_is_writable (settings, key_entry->desc_gsettings_key);
gchar *gsettings_signal = g_strconcat ("changed::", key_entry->desc_gsettings_key, NULL);
key_entry->gsettings_cnxn_desc = g_signal_connect (settings,
gsettings_signal,
G_CALLBACK (keybinding_description_changed),
key_entry);
g_free (gsettings_signal);
}
if (keys_list[j].cmd_key != NULL)
{
key_entry->cmd_gsettings_key = g_strdup (keys_list[j].cmd_key);
key_entry->cmd_editable = g_settings_is_writable (settings, key_entry->cmd_gsettings_key);
gchar *gsettings_signal = g_strconcat ("changed::", key_entry->cmd_gsettings_key, NULL);
key_entry->gsettings_cnxn_cmd = g_signal_connect (settings,
gsettings_signal,
G_CALLBACK (keybinding_command_changed),
key_entry);
g_free (gsettings_signal);
}
gchar *gsettings_signal = g_strconcat ("changed::", key_string, NULL);
key_entry->gsettings_cnxn = g_signal_connect (settings,
gsettings_signal,
G_CALLBACK (keybinding_key_changed),
key_entry);
g_free (gsettings_signal);
key_value = g_settings_get_string (settings, key_string);
binding_from_string (key_value, &key_entry->keyval, &key_entry->keycode, &key_entry->mask);
g_free (key_value);
ensure_scrollbar (builder, i);
++i;
gtk_tree_store_append (GTK_TREE_STORE (model), &iter, &parent_iter);
/* we use the DESCRIPTION_COLUMN only for the section headers */
gtk_tree_store_set (GTK_TREE_STORE (model), &iter,
KEYENTRY_COLUMN, key_entry,
-1);
gtk_tree_view_expand_all (GTK_TREE_VIEW (gtk_builder_get_object (builder, "shortcut_treeview")));
}
/* Don't show an empty section */
if (gtk_tree_model_iter_n_children (model, &parent_iter) == 0)
gtk_tree_store_remove (GTK_TREE_STORE (model), &parent_iter);
if (i == 0)
gtk_widget_hide (_gtk_builder_get_widget (builder, "shortcuts_vbox"));
else
gtk_widget_show (_gtk_builder_get_widget (builder, "shortcuts_vbox"));
}
static void
parse_start_tag (GMarkupParseContext *ctx,
const gchar *element_name,
const gchar **attr_names,
const gchar **attr_values,
gpointer user_data,
GError **error)
{
KeyList *keylist = (KeyList *) user_data;
KeyListEntry key;
const char *name, *value_key, *description, *value_schema;
int value;
Comparison comparison;
const char *schema = NULL;
name = NULL;
/* The top-level element, names the section in the tree */
if (g_str_equal (element_name, "KeyListEntries"))
{
const char *wm_name = NULL;
const char *package = NULL;
while (*attr_names && *attr_values)
{
if (g_str_equal (*attr_names, "name"))
{
if (**attr_values)
name = *attr_values;
}
else if (g_str_equal (*attr_names, "wm_name"))
{
if (**attr_values)
wm_name = *attr_values;
}
else if (g_str_equal (*attr_names, "package"))
{
if (**attr_values)
package = *attr_values;
}
else if (g_str_equal (*attr_names, "schema"))
{
if (**attr_values)
schema = *attr_values;
}
++attr_names;
++attr_values;
}
if (name)
{
if (keylist->name)
g_warning ("Duplicate section name");
g_free (keylist->name);
keylist->name = g_strdup (name);
}
if (wm_name)
{
if (keylist->wm_name)
g_warning ("Duplicate window manager name");
g_free (keylist->wm_name);
keylist->wm_name = g_strdup (wm_name);
}
if (package)
{
if (keylist->package)
g_warning ("Duplicate gettext package name");
g_free (keylist->package);
keylist->package = g_strdup (package);
}
if (schema)
{
if (keylist->schema)
g_warning ("Duplicate schema name");
g_free (keylist->schema);
keylist->schema = g_strdup (schema);
}
return;
}
if (!g_str_equal (element_name, "KeyListEntry")
|| attr_names == NULL
|| attr_values == NULL)
return;
value = 0;
comparison = COMPARISON_NONE;
value_key = NULL;
value_schema = NULL;
description = NULL;
while (*attr_names && *attr_values)
{
if (g_str_equal (*attr_names, "name"))
{
/* skip if empty */
if (**attr_values)
name = *attr_values;
} else if (g_str_equal (*attr_names, "value")) {
if (**attr_values) {
value = (int) g_ascii_strtoull (*attr_values, NULL, 0);
}
} else if (g_str_equal (*attr_names, "key")) {
if (**attr_values) {
value_key = *attr_values;
}
} else if (g_str_equal (*attr_names, "comparison")) {
if (**attr_values) {
if (g_str_equal (*attr_values, "gt")) {
comparison = COMPARISON_GT;
} else if (g_str_equal (*attr_values, "lt")) {
comparison = COMPARISON_LT;
} else if (g_str_equal (*attr_values, "eq")) {
comparison = COMPARISON_EQ;
}
}
} else if (g_str_equal (*attr_names, "description")) {
if (**attr_values) {
description = *attr_values;
}
} else if (g_str_equal (*attr_names, "schema")) {
if (**attr_values) {
value_schema = *attr_values;
}
}
++attr_names;
++attr_values;
}
if (name == NULL)
return;
key.name = g_strdup (name);
key.gsettings_path = NULL;
key.description_key = NULL;
key.description = g_strdup(description);
key.schema = g_strdup(schema);
key.value = value;
if (value_key) {
key.value_key = g_strdup (value_key);
key.value_schema = g_strdup (value_schema);
}
else {
key.value_key = NULL;
key.value_schema = NULL;
}
key.comparison = comparison;
key.cmd_key = NULL;
g_array_append_val (keylist->entries, key);
}
static gboolean
strv_contains (char **strv,
char *str)
{
char **p = strv;
for (p = strv; *p; p++)
if (strcmp (*p, str) == 0)
return TRUE;
return FALSE;
}
static void
append_keys_to_tree_from_file (GtkBuilder *builder,
const char *filename,
char **wm_keybindings)
{
GMarkupParseContext *ctx;
GMarkupParser parser = { parse_start_tag, NULL, NULL, NULL, NULL };
KeyList *keylist;
KeyListEntry key, *keys;
GError *err = NULL;
char *buf;
const char *title;
gsize buf_len;
guint i;
if (!g_file_get_contents (filename, &buf, &buf_len, &err))
return;
keylist = g_new0 (KeyList, 1);
keylist->entries = g_array_new (FALSE, TRUE, sizeof (KeyListEntry));
ctx = g_markup_parse_context_new (&parser, 0, keylist, NULL);
if (!g_markup_parse_context_parse (ctx, buf, buf_len, &err))
{
g_warning ("Failed to parse '%s': '%s'", filename, err->message);
g_error_free (err);
g_free (keylist->name);
g_free (keylist->package);
g_free (keylist->wm_name);
g_free (keylist->schema);
for (i = 0; i < keylist->entries->len; i++)
g_free (((KeyListEntry *) &(keylist->entries->data[i]))->name);
g_array_free (keylist->entries, TRUE);
g_free (keylist);
keylist = NULL;
}
g_markup_parse_context_free (ctx);
g_free (buf);
if (keylist == NULL)
return;
/* If there's no keys to add, or the settings apply to a window manager
* that's not the one we're running */
if (keylist->entries->len == 0
|| (keylist->wm_name != NULL && !strv_contains (wm_keybindings, keylist->wm_name))
|| keylist->name == NULL)
{
g_free (keylist->name);
g_free (keylist->package);
g_free (keylist->wm_name);
g_free (keylist->schema);
g_array_free (keylist->entries, TRUE);
g_free (keylist);
return;
}
/* Empty KeyListEntry to end the array */
key.name = NULL;
key.description_key = NULL;
key.value_key = NULL;
key.value = 0;
key.comparison = COMPARISON_NONE;
g_array_append_val (keylist->entries, key);
keys = (KeyListEntry *) g_array_free (keylist->entries, FALSE);
if (keylist->package)
{
bind_textdomain_codeset (keylist->package, "UTF-8");
title = dgettext (keylist->package, keylist->name);
} else {
title = _(keylist->name);
}
append_keys_to_tree (builder, title, keylist->schema, keylist->package, keys);
g_free (keylist->name);
g_free (keylist->package);
for (i = 0; keys[i].name != NULL; i++)
g_free (keys[i].name);
g_free (keylist);
}
static void
append_keys_to_tree_from_gsettings (GtkBuilder *builder, const gchar *gsettings_path)
{
gchar **custom_list;
GArray *entries;
KeyListEntry key;
gint i;
/* load custom shortcuts from GSettings */
entries = g_array_new (FALSE, TRUE, sizeof (KeyListEntry));
key.value_key = NULL;
key.value = 0;
key.comparison = COMPARISON_NONE;
custom_list = dconf_util_list_subdirs (gsettings_path, FALSE);
if (custom_list != NULL)
{
for (i = 0; custom_list[i] != NULL; i++)
{
key.gsettings_path = g_strdup_printf("%s%s", gsettings_path, custom_list[i]);
key.name = g_strdup("binding");
key.cmd_key = g_strdup("action");
key.description_key = g_strdup("name");
key.schema = NULL;
g_array_append_val (entries, key);
}
}
g_strfreev (custom_list);
if (entries->len > 0)
{
KeyListEntry *keys;
int i;
/* Empty KeyListEntry to end the array */
key.gsettings_path = NULL;
key.name = NULL;
key.description_key = NULL;
key.cmd_key = NULL;
g_array_append_val (entries, key);
keys = (KeyListEntry *) entries->data;
append_keys_to_tree (builder, _("Custom Shortcuts"), CUSTOM_KEYBINDING_SCHEMA, NULL, keys);
for (i = 0; i < entries->len; ++i)
{
g_free (keys[i].name);
g_free (keys[i].description_key);
g_free (keys[i].cmd_key);
g_free (keys[i].gsettings_path);
}
}
g_array_free (entries, TRUE);
}
static void
reload_key_entries (GtkBuilder *builder)
{
gchar **wm_keybindings;
GDir *dir;
const char *name;
GList *list, *l;
wm_keybindings = wm_common_get_current_keybindings();
clear_old_model (builder);
dir = g_dir_open (MATECC_KEYBINDINGS_DIR, 0, NULL);
if (!dir)
return;
list = NULL;
for (name = g_dir_read_name (dir) ; name ; name = g_dir_read_name (dir))
{
if (g_str_has_suffix (name, ".xml"))
{
list = g_list_insert_sorted (list, g_strdup (name),
(GCompareFunc) g_ascii_strcasecmp);
}
}
g_dir_close (dir);
for (l = list; l != NULL; l = l->next)
{
gchar *path;
path = g_build_filename (MATECC_KEYBINDINGS_DIR, l->data, NULL);
append_keys_to_tree_from_file (builder, path, wm_keybindings);
g_free (l->data);
g_free (path);
}
g_list_free (list);
/* Load custom shortcuts _after_ system-provided ones,
* since some of the custom shortcuts may also be listed
* in a file. Loading the custom shortcuts last makes
* such keys not show up in the custom section.
*/
append_keys_to_tree_from_gsettings (builder, GSETTINGS_KEYBINDINGS_DIR);
g_strfreev (wm_keybindings);
}
static void
key_entry_controlling_key_changed (GSettings *settings, gchar *key, gpointer user_data)
{
reload_key_entries (user_data);
}
static gboolean cb_check_for_uniqueness(GtkTreeModel* model, GtkTreePath* path, GtkTreeIter* iter, KeyEntry* new_key)
{
KeyEntry* element;
gtk_tree_model_get (new_key->model, iter,
KEYENTRY_COLUMN, &element,
-1);
/* no conflict for : blanks, different modifiers, or ourselves */
if (element == NULL || new_key->mask != element->mask)
{
return FALSE;
}
gchar *new_key_schema = NULL;
gchar *element_schema = NULL;
gchar *new_key_path = NULL;
gchar *element_path = NULL;
if (new_key && new_key->settings)
{
g_object_get (new_key->settings, "schema-id", &new_key_schema, NULL);
g_object_get (new_key->settings, "path", &new_key_path, NULL);
}
if (element->settings)
{
g_object_get (element->settings, "schema-id", &element_schema, NULL);
g_object_get (element->settings, "path", &element_path, NULL);
}
if (!g_strcmp0 (new_key->gsettings_key, element->gsettings_key) &&
!g_strcmp0 (new_key_schema, element_schema) &&
!g_strcmp0 (new_key_path, element_path))
{
return FALSE;
}
if (new_key->keyval != 0)
{
if (new_key->keyval != element->keyval)
{
return FALSE;
}
}
else if (element->keyval != 0 || new_key->keycode != element->keycode)
{
return FALSE;
}
new_key->editable = FALSE;
new_key->settings = element->settings;
new_key->gsettings_key = element->gsettings_key;
new_key->description = element->description;
new_key->desc_gsettings_key = element->desc_gsettings_key;
new_key->desc_editable = element->desc_editable;
return TRUE;
}
static const guint forbidden_keyvals[] = {
/* Navigation keys */
GDK_Home,
GDK_Left,
GDK_Up,
GDK_Right,
GDK_Down,
GDK_Page_Up,
GDK_Page_Down,
GDK_End,
GDK_Tab,
/* Return */
GDK_KP_Enter,
GDK_Return,
GDK_space,
GDK_Mode_switch
};
static gboolean keyval_is_forbidden(guint keyval)
{
guint i;
for (i = 0; i < G_N_ELEMENTS(forbidden_keyvals); i++)
{
if (keyval == forbidden_keyvals[i])
{
return TRUE;
}
}
return FALSE;
}
static void show_error(GtkWindow* parent, GError* err)
{
GtkWidget *dialog;
dialog = gtk_message_dialog_new (parent,
GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL,
GTK_MESSAGE_WARNING,
GTK_BUTTONS_OK,
_("Error saving the new shortcut"));
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
"%s", err->message);
gtk_dialog_run (GTK_DIALOG (dialog));
gtk_widget_destroy (dialog);
}
static void accel_edited_callback(GtkCellRendererText* cell, const char* path_string, guint keyval, EggVirtualModifierType mask, guint keycode, gpointer data)
{
GtkTreeView* view = (GtkTreeView*) data;
GtkTreeModel* model;
GtkTreePath* path = gtk_tree_path_new_from_string (path_string);
GtkTreeIter iter;
KeyEntry* key_entry, tmp_key;
char* str;
block_accels = FALSE;
model = gtk_tree_view_get_model (view);
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_path_free (path);
gtk_tree_model_get (model, &iter,
KEYENTRY_COLUMN, &key_entry,
-1);
/* sanity check */
if (key_entry == NULL)
{
return;
}
/* CapsLock isn't supported as a keybinding modifier, so keep it from confusing us */
mask &= ~EGG_VIRTUAL_LOCK_MASK;
tmp_key.model = model;
tmp_key.keyval = keyval;
tmp_key.keycode = keycode;
tmp_key.mask = mask;
tmp_key.settings = key_entry->settings;
tmp_key.gsettings_key = key_entry->gsettings_key;
tmp_key.description = NULL;
tmp_key.editable = TRUE; /* kludge to stuff in a return flag */
if (keyval != 0 || keycode != 0) /* any number of keys can be disabled */
{
gtk_tree_model_foreach(model, (GtkTreeModelForeachFunc) cb_check_for_uniqueness, &tmp_key);
}
/* Check for unmodified keys */
if (tmp_key.mask == 0 && tmp_key.keycode != 0)
{
if ((tmp_key.keyval >= GDK_a && tmp_key.keyval <= GDK_z)
|| (tmp_key.keyval >= GDK_A && tmp_key.keyval <= GDK_Z)
|| (tmp_key.keyval >= GDK_0 && tmp_key.keyval <= GDK_9)
|| (tmp_key.keyval >= GDK_kana_fullstop && tmp_key.keyval <= GDK_semivoicedsound)
|| (tmp_key.keyval >= GDK_Arabic_comma && tmp_key.keyval <= GDK_Arabic_sukun)
|| (tmp_key.keyval >= GDK_Serbian_dje && tmp_key.keyval <= GDK_Cyrillic_HARDSIGN)
|| (tmp_key.keyval >= GDK_Greek_ALPHAaccent && tmp_key.keyval <= GDK_Greek_omega)
|| (tmp_key.keyval >= GDK_hebrew_doublelowline && tmp_key.keyval <= GDK_hebrew_taf)
|| (tmp_key.keyval >= GDK_Thai_kokai && tmp_key.keyval <= GDK_Thai_lekkao)
|| (tmp_key.keyval >= GDK_Hangul && tmp_key.keyval <= GDK_Hangul_Special)
|| (tmp_key.keyval >= GDK_Hangul_Kiyeog && tmp_key.keyval <= GDK_Hangul_J_YeorinHieuh)
|| keyval_is_forbidden (tmp_key.keyval))
{
GtkWidget *dialog;
char *name;
name = binding_name (keyval, keycode, mask, TRUE);
dialog = gtk_message_dialog_new (
GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (view))),
GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL,
GTK_MESSAGE_WARNING,
GTK_BUTTONS_CANCEL,
_("The shortcut \"%s\" cannot be used because it will become impossible to type using this key.\n"
"Please try with a key such as Control, Alt or Shift at the same time."),
name);
g_free (name);
gtk_dialog_run (GTK_DIALOG (dialog));
gtk_widget_destroy (dialog);
/* set it back to its previous value. */
egg_cell_renderer_keys_set_accelerator(
EGG_CELL_RENDERER_KEYS(cell),
key_entry->keyval,
key_entry->keycode,
key_entry->mask);
return;
}
}
/* flag to see if the new accelerator was in use by something */
if (!tmp_key.editable)
{
GtkWidget* dialog;
char* name;
int response;
name = binding_name(keyval, keycode, mask, TRUE);
dialog = gtk_message_dialog_new(
GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(view))),
GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL,
GTK_MESSAGE_WARNING,
GTK_BUTTONS_CANCEL,
_("The shortcut \"%s\" is already used for\n\"%s\""),
name,
tmp_key.description ? tmp_key.description : tmp_key.gsettings_key);
g_free (name);
gtk_message_dialog_format_secondary_text (
GTK_MESSAGE_DIALOG (dialog),
_("If you reassign the shortcut to \"%s\", the \"%s\" shortcut "
"will be disabled."),
key_entry->description ? key_entry->description : key_entry->gsettings_key,
tmp_key.description ? tmp_key.description : tmp_key.gsettings_key);
gtk_dialog_add_button(GTK_DIALOG (dialog), _("_Reassign"), GTK_RESPONSE_ACCEPT);
gtk_dialog_set_default_response(GTK_DIALOG (dialog), GTK_RESPONSE_ACCEPT);
response = gtk_dialog_run (GTK_DIALOG (dialog));
gtk_widget_destroy (dialog);
if (response == GTK_RESPONSE_ACCEPT)
{
g_settings_set_string (tmp_key.settings, tmp_key.gsettings_key, "disabled");
str = binding_name (keyval, keycode, mask, FALSE);
g_settings_set_string (key_entry->settings, key_entry->gsettings_key, str);
g_free (str);
}
else
{
/* set it back to its previous value. */
egg_cell_renderer_keys_set_accelerator(
EGG_CELL_RENDERER_KEYS(cell),
key_entry->keyval,
key_entry->keycode,
key_entry->mask);
}
return;
}
str = binding_name (keyval, keycode, mask, FALSE);
g_settings_set_string(
key_entry->settings,
key_entry->gsettings_key,
str);
g_free (str);
}
static void
accel_cleared_callback (GtkCellRendererText *cell,
const char *path_string,
gpointer data)
{
GtkTreeView *view = (GtkTreeView *) data;
GtkTreePath *path = gtk_tree_path_new_from_string (path_string);
KeyEntry *key_entry;
GtkTreeIter iter;
GtkTreeModel *model;
block_accels = FALSE;
model = gtk_tree_view_get_model (view);
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_path_free (path);
gtk_tree_model_get (model, &iter,
KEYENTRY_COLUMN, &key_entry,
-1);
/* sanity check */
if (key_entry == NULL)
return;
/* Unset the key */
g_settings_set_string (key_entry->settings,
key_entry->gsettings_key,
"disabled");
}
static void
description_edited_callback (GtkCellRendererText *renderer,
gchar *path_string,
gchar *new_text,
gpointer user_data)
{
GtkTreeView *view = GTK_TREE_VIEW (user_data);
GtkTreeModel *model;
GtkTreePath *path = gtk_tree_path_new_from_string (path_string);
GtkTreeIter iter;
KeyEntry *key_entry;
model = gtk_tree_view_get_model (view);
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_path_free (path);
gtk_tree_model_get (model, &iter,
KEYENTRY_COLUMN, &key_entry,
-1);
/* sanity check */
if (key_entry == NULL || key_entry->desc_gsettings_key == NULL)
return;
if (!g_settings_set_string (key_entry->settings, key_entry->desc_gsettings_key, new_text))
key_entry->desc_editable = FALSE;
}
typedef struct
{
GtkTreeView *tree_view;
GtkTreePath *path;
GtkTreeViewColumn *column;
} IdleData;
static gboolean
real_start_editing_cb (IdleData *idle_data)
{
gtk_widget_grab_focus (GTK_WIDGET (idle_data->tree_view));
gtk_tree_view_set_cursor (idle_data->tree_view,
idle_data->path,
idle_data->column,
TRUE);
gtk_tree_path_free (idle_data->path);
g_free (idle_data);
return FALSE;
}
static gboolean
edit_custom_shortcut (KeyEntry *key)
{
gint result;
const gchar *text;
gboolean ret;
gtk_entry_set_text (GTK_ENTRY (custom_shortcut_name_entry), key->description ? key->description : "");
gtk_widget_set_sensitive (custom_shortcut_name_entry, key->desc_editable);
gtk_widget_grab_focus (custom_shortcut_name_entry);
gtk_entry_set_text (GTK_ENTRY (custom_shortcut_command_entry), key->command ? key->command : "");
gtk_widget_set_sensitive (custom_shortcut_command_entry, key->cmd_editable);
gtk_window_present (GTK_WINDOW (custom_shortcut_dialog));
result = gtk_dialog_run (GTK_DIALOG (custom_shortcut_dialog));
switch (result)
{
case GTK_RESPONSE_OK:
text = gtk_entry_get_text (GTK_ENTRY (custom_shortcut_name_entry));
g_free (key->description);
key->description = g_strdup (text);
text = gtk_entry_get_text (GTK_ENTRY (custom_shortcut_command_entry));
g_free (key->command);
key->command = g_strdup (text);
ret = TRUE;
break;
default:
ret = FALSE;
break;
}
gtk_widget_hide (custom_shortcut_dialog);
return ret;
}
static gboolean
remove_custom_shortcut (GtkTreeModel *model, GtkTreeIter *iter)
{
GtkTreeIter parent;
KeyEntry *key;
gtk_tree_model_get (model, iter,
KEYENTRY_COLUMN, &key,
-1);
/* not a custom shortcut */
if (key->command == NULL)
return FALSE;
g_signal_handler_disconnect (key->settings, key->gsettings_cnxn);
if (key->gsettings_cnxn_desc != 0)
g_signal_handler_disconnect (key->settings, key->gsettings_cnxn_desc);
if (key->gsettings_cnxn_cmd != 0)
g_signal_handler_disconnect (key->settings, key->gsettings_cnxn_cmd);
dconf_util_recursive_reset (key->gsettings_path, NULL);
g_object_unref (key->settings);
g_free (key->gsettings_path);
g_free (key->gsettings_key);
g_free (key->description);
g_free (key->desc_gsettings_key);
g_free (key->command);
g_free (key->cmd_gsettings_key);
g_free (key);
gtk_tree_model_iter_parent (model, &parent, iter);
gtk_tree_store_remove (GTK_TREE_STORE (model), iter);
if (!gtk_tree_model_iter_has_child (model, &parent))
gtk_tree_store_remove (GTK_TREE_STORE (model), &parent);
return TRUE;
}
static void
update_custom_shortcut (GtkTreeModel *model, GtkTreeIter *iter)
{
KeyEntry *key;
gtk_tree_model_get (model, iter,
KEYENTRY_COLUMN, &key,
-1);
edit_custom_shortcut (key);
if (key->command == NULL || key->command[0] == '\0')
{
remove_custom_shortcut (model, iter);
}
else
{
gtk_tree_store_set (GTK_TREE_STORE (model), iter,
KEYENTRY_COLUMN, key, -1);
if (key->description != NULL)
g_settings_set_string (key->settings, key->desc_gsettings_key, key->description);
else
g_settings_reset (key->settings, key->desc_gsettings_key);
g_settings_set_string (key->settings, key->cmd_gsettings_key, key->command);
}
}
static gchar *
find_free_gsettings_path (GError **error)
{
gchar **existing_dirs;
gchar *dir = NULL;
gchar *fulldir = NULL;
int i;
int j;
gboolean found;
existing_dirs = dconf_util_list_subdirs (GSETTINGS_KEYBINDINGS_DIR, FALSE);
for (i = 0; i < MAX_CUSTOM_SHORTCUTS; i++)
{
found = TRUE;
dir = g_strdup_printf ("custom%d/", i);
for (j = 0; existing_dirs[j] != NULL; j++)
if (!g_strcmp0(dir, existing_dirs[j]))
{
found = FALSE;
g_free (dir);
break;
}
if (found)
break;
}
g_strfreev (existing_dirs);
if (i == MAX_CUSTOM_SHORTCUTS)
{
g_free (dir);
dir = NULL;
g_set_error_literal (error,
g_quark_from_string ("Keyboard Shortcuts"),
0,
_("Too many custom shortcuts"));
}
fulldir = g_strdup_printf ("%s%s", GSETTINGS_KEYBINDINGS_DIR, dir);
g_free (dir);
return fulldir;
}
static void
add_custom_shortcut (GtkTreeView *tree_view,
GtkTreeModel *model)
{
KeyEntry *key_entry;
GtkTreeIter iter;
GtkTreeIter parent_iter;
GtkTreePath *path;
gchar *dir;
GError *error;
error = NULL;
dir = find_free_gsettings_path (&error);
if (dir == NULL)
{
show_error (GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (tree_view))), error);
g_error_free (error);
return;
}
key_entry = g_new0 (KeyEntry, 1);
key_entry->gsettings_path = g_strdup(dir);
key_entry->gsettings_key = g_strdup("binding");
key_entry->editable = TRUE;
key_entry->model = model;
key_entry->desc_gsettings_key = g_strdup("name");
key_entry->description = g_strdup ("");
key_entry->desc_editable = TRUE;
key_entry->cmd_gsettings_key = g_strdup("action");
key_entry->command = g_strdup ("");
key_entry->cmd_editable = TRUE;
g_free (dir);
if (edit_custom_shortcut (key_entry) &&
key_entry->command && key_entry->command[0])
{
find_section (model, &iter, _("Custom Shortcuts"));
parent_iter = iter;
gtk_tree_store_append (GTK_TREE_STORE (model), &iter, &parent_iter);
gtk_tree_store_set (GTK_TREE_STORE (model), &iter, KEYENTRY_COLUMN, key_entry, -1);
/* store in gsettings */
key_entry->settings = g_settings_new_with_path (CUSTOM_KEYBINDING_SCHEMA, key_entry->gsettings_path);
g_settings_set_string (key_entry->settings, key_entry->gsettings_key, "disabled");
g_settings_set_string (key_entry->settings, key_entry->desc_gsettings_key, key_entry->description);
g_settings_set_string (key_entry->settings, key_entry->cmd_gsettings_key, key_entry->command);
/* add gsettings watches */
key_entry->gsettings_cnxn_desc = g_signal_connect (key_entry->settings,
"changed::name",
G_CALLBACK (keybinding_description_changed),
key_entry);
key_entry->gsettings_cnxn_cmd = g_signal_connect (key_entry->settings,
"changed::action",
G_CALLBACK (keybinding_command_changed),
key_entry);
key_entry->gsettings_cnxn = g_signal_connect (key_entry->settings,
"changed::binding",
G_CALLBACK (keybinding_key_changed),
key_entry);
/* make the new shortcut visible */
path = gtk_tree_model_get_path (model, &iter);
gtk_tree_view_expand_to_path (tree_view, path);
gtk_tree_view_scroll_to_cell (tree_view, path, NULL, FALSE, 0, 0);
gtk_tree_path_free (path);
}
else
{
g_free (key_entry->gsettings_path);
g_free (key_entry->gsettings_key);
g_free (key_entry->description);
g_free (key_entry->desc_gsettings_key);
g_free (key_entry->command);
g_free (key_entry->cmd_gsettings_key);
g_free (key_entry);
}
}
static void
start_editing_kb_cb (GtkTreeView *treeview,
GtkTreePath *path,
GtkTreeViewColumn *column,
gpointer user_data)
{
GtkTreeModel *model;
GtkTreeIter iter;
KeyEntry *key;
model = gtk_tree_view_get_model (treeview);
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_model_get (model, &iter,
KEYENTRY_COLUMN, &key,
-1);
if (key == NULL)
{
/* This is a section heading - expand or collapse */
if (gtk_tree_view_row_expanded (treeview, path))
gtk_tree_view_collapse_row (treeview, path);
else
gtk_tree_view_expand_row (treeview, path, FALSE);
return;
}
/* if only the accel can be edited on the selected row
* always select the accel column */
if (key->desc_editable &&
column == gtk_tree_view_get_column (treeview, 0))
{
gtk_widget_grab_focus (GTK_WIDGET (treeview));
gtk_tree_view_set_cursor (treeview, path,
gtk_tree_view_get_column (treeview, 0),
FALSE);
update_custom_shortcut (model, &iter);
}
else
{
gtk_widget_grab_focus (GTK_WIDGET (treeview));
gtk_tree_view_set_cursor (treeview,
path,
gtk_tree_view_get_column (treeview, 1),
TRUE);
}
}
static gboolean
start_editing_cb (GtkTreeView *tree_view,
GdkEventButton *event,
gpointer user_data)
{
GtkTreePath *path;
GtkTreeViewColumn *column;
if (event->window != gtk_tree_view_get_bin_window (tree_view))
return FALSE;
if (gtk_tree_view_get_path_at_pos (tree_view,
(gint) event->x,
(gint) event->y,
&path, &column,
NULL, NULL))
{
IdleData *idle_data;
GtkTreeModel *model;
GtkTreeIter iter;
KeyEntry *key;
if (gtk_tree_path_get_depth (path) == 1)
{
gtk_tree_path_free (path);
return FALSE;
}
model = gtk_tree_view_get_model (tree_view);
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_model_get (model, &iter,
KEYENTRY_COLUMN, &key,
-1);
/* if only the accel can be edited on the selected row
* always select the accel column */
if (key->desc_editable &&
column == gtk_tree_view_get_column (tree_view, 0))
{
gtk_widget_grab_focus (GTK_WIDGET (tree_view));
gtk_tree_view_set_cursor (tree_view, path,
gtk_tree_view_get_column (tree_view, 0),
FALSE);
update_custom_shortcut (model, &iter);
}
else
{
idle_data = g_new (IdleData, 1);
idle_data->tree_view = tree_view;
idle_data->path = path;
idle_data->column = key->desc_editable ? column :
gtk_tree_view_get_column (tree_view, 1);
g_idle_add ((GSourceFunc) real_start_editing_cb, idle_data);
block_accels = TRUE;
}
g_signal_stop_emission_by_name (tree_view, "button_press_event");
}
return TRUE;
}
/* this handler is used to keep accels from activating while the user
* is assigning a new shortcut so that he won't accidentally trigger one
* of the widgets */
static gboolean maybe_block_accels(GtkWidget* widget, GdkEventKey* event, gpointer user_data)
{
if (block_accels)
{
return gtk_window_propagate_key_event(GTK_WINDOW(widget), event);
}
return FALSE;
}
static void
cb_dialog_response (GtkWidget *widget, gint response_id, gpointer data)
{
GtkBuilder *builder = data;
GtkTreeView *treeview;
GtkTreeModel *model;
GtkTreeSelection *selection;
GtkTreeIter iter;
treeview = GTK_TREE_VIEW (gtk_builder_get_object (builder,
"shortcut_treeview"));
model = gtk_tree_view_get_model (treeview);
if (response_id == GTK_RESPONSE_HELP)
{
capplet_help (GTK_WINDOW (widget),
"goscustdesk-39");
}
else if (response_id == RESPONSE_ADD)
{
add_custom_shortcut (treeview, model);
}
else if (response_id == RESPONSE_REMOVE)
{
selection = gtk_tree_view_get_selection (treeview);
if (gtk_tree_selection_get_selected (selection, NULL, &iter))
{
remove_custom_shortcut (model, &iter);
}
}
else
{
clear_old_model (builder);
gtk_main_quit ();
}
}
static void
selection_changed (GtkTreeSelection *selection, gpointer data)
{
GtkWidget *button = data;
GtkTreeModel *model;
GtkTreeIter iter;
KeyEntry *key;
gboolean can_remove;
can_remove = FALSE;
if (gtk_tree_selection_get_selected (selection, &model, &iter))
{
gtk_tree_model_get (model, &iter, KEYENTRY_COLUMN, &key, -1);
if (key && key->command != NULL && key->editable)
can_remove = TRUE;
}
gtk_widget_set_sensitive (button, can_remove);
}
static void
setup_dialog (GtkBuilder *builder, GSettings *marco_settings)
{
GtkCellRenderer *renderer;
GtkTreeViewColumn *column;
GtkWidget *widget;
GtkTreeView *treeview;
GtkTreeSelection *selection;
treeview = GTK_TREE_VIEW (gtk_builder_get_object (builder,
"shortcut_treeview"));
g_signal_connect (treeview, "button_press_event",
G_CALLBACK (start_editing_cb), builder);
g_signal_connect (treeview, "row-activated",
G_CALLBACK (start_editing_kb_cb), NULL);
renderer = gtk_cell_renderer_text_new ();
g_signal_connect (renderer, "edited",
G_CALLBACK (description_edited_callback),
treeview);
column = gtk_tree_view_column_new_with_attributes (_("Action"),
renderer,
"text", DESCRIPTION_COLUMN,
NULL);
gtk_tree_view_column_set_cell_data_func (column, renderer, description_set_func, NULL, NULL);
gtk_tree_view_column_set_resizable (column, FALSE);
gtk_tree_view_append_column (treeview, column);
gtk_tree_view_column_set_sort_column_id (column, DESCRIPTION_COLUMN);
renderer = (GtkCellRenderer *) g_object_new (EGG_TYPE_CELL_RENDERER_KEYS,
"accel_mode", EGG_CELL_RENDERER_KEYS_MODE_X,
NULL);
g_signal_connect (renderer, "accel_edited",
G_CALLBACK (accel_edited_callback),
treeview);
g_signal_connect (renderer, "accel_cleared",
G_CALLBACK (accel_cleared_callback),
treeview);
column = gtk_tree_view_column_new_with_attributes (_("Shortcut"), renderer, NULL);
gtk_tree_view_column_set_cell_data_func (column, renderer, accel_set_func, NULL, NULL);
gtk_tree_view_column_set_resizable (column, FALSE);
gtk_tree_view_append_column (treeview, column);
gtk_tree_view_column_set_sort_column_id (column, KEYENTRY_COLUMN);
g_signal_connect (marco_settings,
"changed::num-workspaces",
G_CALLBACK (key_entry_controlling_key_changed),
builder);
/* set up the dialog */
reload_key_entries (builder);
#if GTK_CHECK_VERSION(3, 0, 0)
widget = _gtk_builder_get_widget (builder, "mate-keybinding-dialog");
gtk_window_set_default_size (GTK_WINDOW (widget), 400, 500);
widget = _gtk_builder_get_widget (builder, "label-suggest");
gtk_label_set_line_wrap (GTK_LABEL (widget), TRUE);
gtk_label_set_max_width_chars (GTK_LABEL (widget), 60);
#endif
widget = _gtk_builder_get_widget (builder, "mate-keybinding-dialog");
capplet_set_icon (widget, "preferences-desktop-keyboard-shortcuts");
gtk_widget_show (widget);
g_signal_connect (widget, "key_press_event", G_CALLBACK (maybe_block_accels), NULL);
g_signal_connect (widget, "response", G_CALLBACK (cb_dialog_response), builder);
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview));
g_signal_connect (selection, "changed",
G_CALLBACK (selection_changed),
_gtk_builder_get_widget (builder, "remove-button"));
/* setup the custom shortcut dialog */
custom_shortcut_dialog = _gtk_builder_get_widget (builder,
"custom-shortcut-dialog");
custom_shortcut_name_entry = _gtk_builder_get_widget (builder,
"custom-shortcut-name-entry");
custom_shortcut_command_entry = _gtk_builder_get_widget (builder,
"custom-shortcut-command-entry");
gtk_dialog_set_default_response (GTK_DIALOG (custom_shortcut_dialog),
GTK_RESPONSE_OK);
gtk_window_set_transient_for (GTK_WINDOW (custom_shortcut_dialog),
GTK_WINDOW (widget));
}
static void
on_window_manager_change (const char *wm_name, GtkBuilder *builder)
{
reload_key_entries (builder);
}
int
main (int argc, char *argv[])
{
GtkBuilder *builder;
GSettings *marco_settings;
gtk_init (&argc, &argv);
bindtextdomain (GETTEXT_PACKAGE, MATELOCALEDIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
textdomain (GETTEXT_PACKAGE);
gtk_init (&argc, &argv);
activate_settings_daemon ();
builder = create_builder ();
if (!builder) /* Warning was already printed to console */
exit (EXIT_FAILURE);
wm_common_register_window_manager_change ((GFunc) on_window_manager_change, builder);
marco_settings = g_settings_new ("org.mate.Marco.general");
setup_dialog (builder, marco_settings);
gtk_main ();
g_object_unref (marco_settings);
g_object_unref (builder);
return 0;
}
/*
* vim: sw=2 ts=8 cindent noai bs=2
*/
| Java |
jQuery('#bootstrapslider').carousel({
interval: bootstrapslider_script_vars.interval,
pause: bootstrapslider_script_vars.pause,
wrap: bootstrapslider_script_vars.wrap
});
| Java |
/******************************************************************************
*
* Copyright (C) 1997-2013 by Dimitri van Heesch.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation under the terms of the GNU General Public License is hereby
* granted. No representations are made about the suitability of this software
* for any purpose. It is provided "as is" without express or implied warranty.
* See the GNU General Public License for more details.
*
* Documents produced by Doxygen are derivative works derived from the
* input used in their production; they are not affected by this license.
*
*/
#include <stdlib.h>
#include <qdir.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qintdict.h>
#include "xmlgen.h"
#include "doxygen.h"
#include "message.h"
#include "config.h"
#include "classlist.h"
#include "util.h"
#include "defargs.h"
#include "outputgen.h"
#include "dot.h"
#include "pagedef.h"
#include "filename.h"
#include "version.h"
#include "xmldocvisitor.h"
#include "docparser.h"
#include "language.h"
#include "parserintf.h"
#include "arguments.h"
#include "memberlist.h"
#include "groupdef.h"
#include "memberdef.h"
#include "namespacedef.h"
#include "membername.h"
#include "membergroup.h"
#include "dirdef.h"
#include "section.h"
// no debug info
#define XML_DB(x) do {} while(0)
// debug to stdout
//#define XML_DB(x) printf x
// debug inside output
//#define XML_DB(x) QCString __t;__t.sprintf x;m_t << __t
//------------------
static const char index_xsd[] =
#include "index_xsd.h"
;
//------------------
//
static const char compound_xsd[] =
#include "compound_xsd.h"
;
//------------------
/** Helper class mapping MemberList::ListType to a string representing */
class XmlSectionMapper : public QIntDict<char>
{
public:
XmlSectionMapper() : QIntDict<char>(47)
{
insert(MemberListType_pubTypes,"public-type");
insert(MemberListType_pubMethods,"public-func");
insert(MemberListType_pubAttribs,"public-attrib");
insert(MemberListType_pubSlots,"public-slot");
insert(MemberListType_signals,"signal");
insert(MemberListType_dcopMethods,"dcop-func");
insert(MemberListType_properties,"property");
insert(MemberListType_events,"event");
insert(MemberListType_pubStaticMethods,"public-static-func");
insert(MemberListType_pubStaticAttribs,"public-static-attrib");
insert(MemberListType_proTypes,"protected-type");
insert(MemberListType_proMethods,"protected-func");
insert(MemberListType_proAttribs,"protected-attrib");
insert(MemberListType_proSlots,"protected-slot");
insert(MemberListType_proStaticMethods,"protected-static-func");
insert(MemberListType_proStaticAttribs,"protected-static-attrib");
insert(MemberListType_pacTypes,"package-type");
insert(MemberListType_pacMethods,"package-func");
insert(MemberListType_pacAttribs,"package-attrib");
insert(MemberListType_pacStaticMethods,"package-static-func");
insert(MemberListType_pacStaticAttribs,"package-static-attrib");
insert(MemberListType_priTypes,"private-type");
insert(MemberListType_priMethods,"private-func");
insert(MemberListType_priAttribs,"private-attrib");
insert(MemberListType_priSlots,"private-slot");
insert(MemberListType_priStaticMethods,"private-static-func");
insert(MemberListType_priStaticAttribs,"private-static-attrib");
insert(MemberListType_friends,"friend");
insert(MemberListType_related,"related");
insert(MemberListType_decDefineMembers,"define");
insert(MemberListType_decProtoMembers,"prototype");
insert(MemberListType_decTypedefMembers,"typedef");
insert(MemberListType_decEnumMembers,"enum");
insert(MemberListType_decFuncMembers,"func");
insert(MemberListType_decVarMembers,"var");
}
};
static XmlSectionMapper g_xmlSectionMapper;
inline void writeXMLString(FTextStream &t,const char *s)
{
t << convertToXML(s);
}
inline void writeXMLCodeString(FTextStream &t,const char *s, int &col)
{
char c;
while ((c=*s++))
{
switch(c)
{
case '\t':
{
static int tabSize = Config_getInt("TAB_SIZE");
int spacesToNextTabStop = tabSize - (col%tabSize);
col+=spacesToNextTabStop;
while (spacesToNextTabStop--) t << "<sp/>";
break;
}
case ' ': t << "<sp/>"; col++; break;
case '<': t << "<"; col++; break;
case '>': t << ">"; col++; break;
case '&': t << "&"; col++; break;
case '\'': t << "'"; col++; break;
case '"': t << """; col++; break;
default: t << c; col++; break;
}
}
}
static void writeXMLHeader(FTextStream &t)
{
t << "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" << endl;;
t << "<doxygen xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ";
t << "xsi:noNamespaceSchemaLocation=\"compound.xsd\" ";
t << "version=\"" << versionString << "\">" << endl;
}
static void writeCombineScript()
{
QCString outputDirectory = Config_getString("XML_OUTPUT");
QCString fileName=outputDirectory+"/combine.xslt";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
t <<
"<!-- XSLT script to combine the generated output into a single file. \n"
" If you have xsltproc you could use:\n"
" xsltproc combine.xslt index.xml >all.xml\n"
"-->\n"
"<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n"
" <xsl:output method=\"xml\" version=\"1.0\" indent=\"no\" standalone=\"yes\" />\n"
" <xsl:template match=\"/\">\n"
" <doxygen version=\"{doxygenindex/@version}\">\n"
" <!-- Load all doxgen generated xml files -->\n"
" <xsl:for-each select=\"doxygenindex/compound\">\n"
" <xsl:copy-of select=\"document( concat( @refid, '.xml' ) )/doxygen/*\" />\n"
" </xsl:for-each>\n"
" </doxygen>\n"
" </xsl:template>\n"
"</xsl:stylesheet>\n";
}
void writeXMLLink(FTextStream &t,const char *extRef,const char *compoundId,
const char *anchorId,const char *text,const char *tooltip)
{
t << "<ref refid=\"" << compoundId;
if (anchorId) t << "_1" << anchorId;
t << "\" kindref=\"";
if (anchorId) t << "member"; else t << "compound";
t << "\"";
if (extRef) t << " external=\"" << extRef << "\"";
if (tooltip) t << " tooltip=\"" << convertToXML(tooltip) << "\"";
t << ">";
writeXMLString(t,text);
t << "</ref>";
}
/** Implements TextGeneratorIntf for an XML stream. */
class TextGeneratorXMLImpl : public TextGeneratorIntf
{
public:
TextGeneratorXMLImpl(FTextStream &t): m_t(t) {}
void writeString(const char *s,bool /*keepSpaces*/) const
{
writeXMLString(m_t,s);
}
void writeBreak(int) const {}
void writeLink(const char *extRef,const char *file,
const char *anchor,const char *text
) const
{
writeXMLLink(m_t,extRef,file,anchor,text,0);
}
private:
FTextStream &m_t;
};
/** Helper class representing a stack of objects stored by value */
template<class T> class ValStack
{
public:
ValStack() : m_values(10), m_sp(0), m_size(10) {}
virtual ~ValStack() {}
ValStack(const ValStack<T> &s)
{
m_values=s.m_values.copy();
m_sp=s.m_sp;
m_size=s.m_size;
}
ValStack &operator=(const ValStack<T> &s)
{
m_values=s.m_values.copy();
m_sp=s.m_sp;
m_size=s.m_size;
return *this;
}
void push(T v)
{
m_sp++;
if (m_sp>=m_size)
{
m_size+=10;
m_values.resize(m_size);
}
m_values[m_sp]=v;
}
T pop()
{
ASSERT(m_sp!=0);
return m_values[m_sp--];
}
T& top()
{
ASSERT(m_sp!=0);
return m_values[m_sp];
}
bool isEmpty()
{
return m_sp==0;
}
uint count() const
{
return m_sp;
}
private:
QArray<T> m_values;
int m_sp;
int m_size;
};
/** Generator for producing XML formatted source code. */
class XMLCodeGenerator : public CodeOutputInterface
{
public:
XMLCodeGenerator(FTextStream &t) : m_t(t), m_lineNumber(-1),
m_insideCodeLine(FALSE), m_normalHLNeedStartTag(TRUE),
m_insideSpecialHL(FALSE) {}
virtual ~XMLCodeGenerator() { }
void codify(const char *text)
{
XML_DB(("(codify \"%s\")\n",text));
if (m_insideCodeLine && !m_insideSpecialHL && m_normalHLNeedStartTag)
{
m_t << "<highlight class=\"normal\">";
m_normalHLNeedStartTag=FALSE;
}
writeXMLCodeString(m_t,text,col);
}
void writeCodeLink(const char *ref,const char *file,
const char *anchor,const char *name,
const char *tooltip)
{
XML_DB(("(writeCodeLink)\n"));
if (m_insideCodeLine && !m_insideSpecialHL && m_normalHLNeedStartTag)
{
m_t << "<highlight class=\"normal\">";
m_normalHLNeedStartTag=FALSE;
}
writeXMLLink(m_t,ref,file,anchor,name,tooltip);
col+=qstrlen(name);
}
void startCodeLine(bool)
{
XML_DB(("(startCodeLine)\n"));
m_t << "<codeline";
if (m_lineNumber!=-1)
{
m_t << " lineno=\"" << m_lineNumber << "\"";
if (!m_refId.isEmpty())
{
m_t << " refid=\"" << m_refId << "\"";
if (m_isMemberRef)
{
m_t << " refkind=\"member\"";
}
else
{
m_t << " refkind=\"compound\"";
}
}
if (!m_external.isEmpty())
{
m_t << " external=\"" << m_external << "\"";
}
}
m_t << ">";
m_insideCodeLine=TRUE;
col=0;
}
void endCodeLine()
{
XML_DB(("(endCodeLine)\n"));
if (!m_insideSpecialHL && !m_normalHLNeedStartTag)
{
m_t << "</highlight>";
m_normalHLNeedStartTag=TRUE;
}
m_t << "</codeline>" << endl; // non DocBook
m_lineNumber = -1;
m_refId.resize(0);
m_external.resize(0);
m_insideCodeLine=FALSE;
}
void startCodeAnchor(const char *id)
{
XML_DB(("(startCodeAnchor)\n"));
if (m_insideCodeLine && !m_insideSpecialHL && m_normalHLNeedStartTag)
{
m_t << "<highlight class=\"normal\">";
m_normalHLNeedStartTag=FALSE;
}
m_t << "<anchor id=\"" << id << "\">";
}
void endCodeAnchor()
{
XML_DB(("(endCodeAnchor)\n"));
m_t << "</anchor>";
}
void startFontClass(const char *colorClass)
{
XML_DB(("(startFontClass)\n"));
if (m_insideCodeLine && !m_insideSpecialHL && !m_normalHLNeedStartTag)
{
m_t << "</highlight>";
m_normalHLNeedStartTag=TRUE;
}
m_t << "<highlight class=\"" << colorClass << "\">"; // non DocBook
m_insideSpecialHL=TRUE;
}
void endFontClass()
{
XML_DB(("(endFontClass)\n"));
m_t << "</highlight>"; // non DocBook
m_insideSpecialHL=FALSE;
}
void writeCodeAnchor(const char *)
{
XML_DB(("(writeCodeAnchor)\n"));
}
void writeLineNumber(const char *extRef,const char *compId,
const char *anchorId,int l)
{
XML_DB(("(writeLineNumber)\n"));
// we remember the information provided here to use it
// at the <codeline> start tag.
m_lineNumber = l;
if (compId)
{
m_refId=compId;
if (anchorId) m_refId+=(QCString)"_1"+anchorId;
m_isMemberRef = anchorId!=0;
if (extRef) m_external=extRef;
}
}
void linkableSymbol(int, const char *,Definition *,Definition *)
{
}
void setCurrentDoc(Definition *,const char *,bool)
{
}
void addWord(const char *,bool)
{
}
void finish()
{
if (m_insideCodeLine) endCodeLine();
}
private:
FTextStream &m_t;
QCString m_refId;
QCString m_external;
int m_lineNumber;
bool m_isMemberRef;
int col;
bool m_insideCodeLine;
bool m_normalHLNeedStartTag;
bool m_insideSpecialHL;
};
static void writeTemplateArgumentList(ArgumentList *al,
FTextStream &t,
Definition *scope,
FileDef *fileScope,
int indent)
{
QCString indentStr;
indentStr.fill(' ',indent);
if (al)
{
t << indentStr << "<templateparamlist>" << endl;
ArgumentListIterator ali(*al);
Argument *a;
for (ali.toFirst();(a=ali.current());++ali)
{
t << indentStr << " <param>" << endl;
if (!a->type.isEmpty())
{
t << indentStr << " <type>";
linkifyText(TextGeneratorXMLImpl(t),scope,fileScope,0,a->type);
t << "</type>" << endl;
}
if (!a->name.isEmpty())
{
t << indentStr << " <declname>" << a->name << "</declname>" << endl;
t << indentStr << " <defname>" << a->name << "</defname>" << endl;
}
if (!a->defval.isEmpty())
{
t << indentStr << " <defval>";
linkifyText(TextGeneratorXMLImpl(t),scope,fileScope,0,a->defval);
t << "</defval>" << endl;
}
t << indentStr << " </param>" << endl;
}
t << indentStr << "</templateparamlist>" << endl;
}
}
static void writeMemberTemplateLists(MemberDef *md,FTextStream &t)
{
LockingPtr<ArgumentList> templMd = md->templateArguments();
if (templMd!=0) // function template prefix
{
writeTemplateArgumentList(templMd.pointer(),t,md->getClassDef(),md->getFileDef(),8);
}
}
static void writeTemplateList(ClassDef *cd,FTextStream &t)
{
writeTemplateArgumentList(cd->templateArguments(),t,cd,0,4);
}
static void writeXMLDocBlock(FTextStream &t,
const QCString &fileName,
int lineNr,
Definition *scope,
MemberDef * md,
const QCString &text)
{
QCString stext = text.stripWhiteSpace();
if (stext.isEmpty()) return;
// convert the documentation string into an abstract syntax tree
DocNode *root = validatingParseDoc(fileName,lineNr,scope,md,text+"\n",FALSE,FALSE);
// create a code generator
XMLCodeGenerator *xmlCodeGen = new XMLCodeGenerator(t);
// create a parse tree visitor for XML
XmlDocVisitor *visitor = new XmlDocVisitor(t,*xmlCodeGen);
// visit all nodes
root->accept(visitor);
// clean up
delete visitor;
delete xmlCodeGen;
delete root;
}
void writeXMLCodeBlock(FTextStream &t,FileDef *fd)
{
ParserInterface *pIntf=Doxygen::parserManager->getParser(fd->getDefFileExtension());
pIntf->resetCodeParserState();
XMLCodeGenerator *xmlGen = new XMLCodeGenerator(t);
pIntf->parseCode(*xmlGen, // codeOutIntf
0, // scopeName
fileToString(fd->absFilePath(),Config_getBool("FILTER_SOURCE_FILES")),
FALSE, // isExampleBlock
0, // exampleName
fd, // fileDef
-1, // startLine
-1, // endLine
FALSE, // inlineFragement
0, // memberDef
TRUE // showLineNumbers
);
xmlGen->finish();
delete xmlGen;
}
static void writeMemberReference(FTextStream &t,Definition *def,MemberDef *rmd,const char *tagName)
{
QCString scope = rmd->getScopeString();
QCString name = rmd->name();
if (!scope.isEmpty() && scope!=def->name())
{
name.prepend(scope+getLanguageSpecificSeparator(rmd->getLanguage()));
}
t << " <" << tagName << " refid=\"";
t << rmd->getOutputFileBase() << "_1" << rmd->anchor() << "\"";
if (rmd->getStartBodyLine()!=-1 && rmd->getBodyDef())
{
t << " compoundref=\"" << rmd->getBodyDef()->getOutputFileBase() << "\"";
t << " startline=\"" << rmd->getStartBodyLine() << "\"";
if (rmd->getEndBodyLine()!=-1)
{
t << " endline=\"" << rmd->getEndBodyLine() << "\"";
}
}
t << ">" << convertToXML(name) << "</" << tagName << ">" << endl;
}
static void stripQualifiers(QCString &typeStr)
{
bool done=FALSE;
while (!done)
{
if (typeStr.stripPrefix("static "));
else if (typeStr.stripPrefix("virtual "));
else if (typeStr.stripPrefix("volatile "));
else if (typeStr=="virtual") typeStr="";
else done=TRUE;
}
}
static QCString classOutputFileBase(ClassDef *cd)
{
//static bool inlineGroupedClasses = Config_getBool("INLINE_GROUPED_CLASSES");
//if (inlineGroupedClasses && cd->partOfGroups()!=0)
return cd->getOutputFileBase();
//else
// return cd->getOutputFileBase();
}
static QCString memberOutputFileBase(MemberDef *md)
{
//static bool inlineGroupedClasses = Config_getBool("INLINE_GROUPED_CLASSES");
//if (inlineGroupedClasses && md->getClassDef() && md->getClassDef()->partOfGroups()!=0)
// return md->getClassDef()->getXmlOutputFileBase();
//else
// return md->getOutputFileBase();
return md->getOutputFileBase();
}
static void generateXMLForMember(MemberDef *md,FTextStream &ti,FTextStream &t,Definition *def)
{
// + declaration/definition arg lists
// + reimplements
// + reimplementedBy
// + exceptions
// + const/volatile specifiers
// - examples
// + source definition
// + source references
// + source referenced by
// - body code
// + template arguments
// (templateArguments(), definitionTemplateParameterLists())
// - call graph
// enum values are written as part of the enum
if (md->memberType()==MemberType_EnumValue) return;
if (md->isHidden()) return;
//if (md->name().at(0)=='@') return; // anonymous member
// group members are only visible in their group
//if (def->definitionType()!=Definition::TypeGroup && md->getGroupDef()) return;
QCString memType;
bool isFunc=FALSE;
switch (md->memberType())
{
case MemberType_Define: memType="define"; break;
case MemberType_EnumValue: ASSERT(0); break;
case MemberType_Property: memType="property"; break;
case MemberType_Event: memType="event"; break;
case MemberType_Variable: memType="variable"; break;
case MemberType_Typedef: memType="typedef"; break;
case MemberType_Enumeration: memType="enum"; break;
case MemberType_Function: memType="function"; isFunc=TRUE; break;
case MemberType_Signal: memType="signal"; isFunc=TRUE; break;
case MemberType_Friend: memType="friend"; isFunc=TRUE; break;
case MemberType_DCOP: memType="dcop"; isFunc=TRUE; break;
case MemberType_Slot: memType="slot"; isFunc=TRUE; break;
}
ti << " <member refid=\"" << memberOutputFileBase(md)
<< "_1" << md->anchor() << "\" kind=\"" << memType << "\"><name>"
<< convertToXML(md->name()) << "</name></member>" << endl;
QCString scopeName;
if (md->getClassDef())
scopeName=md->getClassDef()->name();
else if (md->getNamespaceDef())
scopeName=md->getNamespaceDef()->name();
t << " <memberdef kind=\"";
//enum { define_t,variable_t,typedef_t,enum_t,function_t } xmlType = function_t;
t << memType << "\" id=\"";
if (md->getGroupDef() && def->definitionType()==Definition::TypeGroup)
{
t << md->getGroupDef()->getOutputFileBase();
}
else
{
t << memberOutputFileBase(md);
}
t << "_1" // encoded `:' character (see util.cpp:convertNameToFile)
<< md->anchor();
t << "\" prot=\"";
switch(md->protection())
{
case Public: t << "public"; break;
case Protected: t << "protected"; break;
case Private: t << "private"; break;
case Package: t << "package"; break;
}
t << "\"";
t << " static=\"";
if (md->isStatic()) t << "yes"; else t << "no";
t << "\"";
if (isFunc)
{
LockingPtr<ArgumentList> al = md->argumentList();
t << " const=\"";
if (al!=0 && al->constSpecifier) t << "yes"; else t << "no";
t << "\"";
t << " explicit=\"";
if (md->isExplicit()) t << "yes"; else t << "no";
t << "\"";
t << " inline=\"";
if (md->isInline()) t << "yes"; else t << "no";
t << "\"";
if (md->isFinal())
{
t << " final=\"yes\"";
}
if (md->isSealed())
{
t << " sealed=\"yes\"";
}
if (md->isNew())
{
t << " new=\"yes\"";
}
if (md->isOptional())
{
t << " optional=\"yes\"";
}
if (md->isRequired())
{
t << " required=\"yes\"";
}
t << " virt=\"";
switch (md->virtualness())
{
case Normal: t << "non-virtual"; break;
case Virtual: t << "virtual"; break;
case Pure: t << "pure-virtual"; break;
default: ASSERT(0);
}
t << "\"";
}
if (md->memberType() == MemberType_Variable)
{
//ArgumentList *al = md->argumentList();
//t << " volatile=\"";
//if (al && al->volatileSpecifier) t << "yes"; else t << "no";
t << " mutable=\"";
if (md->isMutable()) t << "yes"; else t << "no";
t << "\"";
if (md->isInitonly())
{
t << " initonly=\"yes\"";
}
}
else if (md->memberType() == MemberType_Property)
{
t << " readable=\"";
if (md->isReadable()) t << "yes"; else t << "no";
t << "\"";
t << " writable=\"";
if (md->isWritable()) t << "yes"; else t << "no";
t << "\"";
t << " gettable=\"";
if (md->isGettable()) t << "yes"; else t << "no";
t << "\"";
t << " settable=\"";
if (md->isSettable()) t << "yes"; else t << "no";
t << "\"";
if (md->isAssign() || md->isCopy() || md->isRetain() || md->isStrong() || md->isWeak())
{
t << " accessor=\"";
if (md->isAssign()) t << "assign";
else if (md->isCopy()) t << "copy";
else if (md->isRetain()) t << "retain";
else if (md->isStrong()) t << "strong";
else if (md->isWeak()) t << "weak";
t << "\"";
}
}
else if (md->memberType() == MemberType_Event)
{
t << " add=\"";
if (md->isAddable()) t << "yes"; else t << "no";
t << "\"";
t << " remove=\"";
if (md->isRemovable()) t << "yes"; else t << "no";
t << "\"";
t << " raise=\"";
if (md->isRaisable()) t << "yes"; else t << "no";
t << "\"";
}
t << ">" << endl;
if (md->memberType()!=MemberType_Define &&
md->memberType()!=MemberType_Enumeration
)
{
if (md->memberType()!=MemberType_Typedef)
{
writeMemberTemplateLists(md,t);
}
QCString typeStr = md->typeString(); //replaceAnonymousScopes(md->typeString());
stripQualifiers(typeStr);
t << " <type>";
linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,typeStr);
t << "</type>" << endl;
t << " <definition>" << convertToXML(md->definition()) << "</definition>" << endl;
t << " <argsstring>" << convertToXML(md->argsString()) << "</argsstring>" << endl;
}
t << " <name>" << convertToXML(md->name()) << "</name>" << endl;
if (md->memberType() == MemberType_Property)
{
if (md->isReadable())
t << " <read>" << convertToXML(md->getReadAccessor()) << "</read>" << endl;
if (md->isWritable())
t << " <write>" << convertToXML(md->getWriteAccessor()) << "</write>" << endl;
}
if (md->memberType()==MemberType_Variable && md->bitfieldString())
{
QCString bitfield = md->bitfieldString();
if (bitfield.at(0)==':') bitfield=bitfield.mid(1);
t << " <bitfield>" << bitfield << "</bitfield>" << endl;
}
MemberDef *rmd = md->reimplements();
if (rmd)
{
t << " <reimplements refid=\""
<< memberOutputFileBase(rmd) << "_1" << rmd->anchor() << "\">"
<< convertToXML(rmd->name()) << "</reimplements>" << endl;
}
LockingPtr<MemberList> rbml = md->reimplementedBy();
if (rbml!=0)
{
MemberListIterator mli(*rbml);
for (mli.toFirst();(rmd=mli.current());++mli)
{
t << " <reimplementedby refid=\""
<< memberOutputFileBase(rmd) << "_1" << rmd->anchor() << "\">"
<< convertToXML(rmd->name()) << "</reimplementedby>" << endl;
}
}
if (isFunc) //function
{
LockingPtr<ArgumentList> declAl = md->declArgumentList();
LockingPtr<ArgumentList> defAl = md->argumentList();
if (declAl!=0 && declAl->count()>0)
{
ArgumentListIterator declAli(*declAl);
ArgumentListIterator defAli(*defAl);
Argument *a;
for (declAli.toFirst();(a=declAli.current());++declAli)
{
Argument *defArg = defAli.current();
t << " <param>" << endl;
if (!a->attrib.isEmpty())
{
t << " <attributes>";
writeXMLString(t,a->attrib);
t << "</attributes>" << endl;
}
if (!a->type.isEmpty())
{
t << " <type>";
linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,a->type);
t << "</type>" << endl;
}
if (!a->name.isEmpty())
{
t << " <declname>";
writeXMLString(t,a->name);
t << "</declname>" << endl;
}
if (defArg && !defArg->name.isEmpty() && defArg->name!=a->name)
{
t << " <defname>";
writeXMLString(t,defArg->name);
t << "</defname>" << endl;
}
if (!a->array.isEmpty())
{
t << " <array>";
writeXMLString(t,a->array);
t << "</array>" << endl;
}
if (!a->defval.isEmpty())
{
t << " <defval>";
linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,a->defval);
t << "</defval>" << endl;
}
if (defArg && defArg->hasDocumentation())
{
t << " <briefdescription>";
writeXMLDocBlock(t,md->getDefFileName(),md->getDefLine(),
md->getOuterScope(),md,defArg->docs);
t << "</briefdescription>" << endl;
}
t << " </param>" << endl;
if (defArg) ++defAli;
}
}
}
else if (md->memberType()==MemberType_Define &&
md->argsString()) // define
{
if (md->argumentList()->count()==0) // special case for "foo()" to
// disguish it from "foo".
{
t << " <param></param>" << endl;
}
else
{
ArgumentListIterator ali(*md->argumentList());
Argument *a;
for (ali.toFirst();(a=ali.current());++ali)
{
t << " <param><defname>" << a->type << "</defname></param>" << endl;
}
}
}
// avoid that extremely large tables are written to the output.
// todo: it's better to adhere to MAX_INITIALIZER_LINES.
if (!md->initializer().isEmpty() && md->initializer().length()<2000)
{
t << " <initializer>";
linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,md->initializer());
t << "</initializer>" << endl;
}
if (md->excpString())
{
t << " <exceptions>";
linkifyText(TextGeneratorXMLImpl(t),def,md->getBodyDef(),md,md->excpString());
t << "</exceptions>" << endl;
}
if (md->memberType()==MemberType_Enumeration) // enum
{
LockingPtr<MemberList> enumFields = md->enumFieldList();
if (enumFields!=0)
{
MemberListIterator emli(*enumFields);
MemberDef *emd;
for (emli.toFirst();(emd=emli.current());++emli)
{
ti << " <member refid=\"" << memberOutputFileBase(emd)
<< "_1" << emd->anchor() << "\" kind=\"enumvalue\"><name>"
<< convertToXML(emd->name()) << "</name></member>" << endl;
t << " <enumvalue id=\"" << memberOutputFileBase(emd) << "_1"
<< emd->anchor() << "\" prot=\"";
switch (emd->protection())
{
case Public: t << "public"; break;
case Protected: t << "protected"; break;
case Private: t << "private"; break;
case Package: t << "package"; break;
}
t << "\">" << endl;
t << " <name>";
writeXMLString(t,emd->name());
t << "</name>" << endl;
if (!emd->initializer().isEmpty())
{
t << " <initializer>";
writeXMLString(t,emd->initializer());
t << "</initializer>" << endl;
}
t << " <briefdescription>" << endl;
writeXMLDocBlock(t,emd->briefFile(),emd->briefLine(),emd->getOuterScope(),emd,emd->briefDescription());
t << " </briefdescription>" << endl;
t << " <detaileddescription>" << endl;
writeXMLDocBlock(t,emd->docFile(),emd->docLine(),emd->getOuterScope(),emd,emd->documentation());
t << " </detaileddescription>" << endl;
t << " </enumvalue>" << endl;
}
}
}
t << " <briefdescription>" << endl;
writeXMLDocBlock(t,md->briefFile(),md->briefLine(),md->getOuterScope(),md,md->briefDescription());
t << " </briefdescription>" << endl;
t << " <detaileddescription>" << endl;
writeXMLDocBlock(t,md->docFile(),md->docLine(),md->getOuterScope(),md,md->documentation());
t << " </detaileddescription>" << endl;
t << " <inbodydescription>" << endl;
writeXMLDocBlock(t,md->docFile(),md->inbodyLine(),md->getOuterScope(),md,md->inbodyDocumentation());
t << " </inbodydescription>" << endl;
if (md->getDefLine()!=-1)
{
t << " <location file=\""
<< md->getDefFileName() << "\" line=\""
<< md->getDefLine() << "\"";
if (md->getStartBodyLine()!=-1)
{
FileDef *bodyDef = md->getBodyDef();
if (bodyDef)
{
t << " bodyfile=\"" << bodyDef->absFilePath() << "\"";
}
t << " bodystart=\"" << md->getStartBodyLine() << "\" bodyend=\""
<< md->getEndBodyLine() << "\"";
}
t << "/>" << endl;
}
//printf("md->getReferencesMembers()=%p\n",md->getReferencesMembers());
LockingPtr<MemberSDict> mdict = md->getReferencesMembers();
if (mdict!=0)
{
MemberSDict::Iterator mdi(*mdict);
MemberDef *rmd;
for (mdi.toFirst();(rmd=mdi.current());++mdi)
{
writeMemberReference(t,def,rmd,"references");
}
}
mdict = md->getReferencedByMembers();
if (mdict!=0)
{
MemberSDict::Iterator mdi(*mdict);
MemberDef *rmd;
for (mdi.toFirst();(rmd=mdi.current());++mdi)
{
writeMemberReference(t,def,rmd,"referencedby");
}
}
t << " </memberdef>" << endl;
}
static void generateXMLSection(Definition *d,FTextStream &ti,FTextStream &t,
MemberList *ml,const char *kind,const char *header=0,
const char *documentation=0)
{
if (ml==0) return;
MemberListIterator mli(*ml);
MemberDef *md;
int count=0;
for (mli.toFirst();(md=mli.current());++mli)
{
// namespace members are also inserted in the file scope, but
// to prevent this duplication in the XML output, we filter those here.
if (d->definitionType()!=Definition::TypeFile || md->getNamespaceDef()==0)
{
count++;
}
}
if (count==0) return; // empty list
t << " <sectiondef kind=\"" << kind << "\">" << endl;
if (header)
{
t << " <header>" << convertToXML(header) << "</header>" << endl;
}
if (documentation)
{
t << " <description>";
writeXMLDocBlock(t,d->docFile(),d->docLine(),d,0,documentation);
t << "</description>" << endl;
}
for (mli.toFirst();(md=mli.current());++mli)
{
// namespace members are also inserted in the file scope, but
// to prevent this duplication in the XML output, we filter those here.
if (d->definitionType()!=Definition::TypeFile || md->getNamespaceDef()==0)
{
generateXMLForMember(md,ti,t,d);
}
}
t << " </sectiondef>" << endl;
}
static void writeListOfAllMembers(ClassDef *cd,FTextStream &t)
{
t << " <listofallmembers>" << endl;
if (cd->memberNameInfoSDict())
{
MemberNameInfoSDict::Iterator mnii(*cd->memberNameInfoSDict());
MemberNameInfo *mni;
for (mnii.toFirst();(mni=mnii.current());++mnii)
{
MemberNameInfoIterator mii(*mni);
MemberInfo *mi;
for (mii.toFirst();(mi=mii.current());++mii)
{
MemberDef *md=mi->memberDef;
if (md->name().at(0)!='@') // skip anonymous members
{
Protection prot = mi->prot;
Specifier virt=md->virtualness();
t << " <member refid=\"" << memberOutputFileBase(md) << "_1" <<
md->anchor() << "\" prot=\"";
switch (prot)
{
case Public: t << "public"; break;
case Protected: t << "protected"; break;
case Private: t << "private"; break;
case Package: t << "package"; break;
}
t << "\" virt=\"";
switch(virt)
{
case Normal: t << "non-virtual"; break;
case Virtual: t << "virtual"; break;
case Pure: t << "pure-virtual"; break;
}
t << "\"";
if (!mi->ambiguityResolutionScope.isEmpty())
{
t << " ambiguityscope=\"" << convertToXML(mi->ambiguityResolutionScope) << "\"";
}
t << "><scope>" << convertToXML(cd->name()) << "</scope><name>" <<
convertToXML(md->name()) << "</name></member>" << endl;
}
}
}
}
t << " </listofallmembers>" << endl;
}
static void writeInnerClasses(const ClassSDict *cl,FTextStream &t)
{
if (cl)
{
ClassSDict::Iterator cli(*cl);
ClassDef *cd;
for (cli.toFirst();(cd=cli.current());++cli)
{
if (!cd->isHidden() && cd->name().find('@')==-1) // skip anonymous scopes
{
t << " <innerclass refid=\"" << classOutputFileBase(cd)
<< "\" prot=\"";
switch(cd->protection())
{
case Public: t << "public"; break;
case Protected: t << "protected"; break;
case Private: t << "private"; break;
case Package: t << "package"; break;
}
t << "\">" << convertToXML(cd->name()) << "</innerclass>" << endl;
}
}
}
}
static void writeInnerNamespaces(const NamespaceSDict *nl,FTextStream &t)
{
if (nl)
{
NamespaceSDict::Iterator nli(*nl);
NamespaceDef *nd;
for (nli.toFirst();(nd=nli.current());++nli)
{
if (!nd->isHidden() && nd->name().find('@')==-1) // skip anonymouse scopes
{
t << " <innernamespace refid=\"" << nd->getOutputFileBase()
<< "\">" << convertToXML(nd->name()) << "</innernamespace>" << endl;
}
}
}
}
static void writeInnerFiles(const FileList *fl,FTextStream &t)
{
if (fl)
{
QListIterator<FileDef> fli(*fl);
FileDef *fd;
for (fli.toFirst();(fd=fli.current());++fli)
{
t << " <innerfile refid=\"" << fd->getOutputFileBase()
<< "\">" << convertToXML(fd->name()) << "</innerfile>" << endl;
}
}
}
static void writeInnerPages(const PageSDict *pl,FTextStream &t)
{
if (pl)
{
PageSDict::Iterator pli(*pl);
PageDef *pd;
for (pli.toFirst();(pd=pli.current());++pli)
{
t << " <innerpage refid=\"" << pd->getOutputFileBase();
if (pd->getGroupDef())
{
t << "_" << pd->name();
}
t << "\">" << convertToXML(pd->title()) << "</innerpage>" << endl;
}
}
}
static void writeInnerGroups(const GroupList *gl,FTextStream &t)
{
if (gl)
{
GroupListIterator gli(*gl);
GroupDef *sgd;
for (gli.toFirst();(sgd=gli.current());++gli)
{
t << " <innergroup refid=\"" << sgd->getOutputFileBase()
<< "\">" << convertToXML(sgd->groupTitle())
<< "</innergroup>" << endl;
}
}
}
static void writeInnerDirs(const DirList *dl,FTextStream &t)
{
if (dl)
{
QListIterator<DirDef> subdirs(*dl);
DirDef *subdir;
for (subdirs.toFirst();(subdir=subdirs.current());++subdirs)
{
t << " <innerdir refid=\"" << subdir->getOutputFileBase()
<< "\">" << convertToXML(subdir->displayName()) << "</innerdir>" << endl;
}
}
}
static void generateXMLForClass(ClassDef *cd,FTextStream &ti)
{
// + brief description
// + detailed description
// + template argument list(s)
// - include file
// + member groups
// + inheritance diagram
// + list of direct super classes
// + list of direct sub classes
// + list of inner classes
// + collaboration diagram
// + list of all members
// + user defined member sections
// + standard member sections
// + detailed member documentation
// - examples using the class
if (cd->isReference()) return; // skip external references.
if (cd->isHidden()) return; // skip hidden classes.
if (cd->name().find('@')!=-1) return; // skip anonymous compounds.
if (cd->templateMaster()!=0) return; // skip generated template instances.
if (cd->isArtificial()) return; // skip artificially created classes
msg("Generating XML output for class %s\n",cd->name().data());
ti << " <compound refid=\"" << classOutputFileBase(cd)
<< "\" kind=\"" << cd->compoundTypeString()
<< "\"><name>" << convertToXML(cd->name()) << "</name>" << endl;
QCString outputDirectory = Config_getString("XML_OUTPUT");
QCString fileName=outputDirectory+"/"+ classOutputFileBase(cd)+".xml";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
writeXMLHeader(t);
t << " <compounddef id=\""
<< classOutputFileBase(cd) << "\" kind=\""
<< cd->compoundTypeString() << "\" prot=\"";
switch (cd->protection())
{
case Public: t << "public"; break;
case Protected: t << "protected"; break;
case Private: t << "private"; break;
case Package: t << "package"; break;
}
if (cd->isFinal()) t << "\" final=\"yes";
if (cd->isSealed()) t << "\" sealed=\"yes";
if (cd->isAbstract()) t << "\" abstract=\"yes";
t << "\">" << endl;
t << " <compoundname>";
writeXMLString(t,cd->name());
t << "</compoundname>" << endl;
if (cd->baseClasses())
{
BaseClassListIterator bcli(*cd->baseClasses());
BaseClassDef *bcd;
for (bcli.toFirst();(bcd=bcli.current());++bcli)
{
t << " <basecompoundref ";
if (bcd->classDef->isLinkable())
{
t << "refid=\"" << classOutputFileBase(bcd->classDef) << "\" ";
}
t << "prot=\"";
switch (bcd->prot)
{
case Public: t << "public"; break;
case Protected: t << "protected"; break;
case Private: t << "private"; break;
case Package: ASSERT(0); break;
}
t << "\" virt=\"";
switch(bcd->virt)
{
case Normal: t << "non-virtual"; break;
case Virtual: t << "virtual"; break;
case Pure: t <<"pure-virtual"; break;
}
t << "\">";
if (!bcd->templSpecifiers.isEmpty())
{
t << convertToXML(
insertTemplateSpecifierInScope(
bcd->classDef->name(),bcd->templSpecifiers)
);
}
else
{
t << convertToXML(bcd->classDef->displayName());
}
t << "</basecompoundref>" << endl;
}
}
if (cd->subClasses())
{
BaseClassListIterator bcli(*cd->subClasses());
BaseClassDef *bcd;
for (bcli.toFirst();(bcd=bcli.current());++bcli)
{
t << " <derivedcompoundref refid=\""
<< classOutputFileBase(bcd->classDef)
<< "\" prot=\"";
switch (bcd->prot)
{
case Public: t << "public"; break;
case Protected: t << "protected"; break;
case Private: t << "private"; break;
case Package: ASSERT(0); break;
}
t << "\" virt=\"";
switch(bcd->virt)
{
case Normal: t << "non-virtual"; break;
case Virtual: t << "virtual"; break;
case Pure: t << "pure-virtual"; break;
}
t << "\">" << convertToXML(bcd->classDef->displayName())
<< "</derivedcompoundref>" << endl;
}
}
IncludeInfo *ii=cd->includeInfo();
if (ii)
{
QCString nm = ii->includeName;
if (nm.isEmpty() && ii->fileDef) nm = ii->fileDef->docName();
if (!nm.isEmpty())
{
t << " <includes";
if (ii->fileDef && !ii->fileDef->isReference()) // TODO: support external references
{
t << " refid=\"" << ii->fileDef->getOutputFileBase() << "\"";
}
t << " local=\"" << (ii->local ? "yes" : "no") << "\">";
t << nm;
t << "</includes>" << endl;
}
}
writeInnerClasses(cd->getClassSDict(),t);
writeTemplateList(cd,t);
if (cd->getMemberGroupSDict())
{
MemberGroupSDict::Iterator mgli(*cd->getMemberGroupSDict());
MemberGroup *mg;
for (;(mg=mgli.current());++mgli)
{
generateXMLSection(cd,ti,t,mg->members(),"user-defined",mg->header(),
mg->documentation());
}
}
QListIterator<MemberList> mli(cd->getMemberLists());
MemberList *ml;
for (mli.toFirst();(ml=mli.current());++mli)
{
if ((ml->listType()&MemberListType_detailedLists)==0)
{
generateXMLSection(cd,ti,t,ml,g_xmlSectionMapper.find(ml->listType()));
}
}
#if 0
generateXMLSection(cd,ti,t,cd->pubTypes,"public-type");
generateXMLSection(cd,ti,t,cd->pubMethods,"public-func");
generateXMLSection(cd,ti,t,cd->pubAttribs,"public-attrib");
generateXMLSection(cd,ti,t,cd->pubSlots,"public-slot");
generateXMLSection(cd,ti,t,cd->signals,"signal");
generateXMLSection(cd,ti,t,cd->dcopMethods,"dcop-func");
generateXMLSection(cd,ti,t,cd->properties,"property");
generateXMLSection(cd,ti,t,cd->events,"event");
generateXMLSection(cd,ti,t,cd->pubStaticMethods,"public-static-func");
generateXMLSection(cd,ti,t,cd->pubStaticAttribs,"public-static-attrib");
generateXMLSection(cd,ti,t,cd->proTypes,"protected-type");
generateXMLSection(cd,ti,t,cd->proMethods,"protected-func");
generateXMLSection(cd,ti,t,cd->proAttribs,"protected-attrib");
generateXMLSection(cd,ti,t,cd->proSlots,"protected-slot");
generateXMLSection(cd,ti,t,cd->proStaticMethods,"protected-static-func");
generateXMLSection(cd,ti,t,cd->proStaticAttribs,"protected-static-attrib");
generateXMLSection(cd,ti,t,cd->pacTypes,"package-type");
generateXMLSection(cd,ti,t,cd->pacMethods,"package-func");
generateXMLSection(cd,ti,t,cd->pacAttribs,"package-attrib");
generateXMLSection(cd,ti,t,cd->pacStaticMethods,"package-static-func");
generateXMLSection(cd,ti,t,cd->pacStaticAttribs,"package-static-attrib");
generateXMLSection(cd,ti,t,cd->priTypes,"private-type");
generateXMLSection(cd,ti,t,cd->priMethods,"private-func");
generateXMLSection(cd,ti,t,cd->priAttribs,"private-attrib");
generateXMLSection(cd,ti,t,cd->priSlots,"private-slot");
generateXMLSection(cd,ti,t,cd->priStaticMethods,"private-static-func");
generateXMLSection(cd,ti,t,cd->priStaticAttribs,"private-static-attrib");
generateXMLSection(cd,ti,t,cd->friends,"friend");
generateXMLSection(cd,ti,t,cd->related,"related");
#endif
t << " <briefdescription>" << endl;
writeXMLDocBlock(t,cd->briefFile(),cd->briefLine(),cd,0,cd->briefDescription());
t << " </briefdescription>" << endl;
t << " <detaileddescription>" << endl;
writeXMLDocBlock(t,cd->docFile(),cd->docLine(),cd,0,cd->documentation());
t << " </detaileddescription>" << endl;
DotClassGraph inheritanceGraph(cd,DotNode::Inheritance);
if (!inheritanceGraph.isTrivial())
{
t << " <inheritancegraph>" << endl;
inheritanceGraph.writeXML(t);
t << " </inheritancegraph>" << endl;
}
DotClassGraph collaborationGraph(cd,DotNode::Collaboration);
if (!collaborationGraph.isTrivial())
{
t << " <collaborationgraph>" << endl;
collaborationGraph.writeXML(t);
t << " </collaborationgraph>" << endl;
}
t << " <location file=\""
<< cd->getDefFileName() << "\" line=\""
<< cd->getDefLine() << "\"";
if (cd->getStartBodyLine()!=-1)
{
FileDef *bodyDef = cd->getBodyDef();
if (bodyDef)
{
t << " bodyfile=\"" << bodyDef->absFilePath() << "\"";
}
t << " bodystart=\"" << cd->getStartBodyLine() << "\" bodyend=\""
<< cd->getEndBodyLine() << "\"";
}
t << "/>" << endl;
writeListOfAllMembers(cd,t);
t << " </compounddef>" << endl;
t << "</doxygen>" << endl;
ti << " </compound>" << endl;
}
static void generateXMLForNamespace(NamespaceDef *nd,FTextStream &ti)
{
// + contained class definitions
// + contained namespace definitions
// + member groups
// + normal members
// + brief desc
// + detailed desc
// + location
// - files containing (parts of) the namespace definition
if (nd->isReference() || nd->isHidden()) return; // skip external references
ti << " <compound refid=\"" << nd->getOutputFileBase()
<< "\" kind=\"namespace\"" << "><name>"
<< convertToXML(nd->name()) << "</name>" << endl;
QCString outputDirectory = Config_getString("XML_OUTPUT");
QCString fileName=outputDirectory+"/"+nd->getOutputFileBase()+".xml";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
writeXMLHeader(t);
t << " <compounddef id=\""
<< nd->getOutputFileBase() << "\" kind=\"namespace\">" << endl;
t << " <compoundname>";
writeXMLString(t,nd->name());
t << "</compoundname>" << endl;
writeInnerClasses(nd->getClassSDict(),t);
writeInnerNamespaces(nd->getNamespaceSDict(),t);
if (nd->getMemberGroupSDict())
{
MemberGroupSDict::Iterator mgli(*nd->getMemberGroupSDict());
MemberGroup *mg;
for (;(mg=mgli.current());++mgli)
{
generateXMLSection(nd,ti,t,mg->members(),"user-defined",mg->header(),
mg->documentation());
}
}
QListIterator<MemberList> mli(nd->getMemberLists());
MemberList *ml;
for (mli.toFirst();(ml=mli.current());++mli)
{
if ((ml->listType()&MemberListType_declarationLists)!=0)
{
generateXMLSection(nd,ti,t,ml,g_xmlSectionMapper.find(ml->listType()));
}
}
#if 0
generateXMLSection(nd,ti,t,&nd->decDefineMembers,"define");
generateXMLSection(nd,ti,t,&nd->decProtoMembers,"prototype");
generateXMLSection(nd,ti,t,&nd->decTypedefMembers,"typedef");
generateXMLSection(nd,ti,t,&nd->decEnumMembers,"enum");
generateXMLSection(nd,ti,t,&nd->decFuncMembers,"func");
generateXMLSection(nd,ti,t,&nd->decVarMembers,"var");
#endif
t << " <briefdescription>" << endl;
writeXMLDocBlock(t,nd->briefFile(),nd->briefLine(),nd,0,nd->briefDescription());
t << " </briefdescription>" << endl;
t << " <detaileddescription>" << endl;
writeXMLDocBlock(t,nd->docFile(),nd->docLine(),nd,0,nd->documentation());
t << " </detaileddescription>" << endl;
t << " <location file=\""
<< nd->getDefFileName() << "\" line=\""
<< nd->getDefLine() << "\"/>" << endl;
t << " </compounddef>" << endl;
t << "</doxygen>" << endl;
ti << " </compound>" << endl;
}
static void generateXMLForFile(FileDef *fd,FTextStream &ti)
{
// + includes files
// + includedby files
// + include graph
// + included by graph
// + contained class definitions
// + contained namespace definitions
// + member groups
// + normal members
// + brief desc
// + detailed desc
// + source code
// + location
// - number of lines
if (fd->isReference()) return; // skip external references
ti << " <compound refid=\"" << fd->getOutputFileBase()
<< "\" kind=\"file\"><name>" << convertToXML(fd->name())
<< "</name>" << endl;
QCString outputDirectory = Config_getString("XML_OUTPUT");
QCString fileName=outputDirectory+"/"+fd->getOutputFileBase()+".xml";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
writeXMLHeader(t);
t << " <compounddef id=\""
<< fd->getOutputFileBase() << "\" kind=\"file\">" << endl;
t << " <compoundname>";
writeXMLString(t,fd->name());
t << "</compoundname>" << endl;
IncludeInfo *inc;
if (fd->includeFileList())
{
QListIterator<IncludeInfo> ili1(*fd->includeFileList());
for (ili1.toFirst();(inc=ili1.current());++ili1)
{
t << " <includes";
if (inc->fileDef && !inc->fileDef->isReference()) // TODO: support external references
{
t << " refid=\"" << inc->fileDef->getOutputFileBase() << "\"";
}
t << " local=\"" << (inc->local ? "yes" : "no") << "\">";
t << inc->includeName;
t << "</includes>" << endl;
}
}
if (fd->includedByFileList())
{
QListIterator<IncludeInfo> ili2(*fd->includedByFileList());
for (ili2.toFirst();(inc=ili2.current());++ili2)
{
t << " <includedby";
if (inc->fileDef && !inc->fileDef->isReference()) // TODO: support external references
{
t << " refid=\"" << inc->fileDef->getOutputFileBase() << "\"";
}
t << " local=\"" << (inc->local ? "yes" : "no") << "\">";
t << inc->includeName;
t << "</includedby>" << endl;
}
}
DotInclDepGraph incDepGraph(fd,FALSE);
if (!incDepGraph.isTrivial())
{
t << " <incdepgraph>" << endl;
incDepGraph.writeXML(t);
t << " </incdepgraph>" << endl;
}
DotInclDepGraph invIncDepGraph(fd,TRUE);
if (!invIncDepGraph.isTrivial())
{
t << " <invincdepgraph>" << endl;
invIncDepGraph.writeXML(t);
t << " </invincdepgraph>" << endl;
}
if (fd->getClassSDict())
{
writeInnerClasses(fd->getClassSDict(),t);
}
if (fd->getNamespaceSDict())
{
writeInnerNamespaces(fd->getNamespaceSDict(),t);
}
if (fd->getMemberGroupSDict())
{
MemberGroupSDict::Iterator mgli(*fd->getMemberGroupSDict());
MemberGroup *mg;
for (;(mg=mgli.current());++mgli)
{
generateXMLSection(fd,ti,t,mg->members(),"user-defined",mg->header(),
mg->documentation());
}
}
QListIterator<MemberList> mli(fd->getMemberLists());
MemberList *ml;
for (mli.toFirst();(ml=mli.current());++mli)
{
if ((ml->listType()&MemberListType_declarationLists)!=0)
{
generateXMLSection(fd,ti,t,ml,g_xmlSectionMapper.find(ml->listType()));
}
}
#if 0
generateXMLSection(fd,ti,t,fd->decDefineMembers,"define");
generateXMLSection(fd,ti,t,fd->decProtoMembers,"prototype");
generateXMLSection(fd,ti,t,fd->decTypedefMembers,"typedef");
generateXMLSection(fd,ti,t,fd->decEnumMembers,"enum");
generateXMLSection(fd,ti,t,fd->decFuncMembers,"func");
generateXMLSection(fd,ti,t,fd->decVarMembers,"var");
#endif
t << " <briefdescription>" << endl;
writeXMLDocBlock(t,fd->briefFile(),fd->briefLine(),fd,0,fd->briefDescription());
t << " </briefdescription>" << endl;
t << " <detaileddescription>" << endl;
writeXMLDocBlock(t,fd->docFile(),fd->docLine(),fd,0,fd->documentation());
t << " </detaileddescription>" << endl;
if (Config_getBool("XML_PROGRAMLISTING"))
{
t << " <programlisting>" << endl;
writeXMLCodeBlock(t,fd);
t << " </programlisting>" << endl;
}
t << " <location file=\"" << fd->getDefFileName() << "\"/>" << endl;
t << " </compounddef>" << endl;
t << "</doxygen>" << endl;
ti << " </compound>" << endl;
}
static void generateXMLForGroup(GroupDef *gd,FTextStream &ti)
{
// + members
// + member groups
// + files
// + classes
// + namespaces
// - packages
// + pages
// + child groups
// - examples
// + brief description
// + detailed description
if (gd->isReference()) return; // skip external references
ti << " <compound refid=\"" << gd->getOutputFileBase()
<< "\" kind=\"group\"><name>" << convertToXML(gd->name()) << "</name>" << endl;
QCString outputDirectory = Config_getString("XML_OUTPUT");
QCString fileName=outputDirectory+"/"+gd->getOutputFileBase()+".xml";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
writeXMLHeader(t);
t << " <compounddef id=\""
<< gd->getOutputFileBase() << "\" kind=\"group\">" << endl;
t << " <compoundname>" << convertToXML(gd->name()) << "</compoundname>" << endl;
t << " <title>" << convertToXML(gd->groupTitle()) << "</title>" << endl;
writeInnerFiles(gd->getFiles(),t);
writeInnerClasses(gd->getClasses(),t);
writeInnerNamespaces(gd->getNamespaces(),t);
writeInnerPages(gd->getPages(),t);
writeInnerGroups(gd->getSubGroups(),t);
if (gd->getMemberGroupSDict())
{
MemberGroupSDict::Iterator mgli(*gd->getMemberGroupSDict());
MemberGroup *mg;
for (;(mg=mgli.current());++mgli)
{
generateXMLSection(gd,ti,t,mg->members(),"user-defined",mg->header(),
mg->documentation());
}
}
QListIterator<MemberList> mli(gd->getMemberLists());
MemberList *ml;
for (mli.toFirst();(ml=mli.current());++mli)
{
if ((ml->listType()&MemberListType_declarationLists)!=0)
{
generateXMLSection(gd,ti,t,ml,g_xmlSectionMapper.find(ml->listType()));
}
}
#if 0
generateXMLSection(gd,ti,t,&gd->decDefineMembers,"define");
generateXMLSection(gd,ti,t,&gd->decProtoMembers,"prototype");
generateXMLSection(gd,ti,t,&gd->decTypedefMembers,"typedef");
generateXMLSection(gd,ti,t,&gd->decEnumMembers,"enum");
generateXMLSection(gd,ti,t,&gd->decFuncMembers,"func");
generateXMLSection(gd,ti,t,&gd->decVarMembers,"var");
#endif
t << " <briefdescription>" << endl;
writeXMLDocBlock(t,gd->briefFile(),gd->briefLine(),gd,0,gd->briefDescription());
t << " </briefdescription>" << endl;
t << " <detaileddescription>" << endl;
writeXMLDocBlock(t,gd->docFile(),gd->docLine(),gd,0,gd->documentation());
t << " </detaileddescription>" << endl;
t << " </compounddef>" << endl;
t << "</doxygen>" << endl;
ti << " </compound>" << endl;
}
static void generateXMLForDir(DirDef *dd,FTextStream &ti)
{
if (dd->isReference()) return; // skip external references
ti << " <compound refid=\"" << dd->getOutputFileBase()
<< "\" kind=\"dir\"><name>" << convertToXML(dd->displayName())
<< "</name>" << endl;
QCString outputDirectory = Config_getString("XML_OUTPUT");
QCString fileName=outputDirectory+"/"+dd->getOutputFileBase()+".xml";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
writeXMLHeader(t);
t << " <compounddef id=\""
<< dd->getOutputFileBase() << "\" kind=\"dir\">" << endl;
t << " <compoundname>" << convertToXML(dd->displayName()) << "</compoundname>" << endl;
writeInnerDirs(&dd->subDirs(),t);
writeInnerFiles(dd->getFiles(),t);
t << " <briefdescription>" << endl;
writeXMLDocBlock(t,dd->briefFile(),dd->briefLine(),dd,0,dd->briefDescription());
t << " </briefdescription>" << endl;
t << " <detaileddescription>" << endl;
writeXMLDocBlock(t,dd->docFile(),dd->docLine(),dd,0,dd->documentation());
t << " </detaileddescription>" << endl;
t << " <location file=\"" << dd->name() << "\"/>" << endl;
t << " </compounddef>" << endl;
t << "</doxygen>" << endl;
ti << " </compound>" << endl;
}
static void generateXMLForPage(PageDef *pd,FTextStream &ti,bool isExample)
{
// + name
// + title
// + documentation
const char *kindName = isExample ? "example" : "page";
if (pd->isReference()) return;
QCString pageName = pd->getOutputFileBase();
if (pd->getGroupDef())
{
pageName+=(QCString)"_"+pd->name();
}
if (pageName=="index") pageName="indexpage"; // to prevent overwriting the generated index page.
ti << " <compound refid=\"" << pageName
<< "\" kind=\"" << kindName << "\"><name>" << convertToXML(pd->name())
<< "</name>" << endl;
QCString outputDirectory = Config_getString("XML_OUTPUT");
QCString fileName=outputDirectory+"/"+pageName+".xml";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
writeXMLHeader(t);
t << " <compounddef id=\"" << pageName;
t << "\" kind=\"" << kindName << "\">" << endl;
t << " <compoundname>" << convertToXML(pd->name())
<< "</compoundname>" << endl;
if (pd==Doxygen::mainPage) // main page is special
{
QCString title;
if (!pd->title().isEmpty() && pd->title().lower()!="notitle")
{
title = filterTitle(Doxygen::mainPage->title());
}
else
{
title = Config_getString("PROJECT_NAME");
}
t << " <title>" << convertToXML(title) << "</title>" << endl;
}
else
{
SectionInfo *si = Doxygen::sectionDict->find(pd->name());
if (si)
{
t << " <title>" << convertToXML(si->title) << "</title>" << endl;
}
}
writeInnerPages(pd->getSubPages(),t);
t << " <detaileddescription>" << endl;
if (isExample)
{
writeXMLDocBlock(t,pd->docFile(),pd->docLine(),pd,0,
pd->documentation()+"\n\\include "+pd->name());
}
else
{
writeXMLDocBlock(t,pd->docFile(),pd->docLine(),pd,0,
pd->documentation());
}
t << " </detaileddescription>" << endl;
t << " </compounddef>" << endl;
t << "</doxygen>" << endl;
ti << " </compound>" << endl;
}
void generateXML()
{
// + classes
// + namespaces
// + files
// + groups
// + related pages
// - examples
QCString outputDirectory = Config_getString("XML_OUTPUT");
if (outputDirectory.isEmpty())
{
outputDirectory=QDir::currentDirPath().utf8();
}
else
{
QDir dir(outputDirectory);
if (!dir.exists())
{
dir.setPath(QDir::currentDirPath());
if (!dir.mkdir(outputDirectory))
{
err("error: tag XML_OUTPUT: Output directory `%s' does not "
"exist and cannot be created\n",outputDirectory.data());
exit(1);
}
else if (!Config_getBool("QUIET"))
{
err("notice: Output directory `%s' does not exist. "
"I have created it for you.\n", outputDirectory.data());
}
dir.cd(outputDirectory);
}
outputDirectory=dir.absPath().utf8();
}
QDir dir(outputDirectory);
if (!dir.exists())
{
dir.setPath(QDir::currentDirPath());
if (!dir.mkdir(outputDirectory))
{
err("Cannot create directory %s\n",outputDirectory.data());
return;
}
}
QDir xmlDir(outputDirectory);
createSubDirs(xmlDir);
QCString fileName=outputDirectory+"/index.xsd";
QFile f(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
f.writeBlock(index_xsd,qstrlen(index_xsd));
f.close();
fileName=outputDirectory+"/compound.xsd";
f.setName(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
f.writeBlock(compound_xsd,qstrlen(compound_xsd));
f.close();
fileName=outputDirectory+"/index.xml";
f.setName(fileName);
if (!f.open(IO_WriteOnly))
{
err("Cannot open file %s for writing!\n",fileName.data());
return;
}
FTextStream t(&f);
//t.setEncoding(FTextStream::UnicodeUTF8);
// write index header
t << "<?xml version='1.0' encoding='UTF-8' standalone='no'?>" << endl;;
t << "<doxygenindex xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ";
t << "xsi:noNamespaceSchemaLocation=\"index.xsd\" ";
t << "version=\"" << versionString << "\">" << endl;
{
ClassSDict::Iterator cli(*Doxygen::classSDict);
ClassDef *cd;
for (cli.toFirst();(cd=cli.current());++cli)
{
generateXMLForClass(cd,t);
}
}
//{
// ClassSDict::Iterator cli(Doxygen::hiddenClasses);
// ClassDef *cd;
// for (cli.toFirst();(cd=cli.current());++cli)
// {
// msg("Generating XML output for class %s\n",cd->name().data());
// generateXMLForClass(cd,t);
// }
//}
NamespaceSDict::Iterator nli(*Doxygen::namespaceSDict);
NamespaceDef *nd;
for (nli.toFirst();(nd=nli.current());++nli)
{
msg("Generating XML output for namespace %s\n",nd->name().data());
generateXMLForNamespace(nd,t);
}
FileNameListIterator fnli(*Doxygen::inputNameList);
FileName *fn;
for (;(fn=fnli.current());++fnli)
{
FileNameIterator fni(*fn);
FileDef *fd;
for (;(fd=fni.current());++fni)
{
msg("Generating XML output for file %s\n",fd->name().data());
generateXMLForFile(fd,t);
}
}
GroupSDict::Iterator gli(*Doxygen::groupSDict);
GroupDef *gd;
for (;(gd=gli.current());++gli)
{
msg("Generating XML output for group %s\n",gd->name().data());
generateXMLForGroup(gd,t);
}
{
PageSDict::Iterator pdi(*Doxygen::pageSDict);
PageDef *pd=0;
for (pdi.toFirst();(pd=pdi.current());++pdi)
{
msg("Generating XML output for page %s\n",pd->name().data());
generateXMLForPage(pd,t,FALSE);
}
}
{
DirDef *dir;
DirSDict::Iterator sdi(*Doxygen::directories);
for (sdi.toFirst();(dir=sdi.current());++sdi)
{
msg("Generate XML output for dir %s\n",dir->name().data());
generateXMLForDir(dir,t);
}
}
{
PageSDict::Iterator pdi(*Doxygen::exampleSDict);
PageDef *pd=0;
for (pdi.toFirst();(pd=pdi.current());++pdi)
{
msg("Generating XML output for example %s\n",pd->name().data());
generateXMLForPage(pd,t,TRUE);
}
}
if (Doxygen::mainPage)
{
msg("Generating XML output for the main page\n");
generateXMLForPage(Doxygen::mainPage,t,FALSE);
}
//t << " </compoundlist>" << endl;
t << "</doxygenindex>" << endl;
writeCombineScript();
}
| Java |
<?php
/**
* @package hubzero-cms
* @copyright Copyright (c) 2005-2020 The Regents of the University of California.
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Components\Events\Api;
use Hubzero\Component\Router\Base;
/**
* Routing class for the component
*/
class Router extends Base
{
/**
* Build the route for the component.
*
* @param array &$query An array of URL arguments
* @return array The URL arguments to use to assemble the subsequent URL.
*/
public function build(&$query)
{
$segments = array();
if (!empty($query['controller']))
{
$segments[] = $query['controller'];
unset($query['controller']);
}
if (!empty($query['task']))
{
$segments[] = $query['task'];
unset($query['task']);
}
return $segments;
}
/**
* Parse the segments of a URL.
*
* @param array &$segments The segments of the URL to parse.
* @return array The URL attributes to be used by the application.
*/
public function parse(&$segments)
{
$vars = array();
$vars['controller'] = 'events';
if (isset($segments[0]))
{
if (is_numeric($segments[0]))
{
$vars['id'] = $segments[0];
if (\App::get('request')->method() == 'GET')
{
$vars['task'] = 'read';
}
}
else
{
$vars['task'] = $segments[0];
}
}
return $vars;
}
}
| Java |
@echo off
SETLOCAL
REM http://dev.exiv2.org/projects/exiv2/repository/
SET EXIV2_COMMIT=3364
REM http://sourceforge.net/p/libjpeg-turbo/code/
SET LIBJPEG_COMMIT=1093
rem error 1406
rem https://github.com/madler/zlib/commits
SET ZLIB_COMMIT_LONG=50893291621658f355bc5b4d450a8d06a563053d
rem https://github.com/openexr/openexr
SET OPENEXR_COMMIT_LONG=91015147e5a6a1914bcb16b12886aede9e1ed065
SET OPENEXR_CMAKE_VERSION=2.2
rem http://www.boost.org/
SET BOOST_MINOR=55
REM ftp://ftp.fftw.org/pub/fftw/
SET FFTW_VER=3.3.4
rem https://github.com/mm2/Little-CMS
SET LCMS_COMMIT_LONG=d61231a1efb9eb926cbf0235afe03452302c6009
rem https://github.com/LibRaw/LibRaw
SET LIBRAW_COMMIT_LONG=32e21b28e24b6cecdae8813b5ef9c103b8a8ccf0
SET LIBRAW_DEMOS2_COMMIT_LONG=ffea825e121e92aa780ae587b65f80fc5847637c
SET LIBRAW_DEMOS3_COMMIT_LONG=f0895891fdaa775255af02275fce426a5bf5c9fc
rem ftp://sourceware.org/pub/pthreads-win32/
SET PTHREADS_DIR=prebuilt-dll-2-9-1-release
rem http://heasarc.gsfc.nasa.gov/FTP/software/fitsio/c
SET CFITSIO_VER=3360
rem broken 3370
rem Internal version number for http://qtpfsgui.sourceforge.net/win/hugin-*
SET HUGIN_VER=201300
IF EXIST .settings\vsexpress.txt (
SET VSCOMMAND=vcexpress
) ELSE IF EXIST .settings\devent.txt (
SET VSCOMMAND=devenv
) ELSE (
vcexpress XXXXXXXXXXXXX 2>NUL >NUL
IF ERRORLEVEL 1 (
devenv /? 2>NUL >NUL
IF ERRORLEVEL 1 (
echo.
echo.ERROR: This file must be run inside a VS command prompt!
echo.
goto error_end
) ELSE (
SET VSCOMMAND=devenv
)
) ELSE (
SET VSCOMMAND=vcexpress
)
mkdir .settings 2>NUL >NUL
echo x>.settings\%VSCOMMAND%.txt
)
IF EXIST ..\msvc (
echo.
echo.ERROR: This file should NOT be executed within the LuminanceHDR source directory,
echo. but in a new empty folder!
echo.
goto error_end
)
ml64.exe > NUL
IF ERRORLEVEL 1 (
set Platform=Win32
set RawPlatform=x86
set CpuPlatform=ia32
) ELSE (
set Platform=x64
set RawPlatform=x64
set CpuPlatform=intel64
)
SET VISUAL_STUDIO_VC_REDIST=%VCINSTALLDIR%\redist\%RawPlatform%
IF DEFINED VS110COMNTOOLS (
REM Visual Studio 2012
set VS_SHORT=vc11
set VS_CMAKE=Visual Studio 11
set VS_PROG_FILES=Microsoft Visual Studio 11.0
) ELSE IF DEFINED VS100COMNTOOLS (
REM Visual Studio 2010
set VS_SHORT=vc10
set VS_CMAKE=Visual Studio 10
set VS_PROG_FILES=Microsoft Visual Studio 10.0
) ELSE (
REM Visual Studio 2008
set VS_SHORT=vc9
set VS_CMAKE=Visual Studio 9 2008
set VS_PROG_FILES=Microsoft Visual Studio 9.0
)
IF %Platform% EQU x64 (
set VS_CMAKE=%VS_CMAKE% Win64
)
call setenv.cmd
IF NOT EXIST %CMAKE_DIR%\bin\cmake.exe (
echo.
echo.ERROR: CMake not found: %CMAKE_DIR%\bin\cmake.exe
echo.
goto error_end
)
IF NOT EXIST %CYGWIN_DIR%\bin\cp.exe GOTO cygwin_error
IF NOT EXIST %CYGWIN_DIR%\bin\cvs.exe GOTO cygwin_error
IF NOT EXIST %CYGWIN_DIR%\bin\git.exe GOTO cygwin_error
IF NOT EXIST %CYGWIN_DIR%\bin\gzip.exe GOTO cygwin_error
IF NOT EXIST %CYGWIN_DIR%\bin\mv.exe GOTO cygwin_error
IF NOT EXIST %CYGWIN_DIR%\bin\nasm.exe GOTO cygwin_error
IF NOT EXIST %CYGWIN_DIR%\bin\sed.exe GOTO cygwin_error
IF NOT EXIST %CYGWIN_DIR%\bin\ssh.exe GOTO cygwin_error
IF NOT EXIST %CYGWIN_DIR%\bin\svn.exe GOTO cygwin_error
IF NOT EXIST %CYGWIN_DIR%\bin\tar.exe GOTO cygwin_error
IF NOT EXIST %CYGWIN_DIR%\bin\unzip.exe GOTO cygwin_error
IF NOT EXIST %CYGWIN_DIR%\bin\wget.exe GOTO cygwin_error
GOTO cygwin_ok
:cygwin_error
echo ERROR: Cygwin with
echo cp
echo cvs
echo git
echo gzip
echo mv
echo nasm
echo sed
echo ssh
echo svn
echo tar
echo unzip
echo wget
echo is required
GOTO error_end
:cygwin_ok
IF NOT DEFINED Configuration (
set Configuration=Release
)
IF NOT DEFINED ConfigurationLuminance (
set ConfigurationLuminance=RelWithDebInfo
)
cls
echo.
echo.--- %VS_CMAKE% ---
echo.Configuration = %Configuration%
echo.ConfigurationLuminance = %ConfigurationLuminance%
echo.Platform = %Platform% (%RawPlatform%)
echo.
IF NOT EXIST %TEMP_DIR% (
mkdir %TEMP_DIR%
)
IF NOT EXIST vcDlls (
mkdir vcDlls
robocopy "%vcinstalldir%redist\%RawPlatform%" vcDlls /MIR >nul
)
IF NOT EXIST vcDlls\selected (
mkdir vcDlls\selected
%CYGWIN_DIR%\bin\cp.exe vcDlls/**/vcomp* vcDlls/selected
%CYGWIN_DIR%\bin\cp.exe vcDlls/**/msv* vcDlls/selected
)
IF NOT EXIST %TEMP_DIR%\hugin-%HUGIN_VER%-%RawPlatform%.zip (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/hugin-%HUGIN_VER%-%RawPlatform%.zip qtpfsgui.sourceforge.net/win/hugin-%HUGIN_VER%-%RawPlatform%.zip
)
IF NOT EXIST hugin-%HUGIN_VER%-%RawPlatform% (
%CYGWIN_DIR%\bin\unzip.exe -o -q -d hugin-%HUGIN_VER%-%RawPlatform% %TEMP_DIR%\hugin-%HUGIN_VER%-%RawPlatform%.zip
)
SET ZLIB_COMMIT=%ZLIB_COMMIT_LONG:~0,7%
IF NOT EXIST %TEMP_DIR%\zlib-%ZLIB_COMMIT%.zip (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/zlib-%ZLIB_COMMIT%.zip --no-check-certificate http://github.com/madler/zlib/zipball/%ZLIB_COMMIT_LONG%
)
IF NOT EXIST zlib-%ZLIB_COMMIT% (
%CYGWIN_DIR%\bin\unzip.exe -q %TEMP_DIR%/zlib-%ZLIB_COMMIT%.zip
%CYGWIN_DIR%\bin\mv.exe madler-zlib-* zlib-%ZLIB_COMMIT%
REM zlib must be compiled in the source folder, else exiv2 compilation
REM fails due to zconf.h rename/compile problems, due to cmake
pushd zlib-%ZLIB_COMMIT%
%CMAKE_DIR%\bin\cmake.exe -G "%VS_CMAKE%"
IF errorlevel 1 goto error_end
%VSCOMMAND% zlib.sln /build "%Configuration%|%Platform%" /Project zlib
IF errorlevel 1 goto error_end
popd
)
IF NOT EXIST %TEMP_DIR%\lpng170b35.zip (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/lpng170b35.zip http://sourceforge.net/projects/libpng/files/libpng17/1.7.0beta35/lp170b35.zip/download
IF errorlevel 1 goto error_end
)
IF NOT EXIST lp170b35 (
%CYGWIN_DIR%\bin\unzip.exe -q %TEMP_DIR%/lpng170b35.zip
pushd lp170b35
%CMAKE_DIR%\bin\cmake.exe -G "%VS_CMAKE%" . -DZLIB_ROOT=..\zlib-%ZLIB_COMMIT%;..\zlib-%ZLIB_COMMIT%\%Configuration%
IF errorlevel 1 goto error_end
%VSCOMMAND% libpng.sln /build "%Configuration%|%Platform%" /Project png17
IF errorlevel 1 goto error_end
popd
)
IF NOT EXIST %TEMP_DIR%\expat-2.1.0.tar (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/expat-2.1.0.tar.gz http://sourceforge.net/projects/expat/files/expat/2.1.0/expat-2.1.0.tar.gz/download
%CYGWIN_DIR%\bin\gzip.exe -d %TEMP_DIR%/expat-2.1.0.tar.gz
)
IF NOT EXIST expat-2.1.0 (
%CYGWIN_DIR%\bin\tar.exe -xf %TEMP_DIR%/expat-2.1.0.tar
pushd expat-2.1.0
%CMAKE_DIR%\bin\cmake.exe -G "%VS_CMAKE%"
IF errorlevel 1 goto error_end
%VSCOMMAND% expat.sln /build "%Configuration%|%Platform%" /Project expat
IF errorlevel 1 goto error_end
popd
)
IF NOT EXIST exiv2-%EXIV2_COMMIT% (
%CYGWIN_DIR%\bin\svn.exe co -r %EXIV2_COMMIT% svn://dev.exiv2.org/svn/trunk exiv2-%EXIV2_COMMIT%
pushd exiv2-%EXIV2_COMMIT%
%CMAKE_DIR%\bin\cmake.exe -G "%VS_CMAKE%" -DZLIB_ROOT=..\zlib-%ZLIB_COMMIT%;..\zlib-%ZLIB_COMMIT%\Release
IF errorlevel 1 goto error_end
%VSCOMMAND% exiv2.sln /build "%Configuration%|%Platform%" /Project exiv2
IF errorlevel 1 goto error_end
copy bin\%Platform%\Dynamic\*.h include
popd
)
IF NOT EXIST libjpeg-turbo-%LIBJPEG_COMMIT% (
%CYGWIN_DIR%\bin\svn.exe co -r %LIBJPEG_COMMIT% svn://svn.code.sf.net/p/libjpeg-turbo/code/trunk libjpeg-turbo-%LIBJPEG_COMMIT%
)
IF NOT EXIST libjpeg-turbo-%LIBJPEG_COMMIT%.build (
mkdir libjpeg-turbo-%LIBJPEG_COMMIT%.build
pushd libjpeg-turbo-%LIBJPEG_COMMIT%.build
%CMAKE_DIR%\bin\cmake.exe -G "%VS_CMAKE%" -DCMAKE_BUILD_TYPE=%Configuration% -DNASM="%CYGWIN_DIR%\bin\nasm.exe" -DWITH_JPEG8=TRUE ..\libjpeg-turbo-%LIBJPEG_COMMIT%
IF errorlevel 1 goto error_end
%VSCOMMAND% libjpeg-turbo.sln /build "%Configuration%|%Platform%"
IF errorlevel 1 goto error_end
copy jconfig.h ..\libjpeg-turbo-%LIBJPEG_COMMIT%
popd
)
SET LCMS_COMMIT=%LCMS_COMMIT_LONG:~0,7%
IF NOT EXIST %TEMP_DIR%\lcms2-%LCMS_COMMIT%.zip (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/lcms2-%LCMS_COMMIT%.zip --no-check-certificate https://github.com/mm2/Little-CMS/zipball/%LCMS_COMMIT_LONG%
)
IF NOT EXIST lcms2-%LCMS_COMMIT% (
%CYGWIN_DIR%\bin\unzip.exe -q %TEMP_DIR%/lcms2-%LCMS_COMMIT%.zip
%CYGWIN_DIR%\bin\mv.exe mm2-Little-CMS-* lcms2-%LCMS_COMMIT%
pushd lcms2-%LCMS_COMMIT%
%VSCOMMAND% Projects\VC2010\lcms2.sln /Upgrade
%VSCOMMAND% Projects\VC2010\lcms2.sln /build "%Configuration%|%Platform%" /Project lcms2_DLL
IF errorlevel 1 goto error_end
popd
)
IF NOT EXIST %TEMP_DIR%\tiff-4.0.3.zip (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/tiff-4.0.3.zip http://download.osgeo.org/libtiff/tiff-4.0.3.zip
)
IF NOT EXIST tiff-4.0.3 (
%CYGWIN_DIR%\bin\unzip.exe -q %TEMP_DIR%/tiff-4.0.3.zip
echo.JPEG_SUPPORT=^1> tiff-4.0.3\qtpfsgui_commands.in
echo.JPEGDIR=%CD%\libjpeg-turbo-%LIBJPEG_COMMIT%>> tiff-4.0.3\qtpfsgui_commands.in
echo.JPEG_INCLUDE=-I%CD%\libjpeg-turbo-%LIBJPEG_COMMIT%>> tiff-4.0.3\qtpfsgui_commands.in
echo.JPEG_LIB=%CD%\libjpeg-turbo-%LIBJPEG_COMMIT%.build\sharedlib\%Configuration%\jpeg.lib>> tiff-4.0.3\qtpfsgui_commands.in
echo.ZIP_SUPPORT=^1>> tiff-4.0.3\qtpfsgui_commands.in
echo.ZLIBDIR=..\..\zlib-%ZLIB_COMMIT%\%Configuration%>> tiff-4.0.3\qtpfsgui_commands.in
echo.ZLIB_INCLUDE=-I..\..\zlib-%ZLIB_COMMIT%>> tiff-4.0.3\qtpfsgui_commands.in
echo.ZLIB_LIB=$^(ZLIBDIR^)\zlib.lib>> tiff-4.0.3\qtpfsgui_commands.in
pushd tiff-4.0.3
nmake /s /c /f Makefile.vc @qtpfsgui_commands.in
IF errorlevel 1 goto error_end
popd
)
SET LIBRAW_COMMIT=%LIBRAW_COMMIT_LONG:~0,7%
SET LIBRAW_DEMOS2_COMMIT=%LIBRAW_DEMOS2_COMMIT_LONG:~0,7%
SET LIBRAW_DEMOS3_COMMIT=%LIBRAW_DEMOS3_COMMIT_LONG:~0,7%
IF NOT EXIST %TEMP_DIR%\LibRaw-%LIBRAW_COMMIT%.zip (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/LibRaw-%LIBRAW_COMMIT%.zip --no-check-certificate https://github.com/LibRaw/LibRaw/zipball/%LIBRAW_COMMIT_LONG%
)
IF NOT EXIST %TEMP_DIR%\LibRaw-demosaic-pack-GPL2-%LIBRAW_DEMOS2_COMMIT%.zip (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/LibRaw-demosaic-pack-GPL2-%LIBRAW_DEMOS2_COMMIT%.zip --no-check-certificate https://github.com/LibRaw/LibRaw-demosaic-pack-GPL2/zipball/%LIBRAW_DEMOS2_COMMIT_LONG%
)
IF NOT EXIST LibRaw-demosaic-pack-GPL2-%LIBRAW_DEMOS2_COMMIT% (
%CYGWIN_DIR%\bin\unzip.exe -q %TEMP_DIR%/LibRaw-demosaic-pack-GPL2-%LIBRAW_DEMOS2_COMMIT%.zip
%CYGWIN_DIR%\bin\mv.exe LibRaw-LibRaw-* LibRaw-demosaic-pack-GPL2-%LIBRAW_DEMOS2_COMMIT%
)
IF NOT EXIST %TEMP_DIR%\LibRaw-demosaic-pack-GPL3-%LIBRAW_DEMOS3_COMMIT%.zip (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/LibRaw-demosaic-pack-GPL3-%LIBRAW_DEMOS3_COMMIT%.zip --no-check-certificate https://github.com/LibRaw/LibRaw-demosaic-pack-GPL3/zipball/%LIBRAW_DEMOS3_COMMIT_LONG%
)
IF NOT EXIST LibRaw-demosaic-pack-GPL3-%LIBRAW_DEMOS3_COMMIT% (
%CYGWIN_DIR%\bin\unzip.exe -q %TEMP_DIR%/LibRaw-demosaic-pack-GPL3-%LIBRAW_DEMOS3_COMMIT%.zip
%CYGWIN_DIR%\bin\mv.exe LibRaw-LibRaw-* LibRaw-demosaic-pack-GPL3-%LIBRAW_DEMOS3_COMMIT%
)
IF NOT EXIST LibRaw-%LIBRAW_COMMIT% (
%CYGWIN_DIR%\bin\unzip.exe -q %TEMP_DIR%/LibRaw-%LIBRAW_COMMIT%.zip
%CYGWIN_DIR%\bin\mv.exe LibRaw-LibRaw-* LibRaw-%LIBRAW_COMMIT%
pushd LibRaw-%LIBRAW_COMMIT%
rem /openmp
echo.COPT_OPT="/arch:SSE2"> qtpfsgui_commands.in
echo.CFLAGS_DP2=/I..\LibRaw-demosaic-pack-GPL2-%LIBRAW_DEMOS2_COMMIT%>> qtpfsgui_commands.in
echo.CFLAGSG2=/DLIBRAW_DEMOSAIC_PACK_GPL2>> qtpfsgui_commands.in
echo.CFLAGS_DP3=/I..\LibRaw-demosaic-pack-GPL3-%LIBRAW_DEMOS3_COMMIT%>> qtpfsgui_commands.in
echo.CFLAGSG3=/DLIBRAW_DEMOSAIC_PACK_GPL3>> qtpfsgui_commands.in
echo.LCMS_DEF="/DUSE_LCMS2 /DCMS_DLL /I..\lcms2-%LCMS_COMMIT%\include">> qtpfsgui_commands.in
echo.LCMS_LIB="..\lcms2-%LCMS_COMMIT%\bin\lcms2.lib">> qtpfsgui_commands.in
echo.JPEG_DEF="/DUSE_JPEG8 /DUSE_JPEG /I..\libjpeg-turbo-%LIBJPEG_COMMIT%">> qtpfsgui_commands.in
echo.JPEG_LIB="..\libjpeg-turbo-%LIBJPEG_COMMIT%.build\sharedlib\%Configuration%\jpeg.lib">> qtpfsgui_commands.in
nmake /f Makefile.msvc @qtpfsgui_commands.in clean > nul
nmake /f Makefile.msvc @qtpfsgui_commands.in bin\libraw.dll
popd
)
SET PTHREADS_CURRENT_DIR=pthreads_%PTHREADS_DIR%_%RawPlatform%
IF NOT EXIST %TEMP_DIR%\%PTHREADS_CURRENT_DIR% (
mkdir %TEMP_DIR%\%PTHREADS_CURRENT_DIR%
pushd %TEMP_DIR%\%PTHREADS_CURRENT_DIR%
%CYGWIN_DIR%\bin\wget.exe -O pthread.h --retry-connrefused --tries=5 ftp://sourceware.org/pub/pthreads-win32/%PTHREADS_DIR%/include/pthread.h
%CYGWIN_DIR%\bin\wget.exe -O sched.h --retry-connrefused --tries=5 ftp://sourceware.org/pub/pthreads-win32/%PTHREADS_DIR%/include/sched.h
%CYGWIN_DIR%\bin\wget.exe -O semaphore.h --retry-connrefused --tries=5 ftp://sourceware.org/pub/pthreads-win32/%PTHREADS_DIR%/include/semaphore.h
%CYGWIN_DIR%\bin\wget.exe -O pthreadVC2.dll --retry-connrefused --tries=5 ftp://sourceware.org/pub/pthreads-win32/%PTHREADS_DIR%/dll/%RawPlatform%/pthreadVC2.dll
%CYGWIN_DIR%\bin\wget.exe -O pthreadVC2.lib --retry-connrefused --tries=5 ftp://sourceware.org/pub/pthreads-win32/%PTHREADS_DIR%/lib/%RawPlatform%/pthreadVC2.lib
popd
)
IF NOT EXIST %PTHREADS_CURRENT_DIR% (
mkdir %PTHREADS_CURRENT_DIR%
robocopy %TEMP_DIR%\%PTHREADS_CURRENT_DIR% %PTHREADS_CURRENT_DIR% >nul
)
IF NOT EXIST %TEMP_DIR%\cfit%CFITSIO_VER%.zip (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/cfit%CFITSIO_VER%.zip ftp://heasarc.gsfc.nasa.gov/software/fitsio/c/cfit%CFITSIO_VER%.zip
)
IF NOT EXIST cfit%CFITSIO_VER% (
%CYGWIN_DIR%\bin\unzip.exe -o -q -d cfit%CFITSIO_VER% %TEMP_DIR%/cfit%CFITSIO_VER%.zip
)
IF NOT EXIST cfit%CFITSIO_VER%.build (
mkdir cfit%CFITSIO_VER%.build
pushd cfit%CFITSIO_VER%.build
%CMAKE_DIR%\bin\cmake.exe -G "%VS_CMAKE%" ..\cfit%CFITSIO_VER% -DUSE_PTHREADS=1 -DCMAKE_INCLUDE_PATH=..\%PTHREADS_CURRENT_DIR% -DCMAKE_LIBRARY_PATH=..\%PTHREADS_CURRENT_DIR%
IF errorlevel 1 goto error_end
%CMAKE_DIR%\bin\cmake.exe --build . --config %Configuration% --target cfitsio
IF errorlevel 1 goto error_end
popd
)
pushd cfit%CFITSIO_VER%
SET CFITSIO=%CD%
popd
pushd cfit%CFITSIO_VER%.build\%Configuration%
SET CFITSIO=%CFITSIO%;%CD%
popd
rem IF NOT EXIST %TEMP_DIR%\CCfits-2.4.tar (
rem %CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/CCfits-2.4.tar.gz http://heasarc.gsfc.nasa.gov/docs/software/fitsio/CCfits/CCfits-2.4.tar.gz
rem %CYGWIN_DIR%\bin\gzip.exe -d %TEMP_DIR%/CCfits-2.4.tar.gz
rem %CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/CCfits2.4patch.zip http://qtpfsgui.sourceforge.net/win/CCfits2.4patch.zip
rem )
rem IF NOT EXIST CCfits2.4 (
rem %CYGWIN_DIR%\bin\tar.exe -xf %TEMP_DIR%/CCfits-2.4.tar
rem ren CCfits CCfits2.4
rem %CYGWIN_DIR%\bin\unzip.exe -o -q -d CCfits2.4 %TEMP_DIR%/CCfits2.4patch.zip
rem )
rem IF NOT EXIST CCfits2.4.build (
rem mkdir CCfits2.4.build
rem
rem pushd CCfits2.4.build
rem %CMAKE_DIR%\bin\cmake.exe -G "%VS_CMAKE%" ..\CCfits2.4 -DCMAKE_INCLUDE_PATH=..\cfit%CFITSIO_VER% -DCMAKE_LIBRARY_PATH=..\cfit%CFITSIO_VER%.build\%Configuration%
rem IF errorlevel 1 goto error_end
rem %CMAKE_DIR%\bin\cmake.exe --build . --config %Configuration% --target CCfits
rem IF errorlevel 1 goto error_end
rem popd
rem )
rem pushd CCfits2.4.build\%Configuration%
rem SET CCFITS_ROOT_DIR=%CD%
rem popd
IF NOT EXIST %TEMP_DIR%\gsl-1.15.tar (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/gsl-1.15.tar.gz ftp://ftp.gnu.org/gnu/gsl/gsl-1.15.tar.gz
%CYGWIN_DIR%\bin\gzip -d %TEMP_DIR%/gsl-1.15.tar.gz
)
IF NOT EXIST %TEMP_DIR%\gsl-1.15-vc10.zip (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/gsl-1.15-vc10.zip http://gladman.plushost.co.uk/oldsite/computing/gsl-1.15-vc10.zip
)
IF NOT EXIST gsl-1.15 (
%CYGWIN_DIR%\bin\tar.exe -xf %TEMP_DIR%/gsl-1.15.tar
%CYGWIN_DIR%\bin\unzip.exe -o -q -d gsl-1.15 %TEMP_DIR%/gsl-1.15-vc10.zip
pushd gsl-1.15\build.vc10
IF %VS_SHORT% EQU vc9 (
%CYGWIN_DIR%\bin\sed.exe -i 's/Format Version 11.00/Format Version 10.00/g' gsl.lib.sln
)
%VSCOMMAND% gsl.lib.sln /Upgrade
%VSCOMMAND% gsl.lib.sln /build "%Configuration%|%Platform%" /Project gslhdrs
gslhdrs\%Platform%\%Configuration%\gslhdrs.exe
%VSCOMMAND% gsl.lib.sln /build "%Configuration%|%Platform%" /Project gsllib
popd
)
SET OPENEXR_COMMIT=%OPENEXR_COMMIT_LONG:~0,7%
IF NOT EXIST %TEMP_DIR%\OpenEXR-dk-%OPENEXR_COMMIT%.zip (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/OpenEXR-dk-%OPENEXR_COMMIT%.zip --no-check-certificate https://github.com/openexr/openexr/zipball/%OPENEXR_COMMIT_LONG%
)
IF NOT EXIST OpenEXR-dk-%OPENEXR_COMMIT% (
%CYGWIN_DIR%\bin\unzip.exe -q %TEMP_DIR%/OpenEXR-dk-%OPENEXR_COMMIT%.zip
%CYGWIN_DIR%\bin\mv.exe openexr-openexr-* OpenEXR-dk-%OPENEXR_COMMIT%
)
IF NOT EXIST OpenEXR-dk-%OPENEXR_COMMIT%\IlmBase.build (
mkdir OpenEXR-dk-%OPENEXR_COMMIT%\IlmBase.build
pushd OpenEXR-dk-%OPENEXR_COMMIT%\IlmBase.build
%CMAKE_DIR%\bin\cmake.exe -G "%VS_CMAKE%" -DCMAKE_BUILD_TYPE=%Configuration% -DCMAKE_INSTALL_PREFIX=..\output -DZLIB_ROOT=..\..\zlib-%ZLIB_COMMIT%;..\..\zlib-%ZLIB_COMMIT%\%Configuration% -DBUILD_SHARED_LIBS=OFF ../IlmBase
IF errorlevel 1 goto error_end
%VSCOMMAND% IlmBase.sln /build "%Configuration%|%Platform%"
IF errorlevel 1 goto error_end
%VSCOMMAND% IlmBase.sln /build "%Configuration%|%Platform%" /Project INSTALL
IF errorlevel 1 goto error_end
popd
)
IF NOT EXIST OpenEXR-dk-%OPENEXR_COMMIT%\OpenEXR.build (
mkdir OpenEXR-dk-%OPENEXR_COMMIT%\OpenEXR.build
pushd OpenEXR-dk-%OPENEXR_COMMIT%\OpenEXR.build
%CMAKE_DIR%\bin\cmake.exe -G "%VS_CMAKE%" -DCMAKE_BUILD_TYPE=%Configuration% ^
-DZLIB_ROOT=..\..\zlib-%ZLIB_COMMIT%;..\..\zlib-%ZLIB_COMMIT%\%Configuration% ^
-DILMBASE_PACKAGE_PREFIX=%CD%\OpenEXR-dk-%OPENEXR_COMMIT%\output -DBUILD_SHARED_LIBS=OFF ^
-DCMAKE_INSTALL_PREFIX=..\output ^
../OpenEXR
IF errorlevel 1 goto error_end
%VSCOMMAND% OpenEXR.sln /build "%Configuration%|%Platform%" /Project IlmImf
IF errorlevel 1 goto error_end
%VSCOMMAND% OpenEXR.sln /build "%Configuration%|%Platform%" /Project INSTALL
IF errorlevel 1 goto error_end
popd
)
IF %Platform% EQU Win32 (
IF NOT EXIST %TEMP_DIR%\fftw-%FFTW_VER%-dll32.zip (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/fftw-%FFTW_VER%-dll32.zip ftp://ftp.fftw.org/pub/fftw/fftw-%FFTW_VER%-dll32.zip
)
) ELSE (
IF NOT EXIST %TEMP_DIR%\fftw-%FFTW_VER%-dll64.zip (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/fftw-%FFTW_VER%-dll64.zip ftp://ftp.fftw.org/pub/fftw/fftw-%FFTW_VER%-dll64.zip
)
)
IF NOT EXIST fftw-%FFTW_VER%-dll (
IF %Platform% EQU Win32 (
%CYGWIN_DIR%\bin\unzip.exe -q -d fftw-%FFTW_VER%-dll %TEMP_DIR%/fftw-%FFTW_VER%-dll32.zip
) ELSE (
%CYGWIN_DIR%\bin\unzip.exe -q -d fftw-%FFTW_VER%-dll %TEMP_DIR%/fftw-%FFTW_VER%-dll64.zip
)
pushd fftw-%FFTW_VER%-dll
lib /def:libfftw3-3.def
lib /def:libfftw3f-3.def
lib /def:libfftw3l-3.def
popd
)
REM IF NOT EXIST %TEMP_DIR%\tbb40_20120613oss_win.zip (
REM %CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/tbb40_20120613oss_win.zip "http://threadingbuildingblocks.org/uploads/77/187/4.0 update 5/tbb40_20120613oss_win.zip"
REM )
REM
REM IF NOT EXIST tbb40_20120613oss (
REM %CYGWIN_DIR%\bin\unzip.exe -q %TEMP_DIR%/tbb40_20120613oss_win.zip
REM REM Everthing is already compiled, nothing to do!
REM )
REM IF NOT EXIST %TEMP_DIR%\gtest-1.6.0.zip (
SET GTEST_DIR=gtest-r680
IF NOT EXIST %GTEST_DIR% (
REM %CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/gtest-1.6.0.zip http://googletest.googlecode.com/files/gtest-1.6.0.zip
%CYGWIN_DIR%\bin\svn.exe co -r 680 http://googletest.googlecode.com/svn/trunk/ %GTEST_DIR%
pushd %GTEST_DIR%
%CMAKE_DIR%\bin\cmake.exe -G "%VS_CMAKE%" . -DBUILD_SHARED_LIBS=1
%VSCOMMAND% gtest.sln /build "%Configuration%|%Platform%"
REN Release lib
popd
)
SET GTEST_ROOT=%CD%\%GTEST_DIR%
REM IF NOT EXIST %GTEST_DIR%.build (
REM mkdir %GTEST_DIR%.build
REM pushd %GTEST_DIR%.build
REM %CMAKE_DIR%\bin\cmake.exe -G "%VS_CMAKE%" ..\%GTEST_DIR% -DBUILD_SHARED_LIBS=1
REM %VSCOMMAND% gtest.sln /build "%Configuration%|%Platform%"
REM popd
REM )
REM IF NOT EXIST gtest-1.6.0 (
REM %CYGWIN_DIR%\bin\unzip.exe -q %TEMP_DIR%/gtest-1.6.0.zip
REM )
IF NOT DEFINED L_BOOST_DIR (
set L_BOOST_DIR=.
)
IF NOT EXIST %TEMP_DIR%\boost_1_%BOOST_MINOR%_0.zip (
%CYGWIN_DIR%\bin\wget.exe -O %TEMP_DIR%/boost_1_%BOOST_MINOR%_0.zip http://sourceforge.net/projects/boost/files/boost/1.%BOOST_MINOR%.0/boost_1_%BOOST_MINOR%_0.zip/download
)
IF NOT EXIST %L_BOOST_DIR%\boost_1_%BOOST_MINOR%_0 (
echo.Extracting boost. Be patient!
pushd %L_BOOST_DIR%
%CYGWIN_DIR%\bin\unzip.exe -q %TEMP_DIR%/boost_1_%BOOST_MINOR%_0.zip
popd
pushd %L_BOOST_DIR%\boost_1_%BOOST_MINOR%_0
bootstrap.bat
popd
pushd %L_BOOST_DIR%\boost_1_%BOOST_MINOR%_0
IF %Platform% EQU Win32 (
IF %Configuration% EQU Release (
cmd.exe /C b2.exe toolset=msvc variant=release
) ELSE (
cmd.exe /C b2.exe toolset=msvc variant=debug
)
) ELSE (
IF %Configuration% EQU Release (
cmd.exe /C b2.exe toolset=msvc variant=release address-model=64
) ELSE (
cmd.exe /C b2.exe toolset=msvc variant=debug address-model=64
)
)
popd
)
REM Set Boost-directory as ENV variable (needed for CMake)
pushd %L_BOOST_DIR%\boost_1_%BOOST_MINOR%_0
rem SET Boost_DIR=%CD%
REM SET BOOST_ROOT=%CD%
popd
IF NOT EXIST LuminanceHdrStuff (
mkdir LuminanceHdrStuff
)
IF NOT EXIST LuminanceHdrStuff\qtpfsgui (
pushd LuminanceHdrStuff
%CYGWIN_DIR%\bin\git.exe clone git://git.code.sf.net/p/qtpfsgui/code qtpfsgui
popd
) ELSE (
pushd LuminanceHdrStuff\qtpfsgui
IF %UPDATE_REPO_LUMINANCE% EQU 1 (
%CYGWIN_DIR%\bin\git.exe pull
)
popd
)
IF NOT EXIST LuminanceHdrStuff\DEPs (
pushd LuminanceHdrStuff
mkdir DEPs
cd DEPs
mkdir include
mkdir lib
mkdir bin
popd
for %%v in ("libpng", "libjpeg", "lcms2", "exiv2", "libtiff", "libraw", "fftw3", "gsl", "CCfits") do (
mkdir LuminanceHdrStuff\DEPs\include\%%v
mkdir LuminanceHdrStuff\DEPs\lib\%%v
mkdir LuminanceHdrStuff\DEPs\bin\%%v
)
mkdir LuminanceHdrStuff\DEPs\include\libraw\libraw
mkdir LuminanceHdrStuff\DEPs\include\gsl\gsl
copy gsl-1.15\gsl\*.h LuminanceHdrStuff\DEPs\include\gsl\gsl
copy gsl-1.15\build.vc10\lib\%Platform%\%Configuration%\*.lib LuminanceHdrStuff\DEPs\lib\gsl
rem copy gsl-1.15\build.vc10\dll\*.dll LuminanceHdrStuff\DEPs\bin\gsl
)
robocopy fftw-%FFTW_VER%-dll LuminanceHdrStuff\DEPs\include\fftw3 *.h /MIR >nul
robocopy fftw-%FFTW_VER%-dll LuminanceHdrStuff\DEPs\lib\fftw3 *.lib /MIR /NJS >nul
robocopy fftw-%FFTW_VER%-dll LuminanceHdrStuff\DEPs\bin\fftw3 *.dll /MIR /NJS >nul
robocopy tiff-4.0.3\libtiff LuminanceHdrStuff\DEPs\include\libtiff *.h /MIR >nul
robocopy tiff-4.0.3\libtiff LuminanceHdrStuff\DEPs\lib\libtiff *.lib /MIR /NJS >nul
robocopy tiff-4.0.3\libtiff LuminanceHdrStuff\DEPs\bin\libtiff *.dll /MIR /NJS >nul
rem robocopy expat: included indirectly in in exiv2
rem robocopy zlib: included indirectly in in exiv2
robocopy exiv2-%EXIV2_COMMIT%\include LuminanceHdrStuff\DEPs\include\exiv2 *.h *.hpp /MIR >nul
robocopy exiv2-%EXIV2_COMMIT%\bin\%Platform%\Dynamic\%Configuration% LuminanceHdrStuff\DEPs\lib\exiv2 *.lib /MIR >nul
robocopy exiv2-%EXIV2_COMMIT%\bin\%Platform%\Dynamic\%Configuration% LuminanceHdrStuff\DEPs\bin\exiv2 *.dll /MIR >nul
robocopy lp170b35 LuminanceHdrStuff\DEPs\include\libpng *.h /MIR >nul
robocopy lp170b35\%Configuration% LuminanceHdrStuff\DEPs\lib\libpng *.lib /MIR >nul
robocopy lp170b35\%Configuration% LuminanceHdrStuff\DEPs\bin\libpng *.dll /MIR >nul
robocopy LibRaw-%LIBRAW_COMMIT%\libraw LuminanceHdrStuff\DEPs\include\libraw\libraw /MIR >nul
robocopy LibRaw-%LIBRAW_COMMIT%\lib LuminanceHdrStuff\DEPs\lib\libraw *.lib /MIR >nul
robocopy LibRaw-%LIBRAW_COMMIT%\bin LuminanceHdrStuff\DEPs\bin\libraw *.dll /MIR >nul
robocopy lcms2-%LCMS_COMMIT%\include LuminanceHdrStuff\DEPs\include\lcms2 *.h /MIR >nul
robocopy lcms2-%LCMS_COMMIT%\bin LuminanceHdrStuff\DEPs\lib\lcms2 *.lib /MIR /NJS >nul
rem robocopy lcms2-%LCMS_COMMIT%\bin LuminanceHdrStuff\DEPs\bin\lcms2 *.dll /MIR /NJS >nul
robocopy libjpeg-turbo-%LIBJPEG_COMMIT% LuminanceHdrStuff\DEPs\include\libjpeg *.h /MIR >nul
robocopy libjpeg-turbo-%LIBJPEG_COMMIT%.build\sharedlib\%Configuration% LuminanceHdrStuff\DEPs\lib\libjpeg *.lib /MIR /NJS >nul
robocopy libjpeg-turbo-%LIBJPEG_COMMIT%.build\sharedlib\%Configuration% LuminanceHdrStuff\DEPs\bin\libjpeg *.dll /MIR /NJS >nul
REM robocopy tbb40_20120613oss\include LuminanceHdrStuff\DEPs\include\tbb /MIR >nul
REM robocopy tbb40_20120613oss\lib\%CpuPlatform%\%VS_SHORT% LuminanceHdrStuff\DEPs\lib\tbb /MIR >nul
REM robocopy tbb40_20120613oss\bin\%CpuPlatform%\%VS_SHORT% LuminanceHdrStuff\DEPs\bin\tbb /MIR >nul
robocopy CCfits2.4 LuminanceHdrStuff\DEPs\include\CCfits *.h CCfits /MIR >nul
pushd LuminanceHdrStuff\DEPs\include
SET CCFITS_ROOT_DIR=%CCFITS_ROOT_DIR%;%CD%
popd
IF NOT EXIST LuminanceHdrStuff\qtpfsgui.build (
mkdir LuminanceHdrStuff\qtpfsgui.build
)
pushd LuminanceHdrStuff\qtpfsgui.build
IF %OPTION_LUMINANCE_UPDATE_TRANSLATIONS% EQU 1 (
set CMAKE_OPTIONS=-DUPDATE_TRANSLATIONS=1
) ELSE (
set CMAKE_OPTIONS=-UUPDATE_TRANSLATIONS
)
IF %OPTION_LUPDATE_NOOBSOLETE% EQU 1 (
set CMAKE_OPTIONS=%CMAKE_OPTIONS% -DLUPDATE_NOOBSOLETE=1
) ELSE (
set CMAKE_OPTIONS=%CMAKE_OPTIONS% -ULUPDATE_NOOBSOLETE
)
set L_CMAKE_INCLUDE=..\DEPs\include\libtiff;..\DEPs\include\libpng;..\..\zlib-%ZLIB_COMMIT%;..\..\boost_1_%BOOST_MINOR%_0;..\..\OpenEXR-dk-%OPENEXR_COMMIT%\output\include
set L_CMAKE_LIB=..\DEPs\lib\libtiff;..\DEPs\lib\libpng;..\..\zlib-%ZLIB_COMMIT%\%Configuration%;..\..\boost_1_%BOOST_MINOR%_0\stage\lib;..\..\OpenEXR-dk-%OPENEXR_COMMIT%\output\lib
set L_CMAKE_PROGRAM_PATH=%CYGWIN_DIR%\bin
set L_CMAKE_PREFIX_PATH=%QTDIR%
set CMAKE_OPTIONS=%CMAKE_OPTIONS% -DPC_EXIV2_INCLUDEDIR=..\DEPs\include\exiv2 -DPC_EXIV2_LIBDIR=..\DEPs\lib\exiv2 -DCMAKE_INCLUDE_PATH=%L_CMAKE_INCLUDE% -DCMAKE_LIBRARY_PATH=%L_CMAKE_LIB% -DCMAKE_PROGRAM_PATH=%L_CMAKE_PROGRAM_PATH% -DCMAKE_PREFIX_PATH=%L_CMAKE_PREFIX_PATH% -DPNG_NAMES=libpng16;libpng17 -DOPENEXR_VERSION=%OPENEXR_CMAKE_VERSION%
REM IF EXIST ..\..\gtest-1.6.0 (
REM SET GTEST_ROOT=%CD%\..\..\gtest-1.6.0
REM )
echo CMake command line options ------------------------------------
echo %CMAKE_OPTIONS%
echo ---------------------------------------------------------------
%CMAKE_DIR%\bin\cmake.exe -G "%VS_CMAKE%" ..\qtpfsgui %CMAKE_OPTIONS%
IF errorlevel 1 goto error_end
popd
IF EXIST LuminanceHdrStuff\qtpfsgui.build\Luminance HDR.sln (
pushd LuminanceHdrStuff\qtpfsgui.build
rem %VSCOMMAND% luminance-hdr.sln /Upgrade
%VSCOMMAND% "Luminance HDR.sln" /build "%ConfigurationLuminance%|%Platform%" /Project luminance-hdr
IF errorlevel 1 goto error_end
popd
)
IF EXIST LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance%\luminance-hdr.exe (
IF EXIST LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance% (
robocopy LuminanceHdrStuff\qtpfsgui LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance% LICENSE >nul
IF NOT EXIST LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance%\align_image_stack.exe (
copy vcDlls\selected\* LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance%\
)
pushd LuminanceHdrStuff\DEPs\bin
robocopy libjpeg ..\..\qtpfsgui.build\%ConfigurationLuminance% jpeg8.dll >nul
robocopy exiv2 ..\..\qtpfsgui.build\%ConfigurationLuminance% exiv2.dll >nul
robocopy exiv2 ..\..\qtpfsgui.build\%ConfigurationLuminance% zlib.dll >nul
robocopy exiv2 ..\..\qtpfsgui.build\%ConfigurationLuminance% expat.dll >nul
robocopy libraw ..\..\qtpfsgui.build\%ConfigurationLuminance% libraw.dll >nul
robocopy fftw3 ..\..\qtpfsgui.build\%ConfigurationLuminance% libfftw3f-3.dll >nul
robocopy libpng ..\..\qtpfsgui.build\%ConfigurationLuminance% libpng17.dll >nul
popd
robocopy cfit%CFITSIO_VER%.build\%Configuration% LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance% cfitsio.dll >nul
robocopy %PTHREADS_CURRENT_DIR% LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance% pthreadVC2.dll >nul
robocopy lcms2-%LCMS_COMMIT%\bin LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance% lcms2.dll >nul
IF NOT EXIST LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance%\i18n\ (
mkdir LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance%\i18n
)
IF NOT EXIST LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance%\help\ (
mkdir LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance%\help
)
robocopy LuminanceHdrStuff\qtpfsgui.build LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance%\i18n lang_*.qm >nul
robocopy LuminanceHdrStuff\qtpfsgui\help LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance%\help /MIR >nul
REM ----- QT Stuff (Dlls, translations) --------------------------------------------
pushd LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance%
for %%v in ( "Qt5Concurrent.dll", "Qt5Core.dll", "Qt5Gui.dll", "Qt5Multimedia.dll", "Qt5MultimediaWidgets.dll", "Qt5Network.dll", "Qt5Positioning.dll", "Qt5WinExtras.dll", "Qt5OpenGL.dll", "Qt5PrintSupport.dll", "Qt5Qml.dll", "Qt5Quick.dll", "Qt5Sensors.dll", "Qt5Sql.dll", "Qt5V8.dll", "Qt5WebKit.dll", "Qt5WebKitWidgets.dll", "Qt5Widgets.dll", "Qt5Xml.dll", "icudt51.dll", "icuin51.dll", "icuuc51.dll" ) do (
robocopy %QTDIR%\bin . %%v >nul
)
for %%v in ("imageformats", "sqldrivers", "platforms") do (
IF NOT EXIST %%v (
mkdir %%v
)
)
robocopy %QTDIR%\plugins\imageformats imageformats qjpeg.dll >nul
robocopy %QTDIR%\plugins\sqldrivers sqldrivers qsqlite.dll >nul
robocopy %QTDIR%\plugins\platforms platforms qwindows.dll >nul
robocopy %QTDIR%\translations i18n qt_??.qm >nul
robocopy %QTDIR%\translations i18n qt_??_*.qm >nul
popd
robocopy hugin-%HUGIN_VER%-%RawPlatform% LuminanceHdrStuff\qtpfsgui.build\%ConfigurationLuminance%\hugin /MIR >nul
)
)
goto end
:error_end
pause
:end
endlocal | Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_23) on Tue Nov 10 20:55:20 CET 2015 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.slf4j.profiler.SortAndPruneComposites (SLF4J 1.7.13 Test API)
</TITLE>
<META NAME="date" CONTENT="2015-11-10">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.slf4j.profiler.SortAndPruneComposites (SLF4J 1.7.13 Test API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/slf4j/profiler/SortAndPruneComposites.html" title="class in org.slf4j.profiler"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/slf4j/profiler/\class-useSortAndPruneComposites.html" target="_top"><B>FRAMES</B></A>
<A HREF="SortAndPruneComposites.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.slf4j.profiler.SortAndPruneComposites</B></H2>
</CENTER>
No usage of org.slf4j.profiler.SortAndPruneComposites
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/slf4j/profiler/SortAndPruneComposites.html" title="class in org.slf4j.profiler"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/slf4j/profiler/\class-useSortAndPruneComposites.html" target="_top"><B>FRAMES</B></A>
<A HREF="SortAndPruneComposites.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2005–2015 <a href="http://www.qos.ch">QOS.ch</a>. All rights reserved.
</BODY>
</HTML>
| Java |
//
// (c) Copyright 2013 DESY, Eugen Wintersberger <eugen.wintersberger@desy.de>
//
// This file is part of pninexus.
//
// pninexus 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.
//
// pninexus 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 pninexus. If not, see <http://www.gnu.org/licenses/>.
//
// ===========================================================================
//
// Created on: Oct 28, 2013
// Author: Eugen Wintersberger <eugen.wintersberger@desy.de>
//
#ifdef __GNUG__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#include <boost/test/unit_test.hpp>
#ifdef __GNUG__
#pragma GCC diagnostic pop
#endif
#include <pni/arrays.hpp>
#include "array_types.hpp"
#include "../data_generator.hpp"
#include "../compiler_version.hpp"
using namespace pni;
template<typename AT> struct test_mdarray_fixture
{
typedef AT array_type;
typedef typename array_type::value_type value_type;
typedef typename array_type::storage_type storage_type;
typedef typename array_type::map_type map_type;
typedef random_generator<value_type> generator_type;
generator_type generator;
shape_t shape;
test_mdarray_fixture():
generator(),
shape(shape_t{2,3,5})
{}
};
BOOST_AUTO_TEST_SUITE(test_mdarray)
typedef boost::mpl::joint_view<all_dynamic_arrays,
#if GCC_VERSION > 40800
boost::mpl::joint_view<
all_fixed_dim_arrays<3>,
all_static_arrays<2,3,5>
>
#else
all_fixed_dim_arrays<3>
#endif
> array_types;
template<typename CTYPE,typename...ITYPES>
static void create_index(CTYPE &index,ITYPES ...indexes)
{
index = CTYPE{indexes...};
}
template<typename T,size_t N,typename ...ITYPES>
static void create_index(std::array<T,N> &c,ITYPES ...indexes)
{
c = std::array<T,N>{{indexes...}};
}
template<
typename ITYPE,
typename ATYPE
>
void test_multiindex_access_with_container()
{
typedef test_mdarray_fixture<ATYPE> fixture_type;
typedef typename fixture_type::value_type value_type;
fixture_type fixture;
auto a = ATYPE::create(fixture.shape);
ITYPE index;
for(size_t i=0;i<fixture.shape[0];i++)
for(size_t j=0;j<fixture.shape[1];j++)
for(size_t k=0;k<fixture.shape[2];k++)
{
value_type v = fixture.generator();
create_index(index,i,j,k);
a(index) = v;
BOOST_CHECK_EQUAL(a(index),v);
}
}
//========================================================================
// Create a mdarray instance from a view
BOOST_AUTO_TEST_CASE_TEMPLATE(test_view_construction,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
typedef typename fixture_type::value_type value_type;
typedef dynamic_array<value_type> darray_type;
fixture_type fixture;
auto a = darray_type::create(shape_t{100,20,30});
std::generate(a.begin(),a.end(),fixture.generator);
auto view = a(slice(0,2),slice(0,3),slice(0,5));
AT target(view);
auto view_shape = view.template shape<shape_t>();
auto target_shape = target.template shape<shape_t>();
BOOST_CHECK_EQUAL_COLLECTIONS(view_shape.begin(),view_shape.end(),
target_shape.begin(),target_shape.end());
BOOST_CHECK_EQUAL(view.size(),target.size());
BOOST_CHECK_EQUAL(view.rank(),target.rank());
BOOST_CHECK_EQUAL_COLLECTIONS(view.begin(),view.end(),
target.begin(),target.end());
}
//========================================================================
BOOST_AUTO_TEST_CASE(test_is_view_index)
{
BOOST_CHECK((is_view_index<size_t,size_t,size_t>::value==false));
BOOST_CHECK((is_view_index<slice,size_t,size_t>::value==true));
BOOST_CHECK((is_view_index<size_t,slice,size_t>::value==true));
BOOST_CHECK((is_view_index<size_t,size_t,slice>::value==true));
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_inquery,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
typedef typename fixture_type::value_type value_type;
fixture_type fixture;
auto a = AT::create(fixture.shape);
BOOST_CHECK_EQUAL(a.size(),30u);
BOOST_CHECK_EQUAL(a.rank(),3u);
BOOST_CHECK(AT::type_id == type_id_map<value_type>::type_id);
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_operator,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
typedef typename fixture_type::value_type value_type;
fixture_type fixture;
auto a = AT::create(fixture.shape);
const AT &ca = a;
for(size_t index=0;index<a.size();++index)
{
value_type v = fixture.generator();
a[index] = v;
BOOST_CHECK_EQUAL(a[index],v);
BOOST_CHECK_EQUAL(ca[index],v);
}
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_pointer,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
fixture_type fixture;
auto a = AT::create(fixture.shape);
std::generate(a.begin(),a.end(),fixture.generator);
auto ptr = a.data();
for(size_t index=0;index<a.size();++index)
BOOST_CHECK_EQUAL(a[index],*(ptr++));
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_at,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
typedef typename fixture_type::value_type value_type;
fixture_type fixture;
auto a = AT::create(fixture.shape);
const AT &ca = a;
for(size_t index=0;index<a.size();++index)
{
value_type v = fixture.generator();
a.at(index) = v;
BOOST_CHECK_EQUAL(a.at(index),v);
BOOST_CHECK_EQUAL(ca.at(index),v);
}
BOOST_CHECK_THROW(a.at(a.size()),index_error);
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_iter,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
typedef typename fixture_type::value_type value_type;
fixture_type fixture;
auto a = AT::create(fixture.shape);
typename AT::iterator iter = a.begin();
typename AT::const_iterator citer = a.begin();
for(;iter!=a.end();++iter,++citer)
{
value_type v = fixture.generator();
*iter = v;
BOOST_CHECK_EQUAL(*iter,v);
BOOST_CHECK_EQUAL(*citer,v);
}
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_linear_access_riter,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
typedef typename fixture_type::value_type value_type;
fixture_type fixture;
auto a = AT::create(fixture.shape);
typename AT::reverse_iterator iter = a.rbegin();
typename AT::const_reverse_iterator citer = a.rbegin();
for(;iter!=a.rend();++iter,++citer)
{
value_type v = fixture.generator();
*iter = v;
BOOST_CHECK_EQUAL(*iter,v);
BOOST_CHECK_EQUAL(*citer,v);
}
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_multiindex_access,AT,array_types)
{
typedef test_mdarray_fixture<AT> fixture_type;
typedef typename fixture_type::value_type value_type;
fixture_type fixture;
auto a = AT::create(fixture.shape);
for(size_t i=0;i<fixture.shape[0];i++)
for(size_t j=0;j<fixture.shape[1];j++)
for(size_t k=0;k<fixture.shape[2];k++)
{
value_type v = fixture.generator();
a(i,j,k) = v;
BOOST_CHECK_EQUAL(a(i,j,k),v);
}
}
//========================================================================
BOOST_AUTO_TEST_CASE_TEMPLATE(test_muldiindex_access_container,AT,array_types)
{
test_multiindex_access_with_container<std::vector<size_t>,AT>();
test_multiindex_access_with_container<std::array<size_t,3>,AT>();
test_multiindex_access_with_container<std::list<size_t>,AT>();
test_multiindex_access_with_container<std::vector<uint64>,AT>();
test_multiindex_access_with_container<std::array<uint64,3>,AT>();
test_multiindex_access_with_container<std::list<uint64>,AT>();
}
BOOST_AUTO_TEST_SUITE_END()
| Java |
/**
* Setup (required for Joomla! 3)
*/
if(typeof(akeeba) == 'undefined') {
var akeeba = {};
}
if(typeof(akeeba.jQuery) == 'undefined') {
akeeba.jQuery = jQuery.noConflict();
}
akeeba.jQuery(document).ready(function($){
function atsAssignmentClick()
{
var parent = akeeba.jQuery(this).parent('td');
var id = akeeba.jQuery(this).parents('td').find('input.ticket_id').val();
var hide = ['.loading img', '.loading .icon-warning-sign'];
var show = ['.loading .icon-ok'];
var assign_to = 0;
if(akeeba.jQuery(this).hasClass('assignme'))
{
assign_to = akeeba.jQuery('#user').val();
}
else if(akeeba.jQuery(this).parent('.assignto'))
{
assign_to = akeeba.jQuery(this).parent().find('input.assignto').val();
}
if(this.hasClass('unassign')){
hide.push('.unassign');
show.push('.assignme');
}
else{
hide.push('.assignme');
show.push('.unassign');
}
var structure = {
_rootElement: this,
type: "POST",
dataType: 'json',
url : ATS_ROOT_URL + 'index.php?option=com_ats&view=ticket&format=json&' + akeeba.jQuery('#token').attr('name') + '=1',
data: {
'task' : 'assign',
'id' : id,
'assigned_to' : assign_to
},
beforeSend: function() {
var wait = akeeba.jQuery(this._rootElement).parents('td').find('.loading');
wait.css('display','inline').find('i').css('display', 'none');
wait.find('img').css('display', 'inline-block');
},
success: function(responseJSON)
{
var assigned = akeeba.jQuery(this._rootElement).parents('td').find('.assigned_to');
var unassign = akeeba.jQuery(this._rootElement).hasClass('unassign');
if(responseJSON.result == true){
assigned.html(responseJSON.assigned);
unassign ? assigned.removeClass('badge-info') : assigned.addClass('badge-info');
for (var i = 0; i < hide.length; i++)
{
var elementDefinition = hide[i];
akeeba.jQuery(this._rootElement).parents('td').find(elementDefinition).css('display', 'none');
}
for (var i = 0; i < show.length; i++)
{
var elementDefinition = show[i];
akeeba.jQuery(this._rootElement).parents('td').find(elementDefinition).css('display', 'inline-block');
}
}
else
{
var wait = akeeba.jQuery(this._rootElement).parents('td').find('.loading');
wait.find('.icon-ok,img').css('display', 'none');
wait.find('.icon-warning-sign').show('fast');
}
}
};
akeeba.jQuery.ajax( structure );
}
akeeba.jQuery('.unassign a').click(atsAssignmentClick);
akeeba.jQuery('.assignme a').click(atsAssignmentClick);
akeeba.jQuery('.assignto li a').click(atsAssignmentClick);
akeeba.jQuery('.select-status li a').click(function(){
var image = akeeba.jQuery(this).parent().find('img');
var self = this;
akeeba.jQuery.ajax(ATS_ROOT_URL + 'index.php?option=com_ats&view=tickets&task=ajax_set_status&format=json&'+jQuery('#token').attr('name')+'=1',{
type : 'POST',
dataType : 'json',
data : {
'id' : akeeba.jQuery(this).parents('tr').find('.ats_ticket_id').val(),
'status' : akeeba.jQuery(this).data('status')
},
beforeSend : function(){
image.show();
},
success : function(responseJSON){
image.hide();
if(responseJSON.err){
alert(responseJSON.err);
}
else{
var label = akeeba.jQuery(self).parents('td').find('span[class*="label-"]');
label.attr('class', 'ats-status label pull-right ' + responseJSON.ats_class).html(responseJSON.msg);
}
}
})
})
}); | Java |
/*
* BackFS Filesystem Cache
* Copyright (c) 2010-2014 William R. Fraser
*/
#define _XOPEN_SOURCE 500 // for pread()
#include "fscache.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <libgen.h>
#include <limits.h>
#include <pthread.h>
static pthread_mutex_t lock;
#define BACKFS_LOG_SUBSYS "Cache"
#include "global.h"
#include "fsll.h"
#include "util.h"
extern int backfs_log_level;
extern bool backfs_log_stderr;
static char *cache_dir;
static uint64_t cache_size;
static volatile uint64_t cache_used_size = 0;
struct bucket_node { uint32_t number; struct bucket_node* next; };
static struct bucket_node * volatile to_check;
static bool use_whole_device;
static uint64_t bucket_max_size;
uint64_t prepare_buckets_size_check(const char *root)
{
INFO("taking inventory of cache directory\n");
uint64_t total = 0;
struct dirent *e = malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
struct dirent *result = e;
DIR *dir = opendir(root);
struct bucket_node* volatile * next = &to_check;
while (readdir_r(dir, e, &result) == 0 && result != NULL) {
if (e->d_name[0] < '0' || e->d_name[0] > '9') continue;
*next = (struct bucket_node*)malloc(sizeof(struct bucket_node));
(*next)->number = atoi(e->d_name);
next = &((*next)->next);
*next = NULL;
++total;
}
closedir(dir);
FREE(e);
return total;
}
/*
* returns the bucket number corresponding to a bucket path
* i.e. reads the number off the end.
*/
uint32_t bucket_path_to_number(const char *bucketpath)
{
uint32_t number = 0;
size_t s = strlen(bucketpath);
size_t i;
for (i = 1; i < s; i++) {
char c = bucketpath[s - i];
if (c < '0' || c > '9') {
i--;
break;
}
}
for (i = s - i; i < s; i++) {
number *= 10;
number += (bucketpath[i] - '0');
}
return number;
}
bool is_unchecked(const char* path)
{
uint32_t number = bucket_path_to_number(path);
struct bucket_node* node = to_check;
while(node) {
if (node->number == number)
return true;
node = node->next;
}
return false;
}
void* check_buckets_size(void* arg)
{
INFO("starting cache size check\n");
struct stat s;
struct bucket_node* bucket;
if (arg != NULL) {
abort();
}
char buf[PATH_MAX];
while (to_check) {
pthread_mutex_lock(&lock);
bucket = to_check;
if (bucket) {
s.st_size = 0;
snprintf(buf, PATH_MAX, "%s/buckets/%u/data", cache_dir, bucket->number);
if (stat(buf, &s) == -1 && errno != ENOENT) {
PERROR("stat in get_cache_used_size");
ERROR("\tcaused by stat(%s)\n", buf);
abort();
}
DEBUG("bucket %u: %llu bytes\n",
bucket->number, (unsigned long long) s.st_size);
cache_used_size -= bucket_max_size - s.st_size;
to_check = bucket->next;
}
pthread_mutex_unlock(&lock);
free(bucket);
}
INFO("finished cache size check: %llu bytes used\n",
cache_used_size);
return NULL;
}
uint64_t get_cache_fs_free_size(const char *root)
{
struct statvfs s;
if (statvfs(root, &s) == -1) {
PERROR("statfs in get_cache_fs_free_size");
return 0;
}
uint64_t dev_free = (uint64_t) s.f_bavail * s.f_bsize;
return dev_free;
}
/*
* Initialize the cache.
*/
void cache_init(const char *a_cache_dir, uint64_t a_cache_size, uint64_t a_bucket_max_size)
{
cache_dir = (char*)malloc(strlen(a_cache_dir)+1);
strcpy(cache_dir, a_cache_dir);
cache_size = a_cache_size;
use_whole_device = (cache_size == 0);
char bucket_dir[PATH_MAX];
snprintf(bucket_dir, PATH_MAX, "%s/buckets", cache_dir);
uint64_t number_of_buckets = prepare_buckets_size_check(bucket_dir);
INFO("%llu buckets in cache dir\n",
(unsigned long long) number_of_buckets);
cache_used_size = number_of_buckets * a_bucket_max_size;
INFO("Estimated %llu bytes used in cache dir\n",
(unsigned long long) cache_used_size);
uint64_t cache_free_size = get_cache_fs_free_size(bucket_dir);
INFO("%llu bytes free in cache dir\n",
(unsigned long long) cache_free_size);
bucket_max_size = a_bucket_max_size;
if (number_of_buckets > 0) {
pthread_t thread;
if (pthread_create(&thread, NULL, &check_buckets_size, NULL) != 0) {
PERROR("cache_init: error creating checked thread");
abort();
}
}
}
const char * bucketname(const char *path)
{
return fsll_basename(path);
}
void dump_queues()
{
#ifdef FSLL_DUMP
fprintf(stderr, "BackFS Used Bucket Queue:\n");
fsll_dump(cache_dir, "buckets/head", "buckets/tail");
fprintf(stderr, "BackFS Free Bucket Queue:\n");
fsll_dump(cache_dir, "buckets/free_head", "buckets/free_tail");
#endif //FSLL_DUMP
}
/*
* don't use this function directly.
*/
char * makebucket(uint64_t number)
{
char *new_bucket = fsll_make_entry(cache_dir, "buckets", number);
fsll_insert_as_head(cache_dir, new_bucket,
"buckets/head", "buckets/tail");
return new_bucket;
}
/*
* make a new bucket
*
* either re-use one from the free queue,
* or increment the next_bucket_number file and return that.
*
* If one from the free queue is returned, that bucket is made the head of the
* used queue.
*/
char * next_bucket(void)
{
char *bucket = fsll_getlink(cache_dir, "buckets/free_head");
if (bucket != NULL) {
DEBUG("re-using free bucket %s\n", bucketname(bucket));
// disconnect from free queue
fsll_disconnect(cache_dir, bucket,
"buckets/free_head", "buckets/free_tail");
// make head of the used queue
fsll_insert_as_head(cache_dir, bucket,
"buckets/head", "buckets/tail");
return bucket;
} else {
char nbnpath[PATH_MAX];
snprintf(nbnpath, PATH_MAX, "%s/buckets/next_bucket_number", cache_dir);
uint64_t next = 0;
FILE *f = fopen(nbnpath, "r+");
if (f == NULL && errno != ENOENT) {
PERROR("open next_bucket");
return makebucket(0);
} else {
if (f != NULL) {
// we had a number already there; read it
if (fscanf(f, "%llu", (unsigned long long *)&next) != 1) {
ERROR("unable to read next_bucket\n");
fclose(f);
return makebucket(0);
}
f = freopen(nbnpath, "w+", f);
} else {
// next_bucket_number doesn't exist; create it and write a 1.
f = fopen(nbnpath, "w+");
if (f == NULL) {
PERROR("open next_bucket again");
return makebucket(0);
}
}
// write the next number
if (f == NULL) {
PERROR("fdopen for writing in next_bucket");
return makebucket(0);
}
fprintf(f, "%llu\n", (unsigned long long) next+1);
fclose(f);
}
DEBUG("making new bucket %lu\n", (unsigned long) next);
char *new_bucket = makebucket(next);
return new_bucket;
}
}
/*
* moves a bucket to the head of the used queue
*/
void bucket_to_head(const char *bucketpath)
{
DEBUG("bucket_to_head(%s)\n", bucketpath);
fsll_to_head(cache_dir, bucketpath, "buckets/head", "buckets/tail");
}
/*
* Starting at the dirname of path, remove empty directories upwards in the
* path heirarchy.
*
* Stops when it gets to <cache_dir>/buckets or <cache_dir>/map
*/
void trim_directory(const char *path)
{
size_t len = strlen(path);
char *copy = (char*)malloc(len+1);
strncpy(copy, path, len+1);
char map[PATH_MAX];
char buckets[PATH_MAX];
snprintf(map, PATH_MAX, "%s/map", cache_dir);
snprintf(buckets, PATH_MAX, "%s/buckets", cache_dir);
char *dir = dirname(copy);
while ((strcmp(dir, map) != 0) && (strcmp(dir, buckets) != 0)) {
DIR *d = opendir(dir);
struct dirent *e;
bool found_mtime = false;
while ((e = readdir(d)) != NULL) {
if (e->d_name[0] == '.')
continue;
// remove mtime files, if found
if (strcmp(e->d_name, "mtime") == 0) {
struct stat s;
char mtime[PATH_MAX];
snprintf(mtime, PATH_MAX, "%s/mtime", dir);
stat(mtime, &s);
if (S_IFREG & s.st_mode) {
found_mtime = true;
continue;
}
}
// if we got here, the directory has entries
DEBUG("directory has entries -- in %s found '%s'\n", dir, e->d_name);
closedir(d);
FREE(copy);
return;
}
if (found_mtime) {
char mtime[PATH_MAX];
snprintf(mtime, PATH_MAX, "%s/mtime", dir);
if (unlink(mtime) == -1) {
PERROR("in trim_directory, unable to unlink mtime file");
ERROR("\tpath was %s\n", mtime);
} else {
DEBUG("removed mtime file %s/mtime\n", dir);
}
}
closedir(d);
d = NULL;
int result = rmdir(dir);
if (result == -1) {
if (errno != EEXIST && errno != ENOTEMPTY) {
PERROR("in trim_directory, rmdir");
}
WARN("in trim_directory, directory still not empty, but how? path was %s\n", dir);
FREE(copy);
return;
} else {
DEBUG("removed empty map directory %s\n", dir);
}
dir = dirname(dir);
}
FREE(copy);
}
/*
* free a bucket
*
* moves bucket from the tail of the used queue to the tail of the free queue,
* deletes the data in the bucket
* returns the size of the data deleted
*/
uint64_t free_bucket_real(const char *bucketpath, bool free_in_the_middle_is_bad)
{
char *parent = fsll_getlink(bucketpath, "parent");
if (parent && fsll_file_exists(parent, NULL)) {
DEBUG("bucket parent: %s\n", parent);
if (unlink(parent) == -1) {
PERROR("unlink parent in free_bucket");
}
// if this was the last block, remove the directory
trim_directory(parent);
}
FREE(parent);
fsll_makelink(bucketpath, "parent", NULL);
if (free_in_the_middle_is_bad) {
char *n = fsll_getlink(bucketpath, "next");
if (n != NULL) {
ERROR("bucket freed (#%lu) was not the queue tail\n",
(unsigned long) bucket_path_to_number(bucketpath));
FREE(n);
return 0;
}
}
fsll_disconnect(cache_dir, bucketpath,
"buckets/head", "buckets/tail");
fsll_insert_as_tail(cache_dir, bucketpath,
"buckets/free_head", "buckets/free_tail");
char data[PATH_MAX];
snprintf(data, PATH_MAX, "%s/data", bucketpath);
struct stat s;
if (stat(data, &s) == -1) {
PERROR("stat data in free_bucket");
}
pthread_mutex_lock(&lock);
uint64_t result = 0;
if (unlink(data) == -1) {
PERROR("unlink data in free_bucket");
} else {
result = (uint64_t) s.st_size;
if (!is_unchecked(bucketpath)) {
cache_used_size -= result;
}
}
pthread_mutex_unlock(&lock);
return result;
}
uint64_t free_bucket_mid_queue(const char *bucketpath)
{
return free_bucket_real(bucketpath, false);
}
uint64_t free_bucket(const char *bucketpath)
{
return free_bucket_real(bucketpath, true);
}
/*
* do not use this function directly
*/
int cache_invalidate_bucket(const char *filename, uint32_t block,
const char *bucket)
{
DEBUG("invalidating block %lu of file %s\n",
(unsigned long) block, filename);
uint64_t freed_size = free_bucket_mid_queue(bucket);
DEBUG("freed %llu bytes in bucket %s\n",
(unsigned long long) freed_size,
bucketname(bucket));
return 0;
}
int cache_invalidate_file_real(const char *filename, bool error_if_not_exist)
{
char mappath[PATH_MAX];
snprintf(mappath, PATH_MAX, "%s/map%s", cache_dir, filename);
DIR *d = opendir(mappath);
if (d == NULL) {
if (errno != ENOENT || error_if_not_exist) {
PERROR("opendir in cache_invalidate");
}
return -errno;
}
struct dirent *e = malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
struct dirent *result = e;
while (readdir_r(d, e, &result) == 0 && result != NULL) {
// probably not needed, because trim_directory would take care of the
// mtime file, but might as well do it now to save time.
if (strcmp(e->d_name, "mtime") == 0) {
char mtime[PATH_MAX];
snprintf(mtime, PATH_MAX, "%s/mtime", mappath);
DEBUG("removed mtime file %s\n", mtime);
unlink(mtime);
continue;
}
if (e->d_name[0] < '0' || e->d_name[0] > '9') continue;
char *bucket = fsll_getlink(mappath, e->d_name);
uint32_t block;
sscanf(e->d_name, "%lu", (unsigned long *)&block);
cache_invalidate_bucket(filename, block, bucket);
FREE(bucket);
}
FREE(e);
closedir(d);
return 0;
}
int cache_invalidate_file_(const char *filename, bool error_if_not_exist)
{
pthread_mutex_lock(&lock);
int retval = cache_invalidate_file_real(filename, error_if_not_exist);
pthread_mutex_unlock(&lock);
return retval;
}
int cache_invalidate_file(const char *filename)
{
return cache_invalidate_file_(filename, true);
}
int cache_try_invalidate_file(const char *filename)
{
return cache_invalidate_file_(filename, false);
}
int cache_invalidate_block_(const char *filename, uint32_t block,
bool warn_if_not_exist)
{
char mappath[PATH_MAX];
snprintf(mappath, PATH_MAX, "map%s/%lu",
filename, (unsigned long) block);
pthread_mutex_lock(&lock);
char *bucket = fsll_getlink(cache_dir, mappath);
if (bucket == NULL) {
if (warn_if_not_exist) {
WARN("Cache invalidation: block %lu of file %s doesn't exist.\n",
(unsigned long) block, filename);
}
pthread_mutex_unlock(&lock);
return -ENOENT;
}
cache_invalidate_bucket(filename, block, bucket);
FREE(bucket);
pthread_mutex_unlock(&lock);
return 0;
}
int cache_invalidate_block(const char *filename, uint32_t block)
{
return cache_invalidate_block_(filename, block, true);
}
int cache_try_invalidate_block(const char *filename, uint32_t block)
{
return cache_invalidate_block_(filename, block, false);
}
int cache_try_invalidate_blocks_above(const char *filename, uint32_t block)
{
DEBUG("trying to invalidate blocks >= %ld in %s\n", block, filename);
int ret = 0;
DIR *mapdir = NULL;
bool locked = false;
struct dirent *e = NULL;
char mappath[PATH_MAX];
snprintf(mappath, PATH_MAX, "%s/map%s", cache_dir, filename);
pthread_mutex_lock(&lock);
locked = true;
mapdir = opendir(mappath);
if (mapdir == NULL) {
ret = -errno;
goto exit;
}
e = malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
struct dirent *result = e;
while ((readdir_r(mapdir, e, &result) == 0) && (result != NULL)) {
if ((e->d_name[0] < '0') || (e->d_name[0] > '9')) continue;
uint32_t block_found;
sscanf(e->d_name, "%lu", &block_found);
if (block_found >= block) {
char *bucket = fsll_getlink(mappath, e->d_name);
cache_invalidate_bucket(filename, block_found, bucket);
FREE(bucket);
}
}
exit:
closedir(mapdir);
FREE(e);
if (locked)
pthread_mutex_unlock(&lock);
return ret;
}
int cache_free_orphan_buckets(void)
{
char bucketdir[PATH_MAX];
snprintf(bucketdir, PATH_MAX, "%s/buckets", cache_dir);
pthread_mutex_lock(&lock);
DIR *d = opendir(bucketdir);
if (d == NULL) {
PERROR("opendir in cache_free_orphan_buckets");
pthread_mutex_unlock(&lock);
return -1*errno;
}
struct dirent *e = malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
struct dirent *result = e;
while (readdir_r(d, e, &result) == 0 && result != NULL) {
if (e->d_name[0] < '0' || e->d_name[0] > '9') continue;
char bucketpath[PATH_MAX];
snprintf(bucketpath, PATH_MAX, "%s/buckets/%s", cache_dir, e->d_name);
char *parent = fsll_getlink(bucketpath, "parent");
if (fsll_file_exists(bucketpath, "data") &&
(parent == NULL || !fsll_file_exists(parent, NULL))) {
DEBUG("bucket %s is an orphan\n", e->d_name);
if (parent) {
DEBUG("\tparent was %s\n", parent);
}
free_bucket_mid_queue(bucketpath);
}
FREE(parent);
}
closedir(d);
FREE(e);
pthread_mutex_unlock(&lock);
return 0;
}
/*
* Read a block from the cache.
* Important: you can specify less than one block, but not more.
* Nor can a read be across block boundaries.
*
* mtime is the file modification time. If what's in the cache doesn't match
* this, the cache data is invalidated and this function returns -1 and sets
* ENOENT.
*
* Returns 0 on success.
* On error returns -1 and sets errno.
* In particular, if the block is not in the cache, sets ENOENT
*/
int cache_fetch(const char *filename, uint32_t block, uint64_t offset,
char *buf, uint64_t len, uint64_t *bytes_read, time_t mtime)
{
if (offset + len > bucket_max_size || filename == NULL) {
errno = EINVAL;
return -1;
}
if (len == 0) {
*bytes_read = 0;
return 0;
}
DEBUG("getting block %lu of file %s\n", (unsigned long) block, filename);
//###
pthread_mutex_lock(&lock);
char mapfile[PATH_MAX];
snprintf(mapfile, PATH_MAX, "%s/map%s/%lu",
cache_dir, filename, (unsigned long) block);
char bucketpath[PATH_MAX];
ssize_t bplen;
if ((bplen = readlink(mapfile, bucketpath, PATH_MAX-1)) == -1) {
if (errno == ENOENT || errno == ENOTDIR) {
DEBUG("block not in cache\n");
errno = ENOENT;
pthread_mutex_unlock(&lock);
return -1;
} else {
PERROR("readlink error");
errno = EIO;
pthread_mutex_unlock(&lock);
return -1;
}
}
bucketpath[bplen] = '\0';
bucket_to_head(bucketpath);
uint64_t bucket_mtime;
char mtimepath[PATH_MAX];
snprintf(mtimepath, PATH_MAX, "%s/map%s/mtime", cache_dir, filename);
FILE *f = fopen(mtimepath, "r");
if (f == NULL) {
PERROR("open mtime file failed");
bucket_mtime = 0; // will cause invalidation
} else {
if (fscanf(f, "%llu", (unsigned long long *) &bucket_mtime) != 1) {
ERROR("error reading mtime file");
// debug
char buf[4096];
fseek(f, 0, SEEK_SET);
size_t b = fread(buf, 1, 4096, f);
buf[b] = '\0';
ERROR("mtime file contains: %u bytes: %s", (unsigned int) b, buf);
fclose(f);
f = NULL;
unlink(mtimepath);
bucket_mtime = 0; // will cause invalidation
}
}
if (f) fclose(f);
if (bucket_mtime != (uint64_t)mtime) {
// mtime mismatch; invalidate and return
if (bucket_mtime < (uint64_t)mtime) {
DEBUG("cache data is %llu seconds older than the backing data\n",
(unsigned long long) mtime - bucket_mtime);
} else {
DEBUG("cache data is %llu seconds newer than the backing data\n",
(unsigned long long) bucket_mtime - mtime);
}
cache_invalidate_file_real(filename, true);
errno = ENOENT;
pthread_mutex_unlock(&lock);
return -1;
}
// [cache_dir]/buckets/%lu/data
char bucketdata[PATH_MAX];
snprintf(bucketdata, PATH_MAX, "%s/data", bucketpath);
uint64_t size = 0;
struct stat stbuf;
if (stat(bucketdata, &stbuf) == -1) {
PERROR("stat on bucket error");
errno = EIO;
pthread_mutex_unlock(&lock);
return -1;
}
size = (uint64_t) stbuf.st_size;
if (size < offset) {
WARN("offset for read is past the end: %llu vs %llu, bucket %s\n",
(unsigned long long) offset,
(unsigned long long) size,
bucketname(bucketpath));
pthread_mutex_unlock(&lock);
*bytes_read = 0;
return 0;
}
/*
if (e->bucket->size - offset < len) {
WARN("length + offset for read is past the end\n");
errno = ENXIO;
FREE(f);
pthread_mutex_unlock(&lock);
return -1;
}
*/
int fd = open(bucketdata, O_RDONLY);
if (fd == -1) {
PERROR("error opening file from cache dir");
errno = EBADF;
pthread_mutex_unlock(&lock);
return -1;
}
*bytes_read = pread(fd, buf, len, offset);
if (*bytes_read == -1) {
PERROR("error reading file from cache dir");
errno = EIO;
close(fd);
pthread_mutex_unlock(&lock);
return -1;
}
if (*bytes_read != len) {
DEBUG("read fewer than requested bytes from cache file: %llu instead of %llu\n",
(unsigned long long) *bytes_read,
(unsigned long long) len
);
/*
errno = EIO;
FREE(f);
FREE(cachefile);
close(fd);
pthread_mutex_unlock(&lock);
return -1;
*/
}
close(fd);
pthread_mutex_unlock(&lock);
//###
return 0;
}
uint64_t free_tail_bucket()
{
uint64_t freed_bytes = 0;
char *tail = fsll_getlink(cache_dir, "buckets/tail");
if (tail == NULL) {
ERROR("can't free the tail bucket, no buckets in queue!\n");
goto exit;
}
freed_bytes = free_bucket(tail);
DEBUG("freed %llu bytes in bucket %lu\n",
(unsigned long long)freed_bytes,
(unsigned long)bucket_path_to_number(tail));
exit:
FREE(tail);
return freed_bytes;
}
void make_space_available(uint64_t bytes_needed)
{
uint64_t bytes_freed = 0;
if (bytes_needed == 0)
return;
uint64_t dev_free = get_cache_fs_free_size(cache_dir);
if (dev_free >= bytes_needed) {
// device has plenty
if (use_whole_device) {
return;
} else {
// cache_size is limiting factor
if (cache_used_size + bytes_needed <= cache_size) {
return;
} else {
bytes_needed = (cache_used_size + bytes_needed) - cache_size;
}
}
} else {
// dev_free is limiting factor
bytes_needed = bytes_needed - dev_free;
}
DEBUG("need to free %llu bytes\n",
(unsigned long long) bytes_needed);
while (bytes_freed < bytes_needed) {
bytes_freed += free_tail_bucket();
}
DEBUG("freed %llu bytes total\n",
(unsigned long long) bytes_freed);
}
/*
* Adds a data block to the cache.
* Important: this must be the FULL block. All subsequent reads will
* assume that the full block is here.
*/
int cache_add(const char *filename, uint32_t block, const char *buf,
uint64_t len, time_t mtime)
{
if (len > bucket_max_size) {
errno = EOVERFLOW;
return -1;
}
if (len == 0) {
return 0;
}
char fileandblock[PATH_MAX];
snprintf(fileandblock, PATH_MAX, "map%s/%lu", filename, (unsigned long) block);
DEBUG("writing %llu bytes to %s\n", (unsigned long long) len, fileandblock);
//###
pthread_mutex_lock(&lock);
char *bucketpath = fsll_getlink(cache_dir, fileandblock);
if (bucketpath != NULL) {
if (fsll_file_exists(bucketpath, "data")) {
WARN("data already exists in cache\n");
FREE(bucketpath);
pthread_mutex_unlock(&lock);
return 0;
}
}
char *filemap = (char*)malloc(strlen(filename) + 4);
snprintf(filemap, strlen(filename)+4, "map%s", filename);
char *full_filemap_dir = (char*)malloc(strlen(cache_dir) + 5 + strlen(filename) + 1);
snprintf(full_filemap_dir, strlen(cache_dir)+5+strlen(filename)+1, "%s/map%s/",
cache_dir, filename);
DEBUG("map file = %s\n", filemap);
DEBUG("full filemap dir = %s\n", full_filemap_dir);
if (!fsll_file_exists(cache_dir, filemap)) {
FREE(filemap);
size_t i;
// start from "$cache_dir/map/"
for (i = strlen(cache_dir) + 5; i < strlen(full_filemap_dir); i++) {
if (full_filemap_dir[i] == '/') {
char *component = (char*)malloc(i+1);
strncpy(component, full_filemap_dir, i+1);
component[i] = '\0';
DEBUG("making %s\n", component);
if(mkdir(component, 0700) == -1 && errno != EEXIST) {
if (errno == ENOSPC) {
// try to free some space
DEBUG("mkdir says ENOSPC, freeing and trying again\n");
free_tail_bucket();
errno = EAGAIN;
}
else {
PERROR("mkdir in cache_add");
ERROR("\tcaused by mkdir(%s)\n", component);
errno = EIO;
}
FREE(component);
FREE(full_filemap_dir);
pthread_mutex_unlock(&lock);
return -1;
}
FREE(component);
}
}
} else {
FREE(filemap);
}
FREE(full_filemap_dir);
make_space_available(len);
FREE(bucketpath);
bucketpath = next_bucket();
DEBUG("bucket path = %s\n", bucketpath);
fsll_makelink(cache_dir, fileandblock, bucketpath);
char *fullfilemap = (char*)malloc(PATH_MAX);
snprintf(fullfilemap, PATH_MAX, "%s/%s", cache_dir, fileandblock);
fsll_makelink(bucketpath, "parent", fullfilemap);
FREE(fullfilemap);
// write mtime
char mtimepath[PATH_MAX];
snprintf(mtimepath, PATH_MAX, "%s/map%s/mtime", cache_dir, filename);
FILE *f = fopen(mtimepath, "w");
if (f == NULL) {
PERROR("opening mtime file in cache_add failed");
} else {
fprintf(f, "%llu\n", (unsigned long long) mtime);
fclose(f);
}
// finally, write data
char datapath[PATH_MAX];
snprintf(datapath, PATH_MAX, "%s/data", bucketpath);
int fd = open(datapath, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
PERROR("open in cache_add");
ERROR("\tcaused by open(%s, O_WRONLY|O_CREAT)\n", datapath);
errno = EIO;
pthread_mutex_unlock(&lock);
return -1;
}
ssize_t bytes_written = write(fd, buf, len);
if (bytes_written == -1) {
if (errno == ENOSPC) {
DEBUG("nothing written (no space on device)\n");
bytes_written = 0;
} else {
PERROR("write in cache_add");
errno = EIO;
close(fd);
pthread_mutex_unlock(&lock);
return -1;
}
}
DEBUG("%llu bytes written to cache\n",
(unsigned long long) bytes_written);
bool unchecked = is_unchecked(bucketpath);
if (!unchecked) {
cache_used_size += bytes_written;
}
// for some reason (filesystem metadata overhead?) this may need to loop a
// few times to write everything out.
while (bytes_written != len) {
DEBUG("not all bytes written to cache\n");
// Try again, more forcefully this time.
// Don't care if the FS says it has space, make some space anyway.
free_tail_bucket();
ssize_t more_bytes_written = write(fd, buf + bytes_written, len - bytes_written);
if (more_bytes_written == -1) {
if (errno == ENOSPC) {
// this is normal
DEBUG("nothing written (no space on device)\n");
more_bytes_written = 0;
} else {
PERROR("write error");
close(fd);
pthread_mutex_unlock(&lock);
return -EIO;
}
}
DEBUG("%llu more bytes written to cache (%llu total)\n",
(unsigned long long) more_bytes_written,
(unsigned long long) more_bytes_written + bytes_written);
if (!unchecked) {
cache_used_size += more_bytes_written;
}
bytes_written += more_bytes_written;
}
DEBUG("size now %llu bytes of %llu bytes (%lf%%)\n",
(unsigned long long) cache_used_size,
(unsigned long long) cache_size,
(double)100 * cache_used_size / cache_size
);
dump_queues();
close(fd);
pthread_mutex_unlock(&lock);
//###
FREE(bucketpath);
return 0;
}
int cache_has_file_real(const char *filename, uint64_t *cached_byte_count, bool do_lock)
{
DEBUG("cache_has_file %s\n", filename);
int ret = 0;
bool locked = false;
char *mapdir = NULL;
char *data = NULL;
DIR *dir = NULL;
if (filename == NULL || cached_byte_count == NULL) {
errno = EINVAL;
ret = -1;
goto exit;
}
if (do_lock) {
pthread_mutex_lock(&lock);
locked = true;
}
// Look up the file in the map.
asprintf(&mapdir, "%s/map%s", cache_dir, filename);
dir = opendir(mapdir);
if (dir == NULL) {
if (errno == ENOENT) {
DEBUG("not in cache (%s)\n", mapdir);
ret = 0;
goto exit;
}
else {
PERROR("opendir");
ERROR("\topendir on %s\n", mapdir);
ret = -EIO;
goto exit;
}
}
// Check if it's a file or directory (see if it has an mtime file).
asprintf(&data, "%s/mtime", mapdir);
bool is_file = false;
struct stat mtime_stat = {0};
if (0 == stat(data, &mtime_stat)) {
is_file = (mtime_stat.st_mode & S_IFREG) != 0;
}
else if (errno != ENOENT) {
PERROR("stat");
ERROR("\tstat on %s\n", mapdir);
ret = -EIO;
goto exit;
}
// Loop over the sub-entries in the map.
struct dirent *dirent = NULL;
while ((dirent = readdir(dir)) != NULL) {
if (dirent->d_name[0] != '.' && strcmp(dirent->d_name, "mtime") != 0) {
FREE(data);
if (is_file) {
asprintf(&data, "%s/%s/data", mapdir, dirent->d_name);
struct stat statbuf = {0};
if (0 != stat(data, &statbuf)) {
PERROR("stat");
ERROR("\tstat on %s\n", data);
ret = -EIO;
goto exit;
}
DEBUG("%llu bytes in %s\n", statbuf.st_size, data);
*cached_byte_count += statbuf.st_size;
}
else {
asprintf(&data, "%s/%s", filename, dirent->d_name);
ret = cache_has_file_real(data, cached_byte_count, false /*don't lock*/);
if (ret != 0) {
break;
}
}
}
}
exit:
if (locked)
pthread_mutex_unlock(&lock);
FREE(mapdir);
FREE(data);
closedir(dir);
return ret;
}
int cache_has_file(const char *filename, uint64_t *cached_bytes)
{
*cached_bytes = 0;
return cache_has_file_real(filename, cached_bytes, true);
}
int cache_rename(const char *path, const char *path_new)
{
DEBUG("cache_rename %s\n\t%s\n", path, path_new);
int ret = 0;
char *mapdir = NULL;
char *mapdir_new = NULL;
DIR *dir = NULL;
char *parentlink = NULL;
if (path == NULL || path_new == NULL) {
errno = EINVAL;
ret = -1;
goto exit;
}
// Look up and rename the cache map dir.
asprintf(&mapdir, "%s/map%s", cache_dir, path);
asprintf(&mapdir_new, "%s/map%s", cache_dir, path_new);
ret = rename(mapdir, mapdir_new);
if (0 != ret) {
if (ENOENT == errno) {
DEBUG("not in cache: %s\n", path);
ret = 0;
}
else {
PERROR("rename");
ret = -EIO;
}
goto exit;
}
// Next, need to fix all the buckets' parent links.
dir = opendir(mapdir_new);
if (dir == NULL) {
PERROR("opendir");
ERROR("\topendir on %s\n", mapdir_new);
ret = -EIO;
goto exit;
}
size_t cch_parentlink = strlen(mapdir_new) + 20;
parentlink = (char*)malloc(cch_parentlink);
struct dirent *dirent = NULL;
while ((dirent = readdir(dir)) != NULL) {
if (dirent->d_name[0] != '.' && strcmp(dirent->d_name, "mtime") != 0) {
snprintf(parentlink, cch_parentlink, "%s/%s/parent",
mapdir_new, dirent->d_name);
ret = unlink(parentlink);
if (0 != ret) {
PERROR("unlink");
ERROR("\tunlink on %s\n", parentlink);
ret = -EIO;
goto exit;
}
ret = symlink(mapdir_new, parentlink);
if (0 != ret) {
PERROR("symlink");
ERROR("\tsymlink from %s\n\tto %s\n", parentlink, mapdir_new);
ret = -EIO;
goto exit;
}
}
}
exit:
FREE(mapdir);
FREE(mapdir_new);
FREE(parentlink);
closedir(dir);
return ret;
}
/*
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.
*/
| Java |
/*
* Intel 3000/3010 Memory Controller kernel module
* Copyright (C) 2007 Akamai Technologies, Inc.
* Shamelessly copied from:
* Intel D82875P Memory Controller kernel module
* (C) 2003 Linux Networx (http://lnxi.com)
*
* This file may be distributed under the terms of the
* GNU General Public License.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/edac.h>
#include "edac_core.h"
#define I3000_REVISION "1.1"
#define EDAC_MOD_STR "i3000_edac"
#define I3000_RANKS 8
#define I3000_RANKS_PER_CHANNEL 4
#define I3000_CHANNELS 2
/* Intel 3000 register addresses - device 0 function 0 - DRAM Controller */
#define I3000_MCHBAR 0x44 /* MCH Memory Mapped Register BAR */
#define I3000_MCHBAR_MASK 0xffffc000
#define I3000_MMR_WINDOW_SIZE 16384
#define I3000_EDEAP 0x70 /* Extended DRAM Error Address Pointer (8b)
*
* 7:1 reserved
* 0 bit 32 of address
*/
#define I3000_DEAP 0x58 /* DRAM Error Address Pointer (32b)
*
* 31:7 address
* 6:1 reserved
* 0 Error channel 0/1
*/
#define I3000_DEAP_GRAIN (1 << 7)
/*
* Helper functions to decode the DEAP/EDEAP hardware registers.
*
* The type promotion here is deliberate; we're deriving an
* unsigned long pfn and offset from hardware regs which are u8/u32.
*/
static inline unsigned long deap_pfn(u8 edeap, u32 deap)
{
deap >>= PAGE_SHIFT;
deap |= (edeap & 1) << (32 - PAGE_SHIFT);
return deap;
}
static inline unsigned long deap_offset(u32 deap)
{
return deap & ~(I3000_DEAP_GRAIN - 1) & ~PAGE_MASK;
}
static inline int deap_channel(u32 deap)
{
return deap & 1;
}
#define I3000_DERRSYN 0x5c /* DRAM Error Syndrome (8b)
*
* 7:0 DRAM ECC Syndrome
*/
#define I3000_ERRSTS 0xc8 /* Error Status Register (16b)
*
* 15:12 reserved
* 11 MCH Thermal Sensor Event
* for SMI/SCI/SERR
* 10 reserved
* 9 LOCK to non-DRAM Memory Flag (LCKF)
* 8 Received Refresh Timeout Flag (RRTOF)
* 7:2 reserved
* 1 Multi-bit DRAM ECC Error Flag (DMERR)
* 0 Single-bit DRAM ECC Error Flag (DSERR)
*/
#define I3000_ERRSTS_BITS 0x0b03 /* bits which indicate errors */
#define I3000_ERRSTS_UE 0x0002
#define I3000_ERRSTS_CE 0x0001
#define I3000_ERRCMD 0xca /* Error Command (16b)
*
* 15:12 reserved
* 11 SERR on MCH Thermal Sensor Event
* (TSESERR)
* 10 reserved
* 9 SERR on LOCK to non-DRAM Memory
* (LCKERR)
* 8 SERR on DRAM Refresh Timeout
* (DRTOERR)
* 7:2 reserved
* 1 SERR Multi-Bit DRAM ECC Error
* (DMERR)
* 0 SERR on Single-Bit ECC Error
* (DSERR)
*/
/* Intel MMIO register space - device 0 function 0 - MMR space */
#define I3000_DRB_SHIFT 25 /* 32MiB grain */
#define I3000_C0DRB 0x100 /* Channel 0 DRAM Rank Boundary (8b x 4)
*
* 7:0 Channel 0 DRAM Rank Boundary Address
*/
#define I3000_C1DRB 0x180 /* Channel 1 DRAM Rank Boundary (8b x 4)
*
* 7:0 Channel 1 DRAM Rank Boundary Address
*/
#define I3000_C0DRA 0x108 /* Channel 0 DRAM Rank Attribute (8b x 2)
*
* 7 reserved
* 6:4 DRAM odd Rank Attribute
* 3 reserved
* 2:0 DRAM even Rank Attribute
*
* Each attribute defines the page
* size of the corresponding rank:
* 000: unpopulated
* 001: reserved
* 010: 4 KB
* 011: 8 KB
* 100: 16 KB
* Others: reserved
*/
#define I3000_C1DRA 0x188 /* Channel 1 DRAM Rank Attribute (8b x 2) */
static inline unsigned char odd_rank_attrib(unsigned char dra)
{
return (dra & 0x70) >> 4;
}
static inline unsigned char even_rank_attrib(unsigned char dra)
{
return dra & 0x07;
}
#define I3000_C0DRC0 0x120 /* DRAM Controller Mode 0 (32b)
*
* 31:30 reserved
* 29 Initialization Complete (IC)
* 28:11 reserved
* 10:8 Refresh Mode Select (RMS)
* 7 reserved
* 6:4 Mode Select (SMS)
* 3:2 reserved
* 1:0 DRAM Type (DT)
*/
#define I3000_C0DRC1 0x124 /* DRAM Controller Mode 1 (32b)
*
* 31 Enhanced Addressing Enable (ENHADE)
* 30:0 reserved
*/
enum i3000p_chips {
I3000 = 0,
};
struct i3000_dev_info {
const char *ctl_name;
};
struct i3000_error_info {
u16 errsts;
u8 derrsyn;
u8 edeap;
u32 deap;
u16 errsts2;
};
static const struct i3000_dev_info i3000_devs[] = {
[I3000] = {
.ctl_name = "i3000"},
};
static struct pci_dev *mci_pdev;
static int i3000_registered = 1;
static struct edac_pci_ctl_info *i3000_pci;
static void i3000_get_error_info(struct mem_ctl_info *mci,
struct i3000_error_info *info)
{
struct pci_dev *pdev;
pdev = to_pci_dev(mci->dev);
/*
* This is a mess because there is no atomic way to read all the
* registers at once and the registers can transition from CE being
* overwritten by UE.
*/
pci_read_config_word(pdev, I3000_ERRSTS, &info->errsts);
if (!(info->errsts & I3000_ERRSTS_BITS))
return;
pci_read_config_byte(pdev, I3000_EDEAP, &info->edeap);
pci_read_config_dword(pdev, I3000_DEAP, &info->deap);
pci_read_config_byte(pdev, I3000_DERRSYN, &info->derrsyn);
pci_read_config_word(pdev, I3000_ERRSTS, &info->errsts2);
/*
* If the error is the same for both reads then the first set
* of reads is valid. If there is a change then there is a CE
* with no info and the second set of reads is valid and
* should be UE info.
*/
if ((info->errsts ^ info->errsts2) & I3000_ERRSTS_BITS) {
pci_read_config_byte(pdev, I3000_EDEAP, &info->edeap);
pci_read_config_dword(pdev, I3000_DEAP, &info->deap);
pci_read_config_byte(pdev, I3000_DERRSYN, &info->derrsyn);
}
/*
* Clear any error bits.
* (Yes, we really clear bits by writing 1 to them.)
*/
pci_write_bits16(pdev, I3000_ERRSTS, I3000_ERRSTS_BITS,
I3000_ERRSTS_BITS);
}
static int i3000_process_error_info(struct mem_ctl_info *mci,
struct i3000_error_info *info,
int handle_errors)
{
int row, multi_chan, channel;
unsigned long pfn, offset;
multi_chan = mci->csrows[0].nr_channels - 1;
if (!(info->errsts & I3000_ERRSTS_BITS))
return 0;
if (!handle_errors)
return 1;
if ((info->errsts ^ info->errsts2) & I3000_ERRSTS_BITS) {
edac_mc_handle_ce_no_info(mci, "UE overwrote CE");
info->errsts = info->errsts2;
}
pfn = deap_pfn(info->edeap, info->deap);
offset = deap_offset(info->deap);
channel = deap_channel(info->deap);
row = edac_mc_find_csrow_by_page(mci, pfn);
if (info->errsts & I3000_ERRSTS_UE)
edac_mc_handle_ue(mci, pfn, offset, row, "i3000 UE");
else
edac_mc_handle_ce(mci, pfn, offset, info->derrsyn, row,
multi_chan ? channel : 0, "i3000 CE");
return 1;
}
static void i3000_check(struct mem_ctl_info *mci)
{
struct i3000_error_info info;
debugf1("MC%d: %s()\n", mci->mc_idx, __func__);
i3000_get_error_info(mci, &info);
i3000_process_error_info(mci, &info, 1);
}
static int i3000_is_interleaved(const unsigned char *c0dra,
const unsigned char *c1dra,
const unsigned char *c0drb,
const unsigned char *c1drb)
{
int i;
/*
* If the channels aren't populated identically then
* we're not interleaved.
*/
for (i = 0; i < I3000_RANKS_PER_CHANNEL / 2; i++)
if (odd_rank_attrib(c0dra[i]) != odd_rank_attrib(c1dra[i]) ||
even_rank_attrib(c0dra[i]) !=
even_rank_attrib(c1dra[i]))
return 0;
/*
* If the rank boundaries for the two channels are different
* then we're not interleaved.
*/
for (i = 0; i < I3000_RANKS_PER_CHANNEL; i++)
if (c0drb[i] != c1drb[i])
return 0;
return 1;
}
static int i3000_probe1(struct pci_dev *pdev, int dev_idx)
{
int rc;
int i;
struct mem_ctl_info *mci = NULL;
unsigned long last_cumul_size;
int interleaved, nr_channels;
unsigned char dra[I3000_RANKS / 2], drb[I3000_RANKS];
unsigned char *c0dra = dra, *c1dra = &dra[I3000_RANKS_PER_CHANNEL / 2];
unsigned char *c0drb = drb, *c1drb = &drb[I3000_RANKS_PER_CHANNEL];
unsigned long mchbar;
void __iomem *window;
debugf0("MC: %s()\n", __func__);
pci_read_config_dword(pdev, I3000_MCHBAR, (u32 *) & mchbar);
mchbar &= I3000_MCHBAR_MASK;
window = ioremap_nocache(mchbar, I3000_MMR_WINDOW_SIZE);
if (!window) {
printk(KERN_ERR "i3000: cannot map mmio space at 0x%lx\n",
mchbar);
return -ENODEV;
}
c0dra[0] = readb(window + I3000_C0DRA + 0); /* ranks 0,1 */
c0dra[1] = readb(window + I3000_C0DRA + 1); /* ranks 2,3 */
c1dra[0] = readb(window + I3000_C1DRA + 0); /* ranks 0,1 */
c1dra[1] = readb(window + I3000_C1DRA + 1); /* ranks 2,3 */
for (i = 0; i < I3000_RANKS_PER_CHANNEL; i++) {
c0drb[i] = readb(window + I3000_C0DRB + i);
c1drb[i] = readb(window + I3000_C1DRB + i);
}
iounmap(window);
/*
* Figure out how many channels we have.
*
* If we have what the datasheet calls "asymmetric channels"
* (essentially the same as what was called "virtual single
* channel mode" in the i82875) then it's a single channel as
* far as EDAC is concerned.
*/
interleaved = i3000_is_interleaved(c0dra, c1dra, c0drb, c1drb);
nr_channels = interleaved ? 2 : 1;
mci = edac_mc_alloc(0, I3000_RANKS / nr_channels, nr_channels, 0);
if (!mci)
return -ENOMEM;
debugf3("MC: %s(): init mci\n", __func__);
mci->dev = &pdev->dev;
mci->mtype_cap = MEM_FLAG_DDR2;
mci->edac_ctl_cap = EDAC_FLAG_SECDED;
mci->edac_cap = EDAC_FLAG_SECDED;
mci->mod_name = EDAC_MOD_STR;
mci->mod_ver = I3000_REVISION;
mci->ctl_name = i3000_devs[dev_idx].ctl_name;
mci->dev_name = pci_name(pdev);
mci->edac_check = i3000_check;
mci->ctl_page_to_phys = NULL;
/*
* The dram rank boundary (DRB) reg values are boundary addresses
* for each DRAM rank with a granularity of 32MB. DRB regs are
* cumulative; the last one will contain the total memory
* contained in all ranks.
*
* If we're in interleaved mode then we're only walking through
* the ranks of controller 0, so we double all the values we see.
*/
for (last_cumul_size = i = 0; i < mci->nr_csrows; i++) {
u8 value;
u32 cumul_size;
struct csrow_info *csrow = &mci->csrows[i];
value = drb[i];
cumul_size = value << (I3000_DRB_SHIFT - PAGE_SHIFT);
if (interleaved)
cumul_size <<= 1;
debugf3("MC: %s(): (%d) cumul_size 0x%x\n",
__func__, i, cumul_size);
if (cumul_size == last_cumul_size) {
csrow->mtype = MEM_EMPTY;
continue;
}
csrow->first_page = last_cumul_size;
csrow->last_page = cumul_size - 1;
csrow->nr_pages = cumul_size - last_cumul_size;
last_cumul_size = cumul_size;
csrow->grain = I3000_DEAP_GRAIN;
csrow->mtype = MEM_DDR2;
csrow->dtype = DEV_UNKNOWN;
csrow->edac_mode = EDAC_UNKNOWN;
}
/*
* Clear any error bits.
* (Yes, we really clear bits by writing 1 to them.)
*/
pci_write_bits16(pdev, I3000_ERRSTS, I3000_ERRSTS_BITS,
I3000_ERRSTS_BITS);
rc = -ENODEV;
if (edac_mc_add_mc(mci)) {
debugf3("MC: %s(): failed edac_mc_add_mc()\n", __func__);
goto fail;
}
/* allocating generic PCI control info */
i3000_pci = edac_pci_create_generic_ctl(&pdev->dev, EDAC_MOD_STR);
if (!i3000_pci) {
printk(KERN_WARNING
"%s(): Unable to create PCI control\n",
__func__);
printk(KERN_WARNING
"%s(): PCI error report via EDAC not setup\n",
__func__);
}
/* get this far and it's successful */
debugf3("MC: %s(): success\n", __func__);
return 0;
fail:
if (mci)
edac_mc_free(mci);
return rc;
}
/* returns count (>= 0), or negative on error */
static int __devinit i3000_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
int rc;
debugf0("MC: %s()\n", __func__);
if (pci_enable_device(pdev) < 0)
return -EIO;
rc = i3000_probe1(pdev, ent->driver_data);
if (!mci_pdev)
mci_pdev = pci_dev_get(pdev);
return rc;
}
static void __devexit i3000_remove_one(struct pci_dev *pdev)
{
struct mem_ctl_info *mci;
debugf0("%s()\n", __func__);
if (i3000_pci)
edac_pci_release_generic_ctl(i3000_pci);
mci = edac_mc_del_mc(&pdev->dev);
if (!mci)
return;
edac_mc_free(mci);
}
static const struct pci_device_id i3000_pci_tbl[] __devinitdata = {
{
PCI_VEND_DEV(INTEL, 3000_HB), PCI_ANY_ID, PCI_ANY_ID, 0, 0,
I3000},
{
0,
} /* 0 terminated list. */
};
MODULE_DEVICE_TABLE(pci, i3000_pci_tbl);
static struct pci_driver i3000_driver = {
.name = EDAC_MOD_STR,
.probe = i3000_init_one,
.remove = __devexit_p(i3000_remove_one),
.id_table = i3000_pci_tbl,
};
static int __init i3000_init(void)
{
int pci_rc;
debugf3("MC: %s()\n", __func__);
/* Ensure that the OPSTATE is set correctly for POLL or NMI */
opstate_init();
pci_rc = pci_register_driver(&i3000_driver);
if (pci_rc < 0)
goto fail0;
if (!mci_pdev) {
i3000_registered = 0;
mci_pdev = pci_get_device(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_3000_HB, NULL);
if (!mci_pdev) {
debugf0("i3000 pci_get_device fail\n");
pci_rc = -ENODEV;
goto fail1;
}
pci_rc = i3000_init_one(mci_pdev, i3000_pci_tbl);
if (pci_rc < 0) {
debugf0("i3000 init fail\n");
pci_rc = -ENODEV;
goto fail1;
}
}
return 0;
fail1:
pci_unregister_driver(&i3000_driver);
fail0:
if (mci_pdev)
pci_dev_put(mci_pdev);
return pci_rc;
}
static void __exit i3000_exit(void)
{
debugf3("MC: %s()\n", __func__);
pci_unregister_driver(&i3000_driver);
if (!i3000_registered) {
i3000_remove_one(mci_pdev);
pci_dev_put(mci_pdev);
}
}
module_init(i3000_init);
module_exit(i3000_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Akamai Technologies Arthur Ulfeldt/Jason Uhlenkott");
MODULE_DESCRIPTION("MC support for Intel 3000 memory hub controllers");
module_param(edac_op_state, int, 0444);
MODULE_PARM_DESC(edac_op_state, "EDAC Error Reporting state: 0=Poll,1=NMI");
| Java |
/***********************************************************************************
* *
* Voreen - The Volume Rendering Engine *
* *
* Copyright (C) 2005-2012 University of Muenster, Germany. *
* Visualization and Computer Graphics Group <http://viscg.uni-muenster.de> *
* For a list of authors please refer to the file "CREDITS.txt". *
* *
* This file is part of the Voreen software package. Voreen 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. *
* *
* Voreen is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR *
* A PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License in the file *
* "LICENSE.txt" along with this file. If not, see <http://www.gnu.org/licenses/>. *
* *
* For non-commercial academic use see the license exception specified in the file *
* "LICENSE-academic.txt". To get information about commercial licensing please *
* contact the authors. *
* *
***********************************************************************************/
#ifndef VRN_CLOSINGBYRECONSTRUCTIONIMAGEFILTER_H
#define VRN_CLOSINGBYRECONSTRUCTIONIMAGEFILTER_H
#include "modules/itk/processors/itkprocessor.h"
#include "voreen/core/processors/volumeprocessor.h"
#include "voreen/core/ports/allports.h"
#include <string>
#include "voreen/core/properties/boolproperty.h"
#include "voreen/core/properties/optionproperty.h"
#include "voreen/core/properties/vectorproperty.h"
namespace voreen {
class VolumeBase;
class ClosingByReconstructionImageFilterITK : public ITKProcessor {
public:
ClosingByReconstructionImageFilterITK();
virtual Processor* create() const;
virtual std::string getCategory() const { return "Volume Processing/Filtering/MathematicalMorphology"; }
virtual std::string getClassName() const { return "ClosingByReconstructionImageFilterITK"; }
virtual CodeState getCodeState() const { return CODE_STATE_STABLE; }
protected:
virtual void setDescriptions() {
setDescription("<a href=\"http://www.itk.org/Doxygen/html/classitk_1_1ClosingByReconstructionImageFilter.html\">Go to ITK-Doxygen-Description</a>");
}
template<class T>
void closingByReconstructionImageFilterITK();
virtual void process();
private:
VolumePort inport1_;
VolumePort outport1_;
BoolProperty enableProcessing_;
StringOptionProperty structuringElement_;
StringOptionProperty shape_;
IntVec3Property radius_;
BoolProperty fullyConnected_;
BoolProperty preserveIntensities_;
static const std::string loggerCat_;
};
}
#endif
| Java |
# Based partially on (wongsyrone/hbl0307106015) versions
include $(TOPDIR)/rules.mk
PKG_NAME:=samba
PKG_VERSION:=4.12.3
PKG_RELEASE:=5
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:= \
https://ftp.gwdg.de/pub/samba/stable/ \
https://ftp.heanet.ie/mirrors/ftp.samba.org/stable/ \
https://ftp.riken.jp/net/samba/samba/stable/ \
http://www.nic.funet.fi/index/samba/pub/samba/stable/ \
http://samba.mirror.bit.nl/samba/ftp/stable/ \
https://download.samba.org/pub/samba/stable/
PKG_HASH:=3fadbca4504937820d0d8a34e500a1efdcc35e0c554f05bd0a844916ae528727
PKG_MAINTAINER:=Andy Walsh <andy.walsh44+github@gmail.com>
PKG_LICENSE:=GPL-3.0-only
PKG_LICENSE_FILES:=COPYING
PKG_CPE_ID:=cpe:/a:samba:samba
# samba4=(asn1_compile,compile_et) rpcsvc-proto=(rpcgen)
HOST_BUILD_DEPENDS:=python3/host rpcsvc-proto/host perl/host perl-parse-yapp/host
PKG_BUILD_DEPENDS:=samba4/host libtasn1/host
PKG_CONFIG_DEPENDS:= \
CONFIG_SAMBA4_SERVER_NETBIOS \
CONFIG_SAMBA4_SERVER_AVAHI \
CONFIG_SAMBA4_SERVER_VFS \
CONFIG_SAMBA4_SERVER_VFSX \
CONFIG_SAMBA4_SERVER_AD_DC \
CONFIG_PACKAGE_kmod-fs-btrfs \
CONFIG_PACKAGE_kmod-fs-xfs
PYTHON3_PKG_BUILD:=0
include $(INCLUDE_DIR)/package.mk
include $(INCLUDE_DIR)/host-build.mk
include $(INCLUDE_DIR)/kernel.mk
include $(INCLUDE_DIR)/version.mk
include ../../lang/python/python3-host.mk
include ../../lang/python/python3-package.mk
include ../../lang/perl/perlver.mk
define Package/samba4/Default
SECTION:=net
CATEGORY:=Network
TITLE:=Samba $(PKG_VERSION)
URL:=https://www.samba.org/
endef
define Package/samba4/Default/description
The Samba software suite is a collection of programs that implements the
SMB/CIFS protocol for UNIX systems, allowing you to serve files and printers.
Samba 4 implements up-to protocol version SMB v3.1.1 (Win10), supports mDNS via AVAHI and a AD-DC setup via krb5.
NOTE: No cluster and printer support.
endef
define Package/samba4-libs
$(call Package/samba4/Default)
TITLE+= libs
DEPENDS:= +libtirpc +libreadline +libpopt +libcap +zlib +libgnutls +libtasn1 +libuuid +libopenssl +USE_GLIBC:libpthread \
+PACKAGE_libpam:libpam \
+SAMBA4_SERVER_VFS:attr \
+SAMBA4_SERVER_VFSX:libaio \
+SAMBA4_SERVER_AVAHI:libavahi-client \
+SAMBA4_SERVER_AD_DC:python3-cryptodome +SAMBA4_SERVER_AD_DC:libopenldap +SAMBA4_SERVER_AD_DC:jansson +SAMBA4_SERVER_AD_DC:libarchive +SAMBA4_SERVER_AD_DC:acl +SAMBA4_SERVER_AD_DC:attr
endef
define Package/samba4-server
$(call Package/samba4/Default)
TITLE+= server
DEPENDS:= +samba4-libs
CONFLICTS:=samba36-server
endef
define Package/samba4-server/description
installs: smbd (nmbd) smbpasswd pdbedit testparm (nmblookup) (smbcacls sharesec)
(samba samba-tool ntlm_auth samba-gpupdate samba_dnsupdate samba_kcc samba_spnupdate samba_upgradedns samba_downgrade_db)
This provides the basic fileserver service and is the minimum needed to serve file shares.
HINT: https://fitzcarraldoblog.wordpress.com/2016/10/17/a-correct-method-of-configuring-samba-for-browsing-smb-shares-in-a-home-network/
endef
define Package/samba4-server/config
select PACKAGE_wsdd2
source "$(SOURCE)/Config.in"
endef
define Package/samba4-client
$(call Package/samba4/Default)
TITLE+= client
DEPENDS:= +samba4-libs
endef
define Package/samba4-client/description
installs: cifsdd smbclient smbget
The smbclient program implements a simple ftp-like client for accessing SMB shares
endef
define Package/samba4-admin
$(call Package/samba4/Default)
TITLE+= admin tools
DEPENDS:= +samba4-libs
endef
define Package/samba4-admin/description
installs: net smbcontrol profiles rpcclient dbwrap_tool eventlogadm
ldbadd ldbdel ldbedit ldbmodify ldbrename ldbsearch
tdbbackup tdbdump tdbrestore tdbtool
Administration tools collection
endef
define Package/samba4-utils
$(call Package/samba4/Default)
TITLE+= utils
DEPENDS:= +samba4-libs
endef
define Package/samba4-utils/description
installs: smbstatus smbtree mvxattr smbtar smbcquotas
Utilities collection
endef
TARGET_CFLAGS += $(FPIC) -ffunction-sections -fdata-sections -I$(STAGING_DIR)/usr/include/tirpc
TARGET_LDFLAGS += -Wl,--gc-sections,--as-needed
# dont mess with sambas private rpath!
RSTRIP:=:
CONFIGURE_VARS += \
CPP="$(TARGET_CROSS)cpp"
CONFIGURE_CMD = ./buildtools/bin/waf
HOST_CONFIGURE_CMD = ./buildtools/bin/waf
# Strip options that WAF configure script does not recognize
CONFIGURE_ARGS:=$(filter-out \
--target=% \
--host=% \
--build=% \
--program-prefix=% \
--program-suffix=% \
--disable-nls \
--disable-ipv6 \
, $(CONFIGURE_ARGS))
HOST_CONFIGURE_ARGS:=$(filter-out \
--target=% \
--host=% \
--build=% \
--program-prefix=% \
--program-suffix=% \
--disable-nls \
--disable-ipv6 \
, $(HOST_CONFIGURE_ARGS))
# Waf needs the "configure" argument
CONFIGURE_ARGS:=configure $(CONFIGURE_ARGS)
HOST_CONFIGURE_ARGS:=configure $(HOST_CONFIGURE_ARGS)
CONFIGURE_ARGS += \
--hostcc="$(HOSTCC)" \
--cross-compile \
--cross-answers=cross-answers.txt \
--disable-cups \
--disable-iprint \
--disable-cephfs \
--disable-fault-handling \
--disable-glusterfs \
--disable-spotlight \
--enable-fhs \
--without-automount \
--without-iconv \
--without-lttng \
--without-ntvfs-fileserver \
--without-pam \
--without-systemd \
--without-utmp \
--without-dmapi \
--without-fam \
--without-gettext \
--without-regedit \
--without-gpgme
HOST_CONFIGURE_ARGS += \
--hostcc="$(HOSTCC)" \
--disable-cups \
--disable-iprint \
--disable-cephfs \
--disable-fault-handling \
--disable-glusterfs \
--disable-spotlight \
--disable-rpath \
--disable-rpath-install \
--disable-rpath-private-install \
--enable-fhs \
--without-automount \
--without-iconv \
--without-lttng \
--without-ntvfs-fileserver \
--without-pam \
--without-systemd \
--without-utmp \
--without-dmapi \
--without-fam \
--without-gettext \
--without-regedit \
--without-gpgme
HOST_CONFIGURE_ARGS += --disable-avahi --without-quotas --without-acl-support --without-winbind \
--without-ad-dc --without-json --without-libarchive --disable-python --nopyc --nopyo \
--without-dnsupdate --without-ads --without-ldap --without-ldb-lmdb
# Optional AES-NI support - https://lists.samba.org/archive/samba-technical/2017-September/122738.html
# Support for Nettle wasn't comitted
ifdef CONFIG_TARGET_x86_64
CONFIGURE_ARGS += --accel-aes=intelaesni
else
CONFIGURE_ARGS += --accel-aes=none
endif
CONFIGURE_ARGS += \
--with-lockdir=/var/lock \
--with-logfilebase=/var/log \
--with-piddir=/var/run \
--with-privatedir=/etc/samba
# features
ifeq ($(CONFIG_SAMBA4_SERVER_VFS),y)
CONFIGURE_ARGS += --with-quotas
else
CONFIGURE_ARGS += --without-quotas
endif
ifeq ($(CONFIG_SAMBA4_SERVER_AVAHI),y)
CONFIGURE_ARGS += --enable-avahi
else
CONFIGURE_ARGS += --disable-avahi
endif
ifeq ($(CONFIG_SAMBA4_SERVER_AD_DC),y)
CONFIGURE_ARGS += --without-winbind --without-ldb-lmdb --with-acl-support
else
CONFIGURE_ARGS += --without-winbind --without-ads --without-ldap --without-ldb-lmdb --without-ad-dc \
--without-json --without-libarchive --disable-python --nopyc --nopyo --without-dnsupdate --without-acl-support
endif
SAMBA4_PDB_MODULES :=pdb_smbpasswd,pdb_tdbsam,
SAMBA4_AUTH_MODULES :=auth_builtin,auth_sam,auth_unix,
SAMBA4_VFS_MODULES :=vfs_default,
SAMBA4_VFS_MODULES_SHARED :=auth_script,
ifeq ($(CONFIG_SAMBA4_SERVER_VFS),y)
SAMBA4_VFS_MODULES_SHARED :=$(SAMBA4_VFS_MODULES_SHARED)vfs_fruit,vfs_shadow_copy2,vfs_recycle,vfs_fake_perms,vfs_readonly,vfs_cap,vfs_offline,vfs_crossrename,vfs_catia,vfs_streams_xattr,vfs_xattr_tdb,vfs_default_quota,
ifeq ($(CONFIG_PACKAGE_kmod-fs-btrfs),y)
SAMBA4_VFS_MODULES_SHARED :=$(SAMBA4_VFS_MODULES_SHARED)vfs_btrfs,
endif
endif
ifeq ($(CONFIG_SAMBA4_SERVER_VFSX),y)
SAMBA4_VFS_MODULES_SHARED :=$(SAMBA4_VFS_MODULES_SHARED)vfs_virusfilter,vfs_shell_snap,vfs_commit,vfs_worm,vfs_aio_fork,vfs_aio_pthread,vfs_netatalk,vfs_dirsort,vfs_fileid,
ifeq ($(CONFIG_PACKAGE_kmod-fs-xfs),y)
SAMBA4_VFS_MODULES_SHARED :=$(SAMBA4_VFS_MODULES_SHARED)vfs_linux_xfs_sgid,
endif
endif
ifeq ($(CONFIG_SAMBA4_SERVER_AD_DC),y)
SAMBA4_PDB_MODULES :=$(SAMBA4_PDB_MODULES)pdb_samba_dsdb,pdb_ldapsam,
SAMBA4_AUTH_MODULES :=$(SAMBA4_AUTH_MODULES)auth_samba4,
SAMBA4_VFS_MODULES :=$(SAMBA4_VFS_MODULES)vfs_posixacl,
SAMBA4_VFS_MODULES_SHARED :=$(SAMBA4_VFS_MODULES_SHARED)vfs_audit,vfs_extd_audit,vfs_full_audit,vfs_acl_xattr,vfs_acl_tdb,
# vfs_zfsacl needs https://github.com/zfsonlinux/zfs/tree/master/include/sys/zfs_acl.h
# vfs_nfs4acl_xattr needs https://github.com/notriddle/libdrpc/blob/master/rpc/xdr.h
endif
SAMBA4_MODULES :=${SAMBA4_VFS_MODULES}${SAMBA4_AUTH_MODULES}${SAMBA4_PDB_MODULES}
SAMBA4_MODULES_SHARDED :=${SAMBA4_VFS_MODULES_SHARED}
CONFIGURE_ARGS += \
--with-static-modules=$(SAMBA4_MODULES)!DEFAULT,!FORCED \
--with-shared-modules=$(SAMBA4_MODULES_SHARDED)!DEFAULT,!FORCED
HOST_CONFIGURE_ARGS += \
--with-static-modules=!DEFAULT,!FORCED \
--with-shared-modules=!DEFAULT,!FORCED
# lib bundling
PY_VER:=$(PYTHON3_VERSION_MAJOR)$(PYTHON3_VERSION_MINOR)
# NOTE: bundle + make private, we want to avoid version configuration (build, link) conflicts
HOST_CONFIGURE_ARGS += --builtin-libraries=replace --nonshared-binary=asn1_compile,compile_et
SYSTEM_BUNDLED_LIBS:=talloc,tevent,tevent-util,texpect,tdb,ldb,tdr,cmocka,replace,com_err
PYTHON_BUNDLED_LIBS:=pytalloc-util.cpython-$(PY_VER),pyldb-util.cpython-$(PY_VER)
# CONFIGURE_ARGS += --builtin-libraries=talloc,tevent,tevent-util,texpect,tdb,ldb,tdr,cmocka,com_err
ifeq ($(CONFIG_SAMBA4_SERVER_AD_DC),y)
CONFIGURE_ARGS += --bundled-libraries=NONE,$(SYSTEM_BUNDLED_LIBS),$(PYTHON_BUNDLED_LIBS)
else
CONFIGURE_ARGS += --bundled-libraries=NONE,$(SYSTEM_BUNDLED_LIBS)
endif
CONFIGURE_ARGS += --private-libraries=$(SYSTEM_BUNDLED_LIBS)
export COMPILE_ET=$(STAGING_DIR_HOSTPKG)/bin/compile_et_samba
export ASN1_COMPILE=$(STAGING_DIR_HOSTPKG)/bin/asn1_compile_samba
# make sure we use the hostpkg build toolset and we need to find host 'yapp'
HOST_CONFIGURE_VARS+= \
PATH="$(STAGING_DIR_HOSTPKG)/bin:$(STAGING_DIR_HOSTPKG)/usr/bin:$(PATH)"
CONFIGURE_VARS += \
PATH="$(STAGING_DIR_HOSTPKG)/bin:$(STAGING_DIR_HOSTPKG)/usr/bin:$(PATH)"
# we need hostpkg bin and target config
ifeq ($(CONFIG_SAMBA4_SERVER_AD_DC),y)
CONFIGURE_VARS += \
PYTHON_CONFIG="$(STAGING_DIR)/host/bin/$(PYTHON3)-config"
endif
# we dont need GnuTLS for the host helpers
define Host/Prepare
$(call Host/Prepare/Default)
$(SED) 's,mandatory=True,mandatory=False,g' $(HOST_BUILD_DIR)/wscript_configure_system_gnutls
$(SED) 's,gnutls_version =.*,gnutls_version = gnutls_min_required_version,g' $(HOST_BUILD_DIR)/wscript_configure_system_gnutls
endef
define Host/Compile
(cd $(HOST_BUILD_DIR); \
./buildtools/bin/waf build \
--targets=asn1_compile,compile_et \
)
endef
define Host/Install
$(INSTALL_DIR) $(STAGING_DIR_HOSTPKG)/bin/
# add host tools suffix, prevent conflicts with krb5
$(INSTALL_BIN) $(HOST_BUILD_DIR)/bin/asn1_compile $(STAGING_DIR_HOSTPKG)/bin/asn1_compile_samba
$(INSTALL_BIN) $(HOST_BUILD_DIR)/bin/compile_et $(STAGING_DIR_HOSTPKG)/bin/compile_et_samba
endef
define Build/Prepare
$(Build/Prepare/Default)
ifeq ($(CONFIG_SAMBA4_SERVER_AD_DC),)
# un-bundle dnspython
$(SED) '/"dns.resolver":/d' $(PKG_BUILD_DIR)/third_party/wscript
# unbundle iso8601
$(SED) '/"iso8601":/d' $(PKG_BUILD_DIR)/third_party/wscript
endif
endef
define Build/Configure
$(CP) ./waf-cross-answers/$(ARCH).txt $(PKG_BUILD_DIR)/cross-answers.txt
echo 'Checking uname sysname type: "$(VERSION_DIST)"' >> $(PKG_BUILD_DIR)/cross-answers.txt
echo 'Checking uname machine type: "$(ARCH)"' >> $(PKG_BUILD_DIR)/cross-answers.txt
echo 'Checking uname release type: "$(LINUX_VERSION)"' >> $(PKG_BUILD_DIR)/cross-answers.txt
echo 'Checking uname version type: "$(VERSION_DIST) Linux-$(LINUX_VERSION) $(shell date +%Y-%m-%d)"' >> $(PKG_BUILD_DIR)/cross-answers.txt
# NOTE: special answers for freeBSD/CircleCI
echo 'checking for clnt_create(): OK' >> $(PKG_BUILD_DIR)/cross-answers.txt
$(call Build/Configure/Default)
endef
# Build via "waf install", avoid the make wrapper. (Samba logic is 'waf install' = build + install)
define Build/Compile
(cd $(PKG_BUILD_DIR); \
./buildtools/bin/waf install \
--jobs=$(shell nproc) \
--destdir="$(PKG_INSTALL_DIR)" \
)
endef
# No default install see above
define Build/Install
endef
define Package/samba4-libs/install
$(INSTALL_DIR) $(1)/usr/lib
$(CP) $(PKG_INSTALL_DIR)/usr/lib/*.so* $(1)/usr/lib/
# rpath-install
$(CP) $(PKG_INSTALL_DIR)/usr/lib/samba $(1)/usr/lib/
endef
define Package/samba4-client/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/{cifsdd,smbclient,smbget} $(1)/usr/bin/
endef
define Package/samba4-admin/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/{net,smbcontrol,profiles,rpcclient,dbwrap_tool} $(1)/usr/bin/
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/{ldbadd,ldbdel,ldbedit,ldbmodify,ldbrename,ldbsearch} $(1)/usr/bin/
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/{tdbbackup,tdbdump,tdbrestore,tdbtool} $(1)/usr/bin/
$(INSTALL_DIR) $(1)/usr/sbin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/sbin/eventlogadm $(1)/usr/sbin/
endef
define Package/samba4-utils/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/{smbstatus,smbtree,mvxattr,smbtar} $(1)/usr/bin/
ifeq ($(CONFIG_SAMBA4_SERVER_VFS),y)
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/smbcquotas $(1)/usr/bin/
endif
endef
define Package/samba4-server/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/{smbpasswd,pdbedit,testparm} $(1)/usr/bin/
$(INSTALL_DIR) $(1)/usr/sbin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/sbin/smbd $(1)/usr/sbin/
ifeq ($(CONFIG_SAMBA4_SERVER_NETBIOS),y)
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/sbin/nmbd $(1)/usr/sbin/
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/nmblookup $(1)/usr/bin/
endif
ifeq ($(CONFIG_SAMBA4_SERVER_AD_DC),y)
$(INSTALL_DIR) $(1)/usr/lib
$(CP) $(PKG_INSTALL_DIR)/usr/lib/$(PYTHON3) $(1)/usr/lib/
$(INSTALL_DIR) $(1)/usr/share/
$(CP) $(PKG_INSTALL_DIR)/usr/share/samba $(1)/usr/share/
# fix wrong hardcoded python3 location
$(SED) '1s,^#!/.*python3.*,#!/usr/bin/python3,' $(PKG_INSTALL_DIR)/usr/bin/samba-tool
$(SED) '1s,^#!/.*python3.*,#!/usr/bin/python3,' $(PKG_INSTALL_DIR)/usr/sbin/{samba-gpupdate,samba_dnsupdate,samba_kcc,samba_spnupdate,samba_upgradedns,samba_downgrade_db}
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/{samba-tool,ntlm_auth,oLschema2ldif} $(1)/usr/bin/
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/{sharesec,smbcacls} $(1)/usr/bin/
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/sbin/{samba,samba-gpupdate,samba_dnsupdate,samba_kcc,samba_spnupdate,samba_upgradedns,samba_downgrade_db} $(1)/usr/sbin/
endif
$(INSTALL_DIR) $(1)/etc/config $(1)/etc/samba $(1)/etc/init.d
$(INSTALL_CONF) ./files/samba.config $(1)/etc/config/samba4
$(INSTALL_DATA) ./files/smb.conf.template $(1)/etc/samba
$(INSTALL_BIN) ./files/samba.init $(1)/etc/init.d/samba4
endef
define Package/samba4-server/conffiles
/etc/config/samba4
/etc/samba/smb.conf.template
/etc/samba/smb.conf
/etc/samba/smbpasswd
/etc/samba/secrets.tdb
/etc/samba/passdb.tdb
/etc/samba/lmhosts
/etc/nsswitch.conf
/etc/krb5.conf
endef
$(eval $(call HostBuild))
$(eval $(call BuildPackage,samba4-libs))
$(eval $(call BuildPackage,samba4-server))
$(eval $(call BuildPackage,samba4-client))
$(eval $(call BuildPackage,samba4-admin))
$(eval $(call BuildPackage,samba4-utils))
| Java |
<?php
namespace Requests\Exception\HTTP;
/**
* Exception for 505 HTTP Version Not Supported responses
*
* @package Requests
*/
/**
* Exception for 505 HTTP Version Not Supported responses
*
* @package Requests
*/
class _505 extends \Requests\Exception\HTTP
{
/**
* HTTP status code
*
* @var integer
*/
protected $code = 505;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'HTTP Version Not Supported';
}
| Java |
<?php
namespace webfilesframework\core\datasystem\file\system\dropbox;
use webfilesframework\core\datasystem\file\system\MFile;
/**
* description
*
* @author Sebastian Monzel < mail@sebastianmonzel.de >
* @since 0.1.7
*/
class MDropboxFile extends MFile
{
protected $dropboxAccount;
protected $fileMetadata;
protected $filePath;
/**
*
* Enter description here ...
* @param MDropboxAccount $account
* @param $filePath
* @param bool $initMetadata
* @internal param unknown_type $fileName
*/
public function __construct(MDropboxAccount $account, $filePath, $initMetadata = true)
{
parent::__construct($filePath);
$this->filePath = $filePath;
$this->dropboxAccount = $account;
if ($initMetadata) {
$this->initMetadata();
}
}
public function initMetadata()
{
$this->fileMetadata = $this->dropboxAccount->getDropboxApi()->metaData($this->filePath);
$lastSlash = strrpos($this->fileMetadata['body']->path, '/');
$fileName = substr($this->fileMetadata['body']->path, $lastSlash + 1);
$this->fileName = $fileName;
}
public function getContent()
{
$file = $this->dropboxAccount->getDropboxApi()->getFile($this->filePath);
return $file['data'];
}
public function writeContent($content, $overwrite = false)
{
// TODO
}
/**
*
* Enter description here ...
*/
public function upload()
{
}
/**
*
* Enter description here ...
* @param $overwriteIfExists
*/
public function download($overwriteIfExists)
{
$file = $this->dropboxAccount->getDropboxApi()->getFile($this->filePath);
if (!file_exists("." . $this->filePath)) {
$fp = fopen("." . $this->filePath, "w");
fputs($fp, $file['data']);
fclose($fp);
}
}
public function downloadImageAsThumbnail()
{
$file = $this->dropboxAccount->getDropbox()->thumbnails($this->filePath, 'JPEG', 'l');
if (!file_exists("." . $this->filePath)) {
$fp = fopen("." . $this->filePath, "w");
fputs($fp, $file['data']);
fclose($fp);
}
}
} | Java |
\documentclass[../../../../testPlan.tex]{subfiles}
\begin{document}
\section{Integration Testing Strategy}
The strategy that we want to follow is the Bottom-Up Strategy. This kind of approach consists in testing the low level components first and then the level just above, until you reach the top level components.
This strategy is suitable for our system because every component is divided in low level components.
\end{document} | Java |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\SettingsWorkingDays */
$this->title = 'Update Settings Working Days: ' . $model->id;
$this->params['breadcrumbs'][] = ['label' => 'Settings Working Days', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="settings-working-days-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| Java |
/*
Copyright (C) 2014, 2015 by Yu Gong
*/
#ifndef JULIA_R_H
#define JULIA_R_H
#ifdef __cplusplus
extern "C" {
#endif
#include <R.h>
#include <julia.h>
//Convert R Type To Julia,which not contain NA
SEXP R_Julia(SEXP Var, SEXP VarNam);
//Convert R Type To Julia,which contain NA
SEXP R_Julia_NA(SEXP Var, SEXP VarNam);
//Convert R Type To Julia,which contain NA
SEXP R_Julia_NA_Factor(SEXP Var, SEXP VarNam);
//Convert R data frame To Julia
SEXP R_Julia_NA_DataFrame(SEXP Var, SEXP VarNam);
#ifdef __cplusplus
}
#endif
#endif
| Java |
/*
* Template Name: Unify - Responsive Bootstrap Template
* Description: Business, Corporate, Portfolio, E-commerce, Blog and One Page Template.
* Version: 1.8
* Author: @htmlstream
* Website: http://htmlstream.com
*/
/*Reset Styles
------------------------------------*/
* {
border-radius: 0 !important;
}
a,
a:focus,
a:hover,
a:active,
button,
button:hover {
outline: 0 !important;
}
a:focus {
text-decoration: none;
}
hr {
margin: 30px 0;
}
hr.hr-xs {
margin: 10px 0;
}
hr.hr-md {
margin: 20px 0;
}
hr.hr-lg {
margin: 40px 0;
}
/*Headings*/
h1 {
font-size: 28px;
line-height: 35px;
}
h2 {
font-size: 24px;
line-height: 33px;
}
h3 {
font-size: 20px;
line-height: 27px;
}
h4 {
line-height: 25px;
}
h5 {
line-height: 20px;
}
h6 {
line-height: 18px;
}
h1, h2, h3, h4, h5, h6 {
color: #555;
margin-top: 5px;
text-shadow: none;
font-weight: normal;
font-family: 'Open Sans', sans-serif;
}
h1 i, h2 i, h3 i, h4 i, h5 i, h6 i {
margin-right: 5px;
}
/*Block Headline*/
.headline {
display: block;
margin: 10px 0 25px 0;
border-bottom: 1px dotted #e4e9f0;
}
.headline h2 {
font-size: 22px;
}
.headline h2,
.headline h3,
.headline h4 {
margin: 0 0 -2px 0;
padding-bottom: 5px;
display: inline-block;
border-bottom: 2px solid #72c02c;
}
.headline-md {
margin-bottom: 15px;
}
.headline-md h2 {
font-size: 21px;
}
/*Heading Options*/
.heading {
text-align: center;
}
.heading h2 {
padding: 0 12px;
position: relative;
display: inline-block;
line-height: 34px !important; /*For Tagline Boxes*/
}
.heading h2:before,
.heading h2:after {
content: ' ';
width: 70%;
position: absolute;
border-width: 1px;
border-color: #bbb;
}
.heading h2:before {
right: 100%;
}
.heading h2:after {
left: 100%;
}
@media (max-width: 768px) {
.heading h2:before,
.heading h2:after {
width: 20%;
}
}
/*Headline v1*/
.heading-v1 h2:before,
.heading-v1 h2:after {
top: 15px;
height: 6px;
border-top-style: solid;
border-bottom-style: solid;
}
/*Headline v2*/
.heading-v2 h2:before,
.heading-v2 h2:after {
top: 15px;
height: 6px;
border-top-style: dashed;
border-bottom-style: dashed;
}
/*Headline v3*/
.heading-v3 h2:before,
.heading-v3 h2:after {
top: 15px;
height: 6px;
border-top-style: dotted;
border-bottom-style: dotted;
}
/*Headline v4*/
.heading-v4 h2:before,
.heading-v4 h2:after {
top: 17px;
border-bottom-style: solid;
}
/*Headline v5*/
.heading-v5 h2:before,
.heading-v5 h2:after {
top: 17px;
border-bottom-style: dashed;
}
/*Headline v6*/
.heading-v6 h2:before,
.heading-v6 h2:after {
top: 17px;
border-bottom-style: dotted;
}
/*Heading Titles v1*/
.title-v1 {
z-index: 1;
position: relative;
text-align: center;
margin-bottom: 60px;
}
.title-v1 h1,
.title-v1 h2 {
color: #444;
font-size: 28px;
position: relative;
margin-bottom: 15px;
padding-bottom: 20px;
text-transform: uppercase;
font-family: 'Open Sans', sans-serif;
}
.title-v1 h1:after,
.title-v1 h2:after {
bottom: 0;
left: 50%;
height: 1px;
width: 70px;
content: " ";
margin-left: -35px;
position: absolute;
background: #72c02c;
}
.title-v1 p {
font-size: 17px;
font-weight: 200;
}
/*Heading Titles v2*/
h2.title-v2 {
color: #555;
position: relative;
margin-bottom: 30px;
}
h2.title-v2:after {
left: 0;
width: 70px;
height: 2px;
content: " ";
bottom: -10px;
background: #555;
position: absolute;
}
h1.title-v2.title-center,
h2.title-v2.title-center,
h3.title-v2.title-center {
text-align: center;
}
h1.title-v2.title-center:after,
h2.title-v2.title-center:after,
h3.title-v2.title-center:after {
left: 50%;
width: 70px;
margin-left: -35px;
}
h1.title-light,
h2.title-light,
h3.title-light {
color: #fff;
}
h2.title-light:after {
background: #fff;
}
/*Heading Title v3*/
h1[class^="title-v3-"],
h2[class^="title-v3-"],
h3[class^="title-v3-"] {
color: #555;
}
h2.title-v3-xlg {
font-size: 28px;
line-height: 32px;
}
h1.title-v3-lg,
h2.title-v3-lg {
font-size: 24px;
line-height: 28px;
}
h1.title-v3-md,
h2.title-v3-md {
font-size: 20px;
line-height: 24px;
}
h2.title-v3-sm,
h3.title-v3-md {
font-size: 18px;
line-height: 24px;
}
h3.title-v3-md {
line-height: 22px;
}
h3.title-v3-sm {
font-size: 16px;
line-height: 20px;
}
h2.title-v3-xs {
font-size: 16px;
line-height: 22px;
}
h3.title-v3-xs {
font-size: 14px;
margin-bottom: 0;
}
/*Headline Center*/
.headline-center {
text-align: center;
position: relative;
}
.headline-center h2 {
color: #555;
font-size: 24px;
position: relative;
margin-bottom: 20px;
padding-bottom: 15px;
}
.headline-center h2:after {
left: 50%;
z-index: 1;
width: 30px;
height: 2px;
content: " ";
bottom: -5px;
margin-left: -15px;
text-align: center;
position: absolute;
background: #72c02c;
}
.headline-center p {
/*color: #999;*/
font-size: 14px;
/*padding: 0 150px;*/
}
@media (max-width: 991px) {
.headline-center p {
padding: 0 50px;
}
}
.headline-center.headline-light h2 {
color: #fff;
}
.headline-center.headline-light p {
color: #eee;
}
/*Headline Center v2*/
.headline-center-v2 {
z-index: 0;
text-align: center;
position: relative;
}
.headline-center-v2 h2 {
color: #555;
font-size: 24px;
margin-bottom: 20px;
text-transform: uppercase;
}
.headline-center-v2 span.bordered-icon {
color: #fff;
padding: 0 10px;
font-size: 15px;
line-height: 18px;
position: relative;
margin-bottom: 25px;
display: inline-block;
}
.headline-center-v2 span.bordered-icon:before,
.headline-center-v2 span.bordered-icon:after {
top: 8px;
height: 1px;
content: " ";
width: 100px;
background: #fff;
position: absolute;
}
.headline-center-v2 span.bordered-icon:before {
left: 100%;
}
.headline-center-v2 span.bordered-icon:after {
right: 100%;
}
.headline-center-v2 p {
color: #555;
font-size: 14px;
padding: 0 70px;
}
.headline-center-v2.headline-center-v2-dark p {
color: #666;
}
.headline-center-v2.headline-center-v2-dark span.bordered-icon {
color: #666;
}
.headline-center-v2.headline-center-v2-dark span.bordered-icon:before,
.headline-center-v2.headline-center-v2-dark span.bordered-icon:after {
background: #666;
}
/*Headline Left*/
.headline-left {
position: relative;
}
.headline-left .headline-brd {
color: #555;
position: relative;
margin-bottom: 25px;
padding-bottom: 10px;
}
.headline-left .headline-brd:after {
left: 1px;
z-index: 1;
width: 30px;
height: 2px;
content: " ";
bottom: -5px;
position: absolute;
background: #72c02c;
}
/*Headline v2
------------------------------------*/
.headline-v2 {
display: block;
background: #fff;
padding: 1px 10px;
margin: 0 0 20px 0;
border-left: 2px solid #000;
}
.headline-v2 h2 {
margin: 3px 0;
font-size: 20px;
font-weight: 200;
}
/*Heading Sizes
------------------------------------*/
h2.heading-md {
font-size: 20px;
line-height: 24px;
}
h2.heading-sm,
h3.heading-md {
font-size: 18px;
line-height: 24px;
}
h3.heading-md {
line-height: 22px;
}
h3.heading-sm {
font-size: 16px;
line-height: 20px;
}
h2.heading-xs {
font-size: 16px;
line-height: 22px;
}
h3.heading-xs {
font-size: 14px;
margin-bottom: 0;
}
/*Devider
------------------------------------*/
.devider.devider-dotted {
border-top: 2px dotted #eee;
}
.devider.devider-dashed {
border-top: 2px dashed #eee;
}
.devider.devider-db {
height: 5px;
border-top: 1px solid #eee;
border-bottom: 1px solid #eee;
}
.devider.devider-db-dashed {
height: 5px;
border-top: 1px dashed #ddd;
border-bottom: 1px dashed #ddd;
}
.devider.devider-db-dotted {
height: 5px;
border-top: 1px dotted #ddd;
border-bottom: 1px dotted #ddd;
}
/*Tables
------------------------------------*/
/*Basic Tables*/
.table thead > tr > th {
border-bottom: none;
}
@media (max-width: 768px) {
.table th.hidden-sm,
.table td.hidden-sm {
display: none !important;
}
}
/*Forms
------------------------------------*/
.form-control {
box-shadow: none;
}
.form-control:focus {
border-color: #bbb;
box-shadow: 0 0 2px #c9c9c9;
}
/*Form Spacing*/
.form-spacing .form-control {
margin-bottom: 15px;
}
/*Form Icons*/
.input-group-addon {
color: #b3b3b3;
font-size: 14px;
background: #fff;
}
/*Carousel v1
------------------------------------*/
.carousel-v1 .carousel-caption {
left: 0;
right: 0;
bottom: 0;
padding: 7px 15px;
background: rgba(0, 0, 0, 0.7);
}
.carousel-v1 .carousel-caption p {
color: #fff;
margin-bottom: 0;
}
.carousel-v1 .carousel-arrow a.carousel-control {
opacity: 1;
font-size:30px;
height:inherit;
width: inherit;
background: none;
text-shadow: none;
position: inherit;
}
.carousel-v1 .carousel-arrow a i {
top: 50%;
opacity: 0.6;
background: #000;
margin-top: -18px;
padding: 2px 12px;
position: absolute;
}
.carousel-v1 .carousel-arrow a i:hover {
opacity: 0.8;
}
.carousel-v1 .carousel-arrow a.left i {
left: 0;
}
.carousel-v1 .carousel-arrow a.right i {
right: 0;
}
/*Carousel v2
------------------------------------*/
.carousel-v2 .carousel-control,
.carousel-v2 .carousel-control:hover {
opacity: 1;
text-shadow: none;
}
.carousel-v2 .carousel-control.left,
.carousel-v2 .carousel-control.right {
top: 50%;
z-index: 5;
color: #eee;
width: 45px;
height: 45px;
font-size: 30px;
margin-top: -22px;
position: absolute;
text-align: center;
display: inline-block;
border: 2px solid #eee;
background: rgba(0,0,0,0.1);
}
.carousel-v2 .carousel-control:hover {
background: rgba(0,0,0,0.3);
-webkit-transition: all 0.4s ease-in-out;
-moz-transition: all 0.4s ease-in-out;
-o-transition: all 0.4s ease-in-out;
transition: all 0.4s ease-in-out;
}
.carousel-v2 .carousel-control.left {
left: 20px;
}
.carousel-v2 .carousel-control.right {
right: 20px;
}
.carousel-v2 .carousel-control .arrow-prev,
.carousel-v2 .carousel-control .arrow-next {
top: -5px;
position: relative;
}
.carousel-v2 .carousel-control .arrow-next {
right: -2px;
}
@media (min-width: 768px) {
.carousel-indicators {
bottom: 10px;
}
}
/*Tabs
------------------------------------*/
/*Tabs v1*/
.tab-v1 .nav-tabs {
border: none;
background: none;
border-bottom: solid 2px #72c02c;
}
.tab-v1 .nav-tabs a {
font-size: 14px;
padding: 5px 15px;
}
.tab-v1 .nav-tabs > .active > a,
.tab-v1 .nav-tabs > .active > a:hover,
.tab-v1 .nav-tabs > .active > a:focus {
color: #fff;
border: none;
background: #72c02c;
}
.tab-v1 .nav-tabs > li > a {
border: none;
}
.tab-v1 .nav-tabs > li > a:hover {
color: #fff;
background: #72c02c;
}
.tab-v1 .tab-content {
padding: 10px 0;
}
.tab-v1 .tab-content img {
margin-top: 4px;
margin-bottom: 15px;
}
.tab-v1 .tab-content img.img-tab-space {
margin-top: 7px;
}
/*Tabs v2*/
.tab-v2 .nav-tabs {
border-bottom: none;
}
.tab-v2 .nav-tabs li a {
padding: 9px 16px;
background: none;
border: none;
}
.tab-v2 .nav-tabs li.active a {
background: #fff;
padding: 7px 15px 9px;
border: solid 1px #eee;
border-top: solid 2px #72c02c;
border-bottom: none !important;
}
.tab-v2 .tab-content {
padding: 10px 16px;
border: solid 1px #eee;
}
/*Tabs v3*/
.tab-v3 .nav-pills li a {
color: #777;
font-size: 17px;
padding: 4px 8px;
margin-bottom: 3px;
background: #fafafa;
border: solid 1px #eee;
}
.tab-v3 .nav-pills li a:hover,
.tab-v3 .nav-pills li.active a {
color: #fff;
background: #72c02c;
border: solid 1px #68af28;
}
.tab-v3 .nav-pills li i {
width: 1.25em;
margin-right: 5px;
text-align: center;
display: inline-block;
}
.tab-v3 .tab-content {
padding: 15px;
background: #fafafa;
border: solid 1px #eee;
}
/*Accordions
------------------------------------*/
/*Accordion v1*/
.acc-v1 .panel-heading {
padding: 0;
box-shadow: none;
}
.acc-v1 .panel-heading a {
display: block;
font-size: 14px;
padding: 5px 15px;
background: #fefefe;
}
.acc-icon a.accordion-toggle i {
color: #555;
margin-right: 8px;
}
.acc-icon a.accordion-toggle:hover i {
color: #39414c;
}
/*Navigation
------------------------------------*/
/*Pegination*/
.pagination li a {
color: #777;
padding: 5px 15px;
}
.pagination li a:hover {
color: #fff;
background: #5fb611;
border-color: #5fb611;
}
.pagination > .active > a,
.pagination > .active > span,
.pagination > .active > a:hover,
.pagination > .active > span:hover,
.pagination > .active > a:focus,
.pagination > .active > span:focus {
border-color: #72c02c;
background-color: #72c02c;
}
/*Pagination Without Space*/
.pagination-no-space .pagination {
margin: 0;
}
/*Pager*/
.pager li > a:hover,
.pager li > a:focus {
color: #fff;
background: #5fb611;
border-color: #5fb611;
}
/*Pager v2 and v3
------------------------------------*/
.pager.pager-v2 li > a {
border: none;
}
.pager.pager-v2 li > a,
.pager.pager-v3 li > a {
-webkit-transition: all 0.1s ease-in-out;
-moz-transition: all 0.1s ease-in-out;
-o-transition: all 0.1s ease-in-out;
transition: all 0.1s ease-in-out;
}
.pager.pager-v2 li > a:hover,
.pager.pager-v2 li > a:focus,
.pager.pager-v3 li > a:hover,
.pager.pager-v3 li > a:focus {
color: #fff;
background: #72c02c;
}
/*Pager Amount*/
.pager.pager-v2 li.page-amount,
.pager.pager-v3 li.page-amount {
font-size: 16px;
font-style: italic;
}
.pager.pager-v2 li.page-amount,
.pager.pager-v2 li.page-amount:hover,
.pager.pager-v2 li.page-amount:focus,
.pager.pager-v3 li.page-amount,
.pager.pager-v3 li.page-amount:hover,
.pager.pager-v3 li.page-amount:focus {
top: 7px;
color: #777;
position: relative;
}
/*Pager Size*/
.pager.pager-v2.pager-md li a,
.pager.pager-v3.pager-md li a {
font-size: 16px;
padding: 8px 18px;
}
/*Sidebar Menu
------------------------------------*/
/*Sidebar Menu v1*/
.sidebar-nav-v1 li {
padding: 0;
}
.sidebar-nav-v1 li a {
display: block;
padding: 8px 30px 8px 10px;
}
.sidebar-nav-v1 li a:hover {
text-decoration: none;
}
.sidebar-nav-v1 > li.active,
.sidebar-nav-v1 > li.active:hover {
background: #717984;
}
.sidebar-nav-v1 > li.active,
.sidebar-nav-v1 > li.active:hover,
.sidebar-nav-v1 > li.active:focus {
border-color: #ddd;
}
.sidebar-nav-v1 > li.active > a {
color: #fff;
}
/*Sidebar Sub Navigation*/
.sidebar-nav-v1 li ul {
padding: 0;
list-style: none;
}
.sidebar-nav-v1 li ul,
.sidebar-nav-v1 li.active ul a {
background: #f8f8f8;
}
.sidebar-nav-v1 li ul a {
color: #555;
font-size: 12px;
border-top: solid 1px #ddd;
padding: 6px 30px 6px 17px;
}
.sidebar-nav-v1 ul li:hover a,
.sidebar-nav-v1 ul li.active a {
color: #72c02c;
}
/*Sidebar Badges*/
.list-group-item li > .badge {
float: right;
}
.sidebar-nav-v1 span.badge {
margin-top: 8px;
margin-right: 10px;
}
.sidebar-nav-v1 .list-toggle > span.badge {
margin-right: 25px;
}
.sidebar-nav-v1 ul li span.badge {
margin-top: 8px;
font-size: 11px;
padding: 3px 5px;
margin-right: 10px;
}
/*Sidebar List Toggle*/
.list-toggle:after {
top: 7px;
right: 10px;
color: #777;
font-size: 14px;
content: "\f105";
position: absolute;
font-weight: normal;
display: inline-block;
font-family: FontAwesome;
}
.list-toggle.active:after {
color: #fff;
content: "\f107";
}
/*Button Styles
------------------------------------*/
.btn {
box-shadow: none;
}
.btn-u {
border: 0;
color: #fff;
font-size: 14px;
cursor: pointer;
font-weight: 400;
padding: 6px 13px;
position: relative;
background: #72c02c;
white-space: nowrap;
display: inline-block;
text-decoration: none;
}
.btn-u:hover {
color: #fff;
text-decoration: none;
-webkit-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-in-out;
-o-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
.btn-u.btn-block {
text-align: center;
}
a.btn-u {
/*padding: 4px 13px;*/
/*vertical-align: middle;*/
}
.btn-u-sm,
a.btn-u-sm {
padding: 3px 12px;
}
.btn-u-lg,
a.btn-u-lg {
font-size: 18px;
padding: 10px 25px;
}
.btn-u-xs,
a.btn-u-xs {
font-size: 12px;
padding: 2px 12px;
line-height: 18px;
}
/*Button Groups*/
.btn-group .dropdown-menu > li > a {
padding: 3px 13px;
}
.btn-group > .btn-u,
.btn-group-vertical > .btn-u {
float: left;
position: relative;
}
.btn-group > .btn-u:first-child {
margin-left: 0;
}
/*For FF Only*/
@-moz-document url-prefix() {
.footer-subsribe .btn-u {
padding-bottom: 4px;
}
}
@media (max-width: 768px) {
@-moz-document url-prefix() {
.btn-u {
padding-bottom: 6px;
}
}
}
/*Buttons Color*/
.btn-u:hover,
.btn-u:focus,
.btn-u:active,
.btn-u.active,
.open .dropdown-toggle.btn-u {
background: #5fb611;
}
.btn-u-split.dropdown-toggle {
border-left: solid 1px #5fb611;
}
.btn-u.btn-u-blue {
background: #3498db;
}
.btn-u.btn-u-blue:hover,
.btn-u.btn-u-blue:focus,
.btn-u.btn-u-blue:active,
.btn-u.btn-u-blue.active,
.open .dropdown-toggle.btn-u.btn-u-blue {
background: #2980b9;
}
.btn-u.btn-u-split-blue.dropdown-toggle {
border-left: solid 1px #2980b9;
}
.btn-u.btn-u-red {
background: #e74c3c;
}
.btn-u.btn-u-red:hover,
.btn-u.btn-u-red:focus,
.btn-u.btn-u-red:active,
.btn-u.btn-u-red.active,
.open .dropdown-toggle.btn-u.btn-u-red {
background: #c0392b;
}
.btn-u.btn-u-split-red.dropdown-toggle {
border-left: solid 1px #c0392b;
}
.btn-u.btn-u-orange {
background: #e67e22;
}
.btn-u.btn-u-orange:hover,
.btn-u.btn-u-orange:focus,
.btn-u.btn-u-orange:active,
.btn-u.btn-u-orange.active,
.open .dropdown-toggle.btn-u.btn-u-orange {
background: #d35400;
}
.btn-u.btn-u-split-orange.dropdown-toggle {
border-left: solid 1px #d35400;
}
.btn-u.btn-u-sea {
background: #1abc9c;
}
.btn-u.btn-u-sea:hover,
.btn-u.btn-u-sea:focus,
.btn-u.btn-u-sea:active,
.btn-u.btn-u-sea.active,
.open .dropdown-toggle.btn-u.btn-u-sea {
background: #16a085;
}
.btn-u.btn-u-split-sea.dropdown-toggle {
border-left: solid 1px #16a085;
}
.btn-u.btn-u-green {
background: #2ecc71;
}
.btn-u.btn-u-green:hover,
.btn-u.btn-u-green:focus,
.btn-u.btn-u-green:active,
.btn-u.btn-u-green.active,
.open .dropdown-toggle.btn-u.btn-u-green {
background: #27ae60;
}
.btn-u.btn-u-split-green.dropdown-toggle {
border-left: solid 1px #27ae60;
}
.btn-u.btn-u-yellow {
background: #f1c40f;
}
.btn-u.btn-u-yellow:hover,
.btn-u.btn-u-yellow:focus,
.btn-u.btn-u-yellow:active,
.btn-u.btn-u-yellow.active,
.open .dropdown-toggle.btn-u.btn-u-yellow {
background: #f39c12;
}
.btn-u.btn-u-split-yellow.dropdown-toggle {
border-left: solid 1px #f39c12;
}
.btn-u.btn-u-default {
background: #95a5a6;
}
.btn-u.btn-u-default:hover,
.btn-u.btn-u-default:focus,
.btn-u.btn-u-default:active,
.btn-u.btn-u-default.active,
.open .dropdown-toggle.btn-u.btn-u-default {
background: #7f8c8d;
}
.btn-u.btn-u-split-default.dropdown-toggle {
border-left: solid 1px #7f8c8d;
}
.btn-u.btn-u-purple {
background: #9b6bcc;
}
.btn-u.btn-u-purple:hover,
.btn-u.btn-u-purple:focus,
.btn-u.btn-u-purple:active,
.btn-u.btn-u-purple.active,
.open .dropdown-toggle.btn-u.btn-u-purple {
background: #814fb5;
}
.btn-u.btn-u-split-purple.dropdown-toggle {
border-left: solid 1px #814fb5;
}
.btn-u.btn-u-aqua {
background: #27d7e7;
}
.btn-u.btn-u-aqua:hover,
.btn-u.btn-u-aqua:focus,
.btn-u.btn-u-aqua:active,
.btn-u.btn-u-aqua.active,
.open .dropdown-toggle.btn-u.btn-u-aqua {
background: #26bac8;
}
.btn-u.btn-u-split-aqua.dropdown-toggle {
border-left: solid 1px #26bac8;
}
.btn-u.btn-u-brown {
background: #9c8061;
}
.btn-u.btn-u-brown:hover,
.btn-u.btn-u-brown:focus,
.btn-u.btn-u-brown:active,
.btn-u.btn-u-brown.active,
.open .dropdown-toggle.btn-u.btn-u-brown {
background: #81674b;
}
.btn-u.btn-u-split-brown.dropdown-toggle {
border-left: solid 1px #81674b;
}
.btn-u.btn-u-dark-blue {
background: #4765a0;
}
.btn-u.btn-u-dark-blue:hover,
.btn-u.btn-u-dark-blue:focus,
.btn-u.btn-u-dark-blue:active,
.btn-u.btn-u-dark-blue.active,
.open .dropdown-toggle.btn-u.btn-u-dark-blue {
background: #324c80;
}
.btn-u.btn-u-split-dark.dropdown-toggle {
border-left: solid 1px #324c80;
}
.btn-u.btn-u-light-green {
background: #79d5b3;
}
.btn-u.btn-u-light-green:hover,
.btn-u.btn-u-light-green:focus,
.btn-u.btn-u-light-green:active,
.btn-u.btn-u-light-green.active,
.open .dropdown-toggle.btn-u.btn-u-light-green {
background: #59b795;
}
.btn-u.btn-u-split-light-green.dropdown-toggle {
border-left: solid 1px #59b795;
}
.btn-u.btn-u-dark {
background: #555;
}
.btn-u.btn-u-dark:hover,
.btn-u.btn-u-dark:focus,
.btn-u.btn-u-dark:active,
.btn-u.btn-u-dark.active,
.open .dropdown-toggle.btn-u.btn-u-dark {
background: #333;
}
.btn-u.btn-u-split-dark.dropdown-toggle {
border-left: solid 1px #333;
}
.btn-u.btn-u-light-grey {
background: #585f69;
}
.btn-u.btn-u-light-grey:hover,
.btn-u.btn-u-light-grey:focus,
.btn-u.btn-u-light-grey:active,
.btn-u.btn-u-light-grey.active,
.open .dropdown-toggle.btn-u.btn-u-light-grey {
background: #484f58;
}
.btn-u.btn-u-split-light-grey.dropdown-toggle {
border-left: solid 1px #484f58;
}
/*Bordered Buttons*/
.btn-u.btn-brd {
color: #555;
/*font-weight: 200;*/
background: none;
padding: 5px 13px;
border: solid 1px transparent;
-webkit-transition: all 0.1s ease-in-out;
-moz-transition: all 0.1s ease-in-out;
-o-transition: all 0.1s ease-in-out;
transition: all 0.1s ease-in-out;
}
.btn-u.btn-brd:hover {
background: none;
border: solid 1px #eee;
}
.btn-u.btn-brd:focus {
background: none;
}
.btn-u.btn-brd.btn-brd-hover:hover {
color: #fff !important;
}
.btn-u.btn-brd {
border-color: #72c02c;
}
.btn-u.btn-brd:hover {
color: #5fb611;
border-color: #5fb611;
}
.btn-u.btn-brd.btn-brd-hover:hover {
background: #5fb611;
}
.btn-u.btn-brd.btn-u-blue {
border-color: #3498db;
}
.btn-u.btn-brd.btn-u-blue:hover {
color: #2980b9;
border-color: #2980b9;
}
.btn-u.btn-brd.btn-u-blue.btn-brd-hover:hover {
background: #2980b9;
}
.btn-u.btn-brd.btn-u-red {
border-color: #e74c3c;
}
.btn-u.btn-brd.btn-u-red:hover {
color: #c0392b;
border-color: #c0392b;
}
.btn-u.btn-brd.btn-u-red.btn-brd-hover:hover {
background: #c0392b;
}
.btn-u.btn-brd.btn-u-orange {
border-color: #e67e22;
}
.btn-u.btn-brd.btn-u-orange:hover {
color: #d35400;
border-color: #d35400;
}
.btn-u.btn-brd.btn-u-orange.btn-brd-hover:hover {
background: #d35400;
}
.btn-u.btn-brd.btn-u-sea {
border-color: #1abc9c;
}
.btn-u.btn-brd.btn-u-sea:hover {
color: #16a085;
border-color: #16a085;
}
.btn-u.btn-brd.btn-u-sea.btn-brd-hover:hover {
background: #16a085;
}
.btn-u.btn-brd.btn-u-green {
border-color: #2ecc71;
}
.btn-u.btn-brd.btn-u-green:hover {
color: #27ae60;
border-color: #27ae60;
}
.btn-u.btn-brd.btn-u-green.btn-brd-hover:hover {
background: #27ae60;
}
.btn-u.btn-brd.btn-u-yellow {
border-color: #f1c40f;
}
.btn-u.btn-brd.btn-u-yellow:hover {
color: #f39c12;
border-color: #f39c12;
}
.btn-u.btn-brd.btn-u-yellow.btn-brd-hover:hover {
background: #f39c12;
}
.btn-u.btn-brd.btn-u-default {
border-color: #95a5a6;
}
.btn-u.btn-brd.btn-u-default:hover {
color: #7f8c8d;
border-color: #7f8c8d;
}
.btn-u.btn-brd.btn-u-default.btn-brd-hover:hover {
background: #7f8c8d;
}
.btn-u.btn-brd.btn-u-dark {
border-color: #555;
}
.btn-u.btn-brd.btn-u-dark:hover {
color: #333;
border-color: #333;
}
.btn-u.btn-brd.btn-u-dark.btn-brd-hover:hover {
background: #333;
}
.btn-u.btn-brd.btn-u-light-grey {
border-color: #585f69;
}
.btn-u.btn-brd.btn-u-light-grey:hover {
color: #484f58;
border-color: #484f58;
}
.btn-u.btn-brd.btn-u-light-grey.btn-brd-hover:hover {
background: #484f58;
}
.btn-u.btn-brd.btn-u-purple {
border-color: #9b6bcc;
}
.btn-u.btn-brd.btn-u-purple:hover {
color: #814fb5;
border-color: #814fb5;
}
.btn-u.btn-brd.btn-u-purple.btn-brd-hover:hover {
background: #814fb5;
}
.btn-u.btn-brd.btn-u-aqua {
border-color: #27d7e7;
}
.btn-u.btn-brd.btn-u-aqua:hover {
color: #26bac8;
border-color: #26bac8;
}
.btn-u.btn-brd.btn-u-aqua.btn-brd-hover:hover {
background: #26bac8;
}
.btn-u.btn-brd.btn-u-brown {
border-color: #9c8061;
}
.btn-u.btn-brd.btn-u-brown:hover {
color: #81674b;
border-color: #81674b;
}
.btn-u.btn-brd.btn-u-brown.btn-brd-hover:hover {
background: #81674b;
}
.btn-u.btn-brd.btn-u-dark-blue {
border-color: #4765a0;
}
.btn-u.btn-brd.btn-u-dark-blue:hover {
color: #324c80;
border-color: #324c80;
}
.btn-u.btn-brd.btn-u-dark-blue.btn-brd-hover:hover {
background: #324c80;
}
.btn-u.btn-brd.btn-u-light-green {
border-color: #79d5b3;
}
.btn-u.btn-brd.btn-u-light-green:hover {
color: #59b795;
border-color: #59b795;
}
.btn-u.btn-brd.btn-u-light-green.btn-brd-hover:hover {
background: #59b795;
}
.btn-u.btn-brd.btn-u-light {
color: #fff;
border-color: #fff;
}
.btn-u.btn-brd.btn-u-light:hover {
border-color: #fff;
}
.btn-u.btn-brd.btn-u-light.btn-brd-hover:hover {
background: #fff;
color: #555 !important;
}
/*Dropdown Buttons
------------------------------------*/
.dropdown-show {
box-shadow: 0 0 4px #eee;
display: inline-block;
position: relative;
}
/*Badges and Labels
------------------------------------*/
/*Labels*/
span.label {
font-size: 11px;
font-weight: 400;
padding: 4px 7px;
}
/*Badges*/
span.badge {
font-weight: 400;
padding: 4px 7px;
}
span.label-u,
span.badge-u {
background: #72c02c;
}
span.label-blue,
span.badge-blue {
background: #3498db;
}
span.label-red,
span.badge-red {
background: #e74c3c;
}
span.label-green,
span.badge-green {
background: #2ecc71;
}
span.label-sea,
span.badge-sea {
background: #1abc9c;
}
span.label-orange,
span.badge-orange {
background: #e67e22;
}
span.label-yellow,
span.badge-yellow {
background: #f1c40f;
}
span.label-purple,
span.badge-purple {
background: #9b6bcc;
}
span.label-aqua,
span.badge-aqua {
background: #27d7e7;
}
span.label-brown,
span.badge-brown {
background: #9c8061;
}
span.label-dark-blue,
span.badge-dark-blue {
background: #4765a0;
}
span.label-light-green,
span.badge-light-green {
background: #79d5b3;
}
span.label-light,
span.badge-light {
color: #777;
background: #ecf0f1;
}
span.label-dark,
span.badge-dark {
background: #555;
}
/*Badge Lists*/
.badge-lists li {
position: relative;
}
.badge-lists span.badge {
top: -10px;
right: -6px;
position: absolute;
}
/*Badge Icons*/
.badge-lists.badge-icons span.badge {
min-width: 12px;
padding: 3px 6px;
}
.badge-lists.badge-icons i {
font-size: 18px;
min-width: 25px;
}
/*Badge Box v1*/
.badge-box-v1 a {
color: #777;
min-width: 40px;
font-size: 18px;
padding: 8px 9px;
display: inline-block;
border: solid 1px #eee;
}
/*Badge Box v2*/
.badge-box-v2 a {
color: #777;
font-size: 12px;
padding: 10px;
min-width: 70px;
text-align: center;
display: inline-block;
border: solid 1px #eee;
}
.badge-box-v2 a i {
font-size: 20px;
}
/*General Badge Box*/
.badge-box-v1 a i,
.badge-box-v2 a i {
display: block;
margin: 1px auto 2px;
}
.badge-box-v1 a:hover,
.badge-box-v2 a:hover {
color: #555;
border-color: #555;
text-decoration: none;
-webkit-transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
}
/*Icons
------------------------------------*/
/*Social Icons*/
.social-icons {
margin: 0;
padding: 0;
}
.social-icons li {
list-style: none;
margin-right: 3px;
margin-bottom: 5px;
text-indent: -9999px;
display: inline-block;
}
.social-icons li a, a.social-icon {
width: 28px;
height: 28px;
display: block;
background-position: 0 0;
background-repeat: no-repeat;
transition: all 0.3s ease-in-out;
-o-transition: all 0.3s ease-in-out;
-ms-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-in-out;
-webkit-transition: all 0.3s ease-in-out;
}
.social-icons li:hover a {
background-position: 0 -38px;
}
.social-icons-color li a {
opacity: 0.7;
background-position: 0 -38px !important;
-webkit-backface-visibility: hidden; /*For Chrome*/
}
.social-icons-color li a:hover {
opacity: 1;
}
.social_amazon {background: url(../img/icons/social/amazon.png) no-repeat;}
.social_behance {background: url(../img/icons/social/behance.png) no-repeat;}
.social_blogger {background: url(../img/icons/social/blogger.png) no-repeat;}
.social_deviantart {background: url(../img/icons/social/deviantart.png) no-repeat;}
.social_dribbble {background: url(../img/icons/social/dribbble.png) no-repeat;}
.social_dropbox {background: url(../img/icons/social/dropbox.png) no-repeat;}
.social_evernote {background: url(../img/icons/social/evernote.png) no-repeat;}
.social_facebook {background: url(../img/icons/social/facebook.png) no-repeat;}
.social_forrst {background: url(../img/icons/social/forrst.png) no-repeat;}
.social_github {background: url(../img/icons/social/github.png) no-repeat;}
.social_googleplus {background: url(../img/icons/social/googleplus.png) no-repeat;}
.social_jolicloud {background: url(../img/icons/social/jolicloud.png) no-repeat;}
.social_last-fm {background: url(../img/icons/social/last-fm.png) no-repeat;}
.social_linkedin {background: url(../img/icons/social/linkedin.png) no-repeat;}
.social_picasa {background: url(../img/icons/social/picasa.png) no-repeat;}
.social_pintrest {background: url(../img/icons/social/pintrest.png) no-repeat;}
.social_rss {background: url(../img/icons/social/rss.png) no-repeat;}
.social_skype {background: url(../img/icons/social/skype.png) no-repeat;}
.social_spotify {background: url(../img/icons/social/spotify.png) no-repeat;}
.social_stumbleupon {background: url(../img/icons/social/stumbleupon.png) no-repeat;}
.social_tumblr {background: url(../img/icons/social/tumblr.png) no-repeat;}
.social_twitter {background: url(../img/icons/social/twitter.png) no-repeat;}
.social_vimeo {background: url(../img/icons/social/vimeo.png) no-repeat;}
.social_wordpress {background: url(../img/icons/social/wordpress.png) no-repeat;}
.social_xing {background: url(../img/icons/social/xing.png) no-repeat;}
.social_yahoo {background: url(../img/icons/social/yahoo.png) no-repeat;}
.social_youtube {background: url(../img/icons/social/youtube.png) no-repeat;}
.social_vk {background: url(../img/icons/social/vk.png) no-repeat;}
.social_instagram {background: url(../img/icons/social/instagram.png) no-repeat;}
/*Font Awesome Icon Styles*/
i.icon-custom {
color: #555;
width: 40px;
height: 40px;
font-size: 20px;
line-height: 40px;
margin-bottom: 5px;
text-align: center;
display: inline-block;
border: solid 1px #555;
}
i.icon-sm {
width: 35px;
height: 35px;
font-size: 16px;
line-height: 35px;
}
i.icon-md {
width: 55px;
height: 55px;
font-size: 22px;
line-height: 55px;
}
i.icon-lg {
width: 60px;
height: 60px;
font-size: 31px;
line-height: 60px;
margin-bottom: 10px;
}
i.icon-2x {
font-size: 30px;
}
i.icon-3x {
font-size: 40px;
}
i.icon-4x {
font-size: 50px;
}
/*Line Icons*/
i.icon-line {
font-size: 17px;
}
i.icon-sm.icon-line {
font-size: 14px;
}
i.icon-md.icon-line {
font-size: 22px;
}
i.icon-lg.icon-line {
font-size: 28px;
}
i.icon-2x.icon-line {
font-size: 27px;
}
i.icon-3x.icon-line {
font-size: 36px;
}
i.icon-4x.icon-line {
font-size: 47px;
}
/*Icon Styles For Links*/
.link-icon,
.link-bg-icon {
color: #555;
}
.link-icon:hover,
.link-bg-icon:hover {
border: none;
text-decoration: none;
}
.link-icon:hover i {
color: #72c02c;
background: none;
border: solid 1px #72c02c;
}
.link-bg-icon:hover i {
color: #72c02c;
background: #72c02c;
border-color: #72c02c;
color: #fff !important;
}
/*Icons Color*/
i.icon-color-u,
i.icon-color-red,
i.icon-color-sea,
i.icon-color-dark,
i.icon-color-grey,
i.icon-color-blue,
i.icon-color-green,
i.icon-color-yellow,
i.icon-color-orange,
i.icon-color-purple,
i.icon-color-aqua,
i.icon-color-brown,
i.icon-color-dark-blue,
i.icon-color-light-grey,
i.icon-color-light-green, {
background: none;
}
i.icon-color-u {
color: #72c02c;
border: solid 1px #72c02c;
}
i.icon-color-blue {
color: #3498db;
border: solid 1px #3498db;
}
i.icon-color-red {
color: #e74c3c;
border: solid 1px #e74c3c;
}
i.icon-color-sea {
color: #1abc9c;
border: solid 1px #1abc9c;
}
i.icon-color-green {
color: #2ecc71;
border: solid 1px #2ecc71;
}
i.icon-color-yellow {
color: #f1c40f;
border: solid 1px #f1c40f;
}
i.icon-color-orange {
color: #e67e22;
border: solid 1px #e67e22;
}
i.icon-color-grey {
color: #95a5a6;
border: solid 1px #95a5a6;
}
i.icon-color-purple {
color: #9b6bcc;
border: solid 1px #9b6bcc;
}
i.icon-color-aqua {
color: #27d7e7;
border: solid 1px #27d7e7;
}
i.icon-color-brown {
color: #9c8061;
border: solid 1px #9c8061;
}
i.icon-color-dark-blue {
color: #4765a0;
border: solid 1px #4765a0;
}
i.icon-color-light-green {
color: #79d5b3;
border: solid 1px #79d5b3;
}
i.icon-color-light {
color: #fff;
border: solid 1px #fff;
}
i.icon-color-light-grey {
color: #585f69;
border: solid 1px #585f69;
}
/*Icons Backgroun Color*/
i.icon-bg-u,
i.icon-bg-red,
i.icon-bg-sea,
i.icon-bg-dark,
i.icon-bg-darker,
i.icon-bg-grey,
i.icon-bg-blue,
i.icon-bg-green,
i.icon-bg-yellow,
i.icon-bg-orange,
i.icon-bg-purple,
i.icon-bg-aqua,
i.icon-bg-brown,
i.icon-bg-dark-blue,
i.icon-bg-light-grey,
i.icon-bg-light-green {
color: #fff;
border-color: transparent;
}
i.icon-bg-u {
background: #72c02c;
}
i.icon-bg-blue {
background: #3498db;
}
i.icon-bg-red {
background: #e74c3c;
}
i.icon-bg-sea {
background: #1abc9c;
}
i.icon-bg-green {
background: #2ecc71;
}
i.icon-bg-yellow {
background: #f1c40f;
}
i.icon-bg-orange {
background: #e67e22;
}
i.icon-bg-grey {
background: #95a5a6;
}
i.icon-bg-dark {
background: #555;
}
i.icon-bg-darker {
background: #333;
}
i.icon-bg-purple {
background: #9b6bcc;
}
i.icon-bg-aqua {
background: #27d7e7;
}
i.icon-bg-brown {
background: #9c8061;
}
i.icon-bg-dark-blue {
background: #4765a0;
}
i.icon-bg-light-green {
background: #79d5b3;
}
i.icon-bg-light {
background: #fff;
border-color: transparent;
}
i.icon-bg-light-grey {
background: #585f69;
border-color: transparent;
}
/* Make Font Awesome icons fixed width */
.fa-fixed [class^="fa"],
.fa-fixed [class*=" fa"] {
width: 1.25em;
text-align: center;
display: inline-block;
}
.fa-fixed [class^="fa"].fa-lg,
.fa-fixed [class*=" fa"].fa-lg {
/* increased font size for fa-lg */
width: 1.5625em;
}
/*Content Boxes
------------------------------------*/
/*Content Boxes v1*/
.content-boxes-v1 {
text-align: center;
}
.content-boxes-v1 span {
display: block;
margin-top: 5px;
}
/*Content Boxes v2*/
@media (max-width: 992px) {
.content-boxes-v2,
.content-boxes-v2 .text-justify {
text-align: center;
}
.content-boxes-v2 span {
display: block;
margin-top: 5px;
}
}
/*Content Boxes v3*/
.content-boxes-v3 i.icon-custom {
top: 8px;
float: left;
position: relative;
}
.content-boxes-v3 .content-boxes-in-v3 {
padding: 0 10px;
overflow: hidden;
}
.content-boxes-v3 .content-boxes-in-v3 h3 {
font-size: 18px;
line-height: 22px;
margin-bottom: 3px;
text-transform: capitalize;
}
.content-boxes-v3 .content-boxes-in-v3 h3 a {
color: #555;
}
/*Content Boxes Right v3*/
.content-boxes-v3.content-boxes-v3-right {
text-align: right;
}
.content-boxes-v3.content-boxes-v3-right i.icon-custom {
float: right;
margin-left: 10px;
}
@media (max-width: 768px){
.content-boxes-v3.content-boxes-v3-right {
text-align: inherit;
}
.content-boxes-v3.content-boxes-v3-right i.icon-custom {
float: left;
margin-left: 0;
}
}
/*Content Boxes v4*/
.content-boxes-v4 h2 {
color: #555;
font-size: 18px;
font-weight: bold;
text-transform: uppercase;
}
.content-boxes-v4 a {
color: #777;
font-size: 11px;
font-weight: bold;
text-transform: uppercase;
}
.content-boxes-v4 i {
width: 25px;
color: #72c02c;
font-size: 35px;
margin-top: 10px;
}
.content-boxes-in-v4 {
padding: 0 10px;
overflow: hidden;
}
.content-boxes-v4-sm i {
font-size: 26px;
margin-top: 10px;
margin-right: 5px;
}
/*Content Boxes v5*/
.content-boxes-v5 i {
float: left;
color: #999;
width: 50px;
height: 50px;
padding: 11px;
font-size: 22px;
background: #eee;
line-height: 28px;
text-align: center;
margin-right: 15px;
display: inline-block;
}
.content-boxes-v5:hover i {
color: #fff;
background: #72c02c;
}
/*Content Boxes v6*/
.content-boxes-v6 {
padding-top: 25px;
text-align: center;
}
.content-boxes-v6 i {
color: #fff;
width: 90px;
height: 90px;
padding: 30px;
font-size: 30px;
line-height: 30px;
position: relative;
text-align: center;
background: #dedede;
margin-bottom: 25px;
display: inline-block;
}
.content-boxes-v6 i:after {
top: -8px;
left: -8px;
right: -8px;
bottom: -8px;
content: " ";
position: absolute;
border: 1px solid #dedede;
border-radius: 50% !important;
}
.content-boxes-v6:hover i,
.content-boxes-v6:hover i:after {
-webkit-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-in-out;
-o-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
.content-boxes-v6:hover i {
background: #72c02c;
}
.content-boxes-v6:hover i:after {
border-color: #72c02c;
}
/*Colored Content Boxes
------------------------------------*/
.service-block {
padding: 20px 30px;
text-align: center;
margin-bottom: 20px;
}
.service-block p,
.service-block h2 {
color: #fff;
}
.service-block h2 a:hover{
text-decoration: none;
}
.service-block-light,
.service-block-default {
background: #fafafa;
border: solid 1px #eee;
}
.service-block-default:hover {
box-shadow: 0 0 8px #eee;
}
.service-block-light p,
.service-block-light h2,
.service-block-default p,
.service-block-default h2 {
color: #555;
}
.service-block-u {
background: #72c02c;
}
.service-block-blue {
background: #3498db;
}
.service-block-red {
background: #e74c3c;
}
.service-block-sea {
background: #1abc9c;
}
.service-block-grey {
background: #95a5a6;
}
.service-block-yellow {
background: #f1c40f;
}
.service-block-orange {
background: #e67e22;
}
.service-block-green {
background: #2ecc71;
}
.service-block-purple {
background: #9b6bcc;
}
.service-block-aqua {
background: #27d7e7;
}
.service-block-brown {
background: #9c8061;
}
.service-block-dark-blue {
background: #4765a0;
}
.service-block-light-green {
background: #79d5b3;
}
.service-block-dark {
background: #555;
}
.service-block-light {
background: #ecf0f1;
}
/*Funny Boxes
------------------------------------*/
.funny-boxes {
background: #f7f7f7;
padding: 20px 20px 15px;
-webkit-transition:all 0.3s ease-in-out;
-moz-transition:all 0.3s ease-in-out;
-o-transition:all 0.3s ease-in-out;
transition:all 0.3s ease-in-out;
}
.funny-boxes h2 {
margin-top: 0;
font-size: 18px;
line-height: 20px;
}
.funny-boxes h2 a {
color: #555;
}
.funny-boxes p a {
color: #72c02c;
}
.funny-boxes .funny-boxes-img li {
font-size: 12px;
margin-bottom: 2px;
}
.funny-boxes .funny-boxes-img li i {
color: #72c02c;
font-size: 12px;
margin-right: 5px;
}
@media (max-width: 992px) {
.funny-boxes .funny-boxes-img li {
display: inline-block;
}
}
.funny-boxes .funny-boxes-img img {
margin: 5px 10px 15px 0;
}
.funny-boxes ul.funny-boxes-rating li {
display: inline-block;
}
.funny-boxes ul.funny-boxes-rating li i {
color: #f8be2c;
cursor: pointer;
font-size: 14px;
}
.funny-boxes ul.funny-boxes-rating li i:hover {
color: #f8be2c;
}
/*Funny Colored Boxes*/
.funny-boxes-colored p,
.funny-boxes-colored h2 a,
.funny-boxes-colored .funny-boxes-img li,
.funny-boxes-colored .funny-boxes-img li i {
color: #fff;
}
/*Red Funny Box*/
.funny-boxes-red {
background: #e74c3c;
}
/*Dark Red Funny Box*/
.funny-boxes-purple {
background: #9b6bcc;
}
/*Blue Funny Box*/
.funny-boxes-blue {
background: #3498db;
}
/*Grey Funny Box*/
.funny-boxes-grey {
background: #95a5a6;
}
/*Turquoise Funny Box*/
.funny-boxes-sea {
background: #1abc9c;
}
/*Turquoise Top Bordered Funny Box*/
.funny-boxes-top-sea {
border-top: solid 2px #1abc9c;
}
.funny-boxes-top-sea:hover {
border-top-color: #16a085;
}
/*Yellow Top Bordered Funny Box**/
.funny-boxes-top-yellow {
border-top: solid 2px #f1c40f;
}
.funny-boxes-top-yellow:hover {
border-top-color: #f39c12;
}
/*Red Top Bordered Funny Box**/
.funny-boxes-top-red {
border-top: solid 2px #e74c3c;
}
.funny-boxes-top-red:hover {
border-top-color: #c0392b;
}
/*Purple Top Bordered Funny Box**/
.funny-boxes-top-purple {
border-top: solid 2px #9b6bcc;
}
.funny-boxes-top-purple:hover {
border-top-color: #814fb5;
}
/*Orange Left Bordered Funny Box**/
.funny-boxes-left-orange {
border-left: solid 2px #e67e22;
}
.funny-boxes-left-orange:hover {
border-left-color: #d35400;
}
/*Green Left Bordered Funny Box**/
.funny-boxes-left-green {
border-left: solid 2px #72c02c;
}
.funny-boxes-left-green:hover {
border-left-color: #5fb611;
}
/*Blue Left Bordered Funny Box**/
.funny-boxes-left-blue {
border-left: solid 2px #3498db;
}
.funny-boxes-left-blue:hover {
border-left-color: #2980b9;
}
/*Dark Left Bordered Funny Box**/
.funny-boxes-left-dark {
border-left: solid 2px #555;
}
.funny-boxes-left-dark:hover {
border-left-color: #333;
}
/*Typography
------------------------------------*/
.text-justify p { text-align: justify;}
.text-transform-uppercase { text-transform: uppercase;}
.text-transform-normal { text-transform: inherit !important;}
.font-bold { font-weight: 600;}
.font-light { font-weight: 200;}
.font-normal { font-weight: 400 !important;}
/*Text Dropcap*/
.dropcap {
float: left;
color: #72c02c;
padding: 5px 0;
font-size: 45px;
font-weight: 200;
line-height: 30px;
margin: 0px 5px 0 0;
}
.dropcap-bg {
float: left;
color: #fff;
padding: 7px 0;
min-width: 50px;
font-size: 35px;
font-weight: 200;
line-height: 35px;
text-align: center;
background: #72c02c;
margin: 4px 10px 0 0;
}
/*Text Highlights*/
.text-highlights {
color: #fff;
font-weight: 200;
padding: 0px 5px;
background: #555;
}
.text-highlights-green {
background: #72c02c;
}
.text-highlights-blue {
background: #3498db;
}
.text-highlights-red {
background: #e74c3c;
}
.text-highlights-sea {
background: #1abc9c;
}
.text-highlights-orange {
background: #e67e22;
}
.text-highlights-yellow {
background: #f1c40f;
}
.text-highlights-purple {
background: #9b6bcc;
}
.text-highlights-aqua {
background: #27d7e7;
}
.text-highlights-brown {
background: #9c8061;
}
.text-highlights-dark-blue {
background: #4765a0;
}
.text-highlights-light-green {
background: #79d5b3;
}
/*Text Borders*/
.text-border {
border-bottom: dashed 1px #555;
}
.text-border-default {
border-color: #95a5a6;
}
.text-border-green {
border-color: #72c02c;
}
.text-border-blue {
border-color: #3498db;
}
.text-border-red {
border-color: #e74c3c;
}
.text-border-yellow {
border-color: #f1c40f;
}
.text-border-purple {
border-color: #9b6bcc;
}
/*List Styles*/
.list-styles li {
margin-bottom: 8px;
}
/*Contextual Backgrounds*/
.contex-bg p {
opacity: 0.8;
padding: 8px 10px;
}
.contex-bg p:hover {
opacity: 1;
}
/*Blockquote*/
blockquote {
padding: 5px 15px;
border-left-width: 2px;
}
blockquote p {
font-size: 14px;
font-weight: 400;
}
blockquote h1,
blockquote h2,
blockquote span {
font-size: 18px;
margin: 0 0 8px;
line-height: 24px;
}
/*Blockquote Styles*/
blockquote.bq-text-lg p,
blockquote.bq-text-lg small {
text-transform: uppercase;
}
blockquote.bq-text-lg p {
font-size: 22px;
font-weight: 300;
line-height: 32px;
}
blockquote.text-right,
blockquote.hero.text-right {
border-left: none;
border-right: 2px solid #eee;
}
blockquote.hero.text-right,
blockquote.hero.text-right:hover {
border-color: #555;
}
blockquote:hover,
blockquote.text-right:hover {
border-color: #72c02c;
-webkit-transition: all 0.4s ease-in-out;
-moz-transition: all 0.4s ease-in-out;
-o-transition: all 0.4s ease-in-out;
transition: all 0.4s ease-in-out;
}
blockquote.bq-dark,
blockquote.bq-dark:hover {
border-color: #585f69;
}
blockquote.bq-green {
border-color: #72c02c;
}
/*Blockquote Hero Styles*/
blockquote.hero {
border: none;
padding: 18px;
font-size: 16px;
background: #f3f3f3;
border-left: solid 2px #666;
}
blockquote.hero:hover {
background: #eee;
border-left-color: #666;
}
blockquote.hero.hero-dark,
blockquote.hero.hero-default {
border: none;
}
blockquote.hero.hero-dark {
background: #444;
}
blockquote.hero.hero-dark:hover {
background: #555;
}
blockquote.hero.hero-default {
background: #72c02c;
}
blockquote.hero.hero-default:hover {
background: #5fb611;
}
blockquote.hero.hero-dark p,
blockquote.hero.hero-dark h2,
blockquote.hero.hero-dark small,
blockquote.hero.hero-default p,
blockquote.hero.hero-default h2,
blockquote.hero.hero-default small {
color: #fff;
font-weight: 200;
}
/*Tag Boxes
------------------------------------*/
.tag-box {
padding: 20px;
background: #fff;
margin-bottom: 30px;
}
.tag-box h2 {
font-size: 20px;
line-height: 25px;
}
.tag-box p {
margin-bottom: 0;
}
.tag-box.tag-text-space p {
margin-bottom: 10px;
}
/*Tag Boxes v1*/
.tag-box-v1 {
border: solid 1px #eee;
border-top: solid 2px #72c02c;
}
/*Tag Boxes v2*/
.tag-box-v2 {
background: #fafafa;
border: solid 1px #eee;
border-left: solid 2px #72c02c;
}
/*Tag Boxes v3*/
.tag-box-v3 {
border: solid 2px #eee;
}
/*Tag Boxes v4*/
.tag-box-v4 {
border: dashed 1px #bbb;
}
/*Tag Boxes v5*/
.tag-box-v5 {
margin: 20px 0;
text-align: center;
border: dashed 1px #ccc;
}
.tag-box-v5 span {
color: #555;
font-size: 28px;
margin-bottom: 0;
}
/*Tag Boxes v6*/
.tag-box-v6 {
background: #fafafa;
border: solid 1px #eee;
}
/*Tag Boxes v7*/
.tag-box-v7 {
border: solid 1px #eee;
border-bottom: solid 2px #72c02c;
}
/*Testimonials
------------------------------------*/
/*Testimonials*/
.testimonials {
margin-bottom: 10px;
}
.testimonials .testimonial-info {
color: #72c02c;
font-size: 16px;
padding: 0 15px;
margin-top: 18px;
}
.testimonials .testimonial-info span {
top: 3px;
position: relative;
}
.testimonials .testimonial-info em {
color: #777;
display: block;
font-size: 13px;
}
.testimonials .testimonial-info img {
width: 60px;
float: left;
height: 60px;
padding: 2px;
margin-right: 15px;
border: solid 1px #ccc;
}
.testimonials .testimonial-author {
overflow: hidden;
}
.testimonials .carousel-arrow {
top: -65px;
position: relative;
}
.testimonials .carousel-arrow i {
color: #777;
padding: 2px;
min-width: 25px;
font-size: 20px;
text-align: center;
background: #f5f5f5;
}
.testimonials .carousel-arrow i:hover {
color: #fff;
background: #72c02c;
}
.testimonials .carousel-control {
opacity: 1;
width: 100%;
text-align: right;
text-shadow: none;
position: absolute;
filter: Alpha(opacity = 100); /*For IE*/
}
.testimonials .carousel-control.left {
right: 27px;
left: auto;
}
.testimonials .carousel-control.right {
right: 0px;
}
/*Testimonials v1*/
.testimonials.testimonials-v1 .item p {
position: relative;
}
.testimonials.testimonials-v1 .item p:after,
.testimonials.testimonials-v1 .item p:before {
left: 80px;
bottom: -20px;
}
.testimonials.testimonials-v1 .item p:after {
border-top: 22px solid;
border-left: 0 solid transparent;
border-right: 22px solid transparent;
}
/*Testimonials v2*/
.testimonials.testimonials-v2 .testimonial-info {
padding: 0 20px;
}
.testimonials.testimonials-v2 p {
padding-bottom: 15px;
}
.testimonials.testimonials-v2 .carousel-arrow {
top: -55px;
}
.testimonials.testimonials-v2 .item p:after,
.testimonials.testimonials-v2 .item p:before {
left: 8%;
bottom: 45px;
}
.testimonials.testimonials-v2 .item p:after {
border-top: 20px solid;
border-left: 25px solid transparent;
border-right: 0px solid transparent;
}
/*General Testimonials v1/v2*/
.testimonials.testimonials-v1 p,
.testimonials.testimonials-v2 p {
padding: 15px;
font-size: 14px;
font-style: italic;
background: #f5f5f5;
}
.testimonials.testimonials-v1 .item p:after,
.testimonials.testimonials-v2 .item p:after {
width: 0;
height: 0;
content: " ";
display: block;
position: absolute;
border-top-color: #f5f5f5;
border-left-style: inset; /*FF fixes*/
border-right-style: inset; /*FF fixes*/
}
/*Testimonials Backgrounds*/
.testimonials-bg-dark .item p,
.testimonials-bg-default .item p {
color: #fff;
font-weight: 200;
}
.testimonials-bg-dark .carousel-arrow i,
.testimonials-bg-default .carousel-arrow i {
color: #fff;
}
/*Testimonials Default*/
.testimonials-bg-default .item p {
background: #72c02c;
}
.testimonials.testimonials-bg-default .item p:after,
.testimonials.testimonials-bg-default .item p:after {
border-top-color: #72c02c;
}
.testimonials-bg-default .carousel-arrow i {
background: #72c02c;
}
.testimonials.testimonials-bg-default .carousel-arrow i:hover {
background: #5fb611;
}
/*Testimonials Dark*/
.testimonials-bg-dark .item p {
background: #555;
}
.testimonials.testimonials-bg-dark .item p:after,
.testimonials.testimonials-bg-dark .item p:after {
border-top-color: #555;
}
.testimonials-bg-dark .carousel-arrow i {
color: #fff;
background: #555;
}
.testimonials.testimonials-bg-dark .carousel-arrow i:hover {
background: #333;
}
.testimonials.testimonials-bg-dark .testimonial-info {
color: #555;
}
/*Panels (Portlets)
------------------------------------*/
.panel-heading {
color: #fff;
padding: 5px 15px;
}
/*Panel Table*/
.panel .table {
margin-bottom: 0;
}
/*Panel Unify*/
.panel-u {
border-color: #72c02c;
}
.panel-u > .panel-heading {
background: #72c02c;
}
/*Panel Blue*/
.panel-blue {
border-color: #3498db;
}
.panel-blue > .panel-heading {
background: #3498db;
}
/*Panel Red*/
.panel-red {
border-color: #e74c3c;
}
.panel-red > .panel-heading {
background: #e74c3c;
}
/*Panel Green*/
.panel-green {
border-color: #2ecc71;
}
.panel-green > .panel-heading {
background: #2ecc71;
}
/*Panel Sea*/
.panel-sea {
border-color: #1abc9c;
}
.panel-sea > .panel-heading {
background: #1abc9c;
}
/*Panel Orange*/
.panel-orange {
border-color: #e67e22;
}
.panel-orange > .panel-heading {
background: #e67e22;
}
/*Panel Yellow*/
.panel-yellow {
border-color: #f1c40f;
}
.panel-yellow > .panel-heading {
background: #f1c40f;
}
/*Panel Grey*/
.panel-grey {
border-color: #95a5a6;
}
.panel-grey > .panel-heading {
background: #95a5a6;
}
/*Panel Dark*/
.panel-dark {
border-color: #555;
}
.panel-dark > .panel-heading {
background: #555;
}
/*Panel Purple*/
.panel-purple {
border-color: #9b6bcc;
}
.panel-purple > .panel-heading {
background: #9b6bcc;
}
/*Panel Aqua*/
.panel-aqua {
border-color: #27d7e7;
}
.panel-aqua > .panel-heading {
background: #27d7e7;
}
/*Panel Brown*/
.panel-brown {
border-color: #9c8061;
}
.panel-brown > .panel-heading {
background: #9c8061;
}
/*Panel Dark Blue*/
.panel-dark-blue {
border-color: #4765a0;
}
.panel-dark-blue > .panel-heading {
background: #4765a0;
}
/*Panel Light Green*/
.panel-light-green {
border-color: #79d5b3;
}
.panel-light-green > .panel-heading {
background: #79d5b3;
}
/*Panel Default Dark*/
.panel-default-dark {
border-color: #585f69;
}
.panel-default-dark > .panel-heading {
background: #585f69;
}
/*Progress Bar
------------------------------------*/
.progress-u {
box-shadow: none;
}
.progress-u .progress-bar {
box-shadow: none;
}
/*progress-bar (sizes)*/
.progress-lg {
height: 25px;
}
.progress-lg p {
padding-top: 3px;
}
.progress-sm {
height: 12px;
}
.progress-xs {
height: 7px;
}
.progress-xxs {
height: 3px;
}
/*progress-bar (colors)*/
.progress {
background: #e5e5e5;
}
.progress-bar-u {
background: #72c02c;
}
.progress-bar-blue {
background: #3498db;
}
.progress-bar-orange {
background: #e67e22;
}
.progress-bar-red {
background: #e74c3c;
}
.progress-bar-purple {
background: #9b6bcc;
}
.progress-bar-aqua {
background: #27d7e7;
}
.progress-bar-brown {
background: #9c8061;
}
.progress-bar-dark-blue {
background: #4765a0;
}
.progress-bar-light-green {
background: #79d5b3;
}
.progress-bar-dark {
background: #555;
}
/*Progress Bar Animation
------------------------------------*/
.progress {
position: relative;
}
.progress .progress-bar {
overflow: hidden;
line-height: 20px;
position: absolute;
}
.progress-box .progress-bar {
transition: all 3s ease-in;
-o-transition: all 3s ease-in;
-ms-transition: all 3s ease-in;
-moz-transition: all 3s ease-in;
-webkit-transition: all 3s ease-in;
}
/*Vertical Progress Bar*/
.progress.vertical {
float: left;
width: 100%;
height: 200px;
margin-right: 20px;
}
.progress.vertical.bottom {
position: relative;
}
.progress.vertical .progress-bar {
height: 0;
width: 100%;
transition: height 3s ease;
-o-transition: height 3s ease;
-ms-transition: height 3s ease;
-moz-transition: height 3s ease;
-webkit-transition: height 3s ease;
}
.progress.vertical.bottom .progress-bar {
bottom: 0;
position: absolute;
}
/*Count Stars
------------------------------------*/
.stars-existing {
color: #72c02c;
cursor: pointer;
}
.star-lg {
font-size: 30px;
}
.star-sm {
font-size: 25px;
}
.star-xs {
font-size: 20px;
}
.star-default {
font-size: 16px;
}
/*Media (Audio/Videos and Images)
------------------------------------*/
/*Images*/
img.img-bordered {
padding: 3px;
border: solid 1px #eee;
}
img.img-circle {
border-radius: 50% !important;
}
img.image-sm {
width: 50px;
height: 50px;
}
img.image-md {
width: 100px;
height: 100px;
}
/*Responsive Video*/
.responsive-video {
height: 0;
padding-top: 1px;
position: relative;
padding-bottom: 56.25%; /*16:9*/
}
.responsive-video iframe {
top: 0;
left: 0;
width: 100%;
height: 100%;
position: absolute;
}
/*Tags v1
------------------------------------*/
.tags-v1 li {
margin: 0;
padding: 0;
}
.tags-v1 li a {
font-size: 13px;
padding: 4px 8px;
line-height: 32px;
border: solid 2px #eee;
border-radius: 20px !important;
-webkit-transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
}
.tags-v1 li a:hover {
text-decoration: none;
border-color: #e0e0e0;
}
/*Tags v2
------------------------------------*/
.tags-v2 li {
padding: 7px 0 7px 4px;
}
.tags-v2 li a {
color: #555;
font-size: 13px;
padding: 5px 10px;
border: solid 1px #bbb;
}
.tags-v2 li a:hover {
color: #fff;
background: #555;
border-color: #555;
text-decoration: none;
-webkit-transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
}
/*Lists
------------------------------------*/
.list-row {
padding: 0;
margin-bottom: 0;
list-style: none;
}
/*Lists v1*/
.lists-v1 li {
margin-bottom: 10px;
}
.lists-v1 i {
color: #fff;
width: 15px;
height: 15px;
padding: 1px;
font-size: 13px;
margin-right: 7px;
text-align: center;
background: #72c02c;
display: inline-block;
border-radius: 50% !important;
}
/*Lists v2*/
.lists-v2 li {
margin-bottom: 10px;
}
.lists-v2 i {
color: #72c02c;
font-size: 13px;
margin-right: 7px;
display: inline-block;
}
/*Column Sizes
------------------------------------*/
/*Remove the Gutter Padding from Columns*/
.no-gutter > [class*='col-'] {
padding-right: 0;
padding-left: 0;
}
.no-gutter.no-gutter-boxed {
padding-right: 15px;
padding-left: 15px;
}
/*Heights
------------------------------------*/
.height-100 { min-height: 100px;}
.height-150 { min-height: 150px;}
.height-200 { min-height: 200px;}
.height-250 { min-height: 250px;}
.height-300 { min-height: 300px;}
.height-350 { min-height: 350px;}
.height-400 { min-height: 400px;}
.height-450 { min-height: 450px;}
.height-500 { min-height: 500px !important;}
/*Spaces
------------------------------------*/
.no-padding {
padding: 0 !important;
}
.no-margin {
margin: 0;
}
.no-top-space {
margin-top: 0 !important;
padding-top: 0 !important;
}
.no-bottom-space {
margin-bottom: 0 !important;
padding-bottom: 0 !important;
}
.no-margin-bottom {
margin-bottom: 0 !important;
}
.no-padding-bottom {
padding-bottom: 0 !important;
}
.content-xs {
padding-top: 20px;
padding-bottom: 20px;
}
.content {
padding-top: 40px;
padding-bottom: 40px;
}
.content-sm {
padding-top: 60px;
padding-bottom: 60px;
}
.content-md {
padding-top: 80px;
padding-bottom: 80px;
}
.content-lg {
padding-top: 100px;
padding-bottom: 100px;
}
.space-lg-hor {
padding-left: 60px;
padding-right: 60px;
}
.space-xlg-hor {
padding-left: 100px;
padding-right: 100px;
}
.margin-bottom-5,
.margin-bottom-10,
.margin-bottom-15,
.margin-bottom-20,
.margin-bottom-25,
.margin-bottom-30,
.margin-bottom-35,
.margin-bottom-40,
.margin-bottom-45,
.margin-bottom-50,
.margin-bottom-55,
.margin-bottom-60 {
clear:both;
}
.margin-bottom-5 { margin-bottom:5px;}
.margin-bottom-10 { margin-bottom:10px;}
.margin-bottom-15 { margin-bottom:15px;}
.margin-bottom-20 { margin-bottom:20px;}
.margin-bottom-25 { margin-bottom:25px;}
.margin-bottom-30 { margin-bottom:30px;}
.margin-bottom-35 { margin-bottom:35px;}
.margin-bottom-40 { margin-bottom:40px;}
.margin-bottom-45 { margin-bottom:45px;}
.margin-bottom-50 { margin-bottom:50px;}
.margin-bottom-55 { margin-bottom:55px;}
.margin-bottom-60 { margin-bottom:60px;}
.margin-bottom-80 { margin-bottom:80px;}
.margin-bottom-100 { margin-bottom:100px;}
@media (max-width: 768px) {
.sm-margin-bottom-10 {
margin-bottom: 10px;
}
.sm-margin-bottom-20 {
margin-bottom: 20px;
}
.sm-margin-bottom-30 {
margin-bottom: 30px;
}
.sm-margin-bottom-40 {
margin-bottom: 40px;
}
.sm-margin-bottom-50 {
margin-bottom: 50px;
}
.sm-margin-bottom-60 {
margin-bottom: 60px;
}
}
@media (max-width: 992px) {
.md-margin-bottom-10 {
margin-bottom: 10px;
}
.md-margin-bottom-20 {
margin-bottom: 20px;
}
.md-margin-bottom-30 {
margin-bottom: 30px;
}
.md-margin-bottom-40 {
margin-bottom: 40px;
}
.md-margin-bottom-50 {
margin-bottom: 50px;
}
.md-margin-bottom-60 {
margin-bottom: 60px;
}
}
/*Other Spaces*/
.margin-top-20 { margin-top: 20px;}
.margin-left-5 { margin-left: 5px;}
.margin-left-10 { margin-left: 10px;}
.margin-right-5 { margin-right: 5px;}
.margin-right-10 { margin-right: 10px;}
.padding-top-5 { padding-top: 5px;}
.padding-top-10 { padding-top: 10px;}
.padding-top-20 { padding-top: 20px;}
.padding-top-50 { padding-top: 50px;}
.padding-top-70 { padding-top: 70px;}
.padding-top-100 { padding-top: 100px;}
.padding-left-5 { padding-left: 5px;}
.padding-bottom-5 { padding-bottom: 5px;}
.padding-bottom-10 { padding-bottom: 10px;}
.padding-bottom-20 { padding-bottom: 20px;}
.padding-bottom-30 { padding-bottom: 30px;}
.padding-bottom-50 { padding-bottom: 50px;}
.padding-bottom-70 { padding-bottom: 70px;}
.padding-bottom-100 { padding-bottom: 100px;}
/*Text Colors
------------------------------------*/
.color-sea { color: #1abc9c;}
.color-red { color: #e74c3c;}
.color-aqua { color: #27d7e7;}
.color-blue { color: #3498db;}
.color-grey { color: #95a5a6;}
.color-dark { color: #555555;}
.color-green { color: #72c02c;}
.color-brown { color: #9c8061;}
.color-light { color: #ffffff;}
.color-orange { color: #e67e22;}
.color-yellow { color: #f1c40f;}
.color-green1 { color: #2ecc71;}
.color-purple { color: #9b6bcc;}
.color-inherit { color: inherit;}
.color-dark-blue { color: #4765a0;}
.color-light-grey { color: #585f69;}
.color-light-green { color: #79d5b3;}
/*Background Colors
------------------------------------*/
.bg-color-dark,
.bg-color-sea,
.bg-color-red,
.bg-color-aqua,
.bg-color-blue,
.bg-color-grey,
.bg-color-light,
.bg-color-green,
.bg-color-brown,
.bg-color-orange,
.bg-color-green1,
.bg-color-purple,
.bg-color-dark-blue,
.bg-color-light-grey,
.bg-color-light-green {
color: #fff;
}
.bg-color-white {
color: #555;
}
.bg-color-dark { background-color: #555 !important;}
.bg-color-white { background-color: #fff !important;}
.bg-color-sea { background-color: #1abc9c !important;}
.bg-color-red { background-color: #e74c3c !important;}
.bg-color-aqua { background-color: #27d7e7 !important;}
.bg-color-blue { background-color: #3498db !important;}
.bg-color-grey { background-color: #95a5a6 !important;}
.bg-color-light { background-color: #f7f7f7 !important;}
.bg-color-green { background-color: #72c02c !important;}
.bg-color-brown { background-color: #9c8061 !important;}
.bg-color-orange { background-color: #e67e22 !important;}
.bg-color-green1 { background-color: #2ecc71 !important;}
.bg-color-purple { background-color: #9b6bcc !important;}
.bg-color-dark-blue { background-color: #4765a0 !important;}
.bg-color-light-grey { background-color: #585f69 !important;}
.bg-color-light-green { background-color: #79d5b3 !important;}
.rgba-red { background-color: rgba(231,76,60,0.8);}
.rgba-blue{ background-color: rgba(52,152,219,0.8);}
.rgba-aqua { background-color: rgba(39,215,231,0.8);}
.rgba-yellow { background-color: rgba(241,196,15,0.8);}
.rgba-default { background-color: rgba(114,192,44,0.8);}
.rgba-purple { background-color: rgba(155,107,204,0.8);}
/*Grey Backroud*/
.bg-grey {
background: #f7f7f7;
border-top: solid 1px #eee;
border-bottom: solid 1px #eee;
}
.bg-grey2 {
background: #f4f6f6;
}
/*Rounded and Circle Classes
------------------------------------*/
.no-rounded { border-radius: 0 !important;}
.rounded { border-radius: 4px !important;}
.rounded-x { border-radius: 50% !important;}
.rounded-2x { border-radius: 10px !important;}
.rounded-3x { border-radius: 15px !important;}
.rounded-4x { border-radius: 20px !important;}
.rounded-sm { border-radius: 2px !important;}
.rounded-md { border-radius: 3px !important;}
.rounded-top { border-radius: 4px 4px 0 0 !important;}
.rounded-left { border-radius: 4px 0 0 4px !important;}
.rounded-right { border-radius: 0 4px 4px 0 !important;}
.rounded-bottom { border-radius: 0 0 4px 4px !important;}
/*Others
------------------------------------*/
.overflow-h { overflow: hidden;}
.overflow-a { overflow: auto;}
.overflow-hidden { overflow: hidden;}
.clear-both { clear: both;}
/*Display*/
.dp-none { display: none;}
.dp-block { display: block;}
.dp-table { display: table;}
.dp-inline-block { display: inline-block;}
.dp-table-cell {
display: table-cell;
vertical-align: middle;
}
/*Full Width*/
.full-width {
width: 100%;
}
/*Equal Height Columns*/
@media (max-width: 767px) {
.equal-height-column {
height: auto !important;
}
}
/*Image Classes*/
.img-width-200 { width:200px;}
.lft-img-margin { margin:0 20px 5px 0;}
.rgt-img-margin { margin:0 0 5px 10px;}
img.img-center,
.img-center img {
margin-left: auto;
margin-right: auto;
}
/*Background Light*/
.bg-light {
padding: 10px 15px;
margin-bottom: 10px;
background: #fcfcfc;
border: solid 1px #e5e5e5;
}
.bg-light:hover {
border: solid 1px #bbb;
}
/*CSS3 Hover Effects*/
.hover-effect {
-webkit-transition: all 0.4s ease-in-out;
-moz-transition: all 0.4s ease-in-out;
-o-transition: all 0.4s ease-in-out;
transition: all 0.4s ease-in-out;
}
.hover-effect-kenburn {
left:10px;
margin-left:-10px;
position:relative;
-webkit-transition: all 0.8s ease-in-out;
-moz-transition: all 0.8s ease-in-out;
-o-transition: all 0.8s ease-in-out;
-ms-transition: all 0.8s ease-in-out;
transition: all 0.8s ease-in-out;
}
.hover-effect-kenburn:hover {
-webkit-transform: scale(2) rotate(5deg);
-moz-transform: scale(2) rotate(5deg);
-o-transform: scale(2) rotate(5deg);
-ms-transform: scale(2) rotate(5deg);
transform: scale(2) rotate(5deg);
} | Java |
cmd_drivers/base/dd.o := arm-eabi-gcc -Wp,-MD,drivers/base/.dd.o.d -nostdinc -isystem /home/tim/ICS/prebuilt/linux-x86/toolchain/arm-eabi-4.4.0/bin/../lib/gcc/arm-eabi/4.4.0/include -I/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include -Iinclude -include include/generated/autoconf.h -D__KERNEL__ -mlittle-endian -Iarch/arm/mach-tegra/include -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -fno-strict-aliasing -fno-common -Werror-implicit-function-declaration -Wno-format-security -fno-delete-null-pointer-checks -Os -marm -fno-dwarf2-cfi-asm -mabi=aapcs-linux -mno-thumb-interwork -funwind-tables -D__LINUX_ARM_ARCH__=7 -march=armv7-a -msoft-float -Uarm -Wframe-larger-than=1024 -fno-stack-protector -fomit-frame-pointer -g -Wdeclaration-after-statement -Wno-pointer-sign -fno-strict-overflow -fconserve-stack -D"KBUILD_STR(s)=\#s" -D"KBUILD_BASENAME=KBUILD_STR(dd)" -D"KBUILD_MODNAME=KBUILD_STR(dd)" -c -o drivers/base/dd.o drivers/base/dd.c
deps_drivers/base/dd.o := \
drivers/base/dd.c \
include/linux/device.h \
$(wildcard include/config/of.h) \
$(wildcard include/config/debug/devres.h) \
$(wildcard include/config/numa.h) \
$(wildcard include/config/devtmpfs.h) \
$(wildcard include/config/printk.h) \
$(wildcard include/config/dynamic/debug.h) \
include/linux/ioport.h \
include/linux/compiler.h \
$(wildcard include/config/trace/branch/profiling.h) \
$(wildcard include/config/profile/all/branches.h) \
$(wildcard include/config/enable/must/check.h) \
$(wildcard include/config/enable/warn/deprecated.h) \
include/linux/compiler-gcc.h \
$(wildcard include/config/arch/supports/optimized/inlining.h) \
$(wildcard include/config/optimize/inlining.h) \
include/linux/compiler-gcc4.h \
include/linux/types.h \
$(wildcard include/config/uid16.h) \
$(wildcard include/config/lbdaf.h) \
$(wildcard include/config/phys/addr/t/64bit.h) \
$(wildcard include/config/64bit.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/types.h \
include/asm-generic/int-ll64.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/bitsperlong.h \
include/asm-generic/bitsperlong.h \
include/linux/posix_types.h \
include/linux/stddef.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/posix_types.h \
include/linux/kobject.h \
$(wildcard include/config/hotplug.h) \
include/linux/list.h \
$(wildcard include/config/debug/list.h) \
include/linux/poison.h \
$(wildcard include/config/illegal/pointer/value.h) \
include/linux/prefetch.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/processor.h \
$(wildcard include/config/mmu.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/ptrace.h \
$(wildcard include/config/cpu/endian/be8.h) \
$(wildcard include/config/arm/thumb.h) \
$(wildcard include/config/smp.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/hwcap.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/cache.h \
$(wildcard include/config/arm/l1/cache/shift.h) \
$(wildcard include/config/aeabi.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/system.h \
$(wildcard include/config/cpu/xsc3.h) \
$(wildcard include/config/cpu/fa526.h) \
$(wildcard include/config/arch/has/barriers.h) \
$(wildcard include/config/arm/dma/mem/bufferable.h) \
$(wildcard include/config/cpu/sa1100.h) \
$(wildcard include/config/cpu/sa110.h) \
$(wildcard include/config/cpu/32v6k.h) \
include/linux/linkage.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/linkage.h \
include/linux/irqflags.h \
$(wildcard include/config/trace/irqflags.h) \
$(wildcard include/config/irqsoff/tracer.h) \
$(wildcard include/config/preempt/tracer.h) \
$(wildcard include/config/trace/irqflags/support.h) \
include/linux/typecheck.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/irqflags.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/outercache.h \
$(wildcard include/config/outer/cache/sync.h) \
$(wildcard include/config/outer/cache.h) \
arch/arm/mach-tegra/include/mach/barriers.h \
include/asm-generic/cmpxchg-local.h \
include/linux/sysfs.h \
$(wildcard include/config/debug/lock/alloc.h) \
$(wildcard include/config/sysfs.h) \
include/linux/errno.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/errno.h \
include/asm-generic/errno.h \
include/asm-generic/errno-base.h \
include/linux/lockdep.h \
$(wildcard include/config/lockdep.h) \
$(wildcard include/config/lock/stat.h) \
$(wildcard include/config/generic/hardirqs.h) \
$(wildcard include/config/prove/locking.h) \
$(wildcard include/config/prove/rcu.h) \
include/linux/kobject_ns.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/atomic.h \
$(wildcard include/config/generic/atomic64.h) \
include/asm-generic/atomic-long.h \
include/linux/spinlock.h \
$(wildcard include/config/debug/spinlock.h) \
$(wildcard include/config/generic/lockbreak.h) \
$(wildcard include/config/preempt.h) \
include/linux/preempt.h \
$(wildcard include/config/debug/preempt.h) \
$(wildcard include/config/preempt/notifiers.h) \
include/linux/thread_info.h \
$(wildcard include/config/compat.h) \
include/linux/bitops.h \
$(wildcard include/config/generic/find/first/bit.h) \
$(wildcard include/config/generic/find/last/bit.h) \
$(wildcard include/config/generic/find/next/bit.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/bitops.h \
include/asm-generic/bitops/non-atomic.h \
include/asm-generic/bitops/fls64.h \
include/asm-generic/bitops/sched.h \
include/asm-generic/bitops/hweight.h \
include/asm-generic/bitops/arch_hweight.h \
include/asm-generic/bitops/const_hweight.h \
include/asm-generic/bitops/lock.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/thread_info.h \
$(wildcard include/config/arm/thumbee.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/fpstate.h \
$(wildcard include/config/vfpv3.h) \
$(wildcard include/config/iwmmxt.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/domain.h \
$(wildcard include/config/io/36.h) \
include/linux/kernel.h \
$(wildcard include/config/preempt/voluntary.h) \
$(wildcard include/config/debug/spinlock/sleep.h) \
$(wildcard include/config/ring/buffer.h) \
$(wildcard include/config/tracing.h) \
$(wildcard include/config/ftrace/mcount/record.h) \
/home/tim/ICS/prebuilt/linux-x86/toolchain/arm-eabi-4.4.0/bin/../lib/gcc/arm-eabi/4.4.0/include/stdarg.h \
include/linux/log2.h \
$(wildcard include/config/arch/has/ilog2/u32.h) \
$(wildcard include/config/arch/has/ilog2/u64.h) \
include/linux/dynamic_debug.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/byteorder.h \
include/linux/byteorder/little_endian.h \
include/linux/swab.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/swab.h \
include/linux/byteorder/generic.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/bug.h \
$(wildcard include/config/bug.h) \
$(wildcard include/config/debug/bugverbose.h) \
include/asm-generic/bug.h \
$(wildcard include/config/generic/bug.h) \
$(wildcard include/config/generic/bug/relative/pointers.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/div64.h \
include/linux/stringify.h \
include/linux/bottom_half.h \
include/linux/spinlock_types.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/spinlock_types.h \
include/linux/rwlock_types.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/spinlock.h \
include/linux/rwlock.h \
include/linux/spinlock_api_smp.h \
$(wildcard include/config/inline/spin/lock.h) \
$(wildcard include/config/inline/spin/lock/bh.h) \
$(wildcard include/config/inline/spin/lock/irq.h) \
$(wildcard include/config/inline/spin/lock/irqsave.h) \
$(wildcard include/config/inline/spin/trylock.h) \
$(wildcard include/config/inline/spin/trylock/bh.h) \
$(wildcard include/config/inline/spin/unlock.h) \
$(wildcard include/config/inline/spin/unlock/bh.h) \
$(wildcard include/config/inline/spin/unlock/irq.h) \
$(wildcard include/config/inline/spin/unlock/irqrestore.h) \
include/linux/rwlock_api_smp.h \
$(wildcard include/config/inline/read/lock.h) \
$(wildcard include/config/inline/write/lock.h) \
$(wildcard include/config/inline/read/lock/bh.h) \
$(wildcard include/config/inline/write/lock/bh.h) \
$(wildcard include/config/inline/read/lock/irq.h) \
$(wildcard include/config/inline/write/lock/irq.h) \
$(wildcard include/config/inline/read/lock/irqsave.h) \
$(wildcard include/config/inline/write/lock/irqsave.h) \
$(wildcard include/config/inline/read/trylock.h) \
$(wildcard include/config/inline/write/trylock.h) \
$(wildcard include/config/inline/read/unlock.h) \
$(wildcard include/config/inline/write/unlock.h) \
$(wildcard include/config/inline/read/unlock/bh.h) \
$(wildcard include/config/inline/write/unlock/bh.h) \
$(wildcard include/config/inline/read/unlock/irq.h) \
$(wildcard include/config/inline/write/unlock/irq.h) \
$(wildcard include/config/inline/read/unlock/irqrestore.h) \
$(wildcard include/config/inline/write/unlock/irqrestore.h) \
include/linux/kref.h \
include/linux/wait.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/current.h \
include/linux/klist.h \
include/linux/module.h \
$(wildcard include/config/symbol/prefix.h) \
$(wildcard include/config/modules.h) \
$(wildcard include/config/modversions.h) \
$(wildcard include/config/unused/symbols.h) \
$(wildcard include/config/kallsyms.h) \
$(wildcard include/config/tracepoints.h) \
$(wildcard include/config/event/tracing.h) \
$(wildcard include/config/module/unload.h) \
$(wildcard include/config/constructors.h) \
include/linux/stat.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/stat.h \
include/linux/time.h \
$(wildcard include/config/arch/uses/gettimeoffset.h) \
include/linux/cache.h \
$(wildcard include/config/arch/has/cache/line/size.h) \
include/linux/seqlock.h \
include/linux/math64.h \
include/linux/kmod.h \
include/linux/gfp.h \
$(wildcard include/config/kmemcheck.h) \
$(wildcard include/config/highmem.h) \
$(wildcard include/config/zone/dma.h) \
$(wildcard include/config/zone/dma32.h) \
$(wildcard include/config/debug/vm.h) \
include/linux/mmzone.h \
$(wildcard include/config/force/max/zoneorder.h) \
$(wildcard include/config/memory/hotplug.h) \
$(wildcard include/config/sparsemem.h) \
$(wildcard include/config/compaction.h) \
$(wildcard include/config/arch/populates/node/map.h) \
$(wildcard include/config/discontigmem.h) \
$(wildcard include/config/flat/node/mem/map.h) \
$(wildcard include/config/cgroup/mem/res/ctlr.h) \
$(wildcard include/config/no/bootmem.h) \
$(wildcard include/config/have/memory/present.h) \
$(wildcard include/config/have/memoryless/nodes.h) \
$(wildcard include/config/need/node/memmap/size.h) \
$(wildcard include/config/need/multiple/nodes.h) \
$(wildcard include/config/have/arch/early/pfn/to/nid.h) \
$(wildcard include/config/flatmem.h) \
$(wildcard include/config/sparsemem/extreme.h) \
$(wildcard include/config/nodes/span/other/nodes.h) \
$(wildcard include/config/holes/in/zone.h) \
$(wildcard include/config/arch/has/holes/memorymodel.h) \
include/linux/threads.h \
$(wildcard include/config/nr/cpus.h) \
$(wildcard include/config/base/small.h) \
include/linux/numa.h \
$(wildcard include/config/nodes/shift.h) \
include/linux/init.h \
include/linux/nodemask.h \
include/linux/bitmap.h \
include/linux/string.h \
$(wildcard include/config/binary/printf.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/string.h \
include/linux/pageblock-flags.h \
$(wildcard include/config/hugetlb/page.h) \
$(wildcard include/config/hugetlb/page/size/variable.h) \
include/generated/bounds.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/page.h \
$(wildcard include/config/cpu/copy/v3.h) \
$(wildcard include/config/cpu/copy/v4wt.h) \
$(wildcard include/config/cpu/copy/v4wb.h) \
$(wildcard include/config/cpu/copy/feroceon.h) \
$(wildcard include/config/cpu/copy/fa.h) \
$(wildcard include/config/cpu/xscale.h) \
$(wildcard include/config/cpu/copy/v6.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/glue.h \
$(wildcard include/config/cpu/arm610.h) \
$(wildcard include/config/cpu/arm710.h) \
$(wildcard include/config/cpu/abrt/lv4t.h) \
$(wildcard include/config/cpu/abrt/ev4.h) \
$(wildcard include/config/cpu/abrt/ev4t.h) \
$(wildcard include/config/cpu/abrt/ev5tj.h) \
$(wildcard include/config/cpu/abrt/ev5t.h) \
$(wildcard include/config/cpu/abrt/ev6.h) \
$(wildcard include/config/cpu/abrt/ev7.h) \
$(wildcard include/config/cpu/pabrt/legacy.h) \
$(wildcard include/config/cpu/pabrt/v6.h) \
$(wildcard include/config/cpu/pabrt/v7.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/memory.h \
$(wildcard include/config/page/offset.h) \
$(wildcard include/config/thumb2/kernel.h) \
$(wildcard include/config/dram/size.h) \
$(wildcard include/config/dram/base.h) \
$(wildcard include/config/have/tcm.h) \
include/linux/const.h \
arch/arm/mach-tegra/include/mach/memory.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/sizes.h \
include/asm-generic/memory_model.h \
$(wildcard include/config/sparsemem/vmemmap.h) \
include/asm-generic/getorder.h \
include/linux/memory_hotplug.h \
$(wildcard include/config/have/arch/nodedata/extension.h) \
$(wildcard include/config/memory/hotremove.h) \
include/linux/notifier.h \
include/linux/mutex.h \
$(wildcard include/config/debug/mutexes.h) \
include/linux/rwsem.h \
$(wildcard include/config/rwsem/generic/spinlock.h) \
include/linux/rwsem-spinlock.h \
include/linux/srcu.h \
include/linux/topology.h \
$(wildcard include/config/sched/smt.h) \
$(wildcard include/config/sched/mc.h) \
$(wildcard include/config/use/percpu/numa/node/id.h) \
include/linux/cpumask.h \
$(wildcard include/config/cpumask/offstack.h) \
$(wildcard include/config/hotplug/cpu.h) \
$(wildcard include/config/debug/per/cpu/maps.h) \
$(wildcard include/config/disable/obsolete/cpumask/functions.h) \
include/linux/smp.h \
$(wildcard include/config/use/generic/smp/helpers.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/smp.h \
arch/arm/mach-tegra/include/mach/smp.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/hardware/gic.h \
include/linux/percpu.h \
$(wildcard include/config/need/per/cpu/embed/first/chunk.h) \
$(wildcard include/config/need/per/cpu/page/first/chunk.h) \
$(wildcard include/config/have/setup/per/cpu/area.h) \
include/linux/pfn.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/percpu.h \
include/asm-generic/percpu.h \
include/linux/percpu-defs.h \
$(wildcard include/config/debug/force/weak/per/cpu.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/topology.h \
include/asm-generic/topology.h \
include/linux/mmdebug.h \
$(wildcard include/config/debug/virtual.h) \
include/linux/workqueue.h \
$(wildcard include/config/debug/objects/work.h) \
$(wildcard include/config/freezer.h) \
include/linux/timer.h \
$(wildcard include/config/timer/stats.h) \
$(wildcard include/config/debug/objects/timers.h) \
include/linux/ktime.h \
$(wildcard include/config/ktime/scalar.h) \
include/linux/jiffies.h \
include/linux/timex.h \
include/linux/param.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/param.h \
$(wildcard include/config/hz.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/timex.h \
arch/arm/mach-tegra/include/mach/timex.h \
include/linux/debugobjects.h \
$(wildcard include/config/debug/objects.h) \
$(wildcard include/config/debug/objects/free.h) \
include/linux/elf.h \
include/linux/elf-em.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/elf.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/user.h \
include/linux/moduleparam.h \
$(wildcard include/config/alpha.h) \
$(wildcard include/config/ia64.h) \
$(wildcard include/config/ppc64.h) \
include/linux/tracepoint.h \
include/linux/rcupdate.h \
$(wildcard include/config/rcu/torture/test.h) \
$(wildcard include/config/tree/rcu.h) \
$(wildcard include/config/tree/preempt/rcu.h) \
$(wildcard include/config/tiny/rcu.h) \
$(wildcard include/config/debug/objects/rcu/head.h) \
include/linux/completion.h \
include/linux/rcutree.h \
$(wildcard include/config/no/hz.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/module.h \
$(wildcard include/config/arm/unwind.h) \
include/trace/events/module.h \
include/trace/define_trace.h \
include/linux/pm.h \
$(wildcard include/config/pm/sleep.h) \
$(wildcard include/config/pm/runtime.h) \
$(wildcard include/config/pm/ops.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/device.h \
$(wildcard include/config/dmabounce.h) \
include/linux/pm_wakeup.h \
$(wildcard include/config/pm.h) \
include/linux/delay.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/delay.h \
$(wildcard include/config/arch/provides/udelay.h) \
arch/arm/mach-tegra/include/mach/delay.h \
include/linux/kthread.h \
include/linux/err.h \
include/linux/sched.h \
$(wildcard include/config/sched/debug.h) \
$(wildcard include/config/lockup/detector.h) \
$(wildcard include/config/detect/hung/task.h) \
$(wildcard include/config/core/dump/default/elf/headers.h) \
$(wildcard include/config/virt/cpu/accounting.h) \
$(wildcard include/config/bsd/process/acct.h) \
$(wildcard include/config/taskstats.h) \
$(wildcard include/config/audit.h) \
$(wildcard include/config/inotify/user.h) \
$(wildcard include/config/epoll.h) \
$(wildcard include/config/posix/mqueue.h) \
$(wildcard include/config/keys.h) \
$(wildcard include/config/perf/events.h) \
$(wildcard include/config/schedstats.h) \
$(wildcard include/config/task/delay/acct.h) \
$(wildcard include/config/fair/group/sched.h) \
$(wildcard include/config/rt/group/sched.h) \
$(wildcard include/config/blk/dev/io/trace.h) \
$(wildcard include/config/cc/stackprotector.h) \
$(wildcard include/config/sysvipc.h) \
$(wildcard include/config/auditsyscall.h) \
$(wildcard include/config/rt/mutexes.h) \
$(wildcard include/config/task/xacct.h) \
$(wildcard include/config/cpusets.h) \
$(wildcard include/config/cgroups.h) \
$(wildcard include/config/futex.h) \
$(wildcard include/config/fault/injection.h) \
$(wildcard include/config/latencytop.h) \
$(wildcard include/config/function/graph/tracer.h) \
$(wildcard include/config/security/sealimemodule.h) \
$(wildcard include/config/have/unstable/sched/clock.h) \
$(wildcard include/config/stack/growsup.h) \
$(wildcard include/config/debug/stack/usage.h) \
$(wildcard include/config/cgroup/sched.h) \
$(wildcard include/config/mm/owner.h) \
include/linux/capability.h \
include/linux/rbtree.h \
include/linux/mm_types.h \
$(wildcard include/config/split/ptlock/cpus.h) \
$(wildcard include/config/want/page/debug/flags.h) \
$(wildcard include/config/aio.h) \
$(wildcard include/config/proc/fs.h) \
$(wildcard include/config/mmu/notifier.h) \
include/linux/auxvec.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/auxvec.h \
include/linux/prio_tree.h \
include/linux/page-debug-flags.h \
$(wildcard include/config/page/poisoning.h) \
$(wildcard include/config/page/debug/something/else.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/mmu.h \
$(wildcard include/config/cpu/has/asid.h) \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/cputime.h \
include/asm-generic/cputime.h \
include/linux/sem.h \
include/linux/ipc.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/ipcbuf.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/sembuf.h \
include/linux/signal.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/signal.h \
include/asm-generic/signal-defs.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/sigcontext.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/siginfo.h \
include/asm-generic/siginfo.h \
include/linux/path.h \
include/linux/pid.h \
include/linux/proportions.h \
include/linux/percpu_counter.h \
include/linux/seccomp.h \
$(wildcard include/config/seccomp.h) \
include/linux/rculist.h \
include/linux/rtmutex.h \
$(wildcard include/config/debug/rt/mutexes.h) \
include/linux/plist.h \
$(wildcard include/config/debug/pi/list.h) \
include/linux/resource.h \
/home/tim/Downloads/mitchtaydev-Thrive-Shiva-Kernel-ee65d90/linux-2.6/arch/arm/include/asm/resource.h \
include/asm-generic/resource.h \
include/linux/hrtimer.h \
$(wildcard include/config/high/res/timers.h) \
include/linux/task_io_accounting.h \
$(wildcard include/config/task/io/accounting.h) \
include/linux/latencytop.h \
include/linux/cred.h \
$(wildcard include/config/debug/credentials.h) \
$(wildcard include/config/security.h) \
include/linux/key.h \
$(wildcard include/config/sysctl.h) \
include/linux/sysctl.h \
include/linux/selinux.h \
$(wildcard include/config/security/selinux.h) \
include/linux/aio.h \
include/linux/aio_abi.h \
include/linux/uio.h \
include/linux/async.h \
include/linux/pm_runtime.h \
drivers/base/base.h \
$(wildcard include/config/sys/hypervisor.h) \
drivers/base/power/power.h \
drivers/base/dd.o: $(deps_drivers/base/dd.o)
$(deps_drivers/base/dd.o):
| Java |
package openra.server;
import openra.core.Unit;
public class UnitAnimEvent extends ActionEvent
{
private Unit un;
private UnitAnimEvent scheduled;
public UnitAnimEvent(int p, Unit un) {
super(p);
//logger->debug("UAE cons: this:%p un:%p\n",this,un);
this.un = un;
//un.referTo();
scheduled = null;
}
void destUnitAnimEvent()
{
//logger->debug("UAE dest: this:%p un:%p sch:%p\n",this,un,scheduled);
if (scheduled != null) {
this.getAequeue().scheduleEvent(scheduled);
}
//un->unrefer();
}
protected void setSchedule(UnitAnimEvent e)
{
//logger->debug("Scheduling an event. (this: %p, e: %p)\n",this,e);
if (scheduled != null) {
scheduled.setSchedule(null);
scheduled.stop();
}
scheduled = e;
}
void stopScheduled()
{
if (scheduled != null) {
scheduled.stop();
}
}
void update()
{
}
}
| Java |
# snake
mini snake en SDL
Le but de ce repo est de proposer un algorithme simple pour comprendre une manière de faire un snake, l'utilisation de la librairie graphique SDL n'étant là que pour la mise en place du cadre du jeu.
Ce tutoriel se veut se concentrer en particulier sur comment faire facilement bouger le ver, de manière rapide et efficace, sans que cela ne devienne trop compliqué ou lent lorsque le ver devient plus grand.
| Java |
/**
* Copyright (C) 2013, Moss Computing Inc.
*
* This file is part of simpledeb.
*
* simpledeb 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.
*
* simpledeb 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 simpledeb; see the file COPYING. If not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under
* terms of your choice, provided that you also meet, for each linked
* independent module, the terms and conditions of the license of that
* module. An independent module is a module which is not derived from
* or based on this library. If you modify this library, you may extend
* this exception to your version of the library, but you are not
* obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
package com.moss.simpledeb.core.action;
import java.io.File;
import java.util.LinkedList;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import com.moss.simpledeb.core.DebComponent;
import com.moss.simpledeb.core.DebState;
import com.moss.simpledeb.core.path.ArchivePath;
import com.moss.simpledeb.core.path.BytesArchivePath;
import com.moss.simpledeb.core.path.DirArchivePath;
@XmlAccessorType(XmlAccessType.FIELD)
public final class LaunchScriptAction extends DebAction {
@XmlAttribute(name="class-name")
private String className;
@XmlAttribute(name="target-file")
private String targetFile;
@XmlAttribute(name="path-level")
private int pathLevel;
@Override
public void run(DebState state) throws Exception {
{
File target = new File(targetFile).getParentFile();
LinkedList<File> pathsNeeded = new LinkedList<File>();
File f = target;
while (f != null) {
pathsNeeded.addFirst(f);
f = f.getParentFile();
}
for (int i=0; i<pathLevel; i++) {
pathsNeeded.removeFirst();
}
for (File e : pathsNeeded) {
String p = "./" + e.getPath();
if (!p.endsWith("/")) {
p = p + "/";
}
TarArchiveEntry tarEntry = new TarArchiveEntry(p);
tarEntry.setGroupId(0);
tarEntry.setGroupName("root");
tarEntry.setIds(0, 0);
tarEntry.setModTime(System.currentTimeMillis());
tarEntry.setSize(0);
tarEntry.setUserId(0);
tarEntry.setUserName("root");
tarEntry.setMode(Integer.parseInt("755", 8));
ArchivePath path = new DirArchivePath(tarEntry);
state.addPath(DebComponent.CONTENT, path);
}
}
String cp;
{
StringBuffer sb = new StringBuffer();
for (String path : state.classpath) {
if (sb.length() == 0) {
sb.append(path);
}
else {
sb.append(":");
sb.append(path);
}
}
cp = sb.toString();
}
StringBuilder sb = new StringBuilder();
sb.append("#!/bin/bash\n");
sb.append("CP=\"");
sb.append(cp);
sb.append("\"\n");
sb.append("/usr/bin/java -cp $CP ");
sb.append(className);
sb.append(" $@\n");
byte[] data = sb.toString().getBytes();
String entryName = "./" + targetFile;
TarArchiveEntry tarEntry = new TarArchiveEntry(entryName);
tarEntry.setGroupId(0);
tarEntry.setGroupName("root");
tarEntry.setIds(0, 0);
tarEntry.setModTime(System.currentTimeMillis());
tarEntry.setSize(data.length);
tarEntry.setUserId(0);
tarEntry.setUserName("root");
tarEntry.setMode(Integer.parseInt("755", 8));
ArchivePath path = new BytesArchivePath(tarEntry, data);
state.addPath(DebComponent.CONTENT, path);
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getTargetFile() {
return targetFile;
}
public void setTargetFile(String targetFile) {
this.targetFile = targetFile;
}
public int getPathLevel() {
return pathLevel;
}
public void setPathLevel(int assumedTargetPathLevel) {
this.pathLevel = assumedTargetPathLevel;
}
}
| Java |
/*µü´úÆ÷ģʽ
*
* ±éÀú¼¯ºÏµÄÖ°Ôð·ÖÀë³öÀ´£»
*/
/**°×Ïä¾ÛºÏ+Íâµü´ú×Ó*/
public interface Iterator
{
public Object first();
public Object next();
//µÃµ½µ±Ç°¶ÔÏó
public Object currentItem();
//ÊÇ·ñµ½Á˽áβ
public boolean isDone();
}
//ÕýÐòµü´úÆ÷
public class ConcreteIterator implements Iterator
{
private int currentIndex = 0;
//¶¨ÒåÒ»¸ö¾ßÌ弯ºÏ¶ÔÏó
private Aggregate aggregate = null;
public ConcreteIterator(Aggregate aggregate)
{
this.aggregate = aggregate;
}
//ÖØÐ´¸¸Àà·½·¨
@Override
public Object first()
{
currentIndex = 0;
return vector.get(currentIndex);
}
@Override
public Object next()
{
if(currentIndex < aggregate.count())
currentIndex++;
return vector.get(currentIndex);
}
@Override
public Object currentItem()
{
return aggregate.getAt(currentIndex);
}
@Override
public boolean isDone()
{
return (currentIndex >= aggregate.count());
}
}
/*¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª*/
//°×Ïä¾ÛºÏÒªÇ󼯺ÏÀàÏòÍâ½çÌṩ·ÃÎÊ×Ô¼ºÄÚ²¿ÔªËصĽӿÚ
public interface Aggregat
{
public Iterator createIterator();
//»ñÈ¡¼¯ºÏÄÚ²¿ÔªËØ×ÜÊý
public int count();
//»ñȡָ¶¨Î»ÖÃÔªËØ
public Object getAt(int index);
}
/*¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª*/
//¾ßÌåµÄ¼¯ºÏÀà
public class ConcreteAggregat implements Aggregat
{
private Vector vector = null;
public Vector getVector()
{
return vector;
}
public void setVector(final Vector vector)
{
this.vector = vector;
}
public ConcreteAggregat()
{
vector = new Vector();
vector.add("item 1");
vector.add("item 2");
}
//»ñÈ¡¼¯ºÏÄÚ²¿ÔªËØ×ÜÊý
@Override
public int count()
{
return vector.size();
}
//»ñȡָ¶¨Î»ÖÃÔªËØ
@Override
public Object getAt(int index)
{
if(0 <= index && index < vector.size())
return vector[index];
else
return null;
}
//´´½¨Ò»¸ö¾ßÌåµü´úÆ÷¶ÔÏ󣬲¢°Ñ¸Ã¼¯ºÏ¶ÔÏó×ÔÉí½»¸ø¸Ãµü´úÆ÷
@Override
public Iterator createIterator()
{
//ÕâÀï¿ÉÒÔʹÓüòµ¥¹¤³§Ä£Ê½
return new ConcreteIterator(this);
}
}
/*¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª¡ª*/
public class Client
{
public static void main(final String[] args)
{
Aggregat agg = new ConcreteAggregat();
final Iterator iterator = agg.createIterator();
System.out.println(iterator.first());
while (!iterator.isDone())
{
//Item item = (Item)iterator.currentItem();
System.out.println(iterator.next());
}
}
}
| Java |
/*
* This file is part of the coreboot project.
*
* Copyright (C) 2007-2008 coresystems GmbH
* 2012 secunet Security Networks AG
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef NORTHBRIDGE_INTEL_I965_CHIP_H
#define NORTHBRIDGE_INTEL_I965_CHIP_H
struct northbridge_intel_i965_config {
int gpu_use_spread_spectrum_clock;
int gpu_lvds_dual_channel;
int gpu_link_frequency_270_mhz;
int gpu_lvds_num_lanes;
};
#endif /* NORTHBRIDGE_INTEL_I965_CHIP_H */
| Java |
/* $Id$ */
/** @file
* VMM - Raw-mode Context.
*/
/*
* Copyright (C) 2006-2012 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#define LOG_GROUP LOG_GROUP_VMM
#include <iprt/asm-amd64-x86.h> /* for SUPGetCpuHzFromGIP */
#include <VBox/vmm/vmm.h>
#include <VBox/vmm/trpm.h>
#include <VBox/vmm/pgm.h>
#include "VMMInternal.h"
#include <VBox/vmm/vm.h>
#include <VBox/sup.h>
#include <VBox/err.h>
#include <VBox/log.h>
#include <iprt/assert.h>
#include <iprt/initterm.h>
/*******************************************************************************
* Global Variables *
*******************************************************************************/
/** Default logger instance. */
extern "C" DECLIMPORT(RTLOGGERRC) g_Logger;
extern "C" DECLIMPORT(RTLOGGERRC) g_RelLogger;
/*******************************************************************************
* Internal Functions *
*******************************************************************************/
static int vmmGCTest(PVM pVM, unsigned uOperation, unsigned uArg);
static DECLCALLBACK(int) vmmGCTestTmpPFHandler(PVM pVM, PCPUMCTXCORE pRegFrame);
static DECLCALLBACK(int) vmmGCTestTmpPFHandlerCorruptFS(PVM pVM, PCPUMCTXCORE pRegFrame);
/**
* The GC entry point.
*
* @returns VBox status code.
* @param pVM Pointer to the VM.
* @param uOperation Which operation to execute (VMMGCOPERATION).
* @param uArg Argument to that operation.
*/
VMMRCDECL(int) VMMGCEntry(PVM pVM, unsigned uOperation, unsigned uArg, ...)
{
/* todo */
switch (uOperation)
{
/*
* Init RC modules.
*/
case VMMGC_DO_VMMGC_INIT:
{
/*
* Validate the svn revision (uArg) and build type (ellipsis).
*/
if (uArg != VMMGetSvnRev())
return VERR_VMM_RC_VERSION_MISMATCH;
va_list va;
va_start(va, uArg);
uint32_t uBuildType = va_arg(va, uint32_t);
if (uBuildType != vmmGetBuildType())
return VERR_VMM_RC_VERSION_MISMATCH;
/*
* Initialize the runtime.
*/
uint64_t u64TS = va_arg(va, uint64_t);
va_end(va);
int rc = RTRCInit(u64TS);
Log(("VMMGCEntry: VMMGC_DO_VMMGC_INIT - uArg=%u (svn revision) u64TS=%RX64; rc=%Rrc\n", uArg, u64TS, rc));
AssertRCReturn(rc, rc);
rc = PGMRegisterStringFormatTypes();
AssertRCReturn(rc, rc);
rc = PGMRCDynMapInit(pVM);
AssertRCReturn(rc, rc);
return VINF_SUCCESS;
}
/*
* Testcase which is used to test interrupt forwarding.
* It spins for a while with interrupts enabled.
*/
case VMMGC_DO_TESTCASE_HYPER_INTERRUPT:
{
uint32_t volatile i = 0;
ASMIntEnable();
while (i < _2G32)
i++;
ASMIntDisable();
return 0;
}
/*
* Testcase which simply returns, this is used for
* profiling of the switcher.
*/
case VMMGC_DO_TESTCASE_NOP:
return 0;
/*
* Testcase executes a privileged instruction to force a world switch. (in both SVM & VMX)
*/
case VMMGC_DO_TESTCASE_HM_NOP:
ASMRdMsr_Low(MSR_IA32_SYSENTER_CS);
return 0;
/*
* Delay for ~100us.
*/
case VMMGC_DO_TESTCASE_INTERRUPT_MASKING:
{
uint64_t u64MaxTicks = (SUPGetCpuHzFromGIP(g_pSUPGlobalInfoPage) != ~(uint64_t)0
? SUPGetCpuHzFromGIP(g_pSUPGlobalInfoPage)
: _2G)
/ 10000;
uint64_t u64StartTSC = ASMReadTSC();
uint64_t u64TicksNow;
uint32_t volatile i = 0;
do
{
/* waste some time and protect against getting stuck. */
for (uint32_t volatile j = 0; j < 1000; j++, i++)
if (i > _2G32)
return VERR_GENERAL_FAILURE;
/* check if we're done.*/
u64TicksNow = ASMReadTSC() - u64StartTSC;
} while (u64TicksNow < u64MaxTicks);
return VINF_SUCCESS;
}
/*
* Trap testcases and unknown operations.
*/
default:
if ( uOperation >= VMMGC_DO_TESTCASE_TRAP_FIRST
&& uOperation < VMMGC_DO_TESTCASE_TRAP_LAST)
return vmmGCTest(pVM, uOperation, uArg);
return VERR_INVALID_PARAMETER;
}
}
/**
* Internal RC logger worker: Flush logger.
*
* @returns VINF_SUCCESS.
* @param pLogger The logger instance to flush.
* @remark This function must be exported!
*/
VMMRCDECL(int) vmmGCLoggerFlush(PRTLOGGERRC pLogger)
{
PVM pVM = &g_VM;
NOREF(pLogger);
if (pVM->vmm.s.fRCLoggerFlushingDisabled)
return VINF_SUCCESS; /* fail quietly. */
return VMMRZCallRing3NoCpu(pVM, VMMCALLRING3_VMM_LOGGER_FLUSH, 0);
}
/**
* Flush logger if almost full.
*
* @param pVM Pointer to the VM.
*/
VMMRCDECL(void) VMMGCLogFlushIfFull(PVM pVM)
{
if ( pVM->vmm.s.pRCLoggerRC
&& pVM->vmm.s.pRCLoggerRC->offScratch >= (sizeof(pVM->vmm.s.pRCLoggerRC->achScratch)*3/4))
{
if (pVM->vmm.s.fRCLoggerFlushingDisabled)
return; /* fail quietly. */
VMMRZCallRing3NoCpu(pVM, VMMCALLRING3_VMM_LOGGER_FLUSH, 0);
}
}
/**
* Switches from guest context to host context.
*
* @param pVM Pointer to the VM.
* @param rc The status code.
*/
VMMRCDECL(void) VMMGCGuestToHost(PVM pVM, int rc)
{
pVM->vmm.s.pfnRCToHost(rc);
}
/**
* Calls the ring-0 host code.
*
* @param pVM Pointer to the VM.
*/
DECLASM(void) vmmRCProbeFireHelper(PVM pVM)
{
pVM->vmm.s.pfnRCToHost(VINF_VMM_CALL_TRACER);
}
/**
* Execute the trap testcase.
*
* There is some common code here, that's why we're collecting them
* like this. Odd numbered variation (uArg) are executed with write
* protection (WP) enabled.
*
* @returns VINF_SUCCESS if it was a testcase setup up to continue and did so successfully.
* @returns VERR_NOT_IMPLEMENTED if the testcase wasn't implemented.
* @returns VERR_GENERAL_FAILURE if the testcase continued when it shouldn't.
*
* @param pVM Pointer to the VM.
* @param uOperation The testcase.
* @param uArg The variation. See function description for odd / even details.
*
* @remark Careful with the trap 08 testcase and WP, it will triple
* fault the box if the TSS, the Trap8 TSS and the fault TSS
* GDTE are in pages which are read-only.
* See bottom of SELMR3Init().
*/
static int vmmGCTest(PVM pVM, unsigned uOperation, unsigned uArg)
{
/*
* Set up the testcase.
*/
#if 0
switch (uOperation)
{
default:
break;
}
#endif
/*
* Enable WP if odd variation.
*/
if (uArg & 1)
vmmGCEnableWP();
/*
* Execute the testcase.
*/
int rc = VERR_NOT_IMPLEMENTED;
switch (uOperation)
{
//case VMMGC_DO_TESTCASE_TRAP_0:
//case VMMGC_DO_TESTCASE_TRAP_1:
//case VMMGC_DO_TESTCASE_TRAP_2:
case VMMGC_DO_TESTCASE_TRAP_3:
{
if (uArg <= 1)
rc = vmmGCTestTrap3();
break;
}
//case VMMGC_DO_TESTCASE_TRAP_4:
//case VMMGC_DO_TESTCASE_TRAP_5:
//case VMMGC_DO_TESTCASE_TRAP_6:
//case VMMGC_DO_TESTCASE_TRAP_7:
case VMMGC_DO_TESTCASE_TRAP_8:
{
#ifndef DEBUG_bird /** @todo dynamic check that this won't triple fault... */
if (uArg & 1)
break;
#endif
if (uArg <= 1)
rc = vmmGCTestTrap8();
break;
}
//VMMGC_DO_TESTCASE_TRAP_9,
//VMMGC_DO_TESTCASE_TRAP_0A,
//VMMGC_DO_TESTCASE_TRAP_0B,
//VMMGC_DO_TESTCASE_TRAP_0C,
case VMMGC_DO_TESTCASE_TRAP_0D:
{
if (uArg <= 1)
rc = vmmGCTestTrap0d();
break;
}
case VMMGC_DO_TESTCASE_TRAP_0E:
{
if (uArg <= 1)
rc = vmmGCTestTrap0e();
else if (uArg == 2 || uArg == 4)
{
/*
* Test the use of a temporary #PF handler.
*/
rc = TRPMGCSetTempHandler(pVM, X86_XCPT_PF, uArg != 4 ? vmmGCTestTmpPFHandler : vmmGCTestTmpPFHandlerCorruptFS);
if (RT_SUCCESS(rc))
{
rc = vmmGCTestTrap0e();
/* in case it didn't fire. */
int rc2 = TRPMGCSetTempHandler(pVM, X86_XCPT_PF, NULL);
if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
rc = rc2;
}
}
break;
}
}
/*
* Re-enable WP.
*/
if (uArg & 1)
vmmGCDisableWP();
return rc;
}
/**
* Temporary \#PF trap handler for the \#PF test case.
*
* @returns VBox status code (appropriate for GC return).
* In this context RT_SUCCESS means to restart the instruction.
* @param pVM Pointer to the VM.
* @param pRegFrame Trap register frame.
*/
static DECLCALLBACK(int) vmmGCTestTmpPFHandler(PVM pVM, PCPUMCTXCORE pRegFrame)
{
if (pRegFrame->eip == (uintptr_t)vmmGCTestTrap0e_FaultEIP)
{
pRegFrame->eip = (uintptr_t)vmmGCTestTrap0e_ResumeEIP;
return VINF_SUCCESS;
}
NOREF(pVM);
return VERR_INTERNAL_ERROR;
}
/**
* Temporary \#PF trap handler for the \#PF test case, this one messes up the fs
* selector.
*
* @returns VBox status code (appropriate for GC return).
* In this context RT_SUCCESS means to restart the instruction.
* @param pVM Pointer to the VM.
* @param pRegFrame Trap register frame.
*/
static DECLCALLBACK(int) vmmGCTestTmpPFHandlerCorruptFS(PVM pVM, PCPUMCTXCORE pRegFrame)
{
int rc = vmmGCTestTmpPFHandler(pVM, pRegFrame);
pRegFrame->fs.Sel = 0x30;
return rc;
}
| Java |
package yuka.detectors;
import yuka.containers.News;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
/**
* Created by imyuka on 18/08/2016.
*/
public class FigureDetector {
private Map<String, Integer> cmap;
private Map<String, Integer> pmap;
private Map<String, Integer> dim;
//private int height = 0;
//private int height = 0;
public FigureDetector(Map<String, String> figure) {
String url = figure.get(News.IMAGE_URL);
dim = getDimension(url);
String caption = figure.get(News.IMAGE_CAPTION);
cmap = ClubDetector.count(caption);
PlayerDetector pd = new PlayerDetector(cmap.keySet());
pmap = pd.count(caption);
}
public int getHeight() {
return dim.get("height");
}
public int getWidth() {
return dim.get("width");
}
public double getPercentage (double totalHeight) {
return (double) getWidth() / HeightDetector.COLUMN_WIDTH
* (getHeight() / totalHeight);
}
public Map<String, Integer> getClubMap() {
return cmap;
}
public Map<String, Integer> getPlayerMap() {
return pmap;
}
public static Map<String, Integer> getDimension (String source) {
//int[] dim = new int[]{0,0};
Map<String, Integer> dim = new HashMap<>();
dim.put("width", 0);
dim.put("height", 0);
try {
URL url = new URL(source);
URLConnection conn = url.openConnection();
// now you get the content length
/////int contentLength = conn.getContentLength();
// you can check size here using contentLength
InputStream in = conn.getInputStream();
BufferedImage image = ImageIO.read(in);
// you can get size dimesion
//int width = image.getWidth();
//int height = image.getHeight();
dim.put("width", image.getWidth());
dim.put("height", image.getHeight());
} catch (IOException e) {
System.out.println();
}
return dim;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.