code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* * This 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. */ /* * ChartListener.java * Copyright (C) 2002 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.util.EventListener; /** * Interface to something that can process a ChartEvent * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision: 1.3 $ */ public interface ChartListener extends EventListener { void acceptDataPoint(ChartEvent e); }
williamClanton/jbossBA
weka/src/main/java/weka/gui/beans/ChartListener.java
Java
gpl-2.0
1,159
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "scumm/actor.h" #include "scumm/charset.h" #include "scumm/object.h" #include "scumm/resource.h" #include "scumm/scumm_v2.h" #include "scumm/sound.h" #include "scumm/util.h" #include "scumm/verbs.h" namespace Scumm { // Helper functions for ManiacMansion workarounds #define MM_SCRIPT(script) (script + (_game.version == 0 ? 0 : 5)) #define MM_VALUE(v0,v1) (_game.version == 0 ? v0 : v1) #define OPCODE(i, x) _opcodes[i]._OPCODE(ScummEngine_v2, x) void ScummEngine_v2::setupOpcodes() { /* 00 */ OPCODE(0x00, o5_stopObjectCode); OPCODE(0x01, o2_putActor); OPCODE(0x02, o5_startMusic); OPCODE(0x03, o5_getActorRoom); /* 04 */ OPCODE(0x04, o2_isGreaterEqual); OPCODE(0x05, o2_drawObject); OPCODE(0x06, o2_getActorElevation); OPCODE(0x07, o2_setState08); /* 08 */ OPCODE(0x08, o5_isNotEqual); OPCODE(0x09, o5_faceActor); OPCODE(0x0a, o2_assignVarWordIndirect); OPCODE(0x0b, o2_setObjPreposition); /* 0C */ OPCODE(0x0c, o2_resourceRoutines); OPCODE(0x0d, o5_walkActorToActor); OPCODE(0x0e, o2_putActorAtObject); OPCODE(0x0f, o2_ifNotState08); /* 10 */ OPCODE(0x10, o5_getObjectOwner); OPCODE(0x11, o5_animateActor); OPCODE(0x12, o2_panCameraTo); OPCODE(0x13, o2_actorOps); /* 14 */ OPCODE(0x14, o5_print); OPCODE(0x15, o2_actorFromPos); OPCODE(0x16, o5_getRandomNr); OPCODE(0x17, o2_clearState02); /* 18 */ OPCODE(0x18, o5_jumpRelative); OPCODE(0x19, o2_doSentence); OPCODE(0x1a, o5_move); OPCODE(0x1b, o2_setBitVar); /* 1C */ OPCODE(0x1c, o5_startSound); OPCODE(0x1d, o2_ifClassOfIs); OPCODE(0x1e, o2_walkActorTo); OPCODE(0x1f, o2_ifState02); /* 20 */ OPCODE(0x20, o5_stopMusic); OPCODE(0x21, o2_putActor); OPCODE(0x22, o4_saveLoadGame); OPCODE(0x23, o2_getActorY); /* 24 */ OPCODE(0x24, o2_loadRoomWithEgo); OPCODE(0x25, o2_drawObject); OPCODE(0x26, o5_setVarRange); OPCODE(0x27, o2_setState04); /* 28 */ OPCODE(0x28, o5_equalZero); OPCODE(0x29, o2_setOwnerOf); OPCODE(0x2a, o2_addIndirect); OPCODE(0x2b, o5_delayVariable); /* 2C */ OPCODE(0x2c, o2_assignVarByte); OPCODE(0x2d, o2_putActorInRoom); OPCODE(0x2e, o2_delay); OPCODE(0x2f, o2_ifNotState04); /* 30 */ OPCODE(0x30, o3_setBoxFlags); OPCODE(0x31, o2_getBitVar); OPCODE(0x32, o2_setCameraAt); OPCODE(0x33, o2_roomOps); /* 34 */ OPCODE(0x34, o5_getDist); OPCODE(0x35, o2_findObject); OPCODE(0x36, o2_walkActorToObject); OPCODE(0x37, o2_setState01); /* 38 */ OPCODE(0x38, o2_isLessEqual); OPCODE(0x39, o2_doSentence); OPCODE(0x3a, o2_subtract); OPCODE(0x3b, o2_waitForActor); /* 3C */ OPCODE(0x3c, o5_stopSound); OPCODE(0x3d, o2_setActorElevation); OPCODE(0x3e, o2_walkActorTo); OPCODE(0x3f, o2_ifNotState01); /* 40 */ OPCODE(0x40, o2_cutscene); OPCODE(0x41, o2_putActor); OPCODE(0x42, o2_startScript); OPCODE(0x43, o2_getActorX); /* 44 */ OPCODE(0x44, o2_isLess); OPCODE(0x45, o2_drawObject); OPCODE(0x46, o5_increment); OPCODE(0x47, o2_clearState08); /* 48 */ OPCODE(0x48, o5_isEqual); OPCODE(0x49, o5_faceActor); OPCODE(0x4a, o2_chainScript); OPCODE(0x4b, o2_setObjPreposition); /* 4C */ OPCODE(0x4c, o2_waitForSentence); OPCODE(0x4d, o5_walkActorToActor); OPCODE(0x4e, o2_putActorAtObject); OPCODE(0x4f, o2_ifState08); /* 50 */ OPCODE(0x50, o2_pickupObject); OPCODE(0x51, o5_animateActor); OPCODE(0x52, o5_actorFollowCamera); OPCODE(0x53, o2_actorOps); /* 54 */ OPCODE(0x54, o5_setObjectName); OPCODE(0x55, o2_actorFromPos); OPCODE(0x56, o5_getActorMoving); OPCODE(0x57, o2_setState02); /* 58 */ OPCODE(0x58, o2_beginOverride); OPCODE(0x59, o2_doSentence); OPCODE(0x5a, o2_add); OPCODE(0x5b, o2_setBitVar); /* 5C */ OPCODE(0x5c, o2_dummy); OPCODE(0x5d, o2_ifClassOfIs); OPCODE(0x5e, o2_walkActorTo); OPCODE(0x5f, o2_ifNotState02); /* 60 */ OPCODE(0x60, o2_cursorCommand); OPCODE(0x61, o2_putActor); OPCODE(0x62, o2_stopScript); OPCODE(0x63, o5_getActorFacing); /* 64 */ OPCODE(0x64, o2_loadRoomWithEgo); OPCODE(0x65, o2_drawObject); OPCODE(0x66, o5_getClosestObjActor); OPCODE(0x67, o2_clearState04); /* 68 */ OPCODE(0x68, o5_isScriptRunning); OPCODE(0x69, o2_setOwnerOf); OPCODE(0x6a, o2_subIndirect); OPCODE(0x6b, o2_dummy); /* 6C */ OPCODE(0x6c, o2_getObjPreposition); OPCODE(0x6d, o2_putActorInRoom); OPCODE(0x6e, o2_dummy); OPCODE(0x6f, o2_ifState04); /* 70 */ OPCODE(0x70, o2_lights); OPCODE(0x71, o5_getActorCostume); OPCODE(0x72, o5_loadRoom); OPCODE(0x73, o2_roomOps); /* 74 */ OPCODE(0x74, o5_getDist); OPCODE(0x75, o2_findObject); OPCODE(0x76, o2_walkActorToObject); OPCODE(0x77, o2_clearState01); /* 78 */ OPCODE(0x78, o2_isGreater); OPCODE(0x79, o2_doSentence); OPCODE(0x7a, o2_verbOps); OPCODE(0x7b, o2_getActorWalkBox); /* 7C */ OPCODE(0x7c, o5_isSoundRunning); OPCODE(0x7d, o2_setActorElevation); OPCODE(0x7e, o2_walkActorTo); OPCODE(0x7f, o2_ifState01); /* 80 */ OPCODE(0x80, o5_breakHere); OPCODE(0x81, o2_putActor); OPCODE(0x82, o5_startMusic); OPCODE(0x83, o5_getActorRoom); /* 84 */ OPCODE(0x84, o2_isGreaterEqual); OPCODE(0x85, o2_drawObject); OPCODE(0x86, o2_getActorElevation); OPCODE(0x87, o2_setState08); /* 88 */ OPCODE(0x88, o5_isNotEqual); OPCODE(0x89, o5_faceActor); OPCODE(0x8a, o2_assignVarWordIndirect); OPCODE(0x8b, o2_setObjPreposition); /* 8C */ OPCODE(0x8c, o2_resourceRoutines); OPCODE(0x8d, o5_walkActorToActor); OPCODE(0x8e, o2_putActorAtObject); OPCODE(0x8f, o2_ifNotState08); /* 90 */ OPCODE(0x90, o5_getObjectOwner); OPCODE(0x91, o5_animateActor); OPCODE(0x92, o2_panCameraTo); OPCODE(0x93, o2_actorOps); /* 94 */ OPCODE(0x94, o5_print); OPCODE(0x95, o2_actorFromPos); OPCODE(0x96, o5_getRandomNr); OPCODE(0x97, o2_clearState02); /* 98 */ OPCODE(0x98, o2_restart); OPCODE(0x99, o2_doSentence); OPCODE(0x9a, o5_move); OPCODE(0x9b, o2_setBitVar); /* 9C */ OPCODE(0x9c, o5_startSound); OPCODE(0x9d, o2_ifClassOfIs); OPCODE(0x9e, o2_walkActorTo); OPCODE(0x9f, o2_ifState02); /* A0 */ OPCODE(0xa0, o5_stopObjectCode); OPCODE(0xa1, o2_putActor); OPCODE(0xa2, o4_saveLoadGame); OPCODE(0xa3, o2_getActorY); /* A4 */ OPCODE(0xa4, o2_loadRoomWithEgo); OPCODE(0xa5, o2_drawObject); OPCODE(0xa6, o5_setVarRange); OPCODE(0xa7, o2_setState04); /* A8 */ OPCODE(0xa8, o5_notEqualZero); OPCODE(0xa9, o2_setOwnerOf); OPCODE(0xaa, o2_addIndirect); OPCODE(0xab, o2_switchCostumeSet); /* AC */ OPCODE(0xac, o2_drawSentence); OPCODE(0xad, o2_putActorInRoom); OPCODE(0xae, o2_waitForMessage); OPCODE(0xaf, o2_ifNotState04); /* B0 */ OPCODE(0xb0, o3_setBoxFlags); OPCODE(0xb1, o2_getBitVar); OPCODE(0xb2, o2_setCameraAt); OPCODE(0xb3, o2_roomOps); /* B4 */ OPCODE(0xb4, o5_getDist); OPCODE(0xb5, o2_findObject); OPCODE(0xb6, o2_walkActorToObject); OPCODE(0xb7, o2_setState01); /* B8 */ OPCODE(0xb8, o2_isLessEqual); OPCODE(0xb9, o2_doSentence); OPCODE(0xba, o2_subtract); OPCODE(0xbb, o2_waitForActor); /* BC */ OPCODE(0xbc, o5_stopSound); OPCODE(0xbd, o2_setActorElevation); OPCODE(0xbe, o2_walkActorTo); OPCODE(0xbf, o2_ifNotState01); /* C0 */ OPCODE(0xc0, o2_endCutscene); OPCODE(0xc1, o2_putActor); OPCODE(0xc2, o2_startScript); OPCODE(0xc3, o2_getActorX); /* C4 */ OPCODE(0xc4, o2_isLess); OPCODE(0xc5, o2_drawObject); OPCODE(0xc6, o5_decrement); OPCODE(0xc7, o2_clearState08); /* C8 */ OPCODE(0xc8, o5_isEqual); OPCODE(0xc9, o5_faceActor); OPCODE(0xca, o2_chainScript); OPCODE(0xcb, o2_setObjPreposition); /* CC */ OPCODE(0xcc, o5_pseudoRoom); OPCODE(0xcd, o5_walkActorToActor); OPCODE(0xce, o2_putActorAtObject); OPCODE(0xcf, o2_ifState08); /* D0 */ OPCODE(0xd0, o2_pickupObject); OPCODE(0xd1, o5_animateActor); OPCODE(0xd2, o5_actorFollowCamera); OPCODE(0xd3, o2_actorOps); /* D4 */ OPCODE(0xd4, o5_setObjectName); OPCODE(0xd5, o2_actorFromPos); OPCODE(0xd6, o5_getActorMoving); OPCODE(0xd7, o2_setState02); /* D8 */ OPCODE(0xd8, o5_printEgo); OPCODE(0xd9, o2_doSentence); OPCODE(0xda, o2_add); OPCODE(0xdb, o2_setBitVar); /* DC */ OPCODE(0xdc, o2_dummy); OPCODE(0xdd, o2_ifClassOfIs); OPCODE(0xde, o2_walkActorTo); OPCODE(0xdf, o2_ifNotState02); /* E0 */ OPCODE(0xe0, o2_cursorCommand); OPCODE(0xe1, o2_putActor); OPCODE(0xe2, o2_stopScript); OPCODE(0xe3, o5_getActorFacing); /* E4 */ OPCODE(0xe4, o2_loadRoomWithEgo); OPCODE(0xe5, o2_drawObject); OPCODE(0xe6, o5_getClosestObjActor); OPCODE(0xe7, o2_clearState04); /* E8 */ OPCODE(0xe8, o5_isScriptRunning); OPCODE(0xe9, o2_setOwnerOf); OPCODE(0xea, o2_subIndirect); OPCODE(0xeb, o2_dummy); /* EC */ OPCODE(0xec, o2_getObjPreposition); OPCODE(0xed, o2_putActorInRoom); OPCODE(0xee, o2_dummy); OPCODE(0xef, o2_ifState04); /* F0 */ OPCODE(0xf0, o2_lights); OPCODE(0xf1, o5_getActorCostume); OPCODE(0xf2, o5_loadRoom); OPCODE(0xf3, o2_roomOps); /* F4 */ OPCODE(0xf4, o5_getDist); OPCODE(0xf5, o2_findObject); OPCODE(0xf6, o2_walkActorToObject); OPCODE(0xf7, o2_clearState01); /* F8 */ OPCODE(0xf8, o2_isGreater); OPCODE(0xf9, o2_doSentence); OPCODE(0xfa, o2_verbOps); OPCODE(0xfb, o2_getActorWalkBox); /* FC */ OPCODE(0xfc, o5_isSoundRunning); OPCODE(0xfd, o2_setActorElevation); OPCODE(0xfe, o2_walkActorTo); OPCODE(0xff, o2_ifState01); } #define SENTENCE_SCRIPT 2 int ScummEngine_v2::getVar() { return readVar(fetchScriptByte()); } void ScummEngine_v2::decodeParseString() { byte buffer[512]; byte *ptr = buffer; byte c; bool insertSpace = false; while ((c = fetchScriptByte())) { insertSpace = (c & 0x80) != 0; c &= 0x7f; if (c < 8) { // Special codes as seen in CHARSET_1 etc. My guess is that they // have a similar function as the corresponding embedded stuff in modern // games. Hence for now we convert them to the modern format. // This might allow us to reuse the existing code. *ptr++ = 0xFF; *ptr++ = c; if (c > 3) { *ptr++ = fetchScriptByte(); *ptr++ = 0; } } else *ptr++ = c; if (insertSpace) *ptr++ = ' '; } *ptr = 0; int textSlot = 0; _string[textSlot].xpos = 0; _string[textSlot].ypos = 0; _string[textSlot].right = _screenWidth - 1; _string[textSlot].center = false; _string[textSlot].overhead = false; if (_game.id == GID_MANIAC && _actorToPrintStrFor == 0xFF) { if (_game.version == 0) { _string[textSlot].color = 14; } else if (_game.features & GF_DEMO) { _string[textSlot].color = (_game.version == 2) ? 15 : 1; } } actorTalk(buffer); } int ScummEngine_v2::readVar(uint var) { if (_game.version >= 1 && var >= 14 && var <= 16) var = _scummVars[var]; assertRange(0, var, _numVariables - 1, "variable (reading)"); debugC(DEBUG_VARS, "readvar(%d) = %d", var, _scummVars[var]); return _scummVars[var]; } void ScummEngine_v2::writeVar(uint var, int value) { assertRange(0, var, _numVariables - 1, "variable (writing)"); debugC(DEBUG_VARS, "writeVar(%d) = %d", var, value); if (VAR_CUTSCENEEXIT_KEY != 0xFF && var == VAR_CUTSCENEEXIT_KEY) { // Remap the cutscene exit key in earlier games if (value == 4 || value == 13 || value == 64) value = 27; } _scummVars[var] = value; } void ScummEngine_v2::getResultPosIndirect() { _resultVarNumber = _scummVars[fetchScriptByte()]; } void ScummEngine_v2::getResultPos() { _resultVarNumber = fetchScriptByte(); } int ScummEngine_v2::getActiveObject() { return getVarOrDirectWord(PARAM_1); } void ScummEngine_v2::setStateCommon(byte type) { int obj = getActiveObject(); putState(obj, getState(obj) | type); } void ScummEngine_v2::clearStateCommon(byte type) { int obj = getActiveObject(); putState(obj, getState(obj) & ~type); } void ScummEngine_v2::ifStateCommon(byte type) { int obj = getActiveObject(); jumpRelative((getState(obj) & type) != 0); } void ScummEngine_v2::ifNotStateCommon(byte type) { int obj = getActiveObject(); jumpRelative((getState(obj) & type) == 0); } void ScummEngine_v2::o2_setState08() { int obj = getActiveObject(); putState(obj, getState(obj) | kObjectState_08); markObjectRectAsDirty(obj); clearDrawObjectQueue(); } void ScummEngine_v2::o2_clearState08() { int obj = getActiveObject(); putState(obj, getState(obj) & ~kObjectState_08); markObjectRectAsDirty(obj); clearDrawObjectQueue(); } void ScummEngine_v2::o2_setState04() { setStateCommon(kObjectStateLocked); } void ScummEngine_v2::o2_clearState04() { clearStateCommon(kObjectStateLocked); } void ScummEngine_v2::o2_setState02() { setStateCommon(kObjectStateUntouchable); } void ScummEngine_v2::o2_clearState02() { clearStateCommon(kObjectStateUntouchable); } void ScummEngine_v2::o2_setState01() { setStateCommon(kObjectStatePickupable); } void ScummEngine_v2::o2_clearState01() { clearStateCommon(kObjectStatePickupable); } void ScummEngine_v2::o2_assignVarWordIndirect() { getResultPosIndirect(); setResult(getVarOrDirectWord(PARAM_1)); } void ScummEngine_v2::o2_assignVarByte() { getResultPos(); setResult(fetchScriptByte()); } void ScummEngine_v2::o2_setObjPreposition() { int obj = getVarOrDirectWord(PARAM_1); int unk = fetchScriptByte(); if (_game.platform == Common::kPlatformNES) return; if (whereIsObject(obj) != WIO_NOT_FOUND) { // FIXME: this might not work properly the moment we save and restore the game. byte *ptr = getOBCDFromObject(obj) + 12; *ptr &= 0x1F; *ptr |= unk << 5; } } void ScummEngine_v2::o2_getObjPreposition() { getResultPos(); int obj = getVarOrDirectWord(PARAM_1); if (whereIsObject(obj) != WIO_NOT_FOUND) { byte *ptr = getOBCDFromObject(obj) + 12; setResult(*ptr >> 5); } else { setResult(0xFF); } } void ScummEngine_v2::o2_setBitVar() { int var = fetchScriptWord(); byte a = getVarOrDirectByte(PARAM_1); int bit_var = var + a; int bit_offset = bit_var & 0x0f; bit_var >>= 4; if (getVarOrDirectByte(PARAM_2)) _scummVars[bit_var] |= (1 << bit_offset); else _scummVars[bit_var] &= ~(1 << bit_offset); } void ScummEngine_v2::o2_getBitVar() { getResultPos(); int var = fetchScriptWord(); byte a = getVarOrDirectByte(PARAM_1); int bit_var = var + a; int bit_offset = bit_var & 0x0f; bit_var >>= 4; setResult((_scummVars[bit_var] & (1 << bit_offset)) ? 1 : 0); } void ScummEngine_v2::o2_ifState08() { ifStateCommon(kObjectState_08); } void ScummEngine_v2::o2_ifNotState08() { ifNotStateCommon(kObjectState_08); } void ScummEngine_v2::o2_ifState04() { ifStateCommon(kObjectStateLocked); } void ScummEngine_v2::o2_ifNotState04() { ifNotStateCommon(kObjectStateLocked); } void ScummEngine_v2::o2_ifState02() { ifStateCommon(kObjectStateUntouchable); } void ScummEngine_v2::o2_ifNotState02() { ifNotStateCommon(kObjectStateUntouchable); } void ScummEngine_v2::o2_ifState01() { ifStateCommon(kObjectStatePickupable); } void ScummEngine_v2::o2_ifNotState01() { ifNotStateCommon(kObjectStatePickupable); } void ScummEngine_v2::o2_addIndirect() { int a; getResultPosIndirect(); a = getVarOrDirectWord(PARAM_1); _scummVars[_resultVarNumber] += a; } void ScummEngine_v2::o2_subIndirect() { int a; getResultPosIndirect(); a = getVarOrDirectWord(PARAM_1); _scummVars[_resultVarNumber] -= a; } void ScummEngine_v2::o2_add() { int a; getResultPos(); a = getVarOrDirectWord(PARAM_1); _scummVars[_resultVarNumber] += a; } void ScummEngine_v2::o2_subtract() { int a; getResultPos(); a = getVarOrDirectWord(PARAM_1); _scummVars[_resultVarNumber] -= a; } void ScummEngine_v2::o2_waitForActor() { Actor *a = derefActor(getVarOrDirectByte(PARAM_1), "o2_waitForActor"); if (a->_moving) { _scriptPointer -= 2; o5_breakHere(); } } void ScummEngine_v2::o2_waitForMessage() { if (VAR(VAR_HAVE_MSG)) { _scriptPointer--; o5_breakHere(); } } void ScummEngine_v2::o2_waitForSentence() { if (!_sentenceNum && !isScriptInUse(SENTENCE_SCRIPT)) return; _scriptPointer--; o5_breakHere(); } void ScummEngine_v2::o2_actorOps() { int act = getVarOrDirectByte(PARAM_1); int arg = getVarOrDirectByte(PARAM_2); Actor *a; int i; _opcode = fetchScriptByte(); if (act == 0 && _opcode == 5) { // This case happens in the Zak/MM bootscripts, to set the default talk color (9). _string[0].color = arg; return; } a = derefActor(act, "actorOps"); switch (_opcode) { case 1: // SO_SOUND a->_sound[0] = arg; break; case 2: // SO_PALETTE if (_game.version == 1) i = act; else i = fetchScriptByte(); a->setPalette(i, arg); break; case 3: // SO_ACTOR_NAME loadPtrToResource(rtActorName, a->_number, NULL); break; case 4: // SO_COSTUME a->setActorCostume(arg); break; case 5: // SO_TALK_COLOR if (_game.id == GID_MANIAC && _game.version == 2 && (_game.features & GF_DEMO) && arg == 1) a->_talkColor = 15; else a->_talkColor = arg; break; default: error("o2_actorOps: opcode %d not yet supported", _opcode); } } void ScummEngine_v2::o2_restart() { restart(); } void ScummEngine_v2::o2_drawObject() { int obj, idx, i; ObjectData *od; uint16 x, y, w, h; int xpos, ypos; obj = getVarOrDirectWord(PARAM_1); xpos = getVarOrDirectByte(PARAM_2); ypos = getVarOrDirectByte(PARAM_3); idx = getObjectIndex(obj); if (idx == -1) return; od = &_objs[idx]; if (xpos != 0xFF) { od->walk_x += (xpos * 8) - od->x_pos; od->x_pos = xpos * 8; od->walk_y += (ypos * 8) - od->y_pos; od->y_pos = ypos * 8; } addObjectToDrawQue(idx); x = od->x_pos; y = od->y_pos; w = od->width; h = od->height; i = _numLocalObjects; while (i--) { if (_objs[i].obj_nr && _objs[i].x_pos == x && _objs[i].y_pos == y && _objs[i].width == w && _objs[i].height == h) putState(_objs[i].obj_nr, getState(_objs[i].obj_nr) & ~kObjectState_08); } putState(obj, getState(od->obj_nr) | kObjectState_08); } void ScummEngine_v2::o2_resourceRoutines() { const ResType resTypes[] = { rtInvalid, rtInvalid, rtCostume, rtRoom, rtInvalid, rtScript, rtSound }; int resid = getVarOrDirectByte(PARAM_1); int opcode = fetchScriptByte(); ResType type = rtInvalid; if (0 <= (opcode >> 4) && (opcode >> 4) < (int)ARRAYSIZE(resTypes)) type = resTypes[opcode >> 4]; if ((opcode & 0x0f) == 0 || type == rtInvalid) return; // HACK V2 Maniac Mansion tries to load an invalid sound resource in demo script. if (_game.id == GID_MANIAC && _game.version == 2 && vm.slot[_currentScript].number == 9 && type == rtSound && resid == 1) return; if ((opcode & 0x0f) == 1) { ensureResourceLoaded(type, resid); } else { if (opcode & 1) _res->lock(type, resid); else _res->unlock(type, resid); } } void ScummEngine_v2::o2_verbOps() { int verb = fetchScriptByte(); int slot, state; switch (verb) { case 0: // SO_DELETE_VERBS slot = getVarOrDirectByte(PARAM_1) + 1; assert(0 < slot && slot < _numVerbs); killVerb(slot); break; case 0xFF: // Verb On/Off verb = fetchScriptByte(); state = fetchScriptByte(); slot = getVerbSlot(verb, 0); _verbs[slot].curmode = state; break; default: { // New Verb int x = fetchScriptByte() * 8; int y = fetchScriptByte() * 8; slot = getVarOrDirectByte(PARAM_1) + 1; int prep = fetchScriptByte(); // Only used in V1? // V1 Maniac verbs are relative to the 'verb area' - under the sentence if (_game.platform == Common::kPlatformNES) x += 8; else if ((_game.id == GID_MANIAC) && (_game.version == 1)) y += 8; VerbSlot *vs; assert(0 < slot && slot < _numVerbs); vs = &_verbs[slot]; vs->verbid = verb; if (_game.platform == Common::kPlatformNES) { vs->color = 1; vs->hicolor = 1; vs->dimcolor = 1; } else if (_game.version == 1) { vs->color = (_game.id == GID_MANIAC && (_game.features & GF_DEMO)) ? 16 : 5; vs->hicolor = 7; vs->dimcolor = 11; } else { vs->color = (_game.id == GID_MANIAC && (_game.features & GF_DEMO)) ? 13 : 2; vs->hicolor = 14; vs->dimcolor = 8; } vs->type = kTextVerbType; vs->charset_nr = _string[0]._default.charset; vs->curmode = 1; vs->saveid = 0; vs->key = 0; vs->center = 0; vs->imgindex = 0; vs->prep = prep; vs->curRect.left = x; vs->curRect.top = y; // FIXME: these keyboard map depends on the language of the game. // E.g. a german keyboard has 'z' and 'y' swapped, while a french // keyboard starts with "azerty", etc. if (_game.platform == Common::kPlatformNES) { static const char keyboard[] = { 'q','w','e','r', 'a','s','d','f', 'z','x','c','v' }; if (1 <= slot && slot <= ARRAYSIZE(keyboard)) vs->key = keyboard[slot - 1]; } else { static const char keyboard[] = { 'q','w','e','r','t', 'a','s','d','f','g', 'z','x','c','v','b' }; if (1 <= slot && slot <= ARRAYSIZE(keyboard)) vs->key = keyboard[slot - 1]; } // It follows the verb name loadPtrToResource(rtVerb, slot, NULL); } break; } // Force redraw of the modified verb slot drawVerb(slot, 0); verbMouseOver(0); } void ScummEngine_v2::o2_doSentence() { int a; SentenceTab *st; a = getVarOrDirectByte(PARAM_1); if (a == 0xFC) { _sentenceNum = 0; stopScript(SENTENCE_SCRIPT); return; } if (a == 0xFB) { resetSentence(); return; } assert(_sentenceNum < NUM_SENTENCE); st = &_sentence[_sentenceNum++]; st->verb = a; st->objectA = getVarOrDirectWord(PARAM_2); st->objectB = getVarOrDirectWord(PARAM_3); st->preposition = (st->objectB != 0); st->freezeCount = 0; // Execute or print the sentence _opcode = fetchScriptByte(); switch (_opcode) { case 0: // Do nothing (besides setting up the sentence above) break; case 1: // Execute the sentence _sentenceNum--; if (st->verb == 254) { ScummEngine::stopObjectScript(st->objectA); } else { bool isBackgroundScript; bool isSpecialVerb; if (st->verb != 253 && st->verb != 250) { VAR(VAR_ACTIVE_VERB) = st->verb; VAR(VAR_ACTIVE_OBJECT1) = st->objectA; VAR(VAR_ACTIVE_OBJECT2) = st->objectB; isBackgroundScript = false; isSpecialVerb = false; } else { isBackgroundScript = (st->verb == 250); isSpecialVerb = true; st->verb = 253; } // Check if an object script for this object is already running. If // so, reuse its script slot. Note that we abuse two script flags: // freezeResistant and recursive. We use them to track two // script flags used in V1/V2 games. The main reason we do it this // ugly evil way is to avoid having to introduce yet another save // game revision. int slot = -1; ScriptSlot *ss; int i; ss = vm.slot; for (i = 0; i < NUM_SCRIPT_SLOT; i++, ss++) { if (st->objectA == ss->number && ss->freezeResistant == isBackgroundScript && ss->recursive == isSpecialVerb && (ss->where == WIO_ROOM || ss->where == WIO_INVENTORY || ss->where == WIO_FLOBJECT)) { slot = i; break; } } runObjectScript(st->objectA, st->verb, isBackgroundScript, isSpecialVerb, NULL, slot); } break; case 2: // Print the sentence _sentenceNum--; VAR(VAR_SENTENCE_VERB) = st->verb; VAR(VAR_SENTENCE_OBJECT1) = st->objectA; VAR(VAR_SENTENCE_OBJECT2) = st->objectB; o2_drawSentence(); break; default: error("o2_doSentence: unknown subopcode %d", _opcode); } } void ScummEngine_v2::drawPreposition(int index) { // The prepositions, like the fonts, were hard code in the engine. Thus // we have to do that, too, and provde localized versions for all the // languages MM/Zak are available in. const char *prepositions[][5] = { { " ", " in", " with", " on", " to" }, // English { " ", " mit", " mit", " mit", " zu" }, // German { " ", " dans", " avec", " sur", " <" }, // French { " ", " in", " con", " su", " a" }, // Italian { " ", " en", " con", " en", " a" }, // Spanish { " ", " \x7f", " \x7f", " na", " \x7f" },// Russian }; int lang; switch (_language) { case Common::DE_DEU: lang = 1; break; case Common::FR_FRA: lang = 2; break; case Common::IT_ITA: lang = 3; break; case Common::ES_ESP: lang = 4; break; case Common::RU_RUS: lang = 5; break; default: lang = 0; // Default to english } if (_game.platform == Common::kPlatformNES) { _sentenceBuf += (const char *)(getResourceAddress(rtCostume, 78) + VAR(VAR_SENTENCE_PREPOSITION) * 8 + 2); } else _sentenceBuf += prepositions[lang][index]; } void ScummEngine_v2::o2_drawSentence() { Common::Rect sentenceline; const byte *temp; int slot = getVerbSlot(VAR(VAR_SENTENCE_VERB), 0); if (!((_userState & USERSTATE_IFACE_SENTENCE) || (_game.platform == Common::kPlatformNES && (_userState & USERSTATE_IFACE_ALL)))) return; if (getResourceAddress(rtVerb, slot)) _sentenceBuf = (char *)getResourceAddress(rtVerb, slot); else return; if (VAR(VAR_SENTENCE_OBJECT1) > 0) { temp = getObjOrActorName(VAR(VAR_SENTENCE_OBJECT1)); if (temp) { _sentenceBuf += " "; _sentenceBuf += (const char *)temp; } // For V1 games, the engine must compute the preposition. // In all other Scumm versions, this is done by the sentence script. if ((_game.id == GID_MANIAC && _game.version == 1 && !(_game.platform == Common::kPlatformNES)) && (VAR(VAR_SENTENCE_PREPOSITION) == 0)) { if (_verbs[slot].prep == 0xFF) { byte *ptr = getOBCDFromObject(VAR(VAR_SENTENCE_OBJECT1)); assert(ptr); VAR(VAR_SENTENCE_PREPOSITION) = (*(ptr + 12) >> 5); } else VAR(VAR_SENTENCE_PREPOSITION) = _verbs[slot].prep; } } if (0 < VAR(VAR_SENTENCE_PREPOSITION) && VAR(VAR_SENTENCE_PREPOSITION) <= 4) { drawPreposition(VAR(VAR_SENTENCE_PREPOSITION)); } if (VAR(VAR_SENTENCE_OBJECT2) > 0) { temp = getObjOrActorName(VAR(VAR_SENTENCE_OBJECT2)); if (temp) { _sentenceBuf += " "; _sentenceBuf += (const char *)temp; } } _string[2].charset = 1; _string[2].ypos = _virtscr[kVerbVirtScreen].topline; _string[2].xpos = 0; _string[2].right = _virtscr[kVerbVirtScreen].w - 1; if (_game.platform == Common::kPlatformNES) { _string[2].xpos = 16; _string[2].color = 0; } else if (_game.version == 1) _string[2].color = 16; else _string[2].color = 13; byte string[80]; const char *ptr = _sentenceBuf.c_str(); int i = 0, len = 0; // Maximum length of printable characters int maxChars = (_game.platform == Common::kPlatformNES) ? 60 : 40; while (*ptr) { if (*ptr != '@') len++; if (len > maxChars) { break; } string[i++] = *ptr++; if (_game.platform == Common::kPlatformNES && len == 30) { string[i++] = 0xFF; string[i++] = 8; } } string[i] = 0; if (_game.platform == Common::kPlatformNES) { sentenceline.top = _virtscr[kVerbVirtScreen].topline; sentenceline.bottom = _virtscr[kVerbVirtScreen].topline + 16; sentenceline.left = 16; sentenceline.right = _virtscr[kVerbVirtScreen].w - 1; } else { sentenceline.top = _virtscr[kVerbVirtScreen].topline; sentenceline.bottom = _virtscr[kVerbVirtScreen].topline + 8; sentenceline.left = 0; sentenceline.right = _virtscr[kVerbVirtScreen].w - 1; } restoreBackground(sentenceline); drawString(2, (byte *)string); } void ScummEngine_v2::o2_ifClassOfIs() { int obj = getVarOrDirectWord(PARAM_1); int clsop = getVarOrDirectByte(PARAM_2); byte *obcd = getOBCDFromObject(obj); if (obcd == 0) { o5_jumpRelative(); return; } byte cls = *(obcd + 6); jumpRelative((cls & clsop) == clsop); } void ScummEngine_v2::o2_walkActorTo() { int x, y; Actor *a; int act = getVarOrDirectByte(PARAM_1); // WORKAROUND bug #1252606 if (_game.id == GID_ZAK && _game.version == 1 && vm.slot[_currentScript].number == 115 && act == 249) { act = VAR(VAR_EGO); } a = derefActor(act, "o2_walkActorTo"); x = getVarOrDirectByte(PARAM_2); y = getVarOrDirectByte(PARAM_3); a->startWalkActor(x, y, -1); } void ScummEngine_v2::o2_putActor() { int act = getVarOrDirectByte(PARAM_1); int x, y; Actor *a; a = derefActor(act, "o2_putActor"); x = getVarOrDirectByte(PARAM_2); y = getVarOrDirectByte(PARAM_3); a->putActor(x, y); } void ScummEngine_v2::o2_startScript() { int script = getVarOrDirectByte(PARAM_1); if (!_copyProtection) { // The enhanced version of Zak McKracken included in the // SelectWare Classic Collection bundle used CD check instead // of the usual key code check at airports. if ((_game.id == GID_ZAK) && (script == 15) && (_roomResource == 45)) return; } // WORKAROUND bug #1447058: In Maniac Mansion, when the door bell // rings, then this normally causes Ted Edison to leave his room. // This is controlled by script 87. On the other hand, when the // player enters Ted's room while Ted is in it, then Ted captures // the player and puts his active ego into the cellar prison. // // Unfortunately, the two events can collide: If the cutscene is // playing in which Ted captures the player (controlled by script // 88) and simultaneously the door bell rings (due to package // delivery...) then this leads to an assertion (in ScummVM, due to // its stricter validity checking), or to unexpected / strange // behavior (in the original engine). The script writers apparently // anticipated the possibility of the door bell ringing: Before // script 91 starts script 88, it explicitly stops script 87. // Unfortunately, this is not quite enough, as script 87 can be // started while script 88 is already running -- specifically, by // the package delivery sequence. // // Now, one can easily suppress this particular assertion, but then // one still gets odd behavior: Ted is in the process of // incarcerating the player, when the door bell rings; Ted promptly // leaves to get the package, leaving the player alone (!), but then // moments later we cut to the cellar, where Ted just put the // player. That seems weird and irrational (the Edisons may be mad, // but they are not stupid when it comes to putting people into // their dungeon ;) // // To avoid this, we use a somewhat more elaborate workaround: If // script 88 or 89 are running (which control the capture resp. // imprisonment of the player), then any attempt to start script 87 // (which makes Ted go answer the door bell) is simply ignored. This // way, the door bell still chimes, but Ted ignores it. if (_game.id == GID_MANIAC) { if (script == MM_SCRIPT(82)) { if (isScriptRunning(MM_SCRIPT(83)) || isScriptRunning(MM_SCRIPT(84))) return; } } // WORKAROUND bug #4556: Purple Tentacle can appear in the lab, after being // chased out and end up stuck in the room. This bug is triggered if the player // enters the lab within 45 minutes of first entering the mansion and has chased Purple Tentacle // out. Eventually the cutscene with Purple Tentacle chasing Sandy in the lab // will play. This script leaves Purple Tentacle in the room causing him to become // a permanent resident. // Our fix is simply to prevent the Cutscene playing, if the lab has already been stormed if (_game.id == GID_MANIAC) { if (_game.version >= 1 && script == 155) { if (VAR(120) == 1) return; } // Script numbers are different in V0 if (_game.version == 0 && script == 150) { if (VAR(104) == 1) return; } } runScript(script, 0, 0, 0); } void ScummEngine_v2::stopScriptCommon(int script) { // WORKAROUND bug #4112: If you enter the lab while Dr. Fred has the powered turned off // to repair the Zom-B-Matic, the script will be stopped and the power will never turn // back on. This fix forces the power on, when the player enters the lab, // if the script which turned it off is running if (_game.id == GID_MANIAC && _roomResource == 4 && isScriptRunning(MM_SCRIPT(138))) { if (vm.slot[_currentScript].number == MM_VALUE(130, 163)) { if (script == MM_SCRIPT(138)) { int obj = MM_VALUE(124, 157); putState(obj, getState(obj) & ~kObjectState_08); } } } if (_game.id == GID_MANIAC && _roomResource == 26 && vm.slot[_currentScript].number == 10001) { // FIXME: Nasty hack for bug #915575 // Don't let the exit script for room 26 stop the script (116), when // switching to the dungeon (script 89) if (script == MM_SCRIPT(111) && isScriptRunning(MM_SCRIPT(84))) return; } if (script == 0) script = vm.slot[_currentScript].number; if (_currentScript != 0 && vm.slot[_currentScript].number == script) stopObjectCode(); else stopScript(script); } void ScummEngine_v2::o2_stopScript() { stopScriptCommon(getVarOrDirectByte(PARAM_1)); } void ScummEngine_v2::o2_panCameraTo() { panCameraTo(getVarOrDirectByte(PARAM_1) * V12_X_MULTIPLIER, 0); } void ScummEngine_v2::walkActorToObject(int actor, int obj) { int x, y, dir; getObjectXYPos(obj, x, y, dir); Actor *a = derefActor(actor, "walkActorToObject"); AdjustBoxResult r = a->adjustXYToBeInBox(x, y); x = r.x; y = r.y; a->startWalkActor(x, y, dir); } void ScummEngine_v2::o2_walkActorToObject() { int actor = getVarOrDirectByte(PARAM_1); int obj = getVarOrDirectWord(PARAM_2); if (whereIsObject(obj) != WIO_NOT_FOUND) { walkActorToObject(actor, obj); } } void ScummEngine_v2::o2_putActorAtObject() { int obj, x, y; Actor *a; a = derefActor(getVarOrDirectByte(PARAM_1), "o2_putActorAtObject"); obj = getVarOrDirectWord(PARAM_2); if (whereIsObject(obj) != WIO_NOT_FOUND) { getObjectXYPos(obj, x, y); AdjustBoxResult r = a->adjustXYToBeInBox(x, y); x = r.x; y = r.y; } else { x = 30; y = 60; } a->putActor(x, y); } void ScummEngine_v2::o2_putActorInRoom() { Actor *a; int act = getVarOrDirectByte(PARAM_1); int room = getVarOrDirectByte(PARAM_2); a = derefActor(act, "o2_putActorInRoom"); a->_room = room; if (!room) { if (_game.id == GID_MANIAC && _game.version <= 1 && _game.platform != Common::kPlatformNES) a->setFacing(180); a->putActor(0, 0, 0); } // WORKAROUND bug #2285: Caponians dont disguise after using blue crystal // This is for a game scripting oversight. // After first using the blue crystal, a cutscene of the two Caponians plays (script-96), // locking object 344 (which prevents the cutscene playing again) and setting Var[245] to 0x18. // script-5 uses this variable to set the Caponian costume // On first apperance after using the blue crystal, the Caponians now will have the disguise on // // If you visit the spacecraft and ring the doorbell, Var[245] will be set to 0x1C (Disguise off) // Using the blue crystal again, will result in the Caponian appearing without his disguise // as Var[245] is never set back to 0x18. This WORKAROUND fixes the problem by ensuring // Var[245] is set to have the Disguise on in most situations // // We don't touch the variable in the following situations // If the Caponian is being put into the space ship room, or the current room is the // space ship and the Caponian is being put into the backroom of the telephone company (you didnt show your fan club card) if (_game.id == GID_ZAK && _game.version <= 2 && act == 7) { // Is script-96 cutscene done if ((getState(344) & kObjectStateLocked)) { // Not 'putting' in the space ship if (room != 10) { // not putting in telephone back room, and not in space ship if (room != 16 && _currentRoom != 10) { // Set caponian costume to 'disguise on' writeVar(245, 0x18); } } } } } void ScummEngine_v2::o2_getActorElevation() { getResultPos(); int act = getVarOrDirectByte(PARAM_1); Actor *a = derefActor(act, "o2_getActorElevation"); setResult(a->getElevation()); } void ScummEngine_v2::o2_setActorElevation() { int act = getVarOrDirectByte(PARAM_1); int elevation = (int8)getVarOrDirectByte(PARAM_2); Actor *a = derefActor(act, "o2_setActorElevation"); a->setElevation(elevation); } void ScummEngine_v2::o2_actorFromPos() { int x, y; getResultPos(); x = getVarOrDirectByte(PARAM_1) * V12_X_MULTIPLIER; y = getVarOrDirectByte(PARAM_2) * V12_Y_MULTIPLIER; setResult(getActorFromPos(x, y)); } void ScummEngine_v2::o2_findObject() { int obj; getResultPos(); int x = getVarOrDirectByte(PARAM_1) * V12_X_MULTIPLIER; int y = getVarOrDirectByte(PARAM_2) * V12_Y_MULTIPLIER; obj = findObject(x, y); if (obj == 0 && (_game.platform == Common::kPlatformNES) && (_userState & USERSTATE_IFACE_INVENTORY)) { if (_mouseOverBoxV2 >= 0 && _mouseOverBoxV2 < 4) obj = findInventory(VAR(VAR_EGO), _mouseOverBoxV2 + _inventoryOffset + 1); } setResult(obj); } void ScummEngine_v2::o2_getActorX() { int a; getResultPos(); a = getVarOrDirectByte(PARAM_1); setResult(getObjX(actorToObj(a))); } void ScummEngine_v2::o2_getActorY() { int a; getResultPos(); a = getVarOrDirectByte(PARAM_1); setResult(getObjY(actorToObj(a))); } void ScummEngine_v2::o2_isGreater() { uint16 a = getVar(); uint16 b = getVarOrDirectWord(PARAM_1); jumpRelative(b > a); } void ScummEngine_v2::o2_isGreaterEqual() { uint16 a = getVar(); uint16 b = getVarOrDirectWord(PARAM_1); jumpRelative(b >= a); } void ScummEngine_v2::o2_isLess() { uint16 a = getVar(); uint16 b = getVarOrDirectWord(PARAM_1); jumpRelative(b < a); } void ScummEngine_v2::o2_isLessEqual() { uint16 a = getVar(); uint16 b = getVarOrDirectWord(PARAM_1); jumpRelative(b <= a); } void ScummEngine_v2::o2_lights() { int a, b, c; a = getVarOrDirectByte(PARAM_1); b = fetchScriptByte(); c = fetchScriptByte(); if (c == 0) { if (_game.id == GID_MANIAC && _game.version == 1 && !(_game.platform == Common::kPlatformNES)) { // Convert older light mode values into // equivalent values of later games. // 0 Darkness // 1 Flashlight // 2 Lighted area if (a == 2) VAR(VAR_CURRENT_LIGHTS) = 11; else if (a == 1) VAR(VAR_CURRENT_LIGHTS) = 4; else VAR(VAR_CURRENT_LIGHTS) = 0; } else VAR(VAR_CURRENT_LIGHTS) = a; } else if (c == 1) { _flashlight.xStrips = a; _flashlight.yStrips = b; } _fullRedraw = true; } void ScummEngine_v2::o2_loadRoomWithEgo() { Actor *a; int obj, room, x, y, x2, y2, dir; obj = getVarOrDirectWord(PARAM_1); room = getVarOrDirectByte(PARAM_2); a = derefActor(VAR(VAR_EGO), "o2_loadRoomWithEgo"); // The original interpreter sets the actors new room X/Y to the last rooms X/Y // This fixes a problem with MM: script 161 in room 12, the 'Oomph!' script // This scripts runs before the actor position is set to the correct room entry location if ((_game.id == GID_MANIAC) && (_game.platform != Common::kPlatformNES)) { a->putActor(a->getPos().x, a->getPos().y, room); } else { a->putActor(0, 0, room); } _egoPositioned = false; x = (int8)fetchScriptByte(); y = (int8)fetchScriptByte(); startScene(a->_room, a, obj); getObjectXYPos(obj, x2, y2, dir); AdjustBoxResult r = a->adjustXYToBeInBox(x2, y2); x2 = r.x; y2 = r.y; a->putActor(x2, y2, _currentRoom); a->setDirection(dir + 180); camera._dest.x = camera._cur.x = a->getPos().x; setCameraAt(a->getPos().x, a->getPos().y); setCameraFollows(a); _fullRedraw = true; resetSentence(); if (x >= 0 && y >= 0) { a->startWalkActor(x, y, -1); } runScript(5, 0, 0, 0); } void ScummEngine_v2::o2_setOwnerOf() { int obj, owner; obj = getVarOrDirectWord(PARAM_1); owner = getVarOrDirectByte(PARAM_2); setOwnerOf(obj, owner); } void ScummEngine_v2::o2_delay() { int delay = fetchScriptByte(); delay |= fetchScriptByte() << 8; delay |= fetchScriptByte() << 16; delay = 0xFFFFFF - delay; vm.slot[_currentScript].delay = delay; vm.slot[_currentScript].status = ssPaused; o5_breakHere(); } void ScummEngine_v2::o2_setCameraAt() { setCameraAtEx(getVarOrDirectByte(PARAM_1) * V12_X_MULTIPLIER); } void ScummEngine_v2::o2_roomOps() { int a = getVarOrDirectByte(PARAM_1); int b = getVarOrDirectByte(PARAM_2); _opcode = fetchScriptByte(); switch (_opcode & 0x1F) { case 1: // SO_ROOM_SCROLL a *= 8; b *= 8; if (a < (_screenWidth / 2)) a = (_screenWidth / 2); if (b < (_screenWidth / 2)) b = (_screenWidth / 2); if (a > _roomWidth - (_screenWidth / 2)) a = _roomWidth - (_screenWidth / 2); if (b > _roomWidth - (_screenWidth / 2)) b = _roomWidth - (_screenWidth / 2); VAR(VAR_CAMERA_MIN_X) = a; VAR(VAR_CAMERA_MAX_X) = b; break; case 2: // SO_ROOM_COLOR if (_game.version == 1) { // V1 zak needs to know when room color is changed _roomPalette[0] = 255; _roomPalette[1] = a; _roomPalette[2] = b; } else { _roomPalette[b] = a; } _fullRedraw = true; break; } } void ScummEngine_v2::o2_cutscene() { vm.cutSceneData[0] = _userState | (_userPut ? 16 : 0); vm.cutSceneData[1] = (int16)VAR(VAR_CURSORSTATE); vm.cutSceneData[2] = _currentRoom; vm.cutSceneData[3] = camera._mode; VAR(VAR_CURSORSTATE) = 200; // Hide inventory, freeze scripts, hide cursor setUserState(USERSTATE_SET_IFACE | USERSTATE_SET_CURSOR | USERSTATE_SET_FREEZE | USERSTATE_FREEZE_ON); _sentenceNum = 0; stopScript(SENTENCE_SCRIPT); resetSentence(); vm.cutScenePtr[0] = 0; } void ScummEngine_v2::o2_endCutscene() { vm.cutSceneStackPointer = 0; VAR(VAR_OVERRIDE) = 0; vm.cutSceneScript[0] = 0; vm.cutScenePtr[0] = 0; VAR(VAR_CURSORSTATE) = vm.cutSceneData[1]; // Reset user state to values before cutscene setUserState(vm.cutSceneData[0] | USERSTATE_SET_IFACE | USERSTATE_SET_CURSOR | USERSTATE_SET_FREEZE); if ((_game.id == GID_MANIAC) && !(_game.platform == Common::kPlatformNES)) { camera._mode = (byte) vm.cutSceneData[3]; if (camera._mode == kFollowActorCameraMode) { actorFollowCamera(VAR(VAR_EGO)); } else if (vm.cutSceneData[2] != _currentRoom) { startScene(vm.cutSceneData[2], 0, 0); } } else { actorFollowCamera(VAR(VAR_EGO)); } } void ScummEngine_v2::o2_beginOverride() { vm.cutScenePtr[0] = _scriptPointer - _scriptOrgPointer; vm.cutSceneScript[0] = _currentScript; // Skip the jump instruction following the override instruction fetchScriptByte(); ScummEngine::fetchScriptWord(); } void ScummEngine_v2::o2_chainScript() { int script = getVarOrDirectByte(PARAM_1); stopScript(vm.slot[_currentScript].number); _currentScript = 0xFF; runScript(script, 0, 0, 0); } void ScummEngine_v2::o2_pickupObject() { int obj = getVarOrDirectWord(PARAM_1); if (obj < 1) { error("pickupObject received invalid index %d (script %d)", obj, vm.slot[_currentScript].number); } if (getObjectIndex(obj) == -1) return; if (whereIsObject(obj) == WIO_INVENTORY) /* Don't take an */ return; /* object twice */ addObjectToInventory(obj, _roomResource); markObjectRectAsDirty(obj); putOwner(obj, VAR(VAR_EGO)); putState(obj, getState(obj) | kObjectState_08 | kObjectStateUntouchable); clearDrawObjectQueue(); runInventoryScript(1); if (_game.platform == Common::kPlatformNES) _sound->addSoundToQueue(51); // play 'pickup' sound } void ScummEngine_v2::o2_cursorCommand() { // TODO: Define the magic numbers uint16 cmd = getVarOrDirectWord(PARAM_1); byte state = cmd >> 8; if (cmd & 0xFF) { VAR(VAR_CURSORSTATE) = cmd & 0xFF; } setUserState(state); } void ScummEngine_v2::setUserState(byte state) { if (state & USERSTATE_SET_IFACE) { // Userface if (_game.platform == Common::kPlatformNES) _userState = (_userState & ~USERSTATE_IFACE_ALL) | (state & USERSTATE_IFACE_ALL); else _userState = state & USERSTATE_IFACE_ALL; } if (state & USERSTATE_SET_FREEZE) { // Freeze if (state & USERSTATE_FREEZE_ON) freezeScripts(0); else unfreezeScripts(); } if (state & USERSTATE_SET_CURSOR) { // Cursor Show/Hide if (_game.platform == Common::kPlatformNES) _userState = (_userState & ~USERSTATE_CURSOR_ON) | (state & USERSTATE_CURSOR_ON); if (state & USERSTATE_CURSOR_ON) { _userPut = 1; _cursor.state = 1; } else { _userPut = 0; _cursor.state = 0; } } // Hide all verbs and inventory Common::Rect rect; rect.top = _virtscr[kVerbVirtScreen].topline; rect.bottom = _virtscr[kVerbVirtScreen].topline + 8 * 88; rect.right = _virtscr[kVerbVirtScreen].w - 1; if (_game.platform == Common::kPlatformNES) { rect.left = 16; } else { rect.left = 0; } restoreBackground(rect); // Draw all verbs and inventory redrawVerbs(); runInventoryScript(1); } void ScummEngine_v2::o2_getActorWalkBox() { Actor *a; getResultPos(); a = derefActor(getVarOrDirectByte(PARAM_1), "o2_getActorWalkbox"); setResult(a->isInCurrentRoom() ? a->_walkbox: 0xFF); } void ScummEngine_v2::o2_dummy() { // Opcode 0xEE is used in maniac and zak but has no purpose if (_opcode != 0xEE) warning("o2_dummy invoked (opcode %d)", _opcode); } void ScummEngine_v2::o2_switchCostumeSet() { // NES version of maniac uses this to switch between the two // groups of costumes it has if (_game.platform == Common::kPlatformNES) NES_loadCostumeSet(fetchScriptByte()); else if (_game.platform == Common::kPlatformC64) fetchScriptByte(); else o2_dummy(); } void ScummEngine_v2::resetSentence() { VAR(VAR_SENTENCE_VERB) = VAR(VAR_BACKUP_VERB); VAR(VAR_SENTENCE_OBJECT1) = 0; VAR(VAR_SENTENCE_OBJECT2) = 0; VAR(VAR_SENTENCE_PREPOSITION) = 0; } void ScummEngine_v2::runInventoryScript(int i) { redrawV2Inventory(); } } // End of namespace Scumm
alexbevi/scummvm
engines/scumm/script_v2.cpp
C++
gpl-2.0
45,801
/** * @package hubzero-cms * @file plugins/projects/files/assets/css/connections.css * @copyright Copyright 2005-2015 HUBzero Foundation, LLC. * @license http://opensource.org/licenses/MIT MIT */ #project-wrap #page_options { list-style: none; margin: 0; padding: 0; text-align: right; } #project-wrap #page_options:after { content: ""; display: table; line-height: 1; clear: right; } .connections { margin-top: 50px; } #project-wrap .connections .connection-wrap { display: block; float: left; border: 1px solid transparent; margin: 15px; padding: 10px; border-radius: 4px; text-align: center; position: relative; } #project-wrap .connections .connection-wrap:hover { background-color: #F1F1F1; border: 1px solid #E9E9E9; } #project-wrap .connections .connection { display: block; border: 1px solid transparent; } .connections .large-icon img { height: 128px; width: 128px; } .connections .small-icon img { height: 64px; width: 64px; } .connections .list img { height: 32px; width: 32px; float: left } #project-wrap .connections .list { float: none; text-align: left; overflow: hidden; margin-top: 5px; margin-bottom: 5px; } .connections .connection .name { text-align: center; color: #555; font-size: 16px; } .connections .list .name { float: left; line-height: 32px; float: left; margin-left: 10px; } #project-wrap .layout a { display: block; height: 40px; width: 40px; background: transparent; border-top: 1px solid #E9E9E9; border-bottom: 1px solid #E9E9E9; border-right: 1px solid #E9E9E9; float: right; position: relative; } #project-wrap .layout a.last { border-left: 1px solid #E9E9E9; border-top-left-radius: 4px; border-bottom-left-radius: 4px; } #project-wrap .layout a.first { border-top-right-radius: 4px; border-bottom-right-radius: 4px; } #project-wrap .layout a:hover, #project-wrap .layout .active { background: #F1F1F1; } .layout a:before { content: ''; color: #999999; line-height: 40px; text-align: center; position: absolute; font-size: 20px; left: 50%; margin-left: -9px; top: 50%; margin-top: -19px; } .layout .layout-large-icon:before { font-family: "fontcons"; content: "\f009"; } .layout .layout-small-icon:before { font-family: "fontcons"; content: "\f00a"; } .layout .layout-list:before { font-family: "fontcons"; content: "\f00b"; } .connections .new-connection { color: #999999; } .connections .new-connection:hover { color: green; } .connections .new-connection .new { height: 128px; line-height: 128px; position: relative; text-align: center; } .connections .small-icon .new { height: 64px; line-height: 64px; } .connections .list .new { height: 32px; width: 32px; line-height: 32px; float: left; } .connection-actions { display: block; padding-top: 0.4em; } .list .connection-actions { position: absolute; right: 0; padding-top: 0; } .connection-actions a { display: inline-block; font-size: 1.5em; width: 1em; height: 1em; overflow: hidden; line-height: 1; margin: 0.2em; color: #bbb; } .connection-actions a:hover { color: #222; } .connection-actions a.connection-delete:hover { color: #c00; } .connections .new-connection .new:before { font-family: "fontcons"; content: '\2295'; height: 128px; width: 128px; font-size: 128px; } .connections .small-icon .new:before { height: 64px; width: 64px; font-size: 64px; } .connections .list .new:before { height: 32px; width: 32px; font-size: 32px; } .connections .new-connection .name { margin-left: 4px; line-height: 28px; } .connections .connection-type { border: 1px solid transparent; padding: 0; margin: 0; outline: none; background-color: transparent; color: #555555; } .connections .connection-type:hover { border: 1px solid #E9E9E9; background-color: white; } .connections .private-connection:before { font-family: "fontcons"; content: "\f023"; position: absolute; top: 2px; left: 2px; font-size: 15px; line-height: 15px; color: #999999; } .connections .small-icon .private-connection:before { font-size: 20px; line-height: 20px; } .connections .large-icon .private-connection:before { font-size: 25px; line-height: 25px; } .connections .private-explanation { margin: 15px; } .connections .private-explanation:before { font-family: "fontcons"; content: "\f023"; }
drewthoennes/hubzero-cms
core/plugins/projects/files/assets/css/connections.css
CSS
gpl-2.0
4,307
/* ** Copyright (C) 2014-2015 Cisco and/or its affiliates. All rights reserved. ** Copyright (C) 2005-2013 Sourcefire, 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. You may not use, modify or ** distribute this program under any other version of the GNU General ** Public 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __DCERPC_H__ #define __DCERPC_H__ #include <sys/types.h> int dcerpc_validate(const uint8_t *data, int size); #endif /* __DCERPC_H__ */
gruberasheridc/snort-2.9.8.0
src/dynamic-preprocessors/appid/service_plugins/dcerpc.h
C
gpl-2.0
1,051
/* * Copyright (c) 2003 Lubos Lunak <l.lunak@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. */ #ifndef __RANDRPASSIVEPOPUP_H__ #define __RANDRPASSIVEPOPUP_H__ #include <kpassivepopup.h> #include <QTimer> //Added by qt3to4: #include <QPixmap> #include <QEvent> #include <X11/Xlib.h> #include <fixx11h.h> class KRandrPassivePopup : public KPassivePopup { Q_OBJECT public: static KRandrPassivePopup *message( const QString &caption, const QString &text, const QPixmap &icon, QWidget *parent, int timeout = -1 ); protected: virtual bool eventFilter( QObject* o, QEvent* e ); virtual bool x11Event( XEvent* e ); private Q_SLOTS: void slotPositionSelf(); private: KRandrPassivePopup( QWidget *parent=0, Qt::WFlags f=0 ); void startWatchingWidget( QWidget* w ); QList< QWidget* > watched_widgets; QList< Window > watched_windows; QTimer update_timer; }; #endif
falbrechtskirchinger/kde-workspace
kcontrol/randr/krandrpassivepopup.h
C
gpl-2.0
1,609
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2013 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #ifndef XCSOAR_MANAGE_CAI302_DIALOG_HPP #define XCSOAR_MANAGE_CAI302_DIALOG_HPP struct DialogLook; class SingleWindow; class Device; void ManageCAI302Dialog(SingleWindow &parent, const DialogLook &look, Device &device); #endif
onkelhotte/XCSoar
src/Dialogs/Device/ManageCAI302Dialog.hpp
C++
gpl-2.0
1,149
/* ********************************************************************************************************* * uC/GUI V3.98 * Universal graphic software for embedded applications * * (c) Copyright 2002, Micrium Inc., Weston, FL * (c) Copyright 2002, SEGGER Microcontroller Systeme GmbH * * µC/GUI is protected by international copyright laws. Knowledge of the * source code may not be used to write a similar product. This file may * only be used in accordance with a license and should not be redistributed * in any way. We appreciate your understanding and fairness. * ---------------------------------------------------------------------- File : LISTVIEW_GetNumRows.c Purpose : Implementation of LISTVIEW_GetNumRows ---------------------------END-OF-HEADER------------------------------ */ #include "LISTVIEW_Private.h" #if GUI_WINSUPPORT /********************************************************************* * * Public routines * ********************************************************************** */ /********************************************************************* * * LISTVIEW_GetNumRows */ unsigned LISTVIEW_GetNumRows(LISTVIEW_Handle hObj) { unsigned NumRows = 0; if (hObj) { LISTVIEW_Obj* pObj; WM_LOCK(); pObj = LISTVIEW_H2P(hObj); NumRows = LISTVIEW__GetNumRows(pObj); WM_UNLOCK(); } return NumRows; } #else /* Avoid problems with empty object modules */ void LISTVIEW_GetNumRows(void); void LISTVIEW_GetNumRows(void) {} #endif /*************************** End of file ****************************/
WildfireTeamPRJ/wildfire_stm32_iso
3-野火ISO-系统进阶篇/uCGUI/竖屏GUI_DEMO/uCGUI/Widget/LISTVIEW_GetNumRows.c
C
gpl-2.0
2,007
<?php /** * Pazpar2 record collection. * * PHP version 5 * * Copyright (C) Villanova University 2010. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @category VuFind2 * @package Search * @author David Maus <maus@hab.de> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org */ namespace VuFindSearch\Backend\Pazpar2\Response; use VuFindSearch\Response\AbstractRecordCollection; /** * Pazpar2 record collection. * * @category VuFind2 * @package Search * @author David Maus <maus@hab.de> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org */ class RecordCollection extends AbstractRecordCollection { /** * Raw response. * * @var array */ protected $response; /** * Constructor. * * @param int $total Total result count * @param int $offset Search offset * * @return void */ public function __construct($total = 0, $offset = 0) { $this->total = $total; $this->offset = $offset; $this->rewind(); } /** * Return total number of records found. * * @return int */ public function getTotal() { return $this->total; } /** * Return facet information. * * @return array */ public function getFacets() { return array(); } }
PetraZabickova/VuFind-2.x
module/VuFindSearch/src/VuFindSearch/Backend/Pazpar2/Response/RecordCollection.php
PHP
gpl-2.0
2,064
//# Euler.h: Vector of Euler rotation angles //# Copyright (C) 1995,1996,1997,1998,1999 //# Associated Universities, Inc. Washington DC, USA. //# //# 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., 675 Massachusetts Ave, Cambridge, MA 02139, USA. //# //# Correspondence concerning AIPS++ should be addressed as follows: //# Internet email: aips2-request@nrao.edu. //# Postal address: AIPS++ Project Office //# National Radio Astronomy Observatory //# 520 Edgemont Road //# Charlottesville, VA 22903-2475 USA //# //# $Id$ #ifndef CASA_EULER_H #define CASA_EULER_H //# Includes #include <casacore/casa/aips.h> #include <casacore/casa/Arrays/Vector.h> #include <casacore/casa/Quanta/Quantum.h> #include <utility> namespace casacore { //# NAMESPACE CASACORE - BEGIN //# Forward Declarations // <summary> // Vector of Euler rotation angles // </summary> // <use visibility=local> // <reviewed reviewer="tcornwel" date="1996/02/15" tests="tMeasMath" demos=""> // </reviewed> // <prerequisite> // <li> <linkto class=Vector>Vector</linkto> class // <li> <linkto class=Quantum>Quantum</linkto> class for units // <li> <linkto class=RotMatrix>RotMatrix</linkto> class for usage // </prerequisite> // // <etymology> // Euler angles describe the rotation of a coordinate system // </etymology> // // <synopsis> // The Euler class is a vector of three angles, together with a vector of // three signed integers. The angles describe the rotation around an axis of a // coordinate system, the integers the actual axis around which to rotate. // The integer can be 0 (do not use this angle) or 1,2,3 to indicate the // axis. // Given angles (a1,a2,a3) and axes (i1,i2,i3), the actual rotation matrix // constructed will be:<br> // R = R<sub>i3</sub>(a3).R<sub>i2</sub>(a2).R<sub>i1</sub>(a1) <br> // It has the following constructors: // <ul> // <li> Euler() creates a zero filled vector of length 3. Axes: (1,2,3) // <li> Euler(Euler) creates a copy // <li> Euler(Double, uInt, Double=0, uInt=0, Double=0, uInt=0) creates an // Euler with specified values // <li> Euler(Double, Double=0, Double=0) creates an Euler with (1,2,3) // <li> Euler(Quantity, uInt, Quantity=0, uInt=0, Quantity=0, uInt=0) creates // an Euler with specified values // <li> Euler(Quantity, Quantity=0, Quantity=0) creates an Euler with // interpretation of angle units in the Quantities // <li> Euler(<src>Quantum<Vector<Double> ></src>) creates a zero expanded // Euler from at most the first three elements of Quantity // vector; with (1,2,3) // <li> Euler(<src>Quantum<Vector<Double> >, Vector<uInt></src>) creates a // zero expanded Euler with given values // </ul> // It has a unary minus operator, which reverses the sign and order of the // three angles, and the order of the axes, to produce the Euler angles // for a rotation with opposite signs, so that <src>RotMatrix(-Euler)</src> // will generate the inverse rotation matrix as compared with // <src>RotMatrix(Euler)</src>.<br> // getAngle() functions return the Euler angles as a Quantum vector.<br> // Eulers have addition and subtraction (on the angles). Note that this // produces the correct angles for a combined rotation only if the // axes are identical.<br> // A (which) operator returns the indicated angle. Set/get functions // manipulate the axes. // </synopsis> // // <example> // <srcblock> // Quantity angle(25,"deg"); // 25 degrees // Euler eul(angle.get().getValue(),2); // rotate over axis 2 (radians) // RotMatrix rot(eul); // generates rotation matrix // </srcblock> // </example> // // <motivation> // To use generated precession and nutation results // </motivation> // // <todo asof="1995/09/04"> // </todo> class Euler { public: //# Friends // Output Euler angles friend ostream &operator<<(ostream &os, const Euler &eul); //# Constructors // Default constructor generates zero filled Double vector of length 3, with // (1,2,3) axes Euler(); // Copy constructor Euler(const Euler &other); // Copy assignment Euler &operator=(const Euler &other); // Constructs an Euler with specified angles and (1,2,3) axes Euler(Double in0, Double in1 = 0, Double in2 = 0); // Constructs an Euler with specified angles and axes Euler(Double in0, uInt ax0, Double in1 = 0, uInt ax1=0, Double in2 = 0, uInt ax2=0); // <thrown> // <li> AipsError if non-angle units used // </thrown> // Constructs an Euler from specified angle quantities // <group> Euler(const Quantity &in0); Euler(const Quantity &in0, const Quantity &in1); Euler(const Quantity &in0, const Quantity &in1, const Quantity &in2); Euler(const Quantity &in0, uInt ax0); Euler(const Quantity &in0, uInt ax0, const Quantity &in1, uInt ax1=0); Euler(const Quantity &in0, uInt ax0, const Quantity &in1, uInt ax1, const Quantity &in2, uInt ax2=0); // Constructs an Euler (zero filled) from elements of Quantity vector // <group> Euler(const Quantum<Vector<Double> > &in); Euler(const Quantum<Vector<Double> > &in, const Vector<uInt> &ax); // </group> // </group> // Destructor ~Euler(); //# Operators // The unary minus reverses the sign and order of the Euler angles Euler operator-() const; // Addition and subtraction // <group> Euler &operator+=(const Euler &right); Euler operator+(const Euler &right) const; Euler &operator-=(const Euler &right); Euler operator-(const Euler &right) const; // </group> // Return the which' angle // <group> Double &operator()(uInt which); const Double &operator()(uInt which) const; // </group> //# General Member Functions // with the optional conversion units. // <group> Quantum<Vector<Double> > getAngle() const; Quantum<Vector<Double> > getAngle(const Unit &unit) const; // </group> // Set an axis void set(uInt which, uInt ax); // Set all axes void set(uInt ax0, uInt ax1, uInt ax2); // Get an axis Int get(uInt which) const; private: //# Data // vector with 3 Euler angles (data.first) Vector<Double> euler; // Axes (data.second) Vector<Int> axes; //# Private Member Functions // The makeRad functions check and convert the input Quantities to radians // <group> static Double makeRad(const Quantity &in); static Vector<Double> makeRad(const Quantum<Vector<Double> > &in); // </group> }; } //# NAMESPACE CASACORE - END #endif
bmerry/casacore
casa/Quanta/Euler.h
C
gpl-2.0
7,087
/* * Copyright (C) Matrix Vision GmbH 2008 * * Matrix Vision mvBlueLYNX-M7 configuration file * based on Freescale's MPC8349ITX. * * SPDX-License-Identifier: GPL-2.0+ */ #ifndef __CONFIG_H #define __CONFIG_H #include <version.h> /* * High Level Configuration Options */ #define CONFIG_E300 1 #define CONFIG_MPC83xx 1 #define CONFIG_MPC834x 1 #define CONFIG_MPC8343 1 #define CONFIG_SYS_TEXT_BASE 0xFFF00000 #define CONFIG_SYS_IMMR 0xE0000000 #define CONFIG_PCI #define CONFIG_PCI_INDIRECT_BRIDGE #define CONFIG_PCI_SKIP_HOST_BRIDGE #define CONFIG_TSEC_ENET #define CONFIG_MPC8XXX_SPI #define CONFIG_HARD_SPI #define MVBLM7_MMC_CS 0x04000000 #define CONFIG_MISC_INIT_R /* I2C */ #define CONFIG_SYS_I2C #define CONFIG_SYS_I2C_FSL #define CONFIG_SYS_FSL_I2C_SPEED 100000 #define CONFIG_SYS_FSL_I2C_SLAVE 0x7F #define CONFIG_SYS_FSL_I2C_OFFSET 0x3000 #define CONFIG_SYS_FSL_I2C2_SPEED 100000 #define CONFIG_SYS_FSL_I2C2_SLAVE 0x7F #define CONFIG_SYS_FSL_I2C2_OFFSET 0x3100 /* * DDR Setup */ #undef CONFIG_SPD_EEPROM #define CONFIG_SYS_DDR_BASE 0x00000000 #define CONFIG_SYS_SDRAM_BASE CONFIG_SYS_DDR_BASE #define CONFIG_SYS_DDR_SDRAM_BASE CONFIG_SYS_DDR_BASE #define CONFIG_SYS_83XX_DDR_USES_CS0 1 #define CONFIG_SYS_MEMTEST_START (60<<20) #define CONFIG_SYS_MEMTEST_END (70<<20) #define CONFIG_VERY_BIG_RAM #define CONFIG_SYS_DDRCDR (DDRCDR_PZ_HIZ \ | DDRCDR_NZ_HIZ \ | DDRCDR_Q_DRN) /* 0x22000001 */ #define CONFIG_SYS_DDR_SDRAM_CLK_CNTL DDR_SDRAM_CLK_CNTL_CLK_ADJUST_05 #define CONFIG_SYS_DDR_SIZE 512 #define CONFIG_SYS_DDR_CS0_CONFIG 0x80014202 #define CONFIG_SYS_DDR_CS0_BNDS 0x0000003f #define CONFIG_SYS_DDR_TIMING_0 0x00260802 #define CONFIG_SYS_DDR_TIMING_1 0x3837c322 #define CONFIG_SYS_DDR_TIMING_2 0x0f9848c6 #define CONFIG_SYS_DDR_TIMING_3 0x00000000 #define CONFIG_SYS_DDR_SDRAM_CFG 0x43080008 #define CONFIG_SYS_DDR_SDRAM_CFG2 0x00401000 #define CONFIG_SYS_DDR_INTERVAL 0x02000100 #define CONFIG_SYS_DDR_MODE 0x04040242 #define CONFIG_SYS_DDR_MODE2 0x00800000 /* Flash */ #define CONFIG_SYS_FLASH_CFI #define CONFIG_FLASH_CFI_DRIVER #define CONFIG_SYS_FLASH_CFI_WIDTH FLASH_CFI_16BIT #define CONFIG_SYS_FLASH_BASE 0xFF800000 #define CONFIG_SYS_FLASH_SIZE 8 #define CONFIG_SYS_FLASH_EMPTY_INFO #define CONFIG_SYS_FLASH_ERASE_TOUT 60000 #define CONFIG_SYS_FLASH_WRITE_TOUT 500 #define CONFIG_SYS_MAX_FLASH_BANKS 1 #define CONFIG_SYS_MAX_FLASH_SECT 256 #define CONFIG_SYS_BR0_PRELIM (CONFIG_SYS_FLASH_BASE \ | BR_PS_16 \ | BR_MS_GPCM \ | BR_V) #define CONFIG_SYS_OR0_PRELIM (MEG_TO_AM(CONFIG_SYS_FLASH_SIZE) \ | OR_UPM_XAM \ | OR_GPCM_CSNT \ | OR_GPCM_ACS_DIV2 \ | OR_GPCM_XACS \ | OR_GPCM_SCY_15 \ | OR_GPCM_TRLX_SET \ | OR_GPCM_EHTR_SET \ | OR_GPCM_EAD) #define CONFIG_SYS_LBLAWBAR0_PRELIM CONFIG_SYS_FLASH_BASE #define CONFIG_SYS_LBLAWAR0_PRELIM (LBLAWAR_EN | LBLAWAR_8MB) /* * U-Boot memory configuration */ #define CONFIG_SYS_MONITOR_BASE CONFIG_SYS_TEXT_BASE #undef CONFIG_SYS_RAMBOOT #define CONFIG_SYS_INIT_RAM_LOCK #define CONFIG_SYS_INIT_RAM_ADDR 0xFD000000 /* Initial RAM address */ #define CONFIG_SYS_INIT_RAM_SIZE 0x1000 /* Size of used area in RAM*/ #define CONFIG_SYS_GBL_DATA_OFFSET \ (CONFIG_SYS_INIT_RAM_SIZE - GENERATED_GBL_DATA_SIZE) #define CONFIG_SYS_INIT_SP_OFFSET CONFIG_SYS_GBL_DATA_OFFSET /* CONFIG_SYS_MONITOR_LEN must be a multiple of CONFIG_ENV_SECT_SIZE */ #define CONFIG_SYS_MONITOR_LEN (512 * 1024) #define CONFIG_SYS_MALLOC_LEN (512 * 1024) /* * Local Bus LCRR and LBCR regs * LCRR: DLL bypass, Clock divider is 4 * External Local Bus rate is * CLKIN * HRCWL_CSB_TO_CLKIN / HRCWL_LCL_BUS_TO_SCB_CLK / LCRR_CLKDIV */ #define CONFIG_SYS_LCRR_DBYP LCRR_DBYP #define CONFIG_SYS_LCRR_CLKDIV LCRR_CLKDIV_4 #define CONFIG_SYS_LBC_LBCR 0x00000000 /* LB sdram refresh timer, about 6us */ #define CONFIG_SYS_LBC_LSRT 0x32000000 /* LB refresh timer prescal, 266MHz/32*/ #define CONFIG_SYS_LBC_MRTPR 0x20000000 /* * Serial Port */ #define CONFIG_CONS_INDEX 1 #define CONFIG_SYS_NS16550 #define CONFIG_SYS_NS16550_SERIAL #define CONFIG_SYS_NS16550_REG_SIZE 1 #define CONFIG_SYS_NS16550_CLK get_bus_freq(0) #define CONFIG_SYS_BAUDRATE_TABLE \ {300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 115200} #define CONFIG_CONSOLE ttyS0 #define CONFIG_BAUDRATE 115200 #define CONFIG_SYS_NS16550_COM1 (CONFIG_SYS_IMMR + 0x4500) #define CONFIG_SYS_NS16550_COM2 (CONFIG_SYS_IMMR + 0x4600) /* pass open firmware flat tree */ #define CONFIG_OF_LIBFDT 1 #define CONFIG_OF_BOARD_SETUP 1 #define CONFIG_OF_STDOUT_VIA_ALIAS 1 #define MV_DTB_NAME "mvblm7.dtb" /* * PCI */ #define CONFIG_SYS_PCI1_MEM_BASE 0x80000000 #define CONFIG_SYS_PCI1_MEM_PHYS CONFIG_SYS_PCI1_MEM_BASE #define CONFIG_SYS_PCI1_MEM_SIZE 0x10000000 #define CONFIG_SYS_PCI1_MMIO_BASE \ (CONFIG_SYS_PCI1_MEM_BASE + CONFIG_SYS_PCI1_MEM_SIZE) #define CONFIG_SYS_PCI1_MMIO_PHYS CONFIG_SYS_PCI1_MMIO_BASE #define CONFIG_SYS_PCI1_MMIO_SIZE 0x10000000 #define CONFIG_SYS_PCI1_IO_BASE 0x00000000 #define CONFIG_SYS_PCI1_IO_PHYS 0xE2000000 #define CONFIG_SYS_PCI1_IO_SIZE 0x01000000 #define CONFIG_NET_RETRY_COUNT 3 #define CONFIG_PCI_66M #define CONFIG_83XX_CLKIN 66666667 #define CONFIG_PCI_PNP #define CONFIG_PCI_SCAN_SHOW /* TSEC */ #define CONFIG_GMII #define CONFIG_SYS_VSC8601_SKEWFIX #define CONFIG_SYS_VSC8601_SKEW_TX 3 #define CONFIG_SYS_VSC8601_SKEW_RX 3 #define CONFIG_TSEC1 #define CONFIG_TSEC2 #define CONFIG_HAS_ETH0 #define CONFIG_TSEC1_NAME "TSEC0" #define CONFIG_FEC1_PHY_NORXERR #define CONFIG_SYS_TSEC1_OFFSET 0x24000 #define CONFIG_SYS_TSEC1 (CONFIG_SYS_IMMR+CONFIG_SYS_TSEC1_OFFSET) #define TSEC1_PHY_ADDR 0x10 #define TSEC1_PHYIDX 0 #define TSEC1_FLAGS (TSEC_GIGABIT|TSEC_REDUCED) #define CONFIG_HAS_ETH1 #define CONFIG_TSEC2_NAME "TSEC1" #define CONFIG_FEC2_PHY_NORXERR #define CONFIG_SYS_TSEC2_OFFSET 0x25000 #define CONFIG_SYS_TSEC2 (CONFIG_SYS_IMMR+CONFIG_SYS_TSEC2_OFFSET) #define TSEC2_PHY_ADDR 0x11 #define TSEC2_PHYIDX 0 #define TSEC2_FLAGS (TSEC_GIGABIT|TSEC_REDUCED) #define CONFIG_ETHPRIME "TSEC0" #define CONFIG_BOOTP_VENDOREX #define CONFIG_BOOTP_SUBNETMASK #define CONFIG_BOOTP_GATEWAY #define CONFIG_BOOTP_DNS #define CONFIG_BOOTP_DNS2 #define CONFIG_BOOTP_HOSTNAME #define CONFIG_BOOTP_BOOTFILESIZE #define CONFIG_BOOTP_BOOTPATH #define CONFIG_BOOTP_NTPSERVER #define CONFIG_BOOTP_RANDOM_DELAY #define CONFIG_BOOTP_SEND_HOSTNAME /* USB */ #define CONFIG_SYS_USB_HOST #define CONFIG_USB_EHCI #define CONFIG_USB_EHCI_FSL #define CONFIG_HAS_FSL_DR_USB #define CONFIG_EHCI_HCD_INIT_AFTER_RESET /* * Environment */ #undef CONFIG_SYS_FLASH_PROTECTION #define CONFIG_ENV_OVERWRITE #define CONFIG_ENV_IS_IN_FLASH 1 #define CONFIG_ENV_ADDR 0xFF800000 #define CONFIG_ENV_SIZE 0x2000 #define CONFIG_ENV_SECT_SIZE 0x2000 #define CONFIG_ENV_ADDR_REDUND (CONFIG_ENV_ADDR+CONFIG_ENV_SIZE) #define CONFIG_ENV_SIZE_REDUND CONFIG_ENV_SIZE #define CONFIG_LOADS_ECHO #define CONFIG_SYS_LOADS_BAUD_CHANGE /* * Command line configuration. */ #include <config_cmd_default.h> #define CONFIG_CMD_CACHE #define CONFIG_CMD_IRQ #define CONFIG_CMD_NET #define CONFIG_CMD_MII #define CONFIG_CMD_PING #define CONFIG_CMD_DHCP #define CONFIG_CMD_SDRAM #define CONFIG_CMD_PCI #define CONFIG_CMD_I2C #define CONFIG_CMD_FPGA #define CONFIG_CMD_USB #define CONFIG_DOS_PARTITION #undef CONFIG_WATCHDOG /* * Miscellaneous configurable options */ #define CONFIG_SYS_LONGHELP #define CONFIG_CMDLINE_EDITING #define CONFIG_AUTO_COMPLETE /* add autocompletion support */ #define CONFIG_SYS_HUSH_PARSER /* default load address */ #define CONFIG_SYS_LOAD_ADDR 0x2000000 /* default location for tftp and bootm */ #define CONFIG_LOADADDR 0x200000 #define CONFIG_SYS_PROMPT "mvBL-M7> " #define CONFIG_SYS_CBSIZE 256 #define CONFIG_SYS_PBSIZE \ (CONFIG_SYS_CBSIZE + sizeof(CONFIG_SYS_PROMPT) + 16) #define CONFIG_SYS_MAXARGS 16 #define CONFIG_SYS_BARGSIZE CONFIG_SYS_CBSIZE /* * For booting Linux, the board info and command line data * have to be in the first 256 MB of memory, since this is * the maximum mapped by the Linux kernel during initialization. */ /* Initial Memory map for Linux*/ #define CONFIG_SYS_BOOTMAPSZ (256 << 20) #define CONFIG_SYS_HRCW_LOW 0x0 #define CONFIG_SYS_HRCW_HIGH 0x0 /* * System performance */ #define CONFIG_SYS_ACR_PIPE_DEP 3 /* Arbiter pipeline depth (0-3) */ #define CONFIG_SYS_ACR_RPTCNT 3 /* Arbiter repeat count (0-7) */ #define CONFIG_SYS_SPCR_TSEC1EP 3 /* TSEC1 emergency priority (0-3) */ #define CONFIG_SYS_SPCR_TSEC2EP 3 /* TSEC2 emergency priority (0-3) */ /* clocking */ #define CONFIG_SYS_SCCR_ENCCM 0 #define CONFIG_SYS_SCCR_USBMPHCM 0 #define CONFIG_SYS_SCCR_USBDRCM 2 #define CONFIG_SYS_SCCR_TSEC1CM 1 #define CONFIG_SYS_SCCR_TSEC2CM 1 #define CONFIG_SYS_SICRH 0x1fef0003 #define CONFIG_SYS_SICRL (SICRL_LDP_A | SICRL_USB1 | SICRL_USB0) #define CONFIG_SYS_HID0_INIT 0x000000000 #define CONFIG_SYS_HID0_FINAL (CONFIG_SYS_HID0_INIT | \ HID0_ENABLE_INSTRUCTION_CACHE) #define CONFIG_SYS_HID2 HID2_HBE #define CONFIG_HIGH_BATS 1 /* DDR */ #define CONFIG_SYS_IBAT0L (CONFIG_SYS_SDRAM_BASE \ | BATL_PP_RW \ | BATL_MEMCOHERENCE) #define CONFIG_SYS_IBAT0U (CONFIG_SYS_SDRAM_BASE \ | BATU_BL_256M \ | BATU_VS \ | BATU_VP) /* PCI */ #define CONFIG_SYS_IBAT1L (CONFIG_SYS_PCI1_MEM_BASE \ | BATL_PP_RW \ | BATL_MEMCOHERENCE) #define CONFIG_SYS_IBAT1U (CONFIG_SYS_PCI1_MEM_BASE \ | BATU_BL_256M \ | BATU_VS \ | BATU_VP) #define CONFIG_SYS_IBAT2L (CONFIG_SYS_PCI1_MMIO_BASE \ | BATL_PP_RW \ | BATL_CACHEINHIBIT \ | BATL_GUARDEDSTORAGE) #define CONFIG_SYS_IBAT2U (CONFIG_SYS_PCI1_MMIO_BASE \ | BATU_BL_256M \ | BATU_VS \ | BATU_VP) /* no PCI2 */ #define CONFIG_SYS_IBAT3L 0 #define CONFIG_SYS_IBAT3U 0 #define CONFIG_SYS_IBAT4L 0 #define CONFIG_SYS_IBAT4U 0 /* IMMRBAR @ 0xE0000000, PCI IO @ 0xE2000000 & BCSR @ 0xE2400000 */ #define CONFIG_SYS_IBAT5L (CONFIG_SYS_IMMR \ | BATL_PP_RW \ | BATL_CACHEINHIBIT \ | BATL_GUARDEDSTORAGE) #define CONFIG_SYS_IBAT5U (CONFIG_SYS_IMMR \ | BATU_BL_256M \ | BATU_VS \ | BATU_VP) /* stack in DCACHE 0xFDF00000 & FLASH @ 0xFF800000 */ #define CONFIG_SYS_IBAT6L (0xF0000000 \ | BATL_PP_RW \ | BATL_MEMCOHERENCE \ | BATL_GUARDEDSTORAGE) #define CONFIG_SYS_IBAT6U (0xF0000000 \ | BATU_BL_256M \ | BATU_VS \ | BATU_VP) #define CONFIG_SYS_IBAT7L 0 #define CONFIG_SYS_IBAT7U 0 #define CONFIG_SYS_DBAT0L CONFIG_SYS_IBAT0L #define CONFIG_SYS_DBAT0U CONFIG_SYS_IBAT0U #define CONFIG_SYS_DBAT1L CONFIG_SYS_IBAT1L #define CONFIG_SYS_DBAT1U CONFIG_SYS_IBAT1U #define CONFIG_SYS_DBAT2L CONFIG_SYS_IBAT2L #define CONFIG_SYS_DBAT2U CONFIG_SYS_IBAT2U #define CONFIG_SYS_DBAT3L CONFIG_SYS_IBAT3L #define CONFIG_SYS_DBAT3U CONFIG_SYS_IBAT3U #define CONFIG_SYS_DBAT4L CONFIG_SYS_IBAT4L #define CONFIG_SYS_DBAT4U CONFIG_SYS_IBAT4U #define CONFIG_SYS_DBAT5L CONFIG_SYS_IBAT5L #define CONFIG_SYS_DBAT5U CONFIG_SYS_IBAT5U #define CONFIG_SYS_DBAT6L CONFIG_SYS_IBAT6L #define CONFIG_SYS_DBAT6U CONFIG_SYS_IBAT6U #define CONFIG_SYS_DBAT7L CONFIG_SYS_IBAT7L #define CONFIG_SYS_DBAT7U CONFIG_SYS_IBAT7U /* * Environment Configuration */ #define CONFIG_ENV_OVERWRITE #define CONFIG_NETDEV eth0 /* Default path and filenames */ #define CONFIG_BOOTDELAY 5 #define CONFIG_AUTOBOOT_KEYED #define CONFIG_AUTOBOOT_STOP_STR "s" #define CONFIG_ZERO_BOOTDELAY_CHECK #define CONFIG_RESET_TO_RETRY 1000 #define MV_CI "mvBL-M7" #define MV_VCI "mvBL-M7" #define MV_FPGA_DATA 0xfff40000 #define MV_FPGA_SIZE 0 #define MV_KERNEL_ADDR 0xff810000 #define MV_INITRD_ADDR 0xffb00000 #define MV_SCRIPT_ADDR 0xff804000 #define MV_SCRIPT_ADDR2 0xff806000 #define MV_DTB_ADDR 0xff808000 #define MV_INITRD_LENGTH 0x00400000 #define CONFIG_SHOW_BOOT_PROGRESS 1 #define MV_KERNEL_ADDR_RAM 0x00100000 #define MV_DTB_ADDR_RAM 0x00600000 #define MV_INITRD_ADDR_RAM 0x01000000 #define CONFIG_BOOTCOMMAND "if imi ${script_addr}; " \ "then source ${script_addr}; " \ "else source ${script_addr2}; " \ "fi;" #define CONFIG_BOOTARGS "root=/dev/ram ro rootfstype=squashfs" #define CONFIG_EXTRA_ENV_SETTINGS \ "console_nr=0\0" \ "baudrate=" __stringify(CONFIG_BAUDRATE) "\0" \ "stdin=serial\0" \ "stdout=serial\0" \ "stderr=serial\0" \ "fpga=0\0" \ "fpgadata=" __stringify(MV_FPGA_DATA) "\0" \ "fpgadatasize=" __stringify(MV_FPGA_SIZE) "\0" \ "script_addr=" __stringify(MV_SCRIPT_ADDR) "\0" \ "script_addr2=" __stringify(MV_SCRIPT_ADDR2) "\0" \ "mv_kernel_addr=" __stringify(MV_KERNEL_ADDR) "\0" \ "mv_kernel_addr_ram=" __stringify(MV_KERNEL_ADDR_RAM) "\0" \ "mv_initrd_addr=" __stringify(MV_INITRD_ADDR) "\0" \ "mv_initrd_addr_ram=" __stringify(MV_INITRD_ADDR_RAM) "\0" \ "mv_initrd_length=" __stringify(MV_INITRD_LENGTH) "\0" \ "mv_dtb_addr=" __stringify(MV_DTB_ADDR) "\0" \ "mv_dtb_addr_ram=" __stringify(MV_DTB_ADDR_RAM) "\0" \ "dtb_name=" __stringify(MV_DTB_NAME) "\0" \ "mv_version=" U_BOOT_VERSION "\0" \ "dhcp_client_id=" MV_CI "\0" \ "dhcp_vendor-class-identifier=" MV_VCI "\0" \ "netretry=no\0" \ "use_static_ipaddr=no\0" \ "static_ipaddr=192.168.90.10\0" \ "static_netmask=255.255.255.0\0" \ "static_gateway=0.0.0.0\0" \ "initrd_name=uInitrd.mvBL-M7-rfs\0" \ "zcip=no\0" \ "netboot=yes\0" \ "mvtest=Ff\0" \ "tried_bootfromflash=no\0" \ "tried_bootfromnet=no\0" \ "bootfile=mvblm72625.boot\0" \ "use_dhcp=yes\0" \ "gev_start=yes\0" \ "mvbcdma_debug=0\0" \ "mvbcia_debug=0\0" \ "propdev_debug=0\0" \ "gevss_debug=0\0" \ "watchdog=0\0" \ "usb_dr_mode=host\0" \ "sensor_cnt=2\0" \ "" #define CONFIG_FPGA_COUNT 1 #define CONFIG_FPGA #define CONFIG_FPGA_ALTERA #define CONFIG_FPGA_CYCLON2 #endif
vkrmsngh/new_pro
u-boot/include/configs/MVBLM7.h
C
gpl-2.0
13,807
/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. Copyright (c) 2008, 2012, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** @file Low level functions for storing data to be send to the MySQL client. The actual communction is handled by the net_xxx functions in net_serv.cc */ #ifdef USE_PRAGMA_IMPLEMENTATION #pragma implementation // gcc: Class implementation #endif #include <my_global.h> #include "sql_priv.h" #include "unireg.h" // REQUIRED: for other includes #include "protocol.h" #include "sql_class.h" // THD #include <stdarg.h> static const unsigned int PACKET_BUFFER_EXTRA_ALLOC= 1024; /* Declared non-static only because of the embedded library. */ bool net_send_error_packet(THD *, uint, const char *, const char *); /* Declared non-static only because of the embedded library. */ bool net_send_ok(THD *, uint, uint, ulonglong, ulonglong, const char *); /* Declared non-static only because of the embedded library. */ bool net_send_eof(THD *thd, uint server_status, uint statement_warn_count); #ifndef EMBEDDED_LIBRARY static bool write_eof_packet(THD *, NET *, uint, uint); #endif #ifndef EMBEDDED_LIBRARY bool Protocol::net_store_data(const uchar *from, size_t length) #else bool Protocol_binary::net_store_data(const uchar *from, size_t length) #endif { ulong packet_length=packet->length(); /* The +9 comes from that strings of length longer than 16M require 9 bytes to be stored (see net_store_length). */ if (packet_length+9+length > packet->alloced_length() && packet->realloc(packet_length+9+length)) return 1; uchar *to= net_store_length((uchar*) packet->ptr()+packet_length, length); memcpy(to,from,length); packet->length((uint) (to+length-(uchar*) packet->ptr())); return 0; } /* net_store_data_cs() - extended version with character set conversion. It is optimized for short strings whose length after conversion is garanteed to be less than 251, which accupies exactly one byte to store length. It allows not to use the "convert" member as a temporary buffer, conversion is done directly to the "packet" member. The limit 251 is good enough to optimize send_result_set_metadata() because column, table, database names fit into this limit. */ #ifndef EMBEDDED_LIBRARY bool Protocol::net_store_data_cs(const uchar *from, size_t length, CHARSET_INFO *from_cs, CHARSET_INFO *to_cs) #else bool Protocol_binary::net_store_data_cs(const uchar *from, size_t length, CHARSET_INFO *from_cs, CHARSET_INFO *to_cs) #endif { uint dummy_errors; /* Calculate maxumum possible result length */ uint conv_length= to_cs->mbmaxlen * length / from_cs->mbminlen; if (conv_length > 250) { /* For strings with conv_length greater than 250 bytes we don't know how many bytes we will need to store length: one or two, because we don't know result length until conversion is done. For example, when converting from utf8 (mbmaxlen=3) to latin1, conv_length=300 means that the result length can vary between 100 to 300. length=100 needs one byte, length=300 needs to bytes. Thus conversion directly to "packet" is not worthy. Let's use "convert" as a temporary buffer. */ return (convert->copy((const char*) from, length, from_cs, to_cs, &dummy_errors) || net_store_data((const uchar*) convert->ptr(), convert->length())); } ulong packet_length= packet->length(); ulong new_length= packet_length + conv_length + 1; if (new_length > packet->alloced_length() && packet->realloc(new_length)) return 1; char *length_pos= (char*) packet->ptr() + packet_length; char *to= length_pos + 1; to+= copy_and_convert(to, conv_length, to_cs, (const char*) from, length, from_cs, &dummy_errors); net_store_length((uchar*) length_pos, to - length_pos - 1); packet->length((uint) (to - packet->ptr())); return 0; } /** Send a error string to client. Design note: net_printf_error and net_send_error are low-level functions that shall be used only when a new connection is being established or at server startup. For SIGNAL/RESIGNAL and GET DIAGNOSTICS functionality it's critical that every error that can be intercepted is issued in one place only, my_message_sql. @param thd Thread handler @param sql_errno The error code to send @param err A pointer to the error message @return @retval FALSE The message was sent to the client @retval TRUE An error occurred and the message wasn't sent properly */ bool net_send_error(THD *thd, uint sql_errno, const char *err, const char* sqlstate) { bool error; DBUG_ENTER("net_send_error"); DBUG_ASSERT(!thd->spcont); DBUG_ASSERT(sql_errno); DBUG_ASSERT(err); DBUG_PRINT("enter",("sql_errno: %d err: %s", sql_errno, err)); if (sqlstate == NULL) sqlstate= mysql_errno_to_sqlstate(sql_errno); /* It's one case when we can push an error even though there is an OK or EOF already. */ thd->get_stmt_da()->set_overwrite_status(true); /* Abort multi-result sets */ thd->server_status&= ~SERVER_MORE_RESULTS_EXISTS; error= net_send_error_packet(thd, sql_errno, err, sqlstate); thd->get_stmt_da()->set_overwrite_status(false); DBUG_RETURN(error); } /** Return ok to the client. The ok packet has the following structure: - 0 : Marker (1 byte) - affected_rows : Stored in 1-9 bytes - id : Stored in 1-9 bytes - server_status : Copy of thd->server_status; Can be used by client to check if we are inside an transaction. New in 4.0 protocol - warning_count : Stored in 2 bytes; New in 4.1 protocol - message : Stored as packed length (1-9 bytes) + message. Is not stored if no message. @param thd Thread handler @param server_status The server status @param statement_warn_count Total number of warnings @param affected_rows Number of rows changed by statement @param id Auto_increment id for first row (if used) @param message Message to send to the client (Used by mysql_status) @return @retval FALSE The message was successfully sent @retval TRUE An error occurred and the messages wasn't sent properly */ #ifndef EMBEDDED_LIBRARY bool net_send_ok(THD *thd, uint server_status, uint statement_warn_count, ulonglong affected_rows, ulonglong id, const char *message) { NET *net= &thd->net; uchar buff[MYSQL_ERRMSG_SIZE+10],*pos; bool error= FALSE; DBUG_ENTER("net_send_ok"); if (! net->vio) // hack for re-parsing queries { DBUG_PRINT("info", ("vio present: NO")); DBUG_RETURN(FALSE); } buff[0]=0; // No fields pos=net_store_length(buff+1,affected_rows); pos=net_store_length(pos, id); if (thd->client_capabilities & CLIENT_PROTOCOL_41) { DBUG_PRINT("info", ("affected_rows: %lu id: %lu status: %u warning_count: %u", (ulong) affected_rows, (ulong) id, (uint) (server_status & 0xffff), (uint) statement_warn_count)); int2store(pos, server_status); pos+=2; /* We can only return up to 65535 warnings in two bytes */ uint tmp= MY_MIN(statement_warn_count, 65535); int2store(pos, tmp); pos+= 2; } else if (net->return_status) // For 4.0 protocol { int2store(pos, server_status); pos+=2; } thd->get_stmt_da()->set_overwrite_status(true); if (message && message[0]) pos= net_store_data(pos, (uchar*) message, strlen(message)); error= my_net_write(net, buff, (size_t) (pos-buff)); if (!error) error= net_flush(net); thd->get_stmt_da()->set_overwrite_status(false); DBUG_PRINT("info", ("OK sent, so no more error sending allowed")); DBUG_RETURN(error); } static uchar eof_buff[1]= { (uchar) 254 }; /* Marker for end of fields */ /** Send eof (= end of result set) to the client. The eof packet has the following structure: - 254 : Marker (1 byte) - warning_count : Stored in 2 bytes; New in 4.1 protocol - status_flag : Stored in 2 bytes; For flags like SERVER_MORE_RESULTS_EXISTS. Note that the warning count will not be sent if 'no_flush' is set as we don't want to report the warning count until all data is sent to the client. @param thd Thread handler @param server_status The server status @param statement_warn_count Total number of warnings @return @retval FALSE The message was successfully sent @retval TRUE An error occurred and the message wasn't sent properly */ bool net_send_eof(THD *thd, uint server_status, uint statement_warn_count) { NET *net= &thd->net; bool error= FALSE; DBUG_ENTER("net_send_eof"); /* Set to TRUE if no active vio, to work well in case of --init-file */ if (net->vio != 0) { thd->get_stmt_da()->set_overwrite_status(true); error= write_eof_packet(thd, net, server_status, statement_warn_count); if (!error) error= net_flush(net); thd->get_stmt_da()->set_overwrite_status(false); DBUG_PRINT("info", ("EOF sent, so no more error sending allowed")); } DBUG_RETURN(error); } /** Format EOF packet according to the current protocol and write it to the network output buffer. @param thd The thread handler @param net The network handler @param server_status The server status @param statement_warn_count The number of warnings @return @retval FALSE The message was sent successfully @retval TRUE An error occurred and the messages wasn't sent properly */ static bool write_eof_packet(THD *thd, NET *net, uint server_status, uint statement_warn_count) { bool error; if (thd->client_capabilities & CLIENT_PROTOCOL_41) { uchar buff[5]; /* Don't send warn count during SP execution, as the warn_list is cleared between substatements, and mysqltest gets confused */ uint tmp= MY_MIN(statement_warn_count, 65535); buff[0]= 254; int2store(buff+1, tmp); /* The following test should never be true, but it's better to do it because if 'is_fatal_error' is set the server is not going to execute other queries (see the if test in dispatch_command / COM_QUERY) */ if (thd->is_fatal_error) server_status&= ~SERVER_MORE_RESULTS_EXISTS; int2store(buff + 3, server_status); error= my_net_write(net, buff, 5); } else error= my_net_write(net, eof_buff, 1); return error; } /** @param thd Thread handler @param sql_errno The error code to send @param err A pointer to the error message @return @retval FALSE The message was successfully sent @retval TRUE An error occurred and the messages wasn't sent properly */ bool net_send_error_packet(THD *thd, uint sql_errno, const char *err, const char* sqlstate) { NET *net= &thd->net; uint length; /* buff[]: sql_errno:2 + ('#':1 + SQLSTATE_LENGTH:5) + MYSQL_ERRMSG_SIZE:512 */ uint error; char converted_err[MYSQL_ERRMSG_SIZE]; char buff[2+1+SQLSTATE_LENGTH+MYSQL_ERRMSG_SIZE], *pos; DBUG_ENTER("send_error_packet"); if (net->vio == 0) { if (thd->bootstrap) { /* In bootstrap it's ok to print on stderr */ fprintf(stderr,"ERROR: %d %s\n",sql_errno,err); } DBUG_RETURN(FALSE); } int2store(buff,sql_errno); pos= buff+2; if (thd->client_capabilities & CLIENT_PROTOCOL_41) { /* The first # is to make the protocol backward compatible */ buff[2]= '#'; pos= strmov(buff+3, sqlstate); } convert_error_message(converted_err, sizeof(converted_err), thd->variables.character_set_results, err, strlen(err), system_charset_info, &error); /* Converted error message is always null-terminated. */ length= (uint) (strmake(pos, converted_err, MYSQL_ERRMSG_SIZE - 1) - buff); DBUG_RETURN(net_write_command(net,(uchar) 255, (uchar*) "", 0, (uchar*) buff, length)); } #endif /* EMBEDDED_LIBRARY */ /** Faster net_store_length when we know that length is less than 65536. We keep a separate version for that range because it's widely used in libmysql. uint is used as agrument type because of MySQL type conventions: - uint for 0..65536 - ulong for 0..4294967296 - ulonglong for bigger numbers. */ static uchar *net_store_length_fast(uchar *packet, uint length) { if (length < 251) { *packet=(uchar) length; return packet+1; } *packet++=252; int2store(packet,(uint) length); return packet+2; } /** Send the status of the current statement execution over network. @param thd in fact, carries two parameters, NET for the transport and Diagnostics_area as the source of status information. In MySQL, there are two types of SQL statements: those that return a result set and those that return status information only. If a statement returns a result set, it consists of 3 parts: - result set meta-data - variable number of result set rows (can be 0) - followed and terminated by EOF or ERROR packet Once the client has seen the meta-data information, it always expects an EOF or ERROR to terminate the result set. If ERROR is received, the result set rows are normally discarded (this is up to the client implementation, libmysql at least does discard them). EOF, on the contrary, means "successfully evaluated the entire result set". Since we don't know how many rows belong to a result set until it's evaluated, EOF/ERROR is the indicator of the end of the row stream. Note, that we can not buffer result set rows on the server -- there may be an arbitrary number of rows. But we do buffer the last packet (EOF/ERROR) in the Diagnostics_area and delay sending it till the very end of execution (here), to be able to change EOF to an ERROR if commit failed or some other error occurred during the last cleanup steps taken after execution. A statement that does not return a result set doesn't send result set meta-data either. Instead it returns one of: - OK packet - ERROR packet. Similarly to the EOF/ERROR of the previous statement type, OK/ERROR packet is "buffered" in the diagnostics area and sent to the client in the end of statement. @note This method defines a template, but delegates actual sending of data to virtual Protocol::send_{ok,eof,error}. This allows for implementation of protocols that "intercept" ok/eof/error messages, and store them in memory, etc, instead of sending to the client. @pre The diagnostics area is assigned or disabled. It can not be empty -- we assume that every SQL statement or COM_* command generates OK, ERROR, or EOF status. @post The status information is encoded to protocol format and sent to the client. @return We conventionally return void, since the only type of error that can happen here is a NET (transport) error, and that one will become visible when we attempt to read from the NET the next command. Diagnostics_area::is_sent is set for debugging purposes only. */ void Protocol::end_statement() { DBUG_ENTER("Protocol::end_statement"); DBUG_ASSERT(! thd->get_stmt_da()->is_sent()); bool error= FALSE; /* Can not be true, but do not take chances in production. */ if (thd->get_stmt_da()->is_sent()) DBUG_VOID_RETURN; switch (thd->get_stmt_da()->status()) { case Diagnostics_area::DA_ERROR: /* The query failed, send error to log and abort bootstrap. */ error= send_error(thd->get_stmt_da()->sql_errno(), thd->get_stmt_da()->message(), thd->get_stmt_da()->get_sqlstate()); break; case Diagnostics_area::DA_EOF: error= send_eof(thd->server_status, thd->get_stmt_da()->statement_warn_count()); break; case Diagnostics_area::DA_OK: error= send_ok(thd->server_status, thd->get_stmt_da()->statement_warn_count(), thd->get_stmt_da()->affected_rows(), thd->get_stmt_da()->last_insert_id(), thd->get_stmt_da()->message()); break; case Diagnostics_area::DA_DISABLED: break; case Diagnostics_area::DA_EMPTY: default: DBUG_ASSERT(0); error= send_ok(thd->server_status, 0, 0, 0, NULL); break; } if (!error) thd->get_stmt_da()->set_is_sent(true); DBUG_VOID_RETURN; } /** A default implementation of "OK" packet response to the client. Currently this implementation is re-used by both network-oriented protocols -- the binary and text one. They do not differ in their OK packet format, which allows for a significant simplification on client side. */ bool Protocol::send_ok(uint server_status, uint statement_warn_count, ulonglong affected_rows, ulonglong last_insert_id, const char *message) { DBUG_ENTER("Protocol::send_ok"); const bool retval= net_send_ok(thd, server_status, statement_warn_count, affected_rows, last_insert_id, message); DBUG_RETURN(retval); } /** A default implementation of "EOF" packet response to the client. Binary and text protocol do not differ in their EOF packet format. */ bool Protocol::send_eof(uint server_status, uint statement_warn_count) { DBUG_ENTER("Protocol::send_eof"); const bool retval= net_send_eof(thd, server_status, statement_warn_count); DBUG_RETURN(retval); } /** A default implementation of "ERROR" packet response to the client. Binary and text protocol do not differ in ERROR packet format. */ bool Protocol::send_error(uint sql_errno, const char *err_msg, const char *sql_state) { DBUG_ENTER("Protocol::send_error"); const bool retval= net_send_error_packet(thd, sql_errno, err_msg, sql_state); DBUG_RETURN(retval); } /** Send a progress report to the client What we send is: header (255,255,255,1) stage, max_stage as on byte integers percentage withing the stage as percentage*1000 (that is, ratio*100000) as a 3 byte integer proc_info as a string */ const uchar progress_header[2]= {(uchar) 255, (uchar) 255 }; void net_send_progress_packet(THD *thd) { uchar buff[200], *pos; const char *proc_info= thd->proc_info ? thd->proc_info : ""; uint length= strlen(proc_info); ulonglong progress; DBUG_ENTER("net_send_progress_packet"); if (unlikely(!thd->net.vio)) DBUG_VOID_RETURN; // Socket is closed pos= buff; /* Store number of strings first. This allows us to later expand the progress indicator if needed. */ *pos++= (uchar) 1; // Number of strings *pos++= (uchar) thd->progress.stage + 1; /* We have the MY_MAX() here to avoid problems if max_stage is not set, which may happen during automatic repair of table */ *pos++= (uchar) MY_MAX(thd->progress.max_stage, thd->progress.stage + 1); progress= 0; if (thd->progress.max_counter) progress= 100000ULL * thd->progress.counter / thd->progress.max_counter; int3store(pos, progress); // Between 0 & 100000 pos+= 3; pos= net_store_data(pos, (const uchar*) proc_info, MY_MIN(length, sizeof(buff)-7)); net_write_command(&thd->net, (uchar) 255, progress_header, sizeof(progress_header), (uchar*) buff, (uint) (pos - buff)); DBUG_VOID_RETURN; } /**************************************************************************** Functions used by the protocol functions (like net_send_ok) to store strings and numbers in the header result packet. ****************************************************************************/ /* The following will only be used for short strings < 65K */ uchar *net_store_data(uchar *to, const uchar *from, size_t length) { to=net_store_length_fast(to,length); memcpy(to,from,length); return to+length; } uchar *net_store_data(uchar *to,int32 from) { char buff[20]; uint length=(uint) (int10_to_str(from,buff,10)-buff); to=net_store_length_fast(to,length); memcpy(to,buff,length); return to+length; } uchar *net_store_data(uchar *to,longlong from) { char buff[22]; uint length=(uint) (longlong10_to_str(from,buff,10)-buff); to=net_store_length_fast(to,length); memcpy(to,buff,length); return to+length; } /***************************************************************************** Default Protocol functions *****************************************************************************/ void Protocol::init(THD *thd_arg) { thd=thd_arg; packet= &thd->packet; convert= &thd->convert_buffer; #ifndef DBUG_OFF field_types= 0; #endif } /** Finish the result set with EOF packet, as is expected by the client, if there is an error evaluating the next row and a continue handler for the error. */ void Protocol::end_partial_result_set(THD *thd_arg) { net_send_eof(thd_arg, thd_arg->server_status, 0 /* no warnings, we're inside SP */); } bool Protocol::flush() { #ifndef EMBEDDED_LIBRARY bool error; thd->get_stmt_da()->set_overwrite_status(true); error= net_flush(&thd->net); thd->get_stmt_da()->set_overwrite_status(false); return error; #else return 0; #endif } #ifndef EMBEDDED_LIBRARY /** Send name and type of result to client. Sum fields has table name empty and field_name. @param THD Thread data object @param list List of items to send to client @param flag Bit mask with the following functions: - 1 send number of rows - 2 send default values - 4 don't write eof packet @retval 0 ok @retval 1 Error (Note that in this case the error is not sent to the client) */ bool Protocol::send_result_set_metadata(List<Item> *list, uint flags) { List_iterator_fast<Item> it(*list); Item *item; uchar buff[MAX_FIELD_WIDTH]; String tmp((char*) buff,sizeof(buff),&my_charset_bin); Protocol_text prot(thd); String *local_packet= prot.storage_packet(); CHARSET_INFO *thd_charset= thd->variables.character_set_results; DBUG_ENTER("Protocol::send_result_set_metadata"); if (flags & SEND_NUM_ROWS) { // Packet with number of elements uchar *pos= net_store_length(buff, list->elements); if (my_net_write(&thd->net, buff, (size_t) (pos-buff))) DBUG_RETURN(1); } #ifndef DBUG_OFF field_types= (enum_field_types*) thd->alloc(sizeof(field_types) * list->elements); uint count= 0; #endif /* We have to reallocate it here as a stored procedure may have reset it */ (void) local_packet->alloc(thd->variables.net_buffer_length); while ((item=it++)) { char *pos; CHARSET_INFO *cs= system_charset_info; Send_field field; item->make_field(&field); /* Keep things compatible for old clients */ if (field.type == MYSQL_TYPE_VARCHAR) field.type= MYSQL_TYPE_VAR_STRING; prot.prepare_for_resend(); if (thd->client_capabilities & CLIENT_PROTOCOL_41) { if (prot.store(STRING_WITH_LEN("def"), cs, thd_charset) || prot.store(field.db_name, (uint) strlen(field.db_name), cs, thd_charset) || prot.store(field.table_name, (uint) strlen(field.table_name), cs, thd_charset) || prot.store(field.org_table_name, (uint) strlen(field.org_table_name), cs, thd_charset) || prot.store(field.col_name, (uint) strlen(field.col_name), cs, thd_charset) || prot.store(field.org_col_name, (uint) strlen(field.org_col_name), cs, thd_charset) || local_packet->realloc(local_packet->length()+12)) goto err; /* Store fixed length fields */ pos= (char*) local_packet->ptr()+local_packet->length(); *pos++= 12; // Length of packed fields /* inject a NULL to test the client */ DBUG_EXECUTE_IF("poison_rs_fields", pos[-1]= (char) 0xfb;); if (item->charset_for_protocol() == &my_charset_bin || thd_charset == NULL) { /* No conversion */ int2store(pos, item->charset_for_protocol()->number); int4store(pos+2, field.length); } else { /* With conversion */ uint32 field_length, max_length; int2store(pos, thd_charset->number); /* For TEXT/BLOB columns, field_length describes the maximum data length in bytes. There is no limit to the number of characters that a TEXT column can store, as long as the data fits into the designated space. For the rest of textual columns, field_length is evaluated as char_count * mbmaxlen, where character count is taken from the definition of the column. In other words, the maximum number of characters here is limited by the column definition. When one has a LONG TEXT column with a single-byte character set, and the connection character set is multi-byte, the client may get fields longer than UINT_MAX32, due to <character set column> -> <character set connection> conversion. In that case column max length does not fit into the 4 bytes reserved for it in the protocol. */ max_length= (field.type >= MYSQL_TYPE_TINY_BLOB && field.type <= MYSQL_TYPE_BLOB) ? field.length / item->collation.collation->mbminlen : field.length / item->collation.collation->mbmaxlen; field_length= char_to_byte_length_safe(max_length, thd_charset->mbmaxlen); int4store(pos + 2, field_length); } pos[6]= field.type; int2store(pos+7,field.flags); pos[9]= (char) field.decimals; pos[10]= 0; // For the future pos[11]= 0; // For the future pos+= 12; } else { if (prot.store(field.table_name, (uint) strlen(field.table_name), cs, thd_charset) || prot.store(field.col_name, (uint) strlen(field.col_name), cs, thd_charset) || local_packet->realloc(local_packet->length()+10)) goto err; pos= (char*) local_packet->ptr()+local_packet->length(); pos[0]=3; int3store(pos+1,field.length); pos[4]=1; pos[5]=field.type; pos[6]=3; int2store(pos+7,field.flags); pos[9]= (char) field.decimals; pos+= 10; } local_packet->length((uint) (pos - local_packet->ptr())); if (flags & SEND_DEFAULTS) item->send(&prot, &tmp); // Send default value if (prot.write()) DBUG_RETURN(1); #ifndef DBUG_OFF field_types[count++]= field.type; #endif } if (flags & SEND_EOF) { /* Mark the end of meta-data result set, and store thd->server_status, to show that there is no cursor. Send no warning information, as it will be sent at statement end. */ if (write_eof_packet(thd, &thd->net, thd->server_status, thd->get_stmt_da()->current_statement_warn_count())) DBUG_RETURN(1); } DBUG_RETURN(prepare_for_send(list->elements)); err: my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0)); /* purecov: inspected */ DBUG_RETURN(1); /* purecov: inspected */ } bool Protocol::write() { DBUG_ENTER("Protocol::write"); DBUG_RETURN(my_net_write(&thd->net, (uchar*) packet->ptr(), packet->length())); } #endif /* EMBEDDED_LIBRARY */ /** Send one result set row. @param row_items a collection of column values for that row @return Error status. @retval TRUE Error. @retval FALSE Success. */ bool Protocol::send_result_set_row(List<Item> *row_items) { char buffer[MAX_FIELD_WIDTH]; String str_buffer(buffer, sizeof (buffer), &my_charset_bin); List_iterator_fast<Item> it(*row_items); DBUG_ENTER("Protocol::send_result_set_row"); for (Item *item= it++; item; item= it++) { if (item->send(this, &str_buffer)) { // If we're out of memory, reclaim some, to help us recover. this->free(); DBUG_RETURN(TRUE); } /* Item::send() may generate an error. If so, abort the loop. */ if (thd->is_error()) DBUG_RETURN(TRUE); /* Reset str_buffer to its original state, as it may have been altered in Item::send(). */ str_buffer.set(buffer, sizeof(buffer), &my_charset_bin); } DBUG_RETURN(FALSE); } /** Send \\0 end terminated string. @param from NullS or \\0 terminated string @note In most cases one should use store(from, length) instead of this function @retval 0 ok @retval 1 error */ bool Protocol::store(const char *from, CHARSET_INFO *cs) { if (!from) return store_null(); uint length= strlen(from); return store(from, length, cs); } /** Send a set of strings as one long string with ',' in between. */ bool Protocol::store(I_List<i_string>* str_list) { char buf[256]; String tmp(buf, sizeof(buf), &my_charset_bin); uint32 len; I_List_iterator<i_string> it(*str_list); i_string* s; tmp.length(0); while ((s=it++)) { tmp.append(s->ptr); tmp.append(','); } if ((len= tmp.length())) len--; // Remove last ',' return store((char*) tmp.ptr(), len, tmp.charset()); } /**************************************************************************** Functions to handle the simple (default) protocol where everything is This protocol is the one that is used by default between the MySQL server and client when you are not using prepared statements. All data are sent as 'packed-string-length' followed by 'string-data' ****************************************************************************/ #ifndef EMBEDDED_LIBRARY void Protocol_text::prepare_for_resend() { packet->length(0); #ifndef DBUG_OFF field_pos= 0; #endif } bool Protocol_text::store_null() { #ifndef DBUG_OFF field_pos++; #endif char buff[1]; buff[0]= (char)251; return packet->append(buff, sizeof(buff), PACKET_BUFFER_EXTRA_ALLOC); } #endif /** Auxilary function to convert string to the given character set and store in network buffer. */ bool Protocol::store_string_aux(const char *from, size_t length, CHARSET_INFO *fromcs, CHARSET_INFO *tocs) { /* 'tocs' is set 0 when client issues SET character_set_results=NULL */ if (tocs && !my_charset_same(fromcs, tocs) && fromcs != &my_charset_bin && tocs != &my_charset_bin) { /* Store with conversion */ return net_store_data_cs((uchar*) from, length, fromcs, tocs); } /* Store without conversion */ return net_store_data((uchar*) from, length); } bool Protocol_text::store(const char *from, size_t length, CHARSET_INFO *fromcs, CHARSET_INFO *tocs) { #ifndef DBUG_OFF DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_DECIMAL || field_types[field_pos] == MYSQL_TYPE_BIT || field_types[field_pos] == MYSQL_TYPE_NEWDECIMAL || (field_types[field_pos] >= MYSQL_TYPE_ENUM && field_types[field_pos] <= MYSQL_TYPE_GEOMETRY)); field_pos++; #endif return store_string_aux(from, length, fromcs, tocs); } bool Protocol_text::store(const char *from, size_t length, CHARSET_INFO *fromcs) { CHARSET_INFO *tocs= this->thd->variables.character_set_results; #ifndef DBUG_OFF DBUG_PRINT("info", ("Protocol_text::store field %u (%u): %.*s", field_pos, field_count, (int) length, (length == 0 ? "" : from))); DBUG_ASSERT(field_pos < field_count); DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_DECIMAL || field_types[field_pos] == MYSQL_TYPE_BIT || field_types[field_pos] == MYSQL_TYPE_NEWDECIMAL || field_types[field_pos] == MYSQL_TYPE_NEWDATE || (field_types[field_pos] >= MYSQL_TYPE_ENUM && field_types[field_pos] <= MYSQL_TYPE_GEOMETRY)); field_pos++; #endif return store_string_aux(from, length, fromcs, tocs); } bool Protocol_text::store_tiny(longlong from) { #ifndef DBUG_OFF DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_TINY); field_pos++; #endif char buff[20]; return net_store_data((uchar*) buff, (size_t) (int10_to_str((int) from, buff, -10) - buff)); } bool Protocol_text::store_short(longlong from) { #ifndef DBUG_OFF DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_YEAR || field_types[field_pos] == MYSQL_TYPE_SHORT); field_pos++; #endif char buff[20]; return net_store_data((uchar*) buff, (size_t) (int10_to_str((int) from, buff, -10) - buff)); } bool Protocol_text::store_long(longlong from) { #ifndef DBUG_OFF DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_INT24 || field_types[field_pos] == MYSQL_TYPE_LONG); field_pos++; #endif char buff[20]; return net_store_data((uchar*) buff, (size_t) (int10_to_str((long int)from, buff, (from <0)?-10:10)-buff)); } bool Protocol_text::store_longlong(longlong from, bool unsigned_flag) { #ifndef DBUG_OFF DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_LONGLONG); field_pos++; #endif char buff[22]; return net_store_data((uchar*) buff, (size_t) (longlong10_to_str(from,buff, unsigned_flag ? 10 : -10)- buff)); } bool Protocol_text::store_decimal(const my_decimal *d) { #ifndef DBUG_OFF DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_NEWDECIMAL); field_pos++; #endif char buff[DECIMAL_MAX_STR_LENGTH]; String str(buff, sizeof(buff), &my_charset_bin); (void) my_decimal2string(E_DEC_FATAL_ERROR, d, 0, 0, 0, &str); return net_store_data((uchar*) str.ptr(), str.length()); } bool Protocol_text::store(float from, uint32 decimals, String *buffer) { #ifndef DBUG_OFF DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_FLOAT); field_pos++; #endif buffer->set_real((double) from, decimals, thd->charset()); return net_store_data((uchar*) buffer->ptr(), buffer->length()); } bool Protocol_text::store(double from, uint32 decimals, String *buffer) { #ifndef DBUG_OFF DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_DOUBLE); field_pos++; #endif buffer->set_real(from, decimals, thd->charset()); return net_store_data((uchar*) buffer->ptr(), buffer->length()); } bool Protocol_text::store(Field *field) { if (field->is_null()) return store_null(); #ifndef DBUG_OFF field_pos++; #endif char buff[MAX_FIELD_WIDTH]; String str(buff,sizeof(buff), &my_charset_bin); CHARSET_INFO *tocs= this->thd->variables.character_set_results; #ifndef DBUG_OFF TABLE *table= field->table; my_bitmap_map *old_map= 0; if (table->file) old_map= dbug_tmp_use_all_columns(table, table->read_set); #endif field->val_str(&str); #ifndef DBUG_OFF if (old_map) dbug_tmp_restore_column_map(table->read_set, old_map); #endif return store_string_aux(str.ptr(), str.length(), str.charset(), tocs); } bool Protocol_text::store(MYSQL_TIME *tm, int decimals) { #ifndef DBUG_OFF DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_DATETIME || field_types[field_pos] == MYSQL_TYPE_TIMESTAMP); field_pos++; #endif char buff[MAX_DATE_STRING_REP_LENGTH]; uint length= my_datetime_to_str(tm, buff, decimals); return net_store_data((uchar*) buff, length); } bool Protocol_text::store_date(MYSQL_TIME *tm) { #ifndef DBUG_OFF DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_DATE); field_pos++; #endif char buff[MAX_DATE_STRING_REP_LENGTH]; size_t length= my_date_to_str(tm, buff); return net_store_data((uchar*) buff, length); } bool Protocol_text::store_time(MYSQL_TIME *tm, int decimals) { #ifndef DBUG_OFF DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_TIME); field_pos++; #endif char buff[MAX_DATE_STRING_REP_LENGTH]; uint length= my_time_to_str(tm, buff, decimals); return net_store_data((uchar*) buff, length); } /** Assign OUT-parameters to user variables. @param sp_params List of PS/SP parameters (both input and output). @return Error status. @retval FALSE Success. @retval TRUE Error. */ bool Protocol_text::send_out_parameters(List<Item_param> *sp_params) { DBUG_ASSERT(sp_params->elements == thd->lex->prepared_stmt_params.elements); List_iterator_fast<Item_param> item_param_it(*sp_params); List_iterator_fast<LEX_STRING> user_var_name_it(thd->lex->prepared_stmt_params); while (true) { Item_param *item_param= item_param_it++; LEX_STRING *user_var_name= user_var_name_it++; if (!item_param || !user_var_name) break; if (!item_param->get_out_param_info()) continue; // It's an IN-parameter. Item_func_set_user_var *suv= new Item_func_set_user_var(*user_var_name, item_param); /* Item_func_set_user_var is not fixed after construction, call fix_fields(). */ if (suv->fix_fields(thd, NULL)) return TRUE; if (suv->check(FALSE)) return TRUE; if (suv->update()) return TRUE; } return FALSE; } /**************************************************************************** Functions to handle the binary protocol used with prepared statements Data format: [ok:1] reserved ok packet [null_field:(field_count+7+2)/8] reserved to send null data. The size is calculated using: bit_fields= (field_count+7+2)/8; 2 bits are reserved for identifying type of package. [[length]data] data field (the length applies only for string/binary/time/timestamp fields and rest of them are not sent as they have the default length that client understands based on the field type [..]..[[length]data] data ****************************************************************************/ bool Protocol_binary::prepare_for_send(uint num_columns) { Protocol::prepare_for_send(num_columns); bit_fields= (field_count+9)/8; return packet->alloc(bit_fields+1); /* prepare_for_resend will be called after this one */ } void Protocol_binary::prepare_for_resend() { packet->length(bit_fields+1); bzero((uchar*) packet->ptr(), 1+bit_fields); field_pos=0; } bool Protocol_binary::store(const char *from, size_t length, CHARSET_INFO *fromcs) { CHARSET_INFO *tocs= thd->variables.character_set_results; field_pos++; return store_string_aux(from, length, fromcs, tocs); } bool Protocol_binary::store(const char *from, size_t length, CHARSET_INFO *fromcs, CHARSET_INFO *tocs) { field_pos++; return store_string_aux(from, length, fromcs, tocs); } bool Protocol_binary::store_null() { uint offset= (field_pos+2)/8+1, bit= (1 << ((field_pos+2) & 7)); /* Room for this as it's allocated in prepare_for_send */ char *to= (char*) packet->ptr()+offset; *to= (char) ((uchar) *to | (uchar) bit); field_pos++; return 0; } bool Protocol_binary::store_tiny(longlong from) { char buff[1]; field_pos++; buff[0]= (uchar) from; return packet->append(buff, sizeof(buff), PACKET_BUFFER_EXTRA_ALLOC); } bool Protocol_binary::store_short(longlong from) { field_pos++; char *to= packet->prep_append(2, PACKET_BUFFER_EXTRA_ALLOC); if (!to) return 1; int2store(to, (int) from); return 0; } bool Protocol_binary::store_long(longlong from) { field_pos++; char *to= packet->prep_append(4, PACKET_BUFFER_EXTRA_ALLOC); if (!to) return 1; int4store(to, from); return 0; } bool Protocol_binary::store_longlong(longlong from, bool unsigned_flag) { field_pos++; char *to= packet->prep_append(8, PACKET_BUFFER_EXTRA_ALLOC); if (!to) return 1; int8store(to, from); return 0; } bool Protocol_binary::store_decimal(const my_decimal *d) { #ifndef DBUG_OFF DBUG_ASSERT(field_types == 0 || field_types[field_pos] == MYSQL_TYPE_NEWDECIMAL); field_pos++; #endif char buff[DECIMAL_MAX_STR_LENGTH]; String str(buff, sizeof(buff), &my_charset_bin); (void) my_decimal2string(E_DEC_FATAL_ERROR, d, 0, 0, 0, &str); return store(str.ptr(), str.length(), str.charset()); } bool Protocol_binary::store(float from, uint32 decimals, String *buffer) { field_pos++; char *to= packet->prep_append(4, PACKET_BUFFER_EXTRA_ALLOC); if (!to) return 1; float4store(to, from); return 0; } bool Protocol_binary::store(double from, uint32 decimals, String *buffer) { field_pos++; char *to= packet->prep_append(8, PACKET_BUFFER_EXTRA_ALLOC); if (!to) return 1; float8store(to, from); return 0; } bool Protocol_binary::store(Field *field) { /* We should not increment field_pos here as send_binary() will call another protocol function to do this for us */ if (field->is_null()) return store_null(); return field->send_binary(this); } bool Protocol_binary::store(MYSQL_TIME *tm, int decimals) { char buff[12],*pos; uint length; field_pos++; pos= buff+1; int2store(pos, tm->year); pos[2]= (uchar) tm->month; pos[3]= (uchar) tm->day; pos[4]= (uchar) tm->hour; pos[5]= (uchar) tm->minute; pos[6]= (uchar) tm->second; DBUG_ASSERT(decimals == AUTO_SEC_PART_DIGITS || (decimals >= 0 && decimals <= TIME_SECOND_PART_DIGITS)); if (decimals != AUTO_SEC_PART_DIGITS) my_time_trunc(tm, decimals); int4store(pos+7, tm->second_part); if (tm->second_part) length=11; else if (tm->hour || tm->minute || tm->second) length=7; else if (tm->year || tm->month || tm->day) length=4; else length=0; buff[0]=(char) length; // Length is stored first return packet->append(buff, length+1, PACKET_BUFFER_EXTRA_ALLOC); } bool Protocol_binary::store_date(MYSQL_TIME *tm) { tm->hour= tm->minute= tm->second=0; tm->second_part= 0; return Protocol_binary::store(tm, 0); } bool Protocol_binary::store_time(MYSQL_TIME *tm, int decimals) { char buff[13], *pos; uint length; field_pos++; pos= buff+1; pos[0]= tm->neg ? 1 : 0; if (tm->hour >= 24) { uint days= tm->hour/24; tm->hour-= days*24; tm->day+= days; } int4store(pos+1, tm->day); pos[5]= (uchar) tm->hour; pos[6]= (uchar) tm->minute; pos[7]= (uchar) tm->second; DBUG_ASSERT(decimals == AUTO_SEC_PART_DIGITS || (decimals >= 0 && decimals <= TIME_SECOND_PART_DIGITS)); if (decimals != AUTO_SEC_PART_DIGITS) my_time_trunc(tm, decimals); int4store(pos+8, tm->second_part); if (tm->second_part) length=12; else if (tm->hour || tm->minute || tm->second || tm->day) length=8; else length=0; buff[0]=(char) length; // Length is stored first return packet->append(buff, length+1, PACKET_BUFFER_EXTRA_ALLOC); } /** Send a result set with OUT-parameter values by means of PS-protocol. @param sp_params List of PS/SP parameters (both input and output). @return Error status. @retval FALSE Success. @retval TRUE Error. */ bool Protocol_binary::send_out_parameters(List<Item_param> *sp_params) { if (!(thd->client_capabilities & CLIENT_PS_MULTI_RESULTS)) { /* The client does not support OUT-parameters. */ return FALSE; } List<Item> out_param_lst; { List_iterator_fast<Item_param> item_param_it(*sp_params); while (true) { Item_param *item_param= item_param_it++; if (!item_param) break; if (!item_param->get_out_param_info()) continue; // It's an IN-parameter. if (out_param_lst.push_back(item_param)) return TRUE; } } if (!out_param_lst.elements) return FALSE; /* We have to set SERVER_PS_OUT_PARAMS in THD::server_status, because it is used in send_result_set_metadata(). */ thd->server_status|= SERVER_PS_OUT_PARAMS | SERVER_MORE_RESULTS_EXISTS; /* Send meta-data. */ if (send_result_set_metadata(&out_param_lst, SEND_NUM_ROWS | SEND_EOF)) return TRUE; /* Send data. */ prepare_for_resend(); if (send_result_set_row(&out_param_lst)) return TRUE; if (write()) return TRUE; /* Restore THD::server_status. */ thd->server_status&= ~SERVER_PS_OUT_PARAMS; /* Send EOF-packet. */ net_send_eof(thd, thd->server_status, 0); /* Reset SERVER_MORE_RESULTS_EXISTS bit, because this is the last packet for sure. */ thd->server_status&= ~SERVER_MORE_RESULTS_EXISTS; return FALSE; }
SunguckLee/MariaDB-PageCompression
sql/protocol.cc
C++
gpl-2.0
45,791
/* * Copyright (C) 2014 Gautier Hattenberger <gautier.hattenberger@enac.fr> * * This file is part of paparazzi. * * paparazzi 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. * * paparazzi 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 paparazzi; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. */ /** * @file subsystems/imu/imu_mpu9250_spi.h * * IMU driver for the MPU9250 using SPI * */ #ifndef IMU_MPU9250_SPI_H #define IMU_MPU9250_SPI_H #include "std.h" #include "generated/airframe.h" #include "subsystems/imu.h" #include "peripherals/mpu9250_spi.h" /** default gyro sensitivy and neutral from the datasheet * MPU with 1000 deg/s has 32.8 LSB/(deg/s) * sens = 1/32.8 * pi/180 * 2^INT32_RATE_FRAC * sens = 1/32.8 * pi/180 * 4096 = 2.17953 I*/ #if !defined IMU_GYRO_P_SENS & !defined IMU_GYRO_Q_SENS & !defined IMU_GYRO_R_SENS // FIXME #define IMU_GYRO_P_SENS 2.17953 #define IMU_GYRO_P_SENS_NUM 18271 #define IMU_GYRO_P_SENS_DEN 8383 #define IMU_GYRO_Q_SENS 2.17953 #define IMU_GYRO_Q_SENS_NUM 18271 #define IMU_GYRO_Q_SENS_DEN 8383 #define IMU_GYRO_R_SENS 2.17953 #define IMU_GYRO_R_SENS_NUM 18271 #define IMU_GYRO_R_SENS_DEN 8383 #endif /** default accel sensitivy from the datasheet * MPU with 8g has 4096 LSB/g * sens = 9.81 [m/s^2] / 4096 [LSB/g] * 2^INT32_ACCEL_FRAC = 2.4525 */ #if !defined IMU_ACCEL_X_SENS & !defined IMU_ACCEL_Y_SENS & !defined IMU_ACCEL_Z_SENS // FIXME #define IMU_ACCEL_X_SENS 2.4525 #define IMU_ACCEL_X_SENS_NUM 981 #define IMU_ACCEL_X_SENS_DEN 400 #define IMU_ACCEL_Y_SENS 2.4525 #define IMU_ACCEL_Y_SENS_NUM 981 #define IMU_ACCEL_Y_SENS_DEN 400 #define IMU_ACCEL_Z_SENS 2.4525 #define IMU_ACCEL_Z_SENS_NUM 981 #define IMU_ACCEL_Z_SENS_DEN 400 #endif struct ImuMpu9250 { struct Mpu9250_Spi mpu; struct spi_transaction wait_slave4_trans; volatile uint8_t wait_slave4_tx_buf[1]; volatile uint8_t wait_slave4_rx_buf[2]; volatile bool slave4_ready; }; extern struct ImuMpu9250 imu_mpu9250; extern void imu_mpu9250_event(void); #define ImuEvent imu_mpu9250_event #endif /* IMU_MPU9250_SPI_H */
deonblaauw/paparazzi
sw/airborne/subsystems/imu/imu_mpu9250_spi.h
C
gpl-2.0
2,530
/* arch/arm/plat-samsung/include/plat/devs.h * * Copyright (c) 2011 Samsung Electronics Co., Ltd. * http://www.samsung.com * * Copyright (c) 2004 Simtec Electronics * Ben Dooks <ben@simtec.co.uk> * * Header file for s3c2410 standard platform devices * * 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. */ #ifndef __PLAT_DEVS_H #define __PLAT_DEVS_H __FILE__ #include <linux/platform_device.h> struct s3c24xx_uart_resources { struct resource *resources; unsigned long nr_resources; }; extern struct s3c24xx_uart_resources s3c2410_uart_resources[]; extern struct s3c24xx_uart_resources s3c64xx_uart_resources[]; extern struct s3c24xx_uart_resources s5p_uart_resources[]; extern struct s3c24xx_uart_resources exynos4_uart_resources[]; extern struct s3c24xx_uart_resources exynos5_uart_resources[]; extern struct platform_device *s3c24xx_uart_devs[]; extern struct platform_device *s3c24xx_uart_src[]; extern struct platform_device s3c64xx_device_ac97; extern struct platform_device s3c64xx_device_iis0; extern struct platform_device s3c64xx_device_iis1; extern struct platform_device s3c64xx_device_iisv4; extern struct platform_device s3c64xx_device_onenand1; extern struct platform_device s3c64xx_device_pcm0; extern struct platform_device s3c64xx_device_pcm1; extern struct platform_device s3c64xx_device_spi0; extern struct platform_device s3c64xx_device_spi1; extern struct platform_device s3c64xx_device_spi2; extern struct platform_device s3c64xx_device_spi3; extern struct platform_device s3c_device_adc; extern struct platform_device s3c_device_cfcon; extern struct platform_device s3c_device_fb; extern struct platform_device s3c_device_hwmon; extern struct platform_device s3c_device_hsmmc0; extern struct platform_device s3c_device_hsmmc1; extern struct platform_device s3c_device_hsmmc2; extern struct platform_device s3c_device_hsmmc3; extern struct platform_device s3c_device_i2c0; extern struct platform_device s3c_device_i2c1; extern struct platform_device s3c_device_i2c2; extern struct platform_device s3c_device_i2c3; extern struct platform_device s3c_device_i2c4; extern struct platform_device s3c_device_i2c5; extern struct platform_device s3c_device_i2c6; extern struct platform_device s3c_device_i2c7; extern struct platform_device s3c_device_iis; extern struct platform_device s3c_device_lcd; extern struct platform_device s3c_device_nand; extern struct platform_device s3c_device_ohci; extern struct platform_device s3c_device_onenand; extern struct platform_device s3c_device_rtc; extern struct platform_device s3c_device_sdi; extern struct platform_device s3c_device_spi0; extern struct platform_device s3c_device_spi1; extern struct platform_device s3c_device_ts; extern struct platform_device s3c_device_timer[]; extern struct platform_device s3c_device_usbgadget; extern struct platform_device s3c_device_usb_hsotg; extern struct platform_device s3c_device_usb_hsudc; extern struct platform_device s3c_device_wdt; extern struct platform_device s5p_device_ehci; extern struct platform_device s5p_device_fimc0; extern struct platform_device s5p_device_fimc1; extern struct platform_device s5p_device_fimc2; extern struct platform_device s5p_device_fimc3; extern struct platform_device s5p_device_flite0; extern struct platform_device s5p_device_flite1; extern struct platform_device s5p_device_fimc_md; extern struct platform_device s5p_device_jpeg; extern struct platform_device s5p_device_g2d; extern struct platform_device s5p_device_fimd0; extern struct platform_device s5p_device_fimd1; extern struct platform_device s5p_device_mipi_dsim0; extern struct platform_device s5p_device_mipi_dsim1; extern struct platform_device s5p_device_dp; extern struct platform_device s5p_device_mic; extern struct platform_device s5p_device_hdmi; extern struct platform_device s5p_device_cec; extern struct platform_device s5p_device_i2c_hdmiphy; extern struct platform_device s5p_device_mfc; extern struct platform_device s5p_device_mfc_l; extern struct platform_device s5p_device_mfc_r; extern struct platform_device s5p_device_mipi_csis0; extern struct platform_device s5p_device_mipi_csis1; extern struct platform_device s5p_device_mipi_csis2; extern struct platform_device s5p_device_mixer; extern struct platform_device s5p_device_onenand; extern struct platform_device s5p_device_sdo; extern struct platform_device s5p_device_ace; extern struct platform_device s5p_device_jpeg; extern struct platform_device s5p6440_device_iis; extern struct platform_device s5p6440_device_pcm; extern struct platform_device s5p6450_device_iis0; extern struct platform_device s5p6450_device_iis1; extern struct platform_device s5p6450_device_iis2; extern struct platform_device s5p6450_device_pcm0; extern struct platform_device s5pc100_device_ac97; extern struct platform_device s5pc100_device_iis0; extern struct platform_device s5pc100_device_iis1; extern struct platform_device s5pc100_device_iis2; extern struct platform_device s5pc100_device_pcm0; extern struct platform_device s5pc100_device_pcm1; extern struct platform_device s5pc100_device_spdif; extern struct platform_device s5pv210_device_ac97; extern struct platform_device s5pv210_device_iis0; extern struct platform_device s5pv210_device_iis1; extern struct platform_device s5pv210_device_iis2; extern struct platform_device s5pv210_device_pcm0; extern struct platform_device s5pv210_device_pcm1; extern struct platform_device s5pv210_device_pcm2; extern struct platform_device s5pv210_device_spdif; extern struct platform_device exynos4_device_ac97; extern struct platform_device exynos4_device_ahci; extern struct platform_device exynos4_device_dwmci; extern struct platform_device exynos4_device_srp; extern struct platform_device exynos4_device_i2s0; extern struct platform_device exynos4_device_i2s1; extern struct platform_device exynos4_device_i2s2; extern struct platform_device exynos4_device_ohci; extern struct platform_device exynos4_device_pcm0; extern struct platform_device exynos4_device_pcm1; extern struct platform_device exynos4_device_pcm2; extern struct platform_device exynos4_device_pd[]; extern struct platform_device exynos4_device_spdif; extern struct platform_device exynos_device_ss_udc; extern struct platform_device exynos4_device_g3d; extern struct platform_device exynos4_device_fimc_is; extern struct platform_device exynos5_device_dwmci0; extern struct platform_device exynos5_device_dwmci1; extern struct platform_device exynos5_device_dwmci2; extern struct platform_device exynos5_device_dwmci3; extern struct platform_device exynos5_device_pcm0; extern struct platform_device exynos5_device_pcm1; extern struct platform_device exynos5_device_pcm2; extern struct platform_device exynos5_device_srp; extern struct platform_device exynos5_device_i2s0; extern struct platform_device exynos5_device_i2s1; extern struct platform_device exynos5_device_i2s2; extern struct platform_device exynos5_device_spdif; extern struct platform_device exynos_device_flite0; extern struct platform_device exynos_device_flite1; extern struct platform_device exynos_device_flite2; extern struct platform_device exynos5_device_rotator; extern struct platform_device exynos5_device_gsc0; extern struct platform_device exynos5_device_gsc1; extern struct platform_device exynos5_device_gsc2; extern struct platform_device exynos5_device_gsc3; extern struct platform_device exynos5_device_scaler0; extern struct platform_device exynos5_device_scaler1; extern struct platform_device exynos5_device_scaler2; extern struct platform_device exynos5_device_fimc_is; extern struct platform_device exynos5_device_jpeg_hx; extern struct platform_device exynos5_device_jpeg2_hx; extern struct platform_device exynos5_device_hs_i2c0; extern struct platform_device exynos5_device_hs_i2c1; extern struct platform_device exynos5_device_hs_i2c2; extern struct platform_device exynos5_device_hs_i2c3; extern struct platform_device exynos5_device_hs_i2c4; extern struct platform_device exynos5_device_hs_i2c5; extern struct platform_device exynos5_device_hs_i2c6; extern struct platform_device samsung_asoc_dma; extern struct platform_device samsung_asoc_idma; extern struct platform_device samsung_device_keypad; extern struct platform_device s5p_device_fimg2d; extern struct platform_device s5p_device_usbswitch; #if defined(CONFIG_MALI_T6XX) || defined(CONFIG_PVR_SGX) || defined(CONFIG_MALI_MIDGARD_WK04) || defined(CONFIG_MALI_T6XX_R7P0) extern struct platform_device exynos5_device_g3d; #endif extern struct platform_device exynos5410_device_tmu; extern struct platform_device exynos5420_device_tmu; /* s3c2440 specific devices */ #ifdef CONFIG_CPU_S3C2440 extern struct platform_device s3c_device_camif; extern struct platform_device s3c_device_ac97; #endif /** * s3c_set_platdata() - helper for setting platform data * @pd: The default platform data for this device. * @pdsize: The size of the platform data. * @pdev: Pointer to the device to fill in. * * This helper replaces a number of calls that copy and then set the * platform data of the device. */ extern void *s3c_set_platdata(void *pd, size_t pdsize, struct platform_device *pdev); #endif /* __PLAT_DEVS_H */
CM-Tab-S/android_kernel_samsung_klimtwifi
arch/arm/plat-samsung/include/plat/devs.h
C
gpl-2.0
9,335
//////////////////////////////////////////////////////////////////////////////////////// // // Nestopia - NES/Famicom emulator written in C++ // // Copyright (C) 2003-2007 Martin Freij // // This file is part of Nestopia. // // Nestopia 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. // // Nestopia 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 Nestopia; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////////////////////////////////////// #ifndef NST_MAPPER_45_H #define NST_MAPPER_45_H #ifdef NST_PRAGMA_ONCE #pragma once #endif namespace Nes { namespace Core { class Mapper45 : public Boards::Mmc3 { public: explicit Mapper45(Context& c) : Mmc3(c) {} private: ~Mapper45() {} void SubReset(bool); void SubSave(State::Saver&) const; void SubLoad(State::Loader&); void UpdatePrg(); void UpdateChr() const; NES_DECL_POKE( 6000 ); uint exRegs[5]; }; } } #endif
Joride/nestopia
core/mapper/NstMapper045.hpp
C++
gpl-2.0
1,550
#ifndef JITCORE_H #define JITCORE_H #define RAISE(errtype, msg) {PyObject* p; p = PyErr_Format( errtype, msg ); return p;} #define RAISE_ret0(errtype, msg) {PyObject* p; p = PyErr_Format( errtype, msg ); return 0;} #define PyGetInt(item, value) \ if (PyInt_Check(item)){ \ value = (uint64_t)PyInt_AsLong(item); \ } \ else if (PyLong_Check(item)){ \ value = (uint64_t)PyLong_AsUnsignedLongLong(item); \ } \ else{ \ RAISE(PyExc_TypeError,"arg must be int"); \ } \ #define PyGetInt_ret0(item, value) \ if (PyInt_Check(item)){ \ value = (uint64_t)PyInt_AsLong(item); \ } \ else if (PyLong_Check(item)){ \ value = (uint64_t)PyLong_AsUnsignedLongLong(item); \ } \ else{ \ printf("error\n"); return 0; \ } \ #define getset_reg_u64(regname) \ static PyObject *JitCpu_get_ ## regname (JitCpu *self, void *closure) \ { \ return PyLong_FromUnsignedLongLong((uint64_t)(((vm_cpu_t*)(self->cpu))-> regname )); \ } \ static int JitCpu_set_ ## regname (JitCpu *self, PyObject *value, void *closure) \ { \ uint64_t val; \ PyGetInt_ret0(value, val); \ ((vm_cpu_t*)(self->cpu))-> regname = val; \ return 0; \ } #define getset_reg_u32(regname) \ static PyObject *JitCpu_get_ ## regname (JitCpu *self, void *closure) \ { \ return PyLong_FromUnsignedLongLong((uint32_t)(((vm_cpu_t*)(self->cpu))-> regname )); \ } \ static int JitCpu_set_ ## regname (JitCpu *self, PyObject *value, void *closure) \ { \ uint32_t val; \ PyGetInt_ret0(value, val); \ ((vm_cpu_t*)(self->cpu))-> regname = val; \ return 0; \ } #define getset_reg_u16(regname) \ static PyObject *JitCpu_get_ ## regname (JitCpu *self, void *closure) \ { \ return PyLong_FromUnsignedLongLong((uint16_t)(((vm_cpu_t*)(self->cpu))-> regname )); \ } \ static int JitCpu_set_ ## regname (JitCpu *self, PyObject *value, void *closure) \ { \ uint16_t val; \ PyGetInt_ret0(value, val); \ ((vm_cpu_t*)(self->cpu))-> regname = val; \ return 0; \ } #define get_reg(reg) do { \ o = PyLong_FromUnsignedLongLong((uint64_t)((vm_cpu_t*)(self->cpu))->reg); \ PyDict_SetItemString(dict, #reg, o); \ Py_DECREF(o); \ } while(0); #define get_reg_off(reg) do { \ o = PyLong_FromUnsignedLongLong((uint64_t)offsetof(vm_cpu_t, reg)); \ PyDict_SetItemString(dict, #reg, o); \ Py_DECREF(o); \ } while(0); typedef struct { uint8_t is_local; uint64_t address; } block_id; typedef struct { PyObject_HEAD PyObject *pyvm; PyObject *jitter; void* cpu; } JitCpu; typedef struct _reg_dict{ char* name; size_t offset; } reg_dict; void JitCpu_dealloc(JitCpu* self); PyObject * JitCpu_new(PyTypeObject *type, PyObject *args, PyObject *kwds); PyObject * JitCpu_get_vmmngr(JitCpu *self, void *closure); PyObject * JitCpu_set_vmmngr(JitCpu *self, PyObject *value, void *closure); PyObject * JitCpu_get_jitter(JitCpu *self, void *closure); PyObject * JitCpu_set_jitter(JitCpu *self, PyObject *value, void *closure); void Resolve_dst(block_id* BlockDst, uint64_t addr, uint64_t is_local); uint8_t MEM_LOOKUP_08(JitCpu* jitcpu, uint64_t addr); uint16_t MEM_LOOKUP_16(JitCpu* jitcpu, uint64_t addr); uint32_t MEM_LOOKUP_32(JitCpu* jitcpu, uint64_t addr); uint64_t MEM_LOOKUP_64(JitCpu* jitcpu, uint64_t addr); void MEM_WRITE_08(JitCpu* jitcpu, uint64_t addr, uint8_t src); void MEM_WRITE_16(JitCpu* jitcpu, uint64_t addr, uint16_t src); void MEM_WRITE_32(JitCpu* jitcpu, uint64_t addr, uint32_t src); void MEM_WRITE_64(JitCpu* jitcpu, uint64_t addr, uint64_t src); PyObject* vm_get_mem(JitCpu *self, PyObject* args); #define VM_exception_flag (((VmMngr*)jitcpu->pyvm)->vm_mngr.exception_flags) #define CPU_exception_flag (((vm_cpu_t*)jitcpu->cpu)->exception_flags) #endif
amohanta/miasm
miasm2/jitter/JitCore.h
C
gpl-2.0
3,953
<?php /** * Functions for making various theme elements context-aware. Controls things such as the smart * and logical body, post, and comment CSS classes as well as context-based action and filter hooks. * The functions also integrate with WordPress' implementations of body_class, post_class, and * comment_class, so your theme won't have any trouble with plugin integration. * * @package HybridCore * @subpackage Functions */ /** * Hybrid's main contextual function. This allows code to be used more than once without running * hundreds of conditional checks within the theme. It returns an array of contexts based on what * page a visitor is currently viewing on the site. This function is useful for making dynamic/contextual * classes, action and filter hooks, and handling the templating system. * * Note that time and date can be tricky because any of the conditionals may be true on time-/date- * based archives depending on several factors. For example, one could load an archive for a specific * second during a specific minute within a specific hour on a specific day and so on. * * @since 0.7.0 * @global $wp_query The current page's query object. * @global $hybrid The global Hybrid object. * @return array $hybrid->context Several contexts based on the current page. */ function hybrid_get_context() { global $hybrid; /* If $hybrid->context has been set, don't run through the conditionals again. Just return the variable. */ if ( isset( $hybrid->context ) ) return $hybrid->context; /* Set some variables for use within the function. */ $hybrid->context = array(); $object = get_queried_object(); $object_id = get_queried_object_id(); /* Front page of the site. */ if ( is_front_page() ) $hybrid->context[] = 'home'; /* Blog page. */ if ( is_home() ) { $hybrid->context[] = 'blog'; } /* Singular views. */ elseif ( is_singular() ) { $hybrid->context[] = 'singular'; $hybrid->context[] = "singular-{$object->post_type}"; $hybrid->context[] = "singular-{$object->post_type}-{$object_id}"; } /* Archive views. */ elseif ( is_archive() ) { $hybrid->context[] = 'archive'; /* Taxonomy archives. */ if ( is_tax() || is_category() || is_tag() ) { $hybrid->context[] = 'taxonomy'; $hybrid->context[] = "taxonomy-{$object->taxonomy}"; $hybrid->context[] = "taxonomy-{$object->taxonomy}-" . sanitize_html_class( $object->slug, $object->term_id ); } /* Post type archives. */ elseif ( is_post_type_archive() ) { $post_type = get_post_type_object( get_query_var( 'post_type' ) ); $hybrid->context[] = "archive-{$post_type->name}"; } /* User/author archives. */ elseif ( is_author() ) { $hybrid->context[] = 'user'; $hybrid->context[] = 'user-' . sanitize_html_class( get_the_author_meta( 'user_nicename', $object_id ), $object_id ); } /* Time/Date archives. */ else { if ( is_date() ) { $hybrid->context[] = 'date'; if ( is_year() ) $hybrid->context[] = 'year'; if ( is_month() ) $hybrid->context[] = 'month'; if ( get_query_var( 'w' ) ) $hybrid->context[] = 'week'; if ( is_day() ) $hybrid->context[] = 'day'; } if ( is_time() ) { $hybrid->context[] = 'time'; if ( get_query_var( 'hour' ) ) $hybrid->context[] = 'hour'; if ( get_query_var( 'minute' ) ) $hybrid->context[] = 'minute'; } } } /* Search results. */ elseif ( is_search() ) { $hybrid->context[] = 'search'; } /* Error 404 pages. */ elseif ( is_404() ) { $hybrid->context[] = 'error-404'; } return array_map( 'esc_attr', $hybrid->context ); } /** * Creates a set of classes for each site entry upon display. Each entry is given the class of * 'hentry'. Posts are given category, tag, and author classes. Alternate post classes of odd, * even, and alt are added. * * @since 0.5.0 * @global $post The current post's DB object. * @param string|array $class Additional classes for more control. * @return string $class */ function hybrid_entry_class( $class = '', $post_id = null ) { static $post_alt; $post = get_post( $post_id ); /* Make sure we have a real post first. */ if ( !empty( $post ) ) { $post_id = $post->ID; /* Add hentry for microformats compliance, the post type, and post status. */ $classes = array( 'hentry', $post->post_type, $post->post_status ); /* Post alt class. */ $classes[] = 'post-' . ++$post_alt; $classes[] = ( $post_alt % 2 ) ? 'odd' : 'even alt'; /* Author class. */ $classes[] = 'author-' . sanitize_html_class( get_the_author_meta( 'user_nicename' ), get_the_author_meta( 'ID' ) ); /* Sticky class (only on home/blog page). */ if ( is_home() && is_sticky() && !is_paged() ) $classes[] = 'sticky'; /* Password-protected posts. */ if ( post_password_required() ) $classes[] = 'protected'; /* Has excerpt. */ if ( has_excerpt() ) $classes[] = 'has-excerpt'; /* Post format. */ if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) ) { $post_format = get_post_format( $post_id ); $classes[] = ( ( empty( $post_format ) || is_wp_error( $post_format ) ) ? 'format-standard' : "format-{$post_format}" ); } /* Add category and post tag terms as classes. */ if ( 'post' == $post->post_type ) { foreach ( array( 'category', 'post_tag' ) as $tax ) { foreach ( (array)get_the_terms( $post->ID, $tax ) as $term ) { if ( !empty( $term->slug ) ) $classes[] = $tax . '-' . sanitize_html_class( $term->slug, $term->term_id ); } } } } /* If not a post. */ else { $classes = array( 'hentry', 'error' ); } /* User-created classes. */ if ( !empty( $class ) ) { if ( !is_array( $class ) ) $class = preg_split( '#\s+#', $class ); $classes = array_merge( $classes, $class ); } /* Apply the filters for WP's 'post_class'. */ $classes = apply_filters( 'post_class', $classes, $class, $post_id ); /* Join all the classes into one string and echo them. */ $class = join( ' ', $classes ); echo apply_atomic( 'entry_class', $class ); } /** * Sets a class for each comment. Sets alt, odd/even, and author/user classes. Adds author, user, * and reader classes. Needs more work because WP, by default, assigns even/odd backwards * (Odd should come first, even second). * * @since 0.2.0 * @global $wpdb WordPress DB access object. * @global $comment The current comment's DB object. */ function hybrid_comment_class( $class = '' ) { global $post, $comment, $hybrid; /* Gets default WP comment classes. */ $classes = get_comment_class( $class ); /* Get the comment type. */ $classes[] = get_comment_type(); /* User classes to match user role and user. */ if ( $comment->user_id > 0 ) { /* Create new user object. */ $user = new WP_User( $comment->user_id ); /* Set a class with the user's role. */ if ( is_array( $user->roles ) ) { foreach ( $user->roles as $role ) $classes[] = "role-{$role}"; } /* Set a class with the user's name. */ $classes[] = 'user-' . sanitize_html_class( $user->user_nicename, $user->ID ); } /* If not a registered user */ else { $classes[] = 'reader'; } /* Comment by the entry/post author. */ if ( $post = get_post( $post_id ) ) { if ( $comment->user_id === $post->post_author ) $classes[] = 'entry-author'; } /* Get comment types that are allowed to have an avatar. */ $avatar_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) ); /* If avatars are enabled and the comment types can display avatars, add the 'has-avatar' class. */ if ( get_option( 'show_avatars' ) && in_array( $comment->comment_type, $avatar_comment_types ) ) $classes[] = 'has-avatar'; /* Join all the classes into one string and echo them. */ $class = join( ' ', $classes ); echo apply_filters( "{$hybrid->prefix}_comment_class", $class ); } /** * Provides classes for the <body> element depending on page context. * * @since 0.1.0 * @uses $wp_query * @param string|array $class Additional classes for more control. * @return string */ function hybrid_body_class( $class = '' ) { global $wp_query; /* Text direction (which direction does the text flow). */ $classes = array( 'wordpress', get_bloginfo( 'text_direction' ), get_locale() ); /* Check if the current theme is a parent or child theme. */ $classes[] = ( is_child_theme() ? 'child-theme' : 'parent-theme' ); /* Multisite check adds the 'multisite' class and the blog ID. */ if ( is_multisite() ) { $classes[] = 'multisite'; $classes[] = 'blog-' . get_current_blog_id(); } /* Date classes. */ $time = time() + ( get_option( 'gmt_offset' ) * 3600 ); $classes[] = strtolower( gmdate( '\yY \mm \dd \hH l', $time ) ); /* Is the current user logged in. */ $classes[] = ( is_user_logged_in() ) ? 'logged-in' : 'logged-out'; /* WP admin bar. */ if ( is_admin_bar_showing() ) $classes[] = 'admin-bar'; /* Merge base contextual classes with $classes. */ $classes = array_merge( $classes, hybrid_get_context() ); /* Singular post (post_type) classes. */ if ( is_singular() ) { /* Get the queried post object. */ $post = get_queried_object(); /* Checks for custom template. */ $template = str_replace( array ( "{$post->post_type}-template-", "{$post->post_type}-", '.php' ), '', get_post_meta( get_queried_object_id(), "_wp_{$post->post_type}_template", true ) ); if ( !empty( $template ) ) $classes[] = "{$post->post_type}-template-{$template}"; /* Post format. */ if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) ) { $post_format = get_post_format( get_queried_object_id() ); $classes[] = ( ( empty( $post_format ) || is_wp_error( $post_format ) ) ? "{$post->post_type}-format-standard" : "{$post->post_type}-format-{$post_format}" ); } /* Attachment mime types. */ if ( is_attachment() ) { foreach ( explode( '/', get_post_mime_type() ) as $type ) $classes[] = "attachment-{$type}"; } } /* Paged views. */ if ( ( ( $page = $wp_query->get( 'paged' ) ) || ( $page = $wp_query->get( 'page' ) ) ) && $page > 1 ) $classes[] = 'paged paged-' . intval( $page ); /* Input class. */ if ( !empty( $class ) ) { if ( !is_array( $class ) ) $class = preg_split( '#\s+#', $class ); $classes = array_merge( $classes, $class ); } /* Apply the filters for WP's 'body_class'. */ $classes = apply_filters( 'body_class', $classes, $class ); /* Join all the classes into one string. */ $class = join( ' ', $classes ); /* Print the body class. */ echo apply_atomic( 'body_class', $class ); } /** * Function for handling what the browser/search engine title should be. Attempts to handle every * possible situation WordPress throws at it for the best optimization. * * @since 0.1.0 * @global $wp_query */ function hybrid_document_title() { global $wp_query; /* Set up some default variables. */ $domain = hybrid_get_textdomain(); $doctitle = ''; $separator = ':'; /* If viewing the front page and posts page of the site. */ if ( is_front_page() && is_home() ) $doctitle = get_bloginfo( 'name' ) . $separator . ' ' . get_bloginfo( 'description' ); /* If viewing the posts page or a singular post. */ elseif ( is_home() || is_singular() ) { $doctitle = get_post_meta( get_queried_object_id(), 'Title', true ); if ( empty( $doctitle ) && is_front_page() ) $doctitle = get_bloginfo( 'name' ) . $separator . ' ' . get_bloginfo( 'description' ); elseif ( empty( $doctitle ) ) $doctitle = single_post_title( '', false ); } /* If viewing any type of archive page. */ elseif ( is_archive() ) { /* If viewing a taxonomy term archive. */ if ( is_category() || is_tag() || is_tax() ) { $doctitle = single_term_title( '', false ); } /* If viewing a post type archive. */ elseif ( is_post_type_archive() ) { $post_type = get_post_type_object( get_query_var( 'post_type' ) ); $doctitle = $post_type->labels->name; } /* If viewing an author/user archive. */ elseif ( is_author() ) { $doctitle = get_user_meta( get_query_var( 'author' ), 'Title', true ); if ( empty( $doctitle ) ) $doctitle = get_the_author_meta( 'display_name', get_query_var( 'author' ) ); } /* If viewing a date-/time-based archive. */ elseif ( is_date () ) { if ( get_query_var( 'minute' ) && get_query_var( 'hour' ) ) $doctitle = sprintf( __( 'Archive for %1$s', $domain ), get_the_time( __( 'g:i a', $domain ) ) ); elseif ( get_query_var( 'minute' ) ) $doctitle = sprintf( __( 'Archive for minute %1$s', $domain ), get_the_time( __( 'i', $domain ) ) ); elseif ( get_query_var( 'hour' ) ) $doctitle = sprintf( __( 'Archive for %1$s', $domain ), get_the_time( __( 'g a', $domain ) ) ); elseif ( is_day() ) $doctitle = sprintf( __( 'Archive for %1$s', $domain ), get_the_time( __( 'F jS, Y', $domain ) ) ); elseif ( get_query_var( 'w' ) ) $doctitle = sprintf( __( 'Archive for week %1$s of %2$s', $domain ), get_the_time( __( 'W', $domain ) ), get_the_time( __( 'Y', $domain ) ) ); elseif ( is_month() ) $doctitle = sprintf( __( 'Archive for %1$s', $domain ), single_month_title( ' ', false) ); elseif ( is_year() ) $doctitle = sprintf( __( 'Archive for %1$s', $domain ), get_the_time( __( 'Y', $domain ) ) ); } /* For any other archives. */ else { $doctitle = __( 'Archives', $domain ); } } /* If viewing a search results page. */ elseif ( is_search() ) $doctitle = sprintf( __( 'Search results for &quot;%1$s&quot;', $domain ), esc_attr( get_search_query() ) ); /* If viewing a 404 not found page. */ elseif ( is_404() ) $doctitle = __( '404 Not Found', $domain ); /* If the current page is a paged page. */ if ( ( ( $page = $wp_query->get( 'paged' ) ) || ( $page = $wp_query->get( 'page' ) ) ) && $page > 1 ) $doctitle = sprintf( __( '%1$s Page %2$s', $domain ), $doctitle . $separator, number_format_i18n( $page ) ); /* Apply the wp_title filters so we're compatible with plugins. */ $doctitle = apply_filters( 'wp_title', $doctitle, $separator, '' ); /* Print the title to the screen. */ echo apply_atomic( 'document_title', esc_attr( $doctitle ) ); } ?>
traj-info/boletos1
wp-content/themes/trending/library/functions/context.php
PHP
gpl-2.0
14,233
/* drivers/usb/gadget/f_diag.c * Diag Function Device - Route ARM9 and ARM11 DIAG messages * between HOST and DEVICE. * Copyright (C) 2007 Google, Inc. * Copyright (c) 2008-2010, Code Aurora Forum. All rights reserved. * Author: Brian Swetland <swetland@google.com> * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/platform_device.h> #include <mach/usbdiag.h> #include <mach/rpc_hsusb.h> #include <linux/usb/composite.h> #include <linux/usb/gadget.h> #include <linux/usb/android_composite.h> #include <linux/workqueue.h> #include <mach/usbdiag.h> #if defined(CONFIG_MACH_MECHA) #include <mach/smsc251x.h> #endif /*#define HTC_DIAG_DEBUG*/ #if DIAG_XPST #include <mach/7x30-lte/msm_smd.h> #include <mach/sdio_al.h> #include <linux/miscdevice.h> #include <linux/sched.h> #include <asm/uaccess.h> #include <linux/fs.h> #include <linux/debugfs.h> #include "../../char/diag/diagchar.h" #include "../../char/diag/diagfwd.h" #include "../../char/diag/diagmem.h" #include "../../char/diag/diagchar_hdlc.h" #include "../../../arch/arm/mach-msm/7x30-lte/sdio_diag.h" static void fdiag_debugfs_init(void); #define USB_DIAG_IOC_MAGIC 0xFF #define USB_DIAG_FUNC_IOC_ENABLE_SET _IOW(USB_DIAG_IOC_MAGIC, 1, int) #define USB_DIAG_FUNC_IOC_ENABLE_GET _IOR(USB_DIAG_IOC_MAGIC, 2, int) #define USB_DIAG_FUNC_IOC_REGISTER_SET _IOW(USB_DIAG_IOC_MAGIC, 3, char *) #define USB_DIAG_FUNC_IOC_AMR_SET _IOW(USB_DIAG_IOC_MAGIC, 4, int) #define USB_DIAG_NV_7K9K_SET _IOW(USB_DIAG_IOC_MAGIC, 1, uint16_t *) #define USB_DIAG_NV_7KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 2, uint16_t *) #define USB_DIAG_NV_9KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 3, uint16_t *) #define USB_DIAG_NV_7K9KDIFF_SET _IOW(USB_DIAG_IOC_MAGIC, 4, uint16_t *) /* #define USB_DIAG_RC9_7K9K_SET _IOW(USB_DIAG_IOC_MAGIC, 5, uint16_t *) #define USB_DIAG_RC9_7KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 6, uint16_t *) #define USB_DIAG_RC9_9KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 7, uint16_t *) #define USB_DIAG_RC9_7K9KDIFF_SET _IOW(USB_DIAG_IOC_MAGIC, 8, uint16_t *) */ #define USB_DIAG_PRL_7K9K_SET _IOW(USB_DIAG_IOC_MAGIC, 9, uint16_t *) #define USB_DIAG_PRL_7KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 10, uint16_t *) #define USB_DIAG_PRL_9KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 11, uint16_t *) #define USB_DIAG_PRL_7K9KDIFF_SET _IOW(USB_DIAG_IOC_MAGIC, 12, uint16_t *) #define USB_DIAG_M29_7K9K_SET _IOW(USB_DIAG_IOC_MAGIC, 13, uint16_t *) #define USB_DIAG_M29_7KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 14, uint16_t *) #define USB_DIAG_M29_9KONLY_SET _IOW(USB_DIAG_IOC_MAGIC, 15, uint16_t *) #define USB_DIAG_M29_7K9KDIFF_SET _IOW(USB_DIAG_IOC_MAGIC, 16, uint16_t *) #define USB_DIAG_FUNC_IOC_MODEM_GET _IOR(USB_DIAG_IOC_MAGIC, 17, int) #define SMD_MAX 8192 #define NV_TABLE_SZ 128 #define M29_TABLE_SZ 10 #define PRL_TABLE_SZ 10 #define EPST_PREFIX 0xC8 #define HPST_PREFIX 0xF1 #define NO_PST 0 #define NO_DEF_ID 1 #define DM7K9K 2 #define DM7KONLY 3 #define DM9KONLY 4 #define DM7K9KDIFF 5 #define NO_DEF_ITEM 0xff #define MAX(x, y) (x > y ? x : y) #endif #if defined(CONFIG_MACH_MECHA) int sdio_diag_init_enable; #endif #if defined(CONFIG_MACH_VIGOR) static unsigned char *diag2arm9_buf_9k = NULL; #endif #if defined(CONFIG_USB_ANDROID_LTE_DIAG) int diag_init_enabled_state = 0; #endif int diag_configured; static DEFINE_SPINLOCK(ch_lock); static LIST_HEAD(usb_diag_ch_list); static struct usb_interface_descriptor intf_desc = { .bLength = sizeof intf_desc, .bDescriptorType = USB_DT_INTERFACE, .bNumEndpoints = 2, .bInterfaceClass = 0xFF, .bInterfaceSubClass = 0xFF, .bInterfaceProtocol = 0xFF, }; static struct usb_endpoint_descriptor hs_bulk_in_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_IN, .bmAttributes = USB_ENDPOINT_XFER_BULK, .wMaxPacketSize = __constant_cpu_to_le16(512), .bInterval = 0, }; static struct usb_endpoint_descriptor fs_bulk_in_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_IN, .bmAttributes = USB_ENDPOINT_XFER_BULK, .wMaxPacketSize = __constant_cpu_to_le16(64), .bInterval = 0, }; static struct usb_endpoint_descriptor hs_bulk_out_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_OUT, .bmAttributes = USB_ENDPOINT_XFER_BULK, .wMaxPacketSize = __constant_cpu_to_le16(512), .bInterval = 0, }; static struct usb_endpoint_descriptor fs_bulk_out_desc = { .bLength = USB_DT_ENDPOINT_SIZE, .bDescriptorType = USB_DT_ENDPOINT, .bEndpointAddress = USB_DIR_OUT, .bmAttributes = USB_ENDPOINT_XFER_BULK, .wMaxPacketSize = __constant_cpu_to_le16(64), .bInterval = 0, }; static struct usb_descriptor_header *fs_diag_desc[] = { (struct usb_descriptor_header *) &intf_desc, (struct usb_descriptor_header *) &fs_bulk_in_desc, (struct usb_descriptor_header *) &fs_bulk_out_desc, NULL, }; static struct usb_descriptor_header *hs_diag_desc[] = { (struct usb_descriptor_header *) &intf_desc, (struct usb_descriptor_header *) &hs_bulk_in_desc, (struct usb_descriptor_header *) &hs_bulk_out_desc, NULL, }; /** * struct diag_context - USB diag function driver private structure * @android_function: Used for registering with Android composite driver * @function: function structure for USB interface * @out: USB OUT endpoint struct * @in: USB IN endpoint struct * @in_desc: USB IN endpoint descriptor struct * @out_desc: USB OUT endpoint descriptor struct * @read_pool: List of requests used for Rx (OUT ep) * @write_pool: List of requests used for Tx (IN ep) * @config_work: Work item schedule after interface is configured to notify * CONNECT event to diag char driver and updating product id * and serial number to MODEM/IMEM. * @lock: Spinlock to proctect read_pool, write_pool lists * @cdev: USB composite device struct * @pdata: Platform data for this driver * @ch: USB diag channel * */ struct diag_context { struct android_usb_function android_function; struct usb_function function; struct usb_ep *out; struct usb_ep *in; struct usb_endpoint_descriptor *in_desc; struct usb_endpoint_descriptor *out_desc; struct list_head read_pool; struct list_head write_pool; struct work_struct config_work; spinlock_t lock; unsigned configured; struct usb_composite_dev *cdev; struct usb_diag_platform_data *pdata; struct usb_diag_ch ch; /* pkt counters */ unsigned long dpkts_tolaptop; unsigned long dpkts_tomodem; unsigned dpkts_tolaptop_pending; unsigned char i_serial_number; unsigned short product_id; int function_enable; #if DIAG_XPST spinlock_t req_lock; struct mutex user_lock; #define ID_TABLE_SZ 20 /* keep this small */ struct list_head rx_req_idle; struct list_head rx_req_user; wait_queue_head_t read_wq; char *user_read_buf; uint32_t user_read_len; char *user_readp; bool opened; /* list of registered command ids to be routed to userspace */ unsigned char id_table[ID_TABLE_SZ]; //smd_channel_t *ch; int online; int error; /* for slate test */ struct list_head rx_arm9_idle; struct list_head rx_arm9_done; struct mutex diag2arm9_lock; struct mutex diag2arm9_read_lock; struct mutex diag2arm9_write_lock; bool diag2arm9_opened; unsigned char toARM9_buf[SMD_MAX]; unsigned char DM_buf[USB_MAX_OUT_BUF]; unsigned read_arm9_count; unsigned char *read_arm9_buf; wait_queue_head_t read_arm9_wq; struct usb_request *read_arm9_req; u64 tx_count; /* to smd */ u64 rx_count; /* from smd */ u64 usb_in_count; /* to pc */ u64 usb_out_count; /* from pc */ #endif }; struct diag_context _context; static struct usb_diag_ch *legacych; static struct diag_context *legacyctxt; #if defined(CONFIG_USB_ANDROID_LTE_DIAG) static struct usb_diag_ch *mdmch; #endif static struct diag_context *mdmctxt; #if DIAG_XPST struct device diag_device; static char *htc_write_buf_copy; static struct diag_request htc_w_diag_req; static struct diag_request *htc_write_diag_req; #define TRX_REQ_BUF_SZ 8192 #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) static uint16_t nv7K9K_table[NV_TABLE_SZ] = {82, 0, 4, 5, 20, 21, 37, 258, 318, 460, 461, 462, 463, 464, 465, 466, 546, 707, 714, 854, 1943, 2825, 2953, 30000, 30001, 30002, 30003, 30004, 30005, 30006, 30007, 30008, 30010, 30013, 30014, 30015, 30018, 30019, 30021, 30031, 30032, 30033, 6, 8, 53, 54, 161, 162, 40, 42, 43, 57, 71, 82, 85, 168, 169, 170, 191, 192, 197, 219, 231, 240, 241, 256, 297, 298, 300, 423, 424, 429, 442, 450, 459, 495, 835, 855, 910, 933, 941, 945, 3634}; static uint16_t nv7Konly_table[NV_TABLE_SZ] = {43, 25, 27, 29, 32, 33, 34, 35, 36, 176, 177, 259, 260, 261, 262, 263, 264, 265, 296, 319, 374, 375, 67, 69, 70, 74, 178, 215, 179, 255, 285, 401, 403, 405, 409, 426, 452, 1018, 4102, 906, 30026, 30027, 30028, 30029}; static uint16_t nv7K9Kdiff_table[NV_TABLE_SZ] = {14, 11, 10, 441, 946, 30016, 30030, 562, 32768+11, 32768+10, 32768+441, 32768+946, 32768+30016, 32768+30030, 32768+562}; static uint16_t nv9Konly_table[NV_TABLE_SZ] = {7, 579, 580, 1192, 1194, 4204, 4964, 818}; /*mode reset */ static uint16_t M297K9K_table[M29_TABLE_SZ] = {4, 1, 2, 4, 5}; static uint16_t M297Konly_table[M29_TABLE_SZ]; static uint16_t M297K9Kdiff_table[M29_TABLE_SZ]; static uint16_t M299Konly_table[M29_TABLE_SZ]; /*PRL read/write*/ static uint16_t PRL7K9K_table[PRL_TABLE_SZ] = {1, 0}; static uint16_t PRL7Konly_table[PRL_TABLE_SZ]; static uint16_t PRL7K9Kdiff_table[PRL_TABLE_SZ]; static uint16_t PRL9Konly_table[PRL_TABLE_SZ]; #endif static struct usb_request *diag_req_new(unsigned len) { struct usb_request *req; if (len > SMD_MAX) return NULL; req = kmalloc(sizeof(struct usb_request), GFP_KERNEL); if (!req) return NULL; req->buf = kmalloc(len, GFP_KERNEL); if (!req->buf) { kfree(req); return NULL; } return req; } static void diag_req_free(struct usb_request *req) { if (!req) return; if (req->buf) { kfree(req->buf); req->buf = 0; } kfree(req); req = 0; } /* add a request to the tail of a list */ static void req_put(struct diag_context *ctxt, struct list_head *head, struct usb_request *req) { unsigned long flags; spin_lock_irqsave(&ctxt->req_lock, flags); list_add_tail(&req->list, head); spin_unlock_irqrestore(&ctxt->req_lock, flags); } /* remove a request from the head of a list */ static struct usb_request *req_get(struct diag_context *ctxt, struct list_head *head) { struct usb_request *req = 0; unsigned long flags; spin_lock_irqsave(&ctxt->req_lock, flags); if (!list_empty(head)) { req = list_first_entry(head, struct usb_request, list); list_del(&req->list); } spin_unlock_irqrestore(&ctxt->req_lock, flags); return req; } #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) int decode_encode_hdlc(void*data, int *len, unsigned char *buf_hdlc, int remove, int pos) { struct diag_send_desc_type send = { NULL, NULL, DIAG_STATE_START, 0 }; struct diag_hdlc_dest_type enc = { NULL, NULL, 0 }; struct diag_hdlc_decode_type hdlc; unsigned char *buf_9k = NULL; int ret; buf_9k = kzalloc(USB_MAX_OUT_BUF, GFP_KERNEL); if (!buf_9k) { DIAG_INFO("%s:out of memory\n", __func__); return -ENOMEM; } hdlc.dest_ptr = buf_9k; hdlc.dest_size = USB_MAX_OUT_BUF; hdlc.src_ptr = data; hdlc.src_size = *len; hdlc.src_idx = 0; hdlc.dest_idx = 0; hdlc.escaping = 0; ret = diag_hdlc_decode(&hdlc); if (!ret) { DIAG_INFO("Packet dropped due to bad HDLC coding/CRC\n"); kfree(buf_9k); return -EINVAL; } if (remove) *((char *)buf_9k+pos) = (*((char *)buf_9k+pos) ^ 0x80); else *((char *)buf_9k+pos) = (*((char *)buf_9k+pos) | 0x80); send.state = DIAG_STATE_START; send.pkt = hdlc.dest_ptr; send.last = (void *)(hdlc.dest_ptr + hdlc.dest_idx - 4); send.terminate = 1; enc.dest = buf_hdlc; enc.dest_last = (void *)(buf_hdlc + 2*hdlc.dest_idx - 3); diag_hdlc_encode(&send, &enc); print_hex_dump(KERN_DEBUG, "encode Data" , DUMP_PREFIX_ADDRESS, 16, 1, buf_hdlc, hdlc.dest_idx, 1); *len = hdlc.dest_idx; kfree(buf_9k); return 0; } #endif int checkcmd_modem_epst(unsigned char *buf) { #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) int j; uint16_t nv_num; uint16_t max_item; if (*buf == EPST_PREFIX) { if (*(buf+1) == 0x26 || *(buf+1) == 0x27) { max_item = MAX(MAX(nv7K9K_table[0], nv7Konly_table[0]), MAX(nv9Konly_table[0], nv7K9Kdiff_table[0])); nv_num = *((uint16_t *)(buf+2)); DIAG_INFO("%s: id = 0x%x nv_num = %d \n", __func__, *(buf+1), nv_num); for (j = 1; j < NV_TABLE_SZ; j++) { if (j <= nv7K9K_table[0] && nv7K9K_table[j] == nv_num) return DM7K9K; if (j <= nv7Konly_table[0] && nv7Konly_table[j] == nv_num) return DM7KONLY; if (j <= nv9Konly_table[0] && nv9Konly_table[j] == nv_num) return DM9KONLY; if (j <= nv7K9Kdiff_table[0] && nv7K9Kdiff_table[j] == nv_num) return DM7K9KDIFF; if (j > max_item) break; } return NO_DEF_ITEM; } else if (*(buf+1) == 0x48 || *(buf+1) == 0x49) { max_item = MAX(MAX(PRL7K9K_table[0], PRL7Konly_table[0]), MAX(PRL9Konly_table[0], PRL7K9Kdiff_table[0])); nv_num = *((uint16_t *)(buf+2)); DIAG_INFO("%s: id = 0x%x nv_num = %d \n", __func__, *(buf+1), nv_num); for (j = 1; j < PRL_TABLE_SZ; j++) { if (j <= PRL7K9K_table[0] && PRL7K9K_table[j] == nv_num) return DM7K9K; if (j <= PRL7Konly_table[0] && PRL7Konly_table[j] == nv_num) return DM7KONLY; if (j <= PRL9Konly_table[0] && PRL9Konly_table[j] == nv_num) return DM9KONLY; if (j <= PRL7K9Kdiff_table[0] && PRL7K9Kdiff_table[j] == nv_num) return DM7K9KDIFF; if (j > max_item) break; } return NO_DEF_ITEM; } else if (*(buf+1) == 0xC9) { nv_num = *(buf+2); DIAG_INFO("%s: id = 0x%x nv_num = %d \n", __func__, *(buf+1), nv_num); if (*(buf+2) == 0x01 || *(buf+2) == 0x11) return DM7K9K; else return NO_DEF_ITEM; } else if (*(buf+1) == 0x29) { max_item = MAX(MAX(M297K9K_table[0], M297Konly_table[0]), MAX(M299Konly_table[0], M297K9Kdiff_table[0])); nv_num = *((uint16_t *)(buf+2)); DIAG_INFO("%s: id = 0x%x nv_num = %d \n", __func__, *(buf+1), nv_num); for (j = 1; j < M29_TABLE_SZ; j++) { if (j <= M297K9K_table[0] && M297K9K_table[j] == nv_num) return DM7K9K; if (j <= M297Konly_table[0] && M297Konly_table[j] == nv_num) return DM7KONLY; if (j <= M299Konly_table[0] && M299Konly_table[j] == nv_num) return DM9KONLY; if (j <= M297K9Kdiff_table[0] && M297K9Kdiff_table[j] == nv_num) return DM7K9KDIFF; if (j > max_item) break; } return NO_DEF_ITEM; } else if (*(buf+1) == 0x41 || *(buf+1) == 0x0C || *(buf+1) == 0x40) { return DM7K9K; } else if (*(buf+1) == 0x00 || *(buf+1) == 0xCD || *(buf+1) == 0xD8 || *(buf+1) == 0x35 || *(buf+1) == 0x36 || *(buf+1) == 0x59) { return DM7KONLY; } else if (*(buf+1) == 0xDF || *(buf+1) == 0xEC) { return DM9KONLY; } else if (*(buf+1) == 0x4B && *(buf+2) == 0x0D) { return DM7KONLY; } else DIAG_INFO("%s:id = 0x%x no default routing path\n", __func__, *(buf+1)); return NO_DEF_ID; } else { /*DIAG_INFO("%s: not EPST_PREFIX id = 0x%x route to USB!!!\n", __func__, *buf);*/ return NO_PST; } #else if (_context.diag2arm9_opened) return DM7KONLY; else return NO_PST; #endif } int modem_to_userspace(void *buf, int r, int type, int is9k) { struct diag_context *ctxt = &_context; struct usb_request *req; #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) unsigned char value; #endif if (!ctxt->diag2arm9_opened) return 0; req = req_get(ctxt, &ctxt->rx_arm9_idle); if (!req) { DIAG_INFO("There is no enough request to ARM11!!\n"); return 0; } memcpy(req->buf, buf, r); #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) if (type == DM7K9KDIFF) { value = *((uint8_t *)req->buf+1); if ((value == 0x27) || (value == 0x26)) { if (is9k == 1) { decode_encode_hdlc(buf, &r, req->buf, 0, 3); } } } else if (type == NO_DEF_ID) { /*in this case, cmd may reply error message*/ value = *((uint8_t *)req->buf+2); DIAG_INFO("%s:check error cmd=0x%x message=ox%x\n", __func__ , value, *((uint8_t *)req->buf+1)); if ((value == 0x27) || (value == 0x26)) { if (is9k == 1) { decode_encode_hdlc(buf, &r, req->buf, 0, 4); } } } #endif if (is9k == 1) print_hex_dump(KERN_DEBUG, "DM Read Packet Data" " from 9k radio (first 16 Bytes): ", DUMP_PREFIX_ADDRESS, 16, 1, req->buf, 16, 1); else print_hex_dump(KERN_DEBUG, "DM Read Packet Data" " from 7k radio (first 16 Bytes): ", DUMP_PREFIX_ADDRESS, 16, 1, req->buf, 16, 1); // ctxt->rx_count += r; req->actual = r; req_put(ctxt, &ctxt->rx_arm9_done, req); wake_up(&ctxt->read_arm9_wq); return 1; } static long htc_diag_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct diag_context *ctxt = &_context; void __user *argp = (void __user *)arg; int tmp_value; unsigned long flags; unsigned char temp_id_table[ID_TABLE_SZ]; DIAG_INFO("%s:%s(parent:%s): tgid=%d\n", __func__, current->comm, current->parent->comm, current->tgid); if (_IOC_TYPE(cmd) != USB_DIAG_IOC_MAGIC) return -ENOTTY; switch (cmd) { case USB_DIAG_FUNC_IOC_ENABLE_SET: if (copy_from_user(&tmp_value, argp, sizeof(int))) return -EFAULT; DIAG_INFO("diag: enable %d\n", tmp_value); #if defined(CONFIG_MACH_VIGOR) android_enable_function(&mdmctxt->function, tmp_value); #endif android_enable_function(&_context.function, tmp_value); diag_smd_enable(driver->ch, "diag_ioctl", tmp_value); #if defined(CONFIG_MACH_MECHA) /* internal hub*/ smsc251x_mdm_port_sw(tmp_value); #endif /* force diag_read to return error when disable diag */ if (tmp_value == 0) ctxt->error = 1; wake_up(&ctxt->read_wq); break; case USB_DIAG_FUNC_IOC_ENABLE_GET: tmp_value = !_context.function.hidden; if (copy_to_user(argp, &tmp_value, sizeof(tmp_value))) return -EFAULT; break; case USB_DIAG_FUNC_IOC_REGISTER_SET: if (copy_from_user(temp_id_table, (unsigned char *)argp, ID_TABLE_SZ)) return -EFAULT; spin_lock_irqsave(&ctxt->req_lock, flags); memcpy(ctxt->id_table, temp_id_table, ID_TABLE_SZ); print_hex_dump(KERN_DEBUG, "ID_TABLE_SZ Data: ", DUMP_PREFIX_ADDRESS, 16, 1, temp_id_table, ID_TABLE_SZ, 1); spin_unlock_irqrestore(&ctxt->req_lock, flags); break; case USB_DIAG_FUNC_IOC_AMR_SET: /* if (copy_from_user(&ctxt->is2ARM11, argp, sizeof(int))) return -EFAULT;*/ DIAG_INFO("diag: fix me USB_DIAG_FUNC_IOC_AMR_SET\n"); break; default: return -ENOTTY; } return 0; } static ssize_t htc_diag_read(struct file *fp, char __user *buf, size_t count, loff_t *pos) { struct diag_context *ctxt = &_context; struct usb_request *req = 0; int ret = 0; DIAG_INFO("%s:%s(parent:%s): tgid=%d\n", __func__, current->comm, current->parent->comm, current->tgid); /* we will block until we're online */ if (!ctxt->online) { ret = wait_event_interruptible(ctxt->read_wq, (ctxt->online || ctxt->error)); if (ret < 0 || ctxt->error) return -EFAULT; } mutex_lock(&ctxt->user_lock); if (ctxt->user_read_len && ctxt->user_readp) { if (count > ctxt->user_read_len) count = ctxt->user_read_len; if (copy_to_user(buf, ctxt->user_readp, count)) ret = -EFAULT; else { ctxt->user_readp += count; ctxt->user_read_len -= count; ret = count; } goto end; } mutex_unlock(&ctxt->user_lock); ret = wait_event_interruptible(ctxt->read_wq, (req = req_get(ctxt, &ctxt->rx_req_user)) || !ctxt->online); mutex_lock(&ctxt->user_lock); if (ret < 0) { DIAG_INFO("%s: wait_event_interruptible error %d\n", __func__, ret); goto end; } if (!ctxt->online) { DIAG_INFO("%s: offline\n", __func__); ret = -EIO; goto end; } if (req) { if (req->actual == 0) { DIAG_INFO("%s: no data\n", __func__); goto end; } if (count > req->actual) count = req->actual; if (copy_to_user(buf, req->buf, count)) { ret = -EFAULT; goto end; } req->actual -= count; if (req->actual) { memcpy(ctxt->user_read_buf, req->buf + count, req->actual); ctxt->user_read_len = req->actual; ctxt->user_readp = ctxt->user_read_buf; } ret = count; } end: if (req) req_put(ctxt, &ctxt->rx_req_idle, req); mutex_unlock(&ctxt->user_lock); return ret; } static ssize_t htc_diag_write(struct file *fp, const char __user *buf, size_t count, loff_t *pos) { struct diag_context *ctxt = &_context; int ret = 0; DIAG_INFO("%s:%s(parent:%s): tgid=%d\n", __func__, current->comm, current->parent->comm, current->tgid); mutex_lock(&ctxt->user_lock); if (ret < 0) { DIAG_INFO("%s: wait_event_interruptible error %d\n", __func__, ret); goto end; } if (!ctxt->online) { DIAG_INFO("%s: offline\n", __func__); ret = -EIO; goto end; } if (count > TRX_REQ_BUF_SZ) count = TRX_REQ_BUF_SZ; if (!htc_write_buf_copy || !htc_write_diag_req) { ret = -EIO; goto end; } if (copy_from_user(htc_write_buf_copy, buf, count)) { ret = -EFAULT; DIAG_INFO("%s:EFAULT\n", __func__); goto end; } htc_write_diag_req->buf = htc_write_buf_copy; htc_write_diag_req->length = count; driver->in_busy_dmrounter = 1; ret = usb_diag_write(driver->legacy_ch, htc_write_diag_req); if (ret < 0) { DIAG_INFO("%s: usb_diag_write error %d\n", __func__, ret); goto end; } ret = count; end: mutex_unlock(&ctxt->user_lock); return ret; } static int htc_diag_open(struct inode *ip, struct file *fp) { struct diag_context *ctxt = &_context; int rc = 0; int n; struct usb_request *req; DIAG_INFO("%s:%s(parent:%s): tgid=%d\n", __func__, current->comm, current->parent->comm, current->tgid); mutex_lock(&ctxt->user_lock); if (ctxt->opened) { pr_err("%s: already opened\n", __func__); rc = -EBUSY; goto done; } ctxt->user_read_len = 0; ctxt->user_readp = 0; if (!ctxt->user_read_buf) { ctxt->user_read_buf = kmalloc(TRX_REQ_BUF_SZ, GFP_KERNEL); if (!ctxt->user_read_buf) { rc = -ENOMEM; goto done; } } if (!htc_write_buf_copy) { htc_write_buf_copy = (char *)kmalloc(TRX_REQ_BUF_SZ, GFP_KERNEL); if (!htc_write_buf_copy) { rc = -ENOMEM; kfree(ctxt->user_read_buf); goto done; } } if (!htc_write_diag_req) { htc_write_diag_req = &htc_w_diag_req; if (!htc_write_diag_req) { kfree(ctxt->user_read_buf); kfree(htc_write_buf_copy); rc = -ENOMEM; goto done; } } /* clear pending data if any */ while ((req = req_get(ctxt, &ctxt->rx_req_idle))) diag_req_free(req); for (n = 0; n < 10; n++) { req = diag_req_new(SMD_MAX); if (!req) { while ((req = req_get(ctxt, &ctxt->rx_req_idle))) diag_req_free(req); rc = -EFAULT; goto done; } req_put(ctxt, &ctxt->rx_req_idle, req); } ctxt->opened = true; /* clear the error latch */ ctxt->error = 0; done: mutex_unlock(&ctxt->user_lock); return rc; } static int htc_diag_release(struct inode *ip, struct file *fp) { struct diag_context *ctxt = &_context; struct usb_request *req; DIAG_INFO("%s: \n", __func__); mutex_lock(&ctxt->user_lock); ctxt->opened = false; ctxt->user_read_len = 0; ctxt->user_readp = 0; if (ctxt->user_read_buf) { kfree(ctxt->user_read_buf); ctxt->user_read_buf = 0; } if (htc_write_buf_copy) { kfree(htc_write_buf_copy); htc_write_buf_copy = 0; } if (htc_write_diag_req) htc_write_diag_req = 0; while ((req = req_get(ctxt, &ctxt->rx_req_idle))) diag_req_free(req); while ((req = req_get(ctxt, &ctxt->rx_req_user))) diag_req_free(req); mutex_unlock(&ctxt->user_lock); return 0; } static struct file_operations htc_diag_fops = { .owner = THIS_MODULE, .read = htc_diag_read, .write = htc_diag_write, .open = htc_diag_open, .release = htc_diag_release, .unlocked_ioctl = htc_diag_ioctl, }; static struct miscdevice htc_diag_device_fops = { .minor = MISC_DYNAMIC_MINOR, .name = "htcdiag", .fops = &htc_diag_fops, }; static int if_route_to_userspace(struct diag_context *ctxt, unsigned int cmd) { unsigned long flags; int i; unsigned short tmp; unsigned char cmd_id, cmd_num; tmp = (unsigned short)cmd; cmd_num = (unsigned char)(tmp >> 8); cmd_id = (unsigned char)(tmp & 0x00ff); if (!ctxt->opened || cmd_id == 0) return 0; /* command ids 0xfb..0xff are not used by msm diag; we steal these ids * for communication between userspace tool and host test tool. */ /*printk("cmd_num=%d cmd_id=%d\n", cmd_num, cmd_id);*/ if (cmd_id >= 0xfb && cmd_id <= 0xff) return 1; spin_lock_irqsave(&ctxt->req_lock, flags); for (i = 0; i < ARRAY_SIZE(ctxt->id_table); i = i+2) if (ctxt->id_table[i] == cmd_id) { /* if the command id equals to any of registered ids, * route to userspace to handle. */ if (ctxt->id_table[i+1] == cmd_num || ctxt->id_table[i+1] == 0xff) { spin_unlock_irqrestore(&ctxt->req_lock, flags); return 1; } } spin_unlock_irqrestore(&ctxt->req_lock, flags); return 0; } #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) static long diag2arm9_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct diag_context *ctxt = &_context; void __user *argp = (void __user *)arg; unsigned long flags; uint16_t temp_nv_table[NV_TABLE_SZ]; int table_size; uint16_t *table_ptr; if (_IOC_TYPE(cmd) != USB_DIAG_IOC_MAGIC) return -ENOTTY; DIAG_INFO("%s:%s(parent:%s): tgid=%d\n", __func__, current->comm, current->parent->comm, current->tgid); switch (cmd) { case USB_DIAG_NV_7K9K_SET: DIAG_INFO("USB_DIAG_NV_7K9K_SET\n"); table_size = NV_TABLE_SZ; table_ptr = nv7K9K_table; break; case USB_DIAG_NV_7KONLY_SET: DIAG_INFO("USB_DIAG_NV_7KONLY_SET\n"); table_size = NV_TABLE_SZ; table_ptr = nv7Konly_table; break; case USB_DIAG_NV_9KONLY_SET: DIAG_INFO("USB_DIAG_NV_9KONLY_SET\n"); table_size = NV_TABLE_SZ; table_ptr = nv9Konly_table; break; case USB_DIAG_NV_7K9KDIFF_SET: DIAG_INFO("USB_DIAG_NV_7K9KDIFF_SET\n"); table_size = NV_TABLE_SZ; table_ptr = nv7K9Kdiff_table; break; case USB_DIAG_PRL_7K9K_SET: DIAG_INFO("USB_DIAG_PRL_7K9K_SET\n"); table_size = PRL_TABLE_SZ; table_ptr = PRL7K9K_table; break; case USB_DIAG_PRL_7KONLY_SET: DIAG_INFO("USB_DIAG_PRL_7KONLY_SET\n"); table_size = PRL_TABLE_SZ; table_ptr = PRL7Konly_table; break; case USB_DIAG_PRL_9KONLY_SET: DIAG_INFO("USB_DIAG_PRL_9KONLY_SET\n"); table_size = PRL_TABLE_SZ; table_ptr = PRL9Konly_table; break; case USB_DIAG_PRL_7K9KDIFF_SET: DIAG_INFO("USB_DIAG_PRL_7K9KDIFF_SET\n"); table_size = PRL_TABLE_SZ; table_ptr = PRL7K9Kdiff_table; break; case USB_DIAG_M29_7K9K_SET: DIAG_INFO("USB_DIAG_M29_7K9K_SET\n"); table_size = M29_TABLE_SZ; table_ptr = M297K9K_table; break; case USB_DIAG_M29_7KONLY_SET: DIAG_INFO("USB_DIAG_M29_7KONLY_SET\n"); table_size = M29_TABLE_SZ; table_ptr = M297Konly_table; break; case USB_DIAG_M29_9KONLY_SET: DIAG_INFO("USB_DIAG_M29_9KONLY_SET\n"); table_size = M29_TABLE_SZ; table_ptr = M299Konly_table; break; case USB_DIAG_M29_7K9KDIFF_SET: DIAG_INFO("USB_DIAG_M29_7K9KDIFF_SET\n"); table_size = M29_TABLE_SZ; table_ptr = M297K9Kdiff_table; break; case USB_DIAG_FUNC_IOC_MODEM_GET: DIAG_INFO("%s:modem status=%d\n", __func__, sdio_diag_initialized); if (copy_to_user(argp, &sdio_diag_initialized, sizeof(sdio_diag_initialized))) return -EFAULT; else return 0; break; default: return -ENOTTY; } if (copy_from_user(temp_nv_table, (uint8_t *)argp, (table_size*2))) return -EFAULT; DIAG_INFO("%s:input %d item\n", __func__, temp_nv_table[0]); if (temp_nv_table[0] > table_size) return -EFAULT; spin_lock_irqsave(&ctxt->req_lock, flags); memcpy((uint8_t *)table_ptr, (uint8_t *)&temp_nv_table[0], (temp_nv_table[0]+1)*2); print_hex_dump(KERN_DEBUG, "TABLE Data: ", DUMP_PREFIX_ADDRESS, 16, 1, table_ptr, (*table_ptr+1)*2, 1); spin_unlock_irqrestore(&ctxt->req_lock, flags); return 0; } #endif static int diag2arm9_open(struct inode *ip, struct file *fp) { struct diag_context *ctxt = &_context; struct usb_request *req; int rc = 0; int n; DIAG_INFO("%s\n", __func__); mutex_lock(&ctxt->diag2arm9_lock); if (ctxt->diag2arm9_opened) { pr_err("%s: already opened\n", __func__); rc = -EBUSY; goto done; } /* clear pending data if any */ while ((req = req_get(ctxt, &ctxt->rx_arm9_done))) diag_req_free(req); for (n = 0; n < 8; n++) { req = diag_req_new(SMD_MAX); if (!req) { while ((req = req_get(ctxt, &ctxt->rx_arm9_idle))) diag_req_free(req); rc = -EFAULT; goto done; } req_put(ctxt, &ctxt->rx_arm9_idle, req); } ctxt->read_arm9_count = 0; ctxt->read_arm9_buf = 0; ctxt->read_arm9_req = 0; ctxt->diag2arm9_opened = true; diag_smd_enable(driver->ch, "diag2arm9_open", SMD_FUNC_OPEN_DIAG); #if defined(CONFIG_MACH_VIGOR) diag2arm9_buf_9k = kzalloc(USB_MAX_OUT_BUF, GFP_KERNEL); #endif done: mutex_unlock(&ctxt->diag2arm9_lock); return rc; } static int diag2arm9_release(struct inode *ip, struct file *fp) { struct diag_context *ctxt = &_context; struct usb_request *req; DIAG_INFO("%s\n", __func__); mutex_lock(&ctxt->diag2arm9_lock); ctxt->diag2arm9_opened = false; wake_up(&ctxt->read_arm9_wq); mutex_lock(&ctxt->diag2arm9_read_lock); while ((req = req_get(ctxt, &ctxt->rx_arm9_idle))) diag_req_free(req); while ((req = req_get(ctxt, &ctxt->rx_arm9_done))) diag_req_free(req); if (ctxt->read_arm9_req) diag_req_free(ctxt->read_arm9_req); mutex_unlock(&ctxt->diag2arm9_read_lock); /************************************* * If smd is closed, it will lead to slate can't be tested. * slate will open it for one time * but close it for several times and never open *************************************/ /*smd_diag_enable("diag2arm9_release", 0);*/ mutex_unlock(&ctxt->diag2arm9_lock); #if defined(CONFIG_MACH_VIGOR) kfree(diag2arm9_buf_9k); #endif return 0; } static ssize_t diag2arm9_write(struct file *fp, const char __user *buf, size_t count, loff_t *pos) { struct diag_context *ctxt = &_context; int r = count; int writed = 0; #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) int path; #if defined(CONFIG_MACH_VIGOR) struct diag_hdlc_decode_type hdlc; int ret; #endif #if defined(CONFIG_MACH_MECHA) unsigned char *buf_9k = NULL; #endif #endif mutex_lock(&ctxt->diag2arm9_write_lock); DIAG_INFO("%s : count = %d\n", __func__, count); while (count > 0) { writed = count > USB_MAX_OUT_BUF ? USB_MAX_OUT_BUF : count; if (copy_from_user(ctxt->DM_buf, buf, writed)) { r = -EFAULT; break; } if (driver->ch == NULL) { DIAG_INFO("%s: driver->ch == NULL", __func__); r = -EFAULT; break; } else if (ctxt->toARM9_buf == NULL) { DIAG_INFO("%s: ctxt->toARM9_buf == NULL", __func__); r = -EFAULT; break; } #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) path = checkcmd_modem_epst(ctxt->DM_buf); print_hex_dump(KERN_DEBUG, "DM Packet Data" " write to radio ", DUMP_PREFIX_ADDRESS, 16, 1, ctxt->DM_buf, writed, 1); switch (path) { case DM7K9K: DIAG_INFO("%s:above date to DM7K9K\n", __func__); /* send to 9k before decode HDLC*/ #if defined(CONFIG_MACH_MECHA) if (sdio_diag_initialized) { buf_9k = kzalloc(writed, GFP_KERNEL); if (!buf_9k) { DIAG_INFO("%s:out of memory\n", __func__); mutex_unlock(&ctxt->diag2arm9_write_lock); return -ENOMEM; } memcpy(buf_9k, ctxt->DM_buf, writed); msm_sdio_diag_write((void *)buf_9k, writed); buf_9k = NULL; } smd_write(driver->ch, ctxt->DM_buf, writed); #endif #if defined(CONFIG_MACH_VIGOR) if (driver->sdio_ch) { memcpy(diag2arm9_buf_9k, ctxt->DM_buf, writed); sdio_write(driver->sdio_ch, diag2arm9_buf_9k, writed); } else { DIAG_INFO("%s: sdio ch fails\n", __func__); } /* send to 8k after decode HDLC*/ hdlc.dest_ptr = ctxt->toARM9_buf; hdlc.dest_size = SMD_MAX; hdlc.src_ptr = ctxt->DM_buf; hdlc.src_size = writed; hdlc.src_idx = 0; hdlc.dest_idx = 0; hdlc.escaping = 0; ret = diag_hdlc_decode(&hdlc); if (!ret) { DIAG_INFO("Packet dropped due to bad HDLC coding/CRC\n"); r = -EFAULT; break; } smd_write(driver->ch, ctxt->toARM9_buf, hdlc.dest_idx-3); #endif break; case DM9KONLY: DIAG_INFO("%s:above date to DM9KONLY\n", __func__); #if defined(CONFIG_MACH_MECHA) if (sdio_diag_initialized) { buf_9k = kzalloc(writed, GFP_KERNEL); if (!buf_9k) { DIAG_INFO("%s:out of memory\n", __func__); mutex_unlock(&ctxt->diag2arm9_write_lock); return -ENOMEM; } memcpy(buf_9k, ctxt->DM_buf, writed); msm_sdio_diag_write((void *)buf_9k, writed); buf_9k = NULL; } #endif #if defined(CONFIG_MACH_VIGOR) if (driver->sdio_ch) { memcpy(diag2arm9_buf_9k, ctxt->DM_buf, writed); sdio_write(driver->sdio_ch, diag2arm9_buf_9k, writed); } else { DIAG_INFO("%s: sdio ch fails\n", __func__); } #endif break; case DM7K9KDIFF: DIAG_INFO("%s:above data to DM7K9KDIFF\n", __func__); /* send to 9k before decode HDLC*/ if ((ctxt->DM_buf[3] & 0x80) == 0x80) { DIAG_INFO("%s:DM7K9KDIFF to 9K\n", __func__); #if defined(CONFIG_MACH_MECHA) if (sdio_diag_initialized) { buf_9k = kzalloc(USB_MAX_OUT_BUF, GFP_KERNEL); if (!buf_9k) { DIAG_INFO("%s:out of memory\n", __func__); mutex_unlock(&ctxt->diag2arm9_write_lock); return -ENOMEM; } if (decode_encode_hdlc(ctxt->DM_buf, &writed, buf_9k, 1, 3)) { kfree(buf_9k); mutex_unlock(&ctxt->diag2arm9_write_lock); return -EINVAL; } msm_sdio_diag_write((void *)buf_9k, writed); buf_9k = NULL; } #endif #if defined(CONFIG_MACH_VIGOR) if (driver->sdio_ch) { if (decode_encode_hdlc(ctxt->DM_buf, &writed, diag2arm9_buf_9k, 1, 3)) { mutex_unlock(&ctxt->diag2arm9_write_lock); return -EINVAL; } sdio_write(driver->sdio_ch, diag2arm9_buf_9k, writed); } else { DIAG_INFO("%s: sdio ch fails\n", __func__); } #endif } else { DIAG_INFO("%s:DM7K9KDIFF to 7K\n", __func__); #if defined(CONFIG_MACH_MECHA) smd_write(driver->ch, ctxt->DM_buf, writed); #endif #if defined(CONFIG_MACH_VIGOR) /* send to 8k after decode HDLC*/ hdlc.dest_ptr = ctxt->toARM9_buf; hdlc.dest_size = SMD_MAX; hdlc.src_ptr = ctxt->DM_buf; hdlc.src_size = writed; hdlc.src_idx = 0; hdlc.dest_idx = 0; hdlc.escaping = 0; ret = diag_hdlc_decode(&hdlc); if (!ret) { DIAG_INFO("Packet dropped due to bad HDLC coding/CRC\n"); r = -EFAULT; break; } smd_write(driver->ch, ctxt->toARM9_buf, hdlc.dest_idx-3); #endif } break; case DM7KONLY: DIAG_INFO("%s:above data to DM7KONLY\n", __func__); #if defined(CONFIG_MACH_MECHA) smd_write(driver->ch, ctxt->DM_buf, writed); #endif #if defined(CONFIG_MACH_VIGOR) /* send to 8k after decode HDLC*/ hdlc.dest_ptr = ctxt->toARM9_buf; hdlc.dest_size = SMD_MAX; hdlc.src_ptr = ctxt->DM_buf; hdlc.src_size = writed; hdlc.src_idx = 0; hdlc.dest_idx = 0; hdlc.escaping = 0; ret = diag_hdlc_decode(&hdlc); if (!ret) { DIAG_INFO("Packet dropped due to bad HDLC coding/CRC\n"); r = -EFAULT; break; } smd_write(driver->ch, ctxt->toARM9_buf, hdlc.dest_idx-3); #endif break; case NO_DEF_ID: case NO_DEF_ITEM: default: DIAG_INFO("%s:no default routing path\n", __func__); print_hex_dump(KERN_DEBUG, "DM Packet Data" " write to radio ", DUMP_PREFIX_ADDRESS, 16, 1, ctxt->DM_buf, writed, 1); } #endif buf += writed; count -= writed; if (count) DIAG_INFO("%s :[WARN] count = %d\n", __func__, count); } mutex_unlock(&ctxt->diag2arm9_write_lock); return r; } static ssize_t diag2arm9_read(struct file *fp, char __user *buf, size_t count, loff_t *pos) { struct diag_context *ctxt = &_context; struct usb_request *req; int r = 0, xfer; int ret; DIAG_INFO("%s\n", __func__); mutex_lock(&ctxt->diag2arm9_read_lock); /* if we have data pending, give it to userspace */ if (ctxt->read_arm9_count > 0) req = ctxt->read_arm9_req; else { retry: /* get data from done queue */ req = 0; ret = wait_event_interruptible(ctxt->read_arm9_wq, ((req = req_get(ctxt, &ctxt->rx_arm9_done)) || !ctxt->diag2arm9_opened)); if (!ctxt->diag2arm9_opened) { if (req) req_put(ctxt, &ctxt->rx_arm9_idle, req); goto done; } if (ret < 0 || req == 0) goto done; if (req->actual == 0) { req_put(ctxt, &ctxt->rx_arm9_idle, req); goto retry; } ctxt->read_arm9_req = req; ctxt->read_arm9_count = req->actual; ctxt->read_arm9_buf = req->buf; } xfer = (ctxt->read_arm9_count < count) ? ctxt->read_arm9_count : count; if (copy_to_user(buf, ctxt->read_arm9_buf, xfer)) { DIAG_INFO("diag: copy_to_user fail\n"); req_put(ctxt, &ctxt->rx_arm9_idle, ctxt->read_arm9_req); r = -EFAULT; goto done; } ctxt->read_arm9_buf += xfer; ctxt->read_arm9_count -= xfer; r += xfer; /* if we've emptied the buffer, release the request */ if (ctxt->read_arm9_count == 0) { print_hex_dump(KERN_DEBUG, "DM Packet Data" " read from radio ", DUMP_PREFIX_ADDRESS, 16, 1, req->buf, req->actual, 1); req_put(ctxt, &ctxt->rx_arm9_idle, ctxt->read_arm9_req); ctxt->read_arm9_req = 0; } done: mutex_unlock(&ctxt->diag2arm9_read_lock); return r; } static struct file_operations diag2arm9_fops = { .owner = THIS_MODULE, .open = diag2arm9_open, .release = diag2arm9_release, .write = diag2arm9_write, .read = diag2arm9_read, #if defined(CONFIG_MACH_MECHA) || defined(CONFIG_MACH_VIGOR) .unlocked_ioctl = diag2arm9_ioctl, #endif }; static struct miscdevice diag2arm9_device = { .minor = MISC_DYNAMIC_MINOR, .name = "diag_arm9", .fops = &diag2arm9_fops, }; #endif static inline struct diag_context *func_to_dev(struct usb_function *f) { return container_of(f, struct diag_context, function); } static void usb_config_work_func(struct work_struct *work) { struct diag_context *ctxt = container_of(work, struct diag_context, config_work); #if 0 struct usb_composite_dev *cdev = ctxt->cdev; struct usb_gadget_strings *table; struct usb_string *s; #endif DIAG_INFO("%s: dev=%s\n", __func__, (ctxt == mdmctxt)?DIAG_MDM:DIAG_LEGACY); ctxt->tx_count = ctxt->rx_count = 0; ctxt->usb_in_count = ctxt->usb_out_count = 0; driver->diag_smd_count = driver->diag_qdsp_count = 0; if (ctxt->ch.notify && (!driver->usb_connected)) ctxt->ch.notify(ctxt->ch.priv, USB_DIAG_CONNECT, NULL); #if 0 if (!ctxt->pdata) return; /* pass on product id and serial number to dload */ if (!cdev->desc.iSerialNumber) { ctxt->pdata->update_pid_and_serial_num( cdev->desc.idProduct, 0); return; } /* * Serial number is filled by the composite driver. So * it is fair enough to assume that it will always be * found at first table of strings. */ table = *(cdev->driver->strings); for (s = table->strings; s && s->s; s++) if (s->id == cdev->desc.iSerialNumber) { ctxt->pdata->update_pid_and_serial_num( cdev->desc.idProduct, s->s); break; } #endif } static void diag_write_complete(struct usb_ep *ep , struct usb_request *req) { struct diag_context *ctxt = ep->driver_data; struct diag_request *d_req = req->context; unsigned long flags; if (ctxt == NULL) { DIAG_INFO("%s: requesting" "NULL device pointer\n", __func__); return; } ctxt->dpkts_tolaptop_pending--; if (!req->status) { if ((req->length >= ep->maxpacket) && ((req->length % ep->maxpacket) == 0)) { ctxt->dpkts_tolaptop_pending++; req->length = 0; d_req->actual = req->actual; d_req->status = req->status; /* Queue zero length packet */ usb_ep_queue(ctxt->in, req, GFP_ATOMIC); return; } } spin_lock_irqsave(&ctxt->lock, flags); list_add_tail(&req->list, &ctxt->write_pool); if (req->length != 0) { d_req->actual = req->actual; d_req->status = req->status; } spin_unlock_irqrestore(&ctxt->lock, flags); if (ctxt->ch.notify) ctxt->ch.notify(ctxt->ch.priv, USB_DIAG_WRITE_DONE, d_req); } static void diag_read_complete(struct usb_ep *ep , struct usb_request *req) { struct diag_context *ctxt = ep->driver_data; struct diag_request *d_req = req->context; struct usb_request *xpst_req; unsigned long flags; #if DIAG_XPST unsigned int cmd_id; #endif d_req->actual = req->actual; d_req->status = req->status; spin_lock_irqsave(&ctxt->lock, flags); list_add_tail(&req->list, &ctxt->read_pool); spin_unlock_irqrestore(&ctxt->lock, flags); ctxt->dpkts_tomodem++; #if DIAG_XPST #ifdef HTC_DIAG_DEBUG DIAG_INFO("%s: dev=%s\n", __func__, (ctxt == mdmctxt)?DIAG_MDM:DIAG_LEGACY); print_hex_dump(KERN_DEBUG, "from PC: ", DUMP_PREFIX_ADDRESS, 16, 1, req->buf, req->actual, 1); #endif cmd_id = *((unsigned short *)req->buf); if ((ctxt != mdmctxt) && if_route_to_userspace(ctxt, cmd_id)) { xpst_req = req_get(ctxt, &ctxt->rx_req_idle); if (xpst_req) { xpst_req->actual = req->actual; xpst_req->status = req->status; memcpy(xpst_req->buf, req->buf, req->actual); req_put(ctxt, &ctxt->rx_req_user, xpst_req); wake_up(&ctxt->read_wq); driver->nohdlc = 1; } else DIAG_INFO("%s No enough xpst_req \n", __func__); } else { driver->nohdlc = 0; ctxt->tx_count += req->actual; } #endif ctxt->usb_out_count += req->actual; if (ctxt->ch.notify) ctxt->ch.notify(ctxt->ch.priv, USB_DIAG_READ_DONE, d_req); } /** * usb_diag_open() - Open a diag channel over USB * @name: Name of the channel * @priv: Private structure pointer which will be passed in notify() * @notify: Callback function to receive notifications * * This function iterates overs the available channels and returns * the channel handler if the name matches. The notify callback is called * for CONNECT, DISCONNECT, READ_DONE and WRITE_DONE events. * */ struct usb_diag_ch *usb_diag_open(const char *name, void *priv, void (*notify)(void *, unsigned, struct diag_request *)) { struct usb_diag_ch *ch; unsigned long flags; int found = 0; DIAG_DBUG("%s: \n", __func__); spin_lock_irqsave(&ch_lock, flags); list_for_each_entry(ch, &usb_diag_ch_list, list) { if (!strcmp(name, ch->name)) { found = 1; break; } } if (!found) { ch = ERR_PTR(-ENOENT); goto out; } if (ch->priv) { ch = ERR_PTR(-EBUSY); goto out; } ch->priv = priv; ch->notify = notify; out: spin_unlock_irqrestore(&ch_lock, flags); return ch; } EXPORT_SYMBOL(usb_diag_open); /** * usb_diag_close() - Close a diag channel over USB * @ch: Channel handler * * This function closes the diag channel. * */ void usb_diag_close(struct usb_diag_ch *ch) { unsigned long flags; DIAG_DBUG("%s: \n", __func__); spin_lock_irqsave(&ch_lock, flags); ch->priv = NULL; ch->notify = NULL; spin_unlock_irqrestore(&ch_lock, flags); } EXPORT_SYMBOL(usb_diag_close); /** * usb_diag_free_req() - Free USB requests * @ch: Channel handler * * This function free read and write USB requests for the interface * associated with this channel. * */ void usb_diag_free_req(struct usb_diag_ch *ch) { struct diag_context *ctxt = ch->priv_usb; struct usb_request *req; struct list_head *act, *tmp; DIAG_INFO("%s: dev=%s\n", __func__, (ctxt == mdmctxt)?DIAG_MDM:DIAG_LEGACY); if (!ctxt) return; list_for_each_safe(act, tmp, &ctxt->write_pool) { req = list_entry(act, struct usb_request, list); list_del(&req->list); usb_ep_free_request(ctxt->in, req); } list_for_each_safe(act, tmp, &ctxt->read_pool) { req = list_entry(act, struct usb_request, list); list_del(&req->list); usb_ep_free_request(ctxt->out, req); } } EXPORT_SYMBOL(usb_diag_free_req); /** * usb_diag_alloc_req() - Allocate USB requests * @ch: Channel handler * @n_write: Number of requests for Tx * @n_read: Number of requests for Rx * * This function allocate read and write USB requests for the interface * associated with this channel. The actual buffer is not allocated. * The buffer is passed by diag char driver. * */ int usb_diag_alloc_req(struct usb_diag_ch *ch, int n_write, int n_read) { struct diag_context *ctxt = ch->priv_usb; struct usb_request *req; int i; DIAG_INFO("%s: dev=%s\n", __func__, (ctxt == mdmctxt)?DIAG_MDM:DIAG_LEGACY); if (!ctxt) return -ENODEV; for (i = 0; i < n_write; i++) { if (!ctxt->in) goto fail; req = usb_ep_alloc_request(ctxt->in, GFP_ATOMIC); if (!req) goto fail; req->complete = diag_write_complete; list_add_tail(&req->list, &ctxt->write_pool); } for (i = 0; i < n_read; i++) { if (!ctxt->out) goto fail; req = usb_ep_alloc_request(ctxt->out, GFP_ATOMIC); if (!req) goto fail; req->complete = diag_read_complete; list_add_tail(&req->list, &ctxt->read_pool); } return 0; fail: usb_diag_free_req(ch); return -ENOMEM; } EXPORT_SYMBOL(usb_diag_alloc_req); /** * usb_diag_read() - Read data from USB diag channel * @ch: Channel handler * @d_req: Diag request struct * * Enqueue a request on OUT endpoint of the interface corresponding to this * channel. This function returns proper error code when interface is not * in configured state, no Rx requests available and ep queue is failed. * * This function operates asynchronously. READ_DONE event is notified after * completion of OUT request. * */ int usb_diag_read(struct usb_diag_ch *ch, struct diag_request *d_req) { struct diag_context *ctxt = ch->priv_usb; unsigned long flags; struct usb_request *req = NULL; #ifdef HTC_DIAG_DEBUG DIAG_DBUG("%s: \n", __func__); #endif spin_lock_irqsave(&ctxt->lock, flags); if (!ctxt->configured) { spin_unlock_irqrestore(&ctxt->lock, flags); return -EIO; } if (list_empty(&ctxt->read_pool)) { spin_unlock_irqrestore(&ctxt->lock, flags); ERROR(ctxt->cdev, "%s: no requests available\n", __func__); return -EAGAIN; } req = list_first_entry(&ctxt->read_pool, struct usb_request, list); list_del(&req->list); spin_unlock_irqrestore(&ctxt->lock, flags); req->buf = d_req->buf; req->length = d_req->length; req->context = d_req; if (usb_ep_queue(ctxt->out, req, GFP_ATOMIC)) { /* If error add the link to linked list again*/ spin_lock_irqsave(&ctxt->lock, flags); list_add_tail(&req->list, &ctxt->read_pool); spin_unlock_irqrestore(&ctxt->lock, flags); ERROR(ctxt->cdev, "%s: cannot queue" " read request\n", __func__); return -EIO; } return 0; } EXPORT_SYMBOL(usb_diag_read); /** * usb_diag_write() - Write data from USB diag channel * @ch: Channel handler * @d_req: Diag request struct * * Enqueue a request on IN endpoint of the interface corresponding to this * channel. This function returns proper error code when interface is not * in configured state, no Tx requests available and ep queue is failed. * * This function operates asynchronously. WRITE_DONE event is notified after * completion of IN request. * */ int usb_diag_write(struct usb_diag_ch *ch, struct diag_request *d_req) { struct diag_context *ctxt = ch->priv_usb; unsigned long flags; struct usb_request *req = NULL; #ifdef HTC_DIAG_DEBUG DIAG_DBUG("%s: \n", __func__); #endif spin_lock_irqsave(&ctxt->lock, flags); if (!ctxt->configured) { spin_unlock_irqrestore(&ctxt->lock, flags); return -EIO; } if (list_empty(&ctxt->write_pool)) { spin_unlock_irqrestore(&ctxt->lock, flags); ERROR(ctxt->cdev, "%s: no requests available\n", __func__); return -EAGAIN; } req = list_first_entry(&ctxt->write_pool, struct usb_request, list); list_del(&req->list); spin_unlock_irqrestore(&ctxt->lock, flags); req->buf = d_req->buf; req->length = d_req->length; req->context = d_req; if (usb_ep_queue(ctxt->in, req, GFP_ATOMIC)) { /* If error add the link to linked list again*/ spin_lock_irqsave(&ctxt->lock, flags); list_add_tail(&req->list, &ctxt->write_pool); spin_unlock_irqrestore(&ctxt->lock, flags); ERROR(ctxt->cdev, "%s: cannot queue" " read request\n", __func__); return -EIO; } ctxt->usb_in_count += d_req->length; ctxt->dpkts_tolaptop++; ctxt->dpkts_tolaptop_pending++; return 0; } EXPORT_SYMBOL(usb_diag_write); struct usb_diag_ch *diag_setup(void) { unsigned long flags; static int debugfs_init; #ifdef HTC_DIAG_DEBUG DIAG_DBUG("%s: \n", __func__); #endif /* ctxt = kzalloc(sizeof(*ctxt), GFP_KERNEL);*/ legacyctxt = &_context; legacych = &legacyctxt->ch; spin_lock_irqsave(&ch_lock, flags); legacych->name = DIAG_LEGACY; list_add_tail(&legacych->list, &usb_diag_ch_list); spin_unlock_irqrestore(&ch_lock, flags); DIAG_INFO("%s: ch->name:%s ctxt:%p pkts_pending:%p\n", __func__, legacych->name, legacyctxt, &legacyctxt->dpkts_tolaptop_pending); #if defined(CONFIG_USB_ANDROID_LTE_DIAG) mdmctxt = kzalloc(sizeof(*mdmctxt), GFP_KERNEL); if (!mdmctxt) return ERR_PTR(-ENOMEM); mdmch = &mdmctxt->ch; spin_lock_irqsave(&ch_lock, flags); mdmch->name = DIAG_MDM; list_add_tail(&mdmch->list, &usb_diag_ch_list); spin_unlock_irqrestore(&ch_lock, flags); DIAG_INFO("%s: ch->name:%s ctxt:%p pkts_pending:%p\n", __func__, mdmch->name, mdmctxt, &mdmctxt->dpkts_tolaptop_pending); #endif if (!debugfs_init) { debugfs_init = 1; fdiag_debugfs_init(); } return legacych; } EXPORT_SYMBOL(diag_setup); static void diag_function_disable(struct usb_function *f) { struct diag_context *dev = func_to_dev(f); unsigned long flags; DIAG_INFO("%s: dev=%s\n", __func__, (dev == mdmctxt)?DIAG_MDM:DIAG_LEGACY); spin_lock_irqsave(&dev->lock, flags); diag_configured = dev->configured = 0; spin_unlock_irqrestore(&dev->lock, flags); if (dev->ch.notify && (driver->usb_connected)) dev->ch.notify(dev->ch.priv, USB_DIAG_DISCONNECT, NULL); usb_ep_disable(dev->in); dev->in->driver_data = NULL; usb_ep_disable(dev->out); dev->out->driver_data = NULL; #if DIAG_XPST if (dev == legacyctxt) { dev->online = 0; wake_up(&dev->read_wq); } #endif } static int diag_function_set_alt(struct usb_function *f, unsigned intf, unsigned alt) { struct diag_context *dev = func_to_dev(f); struct usb_composite_dev *cdev = f->config->cdev; unsigned long flags; int rc = 0; #if DIAG_XPST struct usb_request *req; #endif DIAG_INFO("%s: dev=%s\n", __func__, (dev == mdmctxt)?DIAG_MDM:DIAG_LEGACY); if (!dev) return -ENODEV; dev->in_desc = ep_choose(cdev->gadget, &hs_bulk_in_desc, &fs_bulk_in_desc); dev->out_desc = ep_choose(cdev->gadget, &hs_bulk_out_desc, &fs_bulk_in_desc); dev->in->driver_data = dev; rc = usb_ep_enable(dev->in, dev->in_desc); if (rc) { ERROR(dev->cdev, "can't enable %s, result %d\n", dev->in->name, rc); return rc; } dev->out->driver_data = dev; rc = usb_ep_enable(dev->out, dev->out_desc); if (rc) { ERROR(dev->cdev, "can't enable %s, result %d\n", dev->out->name, rc); usb_ep_disable(dev->in); return rc; } dev->i_serial_number = cdev->desc.iSerialNumber; dev->product_id = cdev->desc.idProduct; schedule_work(&dev->config_work); spin_lock_irqsave(&dev->lock, flags); dev->dpkts_tolaptop = 0; dev->dpkts_tomodem = 0; dev->dpkts_tolaptop_pending = 0; diag_configured = dev->configured = 1; spin_unlock_irqrestore(&dev->lock, flags); #if DIAG_XPST if (dev == legacyctxt) { while ((req = req_get(dev, &dev->rx_req_user))) req_put(dev, &dev->rx_req_idle, req); dev->online = !dev->function.hidden; wake_up(&dev->read_wq); } #endif return rc; } static void diag_function_release(struct usb_configuration *c, struct usb_function *f) { struct diag_context *ctxt = func_to_dev(f); DIAG_INFO("%s: dev=%s\n", __func__, (ctxt == mdmctxt)?DIAG_MDM:DIAG_LEGACY); if (!ctxt) return; if (gadget_is_dualspeed(c->cdev->gadget)) usb_free_descriptors(f->hs_descriptors); usb_free_descriptors(f->descriptors); #if DIAG_XPST if (ctxt == legacyctxt) { misc_deregister(&htc_diag_device_fops); misc_deregister(&diag2arm9_device); ctxt->tx_count = ctxt->rx_count = 0; ctxt->usb_in_count = ctxt->usb_out_count = 0; driver->diag_smd_count = driver->diag_qdsp_count = 0; } #endif } static void diag_function_unbind(struct usb_configuration *c, struct usb_function *f) { struct diag_context *ctxt = func_to_dev(f); DIAG_INFO("%s: dev=%s\n", __func__, (ctxt == mdmctxt)?DIAG_MDM:DIAG_LEGACY); if (!ctxt) return; if (gadget_is_dualspeed(c->cdev->gadget)) usb_free_descriptors(f->hs_descriptors); usb_free_descriptors(f->descriptors); ctxt->ch.priv_usb = NULL; #if DIAG_XPST if (ctxt == legacyctxt) { misc_deregister(&htc_diag_device_fops); misc_deregister(&diag2arm9_device); ctxt->tx_count = ctxt->rx_count = 0; ctxt->usb_in_count = ctxt->usb_out_count = 0; driver->diag_smd_count = driver->diag_qdsp_count = 0; } #endif } static int diag_function_bind(struct usb_configuration *c, struct usb_function *f) { struct usb_composite_dev *cdev = c->cdev; struct diag_context *ctxt = func_to_dev(f); struct usb_ep *ep; int status = -ENODEV; DIAG_INFO("%s: dev=%s\n", __func__, (ctxt == mdmctxt)?DIAG_MDM:DIAG_LEGACY); if (!ctxt) return status; ctxt->cdev = cdev; intf_desc.bInterfaceNumber = usb_interface_id(c, f); ep = usb_ep_autoconfig(cdev->gadget, &fs_bulk_in_desc); if (!ep) goto fail; ctxt->in = ep; ep->driver_data = ctxt; ep = usb_ep_autoconfig(cdev->gadget, &fs_bulk_out_desc); if (!ep) goto fail; ctxt->out = ep; ep->driver_data = ctxt; /* copy descriptors, and track endpoint copies */ f->descriptors = usb_copy_descriptors(fs_diag_desc); if (!f->descriptors) goto fail; if (gadget_is_dualspeed(c->cdev->gadget)) { hs_bulk_in_desc.bEndpointAddress = fs_bulk_in_desc.bEndpointAddress; hs_bulk_out_desc.bEndpointAddress = fs_bulk_out_desc.bEndpointAddress; /* copy descriptors, and track endpoint copies */ f->hs_descriptors = usb_copy_descriptors(hs_diag_desc); } #if DIAG_XPST if (ctxt == legacyctxt) { misc_register(&htc_diag_device_fops); /*DMrounter*/ misc_register(&diag2arm9_device); ctxt->usb_in_count = ctxt->usb_out_count = 0; ctxt->tx_count = ctxt->rx_count = 0; driver->diag_smd_count = driver->diag_qdsp_count = 0; } #endif return 0; fail: if (ctxt->out) ctxt->out->driver_data = NULL; if (ctxt->in) ctxt->in->driver_data = NULL; return status; } static struct usb_string diag_string_defs[] = { [0].s = "HTC DIAG", [1].s = "HTC 9K DIAG", { } /* end of list */ }; static struct usb_gadget_strings diag_string_table = { .language = 0x0409, /* en-us */ .strings = diag_string_defs, }; static struct usb_gadget_strings *diag_strings[] = { &diag_string_table, NULL, }; int diag_function_add(struct usb_configuration *c) { struct diag_context *dev; struct usb_diag_ch *_ch; int found = 0, ret; list_for_each_entry(_ch, &usb_diag_ch_list, list) { /* Find an unused channel */ if (!_ch->priv_usb) { found = 1; break; } } if (!found) { ERROR(c->cdev, "unable to get diag usb channel\n"); return -ENODEV; } dev = container_of(_ch, struct diag_context, ch); /* claim the channel for this USB interface */ _ch->priv_usb = dev; ret = usb_string_id(c->cdev); DIAG_DBUG("%s: ret=%d\n", __func__, ret); if (ret < 0) return ret; if (dev == legacyctxt) diag_string_defs[0].id = ret; else diag_string_defs[1].id = ret; intf_desc.iInterface = ret; dev->cdev = c->cdev; dev->function.name = _ch->name; dev->function.strings = diag_strings; dev->function.descriptors = fs_diag_desc; dev->function.hs_descriptors = hs_diag_desc; dev->function.bind = diag_function_bind; dev->function.unbind = diag_function_unbind; dev->function.set_alt = diag_function_set_alt; dev->function.disable = diag_function_disable; dev->function.release = diag_function_release; spin_lock_init(&dev->lock); INIT_LIST_HEAD(&dev->read_pool); INIT_LIST_HEAD(&dev->write_pool); INIT_WORK(&dev->config_work, usb_config_work_func); dev->function.hidden = !_context.function_enable; #if defined(CONFIG_MACH_MECHA) /*for internal hub*/ smsc251x_set_diag_boot_flag(_context.function_enable); #endif #if DIAG_XPST if (dev == legacyctxt) { spin_lock_init(&dev->req_lock); mutex_init(&dev->user_lock); INIT_LIST_HEAD(&dev->rx_req_user); INIT_LIST_HEAD(&dev->rx_req_idle); init_waitqueue_head(&dev->read_wq); INIT_LIST_HEAD(&dev->rx_arm9_idle); INIT_LIST_HEAD(&dev->rx_arm9_done); init_waitqueue_head(&dev->read_arm9_wq); mutex_init(&dev->diag2arm9_lock); mutex_init(&dev->diag2arm9_read_lock); mutex_init(&dev->diag2arm9_write_lock); } #endif DIAG_DBUG("%s: dev->function.hidden =%d\n", __func__, dev->function.hidden ); ret = usb_add_function(c, &dev->function); if (ret) { INFO(c->cdev, "usb_add_function failed\n"); _ch->priv_usb = NULL; } return ret; } #if defined(CONFIG_DEBUG_FS) static char debug_buffer[PAGE_SIZE]; static ssize_t debug_read_stats(struct file *file, char __user *ubuf, size_t count, loff_t *ppos) { char *buf = debug_buffer; int temp = 0; struct usb_diag_ch *ch; list_for_each_entry(ch, &usb_diag_ch_list, list) { struct diag_context *ctxt; ctxt = ch->priv_usb; temp += scnprintf(buf + temp, PAGE_SIZE - temp, "---Name: %s---\n" "dpkts_tolaptop: %lu\n" "dpkts_tomodem: %lu\n" "pkts_tolaptop_pending: %u\n", ch->name, ctxt->dpkts_tolaptop, ctxt->dpkts_tomodem, ctxt->dpkts_tolaptop_pending); } return simple_read_from_buffer(ubuf, count, ppos, buf, temp); } static ssize_t debug_reset_stats(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct usb_diag_ch *ch; list_for_each_entry(ch, &usb_diag_ch_list, list) { struct diag_context *ctxt; ctxt = ch->priv_usb; ctxt->dpkts_tolaptop = 0; ctxt->dpkts_tomodem = 0; ctxt->dpkts_tolaptop_pending = 0; } return count; } static int debug_open(struct inode *inode, struct file *file) { return 0; } static const struct file_operations debug_fdiag_ops = { .open = debug_open, .read = debug_read_stats, .write = debug_reset_stats, }; static void fdiag_debugfs_init(void) { struct dentry *dent; dent = debugfs_create_dir("usb_diag", 0); if (IS_ERR(dent)) return; debugfs_create_file("status", 0444, dent, 0, &debug_fdiag_ops); } #else static void fdiag_debugfs_init(void) { return; } #endif void usb_diag_debug_dump(void) { struct usb_diag_ch *ch; list_for_each_entry(ch, &usb_diag_ch_list, list) { struct diag_context *ctxt; ctxt = ch->priv_usb; DIAG_INFO("---Name: %s---\n" "dpkts_tolaptop: %lu\n" "dpkts_tomodem: %lu\n" "pkts_tolaptop_pending: %u\n", ch->name, ctxt->dpkts_tolaptop, ctxt->dpkts_tomodem, ctxt->dpkts_tolaptop_pending); } } EXPORT_SYMBOL(usb_diag_debug_dump); static int diag2sd_probe(struct platform_device *pdev) { struct diag2sd_platform_data *pdata = pdev->dev.platform_data; DIAG_DBUG("%s: \n", __func__); if (pdata->enable_sd_log) driver->enable_sd_log = pdata->enable_sd_log; return 0; } static struct platform_driver diag2sd_platform_driver = { .driver = { .name = "diag2sd", }, .probe = diag2sd_probe, }; static int __init usb_diag_init(void) { struct diag_context *dev; struct android_usb_function *func; DIAG_DBUG("%s: \n", __func__); dev = container_of(legacych, struct diag_context, ch); func = &dev->android_function; func->name = DIAG_LEGACY; func->bind_config = diag_function_add; android_register_function(func); #if defined(CONFIG_USB_ANDROID_LTE_DIAG) dev = container_of(mdmch, struct diag_context, ch); func = &dev->android_function; func->name = DIAG_MDM; func->bind_config = diag_function_add; android_register_function(func); #endif platform_driver_register(&diag2sd_platform_driver); return 0; } module_init(usb_diag_init); MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("usb diag gadget driver"); MODULE_VERSION("2.00"); static int diag_set_enabled(const char *val, struct kernel_param *kp) { int enabled = simple_strtol(val, NULL, 0); DIAG_INFO("%s: %d\n", __func__, enabled); if (_context.cdev) { #if defined(CONFIG_USB_ANDROID_LTE_DIAG) android_enable_function(&mdmctxt->function, enabled); #endif android_enable_function(&_context.function, enabled); diag_smd_enable(driver->ch, "diag_set_enabled", !!enabled); } else { #if defined(CONFIG_MACH_MECHA) sdio_diag_init_enable = !enabled; DIAG_INFO("%s: sdio_diag_init_enable=%d\n", __func__, enabled); #elif defined(CONFIG_USB_ANDROID_LTE_DIAG) diag_init_enabled_state = !!enabled; #endif } _context.function_enable = !!enabled; return 0; } static int diag_get_enabled(char *buffer, struct kernel_param *kp) { buffer[0] = '0' + !_context.function.hidden; return 1; } module_param_call(enabled, diag_set_enabled, diag_get_enabled, NULL, 0664); static int show_diag_xfer_count(char *buffer, struct kernel_param *kp) { struct diag_context *ctxt = &_context; ctxt->rx_count = driver->diag_smd_count + driver->diag_qdsp_count; /* return sprintf(buffer, "tx: %llu bytes, rx: %llu bytes", ctxt->tx_count, ctxt->rx_count);*/ return sprintf(buffer, "tx_count: %llu, rx_count: %llu\n", ctxt->tx_count, ctxt->rx_count); } module_param_call(diag_xfer_count, NULL, show_diag_xfer_count, NULL, 0444); static int diag_get_usb_inout_count(char *buffer, struct kernel_param *kp) { struct diag_context *ctxt = &_context; return sprintf(buffer, "FromPC: %llu bytes, ToPC: %llu bytes", ctxt->usb_out_count, ctxt->usb_in_count); } module_param_call(usb_inout_count, NULL, diag_get_usb_inout_count, NULL, 0444);
jdkernel/mecha_aosp_2.6.35
drivers/usb/gadget/f_diag.c
C
gpl-2.0
62,049
-- Copyright © 2013 Xavier Lamien -- -- This copyrighted material is made available to anyone wishing to use, modify, -- copy, or redistribute it subject to the terms and conditions of the GNU -- General Public License v.2. This program is distributed in the hope that it -- will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the -- implied warranties 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. Any Red Hat trademarks that are -- incorporated in the source code or documentation are not subject to the GNU -- General Public License and may only be used or replicated with the express -- permission of Red Hat, Inc. -- -- Author(s): Xavier Lamien <laxathom@fedoraproject.org> -- Please, make sure group name matches the one you entered in fas.cfg NSERT INTO groups (name, display_name, owner_id, group_type) VALUES ('accounts-moderators', 'Accounts System Moderators', (SELECT id from people where username='admin'), 'cla');
ampotty/fas
updates/fas2-0.9.0_to_0.10.0.sql
SQL
gpl-2.0
1,235
/* * Copyright (C) 2007 Casey Schaufler <casey@schaufler-ca.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, version 2. * * Authors: * Casey Schaufler <casey@schaufler-ca.com> * Ahmed S. Darwish <darwish.07@gmail.com> * * Special thanks to the authors of selinuxfs. * * Karl MacMillan <kmacmillan@tresys.com> * James Morris <jmorris@redhat.com> * */ #include <linux/kernel.h> #include <linux/vmalloc.h> #include <linux/security.h> #include <linux/mutex.h> #include <linux/slab.h> #include <net/net_namespace.h> #include <net/cipso_ipv4.h> #include <linux/seq_file.h> #include <linux/ctype.h> #include <linux/audit.h> #include <linux/magic.h> #include "smack.h" /* * smackfs pseudo filesystem. */ enum smk_inos { SMK_ROOT_INO = 2, SMK_LOAD = 3, /* load policy */ SMK_CIPSO = 4, /* load label -> CIPSO mapping */ SMK_DOI = 5, /* CIPSO DOI */ SMK_DIRECT = 6, /* CIPSO level indicating direct label */ SMK_AMBIENT = 7, /* internet ambient label */ SMK_NETLBLADDR = 8, /* single label hosts */ SMK_ONLYCAP = 9, /* the only "capable" label */ SMK_LOGGING = 10, /* logging */ SMK_LOAD_SELF = 11, /* task specific rules */ SMK_ACCESSES = 12, /* access policy */ SMK_MAPPED = 13, /* CIPSO level indicating mapped label */ SMK_LOAD2 = 14, /* load policy with long labels */ SMK_LOAD_SELF2 = 15, /* load task specific rules with long labels */ SMK_ACCESS2 = 16, /* make an access check with long labels */ SMK_CIPSO2 = 17, /* load long label -> CIPSO mapping */ SMK_REVOKE_SUBJ = 18, /* set rules with subject label to '-' */ SMK_CHANGE_RULE = 19, /* change or add rules (long labels) */ SMK_SYSLOG = 20, /* change syslog label) */ SMK_PTRACE = 21, /* set ptrace rule */ #ifdef CONFIG_SECURITY_SMACK_BRINGUP SMK_UNCONFINED = 22, /* define an unconfined label */ #endif }; /* * List locks */ static DEFINE_MUTEX(smack_cipso_lock); static DEFINE_MUTEX(smack_ambient_lock); static DEFINE_MUTEX(smk_netlbladdr_lock); /* * This is the "ambient" label for network traffic. * If it isn't somehow marked, use this. * It can be reset via smackfs/ambient */ struct smack_known *smack_net_ambient; /* * This is the level in a CIPSO header that indicates a * smack label is contained directly in the category set. * It can be reset via smackfs/direct */ int smack_cipso_direct = SMACK_CIPSO_DIRECT_DEFAULT; /* * This is the level in a CIPSO header that indicates a * secid is contained directly in the category set. * It can be reset via smackfs/mapped */ int smack_cipso_mapped = SMACK_CIPSO_MAPPED_DEFAULT; #ifdef CONFIG_SECURITY_SMACK_BRINGUP /* * Allow one label to be unconfined. This is for * debugging and application bring-up purposes only. * It is bad and wrong, but everyone seems to expect * to have it. */ struct smack_known *smack_unconfined; #endif /* * If this value is set restrict syslog use to the label specified. * It can be reset via smackfs/syslog */ struct smack_known *smack_syslog_label; /* * Ptrace current rule * SMACK_PTRACE_DEFAULT regular smack ptrace rules (/proc based) * SMACK_PTRACE_EXACT labels must match, but can be overriden with * CAP_SYS_PTRACE * SMACK_PTRACE_DRACONIAN lables must match, CAP_SYS_PTRACE has no effect */ int smack_ptrace_rule = SMACK_PTRACE_DEFAULT; /* * Certain IP addresses may be designated as single label hosts. * Packets are sent there unlabeled, but only from tasks that * can write to the specified label. */ LIST_HEAD(smk_netlbladdr_list); /* * Rule lists are maintained for each label. * This master list is just for reading /smack/load and /smack/load2. */ struct smack_master_list { struct list_head list; struct smack_rule *smk_rule; }; LIST_HEAD(smack_rule_list); struct smack_parsed_rule { struct smack_known *smk_subject; struct smack_known *smk_object; int smk_access1; int smk_access2; }; static int smk_cipso_doi_value = SMACK_CIPSO_DOI_DEFAULT; struct smack_known smack_cipso_option = { .smk_known = SMACK_CIPSO_OPTION, .smk_secid = 0, }; /* * Values for parsing cipso rules * SMK_DIGITLEN: Length of a digit field in a rule. * SMK_CIPSOMIN: Minimum possible cipso rule length. * SMK_CIPSOMAX: Maximum possible cipso rule length. */ #define SMK_DIGITLEN 4 #define SMK_CIPSOMIN (SMK_LABELLEN + 2 * SMK_DIGITLEN) #define SMK_CIPSOMAX (SMK_CIPSOMIN + SMACK_CIPSO_MAXCATNUM * SMK_DIGITLEN) /* * Values for parsing MAC rules * SMK_ACCESS: Maximum possible combination of access permissions * SMK_ACCESSLEN: Maximum length for a rule access field * SMK_LOADLEN: Smack rule length */ #define SMK_OACCESS "rwxa" #define SMK_ACCESS "rwxatl" #define SMK_OACCESSLEN (sizeof(SMK_OACCESS) - 1) #define SMK_ACCESSLEN (sizeof(SMK_ACCESS) - 1) #define SMK_OLOADLEN (SMK_LABELLEN + SMK_LABELLEN + SMK_OACCESSLEN) #define SMK_LOADLEN (SMK_LABELLEN + SMK_LABELLEN + SMK_ACCESSLEN) /* * Stricly for CIPSO level manipulation. * Set the category bit number in a smack label sized buffer. */ static inline void smack_catset_bit(unsigned int cat, char *catsetp) { if (cat == 0 || cat > (SMK_CIPSOLEN * 8)) return; catsetp[(cat - 1) / 8] |= 0x80 >> ((cat - 1) % 8); } /** * smk_netlabel_audit_set - fill a netlbl_audit struct * @nap: structure to fill */ static void smk_netlabel_audit_set(struct netlbl_audit *nap) { struct smack_known *skp = smk_of_current(); nap->loginuid = audit_get_loginuid(current); nap->sessionid = audit_get_sessionid(current); nap->secid = skp->smk_secid; } /* * Value for parsing single label host rules * "1.2.3.4 X" */ #define SMK_NETLBLADDRMIN 9 /** * smk_set_access - add a rule to the rule list or replace an old rule * @srp: the rule to add or replace * @rule_list: the list of rules * @rule_lock: the rule list lock * @global: if non-zero, indicates a global rule * * Looks through the current subject/object/access list for * the subject/object pair and replaces the access that was * there. If the pair isn't found add it with the specified * access. * * Returns 0 if nothing goes wrong or -ENOMEM if it fails * during the allocation of the new pair to add. */ static int smk_set_access(struct smack_parsed_rule *srp, struct list_head *rule_list, struct mutex *rule_lock, int global) { struct smack_rule *sp; struct smack_master_list *smlp; int found = 0; int rc = 0; mutex_lock(rule_lock); /* * Because the object label is less likely to match * than the subject label check it first */ list_for_each_entry_rcu(sp, rule_list, list) { if (sp->smk_object == srp->smk_object && sp->smk_subject == srp->smk_subject) { found = 1; sp->smk_access |= srp->smk_access1; sp->smk_access &= ~srp->smk_access2; break; } } if (found == 0) { sp = kzalloc(sizeof(*sp), GFP_KERNEL); if (sp == NULL) { rc = -ENOMEM; goto out; } sp->smk_subject = srp->smk_subject; sp->smk_object = srp->smk_object; sp->smk_access = srp->smk_access1 & ~srp->smk_access2; list_add_rcu(&sp->list, rule_list); /* * If this is a global as opposed to self and a new rule * it needs to get added for reporting. */ if (global) { smlp = kzalloc(sizeof(*smlp), GFP_KERNEL); if (smlp != NULL) { smlp->smk_rule = sp; list_add_rcu(&smlp->list, &smack_rule_list); } else rc = -ENOMEM; } } out: mutex_unlock(rule_lock); return rc; } /** * smk_perm_from_str - parse smack accesses from a text string * @string: a text string that contains a Smack accesses code * * Returns an integer with respective bits set for specified accesses. */ static int smk_perm_from_str(const char *string) { int perm = 0; const char *cp; for (cp = string; ; cp++) switch (*cp) { case '-': break; case 'r': case 'R': perm |= MAY_READ; break; case 'w': case 'W': perm |= MAY_WRITE; break; case 'x': case 'X': perm |= MAY_EXEC; break; case 'a': case 'A': perm |= MAY_APPEND; break; case 't': case 'T': perm |= MAY_TRANSMUTE; break; case 'l': case 'L': perm |= MAY_LOCK; break; case 'b': case 'B': perm |= MAY_BRINGUP; break; default: return perm; } } /** * smk_fill_rule - Fill Smack rule from strings * @subject: subject label string * @object: object label string * @access1: access string * @access2: string with permissions to be removed * @rule: Smack rule * @import: if non-zero, import labels * @len: label length limit * * Returns 0 on success, appropriate error code on failure. */ static int smk_fill_rule(const char *subject, const char *object, const char *access1, const char *access2, struct smack_parsed_rule *rule, int import, int len) { const char *cp; struct smack_known *skp; if (import) { rule->smk_subject = smk_import_entry(subject, len); if (IS_ERR(rule->smk_subject)) return PTR_ERR(rule->smk_subject); rule->smk_object = smk_import_entry(object, len); if (IS_ERR(rule->smk_object)) return PTR_ERR(rule->smk_object); } else { cp = smk_parse_smack(subject, len); if (IS_ERR(cp)) return PTR_ERR(cp); skp = smk_find_entry(cp); kfree(cp); if (skp == NULL) return -ENOENT; rule->smk_subject = skp; cp = smk_parse_smack(object, len); if (IS_ERR(cp)) return PTR_ERR(cp); skp = smk_find_entry(cp); kfree(cp); if (skp == NULL) return -ENOENT; rule->smk_object = skp; } rule->smk_access1 = smk_perm_from_str(access1); if (access2) rule->smk_access2 = smk_perm_from_str(access2); else rule->smk_access2 = ~rule->smk_access1; return 0; } /** * smk_parse_rule - parse Smack rule from load string * @data: string to be parsed whose size is SMK_LOADLEN * @rule: Smack rule * @import: if non-zero, import labels * * Returns 0 on success, -1 on errors. */ static int smk_parse_rule(const char *data, struct smack_parsed_rule *rule, int import) { int rc; rc = smk_fill_rule(data, data + SMK_LABELLEN, data + SMK_LABELLEN + SMK_LABELLEN, NULL, rule, import, SMK_LABELLEN); return rc; } /** * smk_parse_long_rule - parse Smack rule from rule string * @data: string to be parsed, null terminated * @rule: Will be filled with Smack parsed rule * @import: if non-zero, import labels * @tokens: numer of substrings expected in data * * Returns number of processed bytes on success, -ERRNO on failure. */ static ssize_t smk_parse_long_rule(char *data, struct smack_parsed_rule *rule, int import, int tokens) { ssize_t cnt = 0; char *tok[4]; int rc; int i; /* * Parsing the rule in-place, filling all white-spaces with '\0' */ for (i = 0; i < tokens; ++i) { while (isspace(data[cnt])) data[cnt++] = '\0'; if (data[cnt] == '\0') /* Unexpected end of data */ return -EINVAL; tok[i] = data + cnt; while (data[cnt] && !isspace(data[cnt])) ++cnt; } while (isspace(data[cnt])) data[cnt++] = '\0'; while (i < 4) tok[i++] = NULL; rc = smk_fill_rule(tok[0], tok[1], tok[2], tok[3], rule, import, 0); return rc == 0 ? cnt : rc; } #define SMK_FIXED24_FMT 0 /* Fixed 24byte label format */ #define SMK_LONG_FMT 1 /* Variable long label format */ #define SMK_CHANGE_FMT 2 /* Rule modification format */ /** * smk_write_rules_list - write() for any /smack rule file * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start - must be 0 * @rule_list: the list of rules to write to * @rule_lock: lock for the rule list * @format: /smack/load or /smack/load2 or /smack/change-rule format. * * Get one smack access rule from above. * The format for SMK_LONG_FMT is: * "subject<whitespace>object<whitespace>access[<whitespace>...]" * The format for SMK_FIXED24_FMT is exactly: * "subject object rwxat" * The format for SMK_CHANGE_FMT is: * "subject<whitespace>object<whitespace> * acc_enable<whitespace>acc_disable[<whitespace>...]" */ static ssize_t smk_write_rules_list(struct file *file, const char __user *buf, size_t count, loff_t *ppos, struct list_head *rule_list, struct mutex *rule_lock, int format) { struct smack_parsed_rule rule; char *data; int rc; int trunc = 0; int tokens; ssize_t cnt = 0; /* * No partial writes. * Enough data must be present. */ if (*ppos != 0) return -EINVAL; if (format == SMK_FIXED24_FMT) { /* * Minor hack for backward compatibility */ if (count < SMK_OLOADLEN || count > SMK_LOADLEN) return -EINVAL; } else { if (count >= PAGE_SIZE) { count = PAGE_SIZE - 1; trunc = 1; } } data = kmalloc(count + 1, GFP_KERNEL); if (data == NULL) return -ENOMEM; if (copy_from_user(data, buf, count) != 0) { rc = -EFAULT; goto out; } /* * In case of parsing only part of user buf, * avoid having partial rule at the data buffer */ if (trunc) { while (count > 0 && (data[count - 1] != '\n')) --count; if (count == 0) { rc = -EINVAL; goto out; } } data[count] = '\0'; tokens = (format == SMK_CHANGE_FMT ? 4 : 3); while (cnt < count) { if (format == SMK_FIXED24_FMT) { rc = smk_parse_rule(data, &rule, 1); if (rc < 0) goto out; cnt = count; } else { rc = smk_parse_long_rule(data + cnt, &rule, 1, tokens); if (rc < 0) goto out; if (rc == 0) { rc = -EINVAL; goto out; } cnt += rc; } if (rule_list == NULL) rc = smk_set_access(&rule, &rule.smk_subject->smk_rules, &rule.smk_subject->smk_rules_lock, 1); else rc = smk_set_access(&rule, rule_list, rule_lock, 0); if (rc) goto out; } rc = cnt; out: kfree(data); return rc; } /* * Core logic for smackfs seq list operations. */ static void *smk_seq_start(struct seq_file *s, loff_t *pos, struct list_head *head) { struct list_head *list; int i = *pos; rcu_read_lock(); for (list = rcu_dereference(list_next_rcu(head)); list != head; list = rcu_dereference(list_next_rcu(list))) { if (i-- == 0) return list; } return NULL; } static void *smk_seq_next(struct seq_file *s, void *v, loff_t *pos, struct list_head *head) { struct list_head *list = v; ++*pos; list = rcu_dereference(list_next_rcu(list)); return (list == head) ? NULL : list; } static void smk_seq_stop(struct seq_file *s, void *v) { rcu_read_unlock(); } static void smk_rule_show(struct seq_file *s, struct smack_rule *srp, int max) { /* * Don't show any rules with label names too long for * interface file (/smack/load or /smack/load2) * because you should expect to be able to write * anything you read back. */ if (strlen(srp->smk_subject->smk_known) >= max || strlen(srp->smk_object->smk_known) >= max) return; if (srp->smk_access == 0) return; seq_printf(s, "%s %s", srp->smk_subject->smk_known, srp->smk_object->smk_known); seq_putc(s, ' '); if (srp->smk_access & MAY_READ) seq_putc(s, 'r'); if (srp->smk_access & MAY_WRITE) seq_putc(s, 'w'); if (srp->smk_access & MAY_EXEC) seq_putc(s, 'x'); if (srp->smk_access & MAY_APPEND) seq_putc(s, 'a'); if (srp->smk_access & MAY_TRANSMUTE) seq_putc(s, 't'); if (srp->smk_access & MAY_LOCK) seq_putc(s, 'l'); if (srp->smk_access & MAY_BRINGUP) seq_putc(s, 'b'); seq_putc(s, '\n'); } /* * Seq_file read operations for /smack/load */ static void *load2_seq_start(struct seq_file *s, loff_t *pos) { return smk_seq_start(s, pos, &smack_rule_list); } static void *load2_seq_next(struct seq_file *s, void *v, loff_t *pos) { return smk_seq_next(s, v, pos, &smack_rule_list); } static int load_seq_show(struct seq_file *s, void *v) { struct list_head *list = v; struct smack_master_list *smlp = list_entry_rcu(list, struct smack_master_list, list); smk_rule_show(s, smlp->smk_rule, SMK_LABELLEN); return 0; } static const struct seq_operations load_seq_ops = { .start = load2_seq_start, .next = load2_seq_next, .show = load_seq_show, .stop = smk_seq_stop, }; /** * smk_open_load - open() for /smack/load * @inode: inode structure representing file * @file: "load" file pointer * * For reading, use load_seq_* seq_file reading operations. */ static int smk_open_load(struct inode *inode, struct file *file) { return seq_open(file, &load_seq_ops); } /** * smk_write_load - write() for /smack/load * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start - must be 0 * */ static ssize_t smk_write_load(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { /* * Must have privilege. * No partial writes. * Enough data must be present. */ if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; return smk_write_rules_list(file, buf, count, ppos, NULL, NULL, SMK_FIXED24_FMT); } static const struct file_operations smk_load_ops = { .open = smk_open_load, .read = seq_read, .llseek = seq_lseek, .write = smk_write_load, .release = seq_release, }; /** * smk_cipso_doi - initialize the CIPSO domain */ static void smk_cipso_doi(void) { int rc; struct cipso_v4_doi *doip; struct netlbl_audit nai; smk_netlabel_audit_set(&nai); rc = netlbl_cfg_map_del(NULL, PF_INET, NULL, NULL, &nai); if (rc != 0) printk(KERN_WARNING "%s:%d remove rc = %d\n", __func__, __LINE__, rc); doip = kmalloc(sizeof(struct cipso_v4_doi), GFP_KERNEL); if (doip == NULL) panic("smack: Failed to initialize cipso DOI.\n"); doip->map.std = NULL; doip->doi = smk_cipso_doi_value; doip->type = CIPSO_V4_MAP_PASS; doip->tags[0] = CIPSO_V4_TAG_RBITMAP; for (rc = 1; rc < CIPSO_V4_TAG_MAXCNT; rc++) doip->tags[rc] = CIPSO_V4_TAG_INVALID; rc = netlbl_cfg_cipsov4_add(doip, &nai); if (rc != 0) { printk(KERN_WARNING "%s:%d cipso add rc = %d\n", __func__, __LINE__, rc); kfree(doip); return; } rc = netlbl_cfg_cipsov4_map_add(doip->doi, NULL, NULL, NULL, &nai); if (rc != 0) { printk(KERN_WARNING "%s:%d map add rc = %d\n", __func__, __LINE__, rc); kfree(doip); return; } } /** * smk_unlbl_ambient - initialize the unlabeled domain * @oldambient: previous domain string */ static void smk_unlbl_ambient(char *oldambient) { int rc; struct netlbl_audit nai; smk_netlabel_audit_set(&nai); if (oldambient != NULL) { rc = netlbl_cfg_map_del(oldambient, PF_INET, NULL, NULL, &nai); if (rc != 0) printk(KERN_WARNING "%s:%d remove rc = %d\n", __func__, __LINE__, rc); } if (smack_net_ambient == NULL) smack_net_ambient = &smack_known_floor; rc = netlbl_cfg_unlbl_map_add(smack_net_ambient->smk_known, PF_INET, NULL, NULL, &nai); if (rc != 0) printk(KERN_WARNING "%s:%d add rc = %d\n", __func__, __LINE__, rc); } /* * Seq_file read operations for /smack/cipso */ static void *cipso_seq_start(struct seq_file *s, loff_t *pos) { return smk_seq_start(s, pos, &smack_known_list); } static void *cipso_seq_next(struct seq_file *s, void *v, loff_t *pos) { return smk_seq_next(s, v, pos, &smack_known_list); } /* * Print cipso labels in format: * label level[/cat[,cat]] */ static int cipso_seq_show(struct seq_file *s, void *v) { struct list_head *list = v; struct smack_known *skp = list_entry_rcu(list, struct smack_known, list); struct netlbl_lsm_catmap *cmp = skp->smk_netlabel.attr.mls.cat; char sep = '/'; int i; /* * Don't show a label that could not have been set using * /smack/cipso. This is in support of the notion that * anything read from /smack/cipso ought to be writeable * to /smack/cipso. * * /smack/cipso2 should be used instead. */ if (strlen(skp->smk_known) >= SMK_LABELLEN) return 0; seq_printf(s, "%s %3d", skp->smk_known, skp->smk_netlabel.attr.mls.lvl); for (i = netlbl_catmap_walk(cmp, 0); i >= 0; i = netlbl_catmap_walk(cmp, i + 1)) { seq_printf(s, "%c%d", sep, i); sep = ','; } seq_putc(s, '\n'); return 0; } static const struct seq_operations cipso_seq_ops = { .start = cipso_seq_start, .next = cipso_seq_next, .show = cipso_seq_show, .stop = smk_seq_stop, }; /** * smk_open_cipso - open() for /smack/cipso * @inode: inode structure representing file * @file: "cipso" file pointer * * Connect our cipso_seq_* operations with /smack/cipso * file_operations */ static int smk_open_cipso(struct inode *inode, struct file *file) { return seq_open(file, &cipso_seq_ops); } /** * smk_set_cipso - do the work for write() for cipso and cipso2 * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start * @format: /smack/cipso or /smack/cipso2 * * Accepts only one cipso rule per write call. * Returns number of bytes written or error code, as appropriate */ static ssize_t smk_set_cipso(struct file *file, const char __user *buf, size_t count, loff_t *ppos, int format) { struct smack_known *skp; struct netlbl_lsm_secattr ncats; char mapcatset[SMK_CIPSOLEN]; int maplevel; unsigned int cat; int catlen; ssize_t rc = -EINVAL; char *data = NULL; char *rule; int ret; int i; /* * Must have privilege. * No partial writes. * Enough data must be present. */ if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; if (*ppos != 0) return -EINVAL; if (format == SMK_FIXED24_FMT && (count < SMK_CIPSOMIN || count > SMK_CIPSOMAX)) return -EINVAL; data = kzalloc(count + 1, GFP_KERNEL); if (data == NULL) return -ENOMEM; if (copy_from_user(data, buf, count) != 0) { rc = -EFAULT; goto unlockedout; } data[count] = '\0'; rule = data; /* * Only allow one writer at a time. Writes should be * quite rare and small in any case. */ mutex_lock(&smack_cipso_lock); skp = smk_import_entry(rule, 0); if (IS_ERR(skp)) { rc = PTR_ERR(skp); goto out; } if (format == SMK_FIXED24_FMT) rule += SMK_LABELLEN; else rule += strlen(skp->smk_known) + 1; ret = sscanf(rule, "%d", &maplevel); if (ret != 1 || maplevel > SMACK_CIPSO_MAXLEVEL) goto out; rule += SMK_DIGITLEN; ret = sscanf(rule, "%d", &catlen); if (ret != 1 || catlen > SMACK_CIPSO_MAXCATNUM) goto out; if (format == SMK_FIXED24_FMT && count != (SMK_CIPSOMIN + catlen * SMK_DIGITLEN)) goto out; memset(mapcatset, 0, sizeof(mapcatset)); for (i = 0; i < catlen; i++) { rule += SMK_DIGITLEN; ret = sscanf(rule, "%u", &cat); if (ret != 1 || cat > SMACK_CIPSO_MAXCATNUM) goto out; smack_catset_bit(cat, mapcatset); } rc = smk_netlbl_mls(maplevel, mapcatset, &ncats, SMK_CIPSOLEN); if (rc >= 0) { netlbl_catmap_free(skp->smk_netlabel.attr.mls.cat); skp->smk_netlabel.attr.mls.cat = ncats.attr.mls.cat; skp->smk_netlabel.attr.mls.lvl = ncats.attr.mls.lvl; rc = count; } out: mutex_unlock(&smack_cipso_lock); unlockedout: kfree(data); return rc; } /** * smk_write_cipso - write() for /smack/cipso * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start * * Accepts only one cipso rule per write call. * Returns number of bytes written or error code, as appropriate */ static ssize_t smk_write_cipso(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { return smk_set_cipso(file, buf, count, ppos, SMK_FIXED24_FMT); } static const struct file_operations smk_cipso_ops = { .open = smk_open_cipso, .read = seq_read, .llseek = seq_lseek, .write = smk_write_cipso, .release = seq_release, }; /* * Seq_file read operations for /smack/cipso2 */ /* * Print cipso labels in format: * label level[/cat[,cat]] */ static int cipso2_seq_show(struct seq_file *s, void *v) { struct list_head *list = v; struct smack_known *skp = list_entry_rcu(list, struct smack_known, list); struct netlbl_lsm_catmap *cmp = skp->smk_netlabel.attr.mls.cat; char sep = '/'; int i; seq_printf(s, "%s %3d", skp->smk_known, skp->smk_netlabel.attr.mls.lvl); for (i = netlbl_catmap_walk(cmp, 0); i >= 0; i = netlbl_catmap_walk(cmp, i + 1)) { seq_printf(s, "%c%d", sep, i); sep = ','; } seq_putc(s, '\n'); return 0; } static const struct seq_operations cipso2_seq_ops = { .start = cipso_seq_start, .next = cipso_seq_next, .show = cipso2_seq_show, .stop = smk_seq_stop, }; /** * smk_open_cipso2 - open() for /smack/cipso2 * @inode: inode structure representing file * @file: "cipso2" file pointer * * Connect our cipso_seq_* operations with /smack/cipso2 * file_operations */ static int smk_open_cipso2(struct inode *inode, struct file *file) { return seq_open(file, &cipso2_seq_ops); } /** * smk_write_cipso2 - write() for /smack/cipso2 * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start * * Accepts only one cipso rule per write call. * Returns number of bytes written or error code, as appropriate */ static ssize_t smk_write_cipso2(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { return smk_set_cipso(file, buf, count, ppos, SMK_LONG_FMT); } static const struct file_operations smk_cipso2_ops = { .open = smk_open_cipso2, .read = seq_read, .llseek = seq_lseek, .write = smk_write_cipso2, .release = seq_release, }; /* * Seq_file read operations for /smack/netlabel */ static void *netlbladdr_seq_start(struct seq_file *s, loff_t *pos) { return smk_seq_start(s, pos, &smk_netlbladdr_list); } static void *netlbladdr_seq_next(struct seq_file *s, void *v, loff_t *pos) { return smk_seq_next(s, v, pos, &smk_netlbladdr_list); } #define BEBITS (sizeof(__be32) * 8) /* * Print host/label pairs */ static int netlbladdr_seq_show(struct seq_file *s, void *v) { struct list_head *list = v; struct smk_netlbladdr *skp = list_entry_rcu(list, struct smk_netlbladdr, list); unsigned char *hp = (char *) &skp->smk_host.sin_addr.s_addr; int maskn; u32 temp_mask = be32_to_cpu(skp->smk_mask.s_addr); for (maskn = 0; temp_mask; temp_mask <<= 1, maskn++); seq_printf(s, "%u.%u.%u.%u/%d %s\n", hp[0], hp[1], hp[2], hp[3], maskn, skp->smk_label->smk_known); return 0; } static const struct seq_operations netlbladdr_seq_ops = { .start = netlbladdr_seq_start, .next = netlbladdr_seq_next, .show = netlbladdr_seq_show, .stop = smk_seq_stop, }; /** * smk_open_netlbladdr - open() for /smack/netlabel * @inode: inode structure representing file * @file: "netlabel" file pointer * * Connect our netlbladdr_seq_* operations with /smack/netlabel * file_operations */ static int smk_open_netlbladdr(struct inode *inode, struct file *file) { return seq_open(file, &netlbladdr_seq_ops); } /** * smk_netlbladdr_insert * @new : netlabel to insert * * This helper insert netlabel in the smack_netlbladdrs list * sorted by netmask length (longest to smallest) * locked by &smk_netlbladdr_lock in smk_write_netlbladdr * */ static void smk_netlbladdr_insert(struct smk_netlbladdr *new) { struct smk_netlbladdr *m, *m_next; if (list_empty(&smk_netlbladdr_list)) { list_add_rcu(&new->list, &smk_netlbladdr_list); return; } m = list_entry_rcu(smk_netlbladdr_list.next, struct smk_netlbladdr, list); /* the comparison '>' is a bit hacky, but works */ if (new->smk_mask.s_addr > m->smk_mask.s_addr) { list_add_rcu(&new->list, &smk_netlbladdr_list); return; } list_for_each_entry_rcu(m, &smk_netlbladdr_list, list) { if (list_is_last(&m->list, &smk_netlbladdr_list)) { list_add_rcu(&new->list, &m->list); return; } m_next = list_entry_rcu(m->list.next, struct smk_netlbladdr, list); if (new->smk_mask.s_addr > m_next->smk_mask.s_addr) { list_add_rcu(&new->list, &m->list); return; } } } /** * smk_write_netlbladdr - write() for /smack/netlabel * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start * * Accepts only one netlbladdr per write call. * Returns number of bytes written or error code, as appropriate */ static ssize_t smk_write_netlbladdr(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct smk_netlbladdr *snp; struct sockaddr_in newname; char *smack; struct smack_known *skp; char *data; char *host = (char *)&newname.sin_addr.s_addr; int rc; struct netlbl_audit audit_info; struct in_addr mask; unsigned int m; int found; u32 mask_bits = (1<<31); __be32 nsa; u32 temp_mask; /* * Must have privilege. * No partial writes. * Enough data must be present. * "<addr/mask, as a.b.c.d/e><space><label>" * "<addr, as a.b.c.d><space><label>" */ if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; if (*ppos != 0) return -EINVAL; if (count < SMK_NETLBLADDRMIN) return -EINVAL; data = kzalloc(count + 1, GFP_KERNEL); if (data == NULL) return -ENOMEM; if (copy_from_user(data, buf, count) != 0) { rc = -EFAULT; goto free_data_out; } smack = kzalloc(count + 1, GFP_KERNEL); if (smack == NULL) { rc = -ENOMEM; goto free_data_out; } data[count] = '\0'; rc = sscanf(data, "%hhd.%hhd.%hhd.%hhd/%u %s", &host[0], &host[1], &host[2], &host[3], &m, smack); if (rc != 6) { rc = sscanf(data, "%hhd.%hhd.%hhd.%hhd %s", &host[0], &host[1], &host[2], &host[3], smack); if (rc != 5) { rc = -EINVAL; goto free_out; } m = BEBITS; } if (m > BEBITS) { rc = -EINVAL; goto free_out; } /* * If smack begins with '-', it is an option, don't import it */ if (smack[0] != '-') { skp = smk_import_entry(smack, 0); if (IS_ERR(skp)) { rc = PTR_ERR(skp); goto free_out; } } else { /* check known options */ if (strcmp(smack, smack_cipso_option.smk_known) == 0) skp = &smack_cipso_option; else { rc = -EINVAL; goto free_out; } } for (temp_mask = 0; m > 0; m--) { temp_mask |= mask_bits; mask_bits >>= 1; } mask.s_addr = cpu_to_be32(temp_mask); newname.sin_addr.s_addr &= mask.s_addr; /* * Only allow one writer at a time. Writes should be * quite rare and small in any case. */ mutex_lock(&smk_netlbladdr_lock); nsa = newname.sin_addr.s_addr; /* try to find if the prefix is already in the list */ found = 0; list_for_each_entry_rcu(snp, &smk_netlbladdr_list, list) { if (snp->smk_host.sin_addr.s_addr == nsa && snp->smk_mask.s_addr == mask.s_addr) { found = 1; break; } } smk_netlabel_audit_set(&audit_info); if (found == 0) { snp = kzalloc(sizeof(*snp), GFP_KERNEL); if (snp == NULL) rc = -ENOMEM; else { rc = 0; snp->smk_host.sin_addr.s_addr = newname.sin_addr.s_addr; snp->smk_mask.s_addr = mask.s_addr; snp->smk_label = skp; smk_netlbladdr_insert(snp); } } else { /* we delete the unlabeled entry, only if the previous label * wasn't the special CIPSO option */ if (snp->smk_label != &smack_cipso_option) rc = netlbl_cfg_unlbl_static_del(&init_net, NULL, &snp->smk_host.sin_addr, &snp->smk_mask, PF_INET, &audit_info); else rc = 0; snp->smk_label = skp; } /* * Now tell netlabel about the single label nature of * this host so that incoming packets get labeled. * but only if we didn't get the special CIPSO option */ if (rc == 0 && skp != &smack_cipso_option) rc = netlbl_cfg_unlbl_static_add(&init_net, NULL, &snp->smk_host.sin_addr, &snp->smk_mask, PF_INET, snp->smk_label->smk_secid, &audit_info); if (rc == 0) rc = count; mutex_unlock(&smk_netlbladdr_lock); free_out: kfree(smack); free_data_out: kfree(data); return rc; } static const struct file_operations smk_netlbladdr_ops = { .open = smk_open_netlbladdr, .read = seq_read, .llseek = seq_lseek, .write = smk_write_netlbladdr, .release = seq_release, }; /** * smk_read_doi - read() for /smack/doi * @filp: file pointer, not actually used * @buf: where to put the result * @count: maximum to send along * @ppos: where to start * * Returns number of bytes read or error code, as appropriate */ static ssize_t smk_read_doi(struct file *filp, char __user *buf, size_t count, loff_t *ppos) { char temp[80]; ssize_t rc; if (*ppos != 0) return 0; sprintf(temp, "%d", smk_cipso_doi_value); rc = simple_read_from_buffer(buf, count, ppos, temp, strlen(temp)); return rc; } /** * smk_write_doi - write() for /smack/doi * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start * * Returns number of bytes written or error code, as appropriate */ static ssize_t smk_write_doi(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { char temp[80]; int i; if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; if (count >= sizeof(temp) || count == 0) return -EINVAL; if (copy_from_user(temp, buf, count) != 0) return -EFAULT; temp[count] = '\0'; if (sscanf(temp, "%d", &i) != 1) return -EINVAL; smk_cipso_doi_value = i; smk_cipso_doi(); return count; } static const struct file_operations smk_doi_ops = { .read = smk_read_doi, .write = smk_write_doi, .llseek = default_llseek, }; /** * smk_read_direct - read() for /smack/direct * @filp: file pointer, not actually used * @buf: where to put the result * @count: maximum to send along * @ppos: where to start * * Returns number of bytes read or error code, as appropriate */ static ssize_t smk_read_direct(struct file *filp, char __user *buf, size_t count, loff_t *ppos) { char temp[80]; ssize_t rc; if (*ppos != 0) return 0; sprintf(temp, "%d", smack_cipso_direct); rc = simple_read_from_buffer(buf, count, ppos, temp, strlen(temp)); return rc; } /** * smk_write_direct - write() for /smack/direct * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start * * Returns number of bytes written or error code, as appropriate */ static ssize_t smk_write_direct(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct smack_known *skp; char temp[80]; int i; if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; if (count >= sizeof(temp) || count == 0) return -EINVAL; if (copy_from_user(temp, buf, count) != 0) return -EFAULT; temp[count] = '\0'; if (sscanf(temp, "%d", &i) != 1) return -EINVAL; /* * Don't do anything if the value hasn't actually changed. * If it is changing reset the level on entries that were * set up to be direct when they were created. */ if (smack_cipso_direct != i) { mutex_lock(&smack_known_lock); list_for_each_entry_rcu(skp, &smack_known_list, list) if (skp->smk_netlabel.attr.mls.lvl == smack_cipso_direct) skp->smk_netlabel.attr.mls.lvl = i; smack_cipso_direct = i; mutex_unlock(&smack_known_lock); } return count; } static const struct file_operations smk_direct_ops = { .read = smk_read_direct, .write = smk_write_direct, .llseek = default_llseek, }; /** * smk_read_mapped - read() for /smack/mapped * @filp: file pointer, not actually used * @buf: where to put the result * @count: maximum to send along * @ppos: where to start * * Returns number of bytes read or error code, as appropriate */ static ssize_t smk_read_mapped(struct file *filp, char __user *buf, size_t count, loff_t *ppos) { char temp[80]; ssize_t rc; if (*ppos != 0) return 0; sprintf(temp, "%d", smack_cipso_mapped); rc = simple_read_from_buffer(buf, count, ppos, temp, strlen(temp)); return rc; } /** * smk_write_mapped - write() for /smack/mapped * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start * * Returns number of bytes written or error code, as appropriate */ static ssize_t smk_write_mapped(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct smack_known *skp; char temp[80]; int i; if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; if (count >= sizeof(temp) || count == 0) return -EINVAL; if (copy_from_user(temp, buf, count) != 0) return -EFAULT; temp[count] = '\0'; if (sscanf(temp, "%d", &i) != 1) return -EINVAL; /* * Don't do anything if the value hasn't actually changed. * If it is changing reset the level on entries that were * set up to be mapped when they were created. */ if (smack_cipso_mapped != i) { mutex_lock(&smack_known_lock); list_for_each_entry_rcu(skp, &smack_known_list, list) if (skp->smk_netlabel.attr.mls.lvl == smack_cipso_mapped) skp->smk_netlabel.attr.mls.lvl = i; smack_cipso_mapped = i; mutex_unlock(&smack_known_lock); } return count; } static const struct file_operations smk_mapped_ops = { .read = smk_read_mapped, .write = smk_write_mapped, .llseek = default_llseek, }; /** * smk_read_ambient - read() for /smack/ambient * @filp: file pointer, not actually used * @buf: where to put the result * @cn: maximum to send along * @ppos: where to start * * Returns number of bytes read or error code, as appropriate */ static ssize_t smk_read_ambient(struct file *filp, char __user *buf, size_t cn, loff_t *ppos) { ssize_t rc; int asize; if (*ppos != 0) return 0; /* * Being careful to avoid a problem in the case where * smack_net_ambient gets changed in midstream. */ mutex_lock(&smack_ambient_lock); asize = strlen(smack_net_ambient->smk_known) + 1; if (cn >= asize) rc = simple_read_from_buffer(buf, cn, ppos, smack_net_ambient->smk_known, asize); else rc = -EINVAL; mutex_unlock(&smack_ambient_lock); return rc; } /** * smk_write_ambient - write() for /smack/ambient * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start * * Returns number of bytes written or error code, as appropriate */ static ssize_t smk_write_ambient(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct smack_known *skp; char *oldambient; char *data; int rc = count; if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; data = kzalloc(count + 1, GFP_KERNEL); if (data == NULL) return -ENOMEM; if (copy_from_user(data, buf, count) != 0) { rc = -EFAULT; goto out; } skp = smk_import_entry(data, count); if (IS_ERR(skp)) { rc = PTR_ERR(skp); goto out; } mutex_lock(&smack_ambient_lock); oldambient = smack_net_ambient->smk_known; smack_net_ambient = skp; smk_unlbl_ambient(oldambient); mutex_unlock(&smack_ambient_lock); out: kfree(data); return rc; } static const struct file_operations smk_ambient_ops = { .read = smk_read_ambient, .write = smk_write_ambient, .llseek = default_llseek, }; /* * Seq_file operations for /smack/onlycap */ static void *onlycap_seq_start(struct seq_file *s, loff_t *pos) { return smk_seq_start(s, pos, &smack_onlycap_list); } static void *onlycap_seq_next(struct seq_file *s, void *v, loff_t *pos) { return smk_seq_next(s, v, pos, &smack_onlycap_list); } static int onlycap_seq_show(struct seq_file *s, void *v) { struct list_head *list = v; struct smack_onlycap *sop = list_entry_rcu(list, struct smack_onlycap, list); seq_puts(s, sop->smk_label->smk_known); seq_putc(s, ' '); return 0; } static const struct seq_operations onlycap_seq_ops = { .start = onlycap_seq_start, .next = onlycap_seq_next, .show = onlycap_seq_show, .stop = smk_seq_stop, }; static int smk_open_onlycap(struct inode *inode, struct file *file) { return seq_open(file, &onlycap_seq_ops); } /** * smk_list_swap_rcu - swap public list with a private one in RCU-safe way * The caller must hold appropriate mutex to prevent concurrent modifications * to the public list. * Private list is assumed to be not accessible to other threads yet. * * @public: public list * @private: private list */ static void smk_list_swap_rcu(struct list_head *public, struct list_head *private) { struct list_head *first, *last; if (list_empty(public)) { list_splice_init_rcu(private, public, synchronize_rcu); } else { /* Remember public list before replacing it */ first = public->next; last = public->prev; /* Publish private list in place of public in RCU-safe way */ private->prev->next = public; private->next->prev = public; rcu_assign_pointer(public->next, private->next); public->prev = private->prev; synchronize_rcu(); /* When all readers are done with the old public list, * attach it in place of private */ private->next = first; private->prev = last; first->prev = private; last->next = private; } } /** * smk_write_onlycap - write() for smackfs/onlycap * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start * * Returns number of bytes written or error code, as appropriate */ static ssize_t smk_write_onlycap(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { char *data; char *data_parse; char *tok; struct smack_known *skp; struct smack_onlycap *sop; struct smack_onlycap *sop2; LIST_HEAD(list_tmp); int rc = count; if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; data = kzalloc(count + 1, GFP_KERNEL); if (data == NULL) return -ENOMEM; if (copy_from_user(data, buf, count) != 0) { kfree(data); return -EFAULT; } data_parse = data; while ((tok = strsep(&data_parse, " ")) != NULL) { if (!*tok) continue; skp = smk_import_entry(tok, 0); if (IS_ERR(skp)) { rc = PTR_ERR(skp); break; } sop = kzalloc(sizeof(*sop), GFP_KERNEL); if (sop == NULL) { rc = -ENOMEM; break; } sop->smk_label = skp; list_add_rcu(&sop->list, &list_tmp); } kfree(data); /* * Clear the smack_onlycap on invalid label errors. This means * that we can pass a null string to unset the onlycap value. * * Importing will also reject a label beginning with '-', * so "-usecapabilities" will also work. * * But do so only on invalid label, not on system errors. * The invalid label must be first to count as clearing attempt. */ if (rc == -EINVAL && list_empty(&list_tmp)) rc = count; if (rc >= 0) { mutex_lock(&smack_onlycap_lock); smk_list_swap_rcu(&smack_onlycap_list, &list_tmp); mutex_unlock(&smack_onlycap_lock); } list_for_each_entry_safe(sop, sop2, &list_tmp, list) kfree(sop); return rc; } static const struct file_operations smk_onlycap_ops = { .open = smk_open_onlycap, .read = seq_read, .write = smk_write_onlycap, .llseek = seq_lseek, .release = seq_release, }; #ifdef CONFIG_SECURITY_SMACK_BRINGUP /** * smk_read_unconfined - read() for smackfs/unconfined * @filp: file pointer, not actually used * @buf: where to put the result * @cn: maximum to send along * @ppos: where to start * * Returns number of bytes read or error code, as appropriate */ static ssize_t smk_read_unconfined(struct file *filp, char __user *buf, size_t cn, loff_t *ppos) { char *smack = ""; ssize_t rc = -EINVAL; int asize; if (*ppos != 0) return 0; if (smack_unconfined != NULL) smack = smack_unconfined->smk_known; asize = strlen(smack) + 1; if (cn >= asize) rc = simple_read_from_buffer(buf, cn, ppos, smack, asize); return rc; } /** * smk_write_unconfined - write() for smackfs/unconfined * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start * * Returns number of bytes written or error code, as appropriate */ static ssize_t smk_write_unconfined(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { char *data; struct smack_known *skp; int rc = count; if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; data = kzalloc(count + 1, GFP_KERNEL); if (data == NULL) return -ENOMEM; if (copy_from_user(data, buf, count) != 0) { rc = -EFAULT; goto freeout; } /* * Clear the smack_unconfined on invalid label errors. This means * that we can pass a null string to unset the unconfined value. * * Importing will also reject a label beginning with '-', * so "-confine" will also work. * * But do so only on invalid label, not on system errors. */ skp = smk_import_entry(data, count); if (PTR_ERR(skp) == -EINVAL) skp = NULL; else if (IS_ERR(skp)) { rc = PTR_ERR(skp); goto freeout; } smack_unconfined = skp; freeout: kfree(data); return rc; } static const struct file_operations smk_unconfined_ops = { .read = smk_read_unconfined, .write = smk_write_unconfined, .llseek = default_llseek, }; #endif /* CONFIG_SECURITY_SMACK_BRINGUP */ /** * smk_read_logging - read() for /smack/logging * @filp: file pointer, not actually used * @buf: where to put the result * @cn: maximum to send along * @ppos: where to start * * Returns number of bytes read or error code, as appropriate */ static ssize_t smk_read_logging(struct file *filp, char __user *buf, size_t count, loff_t *ppos) { char temp[32]; ssize_t rc; if (*ppos != 0) return 0; sprintf(temp, "%d\n", log_policy); rc = simple_read_from_buffer(buf, count, ppos, temp, strlen(temp)); return rc; } /** * smk_write_logging - write() for /smack/logging * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start * * Returns number of bytes written or error code, as appropriate */ static ssize_t smk_write_logging(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { char temp[32]; int i; if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; if (count >= sizeof(temp) || count == 0) return -EINVAL; if (copy_from_user(temp, buf, count) != 0) return -EFAULT; temp[count] = '\0'; if (sscanf(temp, "%d", &i) != 1) return -EINVAL; if (i < 0 || i > 3) return -EINVAL; log_policy = i; return count; } static const struct file_operations smk_logging_ops = { .read = smk_read_logging, .write = smk_write_logging, .llseek = default_llseek, }; /* * Seq_file read operations for /smack/load-self */ static void *load_self_seq_start(struct seq_file *s, loff_t *pos) { struct task_smack *tsp = current_security(); return smk_seq_start(s, pos, &tsp->smk_rules); } static void *load_self_seq_next(struct seq_file *s, void *v, loff_t *pos) { struct task_smack *tsp = current_security(); return smk_seq_next(s, v, pos, &tsp->smk_rules); } static int load_self_seq_show(struct seq_file *s, void *v) { struct list_head *list = v; struct smack_rule *srp = list_entry_rcu(list, struct smack_rule, list); smk_rule_show(s, srp, SMK_LABELLEN); return 0; } static const struct seq_operations load_self_seq_ops = { .start = load_self_seq_start, .next = load_self_seq_next, .show = load_self_seq_show, .stop = smk_seq_stop, }; /** * smk_open_load_self - open() for /smack/load-self2 * @inode: inode structure representing file * @file: "load" file pointer * * For reading, use load_seq_* seq_file reading operations. */ static int smk_open_load_self(struct inode *inode, struct file *file) { return seq_open(file, &load_self_seq_ops); } /** * smk_write_load_self - write() for /smack/load-self * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start - must be 0 * */ static ssize_t smk_write_load_self(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct task_smack *tsp = current_security(); return smk_write_rules_list(file, buf, count, ppos, &tsp->smk_rules, &tsp->smk_rules_lock, SMK_FIXED24_FMT); } static const struct file_operations smk_load_self_ops = { .open = smk_open_load_self, .read = seq_read, .llseek = seq_lseek, .write = smk_write_load_self, .release = seq_release, }; /** * smk_user_access - handle access check transaction * @file: file pointer * @buf: data from user space * @count: bytes sent * @ppos: where to start - must be 0 */ static ssize_t smk_user_access(struct file *file, const char __user *buf, size_t count, loff_t *ppos, int format) { struct smack_parsed_rule rule; char *data; int res; data = simple_transaction_get(file, buf, count); if (IS_ERR(data)) return PTR_ERR(data); if (format == SMK_FIXED24_FMT) { if (count < SMK_LOADLEN) return -EINVAL; res = smk_parse_rule(data, &rule, 0); } else { /* * simple_transaction_get() returns null-terminated data */ res = smk_parse_long_rule(data, &rule, 0, 3); } if (res >= 0) res = smk_access(rule.smk_subject, rule.smk_object, rule.smk_access1, NULL); else if (res != -ENOENT) return res; /* * smk_access() can return a value > 0 in the "bringup" case. */ data[0] = res >= 0 ? '1' : '0'; data[1] = '\0'; simple_transaction_set(file, 2); if (format == SMK_FIXED24_FMT) return SMK_LOADLEN; return count; } /** * smk_write_access - handle access check transaction * @file: file pointer * @buf: data from user space * @count: bytes sent * @ppos: where to start - must be 0 */ static ssize_t smk_write_access(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { return smk_user_access(file, buf, count, ppos, SMK_FIXED24_FMT); } static const struct file_operations smk_access_ops = { .write = smk_write_access, .read = simple_transaction_read, .release = simple_transaction_release, .llseek = generic_file_llseek, }; /* * Seq_file read operations for /smack/load2 */ static int load2_seq_show(struct seq_file *s, void *v) { struct list_head *list = v; struct smack_master_list *smlp = list_entry_rcu(list, struct smack_master_list, list); smk_rule_show(s, smlp->smk_rule, SMK_LONGLABEL); return 0; } static const struct seq_operations load2_seq_ops = { .start = load2_seq_start, .next = load2_seq_next, .show = load2_seq_show, .stop = smk_seq_stop, }; /** * smk_open_load2 - open() for /smack/load2 * @inode: inode structure representing file * @file: "load2" file pointer * * For reading, use load2_seq_* seq_file reading operations. */ static int smk_open_load2(struct inode *inode, struct file *file) { return seq_open(file, &load2_seq_ops); } /** * smk_write_load2 - write() for /smack/load2 * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start - must be 0 * */ static ssize_t smk_write_load2(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { /* * Must have privilege. */ if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; return smk_write_rules_list(file, buf, count, ppos, NULL, NULL, SMK_LONG_FMT); } static const struct file_operations smk_load2_ops = { .open = smk_open_load2, .read = seq_read, .llseek = seq_lseek, .write = smk_write_load2, .release = seq_release, }; /* * Seq_file read operations for /smack/load-self2 */ static void *load_self2_seq_start(struct seq_file *s, loff_t *pos) { struct task_smack *tsp = current_security(); return smk_seq_start(s, pos, &tsp->smk_rules); } static void *load_self2_seq_next(struct seq_file *s, void *v, loff_t *pos) { struct task_smack *tsp = current_security(); return smk_seq_next(s, v, pos, &tsp->smk_rules); } static int load_self2_seq_show(struct seq_file *s, void *v) { struct list_head *list = v; struct smack_rule *srp = list_entry_rcu(list, struct smack_rule, list); smk_rule_show(s, srp, SMK_LONGLABEL); return 0; } static const struct seq_operations load_self2_seq_ops = { .start = load_self2_seq_start, .next = load_self2_seq_next, .show = load_self2_seq_show, .stop = smk_seq_stop, }; /** * smk_open_load_self2 - open() for /smack/load-self2 * @inode: inode structure representing file * @file: "load" file pointer * * For reading, use load_seq_* seq_file reading operations. */ static int smk_open_load_self2(struct inode *inode, struct file *file) { return seq_open(file, &load_self2_seq_ops); } /** * smk_write_load_self2 - write() for /smack/load-self2 * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start - must be 0 * */ static ssize_t smk_write_load_self2(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct task_smack *tsp = current_security(); return smk_write_rules_list(file, buf, count, ppos, &tsp->smk_rules, &tsp->smk_rules_lock, SMK_LONG_FMT); } static const struct file_operations smk_load_self2_ops = { .open = smk_open_load_self2, .read = seq_read, .llseek = seq_lseek, .write = smk_write_load_self2, .release = seq_release, }; /** * smk_write_access2 - handle access check transaction * @file: file pointer * @buf: data from user space * @count: bytes sent * @ppos: where to start - must be 0 */ static ssize_t smk_write_access2(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { return smk_user_access(file, buf, count, ppos, SMK_LONG_FMT); } static const struct file_operations smk_access2_ops = { .write = smk_write_access2, .read = simple_transaction_read, .release = simple_transaction_release, .llseek = generic_file_llseek, }; /** * smk_write_revoke_subj - write() for /smack/revoke-subject * @file: file pointer * @buf: data from user space * @count: bytes sent * @ppos: where to start - must be 0 */ static ssize_t smk_write_revoke_subj(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { char *data; const char *cp; struct smack_known *skp; struct smack_rule *sp; struct list_head *rule_list; struct mutex *rule_lock; int rc = count; if (*ppos != 0) return -EINVAL; if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; if (count == 0 || count > SMK_LONGLABEL) return -EINVAL; data = kzalloc(count, GFP_KERNEL); if (data == NULL) return -ENOMEM; if (copy_from_user(data, buf, count) != 0) { rc = -EFAULT; goto out_data; } cp = smk_parse_smack(data, count); if (IS_ERR(cp)) { rc = PTR_ERR(cp); goto out_data; } skp = smk_find_entry(cp); if (skp == NULL) goto out_cp; rule_list = &skp->smk_rules; rule_lock = &skp->smk_rules_lock; mutex_lock(rule_lock); list_for_each_entry_rcu(sp, rule_list, list) sp->smk_access = 0; mutex_unlock(rule_lock); out_cp: kfree(cp); out_data: kfree(data); return rc; } static const struct file_operations smk_revoke_subj_ops = { .write = smk_write_revoke_subj, .read = simple_transaction_read, .release = simple_transaction_release, .llseek = generic_file_llseek, }; static struct kset *smackfs_kset; /** * smk_init_sysfs - initialize /sys/fs/smackfs * */ static int smk_init_sysfs(void) { smackfs_kset = kset_create_and_add("smackfs", NULL, fs_kobj); if (!smackfs_kset) return -ENOMEM; return 0; } /** * smk_write_change_rule - write() for /smack/change-rule * @file: file pointer * @buf: data from user space * @count: bytes sent * @ppos: where to start - must be 0 */ static ssize_t smk_write_change_rule(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { /* * Must have privilege. */ if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; return smk_write_rules_list(file, buf, count, ppos, NULL, NULL, SMK_CHANGE_FMT); } static const struct file_operations smk_change_rule_ops = { .write = smk_write_change_rule, .read = simple_transaction_read, .release = simple_transaction_release, .llseek = generic_file_llseek, }; /** * smk_read_syslog - read() for smackfs/syslog * @filp: file pointer, not actually used * @buf: where to put the result * @cn: maximum to send along * @ppos: where to start * * Returns number of bytes read or error code, as appropriate */ static ssize_t smk_read_syslog(struct file *filp, char __user *buf, size_t cn, loff_t *ppos) { struct smack_known *skp; ssize_t rc = -EINVAL; int asize; if (*ppos != 0) return 0; if (smack_syslog_label == NULL) skp = &smack_known_star; else skp = smack_syslog_label; asize = strlen(skp->smk_known) + 1; if (cn >= asize) rc = simple_read_from_buffer(buf, cn, ppos, skp->smk_known, asize); return rc; } /** * smk_write_syslog - write() for smackfs/syslog * @file: file pointer, not actually used * @buf: where to get the data from * @count: bytes sent * @ppos: where to start * * Returns number of bytes written or error code, as appropriate */ static ssize_t smk_write_syslog(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { char *data; struct smack_known *skp; int rc = count; if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; data = kzalloc(count + 1, GFP_KERNEL); if (data == NULL) return -ENOMEM; if (copy_from_user(data, buf, count) != 0) rc = -EFAULT; else { skp = smk_import_entry(data, count); if (IS_ERR(skp)) rc = PTR_ERR(skp); else smack_syslog_label = skp; } kfree(data); return rc; } static const struct file_operations smk_syslog_ops = { .read = smk_read_syslog, .write = smk_write_syslog, .llseek = default_llseek, }; /** * smk_read_ptrace - read() for /smack/ptrace * @filp: file pointer, not actually used * @buf: where to put the result * @count: maximum to send along * @ppos: where to start * * Returns number of bytes read or error code, as appropriate */ static ssize_t smk_read_ptrace(struct file *filp, char __user *buf, size_t count, loff_t *ppos) { char temp[32]; ssize_t rc; if (*ppos != 0) return 0; sprintf(temp, "%d\n", smack_ptrace_rule); rc = simple_read_from_buffer(buf, count, ppos, temp, strlen(temp)); return rc; } /** * smk_write_ptrace - write() for /smack/ptrace * @file: file pointer * @buf: data from user space * @count: bytes sent * @ppos: where to start - must be 0 */ static ssize_t smk_write_ptrace(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { char temp[32]; int i; if (!smack_privileged(CAP_MAC_ADMIN)) return -EPERM; if (*ppos != 0 || count >= sizeof(temp) || count == 0) return -EINVAL; if (copy_from_user(temp, buf, count) != 0) return -EFAULT; temp[count] = '\0'; if (sscanf(temp, "%d", &i) != 1) return -EINVAL; if (i < SMACK_PTRACE_DEFAULT || i > SMACK_PTRACE_MAX) return -EINVAL; smack_ptrace_rule = i; return count; } static const struct file_operations smk_ptrace_ops = { .write = smk_write_ptrace, .read = smk_read_ptrace, .llseek = default_llseek, }; /** * smk_fill_super - fill the smackfs superblock * @sb: the empty superblock * @data: unused * @silent: unused * * Fill in the well known entries for the smack filesystem * * Returns 0 on success, an error code on failure */ static int smk_fill_super(struct super_block *sb, void *data, int silent) { int rc; struct inode *root_inode; static struct tree_descr smack_files[] = { [SMK_LOAD] = { "load", &smk_load_ops, S_IRUGO|S_IWUSR}, [SMK_CIPSO] = { "cipso", &smk_cipso_ops, S_IRUGO|S_IWUSR}, [SMK_DOI] = { "doi", &smk_doi_ops, S_IRUGO|S_IWUSR}, [SMK_DIRECT] = { "direct", &smk_direct_ops, S_IRUGO|S_IWUSR}, [SMK_AMBIENT] = { "ambient", &smk_ambient_ops, S_IRUGO|S_IWUSR}, [SMK_NETLBLADDR] = { "netlabel", &smk_netlbladdr_ops, S_IRUGO|S_IWUSR}, [SMK_ONLYCAP] = { "onlycap", &smk_onlycap_ops, S_IRUGO|S_IWUSR}, [SMK_LOGGING] = { "logging", &smk_logging_ops, S_IRUGO|S_IWUSR}, [SMK_LOAD_SELF] = { "load-self", &smk_load_self_ops, S_IRUGO|S_IWUGO}, [SMK_ACCESSES] = { "access", &smk_access_ops, S_IRUGO|S_IWUGO}, [SMK_MAPPED] = { "mapped", &smk_mapped_ops, S_IRUGO|S_IWUSR}, [SMK_LOAD2] = { "load2", &smk_load2_ops, S_IRUGO|S_IWUSR}, [SMK_LOAD_SELF2] = { "load-self2", &smk_load_self2_ops, S_IRUGO|S_IWUGO}, [SMK_ACCESS2] = { "access2", &smk_access2_ops, S_IRUGO|S_IWUGO}, [SMK_CIPSO2] = { "cipso2", &smk_cipso2_ops, S_IRUGO|S_IWUSR}, [SMK_REVOKE_SUBJ] = { "revoke-subject", &smk_revoke_subj_ops, S_IRUGO|S_IWUSR}, [SMK_CHANGE_RULE] = { "change-rule", &smk_change_rule_ops, S_IRUGO|S_IWUSR}, [SMK_SYSLOG] = { "syslog", &smk_syslog_ops, S_IRUGO|S_IWUSR}, [SMK_PTRACE] = { "ptrace", &smk_ptrace_ops, S_IRUGO|S_IWUSR}, #ifdef CONFIG_SECURITY_SMACK_BRINGUP [SMK_UNCONFINED] = { "unconfined", &smk_unconfined_ops, S_IRUGO|S_IWUSR}, #endif /* last one */ {""} }; rc = simple_fill_super(sb, SMACK_MAGIC, smack_files); if (rc != 0) { printk(KERN_ERR "%s failed %d while creating inodes\n", __func__, rc); return rc; } root_inode = d_inode(sb->s_root); return 0; } /** * smk_mount - get the smackfs superblock * @fs_type: passed along without comment * @flags: passed along without comment * @dev_name: passed along without comment * @data: passed along without comment * * Just passes everything along. * * Returns what the lower level code does. */ static struct dentry *smk_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_single(fs_type, flags, data, smk_fill_super); } static struct file_system_type smk_fs_type = { .name = "smackfs", .mount = smk_mount, .kill_sb = kill_litter_super, }; static struct vfsmount *smackfs_mount; static int __init smk_preset_netlabel(struct smack_known *skp) { skp->smk_netlabel.domain = skp->smk_known; skp->smk_netlabel.flags = NETLBL_SECATTR_DOMAIN | NETLBL_SECATTR_MLS_LVL; return smk_netlbl_mls(smack_cipso_direct, skp->smk_known, &skp->smk_netlabel, strlen(skp->smk_known)); } /** * init_smk_fs - get the smackfs superblock * * register the smackfs * * Do not register smackfs if Smack wasn't enabled * on boot. We can not put this method normally under the * smack_init() code path since the security subsystem get * initialized before the vfs caches. * * Returns true if we were not chosen on boot or if * we were chosen and filesystem registration succeeded. */ static int __init init_smk_fs(void) { int err; int rc; if (!security_module_enable("smack")) return 0; err = smk_init_sysfs(); if (err) printk(KERN_ERR "smackfs: sysfs mountpoint problem.\n"); err = register_filesystem(&smk_fs_type); if (!err) { smackfs_mount = kern_mount(&smk_fs_type); if (IS_ERR(smackfs_mount)) { printk(KERN_ERR "smackfs: could not mount!\n"); err = PTR_ERR(smackfs_mount); smackfs_mount = NULL; } } smk_cipso_doi(); smk_unlbl_ambient(NULL); rc = smk_preset_netlabel(&smack_known_floor); if (err == 0 && rc < 0) err = rc; rc = smk_preset_netlabel(&smack_known_hat); if (err == 0 && rc < 0) err = rc; rc = smk_preset_netlabel(&smack_known_huh); if (err == 0 && rc < 0) err = rc; rc = smk_preset_netlabel(&smack_known_invalid); if (err == 0 && rc < 0) err = rc; rc = smk_preset_netlabel(&smack_known_star); if (err == 0 && rc < 0) err = rc; rc = smk_preset_netlabel(&smack_known_web); if (err == 0 && rc < 0) err = rc; return err; } __initcall(init_smk_fs);
identisoft-rashid/ec3_kernel_pre_4.1
security/smack/smackfs.c
C
gpl-2.0
62,971
<?php /** * Part of Windwalker project. * * @copyright Copyright (C) 2015 LYRASOFT. All rights reserved. * @license GNU General Public License version 2 or later; */ namespace Windwalker\Html\Grid; /** * The Grid class to dynamically generate HTML tables. * * This is currently a Joomla JGrid fork. * * @see https://github.com/joomla/joomla-cms/blob/staging/libraries/joomla/grid/grid.php * * @since 2.1 */ class Grid { const ROW_HEAD = 1; const ROW_FOOT = 2; const ROW_NORMAL = 3; /** * Array of columns * @var array */ protected $columns = array(); /** * Current active row * @var int */ protected $activeRow = 0; /** * Rows of the table (including header and footer rows) * @var array */ protected $rows = array(); /** * Header and Footer row-IDs * @var array */ protected $specialRows = array('header' => array(), 'footer' => array()); /** * Associative array of attributes for the table-tag * @var array */ protected $options; /** * Constructor for a Grid object * * @param array $options Associative array of attributes for the table-tag * * @since 2.1 */ public function __construct($options = array()) { $this->setTableOptions($options, true); } /** * create * * @param array $options * * @return static */ public static function create($options = array()) { return new static($options); } /** * Magic function to render this object as a table. * * @return string * * @since 2.1 */ public function __toString() { try { return $this->toString(); } catch (\Exception $e) { return (string) $e; } } /** * Method to set the attributes for a table-tag * * @param array $options Associative array of attributes for the table-tag * @param bool $replace Replace possibly existing attributes * * @return static This object for chaining * * @since 2.1 */ public function setTableOptions($options = array(), $replace = false) { if ($replace) { $this->options = $options; } else { $this->options = array_merge($this->options, $options); } return $this; } /** * Get the Attributes of the current table * * @return array Associative array of attributes * * @since 2.1 */ public function getTableOptions() { return $this->options; } /** * Add new column name to process * * @param string $name Internal column name * * @return static This object for chaining * * @since 2.1 */ public function addColumn($name) { $this->columns[] = $name; return $this; } /** * Returns the list of internal columns * * @return array List of internal columns * * @since 2.1 */ public function getColumns() { return $this->columns; } /** * Delete column by name * * @param string $name Name of the column to be deleted * * @return static This object for chaining * * @since 2.1 */ public function deleteColumn($name) { $index = array_search($name, $this->columns); if ($index !== false) { unset($this->columns[$index]); $this->columns = array_values($this->columns); } return $this; } /** * Method to set a whole range of columns at once * This can be used to re-order the columns, too * * @param array $columns List of internal column names * * @return static This object for chaining * * @since 2.1 */ public function setColumns($columns) { $this->columns = array_values($columns); return $this; } /** * Adds a row to the table and sets the currently * active row to the new row * * @param array $options Associative array of attributes for the row * @param int|bool $special 1 for a new row in the header, 2 for a new row in the footer * * @return static This object for chaining * * @since 2.1 */ public function addRow($options = array(), $special = self::ROW_NORMAL) { $this->rows[]['_row'] = $options; $this->activeRow = count($this->rows) - 1; if ($special) { if ($special === static::ROW_HEAD) { $this->specialRows['header'][] = $this->activeRow; } elseif ($special === static::ROW_FOOT) { $this->specialRows['footer'][] = $this->activeRow; } } return $this; } /** * Method to get the attributes of the currently active row * * @return array Associative array of attributes * * @since 2.1 */ public function getRowOptions() { return $this->rows[$this->activeRow]['_row']; } /** * Method to set the attributes of the currently active row * * @param array $options Associative array of attributes * * @return static This object for chaining * * @since 2.1 */ public function setRowOptions($options) { $this->rows[$this->activeRow]['_row'] = $options; return $this; } /** * Get the currently active row ID * * @return int ID of the currently active row * * @since 2.1 */ public function getActiveRow() { return $this->activeRow; } /** * Set the currently active row * * @param int $id ID of the row to be set to current * * @return static This object for chaining * * @since 2.1 */ public function setActiveRow($id) { $this->activeRow = (int) $id; return $this; } /** * Set cell content for a specific column for the * currently active row * * @param string $name Name of the column * @param string $content Content for the cell * @param array $option Associative array of attributes for the td-element * @param bool $replace If false, the content is appended to the current content of the cell * * @return static This object for chaining * * @since 2.1 */ public function setRowCell($name, $content, $option = array(), $replace = true) { if ($replace || !isset($this->rows[$this->activeRow][$name])) { $cell = new \stdClass; $cell->options = $option; $cell->content = $content; $this->rows[$this->activeRow][$name] = $cell; } else { $this->rows[$this->activeRow][$name]->content .= $content; $this->rows[$this->activeRow][$name]->options = $option; } return $this; } /** * Get all data for a row * * @param int|bool $id ID of the row to return * * @return array Array of columns of a table row * * @since 2.1 */ public function getRow($id = false) { if ($id === false) { $id = $this->activeRow; } if (isset($this->rows[(int) $id])) { return $this->rows[(int) $id]; } else { return false; } } /** * Get the IDs of all rows in the table * * @param int|bool $special false for the standard rows, 1 for the header rows, 2 for the footer rows * * @return array Array of IDs * * @since 2.1 */ public function getRows($special = false) { if ($special) { if ($special === 1) { return $this->specialRows['header']; } else { return $this->specialRows['footer']; } } return array_diff(array_keys($this->rows), array_merge($this->specialRows['header'], $this->specialRows['footer'])); } /** * Delete a row from the object * * @param int $id ID of the row to be deleted * * @return static This object for chaining * * @since 2.1 */ public function deleteRow($id) { unset($this->rows[$id]); if (in_array($id, $this->specialRows['header'])) { unset($this->specialRows['header'][array_search($id, $this->specialRows['header'])]); } if (in_array($id, $this->specialRows['footer'])) { unset($this->specialRows['footer'][array_search($id, $this->specialRows['footer'])]); } if ($this->activeRow == $id) { end($this->rows); $this->activeRow = key($this->rows); } return $this; } /** * Render the HTML table * * @return string The rendered HTML table * * @since 2.1 */ public function toString() { $output = array(); $output[] = '<table' . $this->renderAttributes($this->getTableOptions()) . '>'; if (count($this->specialRows['header'])) { $output[] = $this->renderArea($this->specialRows['header'], 'thead', 'th'); } if (count($this->specialRows['footer'])) { $output[] = $this->renderArea($this->specialRows['footer'], 'tfoot'); } $ids = array_diff(array_keys($this->rows), array_merge($this->specialRows['header'], $this->specialRows['footer'])); if (count($ids)) { $output[] = $this->renderArea($ids); } $output[] = '</table>'; return implode('', $output); } /** * Render an area of the table * * @param array $ids IDs of the rows to render * @param string $area Name of the area to render. Valid: tbody, tfoot, thead * @param string $cell Name of the cell to render. Valid: td, th * * @return string The rendered table area * * @since 2.1 */ protected function renderArea($ids, $area = 'tbody', $cell = 'td') { $output = array(); $output[] = '<' . $area . ">\n"; foreach ($ids as $id) { $output[] = "\t<tr" . $this->renderAttributes($this->rows[$id]['_row']) . ">\n"; foreach ($this->getColumns() as $name) { if (isset($this->rows[$id][$name])) { $column = $this->rows[$id][$name]; $output[] = "\t\t<" . $cell . $this->renderAttributes($column->options) . '>' . $column->content . '</' . $cell . ">\n"; } } $output[] = "\t</tr>\n"; } $output[] = '</' . $area . '>'; return implode('', $output); } /** * Renders an HTML attribute from an associative array * * @param array $attributes Associative array of attributes * * @return string The HTML attribute string * * @since 2.1 */ protected function renderAttributes($attributes) { if (count((array) $attributes) == 0) { return ''; } $return = array(); foreach ($attributes as $key => $option) { $return[] = $key . '="' . $option . '"'; } return ' ' . implode(' ', $return); } }
asika32764/joomla-cmf
libraries/windwalker/vendor/windwalker/html/Grid/Grid.php
PHP
gpl-2.0
9,914
/* * 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. */ /* * MetaCost.java * Copyright (C) 2002 University of Waikato, Hamilton, New Zealand * */ package weka.classifiers.meta; import weka.classifiers.Classifier; import weka.classifiers.CostMatrix; import weka.classifiers.RandomizableSingleClassifierEnhancer; import weka.core.Capabilities; import weka.core.Instance; import weka.core.Instances; import weka.core.Option; import weka.core.OptionHandler; import weka.core.RevisionUtils; import weka.core.SelectedTag; import weka.core.Tag; import weka.core.TechnicalInformation; import weka.core.TechnicalInformationHandler; import weka.core.Utils; import weka.core.Capabilities.Capability; import weka.core.TechnicalInformation.Field; import weka.core.TechnicalInformation.Type; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.StringReader; import java.io.StringWriter; import java.util.Enumeration; import java.util.Vector; /** <!-- globalinfo-start --> * This metaclassifier makes its base classifier cost-sensitive using the method specified in<br/> * <br/> * Pedro Domingos: MetaCost: A general method for making classifiers cost-sensitive. In: Fifth International Conference on Knowledge Discovery and Data Mining, 155-164, 1999.<br/> * <br/> * This classifier should produce similar results to one created by passing the base learner to Bagging, which is in turn passed to a CostSensitiveClassifier operating on minimum expected cost. The difference is that MetaCost produces a single cost-sensitive classifier of the base learner, giving the benefits of fast classification and interpretable output (if the base learner itself is interpretable). This implementation uses all bagging iterations when reclassifying training data (the MetaCost paper reports a marginal improvement when only those iterations containing each training instance are used in reclassifying that instance). * <p/> <!-- globalinfo-end --> * <!-- technical-bibtex-start --> * BibTeX: * <pre> * &#64;inproceedings{Domingos1999, * author = {Pedro Domingos}, * booktitle = {Fifth International Conference on Knowledge Discovery and Data Mining}, * pages = {155-164}, * title = {MetaCost: A general method for making classifiers cost-sensitive}, * year = {1999} * } * </pre> * <p/> <!-- technical-bibtex-end --> * <!-- options-start --> * Valid options are: <p/> * * <pre> -I &lt;num&gt; * Number of bagging iterations. * (default 10)</pre> * * <pre> -C &lt;cost file name&gt; * File name of a cost matrix to use. If this is not supplied, * a cost matrix will be loaded on demand. The name of the * on-demand file is the relation name of the training data * plus ".cost", and the path to the on-demand file is * specified with the -N option.</pre> * * <pre> -N &lt;directory&gt; * Name of a directory to search for cost files when loading * costs on demand (default current directory).</pre> * * <pre> -cost-matrix &lt;matrix&gt; * The cost matrix in Matlab single line format.</pre> * * <pre> -P * Size of each bag, as a percentage of the * training set size. (default 100)</pre> * * <pre> -S &lt;num&gt; * Random number seed. * (default 1)</pre> * * <pre> -D * If set, classifier is run in debug mode and * may output additional info to the console</pre> * * <pre> -W * Full name of base classifier. * (default: weka.classifiers.rules.ZeroR)</pre> * * <pre> * Options specific to classifier weka.classifiers.rules.ZeroR: * </pre> * * <pre> -D * If set, classifier is run in debug mode and * may output additional info to the console</pre> * <!-- options-end --> * * Options after -- are passed to the designated classifier.<p> * * @author Len Trigg (len@reeltwo.com) * @version $Revision: 1.24 $ */ public class MetaCost extends RandomizableSingleClassifierEnhancer implements TechnicalInformationHandler { /** for serialization */ static final long serialVersionUID = 1205317833344726855L; /** load cost matrix on demand */ public static final int MATRIX_ON_DEMAND = 1; /** use explicit matrix */ public static final int MATRIX_SUPPLIED = 2; /** Specify possible sources of the cost matrix */ public static final Tag [] TAGS_MATRIX_SOURCE = { new Tag(MATRIX_ON_DEMAND, "Load cost matrix on demand"), new Tag(MATRIX_SUPPLIED, "Use explicit cost matrix") }; /** Indicates the current cost matrix source */ protected int m_MatrixSource = MATRIX_ON_DEMAND; /** * The directory used when loading cost files on demand, null indicates * current directory */ protected File m_OnDemandDirectory = new File(System.getProperty("user.dir")); /** The name of the cost file, for command line options */ protected String m_CostFile; /** The cost matrix */ protected CostMatrix m_CostMatrix = new CostMatrix(1); /** The number of iterations. */ protected int m_NumIterations = 10; /** The size of each bag sample, as a percentage of the training size */ protected int m_BagSizePercent = 100; /** * Returns a string describing classifier * @return a description suitable for * displaying in the explorer/experimenter gui */ public String globalInfo() { return "This metaclassifier makes its base classifier cost-sensitive using the " + "method specified in\n\n" + getTechnicalInformation().toString() + "\n\n" + "This classifier should produce similar results to one created by " + "passing the base learner to Bagging, which is in turn passed to a " + "CostSensitiveClassifier operating on minimum expected cost. The difference " + "is that MetaCost produces a single cost-sensitive classifier of the " + "base learner, giving the benefits of fast classification and interpretable " + "output (if the base learner itself is interpretable). This implementation " + "uses all bagging iterations when reclassifying training data (the MetaCost " + "paper reports a marginal improvement when only those iterations containing " + "each training instance are used in reclassifying that instance)."; } /** * Returns an instance of a TechnicalInformation object, containing * detailed information about the technical background of this class, * e.g., paper reference or book this class is based on. * * @return the technical information about this class */ public TechnicalInformation getTechnicalInformation() { TechnicalInformation result; result = new TechnicalInformation(Type.INPROCEEDINGS); result.setValue(Field.AUTHOR, "Pedro Domingos"); result.setValue(Field.TITLE, "MetaCost: A general method for making classifiers cost-sensitive"); result.setValue(Field.BOOKTITLE, "Fifth International Conference on Knowledge Discovery and Data Mining"); result.setValue(Field.YEAR, "1999"); result.setValue(Field.PAGES, "155-164"); return result; } /** * Returns an enumeration describing the available options. * * @return an enumeration of all the available options. */ public Enumeration listOptions() { Vector newVector = new Vector(6); newVector.addElement(new Option( "\tNumber of bagging iterations.\n" + "\t(default 10)", "I", 1, "-I <num>")); newVector.addElement(new Option( "\tFile name of a cost matrix to use. If this is not supplied,\n" +"\ta cost matrix will be loaded on demand. The name of the\n" +"\ton-demand file is the relation name of the training data\n" +"\tplus \".cost\", and the path to the on-demand file is\n" +"\tspecified with the -N option.", "C", 1, "-C <cost file name>")); newVector.addElement(new Option( "\tName of a directory to search for cost files when loading\n" +"\tcosts on demand (default current directory).", "N", 1, "-N <directory>")); newVector.addElement(new Option( "\tThe cost matrix in Matlab single line format.", "cost-matrix", 1, "-cost-matrix <matrix>")); newVector.addElement(new Option( "\tSize of each bag, as a percentage of the\n" + "\ttraining set size. (default 100)", "P", 1, "-P")); Enumeration enu = super.listOptions(); while (enu.hasMoreElements()) { newVector.addElement(enu.nextElement()); } return newVector.elements(); } /** * Parses a given list of options. <p/> * <!-- options-start --> * Valid options are: <p/> * * <pre> -I &lt;num&gt; * Number of bagging iterations. * (default 10)</pre> * * <pre> -C &lt;cost file name&gt; * File name of a cost matrix to use. If this is not supplied, * a cost matrix will be loaded on demand. The name of the * on-demand file is the relation name of the training data * plus ".cost", and the path to the on-demand file is * specified with the -N option.</pre> * * <pre> -N &lt;directory&gt; * Name of a directory to search for cost files when loading * costs on demand (default current directory).</pre> * * <pre> -cost-matrix &lt;matrix&gt; * The cost matrix in Matlab single line format.</pre> * * <pre> -P * Size of each bag, as a percentage of the * training set size. (default 100)</pre> * * <pre> -S &lt;num&gt; * Random number seed. * (default 1)</pre> * * <pre> -D * If set, classifier is run in debug mode and * may output additional info to the console</pre> * * <pre> -W * Full name of base classifier. * (default: weka.classifiers.rules.ZeroR)</pre> * * <pre> * Options specific to classifier weka.classifiers.rules.ZeroR: * </pre> * * <pre> -D * If set, classifier is run in debug mode and * may output additional info to the console</pre> * <!-- options-end --> * * Options after -- are passed to the designated classifier.<p> * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ public void setOptions(String[] options) throws Exception { String bagIterations = Utils.getOption('I', options); if (bagIterations.length() != 0) { setNumIterations(Integer.parseInt(bagIterations)); } else { setNumIterations(10); } String bagSize = Utils.getOption('P', options); if (bagSize.length() != 0) { setBagSizePercent(Integer.parseInt(bagSize)); } else { setBagSizePercent(100); } String costFile = Utils.getOption('C', options); if (costFile.length() != 0) { setCostMatrix(new CostMatrix(new BufferedReader( new FileReader(costFile)))); setCostMatrixSource(new SelectedTag(MATRIX_SUPPLIED, TAGS_MATRIX_SOURCE)); m_CostFile = costFile; } else { setCostMatrixSource(new SelectedTag(MATRIX_ON_DEMAND, TAGS_MATRIX_SOURCE)); } String demandDir = Utils.getOption('N', options); if (demandDir.length() != 0) { setOnDemandDirectory(new File(demandDir)); } String cost_matrix= Utils.getOption("cost-matrix", options); if (cost_matrix.length() != 0) { StringWriter writer = new StringWriter(); CostMatrix.parseMatlab(cost_matrix).write(writer); setCostMatrix(new CostMatrix(new StringReader(writer.toString()))); setCostMatrixSource(new SelectedTag(MATRIX_SUPPLIED, TAGS_MATRIX_SOURCE)); } super.setOptions(options); } /** * Gets the current settings of the Classifier. * * @return an array of strings suitable for passing to setOptions */ public String [] getOptions() { String [] superOptions = super.getOptions(); String [] options; options = new String [superOptions.length + 6]; int current = 0; if (m_MatrixSource == MATRIX_SUPPLIED) { if (m_CostFile != null) { options[current++] = "-C"; options[current++] = "" + m_CostFile; } else { options[current++] = "-cost-matrix"; options[current++] = getCostMatrix().toMatlab(); } } else { options[current++] = "-N"; options[current++] = "" + getOnDemandDirectory(); } options[current++] = "-I"; options[current++] = "" + getNumIterations(); options[current++] = "-P"; options[current++] = "" + getBagSizePercent(); System.arraycopy(superOptions, 0, options, current, superOptions.length); return options; } /** * Returns the tip text for this property * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String costMatrixSourceTipText() { return "Gets the source location method of the cost matrix. Will " + "be one of MATRIX_ON_DEMAND or MATRIX_SUPPLIED."; } /** * Gets the source location method of the cost matrix. Will be one of * MATRIX_ON_DEMAND or MATRIX_SUPPLIED. * * @return the cost matrix source. */ public SelectedTag getCostMatrixSource() { return new SelectedTag(m_MatrixSource, TAGS_MATRIX_SOURCE); } /** * Sets the source location of the cost matrix. Values other than * MATRIX_ON_DEMAND or MATRIX_SUPPLIED will be ignored. * * @param newMethod the cost matrix location method. */ public void setCostMatrixSource(SelectedTag newMethod) { if (newMethod.getTags() == TAGS_MATRIX_SOURCE) { m_MatrixSource = newMethod.getSelectedTag().getID(); } } /** * Returns the tip text for this property * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String onDemandDirectoryTipText() { return "Name of directory to search for cost files when loading " + "costs on demand."; } /** * Returns the directory that will be searched for cost files when * loading on demand. * * @return The cost file search directory. */ public File getOnDemandDirectory() { return m_OnDemandDirectory; } /** * Sets the directory that will be searched for cost files when * loading on demand. * * @param newDir The cost file search directory. */ public void setOnDemandDirectory(File newDir) { if (newDir.isDirectory()) { m_OnDemandDirectory = newDir; } else { m_OnDemandDirectory = new File(newDir.getParent()); } m_MatrixSource = MATRIX_ON_DEMAND; } /** * Returns the tip text for this property * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String bagSizePercentTipText() { return "The size of each bag, as a percentage of the training set " + "size."; } /** * Gets the size of each bag, as a percentage of the training set size. * * @return the bag size, as a percentage. */ public int getBagSizePercent() { return m_BagSizePercent; } /** * Sets the size of each bag, as a percentage of the training set size. * * @param newBagSizePercent the bag size, as a percentage. */ public void setBagSizePercent(int newBagSizePercent) { m_BagSizePercent = newBagSizePercent; } /** * Returns the tip text for this property * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String numIterationsTipText() { return "The number of bagging iterations."; } /** * Sets the number of bagging iterations * * @param numIterations the number of iterations to use */ public void setNumIterations(int numIterations) { m_NumIterations = numIterations; } /** * Gets the number of bagging iterations * * @return the maximum number of bagging iterations */ public int getNumIterations() { return m_NumIterations; } /** * Returns the tip text for this property * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String costMatrixTipText() { return "A misclassification cost matrix."; } /** * Gets the misclassification cost matrix. * * @return the cost matrix */ public CostMatrix getCostMatrix() { return m_CostMatrix; } /** * Sets the misclassification cost matrix. * * @param newCostMatrix the cost matrix */ public void setCostMatrix(CostMatrix newCostMatrix) { m_CostMatrix = newCostMatrix; m_MatrixSource = MATRIX_SUPPLIED; } /** * Returns default capabilities of the classifier. * * @return the capabilities of this classifier */ public Capabilities getCapabilities() { Capabilities result = super.getCapabilities(); // class result.disableAllClasses(); result.disableAllClassDependencies(); result.enable(Capability.NOMINAL_CLASS); return result; } /** * Builds the model of the base learner. * * @param data the training data * @throws Exception if the classifier could not be built successfully */ public void buildClassifier(Instances data) throws Exception { // can classifier handle the data? getCapabilities().testWithFail(data); // remove instances with missing class data = new Instances(data); data.deleteWithMissingClass(); if (m_MatrixSource == MATRIX_ON_DEMAND) { String costName = data.relationName() + CostMatrix.FILE_EXTENSION; File costFile = new File(getOnDemandDirectory(), costName); if (!costFile.exists()) { throw new Exception("On-demand cost file doesn't exist: " + costFile); } setCostMatrix(new CostMatrix(new BufferedReader( new FileReader(costFile)))); } // Set up the bagger Bagging bagger = new Bagging(); bagger.setClassifier(getClassifier()); bagger.setSeed(getSeed()); bagger.setNumIterations(getNumIterations()); bagger.setBagSizePercent(getBagSizePercent()); bagger.buildClassifier(data); // Use the bagger to reassign class values according to minimum expected // cost Instances newData = new Instances(data); for (int i = 0; i < newData.numInstances(); i++) { Instance current = newData.instance(i); double [] pred = bagger.distributionForInstance(current); int minCostPred = Utils.minIndex(m_CostMatrix.expectedCosts(pred)); current.setClassValue(minCostPred); } // Build a classifier using the reassigned data m_Classifier.buildClassifier(newData); } /** * Classifies a given instance after filtering. * * @param instance the instance to be classified * @return the class distribution for the given instance * @throws Exception if instance could not be classified * successfully */ public double[] distributionForInstance(Instance instance) throws Exception { return m_Classifier.distributionForInstance(instance); } /** * Gets the classifier specification string, which contains the * class name of the classifier and any options to the classifier * * @return the classifier string. */ protected String getClassifierSpec() { Classifier c = getClassifier(); return c.getClass().getName() + " " + Utils.joinOptions(((OptionHandler)c).getOptions()); } /** * Output a representation of this classifier * * @return a string representaiton of the classifier */ public String toString() { if (m_Classifier == null) { return "MetaCost: No model built yet."; } String result = "MetaCost cost sensitive classifier induction"; result += "\nOptions: " + Utils.joinOptions(getOptions()); result += "\nBase learner: " + getClassifierSpec() + "\n\nClassifier Model\n" + m_Classifier.toString() + "\n\nCost Matrix\n" + m_CostMatrix.toString(); return result; } /** * Returns the revision string. * * @return the revision */ public String getRevision() { return RevisionUtils.extract("$Revision: 1.24 $"); } /** * Main method for testing this class. * * @param argv should contain the following arguments: * -t training file [-T test file] [-c class index] */ public static void main(String [] argv) { runClassifier(new MetaCost(), argv); } }
williamClanton/jbossBA
weka/src/main/java/weka/classifiers/meta/MetaCost.java
Java
gpl-2.0
21,275
/** * $Id$ * Central switchboard for the system. This pulls all the individual modules * together into some kind of coherent structure. This is also where you'd * add Naomi support, if I ever get a board to play with... * * Copyright (c) 2005 Nathan Keynes. * * 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 <errno.h> #include <glib.h> #include <unistd.h> #include "lxdream.h" #include "lxpaths.h" #include "dream.h" #include "eventq.h" #include "mem.h" #include "dreamcast.h" #include "asic.h" #include "syscall.h" #include "gui.h" #include "aica/aica.h" #include "gdrom/ide.h" #include "maple/maple.h" #include "pvr2/pvr2.h" #include "sh4/sh4.h" #include "sh4/sh4core.h" #include "vmu/vmulist.h" static gboolean dreamcast_load_bios( const gchar *filename ); /** * Current state of the DC virtual machine */ typedef enum { STATE_UNINIT=0, STATE_RUNNING, STATE_STOPPING, STATE_STOPPED } dreamcast_state_t; static volatile dreamcast_state_t dreamcast_state = STATE_UNINIT; static gboolean dreamcast_use_bios = TRUE; static gboolean dreamcast_has_bios = FALSE; static gboolean dreamcast_has_flash = FALSE; static gboolean dreamcast_exit_on_stop = FALSE; static gchar *dreamcast_program_name = NULL; static sh4addr_t dreamcast_entry_point = 0xA0000000; static uint32_t timeslice_length = DEFAULT_TIMESLICE_LENGTH; static uint64_t run_time_nanosecs = 0; static unsigned int quick_save_state = -1; #define MAX_MODULES 32 static int num_modules = 0; dreamcast_module_t modules[MAX_MODULES]; /** * The unknown module is used for logging files without an actual module * declaration */ struct dreamcast_module unknown_module = { "****", NULL, NULL, NULL, NULL, NULL, NULL, NULL }; extern struct mem_region_fn mem_region_sdram; extern struct mem_region_fn mem_region_vram32; extern struct mem_region_fn mem_region_vram64; extern struct mem_region_fn mem_region_audioram; extern struct mem_region_fn mem_region_audioscratch; extern struct mem_region_fn mem_region_flashram; extern struct mem_region_fn mem_region_bootrom; extern struct mem_region_fn mem_region_pvr2ta; extern struct mem_region_fn mem_region_pvr2yuv; extern struct mem_region_fn mem_region_pvr2vdma1; extern struct mem_region_fn mem_region_pvr2vdma2; unsigned char dc_main_ram[16 MB]; unsigned char dc_boot_rom[2 MB]; unsigned char dc_flash_ram[128 KB]; /** * This function is responsible for defining how all the pieces of the * dreamcast actually fit together. * * Note currently the locations of the various MMIO pages are hard coded in * the MMIO definitions - they should probably be moved here. */ void dreamcast_configure( gboolean use_bootrom ) { char *bios_path = lxdream_get_global_config_path_value(CONFIG_BIOS_PATH); char *flash_path = lxdream_get_global_config_path_value(CONFIG_FLASH_PATH); /* Initialize the event queue first */ event_init(); /* Register the memory framework */ dreamcast_register_module( &mem_module ); /* Setup standard memory map */ mem_map_region( dc_boot_rom, 0x00000000, 2 MB, MEM_REGION_BIOS, &mem_region_bootrom, MEM_FLAG_ROM, 2 MB, 0 ); mem_map_region( dc_flash_ram, 0x00200000, 128 KB, MEM_REGION_FLASH, &mem_region_flashram, MEM_FLAG_RAM, 128 KB, 0 ); mem_map_region( aica_main_ram, 0x00800000, 2 MB, MEM_REGION_AUDIO, &mem_region_audioram, MEM_FLAG_RAM, 2 MB, 0 ); mem_map_region( aica_scratch_ram,0x00703000, 8 KB, MEM_REGION_AUDIO_SCRATCH,&mem_region_audioscratch, MEM_FLAG_RAM, 8 KB, 0 ); mem_map_region( NULL, 0x04000000, 8 MB, MEM_REGION_VIDEO64, &mem_region_vram64, 0, 8 MB, 0 ); mem_map_region( pvr2_main_ram, 0x05000000, 8 MB, MEM_REGION_VIDEO, &mem_region_vram32, MEM_FLAG_RAM, 8 MB, 0 ); mem_map_region( dc_main_ram, 0x0C000000, 16 MB, MEM_REGION_MAIN, &mem_region_sdram, MEM_FLAG_RAM, 0x01000000, 0x0F000000 ); mem_map_region( NULL, 0x10000000, 8 MB, MEM_REGION_PVR2TA, &mem_region_pvr2ta, 0, 0x02000000, 0x12000000 ); mem_map_region( NULL, 0x10800000, 8 MB, MEM_REGION_PVR2YUV, &mem_region_pvr2yuv, 0, 0x02000000, 0x12800000 ); mem_map_region( NULL, 0x11000000, 16 MB, MEM_REGION_PVR2VDMA1, &mem_region_pvr2vdma1, 0, 16 MB, 0 ); mem_map_region( NULL, 0x13000000, 16 MB, MEM_REGION_PVR2VDMA2, &mem_region_pvr2vdma2, 0, 16 MB, 0 ); dreamcast_use_bios = use_bootrom; dreamcast_has_bios = dreamcast_load_bios( bios_path ); if( !dreamcast_has_bios ) { dreamcast_load_fakebios(); } if( flash_path != NULL && flash_path[0] != '\0' ) { mem_load_block( flash_path, 0x00200000, 0x00020000 ); } dreamcast_has_flash = TRUE; /* Load in the rest of the core modules */ dreamcast_register_module( &sh4_module ); dreamcast_register_module( &asic_module ); dreamcast_register_module( &pvr2_module ); dreamcast_register_module( &aica_module ); dreamcast_register_module( &maple_module ); dreamcast_register_module( &ide_module ); dreamcast_register_module( &eventq_module ); g_free(bios_path); g_free(flash_path); } static gboolean dreamcast_load_bios( const gchar *filename ) { if( dreamcast_use_bios ) { dreamcast_has_bios = mem_load_rom( dc_boot_rom, filename, 2 MB, 0x89f2b1a1 ); } else { dreamcast_has_bios = FALSE; } return dreamcast_has_bios; } static const char fakebios[] = { 0x00, 0xd1, /* movl $+4, r1 */ 0x2b, 0x41, /* jmp @r1 */ 0xa0, 0xff, /* .long 0xffffffa0 */ 0xff, 0xff }; gboolean dreamcast_load_fakebios( ) { memset( dc_boot_rom, 0, 2 MB ); memcpy( dc_boot_rom, fakebios, sizeof(fakebios) ); syscall_add_hook( 0xA0, bios_boot ); dreamcast_has_bios = TRUE; return TRUE; } gboolean dreamcast_load_flash( const gchar *filename ) { if( filename != NULL && filename[0] != '\0' ) { return mem_load_block( filename, 0x00200000, 0x00020000 ) == 0; } return FALSE; } gboolean dreamcast_config_changed(void *data, struct lxdream_config_group *group, unsigned item, const gchar *oldval, const gchar *newval) { gchar *tmp; switch(item) { case CONFIG_BIOS_PATH: tmp = get_expanded_path(newval); dreamcast_load_bios(tmp); g_free(tmp); break; case CONFIG_FLASH_PATH: tmp = get_expanded_path(newval); dreamcast_load_flash(tmp); g_free(tmp); break; } reset_gui_paths(); return TRUE; } void dreamcast_save_flash() { if( dreamcast_has_flash ) { char *file = lxdream_get_global_config_path_value(CONFIG_FLASH_PATH); mem_save_block( file, 0x00200000, 0x00020000 ); g_free(file); } } /** * Constructs a system configuration for the AICA in standalone mode, * ie sound chip only. */ void dreamcast_configure_aica_only( ) { dreamcast_register_module( &mem_module ); mem_map_region( aica_main_ram, 0x00800000, 2 MB, MEM_REGION_AUDIO, &mem_region_audioram, MEM_FLAG_RAM, 2 MB, 0 ); mem_map_region( aica_scratch_ram, 0x00703000, 8 KB, MEM_REGION_AUDIO_SCRATCH, &mem_region_audioscratch, MEM_FLAG_RAM, 8 KB, 0 ); dreamcast_register_module( &aica_module ); aica_enable(); dreamcast_state = STATE_STOPPED; } void dreamcast_register_module( dreamcast_module_t module ) { assert( num_modules < MAX_MODULES ); modules[num_modules++] = module; if( module->init != NULL ) module->init(); } void dreamcast_set_run_time( uint32_t secs, uint32_t nanosecs ) { run_time_nanosecs = (((uint64_t)secs) * 1000000000) + nanosecs; } void dreamcast_set_exit_on_stop( gboolean flag ) { dreamcast_exit_on_stop = flag; } void dreamcast_init( gboolean use_bootrom ) { dreamcast_configure( use_bootrom ); dreamcast_state = STATE_STOPPED; } void dreamcast_reset( void ) { sh4_core_exit(CORE_EXIT_SYSRESET); int i; for( i=0; i<num_modules; i++ ) { if( modules[i]->reset != NULL ) modules[i]->reset(); } } void dreamcast_run( void ) { int i; if( !dreamcast_can_run() ) { ERROR(_("No program is loaded, and no BIOS is configured (required to boot a CD image). To continue, either load a binary program, or set the path to your BIOS file in the Path Preferences")); return; } if( dreamcast_state != STATE_RUNNING ) { for( i=0; i<num_modules; i++ ) { if( modules[i]->start != NULL ) modules[i]->start(); } } if( maple_should_grab() ) { gui_set_use_grab(TRUE); } dreamcast_state = STATE_RUNNING; if( run_time_nanosecs != 0 ) { while( dreamcast_state == STATE_RUNNING ) { uint32_t time_to_run = timeslice_length; if( run_time_nanosecs < time_to_run ) { time_to_run = (uint32_t)run_time_nanosecs; } for( i=0; i<num_modules; i++ ) { if( modules[i]->run_time_slice != NULL ) time_to_run = modules[i]->run_time_slice( time_to_run ); } if( run_time_nanosecs > time_to_run ) { run_time_nanosecs -= time_to_run; } else { run_time_nanosecs = 0; // Finished break; } } } else { while( dreamcast_state == STATE_RUNNING ) { int time_to_run = timeslice_length; for( i=0; i<num_modules; i++ ) { if( modules[i]->run_time_slice != NULL ) time_to_run = modules[i]->run_time_slice( time_to_run ); } } } gui_set_use_grab(FALSE); for( i=0; i<num_modules; i++ ) { if( modules[i]->stop != NULL ) modules[i]->stop(); } vmulist_save_all(); dreamcast_state = STATE_STOPPED; if( dreamcast_exit_on_stop ) { dreamcast_shutdown(); exit(0); } } void dreamcast_stop( void ) { sh4_core_exit(CORE_EXIT_HALT); // returns only if not inside SH4 core if( dreamcast_state == STATE_RUNNING ) dreamcast_state = STATE_STOPPING; } void dreamcast_shutdown() { // Don't do a dreamcast_stop - if we're calling this out of SH4 code, // it's a shutdown-and-quit event if( dreamcast_state == STATE_RUNNING ) dreamcast_state = STATE_STOPPING; dreamcast_save_flash(); vmulist_save_all(); #ifdef ENABLE_SH4STATS sh4_stats_print(stdout); #endif } void dreamcast_program_loaded( const gchar *name, sh4addr_t entry_point ) { if( dreamcast_program_name != NULL ) { g_free(dreamcast_program_name); } dreamcast_program_name = g_strdup(name); dreamcast_entry_point = entry_point; sh4_set_pc(entry_point); sh4_write_sr( sh4_read_sr() & (~SR_BL) ); /* Unmask interrupts */ bios_install(); dcload_install(); gui_update_state(); } gboolean dreamcast_is_running( void ) { return dreamcast_state == STATE_RUNNING; } gboolean dreamcast_can_run(void) { return dreamcast_state != STATE_UNINIT; } /********************************* Save States *****************************/ struct save_state_header { char magic[16]; uint32_t version; uint32_t module_count; }; struct chunk_header { char marker[4]; /* Always BLCK */ char name[8]; /* Block (module) name */ uint32_t block_length; }; /** * Check the save state header to ensure that it is a valid, supported * file. * @return the number of blocks following, or 0 if the file is invalid. */ int dreamcast_read_save_state_header( FILE *f, char *error, int errorlen ) { struct save_state_header header; if( fread( &header, sizeof(header), 1, f ) != 1 ) { return 0; } if( strncmp( header.magic, DREAMCAST_SAVE_MAGIC, 16 ) != 0 ) { if( error != NULL ) snprintf( error, errorlen, _("File is not a %s save state"), APP_NAME ); return 0; } if( header.version != DREAMCAST_SAVE_VERSION ) { if( error != NULL ) snprintf( error, errorlen, _("Unsupported %s save state version"), APP_NAME ); return 0; } if( header.module_count > MAX_MODULES ) { if( error != NULL ) snprintf( error, errorlen, _("%s save state is corrupted (bad module count)"), APP_NAME ); return 0; } return header.module_count; } int dreamcast_write_chunk_header( const gchar *name, uint32_t length, FILE *f ) { struct chunk_header head; memcpy( head.marker, "BLCK", 4 ); memset( head.name, 0, 8 ); memcpy( head.name, name, strlen(name) ); head.block_length = length; return fwrite( &head, sizeof(head), 1, f ); } frame_buffer_t dreamcast_load_preview( const gchar *filename ) { int i; FILE *f = fopen( filename, "r" ); if( f == NULL ) return NULL; int module_count = dreamcast_read_save_state_header(f, NULL, 0); if( module_count <= 0 ) { fclose(f); return NULL; } for( i=0; i<module_count; i++ ) { struct chunk_header head; if( fread( &head, sizeof(head), 1, f ) != 1 ) { fclose(f); return NULL; } if( memcmp("BLCK", head.marker, 4) != 0 ) { fclose(f); return NULL; } if( strcmp("PVR2", head.name) == 0 ) { uint32_t buf_count; int has_front; fread( &buf_count, sizeof(buf_count), 1, f ); fread( &has_front, sizeof(has_front), 1, f ); if( buf_count != 0 && has_front ) { frame_buffer_t result = read_png_from_stream(f); fclose(f); return result; } break; } else { fseek( f, head.block_length, SEEK_CUR ); } } return NULL; } gboolean dreamcast_load_state( const gchar *filename ) { int i,j; int module_count; char error[128]; int have_read[MAX_MODULES]; FILE *f = fopen( filename, "r" ); if( f == NULL ) return FALSE; module_count = dreamcast_read_save_state_header(f, error, sizeof(error)); if( module_count <= 0 ) { ERROR( error ); fclose(f); return FALSE; } for( i=0; i<MAX_MODULES; i++ ) { have_read[i] = 0; } for( i=0; i<module_count; i++ ) { struct chunk_header chunk; fread( &chunk, sizeof(chunk), 1, f ); if( strncmp(chunk.marker, "BLCK", 4) != 0 ) { ERROR( "%s save state is corrupted (missing block header %d)", APP_NAME, i ); fclose(f); return FALSE; } /* Find the matching module by name */ for( j=0; j<num_modules; j++ ) { if( strcmp(modules[j]->name,chunk.name) == 0 ) { have_read[j] = 1; if( modules[j]->load == NULL ) { ERROR( "%s save state is corrupted (no loader for %s)", APP_NAME, modules[j]->name ); fclose(f); return FALSE; } else if( modules[j]->load(f) != 0 ) { ERROR( "%s save state is corrupted (%s failed)", APP_NAME, modules[j]->name ); fclose(f); return FALSE; } break; } } if( j == num_modules ) { fclose(f); ERROR( "%s save state contains unrecognized section", APP_NAME ); return FALSE; } } /* Any modules that we didn't load - reset to the default state. * (ie it's not an error to skip a module if you don't actually * care about its state). */ for( j=0; j<num_modules; j++ ) { if( have_read[j] == 0 && modules[j]->reset != NULL ) { modules[j]->reset(); } } fclose(f); INFO( "Save state read from %s", filename ); return TRUE; } int dreamcast_save_state( const gchar *filename ) { int i; FILE *f; struct save_state_header header; f = fopen( filename, "w" ); if( f == NULL ) return errno; strcpy( header.magic, DREAMCAST_SAVE_MAGIC ); header.version = DREAMCAST_SAVE_VERSION; header.module_count = 0; for( i=0; i<num_modules; i++ ) { if( modules[i]->save != NULL ) header.module_count++; } fwrite( &header, sizeof(header), 1, f ); for( i=0; i<num_modules; i++ ) { if( modules[i]->save != NULL ) { uint32_t blocklen, posn1, posn2; dreamcast_write_chunk_header( modules[i]->name, 0, f ); posn1 = ftell(f); modules[i]->save(f); posn2 = ftell(f); blocklen = posn2 - posn1; fseek( f, posn1-4, SEEK_SET ); fwrite( &blocklen, sizeof(blocklen), 1, f ); fseek( f, posn2, SEEK_SET ); } } fclose( f ); INFO( "Save state written to %s", filename ); return 0; } /********************** Quick save state support ***********************/ /* This section doesn't necessarily belong here, but it probably makes the * most sense here next to the regular save/load functions */ static gchar *get_quick_state_filename( int state ) { gchar *path = lxdream_get_global_config_path_value(CONFIG_SAVE_PATH); gchar *str = g_strdup_printf( QUICK_STATE_FILENAME, path, state ); g_free( path ); return str; } static void dreamcast_quick_state_init() { const char *state = lxdream_get_global_config_value(CONFIG_QUICK_STATE); if( state != NULL ) { quick_save_state = atoi(state); if( quick_save_state > MAX_QUICK_STATE ) { quick_save_state = 0; } } else { quick_save_state = 0; } } void dreamcast_quick_save() { if( quick_save_state == -1 ) dreamcast_quick_state_init(); gchar *str = get_quick_state_filename(quick_save_state); dreamcast_save_state(str); g_free(str); } void dreamcast_quick_load() { if( quick_save_state == -1 ) dreamcast_quick_state_init(); gchar *str = get_quick_state_filename(quick_save_state); dreamcast_load_state(str); g_free(str); } unsigned int dreamcast_get_quick_state( ) { if( quick_save_state == -1 ) dreamcast_quick_state_init(); return quick_save_state; } void dreamcast_set_quick_state( unsigned int state ) { if( state <= MAX_QUICK_STATE && state != quick_save_state ) { quick_save_state = state; char buf[3]; sprintf( buf, "%d", quick_save_state ); lxdream_set_global_config_value(CONFIG_QUICK_STATE, buf); lxdream_save_config(); } } gboolean dreamcast_has_quick_state( unsigned int state ) { gchar *str = get_quick_state_filename(state); int result = access(str, R_OK); g_free(str); return result == 0 ? TRUE : FALSE; } /********************* The Boot ROM address space **********************/ static int32_t FASTCALL ext_bootrom_read_long( sh4addr_t addr ) { return *((int32_t *)(dc_boot_rom + (addr&0x001FFFFF))); } static int32_t FASTCALL ext_bootrom_read_word( sh4addr_t addr ) { return SIGNEXT16(*((int16_t *)(dc_boot_rom + (addr&0x001FFFFF)))); } static int32_t FASTCALL ext_bootrom_read_byte( sh4addr_t addr ) { return SIGNEXT8(*((int16_t *)(dc_boot_rom + (addr&0x001FFFFF)))); } static void FASTCALL ext_bootrom_read_burst( unsigned char *dest, sh4addr_t addr ) { memcpy( dest, dc_boot_rom +(addr&0x001FFFFF), 32 ); } struct mem_region_fn mem_region_bootrom = { ext_bootrom_read_long, unmapped_write_long, ext_bootrom_read_word, unmapped_write_long, ext_bootrom_read_byte, unmapped_write_long, ext_bootrom_read_burst, unmapped_write_burst }; /********************* The Flash RAM address space **********************/ static int32_t FASTCALL ext_flashram_read_long( sh4addr_t addr ) { return *((int32_t *)(dc_flash_ram + (addr&0x0001FFFF))); } static int32_t FASTCALL ext_flashram_read_word( sh4addr_t addr ) { return SIGNEXT16(*((int16_t *)(dc_flash_ram + (addr&0x0001FFFF)))); } static int32_t FASTCALL ext_flashram_read_byte( sh4addr_t addr ) { return SIGNEXT8(*((int16_t *)(dc_flash_ram + (addr&0x0001FFFF)))); } static void FASTCALL ext_flashram_write_long( sh4addr_t addr, uint32_t val ) { *(uint32_t *)(dc_flash_ram + (addr&0x0001FFFF)) = val; asic_g2_write_word(); } static void FASTCALL ext_flashram_write_word( sh4addr_t addr, uint32_t val ) { *(uint16_t *)(dc_flash_ram + (addr&0x0001FFFF)) = (uint16_t)val; asic_g2_write_word(); } static void FASTCALL ext_flashram_write_byte( sh4addr_t addr, uint32_t val ) { *(uint8_t *)(dc_flash_ram + (addr&0x0001FFFF)) = (uint8_t)val; asic_g2_write_word(); } static void FASTCALL ext_flashram_read_burst( unsigned char *dest, sh4addr_t addr ) { memcpy( dest, dc_flash_ram+(addr&0x0001FFFF), 32 ); } static void FASTCALL ext_flashram_write_burst( sh4addr_t addr, unsigned char *src ) { memcpy( dc_flash_ram+(addr&0x0001FFFF), src, 32 ); } struct mem_region_fn mem_region_flashram = { ext_flashram_read_long, ext_flashram_write_long, ext_flashram_read_word, ext_flashram_write_word, ext_flashram_read_byte, ext_flashram_write_byte, ext_flashram_read_burst, ext_flashram_write_burst };
lutris/lxdream
src/dreamcast.c
C
gpl-2.0
21,776
/* ** License Applicability. Except to the extent portions of this file are ** made subject to an alternative license as permitted in the SGI Free ** Software License B, Version 1.1 (the "License"), the contents of this ** file are subject only to the provisions of the License. You may not use ** this file except in compliance with the License. You may obtain a copy ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: ** ** http://oss.sgi.com/projects/FreeB ** ** Note that, as provided in the License, the Software is distributed on an ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. ** ** Original Code. The Original Code is: OpenGL Sample Implementation, ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, ** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. ** Copyright in any portions created by third parties is as indicated ** elsewhere herein. All Rights Reserved. ** ** Additional Notice Provisions: The application programming interfaces ** established by SGI in conjunction with the Original Code are The ** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released ** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version ** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X ** Window System(R) (Version 1.3), released October 19, 1998. This software ** was created using the OpenGL(R) version 1.2.1 Sample Implementation ** published by SGI, but has not been independently verified as being ** compliant with the OpenGL(R) version 1.2.1 Specification. */ /* * gridline.h * * $Date: 2001/03/17 00:25:41 $ $Revision: 1.1 $ * $Header: /home/krh/git/sync/mesa-cvs-repo/Mesa/src/glu/sgi/libnurbs/internals/gridline.h,v 1.1 2001/03/17 00:25:41 brianp Exp $ */ #ifndef __glugridline_h_ #define __glugridline_h_ struct Gridline { long v; REAL vval; long vindex; long ustart; long uend; }; #endif /* __glugridline_h_ */
ZHAW-INES/rioxo-uClinux-dist
lib/mesa/src/glu/sgi/libnurbs/internals/gridline.h
C
gpl-2.0
2,252
/* Socket union related function. * Copyright (c) 1997, 98 Kunihiro Ishiguro * * This file is part of GNU Zebra. * * GNU Zebra 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. * * GNU Zebra 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 GNU Zebra; see the file COPYING. If not, write to the Free * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include <zebra.h> #include "prefix.h" #include "vty.h" #include "sockunion.h" #include "memory.h" #include "str.h" #include "log.h" #ifndef HAVE_INET_ATON int inet_aton (const char *cp, struct in_addr *inaddr) { int dots = 0; register u_long addr = 0; register u_long val = 0, base = 10; do { register char c = *cp; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': val = (val * base) + (c - '0'); break; case '.': if (++dots > 3) return 0; case '\0': if (val > 255) return 0; addr = addr << 8 | val; val = 0; break; default: return 0; } } while (*cp++) ; if (dots < 3) addr <<= 8 * (3 - dots); if (inaddr) inaddr->s_addr = htonl (addr); return 1; } #endif /* ! HAVE_INET_ATON */ #ifndef HAVE_INET_PTON int inet_pton (int family, const char *strptr, void *addrptr) { if (family == AF_INET) { struct in_addr in_val; if (inet_aton (strptr, &in_val)) { memcpy (addrptr, &in_val, sizeof (struct in_addr)); return 1; } return 0; } errno = EAFNOSUPPORT; return -1; } #endif /* ! HAVE_INET_PTON */ #ifndef HAVE_INET_NTOP const char * inet_ntop (int family, const void *addrptr, char *strptr, size_t len) { unsigned char *p = (unsigned char *) addrptr; if (family == AF_INET) { char temp[INET_ADDRSTRLEN]; snprintf(temp, sizeof(temp), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]); if (strlen(temp) >= len) { errno = ENOSPC; return NULL; } strcpy(strptr, temp); return strptr; } errno = EAFNOSUPPORT; return NULL; } #endif /* ! HAVE_INET_NTOP */ const char * inet_sutop (union sockunion *su, char *str) { switch (su->sa.sa_family) { case AF_INET: inet_ntop (AF_INET, &su->sin.sin_addr, str, INET_ADDRSTRLEN); break; #ifdef HAVE_IPV6 case AF_INET6: inet_ntop (AF_INET6, &su->sin6.sin6_addr, str, INET6_ADDRSTRLEN); break; #endif /* HAVE_IPV6 */ } return str; } int str2sockunion (const char *str, union sockunion *su) { int ret; memset (su, 0, sizeof (union sockunion)); ret = inet_pton (AF_INET, str, &su->sin.sin_addr); if (ret > 0) /* Valid IPv4 address format. */ { su->sin.sin_family = AF_INET; #ifdef HAVE_SIN_LEN su->sin.sin_len = sizeof(struct sockaddr_in); #endif /* HAVE_SIN_LEN */ return 0; } #ifdef HAVE_IPV6 ret = inet_pton (AF_INET6, str, &su->sin6.sin6_addr); if (ret > 0) /* Valid IPv6 address format. */ { su->sin6.sin6_family = AF_INET6; #ifdef SIN6_LEN su->sin6.sin6_len = sizeof(struct sockaddr_in6); #endif /* SIN6_LEN */ return 0; } #endif /* HAVE_IPV6 */ return -1; } const char * sockunion2str (union sockunion *su, char *buf, size_t len) { if (su->sa.sa_family == AF_INET) return inet_ntop (AF_INET, &su->sin.sin_addr, buf, len); #ifdef HAVE_IPV6 else if (su->sa.sa_family == AF_INET6) return inet_ntop (AF_INET6, &su->sin6.sin6_addr, buf, len); #endif /* HAVE_IPV6 */ return NULL; } union sockunion * sockunion_str2su (const char *str) { int ret; union sockunion *su; su = XMALLOC (MTYPE_SOCKUNION, sizeof (union sockunion)); memset (su, 0, sizeof (union sockunion)); ret = inet_pton (AF_INET, str, &su->sin.sin_addr); if (ret > 0) /* Valid IPv4 address format. */ { su->sin.sin_family = AF_INET; #ifdef HAVE_SIN_LEN su->sin.sin_len = sizeof(struct sockaddr_in); #endif /* HAVE_SIN_LEN */ return su; } #ifdef HAVE_IPV6 ret = inet_pton (AF_INET6, str, &su->sin6.sin6_addr); if (ret > 0) /* Valid IPv6 address format. */ { su->sin6.sin6_family = AF_INET6; #ifdef SIN6_LEN su->sin6.sin6_len = sizeof(struct sockaddr_in6); #endif /* SIN6_LEN */ return su; } #endif /* HAVE_IPV6 */ XFREE (MTYPE_SOCKUNION, su); return NULL; } char * sockunion_su2str (union sockunion *su) { char str[SU_ADDRSTRLEN]; switch (su->sa.sa_family) { case AF_INET: inet_ntop (AF_INET, &su->sin.sin_addr, str, sizeof (str)); break; #ifdef HAVE_IPV6 case AF_INET6: inet_ntop (AF_INET6, &su->sin6.sin6_addr, str, sizeof (str)); break; #endif /* HAVE_IPV6 */ } return strdup (str); } /* Return socket of sockunion. */ int sockunion_socket (union sockunion *su) { int sock; sock = socket (su->sa.sa_family, SOCK_STREAM, 0); if (sock < 0) { zlog (NULL, LOG_WARNING, "Can't make socket : %s", safe_strerror (errno)); return -1; } return sock; } /* Return accepted new socket file descriptor. */ int sockunion_accept (int sock, union sockunion *su) { socklen_t len; int client_sock; len = sizeof (union sockunion); client_sock = accept (sock, (struct sockaddr *) su, &len); /* Convert IPv4 compatible IPv6 address to IPv4 address. */ #ifdef HAVE_IPV6 if (su->sa.sa_family == AF_INET6) { if (IN6_IS_ADDR_V4MAPPED (&su->sin6.sin6_addr)) { struct sockaddr_in sin; memset (&sin, 0, sizeof (struct sockaddr_in)); sin.sin_family = AF_INET; memcpy (&sin.sin_addr, ((char *)&su->sin6.sin6_addr) + 12, 4); memcpy (su, &sin, sizeof (struct sockaddr_in)); } } #endif /* HAVE_IPV6 */ return client_sock; } /* Return sizeof union sockunion. */ int sockunion_sizeof (union sockunion *su) { int ret; ret = 0; switch (su->sa.sa_family) { case AF_INET: ret = sizeof (struct sockaddr_in); break; #ifdef HAVE_IPV6 case AF_INET6: ret = sizeof (struct sockaddr_in6); break; #endif /* AF_INET6 */ } return ret; } /* return sockunion structure : this function should be revised. */ char * sockunion_log (union sockunion *su) { static char buf[SU_ADDRSTRLEN]; switch (su->sa.sa_family) { case AF_INET: snprintf (buf, SU_ADDRSTRLEN, "%s", inet_ntoa (su->sin.sin_addr)); break; #ifdef HAVE_IPV6 case AF_INET6: snprintf (buf, SU_ADDRSTRLEN, "%s", inet_ntop (AF_INET6, &(su->sin6.sin6_addr), buf, SU_ADDRSTRLEN)); break; #endif /* HAVE_IPV6 */ default: snprintf (buf, SU_ADDRSTRLEN, "af_unknown %d ", su->sa.sa_family); break; } return (strdup (buf)); } /* sockunion_connect returns -1 : error occured 0 : connect success 1 : connect is in progress */ enum connect_result sockunion_connect (int fd, union sockunion *peersu, unsigned short port, unsigned int ifindex) { int ret; int val; union sockunion su; memcpy (&su, peersu, sizeof (union sockunion)); switch (su.sa.sa_family) { case AF_INET: su.sin.sin_port = port; break; #ifdef HAVE_IPV6 case AF_INET6: su.sin6.sin6_port = port; #ifdef KAME if (IN6_IS_ADDR_LINKLOCAL(&su.sin6.sin6_addr) && ifindex) { #ifdef HAVE_SIN6_SCOPE_ID /* su.sin6.sin6_scope_id = ifindex; */ #ifdef MUSICA su.sin6.sin6_scope_id = ifindex; #endif #endif /* HAVE_SIN6_SCOPE_ID */ #ifndef MUSICA SET_IN6_LINKLOCAL_IFINDEX (su.sin6.sin6_addr, ifindex); #endif } #endif /* KAME */ break; #endif /* HAVE_IPV6 */ } /* Make socket non-block. */ val = fcntl (fd, F_GETFL, 0); fcntl (fd, F_SETFL, val|O_NONBLOCK); /* Call connect function. */ ret = connect (fd, (struct sockaddr *) &su, sockunion_sizeof (&su)); /* Immediate success */ if (ret == 0) { fcntl (fd, F_SETFL, val); return connect_success; } /* If connect is in progress then return 1 else it's real error. */ if (ret < 0) { if (errno != EINPROGRESS) { zlog_info ("can't connect to %s fd %d : %s", sockunion_log (&su), fd, safe_strerror (errno)); return connect_error; } } fcntl (fd, F_SETFL, val); return connect_in_progress; } /* Make socket from sockunion union. */ int sockunion_stream_socket (union sockunion *su) { int sock; if (su->sa.sa_family == 0) su->sa.sa_family = AF_INET_UNION; sock = socket (su->sa.sa_family, SOCK_STREAM, 0); if (sock < 0) zlog (NULL, LOG_WARNING, "can't make socket sockunion_stream_socket"); return sock; } /* Bind socket to specified address. */ int sockunion_bind (int sock, union sockunion *su, unsigned short port, union sockunion *su_addr) { int size = 0; int ret; if (su->sa.sa_family == AF_INET) { size = sizeof (struct sockaddr_in); su->sin.sin_port = htons (port); #ifdef HAVE_SIN_LEN su->sin.sin_len = size; #endif /* HAVE_SIN_LEN */ if (su_addr == NULL) su->sin.sin_addr.s_addr = htonl (INADDR_ANY); } #ifdef HAVE_IPV6 else if (su->sa.sa_family == AF_INET6) { size = sizeof (struct sockaddr_in6); su->sin6.sin6_port = htons (port); #ifdef SIN6_LEN su->sin6.sin6_len = size; #endif /* SIN6_LEN */ if (su_addr == NULL) { #if defined(LINUX_IPV6) || defined(NRL) memset (&su->sin6.sin6_addr, 0, sizeof (struct in6_addr)); #else su->sin6.sin6_addr = in6addr_any; #endif /* LINUX_IPV6 */ } } #endif /* HAVE_IPV6 */ ret = bind (sock, (struct sockaddr *)su, size); if (ret < 0) zlog (NULL, LOG_WARNING, "can't bind socket : %s", safe_strerror (errno)); return ret; } int sockopt_reuseaddr (int sock) { int ret; int on = 1; ret = setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof (on)); if (ret < 0) { zlog (NULL, LOG_WARNING, "can't set sockopt SO_REUSEADDR to socket %d", sock); return -1; } return 0; } #ifdef SO_REUSEPORT int sockopt_reuseport (int sock) { int ret; int on = 1; ret = setsockopt (sock, SOL_SOCKET, SO_REUSEPORT, (void *) &on, sizeof (on)); if (ret < 0) { zlog (NULL, LOG_WARNING, "can't set sockopt SO_REUSEADDR to socket %d", sock); return -1; } return 0; } #else int sockopt_reuseport (int sock) { return 0; } #endif /* 0 */ int sockopt_ttl (int family, int sock, int ttl) { int ret; #ifdef IP_TTL if (family == AF_INET) { ret = setsockopt (sock, IPPROTO_IP, IP_TTL, (void *) &ttl, sizeof (int)); if (ret < 0) { zlog (NULL, LOG_WARNING, "can't set sockopt IP_TTL %d to socket %d", ttl, sock); return -1; } return 0; } #endif /* IP_TTL */ #ifdef HAVE_IPV6 if (family == AF_INET6) { ret = setsockopt (sock, IPPROTO_IPV6, IPV6_UNICAST_HOPS, (void *) &ttl, sizeof (int)); if (ret < 0) { zlog (NULL, LOG_WARNING, "can't set sockopt IPV6_UNICAST_HOPS %d to socket %d", ttl, sock); return -1; } return 0; } #endif /* HAVE_IPV6 */ return 0; } /* If same family and same prefix return 1. */ int sockunion_same (union sockunion *su1, union sockunion *su2) { int ret = 0; if (su1->sa.sa_family != su2->sa.sa_family) return 0; switch (su1->sa.sa_family) { case AF_INET: ret = memcmp (&su1->sin.sin_addr, &su2->sin.sin_addr, sizeof (struct in_addr)); break; #ifdef HAVE_IPV6 case AF_INET6: ret = memcmp (&su1->sin6.sin6_addr, &su2->sin6.sin6_addr, sizeof (struct in6_addr)); break; #endif /* HAVE_IPV6 */ } if (ret == 0) return 1; else return 0; } /* After TCP connection is established. Get local address and port. */ union sockunion * sockunion_getsockname (int fd) { int ret; socklen_t len; union { struct sockaddr sa; struct sockaddr_in sin; #ifdef HAVE_IPV6 struct sockaddr_in6 sin6; #endif /* HAVE_IPV6 */ char tmp_buffer[128]; } name; union sockunion *su; memset (&name, 0, sizeof name); len = sizeof name; ret = getsockname (fd, (struct sockaddr *)&name, &len); if (ret < 0) { zlog_warn ("Can't get local address and port by getsockname: %s", safe_strerror (errno)); return NULL; } if (name.sa.sa_family == AF_INET) { su = XCALLOC (MTYPE_TMP, sizeof (union sockunion)); memcpy (su, &name, sizeof (struct sockaddr_in)); return su; } #ifdef HAVE_IPV6 if (name.sa.sa_family == AF_INET6) { su = XCALLOC (MTYPE_TMP, sizeof (union sockunion)); memcpy (su, &name, sizeof (struct sockaddr_in6)); if (IN6_IS_ADDR_V4MAPPED (&su->sin6.sin6_addr)) { struct sockaddr_in sin; sin.sin_family = AF_INET; memcpy (&sin.sin_addr, ((char *)&su->sin6.sin6_addr) + 12, 4); sin.sin_port = su->sin6.sin6_port; memcpy (su, &sin, sizeof (struct sockaddr_in)); } return su; } #endif /* HAVE_IPV6 */ return NULL; } /* After TCP connection is established. Get remote address and port. */ union sockunion * sockunion_getpeername (int fd) { int ret; socklen_t len; union { struct sockaddr sa; struct sockaddr_in sin; #ifdef HAVE_IPV6 struct sockaddr_in6 sin6; #endif /* HAVE_IPV6 */ char tmp_buffer[128]; } name; union sockunion *su; memset (&name, 0, sizeof name); len = sizeof name; ret = getpeername (fd, (struct sockaddr *)&name, &len); if (ret < 0) { zlog (NULL, LOG_WARNING, "Can't get remote address and port: %s", safe_strerror (errno)); return NULL; } if (name.sa.sa_family == AF_INET) { su = XCALLOC (MTYPE_TMP, sizeof (union sockunion)); memcpy (su, &name, sizeof (struct sockaddr_in)); return su; } #ifdef HAVE_IPV6 if (name.sa.sa_family == AF_INET6) { su = XCALLOC (MTYPE_TMP, sizeof (union sockunion)); memcpy (su, &name, sizeof (struct sockaddr_in6)); if (IN6_IS_ADDR_V4MAPPED (&su->sin6.sin6_addr)) { struct sockaddr_in sin; sin.sin_family = AF_INET; memcpy (&sin.sin_addr, ((char *)&su->sin6.sin6_addr) + 12, 4); sin.sin_port = su->sin6.sin6_port; memcpy (su, &sin, sizeof (struct sockaddr_in)); } return su; } #endif /* HAVE_IPV6 */ return NULL; } /* Print sockunion structure */ void sockunion_print (union sockunion *su) { if (su == NULL) return; switch (su->sa.sa_family) { case AF_INET: printf ("%s\n", inet_ntoa (su->sin.sin_addr)); break; #ifdef HAVE_IPV6 case AF_INET6: { char buf [SU_ADDRSTRLEN]; printf ("%s\n", inet_ntop (AF_INET6, &(su->sin6.sin6_addr), buf, sizeof (buf))); } break; #endif /* HAVE_IPV6 */ #ifdef AF_LINK case AF_LINK: { struct sockaddr_dl *sdl; sdl = (struct sockaddr_dl *)&(su->sa); printf ("link#%d\n", sdl->sdl_index); } break; #endif /* AF_LINK */ default: printf ("af_unknown %d\n", su->sa.sa_family); break; } } #ifdef HAVE_IPV6 int in6addr_cmp (struct in6_addr *addr1, struct in6_addr *addr2) { unsigned int i; u_char *p1, *p2; p1 = (u_char *)addr1; p2 = (u_char *)addr2; for (i = 0; i < sizeof (struct in6_addr); i++) { if (p1[i] > p2[i]) return 1; else if (p1[i] < p2[i]) return -1; } return 0; } #endif /* HAVE_IPV6 */ int sockunion_cmp (union sockunion *su1, union sockunion *su2) { if (su1->sa.sa_family > su2->sa.sa_family) return 1; if (su1->sa.sa_family < su2->sa.sa_family) return -1; if (su1->sa.sa_family == AF_INET) { if (ntohl (su1->sin.sin_addr.s_addr) == ntohl (su2->sin.sin_addr.s_addr)) return 0; if (ntohl (su1->sin.sin_addr.s_addr) > ntohl (su2->sin.sin_addr.s_addr)) return 1; else return -1; } #ifdef HAVE_IPV6 if (su1->sa.sa_family == AF_INET6) return in6addr_cmp (&su1->sin6.sin6_addr, &su2->sin6.sin6_addr); #endif /* HAVE_IPV6 */ return 0; } /* Duplicate sockunion. */ union sockunion * sockunion_dup (union sockunion *su) { union sockunion *dup = XCALLOC (MTYPE_SOCKUNION, sizeof (union sockunion)); memcpy (dup, su, sizeof (union sockunion)); return dup; } void sockunion_free (union sockunion *su) { XFREE (MTYPE_SOCKUNION, su); }
kidmaple/CoolWall
user/quagga/lib/sockunion.c
C
gpl-2.0
16,484
/** * collectd - src/configfile.c * Copyright (C) 2005-2011 Florian octo Forster * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Authors: * Florian octo Forster <octo at collectd.org> * Sebastian tokkee Harl <sh at tokkee.org> **/ #include "collectd.h" #include "liboconfig/oconfig.h" #include "common.h" #include "plugin.h" #include "configfile.h" #include "types_list.h" #include "filter_chain.h" #if HAVE_WORDEXP_H # include <wordexp.h> #endif /* HAVE_WORDEXP_H */ #if HAVE_FNMATCH_H # include <fnmatch.h> #endif /* HAVE_FNMATCH_H */ #if HAVE_LIBGEN_H # include <libgen.h> #endif /* HAVE_LIBGEN_H */ #define ESCAPE_NULL(str) ((str) == NULL ? "(null)" : (str)) /* * Private types */ typedef struct cf_callback { const char *type; int (*callback) (const char *, const char *); const char **keys; int keys_num; plugin_ctx_t ctx; struct cf_callback *next; } cf_callback_t; typedef struct cf_complex_callback_s { char *type; int (*callback) (oconfig_item_t *); plugin_ctx_t ctx; struct cf_complex_callback_s *next; } cf_complex_callback_t; typedef struct cf_value_map_s { char *key; int (*func) (const oconfig_item_t *); } cf_value_map_t; typedef struct cf_global_option_s { char *key; char *value; char *def; } cf_global_option_t; /* * Prototypes of callback functions */ static int dispatch_value_typesdb (const oconfig_item_t *ci); static int dispatch_value_plugindir (const oconfig_item_t *ci); static int dispatch_loadplugin (const oconfig_item_t *ci); /* * Private variables */ static cf_callback_t *first_callback = NULL; static cf_complex_callback_t *complex_callback_head = NULL; static cf_value_map_t cf_value_map[] = { {"TypesDB", dispatch_value_typesdb}, {"PluginDir", dispatch_value_plugindir}, {"LoadPlugin", dispatch_loadplugin} }; static int cf_value_map_num = STATIC_ARRAY_SIZE (cf_value_map); static cf_global_option_t cf_global_options[] = { {"BaseDir", NULL, PKGLOCALSTATEDIR}, {"PIDFile", NULL, PIDFILE}, {"Hostname", NULL, NULL}, {"FQDNLookup", NULL, "true"}, {"Interval", NULL, NULL}, {"ReadThreads", NULL, "5"}, {"WriteThreads", NULL, "5"}, {"WriteQueueLimitHigh", NULL, NULL}, {"WriteQueueLimitLow", NULL, NULL}, {"Timeout", NULL, "2"}, {"AutoLoadPlugin", NULL, "false"}, {"PreCacheChain", NULL, "PreCache"}, {"PostCacheChain", NULL, "PostCache"} }; static int cf_global_options_num = STATIC_ARRAY_SIZE (cf_global_options); static int cf_default_typesdb = 1; /* * Functions to handle register/unregister, search, and other plugin related * stuff */ static cf_callback_t *cf_search (const char *type) { cf_callback_t *cf_cb; if (type == NULL) return (NULL); for (cf_cb = first_callback; cf_cb != NULL; cf_cb = cf_cb->next) if (strcasecmp (cf_cb->type, type) == 0) break; return (cf_cb); } static int cf_dispatch (const char *type, const char *orig_key, const char *orig_value) { cf_callback_t *cf_cb; plugin_ctx_t old_ctx; char *key; char *value; int ret; int i; DEBUG ("type = %s, key = %s, value = %s", ESCAPE_NULL(type), ESCAPE_NULL(orig_key), ESCAPE_NULL(orig_value)); if ((cf_cb = cf_search (type)) == NULL) { WARNING ("Found a configuration for the `%s' plugin, but " "the plugin isn't loaded or didn't register " "a configuration callback.", type); return (-1); } if ((key = strdup (orig_key)) == NULL) return (1); if ((value = strdup (orig_value)) == NULL) { free (key); return (2); } ret = -1; old_ctx = plugin_set_ctx (cf_cb->ctx); for (i = 0; i < cf_cb->keys_num; i++) { if ((cf_cb->keys[i] != NULL) && (strcasecmp (cf_cb->keys[i], key) == 0)) { ret = (*cf_cb->callback) (key, value); break; } } plugin_set_ctx (old_ctx); if (i >= cf_cb->keys_num) WARNING ("Plugin `%s' did not register for value `%s'.", type, key); free (key); free (value); DEBUG ("cf_dispatch: return (%i)", ret); return (ret); } /* int cf_dispatch */ static int dispatch_global_option (const oconfig_item_t *ci) { if (ci->values_num != 1) return (-1); if (ci->values[0].type == OCONFIG_TYPE_STRING) return (global_option_set (ci->key, ci->values[0].value.string)); else if (ci->values[0].type == OCONFIG_TYPE_NUMBER) { char tmp[128]; ssnprintf (tmp, sizeof (tmp), "%lf", ci->values[0].value.number); return (global_option_set (ci->key, tmp)); } else if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN) { if (ci->values[0].value.boolean) return (global_option_set (ci->key, "true")); else return (global_option_set (ci->key, "false")); } return (-1); } /* int dispatch_global_option */ static int dispatch_value_typesdb (const oconfig_item_t *ci) { int i = 0; assert (strcasecmp (ci->key, "TypesDB") == 0); cf_default_typesdb = 0; if (ci->values_num < 1) { ERROR ("configfile: `TypesDB' needs at least one argument."); return (-1); } for (i = 0; i < ci->values_num; ++i) { if (OCONFIG_TYPE_STRING != ci->values[i].type) { WARNING ("configfile: TypesDB: Skipping %i. argument which " "is not a string.", i + 1); continue; } read_types_list (ci->values[i].value.string); } return (0); } /* int dispatch_value_typesdb */ static int dispatch_value_plugindir (const oconfig_item_t *ci) { assert (strcasecmp (ci->key, "PluginDir") == 0); if (ci->values_num != 1) return (-1); if (ci->values[0].type != OCONFIG_TYPE_STRING) return (-1); plugin_set_dir (ci->values[0].value.string); return (0); } static int dispatch_loadplugin (const oconfig_item_t *ci) { int i; const char *name; unsigned int flags = 0; plugin_ctx_t ctx; plugin_ctx_t old_ctx; int ret_val; assert (strcasecmp (ci->key, "LoadPlugin") == 0); if (ci->values_num != 1) return (-1); if (ci->values[0].type != OCONFIG_TYPE_STRING) return (-1); name = ci->values[0].value.string; /* default to the global interval set before loading this plugin */ memset (&ctx, 0, sizeof (ctx)); ctx.interval = cf_get_default_interval (); for (i = 0; i < ci->children_num; ++i) { if (strcasecmp("Globals", ci->children[i].key) == 0) cf_util_get_flag (ci->children + i, &flags, PLUGIN_FLAGS_GLOBAL); else if (strcasecmp ("Interval", ci->children[i].key) == 0) { double interval = 0.0; if (cf_util_get_double (ci->children + i, &interval) != 0) { /* cf_util_get_double will log an error */ continue; } ctx.interval = DOUBLE_TO_CDTIME_T (interval); } else { WARNING("Ignoring unknown LoadPlugin option \"%s\" " "for plugin \"%s\"", ci->children[i].key, ci->values[0].value.string); } } old_ctx = plugin_set_ctx (ctx); ret_val = plugin_load (name, (uint32_t) flags); /* reset to the "global" context */ plugin_set_ctx (old_ctx); return (ret_val); } /* int dispatch_value_loadplugin */ static int dispatch_value_plugin (const char *plugin, oconfig_item_t *ci) { char buffer[4096]; char *buffer_ptr; int buffer_free; int i; buffer_ptr = buffer; buffer_free = sizeof (buffer); for (i = 0; i < ci->values_num; i++) { int status = -1; if (ci->values[i].type == OCONFIG_TYPE_STRING) status = ssnprintf (buffer_ptr, buffer_free, " %s", ci->values[i].value.string); else if (ci->values[i].type == OCONFIG_TYPE_NUMBER) status = ssnprintf (buffer_ptr, buffer_free, " %lf", ci->values[i].value.number); else if (ci->values[i].type == OCONFIG_TYPE_BOOLEAN) status = ssnprintf (buffer_ptr, buffer_free, " %s", ci->values[i].value.boolean ? "true" : "false"); if ((status < 0) || (status >= buffer_free)) return (-1); buffer_free -= status; buffer_ptr += status; } /* skip the initial space */ buffer_ptr = buffer + 1; return (cf_dispatch (plugin, ci->key, buffer_ptr)); } /* int dispatch_value_plugin */ static int dispatch_value (const oconfig_item_t *ci) { int ret = -2; int i; for (i = 0; i < cf_value_map_num; i++) if (strcasecmp (cf_value_map[i].key, ci->key) == 0) { ret = cf_value_map[i].func (ci); break; } for (i = 0; i < cf_global_options_num; i++) if (strcasecmp (cf_global_options[i].key, ci->key) == 0) { ret = dispatch_global_option (ci); break; } return (ret); } /* int dispatch_value */ static int dispatch_block_plugin (oconfig_item_t *ci) { int i; char *name; cf_complex_callback_t *cb; if (strcasecmp (ci->key, "Plugin") != 0) return (-1); if (ci->values_num < 1) return (-1); if (ci->values[0].type != OCONFIG_TYPE_STRING) return (-1); name = ci->values[0].value.string; if (IS_TRUE (global_option_get ("AutoLoadPlugin"))) { int status; status = plugin_load (name, /* flags = */ 0); if (status != 0) { ERROR ("Automatically loading plugin \"%s\" failed " "with status %i.", name, status); return (status); } } /* Check for a complex callback first */ for (cb = complex_callback_head; cb != NULL; cb = cb->next) { if (strcasecmp (name, cb->type) == 0) { plugin_ctx_t old_ctx; int ret_val; old_ctx = plugin_set_ctx (cb->ctx); ret_val = (cb->callback (ci)); plugin_set_ctx (old_ctx); return (ret_val); } } /* Hm, no complex plugin found. Dispatch the values one by one */ for (i = 0; i < ci->children_num; i++) { if (ci->children[i].children == NULL) dispatch_value_plugin (name, ci->children + i); else { WARNING ("There is a `%s' block within the " "configuration for the %s plugin. " "The plugin either only expects " "\"simple\" configuration statements " "or wasn't loaded using `LoadPlugin'." " Please check your configuration.", ci->children[i].key, name); } } return (0); } static int dispatch_block (oconfig_item_t *ci) { if (strcasecmp (ci->key, "LoadPlugin") == 0) return (dispatch_loadplugin (ci)); else if (strcasecmp (ci->key, "Plugin") == 0) return (dispatch_block_plugin (ci)); else if (strcasecmp (ci->key, "Chain") == 0) return (fc_configure (ci)); return (0); } static int cf_ci_replace_child (oconfig_item_t *dst, oconfig_item_t *src, int offset) { oconfig_item_t *temp; int i; assert (offset >= 0); assert (dst->children_num > offset); /* Free the memory used by the replaced child. Usually that's the * `Include "blah"' statement. */ temp = dst->children + offset; for (i = 0; i < temp->values_num; i++) { if (temp->values[i].type == OCONFIG_TYPE_STRING) { sfree (temp->values[i].value.string); } } sfree (temp->values); temp = NULL; /* If (src->children_num == 0) the array size is decreased. If offset * is _not_ the last element, (offset < (dst->children_num - 1)), then * we need to move the trailing elements before resizing the array. */ if ((src->children_num == 0) && (offset < (dst->children_num - 1))) { int nmemb = dst->children_num - (offset + 1); memmove (dst->children + offset, dst->children + offset + 1, sizeof (oconfig_item_t) * nmemb); } /* Resize the memory containing the children to be big enough to hold * all children. */ temp = (oconfig_item_t *) realloc (dst->children, sizeof (oconfig_item_t) * (dst->children_num + src->children_num - 1)); if (temp == NULL) { ERROR ("configfile: realloc failed."); return (-1); } dst->children = temp; /* If there are children behind the include statement, and they have * not yet been moved because (src->children_num == 0), then move them * to the end of the list, so that the new children have room before * them. */ if ((src->children_num > 0) && ((dst->children_num - (offset + 1)) > 0)) { int nmemb = dst->children_num - (offset + 1); int old_offset = offset + 1; int new_offset = offset + src->children_num; memmove (dst->children + new_offset, dst->children + old_offset, sizeof (oconfig_item_t) * nmemb); } /* Last but not least: If there are new children, copy them to the * memory reserved for them. */ if (src->children_num > 0) { memcpy (dst->children + offset, src->children, sizeof (oconfig_item_t) * src->children_num); } /* Update the number of children. */ dst->children_num += (src->children_num - 1); return (0); } /* int cf_ci_replace_child */ static int cf_ci_append_children (oconfig_item_t *dst, oconfig_item_t *src) { oconfig_item_t *temp; if ((src == NULL) || (src->children_num == 0)) return (0); temp = (oconfig_item_t *) realloc (dst->children, sizeof (oconfig_item_t) * (dst->children_num + src->children_num)); if (temp == NULL) { ERROR ("configfile: realloc failed."); return (-1); } dst->children = temp; memcpy (dst->children + dst->children_num, src->children, sizeof (oconfig_item_t) * src->children_num); dst->children_num += src->children_num; return (0); } /* int cf_ci_append_children */ #define CF_MAX_DEPTH 8 static oconfig_item_t *cf_read_generic (const char *path, const char *pattern, int depth); static int cf_include_all (oconfig_item_t *root, int depth) { int i; for (i = 0; i < root->children_num; i++) { oconfig_item_t *new; oconfig_item_t *old; char *pattern = NULL; int j; if (strcasecmp (root->children[i].key, "Include") != 0) continue; old = root->children + i; if ((old->values_num != 1) || (old->values[0].type != OCONFIG_TYPE_STRING)) { ERROR ("configfile: `Include' needs exactly one string argument."); continue; } for (j = 0; j < old->children_num; ++j) { oconfig_item_t *child = old->children + j; if (strcasecmp (child->key, "Filter") == 0) cf_util_get_string (child, &pattern); else ERROR ("configfile: Option `%s' not allowed in <Include> block.", child->key); } new = cf_read_generic (old->values[0].value.string, pattern, depth + 1); sfree (pattern); if (new == NULL) return (-1); /* Now replace the i'th child in `root' with `new'. */ cf_ci_replace_child (root, new, i); /* ... and go back to the new i'th child. */ --i; sfree (new->values); sfree (new); } /* for (i = 0; i < root->children_num; i++) */ return (0); } /* int cf_include_all */ static oconfig_item_t *cf_read_file (const char *file, const char *pattern, int depth) { oconfig_item_t *root; int status; assert (depth < CF_MAX_DEPTH); if (pattern != NULL) { #if HAVE_FNMATCH_H && HAVE_LIBGEN_H char *tmp = sstrdup (file); char *filename = basename (tmp); if ((filename != NULL) && (fnmatch (pattern, filename, 0) != 0)) { DEBUG ("configfile: Not including `%s' because it " "does not match pattern `%s'.", filename, pattern); free (tmp); return (NULL); } free (tmp); #else ERROR ("configfile: Cannot apply pattern filter '%s' " "to file '%s': functions basename() and / or " "fnmatch() not available.", pattern, file); #endif /* HAVE_FNMATCH_H && HAVE_LIBGEN_H */ } root = oconfig_parse_file (file); if (root == NULL) { ERROR ("configfile: Cannot read file `%s'.", file); return (NULL); } status = cf_include_all (root, depth); if (status != 0) { oconfig_free (root); return (NULL); } return (root); } /* oconfig_item_t *cf_read_file */ static int cf_compare_string (const void *p1, const void *p2) { return strcmp (*(const char **) p1, *(const char **) p2); } static oconfig_item_t *cf_read_dir (const char *dir, const char *pattern, int depth) { oconfig_item_t *root = NULL; DIR *dh; struct dirent *de; char **filenames = NULL; int filenames_num = 0; int status; int i; assert (depth < CF_MAX_DEPTH); dh = opendir (dir); if (dh == NULL) { char errbuf[1024]; ERROR ("configfile: opendir failed: %s", sstrerror (errno, errbuf, sizeof (errbuf))); return (NULL); } root = (oconfig_item_t *) malloc (sizeof (oconfig_item_t)); if (root == NULL) { ERROR ("configfile: malloc failed."); return (NULL); } memset (root, 0, sizeof (oconfig_item_t)); while ((de = readdir (dh)) != NULL) { char name[1024]; char **tmp; if ((de->d_name[0] == '.') || (de->d_name[0] == 0)) continue; status = ssnprintf (name, sizeof (name), "%s/%s", dir, de->d_name); if ((status < 0) || ((size_t) status >= sizeof (name))) { ERROR ("configfile: Not including `%s/%s' because its" " name is too long.", dir, de->d_name); for (i = 0; i < filenames_num; ++i) free (filenames[i]); free (filenames); free (root); return (NULL); } ++filenames_num; tmp = (char **) realloc (filenames, filenames_num * sizeof (*filenames)); if (tmp == NULL) { ERROR ("configfile: realloc failed."); for (i = 0; i < filenames_num - 1; ++i) free (filenames[i]); free (filenames); free (root); return (NULL); } filenames = tmp; filenames[filenames_num - 1] = sstrdup (name); } qsort ((void *) filenames, filenames_num, sizeof (*filenames), cf_compare_string); for (i = 0; i < filenames_num; ++i) { oconfig_item_t *temp; char *name = filenames[i]; temp = cf_read_generic (name, pattern, depth); if (temp == NULL) { /* An error should already have been reported. */ sfree (name); continue; } cf_ci_append_children (root, temp); sfree (temp->children); sfree (temp); free (name); } free(filenames); return (root); } /* oconfig_item_t *cf_read_dir */ /* * cf_read_generic * * Path is stat'ed and either cf_read_file or cf_read_dir is called * accordingly. * * There are two versions of this function: If `wordexp' exists shell wildcards * will be expanded and the function will include all matches found. If * `wordexp' (or, more precisely, it's header file) is not available the * simpler function is used which does not do any such expansion. */ #if HAVE_WORDEXP_H static oconfig_item_t *cf_read_generic (const char *path, const char *pattern, int depth) { oconfig_item_t *root = NULL; int status; const char *path_ptr; wordexp_t we; size_t i; if (depth >= CF_MAX_DEPTH) { ERROR ("configfile: Not including `%s' because the maximum " "nesting depth has been reached.", path); return (NULL); } status = wordexp (path, &we, WRDE_NOCMD); if (status != 0) { ERROR ("configfile: wordexp (%s) failed.", path); return (NULL); } root = (oconfig_item_t *) malloc (sizeof (oconfig_item_t)); if (root == NULL) { ERROR ("configfile: malloc failed."); return (NULL); } memset (root, '\0', sizeof (oconfig_item_t)); /* wordexp() might return a sorted list already. That's not * documented though, so let's make sure we get what we want. */ qsort ((void *) we.we_wordv, we.we_wordc, sizeof (*we.we_wordv), cf_compare_string); for (i = 0; i < we.we_wordc; i++) { oconfig_item_t *temp; struct stat statbuf; path_ptr = we.we_wordv[i]; status = stat (path_ptr, &statbuf); if (status != 0) { char errbuf[1024]; WARNING ("configfile: stat (%s) failed: %s", path_ptr, sstrerror (errno, errbuf, sizeof (errbuf))); continue; } if (S_ISREG (statbuf.st_mode)) temp = cf_read_file (path_ptr, pattern, depth); else if (S_ISDIR (statbuf.st_mode)) temp = cf_read_dir (path_ptr, pattern, depth); else { WARNING ("configfile: %s is neither a file nor a " "directory.", path); continue; } if (temp == NULL) { oconfig_free (root); return (NULL); } cf_ci_append_children (root, temp); sfree (temp->children); sfree (temp); } wordfree (&we); return (root); } /* oconfig_item_t *cf_read_generic */ /* #endif HAVE_WORDEXP_H */ #else /* if !HAVE_WORDEXP_H */ static oconfig_item_t *cf_read_generic (const char *path, const char *pattern, int depth) { struct stat statbuf; int status; if (depth >= CF_MAX_DEPTH) { ERROR ("configfile: Not including `%s' because the maximum " "nesting depth has been reached.", path); return (NULL); } status = stat (path, &statbuf); if (status != 0) { char errbuf[1024]; ERROR ("configfile: stat (%s) failed: %s", path, sstrerror (errno, errbuf, sizeof (errbuf))); return (NULL); } if (S_ISREG (statbuf.st_mode)) return (cf_read_file (path, pattern, depth)); else if (S_ISDIR (statbuf.st_mode)) return (cf_read_dir (path, pattern, depth)); ERROR ("configfile: %s is neither a file nor a directory.", path); return (NULL); } /* oconfig_item_t *cf_read_generic */ #endif /* !HAVE_WORDEXP_H */ /* * Public functions */ int global_option_set (const char *option, const char *value) { int i; DEBUG ("option = %s; value = %s;", option, value); for (i = 0; i < cf_global_options_num; i++) if (strcasecmp (cf_global_options[i].key, option) == 0) break; if (i >= cf_global_options_num) return (-1); sfree (cf_global_options[i].value); if (value != NULL) cf_global_options[i].value = strdup (value); else cf_global_options[i].value = NULL; return (0); } const char *global_option_get (const char *option) { int i; for (i = 0; i < cf_global_options_num; i++) if (strcasecmp (cf_global_options[i].key, option) == 0) break; if (i >= cf_global_options_num) return (NULL); return ((cf_global_options[i].value != NULL) ? cf_global_options[i].value : cf_global_options[i].def); } /* char *global_option_get */ long global_option_get_long (const char *option, long default_value) { const char *str; long value; str = global_option_get (option); if (NULL == str) return (default_value); errno = 0; value = strtol (str, /* endptr = */ NULL, /* base = */ 0); if (errno != 0) return (default_value); return (value); } /* char *global_option_get_long */ cdtime_t cf_get_default_interval (void) { char const *str = global_option_get ("Interval"); double interval_double = COLLECTD_DEFAULT_INTERVAL; if (str != NULL) { char *endptr = NULL; double tmp = strtod (str, &endptr); if ((endptr == NULL) || (endptr == str) || (*endptr != 0)) ERROR ("cf_get_default_interval: Unable to parse string \"%s\" " "as number.", str); else if (tmp <= 0.0) ERROR ("cf_get_default_interval: Interval must be a positive number. " "The current number is %g.", tmp); else interval_double = tmp; } return (DOUBLE_TO_CDTIME_T (interval_double)); } /* }}} cdtime_t cf_get_default_interval */ void cf_unregister (const char *type) { cf_callback_t *this, *prev; for (prev = NULL, this = first_callback; this != NULL; prev = this, this = this->next) if (strcasecmp (this->type, type) == 0) { if (prev == NULL) first_callback = this->next; else prev->next = this->next; free (this); break; } } /* void cf_unregister */ void cf_unregister_complex (const char *type) { cf_complex_callback_t *this, *prev; for (prev = NULL, this = complex_callback_head; this != NULL; prev = this, this = this->next) if (strcasecmp (this->type, type) == 0) { if (prev == NULL) complex_callback_head = this->next; else prev->next = this->next; sfree (this->type); sfree (this); break; } } /* void cf_unregister */ void cf_register (const char *type, int (*callback) (const char *, const char *), const char **keys, int keys_num) { cf_callback_t *cf_cb; /* Remove this module from the list, if it already exists */ cf_unregister (type); /* This pointer will be free'd in `cf_unregister' */ if ((cf_cb = (cf_callback_t *) malloc (sizeof (cf_callback_t))) == NULL) return; cf_cb->type = type; cf_cb->callback = callback; cf_cb->keys = keys; cf_cb->keys_num = keys_num; cf_cb->ctx = plugin_get_ctx (); cf_cb->next = first_callback; first_callback = cf_cb; } /* void cf_register */ int cf_register_complex (const char *type, int (*callback) (oconfig_item_t *)) { cf_complex_callback_t *new; new = (cf_complex_callback_t *) malloc (sizeof (cf_complex_callback_t)); if (new == NULL) return (-1); new->type = strdup (type); if (new->type == NULL) { sfree (new); return (-1); } new->callback = callback; new->next = NULL; new->ctx = plugin_get_ctx (); if (complex_callback_head == NULL) { complex_callback_head = new; } else { cf_complex_callback_t *last = complex_callback_head; while (last->next != NULL) last = last->next; last->next = new; } return (0); } /* int cf_register_complex */ int cf_read (char *filename) { oconfig_item_t *conf; int i; conf = cf_read_generic (filename, /* pattern = */ NULL, /* depth = */ 0); if (conf == NULL) { ERROR ("Unable to read config file %s.", filename); return (-1); } else if (conf->children_num == 0) { ERROR ("Configuration file %s is empty.", filename); oconfig_free (conf); return (-1); } for (i = 0; i < conf->children_num; i++) { if (conf->children[i].children == NULL) dispatch_value (conf->children + i); else dispatch_block (conf->children + i); } oconfig_free (conf); /* Read the default types.db if no `TypesDB' option was given. */ if (cf_default_typesdb) read_types_list (PKGDATADIR"/types.db"); return (0); } /* int cf_read */ /* Assures the config option is a string, duplicates it and returns the copy in * "ret_string". If necessary "*ret_string" is freed first. Returns zero upon * success. */ int cf_util_get_string (const oconfig_item_t *ci, char **ret_string) /* {{{ */ { char *string; if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) { ERROR ("cf_util_get_string: The %s option requires " "exactly one string argument.", ci->key); return (-1); } string = strdup (ci->values[0].value.string); if (string == NULL) return (-1); if (*ret_string != NULL) sfree (*ret_string); *ret_string = string; return (0); } /* }}} int cf_util_get_string */ /* Assures the config option is a string and copies it to the provided buffer. * Assures null-termination. */ int cf_util_get_string_buffer (const oconfig_item_t *ci, char *buffer, /* {{{ */ size_t buffer_size) { if ((ci == NULL) || (buffer == NULL) || (buffer_size < 1)) return (EINVAL); if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) { ERROR ("cf_util_get_string_buffer: The %s option requires " "exactly one string argument.", ci->key); return (-1); } strncpy (buffer, ci->values[0].value.string, buffer_size); buffer[buffer_size - 1] = 0; return (0); } /* }}} int cf_util_get_string_buffer */ /* Assures the config option is a number and returns it as an int. */ int cf_util_get_int (const oconfig_item_t *ci, int *ret_value) /* {{{ */ { if ((ci == NULL) || (ret_value == NULL)) return (EINVAL); if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER)) { ERROR ("cf_util_get_int: The %s option requires " "exactly one numeric argument.", ci->key); return (-1); } *ret_value = (int) ci->values[0].value.number; return (0); } /* }}} int cf_util_get_int */ int cf_util_get_double (const oconfig_item_t *ci, double *ret_value) /* {{{ */ { if ((ci == NULL) || (ret_value == NULL)) return (EINVAL); if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER)) { ERROR ("cf_util_get_double: The %s option requires " "exactly one numeric argument.", ci->key); return (-1); } *ret_value = ci->values[0].value.number; return (0); } /* }}} int cf_util_get_double */ int cf_util_get_boolean (const oconfig_item_t *ci, _Bool *ret_bool) /* {{{ */ { if ((ci == NULL) || (ret_bool == NULL)) return (EINVAL); if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_BOOLEAN)) { ERROR ("cf_util_get_boolean: The %s option requires " "exactly one boolean argument.", ci->key); return (-1); } *ret_bool = ci->values[0].value.boolean ? 1 : 0; return (0); } /* }}} int cf_util_get_boolean */ int cf_util_get_flag (const oconfig_item_t *ci, /* {{{ */ unsigned int *ret_value, unsigned int flag) { int status; _Bool b; if (ret_value == NULL) return (EINVAL); b = 0; status = cf_util_get_boolean (ci, &b); if (status != 0) return (status); if (b) { *ret_value |= flag; } else { *ret_value &= ~flag; } return (0); } /* }}} int cf_util_get_flag */ /* Assures that the config option is a string or a number if the correct range * of 1-65535. The string is then converted to a port number using * `service_name_to_port_number' and returned. * Returns the port number in the range [1-65535] or less than zero upon * failure. */ int cf_util_get_port_number (const oconfig_item_t *ci) /* {{{ */ { int tmp; if ((ci->values_num != 1) || ((ci->values[0].type != OCONFIG_TYPE_STRING) && (ci->values[0].type != OCONFIG_TYPE_NUMBER))) { ERROR ("cf_util_get_port_number: The \"%s\" option requires " "exactly one string argument.", ci->key); return (-1); } if (ci->values[0].type == OCONFIG_TYPE_STRING) return (service_name_to_port_number (ci->values[0].value.string)); assert (ci->values[0].type == OCONFIG_TYPE_NUMBER); tmp = (int) (ci->values[0].value.number + 0.5); if ((tmp < 1) || (tmp > 65535)) { ERROR ("cf_util_get_port_number: The \"%s\" option requires " "a service name or a port number. The number " "you specified, %i, is not in the valid " "range of 1-65535.", ci->key, tmp); return (-1); } return (tmp); } /* }}} int cf_util_get_port_number */ int cf_util_get_service (const oconfig_item_t *ci, char **ret_string) /* {{{ */ { int port; char *service; int status; if (ci->values_num != 1) { ERROR ("cf_util_get_service: The %s option requires exactly " "one argument.", ci->key); return (-1); } if (ci->values[0].type == OCONFIG_TYPE_STRING) return (cf_util_get_string (ci, ret_string)); if (ci->values[0].type != OCONFIG_TYPE_NUMBER) { ERROR ("cf_util_get_service: The %s option requires " "exactly one string or numeric argument.", ci->key); } port = 0; status = cf_util_get_int (ci, &port); if (status != 0) return (status); else if ((port < 1) || (port > 65535)) { ERROR ("cf_util_get_service: The port number given " "for the %s option is out of " "range (%i).", ci->key, port); return (-1); } service = malloc (6); if (service == NULL) { ERROR ("cf_util_get_service: Out of memory."); return (-1); } ssnprintf (service, 6, "%i", port); sfree (*ret_string); *ret_string = service; return (0); } /* }}} int cf_util_get_service */ int cf_util_get_cdtime (const oconfig_item_t *ci, cdtime_t *ret_value) /* {{{ */ { if ((ci == NULL) || (ret_value == NULL)) return (EINVAL); if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER)) { ERROR ("cf_util_get_cdtime: The %s option requires " "exactly one numeric argument.", ci->key); return (-1); } if (ci->values[0].value.number < 0.0) { ERROR ("cf_util_get_cdtime: The numeric argument of the %s " "option must not be negative.", ci->key); return (-1); } *ret_value = DOUBLE_TO_CDTIME_T (ci->values[0].value.number); return (0); } /* }}} int cf_util_get_cdtime */
spotify/collectd
src/configfile.c
C
gpl-2.0
31,420
/* This file is part of JDasher. JDasher 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. JDasher 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 JDasher; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Copyright (C) 2006 Christopher Smowton <cs448@cam.ac.uk> JDasher is a port derived from the Dasher project; for information on the project see www.dasher.org.uk; for information on JDasher itself and related projects see www.smowton.net/chris */ package dasher; import java.util.ArrayList; /** * Represents a custom colour scheme, wrapping a ColourInfo object * and importing its contents into Collections suitable for random * access. * <p> * This also ensures that the ColourInfo object is read-only * when in use. */ public class CCustomColours { /** * Wrapped colour info object. */ protected CColourIO.ColourInfo m_ColourInfo; /** * Fast-access array of available colours' red values. */ protected ArrayList<Integer> m_Red = new ArrayList<Integer>(); /** * Fast-access array of available colours' green values. */ protected ArrayList<Integer> m_Green = new ArrayList<Integer>(); /** * Fast-access array of available colours' blue values. */ protected ArrayList<Integer> m_Blue = new ArrayList<Integer>(); /** * Sole constructor; copies the data from a given ColourInfo * object. * * @param ColInfo ColourInfo object detailing the scheme we wish to represent. */ public CCustomColours(CColourIO.ColourInfo ColInfo) { m_ColourInfo = ColInfo; // Add all the colours. for(int i = 0; i < m_ColourInfo.Reds.size(); i++) { // loop colours m_Red.add(m_ColourInfo.Reds.get(i)); m_Green.add(m_ColourInfo.Greens.get(i)); m_Blue.add(m_ColourInfo.Blues.get(i)); } } /** * Gets number of available colours. * * @return Number of available colours. */ public int GetNumColours() { return m_Red.size(); } /** * Gets the red value of a given colour. * * @param colour Index of the colour to look up. * @return Red value, on a scale from 0 to 255. */ public int GetRed(int colour) { return m_Red.get(colour); } /** * Gets the green value of a given colour. * * @param colour Index of the colour to look up. * @return green value, on a scale from 0 to 255. */ public int GetGreen(int colour) { return m_Green.get(colour); } /** * Gets the blue value of a given colour. * * @param colour Index of the colour to look up. * @return blue value, on a scale from 0 to 255. */ public int GetBlue(int colour) { return m_Blue.get(colour); } }
ipomoena/dasher
java/src/main/java/dasher/CCustomColours.java
Java
gpl-2.0
3,221
<?php /** * ezcCacheStorageFileEvalArrayTest * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * @package Cache * @subpackage Tests * @version //autogen// * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0 */ /** * Require parent test class. */ require_once 'storage_test.php'; /** * Test suite for ezcStorageFileEvalArray class. * * @package Cache * @subpackage Tests */ class ezcCacheStorageFileEvalArrayTest extends ezcCacheStorageTest { public static function suite() { return new PHPUnit_Framework_TestSuite( "ezcCacheStorageFileEvalArrayTest" ); } } ?>
imadkaf/PFE
ezpublish_legacy/vendor/zetacomponents/cache/tests/storage_file_evalarray_test.php
PHP
gpl-2.0
1,374
// license:BSD-3-Clause // copyright-holders:Luca Elia /*************************************************************************** -= American Speedway =- driver by Luca Elia (l.elia@tin.it) CPU : Z80A x 2 Sound: YM2151 (c)1987 Enerdyne Technologies, Inc. / PGD ***************************************************************************/ #include "emu.h" #include "cpu/z80/z80.h" #include "includes/amspdwy.h" /*************************************************************************** Main CPU ***************************************************************************/ /* 765----- Buttons ---4---- Sgn(Wheel Delta) ----3210 Abs(Wheel Delta) Or last value when wheel delta = 0 */ UINT8 amspdwy_state::amspdwy_wheel_r( int index ) { static const char *const portnames[] = { "WHEEL1", "WHEEL2", "AN1", "AN2" }; UINT8 wheel = ioport(portnames[2 + index])->read(); if (wheel != m_wheel_old[index]) { wheel = (wheel & 0x7fff) - (wheel & 0x8000); if (wheel > m_wheel_old[index]) m_wheel_return[index] = ((+wheel) & 0xf) | 0x00; else m_wheel_return[index] = ((-wheel) & 0xf) | 0x10; m_wheel_old[index] = wheel; } return m_wheel_return[index] | ioport(portnames[index])->read(); } READ8_MEMBER(amspdwy_state::amspdwy_wheel_0_r) { // player 1 return amspdwy_wheel_r(0); } READ8_MEMBER(amspdwy_state::amspdwy_wheel_1_r) { // player 2 return amspdwy_wheel_r(1); } READ8_MEMBER(amspdwy_state::amspdwy_sound_r) { return (m_ym2151->status_r(space, 0) & ~0x30) | ioport("IN0")->read(); } WRITE8_MEMBER(amspdwy_state::amspdwy_sound_w) { soundlatch_byte_w(space, 0, data); m_audiocpu->set_input_line(INPUT_LINE_NMI, PULSE_LINE); } static ADDRESS_MAP_START( amspdwy_map, AS_PROGRAM, 8, amspdwy_state ) AM_RANGE(0x0000, 0x7fff) AM_ROM AM_RANGE(0x8000, 0x801f) AM_DEVWRITE("palette", palette_device, write) AM_SHARE("palette") AM_RANGE(0x9000, 0x93ff) AM_MIRROR(0x0400) AM_RAM_WRITE(amspdwy_videoram_w) AM_SHARE("videoram") AM_RANGE(0x9800, 0x9bff) AM_RAM_WRITE(amspdwy_colorram_w) AM_SHARE("colorram") AM_RANGE(0x9c00, 0x9fff) AM_RAM // unused? // AM_RANGE(0xa000, 0xa000) AM_WRITENOP // ? AM_RANGE(0xa000, 0xa000) AM_READ_PORT("DSW1") AM_RANGE(0xa400, 0xa400) AM_READ_PORT("DSW2") AM_WRITE(amspdwy_flipscreen_w) AM_RANGE(0xa800, 0xa800) AM_READ(amspdwy_wheel_0_r) AM_RANGE(0xac00, 0xac00) AM_READ(amspdwy_wheel_1_r) AM_RANGE(0xb000, 0xb000) AM_WRITENOP // irq ack? AM_RANGE(0xb400, 0xb400) AM_READWRITE(amspdwy_sound_r, amspdwy_sound_w) AM_RANGE(0xc000, 0xc0ff) AM_RAM AM_SHARE("spriteram") AM_RANGE(0xe000, 0xe7ff) AM_RAM ADDRESS_MAP_END static ADDRESS_MAP_START( amspdwy_portmap, AS_IO, 8, amspdwy_state ) AM_RANGE(0x0000, 0x7fff) AM_ROM AM_REGION("tracks", 0) ADDRESS_MAP_END /*************************************************************************** Sound CPU ***************************************************************************/ static ADDRESS_MAP_START( amspdwy_sound_map, AS_PROGRAM, 8, amspdwy_state ) AM_RANGE(0x0000, 0x7fff) AM_ROM // AM_RANGE(0x8000, 0x8000) AM_WRITENOP // ? writes 0 at start AM_RANGE(0x9000, 0x9000) AM_READ(soundlatch_byte_r) AM_RANGE(0xa000, 0xa001) AM_DEVREADWRITE("ymsnd", ym2151_device, read, write) AM_RANGE(0xc000, 0xdfff) AM_RAM AM_RANGE(0xffff, 0xffff) AM_READNOP // ??? IY = FFFF at the start ? ADDRESS_MAP_END /*************************************************************************** Input Ports ***************************************************************************/ static INPUT_PORTS_START( amspdwy ) PORT_START("DSW1") PORT_DIPNAME( 0x01, 0x00, "Character Test" ) PORT_DIPLOCATION("SW1:8") PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x01, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x00, "Show Arrows" ) PORT_DIPLOCATION("SW1:7") PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x02, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Demo_Sounds ) ) PORT_DIPLOCATION("SW1:6") PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x04, DEF_STR( On ) ) PORT_SERVICE_DIPLOC( 0x08, IP_ACTIVE_HIGH, "SW1:5" ) PORT_DIPNAME( 0x10, 0x00, "Steering Test" ) PORT_DIPLOCATION("SW1:4") PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x10, DEF_STR( On ) ) PORT_DIPUNUSED_DIPLOC( 0x20, 0x00, "SW1:3" ) /* Listed as "Unused" */ PORT_DIPUNUSED_DIPLOC( 0x40, 0x00, "SW1:2" ) /* Listed as "Unused" */ PORT_DIPUNUSED_DIPLOC( 0x80, 0x00, "SW1:1" ) /* Listed as "Unused" */ PORT_START("DSW2") PORT_DIPNAME( 0x03, 0x00, DEF_STR( Coinage ) ) PORT_DIPLOCATION("SW2:7,8") PORT_DIPSETTING( 0x03, DEF_STR( 2C_1C ) ) // PORT_DIPSETTING( 0x02, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 1C_2C ) ) PORT_DIPNAME( 0x0c, 0x00, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("SW2:5,6") PORT_DIPSETTING( 0x00, DEF_STR( Easy ) ) PORT_DIPSETTING( 0x04, DEF_STR( Normal ) ) PORT_DIPSETTING( 0x08, DEF_STR( Hard ) ) PORT_DIPSETTING( 0x0c, DEF_STR( Hardest ) ) PORT_DIPNAME( 0x30, 0x00, "Time To Qualify" ) PORT_DIPLOCATION("SW2:3,4") /* code at 0x1770 */ PORT_DIPSETTING( 0x30, "20 sec" ) PORT_DIPSETTING( 0x20, "30 sec" ) PORT_DIPSETTING( 0x10, "45 sec" ) PORT_DIPSETTING( 0x00, "60 sec" ) PORT_DIPUNUSED_DIPLOC( 0x40, 0x00, "SW2:2" ) /* Listed as "Unused" */ PORT_DIPUNUSED_DIPLOC( 0x80, 0x00, "SW2:1" ) /* Listed as "Unused" */ PORT_START("WHEEL1") // Player 1 Wheel + Coins PORT_BIT( 0x1f, IP_ACTIVE_HIGH, IPT_SPECIAL ) // wheel PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_IMPULSE(2) // 2-3f PORT_START("WHEEL2") // Player 2 Wheel + Coins PORT_BIT( 0x1f, IP_ACTIVE_HIGH, IPT_SPECIAL ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_IMPULSE(2) PORT_START("IN0") // Player 1&2 Pedals + YM2151 Sound Status PORT_BIT( 0x0f, IP_ACTIVE_HIGH, IPT_SPECIAL ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0xc0, IP_ACTIVE_HIGH, IPT_SPECIAL ) PORT_START("AN1") // Player 1 Analog Fake Port PORT_BIT( 0xffff, 0x0000, IPT_DIAL ) PORT_SENSITIVITY(15) PORT_KEYDELTA(20) PORT_CODE_DEC(KEYCODE_LEFT) PORT_CODE_INC(KEYCODE_RIGHT) PORT_PLAYER(1) PORT_START("AN2") // Player 2 Analog Fake Port PORT_BIT( 0xffff, 0x0000, IPT_DIAL ) PORT_SENSITIVITY(15) PORT_KEYDELTA(20) PORT_CODE_DEC(KEYCODE_D) PORT_CODE_INC(KEYCODE_G) PORT_PLAYER(2) INPUT_PORTS_END static INPUT_PORTS_START( amspdwya ) PORT_INCLUDE(amspdwy) PORT_MODIFY("DSW2") PORT_DIPNAME( 0x10, 0x00, "Time To Qualify" ) PORT_DIPLOCATION("SW2:4") /* code at 0x2696 */ PORT_DIPSETTING( 0x10, "45 sec" ) PORT_DIPSETTING( 0x00, "60 sec" ) PORT_DIPUNUSED_DIPLOC( 0x20, 0x00, "SW2:3" ) /* Listed as "Unused" */ INPUT_PORTS_END /*************************************************************************** Graphics Layouts ***************************************************************************/ static const gfx_layout layout_8x8x2 = { 8,8, RGN_FRAC(1,2), 2, { RGN_FRAC(0,2), RGN_FRAC(1,2) }, { STEP8(0,1) }, { STEP8(0,8) }, 8*8 }; static GFXDECODE_START( amspdwy ) GFXDECODE_ENTRY( "gfx1", 0, layout_8x8x2, 0, 8 ) GFXDECODE_END /*************************************************************************** Machine Drivers ***************************************************************************/ void amspdwy_state::machine_start() { save_item(NAME(m_flipscreen)); save_item(NAME(m_wheel_old)); save_item(NAME(m_wheel_return)); } void amspdwy_state::machine_reset() { m_flipscreen = 0; m_wheel_old[0] = 0; m_wheel_old[1] = 0; m_wheel_return[0] = 0; m_wheel_return[1] = 0; } static MACHINE_CONFIG_START( amspdwy, amspdwy_state ) /* basic machine hardware */ MCFG_CPU_ADD("maincpu", Z80, 3000000) MCFG_CPU_PROGRAM_MAP(amspdwy_map) MCFG_CPU_IO_MAP(amspdwy_portmap) MCFG_CPU_VBLANK_INT_DRIVER("screen", amspdwy_state, irq0_line_hold) /* IRQ: 60Hz, NMI: retn */ MCFG_CPU_ADD("audiocpu", Z80, 3000000) MCFG_CPU_PROGRAM_MAP(amspdwy_sound_map) MCFG_QUANTUM_PERFECT_CPU("maincpu") /* video hardware */ MCFG_SCREEN_ADD("screen", RASTER) MCFG_SCREEN_REFRESH_RATE(60) MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(0)) MCFG_SCREEN_SIZE(256, 256) MCFG_SCREEN_VISIBLE_AREA(0, 256-1, 0+16, 256-16-1) MCFG_SCREEN_UPDATE_DRIVER(amspdwy_state, screen_update_amspdwy) MCFG_SCREEN_PALETTE("palette") MCFG_GFXDECODE_ADD("gfxdecode", "palette", amspdwy) MCFG_PALETTE_ADD("palette", 32) MCFG_PALETTE_FORMAT(BBGGGRRR_inverted) /* sound hardware */ MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker") MCFG_YM2151_ADD("ymsnd", 3000000) MCFG_YM2151_IRQ_HANDLER(INPUTLINE("audiocpu", 0)) MCFG_SOUND_ROUTE(0, "lspeaker", 1.0) MCFG_SOUND_ROUTE(1, "rspeaker", 1.0) MACHINE_CONFIG_END /*************************************************************************** ROMs Loading ***************************************************************************/ /*************************************************************************** American Speedway USES TWO Z80 CPU'S W/YM2151 SOUND THE NUMBERS WITH THE NAMES ARE PROBABLY CHECKSUMS NAME LOCATION TYPE ------------------------ AUDI9363 U2 27256 CONN BD GAME5807 U33 " " TRKS6092 U34 " " HIHIE12A 4A 2732 REAR BD HILO9B3C 5A " " LOHI4644 2A " " LOLO1D51 1A " " American Speedway (Set 2) 1987 Enerdyne Technologies, Inc. Has Rev 4 PGD written on the top board. Processors ------------------ Dual Z80As YM2151 (sound) RAM ------------------ 12 2114 5 82S16N Eproms ================== Name Loc TYpe Checksum ---------- ---- ----- -------- Game.u22 U33 27256 A222 Tracks.u34 U34 27256 6092 Audio.U02 U2 27256 9363 LOLO1.1A 1A 2732 1D51 LOHI.2A 2A 2732 4644 HIHI.4A 3/4A 2732 E12A HILO.5A 5A 2732 9B3C ***************************************************************************/ ROM_START( amspdwy ) ROM_REGION( 0x10000, "maincpu", 0 ) /* Main Z80 Code */ ROM_LOAD( "game5807.u33", 0x0000, 0x8000, CRC(88233b59) SHA1(bfdf10dde1731cde5c579a9a5173cafe9295a80c) ) ROM_REGION( 0x10000, "audiocpu", 0 ) /* Sound Z80 Code */ ROM_LOAD( "audi9463.u2", 0x0000, 0x8000, CRC(61b0467e) SHA1(74509e7712838dd760919893aeda9241d308d0c3) ) ROM_REGION( 0x8000, "tracks", 0 ) ROM_LOAD( "trks6092.u34", 0x0000, 0x8000, CRC(74a4e7b7) SHA1(b4f6e3faaf048351c6671205f52378a64b81bcb1) ) ROM_REGION( 0x4000, "gfx1", 0 ) /* Layer + Sprites */ ROM_LOAD( "hilo9b3c.5a", 0x0000, 0x1000, CRC(f50f864c) SHA1(5b2412c1558b30a04523fcdf1d5cf6fdae1ba88d) ) ROM_LOAD( "hihie12a.4a", 0x1000, 0x1000, CRC(3d7497f3) SHA1(34820ba42d9c9dab1d6fdda15795450ce08392c1) ) ROM_LOAD( "lolo1d51.1a", 0x2000, 0x1000, CRC(58701c1c) SHA1(67b476e697652a6b684bd76ae6c0078ed4b3e3a2) ) ROM_LOAD( "lohi4644.2a", 0x3000, 0x1000, CRC(a1d802b1) SHA1(1249ce406b1aa518885a02ab063fa14906ccec2e) ) ROM_END ROM_START( amspdwya ) ROM_REGION( 0x10000, "maincpu", 0 ) /* Main Z80 Code */ ROM_LOAD( "game.u33", 0x0000, 0x8000, CRC(facab102) SHA1(e232969eaaad8b89ac8e28ee0a7996107a7de9a2) ) ROM_REGION( 0x10000, "audiocpu", 0 ) /* Sound Z80 Code */ ROM_LOAD( "audi9463.u2", 0x0000, 0x8000, CRC(61b0467e) SHA1(74509e7712838dd760919893aeda9241d308d0c3) ) ROM_REGION( 0x8000, "tracks", 0 ) ROM_LOAD( "trks6092.u34", 0x0000, 0x8000, CRC(74a4e7b7) SHA1(b4f6e3faaf048351c6671205f52378a64b81bcb1) ) ROM_REGION( 0x4000, "gfx1", 0 ) /* Layer + Sprites */ ROM_LOAD( "hilo9b3c.5a", 0x0000, 0x1000, CRC(f50f864c) SHA1(5b2412c1558b30a04523fcdf1d5cf6fdae1ba88d) ) ROM_LOAD( "hihie12a.4a", 0x1000, 0x1000, CRC(3d7497f3) SHA1(34820ba42d9c9dab1d6fdda15795450ce08392c1) ) ROM_LOAD( "lolo1d51.1a", 0x2000, 0x1000, CRC(58701c1c) SHA1(67b476e697652a6b684bd76ae6c0078ed4b3e3a2) ) ROM_LOAD( "lohi4644.2a", 0x3000, 0x1000, CRC(a1d802b1) SHA1(1249ce406b1aa518885a02ab063fa14906ccec2e) ) ROM_END /* (C) 1987 ETI 8402 MAGNOLIA ST. #C SANTEE, CA 92071 */ GAME( 1987, amspdwy, 0, amspdwy, amspdwy, driver_device, 0, ROT0, "Enerdyne Technologies Inc.", "American Speedway (set 1)", MACHINE_SUPPORTS_SAVE ) GAME( 1987, amspdwya, amspdwy, amspdwy, amspdwya, driver_device, 0, ROT0, "Enerdyne Technologies Inc.", "American Speedway (set 2)", MACHINE_SUPPORTS_SAVE )
RJRetro/mame
src/mame/drivers/amspdwy.cpp
C++
gpl-2.0
12,743
#!/bin/sh # # Copyright (C) 2006 Martin Waitz <tali@admingilde.org> # test_description='test clone --reference' GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main export GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME . ./test-lib.sh base_dir=$(pwd) U=$base_dir/UPLOAD_LOG # create a commit in repo $1 with name $2 commit_in () { ( cd "$1" && echo "$2" >"$2" && git add "$2" && git commit -m "$2" ) } # check that there are $2 loose objects in repo $1 test_objcount () { echo "$2" >expect && git -C "$1" count-objects >actual.raw && cut -d' ' -f1 <actual.raw >actual && test_cmp expect actual } test_expect_success 'preparing first repository' ' test_create_repo A && commit_in A file1 ' test_expect_success 'preparing second repository' ' git clone A B && commit_in B file2 && git -C B repack -ad && git -C B prune ' test_expect_success 'cloning with reference (-l -s)' ' git clone -l -s --reference B A C ' test_expect_success 'existence of info/alternates' ' test_line_count = 2 C/.git/objects/info/alternates ' test_expect_success 'pulling from reference' ' git -C C pull ../B main ' test_expect_success 'that reference gets used' ' test_objcount C 0 ' test_expect_success 'cloning with reference (no -l -s)' ' GIT_TRACE_PACKET=$U.D git clone --reference B "file://$(pwd)/A" D ' test_expect_success 'fetched no objects' ' test -s "$U.D" && ! grep " want" "$U.D" ' test_expect_success 'existence of info/alternates' ' test_line_count = 1 D/.git/objects/info/alternates ' test_expect_success 'pulling from reference' ' git -C D pull ../B main ' test_expect_success 'that reference gets used' ' test_objcount D 0 ' test_expect_success 'updating origin' ' commit_in A file3 && git -C A repack -ad && git -C A prune ' test_expect_success 'pulling changes from origin' ' git -C C pull origin ' # the 2 local objects are commit and tree from the merge test_expect_success 'that alternate to origin gets used' ' test_objcount C 2 ' test_expect_success 'pulling changes from origin' ' git -C D pull origin ' # the 5 local objects are expected; file3 blob, commit in A to add it # and its tree, and 2 are our tree and the merge commit. test_expect_success 'check objects expected to exist locally' ' test_objcount D 5 ' test_expect_success 'preparing alternate repository #1' ' test_create_repo F && commit_in F file1 ' test_expect_success 'cloning alternate repo #2 and adding changes to repo #1' ' git clone F G && commit_in F file2 ' test_expect_success 'cloning alternate repo #1, using #2 as reference' ' git clone --reference G F H ' test_expect_success 'cloning with reference being subset of source (-l -s)' ' git clone -l -s --reference A B E ' test_expect_success 'cloning with multiple references drops duplicates' ' git clone -s --reference B --reference A --reference B A dups && test_line_count = 2 dups/.git/objects/info/alternates ' test_expect_success 'clone with reference from a tagged repository' ' ( cd A && git tag -a -m tagged HEAD ) && git clone --reference=A A I ' test_expect_success 'prepare branched repository' ' git clone A J && ( cd J && git checkout -b other main^ && echo other >otherfile && git add otherfile && git commit -m other && git checkout main ) ' test_expect_success 'fetch with incomplete alternates' ' git init K && echo "$base_dir/A/.git/objects" >K/.git/objects/info/alternates && ( cd K && git remote add J "file://$base_dir/J" && GIT_TRACE_PACKET=$U.K git fetch J ) && main_object=$(cd A && git for-each-ref --format="%(objectname)" refs/heads/main) && test -s "$U.K" && ! grep " want $main_object" "$U.K" && tag_object=$(cd A && git for-each-ref --format="%(objectname)" refs/tags/HEAD) && ! grep " want $tag_object" "$U.K" ' test_expect_success 'clone using repo with gitfile as a reference' ' git clone --separate-git-dir=L A M && git clone --reference=M A N && echo "$base_dir/L/objects" >expected && test_cmp expected "$base_dir/N/.git/objects/info/alternates" ' test_expect_success 'clone using repo pointed at by gitfile as reference' ' git clone --reference=M/.git A O && echo "$base_dir/L/objects" >expected && test_cmp expected "$base_dir/O/.git/objects/info/alternates" ' test_expect_success 'clone and dissociate from reference' ' git init P && ( cd P && test_commit one ) && git clone P Q && ( cd Q && test_commit two ) && git clone --no-local --reference=P Q R && git clone --no-local --reference=P --dissociate Q S && # removing the reference P would corrupt R but not S rm -fr P && test_must_fail git -C R fsck && git -C S fsck ' test_expect_success 'clone, dissociate from partial reference and repack' ' rm -fr P Q R && git init P && ( cd P && test_commit one && git repack && test_commit two && git repack ) && git clone --bare P Q && ( cd P && git checkout -b second && test_commit three && git repack ) && git clone --bare --dissociate --reference=P Q R && ls R/objects/pack/*.pack >packs.txt && test_line_count = 1 packs.txt ' test_expect_success 'clone, dissociate from alternates' ' rm -fr A B C && test_create_repo A && commit_in A file1 && git clone --reference=A A B && test_line_count = 1 B/.git/objects/info/alternates && git clone --local --dissociate B C && ! test -f C/.git/objects/info/alternates && ( cd C && git fsck ) ' test_expect_success 'setup repo with garbage in objects/*' ' git init S && ( cd S && test_commit A && cd .git/objects && >.some-hidden-file && >some-file && mkdir .some-hidden-dir && >.some-hidden-dir/some-file && >.some-hidden-dir/.some-dot-file && mkdir some-dir && >some-dir/some-file && >some-dir/.some-dot-file ) ' test_expect_success 'clone a repo with garbage in objects/*' ' for option in --local --no-hardlinks --shared --dissociate do git clone $option S S$option || return 1 && git -C S$option fsck || return 1 done && find S-* -name "*some*" | sort >actual && cat >expected <<-EOF && S--dissociate/.git/objects/.some-hidden-dir S--dissociate/.git/objects/.some-hidden-dir/.some-dot-file S--dissociate/.git/objects/.some-hidden-dir/some-file S--dissociate/.git/objects/.some-hidden-file S--dissociate/.git/objects/some-dir S--dissociate/.git/objects/some-dir/.some-dot-file S--dissociate/.git/objects/some-dir/some-file S--dissociate/.git/objects/some-file S--local/.git/objects/.some-hidden-dir S--local/.git/objects/.some-hidden-dir/.some-dot-file S--local/.git/objects/.some-hidden-dir/some-file S--local/.git/objects/.some-hidden-file S--local/.git/objects/some-dir S--local/.git/objects/some-dir/.some-dot-file S--local/.git/objects/some-dir/some-file S--local/.git/objects/some-file S--no-hardlinks/.git/objects/.some-hidden-dir S--no-hardlinks/.git/objects/.some-hidden-dir/.some-dot-file S--no-hardlinks/.git/objects/.some-hidden-dir/some-file S--no-hardlinks/.git/objects/.some-hidden-file S--no-hardlinks/.git/objects/some-dir S--no-hardlinks/.git/objects/some-dir/.some-dot-file S--no-hardlinks/.git/objects/some-dir/some-file S--no-hardlinks/.git/objects/some-file EOF test_cmp expected actual ' test_expect_success SYMLINKS 'setup repo with manually symlinked or unknown files at objects/' ' git init T && ( cd T && git config gc.auto 0 && test_commit A && git gc && test_commit B && cd .git/objects && mv pack packs && ln -s packs pack && find ?? -type d >loose-dirs && last_loose=$(tail -n 1 loose-dirs) && mv $last_loose a-loose-dir && ln -s a-loose-dir $last_loose && first_loose=$(head -n 1 loose-dirs) && rm -f loose-dirs && cd $first_loose && obj=$(ls *) && mv $obj ../an-object && ln -s ../an-object $obj && cd ../ && find . -type f | sort >../../../T.objects-files.raw && find . -type l | sort >../../../T.objects-symlinks.raw && echo unknown_content >unknown_file ) && git -C T fsck && git -C T rev-list --all --objects >T.objects ' test_expect_success SYMLINKS 'clone repo with symlinked or unknown files at objects/' ' for option in --local --no-hardlinks --shared --dissociate do git clone $option T T$option || return 1 && git -C T$option fsck || return 1 && git -C T$option rev-list --all --objects >T$option.objects && test_cmp T.objects T$option.objects && ( cd T$option/.git/objects && find . -type f | sort >../../../T$option.objects-files.raw && find . -type l | sort >../../../T$option.objects-symlinks.raw ) done && for raw in $(ls T*.raw) do sed -e "s!/../!/Y/!; s![0-9a-f]\{38,\}!Z!" -e "/commit-graph/d" \ -e "/multi-pack-index/d" -e "/rev/d" <$raw >$raw.de-sha-1 && sort $raw.de-sha-1 >$raw.de-sha || return 1 done && cat >expected-files <<-EOF && ./Y/Z ./Y/Z ./Y/Z ./a-loose-dir/Z ./an-object ./info/packs ./pack/pack-Z.idx ./pack/pack-Z.pack ./packs/pack-Z.idx ./packs/pack-Z.pack ./unknown_file EOF for option in --local --no-hardlinks --dissociate do test_cmp expected-files T$option.objects-files.raw.de-sha || return 1 && test_must_be_empty T$option.objects-symlinks.raw.de-sha || return 1 done && echo ./info/alternates >expected-files && test_cmp expected-files T--shared.objects-files.raw && test_must_be_empty T--shared.objects-symlinks.raw ' test_done
felipec/git
t/t5604-clone-reference.sh
Shell
gpl-2.0
9,249
/* Perform arithmetic and other operations on values, for GDB. Copyright (C) 1986, 1988-2005, 2007-2012 Free Software Foundation, Inc. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "defs.h" #include "value.h" #include "symtab.h" #include "gdbtypes.h" #include "expression.h" #include "target.h" #include "language.h" #include "gdb_string.h" #include "doublest.h" #include "dfp.h" #include <math.h> #include "infcall.h" #include "exceptions.h" /* Define whether or not the C operator '/' truncates towards zero for differently signed operands (truncation direction is undefined in C). */ #ifndef TRUNCATION_TOWARDS_ZERO #define TRUNCATION_TOWARDS_ZERO ((-5 / 2) == -2) #endif void _initialize_valarith (void); /* Given a pointer, return the size of its target. If the pointer type is void *, then return 1. If the target type is incomplete, then error out. This isn't a general purpose function, but just a helper for value_ptradd. */ static LONGEST find_size_for_pointer_math (struct type *ptr_type) { LONGEST sz = -1; struct type *ptr_target; gdb_assert (TYPE_CODE (ptr_type) == TYPE_CODE_PTR); ptr_target = check_typedef (TYPE_TARGET_TYPE (ptr_type)); sz = TYPE_LENGTH (ptr_target); if (sz == 0) { if (TYPE_CODE (ptr_type) == TYPE_CODE_VOID) sz = 1; else { char *name; name = TYPE_NAME (ptr_target); if (name == NULL) name = TYPE_TAG_NAME (ptr_target); if (name == NULL) error (_("Cannot perform pointer math on incomplete types, " "try casting to a known type, or void *.")); else error (_("Cannot perform pointer math on incomplete type \"%s\", " "try casting to a known type, or void *."), name); } } return sz; } /* Given a pointer ARG1 and an integral value ARG2, return the result of C-style pointer arithmetic ARG1 + ARG2. */ struct value * value_ptradd (struct value *arg1, LONGEST arg2) { struct type *valptrtype; LONGEST sz; struct value *result; arg1 = coerce_array (arg1); valptrtype = check_typedef (value_type (arg1)); sz = find_size_for_pointer_math (valptrtype); result = value_from_pointer (valptrtype, value_as_address (arg1) + sz * arg2); if (VALUE_LVAL (result) != lval_internalvar) set_value_component_location (result, arg1); return result; } /* Given two compatible pointer values ARG1 and ARG2, return the result of C-style pointer arithmetic ARG1 - ARG2. */ LONGEST value_ptrdiff (struct value *arg1, struct value *arg2) { struct type *type1, *type2; LONGEST sz; arg1 = coerce_array (arg1); arg2 = coerce_array (arg2); type1 = check_typedef (value_type (arg1)); type2 = check_typedef (value_type (arg2)); gdb_assert (TYPE_CODE (type1) == TYPE_CODE_PTR); gdb_assert (TYPE_CODE (type2) == TYPE_CODE_PTR); if (TYPE_LENGTH (check_typedef (TYPE_TARGET_TYPE (type1))) != TYPE_LENGTH (check_typedef (TYPE_TARGET_TYPE (type2)))) error (_("First argument of `-' is a pointer and " "second argument is neither\n" "an integer nor a pointer of the same type.")); sz = TYPE_LENGTH (check_typedef (TYPE_TARGET_TYPE (type1))); if (sz == 0) { warning (_("Type size unknown, assuming 1. " "Try casting to a known type, or void *.")); sz = 1; } return (value_as_long (arg1) - value_as_long (arg2)) / sz; } /* Return the value of ARRAY[IDX]. ARRAY may be of type TYPE_CODE_ARRAY or TYPE_CODE_STRING. If the current language supports C-style arrays, it may also be TYPE_CODE_PTR. To access TYPE_CODE_BITSTRING values, use value_bitstring_subscript. See comments in value_coerce_array() for rationale for reason for doing lower bounds adjustment here rather than there. FIXME: Perhaps we should validate that the index is valid and if verbosity is set, warn about invalid indices (but still use them). */ struct value * value_subscript (struct value *array, LONGEST index) { int c_style = current_language->c_style_arrays; struct type *tarray; array = coerce_ref (array); tarray = check_typedef (value_type (array)); if (TYPE_CODE (tarray) == TYPE_CODE_ARRAY || TYPE_CODE (tarray) == TYPE_CODE_STRING) { struct type *range_type = TYPE_INDEX_TYPE (tarray); LONGEST lowerbound, upperbound; get_discrete_bounds (range_type, &lowerbound, &upperbound); if (VALUE_LVAL (array) != lval_memory) return value_subscripted_rvalue (array, index, lowerbound); if (c_style == 0) { if (index >= lowerbound && index <= upperbound) return value_subscripted_rvalue (array, index, lowerbound); /* Emit warning unless we have an array of unknown size. An array of unknown size has lowerbound 0 and upperbound -1. */ if (upperbound > -1) warning (_("array or string index out of range")); /* fall doing C stuff */ c_style = 1; } index -= lowerbound; array = value_coerce_array (array); } if (c_style) return value_ind (value_ptradd (array, index)); else error (_("not an array or string")); } /* Return the value of EXPR[IDX], expr an aggregate rvalue (eg, a vector register). This routine used to promote floats to doubles, but no longer does. */ struct value * value_subscripted_rvalue (struct value *array, LONGEST index, int lowerbound) { struct type *array_type = check_typedef (value_type (array)); struct type *elt_type = check_typedef (TYPE_TARGET_TYPE (array_type)); unsigned int elt_size = TYPE_LENGTH (elt_type); unsigned int elt_offs = elt_size * longest_to_int (index - lowerbound); struct value *v; if (index < lowerbound || (!TYPE_ARRAY_UPPER_BOUND_IS_UNDEFINED (array_type) && elt_offs >= TYPE_LENGTH (array_type))) error (_("no such vector element")); if (VALUE_LVAL (array) == lval_memory && value_lazy (array)) v = allocate_value_lazy (elt_type); else { v = allocate_value (elt_type); value_contents_copy (v, value_embedded_offset (v), array, value_embedded_offset (array) + elt_offs, elt_size); } set_value_component_location (v, array); VALUE_REGNUM (v) = VALUE_REGNUM (array); VALUE_FRAME_ID (v) = VALUE_FRAME_ID (array); set_value_offset (v, value_offset (array) + elt_offs); return v; } /* Return the value of BITSTRING[IDX] as (boolean) type TYPE. */ struct value * value_bitstring_subscript (struct type *type, struct value *bitstring, LONGEST index) { struct type *bitstring_type, *range_type; struct value *v; int offset, byte, bit_index; LONGEST lowerbound, upperbound; bitstring_type = check_typedef (value_type (bitstring)); gdb_assert (TYPE_CODE (bitstring_type) == TYPE_CODE_BITSTRING); range_type = TYPE_INDEX_TYPE (bitstring_type); get_discrete_bounds (range_type, &lowerbound, &upperbound); if (index < lowerbound || index > upperbound) error (_("bitstring index out of range")); index -= lowerbound; offset = index / TARGET_CHAR_BIT; byte = *((char *) value_contents (bitstring) + offset); bit_index = index % TARGET_CHAR_BIT; byte >>= (gdbarch_bits_big_endian (get_type_arch (bitstring_type)) ? TARGET_CHAR_BIT - 1 - bit_index : bit_index); v = value_from_longest (type, byte & 1); set_value_bitpos (v, bit_index); set_value_bitsize (v, 1); set_value_component_location (v, bitstring); VALUE_FRAME_ID (v) = VALUE_FRAME_ID (bitstring); set_value_offset (v, offset + value_offset (bitstring)); return v; } /* Check to see if either argument is a structure, or a reference to one. This is called so we know whether to go ahead with the normal binop or look for a user defined function instead. For now, we do not overload the `=' operator. */ int binop_types_user_defined_p (enum exp_opcode op, struct type *type1, struct type *type2) { if (op == BINOP_ASSIGN || op == BINOP_CONCAT) return 0; type1 = check_typedef (type1); if (TYPE_CODE (type1) == TYPE_CODE_REF) type1 = check_typedef (TYPE_TARGET_TYPE (type1)); type2 = check_typedef (type1); if (TYPE_CODE (type2) == TYPE_CODE_REF) type2 = check_typedef (TYPE_TARGET_TYPE (type2)); return (TYPE_CODE (type1) == TYPE_CODE_STRUCT || TYPE_CODE (type2) == TYPE_CODE_STRUCT); } /* Check to see if either argument is a structure, or a reference to one. This is called so we know whether to go ahead with the normal binop or look for a user defined function instead. For now, we do not overload the `=' operator. */ int binop_user_defined_p (enum exp_opcode op, struct value *arg1, struct value *arg2) { return binop_types_user_defined_p (op, value_type (arg1), value_type (arg2)); } /* Check to see if argument is a structure. This is called so we know whether to go ahead with the normal unop or look for a user defined function instead. For now, we do not overload the `&' operator. */ int unop_user_defined_p (enum exp_opcode op, struct value *arg1) { struct type *type1; if (op == UNOP_ADDR) return 0; type1 = check_typedef (value_type (arg1)); if (TYPE_CODE (type1) == TYPE_CODE_REF) type1 = check_typedef (TYPE_TARGET_TYPE (type1)); return TYPE_CODE (type1) == TYPE_CODE_STRUCT; } /* Try to find an operator named OPERATOR which takes NARGS arguments specified in ARGS. If the operator found is a static member operator *STATIC_MEMFUNP will be set to 1, and otherwise 0. The search if performed through find_overload_match which will handle member operators, non member operators, operators imported implicitly or explicitly, and perform correct overload resolution in all of the above situations or combinations thereof. */ static struct value * value_user_defined_cpp_op (struct value **args, int nargs, char *operator, int *static_memfuncp) { struct symbol *symp = NULL; struct value *valp = NULL; find_overload_match (args, nargs, operator, BOTH /* could be method */, 0 /* strict match */, &args[0], /* objp */ NULL /* pass NULL symbol since symbol is unknown */, &valp, &symp, static_memfuncp, 0); if (valp) return valp; if (symp) { /* This is a non member function and does not expect a reference as its first argument rather the explicit structure. */ args[0] = value_ind (args[0]); return value_of_variable (symp, 0); } error (_("Could not find %s."), operator); } /* Lookup user defined operator NAME. Return a value representing the function, otherwise return NULL. */ static struct value * value_user_defined_op (struct value **argp, struct value **args, char *name, int *static_memfuncp, int nargs) { struct value *result = NULL; if (current_language->la_language == language_cplus) result = value_user_defined_cpp_op (args, nargs, name, static_memfuncp); else result = value_struct_elt (argp, args, name, static_memfuncp, "structure"); return result; } /* We know either arg1 or arg2 is a structure, so try to find the right user defined function. Create an argument vector that calls arg1.operator @ (arg1,arg2) and return that value (where '@' is any binary operator which is legal for GNU C++). OP is the operatore, and if it is BINOP_ASSIGN_MODIFY, then OTHEROP is the opcode saying how to modify it. Otherwise, OTHEROP is unused. */ struct value * value_x_binop (struct value *arg1, struct value *arg2, enum exp_opcode op, enum exp_opcode otherop, enum noside noside) { struct value **argvec; char *ptr; char tstr[13]; int static_memfuncp; arg1 = coerce_ref (arg1); arg2 = coerce_ref (arg2); /* now we know that what we have to do is construct our arg vector and find the right function to call it with. */ if (TYPE_CODE (check_typedef (value_type (arg1))) != TYPE_CODE_STRUCT) error (_("Can't do that binary op on that type")); /* FIXME be explicit */ argvec = (struct value **) alloca (sizeof (struct value *) * 4); argvec[1] = value_addr (arg1); argvec[2] = arg2; argvec[3] = 0; /* Make the right function name up. */ strcpy (tstr, "operator__"); ptr = tstr + 8; switch (op) { case BINOP_ADD: strcpy (ptr, "+"); break; case BINOP_SUB: strcpy (ptr, "-"); break; case BINOP_MUL: strcpy (ptr, "*"); break; case BINOP_DIV: strcpy (ptr, "/"); break; case BINOP_REM: strcpy (ptr, "%"); break; case BINOP_LSH: strcpy (ptr, "<<"); break; case BINOP_RSH: strcpy (ptr, ">>"); break; case BINOP_BITWISE_AND: strcpy (ptr, "&"); break; case BINOP_BITWISE_IOR: strcpy (ptr, "|"); break; case BINOP_BITWISE_XOR: strcpy (ptr, "^"); break; case BINOP_LOGICAL_AND: strcpy (ptr, "&&"); break; case BINOP_LOGICAL_OR: strcpy (ptr, "||"); break; case BINOP_MIN: strcpy (ptr, "<?"); break; case BINOP_MAX: strcpy (ptr, ">?"); break; case BINOP_ASSIGN: strcpy (ptr, "="); break; case BINOP_ASSIGN_MODIFY: switch (otherop) { case BINOP_ADD: strcpy (ptr, "+="); break; case BINOP_SUB: strcpy (ptr, "-="); break; case BINOP_MUL: strcpy (ptr, "*="); break; case BINOP_DIV: strcpy (ptr, "/="); break; case BINOP_REM: strcpy (ptr, "%="); break; case BINOP_BITWISE_AND: strcpy (ptr, "&="); break; case BINOP_BITWISE_IOR: strcpy (ptr, "|="); break; case BINOP_BITWISE_XOR: strcpy (ptr, "^="); break; case BINOP_MOD: /* invalid */ default: error (_("Invalid binary operation specified.")); } break; case BINOP_SUBSCRIPT: strcpy (ptr, "[]"); break; case BINOP_EQUAL: strcpy (ptr, "=="); break; case BINOP_NOTEQUAL: strcpy (ptr, "!="); break; case BINOP_LESS: strcpy (ptr, "<"); break; case BINOP_GTR: strcpy (ptr, ">"); break; case BINOP_GEQ: strcpy (ptr, ">="); break; case BINOP_LEQ: strcpy (ptr, "<="); break; case BINOP_MOD: /* invalid */ default: error (_("Invalid binary operation specified.")); } argvec[0] = value_user_defined_op (&arg1, argvec + 1, tstr, &static_memfuncp, 2); if (argvec[0]) { if (static_memfuncp) { argvec[1] = argvec[0]; argvec++; } if (noside == EVAL_AVOID_SIDE_EFFECTS) { struct type *return_type; return_type = TYPE_TARGET_TYPE (check_typedef (value_type (argvec[0]))); return value_zero (return_type, VALUE_LVAL (arg1)); } return call_function_by_hand (argvec[0], 2 - static_memfuncp, argvec + 1); } throw_error (NOT_FOUND_ERROR, _("member function %s not found"), tstr); #ifdef lint return call_function_by_hand (argvec[0], 2 - static_memfuncp, argvec + 1); #endif } /* We know that arg1 is a structure, so try to find a unary user defined operator that matches the operator in question. Create an argument vector that calls arg1.operator @ (arg1) and return that value (where '@' is (almost) any unary operator which is legal for GNU C++). */ struct value * value_x_unop (struct value *arg1, enum exp_opcode op, enum noside noside) { struct gdbarch *gdbarch = get_type_arch (value_type (arg1)); struct value **argvec; char *ptr, *mangle_ptr; char tstr[13], mangle_tstr[13]; int static_memfuncp, nargs; arg1 = coerce_ref (arg1); /* now we know that what we have to do is construct our arg vector and find the right function to call it with. */ if (TYPE_CODE (check_typedef (value_type (arg1))) != TYPE_CODE_STRUCT) error (_("Can't do that unary op on that type")); /* FIXME be explicit */ argvec = (struct value **) alloca (sizeof (struct value *) * 4); argvec[1] = value_addr (arg1); argvec[2] = 0; nargs = 1; /* Make the right function name up. */ strcpy (tstr, "operator__"); ptr = tstr + 8; strcpy (mangle_tstr, "__"); mangle_ptr = mangle_tstr + 2; switch (op) { case UNOP_PREINCREMENT: strcpy (ptr, "++"); break; case UNOP_PREDECREMENT: strcpy (ptr, "--"); break; case UNOP_POSTINCREMENT: strcpy (ptr, "++"); argvec[2] = value_from_longest (builtin_type (gdbarch)->builtin_int, 0); argvec[3] = 0; nargs ++; break; case UNOP_POSTDECREMENT: strcpy (ptr, "--"); argvec[2] = value_from_longest (builtin_type (gdbarch)->builtin_int, 0); argvec[3] = 0; nargs ++; break; case UNOP_LOGICAL_NOT: strcpy (ptr, "!"); break; case UNOP_COMPLEMENT: strcpy (ptr, "~"); break; case UNOP_NEG: strcpy (ptr, "-"); break; case UNOP_PLUS: strcpy (ptr, "+"); break; case UNOP_IND: strcpy (ptr, "*"); break; case STRUCTOP_PTR: strcpy (ptr, "->"); break; default: error (_("Invalid unary operation specified.")); } argvec[0] = value_user_defined_op (&arg1, argvec + 1, tstr, &static_memfuncp, nargs); if (argvec[0]) { if (static_memfuncp) { argvec[1] = argvec[0]; nargs --; argvec++; } if (noside == EVAL_AVOID_SIDE_EFFECTS) { struct type *return_type; return_type = TYPE_TARGET_TYPE (check_typedef (value_type (argvec[0]))); return value_zero (return_type, VALUE_LVAL (arg1)); } return call_function_by_hand (argvec[0], nargs, argvec + 1); } throw_error (NOT_FOUND_ERROR, _("member function %s not found"), tstr); return 0; /* For lint -- never reached */ } /* Concatenate two values with the following conditions: (1) Both values must be either bitstring values or character string values and the resulting value consists of the concatenation of ARG1 followed by ARG2. or One value must be an integer value and the other value must be either a bitstring value or character string value, which is to be repeated by the number of times specified by the integer value. (2) Boolean values are also allowed and are treated as bit string values of length 1. (3) Character values are also allowed and are treated as character string values of length 1. */ struct value * value_concat (struct value *arg1, struct value *arg2) { struct value *inval1; struct value *inval2; struct value *outval = NULL; int inval1len, inval2len; int count, idx; char *ptr; char inchar; struct type *type1 = check_typedef (value_type (arg1)); struct type *type2 = check_typedef (value_type (arg2)); struct type *char_type; /* First figure out if we are dealing with two values to be concatenated or a repeat count and a value to be repeated. INVAL1 is set to the first of two concatenated values, or the repeat count. INVAL2 is set to the second of the two concatenated values or the value to be repeated. */ if (TYPE_CODE (type2) == TYPE_CODE_INT) { struct type *tmp = type1; type1 = tmp; tmp = type2; inval1 = arg2; inval2 = arg1; } else { inval1 = arg1; inval2 = arg2; } /* Now process the input values. */ if (TYPE_CODE (type1) == TYPE_CODE_INT) { /* We have a repeat count. Validate the second value and then construct a value repeated that many times. */ if (TYPE_CODE (type2) == TYPE_CODE_STRING || TYPE_CODE (type2) == TYPE_CODE_CHAR) { count = longest_to_int (value_as_long (inval1)); inval2len = TYPE_LENGTH (type2); ptr = (char *) alloca (count * inval2len); if (TYPE_CODE (type2) == TYPE_CODE_CHAR) { char_type = type2; inchar = (char) unpack_long (type2, value_contents (inval2)); for (idx = 0; idx < count; idx++) { *(ptr + idx) = inchar; } } else { char_type = TYPE_TARGET_TYPE (type2); for (idx = 0; idx < count; idx++) { memcpy (ptr + (idx * inval2len), value_contents (inval2), inval2len); } } outval = value_string (ptr, count * inval2len, char_type); } else if (TYPE_CODE (type2) == TYPE_CODE_BITSTRING || TYPE_CODE (type2) == TYPE_CODE_BOOL) { error (_("unimplemented support for bitstring/boolean repeats")); } else { error (_("can't repeat values of that type")); } } else if (TYPE_CODE (type1) == TYPE_CODE_STRING || TYPE_CODE (type1) == TYPE_CODE_CHAR) { /* We have two character strings to concatenate. */ if (TYPE_CODE (type2) != TYPE_CODE_STRING && TYPE_CODE (type2) != TYPE_CODE_CHAR) { error (_("Strings can only be concatenated with other strings.")); } inval1len = TYPE_LENGTH (type1); inval2len = TYPE_LENGTH (type2); ptr = (char *) alloca (inval1len + inval2len); if (TYPE_CODE (type1) == TYPE_CODE_CHAR) { char_type = type1; *ptr = (char) unpack_long (type1, value_contents (inval1)); } else { char_type = TYPE_TARGET_TYPE (type1); memcpy (ptr, value_contents (inval1), inval1len); } if (TYPE_CODE (type2) == TYPE_CODE_CHAR) { *(ptr + inval1len) = (char) unpack_long (type2, value_contents (inval2)); } else { memcpy (ptr + inval1len, value_contents (inval2), inval2len); } outval = value_string (ptr, inval1len + inval2len, char_type); } else if (TYPE_CODE (type1) == TYPE_CODE_BITSTRING || TYPE_CODE (type1) == TYPE_CODE_BOOL) { /* We have two bitstrings to concatenate. */ if (TYPE_CODE (type2) != TYPE_CODE_BITSTRING && TYPE_CODE (type2) != TYPE_CODE_BOOL) { error (_("Bitstrings or booleans can only be concatenated " "with other bitstrings or booleans.")); } error (_("unimplemented support for bitstring/boolean concatenation.")); } else { /* We don't know how to concatenate these operands. */ error (_("illegal operands for concatenation.")); } return (outval); } /* Integer exponentiation: V1**V2, where both arguments are integers. Requires V1 != 0 if V2 < 0. Returns 1 for 0 ** 0. */ static LONGEST integer_pow (LONGEST v1, LONGEST v2) { if (v2 < 0) { if (v1 == 0) error (_("Attempt to raise 0 to negative power.")); else return 0; } else { /* The Russian Peasant's Algorithm. */ LONGEST v; v = 1; for (;;) { if (v2 & 1L) v *= v1; v2 >>= 1; if (v2 == 0) return v; v1 *= v1; } } } /* Integer exponentiation: V1**V2, where both arguments are integers. Requires V1 != 0 if V2 < 0. Returns 1 for 0 ** 0. */ static ULONGEST uinteger_pow (ULONGEST v1, LONGEST v2) { if (v2 < 0) { if (v1 == 0) error (_("Attempt to raise 0 to negative power.")); else return 0; } else { /* The Russian Peasant's Algorithm. */ ULONGEST v; v = 1; for (;;) { if (v2 & 1L) v *= v1; v2 >>= 1; if (v2 == 0) return v; v1 *= v1; } } } /* Obtain decimal value of arguments for binary operation, converting from other types if one of them is not decimal floating point. */ static void value_args_as_decimal (struct value *arg1, struct value *arg2, gdb_byte *x, int *len_x, enum bfd_endian *byte_order_x, gdb_byte *y, int *len_y, enum bfd_endian *byte_order_y) { struct type *type1, *type2; type1 = check_typedef (value_type (arg1)); type2 = check_typedef (value_type (arg2)); /* At least one of the arguments must be of decimal float type. */ gdb_assert (TYPE_CODE (type1) == TYPE_CODE_DECFLOAT || TYPE_CODE (type2) == TYPE_CODE_DECFLOAT); if (TYPE_CODE (type1) == TYPE_CODE_FLT || TYPE_CODE (type2) == TYPE_CODE_FLT) /* The DFP extension to the C language does not allow mixing of * decimal float types with other float types in expressions * (see WDTR 24732, page 12). */ error (_("Mixing decimal floating types with " "other floating types is not allowed.")); /* Obtain decimal value of arg1, converting from other types if necessary. */ if (TYPE_CODE (type1) == TYPE_CODE_DECFLOAT) { *byte_order_x = gdbarch_byte_order (get_type_arch (type1)); *len_x = TYPE_LENGTH (type1); memcpy (x, value_contents (arg1), *len_x); } else if (is_integral_type (type1)) { *byte_order_x = gdbarch_byte_order (get_type_arch (type2)); *len_x = TYPE_LENGTH (type2); decimal_from_integral (arg1, x, *len_x, *byte_order_x); } else error (_("Don't know how to convert from %s to %s."), TYPE_NAME (type1), TYPE_NAME (type2)); /* Obtain decimal value of arg2, converting from other types if necessary. */ if (TYPE_CODE (type2) == TYPE_CODE_DECFLOAT) { *byte_order_y = gdbarch_byte_order (get_type_arch (type2)); *len_y = TYPE_LENGTH (type2); memcpy (y, value_contents (arg2), *len_y); } else if (is_integral_type (type2)) { *byte_order_y = gdbarch_byte_order (get_type_arch (type1)); *len_y = TYPE_LENGTH (type1); decimal_from_integral (arg2, y, *len_y, *byte_order_y); } else error (_("Don't know how to convert from %s to %s."), TYPE_NAME (type1), TYPE_NAME (type2)); } /* Perform a binary operation on two operands which have reasonable representations as integers or floats. This includes booleans, characters, integers, or floats. Does not support addition and subtraction on pointers; use value_ptradd, value_ptrsub or value_ptrdiff for those operations. */ static struct value * scalar_binop (struct value *arg1, struct value *arg2, enum exp_opcode op) { struct value *val; struct type *type1, *type2, *result_type; arg1 = coerce_ref (arg1); arg2 = coerce_ref (arg2); type1 = check_typedef (value_type (arg1)); type2 = check_typedef (value_type (arg2)); if ((TYPE_CODE (type1) != TYPE_CODE_FLT && TYPE_CODE (type1) != TYPE_CODE_DECFLOAT && !is_integral_type (type1)) || (TYPE_CODE (type2) != TYPE_CODE_FLT && TYPE_CODE (type2) != TYPE_CODE_DECFLOAT && !is_integral_type (type2))) error (_("Argument to arithmetic operation not a number or boolean.")); if (TYPE_CODE (type1) == TYPE_CODE_DECFLOAT || TYPE_CODE (type2) == TYPE_CODE_DECFLOAT) { int len_v1, len_v2, len_v; enum bfd_endian byte_order_v1, byte_order_v2, byte_order_v; gdb_byte v1[16], v2[16]; gdb_byte v[16]; /* If only one type is decimal float, use its type. Otherwise use the bigger type. */ if (TYPE_CODE (type1) != TYPE_CODE_DECFLOAT) result_type = type2; else if (TYPE_CODE (type2) != TYPE_CODE_DECFLOAT) result_type = type1; else if (TYPE_LENGTH (type2) > TYPE_LENGTH (type1)) result_type = type2; else result_type = type1; len_v = TYPE_LENGTH (result_type); byte_order_v = gdbarch_byte_order (get_type_arch (result_type)); value_args_as_decimal (arg1, arg2, v1, &len_v1, &byte_order_v1, v2, &len_v2, &byte_order_v2); switch (op) { case BINOP_ADD: case BINOP_SUB: case BINOP_MUL: case BINOP_DIV: case BINOP_EXP: decimal_binop (op, v1, len_v1, byte_order_v1, v2, len_v2, byte_order_v2, v, len_v, byte_order_v); break; default: error (_("Operation not valid for decimal floating point number.")); } val = value_from_decfloat (result_type, v); } else if (TYPE_CODE (type1) == TYPE_CODE_FLT || TYPE_CODE (type2) == TYPE_CODE_FLT) { /* FIXME-if-picky-about-floating-accuracy: Should be doing this in target format. real.c in GCC probably has the necessary code. */ DOUBLEST v1, v2, v = 0; v1 = value_as_double (arg1); v2 = value_as_double (arg2); switch (op) { case BINOP_ADD: v = v1 + v2; break; case BINOP_SUB: v = v1 - v2; break; case BINOP_MUL: v = v1 * v2; break; case BINOP_DIV: v = v1 / v2; break; case BINOP_EXP: errno = 0; v = pow (v1, v2); if (errno) error (_("Cannot perform exponentiation: %s"), safe_strerror (errno)); break; case BINOP_MIN: v = v1 < v2 ? v1 : v2; break; case BINOP_MAX: v = v1 > v2 ? v1 : v2; break; default: error (_("Integer-only operation on floating point number.")); } /* If only one type is float, use its type. Otherwise use the bigger type. */ if (TYPE_CODE (type1) != TYPE_CODE_FLT) result_type = type2; else if (TYPE_CODE (type2) != TYPE_CODE_FLT) result_type = type1; else if (TYPE_LENGTH (type2) > TYPE_LENGTH (type1)) result_type = type2; else result_type = type1; val = allocate_value (result_type); store_typed_floating (value_contents_raw (val), value_type (val), v); } else if (TYPE_CODE (type1) == TYPE_CODE_BOOL || TYPE_CODE (type2) == TYPE_CODE_BOOL) { LONGEST v1, v2, v = 0; v1 = value_as_long (arg1); v2 = value_as_long (arg2); switch (op) { case BINOP_BITWISE_AND: v = v1 & v2; break; case BINOP_BITWISE_IOR: v = v1 | v2; break; case BINOP_BITWISE_XOR: v = v1 ^ v2; break; case BINOP_EQUAL: v = v1 == v2; break; case BINOP_NOTEQUAL: v = v1 != v2; break; default: error (_("Invalid operation on booleans.")); } result_type = type1; val = allocate_value (result_type); store_signed_integer (value_contents_raw (val), TYPE_LENGTH (result_type), gdbarch_byte_order (get_type_arch (result_type)), v); } else /* Integral operations here. */ { /* Determine type length of the result, and if the operation should be done unsigned. For exponentiation and shift operators, use the length and type of the left operand. Otherwise, use the signedness of the operand with the greater length. If both operands are of equal length, use unsigned operation if one of the operands is unsigned. */ if (op == BINOP_RSH || op == BINOP_LSH || op == BINOP_EXP) result_type = type1; else if (TYPE_LENGTH (type1) > TYPE_LENGTH (type2)) result_type = type1; else if (TYPE_LENGTH (type2) > TYPE_LENGTH (type1)) result_type = type2; else if (TYPE_UNSIGNED (type1)) result_type = type1; else if (TYPE_UNSIGNED (type2)) result_type = type2; else result_type = type1; if (TYPE_UNSIGNED (result_type)) { LONGEST v2_signed = value_as_long (arg2); ULONGEST v1, v2, v = 0; v1 = (ULONGEST) value_as_long (arg1); v2 = (ULONGEST) v2_signed; switch (op) { case BINOP_ADD: v = v1 + v2; break; case BINOP_SUB: v = v1 - v2; break; case BINOP_MUL: v = v1 * v2; break; case BINOP_DIV: case BINOP_INTDIV: if (v2 != 0) v = v1 / v2; else error (_("Division by zero")); break; case BINOP_EXP: v = uinteger_pow (v1, v2_signed); break; case BINOP_REM: if (v2 != 0) v = v1 % v2; else error (_("Division by zero")); break; case BINOP_MOD: /* Knuth 1.2.4, integer only. Note that unlike the C '%' op, v1 mod 0 has a defined value, v1. */ if (v2 == 0) { v = v1; } else { v = v1 / v2; /* Note floor(v1/v2) == v1/v2 for unsigned. */ v = v1 - (v2 * v); } break; case BINOP_LSH: v = v1 << v2; break; case BINOP_RSH: v = v1 >> v2; break; case BINOP_BITWISE_AND: v = v1 & v2; break; case BINOP_BITWISE_IOR: v = v1 | v2; break; case BINOP_BITWISE_XOR: v = v1 ^ v2; break; case BINOP_LOGICAL_AND: v = v1 && v2; break; case BINOP_LOGICAL_OR: v = v1 || v2; break; case BINOP_MIN: v = v1 < v2 ? v1 : v2; break; case BINOP_MAX: v = v1 > v2 ? v1 : v2; break; case BINOP_EQUAL: v = v1 == v2; break; case BINOP_NOTEQUAL: v = v1 != v2; break; case BINOP_LESS: v = v1 < v2; break; case BINOP_GTR: v = v1 > v2; break; case BINOP_LEQ: v = v1 <= v2; break; case BINOP_GEQ: v = v1 >= v2; break; default: error (_("Invalid binary operation on numbers.")); } val = allocate_value (result_type); store_unsigned_integer (value_contents_raw (val), TYPE_LENGTH (value_type (val)), gdbarch_byte_order (get_type_arch (result_type)), v); } else { LONGEST v1, v2, v = 0; v1 = value_as_long (arg1); v2 = value_as_long (arg2); switch (op) { case BINOP_ADD: v = v1 + v2; break; case BINOP_SUB: v = v1 - v2; break; case BINOP_MUL: v = v1 * v2; break; case BINOP_DIV: case BINOP_INTDIV: if (v2 != 0) v = v1 / v2; else error (_("Division by zero")); break; case BINOP_EXP: v = integer_pow (v1, v2); break; case BINOP_REM: if (v2 != 0) v = v1 % v2; else error (_("Division by zero")); break; case BINOP_MOD: /* Knuth 1.2.4, integer only. Note that unlike the C '%' op, X mod 0 has a defined value, X. */ if (v2 == 0) { v = v1; } else { v = v1 / v2; /* Compute floor. */ if (TRUNCATION_TOWARDS_ZERO && (v < 0) && ((v1 % v2) != 0)) { v--; } v = v1 - (v2 * v); } break; case BINOP_LSH: v = v1 << v2; break; case BINOP_RSH: v = v1 >> v2; break; case BINOP_BITWISE_AND: v = v1 & v2; break; case BINOP_BITWISE_IOR: v = v1 | v2; break; case BINOP_BITWISE_XOR: v = v1 ^ v2; break; case BINOP_LOGICAL_AND: v = v1 && v2; break; case BINOP_LOGICAL_OR: v = v1 || v2; break; case BINOP_MIN: v = v1 < v2 ? v1 : v2; break; case BINOP_MAX: v = v1 > v2 ? v1 : v2; break; case BINOP_EQUAL: v = v1 == v2; break; case BINOP_NOTEQUAL: v = v1 != v2; break; case BINOP_LESS: v = v1 < v2; break; case BINOP_GTR: v = v1 > v2; break; case BINOP_LEQ: v = v1 <= v2; break; case BINOP_GEQ: v = v1 >= v2; break; default: error (_("Invalid binary operation on numbers.")); } val = allocate_value (result_type); store_signed_integer (value_contents_raw (val), TYPE_LENGTH (value_type (val)), gdbarch_byte_order (get_type_arch (result_type)), v); } } return val; } /* Performs a binary operation on two vector operands by calling scalar_binop for each pair of vector components. */ static struct value * vector_binop (struct value *val1, struct value *val2, enum exp_opcode op) { struct value *val, *tmp, *mark; struct type *type1, *type2, *eltype1, *eltype2, *result_type; int t1_is_vec, t2_is_vec, elsize, i; LONGEST low_bound1, high_bound1, low_bound2, high_bound2; type1 = check_typedef (value_type (val1)); type2 = check_typedef (value_type (val2)); t1_is_vec = (TYPE_CODE (type1) == TYPE_CODE_ARRAY && TYPE_VECTOR (type1)) ? 1 : 0; t2_is_vec = (TYPE_CODE (type2) == TYPE_CODE_ARRAY && TYPE_VECTOR (type2)) ? 1 : 0; if (!t1_is_vec || !t2_is_vec) error (_("Vector operations are only supported among vectors")); if (!get_array_bounds (type1, &low_bound1, &high_bound1) || !get_array_bounds (type2, &low_bound2, &high_bound2)) error (_("Could not determine the vector bounds")); eltype1 = check_typedef (TYPE_TARGET_TYPE (type1)); eltype2 = check_typedef (TYPE_TARGET_TYPE (type2)); elsize = TYPE_LENGTH (eltype1); if (TYPE_CODE (eltype1) != TYPE_CODE (eltype2) || elsize != TYPE_LENGTH (eltype2) || TYPE_UNSIGNED (eltype1) != TYPE_UNSIGNED (eltype2) || low_bound1 != low_bound2 || high_bound1 != high_bound2) error (_("Cannot perform operation on vectors with different types")); val = allocate_value (type1); mark = value_mark (); for (i = 0; i < high_bound1 - low_bound1 + 1; i++) { tmp = value_binop (value_subscript (val1, i), value_subscript (val2, i), op); memcpy (value_contents_writeable (val) + i * elsize, value_contents_all (tmp), elsize); } value_free_to_mark (mark); return val; } /* Perform a binary operation on two operands. */ struct value * value_binop (struct value *arg1, struct value *arg2, enum exp_opcode op) { struct value *val; struct type *type1 = check_typedef (value_type (arg1)); struct type *type2 = check_typedef (value_type (arg2)); int t1_is_vec = (TYPE_CODE (type1) == TYPE_CODE_ARRAY && TYPE_VECTOR (type1)); int t2_is_vec = (TYPE_CODE (type2) == TYPE_CODE_ARRAY && TYPE_VECTOR (type2)); if (!t1_is_vec && !t2_is_vec) val = scalar_binop (arg1, arg2, op); else if (t1_is_vec && t2_is_vec) val = vector_binop (arg1, arg2, op); else { /* Widen the scalar operand to a vector. */ struct value **v = t1_is_vec ? &arg2 : &arg1; struct type *t = t1_is_vec ? type2 : type1; if (TYPE_CODE (t) != TYPE_CODE_FLT && TYPE_CODE (t) != TYPE_CODE_DECFLOAT && !is_integral_type (t)) error (_("Argument to operation not a number or boolean.")); *v = value_cast (t1_is_vec ? type1 : type2, *v); val = vector_binop (arg1, arg2, op); } return val; } /* Simulate the C operator ! -- return 1 if ARG1 contains zero. */ int value_logical_not (struct value *arg1) { int len; const gdb_byte *p; struct type *type1; arg1 = coerce_array (arg1); type1 = check_typedef (value_type (arg1)); if (TYPE_CODE (type1) == TYPE_CODE_FLT) return 0 == value_as_double (arg1); else if (TYPE_CODE (type1) == TYPE_CODE_DECFLOAT) return decimal_is_zero (value_contents (arg1), TYPE_LENGTH (type1), gdbarch_byte_order (get_type_arch (type1))); len = TYPE_LENGTH (type1); p = value_contents (arg1); while (--len >= 0) { if (*p++) break; } return len < 0; } /* Perform a comparison on two string values (whose content are not necessarily null terminated) based on their length. */ static int value_strcmp (struct value *arg1, struct value *arg2) { int len1 = TYPE_LENGTH (value_type (arg1)); int len2 = TYPE_LENGTH (value_type (arg2)); const gdb_byte *s1 = value_contents (arg1); const gdb_byte *s2 = value_contents (arg2); int i, len = len1 < len2 ? len1 : len2; for (i = 0; i < len; i++) { if (s1[i] < s2[i]) return -1; else if (s1[i] > s2[i]) return 1; else continue; } if (len1 < len2) return -1; else if (len1 > len2) return 1; else return 0; } /* Simulate the C operator == by returning a 1 iff ARG1 and ARG2 have equal contents. */ int value_equal (struct value *arg1, struct value *arg2) { int len; const gdb_byte *p1; const gdb_byte *p2; struct type *type1, *type2; enum type_code code1; enum type_code code2; int is_int1, is_int2; arg1 = coerce_array (arg1); arg2 = coerce_array (arg2); type1 = check_typedef (value_type (arg1)); type2 = check_typedef (value_type (arg2)); code1 = TYPE_CODE (type1); code2 = TYPE_CODE (type2); is_int1 = is_integral_type (type1); is_int2 = is_integral_type (type2); if (is_int1 && is_int2) return longest_to_int (value_as_long (value_binop (arg1, arg2, BINOP_EQUAL))); else if ((code1 == TYPE_CODE_FLT || is_int1) && (code2 == TYPE_CODE_FLT || is_int2)) { /* NOTE: kettenis/20050816: Avoid compiler bug on systems where `long double' values are returned in static storage (m68k). */ DOUBLEST d = value_as_double (arg1); return d == value_as_double (arg2); } else if ((code1 == TYPE_CODE_DECFLOAT || is_int1) && (code2 == TYPE_CODE_DECFLOAT || is_int2)) { gdb_byte v1[16], v2[16]; int len_v1, len_v2; enum bfd_endian byte_order_v1, byte_order_v2; value_args_as_decimal (arg1, arg2, v1, &len_v1, &byte_order_v1, v2, &len_v2, &byte_order_v2); return decimal_compare (v1, len_v1, byte_order_v1, v2, len_v2, byte_order_v2) == 0; } /* FIXME: Need to promote to either CORE_ADDR or LONGEST, whichever is bigger. */ else if (code1 == TYPE_CODE_PTR && is_int2) return value_as_address (arg1) == (CORE_ADDR) value_as_long (arg2); else if (code2 == TYPE_CODE_PTR && is_int1) return (CORE_ADDR) value_as_long (arg1) == value_as_address (arg2); else if (code1 == code2 && ((len = (int) TYPE_LENGTH (type1)) == (int) TYPE_LENGTH (type2))) { p1 = value_contents (arg1); p2 = value_contents (arg2); while (--len >= 0) { if (*p1++ != *p2++) break; } return len < 0; } else if (code1 == TYPE_CODE_STRING && code2 == TYPE_CODE_STRING) { return value_strcmp (arg1, arg2) == 0; } else { error (_("Invalid type combination in equality test.")); return 0; /* For lint -- never reached. */ } } /* Compare values based on their raw contents. Useful for arrays since value_equal coerces them to pointers, thus comparing just the address of the array instead of its contents. */ int value_equal_contents (struct value *arg1, struct value *arg2) { struct type *type1, *type2; type1 = check_typedef (value_type (arg1)); type2 = check_typedef (value_type (arg2)); return (TYPE_CODE (type1) == TYPE_CODE (type2) && TYPE_LENGTH (type1) == TYPE_LENGTH (type2) && memcmp (value_contents (arg1), value_contents (arg2), TYPE_LENGTH (type1)) == 0); } /* Simulate the C operator < by returning 1 iff ARG1's contents are less than ARG2's. */ int value_less (struct value *arg1, struct value *arg2) { enum type_code code1; enum type_code code2; struct type *type1, *type2; int is_int1, is_int2; arg1 = coerce_array (arg1); arg2 = coerce_array (arg2); type1 = check_typedef (value_type (arg1)); type2 = check_typedef (value_type (arg2)); code1 = TYPE_CODE (type1); code2 = TYPE_CODE (type2); is_int1 = is_integral_type (type1); is_int2 = is_integral_type (type2); if (is_int1 && is_int2) return longest_to_int (value_as_long (value_binop (arg1, arg2, BINOP_LESS))); else if ((code1 == TYPE_CODE_FLT || is_int1) && (code2 == TYPE_CODE_FLT || is_int2)) { /* NOTE: kettenis/20050816: Avoid compiler bug on systems where `long double' values are returned in static storage (m68k). */ DOUBLEST d = value_as_double (arg1); return d < value_as_double (arg2); } else if ((code1 == TYPE_CODE_DECFLOAT || is_int1) && (code2 == TYPE_CODE_DECFLOAT || is_int2)) { gdb_byte v1[16], v2[16]; int len_v1, len_v2; enum bfd_endian byte_order_v1, byte_order_v2; value_args_as_decimal (arg1, arg2, v1, &len_v1, &byte_order_v1, v2, &len_v2, &byte_order_v2); return decimal_compare (v1, len_v1, byte_order_v1, v2, len_v2, byte_order_v2) == -1; } else if (code1 == TYPE_CODE_PTR && code2 == TYPE_CODE_PTR) return value_as_address (arg1) < value_as_address (arg2); /* FIXME: Need to promote to either CORE_ADDR or LONGEST, whichever is bigger. */ else if (code1 == TYPE_CODE_PTR && is_int2) return value_as_address (arg1) < (CORE_ADDR) value_as_long (arg2); else if (code2 == TYPE_CODE_PTR && is_int1) return (CORE_ADDR) value_as_long (arg1) < value_as_address (arg2); else if (code1 == TYPE_CODE_STRING && code2 == TYPE_CODE_STRING) return value_strcmp (arg1, arg2) < 0; else { error (_("Invalid type combination in ordering comparison.")); return 0; } } /* The unary operators +, - and ~. They free the argument ARG1. */ struct value * value_pos (struct value *arg1) { struct type *type; arg1 = coerce_ref (arg1); type = check_typedef (value_type (arg1)); if (TYPE_CODE (type) == TYPE_CODE_FLT) return value_from_double (type, value_as_double (arg1)); else if (TYPE_CODE (type) == TYPE_CODE_DECFLOAT) return value_from_decfloat (type, value_contents (arg1)); else if (is_integral_type (type)) { return value_from_longest (type, value_as_long (arg1)); } else if (TYPE_CODE (type) == TYPE_CODE_ARRAY && TYPE_VECTOR (type)) { struct value *val = allocate_value (type); memcpy (value_contents_raw (val), value_contents (arg1), TYPE_LENGTH (type)); return val; } else { error (_("Argument to positive operation not a number.")); return 0; /* For lint -- never reached. */ } } struct value * value_neg (struct value *arg1) { struct type *type; arg1 = coerce_ref (arg1); type = check_typedef (value_type (arg1)); if (TYPE_CODE (type) == TYPE_CODE_DECFLOAT) { struct value *val = allocate_value (type); int len = TYPE_LENGTH (type); gdb_byte decbytes[16]; /* a decfloat is at most 128 bits long. */ memcpy (decbytes, value_contents (arg1), len); if (gdbarch_byte_order (get_type_arch (type)) == BFD_ENDIAN_LITTLE) decbytes[len-1] = decbytes[len - 1] | 0x80; else decbytes[0] = decbytes[0] | 0x80; memcpy (value_contents_raw (val), decbytes, len); return val; } else if (TYPE_CODE (type) == TYPE_CODE_FLT) return value_from_double (type, -value_as_double (arg1)); else if (is_integral_type (type)) { return value_from_longest (type, -value_as_long (arg1)); } else if (TYPE_CODE (type) == TYPE_CODE_ARRAY && TYPE_VECTOR (type)) { struct value *tmp, *val = allocate_value (type); struct type *eltype = check_typedef (TYPE_TARGET_TYPE (type)); int i; LONGEST low_bound, high_bound; if (!get_array_bounds (type, &low_bound, &high_bound)) error (_("Could not determine the vector bounds")); for (i = 0; i < high_bound - low_bound + 1; i++) { tmp = value_neg (value_subscript (arg1, i)); memcpy (value_contents_writeable (val) + i * TYPE_LENGTH (eltype), value_contents_all (tmp), TYPE_LENGTH (eltype)); } return val; } else { error (_("Argument to negate operation not a number.")); return 0; /* For lint -- never reached. */ } } struct value * value_complement (struct value *arg1) { struct type *type; struct value *val; arg1 = coerce_ref (arg1); type = check_typedef (value_type (arg1)); if (is_integral_type (type)) val = value_from_longest (type, ~value_as_long (arg1)); else if (TYPE_CODE (type) == TYPE_CODE_ARRAY && TYPE_VECTOR (type)) { struct value *tmp; struct type *eltype = check_typedef (TYPE_TARGET_TYPE (type)); int i; LONGEST low_bound, high_bound; if (!get_array_bounds (type, &low_bound, &high_bound)) error (_("Could not determine the vector bounds")); val = allocate_value (type); for (i = 0; i < high_bound - low_bound + 1; i++) { tmp = value_complement (value_subscript (arg1, i)); memcpy (value_contents_writeable (val) + i * TYPE_LENGTH (eltype), value_contents_all (tmp), TYPE_LENGTH (eltype)); } } else error (_("Argument to complement operation not an integer, boolean.")); return val; } /* The INDEX'th bit of SET value whose value_type is TYPE, and whose value_contents is valaddr. Return -1 if out of range, -2 other error. */ int value_bit_index (struct type *type, const gdb_byte *valaddr, int index) { struct gdbarch *gdbarch = get_type_arch (type); LONGEST low_bound, high_bound; LONGEST word; unsigned rel_index; struct type *range = TYPE_INDEX_TYPE (type); if (get_discrete_bounds (range, &low_bound, &high_bound) < 0) return -2; if (index < low_bound || index > high_bound) return -1; rel_index = index - low_bound; word = extract_unsigned_integer (valaddr + (rel_index / TARGET_CHAR_BIT), 1, gdbarch_byte_order (gdbarch)); rel_index %= TARGET_CHAR_BIT; if (gdbarch_bits_big_endian (gdbarch)) rel_index = TARGET_CHAR_BIT - 1 - rel_index; return (word >> rel_index) & 1; } int value_in (struct value *element, struct value *set) { int member; struct type *settype = check_typedef (value_type (set)); struct type *eltype = check_typedef (value_type (element)); if (TYPE_CODE (eltype) == TYPE_CODE_RANGE) eltype = TYPE_TARGET_TYPE (eltype); if (TYPE_CODE (settype) != TYPE_CODE_SET) error (_("Second argument of 'IN' has wrong type")); if (TYPE_CODE (eltype) != TYPE_CODE_INT && TYPE_CODE (eltype) != TYPE_CODE_CHAR && TYPE_CODE (eltype) != TYPE_CODE_ENUM && TYPE_CODE (eltype) != TYPE_CODE_BOOL) error (_("First argument of 'IN' has wrong type")); member = value_bit_index (settype, value_contents (set), value_as_long (element)); if (member < 0) error (_("First argument of 'IN' not in range")); return member; } void _initialize_valarith (void) { }
adapteva/epiphany-gdb
gdb/valarith.c
C
gpl-2.0
50,180
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="refresh" content="0;URL=../../../../../../libc/constant.PTRACE_SETFPXREGS.html"> </head> <body> <p>Redirecting to <a href="../../../../../../libc/constant.PTRACE_SETFPXREGS.html">../../../../../../libc/constant.PTRACE_SETFPXREGS.html</a>...</p> <script>location.replace("../../../../../../libc/constant.PTRACE_SETFPXREGS.html" + location.search + location.hash);</script> </body> </html>
TheZoq2/Rust-Scad
docs/doc/libc/unix/notbsd/other/b64/x86_64/constant.PTRACE_SETFPXREGS.html
HTML
gpl-2.0
457
/* * Copyright 2006-2015 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 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. * * MZmine 2 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 * MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin * St, Fifth Floor, Boston, MA 02110-1301 USA */ package net.sf.mzmine.modules.peaklistmethods.io.csvexport; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import net.sf.mzmine.datamodel.PeakIdentity; import net.sf.mzmine.datamodel.PeakList; import net.sf.mzmine.datamodel.PeakListRow; import net.sf.mzmine.main.MZmineCore; import net.sf.mzmine.parameters.parametertypes.MultiChoiceComponent; import net.sf.mzmine.parameters.parametertypes.MultiChoiceParameter; /** * Simple Parameter implementation * * */ public class IdentityItemsParameter extends MultiChoiceParameter<String> { public static final String ALL_IDENTITIES = "All identity elements"; public IdentityItemsParameter() { super("Export identity elements", "Selection of identities to export", new String[] { ALL_IDENTITIES }); } @Override public MultiChoiceComponent createEditingComponent() { HashSet<String> elements = new HashSet<String>(); elements.add(ALL_IDENTITIES); for (PeakList peakList : MZmineCore.getProjectManager() .getCurrentProject().getPeakLists()) { for (PeakListRow peakListRow : peakList.getRows()) { PeakIdentity peakIdentity = peakListRow .getPreferredPeakIdentity(); if (peakIdentity != null) { Map<String, String> properties = peakIdentity .getAllProperties(); Iterator<String> subItr = properties.keySet().iterator(); while (subItr.hasNext()) { String propertyName = subItr.next(); if (!elements.contains(propertyName)) { elements.add(propertyName); } } } } } String identityElements[] = elements.toArray(new String[0]); Arrays.sort(identityElements); setChoices(identityElements); return super.createEditingComponent(); } @Override public IdentityItemsParameter cloneParameter() { IdentityItemsParameter copy = new IdentityItemsParameter(); copy.setChoices(this.getChoices()); copy.setValue(this.getValue()); return copy; } }
Veritomyx/mzmine2
src/main/java/net/sf/mzmine/modules/peaklistmethods/io/csvexport/IdentityItemsParameter.java
Java
gpl-2.0
2,766
--CARLOS RAMIREZ alter table npexplab add column montopres numeric(14,2);
cidesa/roraima
varios/script/datamodel/produccion/2009/06-junio/10-mie.sql
SQL
gpl-2.0
75
// This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * JavaScript library for the getkey stat. * * @package local * @subpackage getkey * @copyright 2014 onwards Pinky sharma {@link http://vidyamantra.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ var Y_RANGE = 4; var M_RANGE = 5; var D_RANGE = 6; var cfg = { 'url':"https://c.vidya.io", 'lKey' : '', 'sDate' : '', 'eDate' : '' } var getkey_stat = {}; function getkey_stat_init(Y,param) { cfg.lKey = param; var year = dateFunction('year'); var month = dateFunction('month'); var preMonth = dateFunction('premonth'); var day = dateFunction('day'); var context = M.getkey_stat_init; this.Y = Y; Y.one('#id_day_stat').on('click', function() { hightlightButton(Y,'#id_day_stat'); updateData(day.st, day.ed, D_RANGE) } ); Y.one('#id_currmonth_stat').on('click', function() { hightlightButton(Y,'#id_currmonth_stat'); updateData(month.st, month.ed, M_RANGE) } ); Y.one('#id_premonth_stat').on('click', function() { hightlightButton(Y,'#id_premonth_stat'); updateData(preMonth.st, preMonth.ed, M_RANGE) } ); Y.one('#id_year_stat').on('click', function() { hightlightButton(Y,'#id_year_stat'); updateData(year.st, year.ed, Y_RANGE) } ); if(document.getElementById("msggraph").innerHTML == ""){ hightlightButton(Y,'#id_year_stat'); updateData(year.st, year.ed, Y_RANGE); } } // Highlight button function hightlightButton(Y,btn){ Y.all("#option input[type=button]").removeClass('btnhighlight'); Y.one(btn).addClass("btnhighlight"); } function updateData(sDate,eDate,range) { cfg.sDate = sDate; cfg.eDate = eDate; cfg.range = range; // Load json data for messages d3.jsonp(cfg.url+"?callback={callback}&name=msg&lkey="+cfg.lKey+"&region[st]="+cfg.sDate+"&region[et]="+cfg.eDate+"&range="+cfg.range, function(jdata) { //console.log(jdata); if(jdata !== 'NoData'){ var gData = []; var data = {}; jdata.forEach(function(d) { if(cfg.range > Y_RANGE){ var newDate = toTimestamp(d.key[1],d.key[2],d.key[3],d.key[4],d.key[5]);//60 }else{ var newDate = toTimestamp(d.key[1],d.key[2],d.key[3],d.key[4]);//3600 } gData.push({ value: d.value, date: newDate }); }); document.getElementById("msggraph").innerHTML = ""; if(cfg.range > Y_RANGE){ var dataScale = scaleLimit(jdata,cfg.range);//console.log(dataScale); data = mergeByProperty(dataScale, gData, 'date');//console.log(data); }else{ data = gData; } var margin = {top: 10, right: 10, bottom: 100, left: 50}; var margin2 = {top: 430, right: 10, bottom: 22, left: 50}; mgraphObj = clone(graphObj); //console.log('msg '+data); mgraphObj.init(cfg,data,"#msggraph",margin,margin2,"m"); msgGraph(data); }else{ document.getElementById('msggraph').innerHTML = M.util.get_string('nodata','local_getkey','message'); } }) // Load json data for users d3.jsonp(cfg.url+"?callback={callback}&name=users&lkey="+cfg.lKey+"&region[st]="+cfg.sDate+"&region[et]="+cfg.eDate+"&range="+cfg.range, function(jdata) { //console.log(jdata); if(jdata !== 'NoData'){ var gData = []; var data = {}; jdata.forEach(function(d) { if(cfg.range > Y_RANGE){ var newDate = toTimestamp(d.key[1],d.key[2],d.key[3],d.key[4],d.key[5]);//60 }else{ var newDate = toTimestamp(d.key[1],d.key[2],d.key[3],d.key[4]);//3600 } gData.push({ value : d.value.max, avg : (d.value.sum/d.value.count), date : newDate }); }); document.getElementById("usergraph").innerHTML = ""; if(cfg.range > Y_RANGE){ var dataScale = scaleLimit(jdata, cfg.range);//lowest range for user is month data = mergeByProperty(dataScale, gData, 'date');//console.log(data); }else{ data = gData; } var margin = {top: 10, right: 10, bottom: 100, left: 50}; var margin2 = {top: 430, right: 10, bottom: 22, left: 50}; ugraphObj = clone(graphObj); ugraphObj.init(cfg,data,"#usergraph",margin,margin2,"u"); userGraph(data); }else{ document.getElementById('usergraph').innerHTML = M.util.get_string('nodata','local_getkey','users'); } }); } var graphObj = { cfg : {}, data : {}, margin : {}, margin2 : {}, format : d3.time.format("%Y %m %e %H"), divid : "#", x : 0, x2 : 0, y : 0, y2 : 0, xAxis:0, xAxis2 : 0, yAxis : 0, graph : null, focus : false, context : null, brush : false, area1 : false, area2 : false, width : 0, height : 0, height2 : 0, div : null, error : null, title : 'Graph', _this :this, dateFn : function(d) { return new Date(d.date*1000); /* timestamp to date*/ }, valueFn : function(d) { return d.value }, init : function(cfg,data,divid,margin,margin2,title, callback) { this.cfg = cfg; this.data = data; this.margin = margin; this.margin2 = margin2; this.divid = divid; this.title = title; //console.log(data); this.width = 960 - this.margin.left - this.margin.right; this.height = 500 - this.margin.top - this.margin.bottom; this.height2 = 500 - this.margin2.top - this.margin2.bottom; this.x = d3.time.scale().range([0, this.width]); this.x2 = d3.time.scale().range([0, this.width]) this.y = d3.scale.linear().range([this.height, 20]); this.y2 = d3.scale.linear().range([this.height2, 0]); this.xAxis = d3.svg.axis().scale(this.x).orient("bottom").ticks(5); this.xAxis2 = d3.svg.axis().scale(this.x2).orient("bottom"); this.yAxis = d3.svg.axis().scale(this.y).orient("left").ticks(5); this.div = d3.select(this.divid).append("div") .attr("class", "tooltip") .style("opacity", 0); this.graph = d3.select(this.divid).append("svg:svg") .attr("width", this.width + this.margin.left + this.margin.right) .attr("height", 580); //.attr("height", this.height + this.margin.top + this.margin.bottom); if(title == "m"){ var gtitle = M.util.get_string('msggraph','local_getkey'); }else{ var gtitle = M.util.get_string('usrgraph','local_getkey'); } this.graph.append("text") .attr("x", (this.width / 2)) .attr("y", (17)) .attr("text-anchor", "middle") .style("font-size", "22px") .style("text-decoration", "underline") .text(gtitle); //.append("svg:g").constructor this.graph.append("defs").append("clipPath") .attr("id", "clip") .append("rect") .attr("width", this.width) .attr("height", this.height); this.focus = this.graph.append("g") .attr("class", "focus") .attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")"); this.context = this.graph.append("g") .attr("class", "context") .attr("transform", "translate(" + this.margin2.left + "," + this.margin2.top + ")"); var scope = this; this.area1 = d3.svg.area() .x(function(d) { return scope.x(scope.dateFn(d)); }) .y0(scope.height) .y1(function(d) { return scope.y(scope.valueFn(d)); }) this.area2 = d3.svg.area() .x(function(d) { return scope.x2(scope.dateFn(d)); }) .y0(scope.height2) .y1(function(d) { return scope.y2(scope.valueFn(d)); }) this.brush = d3.svg.brush().x(this.x2).on("brush", window[title+'brushed']); }, }
vidyamantra/moodle-local_getkey
stat/stat.js
JavaScript
gpl-3.0
9,089
#include <linux/version.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/dmi.h> #include <linux/acpi.h> #include <linux/thermal.h> #include <linux/platform_device.h> #include <linux/aee.h> #include <linux/types.h> #include <linux/delay.h> #include <linux/proc_fs.h> #include <linux/syscalls.h> #include <linux/sched.h> #include <linux/writeback.h> #include <asm/uaccess.h> #include <asm/string.h> #include <linux/spinlock.h> #include <mach/system.h> #include "mach/mtk_thermal_monitor.h" #include "mach/mt_typedefs.h" #include "mach/mt_thermal.h" #include "mach/mtk_mdm_monitor.h" extern struct proc_dir_entry * mtk_thermal_get_proc_drv_therm_dir_entry(void); static unsigned int interval = 0; /* seconds, 0 : no auto polling */ static unsigned int trip_temp[10] = {85000,80000,70000,60000,50000,40000,30000,20000,10000,5000}; static int g_THERMAL_TRIP[10] = {0,0,0,0,0,0,0,0,0,0}; static unsigned int cl_dev_sysrst_state = 0; static struct thermal_zone_device *thz_dev; static struct thermal_cooling_device *cl_dev_sysrst; static int mtktspa_debug_log = 0; static int kernelmode = 0; static int num_trip=0; static char g_bind0[20]="mtktspa-sysrst"; static char g_bind1[20]={0}; static char g_bind2[20]={0}; static char g_bind3[20]={0}; static char g_bind4[20]={0}; static char g_bind5[20]={0}; static char g_bind6[20]={0}; static char g_bind7[20]={0}; static char g_bind8[20]={0}; static char g_bind9[20]={0}; /** * If curr_temp >= polling_trip_temp1, use interval * else if cur_temp >= polling_trip_temp2 && curr_temp < polling_trip_temp1, use interval*polling_factor1 * else, use interval*polling_factor2 */ static int polling_trip_temp1 = 40000; static int polling_trip_temp2 = 20000; static int polling_factor1 = 5000; static int polling_factor2 = 10000; #define mtktspa_TEMP_CRIT 85000 /* 85.000 degree Celsius */ #define mtktspa_dprintk(fmt, args...) \ do { \ if (mtktspa_debug_log) { \ pr_notice("Power/PA_Thermal" fmt, ##args); \ } \ } while(0) /* struct md_info{ char *attribute; int value; char *unit; int invalid_value; int index; }; struct md_info g_pinfo_list[] = {{"TXPWR_MD1", -127, "db", -127, 0}, {"TXPWR_MD2", -127, "db", -127, 1}, {"RFTEMP_2G_MD1", -32767, "¢XC", -32767, 2}, {"RFTEMP_2G_MD2", -32767, "¢XC", -32767, 3}, {"RFTEMP_3G_MD1", -32767, "¢XC", -32767, 4}, {"RFTEMP_3G_MD2", -32767, "¢XC", -32767, 5}}; */ static DEFINE_MUTEX(TSPA_lock); static int mtktspa_get_hw_temp(void) { struct md_info *p_info; int size, i; mutex_lock(&TSPA_lock); mtk_mdm_get_md_info(&p_info, &size); for(i=0; i<size; i++) { mtktspa_dprintk("PA temperature: name:%s, vaule:%d, invalid_value=%d \n",p_info[i].attribute, p_info[i].value, p_info[i].invalid_value); if(!strcmp(p_info[i].attribute, "RFTEMP_2G_MD1")) { mtktspa_dprintk("PA temperature: RFTEMP_2G_MD1\n"); if(p_info[i].value != p_info[i].invalid_value) break; } else if(!strcmp(p_info[i].attribute, "RFTEMP_3G_MD1")) { mtktspa_dprintk("PA temperature: RFTEMP_3G_MD1\n"); if(p_info[i].value != p_info[i].invalid_value) break; } } if(i==size) { mtktspa_dprintk("PA temperature: not ready\n"); mutex_unlock(&TSPA_lock); return -127000; } else { mtktspa_dprintk("PA temperature: %d\n",p_info[i].value); if((p_info[i].value>100000) || (p_info[i].value<-30000)) printk("[Power/PA_Thermal] PA T=%d\n",p_info[i].value); mutex_unlock(&TSPA_lock); return (p_info[i].value); } } static int mtktspa_get_temp(struct thermal_zone_device *thermal, unsigned long *t) { *t = mtktspa_get_hw_temp(); if ((int) *t >= polling_trip_temp1) thermal->polling_delay = interval*1000; else if ((int) *t < polling_trip_temp2) thermal->polling_delay = interval * polling_factor2; else thermal->polling_delay = interval * polling_factor1; return 0; } static int mtktspa_bind(struct thermal_zone_device *thermal, struct thermal_cooling_device *cdev) { int table_val=0; if(!strcmp(cdev->type, g_bind0)) { table_val = 0; mtktspa_dprintk("[mtktspa_bind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind1)) { table_val = 1; mtktspa_dprintk("[mtktspa_bind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind2)) { table_val = 2; mtktspa_dprintk("[mtktspa_bind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind3)) { table_val = 3; mtktspa_dprintk("[mtktspa_bind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind4)) { table_val = 4; mtktspa_dprintk("[mtktspa_bind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind5)) { table_val = 5; mtktspa_dprintk("[mtktspa_bind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind6)) { table_val = 6; mtktspa_dprintk("[mtktspa_bind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind7)) { table_val = 7; mtktspa_dprintk("[mtktspa_bind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind8)) { table_val = 8; mtktspa_dprintk("[mtktspa_bind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind9)) { table_val = 9; mtktspa_dprintk("[mtktspa_bind] %s\n", cdev->type); } else return 0; if (mtk_thermal_zone_bind_cooling_device(thermal, table_val, cdev)) { mtktspa_dprintk("[mtktspa_bind] error binding cooling dev\n"); return -EINVAL; } else { mtktspa_dprintk("[mtktspa_bind] binding OK\n"); } return 0; } static int mtktspa_unbind(struct thermal_zone_device *thermal, struct thermal_cooling_device *cdev) { int table_val=0; if(!strcmp(cdev->type, g_bind0)) { table_val = 0; mtktspa_dprintk("[mtktspa_unbind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind1)) { table_val = 1; mtktspa_dprintk("[mtktspa_unbind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind2)) { table_val = 2; mtktspa_dprintk("[mtktspa_unbind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind3)) { table_val = 3; mtktspa_dprintk("[mtktspa_unbind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind4)) { table_val = 4; mtktspa_dprintk("[mtktspa_unbind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind5)) { table_val = 5; mtktspa_dprintk("[mtktspa_unbind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind6)) { table_val = 6; mtktspa_dprintk("[mtktspa_unbind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind7)) { table_val = 7; mtktspa_dprintk("[mtktspa_unbind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind8)) { table_val = 8; mtktspa_dprintk("[mtktspa_unbind] %s\n", cdev->type); } else if(!strcmp(cdev->type, g_bind9)) { table_val = 9; mtktspa_dprintk("[mtktspa_unbind] %s\n", cdev->type); } else return 0; if (thermal_zone_unbind_cooling_device(thermal, table_val, cdev)) { mtktspa_dprintk("[mtktspa_unbind] error unbinding cooling dev\n"); return -EINVAL; } else { mtktspa_dprintk("[mtktspa_unbind] unbinding OK\n"); } return 0; } static int mtktspa_get_mode(struct thermal_zone_device *thermal, enum thermal_device_mode *mode) { *mode = (kernelmode) ? THERMAL_DEVICE_ENABLED : THERMAL_DEVICE_DISABLED; return 0; } static int mtktspa_set_mode(struct thermal_zone_device *thermal, enum thermal_device_mode mode) { kernelmode = mode; return 0; } static int mtktspa_get_trip_type(struct thermal_zone_device *thermal, int trip, enum thermal_trip_type *type) { *type = g_THERMAL_TRIP[trip]; return 0; } static int mtktspa_get_trip_temp(struct thermal_zone_device *thermal, int trip, unsigned long *temp) { *temp = trip_temp[trip]; return 0; } static int mtktspa_get_crit_temp(struct thermal_zone_device *thermal, unsigned long *temperature) { *temperature = mtktspa_TEMP_CRIT; return 0; } /* bind callback functions to thermalzone */ static struct thermal_zone_device_ops mtktspa_dev_ops = { .bind = mtktspa_bind, .unbind = mtktspa_unbind, .get_temp = mtktspa_get_temp, .get_mode = mtktspa_get_mode, .set_mode = mtktspa_set_mode, .get_trip_type = mtktspa_get_trip_type, .get_trip_temp = mtktspa_get_trip_temp, .get_crit_temp = mtktspa_get_crit_temp, }; /* * cooling device callback functions (mtktspa_cooling_sysrst_ops) * 1 : ON and 0 : OFF */ static int tspa_sysrst_get_max_state(struct thermal_cooling_device *cdev, unsigned long *state) { *state = 1; return 0; } static int tspa_sysrst_get_cur_state(struct thermal_cooling_device *cdev, unsigned long *state) { *state = cl_dev_sysrst_state; return 0; } static int tspa_sysrst_set_cur_state(struct thermal_cooling_device *cdev, unsigned long state) { cl_dev_sysrst_state = state; if(cl_dev_sysrst_state == 1) { printk("Power/PA_Thermal: reset, reset, reset!!!"); printk("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); printk("*****************************************"); printk("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); #ifndef CONFIG_ARM64 BUG(); #else *(unsigned int*) 0x0 = 0xdead; // To trigger data abort to reset the system for thermal protection. #endif } return 0; } /* bind fan callbacks to fan device */ static struct thermal_cooling_device_ops mtktspa_cooling_sysrst_ops = { .get_max_state = tspa_sysrst_get_max_state, .get_cur_state = tspa_sysrst_get_cur_state, .set_cur_state = tspa_sysrst_set_cur_state, }; int mtktspa_register_thermal(void); void mtktspa_unregister_thermal(void); static int mtktspa_read(struct seq_file *m, void *v) { seq_printf(m, "[ mtktspa_read] trip_0_temp=%d,trip_1_temp=%d,trip_2_temp=%d,trip_3_temp=%d,trip_4_temp=%d,\n\ trip_5_temp=%d,trip_6_temp=%d,trip_7_temp=%d,trip_8_temp=%d,trip_9_temp=%d,\n\ g_THERMAL_TRIP_0=%d,g_THERMAL_TRIP_1=%d,g_THERMAL_TRIP_2=%d,g_THERMAL_TRIP_3=%d,g_THERMAL_TRIP_4=%d,\n\ g_THERMAL_TRIP_5=%d,g_THERMAL_TRIP_6=%d,g_THERMAL_TRIP_7=%d,g_THERMAL_TRIP_8=%d,g_THERMAL_TRIP_9=%d,\n\ cooldev0=%s,cooldev1=%s,cooldev2=%s,cooldev3=%s,cooldev4=%s,\n\ cooldev5=%s,cooldev6=%s,cooldev7=%s,cooldev8=%s,cooldev9=%s,time_ms=%d\n", trip_temp[0],trip_temp[1],trip_temp[2],trip_temp[3],trip_temp[4], trip_temp[5],trip_temp[6],trip_temp[7],trip_temp[8],trip_temp[9], g_THERMAL_TRIP[0],g_THERMAL_TRIP[1],g_THERMAL_TRIP[2],g_THERMAL_TRIP[3],g_THERMAL_TRIP[4], g_THERMAL_TRIP[5],g_THERMAL_TRIP[6],g_THERMAL_TRIP[7],g_THERMAL_TRIP[8],g_THERMAL_TRIP[9], g_bind0,g_bind1,g_bind2,g_bind3,g_bind4,g_bind5,g_bind6,g_bind7,g_bind8,g_bind9, interval*1000); return 0; } static ssize_t mtktspa_write(struct file *file, const char __user *buffer, size_t count, loff_t *data) { int len=0,time_msec=0; int trip[10]={0}; int t_type[10]={0}; int i; char bind0[20],bind1[20],bind2[20],bind3[20],bind4[20]; char bind5[20],bind6[20],bind7[20],bind8[20],bind9[20]; char desc[512]; len = (count < (sizeof(desc) - 1)) ? count : (sizeof(desc) - 1); if (copy_from_user(desc, buffer, len)) { return 0; } desc[len] = '\0'; if (sscanf(desc, "%d %d %d %s %d %d %s %d %d %s %d %d %s %d %d %s %d %d %s %d %d %s %d %d %s %d %d %s %d %d %s %d", &num_trip, &trip[0],&t_type[0],bind0, &trip[1],&t_type[1],bind1, &trip[2],&t_type[2],bind2, &trip[3],&t_type[3],bind3, &trip[4],&t_type[4],bind4, &trip[5],&t_type[5],bind5, &trip[6],&t_type[6],bind6, &trip[7],&t_type[7],bind7, &trip[8],&t_type[8],bind8, &trip[9],&t_type[9],bind9, &time_msec) == 32) { mtktspa_dprintk("[mtktspa_write] mtktspa_unregister_thermal\n"); mtktspa_unregister_thermal(); for(i=0; i<num_trip; i++) g_THERMAL_TRIP[i] = t_type[i]; g_bind0[0]=g_bind1[0]=g_bind2[0]=g_bind3[0]=g_bind4[0]=g_bind5[0]=g_bind6[0]=g_bind7[0]=g_bind8[0]=g_bind9[0]='\0'; for(i=0; i<20; i++) { g_bind0[i]=bind0[i]; g_bind1[i]=bind1[i]; g_bind2[i]=bind2[i]; g_bind3[i]=bind3[i]; g_bind4[i]=bind4[i]; g_bind5[i]=bind5[i]; g_bind6[i]=bind6[i]; g_bind7[i]=bind7[i]; g_bind8[i]=bind8[i]; g_bind9[i]=bind9[i]; } mtktspa_dprintk("[mtktspa_write] g_THERMAL_TRIP_0=%d,g_THERMAL_TRIP_1=%d,g_THERMAL_TRIP_2=%d,g_THERMAL_TRIP_3=%d,g_THERMAL_TRIP_4=%d,\ g_THERMAL_TRIP_5=%d,g_THERMAL_TRIP_6=%d,g_THERMAL_TRIP_7=%d,g_THERMAL_TRIP_8=%d,g_THERMAL_TRIP_9=%d,\n", g_THERMAL_TRIP[0],g_THERMAL_TRIP[1],g_THERMAL_TRIP[2],g_THERMAL_TRIP[3],g_THERMAL_TRIP[4], g_THERMAL_TRIP[5],g_THERMAL_TRIP[6],g_THERMAL_TRIP[7],g_THERMAL_TRIP[8],g_THERMAL_TRIP[9]); mtktspa_dprintk("[mtktspa_write] cooldev0=%s,cooldev1=%s,cooldev2=%s,cooldev3=%s,cooldev4=%s,\ cooldev5=%s,cooldev6=%s,cooldev7=%s,cooldev8=%s,cooldev9=%s\n", g_bind0,g_bind1,g_bind2,g_bind3,g_bind4,g_bind5,g_bind6,g_bind7,g_bind8,g_bind9); for(i=0; i<num_trip; i++) { trip_temp[i]=trip[i]; } interval=time_msec / 1000; mtktspa_dprintk("[mtktspa_write] trip_0_temp=%d,trip_1_temp=%d,trip_2_temp=%d,trip_3_temp=%d,trip_4_temp=%d,\ trip_5_temp=%d,trip_6_temp=%d,trip_7_temp=%d,trip_8_temp=%d,trip_9_temp=%d,time_ms=%d\n", trip_temp[0],trip_temp[1],trip_temp[2],trip_temp[3],trip_temp[4], trip_temp[5],trip_temp[6],trip_temp[7],trip_temp[8],trip_temp[9],interval*1000); mtktspa_dprintk("[mtktspa_write] mtktspa_register_thermal\n"); mtktspa_register_thermal(); return count; } else { mtktspa_dprintk("[mtktspa_write] bad argument\n"); } return -EINVAL; } static int mtktspa_open(struct inode *inode, struct file *file) { return single_open(file, mtktspa_read, NULL); } static const struct file_operations mtktspa_fops = { .owner = THIS_MODULE, .open = mtktspa_open, .read = seq_read, .llseek = seq_lseek, .write = mtktspa_write, .release = single_release, }; int mtktspa_register_cooler(void) { /* cooling devices */ cl_dev_sysrst = mtk_thermal_cooling_device_register("mtktspa-sysrst", NULL, &mtktspa_cooling_sysrst_ops); return 0; } int mtktspa_register_thermal(void) { mtktspa_dprintk("[mtktspa_register_thermal]\n"); /* trips */ if (NULL == thz_dev) { thz_dev = mtk_thermal_zone_device_register("mtktspa", num_trip, NULL, &mtktspa_dev_ops, 0, 0, 0, interval*1000); } mtk_mdm_set_md1_signal_period(interval); return 0; } void mtktspa_unregister_cooler(void) { if (cl_dev_sysrst) { mtk_thermal_cooling_device_unregister(cl_dev_sysrst); cl_dev_sysrst = NULL; } } void mtktspa_unregister_thermal(void) { mtktspa_dprintk("[mtktspa_unregister_thermal]\n"); if (thz_dev) { mtk_thermal_zone_device_unregister(thz_dev); thz_dev = NULL; } } static int __init mtktspa_init(void) { int err = 0; struct proc_dir_entry *entry = NULL; struct proc_dir_entry *mtktspa_dir = NULL; mtktspa_dprintk("[%s]\n", __func__); err = mtktspa_register_cooler(); if(err) return err; err = mtktspa_register_thermal(); if (err) goto err_unreg; mtktspa_dir = mtk_thermal_get_proc_drv_therm_dir_entry(); if (!mtktspa_dir) { mtktspa_dprintk("[%s]: mkdir /proc/driver/thermal failed\n", __func__); } else { entry = proc_create("tzpa", S_IRUGO | S_IWUSR | S_IWGRP, mtktspa_dir, &mtktspa_fops); if (entry) { #if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 10, 0) proc_set_user(entry, 0, 1000); #else entry->gid = 1000; #endif } } return 0; err_unreg: mtktspa_unregister_cooler(); return err; } static void __exit mtktspa_exit(void) { mtktspa_dprintk("[mtktspa_exit] \n"); mtktspa_unregister_thermal(); mtktspa_unregister_cooler(); } module_init(mtktspa_init); module_exit(mtktspa_exit);
psycho-source/Psycho-Kernel
drivers/misc/mediatek/thermal/mt6795/mtk_ts_pa.c
C
gpl-3.0
15,511
/* * Copyright 2016 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/base/task_queue_posix.h" #include "webrtc/base/checks.h" #include "webrtc/base/task_queue.h" namespace rtc { namespace internal { pthread_key_t g_queue_ptr_tls = 0; void InitializeTls() { RTC_CHECK(pthread_key_create(&g_queue_ptr_tls, nullptr) == 0); } pthread_key_t GetQueuePtrTls() { static pthread_once_t init_once = PTHREAD_ONCE_INIT; RTC_CHECK(pthread_once(&init_once, &InitializeTls) == 0); return g_queue_ptr_tls; } AutoSetCurrentQueuePtr::AutoSetCurrentQueuePtr(TaskQueue* q) : prev_(TaskQueue::Current()) { pthread_setspecific(GetQueuePtrTls(), q); } AutoSetCurrentQueuePtr::~AutoSetCurrentQueuePtr() { pthread_setspecific(GetQueuePtrTls(), prev_); } } // namespace internal } // namespace rtc
AnyRTC/AnyRTC-RTMP
webrtc/base/task_queue_posix.cc
C++
gpl-3.0
1,155
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2011 Nicolas Wack <wackou@gmail.com> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # GuessIt 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 # Lesser GNU General Public License for more details. # # You should have received a copy of the Lesser GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # __version__ = '0.5.2' __all__ = ['Guess', 'Language', 'guess_file_info', 'guess_video_info', 'guess_movie_info', 'guess_episode_info'] # Do python3 detection before importing any other module, to be sure that # it will then always be available # with code from http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/ import sys if sys.version_info[0] >= 3: PY3 = True unicode_text_type = str native_text_type = str base_text_type = str def u(x): return str(x) def s(x): return x class UnicodeMixin(object): __str__ = lambda x: x.__unicode__() import binascii def to_hex(x): return binascii.hexlify(x).decode('utf-8') else: PY3 = False __all__ = [ str(s) for s in __all__ ] # fix imports for python2 unicode_text_type = unicode native_text_type = str base_text_type = basestring def u(x): if isinstance(x, str): return x.decode('utf-8') return unicode(x) def s(x): if isinstance(x, unicode): return x.encode('utf-8') if isinstance(x, list): return [ s(y) for y in x ] if isinstance(x, tuple): return tuple(s(y) for y in x) if isinstance(x, dict): return dict((s(key), s(value)) for key, value in x.items()) return x class UnicodeMixin(object): __str__ = lambda x: unicode(x).encode('utf-8') def to_hex(x): return x.encode('hex') from guessit.guess import Guess, merge_all from guessit.language import Language from guessit.matcher import IterativeMatcher import logging log = logging.getLogger(__name__) class NullHandler(logging.Handler): def emit(self, record): pass # let's be a nicely behaving library h = NullHandler() log.addHandler(h) def guess_file_info(filename, filetype, info=None): """info can contain the names of the various plugins, such as 'filename' to detect filename info, or 'hash_md5' to get the md5 hash of the file. >>> guess_file_info('tests/dummy.srt', 'autodetect', info = ['hash_md5', 'hash_sha1']) {'hash_md5': 'e781de9b94ba2753a8e2945b2c0a123d', 'hash_sha1': 'bfd18e2f4e5d59775c2bc14d80f56971891ed620'} """ result = [] hashers = [] if info is None: info = ['filename'] if isinstance(info, base_text_type): info = [info] for infotype in info: if infotype == 'filename': m = IterativeMatcher(filename, filetype=filetype) result.append(m.matched()) elif infotype == 'hash_mpc': from guessit.hash_mpc import hash_file try: result.append(Guess({'hash_mpc': hash_file(filename)}, confidence=1.0)) except Exception as e: log.warning('Could not compute MPC-style hash because: %s' % e) elif infotype == 'hash_ed2k': from guessit.hash_ed2k import hash_file try: result.append(Guess({'hash_ed2k': hash_file(filename)}, confidence=1.0)) except Exception as e: log.warning('Could not compute ed2k hash because: %s' % e) elif infotype.startswith('hash_'): import hashlib hashname = infotype[5:] try: hasher = getattr(hashlib, hashname)() hashers.append((infotype, hasher)) except AttributeError: log.warning('Could not compute %s hash because it is not available from python\'s hashlib module' % hashname) else: log.warning('Invalid infotype: %s' % infotype) # do all the hashes now, but on a single pass if hashers: try: blocksize = 8192 hasherobjs = dict(hashers).values() with open(filename, 'rb') as f: chunk = f.read(blocksize) while chunk: for hasher in hasherobjs: hasher.update(chunk) chunk = f.read(blocksize) for infotype, hasher in hashers: result.append(Guess({infotype: hasher.hexdigest()}, confidence=1.0)) except Exception as e: log.warning('Could not compute hash because: %s' % e) result = merge_all(result) # last minute adjustments # if country is in the guessed properties, make it part of the filename if 'country' in result: result['series'] += ' (%s)' % result['country'].alpha2.upper() return result def guess_video_info(filename, info=None): return guess_file_info(filename, 'autodetect', info) def guess_movie_info(filename, info=None): return guess_file_info(filename, 'movie', info) def guess_episode_info(filename, info=None): return guess_file_info(filename, 'episode', info)
nabsboss/CouchPotatoServer
libs/guessit/__init__.py
Python
gpl-3.0
5,753
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * Zend_Gdata_App_Exception */ require_once 'Zend/Gdata/App/Exception.php'; /** * Gdata exceptions * * Class to represent exceptions that occur during Gdata operations. * * @category Zend * @package Zend_Gdata * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_App_InvalidArgumentException extends Zend_Gdata_App_Exception { }
dragermrb/gcalfaces
libs/Zend/Gdata/App/InvalidArgumentException.php
PHP
gpl-3.0
1,159
/* ****************************************************************************** * Portions COPYRIGHT 2012 STMicroelectronics * Portions SPIRIT Audio Engine Copyright (c) 1995-2009, SPIRIT * * Licensed under MCD-ST Image SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_image_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __SPIRIT_LOUDNESS_CONTROL_H__ #define __SPIRIT_LOUDNESS_CONTROL_H__ #ifdef __cplusplus extern "C" { #endif //__cplusplus /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ typedef void TSpiritLdCtrl; typedef struct { int gainQ8; } TSpiritLdCtrl_Prms; /* Exported constants --------------------------------------------------------*/ /* SUCCESS codes */ #define SPIRIT_LDCTRL_S_OK 0 /* ERROR codes */ #define SPIRIT_LDCTRL_E_INVALIDARG -1 #define SPIRIT_LDCTRL_E_SAMPLERATE -2 #define SPIRIT_LDCTRL_E_CH -3 #define SPIRIT_LDCTRL_E_BADALIGN_PERSIST -4 #define SPIRIT_LDCTRL_E_BADALIGN_SCRATCH -5 #define SPIRIT_LDCTRL_PERSIST_SIZE_IN_BYTES 120 #define SPIRIT_LDCTRL_SCRATCH_SIZE_IN_BYTES 512 #define SPIRIT_LDCTRL_MAX_CH 2 #define SPIRIT_LDCTRL_GAIN_Q_BITS 8 #define SPIRIT_LDCTRL_GAIN_MAX (1<<(SPIRIT_LDCTRL_GAIN_Q_BITS + 6)) #define SPIRIT_LDCTRL_GAIN_MIN (1<<(SPIRIT_LDCTRL_GAIN_Q_BITS - 6)) /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ int SpiritLdCtrl_Reset ( TSpiritLdCtrl *_); int SpiritLdCtrl_Init ( TSpiritLdCtrl *_, unsigned long sampleRateHz); int SpiritLdCtrl_SetPrms( TSpiritLdCtrl *_, const TSpiritLdCtrl_Prms *prms); int SpiritLdCtrl_GetPrms(const TSpiritLdCtrl *_, TSpiritLdCtrl_Prms *prms); int SpiritLdCtrl_Apply ( TSpiritLdCtrl *_, int nChannels, short *pcm, short nSamplesPerCh, void *scratch); #ifdef __cplusplus } #endif #endif /* __SPIRIT_LOUDNESS_CONTROL_H__ */
TRothfelder/Multicopter
libs/STM32Cube_FW_F4_V1.16.0/Projects/STM32469I_EVAL/Demonstrations/Modules/audio_player/Addons/SpiritDSP_LoudnessControl/spiritLdCtrl.h
C
gpl-3.0
2,828
#include "metatypes.h" #include <QMetaType> #include <QNetworkCookie> #include "config.h" #include "covers/albumcoverfetcher.h" #include "engines/enginebase.h" #include "globalsearch/searchprovider.h" #include "internet/digitallyimportedclient.h" #include "internet/geolocator.h" #include "internet/somafmservice.h" #include "library/directory.h" #include "playlist/playlist.h" #include "podcasts/podcastepisode.h" #include "podcasts/podcast.h" #include "ui/equalizer.h" #ifdef HAVE_DBUS #include <QDBusMetaType> #include "core/mpris2.h" #include "dbus/metatypes.h" #endif class GstBuffer; class GstElement; class GstEnginePipeline; class QNetworkReply; void RegisterMetaTypes() { qRegisterMetaType<ColumnAlignmentMap>("ColumnAlignmentMap"); qRegisterMetaType<const char*>("const char*"); qRegisterMetaType<CoverSearchResult>("CoverSearchResult"); qRegisterMetaType<CoverSearchResults>("CoverSearchResults"); qRegisterMetaType<DigitallyImportedClient::Channel>("DigitallyImportedClient::Channel"); qRegisterMetaType<Directory>("Directory"); qRegisterMetaType<DirectoryList>("DirectoryList"); qRegisterMetaType<Engine::SimpleMetaBundle>("Engine::SimpleMetaBundle"); qRegisterMetaType<Engine::State>("Engine::State"); qRegisterMetaType<Engine::TrackChangeFlags>("Engine::TrackChangeFlags"); qRegisterMetaType<Equalizer::Params>("Equalizer::Params"); qRegisterMetaType<Geolocator::LatLng>("Geolocator::LatLng"); qRegisterMetaType<GstBuffer*>("GstBuffer*"); qRegisterMetaType<GstElement*>("GstElement*"); qRegisterMetaType<GstEnginePipeline*>("GstEnginePipeline*"); qRegisterMetaType<PlaylistItemList>("PlaylistItemList"); qRegisterMetaType<PlaylistItemPtr>("PlaylistItemPtr"); qRegisterMetaType<PodcastEpisodeList>("PodcastEpisodeList"); qRegisterMetaType<PodcastList>("PodcastList"); qRegisterMetaType<QList<CoverSearchResult> >("QList<CoverSearchResult>"); qRegisterMetaType<QList<PlaylistItemPtr> >("QList<PlaylistItemPtr>"); qRegisterMetaType<PlaylistSequence::RepeatMode>("PlaylistSequence::RepeatMode"); qRegisterMetaType<PlaylistSequence::ShuffleMode>("PlaylistSequence::ShuffleMode"); qRegisterMetaType<QList<PodcastEpisode> >("QList<PodcastEpisode>"); qRegisterMetaType<QList<Podcast> >("QList<Podcast>"); qRegisterMetaType<QList<QNetworkCookie> >("QList<QNetworkCookie>"); qRegisterMetaType<QList<Song> >("QList<Song>"); qRegisterMetaType<QNetworkCookie>("QNetworkCookie"); qRegisterMetaType<QNetworkReply*>("QNetworkReply*"); qRegisterMetaType<QNetworkReply**>("QNetworkReply**"); qRegisterMetaType<SearchProvider::ResultList>("SearchProvider::ResultList"); qRegisterMetaType<SearchProvider::Result>("SearchProvider::Result"); qRegisterMetaType<smart_playlists::GeneratorPtr>("smart_playlists::GeneratorPtr"); qRegisterMetaType<SomaFMService::Stream>("SomaFMService::Stream"); qRegisterMetaType<SongList>("SongList"); qRegisterMetaType<Song>("Song"); qRegisterMetaTypeStreamOperators<DigitallyImportedClient::Channel>("DigitallyImportedClient::Channel"); qRegisterMetaTypeStreamOperators<Equalizer::Params>("Equalizer::Params"); qRegisterMetaTypeStreamOperators<QMap<int, int> >("ColumnAlignmentMap"); qRegisterMetaTypeStreamOperators<SomaFMService::Stream>("SomaFMService::Stream"); qRegisterMetaType<SubdirectoryList>("SubdirectoryList"); qRegisterMetaType<Subdirectory>("Subdirectory"); qRegisterMetaType<QList<QUrl> >("QList<QUrl>"); #ifdef HAVE_DBUS qDBusRegisterMetaType<QImage>(); qDBusRegisterMetaType<TrackMetadata>(); qDBusRegisterMetaType<TrackIds>(); qDBusRegisterMetaType<QList<QByteArray> >(); qDBusRegisterMetaType<MprisPlaylist>(); qDBusRegisterMetaType<MaybePlaylist>(); qDBusRegisterMetaType<MprisPlaylistList>(); #endif }
cincodenada/clementine-player
src/core/metatypes.cpp
C++
gpl-3.0
3,755
# voronoi.py - functions for computing the Voronoi partition of a graph # # Copyright 2016-2018 NetworkX developers. # # This file is part of NetworkX. # # NetworkX is distributed under a BSD license; see LICENSE.txt for more # information. """Functions for computing the Voronoi cells of a graph.""" import networkx as nx from networkx.utils import groups __all__ = ['voronoi_cells'] def voronoi_cells(G, center_nodes, weight='weight'): """Returns the Voronoi cells centered at `center_nodes` with respect to the shortest-path distance metric. If *C* is a set of nodes in the graph and *c* is an element of *C*, the *Voronoi cell* centered at a node *c* is the set of all nodes *v* that are closer to *c* than to any other center node in *C* with respect to the shortest-path distance metric. [1]_ For directed graphs, this will compute the "outward" Voronoi cells, as defined in [1]_, in which distance is measured from the center nodes to the target node. For the "inward" Voronoi cells, use the :meth:`DiGraph.reverse` method to reverse the orientation of the edges before invoking this function on the directed graph. Parameters ---------- G : NetworkX graph center_nodes : set A nonempty set of nodes in the graph `G` that represent the center of the Voronoi cells. weight : string or function The edge attribute (or an arbitrary function) representing the weight of an edge. This keyword argument is as described in the documentation for :func:`~networkx.multi_source_dijkstra_path`, for example. Returns ------- dictionary A mapping from center node to set of all nodes in the graph closer to that center node than to any other center node. The keys of the dictionary are the element of `center_nodes`, and the values of the dictionary form a partition of the nodes of `G`. Examples -------- To get only the partition of the graph induced by the Voronoi cells, take the collection of all values in the returned dictionary:: >>> G = nx.path_graph(6) >>> center_nodes = {0, 3} >>> cells = nx.voronoi_cells(G, center_nodes) >>> partition = set(map(frozenset, cells.values())) >>> sorted(map(sorted, partition)) [[0, 1], [2, 3, 4, 5]] Raises ------ ValueError If `center_nodes` is empty. References ---------- .. [1] Erwig, Martin. (2000), "The graph Voronoi diagram with applications." *Networks*, 36: 156--163. <dx.doi.org/10.1002/1097-0037(200010)36:3<156::AID-NET2>3.0.CO;2-L> """ # Determine the shortest paths from any one of the center nodes to # every node in the graph. # # This raises `ValueError` if `center_nodes` is an empty set. paths = nx.multi_source_dijkstra_path(G, center_nodes, weight=weight) # Determine the center node from which the shortest path originates. nearest = {v: p[0] for v, p in paths.items()} # Get the mapping from center node to all nodes closer to it than to # any other center node. cells = groups(nearest) # We collect all unreachable nodes under a special key, if there are any. unreachable = set(G) - set(nearest) if unreachable: cells['unreachable'] = unreachable return cells
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/networkx/algorithms/voronoi.py
Python
gpl-3.0
3,399
namespace Chummer { partial class frmCreateCustomDrug { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.TreeNode treeNode1 = new System.Windows.Forms.TreeNode("Foundations"); System.Windows.Forms.TreeNode treeNode2 = new System.Windows.Forms.TreeNode("Blocks"); System.Windows.Forms.TreeNode treeNode3 = new System.Windows.Forms.TreeNode("Enhancers"); System.Windows.Forms.TreeNode treeNode4 = new System.Windows.Forms.TreeNode("Foundations"); System.Windows.Forms.TreeNode treeNode5 = new System.Windows.Forms.TreeNode("Blocks"); System.Windows.Forms.TreeNode treeNode6 = new System.Windows.Forms.TreeNode("Enhancers"); this.treAvailableComponents = new System.Windows.Forms.TreeView(); this.btnAddComponent = new System.Windows.Forms.Button(); this.btnRemoveComponent = new System.Windows.Forms.Button(); this.treChoosenComponents = new System.Windows.Forms.TreeView(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOk = new System.Windows.Forms.Button(); this.lblDrugDescription = new System.Windows.Forms.Label(); this.lblBlockDescription = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.txtDrugName = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // treAvailableComponents // this.treAvailableComponents.HideSelection = false; this.treAvailableComponents.Location = new System.Drawing.Point(12, 12); this.treAvailableComponents.Name = "treAvailableComponents"; treeNode1.Name = "Foundations"; treeNode1.Text = "Foundations"; treeNode2.Name = "Blocks"; treeNode2.Text = "Blocks"; treeNode3.Name = "Enhancers"; treeNode3.Text = "Enhancers"; this.treAvailableComponents.Nodes.AddRange(new System.Windows.Forms.TreeNode[] { treeNode1, treeNode2, treeNode3}); this.treAvailableComponents.Size = new System.Drawing.Size(265, 316); this.treAvailableComponents.TabIndex = 0; this.treAvailableComponents.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treAvailableComponents_AfterSelect); this.treAvailableComponents.NodeMouseDoubleClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.treAvailableComponents_NodeMouseDoubleClick); // // btnAddComponent // this.btnAddComponent.Location = new System.Drawing.Point(283, 122); this.btnAddComponent.Name = "btnAddComponent"; this.btnAddComponent.Size = new System.Drawing.Size(44, 23); this.btnAddComponent.TabIndex = 2; this.btnAddComponent.Text = ">>"; this.btnAddComponent.UseVisualStyleBackColor = true; this.btnAddComponent.Click += new System.EventHandler(this.btnAddComponent_Click); // // btnRemoveComponent // this.btnRemoveComponent.Location = new System.Drawing.Point(283, 151); this.btnRemoveComponent.Name = "btnRemoveComponent"; this.btnRemoveComponent.Size = new System.Drawing.Size(44, 23); this.btnRemoveComponent.TabIndex = 2; this.btnRemoveComponent.Text = "<<"; this.btnRemoveComponent.UseVisualStyleBackColor = true; this.btnRemoveComponent.Click += new System.EventHandler(this.btnRemoveComponent_Click); // // treChoosenComponents // this.treChoosenComponents.HideSelection = false; this.treChoosenComponents.Location = new System.Drawing.Point(333, 35); this.treChoosenComponents.Name = "treChoosenComponents"; treeNode4.Name = "Foundations"; treeNode4.Text = "Foundations"; treeNode5.Name = "Blocks"; treeNode5.Text = "Blocks"; treeNode6.Name = "Enhancers"; treeNode6.Text = "Enhancers"; this.treChoosenComponents.Nodes.AddRange(new System.Windows.Forms.TreeNode[] { treeNode4, treeNode5, treeNode6}); this.treChoosenComponents.Size = new System.Drawing.Size(278, 293); this.treChoosenComponents.TabIndex = 0; this.treChoosenComponents.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treChoosenComponents_AfterSelect); // // btnCancel // this.btnCancel.Location = new System.Drawing.Point(536, 487); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 23); this.btnCancel.TabIndex = 3; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnOk // this.btnOk.Location = new System.Drawing.Point(455, 487); this.btnOk.Name = "btnOk"; this.btnOk.Size = new System.Drawing.Size(75, 23); this.btnOk.TabIndex = 3; this.btnOk.Text = "Add"; this.btnOk.UseVisualStyleBackColor = true; this.btnOk.Click += new System.EventHandler(this.btnOk_Click); // // lblDrugDescription // this.lblDrugDescription.Location = new System.Drawing.Point(330, 331); this.lblDrugDescription.Name = "lblDrugDescription"; this.lblDrugDescription.Size = new System.Drawing.Size(281, 153); this.lblDrugDescription.TabIndex = 4; // // lblBlockDescription // this.lblBlockDescription.Location = new System.Drawing.Point(12, 331); this.lblBlockDescription.Name = "lblBlockDescription"; this.lblBlockDescription.Size = new System.Drawing.Size(265, 153); this.lblBlockDescription.TabIndex = 5; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(283, 12); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(38, 13); this.label1.TabIndex = 6; this.label1.Text = "Name:"; // // txtDrugName // this.txtDrugName.Location = new System.Drawing.Point(333, 9); this.txtDrugName.Name = "txtDrugName"; this.txtDrugName.Size = new System.Drawing.Size(278, 20); this.txtDrugName.TabIndex = 7; this.txtDrugName.Text = "New Drug"; this.txtDrugName.TextChanged += new System.EventHandler(this.txtDrugName_TextChanged); // // frmCreateCustomDrug // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(623, 522); this.Controls.Add(this.txtDrugName); this.Controls.Add(this.label1); this.Controls.Add(this.lblBlockDescription); this.Controls.Add(this.lblDrugDescription); this.Controls.Add(this.btnOk); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnRemoveComponent); this.Controls.Add(this.btnAddComponent); this.Controls.Add(this.treChoosenComponents); this.Controls.Add(this.treAvailableComponents); this.Name = "frmCreateCustomDrug"; this.Text = "Create Custom Drug"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TreeView treAvailableComponents; private System.Windows.Forms.Button btnAddComponent; private System.Windows.Forms.Button btnRemoveComponent; private System.Windows.Forms.TreeView treChoosenComponents; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOk; private System.Windows.Forms.Label lblDrugDescription; private System.Windows.Forms.Label lblBlockDescription; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtDrugName; } }
SquadronROE/chummer5a
Chummer/frmCreateCustomDrug.Designer.cs
C#
gpl-3.0
9,470
<?php /* Copyright (C) 2002-2003 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2004-2014 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@capnetworks.com> * Copyright (C) 2011-2013 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com> * Copyright (C) 2015 Charlie Benke <charlie@patas-monkey.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 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/>. */ /** * \file htdocs/fichinter/class/fichinter.class.php * \ingroup ficheinter * \brief Fichier de la classe des gestion des fiches interventions */ require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; require_once DOL_DOCUMENT_ROOT .'/core/class/commonobjectline.class.php'; /** * Class to manage interventions */ class Fichinter extends CommonObject { public $element='fichinter'; public $table_element='fichinter'; public $fk_element='fk_fichinter'; public $table_element_line='fichinterdet'; public $picto = 'intervention'; /** * {@inheritdoc} */ protected $table_ref_field = 'ref'; var $socid; // Id client var $author; var $datec; var $datev; var $dateo; var $datee; var $datet; var $datem; var $duration; var $statut; // 0=draft, 1=validated, 2=invoiced, 3=Terminate var $description; var $fk_contrat; var $extraparams=array(); var $lines = array(); /** * Constructor * * @param DoliDB $db Database handler */ function __construct($db) { $this->db = $db; $this->products = array(); $this->fk_project = 0; $this->fk_contrat = 0; $this->statut = 0; // List of language codes for status $this->statuts[0]='Draft'; $this->statuts[1]='Validated'; $this->statuts[2]='StatusInterInvoiced'; $this->statuts[3]='Done'; $this->statuts_short[0]='Draft'; $this->statuts_short[1]='Validated'; $this->statuts_short[2]='StatusInterInvoiced'; $this->statuts_short[3]='Done'; $this->statuts_logo[0]='statut0'; $this->statuts_logo[1]='statut1'; $this->statuts_logo[2]='statut6'; $this->statuts_logo[3]='statut6'; } /** * Load indicators into this->nb for board * * @return int <0 if KO, >0 if OK */ function load_state_board() { global $user; $this->nb=array(); $clause = "WHERE"; $sql = "SELECT count(fi.rowid) as nb"; $sql.= " FROM ".MAIN_DB_PREFIX."fichinter as fi"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON fi.fk_soc = s.rowid"; if (!$user->rights->societe->client->voir && !$user->societe_id) { $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql.= " WHERE sc.fk_user = " .$user->id; $clause = "AND"; } $sql.= " ".$clause." fi.entity IN (".getEntity($this->element, 1).")"; $resql=$this->db->query($sql); if ($resql) { while ($obj=$this->db->fetch_object($resql)) { $this->nb["fichinters"]=$obj->nb; } $this->db->free($resql); return 1; } else { dol_print_error($this->db); $this->error=$this->db->error(); return -1; } } /** * Create an intervention into data base * * @param User $user Objet user that make creation * @param int $notrigger Disable all triggers * @return int <0 if KO, >0 if OK */ function create($user, $notrigger=0) { global $conf, $user, $langs; dol_syslog(get_class($this)."::create ref=".$this->ref); // Check parameters if (! empty($this->ref)) // We check that ref is not already used { $result=self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used if ($result > 0) { $this->error='ErrorRefAlreadyExists'; dol_syslog(get_class($this)."::create ".$this->error,LOG_WARNING); $this->db->rollback(); return -1; } } if (! is_numeric($this->duration)) $this->duration = 0; if ($this->socid <= 0) { $this->error='ErrorBadParameterForFunc'; dol_syslog(get_class($this)."::create ".$this->error,LOG_ERR); return -1; } $soc = new Societe($this->db); $result=$soc->fetch($this->socid); $now=dol_now(); $this->db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."fichinter ("; $sql.= "fk_soc"; $sql.= ", datec"; $sql.= ", ref"; $sql.= ", entity"; $sql.= ", fk_user_author"; $sql.= ", fk_user_modif"; $sql.= ", description"; $sql.= ", model_pdf"; $sql.= ", fk_projet"; $sql.= ", fk_contrat"; $sql.= ", fk_statut"; $sql.= ", note_private"; $sql.= ", note_public"; $sql.= ") "; $sql.= " VALUES ("; $sql.= $this->socid; $sql.= ", '".$this->db->idate($now)."'"; $sql.= ", '".$this->db->escape($this->ref)."'"; $sql.= ", ".$conf->entity; $sql.= ", ".$user->id; $sql.= ", ".$user->id; $sql.= ", ".($this->description?"'".$this->db->escape($this->description)."'":"null"); $sql.= ", '".$this->db->escape($this->modelpdf)."'"; $sql.= ", ".($this->fk_project ? $this->fk_project : 0); $sql.= ", ".($this->fk_contrat ? $this->fk_contrat : 0); $sql.= ", ".$this->statut; $sql.= ", ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null"); $sql.= ", ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null"); $sql.= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); $result=$this->db->query($sql); if ($result) { $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX."fichinter"); if ($this->id) { $this->ref='(PROV'.$this->id.')'; $sql = 'UPDATE '.MAIN_DB_PREFIX."fichinter SET ref='".$this->ref."' WHERE rowid=".$this->id; dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) $error++; } if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { $result=$this->insertExtraFields(); if ($result < 0) { $error++; } } // Add linked object if (! $error && $this->origin && $this->origin_id) { $ret = $this->add_object_linked(); if (! $ret) dol_print_error($this->db); } if (! $notrigger) { // Call trigger $result=$this->call_trigger('FICHINTER_CREATE',$user); if ($result < 0) { $error++; } // End call triggers } if (! $error) { $this->db->commit(); return $this->id; } else { $this->db->rollback(); $this->error=join(',',$this->errors); dol_syslog(get_class($this)."::create ".$this->error,LOG_ERR); return -1; } } else { $this->error=$this->db->error(); $this->db->rollback(); return -1; } } /** * Update an intervention * * @param User $user Objet user that make creation * @param int $notrigger Disable all triggers * @return int <0 if KO, >0 if OK */ function update($user, $notrigger=0) { if (! is_numeric($this->duration)) { $this->duration = 0; } if (! dol_strlen($this->fk_project)) { $this->fk_project = 0; } $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter SET "; $sql.= "description = '".$this->db->escape($this->description)."'"; $sql.= ", duree = ".$this->duration; $sql.= ", fk_projet = ".$this->fk_project; $sql.= ", note_private = ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null"); $sql.= ", note_public = ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null"); $sql.= ", fk_user_modif = ".$user->id; $sql.= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::update", LOG_DEBUG); if ($this->db->query($sql)) { if (! $notrigger) { // Call trigger $result=$this->call_trigger('FICHINTER_MODIFY',$user); if ($result < 0) { $error++; $this->db->rollback(); return -1; } // End call triggers } $this->db->commit(); return 1; } else { $this->error=$this->db->error(); $this->db->rollback(); return -1; } } /** * Fetch a intervention * * @param int $rowid Id of intervention * @param string $ref Ref of intervention * @return int <0 if KO, >0 if OK */ function fetch($rowid,$ref='') { $sql = "SELECT f.rowid, f.ref, f.description, f.fk_soc, f.fk_statut,"; $sql.= " f.datec, f.dateo, f.datee, f.datet,"; $sql.= " f.date_valid as datev,"; $sql.= " f.tms as datem,"; $sql.= " f.duree, f.fk_projet, f.note_public, f.note_private, f.model_pdf, f.extraparams, fk_contrat"; $sql.= " FROM ".MAIN_DB_PREFIX."fichinter as f"; if ($ref) $sql.= " WHERE f.ref='".$this->db->escape($ref)."'"; else $sql.= " WHERE f.rowid=".$rowid; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; $this->ref = $obj->ref; $this->description = $obj->description; $this->socid = $obj->fk_soc; $this->statut = $obj->fk_statut; $this->duration = $obj->duree; $this->datec = $this->db->jdate($obj->datec); $this->datee = $this->db->jdate($obj->dateo); $this->dateo = $this->db->jdate($obj->datee); $this->datet = $this->db->jdate($obj->datet); $this->datev = $this->db->jdate($obj->datev); $this->datem = $this->db->jdate($obj->datem); $this->fk_project = $obj->fk_projet; $this->note_public = $obj->note_public; $this->note_private = $obj->note_private; $this->modelpdf = $obj->model_pdf; $this->fk_contrat = $obj->fk_contrat; $this->extraparams = (array) json_decode($obj->extraparams, true); if ($this->statut == 0) $this->brouillon = 1; require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); $extrafields=new ExtraFields($this->db); $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); $this->fetch_optionals($this->id,$extralabels); /* * Lines */ $result=$this->fetch_lines(); if ($result < 0) { return -3; } $this->db->free($resql); return 1; } } else { $this->error=$this->db->lasterror(); return -1; } } /** * Set status to draft * * @param User $user User that set draft * @return int <0 if KO, >0 if OK */ function setDraft($user) { global $langs, $conf; if ($this->statut != 0) { $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter"; $sql.= " SET fk_statut = 0"; $sql.= " WHERE rowid = ".$this->id; $sql.= " AND entity = ".$conf->entity; dol_syslog("Fichinter::setDraft", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { $this->db->commit(); return 1; } else { $this->db->rollback(); $this->error=$this->db->lasterror(); return -1; } } } /** * Validate a intervention * * @param User $user User that validate * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function setValid($user, $notrigger=0) { global $conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $error=0; if ($this->statut != 1) { $this->db->begin(); $now=dol_now(); // Define new ref if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life { $num = $this->getNextNumRef($this->thirdparty); } else { $num = $this->ref; } $this->newref = $num; $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter"; $sql.= " SET fk_statut = 1"; $sql.= ", ref = '".$num."'"; $sql.= ", date_valid = '".$this->db->idate($now)."'"; $sql.= ", fk_user_valid = ".$user->id; $sql.= " WHERE rowid = ".$this->id; $sql.= " AND entity = ".$conf->entity; $sql.= " AND fk_statut = 0"; dol_syslog(get_class($this)."::setValid", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { dol_print_error($this->db); $error++; } if (! $error && ! $notrigger) { // Call trigger $result=$this->call_trigger('FICHINTER_VALIDATE',$user); if ($result < 0) { $error++; } // End call triggers } if (! $error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Rename of object directory ($this->ref = old ref, $num = new ref) // to not lose the linked files $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->ficheinter->dir_output.'/'.$oldref; $dirdest = $conf->ficheinter->dir_output.'/'.$newref; if (file_exists($dirsource)) { dol_syslog(get_class($this)."::setValid rename dir ".$dirsource." into ".$dirdest); if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles=dol_dir_list($conf->ficheinter->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); foreach($listoffiles as $fileentry) { $dirsource=$fileentry['name']; $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); $dirsource=$fileentry['path'].'/'.$dirsource; $dirdest=$fileentry['path'].'/'.$dirdest; @rename($dirsource, $dirdest); } } } } } // Set new ref and define current statut if (! $error) { $this->ref = $num; $this->statut=1; $this->brouillon=0; $this->date_validation=$now; } if (! $error) { $this->db->commit(); return 1; } else { $this->db->rollback(); dol_syslog(get_class($this)."::setValid ".$this->error,LOG_ERR); return -1; } } } /** * Returns the label status * * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto * @return string Label */ function getLibStatut($mode=0) { return $this->LibStatut($this->statut,$mode); } /** * Returns the label of a statut * * @param int $statut id statut * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto * @return string Label */ function LibStatut($statut,$mode=0) { global $langs; if ($mode == 0) return $langs->trans($this->statuts[$statut]); if ($mode == 1) return $langs->trans($this->statuts_short[$statut]); if ($mode == 2) return img_picto($langs->trans($this->statuts_short[$statut]), $this->statuts_logo[$statut]).' '.$langs->trans($this->statuts_short[$statut]); if ($mode == 3) return img_picto($langs->trans($this->statuts_short[$statut]), $this->statuts_logo[$statut]); if ($mode == 4) return img_picto($langs->trans($this->statuts_short[$statut]),$this->statuts_logo[$statut]).' '.$langs->trans($this->statuts[$statut]); if ($mode == 5) return '<span class="hideonsmartphone">'.$langs->trans($this->statuts_short[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),$this->statuts_logo[$statut]); if ($mode == 6) return '<span class="hideonsmartphone">'.$langs->trans($this->statuts[$statut]).' </span>'.img_picto($langs->trans($this->statuts[$statut]),$this->statuts_logo[$statut]); return ''; } /** * Return clicable name (with picto eventually) * * @param int $withpicto 0=_No picto, 1=Includes the picto in the linkn, 2=Picto only * @param string $option Options * @return string String with URL */ function getNomUrl($withpicto=0,$option='') { global $langs; $result=''; $label = '<u>' . $langs->trans("ShowIntervention") . '</u>'; if (! empty($this->ref)) $label .= '<br><b>' . $langs->trans('Ref') . ':</b> '.$this->ref; $link = '<a href="'.DOL_URL_ROOT.'/fichinter/card.php?id='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; $linkend='</a>'; $picto='intervention'; if ($withpicto) $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); if ($withpicto && $withpicto != 2) $result.=' '; if ($withpicto != 2) $result.=$link.$this->ref.$linkend; return $result; } /** * Returns the next non used reference of intervention * depending on the module numbering assets within FICHEINTER_ADDON * * @param Societe $soc Thirdparty object * @return string Free reference for intervention */ function getNextNumRef($soc) { global $conf, $db, $langs; $langs->load("interventions"); if (! empty($conf->global->FICHEINTER_ADDON)) { $mybool = false; $file = "mod_".$conf->global->FICHEINTER_ADDON.".php"; $classname = "mod_".$conf->global->FICHEINTER_ADDON; // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/fichinter/"); // Load file with numbering class (if found) $mybool|=@include_once $dir.$file; } if (! $mybool) { dol_print_error('',"Failed to include file ".$file); return ''; } $obj = new $classname(); $numref = ""; $numref = $obj->getNextValue($soc,$this); if ( $numref != "") { return $numref; } else { dol_print_error($db,"Fichinter::getNextNumRef ".$obj->error); return ""; } } else { $langs->load("errors"); print $langs->trans("Error")." ".$langs->trans("Error_FICHEINTER_ADDON_NotDefined"); return ""; } } /** * Load information on object * * @param int $id Id of object * @return void */ function info($id) { global $conf; $sql = "SELECT f.rowid,"; $sql.= " f.datec,"; $sql.= " f.tms as date_modification,"; $sql.= " f.date_valid as datev,"; $sql.= " f.fk_user_author,"; $sql.= " f.fk_user_modif as fk_user_modification,"; $sql.= " f.fk_user_valid"; $sql.= " FROM ".MAIN_DB_PREFIX."fichinter as f"; $sql.= " WHERE f.rowid = ".$id; $sql.= " AND f.entity = ".$conf->entity; $resql = $this->db->query($sql); if ($resql) { if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; $this->date_creation = $this->db->jdate($obj->datec); $this->date_modification = $this->db->jdate($obj->date_modification); $this->date_validation = $this->db->jdate($obj->datev); $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } if ($obj->fk_user_modification) { $muser = new User($this->db); $muser->fetch($obj->fk_user_modification); $this->user_modification = $muser; } } $this->db->free($resql); } else { dol_print_error($this->db); } } /** * Delete intervetnion * * @param User $user Object user who delete * @param int $notrigger Disable trigger * @return int <0 if KO, >0 if OK */ function delete($user, $notrigger=0) { global $conf,$langs; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $error=0; $this->db->begin(); // Delete linked object $res = $this->deleteObjectLinked(); if ($res < 0) $error++; // Delete linked contacts $res = $this->delete_linked_contact(); if ($res < 0) { $this->error='ErrorFailToDeleteLinkedContact'; $error++; } if ($error) { $this->db->rollback(); return -1; } $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet"; $sql.= " WHERE fk_fichinter = ".$this->id; dol_syslog("Fichinter::delete", LOG_DEBUG); if ( $this->db->query($sql) ) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinter"; $sql.= " WHERE rowid = ".$this->id; $sql.= " AND entity = ".$conf->entity; dol_syslog("Fichinter::delete", LOG_DEBUG); if ( $this->db->query($sql) ) { // Remove directory with files $fichinterref = dol_sanitizeFileName($this->ref); if ($conf->ficheinter->dir_output) { $dir = $conf->ficheinter->dir_output . "/" . $fichinterref ; $file = $conf->ficheinter->dir_output . "/" . $fichinterref . "/" . $fichinterref . ".pdf"; if (file_exists($file)) { dol_delete_preview($this); if (! dol_delete_file($file,0,0,0,$this)) // For triggers { $this->error=$langs->trans("ErrorCanNotDeleteFile",$file); return 0; } } if (file_exists($dir)) { if (! dol_delete_dir_recursive($dir)) { $this->error=$langs->trans("ErrorCanNotDeleteDir",$dir); return 0; } } } if (! $notrigger) { // Call trigger $result=$this->call_trigger('FICHINTER_DELETE',$user); if ($result < 0) { $error++; $this->db->rollback(); return -1; } // End call triggers } $this->db->commit(); return 1; } else { $this->error=$this->db->lasterror(); $this->db->rollback(); return -2; } } else { $this->error=$this->db->lasterror(); $this->db->rollback(); return -1; } } /** * Defines a delivery date of intervention * * @param User $user Object user who define * @param date $date_delivery date of delivery * @return int <0 if ko, >0 if ok */ function set_date_delivery($user, $date_delivery) { global $conf; if ($user->rights->ficheinter->creer) { $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter "; $sql.= " SET datei = '".$this->db->idate($date_delivery)."'"; $sql.= " WHERE rowid = ".$this->id; $sql.= " AND entity = ".$conf->entity; $sql.= " AND fk_statut = 0"; if ($this->db->query($sql)) { $this->date_delivery = $date_delivery; return 1; } else { $this->error=$this->db->error(); dol_syslog("Fichinter::set_date_delivery Erreur SQL"); return -1; } } } /** * Define the label of the intervention * * @param User $user Object user who modify * @param string $description description * @return int <0 if KO, >0 if OK */ function set_description($user, $description) { global $conf; if ($user->rights->ficheinter->creer) { $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter "; $sql.= " SET description = '".$this->db->escape($description)."',"; $sql.= " fk_user_modif = ".$user->id; $sql.= " WHERE rowid = ".$this->id; $sql.= " AND entity = ".$conf->entity; if ($this->db->query($sql)) { $this->description = $description; return 1; } else { $this->error=$this->db->error(); dol_syslog("Fichinter::set_description Erreur SQL"); return -1; } } } /** * Link intervention to a contract * * @param User $user Object user who modify * @param int $contractid Description * @return int <0 if ko, >0 if ok */ function set_contrat($user, $contractid) { global $conf; if ($user->rights->ficheinter->creer) { $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter "; $sql.= " SET fk_contrat = '".$contractid."'"; $sql.= " WHERE rowid = ".$this->id; $sql.= " AND entity = ".$conf->entity; if ($this->db->query($sql)) { $this->fk_contrat = $contractid; return 1; } else { $this->error=$this->db->error(); return -1; } } return -2; } /** * Load an object from its id and create a new one in database * * @param int $socid Id of thirdparty * @return int New id of clone */ function createFromClone($socid=0) { global $user,$hookmanager; $error=0; $this->context['createfromclone'] = 'createfromclone'; $this->db->begin(); // get extrafields so they will be clone foreach($this->lines as $line) $line->fetch_optionals($line->rowid); // Load source object $objFrom = clone $this; // Change socid if needed if (! empty($socid) && $socid != $this->socid) { $objsoc = new Societe($this->db); if ($objsoc->fetch($socid)>0) { $this->socid = $objsoc->id; //$this->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); //$this->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); $this->fk_project = ''; $this->fk_delivery_address = ''; } // TODO Change product price if multi-prices } $this->id=0; $this->ref = ''; $this->statut=0; // Clear fields $this->user_author_id = $user->id; $this->user_valid = ''; $this->date_creation = ''; $this->date_validation = ''; $this->ref_client = ''; // Create clone $result=$this->create($user); if ($result < 0) $error++; if (! $error) { // Add lines because it is not included into create function foreach ($this->lines as $line) { $this->addline($user, $this->id, $line->desc, $line->datei, $line->duration); } // Hook of thirdparty module if (is_object($hookmanager)) { $parameters=array('objFrom'=>$objFrom); $action=''; $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) $error++; } // Call trigger $result=$this->call_trigger('INTERVENTION_CLONE',$user); if ($result < 0) $error++; // End call triggers } unset($this->context['createfromclone']); // End if (! $error) { $this->db->commit(); return $this->id; } else { $this->db->rollback(); return -1; } } /** * Adding a line of intervention into data base * * @param user $user User that do the action * @param int $fichinterid Id of intervention * @param string $desc Line description * @param date $date_intervention Intervention date * @param int $duration Intervention duration * @param array $array_options Array option * @return int >0 if ok, <0 if ko */ function addline($user,$fichinterid, $desc, $date_intervention, $duration, $array_options='') { dol_syslog(get_class($this)."::addline $fichinterid, $desc, $date_intervention, $duration"); if ($this->statut == 0) { $this->db->begin(); // Insertion ligne $line=new FichinterLigne($this->db); $line->fk_fichinter = $fichinterid; $line->desc = $desc; $line->datei = $date_intervention; $line->duration = $duration; if (is_array($array_options) && count($array_options)>0) { $line->array_options=$array_options; } $result=$line->insert($user); if ($result >= 0) { $this->db->commit(); return 1; } else { $this->error=$this->db->error(); $this->db->rollback(); return -1; } } } /** * Initialise an instance with random values. * Used to build previews or test instances. * id must be 0 if object instance is a specimen. * * @return void */ function initAsSpecimen() { global $user,$langs,$conf; $now=dol_now(); // Initialise parametres $this->id=0; $this->ref = 'SPECIMEN'; $this->specimen=1; $this->socid = 1; $this->datec = $now; $this->note_private='Private note'; $this->note_public='SPECIMEN'; $this->duration = 0; $nbp = 25; $xnbp = 0; while ($xnbp < $nbp) { $line=new FichinterLigne($this->db); $line->desc=$langs->trans("Description")." ".$xnbp; $line->datei=($now-3600*(1+$xnbp)); $line->duration=600; $line->fk_fichinter=0; $this->lines[$xnbp]=$line; $xnbp++; $this->duration+=$line->duration; } } /** * Load array lines ->lines * * @return int <0 if KO, >0 if OK */ function fetch_lines() { $sql = 'SELECT rowid, description, duree, date, rang'; $sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet'; $sql.=' WHERE fk_fichinter = '.$this->id .' ORDER BY rang ASC, date ASC' ; dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); $i = 0; while ($i < $num) { $objp = $this->db->fetch_object($resql); $line = new FichinterLigne($this->db); $line->id = $objp->rowid; $line->desc = $objp->description; $line->duration = $objp->duree; //For invoicing we calculing hours $line->qty = round($objp->duree/3600,2); $line->date = $this->db->jdate($objp->date); $line->datei = $this->db->jdate($objp->date); $line->rang = $objp->rang; $line->product_type = 1; $this->lines[$i] = $line; $i++; } $this->db->free($resql); return 1; } else { $this->error=$this->db->error(); return -1; } } /** * Function used to replace a thirdparty id with another one. * * @param DoliDB $db Database handler * @param int $origin_id Old thirdparty id * @param int $dest_id New thirdparty id * @return bool */ public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id) { $tables = array( 'fichinter' ); return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); } } /** * Classe permettant la gestion des lignes d'intervention */ class FichinterLigne extends CommonObjectLine { var $db; var $error; // From llx_fichinterdet var $fk_fichinter; var $desc; // Description ligne var $datei; // Date intervention var $duration; // Duree de l'intervention var $rang = 0; public $element='fichinterdet'; public $table_element='fichinterdet'; public $fk_element='fk_fichinter'; /** * Constructor * * @param DoliDB $db Database handler */ function __construct($db) { $this->db = $db; } /** * Retrieve the line of intervention * * @param int $rowid Line id * @return int <0 if KO, >0 if OK */ function fetch($rowid) { $sql = 'SELECT ft.rowid, ft.fk_fichinter, ft.description, ft.duree, ft.rang,'; $sql.= ' ft.date as datei'; $sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet as ft'; $sql.= ' WHERE ft.rowid = '.$rowid; dol_syslog("FichinterLigne::fetch", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { $objp = $this->db->fetch_object($result); $this->rowid = $objp->rowid; $this->id = $objp->rowid; $this->fk_fichinter = $objp->fk_fichinter; $this->datei = $this->db->jdate($objp->datei); $this->desc = $objp->description; $this->duration = $objp->duree; $this->rang = $objp->rang; $this->db->free($result); return 1; } else { $this->error=$this->db->error().' sql='.$sql; return -1; } } /** * Insert the line into database * * @param User $user Objet user that make creation * @param int $notrigger Disable all triggers * @return int <0 if ko, >0 if ok */ function insert($user, $notrigger=0) { global $langs,$conf; dol_syslog("FichinterLigne::insert rang=".$this->rang); $this->db->begin(); $rangToUse=$this->rang; if ($rangToUse == -1) { // Recupere rang max de la ligne d'intervention dans $rangmax $sql = 'SELECT max(rang) as max FROM '.MAIN_DB_PREFIX.'fichinterdet'; $sql.= ' WHERE fk_fichinter ='.$this->fk_fichinter; $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); $rangToUse = $obj->max + 1; } else { dol_print_error($this->db); $this->db->rollback(); return -1; } } // Insertion dans base de la ligne $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'fichinterdet'; $sql.= ' (fk_fichinter, description, date, duree, rang)'; $sql.= " VALUES (".$this->fk_fichinter.","; $sql.= " '".$this->db->escape($this->desc)."',"; $sql.= " '".$this->db->idate($this->datei)."',"; $sql.= " ".$this->duration.","; $sql.= ' '.$rangToUse; $sql.= ')'; dol_syslog("FichinterLigne::insert", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'fichinterdet'); if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { $this->id=$this->rowid; $result=$this->insertExtraFields(); if ($result < 0) { $error++; } } $result=$this->update_total(); if ($result > 0) { $this->rang=$rangToUse; if (! $notrigger) { // Call trigger $result=$this->call_trigger('LINEFICHINTER_CREATE',$user); if ($result < 0) { $error++; } // End call triggers } } if (!$error) { $this->db->commit(); return $result; } else { $this->db->rollback(); return -1; } } else { $this->error=$this->db->error()." sql=".$sql; $this->db->rollback(); return -1; } } /** * Update intervention into database * * @param User $user Objet user that make creation * @param int $notrigger Disable all triggers * @return int <0 if ko, >0 if ok */ function update($user,$notrigger=0) { global $langs,$conf; $this->db->begin(); // Mise a jour ligne en base $sql = "UPDATE ".MAIN_DB_PREFIX."fichinterdet SET"; $sql.= " description='".$this->db->escape($this->desc)."'"; $sql.= ",date='".$this->db->idate($this->datei)."'"; $sql.= ",duree=".$this->duration; $sql.= ",rang='".$this->rang."'"; $sql.= " WHERE rowid = ".$this->rowid; dol_syslog("FichinterLigne::update", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { $this->id=$this->rowid; $result=$this->insertExtraFields(); if ($result < 0) { $error++; } } $result=$this->update_total(); if ($result > 0) { if (! $notrigger) { // Call trigger $result=$this->call_trigger('LINEFICHINTER_UPDATE',$user); if ($result < 0) { $error++; } // End call triggers } } if (!$error) { $this->db->commit(); return $result; } else { $this->error=$this->db->lasterror(); $this->db->rollback(); return -1; } } else { $this->error=$this->db->lasterror(); $this->db->rollback(); return -1; } } /** * Update total duration into llx_fichinter * * @return int <0 si ko, >0 si ok */ function update_total() { global $conf; $this->db->begin(); $sql = "SELECT SUM(duree) as total_duration, min(date) as dateo, max(date) as datee "; $sql.= " FROM ".MAIN_DB_PREFIX."fichinterdet"; $sql.= " WHERE fk_fichinter=".$this->fk_fichinter; dol_syslog("FichinterLigne::update_total", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { $obj=$this->db->fetch_object($resql); $total_duration=0; if (!empty($obj->total_duration)) $total_duration = $obj->total_duration; $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter"; $sql.= " SET duree = ".$total_duration; $sql.= " , dateo = ".(! empty($obj->dateo)?"'".$this->db->idate($obj->dateo)."'":"null"); $sql.= " , datee = ".(! empty($obj->datee)?"'".$this->db->idate($obj->datee)."'":"null"); $sql.= " WHERE rowid = ".$this->fk_fichinter; $sql.= " AND entity = ".$conf->entity; dol_syslog("FichinterLigne::update_total", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { $this->db->commit(); return 1; } else { $this->error=$this->db->error(); $this->db->rollback(); return -2; } } else { $this->error=$this->db->error(); $this->db->rollback(); return -1; } } /** * Delete a intervention line * * @param User $user Objet user that make creation * @param int $notrigger Disable all triggers * @return int >0 if ok, <0 if ko */ function deleteline($user,$notrigger=0) { global $langs,$conf; if ($this->statut == 0) { dol_syslog(get_class($this)."::deleteline lineid=".$this->rowid); $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet WHERE rowid = ".$this->rowid; $resql = $this->db->query($sql); if ($resql) { $result = $this->update_total(); if ($result > 0) { if (! $notrigger) { // Call trigger $result=$this->call_trigger('LINEFICHINTER_DELETE',$user); if ($result < 0) { $error++; $this->db->rollback(); return -1; } // End call triggers } $this->db->commit(); return $result; } else { $this->db->rollback(); return -1; } } else { $this->error=$this->db->error()." sql=".$sql; $this->db->rollback(); return -1; } } else { return -2; } } }
Murerr/GERESA
htdocs/fichinter/class/fichinter.class.php
PHP
gpl-3.0
38,819
// Copyright (C) 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ****************************************************************************** * * Copyright (C) 2001-2014, International Business Machines * Corporation and others. All Rights Reserved. * ****************************************************************************** * file name: utrie2_builder.cpp * encoding: US-ASCII * tab size: 8 (not used) * indentation:4 * * created on: 2008sep26 (split off from utrie2.c) * created by: Markus W. Scherer * * This is a common implementation of a Unicode trie. * It is a kind of compressed, serializable table of 16- or 32-bit values associated with * Unicode code points (0..0x10ffff). * This is the second common version of a Unicode trie (hence the name UTrie2). * See utrie2.h for a comparison. * * This file contains only the builder code. * See utrie2.c for the runtime and enumeration code. */ #ifdef UTRIE2_DEBUG # include <stdio.h> #endif #include "unicode/utypes.h" #include "cmemory.h" #include "utrie2.h" #include "utrie2_impl.h" #include "utrie.h" /* for utrie2_fromUTrie() and utrie_swap() */ /* Implementation notes ----------------------------------------------------- */ /* * The UTRIE2_SHIFT_1, UTRIE2_SHIFT_2, UTRIE2_INDEX_SHIFT and other values * have been chosen to minimize trie sizes overall. * Most of the code is flexible enough to work with a range of values, * within certain limits. * * Exception: Support for separate values for lead surrogate code _units_ * vs. code _points_ was added after the constants were fixed, * and has not been tested nor particularly designed for different constant values. * (Especially the utrie2_enum() code that jumps to the special LSCP index-2 * part and back.) * * Requires UTRIE2_SHIFT_2<=6. Otherwise 0xc0 which is the top of the ASCII-linear data * including the bad-UTF-8-data block is not a multiple of UTRIE2_DATA_BLOCK_LENGTH * and map[block>>UTRIE2_SHIFT_2] (used in reference counting and compaction * remapping) stops working. * * Requires UTRIE2_SHIFT_1>=10 because utrie2_enumForLeadSurrogate() * assumes that a single index-2 block is used for 0x400 code points * corresponding to one lead surrogate. * * Requires UTRIE2_SHIFT_1<=16. Otherwise one single index-2 block contains * more than one Unicode plane, and the split of the index-2 table into a BMP * part and a supplementary part, with a gap in between, would not work. * * Requires UTRIE2_INDEX_SHIFT>=1 not because of the code but because * there is data with more than 64k distinct values, * for example for Unihan collation with a separate collation weight per * Han character. */ /* Building a trie ----------------------------------------------------------*/ enum { /** The null index-2 block, following the gap in the index-2 table. */ UNEWTRIE2_INDEX_2_NULL_OFFSET=UNEWTRIE2_INDEX_GAP_OFFSET+UNEWTRIE2_INDEX_GAP_LENGTH, /** The start of allocated index-2 blocks. */ UNEWTRIE2_INDEX_2_START_OFFSET=UNEWTRIE2_INDEX_2_NULL_OFFSET+UTRIE2_INDEX_2_BLOCK_LENGTH, /** * The null data block. * Length 64=0x40 even if UTRIE2_DATA_BLOCK_LENGTH is smaller, * to work with 6-bit trail bytes from 2-byte UTF-8. */ UNEWTRIE2_DATA_NULL_OFFSET=UTRIE2_DATA_START_OFFSET, /** The start of allocated data blocks. */ UNEWTRIE2_DATA_START_OFFSET=UNEWTRIE2_DATA_NULL_OFFSET+0x40, /** * The start of data blocks for U+0800 and above. * Below, compaction uses a block length of 64 for 2-byte UTF-8. * From here on, compaction uses UTRIE2_DATA_BLOCK_LENGTH. * Data values for 0x780 code points beyond ASCII. */ UNEWTRIE2_DATA_0800_OFFSET=UNEWTRIE2_DATA_START_OFFSET+0x780 }; /* Start with allocation of 16k data entries. */ #define UNEWTRIE2_INITIAL_DATA_LENGTH ((int32_t)1<<14) /* Grow about 8x each time. */ #define UNEWTRIE2_MEDIUM_DATA_LENGTH ((int32_t)1<<17) static int32_t allocIndex2Block(UNewTrie2 *trie); U_CAPI UTrie2 * U_EXPORT2 utrie2_open(uint32_t initialValue, uint32_t errorValue, UErrorCode *pErrorCode) { UTrie2 *trie; UNewTrie2 *newTrie; uint32_t *data; int32_t i, j; if(U_FAILURE(*pErrorCode)) { return NULL; } trie=(UTrie2 *)uprv_malloc(sizeof(UTrie2)); newTrie=(UNewTrie2 *)uprv_malloc(sizeof(UNewTrie2)); data=(uint32_t *)uprv_malloc(UNEWTRIE2_INITIAL_DATA_LENGTH*4); if(trie==NULL || newTrie==NULL || data==NULL) { uprv_free(trie); uprv_free(newTrie); uprv_free(data); *pErrorCode=U_MEMORY_ALLOCATION_ERROR; return 0; } uprv_memset(trie, 0, sizeof(UTrie2)); trie->initialValue=initialValue; trie->errorValue=errorValue; trie->highStart=0x110000; trie->newTrie=newTrie; newTrie->data=data; newTrie->dataCapacity=UNEWTRIE2_INITIAL_DATA_LENGTH; newTrie->initialValue=initialValue; newTrie->errorValue=errorValue; newTrie->highStart=0x110000; newTrie->firstFreeBlock=0; /* no free block in the list */ newTrie->isCompacted=FALSE; /* * preallocate and reset * - ASCII * - the bad-UTF-8-data block * - the null data block */ for(i=0; i<0x80; ++i) { newTrie->data[i]=initialValue; } for(; i<0xc0; ++i) { newTrie->data[i]=errorValue; } for(i=UNEWTRIE2_DATA_NULL_OFFSET; i<UNEWTRIE2_DATA_START_OFFSET; ++i) { newTrie->data[i]=initialValue; } newTrie->dataNullOffset=UNEWTRIE2_DATA_NULL_OFFSET; newTrie->dataLength=UNEWTRIE2_DATA_START_OFFSET; /* set the index-2 indexes for the 2=0x80>>UTRIE2_SHIFT_2 ASCII data blocks */ for(i=0, j=0; j<0x80; ++i, j+=UTRIE2_DATA_BLOCK_LENGTH) { newTrie->index2[i]=j; newTrie->map[i]=1; } /* reference counts for the bad-UTF-8-data block */ for(; j<0xc0; ++i, j+=UTRIE2_DATA_BLOCK_LENGTH) { newTrie->map[i]=0; } /* * Reference counts for the null data block: all blocks except for the ASCII blocks. * Plus 1 so that we don't drop this block during compaction. * Plus as many as needed for lead surrogate code points. */ /* i==newTrie->dataNullOffset */ newTrie->map[i++]= (0x110000>>UTRIE2_SHIFT_2)- (0x80>>UTRIE2_SHIFT_2)+ 1+ UTRIE2_LSCP_INDEX_2_LENGTH; j+=UTRIE2_DATA_BLOCK_LENGTH; for(; j<UNEWTRIE2_DATA_START_OFFSET; ++i, j+=UTRIE2_DATA_BLOCK_LENGTH) { newTrie->map[i]=0; } /* * set the remaining indexes in the BMP index-2 block * to the null data block */ for(i=0x80>>UTRIE2_SHIFT_2; i<UTRIE2_INDEX_2_BMP_LENGTH; ++i) { newTrie->index2[i]=UNEWTRIE2_DATA_NULL_OFFSET; } /* * Fill the index gap with impossible values so that compaction * does not overlap other index-2 blocks with the gap. */ for(i=0; i<UNEWTRIE2_INDEX_GAP_LENGTH; ++i) { newTrie->index2[UNEWTRIE2_INDEX_GAP_OFFSET+i]=-1; } /* set the indexes in the null index-2 block */ for(i=0; i<UTRIE2_INDEX_2_BLOCK_LENGTH; ++i) { newTrie->index2[UNEWTRIE2_INDEX_2_NULL_OFFSET+i]=UNEWTRIE2_DATA_NULL_OFFSET; } newTrie->index2NullOffset=UNEWTRIE2_INDEX_2_NULL_OFFSET; newTrie->index2Length=UNEWTRIE2_INDEX_2_START_OFFSET; /* set the index-1 indexes for the linear index-2 block */ for(i=0, j=0; i<UTRIE2_OMITTED_BMP_INDEX_1_LENGTH; ++i, j+=UTRIE2_INDEX_2_BLOCK_LENGTH ) { newTrie->index1[i]=j; } /* set the remaining index-1 indexes to the null index-2 block */ for(; i<UNEWTRIE2_INDEX_1_LENGTH; ++i) { newTrie->index1[i]=UNEWTRIE2_INDEX_2_NULL_OFFSET; } /* * Preallocate and reset data for U+0080..U+07ff, * for 2-byte UTF-8 which will be compacted in 64-blocks * even if UTRIE2_DATA_BLOCK_LENGTH is smaller. */ for(i=0x80; i<0x800; i+=UTRIE2_DATA_BLOCK_LENGTH) { utrie2_set32(trie, i, initialValue, pErrorCode); } return trie; } static UNewTrie2 * cloneBuilder(const UNewTrie2 *other) { UNewTrie2 *trie; trie=(UNewTrie2 *)uprv_malloc(sizeof(UNewTrie2)); if(trie==NULL) { return NULL; } trie->data=(uint32_t *)uprv_malloc(other->dataCapacity*4); if(trie->data==NULL) { uprv_free(trie); return NULL; } trie->dataCapacity=other->dataCapacity; /* clone data */ uprv_memcpy(trie->index1, other->index1, sizeof(trie->index1)); uprv_memcpy(trie->index2, other->index2, (size_t)other->index2Length*4); trie->index2NullOffset=other->index2NullOffset; trie->index2Length=other->index2Length; uprv_memcpy(trie->data, other->data, (size_t)other->dataLength*4); trie->dataNullOffset=other->dataNullOffset; trie->dataLength=other->dataLength; /* reference counters */ if(other->isCompacted) { trie->firstFreeBlock=0; } else { uprv_memcpy(trie->map, other->map, ((size_t)other->dataLength>>UTRIE2_SHIFT_2)*4); trie->firstFreeBlock=other->firstFreeBlock; } trie->initialValue=other->initialValue; trie->errorValue=other->errorValue; trie->highStart=other->highStart; trie->isCompacted=other->isCompacted; return trie; } U_CAPI UTrie2 * U_EXPORT2 utrie2_clone(const UTrie2 *other, UErrorCode *pErrorCode) { UTrie2 *trie; if(U_FAILURE(*pErrorCode)) { return NULL; } if(other==NULL || (other->memory==NULL && other->newTrie==NULL)) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return NULL; } trie=(UTrie2 *)uprv_malloc(sizeof(UTrie2)); if(trie==NULL) { return NULL; } uprv_memcpy(trie, other, sizeof(UTrie2)); if(other->memory!=NULL) { trie->memory=uprv_malloc(other->length); if(trie->memory!=NULL) { trie->isMemoryOwned=TRUE; uprv_memcpy(trie->memory, other->memory, other->length); /* make the clone's pointers point to its own memory */ trie->index=(uint16_t *)trie->memory+(other->index-(uint16_t *)other->memory); if(other->data16!=NULL) { trie->data16=(uint16_t *)trie->memory+(other->data16-(uint16_t *)other->memory); } if(other->data32!=NULL) { trie->data32=(uint32_t *)trie->memory+(other->data32-(uint32_t *)other->memory); } } } else /* other->newTrie!=NULL */ { trie->newTrie=cloneBuilder(other->newTrie); } if(trie->memory==NULL && trie->newTrie==NULL) { uprv_free(trie); trie=NULL; } return trie; } typedef struct NewTrieAndStatus { UTrie2 *trie; UErrorCode errorCode; UBool exclusiveLimit; /* rather than inclusive range end */ } NewTrieAndStatus; static UBool U_CALLCONV copyEnumRange(const void *context, UChar32 start, UChar32 end, uint32_t value) { NewTrieAndStatus *nt=(NewTrieAndStatus *)context; if(value!=nt->trie->initialValue) { if(nt->exclusiveLimit) { --end; } if(start==end) { utrie2_set32(nt->trie, start, value, &nt->errorCode); } else { utrie2_setRange32(nt->trie, start, end, value, TRUE, &nt->errorCode); } return U_SUCCESS(nt->errorCode); } else { return TRUE; } } #ifdef UTRIE2_DEBUG static void utrie_printLengths(const UTrie *trie) { long indexLength=trie->indexLength; long dataLength=(long)trie->dataLength; long totalLength=(long)sizeof(UTrieHeader)+indexLength*2+dataLength*(trie->data32!=NULL ? 4 : 2); printf("**UTrieLengths** index:%6ld data:%6ld serialized:%6ld\n", indexLength, dataLength, totalLength); } static void utrie2_printLengths(const UTrie2 *trie, const char *which) { long indexLength=trie->indexLength; long dataLength=(long)trie->dataLength; long totalLength=(long)sizeof(UTrie2Header)+indexLength*2+dataLength*(trie->data32!=NULL ? 4 : 2); printf("**UTrie2Lengths(%s)** index:%6ld data:%6ld serialized:%6ld\n", which, indexLength, dataLength, totalLength); } #endif U_CAPI UTrie2 * U_EXPORT2 utrie2_cloneAsThawed(const UTrie2 *other, UErrorCode *pErrorCode) { NewTrieAndStatus context; UChar lead; if(U_FAILURE(*pErrorCode)) { return NULL; } if(other==NULL || (other->memory==NULL && other->newTrie==NULL)) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return NULL; } if(other->newTrie!=NULL && !other->newTrie->isCompacted) { return utrie2_clone(other, pErrorCode); /* clone an unfrozen trie */ } /* Clone the frozen trie by enumerating it and building a new one. */ context.trie=utrie2_open(other->initialValue, other->errorValue, pErrorCode); if(U_FAILURE(*pErrorCode)) { return NULL; } context.exclusiveLimit=FALSE; context.errorCode=*pErrorCode; utrie2_enum(other, NULL, copyEnumRange, &context); *pErrorCode=context.errorCode; for(lead=0xd800; lead<0xdc00; ++lead) { uint32_t value; if(other->data32==NULL) { value=UTRIE2_GET16_FROM_U16_SINGLE_LEAD(other, lead); } else { value=UTRIE2_GET32_FROM_U16_SINGLE_LEAD(other, lead); } if(value!=other->initialValue) { utrie2_set32ForLeadSurrogateCodeUnit(context.trie, lead, value, pErrorCode); } } if(U_FAILURE(*pErrorCode)) { utrie2_close(context.trie); context.trie=NULL; } return context.trie; } /* Almost the same as utrie2_cloneAsThawed() but copies a UTrie and freezes the clone. */ U_CAPI UTrie2 * U_EXPORT2 utrie2_fromUTrie(const UTrie *trie1, uint32_t errorValue, UErrorCode *pErrorCode) { NewTrieAndStatus context; UChar lead; if(U_FAILURE(*pErrorCode)) { return NULL; } if(trie1==NULL) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return NULL; } context.trie=utrie2_open(trie1->initialValue, errorValue, pErrorCode); if(U_FAILURE(*pErrorCode)) { return NULL; } context.exclusiveLimit=TRUE; context.errorCode=*pErrorCode; utrie_enum(trie1, NULL, copyEnumRange, &context); *pErrorCode=context.errorCode; for(lead=0xd800; lead<0xdc00; ++lead) { uint32_t value; if(trie1->data32==NULL) { value=UTRIE_GET16_FROM_LEAD(trie1, lead); } else { value=UTRIE_GET32_FROM_LEAD(trie1, lead); } if(value!=trie1->initialValue) { utrie2_set32ForLeadSurrogateCodeUnit(context.trie, lead, value, pErrorCode); } } if(U_SUCCESS(*pErrorCode)) { utrie2_freeze(context.trie, trie1->data32!=NULL ? UTRIE2_32_VALUE_BITS : UTRIE2_16_VALUE_BITS, pErrorCode); } #ifdef UTRIE2_DEBUG if(U_SUCCESS(*pErrorCode)) { utrie_printLengths(trie1); utrie2_printLengths(context.trie, "fromUTrie"); } #endif if(U_FAILURE(*pErrorCode)) { utrie2_close(context.trie); context.trie=NULL; } return context.trie; } static inline UBool isInNullBlock(UNewTrie2 *trie, UChar32 c, UBool forLSCP) { int32_t i2, block; if(U_IS_LEAD(c) && forLSCP) { i2=(UTRIE2_LSCP_INDEX_2_OFFSET-(0xd800>>UTRIE2_SHIFT_2))+ (c>>UTRIE2_SHIFT_2); } else { i2=trie->index1[c>>UTRIE2_SHIFT_1]+ ((c>>UTRIE2_SHIFT_2)&UTRIE2_INDEX_2_MASK); } block=trie->index2[i2]; return (UBool)(block==trie->dataNullOffset); } static int32_t allocIndex2Block(UNewTrie2 *trie) { int32_t newBlock, newTop; newBlock=trie->index2Length; newTop=newBlock+UTRIE2_INDEX_2_BLOCK_LENGTH; if(newTop>UPRV_LENGTHOF(trie->index2)) { /* * Should never occur. * Either UTRIE2_MAX_BUILD_TIME_INDEX_LENGTH is incorrect, * or the code writes more values than should be possible. */ return -1; } trie->index2Length=newTop; uprv_memcpy(trie->index2+newBlock, trie->index2+trie->index2NullOffset, UTRIE2_INDEX_2_BLOCK_LENGTH*4); return newBlock; } static int32_t getIndex2Block(UNewTrie2 *trie, UChar32 c, UBool forLSCP) { int32_t i1, i2; if(U_IS_LEAD(c) && forLSCP) { return UTRIE2_LSCP_INDEX_2_OFFSET; } i1=c>>UTRIE2_SHIFT_1; i2=trie->index1[i1]; if(i2==trie->index2NullOffset) { i2=allocIndex2Block(trie); if(i2<0) { return -1; /* program error */ } trie->index1[i1]=i2; } return i2; } static int32_t allocDataBlock(UNewTrie2 *trie, int32_t copyBlock) { int32_t newBlock, newTop; if(trie->firstFreeBlock!=0) { /* get the first free block */ newBlock=trie->firstFreeBlock; trie->firstFreeBlock=-trie->map[newBlock>>UTRIE2_SHIFT_2]; } else { /* get a new block from the high end */ newBlock=trie->dataLength; newTop=newBlock+UTRIE2_DATA_BLOCK_LENGTH; if(newTop>trie->dataCapacity) { /* out of memory in the data array */ int32_t capacity; uint32_t *data; if(trie->dataCapacity<UNEWTRIE2_MEDIUM_DATA_LENGTH) { capacity=UNEWTRIE2_MEDIUM_DATA_LENGTH; } else if(trie->dataCapacity<UNEWTRIE2_MAX_DATA_LENGTH) { capacity=UNEWTRIE2_MAX_DATA_LENGTH; } else { /* * Should never occur. * Either UNEWTRIE2_MAX_DATA_LENGTH is incorrect, * or the code writes more values than should be possible. */ return -1; } data=(uint32_t *)uprv_malloc(capacity*4); if(data==NULL) { return -1; } uprv_memcpy(data, trie->data, (size_t)trie->dataLength*4); uprv_free(trie->data); trie->data=data; trie->dataCapacity=capacity; } trie->dataLength=newTop; } uprv_memcpy(trie->data+newBlock, trie->data+copyBlock, UTRIE2_DATA_BLOCK_LENGTH*4); trie->map[newBlock>>UTRIE2_SHIFT_2]=0; return newBlock; } /* call when the block's reference counter reaches 0 */ static void releaseDataBlock(UNewTrie2 *trie, int32_t block) { /* put this block at the front of the free-block chain */ trie->map[block>>UTRIE2_SHIFT_2]=-trie->firstFreeBlock; trie->firstFreeBlock=block; } static inline UBool isWritableBlock(UNewTrie2 *trie, int32_t block) { return (UBool)(block!=trie->dataNullOffset && 1==trie->map[block>>UTRIE2_SHIFT_2]); } static inline void setIndex2Entry(UNewTrie2 *trie, int32_t i2, int32_t block) { int32_t oldBlock; ++trie->map[block>>UTRIE2_SHIFT_2]; /* increment first, in case block==oldBlock! */ oldBlock=trie->index2[i2]; if(0 == --trie->map[oldBlock>>UTRIE2_SHIFT_2]) { releaseDataBlock(trie, oldBlock); } trie->index2[i2]=block; } /** * No error checking for illegal arguments. * * @return -1 if no new data block available (out of memory in data array) * @internal */ static int32_t getDataBlock(UNewTrie2 *trie, UChar32 c, UBool forLSCP) { int32_t i2, oldBlock, newBlock; i2=getIndex2Block(trie, c, forLSCP); if(i2<0) { return -1; /* program error */ } i2+=(c>>UTRIE2_SHIFT_2)&UTRIE2_INDEX_2_MASK; oldBlock=trie->index2[i2]; if(isWritableBlock(trie, oldBlock)) { return oldBlock; } /* allocate a new data block */ newBlock=allocDataBlock(trie, oldBlock); if(newBlock<0) { /* out of memory in the data array */ return -1; } setIndex2Entry(trie, i2, newBlock); return newBlock; } /** * @return TRUE if the value was successfully set */ static void set32(UNewTrie2 *trie, UChar32 c, UBool forLSCP, uint32_t value, UErrorCode *pErrorCode) { int32_t block; if(trie==NULL || trie->isCompacted) { *pErrorCode=U_NO_WRITE_PERMISSION; return; } block=getDataBlock(trie, c, forLSCP); if(block<0) { *pErrorCode=U_MEMORY_ALLOCATION_ERROR; return; } trie->data[block+(c&UTRIE2_DATA_MASK)]=value; } U_CAPI void U_EXPORT2 utrie2_set32(UTrie2 *trie, UChar32 c, uint32_t value, UErrorCode *pErrorCode) { if(U_FAILURE(*pErrorCode)) { return; } if((uint32_t)c>0x10ffff) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return; } set32(trie->newTrie, c, TRUE, value, pErrorCode); } U_CAPI void U_EXPORT2 utrie2_set32ForLeadSurrogateCodeUnit(UTrie2 *trie, UChar32 c, uint32_t value, UErrorCode *pErrorCode) { if(U_FAILURE(*pErrorCode)) { return; } if(!U_IS_LEAD(c)) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return; } set32(trie->newTrie, c, FALSE, value, pErrorCode); } static void writeBlock(uint32_t *block, uint32_t value) { uint32_t *limit=block+UTRIE2_DATA_BLOCK_LENGTH; while(block<limit) { *block++=value; } } /** * initialValue is ignored if overwrite=TRUE * @internal */ static void fillBlock(uint32_t *block, UChar32 start, UChar32 limit, uint32_t value, uint32_t initialValue, UBool overwrite) { uint32_t *pLimit; pLimit=block+limit; block+=start; if(overwrite) { while(block<pLimit) { *block++=value; } } else { while(block<pLimit) { if(*block==initialValue) { *block=value; } ++block; } } } U_CAPI void U_EXPORT2 utrie2_setRange32(UTrie2 *trie, UChar32 start, UChar32 end, uint32_t value, UBool overwrite, UErrorCode *pErrorCode) { /* * repeat value in [start..end] * mark index values for repeat-data blocks by setting bit 31 of the index values * fill around existing values if any, if(overwrite) */ UNewTrie2 *newTrie; int32_t block, rest, repeatBlock; UChar32 limit; if(U_FAILURE(*pErrorCode)) { return; } if((uint32_t)start>0x10ffff || (uint32_t)end>0x10ffff || start>end) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return; } newTrie=trie->newTrie; if(newTrie==NULL || newTrie->isCompacted) { *pErrorCode=U_NO_WRITE_PERMISSION; return; } if(!overwrite && value==newTrie->initialValue) { return; /* nothing to do */ } limit=end+1; if(start&UTRIE2_DATA_MASK) { UChar32 nextStart; /* set partial block at [start..following block boundary[ */ block=getDataBlock(newTrie, start, TRUE); if(block<0) { *pErrorCode=U_MEMORY_ALLOCATION_ERROR; return; } nextStart=(start+UTRIE2_DATA_BLOCK_LENGTH)&~UTRIE2_DATA_MASK; if(nextStart<=limit) { fillBlock(newTrie->data+block, start&UTRIE2_DATA_MASK, UTRIE2_DATA_BLOCK_LENGTH, value, newTrie->initialValue, overwrite); start=nextStart; } else { fillBlock(newTrie->data+block, start&UTRIE2_DATA_MASK, limit&UTRIE2_DATA_MASK, value, newTrie->initialValue, overwrite); return; } } /* number of positions in the last, partial block */ rest=limit&UTRIE2_DATA_MASK; /* round down limit to a block boundary */ limit&=~UTRIE2_DATA_MASK; /* iterate over all-value blocks */ if(value==newTrie->initialValue) { repeatBlock=newTrie->dataNullOffset; } else { repeatBlock=-1; } while(start<limit) { int32_t i2; UBool setRepeatBlock=FALSE; if(value==newTrie->initialValue && isInNullBlock(newTrie, start, TRUE)) { start+=UTRIE2_DATA_BLOCK_LENGTH; /* nothing to do */ continue; } /* get index value */ i2=getIndex2Block(newTrie, start, TRUE); if(i2<0) { *pErrorCode=U_INTERNAL_PROGRAM_ERROR; return; } i2+=(start>>UTRIE2_SHIFT_2)&UTRIE2_INDEX_2_MASK; block=newTrie->index2[i2]; if(isWritableBlock(newTrie, block)) { /* already allocated */ if(overwrite && block>=UNEWTRIE2_DATA_0800_OFFSET) { /* * We overwrite all values, and it's not a * protected (ASCII-linear or 2-byte UTF-8) block: * replace with the repeatBlock. */ setRepeatBlock=TRUE; } else { /* !overwrite, or protected block: just write the values into this block */ fillBlock(newTrie->data+block, 0, UTRIE2_DATA_BLOCK_LENGTH, value, newTrie->initialValue, overwrite); } } else if(newTrie->data[block]!=value && (overwrite || block==newTrie->dataNullOffset)) { /* * Set the repeatBlock instead of the null block or previous repeat block: * * If !isWritableBlock() then all entries in the block have the same value * because it's the null block or a range block (the repeatBlock from a previous * call to utrie2_setRange32()). * No other blocks are used multiple times before compacting. * * The null block is the only non-writable block with the initialValue because * of the repeatBlock initialization above. (If value==initialValue, then * the repeatBlock will be the null data block.) * * We set our repeatBlock if the desired value differs from the block's value, * and if we overwrite any data or if the data is all initial values * (which is the same as the block being the null block, see above). */ setRepeatBlock=TRUE; } if(setRepeatBlock) { if(repeatBlock>=0) { setIndex2Entry(newTrie, i2, repeatBlock); } else { /* create and set and fill the repeatBlock */ repeatBlock=getDataBlock(newTrie, start, TRUE); if(repeatBlock<0) { *pErrorCode=U_MEMORY_ALLOCATION_ERROR; return; } writeBlock(newTrie->data+repeatBlock, value); } } start+=UTRIE2_DATA_BLOCK_LENGTH; } if(rest>0) { /* set partial block at [last block boundary..limit[ */ block=getDataBlock(newTrie, start, TRUE); if(block<0) { *pErrorCode=U_MEMORY_ALLOCATION_ERROR; return; } fillBlock(newTrie->data+block, 0, rest, value, newTrie->initialValue, overwrite); } return; } /* compaction --------------------------------------------------------------- */ static inline UBool equal_int32(const int32_t *s, const int32_t *t, int32_t length) { while(length>0 && *s==*t) { ++s; ++t; --length; } return (UBool)(length==0); } static inline UBool equal_uint32(const uint32_t *s, const uint32_t *t, int32_t length) { while(length>0 && *s==*t) { ++s; ++t; --length; } return (UBool)(length==0); } static int32_t findSameIndex2Block(const int32_t *idx, int32_t index2Length, int32_t otherBlock) { int32_t block; /* ensure that we do not even partially get past index2Length */ index2Length-=UTRIE2_INDEX_2_BLOCK_LENGTH; for(block=0; block<=index2Length; ++block) { if(equal_int32(idx+block, idx+otherBlock, UTRIE2_INDEX_2_BLOCK_LENGTH)) { return block; } } return -1; } static int32_t findSameDataBlock(const uint32_t *data, int32_t dataLength, int32_t otherBlock, int32_t blockLength) { int32_t block; /* ensure that we do not even partially get past dataLength */ dataLength-=blockLength; for(block=0; block<=dataLength; block+=UTRIE2_DATA_GRANULARITY) { if(equal_uint32(data+block, data+otherBlock, blockLength)) { return block; } } return -1; } /* * Find the start of the last range in the trie by enumerating backward. * Indexes for supplementary code points higher than this will be omitted. */ static UChar32 findHighStart(UNewTrie2 *trie, uint32_t highValue) { const uint32_t *data32; uint32_t value, initialValue; UChar32 c, prev; int32_t i1, i2, j, i2Block, prevI2Block, index2NullOffset, block, prevBlock, nullBlock; data32=trie->data; initialValue=trie->initialValue; index2NullOffset=trie->index2NullOffset; nullBlock=trie->dataNullOffset; /* set variables for previous range */ if(highValue==initialValue) { prevI2Block=index2NullOffset; prevBlock=nullBlock; } else { prevI2Block=-1; prevBlock=-1; } prev=0x110000; /* enumerate index-2 blocks */ i1=UNEWTRIE2_INDEX_1_LENGTH; c=prev; while(c>0) { i2Block=trie->index1[--i1]; if(i2Block==prevI2Block) { /* the index-2 block is the same as the previous one, and filled with highValue */ c-=UTRIE2_CP_PER_INDEX_1_ENTRY; continue; } prevI2Block=i2Block; if(i2Block==index2NullOffset) { /* this is the null index-2 block */ if(highValue!=initialValue) { return c; } c-=UTRIE2_CP_PER_INDEX_1_ENTRY; } else { /* enumerate data blocks for one index-2 block */ for(i2=UTRIE2_INDEX_2_BLOCK_LENGTH; i2>0;) { block=trie->index2[i2Block+ --i2]; if(block==prevBlock) { /* the block is the same as the previous one, and filled with highValue */ c-=UTRIE2_DATA_BLOCK_LENGTH; continue; } prevBlock=block; if(block==nullBlock) { /* this is the null data block */ if(highValue!=initialValue) { return c; } c-=UTRIE2_DATA_BLOCK_LENGTH; } else { for(j=UTRIE2_DATA_BLOCK_LENGTH; j>0;) { value=data32[block+ --j]; if(value!=highValue) { return c; } --c; } } } } } /* deliver last range */ return 0; } /* * Compact a build-time trie. * * The compaction * - removes blocks that are identical with earlier ones * - overlaps adjacent blocks as much as possible (if overlap==TRUE) * - moves blocks in steps of the data granularity * - moves and overlaps blocks that overlap with multiple values in the overlap region * * It does not * - try to move and overlap blocks that are not already adjacent */ static void compactData(UNewTrie2 *trie) { int32_t start, newStart, movedStart; int32_t blockLength, overlap; int32_t i, mapIndex, blockCount; /* do not compact linear-ASCII data */ newStart=UTRIE2_DATA_START_OFFSET; for(start=0, i=0; start<newStart; start+=UTRIE2_DATA_BLOCK_LENGTH, ++i) { trie->map[i]=start; } /* * Start with a block length of 64 for 2-byte UTF-8, * then switch to UTRIE2_DATA_BLOCK_LENGTH. */ blockLength=64; blockCount=blockLength>>UTRIE2_SHIFT_2; for(start=newStart; start<trie->dataLength;) { /* * start: index of first entry of current block * newStart: index where the current block is to be moved * (right after current end of already-compacted data) */ if(start==UNEWTRIE2_DATA_0800_OFFSET) { blockLength=UTRIE2_DATA_BLOCK_LENGTH; blockCount=1; } /* skip blocks that are not used */ if(trie->map[start>>UTRIE2_SHIFT_2]<=0) { /* advance start to the next block */ start+=blockLength; /* leave newStart with the previous block! */ continue; } /* search for an identical block */ if( (movedStart=findSameDataBlock(trie->data, newStart, start, blockLength)) >=0 ) { /* found an identical block, set the other block's index value for the current block */ for(i=blockCount, mapIndex=start>>UTRIE2_SHIFT_2; i>0; --i) { trie->map[mapIndex++]=movedStart; movedStart+=UTRIE2_DATA_BLOCK_LENGTH; } /* advance start to the next block */ start+=blockLength; /* leave newStart with the previous block! */ continue; } /* see if the beginning of this block can be overlapped with the end of the previous block */ /* look for maximum overlap (modulo granularity) with the previous, adjacent block */ for(overlap=blockLength-UTRIE2_DATA_GRANULARITY; overlap>0 && !equal_uint32(trie->data+(newStart-overlap), trie->data+start, overlap); overlap-=UTRIE2_DATA_GRANULARITY) {} if(overlap>0 || newStart<start) { /* some overlap, or just move the whole block */ movedStart=newStart-overlap; for(i=blockCount, mapIndex=start>>UTRIE2_SHIFT_2; i>0; --i) { trie->map[mapIndex++]=movedStart; movedStart+=UTRIE2_DATA_BLOCK_LENGTH; } /* move the non-overlapping indexes to their new positions */ start+=overlap; for(i=blockLength-overlap; i>0; --i) { trie->data[newStart++]=trie->data[start++]; } } else /* no overlap && newStart==start */ { for(i=blockCount, mapIndex=start>>UTRIE2_SHIFT_2; i>0; --i) { trie->map[mapIndex++]=start; start+=UTRIE2_DATA_BLOCK_LENGTH; } newStart=start; } } /* now adjust the index-2 table */ for(i=0; i<trie->index2Length; ++i) { if(i==UNEWTRIE2_INDEX_GAP_OFFSET) { /* Gap indexes are invalid (-1). Skip over the gap. */ i+=UNEWTRIE2_INDEX_GAP_LENGTH; } trie->index2[i]=trie->map[trie->index2[i]>>UTRIE2_SHIFT_2]; } trie->dataNullOffset=trie->map[trie->dataNullOffset>>UTRIE2_SHIFT_2]; /* ensure dataLength alignment */ while((newStart&(UTRIE2_DATA_GRANULARITY-1))!=0) { trie->data[newStart++]=trie->initialValue; } #ifdef UTRIE2_DEBUG /* we saved some space */ printf("compacting UTrie2: count of 32-bit data words %lu->%lu\n", (long)trie->dataLength, (long)newStart); #endif trie->dataLength=newStart; } static void compactIndex2(UNewTrie2 *trie) { int32_t i, start, newStart, movedStart, overlap; /* do not compact linear-BMP index-2 blocks */ newStart=UTRIE2_INDEX_2_BMP_LENGTH; for(start=0, i=0; start<newStart; start+=UTRIE2_INDEX_2_BLOCK_LENGTH, ++i) { trie->map[i]=start; } /* Reduce the index table gap to what will be needed at runtime. */ newStart+=UTRIE2_UTF8_2B_INDEX_2_LENGTH+((trie->highStart-0x10000)>>UTRIE2_SHIFT_1); for(start=UNEWTRIE2_INDEX_2_NULL_OFFSET; start<trie->index2Length;) { /* * start: index of first entry of current block * newStart: index where the current block is to be moved * (right after current end of already-compacted data) */ /* search for an identical block */ if( (movedStart=findSameIndex2Block(trie->index2, newStart, start)) >=0 ) { /* found an identical block, set the other block's index value for the current block */ trie->map[start>>UTRIE2_SHIFT_1_2]=movedStart; /* advance start to the next block */ start+=UTRIE2_INDEX_2_BLOCK_LENGTH; /* leave newStart with the previous block! */ continue; } /* see if the beginning of this block can be overlapped with the end of the previous block */ /* look for maximum overlap with the previous, adjacent block */ for(overlap=UTRIE2_INDEX_2_BLOCK_LENGTH-1; overlap>0 && !equal_int32(trie->index2+(newStart-overlap), trie->index2+start, overlap); --overlap) {} if(overlap>0 || newStart<start) { /* some overlap, or just move the whole block */ trie->map[start>>UTRIE2_SHIFT_1_2]=newStart-overlap; /* move the non-overlapping indexes to their new positions */ start+=overlap; for(i=UTRIE2_INDEX_2_BLOCK_LENGTH-overlap; i>0; --i) { trie->index2[newStart++]=trie->index2[start++]; } } else /* no overlap && newStart==start */ { trie->map[start>>UTRIE2_SHIFT_1_2]=start; start+=UTRIE2_INDEX_2_BLOCK_LENGTH; newStart=start; } } /* now adjust the index-1 table */ for(i=0; i<UNEWTRIE2_INDEX_1_LENGTH; ++i) { trie->index1[i]=trie->map[trie->index1[i]>>UTRIE2_SHIFT_1_2]; } trie->index2NullOffset=trie->map[trie->index2NullOffset>>UTRIE2_SHIFT_1_2]; /* * Ensure data table alignment: * Needs to be granularity-aligned for 16-bit trie * (so that dataMove will be down-shiftable), * and 2-aligned for uint32_t data. */ while((newStart&((UTRIE2_DATA_GRANULARITY-1)|1))!=0) { /* Arbitrary value: 0x3fffc not possible for real data. */ trie->index2[newStart++]=(int32_t)0xffff<<UTRIE2_INDEX_SHIFT; } #ifdef UTRIE2_DEBUG /* we saved some space */ printf("compacting UTrie2: count of 16-bit index-2 words %lu->%lu\n", (long)trie->index2Length, (long)newStart); #endif trie->index2Length=newStart; } static void compactTrie(UTrie2 *trie, UErrorCode *pErrorCode) { UNewTrie2 *newTrie; UChar32 highStart, suppHighStart; uint32_t highValue; newTrie=trie->newTrie; /* find highStart and round it up */ highValue=utrie2_get32(trie, 0x10ffff); highStart=findHighStart(newTrie, highValue); highStart=(highStart+(UTRIE2_CP_PER_INDEX_1_ENTRY-1))&~(UTRIE2_CP_PER_INDEX_1_ENTRY-1); if(highStart==0x110000) { highValue=trie->errorValue; } /* * Set trie->highStart only after utrie2_get32(trie, highStart). * Otherwise utrie2_get32(trie, highStart) would try to read the highValue. */ trie->highStart=newTrie->highStart=highStart; #ifdef UTRIE2_DEBUG printf("UTrie2: highStart U+%04lx highValue 0x%lx initialValue 0x%lx\n", (long)highStart, (long)highValue, (long)trie->initialValue); #endif if(highStart<0x110000) { /* Blank out [highStart..10ffff] to release associated data blocks. */ suppHighStart= highStart<=0x10000 ? 0x10000 : highStart; utrie2_setRange32(trie, suppHighStart, 0x10ffff, trie->initialValue, TRUE, pErrorCode); if(U_FAILURE(*pErrorCode)) { return; } } compactData(newTrie); if(highStart>0x10000) { compactIndex2(newTrie); #ifdef UTRIE2_DEBUG } else { printf("UTrie2: highStart U+%04lx count of 16-bit index-2 words %lu->%lu\n", (long)highStart, (long)trie->newTrie->index2Length, (long)UTRIE2_INDEX_1_OFFSET); #endif } /* * Store the highValue in the data array and round up the dataLength. * Must be done after compactData() because that assumes that dataLength * is a multiple of UTRIE2_DATA_BLOCK_LENGTH. */ newTrie->data[newTrie->dataLength++]=highValue; while((newTrie->dataLength&(UTRIE2_DATA_GRANULARITY-1))!=0) { newTrie->data[newTrie->dataLength++]=trie->initialValue; } newTrie->isCompacted=TRUE; } /* serialization ------------------------------------------------------------ */ /** * Maximum length of the runtime index array. * Limited by its own 16-bit index values, and by uint16_t UTrie2Header.indexLength. * (The actual maximum length is lower, * (0x110000>>UTRIE2_SHIFT_2)+UTRIE2_UTF8_2B_INDEX_2_LENGTH+UTRIE2_MAX_INDEX_1_LENGTH.) */ #define UTRIE2_MAX_INDEX_LENGTH 0xffff /** * Maximum length of the runtime data array. * Limited by 16-bit index values that are left-shifted by UTRIE2_INDEX_SHIFT, * and by uint16_t UTrie2Header.shiftedDataLength. */ #define UTRIE2_MAX_DATA_LENGTH (0xffff<<UTRIE2_INDEX_SHIFT) /* Compact and internally serialize the trie. */ U_CAPI void U_EXPORT2 utrie2_freeze(UTrie2 *trie, UTrie2ValueBits valueBits, UErrorCode *pErrorCode) { UNewTrie2 *newTrie; UTrie2Header *header; uint32_t *p; uint16_t *dest16; int32_t i, length; int32_t allIndexesLength; int32_t dataMove; /* >0 if the data is moved to the end of the index array */ UChar32 highStart; /* argument check */ if(U_FAILURE(*pErrorCode)) { return; } if( trie==NULL || valueBits<0 || UTRIE2_COUNT_VALUE_BITS<=valueBits ) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return; } newTrie=trie->newTrie; if(newTrie==NULL) { /* already frozen */ UTrie2ValueBits frozenValueBits= trie->data16!=NULL ? UTRIE2_16_VALUE_BITS : UTRIE2_32_VALUE_BITS; if(valueBits!=frozenValueBits) { *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; } return; } /* compact if necessary */ if(!newTrie->isCompacted) { compactTrie(trie, pErrorCode); if(U_FAILURE(*pErrorCode)) { return; } } highStart=trie->highStart; if(highStart<=0x10000) { allIndexesLength=UTRIE2_INDEX_1_OFFSET; } else { allIndexesLength=newTrie->index2Length; } if(valueBits==UTRIE2_16_VALUE_BITS) { dataMove=allIndexesLength; } else { dataMove=0; } /* are indexLength and dataLength within limits? */ if( /* for unshifted indexLength */ allIndexesLength>UTRIE2_MAX_INDEX_LENGTH || /* for unshifted dataNullOffset */ (dataMove+newTrie->dataNullOffset)>0xffff || /* for unshifted 2-byte UTF-8 index-2 values */ (dataMove+UNEWTRIE2_DATA_0800_OFFSET)>0xffff || /* for shiftedDataLength */ (dataMove+newTrie->dataLength)>UTRIE2_MAX_DATA_LENGTH ) { *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR; return; } /* calculate the total serialized length */ length=sizeof(UTrie2Header)+allIndexesLength*2; if(valueBits==UTRIE2_16_VALUE_BITS) { length+=newTrie->dataLength*2; } else { length+=newTrie->dataLength*4; } trie->memory=uprv_malloc(length); if(trie->memory==NULL) { *pErrorCode=U_MEMORY_ALLOCATION_ERROR; return; } trie->length=length; trie->isMemoryOwned=TRUE; trie->indexLength=allIndexesLength; trie->dataLength=newTrie->dataLength; if(highStart<=0x10000) { trie->index2NullOffset=0xffff; } else { trie->index2NullOffset=UTRIE2_INDEX_2_OFFSET+newTrie->index2NullOffset; } trie->dataNullOffset=(uint16_t)(dataMove+newTrie->dataNullOffset); trie->highValueIndex=dataMove+trie->dataLength-UTRIE2_DATA_GRANULARITY; /* set the header fields */ header=(UTrie2Header *)trie->memory; header->signature=UTRIE2_SIG; /* "Tri2" */ header->options=(uint16_t)valueBits; header->indexLength=(uint16_t)trie->indexLength; header->shiftedDataLength=(uint16_t)(trie->dataLength>>UTRIE2_INDEX_SHIFT); header->index2NullOffset=trie->index2NullOffset; header->dataNullOffset=trie->dataNullOffset; header->shiftedHighStart=(uint16_t)(highStart>>UTRIE2_SHIFT_1); /* fill the index and data arrays */ dest16=(uint16_t *)(header+1); trie->index=dest16; /* write the index-2 array values shifted right by UTRIE2_INDEX_SHIFT, after adding dataMove */ p=(uint32_t *)newTrie->index2; for(i=UTRIE2_INDEX_2_BMP_LENGTH; i>0; --i) { *dest16++=(uint16_t)((dataMove + *p++)>>UTRIE2_INDEX_SHIFT); } /* write UTF-8 2-byte index-2 values, not right-shifted */ for(i=0; i<(0xc2-0xc0); ++i) { /* C0..C1 */ *dest16++=(uint16_t)(dataMove+UTRIE2_BAD_UTF8_DATA_OFFSET); } for(; i<(0xe0-0xc0); ++i) { /* C2..DF */ *dest16++=(uint16_t)(dataMove+newTrie->index2[i<<(6-UTRIE2_SHIFT_2)]); } if(highStart>0x10000) { int32_t index1Length=(highStart-0x10000)>>UTRIE2_SHIFT_1; int32_t index2Offset=UTRIE2_INDEX_2_BMP_LENGTH+UTRIE2_UTF8_2B_INDEX_2_LENGTH+index1Length; /* write 16-bit index-1 values for supplementary code points */ p=(uint32_t *)newTrie->index1+UTRIE2_OMITTED_BMP_INDEX_1_LENGTH; for(i=index1Length; i>0; --i) { *dest16++=(uint16_t)(UTRIE2_INDEX_2_OFFSET + *p++); } /* * write the index-2 array values for supplementary code points, * shifted right by UTRIE2_INDEX_SHIFT, after adding dataMove */ p=(uint32_t *)newTrie->index2+index2Offset; for(i=newTrie->index2Length-index2Offset; i>0; --i) { *dest16++=(uint16_t)((dataMove + *p++)>>UTRIE2_INDEX_SHIFT); } } /* write the 16/32-bit data array */ switch(valueBits) { case UTRIE2_16_VALUE_BITS: /* write 16-bit data values */ trie->data16=dest16; trie->data32=NULL; p=newTrie->data; for(i=newTrie->dataLength; i>0; --i) { *dest16++=(uint16_t)*p++; } break; case UTRIE2_32_VALUE_BITS: /* write 32-bit data values */ trie->data16=NULL; trie->data32=(uint32_t *)dest16; uprv_memcpy(dest16, newTrie->data, (size_t)newTrie->dataLength*4); break; default: *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return; } /* Delete the UNewTrie2. */ uprv_free(newTrie->data); uprv_free(newTrie); trie->newTrie=NULL; } /* * This is here to avoid a dependency from utrie2.cpp on utrie.c. * This file already depends on utrie.c. * Otherwise, this should be in utrie2.cpp right after utrie2_swap(). */ U_CAPI int32_t U_EXPORT2 utrie2_swapAnyVersion(const UDataSwapper *ds, const void *inData, int32_t length, void *outData, UErrorCode *pErrorCode) { if(U_SUCCESS(*pErrorCode)) { switch(utrie2_getVersion(inData, length, TRUE)) { case 1: return utrie_swap(ds, inData, length, outData, pErrorCode); case 2: return utrie2_swap(ds, inData, length, outData, pErrorCode); default: *pErrorCode=U_INVALID_FORMAT_ERROR; return 0; } } return 0; }
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/icu/source/common/utrie2_builder.cpp
C++
gpl-3.0
46,925
/* Soot - a J*va Optimization Framework * Copyright (C) 2003 Ondrej Lhotak * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* THIS FILE IS AUTO-GENERATED FROM soot_options.xml. DO NOT MODIFY. */ package soot.options; import java.util.*; /** Option parser for May Happen in Parallel Analyses. */ public class MhpTransformer { private Map<String, String> options; public MhpTransformer( Map<String, String> options ) { this.options = options; } /** Enabled -- * . * */ public boolean enabled() { return soot.PhaseOptions.getBoolean( options, "enabled" ); } }
flankerhqd/JAADAS
soot/generated/options/soot/options/MhpTransformer.java
Java
gpl-3.0
1,346
YUI.add('moodle-report_overviewstats-charts', function (Y, NAME) { M.report_overviewstats = M.report_overviewstats || {}; M.report_overviewstats.charts = M.report_overviewstats.charts || {}; M.report_overviewstats.charts.countries = { /** * @method init * @param data */ init: function(data) { var chart = new Y.Chart({ type: "bar", categoryKey: "country", verticalGridlines: true, dataProvider: data }); Y.one("#chart_countries").setStyle("backgroundImage", "none"); chart.render("#chart_countries"); } }; M.report_overviewstats = M.report_overviewstats || {}; M.report_overviewstats.charts = M.report_overviewstats.charts || {}; M.report_overviewstats.charts.courses = { /** * @method init * @param data */ init: function(data) { var sizes = new Y.Chart({ type: "column", categoryKey: "course_size", horizontalGridlines: true, verticalGridlines: true, dataProvider: data.sizes }); Y.one("#chart_courses_sizes").setStyle("backgroundImage", "none"); sizes.render("#chart_courses_sizes"); } }; M.report_overviewstats = M.report_overviewstats || {}; M.report_overviewstats.charts = M.report_overviewstats.charts || {}; M.report_overviewstats.charts.enrolments = { /** * @method init * @param data */ init: function(data) { var lastmonth = new Y.Chart({ type: "combo", dataProvider: data.lastmonth, categoryKey: "date", horizontalGridlines: true, verticalGridlines: true, styles: { axes: { date: { label: { rotation: -90 } } } } }); Y.one("#chart_enrolments_lastmonth").setStyle("backgroundImage", "none"); lastmonth.render("#chart_enrolments_lastmonth"); var lastyear = new Y.Chart({ type: "combo", dataProvider: data.lastyear, categoryKey: "date", horizontalGridlines: true, verticalGridlines: true, styles: { axes: { date: { label: { rotation: -90 } } } } }); Y.one("#chart_enrolments_lastyear").setStyle("backgroundImage", "none"); lastyear.render("#chart_enrolments_lastyear"); } }; M.report_overviewstats = M.report_overviewstats || {}; M.report_overviewstats.charts = M.report_overviewstats.charts || {}; M.report_overviewstats.charts.langs = { /** * @method init * @param data */ init: function(data) { var chart = new Y.Chart({ type: "bar", categoryKey: "language", verticalGridlines: true, dataProvider: data }); Y.one("#chart_langs").setStyle("backgroundImage", "none"); chart.render("#chart_langs"); } }; M.report_overviewstats = M.report_overviewstats || {}; M.report_overviewstats.charts = M.report_overviewstats.charts || {}; M.report_overviewstats.charts.logins = { /** * @method init * @param data */ init: function(data) { var perday = new Y.Chart({ type: "combo", dataProvider: data.perday, categoryKey: "date", horizontalGridlines: true, verticalGridlines: true, styles: { axes: { date: { label: { rotation: -90 } } } } }); Y.one("#chart_logins_perday").setStyle("backgroundImage", "none"); perday.render("#chart_logins_perday"); } }; }, '@VERSION@', {"requires": ["base", "node", "charts", "charts-legend"]});
jamesclickap/taiwanlife_web
report/overviewstats/yui/build/moodle-report_overviewstats-charts/moodle-report_overviewstats-charts-debug.js
JavaScript
gpl-3.0
4,126
// TUTAO start (disabled for non-touch devices because this script does not support IE9) if ('ontouchstart' in window || 'ontouchstart' in document.documentElement || window.navigator.msMaxTouchPoints) { // TUTAO end /*! Hammer.JS - v2.0.4 - 2014-09-28 * http://hammerjs.github.io/ * * Copyright (c) 2014 Jorik Tangelder; * Licensed under the MIT license */ (function(window, document, exportName, undefined) { 'use strict'; var VENDOR_PREFIXES = ['', 'webkit', 'moz', 'MS', 'ms', 'o']; var TEST_ELEMENT = document.createElement('div'); var TYPE_FUNCTION = 'function'; var round = Math.round; var abs = Math.abs; var now = Date.now; /** * set a timeout with a given scope * @param {Function} fn * @param {Number} timeout * @param {Object} context * @returns {number} */ function setTimeoutContext(fn, timeout, context) { return setTimeout(bindFn(fn, context), timeout); } /** * if the argument is an array, we want to execute the fn on each entry * if it aint an array we don't want to do a thing. * this is used by all the methods that accept a single and array argument. * @param {*|Array} arg * @param {String} fn * @param {Object} [context] * @returns {Boolean} */ function invokeArrayArg(arg, fn, context) { if (Array.isArray(arg)) { each(arg, context[fn], context); return true; } return false; } /** * walk objects and arrays * @param {Object} obj * @param {Function} iterator * @param {Object} context */ function each(obj, iterator, context) { var i; if (!obj) { return; } if (obj.forEach) { obj.forEach(iterator, context); } else if (obj.length !== undefined) { i = 0; while (i < obj.length) { iterator.call(context, obj[i], i, obj); i++; } } else { for (i in obj) { obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj); } } } /** * extend object. * means that properties in dest will be overwritten by the ones in src. * @param {Object} dest * @param {Object} src * @param {Boolean} [merge] * @returns {Object} dest */ function extend(dest, src, merge) { var keys = Object.keys(src); var i = 0; while (i < keys.length) { if (!merge || (merge && dest[keys[i]] === undefined)) { dest[keys[i]] = src[keys[i]]; } i++; } return dest; } /** * merge the values from src in the dest. * means that properties that exist in dest will not be overwritten by src * @param {Object} dest * @param {Object} src * @returns {Object} dest */ function merge(dest, src) { return extend(dest, src, true); } /** * simple class inheritance * @param {Function} child * @param {Function} base * @param {Object} [properties] */ function inherit(child, base, properties) { var baseP = base.prototype, childP; childP = child.prototype = Object.create(baseP); childP.constructor = child; childP._super = baseP; if (properties) { extend(childP, properties); } } /** * simple function bind * @param {Function} fn * @param {Object} context * @returns {Function} */ function bindFn(fn, context) { return function boundFn() { return fn.apply(context, arguments); }; } /** * let a boolean value also be a function that must return a boolean * this first item in args will be used as the context * @param {Boolean|Function} val * @param {Array} [args] * @returns {Boolean} */ function boolOrFn(val, args) { if (typeof val == TYPE_FUNCTION) { return val.apply(args ? args[0] || undefined : undefined, args); } return val; } /** * use the val2 when val1 is undefined * @param {*} val1 * @param {*} val2 * @returns {*} */ function ifUndefined(val1, val2) { return (val1 === undefined) ? val2 : val1; } /** * addEventListener with multiple events at once * @param {EventTarget} target * @param {String} types * @param {Function} handler */ function addEventListeners(target, types, handler) { each(splitStr(types), function(type) { target.addEventListener(type, handler, false); }); } /** * removeEventListener with multiple events at once * @param {EventTarget} target * @param {String} types * @param {Function} handler */ function removeEventListeners(target, types, handler) { each(splitStr(types), function(type) { target.removeEventListener(type, handler, false); }); } /** * find if a node is in the given parent * @method hasParent * @param {HTMLElement} node * @param {HTMLElement} parent * @return {Boolean} found */ function hasParent(node, parent) { while (node) { if (node == parent) { return true; } node = node.parentNode; } return false; } /** * small indexOf wrapper * @param {String} str * @param {String} find * @returns {Boolean} found */ function inStr(str, find) { return str.indexOf(find) > -1; } /** * split string on whitespace * @param {String} str * @returns {Array} words */ function splitStr(str) { return str.trim().split(/\s+/g); } /** * find if a array contains the object using indexOf or a simple polyFill * @param {Array} src * @param {String} find * @param {String} [findByKey] * @return {Boolean|Number} false when not found, or the index */ function inArray(src, find, findByKey) { if (src.indexOf && !findByKey) { return src.indexOf(find); } else { var i = 0; while (i < src.length) { if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) { return i; } i++; } return -1; } } /** * convert array-like objects to real arrays * @param {Object} obj * @returns {Array} */ function toArray(obj) { return Array.prototype.slice.call(obj, 0); } /** * unique array with objects based on a key (like 'id') or just by the array's value * @param {Array} src [{id:1},{id:2},{id:1}] * @param {String} [key] * @param {Boolean} [sort=False] * @returns {Array} [{id:1},{id:2}] */ function uniqueArray(src, key, sort) { var results = []; var values = []; var i = 0; while (i < src.length) { var val = key ? src[i][key] : src[i]; if (inArray(values, val) < 0) { results.push(src[i]); } values[i] = val; i++; } if (sort) { if (!key) { results = results.sort(); } else { results = results.sort(function sortUniqueArray(a, b) { return a[key] > b[key]; }); } } return results; } /** * get the prefixed property * @param {Object} obj * @param {String} property * @returns {String|Undefined} prefixed */ function prefixed(obj, property) { var prefix, prop; var camelProp = property[0].toUpperCase() + property.slice(1); var i = 0; while (i < VENDOR_PREFIXES.length) { prefix = VENDOR_PREFIXES[i]; prop = (prefix) ? prefix + camelProp : property; if (prop in obj) { return prop; } i++; } return undefined; } /** * get a unique id * @returns {number} uniqueId */ var _uniqueId = 1; function uniqueId() { return _uniqueId++; } /** * get the window object of an element * @param {HTMLElement} element * @returns {DocumentView|Window} */ function getWindowForElement(element) { var doc = element.ownerDocument; return (doc.defaultView || doc.parentWindow); } var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i; var SUPPORT_TOUCH = ('ontouchstart' in window); var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined; var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent); var INPUT_TYPE_TOUCH = 'touch'; var INPUT_TYPE_PEN = 'pen'; var INPUT_TYPE_MOUSE = 'mouse'; var INPUT_TYPE_KINECT = 'kinect'; var COMPUTE_INTERVAL = 25; var INPUT_START = 1; var INPUT_MOVE = 2; var INPUT_END = 4; var INPUT_CANCEL = 8; var DIRECTION_NONE = 1; var DIRECTION_LEFT = 2; var DIRECTION_RIGHT = 4; var DIRECTION_UP = 8; var DIRECTION_DOWN = 16; var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT; var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN; var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL; var PROPS_XY = ['x', 'y']; var PROPS_CLIENT_XY = ['clientX', 'clientY']; /** * create new input type manager * @param {Manager} manager * @param {Function} callback * @returns {Input} * @constructor */ function Input(manager, callback) { var self = this; this.manager = manager; this.callback = callback; this.element = manager.element; this.target = manager.options.inputTarget; // smaller wrapper around the handler, for the scope and the enabled state of the manager, // so when disabled the input events are completely bypassed. this.domHandler = function(ev) { if (boolOrFn(manager.options.enable, [manager])) { self.handler(ev); } }; this.init(); } Input.prototype = { /** * should handle the inputEvent data and trigger the callback * @virtual */ handler: function() { }, /** * bind the events */ init: function() { this.evEl && addEventListeners(this.element, this.evEl, this.domHandler); this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler); this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); }, /** * unbind the events */ destroy: function() { this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler); this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler); this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); } }; /** * create new input type manager * called by the Manager constructor * @param {Hammer} manager * @returns {Input} */ function createInputInstance(manager) { var Type; var inputClass = manager.options.inputClass; if (inputClass) { Type = inputClass; } else if (SUPPORT_POINTER_EVENTS) { Type = PointerEventInput; } else if (SUPPORT_ONLY_TOUCH) { Type = TouchInput; } else if (!SUPPORT_TOUCH) { Type = MouseInput; } else { Type = TouchMouseInput; } return new (Type)(manager, inputHandler); } /** * handle input events * @param {Manager} manager * @param {String} eventType * @param {Object} input */ function inputHandler(manager, eventType, input) { var pointersLen = input.pointers.length; var changedPointersLen = input.changedPointers.length; var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0)); var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0)); input.isFirst = !!isFirst; input.isFinal = !!isFinal; if (isFirst) { manager.session = {}; } // source event is the normalized value of the domEvents // like 'touchstart, mouseup, pointerdown' input.eventType = eventType; // compute scale, rotation etc computeInputData(manager, input); // emit secret event manager.emit('hammer.input', input); manager.recognize(input); manager.session.prevInput = input; } /** * extend the data with some usable properties like scale, rotate, velocity etc * @param {Object} manager * @param {Object} input */ function computeInputData(manager, input) { var session = manager.session; var pointers = input.pointers; var pointersLength = pointers.length; // store the first input to calculate the distance and direction if (!session.firstInput) { session.firstInput = simpleCloneInputData(input); } // to compute scale and rotation we need to store the multiple touches if (pointersLength > 1 && !session.firstMultiple) { session.firstMultiple = simpleCloneInputData(input); } else if (pointersLength === 1) { session.firstMultiple = false; } var firstInput = session.firstInput; var firstMultiple = session.firstMultiple; var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center; var center = input.center = getCenter(pointers); input.timeStamp = now(); input.deltaTime = input.timeStamp - firstInput.timeStamp; input.angle = getAngle(offsetCenter, center); input.distance = getDistance(offsetCenter, center); computeDeltaXY(session, input); input.offsetDirection = getDirection(input.deltaX, input.deltaY); input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1; input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0; computeIntervalInputData(session, input); // find the correct target var target = manager.element; if (hasParent(input.srcEvent.target, target)) { target = input.srcEvent.target; } input.target = target; } function computeDeltaXY(session, input) { var center = input.center; var offset = session.offsetDelta || {}; var prevDelta = session.prevDelta || {}; var prevInput = session.prevInput || {}; if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) { prevDelta = session.prevDelta = { x: prevInput.deltaX || 0, y: prevInput.deltaY || 0 }; offset = session.offsetDelta = { x: center.x, y: center.y }; } input.deltaX = prevDelta.x + (center.x - offset.x); input.deltaY = prevDelta.y + (center.y - offset.y); } /** * velocity is calculated every x ms * @param {Object} session * @param {Object} input */ function computeIntervalInputData(session, input) { var last = session.lastInterval || input, deltaTime = input.timeStamp - last.timeStamp, velocity, velocityX, velocityY, direction; if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) { var deltaX = last.deltaX - input.deltaX; var deltaY = last.deltaY - input.deltaY; var v = getVelocity(deltaTime, deltaX, deltaY); velocityX = v.x; velocityY = v.y; velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y; direction = getDirection(deltaX, deltaY); session.lastInterval = input; } else { // use latest velocity info if it doesn't overtake a minimum period velocity = last.velocity; velocityX = last.velocityX; velocityY = last.velocityY; direction = last.direction; } input.velocity = velocity; input.velocityX = velocityX; input.velocityY = velocityY; input.direction = direction; } /** * create a simple clone from the input used for storage of firstInput and firstMultiple * @param {Object} input * @returns {Object} clonedInputData */ function simpleCloneInputData(input) { // make a simple copy of the pointers because we will get a reference if we don't // we only need clientXY for the calculations var pointers = []; var i = 0; while (i < input.pointers.length) { pointers[i] = { clientX: round(input.pointers[i].clientX), clientY: round(input.pointers[i].clientY) }; i++; } return { timeStamp: now(), pointers: pointers, center: getCenter(pointers), deltaX: input.deltaX, deltaY: input.deltaY }; } /** * get the center of all the pointers * @param {Array} pointers * @return {Object} center contains `x` and `y` properties */ function getCenter(pointers) { var pointersLength = pointers.length; // no need to loop when only one touch if (pointersLength === 1) { return { x: round(pointers[0].clientX), y: round(pointers[0].clientY) }; } var x = 0, y = 0, i = 0; while (i < pointersLength) { x += pointers[i].clientX; y += pointers[i].clientY; i++; } return { x: round(x / pointersLength), y: round(y / pointersLength) }; } /** * calculate the velocity between two points. unit is in px per ms. * @param {Number} deltaTime * @param {Number} x * @param {Number} y * @return {Object} velocity `x` and `y` */ function getVelocity(deltaTime, x, y) { return { x: x / deltaTime || 0, y: y / deltaTime || 0 }; } /** * get the direction between two points * @param {Number} x * @param {Number} y * @return {Number} direction */ function getDirection(x, y) { if (x === y) { return DIRECTION_NONE; } if (abs(x) >= abs(y)) { return x > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; } return y > 0 ? DIRECTION_UP : DIRECTION_DOWN; } /** * calculate the absolute distance between two points * @param {Object} p1 {x, y} * @param {Object} p2 {x, y} * @param {Array} [props] containing x and y keys * @return {Number} distance */ function getDistance(p1, p2, props) { if (!props) { props = PROPS_XY; } var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]]; return Math.sqrt((x * x) + (y * y)); } /** * calculate the angle between two coordinates * @param {Object} p1 * @param {Object} p2 * @param {Array} [props] containing x and y keys * @return {Number} angle */ function getAngle(p1, p2, props) { if (!props) { props = PROPS_XY; } var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]]; return Math.atan2(y, x) * 180 / Math.PI; } /** * calculate the rotation degrees between two pointersets * @param {Array} start array of pointers * @param {Array} end array of pointers * @return {Number} rotation */ function getRotation(start, end) { return getAngle(end[1], end[0], PROPS_CLIENT_XY) - getAngle(start[1], start[0], PROPS_CLIENT_XY); } /** * calculate the scale factor between two pointersets * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @param {Array} start array of pointers * @param {Array} end array of pointers * @return {Number} scale */ function getScale(start, end) { return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY); } var MOUSE_INPUT_MAP = { mousedown: INPUT_START, mousemove: INPUT_MOVE, mouseup: INPUT_END }; var MOUSE_ELEMENT_EVENTS = 'mousedown'; var MOUSE_WINDOW_EVENTS = 'mousemove mouseup'; /** * Mouse events input * @constructor * @extends Input */ function MouseInput() { this.evEl = MOUSE_ELEMENT_EVENTS; this.evWin = MOUSE_WINDOW_EVENTS; this.allow = true; // used by Input.TouchMouse to disable mouse events this.pressed = false; // mousedown state Input.apply(this, arguments); } inherit(MouseInput, Input, { /** * handle mouse events * @param {Object} ev */ handler: function MEhandler(ev) { var eventType = MOUSE_INPUT_MAP[ev.type]; // on start we want to have the left mouse button down if (eventType & INPUT_START && ev.button === 0) { this.pressed = true; } if (eventType & INPUT_MOVE && ev.which !== 1) { eventType = INPUT_END; } // mouse must be down, and mouse events are allowed (see the TouchMouse input) if (!this.pressed || !this.allow) { return; } if (eventType & INPUT_END) { this.pressed = false; } this.callback(this.manager, eventType, { pointers: [ev], changedPointers: [ev], pointerType: INPUT_TYPE_MOUSE, srcEvent: ev }); } }); var POINTER_INPUT_MAP = { pointerdown: INPUT_START, pointermove: INPUT_MOVE, pointerup: INPUT_END, pointercancel: INPUT_CANCEL, pointerout: INPUT_CANCEL }; // in IE10 the pointer types is defined as an enum var IE10_POINTER_TYPE_ENUM = { 2: INPUT_TYPE_TOUCH, 3: INPUT_TYPE_PEN, 4: INPUT_TYPE_MOUSE, 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816 }; var POINTER_ELEMENT_EVENTS = 'pointerdown'; var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel'; // IE10 has prefixed support, and case-sensitive if (window.MSPointerEvent) { POINTER_ELEMENT_EVENTS = 'MSPointerDown'; POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel'; } /** * Pointer events input * @constructor * @extends Input */ function PointerEventInput() { this.evEl = POINTER_ELEMENT_EVENTS; this.evWin = POINTER_WINDOW_EVENTS; Input.apply(this, arguments); this.store = (this.manager.session.pointerEvents = []); } inherit(PointerEventInput, Input, { /** * handle mouse events * @param {Object} ev */ handler: function PEhandler(ev) { var store = this.store; var removePointer = false; var eventTypeNormalized = ev.type.toLowerCase().replace('ms', ''); var eventType = POINTER_INPUT_MAP[eventTypeNormalized]; var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType; var isTouch = (pointerType == INPUT_TYPE_TOUCH); // get index of the event in the store var storeIndex = inArray(store, ev.pointerId, 'pointerId'); // start and mouse must be down if (eventType & INPUT_START && (ev.button === 0 || isTouch)) { if (storeIndex < 0) { store.push(ev); storeIndex = store.length - 1; } } else if (eventType & (INPUT_END | INPUT_CANCEL)) { removePointer = true; } // it not found, so the pointer hasn't been down (so it's probably a hover) if (storeIndex < 0) { return; } // update the event in the store store[storeIndex] = ev; this.callback(this.manager, eventType, { pointers: store, changedPointers: [ev], pointerType: pointerType, srcEvent: ev }); if (removePointer) { // remove from the store store.splice(storeIndex, 1); } } }); var SINGLE_TOUCH_INPUT_MAP = { touchstart: INPUT_START, touchmove: INPUT_MOVE, touchend: INPUT_END, touchcancel: INPUT_CANCEL }; var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart'; var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel'; /** * Touch events input * @constructor * @extends Input */ function SingleTouchInput() { this.evTarget = SINGLE_TOUCH_TARGET_EVENTS; this.evWin = SINGLE_TOUCH_WINDOW_EVENTS; this.started = false; Input.apply(this, arguments); } inherit(SingleTouchInput, Input, { handler: function TEhandler(ev) { var type = SINGLE_TOUCH_INPUT_MAP[ev.type]; // should we handle the touch events? if (type === INPUT_START) { this.started = true; } if (!this.started) { return; } var touches = normalizeSingleTouches.call(this, ev, type); // when done, reset the started state if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) { this.started = false; } this.callback(this.manager, type, { pointers: touches[0], changedPointers: touches[1], pointerType: INPUT_TYPE_TOUCH, srcEvent: ev }); } }); /** * @this {TouchInput} * @param {Object} ev * @param {Number} type flag * @returns {undefined|Array} [all, changed] */ function normalizeSingleTouches(ev, type) { var all = toArray(ev.touches); var changed = toArray(ev.changedTouches); if (type & (INPUT_END | INPUT_CANCEL)) { all = uniqueArray(all.concat(changed), 'identifier', true); } return [all, changed]; } var TOUCH_INPUT_MAP = { touchstart: INPUT_START, touchmove: INPUT_MOVE, touchend: INPUT_END, touchcancel: INPUT_CANCEL }; var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel'; /** * Multi-user touch events input * @constructor * @extends Input */ function TouchInput() { this.evTarget = TOUCH_TARGET_EVENTS; this.targetIds = {}; Input.apply(this, arguments); } inherit(TouchInput, Input, { handler: function MTEhandler(ev) { var type = TOUCH_INPUT_MAP[ev.type]; var touches = getTouches.call(this, ev, type); if (!touches) { return; } this.callback(this.manager, type, { pointers: touches[0], changedPointers: touches[1], pointerType: INPUT_TYPE_TOUCH, srcEvent: ev }); } }); /** * @this {TouchInput} * @param {Object} ev * @param {Number} type flag * @returns {undefined|Array} [all, changed] */ function getTouches(ev, type) { var allTouches = toArray(ev.touches); var targetIds = this.targetIds; // when there is only one touch, the process can be simplified if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) { targetIds[allTouches[0].identifier] = true; return [allTouches, allTouches]; } var i, targetTouches, changedTouches = toArray(ev.changedTouches), changedTargetTouches = [], target = this.target; // get target touches from touches targetTouches = allTouches.filter(function(touch) { return hasParent(touch.target, target); }); // collect touches if (type === INPUT_START) { i = 0; while (i < targetTouches.length) { targetIds[targetTouches[i].identifier] = true; i++; } } // filter changed touches to only contain touches that exist in the collected target ids i = 0; while (i < changedTouches.length) { if (targetIds[changedTouches[i].identifier]) { changedTargetTouches.push(changedTouches[i]); } // cleanup removed touches if (type & (INPUT_END | INPUT_CANCEL)) { delete targetIds[changedTouches[i].identifier]; } i++; } if (!changedTargetTouches.length) { return; } return [ // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel' uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true), changedTargetTouches ]; } /** * Combined touch and mouse input * * Touch has a higher priority then mouse, and while touching no mouse events are allowed. * This because touch devices also emit mouse events while doing a touch. * * @constructor * @extends Input */ function TouchMouseInput() { Input.apply(this, arguments); var handler = bindFn(this.handler, this); this.touch = new TouchInput(this.manager, handler); this.mouse = new MouseInput(this.manager, handler); } inherit(TouchMouseInput, Input, { /** * handle mouse and touch events * @param {Hammer} manager * @param {String} inputEvent * @param {Object} inputData */ handler: function TMEhandler(manager, inputEvent, inputData) { var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH), isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE); // when we're in a touch event, so block all upcoming mouse events // most mobile browser also emit mouseevents, right after touchstart if (isTouch) { this.mouse.allow = false; } else if (isMouse && !this.mouse.allow) { return; } // reset the allowMouse when we're done if (inputEvent & (INPUT_END | INPUT_CANCEL)) { this.mouse.allow = true; } this.callback(manager, inputEvent, inputData); }, /** * remove the event listeners */ destroy: function destroy() { this.touch.destroy(); this.mouse.destroy(); } }); var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction'); var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined; // magical touchAction value var TOUCH_ACTION_COMPUTE = 'compute'; var TOUCH_ACTION_AUTO = 'auto'; var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented var TOUCH_ACTION_NONE = 'none'; var TOUCH_ACTION_PAN_X = 'pan-x'; var TOUCH_ACTION_PAN_Y = 'pan-y'; /** * Touch Action * sets the touchAction property or uses the js alternative * @param {Manager} manager * @param {String} value * @constructor */ function TouchAction(manager, value) { this.manager = manager; this.set(value); } TouchAction.prototype = { /** * set the touchAction value on the element or enable the polyfill * @param {String} value */ set: function(value) { // find out the touch-action by the event handlers if (value == TOUCH_ACTION_COMPUTE) { value = this.compute(); } if (NATIVE_TOUCH_ACTION) { this.manager.element.style[PREFIXED_TOUCH_ACTION] = value; } this.actions = value.toLowerCase().trim(); }, /** * just re-set the touchAction value */ update: function() { this.set(this.manager.options.touchAction); }, /** * compute the value for the touchAction property based on the recognizer's settings * @returns {String} value */ compute: function() { var actions = []; each(this.manager.recognizers, function(recognizer) { if (boolOrFn(recognizer.options.enable, [recognizer])) { actions = actions.concat(recognizer.getTouchAction()); } }); return cleanTouchActions(actions.join(' ')); }, /** * this method is called on each input cycle and provides the preventing of the browser behavior * @param {Object} input */ preventDefaults: function(input) { // not needed with native support for the touchAction property if (NATIVE_TOUCH_ACTION) { return; } var srcEvent = input.srcEvent; var direction = input.offsetDirection; // if the touch action did prevented once this session if (this.manager.session.prevented) { srcEvent.preventDefault(); return; } var actions = this.actions; var hasNone = inStr(actions, TOUCH_ACTION_NONE); var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); if (hasNone || (hasPanY && direction & DIRECTION_HORIZONTAL) || (hasPanX && direction & DIRECTION_VERTICAL)) { return this.preventSrc(srcEvent); } }, /** * call preventDefault to prevent the browser's default behavior (scrolling in most cases) * @param {Object} srcEvent */ preventSrc: function(srcEvent) { this.manager.session.prevented = true; srcEvent.preventDefault(); } }; /** * when the touchActions are collected they are not a valid value, so we need to clean things up. * * @param {String} actions * @returns {*} */ function cleanTouchActions(actions) { // none if (inStr(actions, TOUCH_ACTION_NONE)) { return TOUCH_ACTION_NONE; } var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); // pan-x and pan-y can be combined if (hasPanX && hasPanY) { return TOUCH_ACTION_PAN_X + ' ' + TOUCH_ACTION_PAN_Y; } // pan-x OR pan-y if (hasPanX || hasPanY) { return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y; } // manipulation if (inStr(actions, TOUCH_ACTION_MANIPULATION)) { return TOUCH_ACTION_MANIPULATION; } return TOUCH_ACTION_AUTO; } /** * Recognizer flow explained; * * All recognizers have the initial state of POSSIBLE when a input session starts. * The definition of a input session is from the first input until the last input, with all it's movement in it. * * Example session for mouse-input: mousedown -> mousemove -> mouseup * * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed * which determines with state it should be. * * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to * POSSIBLE to give it another change on the next cycle. * * Possible * | * +-----+---------------+ * | | * +-----+-----+ | * | | | * Failed Cancelled | * +-------+------+ * | | * Recognized Began * | * Changed * | * Ended/Recognized */ var STATE_POSSIBLE = 1; var STATE_BEGAN = 2; var STATE_CHANGED = 4; var STATE_ENDED = 8; var STATE_RECOGNIZED = STATE_ENDED; var STATE_CANCELLED = 16; var STATE_FAILED = 32; /** * Recognizer * Every recognizer needs to extend from this class. * @constructor * @param {Object} options */ function Recognizer(options) { this.id = uniqueId(); this.manager = null; this.options = merge(options || {}, this.defaults); // default is enable true this.options.enable = ifUndefined(this.options.enable, true); this.state = STATE_POSSIBLE; this.simultaneous = {}; this.requireFail = []; } Recognizer.prototype = { /** * @virtual * @type {Object} */ defaults: {}, /** * set options * @param {Object} options * @return {Recognizer} */ set: function(options) { extend(this.options, options); // also update the touchAction, in case something changed about the directions/enabled state this.manager && this.manager.touchAction.update(); return this; }, /** * recognize simultaneous with an other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ recognizeWith: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) { return this; } var simultaneous = this.simultaneous; otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); if (!simultaneous[otherRecognizer.id]) { simultaneous[otherRecognizer.id] = otherRecognizer; otherRecognizer.recognizeWith(this); } return this; }, /** * drop the simultaneous link. it doesnt remove the link on the other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ dropRecognizeWith: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) { return this; } otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); delete this.simultaneous[otherRecognizer.id]; return this; }, /** * recognizer can only run when an other is failing * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ requireFailure: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) { return this; } var requireFail = this.requireFail; otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); if (inArray(requireFail, otherRecognizer) === -1) { requireFail.push(otherRecognizer); otherRecognizer.requireFailure(this); } return this; }, /** * drop the requireFailure link. it does not remove the link on the other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ dropRequireFailure: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) { return this; } otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); var index = inArray(this.requireFail, otherRecognizer); if (index > -1) { this.requireFail.splice(index, 1); } return this; }, /** * has require failures boolean * @returns {boolean} */ hasRequireFailures: function() { return this.requireFail.length > 0; }, /** * if the recognizer can recognize simultaneous with an other recognizer * @param {Recognizer} otherRecognizer * @returns {Boolean} */ canRecognizeWith: function(otherRecognizer) { return !!this.simultaneous[otherRecognizer.id]; }, /** * You should use `tryEmit` instead of `emit` directly to check * that all the needed recognizers has failed before emitting. * @param {Object} input */ emit: function(input) { var self = this; var state = this.state; function emit(withState) { self.manager.emit(self.options.event + (withState ? stateStr(state) : ''), input); } // 'panstart' and 'panmove' if (state < STATE_ENDED) { emit(true); } emit(); // simple 'eventName' events // panend and pancancel if (state >= STATE_ENDED) { emit(true); } }, /** * Check that all the require failure recognizers has failed, * if true, it emits a gesture event, * otherwise, setup the state to FAILED. * @param {Object} input */ tryEmit: function(input) { if (this.canEmit()) { return this.emit(input); } // it's failing anyway this.state = STATE_FAILED; }, /** * can we emit? * @returns {boolean} */ canEmit: function() { var i = 0; while (i < this.requireFail.length) { if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) { return false; } i++; } return true; }, /** * update the recognizer * @param {Object} inputData */ recognize: function(inputData) { // make a new copy of the inputData // so we can change the inputData without messing up the other recognizers var inputDataClone = extend({}, inputData); // is is enabled and allow recognizing? if (!boolOrFn(this.options.enable, [this, inputDataClone])) { this.reset(); this.state = STATE_FAILED; return; } // reset when we've reached the end if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) { this.state = STATE_POSSIBLE; } this.state = this.process(inputDataClone); // the recognizer has recognized a gesture // so trigger an event if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) { this.tryEmit(inputDataClone); } }, /** * return the state of the recognizer * the actual recognizing happens in this method * @virtual * @param {Object} inputData * @returns {Const} STATE */ process: function(inputData) { }, // jshint ignore:line /** * return the preferred touch-action * @virtual * @returns {Array} */ getTouchAction: function() { }, /** * called when the gesture isn't allowed to recognize * like when another is being recognized or it is disabled * @virtual */ reset: function() { } }; /** * get a usable string, used as event postfix * @param {Const} state * @returns {String} state */ function stateStr(state) { if (state & STATE_CANCELLED) { return 'cancel'; } else if (state & STATE_ENDED) { return 'end'; } else if (state & STATE_CHANGED) { return 'move'; } else if (state & STATE_BEGAN) { return 'start'; } return ''; } /** * direction cons to string * @param {Const} direction * @returns {String} */ function directionStr(direction) { if (direction == DIRECTION_DOWN) { return 'down'; } else if (direction == DIRECTION_UP) { return 'up'; } else if (direction == DIRECTION_LEFT) { return 'left'; } else if (direction == DIRECTION_RIGHT) { return 'right'; } return ''; } /** * get a recognizer by name if it is bound to a manager * @param {Recognizer|String} otherRecognizer * @param {Recognizer} recognizer * @returns {Recognizer} */ function getRecognizerByNameIfManager(otherRecognizer, recognizer) { var manager = recognizer.manager; if (manager) { return manager.get(otherRecognizer); } return otherRecognizer; } /** * This recognizer is just used as a base for the simple attribute recognizers. * @constructor * @extends Recognizer */ function AttrRecognizer() { Recognizer.apply(this, arguments); } inherit(AttrRecognizer, Recognizer, { /** * @namespace * @memberof AttrRecognizer */ defaults: { /** * @type {Number} * @default 1 */ pointers: 1 }, /** * Used to check if it the recognizer receives valid input, like input.distance > 10. * @memberof AttrRecognizer * @param {Object} input * @returns {Boolean} recognized */ attrTest: function(input) { var optionPointers = this.options.pointers; return optionPointers === 0 || input.pointers.length === optionPointers; }, /** * Process the input and return the state for the recognizer * @memberof AttrRecognizer * @param {Object} input * @returns {*} State */ process: function(input) { var state = this.state; var eventType = input.eventType; var isRecognized = state & (STATE_BEGAN | STATE_CHANGED); var isValid = this.attrTest(input); // on cancel input and we've recognized before, return STATE_CANCELLED if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) { return state | STATE_CANCELLED; } else if (isRecognized || isValid) { if (eventType & INPUT_END) { return state | STATE_ENDED; } else if (!(state & STATE_BEGAN)) { return STATE_BEGAN; } return state | STATE_CHANGED; } return STATE_FAILED; } }); /** * Pan * Recognized when the pointer is down and moved in the allowed direction. * @constructor * @extends AttrRecognizer */ function PanRecognizer() { AttrRecognizer.apply(this, arguments); this.pX = null; this.pY = null; } inherit(PanRecognizer, AttrRecognizer, { /** * @namespace * @memberof PanRecognizer */ defaults: { event: 'pan', threshold: 10, pointers: 1, direction: DIRECTION_ALL }, getTouchAction: function() { var direction = this.options.direction; var actions = []; if (direction & DIRECTION_HORIZONTAL) { actions.push(TOUCH_ACTION_PAN_Y); } if (direction & DIRECTION_VERTICAL) { actions.push(TOUCH_ACTION_PAN_X); } return actions; }, directionTest: function(input) { var options = this.options; var hasMoved = true; var distance = input.distance; var direction = input.direction; var x = input.deltaX; var y = input.deltaY; // lock to axis? if (!(direction & options.direction)) { if (options.direction & DIRECTION_HORIZONTAL) { direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; hasMoved = x != this.pX; distance = Math.abs(input.deltaX); } else { direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN; hasMoved = y != this.pY; distance = Math.abs(input.deltaY); } } input.direction = direction; return hasMoved && distance > options.threshold && direction & options.direction; }, attrTest: function(input) { return AttrRecognizer.prototype.attrTest.call(this, input) && (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input))); }, emit: function(input) { this.pX = input.deltaX; this.pY = input.deltaY; var direction = directionStr(input.direction); if (direction) { this.manager.emit(this.options.event + direction, input); } this._super.emit.call(this, input); } }); /** * Pinch * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out). * @constructor * @extends AttrRecognizer */ function PinchRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(PinchRecognizer, AttrRecognizer, { /** * @namespace * @memberof PinchRecognizer */ defaults: { event: 'pinch', threshold: 0, pointers: 2 }, getTouchAction: function() { return [TOUCH_ACTION_NONE]; }, attrTest: function(input) { return this._super.attrTest.call(this, input) && (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN); }, emit: function(input) { this._super.emit.call(this, input); if (input.scale !== 1) { var inOut = input.scale < 1 ? 'in' : 'out'; this.manager.emit(this.options.event + inOut, input); } } }); /** * Press * Recognized when the pointer is down for x ms without any movement. * @constructor * @extends Recognizer */ function PressRecognizer() { Recognizer.apply(this, arguments); this._timer = null; this._input = null; } inherit(PressRecognizer, Recognizer, { /** * @namespace * @memberof PressRecognizer */ defaults: { event: 'press', pointers: 1, time: 500, // minimal time of the pointer to be pressed threshold: 5 // a minimal movement is ok, but keep it low }, getTouchAction: function() { return [TOUCH_ACTION_AUTO]; }, process: function(input) { var options = this.options; var validPointers = input.pointers.length === options.pointers; var validMovement = input.distance < options.threshold; var validTime = input.deltaTime > options.time; this._input = input; // we only allow little movement // and we've reached an end event, so a tap is possible if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) { this.reset(); } else if (input.eventType & INPUT_START) { this.reset(); this._timer = setTimeoutContext(function() { this.state = STATE_RECOGNIZED; this.tryEmit(); }, options.time, this); } else if (input.eventType & INPUT_END) { return STATE_RECOGNIZED; } return STATE_FAILED; }, reset: function() { clearTimeout(this._timer); }, emit: function(input) { if (this.state !== STATE_RECOGNIZED) { return; } if (input && (input.eventType & INPUT_END)) { this.manager.emit(this.options.event + 'up', input); } else { this._input.timeStamp = now(); this.manager.emit(this.options.event, this._input); } } }); /** * Rotate * Recognized when two or more pointer are moving in a circular motion. * @constructor * @extends AttrRecognizer */ function RotateRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(RotateRecognizer, AttrRecognizer, { /** * @namespace * @memberof RotateRecognizer */ defaults: { event: 'rotate', threshold: 0, pointers: 2 }, getTouchAction: function() { return [TOUCH_ACTION_NONE]; }, attrTest: function(input) { return this._super.attrTest.call(this, input) && (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN); } }); /** * Swipe * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction. * @constructor * @extends AttrRecognizer */ function SwipeRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(SwipeRecognizer, AttrRecognizer, { /** * @namespace * @memberof SwipeRecognizer */ defaults: { event: 'swipe', threshold: 10, velocity: 0.65, direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL, pointers: 1 }, getTouchAction: function() { return PanRecognizer.prototype.getTouchAction.call(this); }, attrTest: function(input) { var direction = this.options.direction; var velocity; if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) { velocity = input.velocity; } else if (direction & DIRECTION_HORIZONTAL) { velocity = input.velocityX; } else if (direction & DIRECTION_VERTICAL) { velocity = input.velocityY; } return this._super.attrTest.call(this, input) && direction & input.direction && input.distance > this.options.threshold && abs(velocity) > this.options.velocity && input.eventType & INPUT_END; }, emit: function(input) { var direction = directionStr(input.direction); if (direction) { this.manager.emit(this.options.event + direction, input); } this.manager.emit(this.options.event, input); } }); /** * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur * between the given interval and position. The delay option can be used to recognize multi-taps without firing * a single tap. * * The eventData from the emitted event contains the property `tapCount`, which contains the amount of * multi-taps being recognized. * @constructor * @extends Recognizer */ function TapRecognizer() { Recognizer.apply(this, arguments); // previous time and center, // used for tap counting this.pTime = false; this.pCenter = false; this._timer = null; this._input = null; this.count = 0; } inherit(TapRecognizer, Recognizer, { /** * @namespace * @memberof PinchRecognizer */ defaults: { event: 'tap', pointers: 1, taps: 1, interval: 300, // max time between the multi-tap taps time: 250, // max time of the pointer to be down (like finger on the screen) threshold: 2, // a minimal movement is ok, but keep it low posThreshold: 10 // a multi-tap can be a bit off the initial position }, getTouchAction: function() { return [TOUCH_ACTION_MANIPULATION]; }, process: function(input) { var options = this.options; var validPointers = input.pointers.length === options.pointers; var validMovement = input.distance < options.threshold; var validTouchTime = input.deltaTime < options.time; this.reset(); if ((input.eventType & INPUT_START) && (this.count === 0)) { return this.failTimeout(); } // we only allow little movement // and we've reached an end event, so a tap is possible if (validMovement && validTouchTime && validPointers) { if (input.eventType != INPUT_END) { return this.failTimeout(); } var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true; var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold; this.pTime = input.timeStamp; this.pCenter = input.center; if (!validMultiTap || !validInterval) { this.count = 1; } else { this.count += 1; } this._input = input; // if tap count matches we have recognized it, // else it has began recognizing... var tapCount = this.count % options.taps; if (tapCount === 0) { // no failing requirements, immediately trigger the tap event // or wait as long as the multitap interval to trigger if (!this.hasRequireFailures()) { return STATE_RECOGNIZED; } else { this._timer = setTimeoutContext(function() { this.state = STATE_RECOGNIZED; this.tryEmit(); }, options.interval, this); return STATE_BEGAN; } } } return STATE_FAILED; }, failTimeout: function() { this._timer = setTimeoutContext(function() { this.state = STATE_FAILED; }, this.options.interval, this); return STATE_FAILED; }, reset: function() { clearTimeout(this._timer); }, emit: function() { if (this.state == STATE_RECOGNIZED ) { this._input.tapCount = this.count; this.manager.emit(this.options.event, this._input); } } }); /** * Simple way to create an manager with a default set of recognizers. * @param {HTMLElement} element * @param {Object} [options] * @constructor */ function Hammer(element, options) { options = options || {}; options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset); return new Manager(element, options); } /** * @const {string} */ Hammer.VERSION = '2.0.4'; /** * default settings * @namespace */ Hammer.defaults = { /** * set if DOM events are being triggered. * But this is slower and unused by simple implementations, so disabled by default. * @type {Boolean} * @default false */ domEvents: false, /** * The value for the touchAction property/fallback. * When set to `compute` it will magically set the correct value based on the added recognizers. * @type {String} * @default compute */ touchAction: TOUCH_ACTION_COMPUTE, /** * @type {Boolean} * @default true */ enable: true, /** * EXPERIMENTAL FEATURE -- can be removed/changed * Change the parent input target element. * If Null, then it is being set the to main element. * @type {Null|EventTarget} * @default null */ inputTarget: null, /** * force an input class * @type {Null|Function} * @default null */ inputClass: null, /** * Default recognizer setup when calling `Hammer()` * When creating a new Manager these will be skipped. * @type {Array} */ preset: [ // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...] [RotateRecognizer, { enable: false }], [PinchRecognizer, { enable: false }, ['rotate']], [SwipeRecognizer,{ direction: DIRECTION_HORIZONTAL }], [PanRecognizer, { direction: DIRECTION_HORIZONTAL }, ['swipe']], [TapRecognizer], [TapRecognizer, { event: 'doubletap', taps: 2 }, ['tap']], [PressRecognizer] ], /** * Some CSS properties can be used to improve the working of Hammer. * Add them to this method and they will be set when creating a new Manager. * @namespace */ cssProps: { /** * Disables text selection to improve the dragging gesture. Mainly for desktop browsers. * @type {String} * @default 'none' */ userSelect: 'none', /** * Disable the Windows Phone grippers when pressing an element. * @type {String} * @default 'none' */ touchSelect: 'none', /** * Disables the default callout shown when you touch and hold a touch target. * On iOS, when you touch and hold a touch target such as a link, Safari displays * a callout containing information about the link. This property allows you to disable that callout. * @type {String} * @default 'none' */ touchCallout: 'none', /** * Specifies whether zooming is enabled. Used by IE10> * @type {String} * @default 'none' */ contentZooming: 'none', /** * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers. * @type {String} * @default 'none' */ userDrag: 'none', /** * Overrides the highlight color shown when the user taps a link or a JavaScript * clickable element in iOS. This property obeys the alpha value, if specified. * @type {String} * @default 'rgba(0,0,0,0)' */ tapHighlightColor: 'rgba(0,0,0,0)' } }; var STOP = 1; var FORCED_STOP = 2; /** * Manager * @param {HTMLElement} element * @param {Object} [options] * @constructor */ function Manager(element, options) { options = options || {}; this.options = merge(options, Hammer.defaults); this.options.inputTarget = this.options.inputTarget || element; this.handlers = {}; this.session = {}; this.recognizers = []; this.element = element; this.input = createInputInstance(this); this.touchAction = new TouchAction(this, this.options.touchAction); toggleCssProps(this, true); each(options.recognizers, function(item) { var recognizer = this.add(new (item[0])(item[1])); item[2] && recognizer.recognizeWith(item[2]); item[3] && recognizer.requireFailure(item[3]); }, this); } Manager.prototype = { /** * set options * @param {Object} options * @returns {Manager} */ set: function(options) { extend(this.options, options); // Options that need a little more setup if (options.touchAction) { this.touchAction.update(); } if (options.inputTarget) { // Clean up existing event listeners and reinitialize this.input.destroy(); this.input.target = options.inputTarget; this.input.init(); } return this; }, /** * stop recognizing for this session. * This session will be discarded, when a new [input]start event is fired. * When forced, the recognizer cycle is stopped immediately. * @param {Boolean} [force] */ stop: function(force) { this.session.stopped = force ? FORCED_STOP : STOP; }, /** * run the recognizers! * called by the inputHandler function on every movement of the pointers (touches) * it walks through all the recognizers and tries to detect the gesture that is being made * @param {Object} inputData */ recognize: function(inputData) { var session = this.session; if (session.stopped) { return; } // run the touch-action polyfill this.touchAction.preventDefaults(inputData); var recognizer; var recognizers = this.recognizers; // this holds the recognizer that is being recognized. // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED // if no recognizer is detecting a thing, it is set to `null` var curRecognizer = session.curRecognizer; // reset when the last recognizer is recognized // or when we're in a new session if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) { curRecognizer = session.curRecognizer = null; } var i = 0; while (i < recognizers.length) { recognizer = recognizers[i]; // find out if we are allowed try to recognize the input for this one. // 1. allow if the session is NOT forced stopped (see the .stop() method) // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one // that is being recognized. // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer. // this can be setup with the `recognizeWith()` method on the recognizer. if (session.stopped !== FORCED_STOP && ( // 1 !curRecognizer || recognizer == curRecognizer || // 2 recognizer.canRecognizeWith(curRecognizer))) { // 3 recognizer.recognize(inputData); } else { recognizer.reset(); } // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the // current active recognizer. but only if we don't already have an active recognizer if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) { curRecognizer = session.curRecognizer = recognizer; } i++; } }, /** * get a recognizer by its event name. * @param {Recognizer|String} recognizer * @returns {Recognizer|Null} */ get: function(recognizer) { if (recognizer instanceof Recognizer) { return recognizer; } var recognizers = this.recognizers; for (var i = 0; i < recognizers.length; i++) { if (recognizers[i].options.event == recognizer) { return recognizers[i]; } } return null; }, /** * add a recognizer to the manager * existing recognizers with the same event name will be removed * @param {Recognizer} recognizer * @returns {Recognizer|Manager} */ add: function(recognizer) { if (invokeArrayArg(recognizer, 'add', this)) { return this; } // remove existing var existing = this.get(recognizer.options.event); if (existing) { this.remove(existing); } this.recognizers.push(recognizer); recognizer.manager = this; this.touchAction.update(); return recognizer; }, /** * remove a recognizer by name or instance * @param {Recognizer|String} recognizer * @returns {Manager} */ remove: function(recognizer) { if (invokeArrayArg(recognizer, 'remove', this)) { return this; } var recognizers = this.recognizers; recognizer = this.get(recognizer); recognizers.splice(inArray(recognizers, recognizer), 1); this.touchAction.update(); return this; }, /** * bind event * @param {String} events * @param {Function} handler * @returns {EventEmitter} this */ on: function(events, handler) { var handlers = this.handlers; each(splitStr(events), function(event) { handlers[event] = handlers[event] || []; handlers[event].push(handler); }); return this; }, /** * unbind event, leave emit blank to remove all handlers * @param {String} events * @param {Function} [handler] * @returns {EventEmitter} this */ off: function(events, handler) { var handlers = this.handlers; each(splitStr(events), function(event) { if (!handler) { delete handlers[event]; } else { handlers[event].splice(inArray(handlers[event], handler), 1); } }); return this; }, /** * emit event to the listeners * @param {String} event * @param {Object} data */ emit: function(event, data) { // we also want to trigger dom events if (this.options.domEvents) { triggerDomEvent(event, data); } // no handlers, so skip it all var handlers = this.handlers[event] && this.handlers[event].slice(); if (!handlers || !handlers.length) { return; } data.type = event; data.preventDefault = function() { data.srcEvent.preventDefault(); }; var i = 0; while (i < handlers.length) { handlers[i](data); i++; } }, /** * destroy the manager and unbinds all events * it doesn't unbind dom events, that is the user own responsibility */ destroy: function() { this.element && toggleCssProps(this, false); this.handlers = {}; this.session = {}; this.input.destroy(); this.element = null; } }; /** * add/remove the css properties as defined in manager.options.cssProps * @param {Manager} manager * @param {Boolean} add */ function toggleCssProps(manager, add) { var element = manager.element; each(manager.options.cssProps, function(value, name) { element.style[prefixed(element.style, name)] = add ? value : ''; }); } /** * trigger dom event * @param {String} event * @param {Object} data */ function triggerDomEvent(event, data) { var gestureEvent = document.createEvent('Event'); gestureEvent.initEvent(event, true, true); gestureEvent.gesture = data; data.target.dispatchEvent(gestureEvent); } extend(Hammer, { INPUT_START: INPUT_START, INPUT_MOVE: INPUT_MOVE, INPUT_END: INPUT_END, INPUT_CANCEL: INPUT_CANCEL, STATE_POSSIBLE: STATE_POSSIBLE, STATE_BEGAN: STATE_BEGAN, STATE_CHANGED: STATE_CHANGED, STATE_ENDED: STATE_ENDED, STATE_RECOGNIZED: STATE_RECOGNIZED, STATE_CANCELLED: STATE_CANCELLED, STATE_FAILED: STATE_FAILED, DIRECTION_NONE: DIRECTION_NONE, DIRECTION_LEFT: DIRECTION_LEFT, DIRECTION_RIGHT: DIRECTION_RIGHT, DIRECTION_UP: DIRECTION_UP, DIRECTION_DOWN: DIRECTION_DOWN, DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL, DIRECTION_VERTICAL: DIRECTION_VERTICAL, DIRECTION_ALL: DIRECTION_ALL, Manager: Manager, Input: Input, TouchAction: TouchAction, TouchInput: TouchInput, MouseInput: MouseInput, PointerEventInput: PointerEventInput, TouchMouseInput: TouchMouseInput, SingleTouchInput: SingleTouchInput, Recognizer: Recognizer, AttrRecognizer: AttrRecognizer, Tap: TapRecognizer, Pan: PanRecognizer, Swipe: SwipeRecognizer, Pinch: PinchRecognizer, Rotate: RotateRecognizer, Press: PressRecognizer, on: addEventListeners, off: removeEventListeners, each: each, merge: merge, extend: extend, inherit: inherit, bindFn: bindFn, prefixed: prefixed }); if (typeof define == TYPE_FUNCTION && define.amd) { define(function() { return Hammer; }); } else if (typeof module != 'undefined' && module.exports) { module.exports = Hammer; } else { window[exportName] = Hammer; } })(window, document, 'Hammer'); /** * Prevent click events after a touchend. * * Inspired/copy-paste from this article of Google by Ryan Fioravanti * https://developers.google.com/mobile/articles/fast_buttons#ghost * * USAGE: * Prevent the click event for an certain element * ```` * PreventGhostClick(myElement); * ```` * * Prevent clicks on the whole document (not recommended!!) * * ```` * PreventGhostClick(document); * ```` * */ (function(window, document, exportName) { var coordinates = []; var threshold = 25; var timeout = 2500; // no touch support if(!("ontouchstart" in window)) { window[exportName] = function(){}; return; } /** * prevent clicks if they're in a registered XY region * @param {MouseEvent} ev */ function preventGhostClick(ev) { for (var i = 0; i < coordinates.length; i++) { var x = coordinates[i][0]; var y = coordinates[i][1]; // within the range, so prevent the click if (Math.abs(ev.clientX - x) < threshold && Math.abs(ev.clientY - y) < threshold) { ev.stopPropagation(); ev.preventDefault(); break; } } } /** * reset the coordinates array */ function resetCoordinates() { coordinates = []; } /** * remove the first coordinates set from the array */ function popCoordinates() { coordinates.splice(0, 1); } /** * if it is an final touchend, we want to register it's place * @param {TouchEvent} ev */ function registerCoordinates(ev) { // touchend is triggered on every releasing finger // changed touches always contain the removed touches on a touchend // the touches object might contain these also at some browsers (firefox os) // so touches - changedTouches will be 0 or lower, like -1, on the final touchend if(ev.touches.length - ev.changedTouches.length <= 0) { var touch = ev.changedTouches[0]; coordinates.push([touch.clientX, touch.clientY]); setTimeout(popCoordinates, timeout); } } /** * prevent click events for the given element * @param {EventTarget} el */ window[exportName] = function(el) { el.addEventListener("touchstart", resetCoordinates, true); el.addEventListener("touchend", registerCoordinates, true); }; document.addEventListener("click", preventGhostClick, true); })(window, document, 'PreventGhostClick'); // TUTAO start } // TUTAO end
elninosi/tutanota
web/lib/hammer-2.0.4.js
JavaScript
gpl-3.0
78,889
// // // This file has been excerpted from Quisk 3.5.11 by James C. Ahlstrom // http://james.ahlstrom.name/quisk/ // // In the original file there is no license. // // This module provides access to the SDR-IQ by RfSpace. It is the source // for the Python extension module sdriq. It can be used as a model for an // extension module for other hardware. Read the end of this file for more // information. This module was written by James Ahlstrom, N2ADR. // // #ifdef MS_WINDOWS #include <windows.h> #include "ftd2xx.h" #else #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <time.h> #include <fcntl.h> #include <termios.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #endif #include <complex.h> //#include "quisk.h" #include "sdriq.h" void QuiskSleepMicrosec(int usec) { #ifdef MS_WINDOWS int msec = (usec + 500) / 1000; // convert to milliseconds if (msec < 1) msec = 1; Sleep(msec); #else struct timespec tspec; tspec.tv_sec = usec / 1000000; tspec.tv_nsec = (usec - tspec.tv_sec * 1000000) * 1000; nanosleep(&tspec, NULL); #endif } double QuiskTimeSec(void) { // return time in seconds as a double #ifdef MS_WINDOWS FILETIME ft; ULARGE_INTEGER ll; GetSystemTimeAsFileTime(&ft); ll.LowPart = ft.dwLowDateTime; ll.HighPart = ft.dwHighDateTime; return (double)ll.QuadPart * 1.e-7; #else struct timeval tv; gettimeofday(&tv, NULL); return (double)tv.tv_sec + tv.tv_usec * 1e-6; #endif } QUISK_SOUND_STATE quisk_sound_state = { 0,0, 6000 }; #include "sdriq.h" struct ad6620 dec360 = { 4, 18, 5, // decimation factors 4, 13, 6, // scale factors {131, -230, -38, -304, -235, -346, -237, -181, 12, 149, 310, 349, 320, 154, -60, -310, -480, -540, -423, -169, 187, 523, 749, 762, 543, 117, -394, -851, -1093, -1025, -621, 22, 737, 1300, 1522, 1288, 625, -309, -1245, -1893, -2013, -1515, -489, 793, 1957, 2623, 2533, 1640, 149, -1533, -2893, -3475, -3023, -1584, 480, 2582, 4063, 4405, 3401, 1246, -1484, -3986, -5455, -5345, -3557, -509, 2951, 5776, 7030, 6193, 3355, -760, -4970, -7969, -8722, -6815, -2628, 2712, 7632, 10563, 10431, 7033, 1169, -5529, -11037, -13543, -12021, -6623, 1287, 9443, 15320, 16896, 13319, 5269, -5122, -14811, -20711, -20642, -14088, -2504, 10961, 22272, 27682, 24909, 13986, -2524, -20051, -33214, -37378, -30153, -12380, 11742, 35506, 51387, 53179, 38008, 7662, -31208, -68176, -91255, -89756, -57102, 7096, 96306, 197916, 295555, 372388, 414662, 414662, 372388, 295555, 197916, 96306, 7096, -57102, -89756, -91255, -68176, -31208, 7662, 38008, 53179, 51387, 35506, 11742, -12380, -30153, -37378, -33214, -20051, -2524, 13986, 24909, 27682, 22272, 10961, -2504, -14088, -20642, -20711, -14811, -5122, 5269, 13319, 16896, 15320, 9443, 1287, -6623, -12021, -13543, -11037, -5529, 1169, 7033, 10431, 10563, 7632, 2712, -2628, -6815, -8722, -7969, -4970, -760, 3355, 6193, 7030, 5776, 2951, -509, -3557, -5345, -5455, -3986, -1484, 1246, 3401, 4405, 4063, 2582, 480, -1584, -3023, -3475, -2893, -1533, 149, 1640, 2533, 2623, 1957, 793, -489, -1515, -2013, -1893, -1245, -309, 625, 1288, 1522, 1300, 737, 22, -621, -1025, -1093, -851, -394, 117, 543, 762, 749, 523, 187, -169, -423, -540, -480, -310, -60, 154, 320, 349, 310, 149, 12, -181, -237, -346, -235, -304, -38, -230, 131}}; struct ad6620 dec500 = { 4, 25, 5, 4, 16, 5, {-197, 356, -153, 176, -101, 34, -125, -46, -106, -7, 12, 115, 129, 157, 86, 12, -116, -197, -251, -203, -97, 80, 242, 364, 367, 259, 33, -228, -461, -565, -504, -255, 106, 488, 756, 813, 604, 172, -377, -868, -1139, -1066, -639, 53, 807, 1390, 1584, 1288, 537, -470, -1439, -2046, -2060, -1406, -232, 1143, 2290, 2820, 2496, 1339, -366, -2120, -3369, -3659, -2808, -976, 1340, 3448, 4652, 4486, 2873, 198, -2785, -5152, -6095, -5184, -2546, 1137, 4785, 7240, 7613, 5604, 1641, -3190, -7438, -9701, -9091, -5546, 69, 6163, 10849, 12519, 10373, 4745, -2905, -10342, -15198, -15692, -11253, -2807, 7368, 16229, 20838, 19296, 11436, -946, -14436, -24891, -28637, -23657, -10406, 8025, 26518, 39215, 41181, 30008, 6896, -23122, -51997, -70364, -69788, -44995, 4465, 73600, 152608, 228689, 288639, 321648, 321648, 288639, 228689, 152608, 73600, 4465, -44995, -69788, -70364, -51997, -23122, 6896, 30008, 41181, 39215, 26518, 8025, -10406, -23657, -28637, -24891, -14436, -946, 11436, 19296, 20838, 16229, 7368, -2807, -11253, -15692, -15198, -10342, -2905, 4745, 10373, 12519, 10849, 6163, 69, -5546, -9091, -9701, -7438, -3190, 1641, 5604, 7613, 7240, 4785, 1137, -2546, -5184, -6095, -5152, -2785, 198, 2873, 4486, 4652, 3448, 1340, -976, -2808, -3659, -3369, -2120, -366, 1339, 2496, 2820, 2290, 1143, -232, -1406, -2060, -2046, -1439, -470, 537, 1288, 1584, 1390, 807, 53, -639, -1066, -1139, -868, -377, 172, 604, 813, 756, 488, 106, -255, -504, -565, -461, -228, 33, 259, 367, 364, 242, 80, -97, -203, -251, -197, -116, 12, 86, 157, 129, 115, 12, -7, -106, -46, -125, 34, -101, 176, -153, 356, -197}}; struct ad6620 dec600 = { 5, 30, 4, // decimation factors 5, 17, 5, // scale factors { 436, -1759, 99, -1281, 0, -280, 619, 409, 553, -71, -344, -753, -537, -203, 453, 782, 838, 325, -326, -949, -1037, -628, 230, 991, 1330, 923, 10, -1032, -1569, -1324, -299, 956, 1822, 1739, 716, -809, -2000, -2212, -1212, 520, 2123, 2678, 1823, -111, -2124, -3143, -2509, -463, 2002, 3548, 3279, 1188, -1699, -3877, -4088, -2087, 1206, 4069, 4920, 3137, -478, -4094, -5720, -4343, -493, 3887, 6454, 5669, 1741, -3412, -7052, -7096, -3266, 2607, 7462, 8573, 5084, -1425, -7602, -10058, -7187, -193, 7400, 11481, 9579, 2301, -6756, -12777, -12244, -4971, 5569, 13854, 15181, 8285, -3699, -14613, -18387, -12369, 966, 14920, 21888, 17412, 2905, -14598, -25744, -23754, -8362, 13363, 30114, 32035, 16259, -10708, -35362, -43638, -28445, 5493, 42387, 62053, 49891, 5603, -53825, -99044, -99811, -38467, 80479, 229234, 365232, 446270, 446270, 365232, 229234, 80479, -38467, -99811, -99044, -53825, 5603, 49891, 62053, 42387, 5493, -28445, -43638, -35362, -10708, 16259, 32035, 30114, 13363, -8362, -23754, -25744, -14598, 2905, 17412, 21888, 14920, 966, -12369, -18387, -14613, -3699, 8285, 15181, 13854, 5569, -4971, -12244, -12777, -6756, 2301, 9579, 11481, 7400, -193, -7187, -10058, -7602, -1425, 5084, 8573, 7462, 2607, -3266, -7096, -7052, -3412, 1741, 5669, 6454, 3887, -493, -4343, -5720, -4094, -478, 3137, 4920, 4069, 1206, -2087, -4088, -3877, -1699, 1188, 3279, 3548, 2002, -463, -2509, -3143, -2124, -111, 1823, 2678, 2123, 520, -1212, -2212, -2000, -809, 716, 1739, 1822, 956, -299, -1324, -1569, -1032, 10, 923, 1330, 991, 230, -628, -1037, -949, -326, 325, 838, 782, 453, -203, -537, -753, -344, -71, 553, 409, 619, -280, 0, -1281, 99, -1759, 436}}; struct ad6620 dec1250 = { 10, 25, 5, // decimation factors 7, 15, 6, // scale factors {-378, 13756, -14444, 8014, -7852, 3556, -3779, 2733, -909, 2861, 208, 1827, -755, -243, -2134, -1267, -1705, 20, 492, 2034, 1885, 1993, 535, -459, -2052, -2387, -2454, -1112, 246, 2053, 2832, 3019, 1774, 133, -1973, -3220, -3654, -2546, -683, 1769, 3531, 4330, 3431, 1417, -1400, -3730, -5013, -4428, -2350, 831, 3780, 5669, 5520, 3489, -23, -3635, -6252, -6689, -4839, -1057, 3245, 6715, 7904, 6403, 2443, -2555, -6998, -9129, -8175, -4172, 1504, 7033, 10318, 10147, 6281, -23, -6747, -11415, -12315, -8815, -1972, 6041, 12354, 14669, 11830, 4593, -4800, -13060, -17207, -15419, -7992, 2861, 13425, 19944, 19729, 12404, 21, -13318, -22930, -25017, -18239, -4245, 12519, 26289, 31789, 26259, 10571, -10635, -30306, -41114, -38121, -20661, 6795, 35686, 55688, 58124, 39093, 1561, -44548, -84372, -101901, -84500, -26969, 66196, 180937, 296484, 390044, 442339, 442339, 390044, 296484, 180937, 66196, -26969, -84500, -101901, -84372, -44548, 1561, 39093, 58124, 55688, 35686, 6795, -20661, -38121, -41114, -30306, -10635, 10571, 26259, 31789, 26289, 12519, -4245, -18239, -25017, -22930, -13318, 21, 12404, 19729, 19944, 13425, 2861, -7992, -15419, -17207, -13060, -4800, 4593, 11830, 14669, 12354, 6041, -1972, -8815, -12315, -11415, -6747, -23, 6281, 10147, 10318, 7033, 1504, -4172, -8175, -9129, -6998, -2555, 2443, 6403, 7904, 6715, 3245, -1057, -4839, -6689, -6252, -3635, -23, 3489, 5520, 5669, 3780, 831, -2350, -4428, -5013, -3730, -1400, 1417, 3431, 4330, 3531, 1769, -683, -2546, -3654, -3220, -1973, 133, 1774, 3019, 2832, 2053, 246, -1112, -2454, -2387, -2052, -459, 535, 1993, 1885, 2034, 492, 20, -1705, -1267, -2134, -243, -755, 1827, 208, 2861, -909, 2733, -3779, 3556, -7852, 8014, -14444, 13756, -378 }}; // This module provides access to the SDR-IQ by RfSpace. It is the source // for the Python extension module sdriq. It can be used as a model for an // extension module for other hardware. Read the end of this file for more // information. This module was written by James Ahlstrom, N2ADR. // Start of SDR-IQ specific code: // #define SDRIQ_BLOCK 8194 #define SDRIQ_BUF_SIZE 131072 #define INC_IREAD if (++iread >= SDRIQ_BUF_SIZE) iread = 0; // Number of milliseconds to wait for SDR-IQ data on each read #define SDRIQ_MSEC 4 // Timeout for SDR-IQ as a multiple of SDRIQ_MSEC #define SDRIQ_TIMEOUT 50 // Type field for the message block header; upper 3 bits of byte #define TYPE_HOST_SET 0 #define TYPE_HOST_GET (1 << 5) #define NAME_SIZE 16 static double sdriq_clock; static int sdr_ack; // got ACK static int sdr_nak; // got NAK static char sdr_name[NAME_SIZE]; // control item 1 static char sdr_serial[NAME_SIZE]; // item 2 static int sdr_interface; // item 3 static int sdr_firmware; // item 4 static int sdr_bootcode; // item 4 static int sdr_status; // item 5 static char sdr_product_id[4]; // item 9 static int sdr_idle; // item 0x18, 1==idle, 2==run static int sdriq_freq=7050000; // set SDR-IQ to this frequency static int sdriq_gstate=2, sdriq_gain=64; // set SDR-IQ gain to this value static int sdriq_decimation = 1250; // set SDR-IQ decimation to this value static int cur_freq, cur_gstate, cur_gain; // current value of frequency and gain static int cur_decimation; // current value of decimation #ifdef MS_WINDOWS static FT_HANDLE quisk_sdriq_fd = INVALID_HANDLE_VALUE; static int Read(void * buf, int bufsize) { DWORD bytes, rx_bytes; if (quisk_sdriq_fd == INVALID_HANDLE_VALUE) return 0; if (FT_GetQueueStatus(quisk_sdriq_fd, &rx_bytes) != FT_OK) { quisk_sound_state.read_error++; return 0; } if (rx_bytes > bufsize) rx_bytes = bufsize; if (rx_bytes == 0) { return 0; } else if (FT_Read(quisk_sdriq_fd, buf, rx_bytes, &bytes) == FT_OK) { return bytes; } else { quisk_sound_state.read_error++; return 0; } } static int Write(void * buf, int length) { DWORD bytes; if (quisk_sdriq_fd == INVALID_HANDLE_VALUE) return 0; if (FT_Write(quisk_sdriq_fd, buf, length, &bytes) == FT_OK) { return bytes; } else { return 0; } } #else #define INVALID_HANDLE_VALUE -1 static int quisk_sdriq_fd = INVALID_HANDLE_VALUE; static int Read(void * buf, int bufsize) { int res; if (quisk_sdriq_fd == INVALID_HANDLE_VALUE) return 0; res = read(quisk_sdriq_fd, buf, bufsize); if (res < 0) { if (errno != EAGAIN && errno != EWOULDBLOCK) { quisk_sound_state.read_error++; } return 0; } return res; } static int Write(void * buf, int length) { int res; if (quisk_sdriq_fd == INVALID_HANDLE_VALUE) return 0; res = write(quisk_sdriq_fd, buf, length); if (res <= 0) return 0; return res; } #endif static void update_item(int item, const unsigned char * data) { switch(item) { // 5.1.General Control Items // 5.1.1 Target Name // Purpose: Returns an ASCII string describing the Target device. // Control Item Code : 0x0001 // Control Item Parameter Format: The data is a NULL(zero) terminated character byte string. // Example, to request the target name, the host sends: // [04][20] [01][00] // The Target responds with "SDR-IQ" : // [0B][00] [01]00] [53][44][52][2D][31][34][00] case 1: strncpy(sdr_name, (char *)data, NAME_SIZE); sdr_name[NAME_SIZE - 1] = 0; break; // 5.1.2 Target Serial Number // Purpose: Contains an ASCII string containing the Target device serial number. // Control Item Code : 0x0002 // Control Item Parameter Format: The data is a NULL(zero) terminated character byte string. // Example, to request the target serial number the host sends: // [04][20] [02][00] // The Target responds with "MT123456" or the serial number the particular device: // [0C][00] [02]00] [4D][54][31][32]33][34[35[36][00]\Uffffffff // case 2: strncpy(sdr_serial, (char *)data, NAME_SIZE); sdr_serial[NAME_SIZE - 1] = 0; break; // 5.1.3 Interface Version // Purpose: Contains the version number of the Host or Targets implemented Interface. This allows the Host or Target // to display or adapt to different versions of the interface. // // Control Item Code: 0x0003 // Control Item Parameter Format: The data is a 2 byte 16 bit unsigned variable equal to the version times 100. For // example the value 123 would be version 1.23. // Example, to request the target interface version the host sends: // [04][20] [03][00] // The Target with an interface version of 5.29 responds with: // [06][00] [03]00] [11][02] case 3: sdr_interface = (data[1] << 8) | data[0]; break; // 5.1.4 Hardware/Firmware Versions // Purpose: Contains the Firmware or Hardware version information of the Target. // Control Item Code: 0x0004 // Control Item Parameter Format: // The first parameter is a 1 byte Firmware ID specifying which firmware or hardware version to retrieve. // ID=0 returns the PIC boot code version. // ID=1 returns the PIC firmware version. // The version data is a 2 byte 16 bit unsigned variable equal to the version times 100. For example the value 123 // would be version 1.23. // // Example, to request the PIC firmware version host sends: // [05][20] [04][00] [01] // The Target with a PIC firmware version of 5.29 responds with: // [07][00] [04][00] [01] [11][02] // // Example, to request the PIC boot code version host sends: // [05][20] [04][00] [00] // The Target with a PIC firmware version of 5.29 responds with: // [07][00] [04][00] [00] [11][02] // case 4: if (data[0]) sdr_firmware = (data[2] << 8) | data[1]; else sdr_bootcode = (data[2] << 8) | data[1]; break; // 5.1.5 Status/Error Code // Purpose: Contains the Error/Status code(s) of the Target. This item is used to notify the Host of any error or // problem using a list of code values. Once the error code(s) are obtained, the host can interrogate the Target "Error // String" Control Item to obtain a description string of the error(s) or status. // Control Item Code: 0x0005 // Control Item Parameter Format: The data is a list of 1 byte unsigned variable equal to the error number associated // with a particular error. There can be multiple error codes returned by the Target. // 0x0B = SDR-IQ Idle // 0x0C = SDR-IQ Busy(capturing data) // 0x0D = SDR-IQ Loading AD6620 parameters // 0x0E = SDR-IQ Boot mode Idle // 0x0F = SDR-IQ Boot mode busy programming // 0x20 = SDR-IQ A/D overload occurred // 0x80 = SDR-IQ Boot mode programming error // Example, host request status: // [04][20] [05][00] // The idle Target responds with // [05][00] [05]00] [0B] // case 5: sdr_status = data[0]; if (data[0] == 0x20) quisk_sound_state.overrange++; #if DEBUG if (data[0] == 0x20) printf ("Got overrange (clip)\n"); else printf ("Got status 0x%X\n", data[0]); #endif break; // 5.1.6 Product ID (Firmware 1.04 or Greater) // Purpose: Returns the 4 byte product ID for the SDR-IQ used in firmware update validation. // Control Item Code: 0x0009 // Control Item Parameter Format: // A read only value returned identifying the SDR-IQ. // Example, host request product ID: // [04][20] [09][00] // The Target responds with // [08][00] [09][00] [00][A5][FF][5A] case 9: memcpy (sdr_product_id, data, 4); break; case 0x18: sdr_idle = data[1]; #if DEBUG if (sdr_idle == 1) printf ("Got idle code IDLE\n"); else if (sdr_idle == 2) printf ("Got idle code RUN\n"); else printf ("Got idle code UNKNOWN\n"); #endif break; } } static void get_item( // Host sends a request for a control item int item, // the item number int nparams, // the length of params char * params) // byte array of parameters, or NULL iff nparams==0 { int length; // length of message block char buf[64]; // message block header and control item and data length = 4 + nparams; if (length > 60) return; // error buf[0] = length & 0xFF; // length LSB buf[1] = TYPE_HOST_GET | ((length >> 8) & 0x1F); // 3-bit type and 5-bit length MSB buf[2] = item & 0xFF; // item LSB buf[3] = (item >> 8) & 0xFF; // item MSB if (nparams) memcpy(buf + 4, params, nparams); if (Write(buf, length) != length) { quisk_sound_state.read_error++; #if DEBUG printf("get_item write error\n"); #endif } #if DEBUG > 1 printf ("get_item 0x%X\n", item); #endif return; } static void set_item( // host command to set a control item int item, // the item number int nparams, // the length of params char * params) // byte array of parameters, or NULL iff nparams==0 { int length; char buf[64]; // message block header and control item and data length = 4 + nparams; // total length if (length > 60) return; // error buf[0] = length & 0xFF; // length LSB buf[1] = TYPE_HOST_SET | ((length >> 8) & 0x1F); // 3-bit type and 5-bit length MSB buf[2] = item & 0xFF; // item LSB buf[3] = (item >> 8) & 0xFF; // item MSB if (nparams) memcpy(buf + 4, params, nparams); if (Write(buf, length) != length) { quisk_sound_state.read_error++; #if DEBUG printf("set_item write error\n"); #endif } #if DEBUG > 1 printf ("set_item 0x%X\n", item); #endif } // The ft245 driver does not have a circular buffer for input; bytes are just appended // to the buffer. When all bytes are read and the buffer goes empty, the pointers are reset to zero. // Be sure to empty out the ft245 frequently so its buffer does not overflow. static int sdr_recv(complex * samp, int sampsize) { // Read all data from the SDR-IQ and process it. // Return the number >= 0 of I/Q data samples that are available in samp. int k, res, item, navail, nSamples; short ii, qq; unsigned char buf128[128]; static unsigned char buf[SDRIQ_BUF_SIZE]; static int iread=0; static int iwrite=0; static int state=0; static int length; static int type; static int sample_count; nSamples = 0; // number of samples added to samp // first read all characters from the ft245 driver into our large buffer if (iread == 0) { k = SDRIQ_BUF_SIZE - iwrite - 1; if (k > 65536) // maximum read for ft245 k = 65536; if (k > 0) { res = Read(buf + iwrite, k); iwrite += res; } } else if (iread <= iwrite) { k = SDRIQ_BUF_SIZE - iwrite; if (k > 65536) // maximum read for ft245 k = 65536; res = Read(buf + iwrite, k); if (res == k) iwrite = 0; else if (res > 0) iwrite += res; } if (iread > iwrite) { k = iread - iwrite - 1; if (k > 65536) // maximum read for ft245 k = 65536; if (k > 0) { res = Read(buf + iwrite, k); iwrite += res; } } // Now process the data we have in buf start_here: if (iread > iwrite) // calculate number of available bytes: navail navail = SDRIQ_BUF_SIZE - iread + iwrite; else navail = iwrite - iread; if (state == 0) { // starting state; we need to read the first two bytes for length and type if (navail < 2) return nSamples; // no more data available // we have the first two bytes length = buf[iread]; INC_IREAD type = (buf[iread] >> 5) & 0x7; // 3-bit type length |= (buf[iread] & 0x1F) << 8; // length including header INC_IREAD #if DEBUG > 1 if (length != 0 && !(type == 3 && length == 3)) printf("Got message type %d length %d\n", type, length); #endif if (type > 3 && length == 0) // data block with zero length length = 8194; // special data length length -= 2; // we read two bytes; length is the remaining bytes if (length < 0) { state = 9; // bad length; attempt resync } else if (length == 0) { // NAK sdr_nak = 1; #if DEBUG printf("Got NAK\n"); #endif // state remains at zero } else if (samp && length > 50 && length < 8192) { // No such message; we are out of sync state = 9; } else if (samp && type == 4 && length == 8192) { // ADC samples data block state = 5; sample_count = 2048; } else if (navail >= length) { state = 3; } else { state = 2; } goto start_here; // process the next state } else if (state == 2) { // waiting for all "length" bytes to be read if (navail < length) return nSamples; // partially read block state = 3; goto start_here; // process the next state } else if (state == 3) { // we have all the bytes of the record available if (length == 1 && type == 3) { // ACK sdr_ack = buf[iread]; INC_IREAD #if DEBUG > 1 printf("Got ACK for 0x%X\n", sdr_ack); #endif } else if ((type == 0 || type == 1) && length >= 2) { // control item item = buf[iread]; INC_IREAD item |= buf[iread] << 8; // control item number INC_IREAD length -= 2; for (k = 0; k < length; k++) { if (k < 128) buf128[k] = buf[iread]; INC_IREAD } update_item(item, buf128); } else { iread += length; // discard block if (iread >= SDRIQ_BUF_SIZE) iread -= SDRIQ_BUF_SIZE; } state = 0; goto start_here; // we read a whole block } else if (state == 5) { // read available samples into samp //ptimer(4096); while (navail >= 4 && sample_count && nSamples < sampsize) { // samples are 16-bit little-endian ii = buf[iread]; // assumes a short is two bytes INC_IREAD ii |= buf[iread] << 8; INC_IREAD qq = buf[iread]; INC_IREAD qq |= buf[iread] << 8; INC_IREAD navail -= 4; // we read four bytes // convert 16-bit samples to 32-bit samples samp[nSamples++] = 65536.0 * ii + 65536.0 * qq * I; // return sample as complex number sample_count--; // we added one sample } //printf("State %d navail %d sample_count %d nSamples %d\n", state, navail, sample_count, nSamples); if (sample_count > 0) // no more samples available return nSamples; // return the available samples state = 0; // this block was completely read goto start_here; // process the next state } else if (state == 9) { // try to re-synchronize quisk_sound_state.read_error++; #if DEBUG printf ("Lost sync: type %d length %d\n", type, length); #endif while (1) { // empty the buffer if (Read(buf, 1024) == 0) break; } #if DEBUG > 2 printf("Buffer is empty\n"); #endif while (1) { // look for the start of data blocks "\x00\x80" res = Read(buf, 1); if (res != 1) { QuiskSleepMicrosec(SDRIQ_MSEC * 1000); } else if (state == 9) { // look for 0x00 if (buf[0] == 0x00) state = 10; } else { // state 10: look for 0x80 if (buf[0] == 0x80) { state = 5; iread = iwrite = 0; sample_count = 2048; #if DEBUG printf("Regained sync\n"); #endif break; // we probably have a data block start } else if (buf[0] != 0x00) { state = 9; } } } goto start_here; // process the next state } return nSamples; // should not happen } static void set_ad6620( // host command to set an AD6620 register int address, // the register address int value) // the value; up to 4 bytes { char buf[12]; buf[0] = '\x09'; buf[1] = '\xA0'; buf[2] = address & 0xFF; // low byte buf[3] = (address >> 8) & 0xFF; // high byte buf[4] = value & 0xFF; // low byte value = value >> 8; buf[5] = value & 0xFF; value = value >> 8; buf[6] = value & 0xFF; value = value >> 8; buf[7] = value & 0xFF; buf[8] = 0; if (Write(buf, 9) != 9) { quisk_sound_state.read_error++; #if DEBUG printf ("set_ad6620 write error\n"); #endif } #if DEBUG > 1 printf ("set_ad6620 address 0x%X\n", address); #endif } static void wset_ad6620(int address, int value) { // Set AD6620 register and wait for ACK int i; sdr_ack = -1; set_ad6620(address, value); for (i = 0; i < SDRIQ_TIMEOUT; i++) { sdr_recv(NULL, 0); if (sdr_ack != -1) break; QuiskSleepMicrosec(SDRIQ_MSEC * 1000); } #if DEBUG if (sdr_ack != 1) printf ("Failed to get ACK for AD6620 address 0x%X\n", address); #endif } static void set_freq_sdriq(void) // Set SDR-IQ frequency { char buf[8]; int freq; freq = sdriq_freq; buf[0] = 0; buf[1] = freq & 0xFF; // low byte freq = freq >> 8; buf[2] = freq & 0xFF; freq = freq >> 8; buf[3] = freq & 0xFF; freq = freq >> 8; buf[4] = freq & 0xFF; buf[5] = 1; set_item(0x0020, 6, buf); cur_freq = sdriq_freq; } static void set_gain_sdriq(void) { char buf[2]; switch (sdriq_gstate) { case 0: buf[0] = 0; buf[1] = sdriq_gain & 0xFF; break; case 1: buf[0] = 1; buf[1] = sdriq_gain & 0x7F; buf[1] |= 0x80; break; case 2: buf[0] = 1; buf[1] = sdriq_gain & 0x7F; break; } set_item(0x0038, 2, buf); cur_gstate = sdriq_gstate; cur_gain = sdriq_gain; } static void program_ad6620(void) // Set registers { int i; struct ad6620 *pt; switch (sdriq_decimation) { case 360: pt = &dec360; break; case 500: pt = &dec500; break; case 600: pt = &dec600; break; case 1250: pt = &dec1250; break; default: pt = &dec1250; break; } wset_ad6620(0x300, 1); // soft reset for (i = 0; i < 256; i++) wset_ad6620(i, pt->coef[i]); wset_ad6620(0x301, 0); wset_ad6620(0x302, -1); wset_ad6620(0x303, 0); wset_ad6620(0x304, 0); wset_ad6620(0x305, pt->Scic2); wset_ad6620(0x306, pt->Mcic2 - 1); wset_ad6620(0x307, pt->Scic5); wset_ad6620(0x308, pt->Mcic5 - 1); wset_ad6620(0x309, pt->Sout); wset_ad6620(0x30A, pt->Mrcf - 1); wset_ad6620(0x30B, 0); wset_ad6620(0x30C, 255); wset_ad6620(0x30D, 0); set_freq_sdriq(); set_gain_sdriq(); wset_ad6620(0x300, 0); cur_decimation = sdriq_decimation; } #ifdef MS_WINDOWS static void quisk_open_sdriq_dev(const char * name, char * buf, int bufsize) { #if DEBUG FT_STATUS ftStatus; FT_DEVICE_LIST_INFO_NODE *devInfo; DWORD numDevs; int i; // create the device information list ftStatus = FT_CreateDeviceInfoList(&numDevs); if (ftStatus == FT_OK) { printf("Number of devices is %d\n", (int)numDevs); } else { printf("Number of devices failed\n"); numDevs = 0; } if (numDevs > 0) { // allocate storage for list based on numDevs devInfo = (FT_DEVICE_LIST_INFO_NODE*)malloc(sizeof(FT_DEVICE_LIST_INFO_NODE)*numDevs); // get the device information list ftStatus = FT_GetDeviceInfoList(devInfo, &numDevs); if (ftStatus == FT_OK) { for (i = 0; i < numDevs; i++) { printf("Dev %d:\n",i); printf(" Flags=0x%x\n", (unsigned int)devInfo[i].Flags); printf(" Type=0x%x\n", (unsigned int)devInfo[i].Type); printf(" ID=0x%x\n", (unsigned int)devInfo[i].ID); printf(" LocId=0x%x\n", (unsigned int)devInfo[i].LocId); printf(" SerialNumber=%s\n", devInfo[i].SerialNumber); printf(" Description=%s\n", devInfo[i].Description); printf(" ftHandle=0x%x\n", (unsigned int)devInfo[i].ftHandle); } } free(devInfo); } #endif // DEBUG if (FT_OpenEx ("SDR-IQ", FT_OPEN_BY_DESCRIPTION, &quisk_sdriq_fd) != FT_OK) { strncpy(buf, "Open SDR-IQ failed", bufsize); quisk_sdriq_fd = INVALID_HANDLE_VALUE; return; } if (FT_SetTimeouts(quisk_sdriq_fd, 2, 100) != FT_OK) { strncpy(buf, "Set Timeouts failed", bufsize); return; } } #else static void quisk_open_sdriq_dev(const char * name, char * buf, int bufsize) { struct termios newtio; if (!strncmp(name, "/dev/ttyUSB", 11)) { // use ftdi_sio driver quisk_sdriq_fd = open(name, O_RDWR | O_NOCTTY); if (quisk_sdriq_fd < 0) { strncpy(buf, "Open SDR-IQ : ", bufsize); strncat(buf, strerror(errno), bufsize - strlen(buf) - 1); quisk_sdriq_fd = INVALID_HANDLE_VALUE; return; } bzero(&newtio, sizeof(newtio)); newtio.c_cflag = CS8 | CLOCAL | CREAD; newtio.c_iflag = IGNPAR; newtio.c_oflag = 0; cfsetispeed(&newtio, B230400); cfsetospeed(&newtio, B230400); newtio.c_lflag = 0; newtio.c_cc[VTIME] = 0; // specify non-blocking read newtio.c_cc[VMIN] = 0; tcflush(quisk_sdriq_fd, TCIFLUSH); tcsetattr(quisk_sdriq_fd, TCSANOW, &newtio); } else { // use ft245 or similar driver quisk_sdriq_fd = open(name, O_RDWR | O_NONBLOCK); if (quisk_sdriq_fd < 0) { strncpy(buf, "Open SDR-IQ: ", bufsize); strncat(buf, strerror(errno), bufsize - strlen(buf) - 1); quisk_sdriq_fd = INVALID_HANDLE_VALUE; return; } } return; } #endif static int quisk_open_sdriq(const char * name, char * buf, int bufsize) { char buf1024[1024]; int i, freq; fprintf (stderr, "********** %s\n", __FUNCTION__); quisk_open_sdriq_dev(name, buf, bufsize); if (quisk_sdriq_fd == INVALID_HANDLE_VALUE) return -1; // error sdr_name[0] = 0; sdr_serial[0] = 0; sdr_idle = -1; // unknown state set_item(0x0018, 4, "\x81\x01\x00\x00"); QuiskSleepMicrosec(1000000); while (1) { // read and discard any available output if (Read(buf1024, 1024) == 0) break; } set_item(0x0018, 4, "\x81\x01\x00\x00"); get_item(0x0002, 0, NULL); // request serial number get_item(0x0003, 0, NULL); // request interface Version get_item(0x0004, 0, NULL); // request harwdware/firmware version //get_item(0x0004, 1, "0x00"); // request harwdware/firmware version //get_item(0x0004, 1, "0x01"); // request harwdware/firmware version get_item(0x0005, 0, NULL); // request status get_item(0x0009, 0, NULL); // request product ID // set sample rate freq = sdriq_clock; buf1024[0] = 0; buf1024[1] = freq & 0xFF; // low byte freq = freq >> 8; buf1024[2] = freq & 0xFF; freq = freq >> 8; buf1024[3] = freq & 0xFF; freq = freq >> 8; buf1024[4] = freq & 0xFF; set_item(0x00B0, 5, buf1024); // set actual clock speed get_item(0x0001, 0, NULL); // request name // loop for input for (i = 0; i < SDRIQ_TIMEOUT; i++) { sdr_recv(NULL, 0); if (sdr_name[0] != 0) break; QuiskSleepMicrosec(SDRIQ_MSEC * 1000); } if (sdr_name[0]) { // we got a response snprintf(buf, bufsize, "Capture from %s serial %s.", sdr_name, sdr_serial); program_ad6620(); } else { snprintf(buf, bufsize, "No response from SDR-IQ"); } #if DEBUG printf ("%s\n", buf); #endif return 0; } static void WaitForPoll(void) { #if 1 static double time0 = 0; // time in seconds double timer; // time remaining from last poll usec timer = quisk_sound_state.data_poll_usec - (QuiskTimeSec() - time0) * 1e6; if (timer > 1000.0) // see if enough time has elapsed QuiskSleepMicrosec((int)timer); // wait for the remainder of the poll interval time0 = QuiskTimeSec(); // reset starting time value #endif } // End of most SDR-IQ specific code. #if 0 /////////////////////////////////////////////////////////////////////////// // The API requires at least two Python functions for Open and Close, plus // additional Python functions as needed. And it requires exactly three // C funcions for Start, Stop and Read samples. Quisk runs in two threads, // a GUI thread and a sound thread. You must not call the GUI or any Python // code from the sound thread. You must return promptly from functions called // by the sound thread. // // The calling sequence is Open, Start, then repeated calls to Read, then // Stop, then Close. // Start of Application Programming Interface (API) code: // Start sample capture; called from the sound thread. static void quisk_start_sdriq(void) { if (sdr_idle != 2) set_item(0x0018, 4, "\x81\x02\x00\x01"); } // Stop sample capture; called from the sound thread. static void quisk_stop_sdriq(void) { int msec; complex samples[2048]; for (msec = 0; msec < 1001; msec++) { if (msec % 100 == 0) set_item(0x0018, 4, "\x81\x01\x00\x00"); sdr_recv(samples, 2048); if (sdr_idle == 1) break; QuiskSleepMicrosec(1000); } #if DEBUG if (msec < 1001) printf("quisk_stop_sdriq succeeded\n"); else printf("quisk_stop_sdriq timed out\n"); #endif } // Called in a loop to read samples; called from the sound thread. static int quisk_read_sdriq (complex * cSamples) { int length; WaitForPoll(); if (quisk_sdriq_fd == INVALID_HANDLE_VALUE) return -1; // sdriq is closed length = sdr_recv(cSamples, SAMP_BUFFER_SIZE); // get all available samples if (cur_freq != sdriq_freq) // check frequency set_freq_sdriq(); if (cur_gstate != sdriq_gstate || cur_gain != sdriq_gain) // check gain set_gain_sdriq(); if (cur_decimation != sdriq_decimation) { // check decimation quisk_stop_sdriq(); program_ad6620(); quisk_start_sdriq(); } return length; // return number of samples } // Called to close the sample source; called from the GUI thread. static PyObject * close_samples(PyObject * self, PyObject * args) { if (!PyArg_ParseTuple (args, "")) return NULL; if (quisk_sdriq_fd != INVALID_HANDLE_VALUE) { sdr_idle = -1; // unknown state #ifdef MS_WINDOWS FT_Close(quisk_sdriq_fd); #else close(quisk_sdriq_fd); #endif quisk_sdriq_fd = INVALID_HANDLE_VALUE; } Py_INCREF (Py_None); return Py_None; } // Called to open the sample source; called from the GUI thread. static PyObject * open_samples(PyObject * self, PyObject * args) { const char * name; char buf[128]; if (!PyArg_ParseTuple (args, "")) return NULL; name = QuiskGetConfigString("sdriq_name", "NoName"); sdriq_clock = QuiskGetConfigDouble("sdriq_clock", 66666667.0); // Record our C-language Start/Stop/Read functions for use by sound.c. pt_sample_start = &quisk_start_sdriq; pt_sample_stop = &quisk_stop_sdriq; pt_sample_read = &quisk_read_sdriq; ////////////// quisk_open_sdriq(name, buf, 128); // SDR-IQ specific return PyString_FromString(buf); // return a string message } // Miscellaneous functions needed by the SDR-IQ; called from the GUI thread as // a result of button presses. // Set the receive frequency; called from the GUI thread. static PyObject * freq_sdriq(PyObject * self, PyObject * args) { if (!PyArg_ParseTuple (args, "i", &sdriq_freq)) return NULL; Py_INCREF (Py_None); return Py_None; } // Set the preamp gain; called from the GUI thread. static PyObject * gain_sdriq(PyObject * self, PyObject * args) // Called from GUI thread { // gstate == 0: Gain must be 0, -10, -20, or -30 // gstate == 1: Attenuator is on and gain is 0 to 127 (7 bits) // gstate == 2: Attenuator is off and gain is 0 to 127 (7 bits) if (!PyArg_ParseTuple (args, "ii", &sdriq_gstate, &sdriq_gain)) return NULL; Py_INCREF (Py_None); return Py_None; } // Set the decimation; called from the GUI thread. static PyObject * set_decimation(PyObject * self, PyObject * args) { if (!PyArg_ParseTuple (args, "i", &sdriq_decimation)) return NULL; Py_INCREF (Py_None); return Py_None; } // Functions callable from Python are listed here: static PyMethodDef QuiskMethods[] = { {"open_samples", open_samples, METH_VARARGS, "Open the RfSpace SDR-IQ."}, {"close_samples", close_samples, METH_VARARGS, "Close the RfSpace SDR-IQ."}, {"freq_sdriq", freq_sdriq, METH_VARARGS, "Set the frequency of the SDR-IQ"}, {"gain_sdriq", gain_sdriq, METH_VARARGS, "Set the gain of the SDR-IQ"}, {"set_decimation", set_decimation, METH_VARARGS, "Set the decimation of the SDR-IQ"}, {NULL, NULL, 0, NULL} /* Sentinel */ }; // Initialization, and registration of public symbol "initsdriq": PyMODINIT_FUNC initsdriq (void) { Py_InitModule ("sdriq", QuiskMethods); } #else #define SAMP_BUFFER_SIZE 66000 void quisk_start_sdriq(void) { fprintf (stderr, "%s\n", __FUNCTION__); if (sdr_idle != 2) set_item(0x0018, 4, "\x81\x02\x00\x01"); } // Stop sample capture; called from the sound thread. void quisk_stop_sdriq(void) { int msec; complex cc[2048]; fprintf (stderr, "%s\n", __FUNCTION__); for (msec = 0; msec < 1001; msec++) { if (msec % 100 == 0) set_item(0x0018, 4, "\x81\x01\x00\x00"); sdr_recv(cc, 2048); if (sdr_idle == 1) break; QuiskSleepMicrosec(1000); } #if DEBUG if (msec < 1001) printf("quisk_stop_sdriq succeeded\n"); else printf("quisk_stop_sdriq timed out\n"); #endif } // Called in a loop to read samples; called from the sound thread. int quisk_read_sdriq(complex * cSamples) { int length; WaitForPoll(); if (quisk_sdriq_fd == INVALID_HANDLE_VALUE) return -1; // sdriq is closed length = sdr_recv(cSamples, SAMP_BUFFER_SIZE); // get all available samples if (cur_freq != sdriq_freq) // check frequency set_freq_sdriq(); if (cur_gstate != sdriq_gstate || cur_gain != sdriq_gain) // check gain set_gain_sdriq(); if (cur_decimation != sdriq_decimation) { // check decimation quisk_stop_sdriq(); program_ad6620(); quisk_start_sdriq(); } return length; // return number of samples } // Called to close the sample source; called from the GUI thread. void close_samples () { fprintf (stderr, "%s\n", __FUNCTION__); if (quisk_sdriq_fd != INVALID_HANDLE_VALUE) { sdr_idle = -1; // unknown state #ifdef MS_WINDOWS FT_Close(quisk_sdriq_fd); #else close(quisk_sdriq_fd); #endif quisk_sdriq_fd = INVALID_HANDLE_VALUE; } } int open_samples(const char *n, const char *clock, char* buf) { const char * name; //static char buf[128]; fprintf (stderr, "%s\n", __FUNCTION__); if (n) { name = n; } else { name = "NoName"; } //name = QuiskGetConfigString("sdriq_name", "NoName"); //sdriq_clock = QuiskGetConfigDouble("sdriq_clock", 66666667.0); sdriq_clock = 66666667.0; // Record our C-language Start/Stop/Read functions for use by sound.c. // pt_sample_start = &quisk_start_sdriq; // pt_sample_stop = &quisk_stop_sdriq; // pt_sample_read = &quisk_read_sdriq; ////////////// return quisk_open_sdriq(name, buf, 128); // SDR-IQ specific } // Miscellaneous functions needed by the SDR-IQ; called from the GUI thread as // a result of button presses. // Set the receive frequency; called from the GUI thread. void freq_sdriq (int f) { sdriq_freq = f; } // Set the preamp gain; called from the GUI thread. void gain_sdriq (int gain_state, int gain) { // gstate == 0: Gain must be 0, -10, -20, or -30 // gstate == 1: Attenuator is on and gain is 0 to 127 (7 bits) // gstate == 2: Attenuator is off and gain is 0 to 127 (7 bits) sdriq_gstate = gain_state; sdriq_gain = gain; } // Set the decimation; called from the GUI thread. void set_decimation (int decimation) { sdriq_decimation = decimation; } void set_bandwidth (int nb) { fprintf (stderr, "%s: BW: %d\n", __FUNCTION__, nb); switch (nb) { case 53333: // 66666667.0 / 1250 set_decimation (1250); break; case 111111: // 66666667.0 / 600 set_decimation (600); break; case 133333: // 66666667.0 / 500 set_decimation (500); break; case 185185: // 66666667.0 / 360 set_decimation (360); break; } } const char *get_serial () { return sdr_serial; } #endif const QUISK_SOUND_STATE *get_state (void) { return &quisk_sound_state; } #include <pthread.h> struct AsynchCtxData { void *pUserData; SDRIQ_CB udcf ; int run; }; typedef struct _hq { pthread_t thread_id; struct AsynchCtxData *pacd ; } HQ; HQ hq = { -1, 0 }; static void *asynch_input_thread (void *p) { static SAMPLE_T ii [SAMP_BUFFER_SIZE]; static SAMPLE_T qq [SAMP_BUFFER_SIZE]; static complex cc [SAMP_BUFFER_SIZE]; struct AsynchCtxData *pacd = (struct AsynchCtxData *)p; quisk_start_sdriq (); fprintf (stderr, "%s STARTED %p %p %p\n", __FUNCTION__, ii, qq, cc); while (pacd->run) { //unsigned char buffer [10240]; //int buf_len = get_data (&hq, buffer, sizeof(buffer));quisk_read_sdriq_ul (ii, qq); int buf_len = quisk_read_sdriq (cc); //fprintf (stderr, "%s: buf_len: %d\n", __FUNCTION__, buf_len); if (buf_len > 0) { int x; for (x=0; x < buf_len; ++x) { ii[x] = crealf(cc[x]); qq[x] = cimagf(cc[x]); } //fprintf (stderr, "buf_len: %d\n", buf_len); #if 0 for (j=0; buf_len > 5 && j<5; ++j) { fprintf(stderr, "(%f + i%f)", crealf(cc[j]), cimagf(cc[j])); } fprintf (stderr, "\n"); for (j=0; buf_len > 5 && j<5; ++j) { fprintf(stderr, "(%f + i%f)", ii[j], qq[j] ); } fprintf (stderr, "\n"); #endif int rcb = pacd->udcf (ii, qq, buf_len, pacd->pUserData); if (rcb < 0) { fprintf (stderr, "SDR-IQ thread exiting with user callback returning: %d\n", rcb); pacd->run = 0; } } else if (buf_len < 0) { // user callback is asked for termination pacd->udcf ((void *)0, (void *)0, 0, 0); break; } } fprintf (stderr, "SDR-IQ thread exiting with RUN: %d\n", pacd->run); quisk_stop_sdriq (); return 0; } int sdriq_start_asynch_input (SDRIQ_CB cb, void *pud) { int rc; fprintf (stderr, "%s\n", __FUNCTION__); if (hq.pacd) free(hq.pacd); hq.pacd = malloc( sizeof(struct AsynchCtxData)); hq.pacd->pUserData = pud; hq.pacd->udcf = cb; hq.pacd->run = 1; // create the thread to receive data rc = pthread_create(&(hq.thread_id),NULL,asynch_input_thread,(void *)(hq.pacd)); if(rc < 0) { perror("pthread_create asynch_input_thread failed"); } return rc; } int sdriq_stop_asynch_input () { int rc = -1; fprintf (stderr, "%s\n", __FUNCTION__); if (hq.thread_id != 0) { void *pExit; hq.pacd->run = 0; rc = pthread_join (hq.thread_id, &pExit); } //hiqsdr_disconnect (); return rc; } #if defined __TEST_MODULE__ #include <stdio.h> #include <time.h> #include <stdlib.h> complex cSamples [SAMP_BUFFER_SIZE]; unsigned long ii [SAMP_BUFFER_SIZE]; unsigned long qq [SAMP_BUFFER_SIZE]; struct timespec diff(struct timespec start, struct timespec end) { struct timespec temp; if ((end.tv_nsec - start.tv_nsec) < 0) { temp.tv_sec = end.tv_sec - start.tv_sec - 1; temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec; } else { temp.tv_sec = end.tv_sec - start.tv_sec; temp.tv_nsec = end.tv_nsec - start.tv_nsec; } return temp; } int asynch_callback (SAMPLE_T *pi, SAMPLE_T *pq, int bsize, void *data) { int *pndp = (int *) data; if (pi && pq && *pndp) { fprintf (stderr, "%s: %d: %d\n", __FUNCTION__, *pndp, bsize); *pndp = (*pndp) - 1; if (bsize > 0) { int j; for (j=0; j<5; ++j) fprintf(stderr, "%f+j%f ", *pi++, *pq++); fprintf (stderr, "\n"); } return 0; } else return -1; } void test_multiple_sr (int dec) { int i; long int ts = 0; struct timespec time_start; struct timespec time_end; struct timespec time_diff; long double diff_s ; set_decimation (dec); quisk_start_sdriq (); fprintf(stderr, "Listening.....\n"); fflush (stderr); clock_gettime (CLOCK_REALTIME, &time_start); for (i=0; i<1000; ++i) { int j; //int n = quisk_read_sdriq (cSamples); int n = quisk_read_sdriq (cSamples); //fprintf (stderr, "**** samples[%d]: %d\n", i, n ); //fflush (stderr); ts += n; #if 0 for (j=0; n > 0 && j<20; ++j) { fprintf(stderr, "%f + %f ", creal(cSamples[j]), cimag(cSamples[j])); } #endif } clock_gettime(CLOCK_REALTIME, &time_end); time_diff = diff(time_start, time_end); diff_s = time_diff.tv_sec + (time_diff.tv_nsec/1E9) ; //fprintf(stderr, "diff: %ds::%dns %Lf seconds\n", time_diff.tv_sec, time_diff.tv_nsec, diff_s); fprintf (stderr, "Samples received: %lu, %.3Lf kS/s\n", ts, ((double)ts / (diff_s)/1E3) ); fflush (stderr); quisk_stop_sdriq (); } int main () { char buf[128]; int i, rc; #if DEBUG fprintf (stderr, "**** DEBUG ACTIVE: %d\n", DEBUG); fprintf (stderr, "short: %d int: %d long: %d\n", sizeof(short), sizeof(int), sizeof(long) ); #endif rc = open_samples("/dev/ttyUSB0", "66666667.0", buf) ; fflush (stderr); if (rc != 0) { fprintf (stderr, "**** OPEN FAILED: [%s]\n", buf ); return 255; } else fprintf (stderr, "**** OPEN SUCCESS: %s\n", buf ); fprintf (stderr, "Name: [%s] Serial: [%s] Interface: %d Firmware: %d Bootcode: %d Product Id: %08lX\n", sdr_name, sdr_serial, sdr_interface, sdr_firmware, sdr_bootcode, *((unsigned long *)sdr_product_id) ); fflush (stderr); //gain_sdriq (0, -30); gain_sdriq (1, 1); #if 1 test_multiple_sr (1250); test_multiple_sr (600); test_multiple_sr (500); test_multiple_sr (360); #else set_decimation (1250); { static int ndp = 5; fprintf (stderr, "\nAsyhchronously listening for %d data packets.....\n", ndp); sdriq_start_asynch_input (asynch_callback, (void *)&ndp); while (ndp) { sleep (1); }; sdriq_stop_asynch_input (); // necessary in order to avoid memory leaks fprintf (stderr, "...............\n"); } #endif // Stop sample capture; called from the sound thread. fflush (stderr); close_samples (); fprintf (stderr, "Errors: %d overrange: %d poll: %d\n", quisk_sound_state.read_error, quisk_sound_state.overrange, quisk_sound_state.data_poll_usec ); return 0; } #endif
w3sz/ghpsdr3-w3sz
trunk/src/sdriq/sdriq.c
C
gpl-3.0
46,368
odoo.define('board.AddToGoogleSpreadsheetMenu', function (require) { "use strict"; var ActionManager = require('web.ActionManager'); var core = require('web.core'); var data = require('web.data'); var Domain = require('web.Domain'); var favorites_submenus_registry = require('web.favorites_submenus_registry'); var pyUtils = require('web.py_utils'); var Widget = require('web.Widget'); var QWeb = core.qweb; var AddToGoogleSpreadsheetMenu = Widget.extend({ events: _.extend({}, Widget.prototype.events, { 'click .add_to_spreadsheet': '_onAddToSpreadsheetClick', }), /** * @override * @param {Object} params * @param {Object} params.action an ir.actions description */ init: function (parent, params) { this._super(parent); this.action = params.action; }, /** * @override */ start: function () { if (this.action.type === 'ir.actions.act_window') { this._render(); } return this._super.apply(this, arguments); }, //-------------------------------------------------------------------------- // Private //-------------------------------------------------------------------------- /** * @private */ _addToSpreadsheet: function () { // AAB: trigger_up an event that will be intercepted by the controller, // as soon as the controller is the parent of the control panel var actionManager = this.findAncestor(function (ancestor) { return ancestor instanceof ActionManager; }); var controller = actionManager.getCurrentController(); var searchQuery; // TO DO: for now the domains in query are evaluated. // This should be changed I think. this.trigger_up('get_search_query', { callback: function (query) { searchQuery = query; } }); var modelName = this.action.res_model; var list_view = _.findWhere(controller.widget.actionViews, {type: 'list'}); var list_view_id = list_view ? list_view.viewID : false; var domain = searchQuery.domain; var groupBys = pyUtils.eval('groupbys', searchQuery.groupBys).join(" "); var ds = new data.DataSet(this, 'google.drive.config'); ds.call('set_spreadsheet', [modelName, Domain.prototype.arrayToString(domain), groupBys, list_view_id]) .then(function (res) { if (res.url){ window.open(res.url, '_blank'); } }); }, /** * Renders the `SearchView.addtogooglespreadsheet` template. * * @private */ _render: function () { var $el = QWeb.render('SearchView.addtogooglespreadsheet', {widget: this}); this._replaceElement($el); }, //-------------------------------------------------------------------------- // Handlers //-------------------------------------------------------------------------- /** * @private * @param {jQueryEvent} event */ _onAddToSpreadsheetClick: function (event) { event.preventDefault(); event.stopPropagation(); this._addToSpreadsheet(); }, }); favorites_submenus_registry.add('add_to_google_spreadsheet_menu', AddToGoogleSpreadsheetMenu, 20); return AddToGoogleSpreadsheetMenu; });
t3dev/odoo
addons/google_spreadsheet/static/src/js/add_to_google_spreadsheet_menu.js
JavaScript
gpl-3.0
3,371
// (C) Copyright John Maddock 2001 - 2003. // (C) Copyright Jens Maurer 2001. // (C) Copyright Peter Dimov 2001. // (C) Copyright David Abrahams 2002. // (C) Copyright Guillaume Melquiond 2003. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. // Dinkumware standard library config: #if !defined(_YVALS) && !defined(_CPPLIB_VER) #include <boost/config/no_tr1/utility.hpp> #if !defined(_YVALS) && !defined(_CPPLIB_VER) #error This is not the Dinkumware lib! #endif #endif #if defined(_CPPLIB_VER) && (_CPPLIB_VER >= 306) // full dinkumware 3.06 and above // fully conforming provided the compiler supports it: # if !(defined(_GLOBAL_USING) && (_GLOBAL_USING+0 > 0)) && !defined(__BORLANDC__) && !defined(_STD) && !(defined(__ICC) && (__ICC >= 700)) // can be defined in yvals.h # define BOOST_NO_STDC_NAMESPACE # endif # if !(defined(_HAS_MEMBER_TEMPLATES_REBIND) && (_HAS_MEMBER_TEMPLATES_REBIND+0 > 0)) && !(defined(_MSC_VER) && (_MSC_VER > 1300)) && defined(BOOST_MSVC) # define BOOST_NO_STD_ALLOCATOR # endif # define BOOST_HAS_PARTIAL_STD_ALLOCATOR # if defined(BOOST_MSVC) && (BOOST_MSVC < 1300) // if this lib version is set up for vc6 then there is no std::use_facet: # define BOOST_NO_STD_USE_FACET # define BOOST_HAS_TWO_ARG_USE_FACET // C lib functions aren't in namespace std either: # define BOOST_NO_STDC_NAMESPACE // and nor is <exception> # define BOOST_NO_EXCEPTION_STD_NAMESPACE # endif // There's no numeric_limits<long long> support unless _LONGLONG is defined: # if !defined(_LONGLONG) && (_CPPLIB_VER <= 310) # define BOOST_NO_MS_INT64_NUMERIC_LIMITS # endif // 3.06 appears to have (non-sgi versions of) <hash_set> & <hash_map>, // and no <slist> at all #else # define BOOST_MSVC_STD_ITERATOR 1 # define BOOST_NO_STD_ITERATOR # define BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS # define BOOST_NO_STD_ALLOCATOR # define BOOST_NO_STDC_NAMESPACE # define BOOST_NO_STD_USE_FACET # define BOOST_NO_STD_OUTPUT_ITERATOR_ASSIGN # define BOOST_HAS_MACRO_USE_FACET # ifndef _CPPLIB_VER // Updated Dinkum library defines this, and provides // its own min and max definitions, as does MTA version. # ifndef __MTA__ # define BOOST_NO_STD_MIN_MAX # endif # define BOOST_NO_MS_INT64_NUMERIC_LIMITS # endif #endif // // std extension namespace is stdext for vc7.1 and later, // the same applies to other compilers that sit on top // of vc7.1 (Intel and Comeau): // #if defined(_MSC_VER) && (_MSC_VER >= 1310) && !defined(__BORLANDC__) # define BOOST_STD_EXTENSION_NAMESPACE stdext #endif #if (defined(_MSC_VER) && (_MSC_VER <= 1300) && !defined(__BORLANDC__)) || !defined(_CPPLIB_VER) || (_CPPLIB_VER < 306) // if we're using a dinkum lib that's // been configured for VC6/7 then there is // no iterator traits (true even for icl) # define BOOST_NO_STD_ITERATOR_TRAITS #endif #if defined(__ICL) && (__ICL < 800) && defined(_CPPLIB_VER) && (_CPPLIB_VER <= 310) // Intel C++ chokes over any non-trivial use of <locale> // this may be an overly restrictive define, but regex fails without it: # define BOOST_NO_STD_LOCALE #endif #include <typeinfo> #if ( (!_HAS_EXCEPTIONS && !defined(__ghs__)) || (!_HAS_NAMESPACE && defined(__ghs__)) ) # define BOOST_NO_STD_TYPEINFO #endif // C++0x headers implemented in 520 (as shipped by Microsoft) // #if !defined(_CPPLIB_VER) || _CPPLIB_VER < 520 # define BOOST_NO_0X_HDR_ARRAY # define BOOST_NO_0X_HDR_CODECVT # define BOOST_NO_0X_HDR_FORWARD_LIST # define BOOST_NO_0X_HDR_INITIALIZER_LIST # define BOOST_NO_0X_HDR_RANDOM # define BOOST_NO_0X_HDR_REGEX # define BOOST_NO_0X_HDR_SYSTEM_ERROR # define BOOST_NO_STD_UNORDERED // deprecated; see following # define BOOST_NO_0X_HDR_UNORDERED_MAP # define BOOST_NO_0X_HDR_UNORDERED_SET # define BOOST_NO_0X_HDR_TUPLE # define BOOST_NO_0X_HDR_TYPEINDEX # define BOOST_NO_NUMERIC_LIMITS_LOWEST #endif #if !defined(_HAS_TR1_IMPORTS) && !defined(BOOST_NO_0X_HDR_TUPLE) # define BOOST_NO_0X_HDR_TUPLE #endif // // C++0x headers not yet (fully) implemented: // # define BOOST_NO_0X_HDR_TYPE_TRAITS # define BOOST_NO_0X_HDR_CHRONO # define BOOST_NO_0X_HDR_CONDITION_VARIABLE # define BOOST_NO_0X_HDR_FUTURE # define BOOST_NO_0X_HDR_MUTEX # define BOOST_NO_0X_HDR_RATIO # define BOOST_NO_0X_HDR_THREAD #ifdef _CPPLIB_VER # define BOOST_DINKUMWARE_STDLIB _CPPLIB_VER #else # define BOOST_DINKUMWARE_STDLIB 1 #endif #ifdef _CPPLIB_VER # define BOOST_STDLIB "Dinkumware standard library version " BOOST_STRINGIZE(_CPPLIB_VER) #else # define BOOST_STDLIB "Dinkumware standard library version 1.x" #endif
beiko-lab/gengis
win32/library3rd/boost_1_47/boost/config/stdlib/dinkumware.hpp
C++
gpl-3.0
5,008
<?php // phpcs:ignoreFile -- compatibility library for PHP 5-7.1 if (class_exists('ParagonIE_Sodium_Core_ChaCha20_Ctx', false)) { return; } /** * Class ParagonIE_Sodium_Core32_ChaCha20_Ctx */ class ParagonIE_Sodium_Core32_ChaCha20_Ctx extends ParagonIE_Sodium_Core32_Util implements ArrayAccess { /** * @var SplFixedArray internally, <int, ParagonIE_Sodium_Core32_Int32> */ protected $container; /** * ParagonIE_Sodium_Core_ChaCha20_Ctx constructor. * * @internal You should not use this directly from another application * * @param string $key ChaCha20 key. * @param string $iv Initialization Vector (a.k.a. nonce). * @param string $counter The initial counter value. * Defaults to 8 0x00 bytes. * @throws InvalidArgumentException * @throws SodiumException * @throws TypeError */ public function __construct($key = '', $iv = '', $counter = '') { if (self::strlen($key) !== 32) { throw new InvalidArgumentException('ChaCha20 expects a 256-bit key.'); } if (self::strlen($iv) !== 8) { throw new InvalidArgumentException('ChaCha20 expects a 64-bit nonce.'); } $this->container = new SplFixedArray(16); /* "expand 32-byte k" as per ChaCha20 spec */ $this->container[0] = new ParagonIE_Sodium_Core32_Int32(array(0x6170, 0x7865)); $this->container[1] = new ParagonIE_Sodium_Core32_Int32(array(0x3320, 0x646e)); $this->container[2] = new ParagonIE_Sodium_Core32_Int32(array(0x7962, 0x2d32)); $this->container[3] = new ParagonIE_Sodium_Core32_Int32(array(0x6b20, 0x6574)); $this->container[4] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 0, 4)); $this->container[5] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 4, 4)); $this->container[6] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 8, 4)); $this->container[7] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 12, 4)); $this->container[8] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 16, 4)); $this->container[9] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 20, 4)); $this->container[10] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 24, 4)); $this->container[11] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($key, 28, 4)); if (empty($counter)) { $this->container[12] = new ParagonIE_Sodium_Core32_Int32(); $this->container[13] = new ParagonIE_Sodium_Core32_Int32(); } else { $this->container[12] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($counter, 0, 4)); $this->container[13] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($counter, 4, 4)); } $this->container[14] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($iv, 0, 4)); $this->container[15] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($iv, 4, 4)); } /** * @internal You should not use this directly from another application * * @param int $offset * @param int|ParagonIE_Sodium_Core32_Int32 $value * @return void */ public function offsetSet($offset, $value) { if (!is_int($offset)) { throw new InvalidArgumentException('Expected an integer'); } if ($value instanceof ParagonIE_Sodium_Core32_Int32) { /* } elseif (is_int($value)) { $value = ParagonIE_Sodium_Core32_Int32::fromInt($value); */ } else { throw new InvalidArgumentException('Expected an integer'); } $this->container[$offset] = $value; } /** * @internal You should not use this directly from another application * * @param int $offset * @return bool * @psalm-suppress MixedArrayOffset */ public function offsetExists($offset) { return isset($this->container[$offset]); } /** * @internal You should not use this directly from another application * * @param int $offset * @return void * @psalm-suppress MixedArrayOffset */ public function offsetUnset($offset) { unset($this->container[$offset]); } /** * @internal You should not use this directly from another application * * @param int $offset * @return mixed|null * @psalm-suppress MixedArrayOffset */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } }
Redcolaborar/Red-Colaborar
wp-content/plugins/wordfence/crypto/vendor/paragonie/sodium_compat/src/Core32/ChaCha20/Ctx.php
PHP
gpl-3.0
4,851
=pod =head1 NAME Locale::Codes::Country - standard codes for country identification =head1 SYNOPSIS use Locale::Codes::Country; $country = code2country('jp' [,CODESET]); # $country gets 'Japan' $code = country2code('Norway' [,CODESET]); # $code gets 'no' @codes = all_country_codes( [CODESET]); @names = all_country_names(); # semi-private routines Locale::Codes::Country::rename_country('gb' => 'Great Britain'); =head1 DESCRIPTION This module provides access to several code sets that can be used for identifying countries, such as those defined in ISO 3166-1. Most of the routines take an optional additional argument which specifies the code set to use. If not specified, the default ISO 3166-1 two-letter codes will be used. =head1 SUPPORTED CODE SETS There are several different code sets you can use for identifying countries. A code set may be specified using either a name, or a constant that is automatically exported by this module. For example, the two are equivalent: $country = code2country('jp','alpha-2'); $country = code2country('jp',LOCALE_CODE_ALPHA_2); The codesets currently supported are: =over 4 =item B<alpha-2, LOCALE_CODE_ALPHA_2> This is the set of two-letter (lowercase) codes from ISO 3166-1, such as 'tv' for Tuvalu. This is the default code set. =item B<alpha-3, LOCALE_CODE_ALPHA_3> This is the set of three-letter (lowercase) codes from ISO 3166-1, such as 'brb' for Barbados. These codes are actually defined and maintained by the U.N. Statistics division. =item B<numeric, LOCALE_CODE_NUMERIC> This is the set of three-digit numeric codes from ISO 3166-1, such as 064 for Bhutan. These codes are actually defined and maintained by the U.N. Statistics division. If a 2-digit code is entered, it is converted to 3 digits by prepending a 0. =item B<dom, LOCALE_CODE_DOM> The IANA is responsible for delegating management of the top level country domains. The country domains are the two-letter (lowercase) codes from ISO 3166 with a few other additions. =item B<un-alpha-3, LOCALE_CODE_UN_ALPHA_3> =item B<un-numeric, LOCALE_CODE_UN_NUMERIC> The UN maintains a list of codes that is similar, but not identical, to the standard ISO 3166 lists. They maintain a 3-letter code (similar to alpha-3) and a numeric code (similar to numeric). =item B<genc-alpha-2, LOCALE_CODE_GENC_ALPHA_2> =item B<genc-alpha-3, LOCALE_CODE_GENC_ALPHA_3> =item B<genc-numeric, LOCALE_CODE_GENC_NUMERIC> The GENC codes are the US Government codes that replace the FIPS-11 codes. They are based on, but not identical to the standard ISO 3166 lists. =back NOTE: As of version 3.27, the FIPS code set is no longer supported. See the Locale::Codes::Changes document for details. =head1 ROUTINES =over 4 =item B<code2country(CODE [,CODESET] [,'retired'])> =item B<country2code(NAME [,CODESET] [,'retired'])> =item B<country_code2code(CODE ,CODESET ,CODESET2)> =item B<all_country_codes([CODESET] [,'retired'])> =item B<all_country_names([CODESET] [,'retired'])> =item B<Locale::Codes::Country::rename_country(CODE ,NEW_NAME [,CODESET])> =item B<Locale::Codes::Country::add_country(CODE ,NAME [,CODESET])> =item B<Locale::Codes::Country::delete_country(CODE [,CODESET])> =item B<Locale::Codes::Country::add_country_alias(NAME ,NEW_NAME)> =item B<Locale::Codes::Country::delete_country_alias(NAME)> =item B<Locale::Codes::Country::rename_country_code(CODE ,NEW_CODE [,CODESET])> =item B<Locale::Codes::Country::add_country_code_alias(CODE ,NEW_CODE [,CODESET])> =item B<Locale::Codes::Country::delete_country_code_alias(CODE [,CODESET])> These routines are all documented in the L<Locale::Codes::API> man page. =back =head1 SEE ALSO =over 4 =item L<Locale::Codes> The Locale-Codes distribution. =item L<Locale::Codes::API> The list of functions supported by this module. =item L<Locale::SubCountry> ISO codes for country sub-divisions (states, counties, provinces, etc), as defined in ISO 3166-2. This module is not part of the Locale-Codes distribution, but is available from CPAN in CPAN/modules/by-module/Locale/ =item L<http://www.iso.org/iso/home/standards/country_codes.htm> Official home page for the ISO 3166 maintenance agency. =item L<http://www.iso.org/iso/home/standards/country_codes/iso-3166-1_decoding_table.htm> The source of ISO 3166-1 two-letter codes used by this module. =item L<http://www.iana.org/domains/root/db/> Official source of the top-level domain names. =item L<http://unstats.un.org/unsd/methods/m49/m49alpha.htm> The source of the UN codes. Previously, this table was treated as a source of the ISO 3166 data, but I found that the table was incomplete, so I stopped using it. Later, it was added back in as it's own list of codes. =item L<https://nsgreg.nga.mil/genc/discovery> The source of the GENC codes. =item L<https://www.cia.gov/library/publications/the-world-factbook/appendix/print_appendix-d.html> The World Factbook maintained by the CIA is a potential source of the data. Unfortunately, it adds/preserves non-standard codes, so it is no longer used as a source of data. =item L<http://www.statoids.com/wab.html> Another unofficial source of data. Currently, it is not used to get data, but the notes and explanatory material were very useful for understanding discrepancies between the sources. =back =head1 AUTHOR See Locale::Codes for full author history. Currently maintained by Sullivan Beck (sbeck@cpan.org). =head1 COPYRIGHT Copyright (c) 1997-2001 Canon Research Centre Europe (CRE). Copyright (c) 2001-2010 Neil Bowers Copyright (c) 2010-2016 Sullivan Beck This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
mgood7123/UPM
perl-5.26.1/perl5.26.1/lib/5.26.1/Locale/Codes/Country.pod
Perl
gpl-3.0
5,763
// License: GPL. For details, see LICENSE file. package org.openstreetmap.josm.gui.preferences; public interface PreferenceSettingFactory { PreferenceSetting createPreferenceSetting(); }
CURocketry/Ground_Station_GUI
src/org/openstreetmap/josm/gui/preferences/PreferenceSettingFactory.java
Java
gpl-3.0
194
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="GENERATOR" content="UltraEdit-32"> <title>Eternity Engine Small Usage Documentation</title> </head> <body bgcolor="#CECECE"> <hr> <b>Eternity Engine Small Usage Documentation v1.1 -- 06/09/05</b> <hr> <br> <a href="../etcengine.html">Return to the Eternity Engine Page</a> <ul> <li><a name="contents"><b>Table of Contents</b></a> <ul> <li><a href="#intro">Introduction</a> <li><a href="#vms">VMs: Gamescript and Levelscript</a> <ul> <li><a href="#gamescript">The Gamescript</a> <ul> <li><a href="#addinggs">Adding a Gamescript</a> <li><a href="#invokegs">Invoking Gamescripts</a> <li><a href="#gamevars">Using Gamescript Variables</a> </ul> <li><a href="#levelscript">The Levelscript</a> <ul> <li><a href="#addingls">Adding a Levelscript</a> <li><a href="#invokels">Invoking Levelscripts</a> <li><a href="#levelvars">Using Levelscript Variables</a> </ul> </ul> <li><a href="#saves">Savegame Semantics</a> <ul> <li><a href="#OnInit">The OnInit Function</a> <li><a href="#saveglobals">Global Variables</a> <li><a href="#localstatics">Static Local Variables</a> <li><a href="#callbacks">Callbacks</a> <li><a href="#loaderrors">Load Errors</a> </ul> <li><a href="#events">System-Defined Event Handlers</a> <ul> <li><a href="#eventOnInit">OnInit</a> <li><a href="#eventOnHUDStart">OnHUDStart</a> <li><a href="#eventOnHUDPreDraw">OnHUDPreDraw</a> </ul> <li><a href="#headers">Eternity Small Headers</a> <li><a href="#reserved">Reserved Identifiers</a> </ul> </ul> <p> <a name="intro"> <hr> <b>Introduction</b> <hr> </a> <br> This documentation covers how the Small scripting system is implemented in the Eternity Engine and how it can be used. This is not a general reference or tutorial for the Small scripting language; see the other documentation on the Eternity Engine webpage for more information. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="vms"> <hr> <b>VMs: Gamescript and Levelscript</b> <hr> </a> <br> The Eternity Engine contains two Small virtual machines, known as the Gamescript and Levelscript. Both of these and the ways in which they can interact are explained in the subsections below. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="gamescript"> <hr align="left" width="75%"> <b>The Gamescript</b> <hr align="left" width="75%"> </a> <br> The Gamescript is an optional set of global scripts which can be invoked at any time during execution. These scripts are shared between levels, and as such, this VM can act as "glue" to connect the scripts of individual maps. Levelscripts are not required for a Gamescript to be loaded. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="addinggs"> <hr align="left" width="50%"> <b>Adding a Gamescript</b> <hr align="left" width="50%"> </a> <br> The Gamescript is a normally compiled Small AMX file inserted into the GAMESCR lump in any wad. Only the last such GAMESCR lump will be loaded, and the functions and variables inside it will become available. The Gamescript area is initialized at startup, and if it contains an OnInit() function, that function will be executed once and only once when the "A_InitGameScript" message appears in the console. The OnInit() function is optional, and if it does not exist, no error will occur. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="invokegs"> <hr align="left" width="50%"> <b>Invoking Gamescripts</b> <hr align="left" width="50%"> </a> <br> Here are the various ways Gamescript public functions (aka scripts) may be invoked: <ul> <li> Console Commands <br><br> The a_execv and a_execi console commands can run public Small functions which take either no parameters, or any number of integer parameters respectively. By passing the second parameter ("vm") as the number 0, you will indicate to look for the named function in the Gamescript VM. If the named function does not exist in the Gamescript, an error message will be printed. See the <a href="console_ref.html">Eternity Engine Console Reference</a> for full information. <br><br> <li> Cross-VM Execution <br><br> Using the Small function <a href="small_funcref.html#_ExecGS">_ExecGS</a>, it is possible to execute Gamescript functions by name from any function in the Levelscript. If the Gamescript is not loaded or _ExecGS is called from within the Gamescript itself, the current script will be aborted and an error message will appear in the console. <br><br> <li> Registering Callbacks <br><br> Callbacks may be registered from OnInit or from any other Gamescript function which may then repeatedly call Gamescript functions under the _INVOKE_CALLBACK invocation model. See the <a href="small_funcref.html#_SetCallback">_SetCallback</a> function for full information. Gamescript callbacks can run at any point during the game, so it is important to monitor the current game mode if using functions which can only be used during levels, etc. If a function is called at an inappropriate time, the callback will be aborted with an "Invalid gamemode for native function" error. <br><br> <li> EDF/BEX Codepointers <br><br> The StartScript and PlayerStartScript codepointers may both execute Gamescripts by number. Only public functions which are named in the fashion "Script#", where # is any positive integer value, and accept 3 integer parameters can be invoked using these codepointers. The numeric value used in the function name is passed to the codepointer as an argument (via the EDF/BEX args frame values). Use the number 0 as the second parameter to either of these codepointers to indicate the Gamescript as the target VM. If the Gamescript is not loaded in this case, the codepointer will perform no action. See the <a href="codeptrs.html">Eternity Engine Definitive Codepointer Reference</a> for full information. <br><br> Warning: If StartScript or PlayerStartScript are called from frames into which an object is set by other scripts, or they call a script which may change the object's state, any new script started will be executed recursively. This means that the second script will be executing before the first has finished. Be sure to carefully account for this in your scripting logic, and do not erroneously assume that any other script must have finished executing before the one that is currently running, or that other scripts will not execute before the current script has finished. </ul> <a href="#contents">Return to Table of Contents</a> <p> <a name="gamevars"> <hr align="left" width="50%"> <b>Using Gamescript Variables</b> <hr align="left" width="50%"> </a> <br> Like any compiled Small program, the Gamescript may contain scalar global variables declared as "public." These variables, aside from being normally accessable from any function within the Gamescript, can also be accessed from outside by using the <a href="small_funcref.html#_GetGameVar">_GetGameVar</a> and <a href="small_funcref.html#_SetGameVar">_SetGameVar</a> functions. Using these functions in your Levelscripts can allow maps to affect each other, by having one map set a variable in the Gamescript, and then having another one check it. This is analogous to game and hub variables in ACS and FraggleScript. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="levelscript"> <hr align="left" width="75%"> <b>The Levelscript</b> <hr align="left" width="75%"> </a> <br> The Levelscript is an optional set of map-local scripts which can be invoked only while the map which owns those scripts is being played. A Gamescript is not required for Levelscripts to be loaded. Levelscripts cannot access the scripts of other levels, but they can access public functions and variables of the Gamescript, and the Gamescript can access public functions and variables of the currently loaded Levelscript. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="addingls"> <hr align="left" width="50%"> <b>Adding a Levelscript</b> <hr align="left" width="50%"> </a> <br> The Levelscript is a normally compiled Small AMX file inserted into any lump. The lump must be attached to the map using <a href="mapinfo.html">MapInfo</a>. The "levelscript" value for the map must be set to the name of the lump containing the compiled scripts for that level. The Levelscript area is initialized during level setup, and if the currently loaded Levelscript contains an OnInit() function, that function will be executed once and only once, provided a save game is not being loaded. The OnInit() function is optional, and if it does not exist, no error will occur. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="invokels"> <hr align="left" width="50%"> <b>Invoking Levelscripts</b> <hr align="left" width="50%"> </a> <br> Here are the various ways Levelscript public functions (aka scripts) may be invoked: <ul> <li> Console Commands <br><br> The a_execv and a_execi console commands can run public Small functions which take either no parameters, or any number of integer parameters respectively. By passing the second parameter ("vm") as the number 1, you will indicate to look for the named function in the Levelscript VM. If the named function does not exist in the Levelscript, an error message will be printed. See the <a href="console_ref.html">Eternity Engine Console Reference</a> for full information. <br><br> <li> Cross-VM Execution <br><br> Using the Small function <a href="small_funcref.html#_ExecLS">_ExecLS</a>, it is possible to execute Levelscript functions by name from any function in the Gamescript. If the Levelscript is not loaded or ExecLS is called from within the Levelscript, the current script will be aborted and an error message will appear in the console. Note that ExecLS can only call functions in the current level's Levelscript. State may be transferred between levels using public Gamescript global variables. <br><br> <li> Registering Callbacks <br><br> Callbacks may be registered from OnInit or from any other Levelscript function which may then repeatedly call Levelscript functions under the _INVOKE_CALLBACK invocation model. See the <a href="small_funcref.html#_SetCallback">_SetCallback</a> function for full information. Levelscript callbacks can only run during gameplay on that map, and any scheduled Levelscript callbacks will be killed immediately any time a level is exited in any manner. <br><br> <li> EDF/BEX Codepointers <br><br> The StartScript and PlayerStartScript codepointers may both execute Levelscripts by number. Only public functions which are named in the fashion "Script#", where # is any positive integer value, and accept 3 integer parameters can be invoked using these codepointers. The numeric value used in the function name is passed to the codepointer as an argument (via the EDF/BEX args frame values). Use the number 1 as the second parameter to either of these codepointers to indicate the Levelscript as the target VM. If the Levelscript is not loaded in this case, the codepointer will perform no action. See the <a href="codeptrs.html">Eternity Engine Definitive Codepointer Reference</a> for full information. <br><br> Warning: If StartScript or PlayerStartScript are called from frames into which an object is set by other scripts, or they call a script which may change the object's state, any new script started will be executed recursively. This means that the second script will be executing before the first has finished. Be sure to carefully account for this in your scripting logic, and do not erroneously assume that any other script must have finished executing before the one that is currently running, or that other scripts will not execute before the current script has finished. <br><br> <li> Script Linedefs <br><br> Levelscripts may also be executed by number using the same naming convention for the StartScript codepointers, but accepting zero parameters and using the tag of the line as the script number, with one of the following specials: <ul> <li> 280: WR Start Script From Tag Number <li> 273: WR Start Script From Tag Number 1-Way (activates from first side only) <li> 274: W1 Start Script From Tag Number <li> 275: W1 Start Script From Tag Number 1-Way (activates from first side only) <li> 276: SR Start Script From Tag Number <li> 277: S1 Start Script From Tag Number <li> 278: GR Start Script From Tag Number <li> 279: G1 Start Script From Tag Number </ul> </ul> <a href="#contents">Return to Table of Contents</a> <p> <a name="levelvars"> <hr align="left" width="50%"> <b>Using Levelscript Variables</b> <hr align="left" width="50%"> </a> <br> Like any compiled Small program, the Levelscript may contain scalar global variables declared as "public." These variables, aside from being normally accessable from any function within the Levelscript, can also be accessed from outside by using the <a href="small_funcref.html#_GetLevelVar">_GetLevelVar</a> and <a href="small_funcref.html#_SetLevelVar">_SetLevelVar</a> functions. Using these functions in your Gamescripts can allow the Gamescript to perform similar actions on many levels. Note that if a variable is not defined in a particular Levelscript, the Gamescript executing _GetLevelVar or _SetLevelVar will abort with an error message. The variable must be defined in each Levelscript in which the Gamescript may attempt to access it. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="saves"> <hr> <b>Savegame Semantics</b> <hr> </a> <br> The following subsections contain information on how the Small system behaves when the game is saved or loaded. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="OnInit"> <hr align="left" width="75%"> <b>The OnInit Function</b> <hr align="left" width="75%"> </a> <br> In the Gamescript, the OnInit function is executed only once at program startup, and therefore this is not affected by saving or loading games. When a game is loaded, it can be assumed that the Gamescript OnInit function has already been executed. <br><br> In the Levelscript, the OnInit function is executed each time the level is loaded from scratch. However, if the level is being initialized during savegame loading, the OnInit function will NOT be executed, as it is expected that the program state created by it was preserved in the savegame. Executing it again in that case could create duplicate objects, show unnecessary messages, etc. Be sure that your OnInit function's changes to the map are saveable or are not necessary to be repeated after loading a saved game. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="saveglobals"> <hr align="left" width="75%"> <b>Global Variables</b> <hr align="left" width="75%"> </a> <br> Global variables declared in both VMs, public or private, will have their values saved in save games. This means that when a normal game loading action takes place, the values of global variables in both VMs will instantly change to reflect the state that was in place at the time of the save. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="localstatics"> <hr align="left" width="75%"> <b>Static Local Variables</b> <hr align="left" width="75%"> </a> <br> Static local variables are variables declared inside functions using the <b>static</b> keyword as opposed to the <b>new</b> keyword. As mentioned in the Small language documentation, static local variables, unlike normal local variables, retain their values between calls to the function in which they are declared. Because static locals are really just limited-scope globals, they are treated the same way, and their values will be saved in savegames. When a normal game loading action takes place, the values of all static local variables in both VMs will instantly change to reflect the state that was in place at the time of the save. <br><br> Normal local variables are the only storage class of variable that is not archived in save games. In addition, the status of the Small stack and heap are also not currently saved, since Eternity does not allow script execution to be interrupted by a save game under any circumstance. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="callbacks"> <hr align="left" width="75%"> <b>Callbacks</b> <hr align="left" width="75%"> </a> <br> Callbacks currently scheduled for either VM will be saved in save games. At the time of a normal load action, any existing callbacks in either VM will be instantly destroyed and will be replaced with the callbacks which were scheduled at the time of the save. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="loaderrors"> <hr align="left" width="75%"> <b>Load Errors</b> <hr align="left" width="75%"> </a> <br> The following fatal errors may occur while loading a savegame which contains script data under the given circumstances. Eternity will currently exit if these errors occur. <ul> <li> "P_UnArchiveScripts: vm presence inconsistency" <br><br> The presence of the Gamescript and/or Levelscript has changed since the time of the savegame. If a Gamescript or Levelscript is removed from a WAD, but a savegame containing its archived image is subsequently loaded, this error will occur. This error will also occur if a Gamescript or Levelscript has been added to a WAD and there is no archived image of it in the savegame. <br><br> <li> "P_UnArchiveSmallAMX: data segment consistency error" <br><br> The size of one or both Small AMX data segments has changed since the time of the savegame. This can only occur if a Small script has been recompiled. You cannot reload savegames if any of the involved scripts have been recompiled. </ul> <a href="#contents">Return to Table of Contents</a> <p> <a name="events"> <hr> <b>System-Defined Event Handlers</b> <hr> </a> <br> Complete documentation of all system-defined event handlers is below. System-defined event handlers are optional functions that you can provide in your script that will be started as callback scripts by the game engine in response to internal events. If the functions do not exist, no calls will be issued. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="eventOnInit"> <hr align="left" width="75%"> <b>OnInit</b> <hr align="left" width="75%"> </a> <br> Required Prototype: public OnInit();<br> Can Be Defined In: Gamescript, Levelscript <br><br> The OnInit function is called when its corresponding virtual machine is initialized. For the Gamescript, the OnInit function is executed only once at program startup. In the Levelscript, the OnInit function is executed each time the level is loaded from scratch, NOT including when a savegame is being loaded. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="eventOnHUDStart"> <hr align="left" width="75%"> <b>OnHUDStart</b> <hr align="left" width="75%"> </a> <br> Required Prototype: public OnHUDStart();<br> Can Be Defined In: Gamescript, Levelscript <br><br> OnHUDStart will be called first in the Gamescript and then in the Levelscript, if defined in either or both. It is called whenever a new level is started, or when the player being displayed by the game engine changes. Because text widgets are cleared by default, you may want to set new values to them in this function. You may also use it to maintain the internal state of your scripts with respect to the HUD. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="eventOnHUDPreDraw"> <hr align="left" width="75%"> <b>OnHUDPreDraw</b> <hr align="left" width="75%"> </a> <br> Required Prototype: public OnHUDPreDraw();<br> Can Be Defined In: Gamescript, Levelscript <br><br> OnHUDPreDraw will be called first in the Gamescript and then in the Levelscript, if defined in either or both. It is called once per frame after HUD widgets from the previous frame have been erased, but before drawing of widgets for the current frame has begun. This is the safest time to alter the properties of HUD widgets. Altering properties such as location or graphic being shown at any other time may result in visual artifacts. Call functions such as <a href="small_funcref.html#_MoveWidget">_MoveWidget</a> from this event handler. <br><br> <a href="#contents">Return to Table of Contents</a> <p> <a name="headers"> <hr> <b>Eternity Small Headers</b> <hr> </a> <br> This section lists the standard headers provided with the Eternity Small compiler distribution. These headers will be automatically included by the compiler, and so it is not necessary (although not an error) to include them explicitly. <br><br> <ul> <li> default.inc : This header includes core.inc and common.inc, and is automatically included by the Small compiler when running with the default parameters. <br><br> <li> core.inc : This header is provided by the Small AMX library. It includes prototypes for all of the suggested core Small functions, but be aware that many of these are not currently supported for use under the Eternity Engine. Only those functions listed in the <a href="small_funcref.html">Eternity Small Function Reference</a> may be used safely and compatibly. <br><br> <li> common.inc : This header includes all of the standard Eternity Engine headers below. <br><br> <li> cameras.inc : Contains function prototypes and constants dealing with game cameras. <br><br> <li> fixed.inc : Contains function prototypes, stock functions, overloaded operators, and constants dealing with fixed-point math. <br><br> <li> game.inc : Contains function prototypes and constants for manipulating game play. <br><br> <li> hud.inc : Contains function prototypes and constants for manipulating the heads-up display system. <br><br> <li> invoke.inc : Contains function prototypes and constants related to invocation models, starting scripts, scheduling callbacks, and external access to public variables. <br><br> <li> io.inc : Contains function prototypes and constants for player input and output. <br><br> <li> random.inc : Contains function prototypes for the DOOM RNG interface. <br><br> <li> sound.inc : Contains function prototypes and constants for sound and music functions. <br><br> <li> specials.inc : Contains function prototypes and constants for manipulating all aspects of a map, including lines and sectors. <br><br> <li> things.inc : Contains function prototypes and constants for manipulating all aspects of moving objects, including monsters, decorations, and player avatars. </ul> <a href="#contents">Return to Table of Contents</a> <p> <a name="reserved"> <hr> <b>Reserved Identifiers</b> <hr> </a> <br> The following function, definition, and constant names are explicitly reserved by the Eternity Engine and should not be used by user script functions or constants. Doing so may cause your scripts to not compile with future versions of the engine. <br> Note: The syntax [&lt;character class&gt;]* means zero or more of the characters within the class indicated inside the brackets. Programmers should recognize this syntax as a regular expression. <br><br> <ul> <li> On[A-Za-z0-9_]* : Reserved for system-defined event handlers. <li> _[A-Za-z0-9_]* : Reserved for system-defined identifiers (ie., native functions). </ul> <a href="#contents">Return to Table of Contents</a> </body> </html>
fragglet/autodoom
docs/small_usagedoc.html
HTML
gpl-3.0
24,331
--------------------------------------------------- -- Double Punch M=6, 2 (still guessing here) --------------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); require("/scripts/globals/summon"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onPetAbility(target, pet, skill) local numhits = 2; local accmod = 1; local dmgmod = 6; local dmgmodsubsequent = 2; local totaldamage = 0; local damage = AvatarPhysicalMove(pet,target,skill,numhits,accmod,dmgmod,dmgmodsubsequent,TP_NO_EFFECT,1,2,3); totaldamage = AvatarFinalAdjustments(damage.dmg,pet,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,numhits); target:delHP(totaldamage); target:updateEnmityFromDamage(pet,totaldamage); return totaldamage; end
xdemolish/darkstar
scripts/globals/abilities/pets/double_punch.lua
Lua
gpl-3.0
934
var CouchPotato = new Class({ Implements: [Events, Options], defaults: { page: 'home', action: 'index', params: {} }, pages: [], block: [], initialize: function(){ var self = this; self.global_events = {}; }, setup: function(options) { var self = this; self.setOptions(options); self.c = $(document.body); self.route = new Route(self.defaults); self.createLayout(); self.createPages(); if(window.location.hash) History.handleInitialState(); else self.openPage(window.location.pathname); History.addEvent('change', self.openPage.bind(self)); self.c.addEvent('click:relay(a[href^=/]:not([target]))', self.pushState.bind(self)); self.c.addEvent('click:relay(a[href^=http])', self.openDerefered.bind(self)); // Check if device is touchenabled self.touch_device = 'ontouchstart' in window || navigator.msMaxTouchPoints; if(self.touch_device) self.c.addClass('touch_enabled'); }, getOption: function(name){ try { return this.options[name]; } catch(e){ return null } }, pushState: function(e){ if((!e.meta && Browser.Platform.mac) || (!e.control && !Browser.Platform.mac)){ (e).preventDefault(); var url = e.target.get('href'); if(History.getPath() != url) History.push(url); } }, isMac: function(){ return Browser.Platform.mac }, createLayout: function(){ var self = this; self.block.header = new Block(); self.c.adopt( $(self.block.header).addClass('header').adopt( new Element('div').adopt( self.block.navigation = new Block.Navigation(self, {}), self.block.search = new Block.Search(self, {}), self.block.more = new Block.Menu(self, {'button_class': 'icon2.cog'}) ) ), self.content = new Element('div.content'), self.block.footer = new Block.Footer(self, {}) ); var setting_links = [ new Element('a', { 'text': 'About CouchPotato', 'href': App.createUrl('settings/about') }), new Element('a', { 'text': 'Check for Updates', 'events': { 'click': self.checkForUpdate.bind(self, null) } }), new Element('span.separator'), new Element('a', { 'text': 'Settings', 'href': App.createUrl('settings/general') }), new Element('a', { 'text': 'Logs', 'href': App.createUrl('log') }), new Element('span.separator'), new Element('a', { 'text': 'Restart', 'events': { 'click': self.restartQA.bind(self) } }), new Element('a', { 'text': 'Shutdown', 'events': { 'click': self.shutdownQA.bind(self) } }) ]; setting_links.each(function(a){ self.block.more.addLink(a) }); new ScrollSpy({ min: 10, onLeave: function(){ $(self.block.header).removeClass('with_shadow') }, onEnter: function(){ $(self.block.header).addClass('with_shadow') } }) }, createPages: function(){ var self = this; Object.each(Page, function(page_class, class_name){ var pg = new Page[class_name](self, {}); self.pages[class_name] = pg; $(pg).inject(self.content); }); self.fireEvent('load'); }, openPage: function(url) { var self = this; self.route.parse(); var page_name = self.route.getPage().capitalize(); var action = self.route.getAction(); var params = self.route.getParams(); var current_url = self.route.getCurrentUrl(); if(current_url == self.current_url) return; if(self.current_page) self.current_page.hide(); try { var page = self.pages[page_name] || self.pages.Home; page.open(action, params, current_url); page.show(); } catch(e){ console.error("Can't open page:" + url, e) } self.current_page = page; self.current_url = current_url; }, getBlock: function(block_name){ return this.block[block_name] }, getPage: function(name){ return this.pages[name] }, shutdown: function(){ var self = this; self.blockPage('You have shutdown. This is what is supposed to happen ;)'); Api.request('app.shutdown', { 'onComplete': self.blockPage.bind(self) }); self.checkAvailable(1000); }, shutdownQA: function(){ var self = this; var q = new Question('Are you sure you want to shutdown CouchPotato?', '', [{ 'text': 'Shutdown', 'class': 'shutdown red', 'events': { 'click': function(e){ (e).preventDefault(); self.shutdown(); q.close.delay(100, q); } } }, { 'text': 'No, nevah!', 'cancel': true }]); }, restart: function(message, title){ var self = this; self.blockPage(message || 'Restarting... please wait. If this takes too long, something must have gone wrong.', title); Api.request('app.restart'); self.checkAvailable(1000); }, restartQA: function(e, message, title){ var self = this; var q = new Question('Are you sure you want to restart CouchPotato?', '', [{ 'text': 'Restart', 'class': 'restart orange', 'events': { 'click': function(e){ (e).preventDefault(); self.restart(message, title); q.close.delay(100, q); } } }, { 'text': 'No, nevah!', 'cancel': true }]); }, checkForUpdate: function(onComplete){ var self = this; Updater.check(onComplete); self.blockPage('Please wait. If this takes too long, something must have gone wrong.', 'Checking for updates'); self.checkAvailable(3000); }, checkAvailable: function(delay, onAvailable){ var self = this; (function(){ Api.request('app.available', { 'onFailure': function(){ self.checkAvailable.delay(1000, self, [delay, onAvailable]); self.fireEvent('unload'); }, 'onSuccess': function(){ if(onAvailable) onAvailable(); self.unBlockPage(); self.fireEvent('reload'); } }); }).delay(delay || 0) }, blockPage: function(message, title){ var self = this; self.unBlockPage(); self.mask = new Element('div.mask').adopt( new Element('div').adopt( new Element('h1', {'text': title || 'Unavailable'}), new Element('div', {'text': message || 'Something must have crashed.. check the logs ;)'}) ) ).fade('hide').inject(document.body).fade('in'); createSpinner(self.mask, { 'top': -50 }); }, unBlockPage: function(){ var self = this; if(self.mask) self.mask.get('tween').start('opacity', 0).chain(function(){ this.element.destroy() }); }, createUrl: function(action, params){ return this.options.base_url + (action ? action+'/' : '') + (params ? '?'+Object.toQueryString(params) : '') }, openDerefered: function(e, el){ (e).stop(); var url = 'http://www.dereferer.org/?' + el.get('href'); if(el.get('target') == '_blank' || (e.meta && Browser.Platform.mac) || (e.control && !Browser.Platform.mac)) window.open(url); else window.location = url; }, createUserscriptButtons: function(){ var host_url = window.location.protocol + '//' + window.location.host; return new Element('div.group_userscript').adopt( new Element('a.userscript.button', { 'text': 'Install userscript', 'href': Api.createUrl('userscript.get')+randomString()+'/couchpotato.user.js', 'target': '_blank' }), new Element('span.or[text=or]'), new Element('span.bookmarklet').adopt( new Element('a.button.orange', { 'text': '+CouchPotato', 'href': "javascript:void((function(){var e=document.createElement('script');e.setAttribute('type','text/javascript');e.setAttribute('charset','UTF-8');e.setAttribute('src','" + host_url + Api.createUrl('userscript.bookmark') + "?host="+ encodeURI(host_url + Api.createUrl('userscript.get')+randomString()+'/') + "&r='+Math.random()*99999999);document.body.appendChild(e)})());", 'target': '', 'events': { 'click': function(e){ (e).stop(); alert('Drag it to your bookmark ;)') } } }), new Element('span', { 'text': '⇽ Drag this to your bookmarks' }) ) ); }, /* * Global events */ on: function(name, handle){ var self = this; if(!self.global_events[name]) self.global_events[name] = []; self.global_events[name].push(handle); }, trigger: function(name, args, on_complete){ var self = this; if(!self.global_events[name]){ return; } if(!on_complete && typeOf(args) == 'function'){ on_complete = args; args = {}; } // Create parallel callback var callbacks = []; self.global_events[name].each(function(handle, nr){ callbacks.push(function(callback){ var results = handle(args || {}); callback(null, results || null); }); }); // Fire events async.parallel(callbacks, function(err, results){ if(err) p(err); if(on_complete) on_complete(results); }); }, off: function(name, handle){ var self = this; if(!self.global_events[name]) return; // Remove single if(handle){ self.global_events[name] = self.global_events[name].erase(handle); } // Reset full event else { self.global_events[name] = []; } } }); window.App = new CouchPotato(); var Route = new Class({ defaults: {}, page: '', action: 'index', params: {}, initialize: function(defaults){ var self = this; self.defaults = defaults }, parse: function(){ var self = this; var rep = function (pa) { return pa.replace(Api.getOption('url'), '/').replace(App.getOption('base_url'), '/') }; var path = rep(History.getPath()); if(path == '/' && location.hash){ path = rep(location.hash.replace('#', '/')) } self.current = path.replace(/^\/+|\/+$/g, ''); var url = self.current.split('/'); self.page = (url.length > 0) ? url.shift() : self.defaults.page; self.action = (url.length > 0) ? url.shift() : self.defaults.action; self.params = Object.merge({}, self.defaults.params); if(url.length > 1){ var key; url.each(function(el, nr){ if(nr%2 == 0) key = el; else if(key) { self.params[key] = el; key = null } }) } else if(url.length == 1){ self.params[url] = true; } return self }, getPage: function(){ return this.page }, getAction: function(){ return this.action }, getParams: function(){ return this.params }, getCurrentUrl: function(){ return this.current }, get: function(param){ return this.params[param] } }); var p = function(){ if(typeof(console) !== 'undefined' && console != null) console.log(arguments) }; (function(){ var events; var check = function(e) { var target = $(e.target); var parents = target.getParents(); events.each(function(item) { var element = item.element; if (element != target && !parents.contains(element)) item.fn.call(element, e); }); }; Element.Events.outerClick = { onAdd : function(fn) { if (!events) { document.addEvent('click', check); events = []; } events.push( { element : this, fn : fn }); }, onRemove : function(fn) { events = events.filter(function(item) { return item.element != this || item.fn != fn; }, this); if (!events.length) { document.removeEvent('click', check); events = null; } } }; })(); function randomString(length, extra) { var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz" + (extra ? '-._!@#$%^&*()+=' : ''); var stringLength = length || 8; var randomString = ''; for (var i = 0; i < stringLength; i++) { var rnum = Math.floor(Math.random() * chars.length); randomString += chars.charAt(rnum); } return randomString; } (function(){ var keyPaths = []; var saveKeyPath = function(path) { keyPaths.push({ sign: (path[0] === '+' || path[0] === '-')? parseInt(path.shift()+1) : 1, path: path }); }; var valueOf = function(object, path) { var ptr = object; path.each(function(key) { ptr = ptr[key] }); return ptr; }; var comparer = function(a, b) { for (var i = 0, l = keyPaths.length; i < l; i++) { var aVal = valueOf(a, keyPaths[i].path), bVal = valueOf(b, keyPaths[i].path); if (aVal > bVal) return keyPaths[i].sign; if (aVal < bVal) return -keyPaths[i].sign; } return 0; }; Array.implement({ sortBy: function(){ keyPaths.empty(); Array.each(arguments, function(argument) { switch (typeOf(argument)) { case "array": saveKeyPath(argument); break; case "string": saveKeyPath(argument.match(/[+-]|[^.]+/g)); break; } }); return this.stableSort(comparer); } }); })(); var createSpinner = function(target, options){ var opts = Object.merge({ lines: 12, length: 5, width: 4, radius: 9, color: '#fff', speed: 1.9, trail: 53, shadow: false, hwaccel: true, className: 'spinner', zIndex: 2e9, top: 'auto', left: 'auto' }, options); return new Spinner(opts).spin(target); };
lebabouin/CouchPotatoServer-develop
couchpotato/static/scripts/couchpotato.js
JavaScript
gpl-3.0
12,670
/*************************************************************************** ** ** Copyright (C) 2013 BlackBerry Limited. All rights reserved. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtNfc module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QNEARFIELDSHARETARGET_P_H #define QNEARFIELDSHARETARGET_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include "qnearfieldsharetarget.h" QT_BEGIN_NAMESPACE class QNearFieldShareTargetPrivate : public QObject { Q_OBJECT public: QNearFieldShareTargetPrivate(QNearFieldShareManager::ShareModes modes, QNearFieldShareTarget *q) : QObject(q) { Q_UNUSED(modes) } ~QNearFieldShareTargetPrivate() { } virtual QNearFieldShareManager::ShareModes shareModes() const { return QNearFieldShareManager::NoShare; } virtual bool share(const QNdefMessage &message) { Q_UNUSED(message) return false; } virtual bool share(const QList<QFileInfo> &files) { Q_UNUSED(files) return false; } virtual void cancel() { } virtual bool isShareInProgress() const { return false; } virtual QNearFieldShareManager::ShareError shareError() const { return QNearFieldShareManager::NoError; } }; QT_END_NAMESPACE #endif /* QNEARFIELDSHARETARGET_P_H */
jlspyaozhongkai/Uter
third_party_build/Qt5.5.0/include/QtNfc/5.5.0/QtNfc/private/qnearfieldsharetarget_p.h
C
gpl-3.0
2,940
/* mbed Microcontroller Library ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************* */ #include "sleep_api.h" #include "cmsis.h" void sleep(void) { // Disable us_ticker update interrupt TIM_ITConfig(TIM1, TIM_IT_Update, DISABLE); SCB->SCR = 0; // Normal sleep mode for ARM core __WFI(); // Re-enable us_ticker update interrupt TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE); } void deepsleep(void) { // Disable us_ticker update interrupt TIM_ITConfig(TIM1, TIM_IT_Update, DISABLE); // Enable PWR clock RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE); // Request to enter STOP mode with regulator in low power mode PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI); // Re-enable us_ticker update interrupt TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE); }
toolbits/tama_hack
mbed-src/targets/hal/TARGET_STM/TARGET_DISCO_F100RB/sleep.c
C
gpl-3.0
2,519
/* * BitbloqMeLEDMatrixData.h * * Copyright 2017 Alberto Valero <alberto.valero@bq.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * DERIVED FROM * * \par History: * <pre> * `<Author>` `<Time>` `<Version>` `<Descr>` * forfish 2015/11/09 1.0.0 Add description * Mark Yan 2016/01/19 1.0.1 Add some new symbol * Mark Yan 2016/01/27 1.0.2 Add digital printing * Mark Yan 2016/01/29 1.0.3 Fix issue when show integer number * </pre> * */ #ifndef BITBLOQ_ME_LEDMATRIX_FONT_DATA_H_ #define BITBLOQ_ME_LEDMATRIX_FONT_DATA_H_ typedef struct { uint8_t Character[1]; uint8_t data[6]; }LED_Matrix_Font_6x8_TypeDef; //Terminal const LED_Matrix_Font_6x8_TypeDef Character_font_6x8[] PROGMEM = { ' ', 0x00,0x00,0x00,0x00,0x00,0x00, '0', 0x00,0x7C,0x82,0x82,0x7C,0x00, '1', 0x00,0x42,0xFE,0x02,0x00,0x00, '2', 0x00,0x46,0x8A,0x92,0x62,0x00, '3', 0x00,0x44,0x92,0x92,0x6C,0x00, '4', 0x00,0x1C,0x64,0xFE,0x04,0x00, '5', 0x00,0xF2,0x92,0x92,0x8C,0x00, '6', 0x00,0x7C,0x92,0x92,0x4C,0x00, '7', 0x00,0xC0,0x8E,0x90,0xE0,0x00, '8', 0x00,0x6C,0x92,0x92,0x6C,0x00, '9', 0x00,0x64,0x92,0x92,0x7C,0x00, 'a', 0x00,0x04,0x2A,0x2A,0x1E,0x00, 'b', 0x00,0xFE,0x12,0x12,0x0C,0x00, 'c', 0x00,0x0C,0x12,0x12,0x12,0x00, 'd', 0x00,0x0C,0x12,0x12,0xFE,0x00, 'e', 0x00,0x1C,0x2A,0x2A,0x18,0x00, 'f', 0x00,0x10,0x3E,0x50,0x50,0x00, 'g', 0x00,0x08,0x15,0x15,0x1E,0x00, 'h', 0x00,0xFE,0x10,0x1E,0x00,0x00, 'i', 0x00,0x00,0x2E,0x00,0x00,0x00, 'j', 0x00,0x02,0x01,0x2E,0x00,0x00, 'k', 0x00,0xFE,0x08,0x14,0x12,0x00, 'l', 0x00,0x00,0xFE,0x02,0x00,0x00, 'm', 0x00,0x1E,0x10,0x0E,0x10,0x0E, 'n', 0x00,0x1E,0x10,0x10,0x0E,0x00, 'o', 0x00,0x0C,0x12,0x12,0x0C,0x00, 'p', 0x00,0x1F,0x12,0x12,0x0C,0x00, 'q', 0x00,0x0C,0x12,0x12,0x1F,0x00, 'r', 0x00,0x1E,0x08,0x10,0x10,0x00, 's', 0x00,0x12,0x29,0x25,0x12,0x00, 't', 0x00,0x10,0x3E,0x12,0x00,0x00, 'u', 0x00,0x1C,0x02,0x02,0x1E,0x00, 'v', 0x18,0x04,0x02,0x04,0x18,0x00, 'w', 0x18,0x06,0x1C,0x06,0x18,0x00, 'x', 0x00,0x12,0x0C,0x0C,0x12,0x00, 'y', 0x00,0x18,0x05,0x05,0x1E,0x00, 'z', 0x00,0x12,0x16,0x1A,0x12,0x00, 'A', 0x00,0x7E,0x88,0x88,0x7E,0x00, 'B', 0x00,0xFE,0x92,0x92,0x6C,0x00, 'C', 0x00,0x7C,0x82,0x82,0x44,0x00, 'D', 0x00,0xFE,0x82,0x82,0x7C,0x00, 'E', 0x00,0xFE,0x92,0x92,0x82,0x00, 'F', 0x00,0xFE,0x90,0x90,0x80,0x00, 'G', 0x00,0x7C,0x82,0x92,0x5C,0x00, 'H', 0x00,0xFE,0x10,0x10,0xFE,0x00, 'I', 0x00,0x82,0xFE,0x82,0x00,0x00, 'J', 0x00,0x0C,0x02,0x02,0xFC,0x00, 'K', 0x00,0xFE,0x10,0x28,0xC6,0x00, 'L', 0x00,0xFE,0x02,0x02,0x02,0x00, 'M', 0x00,0xFE,0x40,0x30,0x40,0xFE, 'N', 0x00,0xFE,0x40,0x30,0x08,0xFE, 'O', 0x00,0x7C,0x82,0x82,0x82,0x7C, 'P', 0x00,0xFE,0x90,0x90,0x60,0x00, 'Q', 0x00,0x7C,0x82,0x8A,0x84,0x7A, 'R', 0x00,0xFE,0x98,0x94,0x62,0x00, 'S', 0x00,0x64,0x92,0x92,0x4C,0x00, 'T', 0x00,0x80,0xFE,0x80,0x80,0x00, 'U', 0x00,0xFC,0x02,0x02,0xFC,0x00, 'V', 0x00,0xF0,0x0C,0x02,0x0C,0xF0, 'W', 0x00,0xFE,0x04,0x38,0x04,0xFE, 'X', 0x00,0xC6,0x38,0x38,0xC6,0x00, 'Y', 0xC0,0x20,0x1E,0x20,0xC0,0x00, 'Z', 0x00,0x86,0x9A,0xB2,0xC2,0x00, ',', 0x00,0x01,0x0e,0x0c,0x00,0x00, '.', 0x00,0x00,0x06,0x06,0x00,0x00, '%', 0x72,0x54,0x78,0x1e,0x2a,0x4e, '!', 0x00,0x00,0x7a,0x00,0x00,0x00, '?', 0x00,0x20,0x4a,0x30,0x00,0x00, '-', 0x00,0x10,0x10,0x10,0x10,0x00, '+', 0x08,0x08,0x3e,0x08,0x08,0x00, '/', 0x00,0x02,0x0c,0x30,0x40,0x00, '*', 0x22,0x14,0x08,0x14,0x22,0x00, ':', 0x00,0x00,0x14,0x00,0x00,0x00, '"', 0x00,0xC0,0x00,0xC0,0x00,0x00, '#', 0x28,0xFE,0x28,0xFE,0x28,0x00, '(', 0x00,0x00,0x7C,0x82,0x00,0x00, ')', 0x00,0x00,0x82,0x7C,0x00,0x00, ';', 0x00,0x02,0x24,0x00,0x00,0x00, '~', 0x00,0x40,0x80,0x40,0x80,0x00, ';', 0x00,0x02,0x24,0x00,0x00,0x00, '=', 0x00,0x28,0x28,0x28,0x28,0x00, '|', 0x00,0x00,0xFE,0x00,0x00,0x00, '>', 0x00,0x82,0x44,0x28,0x10,0x00, '<', 0x00,0x10,0x28,0x44,0x82,0x00, '@', 0x00,0x00,0x00,0x00,0x00,0x00, // End mark of Character_font_6x8 }; typedef struct { uint8_t data[3]; }LED_Matrix_Clock_Number_Font_3x8_TypeDef; const LED_Matrix_Clock_Number_Font_3x8_TypeDef Clock_Number_font_3x8[] PROGMEM = { 0x7C,0x44,0x7C, //0 0x00,0x7C,0x00, //1 0x5C,0x54,0x74, //2 0x54,0x54,0x7C, //3 0x70,0x10,0x7C, //4 0x74,0x54,0x5C, //5 0x7C,0x54,0x5C, //6 0x40,0x40,0x7C, //7 0x7C,0x54,0x7C, //8 0x74,0x54,0x7C, //9 0x00,0x04,0x00, //. 0x20,0x20,0x20, //- 0x00,0x00,0x00, // }; #endif
bq/bitbloq-compiler
pioWS/lib/BitbloqMeLEDMatrix/BitbloqMeLEDMatrixData.h
C
gpl-3.0
5,502
// // IASKSettingsStore.h // http://www.inappsettingskit.com // // Copyright (c) 2010: // Luc Vandal, Edovia Inc., http://www.edovia.com // Ortwin Gentz, FutureTap GmbH, http://www.futuretap.com // Marc-Etienne M.Léveillé, Edovia Inc., http://www.edovia.com // All rights reserved. // // It is appreciated but not required that you give credit to Luc Vandal and Ortwin Gentz, // as the original authors of this code. You can give credit in a blog post, a tweet or on // a info page of your app. Also, the original authors appreciate letting them know if you use this code. // // This code is licensed under the BSD license that is available at: http://www.opensource.org/licenses/bsd-license.php // #import <Foundation/Foundation.h> /** protocol that needs to be implemented from a settings store */ @protocol IASKSettingsStore <NSObject> @required - (void)setBool:(BOOL)value forKey:(NSString*)key; - (void)setFloat:(float)value forKey:(NSString*)key; - (void)setDouble:(double)value forKey:(NSString*)key; - (void)setInteger:(int)value forKey:(NSString*)key; - (void)setObject:(id)value forKey:(NSString*)key; - (BOOL)boolForKey:(NSString*)key; - (float)floatForKey:(NSString*)key; - (double)doubleForKey:(NSString*)key; - (int)integerForKey:(NSString*)key; - (id)objectForKey:(NSString*)key; - (BOOL)synchronize; // Write settings to a permanant storage. Returns YES on success, NO otherwise @end /** abstract default implementation of IASKSettingsStore protocol helper to implement a store which maps all methods to setObject:forKey: and objectForKey:. Those 2 methods need to be overwritten. */ @interface IASKAbstractSettingsStore : NSObject <IASKSettingsStore> /** default implementation raises an exception must be overridden by subclasses */ - (void)setObject:(id)value forKey:(NSString*)key; /** default implementation raises an exception must be overridden by subclasses */ - (id)objectForKey:(NSString*)key; /** default implementation does nothing and returns NO */ - (BOOL)synchronize; @end
stevenarnold/bpr
vendor/Pods/InAppSettingsKit/InAppSettingsKit/Models/IASKSettingsStore.h
C
gpl-3.0
2,055
#include "tommath.h" #ifdef BN_MP_SQRMOD_C /* LibTomMath, multiple-precision integer library -- Tom St Denis * * LibTomMath is a library that provides multiple-precision * integer arithmetic as well as number theoretic functionality. * * The library was designed directly after the MPI library by * Michael Fromberger but has been written from scratch with * additional optimizations in place. * * The library is free for all purposes without any express * guarantee it works. * * Tom St Denis, tomstdenis@gmail.com, http://libtom.org */ /* c = a * a (mod b) */ int mp_sqrmod (mp_int * a, mp_int * b, mp_int * c) { int res; mp_int t; if ((res = mp_init (&t)) != MP_OKAY) { return res; } if ((res = mp_sqr (a, &t)) != MP_OKAY) { mp_clear (&t); return res; } res = mp_mod (&t, b, c); mp_clear (&t); return res; } #endif /* $Source: /cvs/libtom/libtommath/bn_mp_sqrmod.c, v $ */ /* $Revision: 1.4 $ */ /* $Date: 2006/12/28 01:25:13 $ */
Zapuss/ZapekFapeCore
src/tools/extractor/StormLib/src/libtommath/bn_mp_sqrmod.c
C
gpl-3.0
985
/***************************************************************************** * * PROJECT: Multi Theft Auto v1.0 * LICENSE: See LICENSE in the top level directory * FILE: utils/gentable/gentable_vehattr.cpp * PURPOSE: Vehicle attribute table generator * * Multi Theft Auto is available from http://www.multitheftauto.com/ * *****************************************************************************/ #include <stdio.h> #include <string.h> enum eVehicleAttribute { VEHICLE_HAS_TURRENT = 0x0001, VEHICLE_HAS_SIRENS = 0x0002, VEHICLE_HAS_LANDING_GEARS = 0x0004, VEHICLE_HAS_ADJUSTABLE_PROPERTY = 0x0008, VEHICLE_HAS_SMOKE_TRAIL = 0x0010 }; void SetAttribute(unsigned long* table, unsigned long ulModel, eVehicleAttribute attribute) { table[ulModel - 400] |= attribute; } int main() { unsigned long table[611 - 400]; unsigned long tableSize = sizeof(table) / sizeof(unsigned long); memset(table, 0, sizeof(table)); SetAttribute(table, 432, VEHICLE_HAS_TURRENT); SetAttribute(table, 407, VEHICLE_HAS_TURRENT); SetAttribute(table, 601, VEHICLE_HAS_TURRENT); SetAttribute(table, 523, VEHICLE_HAS_SIRENS); SetAttribute(table, 407, VEHICLE_HAS_SIRENS); SetAttribute(table, 544, VEHICLE_HAS_SIRENS); SetAttribute(table, 416, VEHICLE_HAS_SIRENS); SetAttribute(table, 427, VEHICLE_HAS_SIRENS); SetAttribute(table, 490, VEHICLE_HAS_SIRENS); SetAttribute(table, 528, VEHICLE_HAS_SIRENS); SetAttribute(table, 596, VEHICLE_HAS_SIRENS); SetAttribute(table, 597, VEHICLE_HAS_SIRENS); SetAttribute(table, 598, VEHICLE_HAS_SIRENS); SetAttribute(table, 599, VEHICLE_HAS_SIRENS); SetAttribute(table, 601, VEHICLE_HAS_SIRENS); SetAttribute(table, 423, VEHICLE_HAS_SIRENS); SetAttribute(table, 592, VEHICLE_HAS_LANDING_GEARS); SetAttribute(table, 577, VEHICLE_HAS_LANDING_GEARS); SetAttribute(table, 553, VEHICLE_HAS_LANDING_GEARS); SetAttribute(table, 476, VEHICLE_HAS_LANDING_GEARS); SetAttribute(table, 519, VEHICLE_HAS_LANDING_GEARS); SetAttribute(table, 520, VEHICLE_HAS_LANDING_GEARS); SetAttribute(table, 520, VEHICLE_HAS_ADJUSTABLE_PROPERTY); SetAttribute(table, 525, VEHICLE_HAS_ADJUSTABLE_PROPERTY); SetAttribute(table, 524, VEHICLE_HAS_ADJUSTABLE_PROPERTY); SetAttribute(table, 486, VEHICLE_HAS_ADJUSTABLE_PROPERTY); SetAttribute(table, 406, VEHICLE_HAS_ADJUSTABLE_PROPERTY); SetAttribute(table, 443, VEHICLE_HAS_ADJUSTABLE_PROPERTY); SetAttribute(table, 531, VEHICLE_HAS_ADJUSTABLE_PROPERTY); SetAttribute(table, 530, VEHICLE_HAS_ADJUSTABLE_PROPERTY); SetAttribute(table, 592, VEHICLE_HAS_ADJUSTABLE_PROPERTY); SetAttribute(table, 512, VEHICLE_HAS_SMOKE_TRAIL); SetAttribute(table, 513, VEHICLE_HAS_SMOKE_TRAIL); printf( "unsigned long g_ulVehicleAttributes [] = {\n" " "); for (int i = 0; i < tableSize; i++) { if (!(i % 25) && i > 0) { printf("\n ", i - 25 + 400, i + 400 - 1); } printf("%lu, ", table[i]); } printf("\n};\n"); return 0; }
qaisjp/mtasa-blue
Client/utils/gentable/gentable_vehattr.cpp
C++
gpl-3.0
3,136
/* * Copyright (C) 2015, Simon Fuhrmann * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the LICENSE.txt file for details. */ #include <limits> #include <iostream> #include <QFileDialog> #include <QHBoxLayout> #include <QInputDialog> #include <QMessageBox> #include <QPushButton> #include <QVBoxLayout> #include <QColorDialog> #include "util/file_system.h" #include "util/string.h" #include "mve/mesh.h" #include "mve/mesh_io.h" #include "mve/mesh_tools.h" #include "scene_addins/mesh_list.h" QMeshContextMenu::QMeshContextMenu (QMeshList* parent) { this->parent = parent; this->rep = nullptr; this->item = nullptr; } /* ---------------------------------------------------------------- */ void QMeshContextMenu::build (void) { QAction* action_reload_mesh = new QAction("Reload mesh", this); QAction* action_save_mesh = new QAction("Save mesh...", this); QAction* action_rename_mesh = new QAction("Rename mesh...", this); this->connect(action_reload_mesh, SIGNAL(triggered()), this, SLOT(on_reload_mesh())); this->connect(action_save_mesh, SIGNAL(triggered()), this, SLOT(on_save_mesh())); this->connect(action_rename_mesh, SIGNAL(triggered()), this, SLOT(on_rename_mesh())); std::string num_verts(util::string::get(rep->mesh->get_vertices().size())); std::string num_faces(util::string::get(rep->mesh->get_faces().size() / 3)); util::string::punctate(&num_verts, '\''); util::string::punctate(&num_faces, '\''); QMenu* vertices_menu = this->addMenu(tr("Vertices: %1").arg(num_verts.c_str())); { QAction* scale = vertices_menu->addAction(tr("Scale and center")); this->connect(scale, SIGNAL(triggered()), this, SLOT(on_scale_and_center())); if (rep->mesh->get_vertices().empty()) scale->setEnabled(false); QAction* compute_aabb = vertices_menu->addAction(tr("Compute AABB")); this->connect(compute_aabb, SIGNAL(triggered()), this, SLOT(on_compute_aabb())); if (rep->mesh->get_vertices().size() <= 1) compute_aabb->setEnabled(false); } QMenu* faces_menu = this->addMenu(tr("Faces: %1").arg(num_faces.c_str())); { QAction* invert_faces = faces_menu->addAction(tr("Invert faces")); QAction* delete_faces = faces_menu->addAction(tr("Delete faces")); this->connect(invert_faces, SIGNAL(triggered()), this, SLOT(on_invert_faces())); this->connect(delete_faces, SIGNAL(triggered()), this, SLOT(on_delete_faces())); if (rep->mesh->get_faces().empty()) { invert_faces->setEnabled(false); delete_faces->setEnabled(false); } } if (rep->mesh->has_vertex_normals()) { QMenu* menu = this->addMenu(tr("Vertex Normals")); QAction* delete_vnormals = menu->addAction(tr("Delete normals")); QAction* normalize_vnormals = menu->addAction(tr("Normalize normals")); this->connect(delete_vnormals, SIGNAL(triggered()), this, SLOT(on_delete_vertex_normals())); this->connect(normalize_vnormals, SIGNAL(triggered()), this, SLOT(on_normalize_vertex_normals())); } if (rep->mesh->has_vertex_colors()) { QMenu* menu = this->addMenu(tr("Vertex Colors")); QAction* delete_vcolor = menu->addAction(tr("Delete colors")); this->connect(delete_vcolor, SIGNAL(triggered()), this, SLOT(on_delete_vertex_colors())); } if (rep->mesh->has_vertex_confidences()) { QMenu* menu = this->addMenu(tr("Vertex Confidences")); QAction* convert_color = menu->addAction(tr("Map to color")); QAction* delete_vconfs = menu->addAction(tr("Delete confidences")); this->connect(convert_color, SIGNAL(triggered()), this, SLOT(on_colorize_confidences())); this->connect(delete_vconfs, SIGNAL(triggered()), this, SLOT(on_delete_vertex_confidences())); } if (rep->mesh->has_vertex_values()) { QMenu* menu = this->addMenu(tr("Vertex Values")); QAction* convert_color = menu->addAction(tr("Map to color")); QAction* delete_vvalues = menu->addAction(tr("Delete values")); this->connect(convert_color, SIGNAL(triggered()), this, SLOT(on_colorize_values())); this->connect(delete_vvalues, SIGNAL(triggered()), this, SLOT(on_delete_vertex_values())); } if (rep->mesh->has_face_colors()) this->addAction(tr("Face Colors: Yes"))->setEnabled(false); this->addSeparator(); /* Colorize menu. */ { QMenu* menu = this->addMenu(tr("Colorize")); QAction* colorize_red = menu->addAction(tr("Red")); QAction* colorize_green = menu->addAction(tr("Green")); QAction* colorize_blue = menu->addAction(tr("Blue")); QAction* colorize_custom = menu->addAction(tr("Custom...")); this->connect(colorize_red, SIGNAL(triggered()), this, SLOT(on_colorize_mesh_red())); this->connect(colorize_green, SIGNAL(triggered()), this, SLOT(on_colorize_mesh_green())); this->connect(colorize_blue, SIGNAL(triggered()), this, SLOT(on_colorize_mesh_blue())); this->connect(colorize_custom, SIGNAL(triggered()), this, SLOT(on_colorize_mesh_custom())); } this->addSeparator(); this->addAction(action_reload_mesh); this->addAction(action_rename_mesh); this->addAction(action_save_mesh); /* Enable / disable certain actions. */ action_reload_mesh->setEnabled(!rep->filename.empty()); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_reload_mesh (void) { try { this->rep->mesh = mve::geom::load_mesh(this->rep->filename); if (!this->rep->mesh->get_faces().empty()) this->rep->mesh->ensure_normals(); } catch (std::exception& e) { QMessageBox::critical(this->parent, tr("Error reloading mesh"), tr("There was an error while reloading the mesh.\n" "%1").arg(e.what())); return; } this->rep->renderer.reset(); emit this->parent->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_invert_faces (void) { mve::geom::mesh_invert_faces(this->rep->mesh); this->rep->renderer.reset(); emit this->parent->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_delete_faces (void) { this->rep->mesh->get_faces().clear(); this->rep->mesh->get_face_normals().clear(); this->rep->renderer.reset(); emit this->parent->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_scale_and_center (void) { mve::geom::mesh_scale_and_center(this->rep->mesh); this->rep->renderer.reset(); emit this->parent->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_compute_aabb (void) { math::Vec3f aabb_min(std::numeric_limits<float>::max()); math::Vec3f aabb_max(-std::numeric_limits<float>::max()); mve::TriangleMesh::VertexList const& verts = this->rep->mesh->get_vertices(); for (std::size_t i = 0; i < verts.size(); ++i) { for (int j = 0; j < 3; ++j) { aabb_min[j] = std::min(aabb_min[j], verts[i][j]); aabb_max[j] = std::max(aabb_max[j], verts[i][j]); } } std::stringstream aabb_ss; aabb_ss << "<b>Exact AABB</b><br/>" << std::endl; aabb_ss << "AABB min: " << aabb_min << "<br/>" << std::endl; aabb_ss << "AABB max: " << aabb_max << "<br/>" << std::endl; aabb_ss << "AABB string: " << aabb_min[0] << "," << aabb_min[1] << "," << aabb_min[2] << "," << aabb_max[0] << "," << aabb_max[1] << "," << aabb_max[2] << "<br/><br/>" << std::endl; for (int j = 0; j < 3; ++j) { aabb_min[j] -= (aabb_max[j] - aabb_min[j]) / 20.0f; aabb_max[j] += (aabb_max[j] - aabb_min[j]) / 20.0f; } aabb_ss << "<b>AABB with 10% border</b><br/>" << std::endl; aabb_ss << "AABB min: " << aabb_min << "<br/>" << std::endl; aabb_ss << "AABB max: " << aabb_max << "<br/>" << std::endl; aabb_ss << "AABB string: " << aabb_min[0] << "," << aabb_min[1] << "," << aabb_min[2] << "," << aabb_max[0] << "," << aabb_max[1] << "," << aabb_max[2] << "<br/>" << std::endl; QMessageBox::information(this->parent, "Mesh AABB", tr(aabb_ss.str().c_str())); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_save_mesh (void) { QString filename = QFileDialog::getSaveFileName(this->parent, tr("Save mesh to file"), QDir::currentPath()); if (filename.isEmpty()) return; std::string fname(filename.toStdString()); try { mve::geom::save_mesh(this->rep->mesh, fname); this->rep->filename = fname; this->rep->name = util::fs::basename(fname); this->item->setText(this->rep->name.c_str()); } catch (std::exception& e) { QMessageBox::critical(this->parent, "Error saving mesh", e.what()); } } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_rename_mesh (void) { bool pressed_ok = false; QString q_new_name = QInputDialog::getText(this->parent, tr("Rename mesh..."), tr("New mesh name:"), QLineEdit::Normal, this->rep->name.c_str(), &pressed_ok); if (q_new_name.isEmpty() || !pressed_ok) return; /* Check if there is a mesh by that new name. That is not allowed! */ std::string new_name = q_new_name.toStdString(); MeshRep* old_mesh = this->parent->mesh_by_name(new_name); if (old_mesh != nullptr) { QMessageBox::critical(this->parent, "Error renaming mesh", "A mesh by that name does already exist!"); return; } this->rep->name = new_name; this->rep->filename.clear(); this->item->setText(new_name.c_str()); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_delete_vertex_normals (void) { this->rep->mesh->get_vertex_normals().clear(); this->rep->renderer.reset(); emit this->parent->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_normalize_vertex_normals (void) { mve::TriangleMesh::NormalList& nl = this->rep->mesh->get_vertex_normals(); for (std::size_t i = 0; i < nl.size(); ++i) nl[i].normalize(); this->rep->renderer.reset(); emit this->parent->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_delete_vertex_colors (void) { this->rep->mesh->get_vertex_colors().clear(); this->rep->renderer.reset(); emit this->parent->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_delete_vertex_confidences (void) { this->rep->mesh->get_vertex_confidences().clear(); this->rep->renderer.reset(); emit this->parent->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_delete_vertex_values (void) { this->rep->mesh->get_vertex_values().clear(); this->rep->renderer.reset(); emit this->parent->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_colorize_values (void) { this->on_colorize_with_attrib(this->rep->mesh->get_vertex_values()); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_colorize_confidences (void) { this->on_colorize_with_attrib(this->rep->mesh->get_vertex_confidences()); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_colorize_with_attrib (std::vector<float> const& attrib) { mve::TriangleMesh::ColorList& vcolor = this->rep->mesh->get_vertex_colors(); if (attrib.size() != this->rep->mesh->get_vertices().size()) return; #if 1 /* Find min/max value of the attribute. */ float fmin = std::numeric_limits<float>::max(); float fmax = -std::numeric_limits<float>::max(); for (std::size_t i = 0; i < attrib.size(); ++i) { fmin = std::min(fmin, attrib[i]); fmax = std::max(fmax, attrib[i]); } std::cout << "Mapping min: " << fmin << ", max: " << fmax << std::endl; //fmin = 0.0f; //fmax = 0.00002f; #else /* Robust percentile min/max assignment. */ std::vector<float> tmp = attrib; std::sort(tmp.begin(), tmp.end()); float const fmin = tmp[0];// tmp[1 * tmp.size() / 40]; float const fmax = tmp[19 * tmp.size() / 20]; #endif /* Assign the min/max value as gray-scale color value. */ vcolor.clear(); vcolor.resize(attrib.size()); for (std::size_t i = 0; i < attrib.size(); ++i) { float value = (attrib[i] - fmin) / (fmax - fmin); value = std::max(0.0f, std::min(1.0f, value)); //value = std::pow(value, 2.0f); vcolor[i] = math::Vec4f(1.0f, 1.0f - value, 1.0f - value, 1.0f); } this->rep->renderer.reset(); emit this->parent->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshContextMenu::on_colorize_mesh_red (void) { this->on_colorize_mesh(1.0f, 0.0f, 0.0f); } void QMeshContextMenu::on_colorize_mesh_green (void) { this->on_colorize_mesh(0.0f, 1.0f, 0.0f); } void QMeshContextMenu::on_colorize_mesh_blue (void) { this->on_colorize_mesh(0.0f, 0.0f, 1.0f); } void QMeshContextMenu::on_colorize_mesh_custom (void) { QColor color = QColorDialog::getColor(Qt::white, this); if (!color.isValid()) return; this->on_colorize_mesh(color.redF(), color.greenF(), color.blueF()); } void QMeshContextMenu::on_colorize_mesh (float red, float green, float blue) { mve::TriangleMesh::ColorList& vcolor = this->rep->mesh->get_vertex_colors(); vcolor.clear(); vcolor.resize(this->rep->mesh->get_vertices().size(), math::Vec4f(red, green, blue, 1.0f)); this->rep->renderer.reset(); emit this->parent->signal_redraw(); } /* ---------------------------------------------------------------- */ /* ---------------------------------------------------------------- */ QMeshList::QMeshList (QWidget *parent) : QWidget(parent) { //this->toolbar = new QToolBar(); //this->toolbar->setIconSize(QSize(16, 16)); this->qlist = new QListWidget(); this->qlist->setContextMenuPolicy(Qt::CustomContextMenu); QPushButton* select_all_but = new QPushButton("All"); QPushButton* select_none_but = new QPushButton("Nne"); QPushButton* inv_selection_but = new QPushButton("Inv"); QPushButton* select_next_but = new QPushButton("Nxt"); QPushButton* select_toggle_but = new QPushButton("Tgl"); select_all_but->setMinimumWidth(8); select_none_but->setMinimumWidth(8); inv_selection_but->setMinimumWidth(8); select_next_but->setMinimumWidth(8); select_toggle_but->setMinimumWidth(8); select_all_but->setToolTip (tr("Check all meshes")); select_none_but->setToolTip (tr("Uncheck all meshes")); inv_selection_but->setToolTip (tr("Invert check state of all meshes")); select_next_but->setToolTip (tr("Move check state to the next mesh in order")); select_toggle_but->setToolTip (tr("Toggle between a checked and the selected mesh")); QHBoxLayout* button_hbox = new QHBoxLayout(); button_hbox->setSpacing(1); button_hbox->addWidget(select_all_but, 1); button_hbox->addWidget(select_none_but, 1); button_hbox->addWidget(select_next_but, 1); button_hbox->addWidget(inv_selection_but, 1); button_hbox->addWidget(select_toggle_but, 1); QVBoxLayout* vbox = new QVBoxLayout(); vbox->setSpacing(1); vbox->setContentsMargins(0,0,0,0); //vbox->addWidget(this->toolbar); vbox->addWidget(this->qlist); vbox->addLayout(button_hbox); this->setLayout(vbox); this->connect(this->qlist, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(on_item_activated(QListWidgetItem*))); this->connect(this->qlist, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(on_item_changed(QListWidgetItem*))); this->connect(this->qlist, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(on_list_context_menu(QPoint))); this->connect(select_all_but, SIGNAL(clicked()), this, SLOT(on_select_all())); this->connect(select_none_but, SIGNAL(clicked()), this, SLOT(on_select_none())); this->connect(select_next_but, SIGNAL(clicked()), this, SLOT(on_select_next())); this->connect(inv_selection_but, SIGNAL(clicked()), this, SLOT(on_inv_selection())); this->connect(select_toggle_but, SIGNAL(clicked()), this, SLOT(on_select_toggle())); } /* ---------------------------------------------------------------- */ QMeshList::~QMeshList (void) { } /* ---------------------------------------------------------------- */ void QMeshList::add (std::string const& name, mve::TriangleMesh::Ptr mesh, std::string const& filename, ogl::Texture::Ptr texture) { /* Check if mesh by that name is already available. */ for (std::size_t i = 0; i < this->meshes.size(); ++i) { MeshRep& rep(this->meshes[i]); if (rep.name == name) { rep.mesh = mesh; rep.texture = texture; rep.renderer.reset(); return; } } MeshRep rep; rep.name = name; rep.filename = filename; rep.mesh = mesh; rep.texture = texture; rep.active = true; this->meshes.push_back(rep); this->update_list(); } /* ---------------------------------------------------------------- */ void QMeshList::remove (std::string const& name) { MeshList::iterator i = this->meshes.begin(); while (i != this->meshes.end()) { if (i->name == name) i = this->meshes.erase(i); else ++i; } this->update_list(); emit this->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshList::update_list (void) { this->qlist->clear(); for (std::size_t i = 0; i < this->meshes.size(); ++i) { MeshRep const& rep(this->meshes[i]); QListWidgetItem* item = new QListWidgetItem(); item->setText(rep.name.c_str()); item->setCheckState(rep.active ? Qt::Checked : Qt::Unchecked); this->qlist->addItem(item); } } /* ---------------------------------------------------------------- */ MeshRep* QMeshList::mesh_by_name (std::string const& name) { for (std::size_t i = 0; i < this->meshes.size(); ++i) if (this->meshes[i].name == name) return &this->meshes[i]; return nullptr; } /* ---------------------------------------------------------------- */ void QMeshList::on_item_activated (QListWidgetItem* item) { std::string name = item->text().toStdString(); this->remove(name); } /* ---------------------------------------------------------------- */ void QMeshList::on_item_changed (QListWidgetItem* item) { if (this->meshes.size() != (std::size_t)this->qlist->count()) { std::cout << "Error: Meshlist size mismatch!" << std::endl; return; } std::string name = item->text().toStdString(); for (std::size_t i = 0; i < this->meshes.size(); ++i) { MeshRep& rep(this->meshes[i]); QListWidgetItem* item = this->qlist->item(i); if (item->text().toStdString() == rep.name) rep.active = (item->checkState() == Qt::Checked); } emit this->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshList::on_select_all (void) { for (int i = 0; i < this->qlist->count(); ++i) { QListWidgetItem* item = this->qlist->item(i); item->setCheckState(Qt::Checked); } emit this->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshList::on_select_none (void) { for (int i = 0; i < this->qlist->count(); ++i) { QListWidgetItem* item = this->qlist->item(i); item->setCheckState(Qt::Unchecked); } emit this->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshList::on_inv_selection (void) { for (int i = 0; i < this->qlist->count(); ++i) { QListWidgetItem* item = this->qlist->item(i); Qt::CheckState cs = item->checkState(); item->setCheckState(cs == Qt::Checked ? Qt::Unchecked : Qt::Checked); } emit this->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshList::on_select_next (void) { int cnt = this->qlist->count(); std::vector<int> check; for (int i = 0; i < cnt; ++i) { QListWidgetItem* item = this->qlist->item(i); Qt::CheckState cs = item->checkState(); if (cs == Qt::Checked) check.push_back((i + 1) % cnt); item->setCheckState(Qt::Unchecked); } for (std::size_t i = 0; i < check.size(); ++i) this->qlist->item(check[i])->setCheckState(Qt::Checked); emit this->signal_redraw(); } /* ---------------------------------------------------------------- */ void QMeshList::on_select_toggle (void) { int current = this->qlist->currentRow(); int checked = -1; /* Find the mesh that is checked (in case of multiple, find first). */ int cnt = this->qlist->count(); for (int i = 0; i < cnt; ++i) { QListWidgetItem* item = this->qlist->item(i); if (item->checkState() == Qt::Checked) checked = i; item->setCheckState(Qt::Unchecked); } /* Exchange state of checked and selected mesh. */ if (checked != -1) this->qlist->setCurrentRow(checked); if (current != -1) this->qlist->item(current)->setCheckState(Qt::Checked); } /* ---------------------------------------------------------------- */ void QMeshList::on_list_context_menu (QPoint pos) { QListWidgetItem* item = this->qlist->itemAt(pos.x(), pos.y()); if (!item) return; std::string name = item->text().toStdString(); QPoint global_pos = this->mapToGlobal(pos); QMeshContextMenu* menu = new QMeshContextMenu(this); menu->rep = this->mesh_by_name(name); menu->item = item; menu->build(); menu->exec(global_pos); }
rhiestan/mve
apps/umve/scene_addins/mesh_list.cc
C++
gpl-3.0
23,110
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <memory> // unique_ptr //============================================================================= // TESTING std::unique_ptr::unique_ptr() // // Concerns: // 1 The pointer constructor works for any default constructible deleter types. // 2 The pointer constructor accepts pointers to derived types. // 2 The stored type 'T' is allowed to be incomplete. // // Plan // 1 Construct unique_ptr<T, D>'s with a pointer to 'T' and various deleter // types (C-1) // 2 Construct unique_ptr<T, D>'s with a pointer to 'D' and various deleter // types where 'D' is derived from 'T'. (C-1,2) // 3 Construct a unique_ptr<T, D> with a pointer to 'T' and various deleter // types where 'T' is an incomplete type (C-1,3) // Test unique_ptr(pointer) ctor #include <memory> #include <cassert> #include "../../deleter.h" // unique_ptr(pointer) ctor should only require default Deleter ctor struct A { static int count; A() {++count;} A(const A&) {++count;} virtual ~A() {--count;} }; int A::count = 0; struct B : public A { static int count; B() {++count;} B(const B&) {++count;} virtual ~B() {--count;} }; int B::count = 0; struct IncompleteT; IncompleteT* getIncomplete(); void checkNumIncompleteTypeAlive(int i); template <class Del = std::default_delete<IncompleteT> > struct StoresIncomplete { std::unique_ptr<IncompleteT, Del> m_ptr; StoresIncomplete() {} explicit StoresIncomplete(IncompleteT* ptr) : m_ptr(ptr) {} ~StoresIncomplete(); IncompleteT* get() const { return m_ptr.get(); } Del& get_deleter() { return m_ptr.get_deleter(); } }; void test_pointer() { { A* p = new A; assert(A::count == 1); std::unique_ptr<A> s(p); assert(s.get() == p); } assert(A::count == 0); { A* p = new A; assert(A::count == 1); std::unique_ptr<A, NCDeleter<A> > s(p); assert(s.get() == p); assert(s.get_deleter().state() == 0); } assert(A::count == 0); } void test_derived() { { B* p = new B; assert(A::count == 1); assert(B::count == 1); std::unique_ptr<A> s(p); assert(s.get() == p); } assert(A::count == 0); assert(B::count == 0); { B* p = new B; assert(A::count == 1); assert(B::count == 1); std::unique_ptr<A, NCDeleter<A> > s(p); assert(s.get() == p); assert(s.get_deleter().state() == 0); } assert(A::count == 0); assert(B::count == 0); } void test_incomplete() { { IncompleteT* p = getIncomplete(); checkNumIncompleteTypeAlive(1); StoresIncomplete<> s(p); assert(s.get() == p); } checkNumIncompleteTypeAlive(0); { IncompleteT* p = getIncomplete(); checkNumIncompleteTypeAlive(1); StoresIncomplete< NCDeleter<IncompleteT> > s(p); assert(s.get() == p); assert(s.get_deleter().state() == 0); } checkNumIncompleteTypeAlive(0); } struct IncompleteT { static int count; IncompleteT() { ++count; } ~IncompleteT() {--count; } }; int IncompleteT::count = 0; IncompleteT* getIncomplete() { return new IncompleteT; } void checkNumIncompleteTypeAlive(int i) { assert(IncompleteT::count == i); } template <class Del> StoresIncomplete<Del>::~StoresIncomplete() { } int main() { test_pointer(); test_derived(); test_incomplete(); }
HexHive/datashield
libcxx/libcxx/test/std/utilities/memory/unique.ptr/unique.ptr.single/unique.ptr.single.ctor/pointer.pass.cpp
C++
gpl-3.0
3,794
/** * @module * @description * Common directives shipped with Angular. */ import { CONST_EXPR } from './facade/lang'; import { NgClass } from './directives/ng_class'; import { NgFor } from './directives/ng_for'; import { NgIf } from './directives/ng_if'; import { NgStyle } from './directives/ng_style'; import { NgSwitch, NgSwitchWhen, NgSwitchDefault } from './directives/ng_switch'; export { NgClass } from './directives/ng_class'; export { NgFor } from './directives/ng_for'; export { NgIf } from './directives/ng_if'; export { NgStyle } from './directives/ng_style'; export { NgSwitch, NgSwitchWhen, NgSwitchDefault } from './directives/ng_switch'; export * from './directives/observable_list_diff'; /** * A collection of Angular core directives that are likely to be used in each and every Angular * application. * * This collection can be used to quickly enumerate all the built-in directives in the `directives` * property of the `@View` annotation. * * ### Example ([live demo](http://plnkr.co/edit/yakGwpCdUkg0qfzX5m8g?p=preview)) * * Instead of writing: * * ```typescript * import {NgClass, NgIf, NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault} from 'angular2/angular2'; * import {OtherDirective} from './myDirectives'; * * @Component({ * selector: 'my-component', * templateUrl: 'myComponent.html', * directives: [NgClass, NgIf, NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault, OtherDirective] * }) * export class MyComponent { * ... * } * ``` * one could import all the core directives at once: * * ```typescript * import {CORE_DIRECTIVES} from 'angular2/angular2'; * import {OtherDirective} from './myDirectives'; * * @Component({ * selector: 'my-component', * templateUrl: 'myComponent.html', * directives: [CORE_DIRECTIVES, OtherDirective] * }) * export class MyComponent { * ... * } * ``` */ export const CORE_DIRECTIVES = CONST_EXPR([NgClass, NgFor, NgIf, NgStyle, NgSwitch, NgSwitchWhen, NgSwitchDefault]); //# sourceMappingURL=directives.js.map
NodeVision/NodeVision
node_modules/angular2/es6/prod/src/core/directives.js
JavaScript
gpl-3.0
2,022
#!/usr/bin/python # Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # # This module 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 software 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 software. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: os_port short_description: Add/Update/Delete ports from an OpenStack cloud. extends_documentation_fragment: openstack author: "Davide Agnello (@dagnello)" version_added: "2.0" description: - Add, Update or Remove ports from an OpenStack cloud. A I(state) of 'present' will ensure the port is created or updated if required. options: network: description: - Network ID or name this port belongs to. required: true name: description: - Name that has to be given to the port. required: false default: None fixed_ips: description: - Desired IP and/or subnet for this port. Subnet is referenced by subnet_id and IP is referenced by ip_address. required: false default: None admin_state_up: description: - Sets admin state. required: false default: None mac_address: description: - MAC address of this port. required: false default: None security_groups: description: - Security group(s) ID(s) or name(s) associated with the port (comma separated string or YAML list) required: false default: None no_security_groups: description: - Do not associate a security group with this port. required: false default: False allowed_address_pairs: description: - "Allowed address pairs list. Allowed address pairs are supported with dictionary structure. e.g. allowed_address_pairs: - ip_address: 10.1.0.12 mac_address: ab:cd:ef:12:34:56 - ip_address: ..." required: false default: None extra_dhcp_opts: description: - "Extra dhcp options to be assigned to this port. Extra options are supported with dictionary structure. e.g. extra_dhcp_opts: - opt_name: opt name1 opt_value: value1 - opt_name: ..." required: false default: None device_owner: description: - The ID of the entity that uses this port. required: false default: None device_id: description: - Device ID of device using this port. required: false default: None state: description: - Should the resource be present or absent. choices: [present, absent] default: present ''' EXAMPLES = ''' # Create a port - os_port: state: present auth: auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/ username: admin password: admin project_name: admin name: port1 network: foo # Create a port with a static IP - os_port: state: present auth: auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/ username: admin password: admin project_name: admin name: port1 network: foo fixed_ips: - ip_address: 10.1.0.21 # Create a port with No security groups - os_port: state: present auth: auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/ username: admin password: admin project_name: admin name: port1 network: foo no_security_groups: True # Update the existing 'port1' port with multiple security groups (version 1) - os_port: state: present auth: auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/d username: admin password: admin project_name: admin name: port1 security_groups: 1496e8c7-4918-482a-9172-f4f00fc4a3a5,057d4bdf-6d4d-472... # Update the existing 'port1' port with multiple security groups (version 2) - os_port: state: present auth: auth_url: https://region-b.geo-1.identity.hpcloudsvc.com:35357/v2.0/d username: admin password: admin project_name: admin name: port1 security_groups: - 1496e8c7-4918-482a-9172-f4f00fc4a3a5 - 057d4bdf-6d4d-472... ''' RETURN = ''' id: description: Unique UUID. returned: success type: string name: description: Name given to the port. returned: success type: string network_id: description: Network ID this port belongs in. returned: success type: string security_groups: description: Security group(s) associated with this port. returned: success type: list of strings status: description: Port's status. returned: success type: string fixed_ips: description: Fixed ip(s) associated with this port. returned: success type: list of dicts tenant_id: description: Tenant id associated with this port. returned: success type: string allowed_address_pairs: description: Allowed address pairs with this port. returned: success type: list of dicts admin_state_up: description: Admin state up flag for this port. returned: success type: bool ''' try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False def _needs_update(module, port, cloud): """Check for differences in the updatable values. NOTE: We don't currently allow name updates. """ compare_simple = ['admin_state_up', 'mac_address', 'device_owner', 'device_id'] compare_dict = ['allowed_address_pairs', 'extra_dhcp_opts'] compare_list = ['security_groups'] for key in compare_simple: if module.params[key] is not None and module.params[key] != port[key]: return True for key in compare_dict: if module.params[key] is not None and cmp(module.params[key], port[key]) != 0: return True for key in compare_list: if module.params[key] is not None and (set(module.params[key]) != set(port[key])): return True # NOTE: if port was created or updated with 'no_security_groups=True', # subsequent updates without 'no_security_groups' flag or # 'no_security_groups=False' and no specified 'security_groups', will not # result in an update to the port where the default security group is # applied. if module.params['no_security_groups'] and port['security_groups'] != []: return True if module.params['fixed_ips'] is not None: for item in module.params['fixed_ips']: if 'ip_address' in item: # if ip_address in request does not match any in existing port, # update is required. if not any(match['ip_address'] == item['ip_address'] for match in port['fixed_ips']): return True if 'subnet_id' in item: return True for item in port['fixed_ips']: # if ip_address in existing port does not match any in request, # update is required. if not any(match.get('ip_address') == item['ip_address'] for match in module.params['fixed_ips']): return True return False def _system_state_change(module, port, cloud): state = module.params['state'] if state == 'present': if not port: return True return _needs_update(module, port, cloud) if state == 'absent' and port: return True return False def _compose_port_args(module, cloud): port_kwargs = {} optional_parameters = ['name', 'fixed_ips', 'admin_state_up', 'mac_address', 'security_groups', 'allowed_address_pairs', 'extra_dhcp_opts', 'device_owner', 'device_id'] for optional_param in optional_parameters: if module.params[optional_param] is not None: port_kwargs[optional_param] = module.params[optional_param] if module.params['no_security_groups']: port_kwargs['security_groups'] = [] return port_kwargs def get_security_group_id(module, cloud, security_group_name_or_id): security_group = cloud.get_security_group(security_group_name_or_id) if not security_group: module.fail_json(msg="Security group: %s, was not found" % security_group_name_or_id) return security_group['id'] def main(): argument_spec = openstack_full_argument_spec( network=dict(required=False), name=dict(required=False), fixed_ips=dict(type='list', default=None), admin_state_up=dict(type='bool', default=None), mac_address=dict(default=None), security_groups=dict(default=None, type='list'), no_security_groups=dict(default=False, type='bool'), allowed_address_pairs=dict(type='list', default=None), extra_dhcp_opts=dict(type='list', default=None), device_owner=dict(default=None), device_id=dict(default=None), state=dict(default='present', choices=['absent', 'present']), ) module_kwargs = openstack_module_kwargs( mutually_exclusive=[ ['no_security_groups', 'security_groups'], ] ) module = AnsibleModule(argument_spec, supports_check_mode=True, **module_kwargs) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') name = module.params['name'] state = module.params['state'] try: cloud = shade.openstack_cloud(**module.params) if module.params['security_groups']: # translate security_groups to UUID's if names where provided module.params['security_groups'] = [ get_security_group_id(module, cloud, v) for v in module.params['security_groups'] ] port = None network_id = None if name: port = cloud.get_port(name) if module.check_mode: module.exit_json(changed=_system_state_change(module, port, cloud)) changed = False if state == 'present': if not port: network = module.params['network'] if not network: module.fail_json( msg="Parameter 'network' is required in Port Create" ) port_kwargs = _compose_port_args(module, cloud) network_object = cloud.get_network(network) if network_object: network_id = network_object['id'] else: module.fail_json( msg="Specified network was not found." ) port = cloud.create_port(network_id, **port_kwargs) changed = True else: if _needs_update(module, port, cloud): port_kwargs = _compose_port_args(module, cloud) port = cloud.update_port(port['id'], **port_kwargs) changed = True module.exit_json(changed=changed, id=port['id'], port=port) if state == 'absent': if port: cloud.delete_port(port['id']) changed = True module.exit_json(changed=changed) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e)) # this is magic, see lib/ansible/module_common.py from ansible.module_utils.basic import * from ansible.module_utils.openstack import * if __name__ == '__main__': main()
emersonsoftware/ansiblefork
lib/ansible/modules/cloud/openstack/os_port.py
Python
gpl-3.0
12,587
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreD3D11HardwareOcclusionQuery.h" #include "OgreRenderSystemCapabilities.h" #include "OgreException.h" #include "OgreD3D11Device.h" namespace Ogre { /** * This is a class that is the DirectX9 implementation of * hardware occlusion testing. * * @author Lee Sandberg * * Updated on 12/7/2004 by Chris McGuirk * Updated on 4/8/2005 by Tuan Kuranes email: tuan.kuranes@free.fr */ /** * Default object constructor */ D3D11HardwareOcclusionQuery::D3D11HardwareOcclusionQuery( D3D11Device & device ) : mDevice(device) { D3D11_QUERY_DESC queryDesc; queryDesc.Query = D3D11_QUERY_OCCLUSION; queryDesc.MiscFlags = 0; // create the occlusion query const HRESULT hr = mDevice->CreateQuery(&queryDesc, mQuery.ReleaseAndGetAddressOf()); if (FAILED(hr) || mDevice.isError()) { String errorDescription = mDevice.getErrorDescription(hr); OGRE_EXCEPT_EX(Exception::ERR_INTERNAL_ERROR, hr, "Cannot allocate a Hardware query. This video card doesn't supports it, sorry.\nError Description:" + errorDescription, "D3D11HardwareOcclusionQuery::D3D11HardwareOcclusionQuery"); } } /** * Object destructor */ D3D11HardwareOcclusionQuery::~D3D11HardwareOcclusionQuery() { } //------------------------------------------------------------------ // Occlusion query functions (see base class documentation for this) //-- void D3D11HardwareOcclusionQuery::beginOcclusionQuery() { mDevice.GetImmediateContext()->Begin(mQuery.Get());//Issue(D3DISSUE_BEGIN); mIsQueryResultStillOutstanding = true; mPixelCount = 0; } void D3D11HardwareOcclusionQuery::endOcclusionQuery() { mDevice.GetImmediateContext()->End(mQuery.Get());//Issue(D3DISSUE_END); } //------------------------------------------------------------------ bool D3D11HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments ) { // in case you didn't check if query arrived and want the result now. if (mIsQueryResultStillOutstanding) { // Loop until the data becomes available UINT64 pixels; const size_t dataSize = sizeof( UINT64 ); while (1) { const HRESULT hr = mDevice.GetImmediateContext()->GetData(mQuery.Get(), (void *)&pixels, dataSize, 0);//D3DGETDATA_FLUSH if (hr == S_FALSE) continue; if (hr == S_OK) { mPixelCount = (unsigned)pixels; *NumOfFragments = (unsigned)pixels; break; } //in directx10 the device will never be lost /* if (hr == D3DERR_DEVICELOST) { *NumOfFragments = 100000; mPixelCount = 100000; D3D11_QUERY_DESC queryDesc; queryDesc.Query = D3D11_QUERY_OCCLUSION; mDevice->CreateQuery(%queryDesc, mQuery.ReleaseAndGetAddressOf()); break; } */ } mIsQueryResultStillOutstanding = false; } else { // we already stored result from last frames. *NumOfFragments = mPixelCount; } return true; } //------------------------------------------------------------------ bool D3D11HardwareOcclusionQuery::isStillOutstanding(void) { // in case you already asked for this query if (!mIsQueryResultStillOutstanding) return false; UINT64 pixels; const HRESULT hr = mDevice.GetImmediateContext()->GetData(mQuery.Get(), (void *) &pixels, sizeof( UINT64 ), 0); if (hr == S_FALSE) return true; /* if (hr == D3DERR_DEVICELOST) { mPixelCount = 100000; D3D11_QUERY_DESC queryDesc; queryDesc.Query = D3D11_QUERY_OCCLUSION; mDevice->CreateQuery(&queryDesc, mQuery.ReleaseAndGetAddressOf()); } */ mPixelCount = (unsigned)pixels; mIsQueryResultStillOutstanding = false; return false; } }
GDevs/mission-farpoint
ogre/RenderSystems/Direct3D11/src/OgreD3D11HardwareOcclusionQuery.cpp
C++
gpl-3.0
5,755
<?php /* * This file is part of Phraseanet * * (c) 2005-2016 Alchemy * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Alchemy\Phrasea\Application; class module_report_download extends module_report { protected $cor_query = [ 'user' => 'log.user', 'site' => 'log.site', 'societe' => 'log.societe', 'pays' => 'log.pays', 'activite' => 'log.activite', 'fonction' => 'log.fonction', 'usrid' => 'log.usrid', 'ddate' => "log_docs.date", 'id' => 'log_docs.id', 'log_id' => 'log_docs.log_id', 'record_id' => 'log_docs.record_id', 'final' => 'log_docs.final', 'comment' => 'log_docs.comment' ]; /** * constructor * * @param Application $app * @param string $arg1 start date of the report * @param string $arg2 end date of the report * @param integer $sbas_id id of the databox * @param string $collist */ public function __construct(Application $app, $arg1, $arg2, $sbas_id, $collist) { parent::__construct($app, $arg1, $arg2, $sbas_id, ''); $this->title = $this->app->trans('report:: telechargements'); } /** * @desc build the specified requete * @param $obj $conn the current connection to databox * @return string */ protected function buildReq($groupby = false, $on = false) { $this->setDateField('log_docs.date'); // no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n\n", __FILE__, __LINE__), FILE_APPEND); $sql = $this->sqlBuilder('download') ->setOn($on)->setGroupBy($groupby)->buildSql(); // no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n\n", __FILE__, __LINE__), FILE_APPEND); $this->req = $sql->getSql(); $this->params = $sql->getParams(); $this->total = $sql->getTotalRows(); } public function colFilter($field, $on = false) { $ret = []; $sqlBuilder = $this->sqlBuilder('download'); $var = $sqlBuilder->sqlDistinctValByField($field); $sql = $var['sql']; $params = $var['params']; $stmt = $sqlBuilder->getConnBas()->prepare($sql); $stmt->execute($params); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); foreach ($rs as $row) { $value = $row['val']; if ($field == 'coll_id') { $caption = phrasea::bas_labels(phrasea::baseFromColl($this->sbas_id, $value, $this->app), $this->app); } elseif ($field == 'ddate') $caption = $this->app['date-formatter']->getPrettyString(new DateTime($value)); elseif ($field == 'size') $caption = p4string::format_octets($value); else $caption = $value; $ret[] = ['val' => $caption, 'value' => $value]; } return $ret; } /** * @desc build the result from the specified sql * @param array $champ all the field from the request displayed in a array * @param string $sql the request from buildreq * @return $this->result */ protected function buildResult(Application $app, $rs) { $i = 0; $pref = parent::getPreff($app, $this->sbas_id); //// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s) %s\n\n", __FILE__, __LINE__, var_export($rs, true)), FILE_APPEND); foreach ($rs as $row) { if ($this->enable_limit && ($i > $this->nb_record)) break; foreach ($this->champ as $column) { $this->formatResult($column, $row[$column], $i); } if (array_key_exists('record_id', $row)) { //// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s) %s\n\n", __FILE__, __LINE__, $row['record_id']), FILE_APPEND); try { $record = new \record_adapter($app, $this->sbas_id, $row['record_id']); $caption = $record->get_caption(); foreach ($pref as $field) { //// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s) %s\n\n", __FILE__, __LINE__, $field), FILE_APPEND); try { $this->result[$i][$field] = $caption ->get_field($field) ->get_serialized_values(); } catch (\Exception $e) { $this->result[$i][$field] = ''; } } } catch (\Exception_Record_AdapterNotFound $e) { foreach ($pref as $field) { $this->result[$i][$field] = ''; } } } $i ++; //// no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n\n", __FILE__, __LINE__), FILE_APPEND); } } private function formatResult($column, $value, $i) { if ($value) { if ($column == 'coll_id') $this->result[$i][$column] = $this->formatCollId($value); elseif ($column == 'ddate') $this->result[$i][$column] = $this->formatDateValue($value); elseif ($column == 'size') $this->result[$i][$column] = p4string::format_octets($value); else $this->result[$i][$column] = $value; } else { if ($column == 'comment') $this->result[$i][$column] = ''; else $this->result[$i][$column] = $this->formatEmptyValue(); } } private function formatEmptyValue() { return '<i>' . $this->app->trans('report:: non-renseigne') . '</i>'; } private function formatDateValue($value) { $datetime = new DateTime($value); $dateString = $datetime->format(DATE_ATOM); return $this->pretty_string ? $this->app['date-formatter']->getPrettyString($datetime) : $dateString; } private function formatCollId($value) { return phrasea::bas_labels(phrasea::baseFromColl($this->sbas_id, $value, $this->app), $this->app); } public static function getNbDl(Application $app, $dmin, $dmax, $sbas_id, $list_coll_id) { $databox = $app->findDataboxById($sbas_id); $conn = $databox->get_connection(); $params = [':site_id' => $app['conf']->get(['main', 'key'])]; $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax); $params = array_merge($params, $datefilter['params']); $finalfilter = $datefilter['sql'] . ' AND '; $finalfilter .= 'log.site = :site_id'; /* $sql = ' SELECT SUM(1) AS nb FROM ( SELECT DISTINCT(log.id) FROM log FORCE INDEX (date_site) INNER JOIN log_colls FORCE INDEX (couple) ON (log.id = log_colls.log_id) INNER JOIN log_docs as log_date ON (log.id = log_date.log_id) WHERE ' . $finalfilter . ' AND ( log_date.action = \'download\' OR log_date.action = \'mail\' ) ) AS tt '; */ $sql = "SELECT SUM(1) AS nb\n" . " FROM (\n" . " SELECT DISTINCT(log.id)\n" . " FROM log FORCE INDEX (date_site)" . " INNER JOIN log_docs" . " WHERE " . $finalfilter . "\n" . " AND ( log_docs.action = 'download' OR log_docs.action = 'mail' )\n" . " ) AS tt"; // no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND); $stmt = $conn->prepare($sql); $stmt->execute($params); $row = $stmt->fetch(PDO::FETCH_ASSOC); $stmt->closeCursor(); return $row ? $row['nb'] : 0; } public static function getTopDl(Application $app, $dmin, $dmax, $sbas_id, $list_coll_id) { $databox = $app->findDataboxById((int) $sbas_id); $conn = $databox->get_connection(); $params = [':site_id' => $app['conf']->get(['main', 'key'])]; $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax); $params = array_merge($params, $datefilter['params']); $finalfilter = ""; $array = [ 'preview' => [], 'document' => [] ]; $finalfilter .= $datefilter['sql'] . ' AND '; $finalfilter .= 'log.site = :site_id'; /* $sql = ' SELECT tt.id, tt.name, SUM(1) AS nb FROM ( SELECT DISTINCT(log.id) AS log_id, log_date.record_id as id, subdef.name FROM ( log ) INNER JOIN log_colls FORCE INDEX (couple) ON (log.id = log_colls.log_id) INNER JOIN log_docs as log_date ON (log.id = log_date.log_id) INNER JOIN subdef ON (log_date.record_id = subdef.record_id) WHERE ( ' . $finalfilter . ' ) AND ( log_date.action = \'download\' OR log_date.action = \'mail\' ) AND subdef.name = log_date.final ) AS tt GROUP BY id, name '; */ $sql = "SELECT tt.id, tt.name, SUM(1) AS nb\n" . " FROM (\n" . " SELECT DISTINCT(log.id) AS log_id, log_docs.record_id as id, subdef.name\n" . " FROM ( log )\n" . " INNER JOIN log_docs ON (log.id = log_docs.log_id)\n" . " INNER JOIN subdef ON (log_docs.record_id = subdef.record_id)\n" . " WHERE (" . $finalfilter . ")\n" . " AND ( log_docs.action = 'download' OR log_docs.action = 'mail' )\n" . " AND subdef.name = log_docs.final\n" . " ) AS tt\n" . " GROUP BY id, name\n"; // no_file_put_contents("/tmp/report.txt", sprintf("%s (%s)\n%s\n\n", __FILE__, __LINE__, $sql), FILE_APPEND); $stmt = $conn->prepare($sql); $stmt->execute($params); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); foreach ($rs as $row) { $record = $databox->get_record($row['id']); $k = $row['id'] . '_' . $sbas_id; $orig_name = $record->get_original_name(); if ($row['name'] == 'document') { $array[$row['name']][$k]['nb'] = (int) $row['nb']; $array[$row['name']][$k]['lib'] = $orig_name; $array[$row['name']][$k]['sbasid'] = $sbas_id; $array[$row['name']][$k]['id'] = $row['id']; } elseif ($row['name'] == "preview") { $array[$row['name']][$k]['nb'] = (int) $row['nb']; $array[$row['name']][$k]['lib'] = $orig_name; $array[$row['name']][$k]['sbasid'] = $sbas_id; $array[$row['name']][$k]['id'] = $row['id']; } } return $array; } }
nmaillat/Phraseanet
lib/classes/module/report/download.php
PHP
gpl-3.0
11,258
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="refresh" content="0;URL=constant._SC_TRACE_INHERIT.html"> </head> <body> <p>Redirecting to <a href="constant._SC_TRACE_INHERIT.html">constant._SC_TRACE_INHERIT.html</a>...</p> <script>location.replace("constant._SC_TRACE_INHERIT.html" + location.search + location.hash);</script> </body> </html>
surrsurus/edgequest
doc/libc/unix/notbsd/linux/_SC_TRACE_INHERIT.v.html
HTML
mpl-2.0
365
class AddRatingAndCategoryToAccounts < ActiveRecord::Migration def self.up add_column :accounts, :rating, :integer, :default => 0, :null => false add_column :accounts, :category, :string, :limit => 32 end def self.down remove_column :accounts, :category remove_column :accounts, :rating end end
chondm/FatFreeCRM
db/migrate/20101221345678_add_rating_and_category_to_accounts.rb
Ruby
agpl-3.0
320
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program 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. # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from openerp.osv import fields, osv class hr_employee(osv.osv): _name = "hr.employee" _description = "Employee" _inherit = "hr.employee" def _get_latest_contract(self, cr, uid, ids, field_name, args, context=None): res = {} obj_contract = self.pool.get('hr.contract') for emp in self.browse(cr, uid, ids, context=context): contract_ids = obj_contract.search(cr, uid, [('employee_id','=',emp.id),], order='date_start', context=context) if contract_ids: res[emp.id] = contract_ids[-1:][0] else: res[emp.id] = False return res _columns = { 'manager': fields.boolean('Is a Manager'), 'medic_exam': fields.date('Medical Examination Date'), 'place_of_birth': fields.char('Place of Birth', size=30), 'children': fields.integer('Number of Children'), 'vehicle': fields.char('Company Vehicle', size=64), 'vehicle_distance': fields.integer('Home-Work Dist.', help="In kilometers"), 'contract_ids': fields.one2many('hr.contract', 'employee_id', 'Contracts'), 'contract_id':fields.function(_get_latest_contract, string='Contract', type='many2one', relation="hr.contract", help='Latest contract of the employee'), } class hr_contract_type(osv.osv): _name = 'hr.contract.type' _description = 'Contract Type' _columns = { 'name': fields.char('Contract Type', size=32, required=True), } class hr_contract(osv.osv): _name = 'hr.contract' _description = 'Contract' _columns = { 'name': fields.char('Contract Reference', size=64, required=True), 'employee_id': fields.many2one('hr.employee', "Employee", required=True), 'department_id': fields.related('employee_id','department_id', type='many2one', relation='hr.department', string="Department", readonly=True), 'type_id': fields.many2one('hr.contract.type', "Contract Type", required=True), 'job_id': fields.many2one('hr.job', 'Job Title'), 'date_start': fields.date('Start Date', required=True), 'date_end': fields.date('End Date'), 'trial_date_start': fields.date('Trial Start Date'), 'trial_date_end': fields.date('Trial End Date'), 'working_hours': fields.many2one('resource.calendar','Working Schedule'), 'wage': fields.float('Wage', digits=(16,2), required=True, help="Basic Salary of the employee"), 'advantages': fields.text('Advantages'), 'notes': fields.text('Notes'), 'permit_no': fields.char('Work Permit No', size=256, required=False, readonly=False), 'visa_no': fields.char('Visa No', size=64, required=False, readonly=False), 'visa_expire': fields.date('Visa Expire Date'), } def _get_type(self, cr, uid, context=None): type_ids = self.pool.get('hr.contract.type').search(cr, uid, [('name', '=', 'Employee')]) return type_ids and type_ids[0] or False _defaults = { 'date_start': lambda *a: time.strftime("%Y-%m-%d"), 'type_id': _get_type } def onchange_employee_id(self, cr, uid, ids, employee_id, context=None): if not employee_id: return {'value': {'job_id': False}} emp_obj = self.pool.get('hr.employee').browse(cr, uid, employee_id, context=context) job_id = False if emp_obj.job_id: job_id = emp_obj.job_id.id return {'value': {'job_id': job_id}} def _check_dates(self, cr, uid, ids, context=None): for contract in self.read(cr, uid, ids, ['date_start', 'date_end'], context=context): if contract['date_start'] and contract['date_end'] and contract['date_start'] > contract['date_end']: return False return True _constraints = [ (_check_dates, 'Error! Contract start-date must be less than contract end-date.', ['date_start', 'date_end']) ] # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
jmesteve/saas3
openerp/addons/hr_contract/hr_contract.py
Python
agpl-3.0
4,997
-- DB update 2021_06_18_17 -> 2021_06_18_18 DROP PROCEDURE IF EXISTS `updateDb`; DELIMITER // CREATE PROCEDURE updateDb () proc:BEGIN DECLARE OK VARCHAR(100) DEFAULT 'FALSE'; SELECT COUNT(*) INTO @COLEXISTS FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'version_db_world' AND COLUMN_NAME = '2021_06_18_17'; IF @COLEXISTS = 0 THEN LEAVE proc; END IF; START TRANSACTION; ALTER TABLE version_db_world CHANGE COLUMN 2021_06_18_17 2021_06_18_18 bit; SELECT sql_rev INTO OK FROM version_db_world WHERE sql_rev = '1623952547067832000'; IF OK <> 'FALSE' THEN LEAVE proc; END IF; -- -- START UPDATING QUERIES -- INSERT INTO `version_db_world` (`sql_rev`) VALUES ('1623952547067832000'); -- note: this is not ideal, it should be instead: -- - an INSERT IGNORE containing the default DBC values -- - and an UPDATE containing only the change -- but the original author is gone and I do not know what fields are changing, so I'll leave it as it is DELETE FROM `spell_dbc` WHERE (`ID` = 4511); INSERT INTO `spell_dbc` VALUES (4511, 0, 0, 0, 301989888, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 10000, 0, 0, 4, 0, 0, 101, 0, 0, 12, 12, 21, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 6, 0, 0, 1, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 72, 0, 211, 122, 0, 'Phase Shift','','','','','','','','', 0, 0, 0, 0, 0, 0, 0, 16712190,'','','','','','','','','', 0, 0, 0, 0, 0, 0, 0, 16712190, 'Shifts the imp out of phase with the world, making it unattackable unless it attacks.', null, null, null, null, null, null, null, null, 0, 0, 0, 0, 0, 0, 0, 16712190, 'Unattackable.','','','','','','','','', 0, 0, 0, 0, 0, 0, 0, 16712190, 0, 133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0); UPDATE `creature_template` SET `faction` = 73, `type_flags` = 4096, `ScriptName` = '' WHERE (`entry` = 416); -- -- END UPDATING QUERIES -- UPDATE version_db_world SET date = '2021_06_18_18' WHERE sql_rev = '1623952547067832000'; COMMIT; END // DELIMITER ; CALL updateDb(); DROP PROCEDURE IF EXISTS `updateDb`;
ShinDarth/azerothcore-wotlk
data/sql/archive/db_world/4.x/2021_06_18_18.sql
SQL
agpl-3.0
2,258
/** * Copyright (C) 2009-2013 FoundationDB, LLC * * This program 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. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.foundationdb.ais.model; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.foundationdb.ais.model.validation.AISInvariants; public class Group extends HasStorage implements Visitable { public static Group create(AkibanInformationSchema ais, String schemaName, String rootTableName) { ais.checkMutability(); AISInvariants.checkNullName(schemaName, "Group", "schemaName"); AISInvariants.checkNullName(rootTableName, "Group", "rootTableName"); TableName groupName = new TableName(schemaName, rootTableName); AISInvariants.checkDuplicateGroups(ais, groupName); Group group = new Group(groupName); ais.addGroup(group); return group; } private Group(TableName name) { this.name = name; this.indexMap = new HashMap<>(); } public TableName getName() { return name; } public String getDescription() { return name.toString(); } public void setRootTable(Table rootTable) { this.rootTable = rootTable; } public Table getRoot() { return rootTable; } public Collection<GroupIndex> getIndexes() { return Collections.unmodifiableCollection(internalGetIndexMap().values()); } public GroupIndex getIndex(String indexName) { return internalGetIndexMap().get(indexName); } public void addIndex(GroupIndex index) { indexMap.put(index.getIndexName().getName(), index); GroupIndexHelper.actOnGroupIndexTables(index, GroupIndexHelper.ADD); } public void removeIndexes(Collection<GroupIndex> indexesToDrop) { indexMap.values().removeAll(indexesToDrop); for (GroupIndex groupIndex : indexesToDrop) { GroupIndexHelper.actOnGroupIndexTables(groupIndex, GroupIndexHelper.REMOVE); } } private Map<String, GroupIndex> internalGetIndexMap() { return indexMap; } public boolean isVirtual() { return (storageDescription != null) && storageDescription.isVirtual(); } // HasStorage @Override public AkibanInformationSchema getAIS() { return rootTable.getAIS(); } @Override public String getTypeString() { return "Group"; } @Override public String getNameString() { return name.toString(); } @Override public String getSchemaName() { return (rootTable != null) ? rootTable.getName().getSchemaName() : null; } // Visitable /** Visit this instance, the root table and then all group indexes. */ @Override public void visit(Visitor visitor) { visitor.visit(this); rootTable.visit(visitor); for(Index i : getIndexes()) { i.visit(visitor); } } // State private final TableName name; private final Map<String, GroupIndex> indexMap; private Table rootTable; }
wfxiang08/sql-layer-1
fdb-sql-layer-core/src/main/java/com/foundationdb/ais/model/Group.java
Java
agpl-3.0
3,742
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program 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. # //# # //# 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 Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.admin.domain; // Generated from form domain impl public interface Service extends ims.domain.DomainInterface { // Generated from form domain interface definition /** * list services */ public ims.core.vo.ServiceVoCollection listService(ims.core.vo.ServiceShortVo filter); // Generated from form domain interface definition /** * save a service and associated functions/activities */ public ims.core.vo.ServiceVo saveService(ims.core.vo.ServiceVo voService) throws ims.domain.exceptions.StaleObjectException, ims.domain.exceptions.UniqueKeyViolationException; // Generated from form domain interface definition /** * list activities for a service */ public ims.core.vo.ServiceActivityVoCollection listServiceActivity(ims.core.vo.ServiceShortVo voService); // Generated from form domain interface definition /** * list functions for an activity */ public ims.core.vo.ServiceFunctionVoCollection listServiceFunction(ims.core.vo.ServiceShortVo voService); // Generated from form domain interface definition /** * save service functions */ public ims.core.vo.ServiceFunctionVoCollection saveServiceFunction(ims.core.vo.ServiceFunctionVoCollection vocollServiceFunction, ims.core.vo.ServiceFunctionVoCollection voCollServiceFunctionDelete) throws ims.domain.exceptions.StaleObjectException, ims.domain.exceptions.ForeignKeyViolationException, ims.domain.exceptions.UniqueKeyViolationException; // Generated from form domain interface definition /** * remove a service function */ public void removeServiceFunction(ims.core.vo.ServiceFunctionVo voServiceFunction) throws ims.domain.exceptions.StaleObjectException, ims.domain.exceptions.ForeignKeyViolationException, ims.domain.exceptions.UniqueKeyViolationException; // Generated from form domain interface definition /** * list all active services into a specalitylistvo collection */ public ims.core.vo.SpecialtyListVoCollection listService(Boolean bActive); // Generated from form domain interface definition /** * list all services in supplied int array */ public ims.core.vo.ServiceVoCollection listService(Integer[] nServiceIds); // Generated from form domain interface definition /** * list activity */ public ims.core.vo.ActivityVoCollection listActivity(String nameFilter, ims.core.vo.lookups.ActivityType activityType, Boolean bActive) throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition /** * save service activity associations */ public ims.core.vo.ServiceActivityVoCollection saveServiceActivity(ims.core.vo.ServiceActivityVoCollection voCollServiceActivity, ims.core.vo.ServiceActivityVoCollection voCollServiceActivityDelete) throws ims.domain.exceptions.DomainInterfaceException, ims.domain.exceptions.StaleObjectException, ims.domain.exceptions.ForeignKeyViolationException, ims.domain.exceptions.UniqueKeyViolationException; // Generated from form domain interface definition public void removeServiceActivity(ims.core.vo.ServiceActivityVo voServiceActivity) throws ims.domain.exceptions.StaleObjectException, ims.domain.exceptions.ForeignKeyViolationException, ims.domain.exceptions.UniqueKeyViolationException; // Generated from form domain interface definition public ims.core.vo.ServiceActivityVo getServiceActivity(ims.core.clinical.vo.ServiceRefVo serviceRefVo, ims.core.resource.place.vo.ActivityRefVo activityRefVo); // Generated from form domain interface definition public String checkLSALinks(ims.core.vo.ServiceActivityVo voServiceActivity) throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition /** * Get a ProceduteVo for an ActivityVo */ public ims.core.vo.ProcedureVo getProcedureForActivity(ims.core.resource.place.vo.ActivityRefVo activityRefVo); // Generated from form domain interface definition /** * isServiceActivityUnique */ public String isServiceActivityUnique(ims.core.vo.TaxonomyMapCollection map, ims.core.vo.ServiceVo voService); // Generated from form domain interface definition public ims.core.vo.ServiceVo getServiceById(ims.core.vo.ServiceVo voService); // Generated from form domain interface definition /** * listActiveServiceLiteByName */ public ims.core.vo.ServiceLiteVoCollection listActiveServiceLiteByNameAndCategories(String name, ims.core.vo.lookups.ServiceCategoryCollection categoryCollection); // Generated from form domain interface definition /** * listActiveServiceLiteByName */ public ims.core.vo.ServiceLiteVoCollection listActiveServiceLiteByName(String name); // Generated from form domain interface definition /** * list services */ public ims.core.vo.ServiceLiteVoCollection listServiceLite(ims.core.vo.ServiceShortVo filter); }
open-health-hub/openMAXIMS
openmaxims_workspace/Admin/src/ims/admin/domain/Service.java
Java
agpl-3.0
6,438
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program 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. # //# # //# 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 Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.spinalinjuries.vo.lookups; import ims.framework.cn.data.TreeNode; import java.util.ArrayList; import ims.framework.utils.Image; import ims.framework.utils.Color; public class TENSArea extends ims.vo.LookupInstVo implements TreeNode { private static final long serialVersionUID = 1L; public TENSArea() { super(); } public TENSArea(int id) { super(id, "", true); } public TENSArea(int id, String text, boolean active) { super(id, text, active, null, null, null); } public TENSArea(int id, String text, boolean active, TENSArea parent, Image image) { super(id, text, active, parent, image); } public TENSArea(int id, String text, boolean active, TENSArea parent, Image image, Color color) { super(id, text, active, parent, image, color); } public TENSArea(int id, String text, boolean active, TENSArea parent, Image image, Color color, int order) { super(id, text, active, parent, image, color, order); } public static TENSArea buildLookup(ims.vo.LookupInstanceBean bean) { return new TENSArea(bean.getId(), bean.getText(), bean.isActive()); } public String toString() { if(getText() != null) return getText(); return ""; } public TreeNode getParentNode() { return (TENSArea)super.getParentInstance(); } public TENSArea getParent() { return (TENSArea)super.getParentInstance(); } public void setParent(TENSArea parent) { super.setParentInstance(parent); } public TreeNode[] getChildren() { ArrayList children = super.getChildInstances(); TENSArea[] typedChildren = new TENSArea[children.size()]; for (int i = 0; i < children.size(); i++) { typedChildren[i] = (TENSArea)children.get(i); } return typedChildren; } public int addChild(TreeNode child) { if (child instanceof TENSArea) { super.addChild((TENSArea)child); } return super.getChildInstances().size(); } public int removeChild(TreeNode child) { if (child instanceof TENSArea) { super.removeChild((TENSArea)child); } return super.getChildInstances().size(); } public Image getExpandedImage() { return super.getImage(); } public Image getCollapsedImage() { return super.getImage(); } public static ims.framework.IItemCollection getNegativeInstancesAsIItemCollection() { TENSAreaCollection result = new TENSAreaCollection(); return result; } public static TENSArea[] getNegativeInstances() { return new TENSArea[] {}; } public static String[] getNegativeInstanceNames() { return new String[] {}; } public static TENSArea getNegativeInstance(String name) { if(name == null) return null; // No negative instances found return null; } public static TENSArea getNegativeInstance(Integer id) { if(id == null) return null; // No negative instances found return null; } public int getTypeId() { return TYPE_ID; } public static final int TYPE_ID = 1051034; }
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/spinalinjuries/vo/lookups/TENSArea.java
Java
agpl-3.0
4,553
/**************************************************************** * * * Copyright 2001, 2007 Fidelity Information Services, Inc * * * * This source code contains the intellectual property * * of its copyright holder(s), and is made available * * under a license. If you do not know the terms of * * the license, please stop and do not read further. * * * ****************************************************************/ #include "mdef.h" #include "gdsroot.h" #include "gdskill.h" #include "gvcst_kill_sort.h" #define S_CUTOFF 15 void gvcst_kill_sort(kill_set *k) { block_id_ptr_t stack[50],*sp; block_id v,t; block_id_ptr_t l,r; block_id_ptr_t ix,jx,kx; assert(k->used <= BLKS_IN_KILL_SET); sp = stack; l = (block_id_ptr_t)(k->blk); r = l + k->used-1; for (;;) if (r - l < S_CUTOFF) { for (ix = l + 1 ; ix <= r ; ix++) { for (jx = ix , t = *ix; jx > l && *(jx-1) > t; jx--) *jx = *(jx - 1); *jx = t; } if (sp <= stack) break; else { l = *--sp; r = *--sp; } } else { ix = l; jx = r; kx = l + ((int)(r - l) / 2); kx = (*ix > *jx) ? ((*jx > *kx) ? jx: ((*ix > *kx) ? kx : ix)): ((*jx < *kx) ? jx: ((*ix > *kx) ? ix : kx)); t = *kx; *kx = *jx; *jx = t; ix--; do { do ix++; while (*ix < t); do jx--; while (*jx > t); v = *ix; *ix = *jx; *jx = v; } while (jx > ix); *jx = *ix; *ix = *r; *r = v; if (ix - l > r - ix) { *sp++ = ix - 1; *sp++ = l; l = ix + 1; } else { *sp++ = r; *sp++ = ix + 1; r = ix - 1; } } return; }
CoherentLogic/fis-gtm-netbsd
sr_port/gvcst_kill_sort.c
C
agpl-3.0
1,653
""" Stub implementation of LTI Provider. What is supported: ------------------ 1.) This LTI Provider can service only one Tool Consumer at the same time. It is not possible to have this LTI multiple times on a single page in LMS. """ from uuid import uuid4 import textwrap import urllib import re from oauthlib.oauth1.rfc5849 import signature, parameters import oauthlib.oauth1 import hashlib import base64 import mock import requests from http import StubHttpRequestHandler, StubHttpService class StubLtiHandler(StubHttpRequestHandler): """ A handler for LTI POST and GET requests. """ DEFAULT_CLIENT_KEY = 'test_client_key' DEFAULT_CLIENT_SECRET = 'test_client_secret' DEFAULT_LTI_ENDPOINT = 'correct_lti_endpoint' DEFAULT_LTI_ADDRESS = 'http://127.0.0.1:{port}/' def do_GET(self): """ Handle a GET request from the client and sends response back. Used for checking LTI Provider started correctly. """ self.send_response(200, 'This is LTI Provider.', {'Content-type': 'text/plain'}) def do_POST(self): """ Handle a POST request from the client and sends response back. """ if 'grade' in self.path and self._send_graded_result().status_code == 200: status_message = 'LTI consumer (edX) responded with XML content:<br>' + self.server.grade_data['TC answer'] content = self._create_content(status_message) self.send_response(200, content) elif 'lti2_outcome' in self.path and self._send_lti2_outcome().status_code == 200: status_message = 'LTI consumer (edX) responded with HTTP {}<br>'.format( self.server.grade_data['status_code']) content = self._create_content(status_message) self.send_response(200, content) elif 'lti2_delete' in self.path and self._send_lti2_delete().status_code == 200: status_message = 'LTI consumer (edX) responded with HTTP {}<br>'.format( self.server.grade_data['status_code']) content = self._create_content(status_message) self.send_response(200, content) # Respond to request with correct lti endpoint elif self._is_correct_lti_request(): params = {k: v for k, v in self.post_dict.items() if k != 'oauth_signature'} if self._check_oauth_signature(params, self.post_dict.get('oauth_signature', "")): status_message = "This is LTI tool. Success." # Set data for grades what need to be stored as server data if 'lis_outcome_service_url' in self.post_dict: self.server.grade_data = { 'callback_url': self.post_dict.get('lis_outcome_service_url').replace('https', 'http'), 'sourcedId': self.post_dict.get('lis_result_sourcedid') } submit_url = '//{}:{}'.format(*self.server.server_address) content = self._create_content(status_message, submit_url) self.send_response(200, content) else: content = self._create_content("Wrong LTI signature") self.send_response(200, content) else: content = self._create_content("Invalid request URL") self.send_response(500, content) def _send_graded_result(self): """ Send grade request. """ values = { 'textString': 0.5, 'sourcedId': self.server.grade_data['sourcedId'], 'imsx_messageIdentifier': uuid4().hex, } payload = textwrap.dedent(""" <?xml version = "1.0" encoding = "UTF-8"?> <imsx_POXEnvelopeRequest xmlns="http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0"> <imsx_POXHeader> <imsx_POXRequestHeaderInfo> <imsx_version>V1.0</imsx_version> <imsx_messageIdentifier>{imsx_messageIdentifier}</imsx_messageIdentifier> / </imsx_POXRequestHeaderInfo> </imsx_POXHeader> <imsx_POXBody> <replaceResultRequest> <resultRecord> <sourcedGUID> <sourcedId>{sourcedId}</sourcedId> </sourcedGUID> <result> <resultScore> <language>en-us</language> <textString>{textString}</textString> </resultScore> </result> </resultRecord> </replaceResultRequest> </imsx_POXBody> </imsx_POXEnvelopeRequest> """) data = payload.format(**values) url = self.server.grade_data['callback_url'] headers = { 'Content-Type': 'application/xml', 'X-Requested-With': 'XMLHttpRequest', 'Authorization': self._oauth_sign(url, data) } # Send request ignoring verifirecation of SSL certificate response = requests.post(url, data=data, headers=headers, verify=False) self.server.grade_data['TC answer'] = response.content return response def _send_lti2_outcome(self): """ Send a grade back to consumer """ payload = textwrap.dedent(""" {{ "@context" : "http://purl.imsglobal.org/ctx/lis/v2/Result", "@type" : "Result", "resultScore" : {score}, "comment" : "This is awesome." }} """) data = payload.format(score=0.8) return self._send_lti2(data) def _send_lti2_delete(self): """ Send a delete back to consumer """ payload = textwrap.dedent(""" { "@context" : "http://purl.imsglobal.org/ctx/lis/v2/Result", "@type" : "Result" } """) return self._send_lti2(payload) def _send_lti2(self, payload): """ Send lti2 json result service request. """ ### We compute the LTI V2.0 service endpoint from the callback_url (which is set by the launch call) url = self.server.grade_data['callback_url'] url_parts = url.split('/') url_parts[-1] = "lti_2_0_result_rest_handler" anon_id = self.server.grade_data['sourcedId'].split(":")[-1] url_parts.extend(["user", anon_id]) new_url = '/'.join(url_parts) content_type = 'application/vnd.ims.lis.v2.result+json' headers = { 'Content-Type': content_type, 'Authorization': self._oauth_sign(new_url, payload, method='PUT', content_type=content_type) } # Send request ignoring verifirecation of SSL certificate response = requests.put(new_url, data=payload, headers=headers, verify=False) self.server.grade_data['status_code'] = response.status_code self.server.grade_data['TC answer'] = response.content return response def _create_content(self, response_text, submit_url=None): """ Return content (str) either for launch, send grade or get result from TC. """ if submit_url: submit_form = textwrap.dedent(""" <form action="{submit_url}/grade" method="post"> <input type="submit" name="submit-button" value="Submit"> </form> <form action="{submit_url}/lti2_outcome" method="post"> <input type="submit" name="submit-lti2-button" value="Submit"> </form> <form action="{submit_url}/lti2_delete" method="post"> <input type="submit" name="submit-lti2-delete-button" value="Submit"> </form> """).format(submit_url=submit_url) else: submit_form = '' # Show roles only for LTI launch. if self.post_dict.get('roles'): role = '<h5>Role: {}</h5>'.format(self.post_dict['roles']) else: role = '' response_str = textwrap.dedent(""" <html> <head> <title>TEST TITLE</title> </head> <body> <div> <h2>IFrame loaded</h2> <h3>Server response is:</h3> <h3 class="result">{response}</h3> {role} </div> {submit_form} </body> </html> """).format(response=response_text, role=role, submit_form=submit_form) # Currently LTI module doublequotes the lis_result_sourcedid parameter. # Unquote response two times. return urllib.unquote(urllib.unquote(response_str)) def _is_correct_lti_request(self): """ Return a boolean indicating whether the URL path is a valid LTI end-point. """ lti_endpoint = self.server.config.get('lti_endpoint', self.DEFAULT_LTI_ENDPOINT) return lti_endpoint in self.path def _oauth_sign(self, url, body, content_type=u'application/x-www-form-urlencoded', method=u'POST'): """ Signs request and returns signed Authorization header. """ client_key = self.server.config.get('client_key', self.DEFAULT_CLIENT_KEY) client_secret = self.server.config.get('client_secret', self.DEFAULT_CLIENT_SECRET) client = oauthlib.oauth1.Client( client_key=unicode(client_key), client_secret=unicode(client_secret) ) headers = { # This is needed for body encoding: 'Content-Type': content_type, } # Calculate and encode body hash. See http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html sha1 = hashlib.sha1() sha1.update(body) oauth_body_hash = unicode(base64.b64encode(sha1.digest())) # pylint: disable=too-many-function-args params = client.get_oauth_params(None) params.append((u'oauth_body_hash', oauth_body_hash)) mock_request = mock.Mock( uri=unicode(urllib.unquote(url)), headers=headers, body=u"", decoded_body=u"", oauth_params=params, http_method=unicode(method), ) sig = client.get_oauth_signature(mock_request) mock_request.oauth_params.append((u'oauth_signature', sig)) new_headers = parameters.prepare_headers(mock_request.oauth_params, headers, realm=None) return new_headers['Authorization'] def _check_oauth_signature(self, params, client_signature): """ Checks oauth signature from client. `params` are params from post request except signature, `client_signature` is signature from request. Builds mocked request and verifies hmac-sha1 signing:: 1. builds string to sign from `params`, `url` and `http_method`. 2. signs it with `client_secret` which comes from server settings. 3. obtains signature after sign and then compares it with request.signature (request signature comes form client in request) Returns `True` if signatures are correct, otherwise `False`. """ client_secret = unicode(self.server.config.get('client_secret', self.DEFAULT_CLIENT_SECRET)) port = self.server.server_address[1] lti_base = self.DEFAULT_LTI_ADDRESS.format(port=port) lti_endpoint = self.server.config.get('lti_endpoint', self.DEFAULT_LTI_ENDPOINT) url = lti_base + lti_endpoint request = mock.Mock() request.params = [(unicode(k), unicode(v)) for k, v in params.items()] request.uri = unicode(url) request.http_method = u'POST' request.signature = unicode(client_signature) return signature.verify_hmac_sha1(request, client_secret) class StubLtiService(StubHttpService): """ A stub LTI provider server that responds to POST and GET requests to localhost. """ HANDLER_CLASS = StubLtiHandler
wwj718/ANALYSE
common/djangoapps/terrain/stubs/lti.py
Python
agpl-3.0
12,436
# -*- coding: utf-8 -*- import json import re import unicodedata import string from urllib import urlencode from requests import get languages = {'de', 'en', 'es', 'fr', 'hu', 'it', 'nl', 'jp'} url_template = 'https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&{query}&props=labels%7Cdatatype%7Cclaims%7Caliases&languages=' + '|'.join(languages) url_wmflabs_template = 'http://wdq.wmflabs.org/api?q=' url_wikidata_search_template='http://www.wikidata.org/w/api.php?action=query&list=search&format=json&srnamespace=0&srprop=sectiontitle&{query}' wmflabs_queries = [ 'CLAIM[31:8142]', # all devise ] db = { 'iso4217' : { }, 'names' : { } } def remove_accents(data): return unicodedata.normalize('NFKD', data).lower() def normalize_name(name): return re.sub(' +',' ', remove_accents(name.lower()).replace('-', ' ')) def add_currency_name(name, iso4217): global db db_names = db['names'] if not isinstance(iso4217, basestring): print "problem", name, iso4217 return name = normalize_name(name) if name == '': print "name empty", iso4217 return iso4217_set = db_names.get(name, None) if iso4217_set is not None and iso4217 not in iso4217_set: db_names[name].append(iso4217) else: db_names[name] = [ iso4217 ] def add_currency_label(label, iso4217, language): global db db['iso4217'][iso4217] = db['iso4217'].get(iso4217, {}) db['iso4217'][iso4217][language] = label def get_property_value(data, name): prop = data.get('claims', {}).get(name, {}) if len(prop) == 0: return None value = prop[0].get('mainsnak', {}).get('datavalue', {}).get('value', '') if value == '': return None return value def parse_currency(data): iso4217 = get_property_value(data, 'P498') if iso4217 is not None: unit = get_property_value(data, 'P558') if unit is not None: add_currency_name(unit, iso4217) labels = data.get('labels', {}) for language in languages: name = labels.get(language, {}).get('value', None) if name != None: add_currency_name(name, iso4217) add_currency_label(name, iso4217, language) aliases = data.get('aliases', {}) for language in aliases: for i in range(0, len(aliases[language])): alias = aliases[language][i].get('value', None) add_currency_name(alias, iso4217) def fetch_data(wikidata_ids): url = url_template.format(query=urlencode({'ids' : '|'.join(wikidata_ids)})) htmlresponse = get(url) jsonresponse = json.loads(htmlresponse.content) entities = jsonresponse.get('entities', {}) for pname in entities: pvalue = entities.get(pname) parse_currency(pvalue) def add_q(i): return "Q" + str(i) def fetch_data_batch(wikidata_ids): while len(wikidata_ids) > 0: if len(wikidata_ids) > 50: fetch_data(wikidata_ids[0:49]) wikidata_ids = wikidata_ids[50:] else: fetch_data(wikidata_ids) wikidata_ids = [] def wdq_query(query): url = url_wmflabs_template + query htmlresponse = get(url) jsonresponse = json.loads(htmlresponse.content) qlist = map(add_q, jsonresponse.get('items', {})) error = jsonresponse.get('status', {}).get('error', None) if error != None and error != 'OK': print "error for query '" + query + "' :" + error fetch_data_batch(qlist) def wd_query(query, offset=0): qlist = [] url = url_wikidata_search_template.format(query=urlencode({'srsearch': query, 'srlimit': 50, 'sroffset': offset})) htmlresponse = get(url) jsonresponse = json.loads(htmlresponse.content) for r in jsonresponse.get('query', {}).get('search', {}): qlist.append(r.get('title', '')) fetch_data_batch(qlist) ## fetch ## for q in wmflabs_queries: wdq_query(q) # static add_currency_name(u"euro", 'EUR') add_currency_name(u"euros", 'EUR') add_currency_name(u"dollar", 'USD') add_currency_name(u"dollars", 'USD') add_currency_name(u"peso", 'MXN') add_currency_name(u"pesos", 'MXN') # write f = open("currencies.json", "wb") json.dump(db, f, indent=4, encoding="utf-8") f.close()
kdani3/searx
utils/fetch_currencies.py
Python
agpl-3.0
4,394
<html> <head> <title>e2guardian - Äîñòóï çàïðåù¸í</title> <meta content="text/html; charset=windows-1251" http-equiv=Content-Type> </head> <body bgcolor=#FFFFFF> <center> <table border=0 cellspacing=0 cellpadding=2 height=540 width=700> <tr> <td colspan=2 bgcolor=#FEA700 height=100 align=center> <font face=arial,helvetica size=6> <b>Äîñòóï çàïðåù¸í!</b> </td> </tr> <tr> <td colspan=2 bgcolor=#FFFACD height=30 align=right> <font face=arial,helvetica size=3 color=black> <b>-USER-&nbsp;</b> </td> </tr> <tr> <td align=center valign=bottom width=150 bgcolor=#B0C4DE> <font face=arial,helvetica size=1 color=black> Âàøà îðãàíèçàöèÿ </td> <td width=550 bgcolor=#FFFFFF align=center valign=center> <font face=arial,helvetica color=black> <font size=4> Äîñòóï ê èíòåðíåò ðåñóðñó: <br><br> <a href="-URL-" target="_blank">-URL-</a> <br><br> <font size=3> ... çàïðåù¸í ïî ñëåäóþùèì ïðè÷èíàì: <br><br> <font color=red> <b>-REASONGIVEN-</b> <font color=black> <br><br><br><br> Âû âèäèòå ýòó îøèáêó, ïîòîìó ÷òî, ñäåëàëè ïîïûòêó äîñòóïà ê ðåñóðñó ñîäåðæàùåìó èëè ïîìå÷åíîìó êàê ñîäåðæàùèé, ìàòåðèàë, êîòîðûé ñ÷èòàåòñÿ íåñîîòâåòñòâóþùèì èëè èíôèöèðîâàííûì âèðóñàìè. <br><br> Åñëè ó Âàñ åñòü âîïðîñû îáðàòèòåñü ê ñèñòåìíîìó àäìèíèñòðàòîðó ñåòè âàøåé îðãàíèçàöèè . <br><br><br><br> <font size=1> èçãîòîâèòåëü<a href="http://www.e2guardian.org?block" target="_blank">e2guardian</a> </td> </tr> </table> </body> </html> <!-- Äîñòóïíû ñëåäóþùèå ïåðåìåííûå: - URL- ñîäåðæèò URL çàïðàøèâàåìûé ïîëüçîâàòåëåì. - REASONGIVEN- ñîäåðæèò ïðè÷èíó (íå öèòèðóåò çàïðåùåííóþ ôðàçó). - REASONLOGGED- ñîäåðæèò ïðè÷èíó, çàïèñûâàåìóþ â log, âêëþ÷àÿ ïîëíûå ïîäðîáíîñòè. - USER- ñîäåðæèò èìÿ ïîëüçîâàòåëÿ åñëè èçâåñòíî. - IP- ñîäåðæèò òåêóùèé IP. - FILTERGROUP- ñîäåðæèò íîìåð ãðóïïû. - BYPASS- ñîäåðæèò URL ïîçâîëèâøèé âðåìåííûé îáõîä îòêëîíåííîé ñòðàíèöû Âû äîëæíû óñòðàíèòü ïðîáåë ìåæäó "-" è ïåðåìåííîé äëÿ èñïîëüçîâàíèÿ èõ â Âàøåì HTML. Êàê âèäíî âûøå íèêàêîé äîïîëíèòåëüíîé îáðàáîòêè áîëüøå íå òðåáóåòñÿ. Áîëüøå ïðèìåðîâ ìîæíî íàéòè íà ñàéòå e2guardian íà ñòðàíèöå äîïîëíåíèé. This page was designed by Shipitsin Igor. shipitsin@rduorel.ru -->
the-linux-schools-project/karoshi-server
serversetup/modules/squid/e2guardian/languages/russian-1251/template.html
HTML
agpl-3.0
2,174
package tick import ( "bytes" "github.com/influxdata/kapacitor/tick/ast" ) // Formats a TICKscript according to the standard. func Format(script string) (string, error) { root, err := ast.Parse(script) if err != nil { return "", err } var buf bytes.Buffer buf.Grow(len(script)) root.Format(&buf, "", false) return buf.String(), nil }
brianbaker/chronograf
vendor/github.com/influxdata/kapacitor/tick/fmt.go
GO
agpl-3.0
348
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program 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. # //# # //# 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 Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Cornel Ventuneac using IMS Development Environment (version 1.80 build 4471.18200) // Copyright (C) 1995-2012 IMS MAXIMS. All rights reserved. package ims.emergency.forms.systemreview; import ims.clinical.configuration.vo.ClinicalProblemRefVo; import ims.clinical.vo.lookups.BodySystemCollection; import ims.configuration.gen.ConfigFlag; import ims.core.admin.vo.CareContextRefVo; import ims.core.admin.vo.EpisodeOfCareRefVo; import ims.core.patient.vo.PatientRefVo; import ims.domain.exceptions.StaleObjectException; import ims.domain.exceptions.UnqViolationUncheckedException; import ims.emergency.forms.systemreview.GenForm.grdSystemReviewRow; import ims.emergency.vo.SystemReviewForPresentingProblemConfigVo; import ims.emergency.vo.SystemReviewVo; import ims.emergency.vo.SystemReviewVoCollection; import ims.emergency.vo.enums.EdAssessment_CustomControlsEvents; import ims.framework.enumerations.DialogResult; import ims.framework.enumerations.FormMode; import ims.framework.exceptions.PresentationLogicException; public class Logic extends BaseLogic { private static final long serialVersionUID = 1L; public void initialize(CareContextRefVo careContextRef, EpisodeOfCareRefVo episodeRef, PatientRefVo patientRef, ClinicalProblemRefVo problemRef) { form.getLocalContext().setCareContextRef(careContextRef); form.getLocalContext().setEpisodeOfCareRef(episodeRef); form.getLocalContext().setPatientRef(patientRef); form.getLocalContext().setClinicalProblemRef(problemRef); form.getLocalContext().setSelectedSystemReview(null); open(); updateControlsState(); } private void open() { clear(); SystemReviewVoCollection tempColl = domain.listSystemReview(form.getLocalContext().getCareContextRef()); if( tempColl != null && tempColl.size() > 0) { populateGrid(tempColl); } if( form.getLocalContext().getSelectedSystemReviewIsNotNull()) { form.getLocalContext().setSelectedSystemReview(domain.getSystemReview(form.getLocalContext().getSelectedSystemReview())); form.grdSystemReview().setValue(form.getLocalContext().getSelectedSystemReview()); } } private void populateGrid(SystemReviewVoCollection tempColl) { form.grdSystemReview().getRows().clear(); StringBuffer tooltip = new StringBuffer(); if( tempColl != null && tempColl.size() > 0) { for(int i = 0; i < tempColl.size();i++) { if( tempColl.get(i) != null) { grdSystemReviewRow row = form.grdSystemReview().getRows().newRow(); //WDEV-17118 if (Boolean.TRUE.equals(tempColl.get(i).getIsCorrected())) row.setBackColor(ConfigFlag.UI.CORRECTION_ROW_COLOUR.getValue()); if (Boolean.TRUE.equals(tempColl.get(i).getIsCorrected())) { row.setColumnSystemReview(tempColl.get(i).getSystemsIsNotNull() ? "<s>" + tempColl.get(i).getSystems().getText() + "</s>":""); } else row.setColumnSystemReview(tempColl.get(i).getSystemsIsNotNull() ? tempColl.get(i).getSystems().getText():""); tooltip.delete(0, tooltip.length()); tooltip.append(tempColl.get(i).getSystemsIsNotNull() ? tempColl.get(i).getSystems().getText():""); if (Boolean.TRUE.equals(tempColl.get(i).getIsCorrected()) && tempColl.get(i).getCorrectedAuthoringInformation() != null) { tooltip.append("<br><b>Correction HCP: </b>" + tempColl.get(i).getCorrectedAuthoringInformation().getAuthoringHcp()); tooltip.append("<br><b>Corrected Date/Time: </b>" + tempColl.get(i).getCorrectedAuthoringInformation().getAuthoringDateTime()); tooltip.append(tempColl.get(i).getCorrectionCommentsIsNotNull() ? "<br><b>Correction comments: </b>" + tempColl.get(i).getCorrectionComments(): "<br><b>No Comments</b>"); } row.setTooltipForColumnSystemReview(tooltip.toString()); if (Boolean.TRUE.equals(tempColl.get(i).getIsCorrected())) { row.setColumnAuthoringHCP(tempColl.get(i).getAuthoringInformationIsNotNull() && tempColl.get(i).getAuthoringInformation().getAuthoringHcp() != null ? "<s>" + tempColl.get(i).getAuthoringInformation().getAuthoringHcp().toString() + "</s>":""); } else row.setColumnAuthoringHCP(tempColl.get(i).getAuthoringInformationIsNotNull() && tempColl.get(i).getAuthoringInformation().getAuthoringHcp() != null ? tempColl.get(i).getAuthoringInformation().getAuthoringHcp().toString():""); tooltip.delete(0, tooltip.length()); tooltip.append(tempColl.get(i).getAuthoringInformationIsNotNull() && tempColl.get(i).getAuthoringInformation().getAuthoringHcp() != null ? tempColl.get(i).getAuthoringInformation().getAuthoringHcp().toString():""); if (Boolean.TRUE.equals(tempColl.get(i).getIsCorrected()) && tempColl.get(i).getCorrectedAuthoringInformation() != null) { tooltip.append("<br><b>Correction HCP: </b>" + tempColl.get(i).getCorrectedAuthoringInformation().getAuthoringHcp()); tooltip.append("<br><b>Corrected Date/Time: </b>" + tempColl.get(i).getCorrectedAuthoringInformation().getAuthoringDateTime()); tooltip.append(tempColl.get(i).getCorrectionCommentsIsNotNull() ? "<br><b>Correction comments: </b>" + tempColl.get(i).getCorrectionComments(): "<br><b>No Comments</b>"); } row.setTooltipForColumnAuthoringHCP(tooltip.toString()); if (Boolean.TRUE.equals(tempColl.get(i).getIsCorrected())) { row.setColumnAuthoringDateTime(tempColl.get(i).getAuthoringInformationIsNotNull() && tempColl.get(i).getAuthoringInformation().getAuthoringDateTimeIsNotNull() ? "<s>" + tempColl.get(i).getAuthoringInformation().getAuthoringDateTime().toString() + "</s>":""); } else row.setColumnAuthoringDateTime(tempColl.get(i).getAuthoringInformationIsNotNull() && tempColl.get(i).getAuthoringInformation().getAuthoringDateTimeIsNotNull() ? tempColl.get(i).getAuthoringInformation().getAuthoringDateTime().toString():""); tooltip.delete(0, tooltip.length()); tooltip.append(tempColl.get(i).getAuthoringInformationIsNotNull() && tempColl.get(i).getAuthoringInformation().getAuthoringDateTimeIsNotNull() ? tempColl.get(i).getAuthoringInformation().getAuthoringDateTime().toString():""); if (Boolean.TRUE.equals(tempColl.get(i).getIsCorrected()) && tempColl.get(i).getCorrectedAuthoringInformation() != null) { tooltip.append("<br><b>Correction HCP: </b>" + tempColl.get(i).getCorrectedAuthoringInformation().getAuthoringHcp()); tooltip.append("<br><b>Corrected Date/Time: </b>" + tempColl.get(i).getCorrectedAuthoringInformation().getAuthoringDateTime()); tooltip.append(tempColl.get(i).getCorrectionCommentsIsNotNull() ? "<br><b>Correction comments: </b>" + tempColl.get(i).getCorrectionComments(): "<br><b>No Comments</b>"); } row.setTooltipForColumnAuthoringDateTime(tooltip.toString()); row.setColumnNote(Boolean.TRUE.equals(tempColl.get(i).getIsCorrected()) ? "<s>" + tempColl.get(i).getSystemReviewNote() + "</s>" : tempColl.get(i).getSystemReviewNote()); tooltip.delete(0, tooltip.length()); tooltip.append(tempColl.get(i).getSystemReviewNote()); if (Boolean.TRUE.equals(tempColl.get(i).getIsCorrected()) && tempColl.get(i).getCorrectedAuthoringInformation() != null) { tooltip.append("<br><b>Correction HCP: </b>" + tempColl.get(i).getCorrectedAuthoringInformation().getAuthoringHcp()); tooltip.append("<br><b>Corrected Date/Time: </b>" + tempColl.get(i).getCorrectedAuthoringInformation().getAuthoringDateTime()); tooltip.append(tempColl.get(i).getCorrectionCommentsIsNotNull() ? "<br><b>Correction comments: </b>" + tempColl.get(i).getCorrectionComments(): "<br><b>No Comments</b>"); } row.setTooltipForColumnNote(tooltip.toString()); row.setValue(tempColl.get(i)); } } } } private void clear() { form.grdSystemReview().getRows().clear(); } protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException { // TODO Add your code here. } protected void onFormDialogClosed(ims.framework.FormName formName, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException { if (formName.equals(form.getForms().Emergency.SystemsReviewDialog) && result.equals(DialogResult.OK)) { if (form.getGlobalContext().Emergency.getAddEditForSystemsReviewDlg() == null || Boolean.FALSE.equals(form.getGlobalContext().Emergency.getAddEditForSystemsReviewDlg())) //add mode { form.getLocalContext().setSelectedSystemReview(null); } open(); } //WDEV-17118 if (formName.equals(form.getForms().Emergency.SystemReviewNotesDialog) || formName.equals(form.getForms().Emergency.NoteCorrectionDialog)) { open(); } if (formName.equals(form.getForms().Core.RieConfirmationDialog) && DialogResult.OK.equals(result)) { doRIE(); } //WDEV-17337 form.getLocalContext().setSelectedEvent(EdAssessment_CustomControlsEvents.SAVE); form.fireCustomControlValueChanged(); updateControlsState(); } private void doRIE() { if( form.getLocalContext().getSelectedSystemReviewIsNotNull() ) { try { domain.markAsRie(form.getLocalContext().getSelectedSystemReview(), form.getForms().Emergency.SystemReview, form.getGlobalContext().Core.getPatientShort().getID_Patient(), null, form.getGlobalContext().Core.getCurrentCareContextIsNotNull() ? form.getGlobalContext().Core.getCurrentCareContext().getID_CareContext():null, form.getGlobalContext().Core.getRieMessage()); } catch (StaleObjectException e) { engine.showErrors(new String[]{ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue()}); } catch (UnqViolationUncheckedException e) { engine.showErrors(new String[]{ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue()}); } form.getLocalContext().setSelectedSystemReview(null); } open(); } protected void onBtnRieClick() throws ims.framework.exceptions.PresentationLogicException { if(form.getLocalContext().getSelectedSystemReview() == null) return; engine.open(form.getForms().Core.RieConfirmationDialog); } protected void onBtnNewClick() throws ims.framework.exceptions.PresentationLogicException { //form.getGlobalContext().Emergency.setAddEditForSystemsReviewDlg(Boolean.FALSE); //WDEV-17118 SystemReviewVoCollection currentActiveNotes = domain.getAllActiveSystemNotes(form.getLocalContext().getCareContextRef()); SystemReviewForPresentingProblemConfigVo systemsReviewForproblem = domain.getSystemReviewForPresentingProblem(form.getLocalContext().getClinicalProblemRef()); BodySystemCollection newSystems = getSystemsForCreation(currentActiveNotes, systemsReviewForproblem); SystemReviewVoCollection newSystemReviewColl = new SystemReviewVoCollection(); for (int i = 0; i < newSystems.size(); i++) { SystemReviewVo tempVo = new SystemReviewVo(); tempVo.setPatient(form.getLocalContext().getPatientRef()); tempVo.setAttendance(form.getLocalContext().getCareContextRef()); tempVo.setEpisode(form.getLocalContext().getEpisodeOfCareRef()); tempVo.setSystems(newSystems.get(i)); newSystemReviewColl.add(tempVo); } //engine.open(form.getForms().Emergency.SystemsReviewDialog, new Object[]{tempVo, form.getLocalContext().getClinicalProblemRef()}); if (newSystemReviewColl.size() == 0) { engine.showMessage(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue()); open(); updateControlsState(); return; } form.getGlobalContext().Emergency.setSystemReviewCollection(newSystemReviewColl); engine.open(form.getForms().Emergency.SystemReviewNotesDialog); } private BodySystemCollection getSystemsForCreation(SystemReviewVoCollection currentActiveNotes, SystemReviewForPresentingProblemConfigVo systemsReviewForproblem) { if (systemsReviewForproblem == null) return null; BodySystemCollection systemCollection = systemsReviewForproblem.getSystem(); if (currentActiveNotes == null) { return systemsReviewForproblem.getSystem(); } if (systemsReviewForproblem.getSystem() != null && systemsReviewForproblem.getSystem().size() > 0 && currentActiveNotes.size() > 0) { for (int i = 0; i < currentActiveNotes.size(); i++) { if (systemsReviewForproblem.getSystem().contains(currentActiveNotes.get(i).getSystems())) { systemCollection.remove(currentActiveNotes.get(i).getSystems()); } } } return systemCollection; } protected void onGrdSystemReviewSelectionChanged() { if(form.grdSystemReview().getSelectedRow() != null) { form.getLocalContext().setSelectedSystemReview(domain.getSystemReview(form.grdSystemReview().getSelectedRow().getValue())); form.getGlobalContext().Emergency.setSystemReview(form.getLocalContext().getSelectedSystemReview()); } else form.getLocalContext().setSelectedSystemReview(null); updateControlsState(); } private void updateControlsState() { //WDEV-17337 SystemReviewVoCollection currentActiveNotes =null; if (form.getLocalContext().getCareContextRef()!=null) currentActiveNotes= domain.getAllActiveSystemNotes(form.getLocalContext().getCareContextRef()); Boolean isEnable = Boolean.TRUE.equals(form.getLocalContext().getisEnabled()); //WDEV-17118 form.btnNew().setEnabled(form.getMode().equals(FormMode.VIEW) && isEnable && checkIsEnabled(currentActiveNotes)); form.btnNew().setText(currentActiveNotes != null ? "Edit review" :"New review"); form.btnCorrect().setEnabled(form.getMode().equals(FormMode.VIEW) && form.getLocalContext().getSelectedSystemReviewIsNotNull() && (! Boolean.TRUE.equals(form.getLocalContext().getSelectedSystemReview().getIsCorrected())) && isEnable); form.btnRie().setEnabled(form.getMode().equals(FormMode.VIEW) && form.getLocalContext().getSelectedSystemReviewIsNotNull() && isEnable); } //WDEV-17118 private Boolean checkIsEnabled(SystemReviewVoCollection currentActiveNotes) { SystemReviewForPresentingProblemConfigVo systemsReviewForProblem = null; Boolean isOk = Boolean.FALSE; if (form.getLocalContext().getClinicalProblemRef() != null) { systemsReviewForProblem = domain.getSystemReviewForPresentingProblem(form.getLocalContext().getClinicalProblemRef()); } if (currentActiveNotes == null && systemsReviewForProblem != null && systemsReviewForProblem.getSystem() != null && systemsReviewForProblem.getSystem().size() > 0) { isOk = Boolean.TRUE; } else if (currentActiveNotes != null && systemsReviewForProblem != null && systemsReviewForProblem.getSystem() != null) { if (currentActiveNotes.size() != systemsReviewForProblem.getSystem().size() && systemsReviewForProblem.getSystem().size() > currentActiveNotes.size()) { isOk = Boolean.TRUE; } else { BodySystemCollection clone = (BodySystemCollection) systemsReviewForProblem.getSystem().clone(); for (int x = 0; x < currentActiveNotes.size(); x++) { for (int y = 0; y < systemsReviewForProblem.getSystem().size(); y++) { if (currentActiveNotes.get(x).getSystems().equals(systemsReviewForProblem.getSystem().get(y))) { clone.remove(systemsReviewForProblem.getSystem().get(y)); } } } isOk = (clone.size() > 0); } } return isOk; } public void setEnabled(Boolean value) { form.getLocalContext().setisEnabled(value); updateControlsState(); } //WDEV-17118 protected void onBtnCorrectClick() throws PresentationLogicException { engine.open(form.getForms().Emergency.NoteCorrectionDialog); } //WDEV-17337 public EdAssessment_CustomControlsEvents getSelectedEvent() { return form.getLocalContext().getSelectedEvent(); } //WDEV-17337 public void resetSelectedEvent() { form.getLocalContext().setSelectedEvent(null); } }
open-health-hub/openMAXIMS
openmaxims_workspace/Emergency/src/ims/emergency/forms/systemreview/Logic.java
Java
agpl-3.0
17,364
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program 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. # //# # //# 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 Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Peter Martin using IMS Development Environment (version 1.43 build 2232.25589) // Copyright (C) 1995-2006 IMS MAXIMS plc. All rights reserved. package ims.therapies.domain.impl; import java.util.ArrayList; import java.util.List; import ims.admin.domain.HcpAdmin; import ims.admin.domain.impl.HcpAdminImpl; import ims.core.admin.vo.CareContextRefVo; import ims.core.vo.ClinicalContactShortVoCollection; import ims.core.vo.Hcp; import ims.core.vo.HcpCollection; import ims.core.vo.domain.ClinicalContactShortVoAssembler; import ims.domain.DomainFactory; import ims.domain.exceptions.DomainRuntimeException; import ims.domain.exceptions.StaleObjectException; import ims.domain.exceptions.UniqueKeyViolationException; import ims.therapies.domain.base.impl.BaseWheelchairAssessmentImpl; import ims.therapies.mobilitytransfers.domain.objects.WheelchairAssessment; import ims.therapies.vo.WheelchairAssessmentVo; import ims.therapies.vo.WheelchairAssessmentVoCollection; import ims.therapies.vo.domain.WheelchairAssessmentVoAssembler; public class WheelchairAssessmentImpl extends BaseWheelchairAssessmentImpl { private static final long serialVersionUID = 1L; public WheelchairAssessmentVo saveWheelchairAssessment(WheelchairAssessmentVo wheelchairAssessment) throws StaleObjectException, UniqueKeyViolationException { DomainFactory factory = getDomainFactory(); if (!wheelchairAssessment.isValidated()) { throw new DomainRuntimeException("This WheelchairAssessmentVo has not been validated"); } if (wheelchairAssessment.getID_WheelchairAssessment() == null)//Inserting a record { WheelchairAssessmentVoCollection voWA = getWheelchairAssessment(wheelchairAssessment.getClinicalContact().getID_ClinicalContact()); //wdev-13410 WheelchairAssessmentVo tempVo = null; //wdev-13410 if(voWA != null && voWA.size() > 0) //wdev-13410 { tempVo = voWA.get(0); } else { tempVo = null; } if(tempVo != null ) throw new UniqueKeyViolationException("A record exists for this clinical contact, the screen will be refreshed"); } WheelchairAssessment domWheelchairAssessment = WheelchairAssessmentVoAssembler.extractWheelchairAssessment(factory, wheelchairAssessment); factory.save(domWheelchairAssessment); return WheelchairAssessmentVoAssembler.create(domWheelchairAssessment); } //wdev-13410 public WheelchairAssessmentVoCollection getWheelchairAssessment(Integer contactId) { DomainFactory factory = getDomainFactory(); StringBuffer hql = new StringBuffer(" "); String query = "from WheelchairAssessment w "; ArrayList markers = new ArrayList(); ArrayList values = new ArrayList(); String andStr = " "; if (contactId != null) { hql.append(andStr + " w.clinicalContact.id = :id_ClinicalContact order by w.id desc"); //wdev-13410 markers.add("id_ClinicalContact"); values.add(contactId); andStr = " and "; } if (markers.size() > 0) query += " where "; query += hql.toString(); List assessments = factory.find(query, markers, values); WheelchairAssessmentVoCollection collHomeVisitVo = WheelchairAssessmentVoAssembler.createWheelchairAssessmentVoCollectionFromWheelchairAssessment(assessments); //if(collHomeVisitVo!=null && collHomeVisitVo.size()>0) return collHomeVisitVo; //wdev-13410 //return collHomeVisitVo.get(0); //return null; } public HcpCollection listHcps(Hcp filter) { HcpAdmin hcpAdmin = (HcpAdmin) getDomainImpl(HcpAdminImpl.class); return hcpAdmin.listHCPs(filter); } public ClinicalContactShortVoCollection listClinicalContactsByCareContext(CareContextRefVo refCareContext) { DomainFactory factory = getDomainFactory(); StringBuffer hql = new StringBuffer(" "); String query = "from ClinicalContact cc "; ArrayList markers = new ArrayList(); ArrayList values = new ArrayList(); String andStr = " "; if (refCareContext != null) { hql.append(andStr + " cc.careContext.id = :id_CareContext"); markers.add("id_CareContext"); values.add(refCareContext.getID_CareContext()); andStr = " and "; } if (markers.size() > 0) query += " where "; query += hql.toString(); List contacts = factory.find(query, markers, values); return ClinicalContactShortVoAssembler.createClinicalContactShortVoCollectionFromClinicalContact(contacts); } }
open-health-hub/openMAXIMS
openmaxims_workspace/Therapies/src/ims/therapies/domain/impl/WheelchairAssessmentImpl.java
Java
agpl-3.0
5,828
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program 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. # //# # //# 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 Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinical.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; /** * Linked to clinical.SurgicalOperationDetails business object (ID: 1072100085). */ public class SurgicalOperationDetailsRefVoCollection extends ims.vo.ValueObjectCollection implements ims.domain.IDomainCollectionGetter, ims.vo.ImsCloneable, Iterable<SurgicalOperationDetailsRefVo> { private static final long serialVersionUID = 1L; private ArrayList<SurgicalOperationDetailsRefVo> col = new ArrayList<SurgicalOperationDetailsRefVo>(); public final String getBoClassName() { return "ims.clinical.domain.objects.SurgicalOperationDetails"; } public ims.domain.IDomainGetter[] getIDomainGetterItems() { ims.domain.IDomainGetter[] result = new ims.domain.IDomainGetter[col.size()]; col.toArray(result); return result; } public boolean add(SurgicalOperationDetailsRefVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, SurgicalOperationDetailsRefVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(SurgicalOperationDetailsRefVo instance) { return col.indexOf(instance); } public SurgicalOperationDetailsRefVo get(int index) { return this.col.get(index); } public boolean set(int index, SurgicalOperationDetailsRefVo value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(SurgicalOperationDetailsRefVo instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(SurgicalOperationDetailsRefVo instance) { return indexOf(instance) >= 0; } public Object clone() { SurgicalOperationDetailsRefVoCollection clone = new SurgicalOperationDetailsRefVoCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((SurgicalOperationDetailsRefVo)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { return true; } public String[] validate() { return null; } public SurgicalOperationDetailsRefVo[] toArray() { SurgicalOperationDetailsRefVo[] arr = new SurgicalOperationDetailsRefVo[col.size()]; col.toArray(arr); return arr; } public SurgicalOperationDetailsRefVoCollection sort() { return sort(SortOrder.ASCENDING); } public SurgicalOperationDetailsRefVoCollection sort(SortOrder order) { return sort(new SurgicalOperationDetailsRefVoComparator(order)); } @SuppressWarnings("unchecked") public SurgicalOperationDetailsRefVoCollection sort(Comparator comparator) { Collections.sort(this.col, comparator); return this; } public Iterator<SurgicalOperationDetailsRefVo> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class SurgicalOperationDetailsRefVoComparator implements Comparator { private int direction = 1; public SurgicalOperationDetailsRefVoComparator() { this(SortOrder.ASCENDING); } public SurgicalOperationDetailsRefVoComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { this.direction = -1; } } public int compare(Object obj1, Object obj2) { SurgicalOperationDetailsRefVo voObj1 = (SurgicalOperationDetailsRefVo)obj1; SurgicalOperationDetailsRefVo voObj2 = (SurgicalOperationDetailsRefVo)obj2; return direction*(voObj1.compareTo(voObj2)); } } }
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/clinical/vo/SurgicalOperationDetailsRefVoCollection.java
Java
agpl-3.0
5,572
/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero 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 Affero General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef WMOROOT_H #define WMOROOT_H #include <string> #include <vector> #include "ChunkedData.h" #include "Utils.h" #include "WorldModelGroup.h" class WorldModelRoot { public: WorldModelRoot(std::string path); ~WorldModelRoot(); std::string Path; ChunkedData* Data; WorldModelHeader Header; std::vector<DoodadInstance> DoodadInstances; std::vector<DoodadSet> DoodadSets; std::vector<WorldModelGroup> Groups; private: void ReadGroups(); void ReadDoodadSets(); void ReadDoodadInstances(); void ReadHeader(); }; #endif
ShinDarth/azerothcore-wotlk
src/tools/mesh_extractor/WorldModelRoot.h
C
agpl-3.0
1,327
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2012-2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 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.topology.ssh.internal.gwt.client.ui; import com.vaadin.client.ApplicationConnection; import com.vaadin.client.Paintable; import com.vaadin.client.UIDL; /** * The VTerminal class is associated with the GwtTerminal widget and handles all of the communication * from the client and sends it to the server. It also listens for responses from the server and * updates the client side view. * @author Leonardo Bell * @author Philip Grenon */ public class VTerminal extends GwtTerminal implements Paintable { String uidlId; //Component identifier in UIDL communications. ApplicationConnection client; //Reference to the server connection object. private TermHandler termHandler; //Key handler for VT100 codes private boolean isClosed; //Lets the server know the status of the Handler private boolean isFocused; //Lets the server know whether the widget is focused /** * The VTerminal() constructor creates a GwtTerminal Widget and assigns the TermHandler * to each of its key handlers and initializes the status of the Terminal */ public VTerminal() { super(); termHandler = new TermHandler(this); addKeyDownHandler(termHandler); addKeyPressHandler(termHandler); addKeyUpHandler(termHandler); isClosed = false; isFocused = false; } /** * The update method is used by the server whenever it requests an update from * the TermHandler in order to receive the current key presses from the client. */ public void update() { termHandler.update(); } /** * The updateFromUIDL method handles all communication from the server and passes * the data along to the GwtTerminal widget which updates the client side view. */ @Override public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { // This call should be made first. Ensure correct implementation, // and let the containing layout manage caption, etc. if (client.updateComponent(this, uidl, true)) { return; } // Save reference to server connection object to be able to send // user interaction later this.client = client; // Save the UIDL identifier for the component this.uidlId = uidl.getId(); // Check if the server wants the TermHandler to close, if so, send a // response back to the server that it was closed successfully if (uidl.getBooleanVariable("closeClient")) { termHandler.close(); isClosed = true; sendBytes(""); } // Check if the server wants the TermHandler to update manually if (uidl.getBooleanVariable("update")) update(); if (uidl.getBooleanVariable("focus")) { super.focus(); isFocused = true; } // Take the current representation of the Terminal from the server // and set the Inner HTML of the widget dump(uidl.getStringVariable("fromSSH")); } public void sendBytes(String inputKeys){ // Send the server the current state of the TermHandler client.updateVariable(uidlId, "isClosed", isClosed, true); // Send the server the current KeyBuffer from the client if (!isClosed) { client.updateVariable(uidlId, "toSSH", inputKeys, true); } // Tell the server if the widget is focused or not client.updateVariable(uidlId, "isFocused", isFocused, true); } }
roskens/opennms-pre-github
features/topology-map/plugins/org.opennms.features.topology.plugins.ssh/src/main/java/org/opennms/features/topology/ssh/internal/gwt/client/ui/VTerminal.java
Java
agpl-3.0
4,438
# Copyright (C) 2015 The Debsources developers <info@sources.debian.net>. # See the AUTHORS file at the top-level directory of this distribution and at # https://anonscm.debian.org/gitweb/?p=qa/debsources.git;a=blob;f=AUTHORS;hb=HEAD # # This file is part of Debsources. Debsources 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. For more information # see the COPYING file at the top-level directory of this distribution and at # https://anonscm.debian.org/gitweb/?p=qa/debsources.git;a=blob;f=COPYING;hb=HEAD from __future__ import absolute_import from flask import Blueprint # naming rule: bp_{dirname} bp_sources = Blueprint('sources', __name__, template_folder='templates', static_url_path='/static/sources', static_folder='static') from . import routes # NOQA
vivekanand1101/debsources
debsources/app/sources/__init__.py
Python
agpl-3.0
1,057
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2013 VillageReach * * This program 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. *   * 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ package org.openlmis.pageobjects; import org.openlmis.UiUtils.TestWebDriver; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import java.awt.*; import java.awt.event.KeyEvent; import static org.openqa.selenium.support.How.ID; public abstract class Page { public TestWebDriver testWebDriver; @FindBy(how = ID, using = "logout") private static WebElement logoutLink = null; protected Page(TestWebDriver driver) { this.testWebDriver = driver; } public LoginPage logout() { testWebDriver.waitForElementToBeEnabled(logoutLink); logoutLink.click(); testWebDriver.sleep(500); return new LoginPage(testWebDriver); } public void sendKeys(WebElement locator, String value) { String locatorValueAttribute = testWebDriver.getAttribute(locator, "value"); int length = locatorValueAttribute.length(); for (int i = 0; i < length; i++) { locator.sendKeys("\u0008"); } locator.sendKeys(value); } public void downloadFileWhileSaveDialogOPen(WebElement element) throws InterruptedException { try { Robot robot = new Robot(); //get the focus on the element..don't use click since it stalls the driver element.sendKeys(""); element.sendKeys(Keys.RETURN); //wait for the modal dialog to open Thread.sleep(3000); //press s key to save robot.keyPress(KeyEvent.VK_ALT); robot.keyPress(KeyEvent.VK_S); robot.keyRelease(KeyEvent.VK_S); robot.keyRelease(KeyEvent.VK_ALT); Thread.sleep(3000); } catch (AWTException e) { e.printStackTrace(); } } }
OpenLMIS/open-lmis
test-modules/functional-tests/src/main/java/org/openlmis/pageobjects/Page.java
Java
agpl-3.0
2,501
/* * This file is part of libFirm. * Copyright (C) 2012 University of Karlsruhe. */ /** * @file * @brief Performs SSA destruction. * @author Daniel Grund * @date 25.05.2005 */ #ifndef FIRM_BE_BESSADESTR_H #define FIRM_BE_BESSADESTR_H #include <stdbool.h> #include "be_types.h" #include "firm_types.h" /** * Performs SSA destruction. Arguments get adjusted, phi nodes just stay. */ void be_ssa_destruction(ir_graph *irg, const arch_register_class_t *cls); #endif
8l/libfirm
ir/be/bessadestr.h
C
lgpl-2.1
494
/* * This file was generated by qdbusxml2cpp version 0.7 * Command line was: qdbusxml2cpp -c AccountManagerProxy -p accountmanagerproxy.h:accountmanagerproxy.cpp org.freedesktop.Telepathy.AccountManager.xml org.freedesktop.Telepathy.AccountManager * * qdbusxml2cpp is Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * This is an auto-generated file. * Do not edit! All changes made to it will be lost. */ #ifndef ACCOUNTMANAGERPROXY_H_1281083196 #define ACCOUNTMANAGERPROXY_H_1281083196 #include <QtCore/QObject> #include <QtCore/QByteArray> #include <QtCore/QList> #include <QtCore/QMap> #include <QtCore/QString> #include <QtCore/QStringList> #include <QtCore/QVariant> #include <QtDBus/QtDBus> /* * Proxy class for interface org.freedesktop.Telepathy.AccountManager */ class AccountManagerProxy: public QDBusAbstractInterface { Q_OBJECT public: static inline const char *staticInterfaceName() { return "org.freedesktop.Telepathy.AccountManager"; } public: AccountManagerProxy(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent = 0); ~AccountManagerProxy(); public Q_SLOTS: // METHODS inline QDBusPendingReply<QDBusObjectPath> CreateAccount(const QString &Connection_Manager, const QString &Protocol, const QString &Display_Name, const QVariantMap &Parameters, const QVariantMap &Properties) { QList<QVariant> argumentList; argumentList << qVariantFromValue(Connection_Manager) << qVariantFromValue(Protocol) << qVariantFromValue(Display_Name) << qVariantFromValue(Parameters) << qVariantFromValue(Properties); return asyncCallWithArgumentList(QLatin1String("CreateAccount"), argumentList); } Q_SIGNALS: // SIGNALS void AccountRemoved(const QDBusObjectPath &in0); void AccountValidityChanged(const QDBusObjectPath &in0, bool in1); }; namespace org { namespace freedesktop { namespace Telepathy { typedef ::AccountManagerProxy AccountManager; } } } #endif
nevfel/qgvdial
qgv-util/accountmanagerproxy.h
C
lgpl-2.1
2,022
package org.intermine.sql.precompute; /* * Copyright (C) 2002-2017 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.sql.SQLException; import org.intermine.sql.query.Query; /** * This object is a BestQuery tracker that encloses all added queries into a surrounding query as a * subquery, and passes them onto another BestQuery tracker. * * @author Matthew Wakeling */ public class EncloseSubqueryBestQuery extends BestQuery { BestQuery bestQuery; String beginning; String end; /** * Constructor. * * @param bestQuery another BestQuery object to delegate to * @param beginning the String to add to the beginning of all queries * @param end the String to add to the end of all queries */ public EncloseSubqueryBestQuery(BestQuery bestQuery, String beginning, String end) { this.bestQuery = bestQuery; this.beginning = beginning; this.end = end; } /** * Allows a Query to be added to this tracker. * * @param q a Query to be added to the tracker * @throws BestQueryException when adding should stop * @throws SQLException if error occurs in the underlying database */ @Override public void add(Query q) throws BestQueryException, SQLException { bestQuery.add(beginning + q.getSQLString() + end); } /** * Allows a Query to be added to this tracker. * * @param q a query String to be added to the tracker * @throws BestQueryException when adding should stop * @throws SQLException if error occurs in the underlying database */ @Override public void add(String q) throws BestQueryException, SQLException { bestQuery.add(beginning + q + end); } /** * Gets the best Query found so far * * @return the best Query, or null if no Queries added to this object * @throws SQLException if error occurs in the underlying database */ @Override public Query getBestQuery() throws SQLException { return bestQuery.getBestQuery(); } /** * Gets the best query String found so far * * @return the best Query, or null if no Queries added to this object * @throws SQLException if error occurs in the underlying database */ @Override public String getBestQueryString() throws SQLException { return bestQuery.getBestQueryString(); } }
elsiklab/intermine
intermine/objectstore/main/src/org/intermine/sql/precompute/EncloseSubqueryBestQuery.java
Java
lgpl-2.1
2,636
using System; using System.Collections.Generic; using System.Linq.Expressions; using NHibernate.Impl; using NHibernate.SqlCommand; namespace NHibernate.Criterion.Lambda { public class QueryOverSubqueryPropertyBuilder<TRoot,TSubType> : QueryOverSubqueryPropertyBuilderBase<QueryOver<TRoot,TSubType>, TRoot, TSubType> { public QueryOverSubqueryPropertyBuilder() : base() { } } public class IQueryOverSubqueryPropertyBuilder<TRoot,TSubType> : QueryOverSubqueryPropertyBuilderBase<IQueryOver<TRoot,TSubType>, TRoot, TSubType> { public IQueryOverSubqueryPropertyBuilder() : base() { } } public abstract class QueryOverSubqueryPropertyBuilderBase { protected QueryOverSubqueryPropertyBuilderBase() { } internal abstract QueryOverSubqueryPropertyBuilderBase Set(object root, string path, object value); } public class QueryOverSubqueryPropertyBuilderBase<TReturn, TRoot, TSubType> : QueryOverSubqueryPropertyBuilderBase where TReturn : IQueryOver<TRoot,TSubType> { protected TReturn root; protected string path; protected object value; protected QueryOverSubqueryPropertyBuilderBase() { } internal override QueryOverSubqueryPropertyBuilderBase Set(object root, string path, object value) { this.root = (TReturn)root; this.path = path; this.value = value; return this; } private void AddSubquery<U>( Func<string, DetachedCriteria, AbstractCriterion> propertyMethod, Func<object, DetachedCriteria, AbstractCriterion> valueMethod, QueryOver<U> detachedCriteria) { if (path != null) { root.And(propertyMethod(path, detachedCriteria.DetachedCriteria)); } else { root.And(valueMethod(value, detachedCriteria.DetachedCriteria)); } } /// <summary> /// Add a property equal subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn Eq<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyEq, Subqueries.Eq, detachedCriteria); return root; } /// <summary> /// Add a property equal all subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn EqAll<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyEqAll, Subqueries.EqAll, detachedCriteria); return root; } /// <summary> /// Create a property greater than or equal subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn Ge<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyGe, Subqueries.Ge, detachedCriteria); return root; } /// <summary> /// Create a property greater than or equal all subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn GeAll<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyGeAll, Subqueries.GeAll, detachedCriteria); return root; } /// <summary> /// Create a property greater than or equal some subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn GeSome<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyGeSome, Subqueries.GeSome, detachedCriteria); return root; } /// <summary> /// Create a property greater than subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn Gt<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyGt, Subqueries.Gt, detachedCriteria); return root; } /// <summary> /// Create a property greater than all subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn GtAll<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyGtAll, Subqueries.GtAll, detachedCriteria); return root; } /// <summary> /// Create a property greater than some subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn GtSome<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyGtSome, Subqueries.GtSome, detachedCriteria); return root; } /// <summary> /// Create a property in subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn In<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyIn, Subqueries.In, detachedCriteria); return root; } /// <summary> /// Create a property less than or equal subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn Le<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyLe, Subqueries.Le, detachedCriteria); return root; } /// <summary> /// Create a property less than or equal all subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn LeAll<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyLeAll, Subqueries.LeAll, detachedCriteria); return root; } /// <summary> /// Create a property less than or equal some subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn LeSome<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyLeSome, Subqueries.LeSome, detachedCriteria); return root; } /// <summary> /// Create a property less than subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn Lt<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyLt, Subqueries.Lt, detachedCriteria); return root; } /// <summary> /// Create a property less than all subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn LtAll<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyLtAll, Subqueries.LtAll, detachedCriteria); return root; } /// <summary> /// Create a property less than some subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn LtSome<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyLtSome, Subqueries.LtSome, detachedCriteria); return root; } /// <summary> /// Create a property not equal subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn Ne<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyNe, Subqueries.Ne, detachedCriteria); return root; } /// <summary> /// Create a property not in subquery criterion /// </summary> /// <param name="detachedCriteria">detached subquery</param> public TReturn NotIn<U>(QueryOver<U> detachedCriteria) { AddSubquery(Subqueries.PropertyNotIn, Subqueries.NotIn, detachedCriteria); return root; } } }
RogerKratz/nhibernate-core
src/NHibernate/Criterion/Lambda/QueryOverSubqueryPropertyBuilder.cs
C#
lgpl-2.1
7,021
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * **/ package lucee.runtime.type.util; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import lucee.commons.collection.LinkedHashMapPro; import lucee.commons.collection.MapPro; import lucee.commons.collection.MapProWrapper; import lucee.commons.collection.SyncMap; import lucee.commons.collection.WeakHashMapPro; import lucee.commons.digest.HashUtil; import lucee.commons.lang.SizeOf; import lucee.commons.lang.StringUtil; import lucee.runtime.PageContext; import lucee.runtime.dump.DumpProperties; import lucee.runtime.dump.DumpTable; import lucee.runtime.dump.DumpUtil; import lucee.runtime.dump.SimpleDumpData; import lucee.runtime.exp.PageException; import lucee.runtime.op.Caster; import lucee.runtime.op.Duplicator; import lucee.runtime.type.Collection; import lucee.runtime.type.Collection.Key; import lucee.runtime.type.KeyImpl; import lucee.runtime.type.Struct; import lucee.runtime.type.StructImpl; import lucee.runtime.type.comparator.TextComparator; /** * */ public final class StructUtil { /** * copy data from source struct to target struct * @param source * @param target * @param overwrite overwrite data if exist in target */ public static void copy(Struct source, Struct target, boolean overwrite) { Iterator<Entry<Key, Object>> it = source.entryIterator(); Entry<Key, Object> e; while(it.hasNext()) { e = it.next(); if(overwrite || !target.containsKey(e.getKey())) target.setEL(e.getKey(),e.getValue()); } } public static lucee.runtime.type.Collection.Key[] toCollectionKeys(String[] skeys) { lucee.runtime.type.Collection.Key[] keys = new lucee.runtime.type.Collection.Key[skeys.length]; for(int i=0;i<keys.length;i++) { keys[i]=KeyImpl.init(skeys[i]); } return keys; } /** * @param sct * @return */ public static Struct duplicate(Struct sct,boolean deepCopy) { Struct rtn=new StructImpl(); //lucee.runtime.type.Collection.Key[] keys=sct.keys(); //lucee.runtime.type.Collection.Key key; Iterator<Entry<Key, Object>> it = sct.entryIterator(); Entry<Key, Object> e; while(it.hasNext()) { e=it.next(); rtn.setEL(e.getKey(),Duplicator.duplicate(e.getValue(),deepCopy)); } return rtn; } public static void putAll(Struct struct, Map map) { Iterator<Entry> it = map.entrySet().iterator(); Map.Entry entry; while(it.hasNext()) { entry= it.next(); struct.setEL(KeyImpl.toKey(entry.getKey(),null), entry.getValue()); } } public static Set<Entry<String, Object>> entrySet(Struct sct) { Iterator<Entry<Key, Object>> it = sct.entryIterator(); Entry<Key, Object> e; HashSet<Entry<String, Object>> set=new HashSet<Entry<String, Object>>(); while(it.hasNext()){ e= it.next(); set.add(new StructMapEntry(sct,e.getKey(),e.getValue())); } return set; } public static Set<String> keySet(Struct sct, boolean linked) { Iterator<Key> it = sct.keyIterator(); Set<String> set=linked?new LinkedHashSet<String>():new HashSet<String>(); while(it.hasNext()){ set.add(it.next().getString()); } return set; } public static DumpTable toDumpTable(Struct sct,String title,PageContext pageContext, int maxlevel, DumpProperties dp) { Key[] keys = order(sct,CollectionUtil.keys(sct)); DumpTable table = new DumpTable("struct","#9999ff","#ccccff","#000000");// "#9999ff","#ccccff","#000000" int maxkeys=dp.getMaxKeys(); if(maxkeys < sct.size()) { table.setComment("Entries: "+sct.size() + " (showing top " + maxkeys + ")"); } else if(sct.size()>10 && dp.getMetainfo()) { table.setComment("Entries: "+sct.size()); } // advanced /*Map<Key, FunctionLibFunction> members = MemberUtil.getMembers(pageContext, CFTypes.TYPE_STRUCT); if(members!=null) { StringBuilder sb=new StringBuilder("This Struct is supporting the following Object functions:"); Iterator<Entry<Key, FunctionLibFunction>> it = members.entrySet().iterator(); Entry<Key, FunctionLibFunction> e; while(it.hasNext()){ e = it.next(); sb.append("\n .") .append(e.getKey()) .append('('); ArrayList<FunctionLibFunctionArg> args = e.getValue().getArg(); int optionals = 0; for(int i=1;i<args.size();i++) { FunctionLibFunctionArg arg=args.get(i); if(i!=0)sb.append(", "); if(!arg.getRequired()) { sb.append("["); optionals++; } sb.append(arg.getName()); sb.append(":"); sb.append(arg.getTypeAsString()); } for(int i=0;i<optionals;i++) sb.append("]"); sb.append("):"+e.getValue().getReturnTypeAsString()); } table.setComment(sb.toString()); }*/ if(!StringUtil.isEmpty(title))table.setTitle(title); maxlevel--; int index=0; for(int i=0;i<keys.length;i++) { if(DumpUtil.keyValid(dp,maxlevel,keys[i])){ if(maxkeys<=index++)break; table.appendRow(1, new SimpleDumpData(keys[i].toString()), DumpUtil.toDumpData(sct.get(keys[i],null), pageContext,maxlevel,dp)); } } return table; } private static Key[] order(Struct sct, Key[] keys) { if(sct instanceof StructImpl && ((StructImpl)sct).getType()==Struct.TYPE_LINKED) return keys; TextComparator comp=new TextComparator(true,true); Arrays.sort(keys,comp); return keys; } /** * create a value return value out of a struct * @param sct * @return */ public static java.util.Collection<?> values(Struct sct) { ArrayList<Object> arr = new ArrayList<Object>(); //Key[] keys = sct.keys(); Iterator<Object> it = sct.valueIterator(); while(it.hasNext()) { arr.add(it.next()); } return arr; } public static Struct copyToStruct(Map map) throws PageException { Struct sct = new StructImpl(); Iterator it=map.entrySet().iterator(); Map.Entry entry; while(it.hasNext()) { entry=(Entry) it.next(); sct.setEL(Caster.toString(entry.getKey()),entry.getValue()); } return sct; } /** * return the size of given struct, size of values + keys * @param sct * @return */ public static long sizeOf(Struct sct) { Iterator<Entry<Key, Object>> it = sct.entryIterator(); Entry<Key, Object> e; long size = 0; while(it.hasNext()) { e = it.next(); size+=SizeOf.size(e.getKey()); size+=SizeOf.size(e.getValue()); } return size; } public static void setELIgnoreWhenNull(Struct sct, String key, Object value) { setELIgnoreWhenNull(sct, KeyImpl.init(key), value); } public static void setELIgnoreWhenNull(Struct sct, Collection.Key key, Object value) { if(value!=null)sct.setEL(key, value); } /** * remove every entry hat has this value * @param map * @param obj */ public static void removeValue(Map map, Object value) { Iterator it = map.entrySet().iterator(); Map.Entry entry; while(it.hasNext()){ entry=(Entry) it.next(); if(entry.getValue()==value)it.remove(); } } public static Struct merge(Struct[] scts) { Struct sct=new StructImpl(); for(int i=scts.length-1;i>=0;i--){ Iterator<Entry<Key, Object>> it = scts[i].entryIterator(); Entry<Key, Object> e; while(it.hasNext()){ e = it.next(); sct.setEL(e.getKey(), e.getValue()); } } return sct; } public static int getType(MapPro m){ if(m instanceof SyncMap) return ((SyncMap)m).getType(); if(m instanceof LinkedHashMapPro) return Struct.TYPE_LINKED; if(m instanceof WeakHashMapPro) return Struct.TYPE_WEAKED; //if(map instanceof SyncMap) return TYPE_SYNC; if(m instanceof MapProWrapper) return Struct.TYPE_SOFT; return Struct.TYPE_REGULAR; } /** * creates a hash based on the keys of the Map/Struct * @param map * @return */ public static String keyHash(Struct sct) { Key[] keys; Arrays.sort(keys=CollectionUtil.keys(sct)); StringBuilder sb=new StringBuilder(); for(int i=0;i<keys.length;i++){ sb.append(keys[i].getString()).append(';'); } return Long.toString(HashUtil.create64BitHash(sb),Character.MAX_RADIX); } }
lucee/unoffical-Lucee-no-jre
source/java/core/src/lucee/runtime/type/util/StructUtil.java
Java
lgpl-2.1
9,017
/** * Copyright (c) 2014, Oracle and/or its affiliates. * All rights reserved. */ "use strict";var l={"SA":["SA","\u5357\u7F8E\u6D32"]};(this?this:window)['DvtBaseMapManager']['_UNPROCESSED_MAPS'][2].push(["southAmerica","continent",l]);
afsinka/jet_jsp
src/main/webapp/js/libs/oj/v1.1.2/resources/internal-deps/dvt/thematicMap/resourceBundles/SouthAmericaContinentBundle_zh_TW.js
JavaScript
lgpl-2.1
240
/** * This file is part of TelepathyQt * * @copyright Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/> * @copyright Copyright (C) 2008 Nokia Corporation * @license LGPL 2.1 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _TelepathyQt_key_file_h_HEADER_GUARD_ #define _TelepathyQt_key_file_h_HEADER_GUARD_ #include <TelepathyQt/Global> #include <QMetaType> #include <QtGlobal> class QString; class QStringList; #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace Tp { class TP_QT_NO_EXPORT KeyFile { public: enum Status { None = 0, NoError, NotFoundError, AccessError, FormatError, }; KeyFile(); KeyFile(const KeyFile &other); KeyFile(const QString &fileName); ~KeyFile(); KeyFile &operator=(const KeyFile &other); void setFileName(const QString &fileName); QString fileName() const; Status status() const; void setGroup(const QString &group); QString group() const; QStringList allGroups() const; QStringList allKeys() const; QStringList keys() const; bool contains(const QString &key) const; QString rawValue(const QString &key) const; QString value(const QString &key) const; QStringList valueAsStringList(const QString &key) const; static bool unescapeString(const QByteArray &data, int from, int to, QString &result); static bool unescapeStringList(const QByteArray &data, int from, int to, QStringList &result); private: struct Private; friend struct Private; Private *mPriv; }; } Q_DECLARE_METATYPE(Tp::KeyFile); #endif /* DOXYGEN_SHOULD_SKIP_THIS */ #endif
anantkamath/telepathy-qt
TelepathyQt/key-file.h
C
lgpl-2.1
2,351
package org.intermine.webservice.server.output; /* * Copyright (C) 2002-2015 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.json.JSONObject; import static org.apache.commons.lang.StringEscapeUtils.escapeJava; /** * Base class for formatters that process JSON data. The * following basic structure is assumed: The result set * is a single JavaScript object literal, with an optional * callback provided by the user, and some result * status meta-data to round it off (see formatFooter). * @author Alex Kalderimis * */ public class JSONFormatter extends Formatter { private boolean hasCallback = false; private String outro = ""; private boolean shouldQuote = false; private boolean hasPrintedSomething = false; private boolean isExpectingPrimitive = false; private String header = null; /** * The key for the callback */ public static final String KEY_CALLBACK = "callback"; /** the key for the result object. **/ public static final String KEY_INTRO = "intro"; /** The way to wrap up after the result. **/ public static final String KEY_OUTRO = "outro"; /** Whether we should quote the result item. **/ public static final String KEY_QUOTE = "should_quote"; /** Things that should go into the header **/ public static final String KEY_HEADER_OBJS = "headerObjs"; /** * A map of optional key value pairs that should go in the header of the object. * The map should be of type Map<String, String> - woe betide you if you violate * this stern imprecation. */ public static final String KEY_KV_PAIRS = "key_value_pairs"; /** * The key for the execution time */ public static final String KEY_TIME = "executionTime"; /** keys which you aren't allowed to set. **/ public static final Set<String> RESERVED_KEYS = Collections.unmodifiableSet( new HashSet<String>(Arrays.asList( KEY_CALLBACK, KEY_INTRO, KEY_OUTRO, KEY_QUOTE, KEY_HEADER_OBJS, KEY_KV_PAIRS, KEY_TIME))); /** * Constructor */ public JSONFormatter() { //empty constructor } /** * Add the opening brace, and a call-back if any * @see org.intermine.webservice.server.output.Formatter#formatHeader(java.util.Map) * @return the header * @param attributes the attributes passed in from the containing output */ @Override public String formatHeader(Map<String, Object> attributes) { if (attributes == null) { attributes = new HashMap<String, Object>(); } StringBuilder sb = new StringBuilder(); Object callback = attributes.get(KEY_CALLBACK); if (callback != null) { hasCallback = true; sb.append(callback).append("("); } sb.append("{"); formatAttributes(attributes, sb); header = sb.toString(); return header; } /** * Format the header attributes. * @param attributes The header attributes. * @param sb Where to format them to. */ protected void formatAttributes(Map<String, Object> attributes, StringBuilder sb) { if (attributes == null) { return; } if (sb == null) { throw new NullPointerException("sb must not be null"); } if (attributes.containsKey(KEY_KV_PAIRS)) { @SuppressWarnings("unchecked") Map<String, String> kvPairs = (Map<String, String>) attributes.get(KEY_KV_PAIRS); for (Entry<String, String> pair: kvPairs.entrySet()) { sb.append("\"") .append(escapeJava(pair.getKey())) .append("\":") .append(quoteValue(escapeJava(pair.getValue()))) .append(","); } } // Add any complex objects as json-objects to the headers. if (attributes.containsKey(KEY_HEADER_OBJS)) { @SuppressWarnings({ "rawtypes", "unchecked" }) Map<String, Map> headerObjs = (Map<String, Map>) attributes.get(KEY_HEADER_OBJS); for (@SuppressWarnings("rawtypes") Entry<String, Map> pair: headerObjs.entrySet()) { sb.append("\"") .append(escapeJava(pair.getKey())) .append("\":") .append(new JSONObject(pair.getValue())) .append(","); } } if (attributes.get(KEY_INTRO) != null) { sb.append(attributes.get(KEY_INTRO)); if (attributes.containsKey(KEY_OUTRO)) { outro = attributes.get(KEY_OUTRO).toString(); } else { isExpectingPrimitive = true; } } if (attributes.containsKey(KEY_QUOTE)) { shouldQuote = (Boolean) attributes.get(KEY_QUOTE); } } private String quoteValue(String val) { if (val == null) { return "null"; } if ("null".equals(val) || "true".equals(val) || "false".equals(val) || StringUtils.isNumeric(val)) { return val; } return "\"" + val + "\""; } /** * In normal cases a list with a single JSON string item is expected. * But just in case, this formatter will simply join any strings * it gets given, delimiting with a comma. It is the responsibility of * whoever is feeding me these lines to add any necessary commas between * them. * @see org.intermine.webservice.server.output.Formatter#formatResult(java.util.List) * @param resultRow the row as a list of strings * @return A formatted result line, or the empty string if the row is empty */ @Override public String formatResult(List<String> resultRow) { if (resultRow.isEmpty()) { return ""; } Iterator<String> iter = resultRow.iterator(); String first = iter.next(); if (shouldQuote && !"".equals(first)) { first = quoteValue(first); } StringBuffer buffer = new StringBuffer(first == null ? "null" : first); while (iter.hasNext()) { String next = iter.next(); if (shouldQuote && !"".equals(next)) { next = quoteValue(next); } buffer.append(",").append(next); } declarePrinted(); return buffer.toString(); } /** Signal that we have started printing results and that it isn't safe to print headers. **/ protected void declarePrinted() { hasPrintedSomething = true; } /** * Put on the final brace, and close the call-back bracket if needed. * If an error has been reported, format that nicely, * escaping problematic JavaScript characters appropriately * in the message portion. * * @param errorMessage The message reporting the problem encountered * in processing this request, or null if there was none * @param errorCode The status code for the request (200 on success) * * @see org.intermine.webservice.server.output.Formatter#formatFooter() * @return The formatted footer string. */ @Override public String formatFooter(String errorMessage, int errorCode) { StringBuilder sb = new StringBuilder(outro); if (!hasPrintedSomething && isExpectingPrimitive) { sb.append("null"); } if ((header != null) && !hasPrintedSomething && (header.endsWith("{") || header.endsWith(","))) { // That's fine } else { sb.append(','); } Date now = Calendar.getInstance().getTime(); DateFormat dateFormatter = new SimpleDateFormat("yyyy.MM.dd HH:mm::ss"); String executionTime = dateFormatter.format(now); sb.append("\"" + KEY_TIME + "\":\"" + executionTime + "\","); sb.append("\"wasSuccessful\":"); if (errorCode >= 400) { sb.append("false,\"error\":\"" + escapeJava(errorMessage) + "\""); } else { sb.append("true,\"error\":null"); } sb.append(",\"statusCode\":" + errorCode); sb.append("}"); if (hasCallback) { sb.append(");"); } return sb.toString(); } }
joshkh/intermine
intermine/web/main/src/org/intermine/webservice/server/output/JSONFormatter.java
Java
lgpl-2.1
9,031
/********************************************************************************/ /* Projeto: Biblioteca ZeusNFe */ /* Biblioteca C# para emissão de Nota Fiscal Eletrônica - NFe e Nota Fiscal de */ /* Consumidor Eletrônica - NFC-e (http://www.nfe.fazenda.gov.br) */ /* */ /* Direitos Autorais Reservados (c) 2014 Adenilton Batista da Silva */ /* Zeusdev Tecnologia LTDA ME */ /* */ /* Você pode obter a última versão desse arquivo no GitHub */ /* localizado em https://github.com/adeniltonbs/Zeus.Net.NFe.NFCe */ /* */ /* */ /* Esta biblioteca é software livre; você pode redistribuí-la e/ou modificá-la */ /* sob os termos da Licença Pública Geral Menor do GNU conforme publicada pela */ /* Free Software Foundation; tanto a versão 2.1 da Licença, ou (a seu critério) */ /* qualquer versão posterior. */ /* */ /* Esta biblioteca é distribuída na expectativa de que seja útil, porém, SEM */ /* NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU */ /* ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral Menor*/ /* do GNU para mais detalhes. (Arquivo LICENÇA.TXT ou LICENSE.TXT) */ /* */ /* Você deve ter recebido uma cópia da Licença Pública Geral Menor do GNU junto*/ /* com esta biblioteca; se não, escreva para a Free Software Foundation, Inc., */ /* no endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. */ /* Você também pode obter uma copia da licença em: */ /* http://www.opensource.org/licenses/lgpl-license.php */ /* */ /* Zeusdev Tecnologia LTDA ME - adenilton@zeusautomacao.com.br */ /* http://www.zeusautomacao.com.br/ */ /* Rua Comendador Francisco josé da Cunha, 111 - Itabaiana - SE - 49500-000 */ /********************************************************************************/ using System; namespace NFe.Classes.Servicos.ConsultaCadastro { public class infConsEnv { private const string ErroCpfCnpjIePreenchidos = "Somente preencher um dos campos: CNPJ, CPF ou IE, para um objeto do tipo infConsEnv!"; private string _cnpj; private string _cpf; private string _ie; public infConsEnv() { xServ = "CONS-CAD"; } /// <summary> /// GP04 - Serviço solicitado "CONS-CAD" /// </summary> public string xServ { get; set; } /// <summary> /// GP05 - Sigla da UF consultada, informar 'SU' para SUFRAMA. /// </summary> public string UF { get; set; } /// <summary> /// GP06 - Inscrição estadual do contribuinte /// <para>Somente preencher um dos campos: CNPJ, CPF ou IE</para> /// </summary> public string IE { get { return _ie; } set { if (string.IsNullOrEmpty(value)) return; if (string.IsNullOrEmpty(CNPJ) & string.IsNullOrEmpty(CPF)) _ie = value; else { throw new ArgumentException(ErroCpfCnpjIePreenchidos); } } } /// <summary> /// GP07 - CNPJ do contribuinte /// <para>Somente preencher um dos campos: CNPJ, CPF ou IE</para> /// </summary> public string CNPJ { get { return _cnpj; } set { if (string.IsNullOrEmpty(value)) return; if (string.IsNullOrEmpty(CPF) & string.IsNullOrEmpty(IE)) _cnpj = value; else { throw new ArgumentException(ErroCpfCnpjIePreenchidos); } } } /// <summary> /// GP08 - CPF do contribuinte /// <para>Somente preencher um dos campos: CNPJ, CPF ou IE</para> /// </summary> public string CPF { get { return _cpf; } set { if (string.IsNullOrEmpty(value)) return; if (string.IsNullOrEmpty(CNPJ) & string.IsNullOrEmpty(IE)) _cpf = value; else { throw new ArgumentException(ErroCpfCnpjIePreenchidos); } } } } }
adrbarros/Zeus.Net.NFe.NFCe
Shared.NFe.Classes/Servicos/ConsultaCadastro/infConsEnv.cs
C#
lgpl-2.1
5,198
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #ifndef SUBDIRSPROJECTWIZARDDIALOG_H #define SUBDIRSPROJECTWIZARDDIALOG_H #include "qtwizard.h" namespace Qt4ProjectManager { namespace Internal { struct QtProjectParameters; class SubdirsProjectWizardDialog : public BaseQt4ProjectWizardDialog { Q_OBJECT public: explicit SubdirsProjectWizardDialog(const QString &templateName, const QIcon &icon, QWidget *parent, const Core::WizardDialogParameters &parameters); QtProjectParameters parameters() const; }; } // namespace Internal } // namespace Qt4ProjectManager #endif // SUBDIRSPROJECTWIZARDDIALOG_H
ostash/qt-creator-i18n-uk
src/plugins/qt4projectmanager/wizards/subdirsprojectwizarddialog.h
C
lgpl-2.1
1,962
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef TOOLS_H #define TOOLS_H #using <mscorlib.dll> QT_BEGIN_NAMESPACE class QString; QT_END_NAMESPACE System::String *QStringToString(const QString &qstring); QString StringToQString(System::String *string); #endif // TOOLS_H
CodeDJ/qt5-hidpi
qt/qtactiveqt/examples/activeqt/dotnet/wrapper/lib/tools.h
C
lgpl-2.1
2,228
# CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 2.6 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canoncical targets will work. .SUFFIXES: # Remove some rules from gmake that .SUFFIXES does not remove. SUFFIXES = .SUFFIXES: .hpux_make_needs_suffix_list # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/bin/cmake # The command to remove a file. RM = /usr/bin/cmake -E remove -f # The program to use to edit the cache. CMAKE_EDIT_COMMAND = /usr/bin/ccmake # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /ifs/data/zeng/count_error/CountErrors/bamtools-master # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /ifs/data/zeng/count_error/CountErrors/bamtools-master/build #============================================================================= # Targets provided globally by CMake. # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake cache editor..." /usr/bin/ccmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # Special rule for the target install install: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/bin/cmake -P cmake_install.cmake .PHONY : install # Special rule for the target install install/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/bin/cmake -P cmake_install.cmake .PHONY : install/fast # Special rule for the target install/local install/local: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." /usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake .PHONY : install/local # Special rule for the target install/local install/local/fast: install/local .PHONY : install/local/fast # Special rule for the target install/strip install/strip: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." /usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake .PHONY : install/strip # Special rule for the target install/strip install/strip/fast: install/strip .PHONY : install/strip/fast # Special rule for the target list_install_components list_install_components: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Unspecified\"" .PHONY : list_install_components # Special rule for the target list_install_components list_install_components/fast: list_install_components .PHONY : list_install_components/fast # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # The main all target all: cmake_check_build_system cd /ifs/data/zeng/count_error/CountErrors/bamtools-master/build && $(CMAKE_COMMAND) -E cmake_progress_start /ifs/data/zeng/count_error/CountErrors/bamtools-master/build/CMakeFiles /ifs/data/zeng/count_error/CountErrors/bamtools-master/build/src/CMakeFiles/progress.make cd /ifs/data/zeng/count_error/CountErrors/bamtools-master/build && $(MAKE) -f CMakeFiles/Makefile2 src/all $(CMAKE_COMMAND) -E cmake_progress_start /ifs/data/zeng/count_error/CountErrors/bamtools-master/build/CMakeFiles 0 .PHONY : all # The main clean target clean: cd /ifs/data/zeng/count_error/CountErrors/bamtools-master/build && $(MAKE) -f CMakeFiles/Makefile2 src/clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all cd /ifs/data/zeng/count_error/CountErrors/bamtools-master/build && $(MAKE) -f CMakeFiles/Makefile2 src/preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: cd /ifs/data/zeng/count_error/CountErrors/bamtools-master/build && $(MAKE) -f CMakeFiles/Makefile2 src/preinstall .PHONY : preinstall/fast # clear depends depend: cd /ifs/data/zeng/count_error/CountErrors/bamtools-master/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend # Convenience name for target. src/CMakeFiles/SharedHeaders.dir/rule: cd /ifs/data/zeng/count_error/CountErrors/bamtools-master/build && $(MAKE) -f CMakeFiles/Makefile2 src/CMakeFiles/SharedHeaders.dir/rule .PHONY : src/CMakeFiles/SharedHeaders.dir/rule # Convenience name for target. SharedHeaders: src/CMakeFiles/SharedHeaders.dir/rule .PHONY : SharedHeaders # fast build rule for target. SharedHeaders/fast: cd /ifs/data/zeng/count_error/CountErrors/bamtools-master/build && $(MAKE) -f src/CMakeFiles/SharedHeaders.dir/build.make src/CMakeFiles/SharedHeaders.dir/build .PHONY : SharedHeaders/fast # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... SharedHeaders" @echo "... edit_cache" @echo "... install" @echo "... install/local" @echo "... install/strip" @echo "... list_install_components" @echo "... rebuild_cache" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: cd /ifs/data/zeng/count_error/CountErrors/bamtools-master/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system
zengzheng123/CountErrors
bamtools-master/build/src/Makefile
Makefile
lgpl-2.1
6,567
/* GTK - The GIMP Toolkit * gtkpapersize.h: Paper Size * Copyright (C) 2006, Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef __GTK_PAPER_SIZE_H__ #define __GTK_PAPER_SIZE_H__ #if defined(GTK_DISABLE_SINGLE_INCLUDES) && !defined (__GTK_H_INSIDE__) && !defined (GTK_COMPILATION) #error "Only <gtk/gtk.h> can be included directly." #endif #include <gtk/gtkenums.h> G_BEGIN_DECLS typedef struct _GtkPaperSize GtkPaperSize; #define GTK_TYPE_PAPER_SIZE (gtk_paper_size_get_type ()) /* Common names, from PWG 5101.1-2002 PWG: Standard for Media Standardized Names */ #define GTK_PAPER_NAME_A3 "iso_a3" #define GTK_PAPER_NAME_A4 "iso_a4" #define GTK_PAPER_NAME_A5 "iso_a5" #define GTK_PAPER_NAME_B5 "iso_b5" #define GTK_PAPER_NAME_LETTER "na_letter" #define GTK_PAPER_NAME_EXECUTIVE "na_executive" #define GTK_PAPER_NAME_LEGAL "na_legal" GType gtk_paper_size_get_type (void) G_GNUC_CONST; GtkPaperSize *gtk_paper_size_new (const gchar *name); GtkPaperSize *gtk_paper_size_new_from_ppd (const gchar *ppd_name, const gchar *ppd_display_name, gdouble width, gdouble height); GtkPaperSize *gtk_paper_size_new_custom (const gchar *name, const gchar *display_name, gdouble width, gdouble height, GtkUnit unit); GtkPaperSize *gtk_paper_size_copy (GtkPaperSize *other); void gtk_paper_size_free (GtkPaperSize *size); gboolean gtk_paper_size_is_equal (GtkPaperSize *size1, GtkPaperSize *size2); GList *gtk_paper_size_get_paper_sizes (gboolean include_custom); /* The width is always the shortest side, measure in mm */ const gchar *gtk_paper_size_get_name (GtkPaperSize *size); const gchar *gtk_paper_size_get_display_name (GtkPaperSize *size); const gchar *gtk_paper_size_get_ppd_name (GtkPaperSize *size); gdouble gtk_paper_size_get_width (GtkPaperSize *size, GtkUnit unit); gdouble gtk_paper_size_get_height (GtkPaperSize *size, GtkUnit unit); gboolean gtk_paper_size_is_custom (GtkPaperSize *size); /* Only for custom sizes: */ void gtk_paper_size_set_size (GtkPaperSize *size, gdouble width, gdouble height, GtkUnit unit); gdouble gtk_paper_size_get_default_top_margin (GtkPaperSize *size, GtkUnit unit); gdouble gtk_paper_size_get_default_bottom_margin (GtkPaperSize *size, GtkUnit unit); gdouble gtk_paper_size_get_default_left_margin (GtkPaperSize *size, GtkUnit unit); gdouble gtk_paper_size_get_default_right_margin (GtkPaperSize *size, GtkUnit unit); const gchar *gtk_paper_size_get_default (void); GtkPaperSize *gtk_paper_size_new_from_key_file (GKeyFile *key_file, const gchar *group_name, GError **error); void gtk_paper_size_to_key_file (GtkPaperSize *size, GKeyFile *key_file, const gchar *group_name); G_END_DECLS #endif /* __GTK_PAPER_SIZE_H__ */
johne53/MB3Gtk-2
gtk/gtkpapersize.h
C
lgpl-2.1
3,909