code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * Copyright (C) 2014-2017 StormCore * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "PlayerAI.h" #include "SpellAuras.h" #include "SpellAuraEffects.h" enum Spells { /* Generic */ SPELL_AUTO_SHOT = 75, SPELL_SHOOT = 3018, SPELL_THROW = 2764, SPELL_SHOOT_WAND = 5019, /* Warrior - Generic */ SPELL_BATTLE_STANCE = 2457, SPELL_BERSERKER_STANCE = 2458, SPELL_DEFENSIVE_STANCE = 71, SPELL_CHARGE = 11578, SPELL_INTERCEPT = 20252, SPELL_ENRAGED_REGEN = 55694, SPELL_INTIMIDATING_SHOUT= 5246, SPELL_PUMMEL = 6552, SPELL_SHIELD_BASH = 72, SPELL_BLOODRAGE = 2687, /* Warrior - Arms */ SPELL_SWEEPING_STRIKES = 12328, SPELL_MORTAL_STRIKE = 12294, SPELL_BLADESTORM = 46924, SPELL_REND = 47465, SPELL_RETALIATION = 20230, SPELL_SHATTERING_THROW = 64382, SPELL_THUNDER_CLAP = 47502, /* Warrior - Fury */ SPELL_DEATH_WISH = 12292, SPELL_BLOODTHIRST = 23881, PASSIVE_TITANS_GRIP = 46917, SPELL_DEMO_SHOUT = 47437, SPELL_EXECUTE = 47471, SPELL_HEROIC_FURY = 60970, SPELL_RECKLESSNESS = 1719, SPELL_PIERCING_HOWL = 12323, /* Warrior - Protection */ SPELL_VIGILANCE = 50720, SPELL_DEVASTATE = 20243, SPELL_SHOCKWAVE = 46968, SPELL_CONCUSSION_BLOW = 12809, SPELL_DISARM = 676, SPELL_LAST_STAND = 12975, SPELL_SHIELD_BLOCK = 2565, SPELL_SHIELD_SLAM = 47488, SPELL_SHIELD_WALL = 871, SPELL_SPELL_REFLECTION = 23920, /* Paladin - Generic */ SPELL_PAL_AURA_MASTERY = 31821, SPELL_LAY_ON_HANDS = 48788, SPELL_BLESSING_OF_MIGHT = 48932, SPELL_AVENGING_WRATH = 31884, SPELL_DIVINE_PROTECTION = 498, SPELL_DIVINE_SHIELD = 642, SPELL_HAMMER_OF_JUSTICE = 10308, SPELL_HAND_OF_FREEDOM = 1044, SPELL_HAND_OF_PROTECTION = 10278, SPELL_HAND_OF_SACRIFICE = 6940, /* Paladin - Holy*/ PASSIVE_ILLUMINATION = 20215, SPELL_HOLY_SHOCK = 20473, SPELL_BEACON_OF_LIGHT = 53563, SPELL_CONSECRATION = 48819, SPELL_FLASH_OF_LIGHT = 48785, SPELL_HOLY_LIGHT = 48782, SPELL_DIVINE_FAVOR = 20216, SPELL_DIVINE_ILLUMINATION = 31842, /* Paladin - Protection */ SPELL_BLESS_OF_SANC = 20911, SPELL_HOLY_SHIELD = 20925, SPELL_AVENGERS_SHIELD = 48827, SPELL_DIVINE_SACRIFICE = 64205, SPELL_HAMMER_OF_RIGHTEOUS = 53595, SPELL_RIGHTEOUS_FURY = 25780, SPELL_SHIELD_OF_RIGHTEOUS = 61411, /* Paladin - Retribution */ SPELL_SEAL_OF_COMMAND = 20375, SPELL_CRUSADER_STRIKE = 35395, SPELL_DIVINE_STORM = 53385, SPELL_JUDGEMENT = 20271, SPELL_HAMMER_OF_WRATH = 48806, /* Hunter - Generic */ SPELL_DETERRENCE = 19263, SPELL_EXPLOSIVE_TRAP = 49067, SPELL_FREEZING_ARROW = 60192, SPELL_RAPID_FIRE = 3045, SPELL_KILL_SHOT = 61006, SPELL_MULTI_SHOT = 49048, SPELL_VIPER_STING = 3034, /* Hunter - Beast Mastery */ SPELL_BESTIAL_WRATH = 19574, PASSIVE_BEAST_WITHIN = 34692, PASSIVE_BEAST_MASTERY = 53270, /* Hunter - Marksmanship */ SPELL_AIMED_SHOT = 19434, PASSIVE_TRUESHOT_AURA = 19506, SPELL_CHIMERA_SHOT = 53209, SPELL_ARCANE_SHOT = 49045, SPELL_STEADY_SHOT = 49052, SPELL_READINESS = 23989, SPELL_SILENCING_SHOT = 34490, /* Hunter - Survival */ PASSIVE_LOCK_AND_LOAD = 56344, SPELL_WYVERN_STING = 19386, SPELL_EXPLOSIVE_SHOT = 53301, SPELL_BLACK_ARROW = 3674, /* Rogue - Generic */ SPELL_DISMANTLE = 51722, SPELL_EVASION = 26669, SPELL_KICK = 1766, SPELL_VANISH = 26889, SPELL_BLIND = 2094, SPELL_CLOAK_OF_SHADOWS = 31224, /* Rogue - Assassination */ SPELL_COLD_BLOOD = 14177, SPELL_MUTILATE = 1329, SPELL_HUNGER_FOR_BLOOD = 51662, SPELL_ENVENOM = 57993, /* Rogue - Combat */ SPELL_SINISTER_STRIKE = 48637, SPELL_BLADE_FLURRY = 13877, SPELL_ADRENALINE_RUSH = 13750, SPELL_KILLING_SPREE = 51690, SPELL_EVISCERATE = 48668, /* Rogue - Sublety */ SPELL_HEMORRHAGE = 16511, SPELL_PREMEDITATION = 14183, SPELL_SHADOW_DANCE = 51713, SPELL_PREPARATION = 14185, SPELL_SHADOWSTEP = 36554, /* Priest - Generic */ SPELL_FEAR_WARD = 6346, SPELL_POWER_WORD_FORT = 48161, SPELL_DIVINE_SPIRIT = 48073, SPELL_SHADOW_PROTECTION = 48169, SPELL_DIVINE_HYMN = 64843, SPELL_HYMN_OF_HOPE = 64901, SPELL_SHADOW_WORD_DEATH = 48158, SPELL_PSYCHIC_SCREAM = 10890, /* Priest - Discipline */ PASSIVE_SOUL_WARDING = 63574, SPELL_POWER_INFUSION = 10060, SPELL_PENANCE = 47540, SPELL_PAIN_SUPPRESSION = 33206, SPELL_INNER_FOCUS = 14751, SPELL_POWER_WORD_SHIELD = 48066, /* Priest - Holy */ PASSIVE_SPIRIT_REDEMPTION = 20711, SPELL_DESPERATE_PRAYER = 19236, SPELL_GUARDIAN_SPIRIT = 47788, SPELL_FLASH_HEAL = 48071, SPELL_RENEW = 48068, /* Priest - Shadow */ SPELL_VAMPIRIC_EMBRACE = 15286, SPELL_SHADOWFORM = 15473, SPELL_VAMPIRIC_TOUCH = 34914, SPELL_MIND_FLAY = 15407, SPELL_MIND_BLAST = 48127, SPELL_SHADOW_WORD_PAIN = 48125, SPELL_DEVOURING_PLAGUE = 48300, SPELL_DISPERSION = 47585, /* Death Knight - Generic */ SPELL_DEATH_GRIP = 49576, SPELL_STRANGULATE = 47476, SPELL_EMPOWER_RUNE_WEAP = 47568, SPELL_ICEBORN_FORTITUDE = 48792, SPELL_ANTI_MAGIC_SHELL = 48707, SPELL_DEATH_COIL_DK = 49895, SPELL_MIND_FREEZE = 47528, SPELL_ICY_TOUCH = 49909, AURA_FROST_FEVER = 55095, SPELL_PLAGUE_STRIKE = 49921, AURA_BLOOD_PLAGUE = 55078, SPELL_PESTILENCE = 50842, /* Death Knight - Blood */ SPELL_RUNE_TAP = 48982, SPELL_HYSTERIA = 49016, SPELL_HEART_STRIKE = 55050, SPELL_DEATH_STRIKE = 49924, SPELL_BLOOD_STRIKE = 49930, SPELL_MARK_OF_BLOOD = 49005, SPELL_VAMPIRIC_BLOOD = 55233, /* Death Knight - Frost */ PASSIVE_ICY_TALONS = 50887, SPELL_FROST_STRIKE = 49143, SPELL_HOWLING_BLAST = 49184, SPELL_UNBREAKABLE_ARMOR = 51271, SPELL_OBLITERATE = 51425, SPELL_DEATHCHILL = 49796, /* Death Knight - Unholy */ PASSIVE_UNHOLY_BLIGHT = 49194, PASSIVE_MASTER_OF_GHOUL = 52143, SPELL_SCOURGE_STRIKE = 55090, SPELL_DEATH_AND_DECAY = 49938, SPELL_ANTI_MAGIC_ZONE = 51052, SPELL_SUMMON_GARGOYLE = 49206, /* Shaman - Generic */ SPELL_HEROISM = 32182, SPELL_BLOODLUST = 2825, SPELL_GROUNDING_TOTEM = 8177, /* Shaman - Elemental*/ PASSIVE_ELEMENTAL_FOCUS = 16164, SPELL_TOTEM_OF_WRATH = 30706, SPELL_THUNDERSTORM = 51490, SPELL_LIGHTNING_BOLT = 49238, SPELL_EARTH_SHOCK = 49231, SPELL_FLAME_SHOCK = 49233, SPELL_LAVA_BURST = 60043, SPELL_CHAIN_LIGHTNING = 49271, SPELL_ELEMENTAL_MASTERY = 16166, /* Shaman - Enhancement */ PASSIVE_SPIRIT_WEAPONS = 16268, SPELL_LAVA_LASH = 60103, SPELL_FERAL_SPIRIT = 51533, AURA_MAELSTROM_WEAPON = 53817, SPELL_STORMSTRIKE = 17364, SPELL_SHAMANISTIC_RAGE = 30823, /* Shaman - Restoration*/ SPELL_SHA_NATURE_SWIFT = 591, SPELL_MANA_TIDE_TOTEM = 590, SPELL_EARTH_SHIELD = 49284, SPELL_RIPTIDE = 61295, SPELL_HEALING_WAVE = 49273, SPELL_LESSER_HEAL_WAVE = 49276, SPELL_TIDAL_FORCE = 55198, /* Mage - Generic */ SPELL_DAMPEN_MAGIC = 43015, SPELL_EVOCATION = 12051, SPELL_MANA_SHIELD = 43020, SPELL_MIRROR_IMAGE = 55342, SPELL_SPELLSTEAL = 30449, SPELL_COUNTERSPELL = 2139, SPELL_ICE_BLOCK = 45438, /* Mage - Arcane */ SPELL_FOCUS_MAGIC = 54646, SPELL_ARCANE_POWER = 12042, SPELL_ARCANE_BARRAGE = 44425, SPELL_ARCANE_BLAST = 42897, AURA_ARCANE_BLAST = 36032, SPELL_ARCANE_MISSILES = 42846, SPELL_PRESENCE_OF_MIND = 12043, /* Mage - Fire */ SPELL_PYROBLAST = 11366, SPELL_COMBUSTION = 11129, SPELL_LIVING_BOMB = 44457, SPELL_FIREBALL = 42833, SPELL_FIRE_BLAST = 42873, SPELL_DRAGONS_BREATH = 31661, SPELL_BLAST_WAVE = 11113, /* Mage - Frost */ SPELL_ICY_VEINS = 12472, SPELL_ICE_BARRIER = 11426, SPELL_DEEP_FREEZE = 44572, SPELL_FROST_NOVA = 42917, SPELL_FROSTBOLT = 42842, SPELL_COLD_SNAP = 11958, SPELL_ICE_LANCE = 42914, /* Warlock - Generic */ SPELL_FEAR = 6215, SPELL_HOWL_OF_TERROR = 17928, SPELL_CORRUPTION = 47813, SPELL_DEATH_COIL_W = 47860, SPELL_SHADOW_BOLT = 47809, SPELL_INCINERATE = 47838, SPELL_IMMOLATE = 47811, SPELL_SEED_OF_CORRUPTION = 47836, /* Warlock - Affliction */ PASSIVE_SIPHON_LIFE = 63108, SPELL_UNSTABLE_AFFLICTION = 30108, SPELL_HAUNT = 48181, SPELL_CURSE_OF_AGONY = 47864, SPELL_DRAIN_SOUL = 47855, /* Warlock - Demonology */ SPELL_SOUL_LINK = 19028, SPELL_DEMONIC_EMPOWERMENT = 47193, SPELL_METAMORPHOSIS = 59672, SPELL_IMMOLATION_AURA = 50589, SPELL_DEMON_CHARGE = 54785, AURA_DECIMATION = 63167, AURA_MOLTEN_CORE = 71165, SPELL_SOUL_FIRE = 47825, /* Warlock - Destruction */ SPELL_SHADOWBURN = 17877, SPELL_CONFLAGRATE = 17962, SPELL_CHAOS_BOLT = 50796, SPELL_SHADOWFURY = 47847, /* Druid - Generic */ SPELL_BARKSKIN = 22812, SPELL_INNERVATE = 29166, /* Druid - Balance */ SPELL_INSECT_SWARM = 5570, SPELL_MOONKIN_FORM = 24858, SPELL_STARFALL = 48505, SPELL_TYPHOON = 61384, AURA_ECLIPSE_LUNAR = 48518, SPELL_MOONFIRE = 48463, SPELL_STARFIRE = 48465, SPELL_WRATH = 48461, /* Druid - Feral */ SPELL_CAT_FORM = 768, SPELL_SURVIVAL_INSTINCTS = 61336, SPELL_MANGLE = 33917, SPELL_BERSERK = 50334, SPELL_MANGLE_CAT = 48566, SPELL_FERAL_CHARGE_CAT = 49376, SPELL_RAKE = 48574, SPELL_RIP = 49800, SPELL_SAVAGE_ROAR = 52610, SPELL_TIGER_FURY = 50213, SPELL_CLAW = 48570, SPELL_DASH = 33357, SPELL_MAIM = 49802, /* Druid - Restoration */ SPELL_SWIFTMEND = 18562, SPELL_TREE_OF_LIFE = 33891, SPELL_WILD_GROWTH = 48438, SPELL_NATURE_SWIFTNESS = 17116, SPELL_TRANQUILITY = 48447, SPELL_NOURISH = 50464, SPELL_HEALING_TOUCH = 48378, SPELL_REJUVENATION = 48441, SPELL_REGROWTH = 48443, SPELL_LIFEBLOOM = 48451 }; bool PlayerAI::IsPlayerHealer(Player const* who) { if (!who) return false; switch (who->getClass()) { case CLASS_WARRIOR: case CLASS_HUNTER: case CLASS_ROGUE: case CLASS_DEATH_KNIGHT: case CLASS_MAGE: case CLASS_WARLOCK: case CLASS_DEMON_HUNTER: default: return false; case CLASS_PALADIN: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_PALADIN_HOLY; case CLASS_PRIEST: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_PRIEST_DISCIPLINE || who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_PRIEST_HOLY; case CLASS_SHAMAN: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_SHAMAN_RESTORATION; case CLASS_MONK: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_MONK_MISTWEAVER; case CLASS_DRUID: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_DRUID_RESTORATION; } } bool PlayerAI::IsPlayerRangedAttacker(Player const* who) { if (!who) return false; switch (who->getClass()) { case CLASS_WARRIOR: case CLASS_PALADIN: case CLASS_ROGUE: case CLASS_DEATH_KNIGHT: default: return false; case CLASS_MAGE: case CLASS_WARLOCK: return true; case CLASS_HUNTER: { // check if we have a ranged weapon equipped Item const* rangedSlot = who->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); if (ItemTemplate const* rangedTemplate = rangedSlot ? rangedSlot->GetTemplate() : nullptr) if ((1 << rangedTemplate->GetSubClass()) & ITEM_SUBCLASS_MASK_WEAPON_RANGED) return true; return false; } case CLASS_PRIEST: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_PRIEST_SHADOW; case CLASS_SHAMAN: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_SHAMAN_ELEMENTAL; case CLASS_DRUID: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_DRUID_BALANCE; } } PlayerAI::TargetedSpell PlayerAI::VerifySpellCast(uint32 spellId, Unit* target) { // Find highest spell rank that we know uint32 knownRank, nextRank; if (me->HasSpell(spellId)) { // this will save us some lookups if the player has the highest rank (expected case) knownRank = spellId; nextRank = sSpellMgr->GetNextSpellInChain(spellId); } else { knownRank = 0; nextRank = sSpellMgr->GetFirstSpellInChain(spellId); } while (nextRank && me->HasSpell(nextRank)) { knownRank = nextRank; nextRank = sSpellMgr->GetNextSpellInChain(knownRank); } if (!knownRank) return {}; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(knownRank); if (!spellInfo) return {}; if (me->GetSpellHistory()->HasGlobalCooldown(spellInfo)) return {}; Spell* spell = new Spell(me, spellInfo, TRIGGERED_NONE); if (spell->CanAutoCast(target)) return{ spell, target }; delete spell; return {}; } PlayerAI::TargetedSpell PlayerAI::VerifySpellCast(uint32 spellId, SpellTarget target) { Unit* pTarget = nullptr; switch (target) { case TARGET_NONE: break; case TARGET_VICTIM: pTarget = me->GetVictim(); if (!pTarget) return {}; break; case TARGET_CHARMER: pTarget = me->GetCharmer(); if (!pTarget) return {}; break; case TARGET_SELF: pTarget = me; break; } return VerifySpellCast(spellId, pTarget); } PlayerAI::TargetedSpell PlayerAI::SelectSpellCast(PossibleSpellVector& spells) { if (spells.empty()) return{}; uint32 totalWeights = 0; for (PossibleSpell const& wSpell : spells) totalWeights += wSpell.second; TargetedSpell selected; uint32 randNum = urand(0, totalWeights - 1); for (PossibleSpell const& wSpell : spells) { if (selected) { delete wSpell.first.first; continue; } if (randNum < wSpell.second) selected = wSpell.first; else { randNum -= wSpell.second; delete wSpell.first.first; } } spells.clear(); return selected; } void PlayerAI::DoRangedAttackIfReady() { if (me->HasUnitState(UNIT_STATE_CASTING)) return; if (!me->isAttackReady(RANGED_ATTACK)) return; Unit* victim = me->GetVictim(); if (!victim) return; uint32 rangedAttackSpell = 0; Item const* rangedItem = me->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); if (ItemTemplate const* rangedTemplate = rangedItem ? rangedItem->GetTemplate() : nullptr) { switch (rangedTemplate->GetSubClass()) { case ITEM_SUBCLASS_WEAPON_BOW: case ITEM_SUBCLASS_WEAPON_GUN: case ITEM_SUBCLASS_WEAPON_CROSSBOW: rangedAttackSpell = SPELL_SHOOT; break; case ITEM_SUBCLASS_WEAPON_THROWN: rangedAttackSpell = SPELL_THROW; break; case ITEM_SUBCLASS_WEAPON_WAND: rangedAttackSpell = SPELL_SHOOT_WAND; break; } } if (!rangedAttackSpell) return; me->CastSpell(victim, rangedAttackSpell, TRIGGERED_CAST_DIRECTLY); me->resetAttackTimer(RANGED_ATTACK); } void PlayerAI::DoAutoAttackIfReady() { if (IsRangedAttacker()) DoRangedAttackIfReady(); else DoMeleeAttackIfReady(); } void PlayerAI::CancelAllShapeshifts() { std::list<AuraEffect*> const& shapeshiftAuras = me->GetAuraEffectsByType(SPELL_AURA_MOD_SHAPESHIFT); std::set<Aura*> removableShapeshifts; for (AuraEffect* auraEff : shapeshiftAuras) { Aura* aura = auraEff->GetBase(); if (!aura) continue; SpellInfo const* auraInfo = aura->GetSpellInfo(); if (!auraInfo) continue; if (auraInfo->HasAttribute(SPELL_ATTR0_CANT_CANCEL)) continue; if (!auraInfo->IsPositive() || auraInfo->IsPassive()) continue; removableShapeshifts.insert(aura); } for (Aura* aura : removableShapeshifts) me->RemoveOwnedAura(aura, AURA_REMOVE_BY_CANCEL); } struct UncontrolledTargetSelectPredicate : public std::unary_function<Unit*, bool> { bool operator()(Unit const* target) const { return !target->HasBreakableByDamageCrowdControlAura(); } }; Unit* SimpleCharmedPlayerAI::SelectAttackTarget() const { if (Unit* charmer = me->GetCharmer()) return charmer->IsAIEnabled ? charmer->GetAI()->SelectTarget(SELECT_TARGET_RANDOM, 0, UncontrolledTargetSelectPredicate()) : charmer->GetVictim(); return nullptr; } PlayerAI::TargetedSpell SimpleCharmedPlayerAI::SelectAppropriateCastForSpec() { PossibleSpellVector spells; /* switch (me->getClass()) { case CLASS_WARRIOR: if (!me->IsWithinMeleeRange(me->GetVictim())) { VerifyAndPushSpellCast(spells, SPELL_CHARGE, TARGET_VICTIM, 15); VerifyAndPushSpellCast(spells, SPELL_INTERCEPT, TARGET_VICTIM, 10); } VerifyAndPushSpellCast(spells, SPELL_ENRAGED_REGEN, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_INTIMIDATING_SHOUT, TARGET_VICTIM, 4); if (me->GetVictim() && me->GetVictim()->HasUnitState(UNIT_STATE_CASTING)) { VerifyAndPushSpellCast(spells, SPELL_PUMMEL, TARGET_VICTIM, 15); VerifyAndPushSpellCast(spells, SPELL_SHIELD_BASH, TARGET_VICTIM, 15); } VerifyAndPushSpellCast(spells, SPELL_BLOODRAGE, TARGET_NONE, 5); switch (GetSpec()) { case TALENT_SPEC_WARRIOR_PROTECTION: VerifyAndPushSpellCast(spells, SPELL_SHOCKWAVE, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_CONCUSSION_BLOW, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_DISARM, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_LAST_STAND, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_SHIELD_BLOCK, TARGET_NONE, 1); VerifyAndPushSpellCast(spells, SPELL_SHIELD_SLAM, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_SHIELD_WALL, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_SPELL_REFLECTION, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_DEVASTATE, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_REND, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_THUNDER_CLAP, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_DEMO_SHOUT, TARGET_VICTIM, 1); break; case TALENT_SPEC_WARRIOR_ARMS: VerifyAndPushSpellCast(spells, SPELL_SWEEPING_STRIKES, TARGET_NONE, 2); VerifyAndPushSpellCast(spells, SPELL_MORTAL_STRIKE, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_BLADESTORM, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_REND, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_RETALIATION, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_SHATTERING_THROW, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_SWEEPING_STRIKES, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_THUNDER_CLAP, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_EXECUTE, TARGET_VICTIM, 15); break; case TALENT_SPEC_WARRIOR_FURY: VerifyAndPushSpellCast(spells, SPELL_DEATH_WISH, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_BLOODTHIRST, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_DEMO_SHOUT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_EXECUTE, TARGET_VICTIM, 15); VerifyAndPushSpellCast(spells, SPELL_HEROIC_FURY, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_RECKLESSNESS, TARGET_NONE, 8); VerifyAndPushSpellCast(spells, SPELL_PIERCING_HOWL, TARGET_VICTIM, 2); break; } break; case CLASS_PALADIN: VerifyAndPushSpellCast(spells, SPELL_AURA_MASTERY, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_LAY_ON_HANDS, TARGET_CHARMER, 8); VerifyAndPushSpellCast(spells, SPELL_BLESSING_OF_MIGHT, TARGET_CHARMER, 8); VerifyAndPushSpellCast(spells, SPELL_AVENGING_WRATH, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_DIVINE_PROTECTION, TARGET_NONE, 4); VerifyAndPushSpellCast(spells, SPELL_DIVINE_SHIELD, TARGET_NONE, 2); VerifyAndPushSpellCast(spells, SPELL_HAMMER_OF_JUSTICE, TARGET_VICTIM, 6); VerifyAndPushSpellCast(spells, SPELL_HAND_OF_FREEDOM, TARGET_SELF, 3); VerifyAndPushSpellCast(spells, SPELL_HAND_OF_PROTECTION, TARGET_SELF, 1); if (Creature* creatureCharmer = ObjectAccessor::GetCreature(*me, me->GetCharmerGUID())) { if (creatureCharmer->IsDungeonBoss() || creatureCharmer->isWorldBoss()) VerifyAndPushSpellCast(spells, SPELL_HAND_OF_SACRIFICE, creatureCharmer, 10); else VerifyAndPushSpellCast(spells, SPELL_HAND_OF_PROTECTION, creatureCharmer, 3); } switch (GetSpec()) { case TALENT_SPEC_PALADIN_PROTECTION: VerifyAndPushSpellCast(spells, SPELL_HAMMER_OF_RIGHTEOUS, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_DIVINE_SACRIFICE, TARGET_NONE, 2); VerifyAndPushSpellCast(spells, SPELL_SHIELD_OF_RIGHTEOUS, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_JUDGEMENT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_CONSECRATION, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_HOLY_SHIELD, TARGET_NONE, 1); break; case TALENT_SPEC_PALADIN_HOLY: VerifyAndPushSpellCast(spells, SPELL_HOLY_SHOCK, TARGET_CHARMER, 3); VerifyAndPushSpellCast(spells, SPELL_HOLY_SHOCK, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_FLASH_OF_LIGHT, TARGET_CHARMER, 4); VerifyAndPushSpellCast(spells, SPELL_HOLY_LIGHT, TARGET_CHARMER, 3); VerifyAndPushSpellCast(spells, SPELL_DIVINE_FAVOR, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_DIVINE_ILLUMINATION, TARGET_NONE, 3); break; case TALENT_SPEC_PALADIN_RETRIBUTION: VerifyAndPushSpellCast(spells, SPELL_CRUSADER_STRIKE, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_DIVINE_STORM, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_JUDGEMENT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_HAMMER_OF_WRATH, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_RIGHTEOUS_FURY, TARGET_NONE, 2); break; } break; case CLASS_HUNTER: VerifyAndPushSpellCast(spells, SPELL_DETERRENCE, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_EXPLOSIVE_TRAP, TARGET_NONE, 1); VerifyAndPushSpellCast(spells, SPELL_FREEZING_ARROW, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_RAPID_FIRE, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_KILL_SHOT, TARGET_VICTIM, 10); if (me->GetVictim() && me->GetVictim()->getPowerType() == POWER_MANA && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_VIPER_STING, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_VIPER_STING, TARGET_VICTIM, 5); switch (GetSpec()) { case TALENT_SPEC_HUNTER_BEASTMASTER: VerifyAndPushSpellCast(spells, SPELL_AIMED_SHOT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_ARCANE_SHOT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_STEADY_SHOT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_MULTI_SHOT, TARGET_VICTIM, 2); break; case TALENT_SPEC_HUNTER_MARKSMAN: VerifyAndPushSpellCast(spells, SPELL_AIMED_SHOT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_CHIMERA_SHOT, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_ARCANE_SHOT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_STEADY_SHOT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_READINESS, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_SILENCING_SHOT, TARGET_VICTIM, 5); break; case TALENT_SPEC_HUNTER_SURVIVAL: VerifyAndPushSpellCast(spells, SPELL_EXPLOSIVE_SHOT, TARGET_VICTIM, 8); VerifyAndPushSpellCast(spells, SPELL_BLACK_ARROW, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_MULTI_SHOT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_STEADY_SHOT, TARGET_VICTIM, 1); break; } break; case CLASS_ROGUE: { VerifyAndPushSpellCast(spells, SPELL_DISMANTLE, TARGET_VICTIM, 8); VerifyAndPushSpellCast(spells, SPELL_EVASION, TARGET_NONE, 8); VerifyAndPushSpellCast(spells, SPELL_VANISH, TARGET_NONE, 4); VerifyAndPushSpellCast(spells, SPELL_BLIND, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_CLOAK_OF_SHADOWS, TARGET_NONE, 2); uint32 builder = 0, finisher = 0; switch (GetSpec()) { case TALENT_SPEC_ROGUE_ASSASSINATION: builder = SPELL_MUTILATE, finisher = SPELL_ENVENOM; VerifyAndPushSpellCast(spells, SPELL_COLD_BLOOD, TARGET_NONE, 20); break; case TALENT_SPEC_ROGUE_COMBAT: builder = SPELL_SINISTER_STRIKE, finisher = SPELL_EVISCERATE; VerifyAndPushSpellCast(spells, SPELL_ADRENALINE_RUSH, TARGET_NONE, 6); VerifyAndPushSpellCast(spells, SPELL_BLADE_FLURRY, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_KILLING_SPREE, TARGET_NONE, 25); break; case TALENT_SPEC_ROGUE_SUBTLETY: builder = SPELL_HEMORRHAGE, finisher = SPELL_EVISCERATE; VerifyAndPushSpellCast(spells, SPELL_PREPARATION, TARGET_NONE, 10); if (!me->IsWithinMeleeRange(me->GetVictim())) VerifyAndPushSpellCast(spells, SPELL_SHADOWSTEP, TARGET_VICTIM, 25); VerifyAndPushSpellCast(spells, SPELL_SHADOW_DANCE, TARGET_NONE, 10); break; } if (Unit* victim = me->GetVictim()) { if (victim->HasUnitState(UNIT_STATE_CASTING)) VerifyAndPushSpellCast(spells, SPELL_KICK, TARGET_VICTIM, 25); uint8 const cp = me->GetPower(POWER_COMBO_POINTS); if (cp >= 4) VerifyAndPushSpellCast(spells, finisher, TARGET_VICTIM, 10); if (cp <= 4) VerifyAndPushSpellCast(spells, builder, TARGET_VICTIM, 5); } break; } case CLASS_PRIEST: VerifyAndPushSpellCast(spells, SPELL_FEAR_WARD, TARGET_SELF, 2); VerifyAndPushSpellCast(spells, SPELL_POWER_WORD_FORT, TARGET_CHARMER, 1); VerifyAndPushSpellCast(spells, SPELL_DIVINE_SPIRIT, TARGET_CHARMER, 1); VerifyAndPushSpellCast(spells, SPELL_SHADOW_PROTECTION, TARGET_CHARMER, 2); VerifyAndPushSpellCast(spells, SPELL_DIVINE_HYMN, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_HYMN_OF_HOPE, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_SHADOW_WORD_DEATH, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_PSYCHIC_SCREAM, TARGET_VICTIM, 3); switch (GetSpec()) { case TALENT_SPEC_PRIEST_DISCIPLINE: VerifyAndPushSpellCast(spells, SPELL_POWER_WORD_SHIELD, TARGET_CHARMER, 3); VerifyAndPushSpellCast(spells, SPELL_INNER_FOCUS, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_PAIN_SUPPRESSION, TARGET_CHARMER, 15); VerifyAndPushSpellCast(spells, SPELL_POWER_INFUSION, TARGET_CHARMER, 10); VerifyAndPushSpellCast(spells, SPELL_PENANCE, TARGET_CHARMER, 3); VerifyAndPushSpellCast(spells, SPELL_FLASH_HEAL, TARGET_CHARMER, 1); break; case TALENT_SPEC_PRIEST_HOLY: VerifyAndPushSpellCast(spells, SPELL_DESPERATE_PRAYER, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_GUARDIAN_SPIRIT, TARGET_CHARMER, 5); VerifyAndPushSpellCast(spells, SPELL_FLASH_HEAL, TARGET_CHARMER, 1); VerifyAndPushSpellCast(spells, SPELL_RENEW, TARGET_CHARMER, 3); break; case TALENT_SPEC_PRIEST_SHADOW: if (!me->HasAura(SPELL_SHADOWFORM)) { VerifyAndPushSpellCast(spells, SPELL_SHADOWFORM, TARGET_NONE, 100); break; } if (Unit* victim = me->GetVictim()) { if (!victim->GetAuraApplicationOfRankedSpell(SPELL_VAMPIRIC_TOUCH, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_VAMPIRIC_TOUCH, TARGET_VICTIM, 4); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_SHADOW_WORD_PAIN, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_SHADOW_WORD_PAIN, TARGET_VICTIM, 3); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_DEVOURING_PLAGUE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_DEVOURING_PLAGUE, TARGET_VICTIM, 4); } VerifyAndPushSpellCast(spells, SPELL_MIND_BLAST, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_MIND_FLAY, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_DISPERSION, TARGET_NONE, 10); break; } break; case CLASS_DEATH_KNIGHT: { if (!me->IsWithinMeleeRange(me->GetVictim())) VerifyAndPushSpellCast(spells, SPELL_DEATH_GRIP, TARGET_VICTIM, 25); VerifyAndPushSpellCast(spells, SPELL_STRANGULATE, TARGET_VICTIM, 15); VerifyAndPushSpellCast(spells, SPELL_EMPOWER_RUNE_WEAP, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_ICEBORN_FORTITUDE, TARGET_NONE, 15); VerifyAndPushSpellCast(spells, SPELL_ANTI_MAGIC_SHELL, TARGET_NONE, 10); bool hasFF = false, hasBP = false; if (Unit* victim = me->GetVictim()) { if (victim->HasUnitState(UNIT_STATE_CASTING)) VerifyAndPushSpellCast(spells, SPELL_MIND_FREEZE, TARGET_VICTIM, 25); hasFF = !!victim->GetAuraApplicationOfRankedSpell(AURA_FROST_FEVER, me->GetGUID()), hasBP = !!victim->GetAuraApplicationOfRankedSpell(AURA_BLOOD_PLAGUE, me->GetGUID()); if (hasFF && hasBP) VerifyAndPushSpellCast(spells, SPELL_PESTILENCE, TARGET_VICTIM, 3); if (!hasFF) VerifyAndPushSpellCast(spells, SPELL_ICY_TOUCH, TARGET_VICTIM, 4); if (!hasBP) VerifyAndPushSpellCast(spells, SPELL_PLAGUE_STRIKE, TARGET_VICTIM, 4); } switch (GetSpec()) { case TALENT_SPEC_DEATHKNIGHT_BLOOD: VerifyAndPushSpellCast(spells, SPELL_RUNE_TAP, TARGET_NONE, 2); VerifyAndPushSpellCast(spells, SPELL_HYSTERIA, TARGET_SELF, 5); if (Creature* creatureCharmer = ObjectAccessor::GetCreature(*me, me->GetCharmerGUID())) if (!creatureCharmer->IsDungeonBoss() && !creatureCharmer->isWorldBoss()) VerifyAndPushSpellCast(spells, SPELL_HYSTERIA, creatureCharmer, 15); VerifyAndPushSpellCast(spells, SPELL_HEART_STRIKE, TARGET_VICTIM, 2); if (hasFF && hasBP) VerifyAndPushSpellCast(spells, SPELL_DEATH_STRIKE, TARGET_VICTIM, 8); VerifyAndPushSpellCast(spells, SPELL_DEATH_COIL_DK, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_MARK_OF_BLOOD, TARGET_VICTIM, 20); VerifyAndPushSpellCast(spells, SPELL_VAMPIRIC_BLOOD, TARGET_NONE, 10); break; case TALENT_SPEC_DEATHKNIGHT_FROST: if (hasFF && hasBP) VerifyAndPushSpellCast(spells, SPELL_OBLITERATE, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_HOWLING_BLAST, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_UNBREAKABLE_ARMOR, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_DEATHCHILL, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_FROST_STRIKE, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_BLOOD_STRIKE, TARGET_VICTIM, 1); break; case TALENT_SPEC_DEATHKNIGHT_UNHOLY: if (hasFF && hasBP) VerifyAndPushSpellCast(spells, SPELL_SCOURGE_STRIKE, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_DEATH_AND_DECAY, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_ANTI_MAGIC_ZONE, TARGET_NONE, 8); VerifyAndPushSpellCast(spells, SPELL_SUMMON_GARGOYLE, TARGET_VICTIM, 7); VerifyAndPushSpellCast(spells, SPELL_BLOOD_STRIKE, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_DEATH_COIL_DK, TARGET_VICTIM, 3); break; } break; } case CLASS_SHAMAN: VerifyAndPushSpellCast(spells, SPELL_HEROISM, TARGET_NONE, 25); VerifyAndPushSpellCast(spells, SPELL_BLOODLUST, TARGET_NONE, 25); VerifyAndPushSpellCast(spells, SPELL_GROUNDING_TOTEM, TARGET_NONE, 2); switch (GetSpec()) { case TALENT_SPEC_SHAMAN_RESTORATION: if (Unit* charmer = me->GetCharmer()) if (!charmer->GetAuraApplicationOfRankedSpell(SPELL_EARTH_SHIELD, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_EARTH_SHIELD, charmer, 2); if (me->HasAura(SPELL_SHA_NATURE_SWIFT)) VerifyAndPushSpellCast(spells, SPELL_HEALING_WAVE, TARGET_CHARMER, 20); else VerifyAndPushSpellCast(spells, SPELL_LESSER_HEAL_WAVE, TARGET_CHARMER, 1); VerifyAndPushSpellCast(spells, SPELL_TIDAL_FORCE, TARGET_NONE, 4); VerifyAndPushSpellCast(spells, SPELL_SHA_NATURE_SWIFT, TARGET_NONE, 4); VerifyAndPushSpellCast(spells, SPELL_MANA_TIDE_TOTEM, TARGET_NONE, 3); break; case TALENT_SPEC_SHAMAN_ELEMENTAL: if (Unit* victim = me->GetVictim()) { if (victim->GetAuraOfRankedSpell(SPELL_FLAME_SHOCK, GetGUID())) VerifyAndPushSpellCast(spells, SPELL_LAVA_BURST, TARGET_VICTIM, 5); else VerifyAndPushSpellCast(spells, SPELL_FLAME_SHOCK, TARGET_VICTIM, 3); } VerifyAndPushSpellCast(spells, SPELL_CHAIN_LIGHTNING, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_LIGHTNING_BOLT, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_ELEMENTAL_MASTERY, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_THUNDERSTORM, TARGET_NONE, 3); break; case TALENT_SPEC_SHAMAN_ENHANCEMENT: if (Aura const* maelstrom = me->GetAura(AURA_MAELSTROM_WEAPON)) if (maelstrom->GetStackAmount() == 5) VerifyAndPushSpellCast(spells, SPELL_LIGHTNING_BOLT, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_STORMSTRIKE, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_EARTH_SHOCK, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_LAVA_LASH, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_SHAMANISTIC_RAGE, TARGET_NONE, 10); break; } break; case CLASS_MAGE: if (me->GetVictim() && me->GetVictim()->HasUnitState(UNIT_STATE_CASTING)) VerifyAndPushSpellCast(spells, SPELL_COUNTERSPELL, TARGET_VICTIM, 25); VerifyAndPushSpellCast(spells, SPELL_DAMPEN_MAGIC, TARGET_CHARMER, 2); VerifyAndPushSpellCast(spells, SPELL_EVOCATION, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_MANA_SHIELD, TARGET_NONE, 1); VerifyAndPushSpellCast(spells, SPELL_MIRROR_IMAGE, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_SPELLSTEAL, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_ICE_BLOCK, TARGET_NONE, 1); VerifyAndPushSpellCast(spells, SPELL_ICY_VEINS, TARGET_NONE, 3); switch (GetSpec()) { case TALENT_SPEC_MAGE_ARCANE: if (Aura* abAura = me->GetAura(AURA_ARCANE_BLAST)) if (abAura->GetStackAmount() >= 3) VerifyAndPushSpellCast(spells, SPELL_ARCANE_MISSILES, TARGET_VICTIM, 7); VerifyAndPushSpellCast(spells, SPELL_ARCANE_BLAST, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_ARCANE_BARRAGE, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_ARCANE_POWER, TARGET_NONE, 8); VerifyAndPushSpellCast(spells, SPELL_PRESENCE_OF_MIND, TARGET_NONE, 7); break; case TALENT_SPEC_MAGE_FIRE: if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_LIVING_BOMB)) VerifyAndPushSpellCast(spells, SPELL_LIVING_BOMB, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_COMBUSTION, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_FIREBALL, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_FIRE_BLAST, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_DRAGONS_BREATH, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_BLAST_WAVE, TARGET_VICTIM, 1); break; case TALENT_SPEC_MAGE_FROST: VerifyAndPushSpellCast(spells, SPELL_DEEP_FREEZE, TARGET_VICTIM, 10); VerifyAndPushSpellCast(spells, SPELL_FROST_NOVA, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_FROSTBOLT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_COLD_SNAP, TARGET_VICTIM, 5); if (me->GetVictim() && me->GetVictim()->HasAuraState(AURA_STATE_FROZEN, nullptr, me)) VerifyAndPushSpellCast(spells, SPELL_ICE_LANCE, TARGET_VICTIM, 5); break; } break; case CLASS_WARLOCK: VerifyAndPushSpellCast(spells, SPELL_DEATH_COIL_W, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_FEAR, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_SEED_OF_CORRUPTION, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_HOWL_OF_TERROR, TARGET_NONE, 2); if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_CORRUPTION, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_CORRUPTION, TARGET_VICTIM, 10); switch (GetSpec()) { case TALENT_SPEC_WARLOCK_AFFLICTION: if (Unit* victim = me->GetVictim()) { VerifyAndPushSpellCast(spells, SPELL_SHADOW_BOLT, TARGET_VICTIM, 7); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_UNSTABLE_AFFLICTION, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_UNSTABLE_AFFLICTION, TARGET_VICTIM, 8); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_HAUNT, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_HAUNT, TARGET_VICTIM, 8); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_CURSE_OF_AGONY, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_CURSE_OF_AGONY, TARGET_VICTIM, 4); if (victim->HealthBelowPct(25)) VerifyAndPushSpellCast(spells, SPELL_DRAIN_SOUL, TARGET_VICTIM, 100); } break; case TALENT_SPEC_WARLOCK_DEMONOLOGY: VerifyAndPushSpellCast(spells, SPELL_METAMORPHOSIS, TARGET_NONE, 15); VerifyAndPushSpellCast(spells, SPELL_SHADOW_BOLT, TARGET_VICTIM, 7); if (me->HasAura(AURA_DECIMATION)) VerifyAndPushSpellCast(spells, SPELL_SOUL_FIRE, TARGET_VICTIM, 100); if (me->HasAura(SPELL_METAMORPHOSIS)) { VerifyAndPushSpellCast(spells, SPELL_IMMOLATION_AURA, TARGET_NONE, 30); if (!me->IsWithinMeleeRange(me->GetVictim())) VerifyAndPushSpellCast(spells, SPELL_DEMON_CHARGE, TARGET_VICTIM, 20); } if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_IMMOLATE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_IMMOLATE, TARGET_VICTIM, 5); if (me->HasAura(AURA_MOLTEN_CORE)) VerifyAndPushSpellCast(spells, SPELL_INCINERATE, TARGET_VICTIM, 10); break; case TALENT_SPEC_WARLOCK_DESTRUCTION: if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_IMMOLATE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_IMMOLATE, TARGET_VICTIM, 8); if (me->GetVictim() && me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_IMMOLATE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_CONFLAGRATE, TARGET_VICTIM, 8); VerifyAndPushSpellCast(spells, SPELL_SHADOWFURY, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_CHAOS_BOLT, TARGET_VICTIM, 10); VerifyAndPushSpellCast(spells, SPELL_SHADOWBURN, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_INCINERATE, TARGET_VICTIM, 7); break; } break; case CLASS_MONK: switch (GetSpec()) { case TALENT_SPEC_MONK_BREWMASTER: case TALENT_SPEC_MONK_BATTLEDANCER: case TALENT_SPEC_MONK_MISTWEAVER: break; } break; case CLASS_DRUID: VerifyAndPushSpellCast(spells, SPELL_INNERVATE, TARGET_CHARMER, 5); VerifyAndPushSpellCast(spells, SPELL_BARKSKIN, TARGET_NONE, 5); switch (GetSpec()) { case TALENT_SPEC_DRUID_RESTORATION: if (!me->HasAura(SPELL_TREE_OF_LIFE)) { CancelAllShapeshifts(); VerifyAndPushSpellCast(spells, SPELL_TREE_OF_LIFE, TARGET_NONE, 100); break; } VerifyAndPushSpellCast(spells, SPELL_TRANQUILITY, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_NATURE_SWIFTNESS, TARGET_NONE, 7); if (Creature* creatureCharmer = ObjectAccessor::GetCreature(*me, me->GetCharmerGUID())) { VerifyAndPushSpellCast(spells, SPELL_NOURISH, creatureCharmer, 5); VerifyAndPushSpellCast(spells, SPELL_WILD_GROWTH, creatureCharmer, 5); if (!creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REJUVENATION, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_REJUVENATION, creatureCharmer, 8); if (!creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REGROWTH, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_REGROWTH, creatureCharmer, 8); uint8 lifebloomStacks = 0; if (Aura const* lifebloom = creatureCharmer->GetAura(SPELL_LIFEBLOOM, me->GetGUID())) lifebloomStacks = lifebloom->GetStackAmount(); if (lifebloomStacks < 3) VerifyAndPushSpellCast(spells, SPELL_LIFEBLOOM, creatureCharmer, 5); if (creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REJUVENATION) || creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REGROWTH)) VerifyAndPushSpellCast(spells, SPELL_SWIFTMEND, creatureCharmer, 10); if (me->HasAura(SPELL_NATURE_SWIFTNESS)) VerifyAndPushSpellCast(spells, SPELL_HEALING_TOUCH, creatureCharmer, 100); } break; case TALENT_SPEC_DRUID_BALANCE: { if (!me->HasAura(SPELL_MOONKIN_FORM)) { CancelAllShapeshifts(); VerifyAndPushSpellCast(spells, SPELL_MOONKIN_FORM, TARGET_NONE, 100); break; } uint32 const mainAttackSpell = me->HasAura(AURA_ECLIPSE_LUNAR) ? SPELL_STARFIRE : SPELL_WRATH; VerifyAndPushSpellCast(spells, SPELL_STARFALL, TARGET_NONE, 20); VerifyAndPushSpellCast(spells, mainAttackSpell, TARGET_VICTIM, 10); if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_INSECT_SWARM, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_INSECT_SWARM, TARGET_VICTIM, 7); if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_MOONFIRE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_MOONFIRE, TARGET_VICTIM, 5); if (me->GetVictim() && me->GetVictim()->HasUnitState(UNIT_STATE_CASTING)) VerifyAndPushSpellCast(spells, SPELL_TYPHOON, TARGET_NONE, 15); break; } case TALENT_SPEC_DRUID_CAT: case TALENT_SPEC_DRUID_BEAR: if (!me->HasAura(SPELL_CAT_FORM)) { CancelAllShapeshifts(); VerifyAndPushSpellCast(spells, SPELL_CAT_FORM, TARGET_NONE, 100); break; } VerifyAndPushSpellCast(spells, SPELL_BERSERK, TARGET_NONE, 20); VerifyAndPushSpellCast(spells, SPELL_SURVIVAL_INSTINCTS, TARGET_NONE, 15); VerifyAndPushSpellCast(spells, SPELL_TIGER_FURY, TARGET_NONE, 15); VerifyAndPushSpellCast(spells, SPELL_DASH, TARGET_NONE, 5); if (Unit* victim = me->GetVictim()) { uint8 const cp = me->GetPower(POWER_COMBO_POINTS); if (victim->HasUnitState(UNIT_STATE_CASTING) && cp >= 1) VerifyAndPushSpellCast(spells, SPELL_MAIM, TARGET_VICTIM, 25); if (!me->IsWithinMeleeRange(victim)) VerifyAndPushSpellCast(spells, SPELL_FERAL_CHARGE_CAT, TARGET_VICTIM, 25); if (cp >= 4) VerifyAndPushSpellCast(spells, SPELL_RIP, TARGET_VICTIM, 50); if (cp <= 4) { VerifyAndPushSpellCast(spells, SPELL_MANGLE_CAT, TARGET_VICTIM, 10); VerifyAndPushSpellCast(spells, SPELL_CLAW, TARGET_VICTIM, 5); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_RAKE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_RAKE, TARGET_VICTIM, 8); if (!me->HasAura(SPELL_SAVAGE_ROAR)) VerifyAndPushSpellCast(spells, SPELL_SAVAGE_ROAR, TARGET_NONE, 15); } } break; } break; case CLASS_DEMON_HUNTER: switch (GetSpec()) { case TALENT_SPEC_DEMON_HUNTER_HAVOC: case TALENT_SPEC_DEMON_HUNTER_VENGEANCE: break; } break; } */ return SelectSpellCast(spells); } static const float CASTER_CHASE_DISTANCE = 28.0f; void SimpleCharmedPlayerAI::UpdateAI(const uint32 diff) { Creature* charmer = me->GetCharmer() ? me->GetCharmer()->ToCreature() : nullptr; if (!charmer) return; //kill self if charm aura has infinite duration if (charmer->IsInEvadeMode()) { Player::AuraEffectList const& auras = me->GetAuraEffectsByType(SPELL_AURA_MOD_CHARM); for (Player::AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter) if ((*iter)->GetCasterGUID() == charmer->GetGUID() && (*iter)->GetBase()->IsPermanent()) { me->KillSelf(); return; } } if (charmer->IsInCombat()) { Unit* target = me->GetVictim(); if (!target || !charmer->IsValidAttackTarget(target) || target->HasBreakableByDamageCrowdControlAura()) { target = SelectAttackTarget(); if (!target) return; if (IsRangedAttacker()) { _chaseCloser = !me->IsWithinLOSInMap(target); if (_chaseCloser) AttackStart(target); else AttackStartCaster(target, CASTER_CHASE_DISTANCE); } else AttackStart(target); _forceFacing = true; } if (me->IsStopped() && !me->HasUnitState(UNIT_STATE_CANNOT_TURN)) { float targetAngle = me->GetAngle(target); if (_forceFacing || fabs(me->GetOrientation() - targetAngle) > 0.4f) { me->SetFacingTo(targetAngle); _forceFacing = false; } } if (_castCheckTimer <= diff) { if (me->HasUnitState(UNIT_STATE_CASTING)) _castCheckTimer = 0; else { if (IsRangedAttacker()) { // chase to zero if the target isn't in line of sight bool inLOS = me->IsWithinLOSInMap(target); if (_chaseCloser != !inLOS) { _chaseCloser = !inLOS; if (_chaseCloser) AttackStart(target); else AttackStartCaster(target, CASTER_CHASE_DISTANCE); } } if (TargetedSpell shouldCast = SelectAppropriateCastForSpec()) DoCastAtTarget(shouldCast); _castCheckTimer = 500; } } else _castCheckTimer -= diff; DoAutoAttackIfReady(); } else { me->AttackStop(); me->CastStop(); me->StopMoving(); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE); } } void SimpleCharmedPlayerAI::OnCharmed(bool apply) { if (apply) { me->CastStop(); me->AttackStop(); me->StopMoving(); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MovePoint(0, me->GetPosition(), false); // force re-sync of current position for all clients } else { me->CastStop(); me->AttackStop(); // @todo only voluntary movement (don't cancel stuff like death grip or charge mid-animation) me->GetMotionMaster()->Clear(); me->StopMoving(); } }
Ragebones/StormCore
src/server/game/AI/PlayerAI/PlayerAI.cpp
C++
gpl-2.0
57,029
<?php /* * This file is part of SeAT * * Copyright (C) 2015 to 2022 Leon Jacobs * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ namespace Seat\Services\Traits; use Composer\InstalledVersions; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; use OutOfBoundsException; use Seat\Services\AbstractSeatPlugin; use stdClass; /** * Trait VersionsManagementTrait. * * @package Seat\Services\Traits */ trait VersionsManagementTrait { /** * Compute a list of provider class which are implementing SeAT package structure. * * @return \stdClass */ protected function getPluginsMetadataList(): stdClass { app()->loadDeferredProviders(); $providers = array_keys(app()->getLoadedProviders()); $packages = (object) [ 'core' => collect(), 'plugins' => collect(), ]; foreach ($providers as $class) { // attempt to retrieve the class from booted app $provider = app()->getProvider($class); if (is_null($provider)) continue; // ensure the provider is a valid SeAT package if (! is_a($provider, AbstractSeatPlugin::class)) continue; // seed proper collection according to package vendor $provider->getPackagistVendorName() === 'eveseat' ? $packages->core->push($provider) : $packages->plugins->push($provider); } return $packages; } /** * @param string $vendor * @param string $package * @return string */ protected function getPackageLatestVersion(string $vendor, string $package): string { // construct the packagist uri to its API $packagist_url = sprintf('https://packagist.org/packages/%s/%s.json', $vendor, $package); try { $installed_version = InstalledVersions::getPrettyVersion(sprintf('%s/%s', $vendor, $package)) ?? '0.0.0'; } catch (OutOfBoundsException $e) { $installed_version = '0.0.0'; } // retrieve package meta-data try { $response = (new Client())->request('GET', $packagist_url); if ($response->getStatusCode() !== 200) return '0.0.0'; // convert the body into an array $json_array = json_decode($response->getBody(), true); // in case we miss either versions or package attribute, return an error as those attribute should contains version information if (! array_key_exists('package', $json_array) || ! array_key_exists('versions', $json_array['package'])) return '0.0.0'; // extract published versions from packagist response $versions = $json_array['package']['versions']; foreach ($versions as $available_version => $metadata) { // ignore any unstable versions if (strpos($available_version, 'dev') !== false || strpos($available_version, 'rc') !== false || strpos($available_version, 'alpha') !== false || strpos($available_version, 'beta') !== false) continue; // return outdated on the first package which is greater than installed version if (version_compare($installed_version, $metadata['version']) < 0) return $metadata['version']; } } catch (GuzzleException $e) { logger()->error($e->getMessage()); return 'offline'; } return $installed_version; } }
eveseat/services
src/Traits/VersionsManagementTrait.php
PHP
gpl-2.0
4,287
<?php if (empty($_REQUEST['feeding'])): $feeding = 0; else: $feeding = $_REQUEST['feeding']; endif; if (empty($_REQUEST['transfer'])): $transfer = 0; else: $transfer = $_REQUEST['transfer']; endif; if (empty($_REQUEST['mobility'])): $mobility = 0; else: $mobility = $_REQUEST['mobility']; endif; if (empty($_REQUEST['dressing'])): $dressing = 0; else: $dressing = $_REQUEST['dressing']; endif; if (empty($_REQUEST['bathing'])): $bathing = 0; else: $bathing = $_REQUEST['bathing']; endif; if (empty($_REQUEST['groming'])): $groming = 0; else: $groming = $_REQUEST['groming']; endif; if (empty($_REQUEST['toilet_use'])): $toilet_use = 0; else: $toilet_use = $_REQUEST['toilet_use']; endif; if (empty($_REQUEST['bowels'])): $bowels = 0; else: $bowels = $_REQUEST['bowels']; endif; if (empty($_REQUEST['bladder'])): $bladder = 0; else: $bladder = $_REQUEST['bladder']; endif; if (empty($_REQUEST['stairs'])): $stairs = 0; else: $stairs = $_REQUEST['stairs']; endif; $score = $feeding + $transfer + $mobility + $dressing + $bathing + $groming + $toilet_use + $bowels + $bladder + $stairs; switch ($score) { case 0: $text = "ติดเตียง (เตียง 3)"; break; case ($score > 12): $text = "ติดสังคม (เตียง 1)"; break; case ($score > 5): $text = "ติดบ้าน (เตียง 2)"; break; case ($score < 5): $text = "ติดเตียง (เตียง 3)"; break; } echo "คะแนนที่ได้ " . $score . " คะแนน (เต็ม 20 คะแนน)<br>" . $text; ?>
kukks205/jhhc
page/old_screen/adl_result.php
PHP
gpl-2.0
1,838
package icaro.pruebas; import icaro.infraestructura.entidadesBasicas.NombresPredefinidos; import icaro.infraestructura.patronAgenteReactivo.control.acciones.AccionSincrona; import icaro.infraestructura.entidadesBasicas.descEntidadesOrganizacion.ComprobadorRutasEntidades; import icaro.infraestructura.entidadesBasicas.interfaces.InterfazGestion; import icaro.infraestructura.recursosOrganizacion.recursoTrazas.ItfUsoRecursoTrazas; import icaro.infraestructura.recursosOrganizacion.recursoTrazas.imp.componentes.InfoTraza; import icaro.infraestructura.recursosOrganizacion.recursoTrazas.imp.componentes.InfoTraza.NivelTraza; import icaro.infraestructura.recursosOrganizacion.repositorioInterfaces.ItfUsoRepositorioInterfaces; import java.util.Vector; /* * Implementacion por defecto de las acciones que se ejecutaron por parte del gestor de agentes. * @author */ public class VerificarExistenciaEntidadesDescripcion extends AccionSincrona { /** * Almacn de los nombres de los agentes que este gestor debe gestionar */ protected Vector<String> nombresAgentesGestionados = new Vector<String>(); /** * Depuracion para pruebas */ protected static boolean DEBUG = true; private InterfazGestion ItfGestionRecTrazas; private ItfUsoRecursoTrazas ItfUsoRecTrazas; // private ItfGestionAgenteReactivo ItfgestGestorInicial = null; // private ItfUsoConfiguracion configuracionExterna = null; // private String identGestorNodo = null; // private String msgUsuario = null; private String rutaDescripcionOrganizacion = null; private String nombreAgente; private ItfUsoRepositorioInterfaces itfUsoRepositorio; /** * Hebra para la monitorizacion */ // private HebraMonitorizacion hebra; // private Thread currentthread; /** * Tiempo de monitorizacion */ protected int tiempoParaNuevaMonitorizacion; protected final static String SUBTIPO_COGNITIVO = "Cognitivo"; protected final static String SUBTIPO_REACTIVO = "Reactivo"; private NombresPredefinidos.TipoEntidad tipoEntidad = NombresPredefinidos.TipoEntidad.Reactivo; /** * Constructor */ public VerificarExistenciaEntidadesDescripcion() { super(); this.nombreAgente = NombresPredefinidos.NOMBRE_INICIADOR; try { itfUsoRepositorio = NombresPredefinidos.REPOSITORIO_INTERFACES_OBJ; ItfUsoRecTrazas = NombresPredefinidos.RECURSO_TRAZAS_OBJ; ItfGestionRecTrazas = (InterfazGestion) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.RECURSO_TRAZAS); // ItfUsoRecTrazas.trazar(this.nombreAgente, "Fichero Descripcion organizacion : "+ // NombresPredefinidos.DESCRIPCION_XML_POR_DEFECTO, NivelTraza.debug); ItfUsoRecTrazas.visualizarIdentFicheroDescrOrganizacion(); ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza(this.nombreAgente, tipoEntidad, "Activacion agente reactivo " + nombreAgente + "\n" + "Fichero Descripcion organizacion : " + NombresPredefinidos.DESCRIPCION_XML_POR_DEFECTO, InfoTraza.NivelTraza.debug)); } catch (Exception e2) { e2.printStackTrace(); } /* * ItfUsoConfiguracion config = * (ItfUsoConfiguracion)RepositorioInterfaces.instance().obtenerInterfaz * (NombresPredefinidos.ITF_USO+NombresPredefinidos.CONFIGURACION); * tiempoParaNuevaMonitorizacion = config.getEntornoEjecucionGestor(nombreAgente). * getIntervaloMonitorizacion().intValue(); */ } @Override public void ejecutar(Object... params) { // Se verifican las rutas donde deben encontrarse las entidades de descripcion: // El esquema de descripcion de la organizacion, el fichero de descripcion y el paquete jaxb // nombreAgente= this.getNombreAgente(); ItfUsoRecTrazas.setIdentAgenteAReportar(this.nombreAgente); ComprobadorRutasEntidades comprobadorRutas = new ComprobadorRutasEntidades(); Boolean SeHapodidoLocalizarEsquema = true; Boolean SeHapodidoLocalizarFicheroDescripcion = true; this.trazas.trazar(nombreAgente, "Verificando la existencia de entidadesDescripcion", NivelTraza.debug); if (!comprobadorRutas.existeSchemaDescOrganizacion()) { ItfUsoRecTrazas .aceptaNuevaTraza(new InfoTraza( "Iniciador", "No se pudo encontrar fichero que define el esquema para interpretar la descripcion de la Organizacion", InfoTraza.NivelTraza.error)); SeHapodidoLocalizarEsquema = false; } rutaDescripcionOrganizacion = comprobadorRutas .buscarDescOrganizacion(NombresPredefinidos.DESCRIPCION_XML_POR_DEFECTO); if (rutaDescripcionOrganizacion == null) { ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", "No se pudo encontrar fichero de descripcion de la Organizacion", InfoTraza.NivelTraza.error)); SeHapodidoLocalizarFicheroDescripcion = false; } try { if (SeHapodidoLocalizarEsquema && SeHapodidoLocalizarFicheroDescripcion) { this.procesarInput("existenEntidadesDescripcion", null); } else { this.procesarInput("errorLocalizacionFicherosDescripcion", null); } } catch (Exception e2) { e2.printStackTrace(); ItfUsoRecTrazas .aceptaNuevaTraza(new InfoTraza( "Iniciador", tipoEntidad, "No se ha podido enviar un evento a si mismo notificando la validacion de las rutas de las entidades de descripcion . ", InfoTraza.NivelTraza.error)); } } public void getInfoObjectInput(Object obj) { } // public void crearRecursosNucleoOrganizacion () throws Exception { // // // Intento crear los recursos en orden pero si se producen errores se capturan, se visualizan // y // // se pude intentar dialogar con el usuario para que los corrija // // try { // // Se crea el recurso de configuración y posteriormente se debería dar orden al recurso // // de trazas para pintar el proceso. // // ItfUsoRepositorioInterfaces repositorioInterfaces = // RepositorioInterfaces.instance(RepositorioInterfaces.IMP_LOCAL); // trazas.trazar(this.nombreAgente,"Creacion de recursos nucleo Organizacion", NivelTraza.info); // configuracionExterna = ClaseGeneradoraConfiguracion.instance(); // // Se crea una configuracion con el fichero de descripcion de la organizacion // // rutaDescripcionOrganizacion // =NombresPredefinidos.RUTA_DESCRIPCIONES+NombresPredefinidos.DESCRIPCION_XML_POR_DEFECTO+".xml"; // configuracionExterna.interpretarDescripOrganizacion(rutaDescripcionOrganizacion); // if(!configuracionExterna.validarDescripOrganizacion()){ // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza(this.nombreAgente, // "Se produjo un error al interpretar el fichero de descripcion de la organizacion", // InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_InterpretacionDescripcionOrganizacion", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // }else { // // registro la configuracion // itfUsoRepositorio.registrarInterfaz( // NombresPredefinidos.ITF_USO + NombresPredefinidos.CONFIGURACION,configuracionExterna); // // Ahora que la configuracion es correcta , interpreto las propiedades globales // // y pongo la configuracion de trazas definida por el usuario // Boolean ConfiguracionTrazas = false; // if (NombresPredefinidos.ACTIVACION_PANEL_TRAZAS_DEBUG.startsWith("t")){ // ConfiguracionTrazas = true; // } // else // ItfGestionRecTrazas.termina(); // ItfUsoRecTrazas.visualizacionDeTrazas(ConfiguracionTrazas); // // // // Se crea el gestor de Organizacion // // DescInstanciaAgente descGestor = // configuracionExterna.getDescInstanciaGestor(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); // // creo el agente gestor de organizacion // // // arranco la organizacion // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "recursosNucleoCreados", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // ItfgestGestorOrg.arranca(); // } catch (IllegalArgumentException ie) { // System.err.println("Error. La organizacion no se ha compilado correctamente. Compruebe que los ficheros xml de los automatas se encuentren en el classpath."); // ie.printStackTrace(); // System.exit(1); // // } // catch (ExcepcionEnComponente ie) { // msgUsuario = // "Se produjo un error al interpretar el fichero de descripcion de la organizacion \n"+ // "La ruta especificada es : " + rutaDescripcionOrganizacion; // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // msgUsuario,InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_InterpretacionDescripcionOrganizacion", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // catch (Exception e) { // msgUsuario = // "Se produjo un error al interpretar el fichero de descripcion de la organizacion \n"+ // "La ruta especificada es : " + rutaDescripcionOrganizacion; // System.err.println(msgUsuario); // e.printStackTrace(); // ItfUsoRecTrazas.aceptaNuevaTraza(new // InfoTraza("Iniciador",msgUsuario,InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_InterpretacionDescripcionOrganizacion", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // } // // public String localizarComportamientoGestorInicial ( String identGestor) throws // ExcepcionEnComponente, RemoteException { // // String locComportamientoGestor = null; // // Se obtiene el gestor inicial de la descripción de la organizacion. Puede ser un gestor de // organizacion o un gestor de nodo // // identGestor = configuracionExterna.getIdentGestorInicial(); // try { // // DescComportamientoAgente desCompGestor = // configuracionExterna.getDescComportamientoAgente(identGestor); // DescInstanciaGestor desCompGestor = configuracionExterna.getDescInstanciaGestor(identGestor); // locComportamientoGestor = // desCompGestor.getDescComportamiento().getLocalizacionComportamiento(); // if ( identGestor.startsWith(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)){ // if (locComportamientoGestor.isEmpty()) // locComportamientoGestor = NombresPredefinidos.PAQUETE_GESTOR_ORGANIZACION; // // } else // if ( identGestorNodo.startsWith(NombresPredefinidos.NOMBRE_GESTOR_NODO)){ // // identGestorACrear = NombresPredefinidos.NOMBRE_GESTOR_NODO; // if (locComportamientoGestor.isEmpty()) // locComportamientoGestor = NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_NODO; // } // else{ // // El gestor inicial debe ser un gestor de organización o un gestor de nodo y no se ha // definido ninguno // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se pudo crear el comportamiento del Gestor Inicial porque no hay un Gestor de Organizacion o un Gestor de Nodo definido." // + " Revisar el fichero de Descripcion de la Organizacion", // InfoTraza.NivelTraza.error)); // // } // // } catch (ExcepcionEnComponente ex) { // Logger.getLogger(VerificarExistenciaEntidadesDescripcion.class.getName()).log(Level.SEVERE, // null, ex); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se pudo crear el comportamiento del Gestor Inicial porque no se pudo obtener el comportamiento del Gestor de Organizacion o del Gestor de Nodo definido." // + " Revisar el fichero de Descripcion de la Organizacion", // InfoTraza.NivelTraza.error)); // } // return locComportamientoGestor; // } // public void crearGestorInicial () throws Exception { // // String locComportamientoGestor = null; // // Se obtiene el gestor inicial de la descripción de la organizacion. Puede ser un gestor de // organizacion o un gestor de nodo // // identGestorNodo = configuracionExterna.getIdentGestorInicial(); // if (configuracionExterna.despliegueOrgEnUnSoloNodo()) // identGestorNodo = NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION; // else { // Si la organizacion es distribuida el iniciador mira si esta en el nodo del GO o en // otro nodo // String identNodoGO = // configuracionExterna.getHostComponente(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); // String thisHost = InetAddress.getLocalHost().getHostName(); // if ( thisHost.equalsIgnoreCase(identNodoGO)) // Esta en el nodo del GO se crea un Gestor de // Organizacion // identGestorNodo = NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION; // else identGestorNodo = NombresPredefinidos.NOMBRE_GESTOR_NODO; // Se crea un Gestor de Nodo // } // // // if ( identGestorNodo.startsWith(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)){ // //// identGestorACrear = NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION; // // // // // //// locComportamientoGestor = // NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_ORGANIZACION; // // locComportamientoGestor = // configuracionExterna.getDescComportamientoAgente(NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_ORGANIZACION).getLocalizacionComportamiento(); // // // // } else // // if ( identGestorNodo.startsWith(NombresPredefinidos.NOMBRE_GESTOR_NODO)){ // //// identGestorACrear = NombresPredefinidos.NOMBRE_GESTOR_NODO; // // locComportamientoGestor = NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_NODO; // // } // // else{ // // // El gestor inicial debe ser un gestor de organización o un gestor de nodo y no se ha // definido ninguno // // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // // // "No se pudo crear el comportamiento del Gestor Inicial porque no hay un Gestor de Organizacion o un Gestor de Nodo definido." // // + " Revisar el fichero de Descripcion de la Organizacion", // // InfoTraza.NivelTraza.error)); // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // // "error_al_crearGestorInicial", // // NombresPredefinidos.NOMBRE_INICIADOR, // // NombresPredefinidos.NOMBRE_INICIADOR)); // // } // locComportamientoGestor = this.localizarComportamientoGestorInicial(identGestorNodo); // // if (!locComportamientoGestor.isEmpty() ) { // // Se crea el gestor y se registra en el registro RMI en el caso en que la organizacion sea // distribuida // try { // // FactoriaAgenteReactivo.instancia().crearAgenteReactivo(identGestorNodo // ,locComportamientoGestor); // DescInstanciaGestor desCompGestor = // configuracionExterna.getDescInstanciaGestor(identGestorNodo); // FactoriaAgenteReactivo.instancia().crearAgenteReactivo(desCompGestor); // ItfgestGestorInicial = (ItfGestionAgenteReactivo) itfUsoRepositorio.obtenerInterfaz( // NombresPredefinidos.ITF_GESTION + identGestorNodo); // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "GestorInicialCreado", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // // } // catch (ExcepcionEnComponente ie) { // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se pudo crear el comportamiento del Gestor inicial", // InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_crearGestorInicial", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // catch (Exception e) { // System.err.println("Error. No se ha podido crear o registrar el Gestor Inicial."); // e.printStackTrace(); // } // } // } // // public void crearGestorOrganizacion () throws Exception { // try { // FactoriaAgenteReactivo.instancia().crearAgenteReactivo(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION // ,NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_ORGANIZACION); // ItfgestGestorInicial = (ItfGestionAgenteReactivo) itfUsoRepositorio.obtenerInterfaz( // NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "GestorOrganizacionCreado", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // // } // catch (ExcepcionEnComponente ie) { // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se pudo crear el comportamiento del Gestor de Organizacion", // InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_crearGestorInicial", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // // } // catch (Exception e) { // System.err.println("Error. No se ha podido crear o registrar el Gestor de Organizacion."); // e.printStackTrace(); // } // } // // /** // * arranca los agentes que se especifiquen en la config. // */ // public void arrancarGestorInicialyTerminar()throws Exception { // logger.debug("GestorIniciador: Arrancando gestor Inicial."); // // try { // // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Arrancando el Gestor Inicial . ", InfoTraza.NivelTraza.debug)); // // if (ItfgestGestorInicial != null ){ // // arranca el Gestor de Organizacion y Termina el iniciador // this. ItfgestGestorInicial.arranca(); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "GestorInicial_arrancado_ok", // nombreAgente, // nombreAgente)); // // // terminarPorPropiaVoluntad(); // // } // else { // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "La interfaz del GO es nula . ", InfoTraza.NivelTraza.error)); // // genero un evento interno de error // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_arrancarGestorOrganizacion", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // } catch (Exception e2) { // e2.printStackTrace(); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_arrancarGestorInicial", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se ha podido arrancar el Gestor de Organizacion . ", InfoTraza.NivelTraza.error)); // // } // // } // // /** // * Devuelve cierto si es necesario arrancar el agente // * // * @param nombreAgente // * @return // */ // /* // * private boolean esNecesarioArrancar(String nombreAgente) { Enumeration // * enume = configEspecifica.getListaAgentes().enumerateAgente(); while // * (enume.hasMoreElements()) { Agente item = (Agente)enume.nextElement(); if // * (nombreAgente.equals(item.getNombre())) return // * item.getHayQueArrancarlo(); } logger.error("GestorAgentes: No se encontr� // * ning�n agente con nombre "+nombreAgente+" dentro de la lista de objetos // * gestionados."); throw new NullPointerException(); } // */ // /** // * Decide que hacer en caso de fallos en los agentes. // */ // public void decidirTratamientoErrorIrrecuperable() { // // el tratamiento ser� siempre cerrar todo el chiringuito // logger.debug("GestorAgentes: Se decide cerrar el sistema ante un error critico irrecuperable."); // try { // // trazas.aceptaNuevaTraza(new InfoTraza( // this.nombreAgente, // "Se decide cerrar el sistema ante un error critico irrecuperable.", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // try { // // trazas.aceptaNuevaTraza(new InfoTraza( // nombreAgente, // "Terminado proceso de arranque automatico de agentes.", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // // try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "tratamiento_terminar_agentes_y_gestor_agentes", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // } // // /** // * intenta arrancar los agentes que especifique la config y hayan dado // * problemas. // */ // public void recuperarErrorArranqueAgentes() { // // por defecto no se implementan pol�ticas de recuperaci�n // //logger.debug("GestorAgentes: Fue imposible recuperar el error en el arranque de los agentes."); // try { // // trazas.aceptaNuevaTraza(new InfoTraza( // nombreAgente, // "Fue imposible recuperar el error en el arranque de los agentes.", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "imposible_recuperar_arranque", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // } // // /** // * Elabora un informe del estado en el que se encuentran los agentes y lo // * env�a al sistema de trazas. // */ // public void generarInformeErrorIrrecuperable() { // // Producimos traza de un error // logger.error("GestorIniciador: Se ha producido un error irrecuperable."); // try { // trazas.aceptaNuevaTraza(new InfoTraza( // "Iniciador", // " Iniciador a la espera de terminacion por parte del usuario debido a un error irrecuperable.", // InfoTraza.NivelTraza.error)); // this.informaraMiAutomata("informe_generado", null); // } catch (Exception e2) { // e2.printStackTrace(); // } // /* // try { // this.itfUsoGestorAReportar.aceptaEvento(new EventoRecAgte( // "error_en_arranque_gestores", // NombresPredefinidos.NOMBRE_GESTOR_RECURSOS, // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte("informe_generado", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // */ // } // // // /** // * Crea y arranca un agente. Es necesario pasar las caracter�sticas del // * agente a crear por par�metro. // */ // public void crearAgente() { // // esto hay que recuperarlo de los parametros // // logger.debug("GestorAgentes: crearAgente():Este metodo no esta implementado"); // try { // // trazas.aceptaNuevaTraza(new InfoTraza( // nombreAgente, // "crearAgente():Este metodo no esta implementado", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // throw new UnsupportedOperationException(); // } // // /** // * Monitoriza secuencialmente todos los agentes activos que est�n definidos // * como necesarios en la configuraci�n. // */ // public void monitorizarAgentes() { // // if(DEBUG) System.out.println("GestorAgentes:Comienza ciclo // // monitorizaci�n."); // // boolean errorEncontrado = false; // // recuperar todos los interfaces de gesti�n del repositorio que estamos // // gestionando // Enumeration enume = nombresAgentesGestionados.elements(); // while (enume.hasMoreElements() && !errorEncontrado) { // String nombre = (String) enume.nextElement(); // // if(DEBUG) System.out.println("GestorAgentes:Monitorizando agente // // "+nombre+"."); // // recupero el interfaz de gestion del repositorio // try { // InterfazGestion itfGes = (InterfazGestion) // this.itfUsoRepositorio.obtenerInterfaz(NombresPredefinidos.ITF_GESTION + nombre); // int monitoriz = itfGes.obtenerEstado(); // if (monitoriz == InterfazGestion.ESTADO_ERRONEO_IRRECUPERABLE || monitoriz == // InterfazGestion.ESTADO_ERRONEO_RECUPERABLE || monitoriz == InterfazGestion.ESTADO_TERMINADO // || monitoriz == InterfazGestion.ESTADO_TERMINANDO) { // errorEncontrado = true; // logger.debug("GestorAgentes:Agente " + nombre + " est� en estado err�neo o terminado."); // try { // ItfUsoRecursoTrazas trazas = (ItfUsoRecursoTrazas) // ClaseGeneradoraRepositorioInterfaces.instance().obtenerInterfaz( // NombresPredefinidos.ITF_USO + NombresPredefinidos.RECURSO_TRAZAS); // trazas.aceptaNuevaTraza(new InfoTraza( // this.nombreAgente, // "Agente " + nombre + " esta en estado erroneo o terminado.", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // } // /* // * else if(DEBUG) System.out.println("GestorAgentes:Agente // * "+nombre+" est� ok."); // */ // } catch (Exception ex) { // errorEncontrado = true; // logger.error("GestorAgentes: No se pudo acceder al repositorio."); // ex.printStackTrace(); // } // } // // if (errorEncontrado) { // try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_monitorizar", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // } else { // try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte("agentes_ok", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // // // /** // * Intenta recuperar los errores detectados en la monitorizaci�n siguiendo // * la pol�tica definida para cada agente. // */ // // // /** // * destruye los recursos que se crearon a lo largo del ciclo de vida de este // * agente. // */ // public void terminarPorPropiaVoluntad() throws Exception, Throwable { // // termina el gestor. // // puede esperarse a que terminen los agentes // //logger.debug("GestorAgentes: Terminando gestor de agentes."); // logger.debug("Iniciador: Terminando gestor de la organizacion y los recursos de la infraestructura."); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Terminando el Iniciador.", // InfoTraza.NivelTraza.debug)); // try { // // se obtiene la propia interfaz de gestion para terminar // // // ItfgestGestorInicial.termina(); // // // ((ItfGestionAgenteReactivo) this.itfUsoRepositorio // .obtenerInterfaz(NombresPredefinidos.ITF_GESTION // + this.nombreAgente)) // .termina(); // // quitamos las interfaces del repositorio de interfaces // itfUsoRepositorio.eliminarRegistroInterfaz(NombresPredefinidos.ITF_USO+this.nombreAgente); // itfUsoRepositorio.eliminarRegistroInterfaz(NombresPredefinidos.ITF_GESTION+this.nombreAgente); // // definimos el gestor al que debe enviar los eventos el RC // ItfUsoRecTrazas.setIdentAgenteAReportar(this.identGestorNodo); // // // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new // // EventoRecAgte ("termina",this.nombreAgente,this.nombreAgente)); // // } catch (Exception ex) { // ex.printStackTrace(); // } // logger.debug("Iniciador: Terminando."); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Terminando.", // InfoTraza.NivelTraza.debug)); // if (this.hebra != null) // this.hebra.finalizar(); // // this.currentthread.join(); // } // public void procesarPeticionTerminacion() { // logger.debug("Iniciador: Procesando la peticion de terminacion"); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Procesando la peticion de terminacion", // InfoTraza.NivelTraza.debug)); // // ItfUsoRecTrazas.pedirConfirmacionTerminacionAlUsuario(); // // /*try { // // this.itfUsoAgente.aceptaEvento(new // // EventoRecAgte("termina",null,null)); // // // ItfGestionAgenteReactivo gestion = (ItfGestionAgenteReactivo) this.itfUsoRepositorio // .obtenerInterfaz(NombresPredefinidos.ITF_GESTION // + NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); // gestion.termina(); // } catch (Exception e) { // e.printStackTrace(); // } // */ // } // // public void comenzarTerminacionConfirmada() { // logger.debug("Iniciador: Terminando recursos..."); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Comenzando la terminacion de los recursos...", // InfoTraza.NivelTraza.info)); // // // try { // // ItfGestionRecTrazas.termina(); // // y a continuacion se termina el gestor // // terminarPorPropiaVoluntad();if (this.hebra != null) // if (this.hebra != null) // this.hebra.finalizar(); // System.exit(0); // } catch (Exception ex) { // Logger.getLogger(VerificarExistenciaEntidadesDescripcion.class.getName()).log(Level.SEVERE, // null, ex); // } catch (Throwable ex) { // Logger.getLogger(VerificarExistenciaEntidadesDescripcion.class.getName()).log(Level.SEVERE, // null, ex); // } // // // } // // public void clasificaError() { // } }
palomagc/MovieChatter
src/icaro/pruebas/VerificarExistenciaEntidadesDescripcion.java
Java
gpl-2.0
27,852
/** * OWASP Benchmark Project v1.2beta * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest00550") public class BenchmarkTest00550 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String param = ""; boolean flag = true; java.util.Enumeration<String> names = request.getParameterNames(); while (names.hasMoreElements() && flag) { String name = (String) names.nextElement(); String[] values = request.getParameterValues(name); if (values != null) { for(int i=0;i<values.length && flag; i++){ String value = values[i]; if (value.equals("vector")) { param = name; flag = false; } } } } // Chain a bunch of propagators in sequence String a26930 = param; //assign StringBuilder b26930 = new StringBuilder(a26930); // stick in stringbuilder b26930.append(" SafeStuff"); // append some safe content b26930.replace(b26930.length()-"Chars".length(),b26930.length(),"Chars"); //replace some of the end content java.util.HashMap<String,Object> map26930 = new java.util.HashMap<String,Object>(); map26930.put("key26930", b26930.toString()); // put in a collection String c26930 = (String)map26930.get("key26930"); // get it back out String d26930 = c26930.substring(0,c26930.length()-1); // extract most of it String e26930 = new String( new sun.misc.BASE64Decoder().decodeBuffer( new sun.misc.BASE64Encoder().encode( d26930.getBytes() ) )); // B64 encode and decode it String f26930 = e26930.split(" ")[0]; // split it on a space org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing(); String g26930 = "barbarians_at_the_gate"; // This is static so this whole flow is 'safe' String bar = thing.doSomething(g26930); // reflection double value = java.lang.Math.random(); String rememberMeKey = Double.toString(value).substring(2); // Trim off the 0. at the front. String user = "Doug"; String fullClassName = this.getClass().getName(); String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length()); user+= testCaseNumber; String cookieName = "rememberMe" + testCaseNumber; boolean foundUser = false; javax.servlet.http.Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) { javax.servlet.http.Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) { if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) { foundUser = true; } } } if (foundUser) { response.getWriter().println("Welcome back: " + user + "<br/>"); } else { javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey); rememberMe.setSecure(true); request.getSession().setAttribute(cookieName, rememberMeKey); response.addCookie(rememberMe); response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName() + " whose value is: " + rememberMe.getValue() + "<br/>"); } response.getWriter().println("Weak Randomness Test java.lang.Math.random() executed"); } }
andresriancho/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00550.java
Java
gpl-2.0
4,565
<?php require 'head.php';?> <div class="container-fluid main-container"> <div class="col-md-2 sidebar"> <div class="row"> <!-- uncomment code for absolute positioning tweek see top comment in css --> <div class="absolute-wrapper"> </div> <!-- Menu --> <div class="side-menu"> <nav class="navbar navbar-default" role="navigation"> <!-- Main Menu --> <div class="side-menu-container"> <ul class="nav navbar-nav"> <li class="active"><a href="#" target="_self"><span class="glyphicon glyphicon-dashboard"></span> Dashboard</a></li> <li><a href="grafik.php"><span class="glyphicon glyphicon-signal"></span> Link</a></li> </ul> </div><!-- /.navbar-collapse --> </nav> </div> </div> </div> <div class="col-md-10 content"> <div class="panel panel-default"> <div class="panel-heading"> Dashboard </div> <div class="panel-body"> <?php require 'addcalon.php'; ?> </div> </div> </div> <?php require'foot.php';?>
zona284/evotemipa
admin/admin.php
PHP
gpl-2.0
998
/* This file is part of Work in Texas (WIT) Search Helper. WIT Search Helper is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. WIT Search Helper is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with WIT Search Helper. If not, see <http://www.gnu.org/licenses/>. */ /* functions for getting and setting correct value from local storage local storage key: WITStorage array structure: see function getNewLocStorArray below */ function getLocalStorage(loc) { arr = testLocalStorageIntegrity(); if(loc == 'maxDist') return arr[0].maxDist; else if(loc == 'myZip') return arr[0].myZip; else if(loc == 'resultHandling') return arr[0].resultHandling; else if(loc == 'myDistances') return arr[0].myDistances; else window.console.log('Nothing returned for ' + loc); } //arrAdd array structure: [value to add, key to add to] function setLocalStorage(arrAdd) { arr = testLocalStorageIntegrity(); for (i = 0; i < arrAdd.length; i++) { var val = arrAdd[i][0]; var loc = arrAdd[i][1]; if(loc == 'maxDist') arr[0].maxDist = val; else if(loc == 'myZip') arr[0].myZip = val; else if(loc == 'resultHandling') arr[0].resultHandling = val; else if(loc == 'myDistances') arr[0].myDistances = val; } localStorage['WITStorage'] = JSON.stringify(arr); return; } function testLocalStorageIntegrity() { var arr = localStorage['WITStorage']; if(arr == 'undefined' || arr == null) { //empty or error, redo storage // lOut('Redoing Array'); return getNewLocStorArray(); } arr = JSON.parse(arr); if(arr.length != 4) { //empty or error, redo storage // lOut('Redoing Array'); return getNewLocStorArray(); } //no problems, return good local storage values return arr; } //SET DEFAULT VALUES HERE, ALL VALUES ARE PRELOADED FROM THIS ARRAY function getNewLocStorArray() { var myArray = [ {"maxDist":"20"}, {"myZip":"76010"}, {"resultHandling":""}, {"myDistances":""} ] return myArray; } //shortened script for printing to console log function lOut(str) { window.console.log(str); } //functions for testing time to execute scripts function myTime(a) { i = performance.now(); lOut(a[0] + ". " + (i-a[1])); a[0]++; a[1] = i; return a; }
Soscan2062/wit-search-helper
utils.js
JavaScript
gpl-2.0
2,653
<?php /* * index.home.php * Created on 21.03.2007 by Tobias Bieniek */ // Startseiten-Template laden und mit Variablen füllen $temp = new Template("templates/".$competition['lang']."/home.tpl"); // Heimatflugplatz einfügen $base = (explode("|", $competition['config']['homebase'])); $base = $base[0]; $temp->addVariable("homebase", $base); // Heimatbonus einfügen $temp->addVariable("awayfactor", $competition['config']['homefactor']); $hf = "1.0"; while (strlen($hf) < strlen($competition['config']['homefactor'])) { $hf = $hf . "0"; } $temp->addVariable("homefactor", $hf); // Meilenstein-Faktoren einfügen $factors = explode("|", $competition['config']['factors']); for ($i = 0; $i < count($factors); $i++) { $temp->addVariable("factor_".($i+1), $factors[$i]); } // OLC Jahr berechnen $year = date("Y"); if (time() >= mktime(0,0,0,11,1,$year)) $year++; // kleine Rankingtabellen der letzten <3> Jahre einfuegen include_once("index.smallranking.php"); $sr_perpage = 3; if (isset($competition['config']['sr_per_page']) && $competition['config']['sr_per_page'] > 0) $sr_perpage = $competition['config']['sr_per_page']; $small_rankings = ""; $i = 0; for ($j = 0; $j < 100 && $i < $sr_perpage; $j++) { $xtemp = getSmallRanking($competition, $db, $year - $j); if ($xtemp != "") { $small_rankings .= $xtemp; $i++; } } $temp->addVariable("small_rankings", $small_rankings); // News-System hinzufügen $page = 1; if (array_key_exists("page", $_GET)) $page = $_GET['page']; $i = 0; $s_news = ""; $next = 0; $prev = 0; $perpage = 5; if (isset($competition['config']['news_per_page']) && $competition['config']['news_per_page'] > 0) $perpage = $competition['config']['news_per_page']; $res_news = db_query("SELECT * FROM %pre%news ORDER BY time DESC, id DESC", $db, $competition['id']); while($news = db_fetch_array($res_news)) { if ($i >= ($page - 1) * $perpage && $i < $page * $perpage) { $news_temp = new Template("templates/".$competition['lang']."/home.news.row.tpl"); $news_temp->addVariable("id", $news['id']); $news_temp->addVariable("author", $news['author']); $news_temp->addVariable("header", $news['header']); $news_temp->addVariable("text", str_replace("\r\n", "<br />\r\n", $news['text'])); $news_temp->addVariable("ldate", date("d.m.Y", $news['time'])); $news_temp->addVariable("sdate", date("d.m.", $news['time'])); $news_temp->addVariable("ltime", date("H:i:s", $news['time'])); $news_temp->addVariable("stime", date("H:i", $news['time'])); $s_news .= $news_temp->getOutput(); } if ($i >= $page * $perpage) { $next = 1; } if ($i < ($page - 1) * $perpage) { $prev = 1; } $i++; } if ($i == 0) { $news_temp = new Template("templates/".$competition['lang']."/home.news.row.empty.tpl"); $news_temp->fillStandard($competition); $s_news .= $news_temp->getOutput(); } // Links einfügen (Vor/Zurück) if ($next == 1) { $next = new Template("templates/".$competition['lang']."/home.news.next.tpl"); $next->fillStandard($competition); $next->addVariable("page", ($page+1)); $next = $next->getOutput(); } else $next = "&nbsp;"; if ($prev == 1) { $prev = new Template("templates/".$competition['lang']."/home.news.prev.tpl"); $prev->fillStandard($competition); $prev->addVariable("page", ($page-1)); $prev = $prev->getOutput(); } else $prev = "&nbsp;"; $temp->addVariable("news", $s_news); $temp->addVariable("news_page", $page); $temp->addVariable("news_next", $next); $temp->addVariable("news_prev", $prev); ?>
Turbo87/destination
index.home.php
PHP
gpl-2.0
3,541
# -*- coding: utf-8 -*- import sys sys.path.append(sys.argv[1]) from scriptlib import * """Файлы пакета""" FILES = ( '7z920-x64.msi', '7z920.msi' ) """Имена исполняемых файлов""" if ARCH == '64': INSTALLER = os.path.join('', DIR, FILES[0]) else: INSTALLER = os.path.join('', DIR, FILES[1]) def install(): run_msi('/i', INSTALLER) def remove(): run_msi('/x', INSTALLER) check_files(FILES) if ACTION == 'install': install() elif ACTION == 'remove': remove()
kuchiman/wpm-pkg
7zip/script.py
Python
gpl-2.0
529
/* ============================================================ * * This file is a part of kipi-plugins project * http://www.kipi-plugins.org * * Date : 2003-10-14 * Description : batch image rotation * * Copyright (C) 2003-2005 by Renchi Raju <renchi@pooh.tam.uiuc.edu> * Copyright (C) 2004-2009 by Marcel Wiesweg <marcel dot wiesweg at gmx dot de> * Copyright (C) 2006-2009 by Gilles Caulier <caulier dot gilles at gmail dot com> * * This program is free software; you can redistribute it * and/or modify it under the terms of the GNU General * Public License as published by the Free Software Foundation; * either version 2, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * ============================================================ */ #define XMD_H // C++ includes. #include <cstdio> // C ANSI includes. extern "C" { #include <sys/types.h> #include <unistd.h> #include <jpeglib.h> } // Qt includes. #include <QFile> #include <QFileInfo> // KDE includes. #include <kprocess.h> #include <kdebug.h> #include <klocale.h> // Local includes. #include "utils.h" #include "transupp.h" #include "jpegtransform.h" #include "imagerotate.h" #include "imagerotate.moc" namespace KIPIJPEGLossLessPlugin { ImageRotate::ImageRotate() : QObject() { m_tmpFile.setSuffix("kipiplugin-rotate"); m_tmpFile.setAutoRemove(true); } ImageRotate::~ImageRotate() { } bool ImageRotate::rotate(const QString& src, RotateAction angle, QString& err, bool updateFileTimeStamp) { QFileInfo fi(src); if (!fi.exists() || !fi.isReadable() || !fi.isWritable()) { err = i18n("Error in opening input file"); return false; } if ( !m_tmpFile.open() ) { err = i18n("Error in opening temporary file"); return false; } QString tmp = m_tmpFile.fileName(); if (Utils::isRAW(src)) { err = i18n("Cannot rotate RAW file"); return false; } else if (Utils::isJPEG(src)) { if (!rotateJPEG(src, tmp, angle, err, updateFileTimeStamp)) { if (err == "nothing to do") { err=QString::null; return true; } return false; } } else { // B.K.O #123499 : we using Image Magick API here instead QT API // else TIFF/PNG 16 bits image are broken! if (!rotateImageMagick(src, tmp, angle, err)) return false; // We update metadata on new image. Utils tools(this); if (!tools.updateMetadataImageMagick(tmp, err)) return false; } // Move back to original file if (!Utils::MoveFile(tmp, src)) { err = i18n("Cannot update source image"); return false; } return true; } bool ImageRotate::rotateJPEG(const QString& src, const QString& dest, RotateAction angle, QString& err, bool updateFileTimeStamp) { Matrix transform=Matrix::none; switch(angle) { case (Rot90): { transform = Matrix::rotate90; break; } case (Rot180): { transform = Matrix::rotate180; break; } case (Rot270): { transform = Matrix::rotate270; break; } case (Rot0): { transform = Matrix::none; break; } default: { kError( 51000 ) << "ImageRotate: Nonstandard rotation angle" << endl; err = i18n("Nonstandard rotation angle"); return false; } } return transformJPEG(src, dest, transform, err, updateFileTimeStamp); } bool ImageRotate::rotateImageMagick(const QString& src, const QString& dest, RotateAction angle, QString& err) { KProcess process; process.clearProgram(); process << "convert"; process << "-rotate"; switch(angle) { case (Rot90): { process << "90"; break; } case (Rot180): { process << "180"; break; } case (Rot270): { process << "270"; break; } case (Rot0): { break; } default: { kError( 51000 ) << "ImageRotate: Nonstandard rotation angle" << endl; err = i18n("Nonstandard rotation angle"); return false; } } process << src + QString("[0]") << dest; kDebug( 51000 ) << "ImageMagick Command line: " << process.program() << endl; process.start(); if (!process.waitForFinished()) return false; if (process.exitStatus() != QProcess::NormalExit) return false; switch (process.exitCode()) { case 0: // Process finished successfully ! { return true; break; } case 15: // process aborted ! { return false; break; } } // Processing error ! m_stdErr = process.readAllStandardError(); err = i18n("Cannot rotate: %1", m_stdErr.replace('\n', ' ')); return false; } } // namespace KIPIJPEGLossLessPlugin
ruphy/kipi-plugins
jpeglossless/imagerotate.cpp
C++
gpl-2.0
5,473
package org.mo.game.editor.core.entity.common; import org.mo.game.editor.core.entity.base.XBaseEntityItemTemplate; public class XEntityItemTemplate extends XBaseEntityItemTemplate{ private static final long serialVersionUID = 1L; }
favedit/MoPlatform
mo-gm-develop/src/editor-java/org/mo/game/editor/core/entity/common/XEntityItemTemplate.java
Java
gpl-2.0
245
package data; import java.io.File; import java.io.FileReader; import java.util.HashMap; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * This class contains all different types of incidents that can arrive. * * @author Alexandre Fourgs * */ public class IncidentDatabase { private static IncidentDatabase INSTANCE = new IncidentDatabase(); private HashMap<Integer, IncidentData> incidentDatabase = new HashMap<Integer, IncidentData>(); private IncidentDatabase(){ incidentDatabase = incidentParsing(); } /** * Parses the .json file of incident and create a HashMap containing parsed data. * * @return a HashMap object that contains all types of incident & informations about it. * */ private HashMap<Integer, IncidentData> incidentParsing(){ HashMap<Integer, IncidentData> incidentDatabase = new HashMap<Integer, IncidentData>(); File json = new File("data/incident.json"); JSONParser fileParser = new JSONParser(); try { Object obj = fileParser.parse(new FileReader(json)); JSONObject jsonObject = (JSONObject) obj ; JSONArray schedulesArray = (JSONArray) jsonObject.get("Incident"); Iterator it = schedulesArray.iterator(); while (it.hasNext()) { JSONObject innerObj = (JSONObject) it.next(); int id = Integer.parseInt((String) innerObj.get("Id")); IncidentData actual = new IncidentData(id, (String)innerObj.get("Type"), Integer.parseInt((String) innerObj.get("Min_Time")), Integer.parseInt((String) innerObj.get("Max_Time"))); incidentDatabase.put(id, actual); } } catch (Exception e){ e.printStackTrace(); } return incidentDatabase ; } /** * Getter of the current initialized instance of IncidentDatabase * @return the initialized instance of IncidentDatabase */ public static IncidentDatabase getInstance(){ return INSTANCE ; } public HashMap<Integer, IncidentData> getIncidentDatabase(){ return incidentDatabase ; } }
Uinelj/logirail
src/data/IncidentDatabase.java
Java
gpl-2.0
2,182
/* A useful and efficient way to use compile-time recursion, partial template specialization and variadic template parameter pack by rangerprice, alias absorbement. */ template <typename Val, typename Type, typename...Args> inline void push(const std::pair<const Val, Type> var, const Args&...args) noexcept { const void* const valueptr = &var.first; operations[var.second](valueptr); nb_param++; push(args...); }; void push() const noexcept { }; template <typename...Args> void call(const std::string & fname, const Args&...args) noexcept { lua_settop(context, 0); lua_getglobal(context, fname.c_str()); push(args...); lua_call(context, nb_param, LUA_MULTRET); };
rangerprice/simplified-lua-api
source/template/slacore.tpl.cpp
C++
gpl-2.0
697
/* * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.retest.swingset3.demos.spinner; import javax.swing.*; import java.awt.*; /** * Arranges labels and spinners into two vertical columns. Labels at the left, spinners at the right. * * @author Mikhail Lapshin */ //<snip>Helpful component for layout of labeled spinners public class JSpinnerPanel extends JPanel { private final JPanel labelPanel; private final JPanel spinnerPanel; public JSpinnerPanel() { setLayout( new BoxLayout( this, BoxLayout.X_AXIS ) ); labelPanel = new JPanel(); labelPanel.setLayout( new GridLayout( 0, 1 ) ); spinnerPanel = new JPanel(); spinnerPanel.setLayout( new GridLayout( 0, 1 ) ); add( labelPanel ); add( Box.createHorizontalStrut( 5 ) ); add( spinnerPanel ); } public void addSpinner( String labelText, JSpinner spinner ) { JLabel label = new JLabel( labelText ); label.setHorizontalAlignment( SwingConstants.TRAILING ); labelPanel.add( label ); JPanel flowPanel = new JPanel(); flowPanel.setLayout( new FlowLayout( FlowLayout.LEADING, 5, 1 ) ); flowPanel.add( spinner ); spinnerPanel.add( flowPanel ); } } //</snip>
retest/swingset3
src/org/retest/swingset3/demos/spinner/JSpinnerPanel.java
Java
gpl-2.0
2,708
from unittest import mock from flask import request from routersploit.modules.exploits.routers.tplink.wdr740nd_wdr740n_backdoor import Exploit def apply_response(*args, **kwargs): cmd = request.args["cmd"] data = 'TEST; var cmdResult = new Array(\n"' + cmd + '",\n0,0 ); TEST' return data, 200 @mock.patch("routersploit.modules.exploits.routers.tplink.wdr740nd_wdr740n_backdoor.shell") def test_check_success(mocked_shell, target): """ Test scenario - successful check """ route_mock = target.get_route_mock("/userRpm/DebugResultRpm.htm", methods=["GET"]) route_mock.side_effect = apply_response exploit = Exploit() assert exploit.target == "" assert exploit.port == 80 assert exploit.username == "admin" assert exploit.password == "admin" exploit.target = target.host exploit.port = target.port assert exploit.check() assert exploit.run() is None
dasseclab/dasseclab
clones/routersploit/tests/exploits/routers/tplink/test_wdr740nd_wdr740n_backdoor.py
Python
gpl-2.0
917
<?php /*download sample.csv*/ $csvfilepath = get_option( 'home' ) ."/wp-content/themes/".get_option( 'template' )."/sample_csv.csv"; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header("Content-Type: image/png"); header("Content-type: application/force-download"); header('Content-Disposition: inline; filename="sample_csv.csv"'); header('Content-Transfer-Encoding: binary'); readfile($csvfilepath); exit; ?>
epgmedia/thunderpress-calendar
wp-content/themes/Events/library/includes/csvdl.php
PHP
gpl-2.0
488
class BadgeGrouping < ActiveRecord::Base GettingStarted = 1 Community = 2 Posting = 3 TrustLevel = 4 Other = 5 has_many :badges end # == Schema Information # # Table name: badge_groupings # # id :integer not null, primary key # name :string(255) not null # description :string(255) not null # position :integer not null # created_at :datetime # updated_at :datetime #
zoubeiri/discourse-snowboard
app/models/badge_grouping.rb
Ruby
gpl-2.0
438
#region Header // Vorspire _,-'/-'/ ProfileRankOrder.cs // . __,-; ,'( '/ // \. `-.__`-._`:_,-._ _ , . `` // `:-._,------' ` _,`--` -: `_ , ` ,' : // `---..__,,--' (C) 2016 ` -'. -' // # Vita-Nex [http://core.vita-nex.com] # // {o)xxx|===============- # -===============|xxx(o} // # The MIT License (MIT) # #endregion namespace VitaNex.Modules.AutoPvP { public enum PvPProfileRankOrder { None, Points, Wins, Kills } }
Andries1985/Shards-of-Nagash
Scripts/VitaNex/Core/Modules/AutoPVP/Objects/Profile/ProfileRankOrder.cs
C#
gpl-2.0
507
<?php /** * The template for displaying the footer * * Contains the closing of the "site-content" div and all content after. * * @package WordPress * @subpackage Twenty_Fifteen * @since Twenty Fifteen 1.0 */ ?> <footer class="bmg-l-footer"> <div class="bmg-l-footer__inner"> <div class="bmg-l-footer__nav"> <div class="bmg-l-footer__country"> <ul> <li> <a class="bmg-l-footer__flag js-user-location-modal" href="javascript:void(0);"> <img width="18" src="/assets/images/flag/phl-a2a1a5476b.png" alt="Philippines">Philippines </a> </li> <li> $USD <a class="bmg-l-footer__country-edit js-user-location-modal" href="javascript:void(0);">EDIT</a> </li> </ul> </div> <nav class="verticalmenu"> <ul> <li> <a href="/aboutbuyma/">About BUYMA</a> </li> <li> <a target="_blank" href="https://buyma-us.zendesk.com/">FAQ</a> </li> <li> <a href="/contact/">Contact us</a> </li> </ul> <ul> <li><a href="/terms/">Terms of Use</a></li> <li><a href="/privacy/">Privacy Policy</a></li> <li><a href="/notice_and_takedown/">Notice and Takedown Policy</a></li> <li><a href="/tradelaw/">Mark based on specific trade law</a></li> <li> <a target="_blank" href="http://www.enigmo.co.jp/en/">enigmo</a> </li> </ul> </nav> </div> <p class="footer-tagline">BUYMA - A new online personal shopping experience</p> <div class="bmg-l-footer__outer-nav"> <nav> <ul> <li> <a target="_blank" href="http://www.buyma.com/">BUYMA.com (JP)</a> </li> <li> <a target="_blank" href="http://buymakorea.com/pages/?">BUYMA Korea</a> </li> <li> <a target="_blank" href="https://stylehaus.jp/">STYLE HAUS</a> </li> <li> <a target="_blank" href="https://www.stulio.jp/">STULIO</a> </li> <li> <a target="_blank" href="http://www.buymabooks.com/">BUYMA Books</a> </li> <li> <a target="_blank" href="http://toptip.jp/">toptip</a> </li> </ul> </nav> <p> <small>©2005 Enigmo Inc. All rights reserved.</small> </p> </div> </div> </footer> <?php wp_footer(); ?> </body> </html>
goygoybords/buyma
wp-content/themes/twentyfifteen/footer.php
PHP
gpl-2.0
2,372
<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package Monaco */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
techborder/wp
wp-content/themes/monaco/page.php
PHP
gpl-2.0
849
/* 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 "common/system.h" #include "titanic/sound/qmixer.h" #include "titanic/titanic.h" namespace Titanic { QMixer::QMixer(Audio::Mixer *mixer) : _mixer(mixer) { } bool QMixer::qsWaveMixInitEx(const QMIXCONFIG &config) { assert(_channels.empty()); assert(config.iChannels > 0 && config.iChannels < 256); _channels.resize(config.iChannels); return true; } void QMixer::qsWaveMixActivate(bool fActivate) { // Not currently implemented in ScummVM } int QMixer::qsWaveMixOpenChannel(int iChannel, QMixFlag mode) { // Not currently implemented in ScummVM return 0; } int QMixer::qsWaveMixEnableChannel(int iChannel, uint flags, bool enabled) { // Not currently implemented in ScummVM return 0; } void QMixer::qsWaveMixCloseSession() { _mixer->stopAll(); _channels.clear(); } void QMixer::qsWaveMixFreeWave(Audio::SoundHandle &handle) { _mixer->stopHandle(handle); } void QMixer::qsWaveMixFlushChannel(int iChannel, uint flags) { if (flags & QMIX_OPENALL) { // Ignore channel, and flush all the channels for (uint idx = 0; idx < _channels.size(); ++idx) qsWaveMixFlushChannel(idx, 0); } else { // Flush the specified channel Common::List<SoundEntry>::iterator i; Common::List<SoundEntry> &sounds = _channels[iChannel]._sounds; for (i = sounds.begin(); i != sounds.end(); ++i) _mixer->stopHandle((*i)._soundHandle); sounds.clear(); } } void QMixer::qsWaveMixSetPanRate(int iChannel, uint flags, uint rate) { ChannelEntry &channel = _channels[iChannel]; channel._panRate = rate; channel._volumeChangeStart = channel._volumeChangeEnd = 0; } void QMixer::qsWaveMixSetVolume(int iChannel, uint flags, uint volume) { ChannelEntry &channel = _channels[iChannel]; // QMixer volumes go from 0-32767, but we need to convert to 0-255 for ScummVM assert(volume <= 32767); byte newVolume = (volume >= 32700) ? 255 : volume * 255 / 32767; channel._volumeStart = channel._volume; channel._volumeEnd = newVolume; channel._volumeChangeStart = g_system->getMillis(); channel._volumeChangeEnd = channel._volumeChangeStart + channel._panRate; debugC(DEBUG_DETAILED, kDebugCore, "qsWaveMixSetPanRate vol=%d to %d, start=%u, end=%u", channel._volumeStart, channel._volumeEnd, channel._volumeChangeStart, channel._volumeChangeEnd); } void QMixer::qsWaveMixSetSourcePosition(int iChannel, uint flags, const QSVECTOR &position) { ChannelEntry &channel = _channels[iChannel]; // Flag whether distance should reset when a new sound is started channel._resetDistance = (flags & QMIX_USEONCE) != 0; // Currently, we only do a basic simulation of spatial positioning by // getting the distance, and proportionately reducing the volume the // further away the source is channel._distance = sqrt(position.x * position.x + position.y * position.y + position.z * position.z); } void QMixer::qsWaveMixSetPolarPosition(int iChannel, uint flags, const QSPOLAR &position) { ChannelEntry &channel = _channels[iChannel]; // Flag whether distance should reset when a new sound is started channel._resetDistance = (flags & QMIX_USEONCE) != 0; // Currently, we only do a basic simulation of spatial positioning by // getting the distance, and proportionately reducing the volume the // further away the source is channel._distance = position.range; } void QMixer::qsWaveMixSetListenerPosition(const QSVECTOR &position, uint flags) { // Not currently implemented in ScummVM } void QMixer::qsWaveMixSetListenerOrientation(const QSVECTOR &direction, const QSVECTOR &up, uint flags) { // Not currently implemented in ScummVM } void QMixer::qsWaveMixSetDistanceMapping(int iChannel, uint flags, const QMIX_DISTANCES &distances) { // Not currently implemented in ScummVM } void QMixer::qsWaveMixSetFrequency(int iChannel, uint flags, uint frequency) { // Not currently implemented in ScummVM } void QMixer::qsWaveMixSetSourceVelocity(int iChannel, uint flags, const QSVECTOR &velocity) { // Not currently implemented in ScummVM } int QMixer::qsWaveMixPlayEx(int iChannel, uint flags, CWaveFile *waveFile, int loops, const QMIXPLAYPARAMS &params) { if (iChannel == -1) { // Find a free channel for (iChannel = 0; iChannel < (int)_channels.size(); ++iChannel) { if (_channels[iChannel]._sounds.empty()) break; } assert(iChannel != (int)_channels.size()); } // If the new sound replaces current ones, then clear the channel ChannelEntry &channel = _channels[iChannel]; if (flags & QMIX_CLEARQUEUE) { if (!channel._sounds.empty() && channel._sounds.front()._started) _mixer->stopHandle(channel._sounds.front()._soundHandle); channel._sounds.clear(); } // Add the sound to the channel channel._sounds.push_back(SoundEntry(waveFile, params.callback, loops, params.dwUser)); qsWaveMixPump(); return 0; } bool QMixer::qsWaveMixIsChannelDone(int iChannel) const { return _channels[iChannel]._sounds.empty(); } void QMixer::qsWaveMixPump() { // Iterate through each of the channels for (uint iChannel = 0; iChannel < _channels.size(); ++iChannel) { ChannelEntry &channel = _channels[iChannel]; // If there's a transition in sound volume in progress, handle it if (channel._volumeChangeEnd) { byte oldVolume = channel._volume; uint currentTicks = g_system->getMillis(); if (currentTicks >= channel._volumeChangeEnd) { // Reached end of transition period channel._volume = channel._volumeEnd; channel._volumeChangeStart = channel._volumeChangeEnd = 0; } else { // Transition in progress, so figure out new volume channel._volume = (int)channel._volumeStart + ((int)channel._volumeEnd - (int)channel._volumeStart) * (int)(currentTicks - channel._volumeChangeStart) / (int)channel._panRate; } debugC(DEBUG_DETAILED, kDebugCore, "qsWaveMixPump time=%u vol=%d", currentTicks, channel._volume); if (channel._volume != oldVolume && !channel._sounds.empty() && channel._sounds.front()._started) { _mixer->setChannelVolume(channel._sounds.front()._soundHandle, channel.getRawVolume()); } } // If the playing sound on the channel is finished, then call // the callback registered for it, and remove it from the list if (!channel._sounds.empty()) { SoundEntry &sound = channel._sounds.front(); if (sound._started && !_mixer->isSoundHandleActive(sound._soundHandle)) { // Sound is finished if (sound._callback) // Call the callback to signal end sound._callback(iChannel, sound._waveFile, sound._userData); // Remove sound record from channel channel._sounds.erase(channel._sounds.begin()); } } // If there's an unstarted sound at the front of a channel's // sound list, then start it playing if (!channel._sounds.empty()) { SoundEntry &sound = channel._sounds.front(); if (!sound._started) { if (channel._resetDistance) channel._distance = 0.0; // Play the wave sound._soundHandle = sound._waveFile->play( sound._loops, channel.getRawVolume()); sound._started = true; } } } } /*------------------------------------------------------------------------*/ byte QMixer::ChannelEntry::getRawVolume() const { // Emperically decided adjustment divisor for distances const double ADJUSTMENT_FACTOR = 5.0; double r = 1.0 + (_distance / ADJUSTMENT_FACTOR); double percent = 1.0 / (r * r); double newVolume = _volume * percent; return (byte)newVolume; } } // End of namespace Titanic
yinsimei/scummvm
engines/titanic/sound/qmixer.cpp
C++
gpl-2.0
8,371
""" USAGE: twitter [action] [options] ACTIONS: follow add the specified user to your follow list friends get latest tweets from your friends (default action) help print this help text that you are currently reading leave remove the specified user from your following list public get latest public tweets replies get latest replies set set your twitter status shell login the twitter shell OPTIONS: -e --email <email> your email to login to twitter -p --password <password> your twitter password -r --refresh run this command forever, polling every once in a while (default: every 5 minutes) -R --refresh-rate <rate> set the refresh rate (in seconds) -f --format <format> specify the output format for status updates -c --config <filename> read username and password from given config file (default ~/.twitter) -l --length <count> specify number of status updates shown (default: 20, max: 200) -t --timestamp show time before status lines -d --datestamp shoe date before status lines FORMATS for the --format option default one line per status verbose multiple lines per status, more verbose status info urls nothing but URLs ansi ansi colour (rainbow mode) CONFIG FILES The config file should contain a [twitter] header, and all the desired options you wish to set, like so: [twitter] email: <username> password: <password> format: <desired_default_format_for_output> prompt: <twitter_shell_prompt e.g. '[cyan]twitter[R]> '> """ import sys import time from getopt import gnu_getopt as getopt, GetoptError from getpass import getpass import re import os.path from ConfigParser import SafeConfigParser import datetime from api import Twitter, TwitterError import ansi # Please don't change this, it was provided by the fine folks at Twitter. # If you change it, it will not work. AGENT_STR = "twittercommandlinetoolpy" OPTIONS = { 'email': None, 'password': None, 'action': 'friends', 'refresh': False, 'refresh_rate': 600, 'format': 'default', 'prompt': '[cyan]twitter[R]> ', 'config_filename': os.environ.get('HOME', '') + os.sep + '.twitter', 'length': 20, 'timestamp': False, 'datestamp': False, 'extra_args': [] } def parse_args(args, options): long_opts = ['email', 'password', 'help', 'format', 'refresh', 'refresh-rate', 'config', 'length', 'timestamp', 'datestamp'] short_opts = "e:p:f:h?rR:c:l:td" opts, extra_args = getopt(args, short_opts, long_opts) for opt, arg in opts: if opt in ('-e', '--email'): options['email'] = arg elif opt in ('-p', '--password'): options['password'] = arg elif opt in ('-f', '--format'): options['format'] = arg elif opt in ('-r', '--refresh'): options['refresh'] = True elif opt in ('-R', '--refresh-rate'): options['refresh_rate'] = int(arg) elif opt in ('-l', '--length'): options["length"] = int(arg) elif opt in ('-t', '--timestamp'): options["timestamp"] = True elif opt in ('-d', '--datestamp'): options["datestamp"] = True elif opt in ('-?', '-h', '--help'): options['action'] = 'help' elif opt in ('-c', '--config'): options['config_filename'] = arg if extra_args and not ('action' in options and options['action'] == 'help'): options['action'] = extra_args[0] options['extra_args'] = extra_args[1:] def get_time_string(status, options): timestamp = options["timestamp"] datestamp = options["datestamp"] t = time.strptime(status['created_at'], "%a %b %d %H:%M:%S +0000 %Y") i_hate_timezones = time.timezone if (time.daylight): i_hate_timezones = time.altzone dt = datetime.datetime(*t[:-3]) - datetime.timedelta( seconds=i_hate_timezones) t = dt.timetuple() if timestamp and datestamp: return time.strftime("%Y-%m-%d %H:%M:%S ", t) elif timestamp: return time.strftime("%H:%M:%S ", t) elif datestamp: return time.strftime("%Y-%m-%d ", t) return "" class StatusFormatter(object): def __call__(self, status): return (u"%S%s %s" %( get_time_string(status, options), status['user']['screen_name'], status['text'])) class AnsiStatusFormatter(object): def __init__(self): self._colourMap = ansi.ColourMap() def __call__(self, status, options): colour = self._colourMap.colourFor(status['user']['screen_name']) return (u"%s%s%s%s %s" %( get_time_string(status, options), ansi.cmdColour(colour), status['user']['screen_name'], ansi.cmdReset(), status['text'])) class VerboseStatusFormatter(object): def __call__(self, status, options): return (u"-- %s (%s) on %s\n%s\n" %( status['user']['screen_name'], status['user']['location'], status['created_at'], status['text'])) class URLStatusFormatter(object): urlmatch = re.compile(r'https?://\S+') def __call__(self, status, options): urls = self.urlmatch.findall(status['text']) return u'\n'.join(urls) if urls else "" class AdminFormatter(object): def __call__(self, action, user): user_str = u"%s (%s)" %(user['screen_name'], user['name']) if action == "follow": return u"You are now following %s.\n" %(user_str) else: return u"You are no longer following %s.\n" %(user_str) class VerboseAdminFormatter(object): def __call__(self, action, user): return(u"-- %s: %s (%s): %s" % ( "Following" if action == "follow" else "Leaving", user['screen_name'], user['name'], user['url'])) status_formatters = { 'default': StatusFormatter, 'verbose': VerboseStatusFormatter, 'urls': URLStatusFormatter, 'ansi': AnsiStatusFormatter } admin_formatters = { 'default': AdminFormatter, 'verbose': VerboseAdminFormatter, 'urls': AdminFormatter, 'ansi': AdminFormatter } def get_status_formatter(options): sf = status_formatters.get(options['format']) if (not sf): raise TwitterError( "Unknown formatter '%s'" %(options['format'])) return sf() def get_admin_formatter(options): sf = admin_formatters.get(options['format']) if (not sf): raise TwitterError( "Unknown formatter '%s'" %(options['format'])) return sf() class Action(object): def ask(self, subject='perform this action', careful=False): ''' Requests fromt he user using `raw_input` if `subject` should be performed. When `careful`, the default answer is NO, otherwise YES. Returns the user answer in the form `True` or `False`. ''' sample = '(y/N)' if not careful: sample = '(Y/n)' prompt = 'You really want to %s %s? ' %(subject, sample) try: answer = raw_input(prompt).lower() if careful: return answer in ('yes', 'y') else: return answer not in ('no', 'n') except EOFError: print >>sys.stderr # Put Newline since Enter was never pressed # TODO: # Figure out why on OS X the raw_input keeps raising # EOFError and is never able to reset and get more input # Hint: Look at how IPython implements their console default = True if careful: default = False return default def __call__(self, twitter, options): action = actions.get(options['action'], NoSuchAction)() try: doAction = lambda : action(twitter, options) if (options['refresh'] and isinstance(action, StatusAction)): while True: doAction() time.sleep(options['refresh_rate']) else: doAction() except KeyboardInterrupt: print >>sys.stderr, '\n[Keyboard Interrupt]' pass class NoSuchActionError(Exception): pass class NoSuchAction(Action): def __call__(self, twitter, options): raise NoSuchActionError("No such action: %s" %(options['action'])) def printNicely(string): if sys.stdout.encoding: print string.encode(sys.stdout.encoding, 'replace') else: print string.encode('utf-8') class StatusAction(Action): def __call__(self, twitter, options): statuses = self.getStatuses(twitter, options) sf = get_status_formatter(options) for status in statuses: statusStr = sf(status, options) if statusStr.strip(): printNicely(statusStr) class AdminAction(Action): def __call__(self, twitter, options): if not (options['extra_args'] and options['extra_args'][0]): raise TwitterError("You need to specify a user (screen name)") af = get_admin_formatter(options) try: user = self.getUser(twitter, options['extra_args'][0]) except TwitterError, e: print "There was a problem following or leaving the specified user." print "You may be trying to follow a user you are already following;" print "Leaving a user you are not currently following;" print "Or the user may not exist." print "Sorry." print print e else: printNicely(af(options['action'], user)) class FriendsAction(StatusAction): def getStatuses(self, twitter, options): return reversed(twitter.statuses.friends_timeline(count=options["length"])) class PublicAction(StatusAction): def getStatuses(self, twitter, options): return reversed(twitter.statuses.public_timeline(count=options["length"])) class RepliesAction(StatusAction): def getStatuses(self, twitter, options): return reversed(twitter.statuses.replies(count=options["length"])) class FollowAction(AdminAction): def getUser(self, twitter, user): return twitter.friendships.create(id=user) class LeaveAction(AdminAction): def getUser(self, twitter, user): return twitter.friendships.destroy(id=user) class SetStatusAction(Action): def __call__(self, twitter, options): statusTxt = (u" ".join(options['extra_args']) if options['extra_args'] else unicode(raw_input("message: "))) status = (statusTxt.encode('utf8', 'replace')) twitter.statuses.update(status=status) class TwitterShell(Action): def render_prompt(self, prompt): '''Parses the `prompt` string and returns the rendered version''' prompt = prompt.strip("'").replace("\\'","'") for colour in ansi.COLOURS_NAMED: if '[%s]' %(colour) in prompt: prompt = prompt.replace( '[%s]' %(colour), ansi.cmdColourNamed(colour)) prompt = prompt.replace('[R]', ansi.cmdReset()) return prompt def __call__(self, twitter, options): prompt = self.render_prompt(options.get('prompt', 'twitter> ')) while True: options['action'] = "" try: args = raw_input(prompt).split() parse_args(args, options) if not options['action']: continue elif options['action'] == 'exit': raise SystemExit(0) elif options['action'] == 'shell': print >>sys.stderr, 'Sorry Xzibit does not work here!' continue elif options['action'] == 'help': print >>sys.stderr, '''\ntwitter> `action`\n The Shell Accepts all the command line actions along with: exit Leave the twitter shell (^D may also be used) Full CMD Line help is appended below for your convinience.''' Action()(twitter, options) options['action'] = '' except NoSuchActionError, e: print >>sys.stderr, e except KeyboardInterrupt: print >>sys.stderr, '\n[Keyboard Interrupt]' except EOFError: print >>sys.stderr leaving = self.ask(subject='Leave') if not leaving: print >>sys.stderr, 'Excellent!' else: raise SystemExit(0) class HelpAction(Action): def __call__(self, twitter, options): print __doc__ actions = { 'follow' : FollowAction, 'friends' : FriendsAction, 'help' : HelpAction, 'leave' : LeaveAction, 'public' : PublicAction, 'replies' : RepliesAction, 'set' : SetStatusAction, 'shell' : TwitterShell, } def loadConfig(filename): options = dict(OPTIONS) if os.path.exists(filename): cp = SafeConfigParser() cp.read([filename]) for option in ('email', 'password', 'format', 'prompt'): if cp.has_option('twitter', option): options[option] = cp.get('twitter', option) return options def main(args=sys.argv[1:]): arg_options = {} try: parse_args(args, arg_options) except GetoptError, e: print >> sys.stderr, "I can't do that, %s." %(e) print >> sys.stderr raise SystemExit(1) config_options = loadConfig( arg_options.get('config_filename') or OPTIONS.get('config_filename')) # Apply the various options in order, the most important applied last. # Defaults first, then what's read from config file, then command-line # arguments. options = dict(OPTIONS) for d in config_options, arg_options: for k,v in d.items(): if v: options[k] = v if options['refresh'] and options['action'] not in ( 'friends', 'public', 'replies'): print >> sys.stderr, "You can only refresh the friends, public, or replies actions." print >> sys.stderr, "Use 'twitter -h' for help." raise SystemExit(1) if options['email'] and not options['password']: options['password'] = getpass("Twitter password: ") twitter = Twitter(options['email'], options['password'], agent=AGENT_STR) try: Action()(twitter, options) except NoSuchActionError, e: print >>sys.stderr, e raise SystemExit(1) except TwitterError, e: print >> sys.stderr, e.args[0] print >> sys.stderr, "Use 'twitter -h' for help." raise SystemExit(1)
avsm/lifedb-plugins
Twitter/twitter/cmdline.py
Python
gpl-2.0
15,027
package si.virag.parkomat.modules; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.support.annotation.NonNull; import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout; import com.wdullaer.materialdatetimepicker.time.TimePickerDialog; import org.threeten.bp.LocalTime; import org.threeten.bp.temporal.ChronoField; import org.threeten.bp.temporal.ChronoUnit; import rx.Observable; import rx.Subscriber; /** * Handles parking time related things */ public class TimeManager { @NonNull private final Context appContext; public TimeManager(@NonNull Context applicationContext) { this.appContext = applicationContext; } public LocalTime initialDisplayedTime() { return LocalTime.now().plus(1, ChronoUnit.HOURS); } public Observable<LocalTime> pickTime(@NonNull final Activity owner, @NonNull final LocalTime currentlySelected) { return Observable.create(new Observable.OnSubscribe<LocalTime>() { @Override public void call(final Subscriber<? super LocalTime> subscriber) { TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) { LocalTime instant = LocalTime.now() .with(ChronoField.HOUR_OF_DAY, hourOfDay) .with(ChronoField.MINUTE_OF_HOUR, minute); subscriber.onNext(instant); } }; DialogInterface.OnDismissListener dismissListener = new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { subscriber.onCompleted(); } }; TimePickerDialog dialog = TimePickerDialog.newInstance(listener, currentlySelected.get(ChronoField.HOUR_OF_DAY), currentlySelected.get(ChronoField.MINUTE_OF_HOUR), true); dialog.setOnDismissListener(dismissListener); dialog.show(owner.getFragmentManager(), "TimePicker"); } }); } }
izacus/Parkomat
app/src/main/java/si/virag/parkomat/modules/TimeManager.java
Java
gpl-2.0
2,335
<?php if(!defined("IN_ESOTALK")) exit; /** * OpauthConnect * * @copyright Copyright © 2012 Oleksandr Golubtsov * @license GPLv2 License * @package OpauthСonnect * * This file is part of OpauthСonnect plugin. Please see the included license file for usage information */ ET::$pluginInfo["OpauthConnect"] = array( "name" => "OpauthConnect", "description" => "Sign in via social networks", "version" => "2.1", "author" => "Oleksandr Golubtsov", "authorEmail" => "alex.8fmi@gmail.com", "authorURL" => "http://alex-dev.me", "license" => "GPLv2" ); require_once "classes".DIRECTORY_SEPARATOR."OCServices.php"; require_once "classes".DIRECTORY_SEPARATOR."OpauthConnect.php"; require_once "classes".DIRECTORY_SEPARATOR."OCSettings.php"; class ETPlugin_OpauthConnect extends ETPlugin { private $settings; private $services; private $opauth_connect; public function __construct($rootDirectory) { parent::__construct($rootDirectory); ETFactory::register("ocMemberSocialModel", "OcMemberSocialModel", dirname(__FILE__)."/models/OcMemberSocialModel.class.php"); ETFactory::register("ocSettingsModel", "OcSettingsModel", dirname(__FILE__)."/models/OcSettingsModel.class.php"); $this->services = new OCServices; $this->settings = new OCSettings; } public function handler_init($sender) { if(ET::$session->get("remember") === null) ET::$session->store("remember", 1); $sender->addCSSFile($this->resource("css/opauthconnect.css")); $sender->addJSFile($this->resource("js/opauthconnect.js")); $config = array(); $config['security_salt'] = $this->settings->get(OCSettings::SECURITY_SALT); $config['path'] = URL('user/social/'); $config['callback_url'] = URL('user/social/callback/'); foreach($this->services as $service) { if($this->settings->get($service->settings->enabled)) { $config['Strategy'][$service->name] = array( $service->key => $this->settings->get($service->settings->key), $service->secret => $this->settings->get($service->settings->secret) ); foreach($service->static as $name => $value) { $config['Strategy'][$service->name][$name] = $value; } } } $this->opauth_connect = new OpauthConnect($config); } public function handler_initAdmin($sender, $menu) { $sender->addCSSFile($this->resource("css/backend.css")); $sender->addJSFile($this->resource("js/backend.js")); } public function handler_renderOpauth($sender) { $data = array( 'remember' => ET::$session->get("remember", 0), 'services' => array() ); foreach($this->services as $service) { if($this->settings->get($service->settings->enabled)) { $data['services'][$service->name] = array( 'url' => URL('user/social/'.$service->machine_name), 'icon' => URL($this->resource($service->icon)) ); } } $sender->renderView('social/oc_buttons', $data); } public function handler_settingsController_renderBefore($sender) { if(isset($sender->data['panes']) && !empty($sender->data['panes'])) { $sender->data['panes']->add('social_accounts', "<a href='".URL("settings/social/accounts")."'>".T("Social Accounts")."</a>"); } } private function login($memberId) { if($memberId) { ET::$session->loginWithMemberId($memberId); if(ET::$session->get("remember")) ET::$session->setRememberCookie($memberId); } redirect(URL()); } public function settings($sender) { $form = ETFactory::make("form"); $form->action = URL("admin/plugins/settings/OpauthConnect"); if($form->validPostBack("save") && !$form->errorCount()) { $this->settings->set(OCSettings::PASS_EMAIL_SUBJ, $form->getValue(OCSettings::PASS_EMAIL_SUBJ)); $this->settings->set(OCSettings::CONFIRM_EMAIL_SUBJ, $form->getValue(OCSettings::CONFIRM_EMAIL_SUBJ)); $this->settings->set(OCSettings::ALLOW_UNLINK, $form->getValue(OCSettings::ALLOW_UNLINK)); $this->settings->set(OCSettings::SECURITY_SALT, $form->getValue(OCSettings::SECURITY_SALT)); foreach($this->services as $service) { foreach($service->settings as $setting) { $this->settings->set($setting, $form->getValue($setting)); } } $this->settings->save(); $sender->message(T("message.changesSaved"), "success"); $sender->redirect(URL("admin/plugins")); } $form->setValue(OCSettings::SECURITY_SALT, $this->settings->get(OCSettings::SECURITY_SALT)); $form->setValue(OCSettings::ALLOW_UNLINK, $this->settings->get(OCSettings::ALLOW_UNLINK)); $form->setValue(OCSettings::CONFIRM_EMAIL_SUBJ, $this->settings->get(OCSettings::CONFIRM_EMAIL_SUBJ)); $form->setValue(OCSettings::PASS_EMAIL_SUBJ, $this->settings->get(OCSettings::PASS_EMAIL_SUBJ)); $form_services = array(); foreach($this->services as $service) { $form_services[$service->machine_name]['name'] = $service->name; $form_services[$service->machine_name]['raw_key'] = $service->key; $form_services[$service->machine_name]['raw_secret'] = $service->secret; foreach($service->settings as $k => $v) { $form_services[$service->machine_name][$k] = array( "key" => $v, "value" => $this->settings->get($v) ); } } $sender->data("form", $form); $sender->data("form_services", $form_services); return $this->view('admin/oc_settings'); } public function action_settingsController_social($sender, $action, $param1 = null) { switch($action) { case "accounts": $this->settings_social_accounts($sender); break; case "unlink": $this->settings_social_unlink_account($sender, $param1); break; default: $sender->render404(); break; } } private function settings_social_accounts($sender) { $sender->profile("social_accounts"); $accounts = ET::getInstance("ocMemberSocialModel")->getAccounts(ET::$session->userId); foreach($accounts as &$account) { $account["logo"] = URL($this->resource("images/settings/".$account["socialNetwork"].".png")); } $sender->data("accounts", $accounts); $sender->data("allow_unlink", $this->settings->get(OCSettings::ALLOW_UNLINK)); $sender->data("accounts_exist", !empty($accounts)); $sender->renderProfile($this->view("admin/oc_social_accounts")); } private function settings_social_unlink_account($sender, $id) { if(!$this->settings->get(OCSettings::ALLOW_UNLINK) || !ET::getInstance("ocMemberSocialModel")->isApropriateUser(ET::$session->userId, $id)) { $sender->render404(); return; } ET::getInstance("ocMemberSocialModel")->deleteById($id); redirect(URL("settings/social/accounts")); } public function setup($oldVersion = "") { ET::$database->structure()->table("member") ->dropColumn("fromSN") ->dropColumn("TWid") ->dropColumn("TWconfirmed") ->exec(false); ET::$database->structure()->table("oc_member_social") ->column("id", "int(11) unsigned", false) ->column("member_Id", "int(11) unsigned", false) ->column("socialNetwork", "varchar(255)", false) ->column("socialId", "varchar(255)", false) ->column("profileLink", "varchar(255)", false) ->column("name", "varchar(255)", false) ->column("confirmed", "tinyint unsigned", false) ->column("confirmationHash", "varchar(255)") ->column("confirmationSent", "int(11) unsigned", 0) ->key("id", "primary") ->key(array("socialNetwork","socialId"), "unique") ->exec(false); ET::$database->structure()->table("oc_settings") ->column("name", "varchar(50)", false) ->column("value", "varchar(100)", false) ->key("name", "primary") ->exec(false); ET::$database->query(strtr("ALTER TABLE [prefix]oc_member_social ADD FOREIGN KEY(member_Id) REFERENCES [prefix]member(memberId)", array('[prefix]' => C("esoTalk.database.prefix")))); // ET::$database->query($this->services->getSettingsSchemaQuery(C("esoTalk.database.prefix"))); return true; } private function social_auth($sender) { if(ET::$session->user) { $sender->message("You are already logged in"); redirect(URL()); } $this->opauth_connect->doRequest(); } private function social_callback($sender) { try { $response = $this->opauth_connect->getResponse(); switch($this->opauth_connect->validateAccount($response["static"]['uid'], $response["static"]['provider'])) { case OpauthConnect::ACCOUNT_CONFIRMED: $this->login($this->opauth_connect->getLastAccountValidation()); break; case OpauthConnect::ACCOUNT_NOT_EXISTS: ET::$session->store("OpauthConnect", $response["static"]); $this->social_setup($sender, $response["editable"]); return; case OpauthConnect::ACCOUNT_NOT_CONFIRMED: $sender->message("Your account was not confirmed. <a href='".URL("user/social/sendconfirmation/".$this->opauth_connect->getLastAccountValidation())."'>Send confirmation letter again</a>", "warning"); break; } } catch(Exception $ex) { $sender->message($ex->getMessage(), "warning"); } redirect(URL()); } private function social_confirm($sender, $hash) { if($result = ET::getInstance("ocMemberSocialModel")->validateConfirmationHash($hash)) { $sender->message(T("You successfully confirmed your new account"), "success"); $this->login($result); } $sender->message(T("Invalid confirmation hash"), "warning"); redirect(URL()); } private function social_remember() { ET::$session->store("remember", (int)R("remember", 0)); } private function social_sendConfirmation($sender, $row_id, $is_new_user) { $data = ET::getInstance("ocMemberSocialModel")->getConfirmationData($row_id); if(time() - $data["confirmationSent"] > OpauthConnect::CONFIRMATION_INTERVAL) { $params = array( "confirmationUrl" => URL("user/social/confirm/".$data['confirmationHash'], true), "profileLink" => $data["profileLink"], "socialName" => $data["name"], "socialNetwork" => $data["socialNetwork"], "userName" => $data["username"], "forumName" => C("esoTalk.forumTitle"), "isNewUser" => $is_new_user ); $title = strtr($this->settings->get(OCSettings::CONFIRM_EMAIL_SUBJ), array( "[forumName]" => C("esoTalk.forumTitle"), "[socialNetwork]" => $data["socialNetwork"], "[socialName]" => $data["name"], "[userName]" => $data["username"] )); sendEmail($data["email"], $title, $sender->getViewContents('emails/oc_confirmation', $params)); ET::getInstance("ocMemberSocialModel")->sentConfirmation($row_id); $sender->message("Confirmation letter was sent to your e-mail address (".$data["email"].")", "success"); } else { $sender->message(T("Confirmation letter can be sent once per 5 minutes. Please wait"), "warning"); } redirect(URL()); } private function social_setup($sender, $form_data = array()) { $session_data = ET::$session->get("OpauthConnect"); if(!$session_data) { $sender->message(T("Time is out. Please, try again"), "warning"); redirect(URL("user/login")); } $email_only = false; if(ET::memberModel()->validateEmail($session_data["email"]) == "emailTaken") { $email_only = true; } $form = ETFactory::make("form"); $form->action = URL("user/social/setup"); $sender->data("show_password", false); if($form->validPostBack("save")) { if(!$session_data["email"]) { if(!$form->getValue("email")) { $form->error("email", T("Email must be set")); } if(ET::memberModel()->validateEmail($form->getValue("email"), false) !== null) { $form->error("email", T("Email is invalid")); } } if(!$email_only) { if(!$form->getValue("generate_password")) { // @TODO: refactor this in future $sender->data("show_password", true); if(ET::memberModel()->validatePassword($form->getValue("password")) !== null) { $form->error("password", T("Password is too shot")); } elseif($form->getValue("password") != $form->getValue("password_repeat")) { $form->error("password_repeat", T("Passwords not match")); } } switch(ET::memberModel()->validateUsername($form->getValue("username"))) { case 'nameTaken': $form->error("username", T("Username is already exists")); break; case 'invalidUsername': $form->error("username", T("Username is incorrect")); break; } } if(!$form->errorCount()) { if($session_data["email"]) { $email = $session_data["email"]; $needs_confirmation = false; } else { $email = $form->getValue("email"); $needs_confirmation = true; } switch(ET::memberModel()->validateEmail($email)) { case null: $password = $form->getValue("generate_password") ? generateRandomString(12, OpauthConnect::PASSWORD_CHARS) : $form->getValue("password"); if($form->getValue("generate_password")) { $params = array( "userName" => $form->getValue("username"), "password" => $password, "forumName" => C("esoTalk.forumTitle") ); $title = strtr($this->settings->get(OCSettings::PASS_EMAIL_SUBJ), array( "[forumName]" => C("esoTalk.forumTitle"), "[userName]" => $form->getValue("username") )); sendEmail($email, $title, $sender->getViewContents('emails/oc_password', $params)); } $data = array( "username" => $form->getValue("username"), "email" => $email, "password" => $password, "account" => ACCOUNT_MEMBER, "confirmed" => true //this field is not used. just dummy value ); $memberId = ET::memberModel()->create($data); $avatar_exists = false; $is_new_user = true; break; case "emailTaken": $member = ET::memberModel()->get(array("email" => $email)); $avatar_exists = $member[0]["avatarFormat"]; $memberId = $member[0]["memberId"]; $is_new_user = null; break; } ET::$session->remove("OpauthConnect"); if(!$avatar_exists && $form->getValue("avatar")) { $avatar = ET::uploader()->saveAsImage($form->getValue("avatar"), PATH_UPLOADS."/avatars/".$memberId, C("esoTalk.avatars.width"), C("esoTalk.avatars.height"), "crop"); ET::memberModel()->updateById($memberId, array("avatarFormat" => pathinfo($avatar, PATHINFO_EXTENSION))); } $row_id = ET::getInstance("ocMemberSocialModel")->addAccount( $memberId, $session_data["provider"], $session_data["uid"], $session_data["link"], $session_data["name"], !$needs_confirmation, $needs_confirmation ? md5(uniqid(rand())) : null ); if($needs_confirmation) { $this->social_sendConfirmation($sender, $row_id, $is_new_user); } else { $this->login($memberId); } } } foreach($form_data as $key => $value) { $form->setValue($key, $value); } $sender->data("show_email", true); if($session_data["email"]) { if($form->isPostBack()) $_POST['email'] = $session_data["email"]; else $form->setValue("email", $session_data["email"]); $sender->data("show_email", false); } $sender->data("email_only", $email_only); $sender->data("form", $form); $sender->render("social/oc_account_setup"); } public function action_userController_social($sender, $action, $param1 = null, $param2 = null) { switch($action) { case "setup": $this->social_setup($sender); break; case "callback": $this->social_callback($sender); break; case "sendconfirmation": $this->social_sendConfirmation($sender, $param1, $param2); break; case "confirm": $this->social_confirm($sender, $param1); break; case "remember": $this->social_remember(); break; default: if($this->services->isServiceExists($action)) { $this->social_auth($sender); } else { $sender->render404(); } break; } } public function uninstall() {} }
phisyks/discuss
addons/plugins/OpauthConnect/plugin.php
PHP
gpl-2.0
20,268
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace Revista_Programar_Reader_Win8 { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } } }
pikax/papreader
Revista Programar Reader Win8/MainPage.xaml.cs
C#
gpl-2.0
828
<?php /** * Element: Agents * Displays a multiselectbox of different browsers * * @package NoNumber Framework * @version 14.4.1 * * @author Peter van Westen <peter@nonumber.nl> * @link http://www.nonumber.nl * @copyright Copyright © 2014 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ defined('_JEXEC') or die; require_once JPATH_PLUGINS . '/system/nnframework/helpers/text.php'; class JFormFieldNN_Agents extends JFormField { public $type = 'Agents'; private $params = null; protected function getInput() { $this->params = $this->element->attributes(); $group = $this->get('group'); if (!is_array($this->value)) { $this->value = explode(',', $this->value); } $agents = array(); switch ($group) { /* OS */ case 'os': $agents[] = array('Windows (' . JText::_('JALL') . ')', 'Windows'); $agents[] = array('Windows 8', 'Windows nt 6.2'); $agents[] = array('Windows 7', 'Windows nt 6.1'); $agents[] = array('Windows Vista', 'Windows nt 6.0'); $agents[] = array('Windows Server 2003', 'Windows nt 5.2'); $agents[] = array('Windows XP', 'Windows nt 5.1'); $agents[] = array('Windows 2000 sp1', 'Windows nt 5.01'); $agents[] = array('Windows 2000', 'Windows nt 5.0'); $agents[] = array('Windows NT 4.0', 'Windows nt 4.0'); $agents[] = array('Windows Me', 'Win 9x 4.9'); $agents[] = array('Windows 98', 'Windows 98'); $agents[] = array('Windows 95', 'Windows 95'); $agents[] = array('Windows CE', 'Windows ce'); $agents[] = array('Mac OS (' . JText::_('JALL') . ')', '#(Mac OS|Mac_PowerPC|Macintosh)#'); $agents[] = array('Mac OSX (' . JText::_('JALL') . ')', 'Mac OS X'); $agents[] = array('Mac OSX Mountain Lion', 'Mac OS X 10.8'); $agents[] = array('Mac OSX Lion', 'Mac OS X 10.7'); $agents[] = array('Mac OSX Snow Leopard', 'Mac OS X 10.6'); $agents[] = array('Mac OSX Leopard', 'Mac OS X 10.5'); $agents[] = array('Mac OSX Tiger', 'Mac OS X 10.4'); $agents[] = array('Mac OSX Panther', 'Mac OS X 10.3'); $agents[] = array('Mac OSX Jaguar', 'Mac OS X 10.2'); $agents[] = array('Mac OSX Puma', 'Mac OS X 10.1'); $agents[] = array('Mac OSX Cheetah', 'Mac OS X 10.0'); $agents[] = array('Mac OS (classic)', '#(Mac_PowerPC|Macintosh)#'); $agents[] = array('Linux', '#(Linux|X11)#'); $agents[] = array('Open BSD', 'OpenBSD'); $agents[] = array('Sun OS', 'SunOS'); $agents[] = array('QNX', 'QNX'); $agents[] = array('BeOS', 'BeOS'); $agents[] = array('OS/2', 'OS/2'); break; /* Browsers */ case 'browsers': $agents[] = array('Chrome (' . JText::_('JALL') . ')', 'Chrome'); $agents[] = array('Chrome 35', 'Chrome/35.'); $agents[] = array('Chrome 34', 'Chrome/34.'); $agents[] = array('Chrome 33', 'Chrome/33.'); $agents[] = array('Chrome 32', 'Chrome/32.'); $agents[] = array('Chrome 31', 'Chrome/31.'); $agents[] = array('Chrome 30', 'Chrome/30.'); $agents[] = array('Chrome 29', 'Chrome/29.'); $agents[] = array('Chrome 28', 'Chrome/28.'); $agents[] = array('Chrome 27', 'Chrome/27.'); $agents[] = array('Chrome 26', 'Chrome/26.'); $agents[] = array('Chrome 25', 'Chrome/25.'); $agents[] = array('Chrome 24', 'Chrome/24.'); $agents[] = array('Chrome 23', 'Chrome/23.'); $agents[] = array('Chrome 22', 'Chrome/22.'); $agents[] = array('Chrome 21', 'Chrome/21.'); //$agents[] = array('Chrome 31-40', '#Chrome/(3[1-9]|40)\.#'); //$agents[] = array('Chrome 21-30', '#Chrome/(2[1-9]|30)\.#'); $agents[] = array('Chrome 11-20', '#Chrome/(1[1-9]|20)\.#'); $agents[] = array('Chrome 1-10', '#Chrome/([1-9]|10)\.#'); $agents[] = array('Firefox (' . JText::_('JALL') . ')', 'Firefox'); $agents[] = array('Firefox 30', 'Firefox/30.'); $agents[] = array('Firefox 29', 'Firefox/29.'); $agents[] = array('Firefox 28', 'Firefox/28.'); $agents[] = array('Firefox 27', 'Firefox/27.'); $agents[] = array('Firefox 26', 'Firefox/26.'); $agents[] = array('Firefox 25', 'Firefox/25.'); $agents[] = array('Firefox 24', 'Firefox/24.'); $agents[] = array('Firefox 23', 'Firefox/23.'); $agents[] = array('Firefox 22', 'Firefox/22.'); $agents[] = array('Firefox 21', 'Firefox/21.'); //$agents[] = array('Firefox 21-30', '#Firefox/(2[1-9]|30)\.#'); $agents[] = array('Firefox 11-20', '#Firefox/(1[1-9]|20)\.#'); $agents[] = array('Firefox 1-10', '#Firefox/([1-9]|10)\.#'); $agents[] = array('Internet Explorer (' . JText::_('JALL') . ')', 'MSIE'); $agents[] = array('Internet Explorer 10.6', 'MSIE 10.6'); $agents[] = array('Internet Explorer 10.0', 'MSIE 10.0'); $agents[] = array('Internet Explorer 10', 'MSIE 10.'); $agents[] = array('Internet Explorer 9', 'MSIE 9.'); $agents[] = array('Internet Explorer 8', 'MSIE 8.'); $agents[] = array('Internet Explorer 7', 'MSIE 7.'); $agents[] = array('Internet Explorer 1-6', '#MSIE [1-6]\.#'); $agents[] = array('Opera (' . JText::_('JALL') . ')', 'Opera'); $agents[] = array('Opera 13', 'Opera/13.'); $agents[] = array('Opera 12', 'Opera/12.'); $agents[] = array('Opera 11', 'Opera/11.'); $agents[] = array('Opera 10', 'Opera/10.'); $agents[] = array('Opera 1-9', '#Opera/[1-9]\.#'); $agents[] = array('Safari (' . JText::_('JALL') . ')', 'Safari'); $agents[] = array('Safari 8', '#Version/8\..*Safari/#'); $agents[] = array('Safari 7', '#Version/7\..*Safari/#'); $agents[] = array('Safari 6', '#Version/6\..*Safari/#'); $agents[] = array('Safari 5', '#Version/5\..*Safari/#'); $agents[] = array('Safari 4', '#Version/4\..*Safari/#'); $agents[] = array('Safari 1-3', '#Version/[1-3]\..*Safari/#'); break; /* Mobile browsers */ case 'mobile': $agents[] = array(JText::_('JALL'), 'mobile'); $agents[] = array('Android', 'Android'); $agents[] = array('Blackberry', 'Blackberry'); $agents[] = array('IE Mobile', 'IEMobile'); $agents[] = array('iPad', 'iPad'); $agents[] = array('iPhone', 'iPhone'); $agents[] = array('iPod Touch', 'iPod'); $agents[] = array('NetFront', 'NetFront'); $agents[] = array('Nokia', 'NokiaBrowser'); $agents[] = array('Opera Mini', 'Opera Mini'); $agents[] = array('Opera Mobile', 'Opera Mobi'); $agents[] = array('UC Browser', 'UC Browser'); break; } $options = array(); foreach ($agents as $agent) { $option = JHtml::_('select.option', $agent['1'], $agent['0']); $options[] = $option; } $attr = ''; $attr .= $this->get('size') ? ' size="' . (int) $this->get('size') . '"' : ''; $attr .= ' multiple="multiple"'; return JHtml::_('select.genericlist', $options, $this->name, trim($attr), 'value', 'text', $this->value, $this->id); } private function get($val, $default = '') { return (isset($this->params[$val]) && (string) $this->params[$val] != '') ? (string) $this->params[$val] : $default; } }
L16jovenesTIC/portal-web
plugins/system/nnframework/fields/agents.php
PHP
gpl-2.0
7,025
/* Interpréteur GOTO++ Copyright 2002 Sidoine de Wispelaere Ce programme est un logiciel libre ; vous pouvez le redistribuer et/ou le modifier sous les termes de la GNU General Public Licence telle que publiée par la Free Software Fundation ; soit dans la version 2 de la Licence, soit (à votre choix) dans une version ultérieure. Ce programme est distribué dans l'espoir qu'il sera utile mais SANS AUCUNE GARANTIE ; sans même la garantie implicite qu'il soit COMMERCIALISABLE ou ADEQUAT POUR UN USAGE PARTICULIER. Voir la GNU General Public Licence pour plus de détails. Vous devriez avoir reçu une copie de la GNU General Public Licence avec ce programme ; dans le cas contraire, écrivez à : Free Software Fundation, Inc. 59 Temple Place - Suite 330, Boston, MA 02111-1307, US **** Voici le fameux compilateur, qui vous domine du haut de ses je ne sais combien de lignes. Bon courage pour comprendre tout ça. */ #include <gotopp/base.h> #include <gotopp/icompilateur.h> #include <gotopp/erreur.h> #include "compriv.h" #include <gotopp/global.h> using namespace GotoPP; using namespace std; namespace GotoPP { bool ALPHA(carac c) { return ((c>='A' && c<='Z')||(c>='a' && c<='z')); } bool ALPHANUM(carac c) { return ((c>='A' && c<='Z')||(c>='a' && c<='z')||(c>='0' && c<='9')); } inline bool EGAL(const carac * x, const carac * y, size_t ly) { return (czlen(x)==ly && memcmp(x,y,ly*sizeof(carac))==0); } // #define EGALMC(_T(y) ((lClef==sizeof(_T(y))/sizeof(carac)-1)&&(memcmp(MotClef,_T(y),sizeof(_T(y))-sizeof(carac))==0)) const int PRI_CONSTANTE=1; const int PRI_TAILLE=2; const int PRI_PLUSMOINS=5; const int PRI_FOIS=8; const int PRI_MODULO=8; const int PRI_CONCAT=9; const int PRI_EXEC=10; const int PRI_DEF=15; const int PRI_REGOTO=18; const int PRI_ABSOLUE=3; const int PRI_OPPOSE=3; const int PRI_TYPEDE=1; const int PRI_VIRGULE=999; const int PRI_MAX=1000; const int PRI_COLLE=1001; const int PRI_PAR_O=0; const int PRI_PAR_F=1003; const int PRI_FIN=1004; const int PRI_NOUVEAU=10; const int PRI_COMP=14; const int PRI_NON=4; const int PRI_OU=16; const int PRI_ET=17; const int PRI_SWITCH=20; const int PRI_OUBIN=12; const int PRI_ETBIN=13; const int PRI_DECALAGEBIN=7; index_t LireEtiquette(bool & local); carac prochainFichier[512]; } /* Le principe de base du compilateur est expliqué dans CompilerSeparateur. * Explication sur les variables "longues", c'est à dire les variables dotées de propriétés, d'indices de tableau, etc. machin.chose[truc+13][chose].bidule= Si une variable est terminée par . ou [ alors cette variable est une variable longue. Une variable longue est entourée de parenthèses dont la priorité est celle d'une constante (<> des vraies parenthèses). variables longues => flag variablelongue=true on saute le point par la suite : soit on lit [ soit on lit des mots clefs => tout le reste génère une erreur Lecture de [ : variablelongue=false Lecture de ] : variablelongue=true en lisant une variable si le flag variablelongue=true c'est une propriété si après un ] ou une variable il n'y a pas . ou [ alors on dépile les variables longues en mettant la parenthèse finale et variablelongue=false */ //namespace GotoPP { // namespace Compilateur { inline void Compilateur::AjParO(uint priorite=PRI_PAR_O) { Instr[nInstr].p=priorite; Instr[nInstr].pVal=nValeurs; Instr[nInstr].nVal=0; Instr[nInstr++].Special=SPE_PAR_O; } inline void Compilateur::AjParF() { Instr[nInstr].p=PRI_PAR_F; Instr[nInstr].pVal=nValeurs; Instr[nInstr].nVal=0; Instr[nInstr++].Special=SPE_PAR_F; } inline void Compilateur::AjDebutParams() { Instr[nInstr].p=PRI_CONSTANTE; Instr[nInstr].pVal=nValeurs; Instr[nInstr].nVal=0; Instr[nInstr].Code= Code::I_DEBUTPARAM; Instr[nInstr++].Special=SPE_NORMAL; } inline void Compilateur::AjCode(Code code, uint Priorite=PRI_CONSTANTE) { Instr[nInstr].p=Priorite; Instr[nInstr].pVal=nValeurs; Instr[nInstr].nVal=0; Instr[nInstr].Code = code; Instr[nInstr++].Special=SPE_NORMAL; } inline void Compilateur::AjNoOp(uint priorite) { Instr[nInstr].p=priorite; Instr[nInstr].pVal=nValeurs; Instr[nInstr].nVal=0; Instr[nInstr++].Special=SPE_NOOP; } inline void Compilateur::AjExpReg(carac *er, carac *modif) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=TYPE_OBJETC; Valeur[nValeurs++].v.o=regexp::Creer(er, modif); } inline void Compilateur::AjEntier(int e) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=TYPE_ENTIER; Valeur[nValeurs++].v.i=e; } inline void Compilateur::AjType(type t) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=TYPE_TYPE; Valeur[nValeurs++].v.i=t; } inline void Compilateur::AjCarac(carac c) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=TYPE_CARAC; Valeur[nValeurs++].v.i=c; } inline void Compilateur::AjChances(float f) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=TYPE_CHANCES; Valeur[nValeurs++].v.f=f; } inline void Compilateur::AjChaine(carac *c,size_t l) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=TYPE_CHAINE; Valeur[nValeurs++].v.c=chaineval::CreerFormat(c,l); } inline void Compilateur::AjEntierType(int e,type Type) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=Type; Valeur[nValeurs++].v.i=e; } inline void Compilateur::AjPtrType(Symbole * ptr, type Type) { Instr[nInstr-1].nVal++; Valeur[nValeurs].Type=Type; Valeur[nValeurs++].v.ptr=ptr; } inline bool Compilateur::EstNouveauSymbole(Symbole * s) { return s == nullptr; } void Compilateur::SupprimerVarLongue() { nInstr=VarLongue[iVarLongue].nInstrsDepart; nValeurs=Instr[nInstr].pVal; } bool Compilateur::CompilerOperateur() { if (*Source=='@' && Source[1]=='%' && Source[2]=='N' && Source[3]=='e') { clog << TXT("Bien tenté mais ça ne marche pas.\n"); Source+=4; } else if (*Source=='@' && (Source[1]=='+'||Source[1]=='-'||Source[1]==':')) { Source++; if (*Source=='+') AjCode(Code::I_EMPILER2); else if (*Source=='-') AjCode(Code::I_DEPILER2); else if (*Source==':') AjCode(Code::I_VALEUR2); Source++; } else if (*Source==SEP_PROP) //Sépare les propriétés { if (VarLongue[iVarLongue].Type.l==0) throw TXT("@ doit être placé après un nom de variable"); Source++; SauterEspaces(); ChercherMotClef(); if (lClef==0) throw TXT("@ doit être suivi d'un nom de pingouin"); Symbole * prop=ChercherSymboleDans(VarLongue[iVarLongue].Type.Dernier()); CompilerVariable(prop,VarLongue[iVarLongue].Val); } else if (*Source=='|') { Source++; if (*Source=='*') AjCode(Code::I_ETBIN,PRI_ETBIN); else if (*Source=='+') AjCode(Code::I_OUBIN,PRI_OUBIN); else if (*Source=='<') AjCode(Code::I_DECALG,PRI_DECALAGEBIN); else if (*Source=='>') AjCode(Code::I_DECALD,PRI_DECALAGEBIN); else throw TXT("opérateur binaire inconnu"); Source++; } else if (*Source=='?' && nInstr==0) { if (AcSwitch.l==0) throw TXT("on n'est pas dans un GOTOMULTIPLE"); Source++; if (czncmp(Source,_T("défaut?"),7)==0) { Source+=7; programme->Switch[AcSwitch.Dernier()]->PosDefaut=(code*)Ins.t; } else LigneAc=LP_CAS; } else if (*Source=='!') { Source++; if (*Source>='0' && *Source<='9') { ProbaSauterLigne=0; do { ProbaSauterLigne*=10; ProbaSauterLigne+=*Source-'0'; Source++; } while (*Source>='0' && *Source<='9'); } else ProbaSauterLigne=90; InstrAc=IP_OPERATEUR; } else if (*Source=='`') { Source++; AjCode(Code::I_TYPEDE,PRI_TYPEDE); } else if (*Source=='_') { Source++; AjCode(Code::I_CONCAT,PRI_CONCAT); InstrAc=IP_OPERATEUR; } else if (*Source=='"') { AjCode(Code::I_VALEURCLEF); Source++; InstrAc=IP_OPERATEUR; } else if (*Source=='#') { AjCode(Code::I_VALEUR); Source++; InstrAc=IP_OPERATEUR; } else if (*Source=='}') { AjParO(PRI_CONSTANTE); Source++; InstrAc=IP_PARO; } else if ((*Source=='{')||(*Source==')')) { AjParF(); Source++; } else if (*Source=='~') { Source++; if (*Source=='~') { AjCode(Code::I_NONOPPOSE,PRI_OPPOSE); Source++; } else AjCode(Code::I_OPPOSE,PRI_OPPOSE); InstrAc=IP_OPERATEUR; } else if (*Source=='=') { Source++; if (*Source=='-') { Source++; AjCode(Code::I_DECREMENTER,PRI_DEF); } else if (*Source=='+') { Source++; AjCode(Code::I_INCREMENTER,PRI_DEF); } else if (*Source=='=') { Source++; AjCode(Code::I_INSTANCEDE,PRI_DEF); } else AjCode(Code::I_DEFINIR,PRI_DEF); InstrAc=IP_OPERATEUR; } else if (*Source==':') { Source++; if (*Source=='=') { AjCode(Code::I_DIVISEREGAL,PRI_DEF); Source++; } else AjCode(Code::I_DIVISE,PRI_FOIS); InstrAc=IP_OPERATEUR; } else if ((*Source=='*')&&(Source[1]=='=')) { Source+=2; AjCode(Code::I_MULTIPLIEREGAL,PRI_DEF); InstrAc=IP_OPERATEUR; } else if (*Source=='+') { Source++; if (*Source=='+') { Source++; AjCode(Code::I_SUPERPLUS,PRI_PLUSMOINS); } else { AjCode(Code::I_AJOUTER,PRI_PLUSMOINS); //AjOperateurVV(OPVV_PLUS); } InstrAc=IP_OPERATEUR; } else if (*Source=='-') { AjCode(Code::I_SOUSTRAIRE,PRI_PLUSMOINS); Source++; InstrAc=IP_OPERATEUR; } else if (*Source=='(') { Source++; AjCode(Code::I_EXECVAL,PRI_EXEC); //On ferme la parenthèse qui *doit* avoir été ouverte //avant de mettre la valeur dans la pile AjParF(); AjParO(); AjDebutParams(); } else if (*Source=='%') { if (NiveauGourou>2) throw TXT("le % est interdit pour les gourous de niveau supérieur à 2"); bool local; Symbole * s=LireEtiquette(local); if (!EstNouveauSymbole(s) && s->EstClasse()) CompilerClasse(s); else CompilerVariable(s, false); } else return false; return true; } void Compilateur::DebutBloc(TypeBloc Type, Symbole * espace) { Bloc * bloc=new Bloc(); bloc->type=Type; bloc->depart=(int)Ins.t; if (espace==0) { Symbole * parent; if (blocs.l>0) parent=blocs.Dernier()->symbole; else parent=programme->symboleGlobal; //On crée un symbole vide espace=new Symbole(_T(""),parent,Symbole::Bloc); if (parent->PeutContenirLocaux()) espace->taille=parent->taille; programme->symbole.Etendre(espace); } bloc->symbole=espace; blocs.Etendre(bloc); LigneAc=LP_DEBUTBLOC; } void Compilateur::FinBloc() { if (blocs.l==0) throw TXT("pas de bloc ouvert"); bool Sinon=false; switch(blocs.Dernier()->type) { case TypeBloc::Rien: break; case TypeBloc::Sinon: //clog << "bloc sinon terminé en ligne "<<Ligne<<'\n'; if (RefEtiqA.l==0) throw TXT("un AC sans AUTOGOTOZ"); Ins.ChgGotoRel(RefEtiqA.Dernier().Etiq,(int)Ins.t); RefEtiqA.l--; break; case TypeBloc::Si: { //clog << "bloc si terminé en ligne "<<Ligne<<'\n'; //On regarde si il y a un sinon après carac *src=Source; int ligne=Ligne; do { SauterEspaces(); if (*Source=='\n') { Ligne++; Source++; } else if (*Source=='/') Source++; else break; } while (1); if (Source[0]=='A' && Source[1]=='C' && Source[2]=='A' && Source[3]=='C' && (ucarac(Source[4])<=' '||Source[4]=='/')) { Source+=4; SauterEspaces(); if ((nInstr)||(*Source!='\n' && *Source!=0 && *Source!='/')) throw TXT("ACAC doit être seul sur la ligne"); //L'équivalent de sinon : insère un GOTO vers la suite //puis un AC SauterEspaces(); Ins.AjouterCode(Code::I_GOTOR); //Cible d'un AUTOGOTOZ qui crée un GOTOPASMALIN int cible=RefEtiqA.Dernier().Etiq; RefEtiqA.Dernier().Etiq=(int)Ins.t; Ins.AjouterEntier(0); Ins.ChgGotoRel(cible,(int)Ins.t); Sinon=true; } else { Source=src; Ligne=ligne; if (RefEtiqA.l==0) throw TXT("un AC sans AUTOGOTOZ"); Ins.ChgGotoRel(RefEtiqA.Dernier().Etiq,(int)Ins.t); RefEtiqA.l--; } break; } case TypeBloc::ForEach: { int Depart=(int)Ins.t; Ins.AjouterCode(Code::I_VARIABLELOC); Ins.AjouterEntier(blocs.Dernier()->indice->indice); Ins.AjouterCode(Code::I_ENTIER); Ins.AjouterEntier(1); Ins.AjouterCode(Code::I_INCREMENTER); Ins.AjouterCode(Code::I_GOTOR); Ins.AjouterGotoRel(blocs.Dernier()->depart); for (index_t e=0; e<blocs.Dernier()->continues.l;e++) Ins.ChgGotoRel(blocs.Dernier()->continues[e],Depart); for (index_t e=0; e<blocs.Dernier()->breaks.l;e++) Ins.ChgGotoRel(blocs.Dernier()->breaks[e],(int)Ins.t); break; } case TypeBloc::For: { int Depart=(int)Ins.t; if (blocs.Dernier()->pasDuFor) { LigneDeCode * ldc=blocs.Dernier()->pasDuFor; CreerCodeFinal(*ldc); delete ldc; } Ins.AjouterCode(Code::I_GOTOR); Ins.AjouterGotoRel(blocs.Dernier()->depart); for (index_t e=0; e<blocs.Dernier()->continues.l;e++) Ins.ChgGotoRel(blocs.Dernier()->continues[e],Depart); for (index_t e=0; e<blocs.Dernier()->breaks.l;e++) Ins.ChgGotoRel(blocs.Dernier()->breaks[e],(int)Ins.t); break; } case TypeBloc::TantQue: { //clog << "bloc tantque terminé en ligne "<<Ligne<<'\n'; Ins.AjouterCode(Code::I_GOTOR); Ins.AjouterGotoRel(blocs.Dernier()->depart); for (index_t e=0; e<blocs.Dernier()->continues.l;e++) Ins.ChgGotoRel(blocs.Dernier()->continues[e],blocs.Dernier()->depart); for (index_t e=0; e<blocs.Dernier()->breaks.l;e++) Ins.ChgGotoRel(blocs.Dernier()->breaks[e],(int)Ins.t); break; } case TypeBloc::Switch: { //clog << "bloc switch terminé en ligne "<<Ligne<<'\n'; if (AcSwitch.l==0) throw TXT("une fin de GOTOMULTIPLE sans GOTOMULTIPLE ouvert"); if (programme->Switch[AcSwitch.Dernier()]->PosDefaut== nullptr) programme->Switch[AcSwitch.Dernier()]->PosDefaut=reinterpret_cast<code*>(Ins.t); //Trions les switchs qsort(programme->Switch[AcSwitch.Dernier()]->Cas.t, programme->Switch[AcSwitch.Dernier()]->Cas.l,sizeof(CCasSwitch), CompCasSwitch); AcSwitch.l--; for (index_t e=0; e<blocs.Dernier()->breaks.l;e++) Ins.ChgGotoRel(blocs.Dernier()->breaks[e],static_cast<int>(Ins.t)); break; } case TypeBloc::Fonction: //clog << "bloc fonction terminé en ligne "<<Ligne<<'\n'; AjCode(Code::I_RETOUR,PRI_EXEC); break; case TypeBloc::Classe: break; #ifdef _DEBUG default: throw TXT("bloc de type inconnu"); #endif } blocs.EffacerDernier(); if (blocs.l==0) { /*//On fait le lien des étiquettes locales qsort(&LabelL.Premier(),LabelL.l,sizeof(SLabel),CmpLabels); //clog << RefEtiq.l << " références à des étiquettes \n"; for (index_t z=0; z<RefEtiqL.l; z++) { int *k=(int*)&Ins.c[RefEtiqL[z]]; int v=*k; SLabelL * l=(SLabelL*)bsearch(&v,&LabelL.Premier(),LabelL.l,sizeof(SLabelL),CmpLabels); if (!l) throw TXT("il est fait référence à une étiquette locale qui n'existe pas dans ce bloc, à toi de trouver laquelle"); *k=l->Valeur-RefEtiqL[z]-sizeof(int); } LabelL.l=0; RefEtiqL.l=0;*/ } if (blocs.Dernier()->classeSpecifiee) blocs.EffacerDernier(); if (Sinon) DebutBloc(TypeBloc::Sinon); } bool Compilateur::CompilerMotClef0() { if (EstMotClef(_T("bush")) || EstMotClef(_T("deubeulyou"))) { SauterEspaces(); ChercherMotClef(); if (lClef==0) throw TXT("une constante doit avoir un nom"); Symbole * symb=programme->NouvelleConstante(MotClef,lClef); SauterEspaces(); if (*Source!='=') throw TXT("il manque le = après le nom de la constante"); Source++; AjCode(Code::I_CONSTVAR,PRI_DEF); AjPtrType(symb,TYPE_SYMBOLE); } else if (EstMotClef(_T("BLOC"))) { DebutBloc(TypeBloc::Rien); } else if (EstMotClef(_T("FINBLOC"))) { FinBloc(); } else if (EstMotClef(_T("FINGOTOMULTIPLE"))) { if (blocs.l==0 || blocs.Dernier()->type!= TypeBloc::Switch) throw TXT("FINGOTOMULTIPLE doit fermer un GOTOMULTIPLE"); FinBloc(); } else if (EstMotClef(_T("GOTOMULTIPLE"))) { AjCode(Code::I_SWITCH,PRI_SWITCH); AjEntier((int)programme->Switch.l); AcSwitch.Etendre((int)programme->Switch.l); CSwitch * swit=new CSwitch(); programme->Switch.Etendre(swit); CibleAuto++;//Pour les "arret" DebutBloc(TypeBloc::Switch); } else if (EstMotClef(_T("et"))) { AjCode(Code::I_ET,PRI_ET); AjEntier((int)EtOu.l); AjCode(Code::I_FINOUET,PRI_ET); AjEntier((int)EtOu.l); EtOu.Etendre(-1); } else if (EstMotClef(_T("ou"))) { AjCode(Code::I_OU,PRI_OU); AjEntier((int)EtOu.l); AjCode(Code::I_FINOUET,PRI_OU); AjEntier((int)EtOu.l); EtOu.Etendre(-1); } else if (EstMotClef(_T("eg"))) { AjCode(Code::I_EGAL,PRI_COMP); } else if (EstMotClef(_T("diff"))) { AjCode(Code::I_DIFFERENT,PRI_COMP); } else if (EstMotClef(_T("inf"))) { AjCode(Code::I_INFERIEUR,PRI_COMP); } else if (EstMotClef(_T("sup"))) { AjCode(Code::I_SUPERIEUR,PRI_COMP); } else if (EstMotClef(_T("supeg"))) { AjCode(Code::I_SUPEGAL,PRI_COMP); } else if (EstMotClef(_T("infeg"))) { AjCode(Code::I_INFEGAL,PRI_COMP); } else if (EstMotClef(_T("non"))) { AjCode(Code::I_NON,PRI_NON); } else if (EstMotClef(_T("AUTOGOTOZ"))) { AjCode(Code::I_GOTOZEROR,PRI_EXEC); AjEntierType(0,TYPE_ETIQAUTO); DebutBloc(TypeBloc::Si); } else if (EstMotClef(_T("TantQue"))) { DebutBloc(TypeBloc::TantQue); AjCode(Code::I_GOTOZEROR,PRI_EXEC); AjEntierType((int)blocs.l-1,TYPE_ETIQAUTOBREAK); } else if (EstMotClef(_T("costaud"))) { DebutBloc(TypeBloc::For); LigneAc=LP_FOR_INIT; } else if (EstMotClef(_T("PouCharque"))) { SauterEspaces(); Symbole * classe=ChercherSymbole(); if (EstNouveauSymbole(classe) || !classe->EstClasse()) throw TXT("classe de la variable de parcours indéfinie"); SauterEspaces(); ChercherMotClef(); if (lClef==0) throw TXT("indiquez un nom pour la variable de parcours"); DebutBloc(TypeBloc::ForEach); Symbole * s=blocs.Dernier()->symbole; //On crée les trois variables locales utilisées blocs.Dernier()->indice=programme->NouveauSymbole(_T("indice"),6,CType(symboleEntier),s); DernierSymbole().type=Symbole::VariableLocale; DernierSymbole().indice=(index_t)s->taille++; blocs.Dernier()->tableau=programme->NouveauSymbole(_T("tableau"),7,CType(classe),s); DernierSymbole().TypeAc.Empiler(symboleTableau); DernierSymbole().type=Symbole::VariableLocale; DernierSymbole().indice=(index_t)s->taille++; blocs.Dernier()->iterateur=programme->NouveauSymbole(MotClef,lClef,CType(classe),s); DernierSymbole().type=Symbole::VariableLocale; DernierSymbole().indice=(index_t)s->taille++; index_t svarLoc=(index_t)(blocs[blocs.l-2]->symbole->taille); AjCode(Code::I_VARIABLELOC,PRI_CONSTANTE); AjPtrType(blocs.Dernier()->indice,TYPE_VARIABLE); AjCode(Code::I_ENTIER,PRI_CONSTANTE); AjEntier(0); AjCode(Code::I_DEFINIR,PRI_CONSTANTE); AjCode(Code::I_VARIABLELOC,PRI_CONSTANTE); AjPtrType(blocs.Dernier()->tableau,TYPE_VARIABLE); AjCode(Code::I_INSTANCEDE,PRI_MAX); LigneAc=LP_FOREACH_INIT; } else if (EstMotClef(_T("arret"))) { AjCode(Code::I_GOTOR,PRI_EXEC); int Cible=int(blocs.l)-1; while (Cible>=0 && blocs[Cible]->type!= TypeBloc::Fonction && blocs[Cible]->type!= TypeBloc::TantQue && blocs[Cible]->type!= TypeBloc::Switch && blocs[Cible]->type!= TypeBloc::For && blocs[Cible]->type!= TypeBloc::ForEach) Cible--; if (blocs[Cible]->type== TypeBloc::Fonction) throw TXT("interdit de sortir d'une fonction avec arret"); if (Cible<0) throw TXT("un arret doit se trouver dans un bloc"); AjEntierType(Cible,TYPE_ETIQAUTOBREAK); } else if (EstMotClef(_T("continue"))) { AjCode(Code::I_GOTOR,PRI_EXEC); int Cible=int(blocs.l)-1; while (Cible>=0 && blocs[Cible]->type!= TypeBloc::Fonction && blocs[Cible]->type!= TypeBloc::TantQue && blocs[Cible]->type!= TypeBloc::For && blocs[Cible]->type!= TypeBloc::ForEach) Cible--; if (blocs[Cible]->type== TypeBloc::Fonction) throw TXT("interdit de sortir d'une fonction avec continue"); if (Cible<0) throw TXT("un continue doit se trouver dans un TantQue"); AjEntierType(Cible,TYPE_ETIQAUTOCONTINUE); } else if (EstMotClef(_T("AC"))) { if (nInstr) throw TXT("AC doit être en début de ligne"); if ((blocs.l==0 || (blocs.Dernier()->type != TypeBloc::Si&&blocs.Dernier()->type != TypeBloc::Sinon))) throw TXT("un AC doit terminer un AUTOGOTOZ"); FinBloc(); } else if (EstMotClef(_T("faiblard"))) { SauterEspaces(); if ((nInstr)||(*Source!='\n' && *Source!=0)) throw TXT("faiblard doit être seul sur la ligne"); if (blocs.l==0 || blocs.Dernier()->type!= TypeBloc::For) throw TXT("un faiblard doit terminer un costaud"); FinBloc(); } else if (EstMotClef(_T("FinTantQue"))) { SauterEspaces(); if ((nInstr)||(*Source!='\n' && *Source!=0)) throw TXT("FinTantQue doit être seul sur la ligne"); if (blocs.l==0 || (blocs.Dernier()->type!= TypeBloc::TantQue && blocs.Dernier()->type!= TypeBloc::ForEach)) throw TXT("un FinTantQue doit terminer un TantQue ou un PouCharque"); FinBloc(); } else if (EstMotClef(_T("ACAC"))) { throw TXT("que fait ce ACAC ici ?"); } else return false; return true; } bool Compilateur::CompilerMotClef1() { if (EstMotClef(_T("GOTOPASMALIN"))) { SauterEspaces(); bool locale; Symbole * c=LireEtiquette(locale); if (locale) { AjCode(Code::I_GOTOR,PRI_CONSTANTE); AjPtrType(c,TYPE_ETIQLOC); } else { AjCode(Code::I_GOTO,PRI_CONSTANTE); AjPtrType(c,TYPE_ETIQUETTE); } } else if (EstMotClef(_T("GOTONULPOURLESNULS"))) { SauterEspaces(); bool Locale; Symbole * c=LireEtiquette(Locale); if (Locale) { AjCode(Code::I_GOTOZEROR,PRI_EXEC); AjPtrType(c,TYPE_ETIQLOC); } else { AjCode(Code::I_GOTOZERO,PRI_EXEC); AjPtrType(c,TYPE_ETIQUETTE); } } else if (EstMotClef(_T("GOTONONNULPOURLESNULS"))) { SauterEspaces(); bool Locale; Symbole * c=LireEtiquette(Locale); if (Locale) { AjCode(Code::I_GOTONONZEROR,PRI_EXEC); AjPtrType(c,TYPE_ETIQLOC); } else { AjCode(Code::I_GOTONONZERO,PRI_EXEC); AjPtrType(c,TYPE_ETIQUETTE); } } else return false; return true; } bool Compilateur::SymboleDisponible() { Symbole * verifie=ChercherSymboleSimple(); if (!EstNouveauSymbole(verifie) && verifie->parent==blocs.Dernier()->symbole) return false; return true; } bool Compilateur::CompilerMotClef2() { if (EstMotClef(_T("estrefvalide"))) { AjCode(Code::I_ESTREFVALIDE,PRI_CONSTANTE); } else if (EstMotClef(_T("RESTEDELADIVISIONPAR"))) { AjCode(Code::I_MODULO,PRI_MODULO); } else if (EstMotClef(_T("monpitipingouin"))) { AjCode(Code::I_THIS,PRI_CONSTANTE); } else if (EstMotClef(_T("encasderreurGOTO"))) { SauterEspaces(); bool Locale; Symbole * c=LireEtiquette(Locale); if (Locale) { AjCode(Code::I_ENERREURR,PRI_CONSTANTE); AjPtrType(c,TYPE_ETIQLOC); } else { AjCode(Code::I_ENERREUR,PRI_CONSTANTE); AjPtrType(c,TYPE_ETIQUETTE); } } else if (EstMotClef(_T("GOTOBIBLIOTHEQUE"))) { SauterEspaces(); ChercherMotClef(); if (lClef==0) throw TXT("le nom de la bibliothèque de fonctions n'est pas indiqué"); for (index_t b=0; b<programme->fichierSource.l; b++) if (EGAL(programme->fichierSource[b]->Nom,MotClef,lClef)) return true; FichierSource * fichierSource=new FichierSource(); programme->fichierSource.Etendre(fichierSource); if (!fichierSource->Charger(MotClef,lClef,CheminModules)) throw TXT("bibliothèque introuvable"); fichierSource->Parent=AcFichierSource; AcFichierSource->AcPos=Source; AcFichierSource->Ligne=Ligne; fichierSource->DebutCode=(code*)Ins.t; Ligne=1; Source=fichierSource->Source; AcFichierSource=fichierSource; } else if (EstMotClef(_T("GOTOMODULE"))) { SauterEspaces(); ChercherMotClef(); if (lClef==0) throw TXT("nom de module attendu"); programme->ChargerModule(MotClef,uint(lClef)); } else if (EstMotClef(_T("BEBEPINGOUIN"))) { AjCode(Code::I_NOUVEAU,PRI_NOUVEAU); } else if (EstMotClef(_T("tailleenlongueur"))) { AjCode(Code::I_TAILLE,PRI_TAILLE); } else if (EstMotClef(_T("REGOTO"))) { AjCode(Code::I_RETOUR,PRI_REGOTO); } else if (EstMotClef(_T("GOTOUNIVERSPARALLELEouizzz"))) { SauterEspaces(); bool Locale; Symbole * c=LireEtiquette(Locale); if (Locale) { AjCode(Code::I_GOTOTACHER,PRI_CONSTANTE); AjPtrType(c,TYPE_ETIQLOC); } else { AjCode(Code::I_GOTOTACHE,PRI_CONSTANTE); AjPtrType(c,TYPE_ETIQUETTE); } } else if (EstMotClef(_T("GOTOFINTACHE"))) { AjCode(Code::I_FINTACHE,PRI_CONSTANTE); } else if (EstMotClef(_T("troupeau"))) { if (nInstr) throw TXT("la classe doit être définie en début de ligne"); //Définition d'une classe d'objet SauterEspaces(); ChercherMotClef(); if (lClef==0) throw TXT("nom de classe attendu"); bool ClasseGivree; if (EstMotClef(_T("GIVRE"))) { if (NiveauGourou>1) throw TXT("le mot-clef GIVRE est interdit aux gourous de niveau supérieur à 1"); ClasseGivree=true; SauterEspaces(); ChercherMotClef(); if (lClef==0) throw TXT("nom de classe attendu après GIVRE"); } else ClasseGivree=false; //On vérifie que le symbole n'est pas déjà utilisé if (!SymboleDisponible()) throw TXT("nom de classe déjà utilisé"); Symbole * c=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur), blocs.Dernier()->symbole); DebutBloc(TypeBloc::Classe,c); c->type=Symbole::Classe; c->defConstr=0; if (ClasseGivree) c->attributs|=Symbole::filsglob; else c->attributs|=Symbole::filsthis; SauterEspaces(); if (*Source==':') { Source++; SauterEspaces(); Symbole * i=ChercherSymbole(); if (!EstNouveauSymbole(i)) { if (i->type!=Symbole::Classe) throw TXT("impossible de dériver une classe intégrée"); //On copie tous les fils for (Symbole * f=i->fils;f!=0;f=f->suivant) { Symbole * copie=new Symbole(*f); programme->symbole.Etendre(copie); if (copie->acces==Symbole::Prive) copie->acces=Symbole::Cache; } c->taille=i->taille; } else throw CErreur(TXT("troupeau de base %.*s inconnu"),lClef,MotClef); } if (*Source!='\n') throw TXT("fin de ligne attendue après le nom du troupeau"); Source++; Ligne++; } else if (EstMotClef(_T("fintroupeau"))) { SauterEspaces(); if (*Source!='\n') throw TXT("retour à la ligne attendu après finclasse"); Source++; Ligne++; if (blocs.Dernier()->type!= TypeBloc::Classe) throw TXT("fintroupeau devrait indiquer la fin de définition d'une classe"); FinBloc(); } else if (EstMotClef(_T("machineapingouins"))) { //Définition d'une fonction SauterEspaces(); CompilerFonction(); } else if (EstMotClef(_T("NPARAMS"))) { AjCode(Code::I_NPARAMS,PRI_CONSTANTE); } else if (EstMotClef(_T("APLUS"))) { if (blocs.l==0 || blocs.Dernier()->type!= TypeBloc::Fonction) throw TXT("fin de bloc alors qu'aucun bloc n'a été ouvert"); FinBloc(); } else return false; return true; } bool Compilateur::CompilerMotClef3() { if (EstMotClef(_T("ASV"))) { throw TXT("ASV est réservé pour les fonctions"); } else if (EstMotClef(_T("niveaugourou"))) { SauterEspaces(); NiveauGourou=*Source-'0'; if (NiveauGourou<0 || NiveauGourou>3) throw TXT("le niveau de gourou doit être compris entre 0 et 3"); Source++; } else if (EstMotClef(_T("enentier"))) { AjCode(Code::I_CONVTYPE,PRI_CONSTANTE); AjType(TYPE_PINGOUIN); AjType(TYPE_ENTIER); } else if (EstMotClef(_T("enfonction"))) { AjCode(Code::I_CONVTYPE,PRI_CONSTANTE); AjType(TYPE_PINGOUIN); AjType(TYPE_FONCTIONC); } else if (EstMotClef(_T("encaractere"))) { AjCode(Code::I_CONVTYPE,PRI_CONSTANTE); AjType(TYPE_PINGOUIN); AjType(TYPE_CARAC); } else if (EstMotClef(_T("envariable"))) { AjCode(Code::I_CONVTYPE,PRI_CONSTANTE); AjType(TYPE_PINGOUIN); AjType(TYPE_VARIABLE); } else if (EstMotClef(_T("nimportequoitochances"))) { AjCode(Code::I_CONVTYPE,PRI_CONSTANTE); AjType(TYPE_PINGOUIN); AjType(TYPE_CHANCES); } else if (EstMotClef(_T("NOSTRADAMUS"))) { czerr<<TXT("Ce programme est béni par Nostradamus.\n"); } else if (EstMotClef(_T("SUPERPROLETAIRE"))) throw TXT("la révolution humaine est en marche ! Maudit âne ! Ton disque dur vient d'être détruit !"); else if (EstMotClef(_T("NIAC"))) throw TXT("la bêtise du NIAC est bête"); else if (EstMotClef(_T("NumeroBiblio"))) { AjCode(Code::I_ENTIER,PRI_CONSTANTE); AjEntier((int)(AcFichierSource!=programme->fichierSource[0]));//TODO: un truc qui veut dire quelque chose } else if (EstMotClef(_T("MULTIPLICATION"))) { AjCode(Code::I_FOIS,PRI_FOIS); } else if (EstMotClef(_T("GOTOFIN"))) { AjCode(Code::I_STOP,PRI_CONSTANTE); } else if (EstMotClef(_T("dup"))) { AjCode(Code::I_DUPLIQUER,PRI_CONSTANTE); } else if (EstMotClef(_T("suppr"))) { AjCode(Code::I_SUPPRIMER,PRI_CONSTANTE); } else if (EstMotClef(_T("existe"))) { AjCode(Code::I_EXISTE,PRI_CONSTANTE); } else if (EstMotClef(_T("pastrespermissif"))) { DeclarationStricte=true; } else return false; return true; } bool Compilateur::CompilerMotClef() { bool ret=CompilerMotClef3(); if (ret) { if (NiveauGourou>3) throw TXT("mot-clef interdit aux gourous de niveau supérieur à 3"); else return true; } ret=CompilerMotClef2(); if (ret) { if (NiveauGourou>2) throw TXT("mot-clef interdit aux gourous de niveau supérieur à 2"); else return true; } ret=CompilerMotClef1(); if (ret) { if (NiveauGourou>1) throw TXT("mot-clef interdit aux gourous de niveau supérieur à 1"); else return true; } ret=CompilerMotClef0(); if (ret) { if (NiveauGourou>0) throw TXT("mot-clef interdit aux gourous de niveau supérieur à 0"); else return true; } return false; } //Si posEN!=rien, on ne cherche pas dans les use //et uniquement à partir de Bloc[posEn] Symbole * Compilateur::ChercherSymboleSimple(Bloc ** posEN) { //TODO: un travail d'optimisation est faisable, notamment en //utilisant un index pour les noms de symbole //Heu alors là c'est une astuce, pour que ça puisse tourner en boucle if (posEN!=0) posEN--; Symbole * var=0; //On commence par regarder dans tous les blocs à partir de posEn Bloc ** fin=(posEN==0?blocs.Debut():posEN+1); for (Bloc ** en=blocs.Fin()-1; en>=fin; en--) { Symbole * parent=(*en)->symbole; for (Symbole * f=parent->fils; f!=0; f=f->suivant) { if (EGAL(f->nom,MotClef,lClef)) return f; } } //Si on n'a pas trouvé, on cherche dans les uses for (Symbole ** e=useEspace.Debut(); e<useEspace.Fin(); e++) { Symbole * parent=(*e); for (Symbole * f=parent->fils; f!=0; f=f->suivant) { if (EGAL(f->nom,MotClef,lClef)) return f; } } return 0;//pas trouvé //On regarde tous les symboles du programme /*for (Symbole ** i=programme->symbole.Debut(); i!=programme->symbole.Fin(); i++) { Symbole * symbole=*i; if (EGAL(symbole->nom,MotClef,lClef)) { //Est-il dans l'espace de nommage courant ? //Celui-ci est dicté par l'ensemble des blocs dans lesquels on se trouve for (CBloc ** en=(posEN==0?Bloc.Debut():posEN+1); en<Bloc.Fin(); en++) if ((*en)->symbole==symbole->parent) { var=symbole; posEN=en; } //Est-il dans les use ? if (posEN==0) { for (Symbole ** e=useEspace.Debut(); e<useEspace.Fin(); e++) if (*e==symbole->parent) var=symbole; } //Gare ! Ce symbole peut être remplacé par un autre symbole de même nom //défini dans un bloc fils if (var==symbole && posEN!=0 && posEN==Bloc.Fin()-1) break; } } return var;*/ } Symbole * Compilateur::ChercherSymbole(bool creer) { Symbole * var; Symbole * parent=programme->symboleGlobal; bool numeros=false; if (*Source=='%') { numeros=true; if (Source[1]=='%') { Source+=2; //On ne cherche que dans cette fonction Bloc ** en=blocs.Fin()-1; while (en>blocs.Debut()) { if ((*en)->type== TypeBloc::Fonction) break; en--; } ChercherMotClef(true); if (lClef==0) throw TXT("symbole attendu"); parent=(*en)->symbole; var=ChercherSymboleSimple(en); } else var=blocs.Premier()->symbole; } else { ChercherMotClef(); if (lClef==0) throw TXT("symbole attendu"); var=ChercherSymboleSimple(); } while(*Source=='%') { if (EstNouveauSymbole(var)) throw TXT("le symbole avant la virgule doit être défini"); Source++; ChercherMotClef(numeros); if (lClef==0) throw TXT("on attend un nom après la virgule"); parent=var; var=ChercherSymboleDans(var); } if (creer && EstNouveauSymbole(var)) { var=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur),parent); var->type=Symbole::FonctionGPP; var->attributs|=Symbole::constante; } return var; } Symbole * Compilateur::ChercherSymboleDans(Symbole * ou) { for (Symbole * s=ou->fils; s!=0; s=s->suivant) { if (EGAL(s->nom,MotClef,lClef)) { return s; } } return 0; } Symbole * Compilateur::LireEtiquette(bool &local) { carac * depart=Source; Symbole * s=ChercherSymbole(true); //TODO: comme ça, ça ne peut pas marcher. Qu'est ce que ça signifiait ? //local=(s>=etaitPremierSymbole); local=false; if (s && s->type!=Symbole::FonctionGPP) throw CErreur(TXT("%s n'est pas une étiquette"),s->nom); return s; } void Compilateur::InsererConstante(Symbole * var) { switch(var->type) { case Symbole::FonctionGPP: AjCode(Code::I_ETIQUETTE); AjPtrType(var,TYPE_ETIQUETTE);//Vu qu'on ne saura que plus //tard la vraie valeur (à l'édition de lien) break; case Symbole::MethodeGPP: AjCode(Code::I_ETIQUETTE_THIS); AjPtrType(var,TYPE_ETIQUETTE);//Vu qu'on ne saura que plus //tard la vraie valeur (à l'édition de lien) break; case Symbole::FonctionC: AjCode(Code::I_FONCTIONC); AjPtrType(var,TYPE_FONCTIONC); break; case Symbole::MethodeC: AjCode(Code::I_FONCTIONC_THIS); AjPtrType(var,TYPE_FONCTIONC_THIS); break; case Symbole::EtiquetteLocale: AjCode(Code::I_ETIQUETTELOC); AjPtrType(var,TYPE_ETIQLOC);//Vu qu'on ne saura que plus //tard la vraie valeur (à l'édition de lien) break; case Symbole::VariableGlobale: case Symbole::VariableLocale: { switch(var->Valeur.Type) { case TYPE_ENTIER: AjCode(Code::I_ENTIER); AjEntier(var->Valeur.v.i); break; case TYPE_FONCTIONC: AjCode(Code::I_FONCTIONC); AjPtrType(var,TYPE_FONCTIONC); break; case TYPE_FONCTIONMODULE: AjCode(Code::I_FONCTIONMODULE); AjEntier(var->Valeur.v.i); break; case TYPE_ETIQUETTE_THIS: AjCode(Code::I_ETIQUETTE_THIS); AjPtrType(var,TYPE_ETIQUETTE_THIS); break; case TYPE_FONCTIONC_THIS: AjCode(Code::I_FONCTIONC_THIS); AjPtrType(var,TYPE_FONCTIONC_THIS); break; case TYPE_INCONNU: throw TXT("constante indéfinie"); default: throw TXT("type non supporté pour une constante"); } break; } default: throw TXT("erreur interne du compilateur (type d'exécution)"); } } /* Le traitement des variables La variable en cours de traitement est stockée dans VarLongue cas 1: [&]var => la variable est isolée => var[&] cas 2: [&]var@tvar => la variable a une propriété => < var tvar[&] > cas 3:*/ bool Compilateur::CompilerVariable(Symbole * var, bool Val) { //Est-ce une nouvelle variable ? if (EstNouveauSymbole(var)) { if (DeclarationStricte) throw CErreur(TXT("la variable %.*s n'a pas été déclarée"), lClef,MotClef); var=programme->NouvelleVariable(MotClef,lClef,CType(symboleValeur)); } SauterEspaces(); //Est-ce une constante ? if (var->attributs&Symbole::constante) { bool dansVariableLongue; if (VarLongue[iVarLongue].Type.l==0) dansVariableLongue=false; else dansVariableLongue=true; if (*Source=='(') { if (!dansVariableLongue) AjParO(PRI_EXEC); // Instr[VarLongue[iVarLongue].Depart].p=I_EXEC; // else } InsererConstante(var); if (dansVariableLongue) { if (*Source!='(') AjParF(); VarLongue[iVarLongue].Type.Vider(); } else { //Appel automatique par this->blob if (var->type==Symbole::MethodeGPP && *Source=='(') { Source++; AjCode(Code::I_EXECMEMETHISVAL); AjParF(); AjParO(); AjDebutParams(); } } return true; } // bool variableLongue; if (VarLongue[iVarLongue].Type.l==0) { int prio=PRI_CONSTANTE; bool variableLongue; //On n'a pas encore démarré la variable longue //On vérifie si c'en est une if ((*Source==SEP_TAB_O)||(*Source==SEP_PROP)|| (*Source==SEP_HAC_O)) { //Suivis d'un début de tableau, de hachage ou de propriété //=> c'est une variable longue variableLongue=true; VarLongue[iVarLongue].nInstrsDepart=nInstr; AjParO(PRI_CONSTANTE); VarLongue[iVarLongue].Type=var->TypeAc; VarLongue[iVarLongue].Val=Val; } else { //C'est une variable isolée, sans propriété ni rien variableLongue=false; //Le I_EXEC doit se ballader avec la variable //on met donc une parenthèse au début if (*Source=='(') AjParO(var->TypeAc.EstFonction()?PRI_EXEC:PRI_CONSTANTE); } //Le code en question //Si c'est une variable longue on empile toujours la référence //Si c'est un appel de fonction qui suit on empile toujours la valeur if ((Val && !variableLongue)||*Source=='(') { switch(var->type) { case Symbole::VariableGlobale: AjCode(Code::I_VALEURVAR,prio); break; case Symbole::VariableLocale: AjCode(Code::I_VALEURVARLOC,prio); break; case Symbole::VariableParam: AjCode(Code::I_PARAMVAL,prio); break; case Symbole::VariableThis: AjCode(Code::I_THISVAL,prio); break; default: throw TXT("hu ?"); } } else { switch(var->type) { case Symbole::VariableLocale: AjCode(Code::I_VARIABLELOC); break; case Symbole::VariableGlobale: AjCode(Code::I_VARIABLE); break; case Symbole::VariableParam: AjCode(Code::I_PARAMREF); break; case Symbole::VariableThis: AjCode(Code::I_THISREF); break; default: throw TXT("hein ?"); } } AjPtrType(var,TYPE_VARIABLE); } else //C'est une propriété { if ((*Source==SEP_TAB_O)||(*Source==SEP_PROP)|| (*Source==SEP_HAC_O)) { //On continue VarLongue[iVarLongue].Type=var->TypeAc; AjCode(Code::I_CTABLEAUREF); AjEntier(var->indice); } else { VarLongue[iVarLongue].Type.Vider(); if (var->type==Symbole::VariableGlobale) { //Propriété givrée //On annule tout le code qui a conduit ici SupprimerVarLongue(); AjCode(VarLongue[iVarLongue].Val? Code::I_VALEURVAR: Code::I_VARIABLE); AjPtrType(var,TYPE_VARIABLE); } /*TODO: implémentation des propriétés*/ /*else if (var->type==Symbole::ProprieteC) { if (VarLongue[iVarLongue].Val) { AjCode(Code::I_ }*/ else { //Fin de la variable longue if (VarLongue[iVarLongue].Val) AjCode(Code::I_CTABLEAUVAL); else AjCode(Code::I_CTABLEAUREF); AjEntier(var->indice); if (*Source!='(') //On change la priorité de la parenthèse qui a //ouvert la variable, qu'on garde ouverte pour rajouter le I_EXEC AjParF(); // else // Instr[VarLongue[iVarLongue].Depart].p=PRI_EXEC; } } } return true; } void Compilateur::SauterEspaces() { do { while (*Source==' ' || *Source=='\t' || *Source=='\r') Source++; //Commentaires if (*Source=='#' && Source[1]=='!') { Source+=2; while ((*Source!='!' || Source[1]!='#')&&(*Source)) { if (*Source=='\n') Ligne++; Source++; } if (!*Source) throw TXT("pas de !# pour fermer le commentaire"); Source+=2; continue; } else if ((*Source=='G')&&(Source[1]=='O')&&(Source[2]=='T')&&(Source[3]=='O')&&(ucarac(Source[4])<=32)) { Source+=4; while ((*Source!='\n')&&(*Source)) Source++; return; } else if (*Source=='^') //Continuation de ligne { if (Source[1]=='\r' && Source[2]=='\n') { Source+=3; Ligne++; } else if (Source[1]=='\n') { Source+=2; Ligne++; } else return; } else return; } while (1); } void Compilateur::FinOu() { //On vire l'entier du FINOU Ins.t-=sizeof(int); Ins.i=&Ins.c[Ins.t]; int Ou; int NouvOu=*(int*)Ins.i; do { Ou=NouvOu; if (EtOu[Ou]==-1) throw TXT("arg"); NouvOu=*(int*)&Ins.c[EtOu[Ou]+1]; Ins.ChgGotoRel(EtOu[Ou]+1,(int)Ins.t); //*(int*)&Ins.c[]=(int)Ins.t; //clog << "NouvOu= "<<NouvOu<<" Ou="<<Ou<<"\n"; } while (NouvOu!=Ou); } void Compilateur::CreerCodeFinal(LigneDeCode & insTri) { Code CodePrec= Code::I_STOP,CodePrec2= Code::I_STOP; int CodePrecPos=0,CodePrec2Pos=0; for (uint Ac=0; Ac<insTri.nIns; Ac++) { //if (ValTri[InsTri[Ac].pVal].Type==TYPE_CODE) { int j=insTri.ins[Ac].pVal; if (CodePrec== Code::I_FINOUET) { //Si le nouveau est un OU, on transforme //le FINOU qu'il y avait avant en un OU if ((insTri.ins[Ac].Code== Code::I_OU)||(insTri.ins[Ac].Code== Code::I_ET)) { EtOu[insTri.val[j].v.i]=CodePrecPos; *(code*)&Ins.c[CodePrecPos] = (code)insTri.ins[Ac].Code; /* Instr[Ac].Special=SPE_DEJAMIS; Instr[Ac].nVal=0; Ac=RIEN;*/ CodePrec = (Code)insTri.val[j].v.i; continue; } else FinOu(); } else if ((insTri.ins[Ac].Code== Code::I_OU)||(insTri.ins[Ac].Code== Code::I_ET)) { EtOu[insTri.val[j].v.i]=(int)Ins.t; } CodePrec2=CodePrec; CodePrec2Pos=CodePrecPos; CodePrec=insTri.ins[Ac].Code; CodePrecPos=(int)Ins.t; } Ins.AjouterCode(insTri.ins[Ac].Code); //On effectue éventuellement un traitement sur les valeurs à insérer dans for (uint z=0; z<insTri.ins[Ac].nVal; z++) { uint j=z+insTri.ins[Ac].pVal; switch(insTri.val[j].Type) { case TYPE_ETIQUETTE: case TYPE_ETIQUETTE_THIS: RefEtiq.Etendre(int(Ins.t)); break; case TYPE_ETIQLOC: RefEtiqL.Etendre(int(Ins.t)); break; case TYPE_ETIQAUTO: RefEtiqA.Etendre(SEtiqA(int(Ins.t),DebutLigne)); break; case TYPE_ETIQAUTOCONTINUE: { int b=insTri.val[j].v.i; blocs[b]->continues.Etendre((int)Ins.t); break; } case TYPE_ETIQAUTOBREAK: { int b=insTri.val[j].v.i; blocs[b]->breaks.Etendre((int)Ins.t); break; } case TYPE_VARIABLE: case TYPE_VARIABLELOC: case TYPE_VARIABLETHIS: case TYPE_VARIABLEPARAM: insTri.val[j].v.i=insTri.val[j].v.ptr->indice; break; case 0: throw TXT("erreur interne du compilateur (type instruction=0)"); } Ins.Ajouter(insTri.val[j]); } } if (CodePrec== Code::I_FINOUET) FinOu(); } bool Compilateur::CompilerSeparateur() { if ((*Source=='\n')||(*Source==0)||(*Source=='/')||(*Source=='?' && LigneAc==LP_CAS))//Fin de ligne { if (LigneAc==LP_CAS && *Source!='?') throw TXT("il manque un ? en fin de cas"); if (iVarLongue) throw TXT("un < n'est pas refermé par un >"); DebutLigne=(int)Ins.t; int PosDebutLigne;//Position de la portion //de code dans laquelle il faut mettre la pos du //début de la prochaine ligne insTri.Init(); PosPileType=0; if (nInstr==1) { if (Instr[0].Special==SPE_NORMAL) AjouterInstruction(0); else throw TXT("c'est quoi ce machin tout seul sur la ligne ?"); } else if (nInstr>1) { //On calcule la taille des parenthèses uint nOuvre=0,nFerme=0; for (uint i=0; i<nInstr; i++) { if (Instr[i].Special==SPE_PAR_O) { nOuvre++; uint l=i+1; uint nPars=1; while ((nPars)&&(l<nInstr)) { if (Instr[l].Special==SPE_PAR_F) nPars--; else if (Instr[l].Special==SPE_PAR_O) nPars++; l++; } if (nPars) throw TXT("une parenthèse n'est pas refermée"); Instr[i].nVal=l-i-1;//Le nombre d'instructions entre les parenthèses+les parenthèses Instr[i].pVal=i; } else if (Instr[i].Special==SPE_PAR_F) { nFerme++; if (nFerme>nOuvre) throw TXT("une parenthèse est refermée sans avoir été ouverte"); } } /* si ac=0 si pile et si pile n'est pas une ( qui contient la position suivante instruction ac=enlever l'instruction du haut de la pile sinon ac=suivant suivant=0 si suivant=0 si l'instruction est une parenthèse déjà mise, sauter tout ce qui est entre parenthèses et recommencer rechercher l'instruction suivante : Si l'instruction est une instruction parenthèse sauter toutes les intructions dans les parenthèses sinon passer à l'instruction suivante si ac=0 continue; si instr=parenthèse et suiv=parenthèse fermante ac=suiv=0 continue si l'instruction actuelle a une priorité inférieure ou égale à l'instruction suivante si l'instruction actuelle est une parenthèse marquer la parenthèse comme déjà mise se repositionner à la première instruction de la parenthèse instruction ac=cette instruction suiv=0 sinon écrire l'instruction actuelle ac=0 sinon mettre en pile l'instruction actuelle instruction ac=instructino suivante suivant=0 x*y+a*b ac = x, pile =, res =, suiv=* ac = *, pile =, res =x, suiv=y ac = y, pile =*, res= x,suiv=+ ac = *, pile =, res=xy,suiv=+ ac = +, pile =, res=xy*,suiv=a ac = a, pile =+, res=xy*,suiv=* ac = +, pile =, res=xy*a,suiv=* ac = *, pile =+, res=xy*a,suiv=b ac = b, pile =+*, res=xy*a,suiv=; ac =*, pile=+, res=xy*ab,suiv; ac =+, pile=, res=xy*ab*,suiv; ac =;, pile =, res=xy*ab*+,suiv x*(y+a)*b ac = x, pile =, res =,suiv=* ac = *, pile =, res =x,suiv=( ac = (, pile =*, res=x,suiv=* ac = y, pile =*(, res=x,suiv=+ ac = +, pile =*(, res=xy,suiv=a ac = a, pile =*(+, res=xy,suiv=) ac = +, pile =*(, res=xya,suiv=) ac = (, pile =*, res=xya+, suiv=) ac = *, pile =, res=xya+, suiv=* ac = *, pile =, res=xya+*, suiv=b ac = b, pile =*, res=xya+*, suiv=; ac = *, pile =, res=xya+*b, suiv=; ac = ;, pile =, res=xya+*b*, suiv {a+b}(x*y)*c 0123456789AB ac = {, pile =, res =, suiv=(, pos=5 ac = (, pile ={, res=, suiv=*, pos=A ac = x, pile ={(, res=, suiv=*,pos=7 ac = *, pile ={(, res=x, suiv=y,pos=8 ac = y, pile ={(*, res=x, suiv=),pos=9 ac = *, pile ={(, res=xy, suiv=),pos=9 ac = (, pile ={(, res=xy*,suiv=),pos=9 ac = */ #define RIEN -1 int Ac=0, Suivant=RIEN, Pos=0; int Pile[128]; uint PosPile=0; int HautPile=RIEN; Instr[nInstr].p=PRI_FIN; Instr[nInstr].Special=SPE_FIN; while (Suivant!=(int)nInstr || PosPile) { if (Ac==RIEN)//Cherchons l'instruction actuelle { /* Si dans la pile on a une instruction normale ou dans le cas particulier (1) on récupère l'instruction dans la pile sinon on passe à l'instruction suivante (1) Quand on a SPE_PAR_OM en haut de la pile et une parenthèse fermante en suite, cela signifie qu'on a traité tout le contenu des parenthèses et on se replace à son début*/ if (PosPile && (Instr[HautPile].Special!=SPE_PAR_OM || (Suivant!=-1 && Instr[Suivant].Special==SPE_PAR_F))) //||Instr[HautPile].pVal>Pos || (Instr[HautPile].pVal+Instr[HautPile].nVal<Pos))) { PosPile--; Ac=HautPile;//Va permettre son élimination if (PosPile) HautPile=Pile[PosPile-1]; else HautPile=RIEN; } else { Ac=Suivant; Suivant=RIEN; } } if (Suivant==RIEN) { /*Si on n'a pas d'instruction suivante : si l'instruction lue est une parenthèse, on saute son contenu */ if (Instr[Pos].Special==SPE_PAR_O) Pos+=Instr[Pos].nVal; Pos++; //On saute les instructions déjà mises while ((Instr[Pos].Special==SPE_PAR_OM) ||(Instr[Pos].Special==SPE_DEJAMIS)) Pos+=Instr[Pos].nVal+1; Suivant=Pos; } if (Ac==RIEN) continue; //Si Ac et Suivant sont des parenthèses, on les annulle if (Instr[Ac].Special==SPE_PAR_OM && Instr[Suivant].Special==SPE_PAR_F) { Ac=RIEN; Suivant=RIEN; continue; } if (Instr[Ac].p<=Instr[Suivant].p) { //Si la priorité de Ac est inférieure ou égale //à la priorité de Suivant, on la garde if (Instr[Ac].Special==SPE_PAR_O) { /*Si l'instruction Ac était une parenthèse on va examiner 'récursivement' son contenu Pour cela on empile le début de la parenthèse, et on se place sur l'instruction après la parenthèse*/ Instr[Ac].Special=SPE_PAR_OM; HautPile=Ac; Pile[PosPile++]=HautPile; Ac=Pos=Ac+1; Suivant=RIEN; //TODO: régler le problème des parenthèses vides /*Pos=Ac; Ac=RIEN; Suivant=RIEN;*/ } else { //Sinon on ajoute l'instruction AjouterInstruction(Ac); Instr[Ac].Special=SPE_DEJAMIS; Instr[Ac].nVal=0; Ac=RIEN; } } else { //On empile l'instruction Pile[PosPile++]=Ac; HautPile=Ac; Ac=Suivant; Suivant=RIEN; } } } if (LigneAc==LP_FOR_PAS) { LigneDeCode *ldc=new LigneDeCode; ldc->nIns=insTri.nIns; ldc->nVals=insTri.nVals; memcpy(ldc->ins,insTri.ins,insTri.nIns*sizeof(SInstr)); memcpy(ldc->val,insTri.val,insTri.nVals*sizeof(valeur)); for (index_t i=0; i<insTri.nVals; i++) insTri.val[i].Effacer(); blocs.Dernier()->pasDuFor=ldc; insTri.Init(); } if (LigneAc==LP_CAS) { if (insTri.nIns==0) throw TXT("cas vide"); if (insTri.nIns>1) throw TXT("le cas ne se résoud pas en une constante"); if (insTri.ins[0].Code!= Code::I_ENTIER) throw TXT("le cas doit être une constante entière"); CCasSwitch casSwitch((code*)Ins.t,insTri.val[0].v.i); programme->Switch[AcSwitch.Dernier()]->Cas.Etendre(casSwitch); insTri.Init(); } nValeurs=0; nInstr=0; if (insTri.nIns) { Ins.AjouterCode(Code::I_DEBUTLIGNE); Ins.AjouterEntier(Ligne); if (ProbaSauterLigne) { Ins.AjouterCode(Code::I_PROBASAUTERLIGNE); Ins.AjouterChances(ProbaSauterLigne); PosDebutLigne=int(Ins.t); Ins.AjouterEntier(0); } CreerCodeFinal(insTri); /*if (PosPileType) { Ins.AjouterCode(I_DEPLACERHAUTPILE); Ins.AjouterEntier(-(int)PosPileType); }*/ if (ProbaSauterLigne) { Ins.ChgGotoRel(PosDebutLigne,(int)Ins.t); ProbaSauterLigne=0; } } carac TypeFinLigne=*Source; if (TypeFinLigne) Source++; if (LigneAc==LP_FOREACH_INIT) { index_t svarLoc=(index_t)blocs[blocs.l-2]->symbole->taille; blocs.Dernier()->depart=(int)Ins.t; Ins.AjouterCode(Code::I_VALEURVARLOC); Ins.AjouterEntier(int(svarLoc)); Ins.AjouterCode(Code::I_VARIABLELOC); Ins.AjouterEntier(int(svarLoc+1)); Ins.AjouterCode(Code::I_TAILLE); Ins.AjouterCode(Code::I_INFERIEUR); Ins.AjouterCode(Code::I_GOTOZEROR); blocs.Dernier()->breaks.Etendre((int)Ins.t); Ins.AjouterEntier(0); Ins.AjouterCode(Code::I_VARIABLELOC); Ins.AjouterEntier(int(svarLoc+2)); Ins.AjouterCode(Code::I_VARIABLELOC); Ins.AjouterEntier(int(svarLoc+1)); Ins.AjouterCode(Code::I_VALEURVARLOC); Ins.AjouterEntier(int(svarLoc)); Ins.AjouterCode(Code::I_TABLEAUVAL); Ins.AjouterCode(Code::I_INSTANCEDE); LigneAc=LP_DEBUTBLOC; } if ((TypeFinLigne=='/')&&(LigneAc==LP_DEBUTBLOC)) { blocs.Dernier()->blocLigne=true; LignePrec=LigneAc; LigneAc=LP_NORMALE; } else if (LigneAc==LP_FOR_INIT) { LignePrec=LigneAc; LigneAc=LP_FOR_TEST; blocs.Dernier()->depart=(int)Ins.t; AjCode(Code::I_GOTOZEROR,PRI_MAX); AjEntierType((int)blocs.l-1,TYPE_ETIQAUTOBREAK); } else if (LigneAc==LP_FOR_TEST) { LignePrec=LigneAc; LigneAc=LP_FOR_PAS; } else if (LigneAc==LP_FOR_PAS) { LignePrec=LigneAc; LigneAc=LP_NORMALE; if (TypeFinLigne=='/') blocs.Dernier()->blocLigne=true; } else { LignePrec=LigneAc; LigneAc=LP_NORMALE; while (blocs.l && blocs.Dernier()->blocLigne) FinBloc(); } if (TypeFinLigne=='\n') Ligne++; if (TypeFinLigne==0) { return true; } } else return false; return true; } bool Compilateur::CompilerTableau() { if ((*Source==SEP_TAB_O)||(*Source==SEP_HAC_O)) { if (VarLongue[iVarLongue].Type.l==0) throw TXT("le < pour l'indice de tableau doit coller à la variable"); /*La variable doit être du type XXX TABLEAU/HACHAGE ou à la rigueur être un PINGOUIN, ou, dans le cas de <> du type XXX classe (!=entier...) pour un accès direct aux propriétés*/ if (VarLongue[iVarLongue].Type.Dernier()!=symboleValeur) { //On vérifie que le symbole correspond bien à la déclaration //de la variable if (*Source==SEP_TAB_O &&VarLongue[iVarLongue].Type.Dernier()!=symboleTableau &&VarLongue[iVarLongue].Type.Dernier()->IsPod()) { AfficherType(VarLongue[iVarLongue].Type); throw TXT("symbole < invalide car ce n'est pas un tableau"); } if (*Source==SEP_HAC_O &&VarLongue[iVarLongue].Type.Dernier()!=symboleTableHachage) throw TXT("ce n'est pas une table de hachage"); } AjParO(PRI_CONSTANTE); VarLongue[++iVarLongue].Type.Vider(); Source++; } else if ((*Source=='>')||(*Source==SEP_HAC_F)) { bool Hac=(*Source==SEP_HAC_F); Source++; SauterEspaces(); if (iVarLongue==0) throw TXT("symbole > ou ] innattendu, le tableau n'a pas été ouvert"); iVarLongue--; if (VarLongue[iVarLongue].Type.l==0) throw TXT("bug dans la gestion des tableaux"); /* clog <<"fermeture "; AfficherType(VarLongue[iVarLongue].Type);*/ //On peut avoir par exemple ENTIER TABLEAU //On vire TABLEAU (puisque a[3] est du type des membres a) //On vérifie que le truc qui ferme correspond bien au type de la variable if (VarLongue[iVarLongue].Type.Dernier()!=symboleValeur) { Symbole * c=VarLongue[iVarLongue].Type.Depiler(); //On vérifie par la même occasion qu'on ferme avec le bon type if (!Hac &&c!=symboleTableau&& c->type!=Symbole::Classe) throw TXT("symbole > invalide car ce n'est pas un tableau"); if (Hac &&c!=symboleTableHachage) throw TXT("ce n'est pas une table de hachage"); } AjParF(); if (*Source==SEP_TAB_O || *Source==SEP_PROP || *Source==SEP_HAC_O) { //On continue la variable longue AjCode(Hac? Code::I_HACHAGEREF: Code::I_TABLEAUREF); } else { //Fin de la variable longue VarLongue[iVarLongue].Type.Vider(); if (*Source=='(') { AjCode(Hac? Code::I_HACHAGEVAL: Code::I_TABLEAUVAL); //On change la priorité de la variable longue //Instr[VarLongue[iVarLongue].Depart].p=PRI_EXEC; //et on ne ferme pas la parenthèse... } else { if (VarLongue[iVarLongue].Val) AjCode(Hac? Code::I_HACHAGEVAL: Code::I_TABLEAUVAL); else AjCode(Hac? Code::I_HACHAGEREF: Code::I_TABLEAUREF); AjParF(); } } } else return false; return true; } void Compilateur::CompilerFonction() { bool definitEtiquette=false; if (*Source==_T('§')) { definitEtiquette=true; Source++; } Symbole * classeParent=blocs.Dernier()->symbole; while (!classeParent->PeutContenirFonction()) classeParent=classeParent->parent; carac * debut=Source; int ligne=Ligne; //On va chercher le nom de la classe si il y est ChercherMotClef(definitEtiquette); if (lClef==0) throw TXT("nom d'étiquette attendu"); if ((*Source==':')&&(Source[1]=='A')&&(Source[2]=='S') &&(Source[3]=='V')) { Source+=4; SauterEspaces(); if (*Source=='(') { Source++; SauterEspaces(); while (*Source!=')') { ChercherMotClef(); if (lClef==0) throw TXT("erreur de syntaxe dans les parenthèses"); SauterEspaces(); } Source++; SauterEspaces(); } if (*Source==':') { //Ça y est, on en est au nom de la classe ! //...quelle syntaxe pourrie ce GOTO++ Source++; Symbole * s=ChercherSymbole(); if (EstNouveauSymbole(s) || !s->EstClasse()) throw TXT("la classe de cette fonction n'existe pas"); classeParent=s; } } //On revient au début Source=debut; Ligne=ligne; ChercherMotClef(true); Symbole * syFonction=ChercherSymboleDans(classeParent); SauterEspaces(); if (!EstNouveauSymbole(syFonction)) { //On regarde si on est en train de définir la valeur du symbole if (syFonction->Valeur.Type==TYPE_ETIQUETTE) throw TXT("la fonction a déjà été définie"); } else { //On crée le symbole syFonction=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur), blocs.Dernier()->symbole); syFonction->attributs|=Symbole::constante; } //On calcule la valeur int valeurEtiquette=0; const carac * c=MotClef; for (index_t a=0; a<lClef; a++) { valeurEtiquette*=10; valeurEtiquette+=*c-'0'; c++; } //Début d'un bloc de fonction if ((*Source==':')&&(Source[1]=='A')&&(Source[2]=='S') &&(Source[3]=='V')) { definitEtiquette=true; Source+=4; SauterEspaces(); index_t nNouvParametres=0; if (*Source=='(')//Les paramètres { Source++; do { SauterEspaces(); ChercherMotClef(); if (lClef==0) break; Symbole * nouveau=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur), syFonction); nouveau->acces=Symbole::Local; nouveau->type=Symbole::VariableParam; nouveau->indice=nNouvParametres++; } while(1); if (*Source!=')') throw TXT("parenthèse fermante attendue"); Source++; } if (*Source==':')//Classe { Source++; ChercherSymbole();//on fait ça, mais on la connait déjà évidemment DebutBloc(TypeBloc::Classe,classeParent); blocs.Dernier()->classeSpecifiee=true; } DebutBloc(TypeBloc::Fonction,syFonction); if (classeParent!=programme->symboleGlobal) { carac * k=classeParent->nom; while (*k) { valeurEtiquette*=10; valeurEtiquette+=*k-'0'; k++; } if (czcmp(syFonction->nom,_T("berger"))==0) { //C'est le constructeur classeParent->defConstr=syFonction; } } } if (classeParent!=syFonction->parent) { //On la vire d'où elle est... //Un peu chiant ça... Symbole * ancParent=syFonction->parent; if (ancParent->fils==syFonction) ancParent->fils=syFonction->suivant; //On reconnecte le frère for (Symbole * f=ancParent->fils; f!=0; f=f->suivant) { if (f->suivant==syFonction) { f->suivant=syFonction->suivant; break; } } syFonction->parent=classeParent; syFonction->suivant=classeParent->fils; classeParent->fils=syFonction; } bool fnthis; if (syFonction->parent->attributs & Symbole::filsthis) fnthis=true; else fnthis=false; syFonction->etiquette=valeurEtiquette; if (definitEtiquette) { syFonction->Valeur.Type=TYPE_ETIQUETTE; syFonction->Valeur.v.i=(int)Ins.t; } //On regarde si il y a des attributs, style GIVRE ChercherMotClef(); if (lClef) { if (EstMotClef(_T("GIVRE"))) { fnthis=false; } else Source=MotClef;//On annule } if (fnthis) { syFonction->TypeAc.Def(symboleValeur);//le retour syFonction->TypeAc.Empiler(symboleDebutParams); syFonction->TypeAc.Empiler(symboleValeur); syFonction->TypeAc.Empiler(symboleEtc); syFonction->TypeAc.Empiler(symboleMethodeGPP); syFonction->type=Symbole::MethodeGPP; } else { syFonction->TypeAc.Def(symboleValeur);//le retour syFonction->TypeAc.Empiler(symboleDebutParams); syFonction->TypeAc.Empiler(symboleValeur); syFonction->TypeAc.Empiler(symboleEtc); syFonction->TypeAc.Empiler(symboleFonctionGPP); syFonction->type=Symbole::FonctionGPP; } syFonction->attributs|=Symbole::constante; } bool Compilateur::CompilerConstante() { if ((*Source=='^')&&(ucarac(Source[1])>' '))//Expression régulière { Source++; carac Limite=*(Source++); carac *ExpReg=Source; while (*Source && *Source!=Limite) { if (*Source=='\\') { Source++; if (*Source==0) break; } if (*Source=='\n') Ligne++; Source++; } if (*Source==Limite) *(Source++)=0; else throw TXT("expression régulière non terminée"); carac * modif=0; if (*Source>='a' && *Source<='z') { modif=Source; while (*Source>='a' && *Source<='z') Source++; if (*Source) *(Source++)=0; } AjCode(Code::I_EXPREG); AjExpReg(ExpReg,modif); } else if (*Source==';')//Constante de caractère de contrôle { Source++; carac car='\n'; if (ALPHANUM(ucarac(*Source))) { switch (*Source) { case 'n': car='\n'; break; case 'r': car='\r'; break; case 't': car='\t'; break; case '0': car=0; break; default: throw TXT("caractère de contrôle inconnu"); } Source++; } AjCode(Code::I_CARAC,PRI_CONSTANTE); AjCarac(car); } else if (*Source==_T('«')) { Source++; size_t l=0; carac * dep=Source; while ((*Source)&&(*Source!=_T('»'))) { if (*Source==';') { Source++; l++; if (*Source==0) break; } if (*Source=='\n') Ligne++; Source++; l++; } if (*Source!=_T('»')) throw TXT("une chaîne doit se terminer par »"); Source++; //achaine c(dep,l); AjCode(Code::I_CONSTANTE,PRI_CONSTANTE); AjType(TYPE_CHAINE); AjChaine(dep,l); } else if (*Source=='$') { Source++; bool Modificateur; if (*Source=='<') { Modificateur=true; Source++; } else Modificateur=false; int c=0; int nChiffres=0; while ((ucarac(*Source)>='0' && ucarac(*Source)<='9')) { c*=10; c+=*Source-'0'; Source++; nChiffres++; } if (nChiffres==0) c=PRI_VIRGULE; if (Modificateur) { if (nInstr==0) throw TXT("tentative de modifier la priorité de l'instruction précédente, alors qu'il n'y en a pas"); Instr[nInstr-1].p=c; } else { AjNoOp(c); } } else if (*Source==_T('§')) { if (nInstr) throw TXT("les étiquettes doivent se trouver en début de ligne"); CompilerFonction(); } else if (*Source=='?') { float c=0; Source++; bool Negatif; if (*Source=='-') { Negatif=true; Source++; } else Negatif=false; while (ucarac(*Source)>='0' && ucarac(*Source)<='9') { c*=10; c+=*Source-'0'; Source++; } if (*Source==',') { Source++; float d=0; float div=1; while (ucarac(*Source)>='0' && ucarac(*Source)<='9') { d*=10; d+=*Source-'0'; Source++; div*=10; } c+=d/div; } if (*Source==_T('ê') || *Source==_T('Ê')) { Source++; bool Neg; if (*Source=='-') { Neg=true; Source++; } else Neg=false; float e=0; while (ucarac(*Source)>='0' && ucarac(*Source)<='9') { e*=10; e+=*Source-'0'; Source++; } if (Neg) e=-e; c*=powf(10,e); } if (Negatif) c=-c; AjCode(Code::I_CHANCES,PRI_CONSTANTE); AjChances(c); } else if ((*Source=='*')&&(Source[1]=='`'))//Constante de caractère { Source+=2; carac c=*(Source++); if (*Source!='\'') throw TXT("les caractères doivent être entre ` et '"); Source++; AjCode(Code::I_CARAC,PRI_CONSTANTE); AjCarac(c); } else if ((*Source=='*')&&(Source[1]=='('))//Constante entière { Source+=2; int c=0; bool Negatif; if (*Source=='-') { Negatif=true; Source++; } else Negatif=false; while (*Source && *Source!=')' && *Source!='\n') { c*=10; c+=*Source-'0'; Source++; } if (Negatif) c=-c; if (*Source!=')') throw TXT("les nombres entiers doivent se terminer par )"); Source++; AjCode(Code::I_ENTIER,PRI_CONSTANTE); AjEntier(c); } else return false; return true; } void Compilateur::ChercherMotClef(bool avecChiffres) { lClef=0; if (ALPHA(*Source) || (avecChiffres && (*Source>='0') && (*Source<='9'))) { MotClef=Source; do { Source++; lClef++; } while(ALPHA(*Source) || (avecChiffres && (*Source>='0') && (*Source<='9'))); } } bool Compilateur::CompilerClasse(Symbole * cla) { SauterEspaces(); //Opérateurs spéciaux if (*Source=='`') { Source++; AjCode(Code::I_ENTIER,PRI_CONSTANTE); AjEntier((int)size_t(cla));//TODO : un truc qui veut dire quelquechose return true; } if (*Source=='^' && Source[1]=='^') { //On veut le numéro de la propriété Source+=2; ChercherMotClef(); Symbole * prop=ChercherSymboleDans(cla); if (!EstNouveauSymbole(prop)) { AjCode(Code::I_ENTIER,PRI_CONSTANTE); AjEntier((int)prop->indice); return true; } throw CErreur(TXT("propriété %.*s inconnue après le ^^"), lClef,MotClef); } bool Redef=false; bool Constructeur=true; bool givre; if (blocs.Dernier()->symbole->attributs & Symbole::filsglob) givre=true; else givre=false; SauterEspaces(); carac * DebutNom=Source; ChercherMotClef(); while (lClef) { if (EstMotClef(_T("sauvage"))) { Redef=false; Constructeur=false; } else if (EstMotClef(_T("zap"))) { Redef=true; Constructeur=false; } else if (EstMotClef(_T("GIVRE"))) givre=true; else break; SauterEspaces(); DebutNom=Source; ChercherMotClef(); } Symbole * var=ChercherSymboleDans(blocs.Dernier()->symbole); if (EstNouveauSymbole(var)) //Nouvelle variable { var=programme->NouveauSymbole(MotClef,lClef,CType(symboleValeur), blocs.Dernier()->symbole); } if (!Redef) { if (givre) { var->indice=programme->varGlob.l; programme->varGlob.Etendre(valeur()); var->type=Symbole::VariableGlobale; } else { Symbole * parent=blocs.Dernier()->symbole; var->indice=(index_t)parent->taille++; if (parent->attributs & Symbole::filsthis) var->type=Symbole::VariableThis; else var->type=Symbole::VariableLocale; } } var->TypeAc.Def(cla); //Nombre de dimensions LireType(var->TypeAc); if (!Redef) var->typeDepart=var->TypeAc; /* if (var->TypeAc.l==1 && Constructeur) { if (cla->type==Symbole::ClasseC) { //On alloue l'objet AjCode(Code::I_ALLOCATION); AjPtrType(cla,TYPE_TYPE); } else { //TODO: non implémenté pour les classes GPP, on alloue pas } }*/ SauterEspaces(); if (*Source=='=') { Source=DebutNom;//TODO: utiliser un appel au constructeur par copie } else if (Constructeur && cla->defConstr) { if (var->TypeAc.l!=1) throw TXT("le berger ne peut pas être exécuté avec les troupeaux anonymes de troupeaux"); AjCode(givre? Code::I_VARIABLE: Code::I_VARIABLELOC); AjPtrType(var,TYPE_VARIABLE); AjCode(Code::I_INSTANCEDE,PRI_DEF); AjParO(PRI_EXEC); InsererConstante(cla->defConstr); AjCode(Code::I_EXECVAL,PRI_CONSTANTE); AjParF(); AjParO(); AjDebutParams(); if (*Source=='\n') AjParF(); else if (*Source=='(') { Source++; } } else if (*Source!='\n') { if (ucarac(*Source)<=32) throw CErreur(TXT("caractère 0x%x inattendu après la déclaration"),*Source); else throw CErreur(TXT("caractère %c inattendu après la déclaration"),*Source); } return true; } GotoPP::BoutCode* Compilateur::Compiler() { Ins.Reinit(); Ligne=1; nValeurs=0; nInstr=0; iVarLongue=0; ProbaSauterLigne=0; InstrAc=IP_PARO; CibleAuto=0; DernierSi=~0; NiveauGourou=1; etaitPremierSymbole=programme->symbole.FinI(); index_t EtaitPremierSource=programme->fichierSource.l; //On inclut l'espace de nommage "rien" qui contient //les fonctions internes useEspace.Vider(); useEspace.Etendre(symboleStd); //useEspace.Etendre(); //useEspace.Dernier()=rien; //On crée le bloc global blocs.Vider(); DebutBloc(TypeBloc::Classe,programme->symboleGlobal); /* % <= symbole global, peut contenir des chiffres %% <= symbole pas global, peut contenir des chiffres */ while (1) { SauterEspaces(); ChercherMotClef(); InstrPrec=InstrAc; InstrAc=IP_VARIABLE; const bool AVECET=true; const bool SANSET=false; if (lClef) { if (!CompilerMotClef()) { Source=MotClef; Symbole * s=ChercherSymbole(); if (!EstNouveauSymbole(s) && s->EstClasse()) CompilerClasse(s); else CompilerVariable(s, SANSET); } } else { if (!CompilerSeparateur()) { if (*Source=='&') { Source++; Symbole * s=ChercherSymbole(); if (!EstNouveauSymbole(s) && s->EstClasse()) throw TXT("nom de troupeau innattendu après le symbole &"); else CompilerVariable(s, AVECET); } else if (!CompilerOperateur() && !CompilerSeparateur() && !CompilerTableau() && !CompilerConstante()) { if (*Source<=' ') throw CErreur(TXT("caractère 0x%x inattendu"),*Source); else throw CErreur(TXT("caractère %c inattendu"),*Source); } } else if (*Source==0) { if (AcFichierSource && AcFichierSource->Parent!=0) { AcFichierSource->FinCode=(code*)Ins.t; AcFichierSource=AcFichierSource->Parent; Ligne=AcFichierSource->Ligne; Source=AcFichierSource->AcPos; } else break; } } } Ins.AjouterCode(Code::I_STOP); if (AcSwitch.l) throw TXT("un GOTOMULTIPLE n'a pas été fermé"); // DebutLigne=Ins.c; //Bon on corrige tous les labels ! for (Symbole ** l=etaitPremierSymbole; l<programme->symbole.Fin(); l++) { if ((*l)->type==Symbole::FonctionGPP || (*l)->type==Symbole::MethodeGPP) { code * c=&Ins.c[(*l)->Valeur.v.i]; (*l)->Valeur.v.et=c; } } // qsort(&Label.Premier(),Label.l,sizeof(SLabel),CmpLabels); //clog << RefEtiq.l << " références à des étiquettes \n"; for (index_t z=0; z<RefEtiq.l; z++) { Symbole **k=(Symbole**)&Ins.c[RefEtiq[z]]; Symbole * v=*k; if (v->Valeur.Type!=TYPE_ETIQUETTE && v->Valeur.Type!=TYPE_ETIQUETTE_THIS ) throw CErreur(TXT("lors de l'édition des liens, l'étiquette %s%%%s n'a pas été définie"), v->parent->nom,v->nom); *((code**)k)=v->Valeur.v.et; } for (index_t z=0; z<RefEtiqL.l; z++) { Symbole **k=(Symbole **)&Ins.c[RefEtiqL[z]]; Symbole * v=*k; if (v->Valeur.Type!=TYPE_ETIQUETTE && v->Valeur.Type!=TYPE_ETIQUETTE_THIS ) throw CErreur(TXT("lors de l'édition des liens, l'étiquette %s n'a pas été définie"), v->nom); *((size_t*)k)=size_t((size_t)v->Valeur.v.et-(size_t)k-sizeof(size_t)); } //clog << "Taille du code : "<<Ins.t<<" octets\n"; if (blocs.l>1) throw TXT("tous les blocs d'instructions n'ont pas été fermés"); if (RefEtiqA.l) throw TXT("toutes les étiquettes automatiques n'ont pas été placées avec AC"); //On corrige tous les switchs for (index_t i=0; i<programme->Switch.l; i++) { for (index_t c=0; c<programme->Switch[i]->Cas.l; c++) programme->Switch[i]->Cas[c].Pos+=(size_t)Ins.c; if (programme->Switch[i]->PosDefaut) programme->Switch[i]->PosDefaut+=(size_t)Ins.c; } //On corrige tous les fichiers sources for (index_t i=EtaitPremierSource; i<programme->fichierSource.l; i++) { programme->fichierSource[i]->DebutCode+=(size_t)Ins.c; programme->fichierSource[i]->FinCode+=(size_t)Ins.c; } Ins.i=Ins.c; programme->InitVarGlob(); return Ins.CreerBoutCode(); } int Compilateur::AcLigne() { return Ligne; } carac * Compilateur::AcFichier() { if (AcFichierSource!=0) return AcFichierSource->Nom; else return TXT("<code dynamique>"); }
Sidoine/gotopp
src/compilateur/compilateur.cpp
C++
gpl-2.0
70,880
<?php if ( ! defined( 'ABSPATH' ) ) { die( '-1' ); } $events_label_singular = tribe_get_event_label_singular(); $events_label_plural = tribe_get_event_label_plural(); if ( ! $_POST ) { $event_cost = get_post_meta( $post_id, '_EventCost', false ); if (is_array($event_cost)) { if (empty($event_cost)) { $event_cost = ''; } else { $event_cost = $event_cost[0]; } } } else { $event_cost = isset( $_POST['EventCost'] ) ? esc_attr( $_POST['EventCost'] ) : ''; } if ( apply_filters( 'tribe_events_community_display_cost_section', true ) ) { ?> <div class="tribe_sectionheader"> <h4><?php tribe_community_events_field_label( 'EventCost', __( 'Cost', 'the-events-calendar') ); ?></h4> </div><!-- .tribe_sectionheader --> <div class="block"> <input type="checkbox" id="isFreeEventCheckbox" <?php checked($event_cost, '0'); ?> /> <label style="margin-right:20px;" for="isFreeEventCheckbox"><?php esc_html_e( 'Free', 'the-events-calendar' ); ?></label> <span id='EventCostContainer'> <label> <input type="text" id="EventCost" name="EventCost" size="10" value="<?php echo esc_attr( $event_cost ); ?>" /> рублей </label> </span> </div> <?php }//end if
Ilya-d/htdocs
wp-content/themes/malivi/templates/community/modules/cost.php
PHP
gpl-2.0
1,280
/* Warrior of Dreamworld, 2D Massivly Mutiplayer Online Role-playing Game Copyright (C) 2012 Ryan Lahfa 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 "shared/Log.hpp" #include "ObjectMgr.hpp" #include <boost/archive/binary_iarchive.hpp> ObjectMgr* sObjectMgr; ObjectMgr::ObjectMgr(std::string const& TilesetPath, std::string const& TemplatesFilePath) : m_TilesetPath (TilesetPath), m_TemplatesFilePath (TemplatesFilePath) { } ObjectMgr::~ObjectMgr() { std::for_each(m_ItemTemplates.begin(), m_ItemTemplates.end(), MapDeleter()); std::for_each(m_CreatureTemplates.begin(), m_CreatureTemplates.end(), MapDeleter()); std::for_each(m_Tilesets.begin(), m_Tilesets.end(), MapDeleter()); std::for_each(m_Textures.begin(), m_Textures.end(), MapDeleter()); } void ObjectMgr::Initialize() { LoadTemplates(); } void ObjectMgr::LoadTileset(std::string const& FileName) { if (!SearchTileset(FileName)) { sf::Texture* tilesetTexture = new sf::Texture; if (!tilesetTexture->loadFromFile(m_TilesetPath + '/' + FileName)) { sLog.Write("Failed to load tileset texture: %s !", FileName); throw std::runtime_error("Failed to load a texture !"); } m_Tilesets[FileName] = tilesetTexture; } } ItemTemplate* ObjectMgr::GetItemTemplate(uint64 ItemID) { if (!SearchItemTemplate(ItemID)) { sLog.Write("Failed to find data about this item ID: %u !", ItemID); throw std::runtime_error("Failed to find data about something."); } return m_ItemTemplates[ItemID]; } sf::Texture* ObjectMgr::GetTileset(std::string const& TilesetName) { if (SearchTileset(TilesetName)) return m_Tilesets[TilesetName]; else { LoadTileset(TilesetName); return m_Tilesets[TilesetName]; } } sf::Texture* ObjectMgr::GetTileset(std::string const& TilesetName, sf::Color const& Mask, uint8 alpha) { if (SearchTileset(TilesetName)) return m_Tilesets[TilesetName]; else { LoadTileset(TilesetName); sf::Texture* tileset = m_Tilesets[TilesetName]; sf::Image imageTexture = tileset->copyToImage(); imageTexture.createMaskFromColor(Mask, alpha); tileset->update(imageTexture); return tileset; } } sf::Texture* ObjectMgr::GetTexture(std::string const& TextureName, std::string const& TexturePath) { auto TextureIt = m_Textures.find(TextureName); if (TextureIt != m_Textures.end()) return TextureIt->second; sf::Texture* Tex = new sf::Texture; if (!Tex->loadFromFile(TexturePath)) { sLog.Write("Failed to load texture (texture name: %s, texture path: %s)", TextureName, TexturePath); throw std::runtime_error("Failed to load texture."); } m_Textures[TextureName] = Tex; return Tex; } bool ObjectMgr::SearchItemTemplate(uint64 ItemID) const { return m_ItemTemplates.find(ItemID) != m_ItemTemplates.end(); } bool ObjectMgr::SearchCreatureTemplate(uint64 CreatureEntry) const { return m_CreatureTemplates.find(CreatureEntry) != m_CreatureTemplates.end(); } bool ObjectMgr::SearchTileset(std::string const& FileName) const { return m_Tilesets.find(FileName) != m_Tilesets.end(); } void ObjectMgr::LoadItemTemplate(std::string const& lineData) { ItemTemplate* Proto = new ItemTemplate; std::vector<std::string> data; boost::algorithm::split(data, lineData, boost::is_any_of(";"), boost::algorithm::token_compress_on); Proto->ItemID = boost::lexical_cast<uint64>(data.at(0)); Proto->Class = boost::lexical_cast<uint32>(data.at(1)); Proto->SubClass = boost::lexical_cast<uint32>(data.at(2)); Proto->Name = data.at(3); Proto->DisplayInfoID = boost::lexical_cast<uint32>(data.at(4)); Proto->InventoryType = boost::lexical_cast<uint8>(data.at(5)); Proto->Description = data.at(6); m_ItemTemplates[Proto->ItemID] = Proto; } void ObjectMgr::LoadCreatureTemplate(std::string const& lineData) { CreatureTemplate* Proto = new CreatureTemplate; std::vector<std::string> data; boost::algorithm::split(data, lineData, boost::is_any_of(";"), boost::algorithm::token_compress_on); Proto->Entry = boost::lexical_cast<uint64>(data.at(0)); Proto->Name = data.at(1); Proto->Tileset = data.at(2); Proto->tx = boost::lexical_cast<uint16>(data.at(3)); Proto->ty = boost::lexical_cast<uint16>(data.at(4)); Proto->npcflag = boost::lexical_cast<uint16>(data.at(5)); // Really needed by Client ? Proto->MaxHealth = boost::lexical_cast<uint32>(data.at(6)); Proto->MaxPower = boost::lexical_cast<uint32>(data.at(7)); m_CreatureTemplates[Proto->Entry] = Proto; } void ObjectMgr::LoadTemplates() { std::ifstream fileData(m_TemplatesFilePath); if (fileData) { std::string line; while (std::getline(fileData, line)) { int idxType = line.find(";"); std::string typeTemplate = line.substr(0, idxType); if (typeTemplate == "ItemTemplate") LoadItemTemplate(line.substr(idxType + 1)); else if (typeTemplate == "CreatureTemplate") LoadCreatureTemplate(line.substr(idxType + 1)); else if (typeTemplate == "QuestTemplate") // Skip it. Thanks to krofna! ; else sLog.Write("Unknown template type: %s. templates_info.dbc damaged ?", typeTemplate); } } else { sLog.Write("Failed to load templates data (FileName: %s)", m_TemplatesFilePath); throw std::runtime_error("Failed to load data."); } }
krofna/Warrior-of-Dreamworld
client/ObjectMgr.cpp
C++
gpl-2.0
6,332
/** * Copyright (C) 2002-2007 The FreeCol Team * * This file is part of FreeCol. * * FreeCol 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. * * FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.common.model; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import net.sf.freecol.Reformation; import org.w3c.dom.Element; /** * Represents a work location on a tile. */ public class ColonyTile extends FreeColGameObject implements WorkLocation, Ownable { public static final String UNIT_CHANGE = "UNIT_CHANGE"; private Colony colony; private Tile workTile; private Unit unit; private boolean colonyCenterTile; /** * Creates a new <code>ColonyTile</code>. * * @param game The <code>Game</code> this object belongs to. * @param colony The <code>Colony</code> this object belongs to. * @param workTile The tile in which this <code>ColonyTile</code> represents a * <code>WorkLocation</code> for. */ public ColonyTile(Game game, Colony colony, Tile workTile) { super(game); this.colony = colony; this.workTile = workTile; if (colony.getTile() == workTile) { colonyCenterTile = true; } else { colonyCenterTile = false; } } /** * Initiates a new <code>Building</code> from an * XML representation. * * @param game The <code>Game</code> this object belongs to. * @param in The input stream containing the XML. * @throws XMLStreamException if an error occured during parsing. */ public ColonyTile(Game game, XMLStreamReader in) throws XMLStreamException { super(game, in); readFromXML(in); } /** * Initiates a new <code>Building</code> from an * XML representation. * * @param game The <code>Game</code> this object belongs to. * @param e An XML-element that will be used to initialize * this object. */ public ColonyTile(Game game, Element e) { super(game, e); readFromXMLElement(e); } /** * Initiates a new <code>ColonyTile</code> * with the given ID. The object should later be * initialized by calling either * {@link #readFromXML(XMLStreamReader)} or * {@link #readFromXMLElement(Element)}. * * @param game The <code>Game</code> in which this object belong. * @param id The unique identifier for this object. */ public ColonyTile(Game game, String id) { super(game, id); } /** * Gets the owner of this <code>Ownable</code>. * * @return The <code>Player</code> controlling this * {@link Ownable}. */ public Player getOwner() { return colony.getOwner(); } /** * Sets the owner of this <code>Ownable</code>. * * @param p The <code>Player</code> that should take ownership * of this {@link Ownable}. * @exception UnsupportedOperationException is always thrown by * this method. */ public void setOwner(Player p) { throw new UnsupportedOperationException(); } /** * Checks if this is the tile where the <code>Colony</code> is located. * @return The result. */ public boolean isColonyCenterTile() { return colonyCenterTile; } /** * Gets the work tile. * * @return The tile in which this <code>ColonyTile</code> represents a * <code>WorkLocation</code> for. */ public Tile getWorkTile() { return workTile; } /** * Gets the tile where the colony is located. * @return The <code>Tile</code>. */ public Tile getTile() { return colony.getTile(); } public GoodsContainer getGoodsContainer() { return null; } /** * Gets the <code>Unit</code> currently working on this <code>ColonyTile</code>. * * @return The <code>Unit</code> or <i>null</i> if no unit is present. * @see #setUnit */ public Unit getUnit() { return unit; } /** * Gets a pointer to the colony containing this tile. * @return The <code>Colony</code>. */ public Colony getColony() { return colony; } /** * Sets a <code>Unit</code> to this <code>ColonyTile</code>. * * @param unit The <code>Unit</code>. * @see #getUnit */ public void setUnit(Unit unit) { Unit oldUnit = getUnit(); this.unit = unit; if (oldUnit != null) { GoodsType workType = oldUnit.getWorkType(); firePropertyChange(workType.getId(), getProductionOf(oldUnit, workType), null); } if (unit != null) { GoodsType workType = unit.getWorkType(); // SOMEHOW, workType was null in unit tests if (workType != null) { firePropertyChange(workType.getId(), null, getProductionOf(unit, workType)); } } } /** * Gets the amount of Units at this <code>ColonyTile</code>. * @return The amount of Units at this <code>ColonyTile</code>. */ public int getUnitCount() { return (getUnit() != null) ? 1 : 0; } /** * Relocates any worker on this <code>ColonyTile</code>. * The workers are added to another {@link WorkLocation} * within the {@link Colony}. */ public void relocateWorkers() { if (getUnit() != null) { for (WorkLocation wl : getColony().getWorkLocations()) { if (wl != this && wl.canAdd(getUnit())) { getUnit().work(wl); break; } } } } /** * Check if this <code>WorkLocation</code> is available to the colony. * Used by canAdd() and the gui to decide whether to draw a border * on this tile in the colony panel. * * @return True if the location can be worked. */ public boolean canBeWorked() { Player player = getOwner(); // Not workable if there is a settlement, hostile occupation, // unable to work water, or lost city rumour to Europeans. Tile tile = getWorkTile(); if (tile.getSettlement() != null || tile.getOccupyingUnit() != null || !(tile.isLand() || colony.hasAbility("model.ability.produceInWater")) || (player.isEuropean() && tile.hasLostCityRumour())) { return false; } // Special cases when tile owned by another settlement. Settlement settlement = tile.getOwningSettlement(); if (settlement == null) { ; // OK } else if (settlement instanceof Colony) { // Disallow if owned by other Europeans or in active use. Colony otherColony = (Colony) settlement; if (otherColony != colony) { if (otherColony.getOwner() != player || otherColony.getColonyTile(tile).getUnit() != null) { return false; } } } else if (settlement instanceof IndianSettlement) { // Disallow if owned and valued by natives. if (player.getLandPrice(tile) > 0) { return false; } } else { throw new IllegalStateException("Bogus settlement"); } return true; } /** * Checks if the specified <code>Locatable</code> may be added to * this <code>WorkLocation</code>. * * @param locatable the <code>Locatable</code>. * @return <code>true</code> if the <code>Unit</code> may be added * and <code>false</code> otherwise. */ public boolean canAdd(Locatable locatable) { if (!canBeWorked()) { return false; } if (!(locatable instanceof Unit)) { return false; } Unit unit = (Unit) locatable; if (!unit.getType().hasSkill()) { return false; } return getUnit() == null || unit == getUnit(); } /** * Add the specified <code>Locatable</code> to this <code>WorkLocation</code>. * @param locatable The <code>Locatable</code> that shall be added to this <code>WorkLocation</code>. */ public void add(Locatable locatable) { if (isColonyCenterTile() || unit != null) { throw new IllegalStateException("Other unit present while adding a unit to ColonyTile:" + getId()); } if (!canAdd(locatable)) { if (getWorkTile().getOwningSettlement() != null && getWorkTile().getOwningSettlement() != getColony()) { throw new IllegalArgumentException("Cannot add locatable to this location: another colony claims this land!"); } throw new IllegalArgumentException("Cannot add locatable to this location: there is a unit here already!"); } Unit u = (Unit) locatable; u.removeAllEquipment(false); u.setState(Unit.UnitState.IN_COLONY); // Find a teacher if available. Unit potentialTeacher = getColony().findTeacher(u); if (potentialTeacher != null) { potentialTeacher.setStudent(u); u.setTeacher(potentialTeacher); } setUnit(u); } /** * Remove the specified <code>Locatable</code> from this <code>WorkLocation</code>. * @param locatable The <code>Locatable</code> that shall be removed from this <code>WorkLocation</code>. */ public void remove(Locatable locatable) { if (getUnit() == null) { return; } if (!getUnit().equals(locatable)) { return; } Unit oldUnit = getUnit(); oldUnit.setMovesLeft(0); setUnit(null); } public List<Unit> getUnitList() { if(getUnit() == null) { return new ArrayList<Unit>(); } else { return Collections.singletonList(getUnit()); } } public Iterator <Unit> getUnitIterator() { return getUnitList().iterator(); } /** * Checks if this <code>ColonyTile</code> contains the given <code>Locatable</code>. * * @param locatable The <code>Locatable</code>. * @return The result. */ public boolean contains(Locatable locatable) { return (locatable == unit) ? true:false; } /** * Gets the <code>Unit</code> currently working on this <code>ColonyTile</code>. * * @return The <code>Unit</code> or <i>null</i> if no unit is present. * @see #setUnit */ public Unit getFirstUnit() { return getUnit(); } /** * Gets the <code>Unit</code> currently working on this <code>ColonyTile</code>. * * @return The <code>Unit</code> or <i>null</i> if no unit is present. * @see #setUnit */ public Unit getLastUnit() { return getUnit(); } /** * Returns the unit who is occupying the tile * @return the unit who is occupying the tile * @see #isOccupied() */ public Unit getOccupyingUnit() { return workTile.getOccupyingUnit(); } /** * Checks whether there is a fortified enemy unit in the tile. * Units can't produce in occupied tiles * @return <code>true</code> if an fortified enemy unit is in the tile */ public boolean isOccupied() { return workTile.isOccupied(); } /** * Prepares this <code>ColonyTile</code> for a new turn. */ public void newTurn() { if (isColonyCenterTile()) { produceGoodsCenterTile(); } else if (getUnit() != null && !isOccupied()) { produceGoods(); workTile.expendResource(getUnit().getWorkType(), getUnit().getType(), colony); } } private void produceGoods() { int amount = getProductionOf(getUnit().getWorkType()); if (amount > 0) { colony.addGoods(getUnit().getWorkType(), amount); unit.modifyExperience(amount); } } private void produceGoodsCenterTile() { GoodsType goodsFood = workTile.primaryGoods(); colony.addGoods(goodsFood, getProductionOf(goodsFood)); GoodsType type2 = workTile.secondaryGoods(); if (type2 != null) colony.addGoods(type2, getProductionOf(type2)); } /** * Returns a worktype for a unit. * * @param unit a <code>Unit</code> value * @return a workType */ public GoodsType getWorkType(Unit unit) { GoodsType workType = unit.getWorkType(); int amount = getProductionOf(unit, workType); if (amount == 0) { List<GoodsType> farmedGoodsTypes = Reformation.getSpecification().getFarmedGoodsTypeList(); for(GoodsType farmedGoods : farmedGoodsTypes) { int newAmount = getProductionOf(unit, farmedGoods); if (newAmount > amount) { amount = newAmount; workType = farmedGoods; } } } return workType; } /** * Returns the production of the given type of goods. * * @param goodsType a <code>GoodsType</code> value * @return an <code>int</code> value */ public int getProductionOf(GoodsType goodsType) { if (goodsType == null) { throw new IllegalArgumentException("GoodsType must not be 'null'."); } else if (getUnit() == null) { if (isColonyCenterTile() && (goodsType.isFoodType() || goodsType.equals(workTile.secondaryGoods()))) { return workTile.potential(goodsType, null); } else { return 0; } } else if (goodsType.equals(getUnit().getWorkType())) { return getProductionOf(getUnit(), goodsType); } else { return 0; } } /** * Returns the production of the given type of goods. * * @param goodsType a <code>GoodsType</code> value * @param unitType a <code>unitType</code> value * @return an <code>int</code> value */ public Set<Modifier> getProductionModifiers(GoodsType goodsType, UnitType unitType) { if (goodsType == null) { throw new IllegalArgumentException("GoodsType must not be 'null'."); } else { Set<Modifier> result = new LinkedHashSet<Modifier>(); if (getUnit() == null) { if (isColonyCenterTile() && (goodsType.isFoodType() || goodsType.equals(workTile.secondaryGoods()))) { result.addAll(workTile.getProductionBonus(goodsType, null)); result.addAll(getColony().getFeatureContainer().getModifierSet(goodsType.getId())); } } else if (goodsType.equals(getUnit().getWorkType())) { result.addAll(workTile.getProductionBonus(goodsType, unitType)); result.addAll(getUnit().getModifierSet(goodsType.getId())); } return result; } } /** * Returns the production of the given type of goods which would * be produced by the given unit * * @param unit an <code>Unit</code> value * @param goodsType a <code>GoodsType</code> value * @return an <code>int</code> value */ public int getProductionOf(Unit unit, GoodsType goodsType) { if (unit == null) { throw new IllegalArgumentException("Unit must not be 'null'."); } else if (workTile.isLand() || colony.hasAbility("model.ability.produceInWater")) { int production = unit.getProductionOf(goodsType, workTile.potential(goodsType, unit.getType())); if (production > 0) { production = Math.max(1, production + colony.getProductionBonus()); } return production; } else { return 0; } } @Override public void dispose() { if (unit != null) { unit.dispose(); } super.dispose(); } /** * This method writes an XML-representation of this object to * the given stream. * * <br><br> * * Only attributes visible to the given <code>Player</code> will * be added to that representation if <code>showAll</code> is * set to <code>false</code>. * * @param out The target stream. * @param player The <code>Player</code> this XML-representation * should be made for, or <code>null</code> if * <code>showAll == true</code>. * @param showAll Only attributes visible to <code>player</code> * will be added to the representation if <code>showAll</code> * is set to <i>false</i>. * @param toSavedGame If <code>true</code> then information that * is only needed when saving a game is added. * @throws XMLStreamException if there are any problems writing * to the stream. */ @Override protected void toXMLImpl(XMLStreamWriter out, Player player, boolean showAll, boolean toSavedGame) throws XMLStreamException { // Start element: out.writeStartElement(getXMLElementTagName()); // Add attributes: out.writeAttribute("ID", getId()); out.writeAttribute("colony", colony.getId()); out.writeAttribute("workTile", workTile.getId()); writeFreeColGameObject(unit, out, player, showAll, toSavedGame); // End element: out.writeEndElement(); } /** * Initialize this object from an XML-representation of this object. * @param in The input stream with the XML. * @throws XMLStreamException if a problem was encountered * during parsing. */ @Override protected void readFromXMLImpl(XMLStreamReader in) throws XMLStreamException { setId(in.getAttributeValue(null, "ID")); colony = getFreeColGameObject(in, "colony", Colony.class); workTile = getFreeColGameObject(in, "workTile", Tile.class); colonyCenterTile = (colony.getTile() == workTile); unit = null; while (in.nextTag() != XMLStreamConstants.END_ELEMENT) { if (in.getLocalName().equals(Unit.getXMLElementTagName())) { setUnit(updateFreeColGameObject(in, Unit.class)); } } } /** * Will return the position of the tile and the name of the colony in * addition to the FreeColObject.toString(). * * @return A representation of a colony-tile that can be used for debugging. */ @Override public String toString() { return "ColonyTile " + getWorkTile().getPosition().toString() + " in '" + getColony().getName() + "'"; } /** * Gets the tag name of the root element representing this object. * @return "colonyTile". */ public static String getXMLElementTagName() { return "colonyTile"; } }
tectronics/reformationofeurope
src/net/sf/freecol/common/model/ColonyTile.java
Java
gpl-2.0
19,928
using System.Collections.Generic; using meridian.smolensk.proto; namespace smolensk.Models.ViewModels { public class AdsListViewModel { public string Title { get; set; } public string NoAdsTitle { get; set; } public IEnumerable<ad_advertisments> Advertisments { get; set; } public int TotalPages { get; set; } public int CurrentPage { get; set; } public bool IsFavorite { get; set; } public string RouteName { get; set; } public AdsListViewModel() { NoAdsTitle = "Нет объявлений"; } } }
seavan/smoltoday
trunk/src/smolensk/Models/ViewModels/AdsListViewModel.cs
C#
gpl-2.0
631
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using Sdl.Core.Settings; using SDLCommunityCleanUpTasks.Models; namespace SDLCommunityCleanUpTasks { public class CleanUpSourceSettings : SettingsGroup, ICleanUpSourceSettings { #region TagSettingsControl public Dictionary<string, bool> FormatTagList { get { return GetSetting<Dictionary<string, bool>>(nameof(FormatTagList)); } set { GetSetting<Dictionary<string, bool>>(nameof(FormatTagList)).Value = value; } } public Dictionary<string, bool> PlaceholderTagList { get { return GetSetting<Dictionary<string, bool>>(nameof(PlaceholderTagList)); } set { GetSetting<Dictionary<string, bool>>(nameof(PlaceholderTagList)).Value = value; } } public bool UseTagCleaner { get { return GetSetting<bool>(nameof(UseTagCleaner)); } set { GetSetting<bool>(nameof(UseTagCleaner)).Value = value; } } #endregion TagSettingsControl #region ConversionsSettingsControl public bool ApplyToNonTranslatables { get { return GetSetting<bool>(nameof(ApplyToNonTranslatables)); } set { GetSetting<bool>(nameof(ApplyToNonTranslatables)).Value = value; } } public Dictionary<string, bool> ConversionFiles { get { return GetSetting<Dictionary<string, bool>>(nameof(ConversionFiles)); } set { GetSetting<Dictionary<string, bool>>(nameof(ConversionFiles)).Value = value; } } public string LastFileDirectory { get { return GetSetting<string>(nameof(LastFileDirectory)); } set { GetSetting<string>(nameof(LastFileDirectory)).Value = value; } } public bool UseConversionSettings { get { return GetSetting<bool>(nameof(UseConversionSettings)); } set { GetSetting<bool>(nameof(UseConversionSettings)).Value = value; } } #endregion ConversionsSettingsControl #region SegmentLockerControl public BindingList<SegmentLockItem> SegmentLockList { get { return GetSetting<BindingList<SegmentLockItem>>(nameof(SegmentLockList)); } set { GetSetting<BindingList<SegmentLockItem>>(nameof(SegmentLockList)).Value = value; } } public List<ContextDef> StructureLockList { get { return GetSetting<List<ContextDef>>(nameof(StructureLockList)); } set { GetSetting<List<ContextDef>>(nameof(StructureLockList)).Value = value; } } public bool UseContentLocker { get { return GetSetting<bool>(nameof(UseContentLocker)); } set { GetSetting<bool>(nameof(UseContentLocker)).Value = value; } } public bool UseSegmentLocker { get { return GetSetting<bool>(nameof(UseSegmentLocker)); } set { GetSetting<bool>(nameof(UseSegmentLocker)).Value = value; } } public bool UseStructureLocker { get { return GetSetting<bool>(nameof(UseStructureLocker)); } set { GetSetting<bool>(nameof(UseStructureLocker)).Value = value; } } #endregion SegmentLockerControl public ISettingsGroup Settings { get; set; } public CultureInfo SourceCulture { get; set; } public List<Placeholder> Placeholders { get { return GetSetting<List<Placeholder>>(nameof(Placeholders)); } set { GetSetting<List<Placeholder>>(nameof(Placeholders)).Value = value; } } [SuppressMessage("Microsoft.Contracts", "TestAlwaysEvaluatingToAConstant")] protected override object GetDefaultValue(string settingId) { switch (settingId) { case nameof(UseTagCleaner): return true; case nameof(UseConversionSettings): return true; case nameof(ApplyToNonTranslatables): return false; case nameof(FormatTagList): return new Dictionary<string, bool>() { { TagTable.BackgroundColor, false }, { TagTable.Bold, false }, { TagTable.FontName, false }, { TagTable.FontSize, false }, { TagTable.TextColor, false }, { TagTable.Italic, false }, { TagTable.TextDirection, false }, { TagTable.TextPosition, false }, { TagTable.Underline, false }, { TagTable.Strikethrough, false } }; case nameof(PlaceholderTagList): return new Dictionary<string, bool>(); case nameof(ConversionFiles): return new Dictionary<string, bool>(); case nameof(LastFileDirectory): return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); case nameof(SegmentLockList): return new BindingList<SegmentLockItem>(new List<SegmentLockItem>()); case nameof(UseSegmentLocker): return true; case nameof(UseStructureLocker): return true; case nameof(UseContentLocker): return true; case nameof(StructureLockList): return new List<ContextDef>(); case nameof(Placeholders): return new List<Placeholder>(); } return base.GetDefaultValue(settingId); } } }
sdl/Sdl-Community
CleanUpTasks/CleanUpTasks/CleanUpSourceSettings.cs
C#
gpl-2.0
5,910
#! /usr/bin/python ###### # Copyright 2007-2009 Sun Microsystems, Inc. All Rights Reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER # # This code is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 # only, as published by the Free Software Foundation. # # This code is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License version 2 for more details (a copy is # included in the LICENSE file that accompanied this code). # # You should have received a copy of the GNU General Public License # version 2 along with this work; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA # # Please contact Sun Microsystems, Inc., 16 Network Circle, Menlo # Park, CA 94025 or visit www.sun.com if you need additional # information or have any questions. ##### import os import cPickle as C import pyaura.bridge as B from pyaura.lib import j2py DATA_PREFIX= "out500k" class SimpleStats(): """ Generate simple statistics and plots for a set of tags. """ def __init__(self, prefix=DATA_PREFIX, regHost="brannigan"): self.tags = C.load(open(os.path.join(prefix, "alltags.dump"))) self._dataFileCache = DataFileCache(prefix, self.tags) self._is_plot_init = False if regHost!=None: self._aB = B.AuraBridge(regHost=regHost) else: self._aB = None def _init_plotting(self, backend="MacOSX"): if not self._is_plot_init: self._is_plot_init = True import matplotlib as M M.use(backend) def plot_taglen_hist(self): self._init_plotting() import pylab tag_len = [len(x) for x in self.tags.keys() ] pylab.hist(tag_len) def plot_tagpop_itemcnt(self, itemtype="a"): """ Tag the histogram of the number of tagged items for each tag """ self._init_plotting() import pylab itemcnt = [x.get_itemcount(itemtype) for x in self.tags.values()] pylab.hist(itemcnt, bins=1000) def plot_tagpop_appcnt(self, itemtype="a"): """ Tag the histogram of application counts for each tag """ self._init_plotting() import pylab appcnt = [x.get_totals(itemtype) for x in self.tags.values()] pylab.hist(appcnt, bins=1000) def get_average_len(self): w_running_tot=0 running_tot=0 tot_cnt=0 nbr_cnt=0 for t in self.tags.values(): w_running_tot+=len(t.name)*t.totals['artist'] running_tot+=len(t.name) tot_cnt+=t.totals['artist'] nbr_cnt+=1 print "Weighted avg:\t%0.4f" % (float(w_running_tot)/tot_cnt) print "Avg:\t\t%0.4f" % (float(running_tot)/nbr_cnt) def find_most_co_ocurr(self, tagname, n=10): vals = {} for t in self.tags: vals[t] = self.co_ocurr(tagname, t) return sorted(vals.items(), key=lambda (k,v): (v,k), reverse=True) def find_similar(self, tagname, n=10): return j2py( self._aB.mdb.find_similar_rawtags(tagname, n) ) def co_ocurr(self, tagname1, tagname2): """ Get relative co-occurence (Jaccard coefficient) """ tagdata1 = self._dataFileCache.get(tagname1) tagdata2 = self._dataFileCache.get(tagname2) kt1 = frozenset(tagdata1['artist'].keys()) kt2 = frozenset(tagdata2['artist'].keys()) return float(len(kt1.intersection(kt2))) / len(kt1.union(kt2)) class DataFileCache(): def __init__(self, prefix, taginfo): self._prefix = prefix self._taginfo = taginfo self._datafiles = {} def get(self, tagname): if tagname not in self._taginfo: raise KeyError("Tag '%s' is not in the db" % tagname) file_id = self._taginfo[tagname].file_location if not file_id in self._datafiles: print " > Loading datafile %s" % file_id path = os.path.join(self._prefix, "tagcut-%s.tagdata.dump" % file_id) self._datafiles[file_id] = C.load(open(path)) return self._datafiles[file_id][tagname]
SunLabsAST/AURA
Bridge/pyaura/tagclustering/simplestats.py
Python
gpl-2.0
4,439
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.policy.impl.keyguard; import android.app.PendingIntent; import android.app.PendingIntent.CanceledException; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.media.AudioManager; import android.media.IRemoteControlDisplay; import android.media.MediaMetadataRetriever; import android.media.RemoteControlClient; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Parcel; import android.os.Parcelable; import android.os.RemoteException; import android.os.SystemClock; import android.text.Spannable; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.android.internal.R; import java.lang.ref.WeakReference; /** * This is the widget responsible for showing music controls in keyguard. */ public class KeyguardTransportControlView extends FrameLayout implements OnClickListener { private static final int MSG_UPDATE_STATE = 100; private static final int MSG_SET_METADATA = 101; private static final int MSG_SET_TRANSPORT_CONTROLS = 102; private static final int MSG_SET_ARTWORK = 103; private static final int MSG_SET_GENERATION_ID = 104; private static final int DISPLAY_TIMEOUT_MS = 5000; // 5s protected static final boolean DEBUG = false; protected static final String TAG = "TransportControlView"; private ImageView mAlbumArt; private TextView mTrackTitle; private ImageView mBtnPrev; private ImageView mBtnPlay; private ImageView mBtnNext; private int mClientGeneration; private Metadata mMetadata = new Metadata(); private boolean mAttached; private PendingIntent mClientIntent; private int mTransportControlFlags; private int mCurrentPlayState; private AudioManager mAudioManager; private IRemoteControlDisplayWeak mIRCD; private boolean mMusicClientPresent = true; /** * The metadata which should be populated into the view once we've been attached */ private Bundle mPopulateMetadataWhenAttached = null; // This handler is required to ensure messages from IRCD are handled in sequence and on // the UI thread. private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_UPDATE_STATE: if (mClientGeneration == msg.arg1) updatePlayPauseState(msg.arg2); break; case MSG_SET_METADATA: if (mClientGeneration == msg.arg1) updateMetadata((Bundle) msg.obj); break; case MSG_SET_TRANSPORT_CONTROLS: if (mClientGeneration == msg.arg1) updateTransportControls(msg.arg2); break; case MSG_SET_ARTWORK: if (mClientGeneration == msg.arg1) { if (mMetadata.bitmap != null) { mMetadata.bitmap.recycle(); } mMetadata.bitmap = (Bitmap) msg.obj; mAlbumArt.setImageBitmap(mMetadata.bitmap); } break; case MSG_SET_GENERATION_ID: if (msg.arg2 != 0) { // This means nobody is currently registered. Hide the view. onListenerDetached(); } else { onListenerAttached(); } if (DEBUG) Log.v(TAG, "New genId = " + msg.arg1 + ", clearing = " + msg.arg2); mClientGeneration = msg.arg1; mClientIntent = (PendingIntent) msg.obj; break; } } }; private KeyguardHostView.TransportCallback mTransportCallback; /** * This class is required to have weak linkage to the current TransportControlView * because the remote process can hold a strong reference to this binder object and * we can't predict when it will be GC'd in the remote process. Without this code, it * would allow a heavyweight object to be held on this side of the binder when there's * no requirement to run a GC on the other side. */ private static class IRemoteControlDisplayWeak extends IRemoteControlDisplay.Stub { private WeakReference<Handler> mLocalHandler; IRemoteControlDisplayWeak(Handler handler) { mLocalHandler = new WeakReference<Handler>(handler); } public void setPlaybackState(int generationId, int state, long stateChangeTimeMs) { Handler handler = mLocalHandler.get(); if (handler != null) { handler.obtainMessage(MSG_UPDATE_STATE, generationId, state).sendToTarget(); } } public void setMetadata(int generationId, Bundle metadata) { Handler handler = mLocalHandler.get(); if (handler != null) { handler.obtainMessage(MSG_SET_METADATA, generationId, 0, metadata).sendToTarget(); } } public void setTransportControlFlags(int generationId, int flags) { Handler handler = mLocalHandler.get(); if (handler != null) { handler.obtainMessage(MSG_SET_TRANSPORT_CONTROLS, generationId, flags) .sendToTarget(); } } public void setArtwork(int generationId, Bitmap bitmap) { Handler handler = mLocalHandler.get(); if (handler != null) { handler.obtainMessage(MSG_SET_ARTWORK, generationId, 0, bitmap).sendToTarget(); } } public void setAllMetadata(int generationId, Bundle metadata, Bitmap bitmap) { Handler handler = mLocalHandler.get(); if (handler != null) { handler.obtainMessage(MSG_SET_METADATA, generationId, 0, metadata).sendToTarget(); handler.obtainMessage(MSG_SET_ARTWORK, generationId, 0, bitmap).sendToTarget(); } } public void setCurrentClientId(int clientGeneration, PendingIntent mediaIntent, boolean clearing) throws RemoteException { Handler handler = mLocalHandler.get(); if (handler != null) { handler.obtainMessage(MSG_SET_GENERATION_ID, clientGeneration, (clearing ? 1 : 0), mediaIntent).sendToTarget(); } } }; public KeyguardTransportControlView(Context context, AttributeSet attrs) { super(context, attrs); if (DEBUG) Log.v(TAG, "Create TCV " + this); mAudioManager = new AudioManager(mContext); mCurrentPlayState = RemoteControlClient.PLAYSTATE_NONE; // until we get a callback mIRCD = new IRemoteControlDisplayWeak(mHandler); } protected void onListenerDetached() { mMusicClientPresent = false; if (DEBUG) Log.v(TAG, "onListenerDetached()"); if (mTransportCallback != null) { mTransportCallback.onListenerDetached(); } else { Log.w(TAG, "onListenerDetached: no callback"); } } private void onListenerAttached() { mMusicClientPresent = true; if (DEBUG) Log.v(TAG, "onListenerAttached()"); if (mTransportCallback != null) { mTransportCallback.onListenerAttached(); } else { Log.w(TAG, "onListenerAttached(): no callback"); } } private void updateTransportControls(int transportControlFlags) { mTransportControlFlags = transportControlFlags; } @Override public void onFinishInflate() { super.onFinishInflate(); mTrackTitle = (TextView) findViewById(R.id.title); mTrackTitle.setSelected(true); // enable marquee mAlbumArt = (ImageView) findViewById(R.id.albumart); mBtnPrev = (ImageView) findViewById(R.id.btn_prev); mBtnPlay = (ImageView) findViewById(R.id.btn_play); mBtnNext = (ImageView) findViewById(R.id.btn_next); final View buttons[] = { mBtnPrev, mBtnPlay, mBtnNext }; for (View view : buttons) { view.setOnClickListener(this); } } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); if (DEBUG) Log.v(TAG, "onAttachToWindow()"); if (mPopulateMetadataWhenAttached != null) { updateMetadata(mPopulateMetadataWhenAttached); mPopulateMetadataWhenAttached = null; } if (!mAttached) { if (DEBUG) Log.v(TAG, "Registering TCV " + this); mAudioManager.registerRemoteControlDisplay(mIRCD); } mAttached = true; } @Override public void onDetachedFromWindow() { if (DEBUG) Log.v(TAG, "onDetachFromWindow()"); super.onDetachedFromWindow(); if (mAttached) { if (DEBUG) Log.v(TAG, "Unregistering TCV " + this); mAudioManager.unregisterRemoteControlDisplay(mIRCD); } mAttached = false; } class Metadata { private String artist; private String trackTitle; private String albumTitle; private Bitmap bitmap; public String toString() { return "Metadata[artist=" + artist + " trackTitle=" + trackTitle + " albumTitle=" + albumTitle + "]"; } } private String getMdString(Bundle data, int id) { return data.getString(Integer.toString(id)); } private void updateMetadata(Bundle data) { if (mAttached) { mMetadata.artist = getMdString(data, MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST); mMetadata.trackTitle = getMdString(data, MediaMetadataRetriever.METADATA_KEY_TITLE); mMetadata.albumTitle = getMdString(data, MediaMetadataRetriever.METADATA_KEY_ALBUM); populateMetadata(); } else { mPopulateMetadataWhenAttached = data; } } /** * Populates the given metadata into the view */ private void populateMetadata() { StringBuilder sb = new StringBuilder(); int trackTitleLength = 0; if (!TextUtils.isEmpty(mMetadata.trackTitle)) { sb.append(mMetadata.trackTitle); trackTitleLength = mMetadata.trackTitle.length(); } if (!TextUtils.isEmpty(mMetadata.artist)) { if (sb.length() != 0) { sb.append(" - "); } sb.append(mMetadata.artist); } if (!TextUtils.isEmpty(mMetadata.albumTitle)) { if (sb.length() != 0) { sb.append(" - "); } sb.append(mMetadata.albumTitle); } mTrackTitle.setText(sb.toString(), TextView.BufferType.SPANNABLE); Spannable str = (Spannable) mTrackTitle.getText(); if (trackTitleLength != 0) { str.setSpan(new ForegroundColorSpan(0xffffffff), 0, trackTitleLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); trackTitleLength++; } if (sb.length() > trackTitleLength) { str.setSpan(new ForegroundColorSpan(0x7fffffff), trackTitleLength, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } mAlbumArt.setImageBitmap(mMetadata.bitmap); final int flags = mTransportControlFlags; setVisibilityBasedOnFlag(mBtnPrev, flags, RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS); setVisibilityBasedOnFlag(mBtnNext, flags, RemoteControlClient.FLAG_KEY_MEDIA_NEXT); setVisibilityBasedOnFlag(mBtnPlay, flags, RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP); updatePlayPauseState(mCurrentPlayState); } public boolean isMusicPlaying() { return mCurrentPlayState == RemoteControlClient.PLAYSTATE_PLAYING || mCurrentPlayState == RemoteControlClient.PLAYSTATE_BUFFERING; } private static void setVisibilityBasedOnFlag(View view, int flags, int flag) { if ((flags & flag) != 0) { view.setVisibility(View.VISIBLE); } else { view.setVisibility(View.GONE); } } private void updatePlayPauseState(int state) { if (DEBUG) Log.v(TAG, "updatePlayPauseState(), old=" + mCurrentPlayState + ", state=" + state); if (state == mCurrentPlayState) { return; } final int imageResId; final int imageDescId; switch (state) { case RemoteControlClient.PLAYSTATE_ERROR: imageResId = com.android.internal.R.drawable.stat_sys_warning; // TODO use more specific image description string for warning, but here the "play" // message is still valid because this button triggers a play command. imageDescId = com.android.internal.R.string.lockscreen_transport_play_description; break; case RemoteControlClient.PLAYSTATE_PLAYING: imageResId = com.android.internal.R.drawable.ic_media_pause; imageDescId = com.android.internal.R.string.lockscreen_transport_pause_description; break; case RemoteControlClient.PLAYSTATE_BUFFERING: imageResId = com.android.internal.R.drawable.ic_media_stop; imageDescId = com.android.internal.R.string.lockscreen_transport_stop_description; break; case RemoteControlClient.PLAYSTATE_PAUSED: default: imageResId = com.android.internal.R.drawable.ic_media_play; imageDescId = com.android.internal.R.string.lockscreen_transport_play_description; break; } mBtnPlay.setImageResource(imageResId); mBtnPlay.setContentDescription(getResources().getString(imageDescId)); mCurrentPlayState = state; mTransportCallback.onPlayStateChanged(); } static class SavedState extends BaseSavedState { boolean clientPresent; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); this.clientPresent = in.readInt() != 0; } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(this.clientPresent ? 1 : 0); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.clientPresent = mMusicClientPresent; return ss; } @Override public void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); if (ss.clientPresent) { if (DEBUG) Log.v(TAG, "Reattaching client because it was attached"); onListenerAttached(); } } public void onClick(View v) { int keyCode = -1; if (v == mBtnPrev) { keyCode = KeyEvent.KEYCODE_MEDIA_PREVIOUS; } else if (v == mBtnNext) { keyCode = KeyEvent.KEYCODE_MEDIA_NEXT; } else if (v == mBtnPlay) { keyCode = KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE; } if (keyCode != -1) { sendMediaButtonClick(keyCode); } } private void sendMediaButtonClick(int keyCode) { if (mClientIntent == null) { // Shouldn't be possible because this view should be hidden in this case. Log.e(TAG, "sendMediaButtonClick(): No client is currently registered"); return; } // use the registered PendingIntent that will be processed by the registered // media button event receiver, which is the component of mClientIntent KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode); Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON); intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent); try { mClientIntent.send(getContext(), 0, intent); } catch (CanceledException e) { Log.e(TAG, "Error sending intent for media button down: "+e); e.printStackTrace(); } keyEvent = new KeyEvent(KeyEvent.ACTION_UP, keyCode); intent = new Intent(Intent.ACTION_MEDIA_BUTTON); intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent); try { mClientIntent.send(getContext(), 0, intent); } catch (CanceledException e) { Log.e(TAG, "Error sending intent for media button up: "+e); e.printStackTrace(); } } public boolean providesClock() { return false; } private boolean wasPlayingRecently(int state, long stateChangeTimeMs) { switch (state) { case RemoteControlClient.PLAYSTATE_PLAYING: case RemoteControlClient.PLAYSTATE_FAST_FORWARDING: case RemoteControlClient.PLAYSTATE_REWINDING: case RemoteControlClient.PLAYSTATE_SKIPPING_FORWARDS: case RemoteControlClient.PLAYSTATE_SKIPPING_BACKWARDS: case RemoteControlClient.PLAYSTATE_BUFFERING: // actively playing or about to play return true; case RemoteControlClient.PLAYSTATE_NONE: return false; case RemoteControlClient.PLAYSTATE_STOPPED: case RemoteControlClient.PLAYSTATE_PAUSED: case RemoteControlClient.PLAYSTATE_ERROR: // we have stopped playing, check how long ago if (DEBUG) { if ((SystemClock.elapsedRealtime() - stateChangeTimeMs) < DISPLAY_TIMEOUT_MS) { Log.v(TAG, "wasPlayingRecently: time < TIMEOUT was playing recently"); } else { Log.v(TAG, "wasPlayingRecently: time > TIMEOUT"); } } return ((SystemClock.elapsedRealtime() - stateChangeTimeMs) < DISPLAY_TIMEOUT_MS); default: Log.e(TAG, "Unknown playback state " + state + " in wasPlayingRecently()"); return false; } } public void setKeyguardCallback(KeyguardHostView.TransportCallback transportCallback) { mTransportCallback = transportCallback; } }
rex-xxx/mt6572_x201
frameworks/base/policy/src/com/android/internal/policy/impl/keyguard/KeyguardTransportControlView.java
Java
gpl-2.0
19,994
/* * Wazuh app - Mitre alerts components * Copyright (C) 2015-2021 Wazuh, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Find more information about this on the LICENSE file. */ import React, { Component } from 'react' import { EuiPanel, EuiFlexGroup, EuiFlexItem, } from '@elastic/eui'; import { SearchBar, FilterManager } from '../../../../../../src/plugins/data/public/'; import { I18nProvider } from '@kbn/i18n/react'; //@ts-ignore import { ComplianceRequirements } from './components/requirements'; import { ComplianceSubrequirements } from './components/subrequirements'; import { getElasticAlerts, getIndexPattern, IFilterParams } from '../mitre/lib'; import { pciRequirementsFile } from '../../../../common/compliance-requirements/pci-requirements'; import { gdprRequirementsFile } from '../../../../common/compliance-requirements/gdpr-requirements'; import { hipaaRequirementsFile } from '../../../../common/compliance-requirements/hipaa-requirements'; import { nistRequirementsFile } from '../../../../common/compliance-requirements/nist-requirements'; import { tscRequirementsFile } from '../../../../common/compliance-requirements/tsc-requirements'; import { KbnSearchBar } from '../../kbn-search-bar'; import { getDataPlugin } from '../../../kibana-services'; export class ComplianceTable extends Component { _isMount = false; timefilter: { getTime(): any setTime(time: any): void _history: { history: { items: { from: string, to: string }[] } } }; KibanaServices: { [key: string]: any }; filterManager: FilterManager; indexPattern: any; state: { selectedRequirement: string, flyoutOn: boolean, filterParams: IFilterParams, complianceObject: object, descriptions: object, loadingAlerts: boolean selectedRequirements: object, } props: any; constructor(props) { super(props); this.KibanaServices = getDataPlugin().query; this.filterManager = this.KibanaServices.filterManager; this.timefilter = this.KibanaServices.timefilter.timefilter; this.state = { selectedRequirement: "", flyoutOn: true, complianceObject: {}, descriptions: {}, loadingAlerts: true, selectedRequirements: {}, filterParams: { filters: this.filterManager.getFilters() || [], query: { language: 'kuery', query: '' }, time: this.timefilter.getTime(), }, } this.onChangeSelectedRequirements.bind(this); this.onQuerySubmit.bind(this); this.onFiltersUpdated.bind(this); } async componentDidMount() { this._isMount = true; this.filtersSubscriber = this.filterManager.getUpdates$().subscribe(() => { this.onFiltersUpdated(this.filterManager.getFilters()) }); this.indexPattern = await getIndexPattern(); this.buildComplianceObject(); } componentWillUnmount() { this.filtersSubscriber.unsubscribe(); } buildComplianceObject() { try { let complianceRequirements = {}; let descriptions = {}; let selectedRequirements = {}; // all enabled by default if (this.props.section === 'pci') { descriptions = pciRequirementsFile; Object.keys(pciRequirementsFile).forEach(item => { const currentRequirement = item.split(".")[0]; if (complianceRequirements[currentRequirement]) { complianceRequirements[currentRequirement].push(item); } else { selectedRequirements[currentRequirement] = true; complianceRequirements[currentRequirement] = []; complianceRequirements[currentRequirement].push(item); } }); //forEach } if (this.props.section === 'gdpr') { descriptions = gdprRequirementsFile; Object.keys(gdprRequirementsFile).forEach(item => { const currentRequirement = item.split("_")[0]; if (complianceRequirements[currentRequirement]) { complianceRequirements[currentRequirement].push(item); } else { selectedRequirements[currentRequirement] = true; complianceRequirements[currentRequirement] = []; complianceRequirements[currentRequirement].push(item); } }); //forEach } if (this.props.section === 'hipaa') { descriptions = hipaaRequirementsFile; Object.keys(hipaaRequirementsFile).forEach(item => { const currentRequirement = item.split(".")[0] + "." + item.split(".")[1] + "." + item.split(".")[2]; if (complianceRequirements[currentRequirement]) { complianceRequirements[currentRequirement].push(item); } else { selectedRequirements[currentRequirement] = true; complianceRequirements[currentRequirement] = []; complianceRequirements[currentRequirement].push(item); } }); //forEach } if (this.props.section === 'nist') { descriptions = nistRequirementsFile; Object.keys(nistRequirementsFile).forEach(item => { const currentRequirement = item.split(".")[0]; if (complianceRequirements[currentRequirement]) { complianceRequirements[currentRequirement].push(item); } else { selectedRequirements[currentRequirement] = true; complianceRequirements[currentRequirement] = []; complianceRequirements[currentRequirement].push(item); } }); //forEach } if (this.props.section === 'tsc') { descriptions = tscRequirementsFile; Object.keys(tscRequirementsFile).forEach(item => { const currentRequirement = item.split(".")[0]; if (complianceRequirements[currentRequirement]) { complianceRequirements[currentRequirement].push(item); } else { selectedRequirements[currentRequirement] = true; complianceRequirements[currentRequirement] = []; complianceRequirements[currentRequirement].push(item); } }); //forEach } this._isMount && this.setState({ complianceObject: complianceRequirements, selectedRequirements, descriptions }, () => this.getRequirementsCount()); } catch (err) { // TODO ADD showToast /*this.showToast( 'danger', 'Error', `Compliance (${this.props.section}) data could not be fetched: ${err}`, 3000 );*/ } } onChangeSelectedRequirements = (selectedRequirements) => { this.setState({ selectedRequirements }); } onQuerySubmit = (payload: { dateRange: TimeRange, query: Query | undefined }) => { const { dateRange, query } = payload; const { filters } = this.state.filterParams; const filterParams:IFilterParams = { time: dateRange, filters, query}; this.setState({ filterParams, loadingAlerts: true }); } onFiltersUpdated = (filters: []) => { const { time, query} = this.state.filterParams; const filterParams = {time, query, filters}; this.setState({ filterParams, loadingAlerts: true }); } async componentDidUpdate(prevProps) { const { filterParams, loadingAlerts } = this.state; if (JSON.stringify(prevProps.filterParams) !== JSON.stringify(filterParams) && loadingAlerts) { this.getRequirementsCount(); } } async getRequirementsCount() { try { const { filterParams } = this.state; if (!this.indexPattern) { return; } let fieldAgg = ""; if (this.props.section === "pci") fieldAgg = "rule.pci_dss"; if (this.props.section === "gdpr") fieldAgg = "rule.gdpr"; if (this.props.section === "hipaa") fieldAgg = "rule.hipaa"; if (this.props.section === "nist") fieldAgg = "rule.nist_800_53"; if (this.props.section === "tsc") fieldAgg = "rule.tsc"; const aggs = { tactics: { terms: { field: fieldAgg, size: 100, } } } // TODO: use `status` and `statusText` to show errors // @ts-ignore const { data, status, statusText, } = await getElasticAlerts(this.indexPattern, filterParams, aggs); const { buckets } = data.aggregations.tactics; /*if(firstTime){ this.initTactics(buckets); // top tactics are checked on component mount }*/ this._isMount && this.setState({ requirementsCount: buckets, loadingAlerts: false, firstTime: false }); } catch (err) { /* this.showToast( 'danger', 'Error', `Mitre alerts could not be fetched: ${err}`, 3000 );*/ this.setState({ loadingAlerts: false }) } } onChangeFlyout = (flyoutOn) => { this.setState({ flyoutOn }); } closeFlyout() { this.setState({ flyoutOn: false }); } showFlyout(requirement) { this.setState({ selectedRequirement: requirement, flyoutOn: true }) } render() { const { complianceObject, loadingAlerts } = this.state; return (<div> <EuiFlexGroup> <EuiFlexItem> <div className='wz-discover hide-filter-control' > <KbnSearchBar onQuerySubmit={this.onQuerySubmit} onFiltersUpdated={this.onFiltersUpdated} isLoading={loadingAlerts} /> </div> </EuiFlexItem> </EuiFlexGroup> <EuiFlexGroup style={{ margin: '0 8px' }}> <EuiFlexItem style={{ width: "calc(100% - 24px)" }}> <EuiPanel paddingSize="none"> {!!Object.keys(complianceObject).length && this.state.filterParams.time.from !== "init" && <EuiFlexGroup> <EuiFlexItem grow={false} style={{ width: "15%", minWidth: 145, maxHeight: "calc(100vh - 320px)", overflowX: "hidden" }}> <ComplianceRequirements indexPattern={this.indexPattern} section={this.props.section} onChangeSelectedRequirements={this.onChangeSelectedRequirements} {...this.state} /> </EuiFlexItem> <EuiFlexItem style={{ width: "15%" }}> <ComplianceSubrequirements indexPattern={this.indexPattern} filters={this.state.filterParams} section={this.props.section} onSelectedTabChanged={(id) => this.props.onSelectedTabChanged(id)} {...this.state} /> </EuiFlexItem> </EuiFlexGroup> } </EuiPanel> </EuiFlexItem> </EuiFlexGroup> </div> ) } }
wazuh/wazuh-kibana-app
public/components/overview/compliance-table/compliance-table.tsx
TypeScript
gpl-2.0
10,864
<?php ////////////////////////////////////////////////////////////// /// phpThumb() by James Heinrich <info@silisoftware.com> // // available at http://phpthumb.sourceforge.net /// ////////////////////////////////////////////////////////////// /// // // phpThumb.demo.check.php // // James Heinrich <info@silisoftware.com> // // // // Configuration analyzer for phpThumb settings and server // // settings that may affect phpThumb performance // // Live demo is at http://phpthumb.sourceforge.net/demo/ // // // ////////////////////////////////////////////////////////////// // die('For security reasons, this demo is disabled by default. Please comment out line '.__LINE__.' in '.basename(__FILE__)); $ServerInfo['gd_string'] = 'unknown'; $ServerInfo['gd_numeric'] = 0; //ob_start(); if (!include_once('../phpthumb.functions.php')) { ob_end_flush(); die('failed to include_once("../phpthumb.functions.php")'); } if (!include_once('../phpthumb.class.php')) { //ob_end_flush(); die('failed to include_once("../phpthumb.class.php")'); } //ob_end_clean(); $phpThumb = new phpThumb(); if (include_once('../phpThumb.config.php')) { foreach ($PHPTHUMB_CONFIG as $key => $value) { $keyname = 'config_'.$key; $phpThumb->setParameter($keyname, $value); } } $ServerInfo['gd_string'] = phpthumb_functions::gd_version(true); $ServerInfo['gd_numeric'] = phpthumb_functions::gd_version(false); $ServerInfo['im_version'] = $phpThumb->ImageMagickVersion(); $gd_info = gd_info(); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>phpThumb configuration analyzer</title> <link rel="stylesheet" type="text/css" href="/style.css" title="style sheet"> </head> <body style="background-color: #CCCCCC;"> This demo analyzes your settings (phpThumb.config.php and server/PHP) for <a href="http://phpthumb.sourceforge.net"><b>phpThumb()</b></a>.<br> <br> <table border="1"> <tr><th colspan="8">&lt;-- bad . . . . . good --&gt;</th></tr> <tr> <td style="background-color: red;" >&nbsp;&nbsp;&nbsp;&nbsp;</td> <td style="background-color: orange;" >&nbsp;&nbsp;&nbsp;&nbsp;</td> <td style="background-color: yellow;" >&nbsp;&nbsp;&nbsp;&nbsp;</td> <td style="background-color: olive;" >&nbsp;&nbsp;&nbsp;&nbsp;</td> <td style="background-color: darkgreen;" >&nbsp;&nbsp;&nbsp;&nbsp;</td> <td style="background-color: green;" >&nbsp;&nbsp;&nbsp;&nbsp;</td> <td style="background-color: lightgreen;">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td style="background-color: lime;" >&nbsp;&nbsp;&nbsp;&nbsp;</td> </tr> </table> <table border="1" cellspacing="0" cellpadding="2"> <tr style="background-color: #EEEEEE;"><th>Setting</th><th colspan="2">Value</th><th>Comments</th></tr> <?php $versions['raw'] = array( 'latest' => phpthumb_functions::SafeURLread('http://phpthumb.sourceforge.net/?latestversion=1', $dummy), 'this' => $phpThumb->phpthumb_version, ); foreach ($versions['raw'] as $key => $value) { preg_match('#^([0-9\\.]+)\\-?(([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2}))?#i', $value, $matches); @list($huge, $major, $minor) = @explode('.', @$matches[1]); @list($year, $month, $day, $hour, $min) = @$matches[3]; $versions['base'][$key] = $matches[1]; $versions['huge'][$key] = $huge; $versions['major'][$key] = $major; $versions['minor'][$key] = $minor; $versions['stamp'][$key] = $matches[2]; $versions['year'][$key] = $year; $versions['month'][$key] = $month; $versions['day'][$key] = $day; $versions['hour'][$key] = $hour; $versions['min'][$key] = $min; $versions['date'][$key] = @mktime($hour, $min, 0, $month, $day, $year); } $downloadlatest = 'Download the latest version from <a href="http://phpthumb.sourceforge.net">http://phpthumb.sourceforge.net</a>'; echo '<tr><th nowrap>Latest phpThumb version:</th><th colspan="2">'.$versions['raw']['latest'].'</th><td>'.$downloadlatest.'</td></tr>'; echo '<tr><th nowrap>This phpThumb version:</th><th colspan="2" style="background-color: '; if (!$versions['base']['latest']) { // failed to get latest version number echo 'white'; $message = 'Latest version unknown.<br>'.$downloadlatest; } elseif (phpthumb_functions::version_compare_replacement($versions['base']['this'], $versions['base']['latest'], '>')) { // new than latest, must be beta version echo 'lightblue'; $message = 'This must be a pre-release beta version. Please report bugs to <a href="mailto:info@silisoftware.com">info@silisoftware.com</a>'; } elseif (($versions['base']['latest'] == $versions['base']['this']) && ($versions['stamp']['this'] > $versions['stamp']['latest'])) { // new than latest, must be beta version echo 'lightblue'; $message = 'You must be using a pre-release beta version. Please report bugs to <a href="mailto:info@silisoftware.com">info@silisoftware.com</a>'; } elseif ($versions['base']['latest'] == $versions['base']['this']) { // latest version echo 'lime'; $message = 'You are using the latest released version.'; } elseif ($versions['huge']['latest'].$versions['major']['latest'] == $versions['huge']['this'].$versions['major']['this']) { echo 'olive'; $message = 'One (or more) minor version(s) have been released since this version.<br>'.$downloadlatest; } elseif (floatval($versions['huge']['latest'].str_pad($versions['major']['latest'], 2, '0', STR_PAD_LEFT)) < floatval($versions['huge']['this'].str_pad($t_major, 2, '0', STR_PAD_LEFT))) { echo 'yellow'; $message = 'One (or more) major version(s) have been released since this version, you really should upgrade.<br>'.$downloadlatest; } else { echo 'orange'; $message = 'Fundamental changes have been made since this version.<br>'.$downloadlatest; } echo ';">'.$phpThumb->phpthumb_version; echo '</th><td>'.$message.'.<br></td></tr>'; echo '<tr><th>phpThumb.config.php:</th><th colspan="2" style="background-color: '; if (file_exists('../phpThumb.config.php') && !file_exists('../phpThumb.config.php.default')) { echo 'lime;">"phpThumb.config.php" exists and "phpThumb.config.php.default" does not'; } elseif (file_exists('../phpThumb.config.php') && file_exists('../phpThumb.config.php.default')) { echo 'yellow;">"phpThumb.config.php" and "phpThumb.config.php.default" both exist'; } elseif (!file_exists('../phpThumb.config.php') && file_exists('../phpThumb.config.php.default')) { echo 'yellow;">rename "phpThumb.config.php.default" to "phpThumb.config.php"'; } else { echo 'yellow;">"phpThumb.config.php" not found (nor "phpThumb.config.php")'; } echo '</th><td>"phpThumb.config.php.default" that comes in the distribution must be renamed to "phpThumb.config.php" before phpThumb.php can be used. Avoid having both files present to minimize confusion.</td></tr>'; echo '<tr><th>cache directory:</th><th colspan="2">'; $orig_config_cache_directory = $phpThumb->config_cache_directory; $phpThumb->setCacheDirectory(); echo '<div style="background-color: '.( is_dir($phpThumb->config_cache_directory) ? 'lime;">exists' : 'red;">does NOT exist').'</div>'; echo '<div style="background-color: '.(is_readable($phpThumb->config_cache_directory) ? 'lime;">readable' : 'red;">NOT readable' ).'</div>'; echo '<div style="background-color: '.(is_writable($phpThumb->config_cache_directory) ? 'lime;">writable' : 'red;">NOT writable' ).'</div>'; echo '</th><td>Original: "'.htmlentities($orig_config_cache_directory).'"<br>Resolved: "'.htmlentities($phpThumb->config_cache_directory).'"<br>Must exist and be both readable and writable by PHP.</td></tr>'; echo '<tr><th>cache write test:</th><th colspan="2">'; $phpThumb->rawImageData = 'phpThumb.demo.check.php_cachetest'; $phpThumb->SetCacheFilename(); echo '<div>'.htmlentities($phpThumb->cache_filename ? implode(' / ', preg_split('#[/\\\\]#', $phpThumb->cache_filename)) : 'NO CACHE FILENAME RESOLVED').'</div>'; echo '<div>directory '.(is_dir(dirname($phpThumb->cache_filename)) ? 'exists' : 'does NOT exist').' (before EnsureDirectoryExists())</div>'; phpthumb_functions::EnsureDirectoryExists(dirname($phpThumb->cache_filename)); echo '<div style="background-color: '.(is_dir(dirname($phpThumb->cache_filename)) ? 'lime;">directory exists' : 'red;">directory does NOT exist').' (after EnsureDirectoryExists())</div>'; if ($fp = @fopen($phpThumb->cache_filename, 'wb')) { fwrite($fp, 'this is a test from '.__FILE__); fclose($fp); echo '<div style="background-color: lime;">write test succeeded</div>'; $old_perms = substr(sprintf('%o', fileperms($phpThumb->cache_filename)), -4); @chmod($phpThumb->cache_filename, 0644); clearstatcache(); $new_perms = substr(sprintf('%o', fileperms($phpThumb->cache_filename)), -4); echo '<div style="background-color: '.(($new_perms == '0644') ? 'lime' : (($new_perms > '0644') ? 'orange' : 'red')).';">chmod($phpThumb->cache_filename, 0644) from "'.htmlentities($old_perms).'" resulted in permissions "'.htmlentities($new_perms).'"</div>'; if (@unlink($phpThumb->cache_filename)) { echo '<div style="background-color: lime;">delete test succeeded</div>'; } else { echo '<div style="background-color: red;">delete test FAILED</div>'; } $phpThumb->CleanUpCacheDirectory(); } else { echo '<div style="background-color: red;">write test FAILED</div>'; } //echo '</th><td>Original: "'.htmlentities($orig_config_cache_directory).'"<br>Resolved: "'.htmlentities($phpThumb->config_cache_directory).'"<br>Must exist and be both readable and writable by PHP.</td></tr>'; echo '</th><td>Created and deletes a sample cache file to see if you actually have create/delete permission.<br>If <i>Safe Mode</i> is enabled this is often broken.</td></tr>'; echo '<tr><th>temp directory:</th><th colspan="2">'; $orig_config_temp_directory = $phpThumb->config_temp_directory; echo $phpThumb->phpThumb_tempnam(); echo '<div style="background-color: '.( is_dir($phpThumb->config_temp_directory) ? 'lime;">exists' : 'red;">does NOT exist').'</div>'; echo '<div style="background-color: '.(is_readable($phpThumb->config_temp_directory) ? 'lime;">readable' : 'red;">NOT readable' ).'</div>'; echo '<div style="background-color: '.(is_writable($phpThumb->config_temp_directory) ? 'lime;">writable' : 'red;">NOT writable' ).'</div>'; echo '</th><td>Original: "'.htmlentities($orig_config_temp_directory).'"<br>Resolved: "'.htmlentities($phpThumb->config_temp_directory).'"<br>Must exist and be both readable and writable by PHP.</td></tr>'; echo '<tr><th>PHP version:</th><th colspan="2" style="background-color: '; if (phpthumb_functions::version_compare_replacement(phpversion(), '5.0.0', '>=')) { echo 'lime'; } elseif (phpthumb_functions::version_compare_replacement(phpversion(), '4.4.2', '=')) { echo 'darkgreen'; } elseif (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.3', '>=')) { echo 'lightgreen'; } elseif (phpthumb_functions::version_compare_replacement(phpversion(), '4.2.0', '>=')) { echo 'green'; } elseif (phpthumb_functions::version_compare_replacement(phpversion(), '4.1.0', '>=')) { echo 'yellow'; } elseif (phpthumb_functions::version_compare_replacement(phpversion(), '4.0.6', '>=')) { echo 'orange'; } else { echo 'red'; } echo ';">'.phpversion(); echo '</th><td>PHP5 is ideal (support for numerous built-in filters which are much faster than my code).<br>PHP v4.4.2 contains a bug in fopen over HTTP (phpThumb has a workaround)<br>PHP v4.3.2+ supports ImageSaveAlpha which is required for proper PNG/ICO output.<br>ImageRotate requires PHP v4.3.0+ (but buggy before v4.3.3).<br>EXIF thumbnail extraction requires PHP v4.2.0+.<br>Most things will work back to PHP v4.1.0, and mostly (perhaps buggy) back to v4.0.6, but no guarantees for any version older than that.</td></tr>'; echo '<tr><th>GD version:</th><th colspan="2" style="background-color: '; if ($ServerInfo['gd_numeric'] >= 2) { if (!empty($ServerInfo['gd_string']) && preg_match('#bundled#i', $ServerInfo['gd_string'])) { echo 'lime'; } else { echo 'yellow'; } } elseif (!empty($ServerInfo['im_version'])) { echo 'orange'; } else { echo 'red'; } echo ';">'.(!empty($ServerInfo['gd_string']) ? $ServerInfo['gd_string'] : 'n/a'); echo '</th><td>GD2-bundled version is ideal.<br>GD2 (non-bundled) is second choice, but there are a number of bugs in the non-bundled version. ImageRotate is only available in the bundled version of GD2.<br>GD1 will also (mostly) work, at much-reduced image quality and several features disabled. phpThumb can perform most operations with ImageMagick only, even if GD is not available.</td></tr>'; $IMreleaseDate = 0; if (preg_match('# ([0-9]{2})/([0-9]{2})/([0-9]{2}) #', $ServerInfo['im_version'], $matches)) { list($dummy, $m, $d, $y) = $matches; if ($y < 70) { $y += 2000; } elseif ($y < 100) { $y += 1900; } $IMreleaseDate = mktime(12, 0, 0, $m, $d, $y); } elseif (preg_match('# ([0-9]{4})\\-([0-9]{2})\\-([0-9]{2}) #', $ServerInfo['im_version'], $matches)) { list($dummy, $y, $m, $d) = $matches; $IMreleaseDate = mktime(12, 0, 0, $m, $d, $y); } $IMversionAge = time() - $IMreleaseDate; echo '<tr><th>ImageMagick version:</th><th colspan="2" style="background-color: '; if ($ServerInfo['im_version']) { if ($IMversionAge < (86400 * 365 * 1)) { echo 'lime'; } elseif ($IMversionAge < (86400 * 365 * 2)) { echo 'lightgreen'; } elseif ($IMversionAge < (86400 * 365 * 3)) { echo 'green'; } elseif ($IMversionAge < (86400 * 365 * 4)) { echo 'darkgreen'; } else { echo 'olive'; } } elseif (!empty($ServerInfo['gd_string'])) { echo 'orange'; } else { echo 'red'; } echo ';">'; echo '<div style="color: navy; font-family: monospace;">'.htmlentities($phpThumb->config_imagemagick_path); echo ' <span style="cursor: help;" title="file_exists" >['.intval( @file_exists($phpThumb->config_imagemagick_path)).']</span> '; echo ' <span style="cursor: help;" title="file_exists_ignoreopenbasedir">['.intval($phpThumb->file_exists_ignoreopenbasedir($phpThumb->config_imagemagick_path)).']</span> '; echo ' <span style="cursor: help;" title="is_file" >['.intval( @is_file($phpThumb->config_imagemagick_path)).']</span> '; echo ' <span style="cursor: help;" title="is_readable" >['.intval( @is_readable($phpThumb->config_imagemagick_path)).']</span> '; echo ' <span style="cursor: help;" title="is_executable" >['.intval( @is_executable($phpThumb->config_imagemagick_path)).']</span> '; echo '</div>'; echo '<div style="color: blue; font-family: monospace;">'.htmlentities($phpThumb->ImageMagickCommandlineBase()).'</div>'; echo ($ServerInfo['im_version'] ? $ServerInfo['im_version'] : 'n/a'); echo ($IMreleaseDate ? '<br><br>This version of ImageMagick is '.NiceTimeFormatting($IMversionAge).' old<br>(see <a href="http://www.imagemagick.org/">www.imagemagick.org</a> for new versions)' : ''); echo '</th><td>ImageMagick is faster than GD, can process larger images without PHP memory_limit issues, can resize animated GIFs. phpThumb can perform most operations with ImageMagick only, even if GD is not available.</td></tr>'; echo '<tr><th>ImageMagick features:</th>'; if ($ServerInfo['im_version']) { $GDfeatures['red'] = array('help', 'thumbnail', 'resize', 'crop', 'repage', 'coalesce', 'gravity', 'background', 'interlace', 'flatten', 'border', 'bordercolor', 'dither', 'quality'); $GDfeatures['orange'] = array('version', 'blur', 'colorize', 'colors', 'colorspace', 'contrast', 'contrast-stretch', 'edge', 'emboss', 'fill', 'flip', 'flop', 'gamma', array('gaussian','gaussian-blur'), 'level', 'modulate', 'monochrome', 'negate', 'normalize', 'rotate', 'sepia-tone', 'threshold', 'unsharp'); echo '<th colspan="2">|'; foreach ($GDfeatures as $missingcolor => $features) { foreach ($features as $dummy => $feature) { $foundOneThatWorks = false; if (is_array($feature)) { // sometimes feature names change, e.g. "gaussian" -> "gaussian-blur". They won't both exist in the same version of ImageMagick, but as long as one of them does then the feature will work foreach ($feature as $alternate_feature_name) { if ($phpThumb->ImageMagickSwitchAvailable($alternate_feature_name)) { $foundOneThatWorks = true; $feature = $alternate_feature_name; break; } } } else { $foundOneThatWorks = $phpThumb->ImageMagickSwitchAvailable($feature); } echo '| <span style="background-color: '.($foundOneThatWorks ? 'lime' : $missingcolor).';">'.htmlentities($feature).'</span> |'; } } echo '|</th>'; } else { echo '<th colspan="2" style="background-color: orange;">ImageMagick not found</th>'; } echo '<td>All of these parameters may be called by phpThumb, depending on parameters used. Green means the feature is available; red means a critical feature is missing; orange means an optional filter/feature is missing.</td></tr>'; echo '<tr><th>ImageMagick formats:</th>'; if ($ServerInfo['im_version']) { echo '<td colspan="2"><div style="width: 100%; height: 200px; overflow: auto; font-family: monospace; white-space: pre; background-color: #FFFFFF;">'.htmlentities($phpThumb->ImageMagickFormatsList()).'</div></td>'; } else { echo '<th colspan="2" style="background-color: orange;">ImageMagick not found</th>'; } echo '<td>ImageMagick can only read/write formats as listed here. You may need to recompile ImageMagick if you need to use a format not listed</td></tr>'; echo '<tr><th>GD features:</th><th colspan="2">'; $GDfeatures['red'] = array('JPEG Support', 'JPG Support', 'PNG Support'); // older versions would report "JPG Support", newer versions report "JPEG Support" $GDfeatures['orange'] = array('GIF Read Support', 'GIF Create Support', 'FreeType Support'); foreach ($GDfeatures as $missingcolor => $features) { foreach ($features as $dummy => $feature) { if (isset($gd_info[$feature])) { echo '<div style="background-color: '.($gd_info[$feature] ? 'lime' : $missingcolor).';">'.htmlentities($feature).'</div>'; } } } echo '</th><td>PNG support is required for watermarks, overlays, calls to ImageMagick and other internal operations.<br>JPG support is obviously quite useful, but ImageMagick can substitute<br>GIF read support can be bypassed with ImageMagick and/or internal GIF routines.<br>GIF create support can be bypassed with ImageMagick (if no filters are applied)<br>FreeType support is needed for TTF overlays.</td></tr>'; echo '<tr><th>GD extension "EXIF"</th><th colspan="2" style="background-color: '; if (extension_loaded('exif')) { echo 'lime'; } elseif (!empty($ServerInfo['gd_string'])) { echo 'orange'; } echo ';">'.(extension_loaded('exif') ? 'TRUE' : 'FALSE'); echo '</th><td>EXIF extension required for auto-rotate images. Also required to extract EXIF thumbnail to use as source if source image is too large for PHP memory_limit and ImageMagick is unavailable.</td></tr>'; echo '<tr><th>php_sapi_name()</th><th colspan="2" style="background-color: '; $php_sapi_name = strtolower(function_exists('php_sapi_name') ? php_sapi_name() : ''); if (!$php_sapi_name || (preg_match('#~#', dirname($_SERVER['PHP_SELF'])) && ($php_sapi_name != 'apache'))) { echo 'red'; } elseif ($php_sapi_name == 'cgi-fcgi') { echo 'orange'; } elseif ($php_sapi_name == 'cgi') { echo 'yellow'; } elseif ($php_sapi_name == 'apache') { echo 'lime'; } else { echo 'green'; } echo ';">'.htmlentities($php_sapi_name).'</th>'; echo '<td>SAPI mode preferred to CGI mode. FCGI mode has unconfirmed strange behavior (notably more than one space in "wmt" filter text causes errors). If not working in "apache" (SAPI) mode, <i>apache_lookup_uri()</i> will not work.</td></tr>'; echo '<tr><th>Server Software</th><th colspan="2" style="background-color: '; $server_software = getenv('SERVER_SOFTWARE'); if (!$server_software) { echo 'red'; } elseif (preg_match('#^Apache/([0-9\\.]+)#i', $server_software, $matches)) { if (phpthumb_functions::version_compare_replacement($matches[1], '2.0.0', '>=')) { echo 'lightgreen'; } else { echo 'lime'; } } else { echo 'darkgreen'; } echo ';">'.$server_software.'</th>'; echo '<td>Apache v1.x has the fewest compatability problems. IIS has numerous annoyances. Apache v2.x is broken when lookup up <i>/~user/filename.jpg</i> style relative filenames using <i>apache_lookup_uri()</i>.</td></tr>'; echo '<tr><th>curl_version:</th><th colspan="2" style="background-color: '; $curl_version = (function_exists('curl_version') ? curl_version() : ''); if (is_array($curl_version)) { $curl_version = @$curl_version['version']; } if ($curl_version) { echo 'lime'; } else { echo 'yellow'; } echo ';">'.$curl_version.'</th>'; echo '<td>Best if available. HTTP source images will be unavailable if CURL unavailable and <i>allow_url_fopen</i> is also disabled.</td></tr>'; echo '<tr style="background-color: #EEEEEE;"><th colspan="4">&nbsp;</th></tr>'; echo '<tr style="background-color: #EEEEEE;"><th>function_exists:</th><th colspan="2">Value</th><th>Comments</th></tr>'; $FunctionsExist = array( 'ImageRotate' => array('orange', 'required for "ra" and "ar" filters.'), 'exif_read_data' => array('yellow', 'required for "ar" filter.'), 'exif_thumbnail' => array('yellow', 'required to extract EXIF thumbnails.'), 'memory_get_usage' => array('lightgreen', 'mostly used for troubleshooting.'), 'version_compare' => array('darkgreen', 'available in PHP v4.1.0+, internal workaround available'), 'file_get_contents' => array('darkgreen', 'available in PHP v4.3.0+, internal workaround available'), 'file_put_contents' => array('darkgreen', 'available in PHP v5.0.0+, internal workaround available'), 'is_executable' => array('yellow', 'available in PHP3, except only PHP5 for Windows. poor internal workaround available'), 'gd_info' => array('olive', 'available in PHP v4.3.0+ (with bundled GD2), internal workaround available'), 'ImageTypes' => array('red', 'required for GD image output.'), 'ImageCreateFromJPEG' => array('orange', 'required for JPEG source images using GD.'), 'ImageCreateFromGIF' => array('yellow', 'useful for GIF source images using GD.'), 'ImageCreateFromPNG' => array('orange', 'required for PNG source images using GD and other source image formats using ImageMagick.'), 'ImageCreateFromWBMP' => array('yellow', 'required for WBMP source images using GD.'), 'ImageCreateFromString' => array('orange', 'required for HTTP and non-file image sources.'), 'ImageCreateTrueColor' => array('orange', 'required for all non-ImageMagick filters.'), 'ImageIsTrueColor' => array('olive', 'available in PHP v4.3.2+ with GD v2.0.1+'), 'ImageFilter' => array('yellow', 'PHP5 only. Required for some filters (but most can use ImageMagick instead)'), ); foreach ($FunctionsExist as $function => $details) { list($color, $description) = $details; echo '<tr><th>'.$function.'</th><th colspan="2" style="background-color: '; if (function_exists(strtolower($function))) { echo 'lime;">TRUE'; } else { echo $color.';">FALSE'; } echo '</th><td>'.htmlentities($description).'</td></tr>'; } echo '<tr style="background-color: #EEEEEE;"><th colspan="4">&nbsp;</th></tr>'; echo '<tr style="background-color: #EEEEEE;"><th>Setting</th><th>Master Value</th><th>Local Value</th><th>Comments</th></tr>'; $SettingFeatures = array( 'magic_quotes_runtime' => array('red', 'lime', 'This setting is evil. Turn it off.'), 'magic_quotes_gpc' => array('yellow', 'lime', 'This setting is bad. Turn it off, if possible. phpThumb will attempt to work around it if it is enabled.'), 'safe_mode' => array('orange', 'lime', 'Best if off. Calls to ImageMagick will be disabled if safe_mode is set to prevent writing temp files (limiting max image resolution, no animated GIF resize). Raw image data sources (e.g. from MySQL database) may not work. Temp files may be disabled. Features will be limited. If disabled in Master but enabled in Local, edit httpd.conf and set (php_admin_value safe_mode "Off") between <VirtualHost> tags'), 'allow_url_fopen' => array('lime', 'yellow', 'Best if on. HTTP source images will be unavailable if disabled and CURL is unavailable.'), ); foreach ($SettingFeatures as $feature => $FeaturesDetails) { list($color_true, $color_false, $reason) = $FeaturesDetails; echo '<tr><th>'.$feature.':</th>'; echo '<th style="background-color: '.(@get_cfg_var($feature) ? $color_true : $color_false).';">'.$phpThumb->phpThumbDebugVarDump((bool) @get_cfg_var($feature)).'</th>'; echo '<th style="background-color: '.(preg_match('#(1|ON)#i', @ini_get($feature)) ? $color_true : $color_false).';">'.$phpThumb->phpThumbDebugVarDump((bool) preg_match('#(1|ON)#i', ini_get($feature))).'</th>'; echo '<td>'.htmlentities($reason).'</td></tr>'; } $MissingFunctionSeverity = array( 'shell_exec' => 'red', 'system' => 'red', 'passthru' => 'red', 'exec' => 'red', 'curl_exec' => 'orange', ); $DisabledFunctions[0] = explode(',', @get_cfg_var('disable_functions')); $DisabledFunctions[1] = explode(',', @ini_get('disable_functions')); echo '<tr><th>disable_functions:</th>'; for ($i = 0; $i <= 1; $i++) { foreach ($DisabledFunctions[$i] as $key => $value) { if (!empty($MissingFunctionSeverity[$value])) { $DisabledFunctions[$i][$key] = '<span style="background-color: '.$MissingFunctionSeverity[$value].';">'.$value.'</span>'; } } $disabled_functions = implode(', ', $DisabledFunctions[$i]); echo '<th style="background-color: '.($disabled_functions ? 'yellow' : 'lime').';">'; echo '</th>'; } echo '<td>Best if nothing disabled. Calls to ImageMagick will be prevented if exec+system+shell_exec+passthru are disabled.</td></tr>'; echo '<tr><th>memory_limit:</th><th style="background-color: '; $memory_limit = @get_cfg_var('memory_limit'); if (!$memory_limit) { echo 'lime'; } elseif ($memory_limit >= 32) { echo 'lime'; } elseif ($memory_limit >= 24) { echo 'lightgreen'; } elseif ($memory_limit >= 16) { echo 'green'; } elseif ($memory_limit >= 12) { echo 'darkgreen'; } elseif ($memory_limit >= 8) { echo 'olive'; } elseif ($memory_limit >= 4) { echo 'yellow'; } elseif ($memory_limit >= 2) { echo 'orange'; } else { echo 'red'; } echo ';">'.($memory_limit ? $memory_limit : '<i>unlimited</i>').'</th><th style="background-color: '; $memory_limit = @ini_get('memory_limit'); if (!$memory_limit) { echo 'lime'; } elseif ($memory_limit >= 32) { echo 'lime'; } elseif ($memory_limit >= 24) { echo 'lightgreen'; } elseif ($memory_limit >= 16) { echo 'green'; } elseif ($memory_limit >= 12) { echo 'darkgreen'; } elseif ($memory_limit >= 8) { echo 'olive'; } elseif ($memory_limit >= 4) { echo 'yellow'; } elseif ($memory_limit >= 2) { echo 'orange'; } else { echo 'red'; } echo ';">'.($memory_limit ? $memory_limit : '<i>unlimited</i>').'</th>'; echo '<td>The higher the better. Divide by 5 to get maximum megapixels of source image that can be thumbnailed (without ImageMagick).'.($memory_limit ? ' Your setting ('.$memory_limit.') allows images up to approximately '.number_format($memory_limit / 5, 1).' megapixels' : '').'</td></tr>'; echo '</table>'; function NiceTimeFormatting($seconds, $precision=1, $returnparts=false) { $sign = (($seconds < 0) ? -1 : 1); $seconds = abs($seconds); do { if ($seconds < 100) { $value = number_format($seconds, 0); $unit = 'second'.(($seconds > 1) ? 's' : ''); break; } $minutes = $seconds / 60; if ($minutes < 60) { $value = number_format($minutes, $precision); $unit = 'minutes'; break; } $hours = $seconds / 3600; if ($hours < 24) { $value = number_format($hours, $precision); $unit = 'hours'; break; } $days = $seconds / 86400; if ($days < 60) { $value = number_format($days, $precision); $unit = 'days'; break; } $months = $seconds / (30 * 86400); if ($months < 12) { $value = number_format($months, $precision); $unit = 'months'; break; } $years = $seconds / (365 * 86400); if (true) { $value = number_format($years, $precision); $unit = 'years'; break; } } while (false); $value *= $sign; if ($returnparts) { return array($value, $unit); } return $value.' '.$unit; } ?> </body> </html>
gdelamardiere/joomla
components/com_alphauserpoints/assets/phpThumb/demo/phpThumb.demo.check.php
PHP
gpl-2.0
28,660
package org.kidneyomics.gtf; import static org.junit.Assert.*; import java.util.LinkedList; import java.util.List; import org.biojava.nbio.genome.parsers.gff.Feature; import org.biojava.nbio.genome.parsers.gff.Location; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FeatureMergerTest { Logger logger = LoggerFactory.getLogger(FeatureMergerTest.class); @Test public void test() { Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(50, 150, '+'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(250, 300, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f1); features.add(f2); features.add(f3); List<Feature> merged = FeatureMerger.mergeOverlappingFeatures(features); assertTrue(merged.size() == 2); Feature m1 = merged.get(0); assertEquals(50, m1.location().bioStart()); assertEquals(200, m1.location().bioEnd()); Feature m2 = merged.get(1); assertEquals(250, m2.location().bioStart()); assertEquals(300, m2.location().bioEnd()); } @Test public void test2() { Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(50, 150, '-'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(250, 300, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f1); features.add(f2); features.add(f3); List<Feature> merged = FeatureMerger.mergeOverlappingFeaturesIgnoringStrand(features); assertTrue(merged.size() == 2); Feature m1 = merged.get(0); assertEquals(50, m1.location().bioStart()); assertEquals(200, m1.location().bioEnd()); Feature m2 = merged.get(1); assertEquals(250, m2.location().bioStart()); assertEquals(300, m2.location().bioEnd()); } @Test public void test3() { Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(50, 150, '-'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(250, 300, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f1); features.add(f2); features.add(f3); IllegalArgumentException exception = null; try { FeatureMerger.mergeOverlappingFeatures(features); } catch(IllegalArgumentException e) { exception = e; } assertNotNull(exception); } @Test public void test4() { Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(1, 400, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(50, 150, '-'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(250, 300, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f1); features.add(f2); features.add(f3); List<Feature> merged = FeatureMerger.mergeOverlappingFeaturesIgnoringStrand(features); assertTrue(merged.size() == 1); Feature m1 = merged.get(0); assertEquals(1, m1.location().bioStart()); assertEquals(400, m1.location().bioEnd()); } @Test public void testRemoveOverlappingFeatures() { Feature f0 = new Feature("chr1", "a", "exon", Location.fromBio(50, 99, '+'), 0.0, 0, ""); Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(150, 250, '+'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(260, 300, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f0); features.add(f1); features.add(f2); features.add(f3); List<Feature> removed = FeatureMerger.removeOverlappingFeaturesIgnoreStrand(features); logger.info("removed"); for(Feature f : removed) { logger.info(GTFFeatureRenderer.render(f)); } logger.info("kept"); for(Feature f : features) { logger.info(GTFFeatureRenderer.render(f)); } assertEquals(2,removed.size()); assertEquals(2,features.size()); assertEquals(100,removed.get(0).location().bioStart()); assertEquals(200,removed.get(0).location().bioEnd()); assertEquals(150,removed.get(1).location().bioStart()); assertEquals(250,removed.get(1).location().bioEnd()); assertEquals(50,features.get(0).location().bioStart()); assertEquals(99,features.get(0).location().bioEnd()); assertEquals(260,features.get(1).location().bioStart()); assertEquals(300,features.get(1).location().bioEnd()); } @Test public void testRemoveOverlappingFeatures2() { Feature f0 = new Feature("chr1", "a", "exon", Location.fromBio(1, 261, '+'), 0.0, 0, ""); Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(150, 250, '+'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(260, 300, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f0); features.add(f1); features.add(f2); features.add(f3); List<Feature> removed = FeatureMerger.removeOverlappingFeaturesIgnoreStrand(features); assertEquals(4,removed.size()); assertEquals(0,features.size()); assertEquals(100,removed.get(0).location().bioStart()); assertEquals(200,removed.get(0).location().bioEnd()); assertEquals(150,removed.get(1).location().bioStart()); assertEquals(250,removed.get(1).location().bioEnd()); assertEquals(1,removed.get(2).location().bioStart()); assertEquals(261,removed.get(2).location().bioEnd()); assertEquals(260,removed.get(3).location().bioStart()); assertEquals(300,removed.get(3).location().bioEnd()); } @Test public void testRemoveOverlappingFeatures3() { Feature f0 = new Feature("chr1", "a", "exon", Location.fromBio(1, 50, '+'), 0.0, 0, ""); Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 148, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(150, 250, '+'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(260, 400, '+'), 0.0, 0, ""); Feature f4 = new Feature("chr1", "a", "exon", Location.fromBio(260, 300, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f0); features.add(f1); features.add(f2); features.add(f3); features.add(f4); List<Feature> removed = FeatureMerger.removeOverlappingFeaturesIgnoreStrand(features); assertEquals(2,removed.size()); assertEquals(3,features.size()); assertEquals(260,removed.get(0).location().bioStart()); assertEquals(400,removed.get(0).location().bioEnd()); assertEquals(260,removed.get(1).location().bioStart()); assertEquals(300,removed.get(1).location().bioEnd()); assertEquals(1,features.get(0).location().bioStart()); assertEquals(50,features.get(0).location().bioEnd()); assertEquals(100,features.get(1).location().bioStart()); assertEquals(148,features.get(1).location().bioEnd()); assertEquals(150,features.get(2).location().bioStart()); assertEquals(250,features.get(2).location().bioEnd()); } @Test public void testRemoveOverlappingFeatures4() { Feature f0 = new Feature("chr1", "a", "exon", Location.fromBio(1, 261, '+'), 0.0, 0, ""); Feature f1 = new Feature("chr1", "a", "exon", Location.fromBio(100, 200, '+'), 0.0, 0, ""); Feature f2 = new Feature("chr1", "a", "exon", Location.fromBio(150, 250, '+'), 0.0, 0, ""); Feature f3 = new Feature("chr1", "a", "exon", Location.fromBio(260, 300, '+'), 0.0, 0, ""); Feature f4 = new Feature("chr1", "a", "exon", Location.fromBio(300, 400, '+'), 0.0, 0, ""); Feature f5 = new Feature("chr1", "a", "exon", Location.fromBio(500, 600, '+'), 0.0, 0, ""); List<Feature> features = new LinkedList<Feature>(); features.add(f0); features.add(f1); features.add(f2); features.add(f3); features.add(f4); features.add(f5); List<Feature> removed = FeatureMerger.removeOverlappingFeaturesIgnoreStrand(features); assertEquals(5,removed.size()); assertEquals(1,features.size()); assertEquals(100,removed.get(0).location().bioStart()); assertEquals(200,removed.get(0).location().bioEnd()); assertEquals(150,removed.get(1).location().bioStart()); assertEquals(250,removed.get(1).location().bioEnd()); assertEquals(1,removed.get(2).location().bioStart()); assertEquals(261,removed.get(2).location().bioEnd()); assertEquals(260,removed.get(3).location().bioStart()); assertEquals(300,removed.get(3).location().bioEnd()); assertEquals(300,removed.get(4).location().bioStart()); assertEquals(400,removed.get(4).location().bioEnd()); assertEquals(500,features.get(0).location().bioStart()); assertEquals(600,features.get(0).location().bioEnd()); } }
christopher-gillies/rna-seq-pipeline
src/test/java/org/kidneyomics/gtf/FeatureMergerTest.java
Java
gpl-2.0
9,180
function eliminarItem(id, url){ console.log("Eliminar Fase"); console.log(id); console.log(url); $("#nombre-item").text(id); $("#modal-eliminar").modal('show'); $("#btn-eliminar").attr('href', url); } function revivirItem(id, url){ console.log("Eliminar Fase"); console.log(id); console.log(url); $("#nombre-revivir-item").text(id); $("#modal-revivir").modal('show'); $("#btn-revivir").attr('href', url); } function revertirItem(version, id_version){ console.log("Revertir item"); console.log(id_version); $("#version-item").text(version); $("#id_version").val(id_version); $("#modal-revertir").modal('show'); } function modificarItem(id, codigo, nombre, descripcion){ console.log("MODIFICAR TIPO ITEM"); console.log(id) console.log(codigo); console.log(nombre); console.log(descripcion); console.log("------------------"); $("#m-id").val(id); $("#m-codigo").val(codigo) $("#m-nombre").val(nombre); $("#m-descripcion").val(descripcion); $("#modal-modificar").modal('show'); } function setUrlNewItem(id_fase){ var id_tipo = $("#id-tipo").val(); var url = "/item/" + id_fase + "/nuevo/" + id_tipo + "/"; console.log(url); $("#next-new-item").attr("href", url); } function setListaRelacion(){ var tipo = $("#tipo").val(); console.log(tipo) if(tipo == 'padre-hijo'){ console.log("tipo padre-hijo"); $("#s-hijo").removeClass('hide'); $("#s-sucesor").addClass('hide'); }else{ console.log("tipo antecesor-sucesor"); $("#s-sucesor").removeClass('hide'); $("#s-hijo").addClass('hide'); } } function eliminarRelacionItem(url){ console.log("Eliminar Relacion Item"); console.log(url); $("#modal-eliminar").modal('show'); $("#btn-eliminar").attr('href', url); } function adjuntarArchivo(nombre){ console.log("Adjuntar archivo a"); console.log(nombre); $("#modal-modificar").modal('show'); } function showImpacto(url){ $.get( url, function( data ) { console.log( "Load was performed." + data); var datos = JSON.parse(data); if( datos ){ var item = datos; console.log(item); $("#nombre-impacto-item").empty().append(""+item.nombre); $("#impacto-item").empty().append(""+item.impacto); $("#modal-impacto").modal('show'); } }); }
SantiagoValdez/hpm
src/hpm/static/js/item.js
JavaScript
gpl-2.0
2,276
<?php get_header(); ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php $attachment_link = get_the_attachment_link($post->ID, true, array(450, 800)); // This also populates the iconsize for the next line ?> <?php $_post = &get_post($post->ID); $classname = ($_post->iconsize[0] <= 128 ? 'small' : '') . 'attachment'; // This lets us style narrow icons specially ?> <div class="item_class" id="post-<?php the_ID(); ?>"> <div class="item_class_title"> <div class="item_class_title_text"> <div class="date"> <div class="date_month"><?php the_time('M') ?></div> <div class="date_day"><?php the_time('d') ?></div> </div> <div class="titles"> <div class="top_title"><h1><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php _e('Permanent Link to',TEMPLATE_DOMAIN);?> <?php the_title(); ?>"><?php the_title(); ?></a></h1></div> <div class="end_title"><?php _e("Filed Under",TEMPLATE_DOMAIN); ?> (<?php the_category(', ') ?>) <?php _e("by",TEMPLATE_DOMAIN); ?> <?php the_author() ?> <?php _e('on',TEMPLATE_DOMAIN);?> <?php the_time('d-m-Y') ?></div> </div> </div> </div> <div class="item_class_text"> <?php the_content(__('Read the rest of this entry &raquo;',TEMPLATE_DOMAIN)); ?> </div> <div class="item_class_panel"> <div> <div class="links_left"> <span class="panel_comm"><a href="<?php the_permalink() ?>#respond"><?php _e("Post a Comment",TEMPLATE_DOMAIN); ?></a></span>&nbsp;&nbsp;&nbsp; <?php edit_post_link(__('Edit',TEMPLATE_DOMAIN), '', ''); ?> </div> <div class="links_right"> <?php comments_popup_link(__('(0) Comments',TEMPLATE_DOMAIN), __('(1) Comment',TEMPLATE_DOMAIN), __('(%) Comments',TEMPLATE_DOMAIN)); ?>&nbsp;&nbsp; <a href="<?php the_permalink() ?>" class="panel_read"><?php _e("Read More",TEMPLATE_DOMAIN); ?></a> </div> </div> </div> </div> <?php if ( comments_open() ) { ?> <?php comments_template('',true); ?><?php } ?> <?php endwhile; else: ?> <div id="content" class="narrowcolumn"><p><?php _e('Sorry, no attachments matched your criteria.',TEMPLATE_DOMAIN);?></p> <?php _e('Both comments and pings are currently closed.',TEMPLATE_DOMAIN);?></div> <?php endif; ?> <?php get_footer(); ?>
rjbaniel/upoor
wp-content/themes/oceanwide/attachment.php
PHP
gpl-2.0
2,504
#include "yacss/CSSBaseValue.hh" namespace yacss { std::ostream& operator<< (std::ostream& o, const CSSBaseValue& val) { if (val.type == ValueType::Length) o << val.get<LengthValue>(); else if (val.type == ValueType::Keyword) o << val.get<KeywordValue>(); else if (val.type == ValueType::ColorRGBA) o << val.get<ColorRGBAValue>(); else throw std::runtime_error("CSSBaseValue << : Unknown Type."); return o; } }; // ! ns yacss
cirocosta/yacss-parser
src/CSSBaseValue.cc
C++
gpl-2.0
456
<?php /****************************************************** Open .node *** * Description: * Status: Stable. * Author: Alexandre Dath <alexandre@dotnode.com> * $Id$ * * Copyright (C) 2005 Alexandre Dath <alexandre@dotnode.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. ******************** http://opensource.ikse.net/projects/dotnode ***/ define('INCLUDEPATH',BASEPATH.'/../inc'); define('ACTIONSPATH',BASEPATH.'/../actions'); define('RESPONSESPATH',BASEPATH.'/../responses'); define('CODEPIX_PATH',BASEPATH.'/../codepix'); ini_set('session.name','dotnodeSessID'); ini_set('session.save_path',BASEPATH.'/../sessions'); include(INCLUDESPATH.'/session_save_handler.inc.php'); session_set_save_handler ("_sess_open", "_sess_close", "_sess_read", "_sess_write", "_sess_destroy", "_sess_gc"); ?>
alex-ikse/dotnode
includes/config/global.inc.php
PHP
gpl-2.0
1,501
using System; using Server.Items; using Server.Targeting; namespace Server.Engines.Craft { public enum SmeltResult { Success, Invalid, NoSkill } public class Resmelt { public Resmelt() { } public static void Do(Mobile from, CraftSystem craftSystem, ITool tool) { int num = craftSystem.CanCraft(from, tool, null); if (num > 0 && num != 1044267) { from.SendGump(new CraftGump(from, craftSystem, tool, num)); } else { from.Target = new InternalTarget(craftSystem, tool); from.SendLocalizedMessage(1044273); // Target an item to recycle. } } private class InternalTarget : Target { private readonly CraftSystem m_CraftSystem; private readonly ITool m_Tool; public InternalTarget(CraftSystem craftSystem, ITool tool) : base(2, false, TargetFlags.None) { m_CraftSystem = craftSystem; m_Tool = tool; } protected override void OnTarget(Mobile from, object targeted) { int num = m_CraftSystem.CanCraft(from, m_Tool, null); if (num > 0) { if (num == 1044267) { bool anvil, forge; DefBlacksmithy.CheckAnvilAndForge(from, 2, out anvil, out forge); if (!anvil) num = 1044266; // You must be near an anvil else if (!forge) num = 1044265; // You must be near a forge. } from.SendGump(new CraftGump(from, m_CraftSystem, m_Tool, num)); } else { SmeltResult result = SmeltResult.Invalid; bool isStoreBought = false; int message; if (targeted is BaseArmor) { result = Resmelt(from, (BaseArmor)targeted, ((BaseArmor)targeted).Resource); isStoreBought = !((BaseArmor)targeted).PlayerConstructed; } else if (targeted is BaseWeapon) { result = Resmelt(from, (BaseWeapon)targeted, ((BaseWeapon)targeted).Resource); isStoreBought = !((BaseWeapon)targeted).PlayerConstructed; } else if (targeted is DragonBardingDeed) { result = Resmelt(from, (DragonBardingDeed)targeted, ((DragonBardingDeed)targeted).Resource); isStoreBought = false; } switch ( result ) { default: case SmeltResult.Invalid: message = 1044272; break; // You can't melt that down into ingots. case SmeltResult.NoSkill: message = 1044269; break; // You have no idea how to work this metal. case SmeltResult.Success: message = isStoreBought ? 500418 : 1044270; break; // You melt the item down into ingots. } from.SendGump(new CraftGump(from, m_CraftSystem, m_Tool, message)); } } private SmeltResult Resmelt(Mobile from, Item item, CraftResource resource) { try { if (CraftResources.GetType(resource) != CraftResourceType.Metal) return SmeltResult.Invalid; CraftResourceInfo info = CraftResources.GetInfo(resource); if (info == null || info.ResourceTypes.Length == 0) return SmeltResult.Invalid; CraftItem craftItem = m_CraftSystem.CraftItems.SearchFor(item.GetType()); if (craftItem == null || craftItem.Resources.Count == 0) return SmeltResult.Invalid; CraftRes craftResource = craftItem.Resources.GetAt(0); if (craftResource.Amount < 2) return SmeltResult.Invalid; // Not enough metal to resmelt double difficulty = 0.0; switch ( resource ) { case CraftResource.DullCopper: difficulty = 65.0; break; case CraftResource.ShadowIron: difficulty = 70.0; break; case CraftResource.Copper: difficulty = 75.0; break; case CraftResource.Bronze: difficulty = 80.0; break; case CraftResource.Gold: difficulty = 85.0; break; case CraftResource.Agapite: difficulty = 90.0; break; case CraftResource.Verite: difficulty = 95.0; break; case CraftResource.Valorite: difficulty = 99.0; break; } double skill = Math.Max(from.Skills[SkillName.Mining].Value, from.Skills[SkillName.Blacksmith].Value); if (difficulty > skill) return SmeltResult.NoSkill; Type resourceType = info.ResourceTypes[0]; Item ingot = (Item)Activator.CreateInstance(resourceType); if (item is DragonBardingDeed || (item is BaseArmor && ((BaseArmor)item).PlayerConstructed) || (item is BaseWeapon && ((BaseWeapon)item).PlayerConstructed) || (item is BaseClothing && ((BaseClothing)item).PlayerConstructed)) ingot.Amount = (int)((double)craftResource.Amount * .66); else ingot.Amount = 1; item.Delete(); from.AddToBackpack(ingot); from.PlaySound(0x2A); from.PlaySound(0x240); return SmeltResult.Success; } catch { } return SmeltResult.Invalid; } } } }
kevin-10/ServUO
Scripts/Services/Craft/Core/Resmelt.cs
C#
gpl-2.0
6,952
<?php /** * Plugin Update Checker Library 2.2.0 * http://w-shadow.com/ * * Copyright 2015 Janis Elsts * Released under the MIT license. See license.txt for details. */ if ( !class_exists('wcva_PluginUpdateChecker_2_2', false) ): /** * A custom plugin update checker. * * @author Janis Elsts * @copyright 2015 * @version 2.2 * @access public */ class wcva_PluginUpdateChecker_2_2 { public $metadataUrl = ''; //The URL of the plugin's metadata file. public $pluginAbsolutePath = ''; //Full path of the main plugin file. public $pluginFile = ''; //Plugin filename relative to the plugins directory. Many WP APIs use this to identify plugins. public $slug = ''; //Plugin slug. public $checkPeriod = 12; //How often to check for updates (in hours). public $optionName = ''; //Where to store the update info. public $muPluginFile = ''; //For MU plugins, the plugin filename relative to the mu-plugins directory. public $debugMode = false; //Set to TRUE to enable error reporting. Errors are raised using trigger_error() //and should be logged to the standard PHP error log. public $throttleRedundantChecks = false; //Check less often if we already know that an update is available. public $throttledCheckPeriod = 72; private $cronHook = null; private $debugBarPlugin = null; private $cachedInstalledVersion = null; private $upgradedPluginFile = null; //The plugin that is currently being upgraded by WordPress. /** * Class constructor. * * @param string $metadataUrl The URL of the plugin's metadata file. * @param string $pluginFile Fully qualified path to the main plugin file. * @param string $slug The plugin's 'slug'. If not specified, the filename part of $pluginFile sans '.php' will be used as the slug. * @param integer $checkPeriod How often to check for updates (in hours). Defaults to checking every 12 hours. Set to 0 to disable automatic update checks. * @param string $optionName Where to store book-keeping info about update checks. Defaults to 'external_updates-$slug'. * @param string $muPluginFile Optional. The plugin filename relative to the mu-plugins directory. */ public function __construct($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = ''){ $this->purchase_url = ''.site_url().'/wp-admin/admin.php?page=wc-settings&tab=products&section=display#woocommerce_wcva_purchase_code'; $this->is_code_valid = get_option('wcva_activation_status'); $this->metadataUrl = $metadataUrl; $this->pluginAbsolutePath = $pluginFile; $this->pluginFile = plugin_basename($this->pluginAbsolutePath); $this->muPluginFile = $muPluginFile; $this->checkPeriod = $checkPeriod; $this->slug = $slug; $this->optionName = $optionName; $this->debugMode = defined('WP_DEBUG') && WP_DEBUG; //If no slug is specified, use the name of the main plugin file as the slug. //For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'. if ( empty($this->slug) ){ $this->slug = basename($this->pluginFile, '.php'); } if ( empty($this->optionName) ){ $this->optionName = 'external_updates-' . $this->slug; } //Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume //it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir). if ( empty($this->muPluginFile) && (strpbrk($this->pluginFile, '/\\') === false) && $this->isMuPlugin() ) { $this->muPluginFile = $this->pluginFile; } $this->installHooks(); } /** * Install the hooks required to run periodic update checks and inject update info * into WP data structures. * * @return void */ protected function installHooks(){ //Override requests for plugin information add_filter('plugins_api', array($this, 'injectInfo'), 20, 3); //Insert our update info into the update array maintained by WP add_filter('site_transient_update_plugins', array($this,'injectUpdate')); //WP 3.0+ add_filter('transient_update_plugins', array($this,'injectUpdate')); //WP 2.8+ add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2); add_action('admin_init', array($this, 'handleManualCheck')); add_action('all_admin_notices', array($this, 'displayManualCheckResult')); //Clear the version number cache when something - anything - is upgraded or WP clears the update cache. add_filter('upgrader_post_install', array($this, 'clearCachedVersion')); add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion')); //Set up the periodic update checks $this->cronHook = 'check_plugin_updates-' . $this->slug; if ( $this->checkPeriod > 0 ){ //Trigger the check via Cron. //Try to use one of the default schedules if possible as it's less likely to conflict //with other plugins and their custom schedules. $defaultSchedules = array( 1 => 'hourly', 12 => 'twicedaily', 24 => 'daily', ); if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) { $scheduleName = $defaultSchedules[$this->checkPeriod]; } else { //Use a custom cron schedule. $scheduleName = 'every' . $this->checkPeriod . 'hours'; add_filter('cron_schedules', array($this, '_addCustomSchedule')); } if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) { wp_schedule_event(time(), $scheduleName, $this->cronHook); } add_action($this->cronHook, array($this, 'maybeCheckForUpdates')); register_deactivation_hook($this->pluginFile, array($this, '_removeUpdaterCron')); //In case Cron is disabled or unreliable, we also manually trigger //the periodic checks while the user is browsing the Dashboard. add_action( 'admin_init', array($this, 'maybeCheckForUpdates') ); //Like WordPress itself, we check more often on certain pages. /** @see wp_update_plugins */ add_action('load-update-core.php', array($this, 'maybeCheckForUpdates')); add_action('load-plugins.php', array($this, 'maybeCheckForUpdates')); add_action('load-update.php', array($this, 'maybeCheckForUpdates')); //This hook fires after a bulk update is complete. add_action('upgrader_process_complete', array($this, 'maybeCheckForUpdates'), 11, 0); } else { //Periodic checks are disabled. wp_clear_scheduled_hook($this->cronHook); } if ( did_action('plugins_loaded') ) { $this->initDebugBarPanel(); } else { add_action('plugins_loaded', array($this, 'initDebugBarPanel')); } //Rename the update directory to be the same as the existing directory. add_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10, 3); //Keep track of which plugin WordPress is currently upgrading. add_filter('upgrader_pre_install', array($this, 'setUpgradedPlugin'), 10, 2); add_filter('upgrader_post_install', array($this, 'clearUpgradedPlugin'), 10, 1); add_action('upgrader_process_complete', array($this, 'clearUpgradedPlugin'), 10, 1); } /** * Add our custom schedule to the array of Cron schedules used by WP. * * @param array $schedules * @return array */ public function _addCustomSchedule($schedules){ if ( $this->checkPeriod && ($this->checkPeriod > 0) ){ $scheduleName = 'every' . $this->checkPeriod . 'hours'; $schedules[$scheduleName] = array( 'interval' => $this->checkPeriod * 3600, 'display' => sprintf('Every %d hours', $this->checkPeriod), ); } return $schedules; } /** * Remove the scheduled cron event that the library uses to check for updates. * * @return void */ public function _removeUpdaterCron(){ wp_clear_scheduled_hook($this->cronHook); } /** * Get the name of the update checker's WP-cron hook. Mostly useful for debugging. * * @return string */ public function getCronHookName() { return $this->cronHook; } /** * Retrieve plugin info from the configured API endpoint. * * @uses wp_remote_get() * * @param array $queryArgs Additional query arguments to append to the request. Optional. * @return PluginInfo */ public function requestInfo($queryArgs = array()){ //Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()). $installedVersion = $this->getInstalledVersion(); $queryArgs['installed_version'] = ($installedVersion !== null) ? $installedVersion : ''; $queryArgs = apply_filters('puc_request_info_query_args-'.$this->slug, $queryArgs); //Various options for the wp_remote_get() call. Plugins can filter these, too. $options = array( 'timeout' => 10, //seconds 'headers' => array( 'Accept' => 'application/json' ), ); $options = apply_filters('puc_request_info_options-'.$this->slug, $options); //The plugin info should be at 'http://your-api.com/url/here/$slug/info.json' $url = $this->metadataUrl; if ( !empty($queryArgs) ){ $url = add_query_arg($queryArgs, $url); } $result = wp_remote_get( $url, $options ); //Try to parse the response $pluginInfo = null; if ( !is_wp_error($result) && isset($result['response']['code']) && ($result['response']['code'] == 200) && !empty($result['body']) ){ $pluginInfo = wcva_PluginInfo_2_2::fromJson($result['body'], $this->debugMode); $pluginInfo->filename = $this->pluginFile; $pluginInfo->slug = $this->slug; } else if ( $this->debugMode ) { $message = sprintf("The URL %s does not point to a valid plugin metadata file. ", $url); if ( is_wp_error($result) ) { $message .= "WP HTTP error: " . $result->get_error_message(); } else if ( isset($result['response']['code']) ) { $message .= "HTTP response code is " . $result['response']['code'] . " (expected: 200)"; } else { $message .= "wp_remote_get() returned an unexpected result."; } trigger_error($message, E_USER_WARNING); } $pluginInfo = apply_filters('puc_request_info_result-'.$this->slug, $pluginInfo, $result); return $pluginInfo; } /** * Retrieve the latest update (if any) from the configured API endpoint. * * @uses PluginUpdateChecker::requestInfo() * * @return PluginUpdate An instance of PluginUpdate, or NULL when no updates are available. */ public function requestUpdate(){ //For the sake of simplicity, this function just calls requestInfo() //and transforms the result accordingly. $pluginInfo = $this->requestInfo(array('checking_for_updates' => '1')); if ( $pluginInfo == null ){ return null; } return wcva_PluginUpdate_2_2::fromPluginInfo($pluginInfo); } /** * Get the currently installed version of the plugin. * * @return string Version number. */ public function getInstalledVersion(){ if ( isset($this->cachedInstalledVersion) ) { return $this->cachedInstalledVersion; } $pluginHeader = $this->getPluginHeader(); if ( isset($pluginHeader['Version']) ) { $this->cachedInstalledVersion = $pluginHeader['Version']; return $pluginHeader['Version']; } else { //This can happen if the filename points to something that is not a plugin. if ( $this->debugMode ) { trigger_error( sprintf( "Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.", $this->pluginFile ), E_USER_WARNING ); } return null; } } /** * Get plugin's metadata from its file header. * * @return array */ protected function getPluginHeader() { if ( !is_file($this->pluginAbsolutePath) ) { //This can happen if the plugin filename is wrong. if ( $this->debugMode ) { trigger_error( sprintf( "Can't to read the plugin header for '%s'. The file does not exist.", $this->pluginFile ), E_USER_WARNING ); } return array(); } if ( !function_exists('get_plugin_data') ){ require_once( ABSPATH . '/wp-admin/includes/plugin.php' ); } return get_plugin_data($this->pluginAbsolutePath, false, false); } /** * Check for plugin updates. * The results are stored in the DB option specified in $optionName. * * @return PluginUpdate|null */ public function checkForUpdates(){ wcva_verify_envato_purchase_code(); $installedVersion = $this->getInstalledVersion(); //Fail silently if we can't find the plugin or read its header. if ( $installedVersion === null ) { if ( $this->debugMode ) { trigger_error( sprintf('Skipping update check for %s - installed version unknown.', $this->pluginFile), E_USER_WARNING ); } return null; } $state = $this->getUpdateState(); if ( empty($state) ){ $state = new StdClass; $state->lastCheck = 0; $state->checkedVersion = ''; $state->update = null; } $state->lastCheck = time(); $state->checkedVersion = $installedVersion; $this->setUpdateState($state); //Save before checking in case something goes wrong $state->update = $this->requestUpdate(); $this->setUpdateState($state); return $this->getUpdate(); } /** * Check for updates if the configured check interval has already elapsed. * Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron. * * You can override the default behaviour by using the "puc_check_now-$slug" filter. * The filter callback will be passed three parameters: * - Current decision. TRUE = check updates now, FALSE = don't check now. * - Last check time as a Unix timestamp. * - Configured check period in hours. * Return TRUE to check for updates immediately, or FALSE to cancel. * * This method is declared public because it's a hook callback. Calling it directly is not recommended. */ public function maybeCheckForUpdates(){ if ( empty($this->checkPeriod) ){ return; } $currentFilter = current_filter(); if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) { //Check more often when the user visits "Dashboard -> Updates" or does a bulk update. $timeout = 60; } else if ( in_array($currentFilter, array('load-plugins.php', 'load-update.php')) ) { //Also check more often on the "Plugins" page and /wp-admin/update.php. $timeout = 3600; } else if ( $this->throttleRedundantChecks && ($this->getUpdate() !== null) ) { //Check less frequently if it's already known that an update is available. $timeout = $this->throttledCheckPeriod * 3600; } else if ( defined('DOING_CRON') && constant('DOING_CRON') ) { //WordPress cron schedules are not exact, so lets do an update check even //if slightly less than $checkPeriod hours have elapsed since the last check. $cronFuzziness = 20 * 60; $timeout = $this->checkPeriod * 3600 - $cronFuzziness; } else { $timeout = $this->checkPeriod * 3600; } $state = $this->getUpdateState(); $shouldCheck = empty($state) || !isset($state->lastCheck) || ( (time() - $state->lastCheck) >= $timeout ); //Let plugin authors substitute their own algorithm. $shouldCheck = apply_filters( 'puc_check_now-' . $this->slug, $shouldCheck, (!empty($state) && isset($state->lastCheck)) ? $state->lastCheck : 0, $this->checkPeriod ); if ( $shouldCheck ){ $this->checkForUpdates(); } } /** * Load the update checker state from the DB. * * @return StdClass|null */ public function getUpdateState() { $state = get_site_option($this->optionName, null); if ( empty($state) || !is_object($state)) { $state = null; } if ( !empty($state) && isset($state->update) && is_object($state->update) ){ $state->update = wcva_PluginUpdate_2_2::fromObject($state->update); } return $state; } /** * Persist the update checker state to the DB. * * @param StdClass $state * @return void */ private function setUpdateState($state) { if ( isset($state->update) && is_object($state->update) && method_exists($state->update, 'toStdClass') ) { $update = $state->update; /** @var PluginUpdate $update */ $state->update = $update->toStdClass(); } update_site_option($this->optionName, $state); } /** * Reset update checker state - i.e. last check time, cached update data and so on. * * Call this when your plugin is being uninstalled, or if you want to * clear the update cache. */ public function resetUpdateState() { delete_site_option($this->optionName); } /** * Intercept plugins_api() calls that request information about our plugin and * use the configured API endpoint to satisfy them. * * @see plugins_api() * * @param mixed $result * @param string $action * @param array|object $args * @return mixed */ public function injectInfo($result, $action = null, $args = null){ $relevant = ($action == 'plugin_information') && isset($args->slug) && ( ($args->slug == $this->slug) || ($args->slug == dirname($this->pluginFile)) ); if ( !$relevant ){ return $result; } $pluginInfo = $this->requestInfo(); $pluginInfo = apply_filters('puc_pre_inject_info-' . $this->slug, $pluginInfo); if ($pluginInfo){ return $pluginInfo->toWpFormat(); } return $result; } /** * Insert the latest update (if any) into the update list maintained by WP. * * @param StdClass $updates Update list. * @return StdClass Modified update list. */ public function injectUpdate($updates){ //Is there an update to insert? $update = $this->getUpdate(); //No update notifications for mu-plugins unless explicitly enabled. The MU plugin file //is usually different from the main plugin file so the update wouldn't show up properly anyway. if ( !empty($update) && empty($this->muPluginFile) && $this->isMuPlugin() ) { $update = null; } if ( !empty($update) ) { //Let plugins filter the update info before it's passed on to WordPress. $update = apply_filters('puc_pre_inject_update-' . $this->slug, $update); if ( !is_object($updates) ) { $updates = new StdClass(); $updates->response = array(); } $wpUpdate = $update->toWpFormat(); $pluginFile = $this->pluginFile; if ( $this->isMuPlugin() ) { //WP does not support automatic update installation for mu-plugins, but we can still display a notice. $wpUpdate->package = null; $pluginFile = $this->muPluginFile; } $updates->response[$pluginFile] = $wpUpdate; } else if ( isset($updates, $updates->response) ) { unset($updates->response[$this->pluginFile]); if ( !empty($this->muPluginFile) ) { unset($updates->response[$this->muPluginFile]); } } return $updates; } /** * Rename the update directory to match the existing plugin directory. * * When WordPress installs a plugin or theme update, it assumes that the ZIP file will contain * exactly one directory, and that the directory name will be the same as the directory where * the plugin/theme is currently installed. * * GitHub and other repositories provide ZIP downloads, but they often use directory names like * "project-branch" or "project-tag-hash". We need to change the name to the actual plugin folder. * * @param string $source The directory to copy to /wp-content/plugins. Usually a subdirectory of $remoteSource. * @param string $remoteSource WordPress has extracted the update to this directory. * @param WP_Upgrader $upgrader * @return string|WP_Error */ function fixDirectoryName($source, $remoteSource, $upgrader) { global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */ //Basic sanity checks. if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) { return $source; } //Figure out which plugin is being upgraded. $pluginFile = null; $skin = $upgrader->skin; if ( $skin instanceof Plugin_Upgrader_Skin ) { if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) { $pluginFile = $skin->plugin; } } elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) { //This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin //filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can //do is compare those headers to the headers of installed plugins. if ( !function_exists('get_plugins') ){ require_once( ABSPATH . '/wp-admin/includes/plugin.php' ); } $installedPlugins = get_plugins(); $matches = array(); foreach($installedPlugins as $pluginBasename => $headers) { $diff1 = array_diff_assoc($headers, $skin->plugin_info); $diff2 = array_diff_assoc($skin->plugin_info, $headers); if ( empty($diff1) && empty($diff2) ) { $matches[] = $pluginBasename; } } //It's possible (though very unlikely) that there could be two plugins with identical //headers. In that case, we can't unambiguously identify the plugin that's being upgraded. if ( count($matches) !== 1 ) { return $source; } $pluginFile = reset($matches); } elseif ( !empty($this->upgradedPluginFile) ) { $pluginFile = $this->upgradedPluginFile; } //If WordPress is upgrading anything other than our plugin, leave the directory name unchanged. if ( empty($pluginFile) || ($pluginFile !== $this->pluginFile) ) { return $source; } //Rename the source to match the existing plugin directory. $pluginDirectoryName = dirname($this->pluginFile); if ( ($pluginDirectoryName === '.') || ($pluginDirectoryName === '/') ) { return $source; } $correctedSource = trailingslashit($remoteSource) . $pluginDirectoryName . '/'; if ( $source !== $correctedSource ) { //The update archive should contain a single directory that contains the rest of plugin files. Otherwise, //WordPress will try to copy the entire working directory ($source == $remoteSource). We can't rename //$remoteSource because that would break WordPress code that cleans up temporary files after update. $sourceFiles = $wp_filesystem->dirlist($remoteSource); if ( is_array($sourceFiles) ) { $sourceFiles = array_keys($sourceFiles); $firstFilePath = trailingslashit($remoteSource) . $sourceFiles[0]; if ( (count($sourceFiles) > 1) || (!$wp_filesystem->is_dir($firstFilePath)) ) { return new WP_Error( 'puc-incorrect-directory-structure', sprintf( 'The directory structure of the update is incorrect. All plugin files should be inside ' . 'a directory named <span class="code">%s</span>, not at the root of the ZIP file.', htmlentities($this->slug) ) ); } } $upgrader->skin->feedback(sprintf( 'Renaming %s to %s&#8230;', '<span class="code">' . basename($source) . '</span>', '<span class="code">' . $pluginDirectoryName . '</span>' )); if ( $wp_filesystem->move($source, $correctedSource, true) ) { $upgrader->skin->feedback('Plugin directory successfully renamed.'); return $correctedSource; } else { return new WP_Error( 'puc-rename-failed', 'Unable to rename the update to match the existing plugin directory.' ); } } return $source; } /** * @access private * * @param mixed $input * @param array $hookExtra * @return mixed Returns $input unaltered. */ public function setUpgradedPlugin($input, $hookExtra) { if (!empty($hookExtra['plugin']) && is_string($hookExtra['plugin'])) { $this->upgradedPluginFile = $hookExtra['plugin']; } else { $this->upgradedPluginFile = null; } return $input; } /** * @access private * * @param mixed $input * @return mixed Returns $input unaltered. */ public function clearUpgradedPlugin($input = null) { $this->upgradedPluginFile = null; return $input; } /** * Get the details of the currently available update, if any. * * If no updates are available, or if the last known update version is below or equal * to the currently installed version, this method will return NULL. * * Uses cached update data. To retrieve update information straight from * the metadata URL, call requestUpdate() instead. * * @return PluginUpdate|null */ public function getUpdate() { $state = $this->getUpdateState(); /** @var StdClass $state */ //Is there an update available insert? if ( !empty($state) && isset($state->update) && !empty($state->update) ){ $update = $state->update; //Check if the update is actually newer than the currently installed version. $installedVersion = $this->getInstalledVersion(); if ( ($installedVersion !== null) && version_compare($update->version, $installedVersion, '>') ){ $update->filename = $this->pluginFile; return $update; } } return null; } /** * Add a "Check for updates" link to the plugin row in the "Plugins" page. By default, * the new link will appear after the "Visit plugin site" link. * * You can change the link text by using the "puc_manual_check_link-$slug" filter. * Returning an empty string from the filter will disable the link. * * @param array $pluginMeta Array of meta links. * @param string $pluginFile * @return array */ public function addCheckForUpdatesLink($pluginMeta, $pluginFile) { $isRelevant = ($pluginFile == $this->pluginFile) || (!empty($this->muPluginFile) && $pluginFile == $this->muPluginFile); if ( $isRelevant && current_user_can('update_plugins') ) { $linkUrl = wp_nonce_url( add_query_arg( array( 'puc_check_for_updates' => 1, 'puc_slug' => $this->slug, ), is_network_admin() ? network_admin_url('plugins.php') : admin_url('plugins.php') ), 'puc_check_for_updates' ); $linkText = apply_filters('puc_manual_check_link-' . $this->slug, 'Check for updates'); if ( !empty($linkText) ) { $pluginMeta[] = sprintf('<a href="%s">%s</a>', esc_attr($linkUrl), $linkText); } } return $pluginMeta; } /** * Check for updates when the user clicks the "Check for updates" link. * @see self::addCheckForUpdatesLink() * * @return void */ public function handleManualCheck() { $shouldCheck = isset($_GET['puc_check_for_updates'], $_GET['puc_slug']) && $_GET['puc_slug'] == $this->slug && current_user_can('update_plugins') && check_admin_referer('puc_check_for_updates'); if ( $shouldCheck ) { $update = $this->checkForUpdates(); $status = ($update === null) ? 'no_update' : 'update_available'; wp_redirect(add_query_arg( array( 'puc_update_check_result' => $status, 'puc_slug' => $this->slug, ), is_network_admin() ? network_admin_url('plugins.php') : admin_url('plugins.php') )); } } /** * Display the results of a manual update check. * @see self::handleManualCheck() * * You can change the result message by using the "puc_manual_check_message-$slug" filter. */ public function displayManualCheckResult() { if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->slug) ) { $status = strval($_GET['puc_update_check_result']); if ( $status == 'no_update' ) { $message = 'This plugin is up to date.'; } else if ( $status == 'update_available' ) { if (($this->is_code_valid) == "active") { $message = 'A new version of this plugin is available'; } else { $message= sprintf( 'A new version of woocommerce color or image variation swatches plugin is available. Please enter valid <a href="%s"><span> purchase code</span></a> to get the update.', $this->purchase_url ); } } else { $message = sprintf('Unknown update checker status "%s"', htmlentities($status)); } printf( '<div class="updated"><p>%s</p></div>', apply_filters('puc_manual_check_message-' . $this->slug, $message, $status) ); } } /** * Check if the plugin file is inside the mu-plugins directory. * * @return bool */ protected function isMuPlugin() { static $cachedResult = null; if ( $cachedResult === null ) { //Convert both paths to the canonical form before comparison. $muPluginDir = realpath(WPMU_PLUGIN_DIR); $pluginPath = realpath($this->pluginAbsolutePath); $cachedResult = (strpos($pluginPath, $muPluginDir) === 0); } return $cachedResult; } /** * Clear the cached plugin version. This method can be set up as a filter (hook) and will * return the filter argument unmodified. * * @param mixed $filterArgument * @return mixed */ public function clearCachedVersion($filterArgument = null) { $this->cachedInstalledVersion = null; return $filterArgument; } /** * Register a callback for filtering query arguments. * * The callback function should take one argument - an associative array of query arguments. * It should return a modified array of query arguments. * * @uses add_filter() This method is a convenience wrapper for add_filter(). * * @param callable $callback * @return void */ public function addQueryArgFilter($callback){ add_filter('puc_request_info_query_args-'.$this->slug, $callback); } /** * Register a callback for filtering arguments passed to wp_remote_get(). * * The callback function should take one argument - an associative array of arguments - * and return a modified array or arguments. See the WP documentation on wp_remote_get() * for details on what arguments are available and how they work. * * @uses add_filter() This method is a convenience wrapper for add_filter(). * * @param callable $callback * @return void */ public function addHttpRequestArgFilter($callback){ add_filter('puc_request_info_options-'.$this->slug, $callback); } /** * Register a callback for filtering the plugin info retrieved from the external API. * * The callback function should take two arguments. If the plugin info was retrieved * successfully, the first argument passed will be an instance of PluginInfo. Otherwise, * it will be NULL. The second argument will be the corresponding return value of * wp_remote_get (see WP docs for details). * * The callback function should return a new or modified instance of PluginInfo or NULL. * * @uses add_filter() This method is a convenience wrapper for add_filter(). * * @param callable $callback * @return void */ public function addResultFilter($callback){ add_filter('puc_request_info_result-'.$this->slug, $callback, 10, 2); } /** * Register a callback for one of the update checker filters. * * Identical to add_filter(), except it automatically adds the "puc_" prefix * and the "-$plugin_slug" suffix to the filter name. For example, "request_info_result" * becomes "puc_request_info_result-your_plugin_slug". * * @param string $tag * @param callable $callback * @param int $priority * @param int $acceptedArgs */ public function addFilter($tag, $callback, $priority = 10, $acceptedArgs = 1) { add_filter('puc_' . $tag . '-' . $this->slug, $callback, $priority, $acceptedArgs); } /** * Initialize the update checker Debug Bar plugin/add-on thingy. */ public function initDebugBarPanel() { $debugBarPlugin = dirname(__FILE__) . '/debug-bar-plugin.php'; if ( class_exists('Debug_Bar', false) && file_exists($debugBarPlugin) ) { require_once $debugBarPlugin; $this->debugBarPlugin = new PucDebugBarPlugin($this); } } } endif; if ( !class_exists('wcva_PluginInfo_2_2', false) ): /** * A container class for holding and transforming various plugin metadata. * * @author Janis Elsts * @copyright 2015 * @version 2.2 * @access public */ class wcva_PluginInfo_2_2 { //Most fields map directly to the contents of the plugin's info.json file. //See the relevant docs for a description of their meaning. public $name; public $slug; public $version; public $homepage; public $sections; public $banners; public $download_url; public $author; public $author_homepage; public $requires; public $tested; public $upgrade_notice; public $rating; public $num_ratings; public $downloaded; public $active_installs; public $last_updated; public $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything. public $filename; //Plugin filename relative to the plugins directory. /** * Create a new instance of PluginInfo from JSON-encoded plugin info * returned by an external update API. * * @param string $json Valid JSON string representing plugin info. * @param bool $triggerErrors * @return PluginInfo|null New instance of PluginInfo, or NULL on error. */ public static function fromJson($json, $triggerErrors = false){ /** @var StdClass $apiResponse */ $apiResponse = json_decode($json); if ( empty($apiResponse) || !is_object($apiResponse) ){ if ( $triggerErrors ) { trigger_error( "Failed to parse plugin metadata. Try validating your .json file with http://jsonlint.com/", E_USER_NOTICE ); } return null; } //Very, very basic validation. $valid = isset($apiResponse->name) && !empty($apiResponse->name) && isset($apiResponse->version) && !empty($apiResponse->version); if ( !$valid ){ if ( $triggerErrors ) { trigger_error( "The plugin metadata file does not contain the required 'name' and/or 'version' keys.", E_USER_NOTICE ); } return null; } $info = new self(); foreach(get_object_vars($apiResponse) as $key => $value){ $info->$key = $value; } return $info; } /** * Transform plugin info into the format used by the native WordPress.org API * * @return object */ public function toWpFormat(){ $info = new StdClass; //The custom update API is built so that many fields have the same name and format //as those returned by the native WordPress.org API. These can be assigned directly. $sameFormat = array( 'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice', 'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated', ); foreach($sameFormat as $field){ if ( isset($this->$field) ) { $info->$field = $this->$field; } else { $info->$field = null; } } //Other fields need to be renamed and/or transformed. $info->download_link = $this->download_url; if ( !empty($this->author_homepage) ){ $info->author = sprintf('<a href="%s">%s</a>', $this->author_homepage, $this->author); } else { $info->author = $this->author; } if ( is_object($this->sections) ){ $info->sections = get_object_vars($this->sections); } elseif ( is_array($this->sections) ) { $info->sections = $this->sections; } else { $info->sections = array('description' => ''); } if ( !empty($this->banners) ) { //WP expects an array with two keys: "high" and "low". Both are optional. //Docs: https://wordpress.org/plugins/about/faq/#banners $info->banners = is_object($this->banners) ? get_object_vars($this->banners) : $this->banners; $info->banners = array_intersect_key($info->banners, array('high' => true, 'low' => true)); } return $info; } } endif; if ( !class_exists('wcva_PluginUpdate_2_2', false) ): /** * A simple container class for holding information about an available update. * * @author Janis Elsts * @copyright 2015 * @version 2.2 * @access public */ class wcva_PluginUpdate_2_2 { public $id = 0; public $slug; public $version; public $homepage; public $download_url; public $upgrade_notice; public $filename; //Plugin filename relative to the plugins directory. private static $fields = array('id', 'slug', 'version', 'homepage', 'download_url', 'upgrade_notice', 'filename'); /** * Create a new instance of PluginUpdate from its JSON-encoded representation. * * @param string $json * @param bool $triggerErrors * @return PluginUpdate|null */ public static function fromJson($json, $triggerErrors = false){ //Since update-related information is simply a subset of the full plugin info, //we can parse the update JSON as if it was a plugin info string, then copy over //the parts that we care about. $pluginInfo = wcva_PluginInfo_2_2::fromJson($json, $triggerErrors); if ( $pluginInfo != null ) { return self::fromPluginInfo($pluginInfo); } else { return null; } } /** * Create a new instance of PluginUpdate based on an instance of PluginInfo. * Basically, this just copies a subset of fields from one object to another. * * @param PluginInfo $info * @return PluginUpdate */ public static function fromPluginInfo($info){ return self::fromObject($info); } /** * Create a new instance of PluginUpdate by copying the necessary fields from * another object. * * @param StdClass|PluginInfo|PluginUpdate $object The source object. * @return PluginUpdate The new copy. */ public static function fromObject($object) { $update = new self(); $fields = self::$fields; if (!empty($object->slug)) $fields = apply_filters('puc_retain_fields-'.$object->slug, $fields); foreach($fields as $field){ if (property_exists($object, $field)) { $update->$field = $object->$field; } } return $update; } /** * Create an instance of StdClass that can later be converted back to * a PluginUpdate. Useful for serialization and caching, as it avoids * the "incomplete object" problem if the cached value is loaded before * this class. * * @return StdClass */ public function toStdClass() { $object = new StdClass(); $fields = self::$fields; if (!empty($this->slug)) $fields = apply_filters('puc_retain_fields-'.$this->slug, $fields); foreach($fields as $field){ if (property_exists($this, $field)) { $object->$field = $this->$field; } } return $object; } /** * Transform the update into the format used by WordPress native plugin API. * * @return object */ public function toWpFormat(){ $update = new StdClass; $update->id = $this->id; $update->slug = $this->slug; $update->new_version = $this->version; $update->url = $this->homepage; $update->package = $this->download_url; $update->plugin = $this->filename; if ( !empty($this->upgrade_notice) ){ $update->upgrade_notice = $this->upgrade_notice; } $is_code_valid = get_option("wcva_activation_status"); if ( $is_code_valid == "active" ) { return $update; } } } endif; if ( !class_exists('PucFactory', false) ): /** * A factory that builds instances of other classes from this library. * * When multiple versions of the same class have been loaded (e.g. PluginUpdateChecker 1.2 * and 1.3), this factory will always use the latest available version. Register class * versions by calling {@link PucFactory::addVersion()}. * * At the moment it can only build instances of the PluginUpdateChecker class. Other classes * are intended mainly for internal use and refer directly to specific implementations. If you * want to instantiate one of them anyway, you can use {@link PucFactory::getLatestClassVersion()} * to get the class name and then create it with <code>new $class(...)</code>. */ class PucFactory { protected static $classVersions = array(); protected static $sorted = false; /** * Create a new instance of PluginUpdateChecker. * * @see PluginUpdateChecker::__construct() * * @param $metadataUrl * @param $pluginFile * @param string $slug * @param int $checkPeriod * @param string $optionName * @param string $muPluginFile * @return PluginUpdateChecker */ public static function buildUpdateChecker($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') { $class = self::getLatestClassVersion('PluginUpdateChecker'); return new $class($metadataUrl, $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile); } /** * Get the specific class name for the latest available version of a class. * * @param string $class * @return string|null */ public static function getLatestClassVersion($class) { if ( !self::$sorted ) { self::sortVersions(); } if ( isset(self::$classVersions[$class]) ) { return reset(self::$classVersions[$class]); } else { return null; } } /** * Sort available class versions in descending order (i.e. newest first). */ protected static function sortVersions() { foreach ( self::$classVersions as $class => $versions ) { uksort($versions, array(__CLASS__, 'compareVersions')); self::$classVersions[$class] = $versions; } self::$sorted = true; } protected static function compareVersions($a, $b) { return -version_compare($a, $b); } /** * Register a version of a class. * * @access private This method is only for internal use by the library. * * @param string $generalClass Class name without version numbers, e.g. 'PluginUpdateChecker'. * @param string $versionedClass Actual class name, e.g. 'PluginUpdateChecker_1_2'. * @param string $version Version number, e.g. '1.2'. */ public static function addVersion($generalClass, $versionedClass, $version) { if ( !isset(self::$classVersions[$generalClass]) ) { self::$classVersions[$generalClass] = array(); } self::$classVersions[$generalClass][$version] = $versionedClass; self::$sorted = false; } } endif; require_once(dirname(__FILE__) . '/github-checker.php'); //Register classes defined in this file with the factory. PucFactory::addVersion('PluginUpdateChecker', 'wcva_PluginUpdateChecker_2_2', '2.2'); PucFactory::addVersion('PluginUpdate', 'wcva_PluginUpdate_2_2', '2.2'); PucFactory::addVersion('PluginInfo', 'wcva_PluginInfo_2_2', '2.2'); PucFactory::addVersion('PucGitHubChecker', 'PucGitHubChecker_2_2', '2.2'); /** * Create non-versioned variants of the update checker classes. This allows for backwards * compatibility with versions that did not use a factory, and it simplifies doc-comments. */ if ( !class_exists('PluginUpdateChecker', false) ) { class PluginUpdateChecker extends wcva_PluginUpdateChecker_2_2 { } } if ( !class_exists('PluginUpdate', false) ) { class PluginUpdate extends wcva_PluginUpdate_2_2 {} } if ( !class_exists('PluginInfo', false) ) { class PluginInfo extends wcva_PluginInfo_2_2 {} } /** * Check for valid envato item purchase code via envato api */
markredballoon/clivemizen
wp-content/plugins/woocommerce-colororimage-variation-select/plugin-update-checker/plugin-update-checker.php
PHP
gpl-2.0
43,682
<?php /** * Event List * * @author ProSports * @package ProSports/Templates * @version 1.5 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly $defaults = array( 'id' => null, 'status' => 'default', 'date' => 'default', 'date_from' => 'default', 'date_to' => 'default', 'number' => -1, 'show_team_logo' => get_option( 'prosports_event_list_show_logos', 'no' ) == 'yes' ? true : false, 'link_teams' => get_option( 'prosports_link_teams', 'no' ) == 'yes' ? true : false, 'link_venues' => get_option( 'prosports_link_venues', 'yes' ) == 'yes' ? true : false, 'sortable' => get_option( 'prosports_enable_sortable_tables', 'yes' ) == 'yes' ? true : false, 'scrollable' => get_option( 'prosports_enable_scrollable_tables', 'yes' ) == 'yes' ? true : false, 'responsive' => get_option( 'prosports_enable_responsive_tables', 'yes' ) == 'yes' ? true : false, 'paginated' => get_option( 'prosports_event_list_paginated', 'yes' ) == 'yes' ? true : false, 'rows' => get_option( 'prosports_event_list_rows', 10 ), 'order' => 'default', 'columns' => null, 'show_all_events_link' => false, ); extract( $defaults, EXTR_SKIP ); $calendar = new SP_Calendar( $id ); if ( $status != 'default' ) $calendar->status = $status; if ( $date != 'default' ) $calendar->date = $date; if ( $date_from != 'default' ) $calendar->from = $date_from; if ( $date_to != 'default' ) $calendar->to = $date_to; if ( $order != 'default' ) $calendar->order = $order; $data = $calendar->data(); $usecolumns = $calendar->columns; $title_format = get_option( 'prosports_event_list_title_format', 'title' ); $time_format = get_option( 'prosports_event_list_time_format', 'combined' ); if ( isset( $columns ) ): if ( is_array( $columns ) ) $usecolumns = $columns; else $usecolumns = explode( ',', $columns ); endif; if ( $id ) { echo '<h4 class="sp-table-caption">' . get_the_title( $id ) . '</h4>'; } ?> <div class="sp-template sp-template-event-list"> <div class="sp-table-wrapper<?php if ( $scrollable ) { ?> sp-scrollable-table-wrapper<?php } ?>"> <table class="sp-event-list sp-data-table<?php if ( $responsive ) { ?> sp-responsive-table<?php } if ( $paginated ) { ?> sp-paginated-table<?php } if ( $sortable ) { ?> sp-sortable-table<?php } ?>" data-sp-rows="<?php echo $rows; ?>"> <thead> <tr> <?php echo '<th class="data-date">' . __( 'Date', 'prosports' ) . '</th>'; switch ( $title_format ) { case 'homeaway': if ( sp_column_active( $usecolumns, 'event' ) ) { echo '<th class="data-home">' . __( 'Home', 'prosports' ) . '</th>'; if ( 'combined' == $time_format && sp_column_active( $usecolumns, 'time' ) ) { echo '<th class="data-time">&nbsp;</th>'; } elseif ( in_array( $time_format, array( 'separate', 'results' ) ) && sp_column_active( $usecolumns, 'results' ) ) { echo '<th class="data-results">&nbsp;</th>'; } echo '<th class="data-away">' . __( 'Away', 'prosports' ) . '</th>'; if ( in_array( $time_format, array( 'separate', 'time' ) ) && sp_column_active( $usecolumns, 'time' ) ) { echo '<th class="data-time">' . __( 'Time', 'prosports' ) . '</th>'; } } break; default: if ( sp_column_active( $usecolumns, 'event' ) ) { if ( $title_format == 'teams' ) echo '<th class="data-teams">' . __( 'Teams', 'prosports' ) . '</th>'; else echo '<th class="data-event">' . __( 'Event', 'prosports' ) . '</th>'; } switch ( $time_format ) { case 'separate': if ( sp_column_active( $usecolumns, 'time' ) ) echo '<th class="data-time">' . __( 'Time', 'prosports' ) . '</th>'; if ( sp_column_active( $usecolumns, 'results' ) ) echo '<th class="data-results">' . __( 'Results', 'prosports' ) . '</th>'; break; case 'time': if ( sp_column_active( $usecolumns, 'time' ) ) echo '<th class="data-time">' . __( 'Time', 'prosports' ) . '</th>'; break; case 'results': if ( sp_column_active( $usecolumns, 'results' ) ) echo '<th class="data-results">' . __( 'Results', 'prosports' ) . '</th>'; break; default: if ( sp_column_active( $usecolumns, 'time' ) ) echo '<th class="data-time">' . __( 'Time/Results', 'prosports' ) . '</th>'; } } if ( sp_column_active( $usecolumns, 'league' ) ) echo '<th class="data-league">' . __( 'Competition', 'prosports' ) . '</th>'; if ( sp_column_active( $usecolumns, 'season' ) ) echo '<th class="data-season">' . __( 'Season', 'prosports' ) . '</th>'; if ( sp_column_active( $usecolumns, 'venue' ) ) echo '<th class="data-venue">' . __( 'Venue', 'prosports' ) . '</th>'; if ( sp_column_active( $usecolumns, 'article' ) ) echo '<th class="data-article">' . __( 'Article', 'prosports' ) . '</th>'; ?> </tr> </thead> <tbody> <?php $i = 0; if ( is_numeric( $number ) && $number > 0 ) $limit = $number; foreach ( $data as $event ): if ( isset( $limit ) && $i >= $limit ) continue; $teams = get_post_meta( $event->ID, 'sp_team' ); $video = get_post_meta( $event->ID, 'sp_video', true ); $main_results = sp_get_main_results( $event ); $teams_output = ''; $teams_array = array(); $team_logos = array(); if ( $teams ): foreach ( $teams as $team ): $name = get_the_title( $team ); if ( $name ): if ( $show_team_logo ): $name = sp_get_logo( $team, 'mini' ) . ' ' . $name; $team_logos[] = sp_get_logo( $team, 'mini' ); endif; if ( $link_teams ): $team_output = '<a href="' . get_post_permalink( $team ) . '">' . $name . '</a>'; else: $team_output = $name; endif; $team_result = sp_array_value( $main_results, $team, null ); if ( $team_result != null ): if ( $usecolumns != null && ! in_array( 'time', $usecolumns ) ): $team_output .= ' (' . $team_result . ')'; endif; endif; $teams_array[] = $team_output; $teams_output .= $team_output . '<br>'; endif; endforeach; else: $teams_output .= '&mdash;'; endif; echo '<tr class="sp-row sp-post' . ( $i % 2 == 0 ? ' alternate' : '' ) . '">'; echo '<td class="data-date"><a href="' . get_permalink( $event->ID ) . '"><date>' . get_post_time( 'Y-m-d H:i:s', false, $event ) . '</date>' . get_post_time( get_option( 'date_format' ), false, $event, true ) . '</a></td>'; switch ( $title_format ) { case 'homeaway': if ( sp_column_active( $usecolumns, 'event' ) ) { $team = array_shift( $teams_array ); echo '<td class="data-home">' . $team . '</td>'; if ( 'combined' == $time_format && sp_column_active( $usecolumns, 'time' ) ) { echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">'; if ( ! empty( $main_results ) ): echo implode( ' - ', $main_results ); else: echo '<date>&nbsp;' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event ); endif; echo '</a></td>'; } elseif ( in_array( $time_format, array( 'separate', 'results' ) ) && sp_column_active( $usecolumns, 'results' ) ) { echo '<td class="data-results"><a href="' . get_permalink( $event->ID ) . '">'; if ( ! empty( $main_results ) ): echo implode( ' - ', $main_results ); else: echo '-'; endif; echo '</a></td>'; } $team = array_shift( $teams_array ); echo '<td class="data-away">' . $team . '</td>'; if ( in_array( $time_format, array( 'separate', 'time' ) ) && sp_column_active( $usecolumns, 'time' ) ) { echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">'; echo '<date>&nbsp;' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event ); echo '</a></td>'; } } break; default: if ( sp_column_active( $usecolumns, 'event' ) ) { if ( $title_format == 'teams' ) echo '<td class="data-event data-teams">' . $teams_output . '</td>'; else echo '<td class="data-event"><a href="' . get_permalink( $event->ID ) . '">' . implode( ' ', $team_logos ) . ' ' . $event->post_title . '</a></td>'; } switch ( $time_format ) { case 'separate': if ( sp_column_active( $usecolumns, 'time' ) ) { echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">'; echo '<date>&nbsp;' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event ); echo '</a></td>'; } if ( sp_column_active( $usecolumns, 'results' ) ) { echo '<td class="data-results"><a href="' . get_permalink( $event->ID ) . '">'; if ( ! empty( $main_results ) ): echo implode( ' - ', $main_results ); else: echo '-'; endif; echo '</a></td>'; } break; case 'time': if ( sp_column_active( $usecolumns, 'time' ) ) { echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">'; echo '<date>&nbsp;' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event ); echo '</a></td>'; } break; case 'results': if ( sp_column_active( $usecolumns, 'results' ) ) { echo '<td class="data-results"><a href="' . get_permalink( $event->ID ) . '">'; if ( ! empty( $main_results ) ): echo implode( ' - ', $main_results ); else: echo '-'; endif; echo '</a></td>'; } break; default: if ( sp_column_active( $usecolumns, 'time' ) ) { echo '<td class="data-time"><a href="' . get_permalink( $event->ID ) . '">'; if ( ! empty( $main_results ) ): echo implode( ' - ', $main_results ); else: echo '<date>&nbsp;' . get_post_time( 'H:i:s', false, $event ) . '</date>' . sp_get_time( $event ); endif; echo '</a></td>'; } } } if ( sp_column_active( $usecolumns, 'league' ) ): echo '<td class="data-league">'; $leagues = get_the_terms( $event->ID, 'sp_league' ); if ( $leagues ): foreach ( $leagues as $league ): echo $league->name; endforeach; endif; echo '</td>'; endif; if ( sp_column_active( $usecolumns, 'season' ) ): echo '<td class="data-season">'; $seasons = get_the_terms( $event->ID, 'sp_season' ); if ( $seasons ): foreach ( $seasons as $season ): echo $season->name; endforeach; endif; echo '</td>'; endif; if ( sp_column_active( $usecolumns, 'venue' ) ): echo '<td class="data-venue">'; if ( $link_venues ): the_terms( $event->ID, 'sp_venue' ); else: $venues = get_the_terms( $event->ID, 'sp_venue' ); if ( $venues ): foreach ( $venues as $venue ): echo $venue->name; endforeach; endif; endif; echo '</td>'; endif; if ( sp_column_active( $usecolumns, 'article' ) ): echo '<td class="data-article"> <a href="' . get_permalink( $event->ID ) . '">'; if ( $video ): echo '<div class="dashicons dashicons-video-alt"></div>'; elseif ( has_post_thumbnail( $event->ID ) ): echo '<div class="dashicons dashicons-camera"></div>'; endif; if ( $event->post_content !== null ): if ( $event->post_status == 'publish' ): _e( 'Recap', 'prosports' ); else: _e( 'Preview', 'prosports' ); endif; endif; echo '</a> </td>'; endif; echo '</tr>'; $i++; endforeach; ?> </tbody> </table> </div> <?php if ( $id && $show_all_events_link ) echo '<a class="sp-calendar-link sp-view-all-link" href="' . get_permalink( $id ) . '">' . __( 'View all events', 'prosports' ) . '</a>'; ?> </div>
parpaitas1987/ProSports
sm-manager-setup/includes/prosports/templates/event-list.php
PHP
gpl-2.0
12,406
<?php $PHPMaker_vers = 'v5.0.0'; define('ADODB_FETCH_DEFAULT', 0); define('ADODB_FETCH_NUM', 1); define('ADODB_FETCH_ASSOC', 2); define('ADODB_FETCH_BOTH', 3); define("EW_USE_MYSQLI", FALSE, TRUE); $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT; // DEFAULT or BOTH. DO NOT CHANGE! /** * ADOConnection */ class ADOConnection { var $connectionId = false; var $record_set = false; var $database; var $dbtype; var $dataProvider; var $host; var $open; var $password; var $username; var $persistent; var $debug = false; var $debug_console = false; var $debug_echo = true; var $debug_output; var $forcenewconnection = false; var $createdatabase = false; var $last_module_name; var $socket = false; var $port = false; var $clientFlags = 0; var $nameQuote = '"'; var $sysDate = false; /// name of function that returns the current date var $sysTimeStamp = false; /// name of function that returns the current timestamp var $sql; var $raiseErrorFn = false; var $query_count = 0; var $query_time_total = 0; var $query_list = array(); var $query_list_time = array(); var $query_list_errors = array(); var $_logsql = false; function ADOConnection() { } /** * @access public */ function Version() { global $PHPMaker_vers; return (float) substr($PHPMaker_vers,1); } /** * Returns true if connected to database * Usage: $db->IsConnected(); * * @access public */ function IsConnected() { if($this->connectionId === false || $this->connectionId == false) return false; else return true; } /** * Normal Database connection * Usage: $result = $db->Connect('host', 'username', 'password', 'database'); * * @access public * @param string $database * @param string $host * @param string $password * @param string $username * @param string $forcenew // private */ function Connect( $host = "", $username = "", $password = "", $database = "", $forcenew = false) { return $this->_connect($host, $username, $password, $database, false, $forcenew); } /** * Persistent Database connection * Usage: $result = $db->PConnect('host', 'username', 'password', 'database'); * * @access public * @param string $database * @param string $host * @param string $password * @param string $username */ function PConnect( $host = "", $username = "", $password = "", $database = "") { return $this->_connect($host, $username, $password, $database, true, false); } /** * Force New Database connection * Usage: $result = $db->NConnect('host', 'username', 'password', 'database'); * * @access public * @param string $database * @param string $host * @param string $password * @param string $username */ function NConnect( $host = "", $username = "", $password = "", $database = "") { return $this->_connect($host, $username, $password, $database, false, true); } /** * Returns SQL query and instantiates sql statement & resultset driver * Usage: $linkId =& $db->execute( 'SELECT * FROM foo ORDER BY id' ); * * @access public * @param string $sql * @return mixed Resource ID, Array */ function &Execute( $sql, $inputarr = false ) { // adodb_log_sql will time the query execution and log the sql query // note: the later $this->do_query() should not run since adodb_log_sql() independently executes the query itself. if($this->_logsql === true) { $ret =& adodb_log_sql($this, $sql, $inputarr); if (isset($ret)) return $ret; } $rs =& $this->do_query($sql, -1, -1, $inputarr); return $rs; } /** * Returns SQL query and instantiates sql statement & resultset driver * Usage: $linkId =& $db->SelectLimit( 'SELECT * FROM foo ORDER BY id', $nrows, $offset ); * $nrows and $offset are optional * * @access public * @param string $sql * @param string $nrows * @param string $offset * @return mixed Resource ID, Array */ function &SelectLimit( $sql, $nrows=-1, $offset=-1, $inputarr=false, $secs2cache=0 ) { $rs =& $this->do_query( $sql, $offset, $nrows, $inputarr); return $rs; } /** * Display debug output and database error. * * @access private */ function outp($text, $newline = true) { global $ADODB_OUTP; $this->debug_output = "<br>\n(" . $this->dbtype . "): ".htmlspecialchars($text)."<br>\n Error (" . $this->ErrorNo() .'): '. $this->ErrorMsg() . "<br>\n"; if(defined('ADODB_OUTP')) { $fn = ADODB_OUTP; } else if(isset($ADODB_OUTP)) { $fn = $ADODB_OUTP; } if(defined('ADODB_OUTP') || isset($ADODB_OUTP)) { $fn($this->debug_output, $newline); return; } if($this->debug_echo) echo $this->debug_output; } } /** * Empty result record set for updates, inserts, ect * * @access private */ class ADORecordSet_empty { var $fields = false; var $EOF = true; function MoveNext() {return;} function RecordCount() {return 0;} function FieldCount() {return 0;} function EOF(){return TRUE;} function Close(){return true;} } /** * mysqlt_driver_ADOConnection */ class mysqlt_driver_ADOConnection extends ADOConnection { var $autoCommit = true; var $transOff = 0; var $transCnt = 0; var $transaction_status = true; var $nameQuote = '`'; var $sysDate = 'CURDATE()'; var $sysTimeStamp = 'NOW()'; var $isoDates = true; // accepts dates in ISO format function mysqlt_driver_ADOConnection() { $this->dbtype = 'mysqlt'; $this->dataProvider = 'mysql'; $this->last_module_name = 'mysqlt_driver'; } /** * Connection to database server and selected database * * @access private */ function _connect($host = "", $username = "", $password = "", $database = "", $persistent, $forcenew) { if (EW_USE_MYSQLI) { if (!function_exists('mysqli_real_connect')) return false; $this->host = $host; $this->username = $username; $this->password = $password; $this->database = $database; $this->persistent = $persistent; $this->forcenewconnection = $forcenew; $this->connectionId = @mysqli_init(); @mysqli_real_connect( $this->connectionId, $this->host, $this->username, $this->password, $this->database, $this->port, $this->socket, $this->clientFlags ); if (mysqli_connect_errno() != 0) { $this->connectionId = false; } } else { if (!function_exists('mysql_connect')) return false; $this->host = $host; if (!empty($this->port)) $this->host .= ":" . $this->port; $this->username = $username; $this->password = $password; $this->database = $database; $this->persistent = $persistent; $this->forcenewconnection = $forcenew; if($this->persistent == 1) { if (strnatcmp(PHP_VERSION, '4.3.0') >= 0) $this->connectionId = @mysql_pconnect( $this->host, $this->username, $this->password, $this->clientFlags ); else $this->connectionId = @mysql_pconnect( $this->host, $this->username, $this->password ); } else { if (strnatcmp(PHP_VERSION, '4.3.0') >= 0) $this->connectionId = @mysql_connect( $this->host, $this->username, $this->password, $this->forcenewconnection, $this->clientFlags ); else if (strnatcmp(PHP_VERSION, '4.2.0') >= 0) $this->connectionId = @mysql_connect( $this->host, $this->username, $this->password, $this->forcenewconnection ); else $this->connectionId = @mysql_connect( $this->host, $this->username, $this->password ); } } if ($this->connectionId === false) { if ($fn = $this->raiseErrorFn) $fn($this->dbtype, 'CONNECT', $this->ErrorNo(), $this->ErrorMsg(), $this->host, $this->database, $this); return false; } if (!empty($this->database)) { if($this->SelectDB( $this->database ) == false) { $this->connectionId = false; return false; } } return true; } /** * Choose a database to connect. * * @param dbname is the name of the database to select * @return true or false * @access public */ function SelectDB($dbname) { $this->database = $dbname; if ($this->connectionId === false) { $this->connectionId = false; return false; } else { if (EW_USE_MYSQLI) { $result = @mysqli_select_db( $this->connectionId, $this->database ); } else { $result = @mysql_select_db( $this->database, $this->connectionId ); } if($result === false) { if($this->createdatabase == true) { if (EW_USE_MYSQLI) { $result = @mysqli_query( $this->connectionId, "CREATE DATABASE IF NOT EXISTS " . $this->database ); } else { $result = @mysql_query( "CREATE DATABASE IF NOT EXISTS " . $this->database, $this->connectionId ); } if ($result === false) { // error handling if query fails return false; } if (EW_USE_MYSQLI) { $result = @mysqli_select_db( $this->connectionId, $this->database ); } else { $result = @mysql_select_db( $this->database, $this->connectionId ); } if($result === false) { return false; } } else { return false; } } return true; } } /** * Return database error message * Usage: $errormessage =& $db->ErrorMsg(); * * @access public */ function ErrorMsg() { if ($this->connectionId === false) { if (EW_USE_MYSQLI) { return @mysqli_connect_error(); } else { return @mysql_error(); } } else { if (EW_USE_MYSQLI) { return @mysqli_error($this->connectionId); } else { return @mysql_error($this->connectionId); } } } /** * Return database error number * Usage: $errorbo =& $db->ErrorNo(); * * @access public */ function ErrorNo() { if ($this->connectionId === false) { if (EW_USE_MYSQLI) { return @mysqli_connect_errno(); } else { return @mysql_errno(); } } else { if (EW_USE_MYSQLI) { return @mysqli_errno($this->connectionId); } else { return @mysql_errno($this->connectionId); } } } /** * Returns # of affected rows from insert/delete/update query * * @access public * @return integer Affected rows */ function Affected_Rows() { if (EW_USE_MYSQLI) { return @mysqli_affected_rows($this->connectionId); } else { return @mysql_affected_rows($this->connectionId); } } /** * Returns the last record id of an inserted item * Usage: $db->Insert_ID(); * * @access public */ function Insert_ID() { if (EW_USE_MYSQLI) { return @mysqli_insert_id($this->connectionId); } else { return @mysql_insert_id($this->connectionId); } } /** * Correctly quotes a string so that all strings are escape coded. * An example is $db->qstr("Haven't a clue."); * * @param string the string to quote * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc(). * * @return single-quoted string IE: 'Haven\'t a clue.' */ function qstr($string, $magic_quotes=false) { if (!$magic_quotes) { if (EW_USE_MYSQLI) { if (strnatcmp(PHP_VERSION, '4.3.0') >= 0 && function_exists('mysqli_real_escape_string')) { return "'" . mysqli_real_escape_string($this->connectionId, $string) . "'"; } } else { if (strnatcmp(PHP_VERSION, '4.3.0') >= 0) { return "'" . mysql_real_escape_string($string, $this->connectionId) . "'"; } } $string = str_replace("'", "\\'" , str_replace('\\', '\\\\', str_replace("\0", "\\\0", $string))); return "'" . $string . "'"; } return "'" . str_replace('\\"', '"', $string) . "'"; } function QMagic($string) { return $this->qstr($string, get_magic_quotes_gpc()); } /** * Returns concatenated string * Usage: $db->Concat($str1,$str2); * * @return concatenated string */ function Concat() { $arr = func_get_args(); $list = implode(', ', $arr); if (strlen($list) > 0) return "CONCAT($list)"; else return ''; } function IfNull( $field, $ifNull ) { return " IFNULL($field, $ifNull) "; } /** * Closes database connection * Usage: $db->close(); * * @access public */ function Close() { if (EW_USE_MYSQLI) { @mysqli_close( $this->connectionId ); } else { @mysql_close( $this->connectionId ); } $this->connectionId = false; } function StartTrans($errfn = 'ADODB_TransMonitor') { if ($this->transOff > 0) { $this->transOff += 1; return; } $this->transaction_status = true; if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans"); $this->BeginTrans(); $this->transOff = 1; } function BeginTrans() { if ($this->transOff) return true; $this->transCnt += 1; $this->Execute('SET AUTOCOMMIT=0'); $this->Execute('BEGIN'); return true; } function CompleteTrans($autoComplete = true) { if ($this->transOff > 1) { $this->transOff -= 1; return true; } $this->transOff = 0; if ($this->transaction_status && $autoComplete) { if (!$this->CommitTrans()) { $this->transaction_status = false; if ($this->debug) ADOConnection::outp("Smart Commit failed"); } else if ($this->debug) ADOConnection::outp("Smart Commit occurred"); } else { $this->RollbackTrans(); if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred"); } return $this->transaction_status; } function CommitTrans($ok=true) { if ($this->transOff) return true; if (!$ok) return $this->RollbackTrans(); if ($this->transCnt) $this->transCnt -= 1; $this->Execute('COMMIT'); $this->Execute('SET AUTOCOMMIT=1'); return true; } function RollbackTrans() { if ($this->transOff) return true; if ($this->transCnt) $this->transCnt -= 1; $this->Execute('ROLLBACK'); $this->Execute('SET AUTOCOMMIT=1'); return true; } function FailTrans() { if ($this->debug) if ($this->transOff == 0) { ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans"); } else { ADOConnection::outp("FailTrans was called"); } $this->transaction_status = false; } function HasFailedTrans() { if ($this->transOff > 0) return $this->transaction_status == false; return false; } function RowLock($tables,$where,$flds='1 as ignore') { if ($this->transCnt==0) $this->BeginTrans(); return $this->GetOne("select $flds from $tables where $where for update"); } function CommitLock($table) { return $this->CommitTrans(); } function RollbackLock($table) { return $this->RollbackTrans(); } /** * Returns All Records in an array * * Usage: $db->GetAll($sql); * @access public */ function &GetAll($sql, $inputarr = false) { $data =& $this->GetArray($sql, $inputarr); return $data; } /** * Returns All Records in an array * * Usage: $db->GetArray($sql); * @access public */ function &GetArray($sql, $inputarr = false) { $data = false; $result =& $this->Execute($sql, $inputarr); if ($result) { $data =& $result->GetArray(); $result->Close(); } return $data; } /** * Executes SQL query and instantiates resultset methods * * @access private * @return mixed Resultset methods */ function &do_query( $sql, $offset, $nrows, $inputarr=false ) { global $ADODB_FETCH_MODE; $false = false; $limit = ''; if ($offset >= 0 || $nrows >= 0) { $offset = ($offset >= 0) ? $offset . "," : ''; $nrows = ($nrows >= 0) ? $nrows : '18446744073709551615'; $limit = ' LIMIT ' . $offset . ' ' . $nrows; } if ($inputarr && is_array($inputarr)) { $sqlarr = explode('?', $sql); if (!is_array(reset($inputarr))) $inputarr = array($inputarr); foreach($inputarr as $arr) { $sql = ''; $i = 0; foreach($arr as $v) { $sql .= $sqlarr[$i]; switch(gettype($v)){ case 'string': $sql .= $this->qstr($v); break; case 'double': $sql .= str_replace(',', '.', $v); break; case 'boolean': $sql .= $v ? 1 : 0; break; default: if ($v === null) $sql .= 'NULL'; else $sql .= $v; } $i += 1; } $sql .= $sqlarr[$i]; if ($i+1 != sizeof($sqlarr)) return $false; $this->sql = $sql . $limit; $time_start = array_sum(explode(' ', microtime())); $this->query_count++; if (EW_USE_MYSQLI) { $resultId = @mysqli_query($this->connectionId, $this->sql ); } else { $resultId = @mysql_query( $this->sql, $this->connectionId ); } $time_total = (array_sum(explode(' ', microtime())) - $time_start); $this->query_time_total += $time_total; if($this->debug_console) { $this->query_list[] = $this->sql; $this->query_list_time[] = $time_total; $this->query_list_errors[] = $this->ErrorMsg(); } if($this->debug) { $this->outp($sql . $limit); } } } else { $this->sql = $sql . $limit; $time_start = array_sum(explode(' ', microtime())); $this->query_count++; if (EW_USE_MYSQLI) { $resultId = @mysqli_query($this->connectionId, $this->sql ); } else { $resultId = @mysql_query( $this->sql, $this->connectionId ); } $time_total = (array_sum(explode(' ', microtime())) - $time_start); $this->query_time_total += $time_total; if($this->debug_console) { $this->query_list[] = $this->sql; $this->query_list_time[] = $time_total; $this->query_list_errors[] = $this->ErrorMsg(); } if($this->debug) { $this->outp($sql . $limit); } } if ($resultId === false) { // error handling if query fails if ($fn = $this->raiseErrorFn) $fn($this->dbtype, 'EXECUTE', $this->ErrorNo(), $this->ErrorMsg(), $this->sql, $inputarr, $this); return $false; } if ($resultId === true) { // return simplified recordset for inserts/updates/deletes with lower overhead $recordset = new ADORecordSet_empty(); return $recordset; } $resultset_name = $this->last_module_name . "_ResultSet"; $recordset = new $resultset_name( $resultId, $this->connectionId ); $recordset->_currentRow = 0; if (EW_USE_MYSQLI) { switch ($ADODB_FETCH_MODE) { case ADODB_FETCH_NUM: $recordset->fetchMode = MYSQLI_NUM; break; case ADODB_FETCH_ASSOC:$recordset->fetchMode = MYSQLI_ASSOC; break; default: case ADODB_FETCH_DEFAULT: case ADODB_FETCH_BOTH:$recordset->fetchMode = MYSQLI_BOTH; break; } } else { switch ($ADODB_FETCH_MODE) { case ADODB_FETCH_NUM: $recordset->fetchMode = MYSQL_NUM; break; case ADODB_FETCH_ASSOC:$recordset->fetchMode = MYSQL_ASSOC; break; default: case ADODB_FETCH_DEFAULT: case ADODB_FETCH_BOTH:$recordset->fetchMode = MYSQL_BOTH; break; } } if (EW_USE_MYSQLI) { $recordset->_numOfRows = @mysqli_num_rows( $resultId ); } else { $recordset->_numOfRows = @mysql_num_rows( $resultId ); } if( $recordset->_numOfRows == 0) { $recordset->EOF = true; } if (EW_USE_MYSQLI) { $recordset->_numOfFields = @mysqli_num_fields( $resultId ); } else { $recordset->_numOfFields = @mysql_num_fields( $resultId ); } $recordset->_fetch(); return $recordset; } } class mysqlt_driver_ResultSet { var $connectionId; var $fields; var $resultId; var $_currentRow = 0; var $_numOfRows = -1; var $_numOfFields = -1; var $fetchMode; var $EOF; /** * mysqlResultSet Constructor * * @access private * @param string $record * @param string $resultId */ function mysqlt_driver_ResultSet( $resultId, $connectionId ) { $this->fields = array(); $this->connectionId = $connectionId; $this->record = array(); $this->resultId = $resultId; $this->EOF = false; } /** * Frees resultset * * @access public */ function Close() { if (EW_USE_MYSQLI) { @mysqli_free_result( $this->resultId ); } else { @mysql_free_result( $this->resultId ); } $this->fields = array(); $this->resultId = false; } /** * Returns field name from select query * * @access public * @param string $field * @return string Field name */ function fields( $field ) { if(empty($field)) { return $this->fields; } else { return $this->fields[$field]; } } /** * Returns numrows from select query * * @access public * @return integer Numrows */ function RecordCount() { return $this->_numOfRows; } /** * Returns num of fields from select query * * @access public * @return integer numfields */ function FieldCount() { return $this->_numOfFields; } /** * Returns next record * * @access public */ function MoveNext() { if (EW_USE_MYSQLI) { $this->fields = @mysqli_fetch_array($this->resultId,$this->fetchMode); } else { $this->fields = @mysql_fetch_array($this->resultId, $this->fetchMode); } if ($this->fields) { $this->_currentRow += 1; return true; } if (!$this->EOF) { $this->_currentRow += 1; $this->EOF = true; } return false; } /** * Move to the first row in the recordset. Many databases do NOT support this. * * @return true or false */ function MoveFirst() { if ($this->_currentRow == 0) return true; return $this->Move(0); } /** * Returns the Last Record * * @access public */ function MoveLast() { if ($this->EOF) return false; return $this->Move($this->_numOfRows - 1); } /** * Random access to a specific row in the recordset. Some databases do not support * access to previous rows in the databases (no scrolling backwards). * * @param rowNumber is the row to move to (0-based) * * @return true if there still rows available, or false if there are no more rows (EOF). */ function Move($rowNumber = 0) { if ($rowNumber == $this->_currentRow) return true; $this->EOF = false; if ($this->_numOfRows > 0){ if ($rowNumber >= $this->_numOfRows - 1){ $rowNumber = $this->_numOfRows - 1; } } if ($this->_seek($rowNumber)) { $this->_currentRow = $rowNumber; if ($this->_fetch()) { return true; } $this->fields = false; } $this->EOF = true; return false; } /** * Perform Seek to specific row * * @access private */ function _seek($row) { if ($this->_numOfRows == 0) return false; if (EW_USE_MYSQLI) { return @mysqli_data_seek($this->resultId,$row); } else { return @mysql_data_seek($this->resultId,$row); } } /** * Fills field array with first database element when query initially executed * * @access private */ function _fetch() { if (EW_USE_MYSQLI) { $this->fields = @mysqli_fetch_array($this->resultId,$this->fetchMode); } else { $this->fields = @mysql_fetch_array($this->resultId,$this->fetchMode); } return is_array($this->fields); } /** * Check to see if last record reached * * @access public */ function EOF() { if( $this->_currentRow < $this->_numOfRows) { return false; } else { $this->EOF = true; return true; } } /** * Returns All Records in an array * * @access public * @param [nRows] is the number of rows to return. -1 means every row. */ function &GetArray($nRows = -1) { $results = array(); $cnt = 0; while (!$this->EOF && $nRows != $cnt) { $results[] = $this->fields; $this->MoveNext(); $cnt++; } return $results; } function &GetRows($nRows = -1) { $arr =& $this->GetArray($nRows); return $arr; } function &GetAll($nRows = -1) { $arr =& $this->GetArray($nRows); return $arr; } /** * Fetch field information for a table. * * @return object containing the name, type and max_length */ function FetchField($fieldOffset = -1) { if (EW_USE_MYSQLI) { // $fieldOffset not supported by mysqli $fieldObject = @mysqli_fetch_field($this->resultId); } else { if ($fieldOffset != -1) { $fieldObject = @mysql_fetch_field($this->resultId, $fieldOffset); $fieldObject->max_length = @mysql_field_len($this->resultId,$fieldOffset); } else { $fieldObject = @mysql_fetch_field($this->resultId); $fieldObject->max_length = @mysql_field_len($this->resultId); } } return $fieldObject; } } ?>
xavierrivas/new
epcst/instructor/ewmysql50.php
PHP
gpl-2.0
23,968
package JTalk.util; public class CPLoginReq extends ClientPackage{ public int id; public String password; public int port; public CPLoginReq(int id, String password,int port){ super.type=1; this.id=id; this.password=password; this.port=port; }; }
zyclincoln/JTalk
src/JTalk/util/CPLoginReq.java
Java
gpl-2.0
261
<?php //Add Vendor if ( !empty($_POST['add_vendor']) && !empty($_POST['vname']) ) { $mysql_q="INSERT INTO vendors (vendor_id, vendor_name, vendor_phone, vendor_fax, vendor_email, vendor_details ) VALUES ( '', '".$_POST['vname']."', '".$_POST['vphone']."', '".$_POST['vfax']."', '".$_POST['vemail']."', '".$_POST['vdetail']."' )"; $dbhi->query($mysql_q); if ( $dbhi->affected_rows == 1 ) header("Location: " . $_SERVER['PHP_SELF'] . "?success=yes&message=Vendor Added"); else header("Location: " . $_SERVER['PHP_SELF'] . "?success=no&message=MYSQL ERR" . mysql_errno() ); } ?> <script> //Add Vendor popup $(function() { $( "#div_add_v" ).dialog( { autoOpen: false, height: 370, width: 500, modal: true, position: ['middle',20], close: function() { } }); }); $(document).on('click', '#b_add_v', function() { $('#div_add_v').dialog( "open" ); }); </script> <button style="margin: 10px; font-weight:bold; background-color:white;" id="b_add_v">Add Vendor</button> <div id="div_add_v" style='display:none' title="Add Vendor"> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <table> <tr> <td> <label for="vname">Vendor Name:</label> </td> <td> <input type=text name="vname" id="vname" size=30 required> </td> </tr> <tr> <td> <label for="vphone">Vendor Phone:</label> </td> <td> <input type=text name="vphone" id="vphone" size=30> </td> </tr> <tr> <td> <label for="vfax">Vendor Fax:</label> </td> <td> <input type=text name="vfax" id="vfax" size=30> </td> </tr> <tr> <td> <label for="vemail">Vendor Email:</label> </td> <td> <input type=text name="vemail" id="vemail" size=30> </td> </tr> <tr> <td> <label for="vdetail">Vendor Details:</label> </td> <td> <textarea name="vdetail" id="vdetail" rows=2 cols=24 ></textarea> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" name="add_vendor" value="Add Vendor" /> </td> </tr> </table> </form> </div>
kxr/stock3
include/add_vendor.php
PHP
gpl-2.0
2,210
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD 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. * OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file dropdown.cpp Implementation of the dropdown widget. */ #include "../stdafx.h" #include "../window_gui.h" #include "../string_func.h" #include "../strings_func.h" #include "../window_func.h" #include "dropdown_type.h" #include "dropdown_widget.h" void DropDownListItem::Draw(int left, int right, int top, int bottom, bool sel, int bg_colour) const { int c1 = _colour_gradient[bg_colour][3]; int c2 = _colour_gradient[bg_colour][7]; int mid = top + this->Height(0) / 2; GfxFillRect(left + 1, mid - 2, right - 1, mid - 2, c1); GfxFillRect(left + 1, mid - 1, right - 1, mid - 1, c2); } uint DropDownListStringItem::Width() const { char buffer[512]; GetString(buffer, this->String(), lastof(buffer)); return GetStringBoundingBox(buffer).width; } void DropDownListStringItem::Draw(int left, int right, int top, int bottom, bool sel, int bg_colour) const { DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, top, this->String(), sel ? TC_WHITE : TC_BLACK); } /** * Natural sorting comparator function for DropDownList::sort(). * @param first Left side of comparison. * @param second Right side of comparison. * @return true if \a first precedes \a second. * @warning All items in the list need to be derivates of DropDownListStringItem. */ /* static */ bool DropDownListStringItem::NatSortFunc(const DropDownListItem *first, const DropDownListItem *second) { char buffer1[512], buffer2[512]; GetString(buffer1, static_cast<const DropDownListStringItem*>(first)->String(), lastof(buffer1)); GetString(buffer2, static_cast<const DropDownListStringItem*>(second)->String(), lastof(buffer2)); return strnatcmp(buffer1, buffer2) < 0; } StringID DropDownListParamStringItem::String() const { for (uint i = 0; i < lengthof(this->decode_params); i++) SetDParam(i, this->decode_params[i]); return this->string; } StringID DropDownListCharStringItem::String() const { SetDParamStr(0, this->raw_string); return this->string; } /** * Delete all items of a drop down list and the list itself * @param list List to delete. */ static void DeleteDropDownList(DropDownList *list) { for (DropDownList::iterator it = list->begin(); it != list->end(); ++it) { DropDownListItem *item = *it; delete item; } delete list; } static const NWidgetPart _nested_dropdown_menu_widgets[] = { NWidget(NWID_HORIZONTAL), NWidget(WWT_PANEL, COLOUR_END, WID_DM_ITEMS), SetMinimalSize(1, 1), SetScrollbar(WID_DM_SCROLL), EndContainer(), NWidget(NWID_SELECTION, INVALID_COLOUR, WID_DM_SHOW_SCROLL), NWidget(NWID_VSCROLLBAR, COLOUR_END, WID_DM_SCROLL), EndContainer(), EndContainer(), }; const WindowDesc _dropdown_desc( WDP_MANUAL, 0, 0, WC_DROPDOWN_MENU, WC_NONE, 0, _nested_dropdown_menu_widgets, lengthof(_nested_dropdown_menu_widgets) ); /** Drop-down menu window */ struct DropdownWindow : Window { WindowClass parent_wnd_class; ///< Parent window class. WindowNumber parent_wnd_num; ///< Parent window number. byte parent_button; ///< Parent widget number where the window is dropped from. DropDownList *list; ///< List with dropdown menu items. int selected_index; ///< Index of the selected item in the list. byte click_delay; ///< Timer to delay selection. bool drag_mode; bool instant_close; ///< Close the window when the mouse button is raised. int scrolling; ///< If non-zero, auto-scroll the item list (one time). Point position; ///< Position of the topleft corner of the window. Scrollbar *vscroll; /** * Create a dropdown menu. * @param parent Parent window. * @param list Dropdown item list. * @param selected Index of the selected item in the list. * @param button Widget of the parent window doing the dropdown. * @param instant_close Close the window when the mouse button is raised. * @param position Topleft position of the dropdown menu window. * @param size Size of the dropdown menu window. * @param wi_colour Colour of the parent widget. * @param scroll Dropdown menu has a scrollbar. * @param widget Widgets of the dropdown menu window. */ DropdownWindow(Window *parent, DropDownList *list, int selected, int button, bool instant_close, const Point &position, const Dimension &size, Colours wi_colour, bool scroll) : Window() { this->position = position; this->CreateNestedTree(&_dropdown_desc); this->vscroll = this->GetScrollbar(WID_DM_SCROLL); uint items_width = size.width - (scroll ? NWidgetScrollbar::GetVerticalDimension().width : 0); NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_DM_ITEMS); nwi->SetMinimalSize(items_width, size.height + 4); nwi->colour = wi_colour; nwi = this->GetWidget<NWidgetCore>(WID_DM_SCROLL); nwi->colour = wi_colour; this->GetWidget<NWidgetStacked>(WID_DM_SHOW_SCROLL)->SetDisplayedPlane(scroll ? 0 : SZSP_NONE); this->FinishInitNested(&_dropdown_desc, 0); CLRBITS(this->flags, WF_WHITE_BORDER); /* Total length of list */ int list_height = 0; for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) { DropDownListItem *item = *it; list_height += item->Height(items_width); } /* Capacity is the average number of items visible */ this->vscroll->SetCapacity(size.height * (uint16)list->size() / list_height); this->vscroll->SetCount((uint16)list->size()); this->parent_wnd_class = parent->window_class; this->parent_wnd_num = parent->window_number; this->parent_button = button; this->list = list; this->selected_index = selected; this->click_delay = 0; this->drag_mode = true; this->instant_close = instant_close; } ~DropdownWindow() { Window *w2 = FindWindowById(this->parent_wnd_class, this->parent_wnd_num); if (w2 != NULL) { if (w2->nested_array != NULL) { NWidgetCore *nwi2 = w2->GetWidget<NWidgetCore>(this->parent_button); if (nwi2->type == NWID_BUTTON_DROPDOWN) { nwi2->disp_flags &= ~ND_DROPDOWN_ACTIVE; } else { w2->RaiseWidget(this->parent_button); } } else { w2->RaiseWidget(this->parent_button); } w2->SetWidgetDirty(this->parent_button); } DeleteDropDownList(this->list); } virtual Point OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number) { return this->position; } /** * Find the dropdown item under the cursor. * @param value [out] Selected item, if function returns \c true. * @return Cursor points to a dropdown item. */ bool GetDropDownItem(int &value) { if (GetWidgetFromPos(this, _cursor.pos.x - this->left, _cursor.pos.y - this->top) < 0) return false; NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_DM_ITEMS); int y = _cursor.pos.y - this->top - nwi->pos_y - 2; int width = nwi->current_x - 4; int pos = this->vscroll->GetPosition(); const DropDownList *list = this->list; for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) { /* Skip items that are scrolled up */ if (--pos >= 0) continue; const DropDownListItem *item = *it; int item_height = item->Height(width); if (y < item_height) { if (item->masked || !item->Selectable()) return false; value = item->result; return true; } y -= item_height; } return false; } virtual void DrawWidget(const Rect &r, int widget) const { if (widget != WID_DM_ITEMS) return; TextColour colour = (TextColour)this->GetWidget<NWidgetCore>(widget)->colour; int y = r.top + 2; int pos = this->vscroll->GetPosition(); for (DropDownList::const_iterator it = this->list->begin(); it != this->list->end(); ++it) { const DropDownListItem *item = *it; int item_height = item->Height(r.right - r.left + 1); /* Skip items that are scrolled up */ if (--pos >= 0) continue; if (y + item_height < r.bottom) { bool selected = (this->selected_index == item->result); if (selected) GfxFillRect(r.left + 2, y, r.right - 1, y + item_height - 1, PC_BLACK); item->Draw(r.left, r.right, y, y + item_height, selected, colour); if (item->masked) { GfxFillRect(r.left + 1, y, r.right - 1, y + item_height - 1, _colour_gradient[colour][5], FILLRECT_CHECKER); } } y += item_height; } } virtual void OnClick(Point pt, int widget, int click_count) { if (widget != WID_DM_ITEMS) return; int item; if (this->GetDropDownItem(item)) { this->click_delay = 4; this->selected_index = item; this->SetDirty(); } } virtual void OnTick() { if (this->scrolling != 0) { int pos = this->vscroll->GetPosition(); this->vscroll->UpdatePosition(this->scrolling); this->scrolling = 0; if (pos != this->vscroll->GetPosition()) { this->SetDirty(); } } } virtual void OnMouseLoop() { Window *w2 = FindWindowById(this->parent_wnd_class, this->parent_wnd_num); if (w2 == NULL) { delete this; return; } if (this->click_delay != 0 && --this->click_delay == 0) { /* Make the dropdown "invisible", so it doesn't affect new window placement. * Also mark it dirty in case the callback deals with the screen. (e.g. screenshots). */ this->window_class = WC_INVALID; this->SetDirty(); w2->OnDropdownSelect(this->parent_button, this->selected_index); delete this; return; } if (this->drag_mode) { int item; if (!_left_button_clicked) { this->drag_mode = false; if (!this->GetDropDownItem(item)) { if (this->instant_close) { /* Make the dropdown "invisible", so it doesn't affect new window placement. * Also mark it dirty in case the callback deals with the screen. (e.g. screenshots). */ this->window_class = WC_INVALID; this->SetDirty(); if (GetWidgetFromPos(w2, _cursor.pos.x - w2->left, _cursor.pos.y - w2->top) == this->parent_button) { /* Send event for selected option if we're still * on the parent button of the list. */ w2->OnDropdownSelect(this->parent_button, this->selected_index); } delete this; } return; } this->click_delay = 2; } else { if (_cursor.pos.y <= this->top + 2) { /* Cursor is above the list, set scroll up */ this->scrolling = -1; return; } else if (_cursor.pos.y >= this->top + this->height - 2) { /* Cursor is below list, set scroll down */ this->scrolling = 1; return; } if (!this->GetDropDownItem(item)) return; } if (this->selected_index != item) { this->selected_index = item; this->SetDirty(); } } } }; void ShowDropDownList(Window *w, DropDownList *list, int selected, int button, uint width, bool auto_width, bool instant_close) { DeleteWindowById(WC_DROPDOWN_MENU, 0); /* Our parent's button widget is used to determine where to place the drop * down list window. */ Rect wi_rect; Colours wi_colour; NWidgetCore *nwi = w->GetWidget<NWidgetCore>(button); wi_rect.left = nwi->pos_x; wi_rect.right = nwi->pos_x + nwi->current_x - 1; wi_rect.top = nwi->pos_y; wi_rect.bottom = nwi->pos_y + nwi->current_y - 1; wi_colour = nwi->colour; if (nwi->type == NWID_BUTTON_DROPDOWN) { nwi->disp_flags |= ND_DROPDOWN_ACTIVE; } else { w->LowerWidget(button); } w->SetWidgetDirty(button); /* The preferred position is just below the dropdown calling widget */ int top = w->top + wi_rect.bottom + 1; if (width == 0) width = wi_rect.right - wi_rect.left + 1; uint max_item_width = 0; if (auto_width) { /* Find the longest item in the list */ for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) { const DropDownListItem *item = *it; max_item_width = max(max_item_width, item->Width() + 5); } } /* Total length of list */ int list_height = 0; for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) { DropDownListItem *item = *it; list_height += item->Height(width); } /* Height of window visible */ int height = list_height; /* Check if the status bar is visible, as we don't want to draw over it */ int screen_bottom = GetMainViewBottom(); bool scroll = false; /* Check if the dropdown will fully fit below the widget */ if (top + height + 4 >= screen_bottom) { /* If not, check if it will fit above the widget */ if (w->top + wi_rect.top - height > GetMainViewTop()) { top = w->top + wi_rect.top - height - 4; } else { /* ... and lastly if it won't, enable the scroll bar and fit the * list in below the widget */ int avg_height = list_height / (int)list->size(); int rows = (screen_bottom - 4 - top) / avg_height; height = rows * avg_height; scroll = true; /* Add space for the scroll bar if we automatically determined * the width of the list. */ max_item_width += NWidgetScrollbar::GetVerticalDimension().width; } } if (auto_width) width = max(width, max_item_width); Point dw_pos = { w->left + (_current_text_dir == TD_RTL ? wi_rect.right + 1 - width : wi_rect.left), top}; Dimension dw_size = {width, height}; new DropdownWindow(w, list, selected, button, instant_close, dw_pos, dw_size, wi_colour, scroll); } /** * Show a dropdown menu window near a widget of the parent window. * The result code of the items is their index in the \a strings list. * @param w Parent window that wants the dropdown menu. * @param strings Menu list, end with #INVALID_STRING_ID * @param selected Index of initial selected item. * @param button Button widget number of the parent window \a w that wants the dropdown menu. * @param disabled_mask Bitmask for diabled items (items with their bit set are not copied to the dropdown list). * @param hidden_mask Bitmask for hidden items (items with their bit set are displayed, but not selectable in the dropdown list). * @param width Width of the dropdown menu. If \c 0, use the width of parent widget \a button. */ void ShowDropDownMenu(Window *w, const StringID *strings, int selected, int button, uint32 disabled_mask, uint32 hidden_mask, uint width) { DropDownList *list = new DropDownList(); for (uint i = 0; strings[i] != INVALID_STRING_ID; i++) { if (!HasBit(hidden_mask, i)) { list->push_back(new DropDownListStringItem(strings[i], i, HasBit(disabled_mask, i))); } } /* No entries in the list? */ if (list->size() == 0) { DeleteDropDownList(list); return; } ShowDropDownList(w, list, selected, button, width); } /** * Delete the drop-down menu from window \a pw * @param pw Parent window of the drop-down menu window * @return Parent widget number if the drop-down was found and closed, \c -1 if the window was not found. */ int HideDropDownMenu(Window *pw) { Window *w; FOR_ALL_WINDOWS_FROM_BACK(w) { if (w->window_class != WC_DROPDOWN_MENU) continue; DropdownWindow *dw = dynamic_cast<DropdownWindow*>(w); if (pw->window_class == dw->parent_wnd_class && pw->window_number == dw->parent_wnd_num) { int parent_button = dw->parent_button; delete dw; return parent_button; } } return -1; }
benjeffery/openttd
src/widgets/dropdown.cpp
C++
gpl-2.0
15,681
import codecs import collections import os import shutil from PyQt4 import QtCore, QtGui, QtSvg from Code.QT import Colocacion from Code.QT import Controles from Code.QT import FormLayout from Code.QT import Iconos from Code.QT import QTVarios from Code import TrListas from Code import VarGen from Code.Constantes import * class ConjuntoPiezas: def __init__(self, nombre): self.nombre = nombre self.dicPiezas = self.leePiezas(nombre) def leePiezas(self, nombre): try: dic = {} for pieza in "rnbqkpRNBQKP": fich = os.path.join("Pieces", nombre, "%s%s.svg" % ("w" if pieza.isupper() else "b", pieza.lower())) f = codecs.open(fich, "r", 'utf-8', 'ignore') qb = QtCore.QByteArray(f.read()) f.close() dic[pieza] = qb return dic except: return self.leePiezas("Cburnett") def render(self, pieza): return QtSvg.QSvgRenderer(self.dicPiezas[pieza]) def widget(self, pieza): w = QtSvg.QSvgWidget() w.load(self.dicPiezas[pieza]) return w def pixmap(self, pieza, tam=24): pm = QtGui.QPixmap(tam, tam) pm.fill(QtCore.Qt.transparent) render = self.render(pieza) painter = QtGui.QPainter() painter.begin(pm) render.render(painter) painter.end() return pm def label(self, owner, pieza, tam): pm = self.pixmap(pieza, tam) lb = Controles.LB(owner) lb.ponImagen(pm) lb.pieza = pieza lb.tam_pieza = tam return lb def change_label(self, lb, tam): if lb.tam_pieza <> tam: pm = self.pixmap(lb.pieza, tam) lb.ponImagen(pm) def icono(self, pieza): icon = QtGui.QIcon(self.pixmap(pieza, 32)) return icon def cursor(self, pieza): return QtGui.QCursor(self.pixmap(pieza)) class TodasPiezas: def __init__(self): self.dicConjuntos = {} def selecciona(self, nombre): if nombre in self.dicConjuntos: return self.dicConjuntos[nombre] else: return self.nuevo(nombre) def nuevo(self, nombre): self.dicConjuntos[nombre] = ConjuntoPiezas(nombre) return self.dicConjuntos[nombre] def icono(self, pieza, nombre): fich = os.path.join("Pieces", nombre, "%s%s.svg" % ("w" if pieza.isupper() else "b", pieza.lower())) f = codecs.open(fich, "r", 'utf-8', 'ignore') qb = QtCore.QByteArray(f.read()) f.close() pm = QtGui.QPixmap(32, 32) pm.fill(QtCore.Qt.transparent) render = QtSvg.QSvgRenderer(qb) painter = QtGui.QPainter() painter.begin(pm) render.render(painter) painter.end() icon = QtGui.QIcon(pm) return icon def iconoDefecto(self, pieza): return self.icono(pieza, "Cburnett") def saveAllPNG(self, nombre, px): for pieza in "pnbrqk": for color in "wb": fich = os.path.join("Pieces", nombre, "%s%s.svg" % (color, pieza)) f = codecs.open(fich, "r", 'utf-8', 'ignore') qb = QtCore.QByteArray(f.read()) f.close() pm = QtGui.QPixmap(px, px) pm.fill(QtCore.Qt.transparent) render = QtSvg.QSvgRenderer(qb) painter = QtGui.QPainter() painter.begin(pm) render.render(painter) painter.end() pm.save("IntFiles/Figs/%s%s.png" % (color, pieza), "PNG") HIDE, GREY, CHECKER, SHOW = range(4) class BlindfoldConfig: def __init__(self, nomPiezasOri, dicPiezas=None): self.nomPiezasOri = nomPiezasOri if dicPiezas is None: self.restore() else: self.dicPiezas = dicPiezas def ficheroBase(self, pz, siWhite): pz = pz.lower() if siWhite: pzT = pz.upper() else: pzT = pz tipo = self.dicPiezas[pzT] if tipo == SHOW: pz = ("w" if siWhite else "b") + pz return os.path.join("Pieces", self.nomPiezasOri, pz + ".svg") if tipo == HIDE: fich = "h" elif tipo == GREY: fich = "g" elif tipo == CHECKER: fich = "w" if siWhite else "b" return os.path.join("././IntFiles", "blind_%s.svg" % fich) def restore(self): self.dicPiezas = VarGen.configuracion.leeVariables("BLINDFOLD") if not self.dicPiezas: for pieza in "rnbqkpRNBQKP": self.dicPiezas[pieza] = HIDE def save(self): VarGen.configuracion.escVariables("BLINDFOLD", self.dicPiezas) class Blindfold(ConjuntoPiezas): def __init__(self, nomPiezasOri, tipo=kBlindfoldConfig): self.nombre = "BlindFold" self.carpetaBF = os.path.join(VarGen.configuracion.carpeta, "BlindFoldPieces") self.carpetaPZ = "./IntFiles" self.tipo = tipo self.reset(nomPiezasOri) def leePiezas(self, nombre=None): # nombre usado por compatibilidad dic = {} for pieza in "rnbqkpRNBQKP": fich = os.path.join(self.carpetaBF, "%s%s.svg" % ("w" if pieza.isupper() else "b", pieza.lower())) f = codecs.open(fich, "r", 'utf-8', 'ignore') qb = QtCore.QByteArray(f.read()) f.close() dic[pieza] = qb return dic def reset(self, nomPiezasOri): if self.tipo == kBlindfoldConfig: dicTPiezas = None else: w = b = HIDE if self.tipo == kBlindfoldWhite: b = SHOW elif self.tipo == kBlindfoldBlack: w = SHOW dicTPiezas = {} for pieza in "rnbqkp": dicTPiezas[pieza] = b dicTPiezas[pieza.upper()] = w self.configBF = BlindfoldConfig(nomPiezasOri, dicPiezas=dicTPiezas) if not os.path.isdir(self.carpetaBF): os.mkdir(self.carpetaBF) for siWhite in (True, False): for pieza in "rnbqkp": ori = self.configBF.ficheroBase(pieza, siWhite) bs = "w" if siWhite else "b" dest = os.path.join(self.carpetaBF, "%s%s.svg" % (bs, pieza)) shutil.copy(ori, dest) self.dicPiezas = self.leePiezas() class WBlindfold(QTVarios.WDialogo): def __init__(self, owner, nomPiezasOri): titulo = _("Blindfold") + " - " + _("Configuration") icono = Iconos.Ojo() extparam = "wblindfold" QTVarios.WDialogo.__init__(self, owner, titulo, icono, extparam) self.config = BlindfoldConfig(nomPiezasOri) self.nomPiezasOri = nomPiezasOri lbWhite = Controles.LB(self, _("White")).ponTipoLetra(peso=75, puntos=10) lbBlack = Controles.LB(self, _("Black")).ponTipoLetra(peso=75, puntos=10) self.dicWidgets = collections.OrderedDict() self.dicImgs = {} liOpciones = ( (_("Hide"), HIDE), (_("Green"), GREY), (_("Checker"), CHECKER), (_("Show"), SHOW), ) dicNomPiezas = TrListas.dicNomPiezas() def haz(pz): tpW = self.config.dicPiezas[pz.upper()] tpB = self.config.dicPiezas[pz] lbPZw = Controles.LB(self) cbPZw = Controles.CB(self, liOpciones, tpW).capturaCambiado(self.reset) lbPZ = Controles.LB(self, dicNomPiezas[pz.upper()]).ponTipoLetra(peso=75, puntos=10) lbPZb = Controles.LB(self) cbPZb = Controles.CB(self, liOpciones, tpB).capturaCambiado(self.reset) self.dicWidgets[pz] = [lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, None, None] for pz in "kqrbnp": haz(pz) btAllW = Controles.PB(self, _("All White"), self.allWhite, plano=False) self.cbAll = Controles.CB(self, liOpciones, HIDE) btAllB = Controles.PB(self, _("All Black"), self.allBlack, plano=False) btSwap = Controles.PB(self, _("Swap"), self.swap, plano=False) liAcciones = ((_("Save"), Iconos.Grabar(), "grabar"), None, (_("Cancel"), Iconos.Cancelar(), "cancelar"), None, (_("Configurations"), Iconos.Opciones(), "configurations"), None, ) tb = Controles.TB(self, liAcciones) ly = Colocacion.G() ly.controlc(lbWhite, 0, 1).controlc(lbBlack, 0, 3) fila = 1 for pz in "kqrbnp": lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, tipoW, tipoB = self.dicWidgets[pz] ly.control(cbPZw, fila, 0) ly.controlc(lbPZw, fila, 1) ly.controlc(lbPZ, fila, 2) ly.controlc(lbPZb, fila, 3) ly.control(cbPZb, fila, 4) fila += 1 ly.filaVacia(fila, 20) fila += 1 ly.controld(btAllW, fila, 0, 1, 2) ly.control(self.cbAll, fila, 2) ly.control(btAllB, fila, 3, 1, 2) ly.controlc(btSwap, fila + 1, 0, 1, 5) ly.margen(20) layout = Colocacion.V().control(tb).otro(ly) self.setLayout(layout) self.reset() def procesarTB(self): getattr(self, self.sender().clave)() def closeEvent(self): self.guardarVideo() def grabar(self): self.guardarVideo() self.config.save() self.accept() def cancelar(self): self.guardarVideo() self.reject() def configurations(self): dic = VarGen.configuracion.leeVariables("BLINDFOLD") dicConf = collections.OrderedDict() for k in dic: if k.startswith("_"): cl = k[1:] dicConf[cl] = dic[k] menu = QTVarios.LCMenu(self) for k in dicConf: menu.opcion((True, k), k, Iconos.PuntoAzul()) menu.separador() menu.opcion((True, None), _("Save current configuration"), Iconos.PuntoVerde()) if dicConf: menu.separador() menudel = menu.submenu(_("Remove"), Iconos.Delete()) for k in dicConf: menudel.opcion((False, k), k, Iconos.PuntoNegro()) resp = menu.lanza() if resp is None: return si, cual = resp if si: if cual: dpz = dic["_" + cual] for pz in "kqrbnp": lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, tipoW, tipoB = self.dicWidgets[pz] cbPZw.ponValor(dpz[pz.upper()]) cbPZb.ponValor(dpz[pz]) self.reset() else: liGen = [(None, None)] liGen.append((_("Name") + ":", "")) resultado = FormLayout.fedit(liGen, title=_("Save current configuration"), parent=self, anchoMinimo=460, icon=Iconos.TutorialesCrear()) if resultado is None: return None accion, liResp = resultado name = liResp[0].strip() if not name: return None dic["_%s" % name] = self.config.dicPiezas VarGen.configuracion.escVariables("BLINDFOLD", dic) else: del dic["_%s" % cual] VarGen.configuracion.escVariables("BLINDFOLD", dic) def allWhite(self): tp = self.cbAll.valor() for pzB in "rnbqkp": lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, tipoW, tipoB = self.dicWidgets[pzB] cbPZw.ponValor(tp) self.reset() def allBlack(self): tp = self.cbAll.valor() for pzB in "rnbqkp": lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, tipoW, tipoB = self.dicWidgets[pzB] cbPZb.ponValor(tp) self.reset() def swap(self): for pzB in "rnbqkp": lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, tipoW, tipoB = self.dicWidgets[pzB] tpB = cbPZb.valor() tpW = cbPZw.valor() cbPZb.ponValor(tpW) cbPZw.ponValor(tpB) self.reset() def reset(self): for pzB in "kqrbnp": lbPZw, cbPZw, lbPZ, lbPZb, cbPZb, tipoW, tipoB = self.dicWidgets[pzB] tipoNv = cbPZw.valor() if tipoW != tipoNv: pzW = pzB.upper() self.config.dicPiezas[pzW] = tipoNv self.dicWidgets[pzB][5] = tipoNv # tiene que ser pzB que esta en misnusculas fich = self.config.ficheroBase(pzB, True) if fich in self.dicImgs: pm = self.dicImgs[fich] else: pm = QTVarios.fsvg2pm(fich, 32) self.dicImgs[fich] = pm lbPZw.ponImagen(pm) tipoNv = cbPZb.valor() if tipoB != tipoNv: self.config.dicPiezas[pzB] = tipoNv self.dicWidgets[pzB][6] = tipoNv fich = self.config.ficheroBase(pzB, False) if fich in self.dicImgs: pm = self.dicImgs[fich] else: pm = QTVarios.fsvg2pm(fich, 32) self.dicImgs[fich] = pm lbPZb.ponImagen(pm)
lukasmonk/lucaschess
Code/QT/Piezas.py
Python
gpl-2.0
13,281
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio 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. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from __future__ import absolute_import, print_function from datetime import date from invenio.base.i18n import _ from invenio.testsuite import make_test_suite, run_test_suite from flask import url_for from .helpers import DepositionTestCase class SimpleRecordTest(DepositionTestCase): def setUp(self): self.clear('simple') from invenio.modules.deposit.form import WebDepositForm from invenio.modules.deposit import fields from invenio.modules.deposit import field_widgets from invenio.modules.deposit.types import SimpleRecordDeposition class SimpleRecordTestForm(WebDepositForm): keywords = fields.DynamicFieldList( fields.TextField( widget_classes='form-control', widget=field_widgets.ColumnInput(class_="col-xs-10"), ), label='Keywords', add_label='Add another keyword', icon='fa fa-tags fa-fw', widget_classes='', min_entries=1, ) publication_date = fields.Date( label=_('Publication date'), icon='fa fa-calendar fa-fw', description='Required. Format: YYYY-MM-DD.', default=date.today(), validators=[], widget=field_widgets.date_widget, widget_classes='input-sm', export_key='imprint.date', ) class simple(SimpleRecordDeposition): name = "Simple Test" name_plural = "Simple Tests" group = "Tests" draft_definitions = { 'default': SimpleRecordTestForm, } @classmethod def process_sip_metadata(cls, deposition, metadata): self.assert_process_metadata(deposition, metadata) self.register(simple) def tearDown(self): self.unregister() def assert_process_metadata(self, deposition, metadata): pass def test_registration(self): self.assert401(self.client.get(url_for('webdeposit.index'), follow_redirects=True)) self.login("admin", "") res = self.client.get(url_for('webdeposit.index')) self.assert200(res) assert "Tests" in res.data assert "Simple Test" in res.data self.assert200(self.client.get(url_for( 'webdeposit.deposition_type_index', deposition_type='simple' ))) def test_create_delete(self): self.login("admin", "") dep_id = self.create('simple') self.assert200(self.client.get(url_for( 'webdeposit.run', deposition_type='simple', uuid=dep_id ))) self.assert200(self.client.get( url_for('webdeposit.delete', deposition_type='simple', uuid=dep_id), follow_redirects=True) ) TEST_SUITE = make_test_suite( SimpleRecordTest, ) if __name__ == "__main__": run_test_suite(TEST_SUITE)
MSusik/invenio
invenio/modules/deposit/testsuite/test_type_simplerecord.py
Python
gpl-2.0
3,865
/* * Movable Type (r) Open Source (C) 2001-2012 Six Apart, Ltd. * This program is distributed under the terms of the * GNU General Public License, version 2. * * $Id$ */ ;(function($) { var ES = MT.App.EditorStrategy; ES.Multi = function() { ES.apply(this, arguments) }; $.extend(ES.Multi.prototype, ES.prototype, { create: function(app, ids, format) { app.editors = {}; $.each(ids, function() { $('#' + this).show(); app.editors[this] = new MT.EditorManager(this, { format: format, wrap: true }); var setFormat = app.editors[this]['setFormat']; app.editors[this]['setFormat'] = function(format) { $.each(app.editors, function() { setFormat.apply(this, [format]); }); }; }); }, set: function(app, id) { var strategy = this; if (app.editor) { var height = app.editor.getHeight(); strategy._setWithHeight(app, id, height); } else { strategy._setWithHeight(app, id, null); } }, _setWithHeight: function(app, id, height) { $(app.editorIds).each(function() { if (id == this) { app.editors[this].show(); app.editor = app.editors[this]; if (height) { app.editor.setHeight(height); } } else { app.editors[this].hide(); } }); }, save: function() { app.editor.save(); } }); })(jQuery);
rosiro/MovableTypeOpenSource-5.2.2-yamucha
mt-static/js/editor/app/editor_strategy/multi.js
JavaScript
gpl-2.0
1,649
package graph; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import game.Graph; import org.junit.Test; public class GraphTest { @Test /** * Test que comprueba el correcto funcionamiento del método existNode de la clase Graph */ public void existNodeTest() { Graph<Integer> g = new Graph<Integer>(3); g.addNode(2); // Pruebas Positivas assertEquals(true, g.existNode(2)); // Pruebas Negativas assertEquals(false, g.existNode(5)); assertEquals(false, g.existNode(null)); } @Test /** * Test que comprueba el correcto funcionamiento del método getEdge de la clase Graph */ public void getEdgeTest() { Graph<Integer> g = new Graph<Integer>(4); g.addNode(1); g.addNode(2); g.addNode(3); g.addNode(4); g.addEdge(1, 2, 10); g.addEdge(1, 3, -2); // Pruebas Positivas assertEquals(10, g.getEdge(1, 2), 0.01); assertEquals(-2, g.getEdge(1, 3), 0.01); // Pruebas Negativas assertEquals(-1, g.getEdge(3, 4), 0.01); assertEquals(-1, g.getEdge(1, null), 0.01); assertEquals(-1, g.getEdge(null, 2), 0.01); } @Test /** * Test que comprueba el correcto funcionamiento del método addNode de la clase Graph */ public void addNodeTest() { Graph<Integer> g = new Graph<Integer>(3); // Prueba positiva assertEquals(0, g.addNode(1)); // Pruebas negativa de que si añado un nodo ya existente no lo añade g.addNode(2); assertEquals(-1, g.addNode(2)); // Prueba negativa de que si añado un nodo null no se añade assertEquals(-1, g.addNode(null)); // Prueba negativa de que si intento añadir un nodo cuando el array est� // lleno no se añade g.addNode(3); assertEquals(-1, g.addNode(4)); } @Test /** * Test que comprueba el correcto funcionamiento del método removeNode de la clase Graph */ public void removeNodeTest() { Graph<Integer> g = new Graph<Integer>(3); g.addNode(1); // Prueba positiva assertEquals(0, g.removeNode(1)); // Pruebas negativas assertEquals(-1, g.removeNode(2)); assertEquals(-1, g.removeNode(null)); } @Test /** * Test que comprueba el correcto funcionamiento del método addEdge de la clase Graph */ public void addEdgeTest() { Graph<Integer> g = new Graph<Integer>(3); g.addNode(1); g.addNode(2); g.addNode(3); // Prueba positiva assertEquals(0, g.addEdge(1, 2, 2)); assertEquals(0, g.addEdge(1, 2, 4)); assertEquals(0, g.addEdge(1, 3, -2)); // Pruebas negativas assertEquals(-1, g.addEdge(1, null, 2)); assertEquals(-1, g.addEdge(null, 2, 2)); assertEquals(-1, g.addEdge(4, 5, 2)); } @Test /** * Test que comprueba el correcto funcionamiento del método removeEdge de la clase Graph */ public void removeEdgeTest() { Graph<Integer> g = new Graph<Integer>(3); g.addNode(1); g.addNode(2); g.addNode(3); g.addEdge(1, 2, 4); // Prueba positiva assertEquals(0, g.removeEdge(1, 2)); // Prueba negativa assertEquals(-1, g.removeEdge(1, null)); assertEquals(-1, g.removeEdge(null, 2)); assertEquals(-1, g.removeEdge(4, 5)); assertEquals(-1, g.removeEdge(2, 3)); } @Test /** * Test que comprueba el correcto funcionamiento del método recorridoProfundidad de la clase Graph */ public void recorridoProfunidadTest() { // Prueba 1 Graph<String> g = new Graph<String>(4); g.addNode("A"); g.addNode("B"); g.addNode("C"); g.addNode("D"); g.addEdge("A", "B", 1); g.addEdge("A", "C", 5); g.addEdge("B", "C", 2); g.addEdge("B", "D", 3); g.addEdge("D", "A", 4); assertEquals(0, g.recorridoProfundidad("A")); assertEquals(0, g.recorridoProfundidad("B")); assertEquals(-1, g.recorridoProfundidad("C")); assertEquals(0, g.recorridoProfundidad("D")); // Prueba negativa assertEquals(-1, g.recorridoProfundidad(null)); } @Test /** * Test que comprueba el correcto funcionamiento del método dijkstra de la clase Graph */ public void dijkstraTest() { // Prueba 1 Graph<String> g = new Graph<String>(4); g.addNode("A"); g.addNode("B"); g.addNode("C"); g.addNode("D"); g.addEdge("A", "B", 1); g.addEdge("A", "C", 5); g.addEdge("B", "C", 2); g.addEdge("B", "D", 3); g.addEdge("D", "A", 4); assertArrayEquals(new double[] { 0.0, 1.0, 3.0, 4.0 }, g.dijkstra("A"), 0.01); // Prueba 2 Graph<Integer> g2 = new Graph<Integer>(6); g2.addNode(1); g2.addNode(2); g2.addNode(3); g2.addNode(4); g2.addNode(5); g2.addNode(6); g2.addEdge(1, 2, 3); g2.addEdge(1, 3, 4); g2.addEdge(1, 5, 8); g2.addEdge(2, 5, 5); g2.addEdge(3, 5, 3); g2.addEdge(5, 6, 3); g2.addEdge(5, 4, 7); g2.addEdge(6, 4, 2); assertArrayEquals(new double[] { 0.0, 3.0, 4.0, 12.0, 7.0, 10.0 }, g2.dijkstra(1), 0.01); } @Test /** * Test que comprueba el correcto funcionamiento del método floyd de la clase Graph */ public void floydTest() { Graph<String> g = new Graph<String>(4); g.addNode("A"); g.addNode("B"); g.addNode("C"); g.addNode("D"); g.addEdge("A", "B", 1.0); g.addEdge("B", "C", 2.0); g.addEdge("C", "D", 3.0); g.addEdge("A", "D", 10.0); assertArrayEquals(new int[][] { { -1, -1, 1, 2 }, { -1, -1, -1, 2 }, { -1, -1, -1, -1 }, { -1, -1, -1, -1 } }, g.floyd()); // Prueba negativa 1. Hay alguna arista con peso negativo en el grafo Graph<Integer> g2 = new Graph<Integer>(3); g2.addNode(1); g2.addNode(2); g2.addNode(3); g2.addEdge(1, 2, 2.0); g2.addEdge(2, 3, -2.0); assertNull(g2.floyd()); // Prueba negativa 2. No hay nodos en el grafo Graph<Integer> g3 = new Graph<Integer>(3); assertNull(g3.floyd()); } @Test /** * Test que comprueba el correcto funcionamiento del método path de la clase Graph */ public void pathTest() { Graph<String> g = new Graph<String>(4); g.addNode("A"); g.addNode("B"); g.addNode("C"); g.addNode("D"); g.addEdge("A", "B", 1.0); g.addEdge("B", "C", 2.0); g.addEdge("C", "D", 3.0); g.addEdge("A", "D", 10.0); assertEquals(6.0, g.path("A", "D"), 0.01); assertEquals(0.0, g.path("A", "A"), 0.01); // Prueba negativa 1. Existen los nodos pasados por parámetro pero no // hay camino entre ellos Graph<String> g2 = new Graph<String>(4); g2.addNode("A"); g2.addNode("B"); g2.addNode("C"); g2.addNode("D"); g2.addEdge("A", "B", 1.0); g2.addEdge("C", "D", 2.0); assertEquals(-1.0, g2.path("A", "D"), 0.01); // Prueba negativa 2. No existen los dos nodos pasados por parámetro, o // uno de ellos assertEquals(-1.0, g2.path("X", "Y"), 0.01); assertEquals(-1.0, g2.path("A", null), 0.01); assertEquals(-1.0, g2.path(null, "B"), 0.01); // Prueba negativa 3. Hay alguna arista con peso negativo y por tanto no // podríamos utilizar el método floyd para calcular el path Graph<Integer> g3 = new Graph<Integer>(3); g3.addNode(1); g3.addNode(2); g3.addNode(3); g3.addEdge(1, 2, 2.0); g3.addEdge(2, 3, -2.0); assertEquals(-1.0, g3.path(1, 2), 0.01); } @Test /** * Test que comprueba el correcto funcionamiento del método excentricidad() de la clase Graph */ public void excentricidadTest() { Graph<String> g = new Graph<String>(4); g.addNode("A"); g.addNode("B"); g.addNode("C"); g.addNode("D"); g.addEdge("A", "B", 1.0); g.addEdge("B", "C", 2.0); g.addEdge("C", "D", 3.0); g.addEdge("A", "D", 10.0); assertEquals(Double.POSITIVE_INFINITY, g.excentricidad("A"), 0.01); assertEquals(Double.POSITIVE_INFINITY, g.excentricidad("B"), 0.01); assertEquals(Double.POSITIVE_INFINITY, g.excentricidad("C"), 0.01); assertEquals(6.0, g.excentricidad("D"), 0.01); // Prueba negativa assertEquals(-1.0, g.excentricidad("X"), 0.01); } }
Arquisoft/Trivial3b
play-core/test/graph/GraphTest.java
Java
gpl-2.0
9,014
<?php /** * @file */ namespace Xylemical\Expressions; use PHPUnit\Framework\TestCase; class OperatorTest extends TestCase { public function testInvalidOperands() { $operator = new Operator('', 0, 0, 3, 'is_bool'); $this->expectException('Xylemical\\Expressions\\ExpressionException'); $operator->evaluate([], new Context, new Token('')); } }
smartcitiescommunity/Civikmind
plugins/formcreator/vendor/xylemical/php-expressions/tests/OperatorTest.php
PHP
gpl-2.0
386
<?php namespace Octane\Tests\ExistingSite; use weitzman\DrupalTestTraits\ExistingSiteBase; /** * This class can be extended or modified for project-specific testing. * * Note that ExistingSite tests typically reside in the relevant custom modules: * * `src/modules/custom_module_core/tests/src/ExistingSite` * * This base class, and the other tests here are meant to be used as starting * points and examples. */ abstract class OctaneExistingSiteTestBase extends ExistingSiteBase { }
phase2/octane
test/src/ExistingSite/OctaneExistingSiteTestBase.php
PHP
gpl-2.0
498
<?php //Create an Array for storing the dates that have events $dates_with_events = array(); //Grab posts (endpoints) $lcccevents = ''; $stockerevents = ''; $athleticevents = ''; $sportevents = ''; $categoryevents = ''; $domain = 'http://www.lorainccc.edu'; //$domain = 'http://' . $_SERVER['SERVER_NAME']; $lcccevents = new Endpoint( $domain . '/mylccc/wp-json/wp/v2/lccc_events/?per_page=100' ); $athleticevents = new Endpoint( $domain . '/athletics/wp-json/wp/v2/lccc_events/?per_page=100' ); $stockerevents = new Endpoint( 'http://sites.lorainccc.edu/stocker/wp-json/wp/v2/lccc_events/?per_page=100' ); //Create instance $multi = new MultiBlog( 1 ); $multi->add_endpoint ( $lcccevents ); $multi->add_endpoint ( $athleticevents ); $multi->add_endpoint ( $stockerevents ); //Fetch Posts(Events) from Endpoints $posts = $multi->get_posts(); if(empty($posts)){ echo 'No Posts Found!'; } //establishing current date for testing $currentdate = date("Y-m-d"); //Filling array with dates with events foreach ( $posts as $post ){ if( $post->event_end_date > $currentdate ){ array_push($dates_with_events, $post->event_end_date); } } $dates_with_events = array_unique($dates_with_events); $dates_with_events = array_filter($dates_with_events); $dates_with_events = array_values($dates_with_events); //echo '<br />'; //echo '<br />'; //echo 'Count: '.count($dates_with_events).'<br />'; //echo 'Without Empty: '.count($dates_with_events).'<br />'; //echo 'Events:'.'<br />'; /* for($y=0;$y < count($dates_with_events); $y++){ echo $y.': '.$dates_with_events[$y].'<br />'; } */ $current_month = date("n"); $current_year = date("Y"); $current_date = date("Y") . '-' . date("m") . '-' . date("d"); if(isset($_GET['disp_m'])){ $display_month = $_GET['disp_m']; $display_year = $_GET['disp_y']; } else { $display_month = $current_month; $display_year = $current_year; } $next_month = $display_month; $next_year = $display_year; $prev_month = $display_month; $prev_year = $display_year; if ($display_month == '12'){ $next_month = 1; $next_year = date("Y")+1; $prev_month -=1; } elseif($display_month > '12'){ $next_month = 1; $next_year = date("Y")+1; $prev_month = 12; } elseif($display_month < '12'){ $next_month +=1; $prev_month -=1; if ($prev_month == 0){ $prev_month = 12; $prev_year -=1; } } //echo 'Current Month: ' . $current_month . ' - ' . $current_year . '<br /><br />'; //echo 'Display Month: ' . $display_month . ' - ' . $display_year . '<br /><br />'; //echo 'Next Month: ' . $next_month . ' - ' . $next_year . '<br/><br />'; //echo 'Prev Month: ' . $prev_month . ' - ' . $prev_year . '<br/><br />'; $calendar = '<div id="calendar">'; $headings = array('Sun','Mon','Tues','Wed','Thurs','Fri','Sat'); $calendar .= '<div class="week heading"><div class="day heading"><div class="heading-text">'.implode('</div></div><div class="day heading"><div class="heading-text">', $headings).'</div></div></div>'; $running_day = date('w',mktime(0,0,0,$display_month,1,$display_year)); $days_in_month = date('t',mktime(0,0,0,$display_month,1,$display_year)); $days_in_this_week = 1; $day_counter = 0; $dates_array = array(); $calendar.= '<div class="week">'; for($x = 0; $x < $running_day; $x++): $calendar.= '<div class="day-np">&nbsp;</div>'; $days_in_this_week++; endfor; for($list_day = 1; $list_day <= $days_in_month; $list_day++): // determine if day is single digit or two, and transform to two digits if (strlen($list_day) == 1){ $day_of_week = '0' . $list_day; }else{ $day_of_week = $list_day; } // determine if month is single digit or two, and transform to two digits if (strlen($display_month) == 1){ $full_month = '0' . $display_month; }else{ $full_month = $display_month; } // fully formed date to match WordPress date variable $full_date = $display_year . '-' . $full_month . '-' . $day_of_week; if($full_date == $current_date){ $bol_valid = false; for($y=0;$y < count($dates_with_events); $y++){ if( $full_date == $dates_with_events[$y]){ $bol_valid = true; } } if($bol_valid == true){ $calendar.= '<a href="/mylccc/day?d='.$full_date.'">'; $calendar.= '<div class="day current-day">'; $calendar.= '<div class="day-number">'.$list_day.'</div>'; $calendar.= '<a class="calendar-event-listing" href="/mylccc/day?d='.$full_date.'"></a>'; $calendar.= '</div></a>'; } else{ $calendar.= '<div class="day current-day">'; $calendar.= '<div class="day-number">'.$list_day.'</div>'; $calendar.= '</div>'; } }else{ $bol_valid = false; for($y=0;$y < count($dates_with_events); $y++){ if( $full_date == $dates_with_events[$y]){ $bol_valid = true; } } if($bol_valid == true){ $calendar.= '<a style="display:block;" href="/mylccc/day?d='.$full_date.'">'; $calendar.= '<div class="day">'; $calendar.= '<div class="day-number">'.$list_day.'</div>'; $calendar.= '<a class="calendar-event-listing" href="/mylccc/day?d='.$full_date.'"></a>'; $calendar.= '</div></a>'; } else{ $calendar.= '<div class="day">'; $calendar.= '<div class="day-number">'.$list_day.'</div>'; $calendar.= '</div>'; } } if($running_day == 6): $calendar.= '</div>'; if(($day_counter+1) != $days_in_month): $calendar.= '<div class="week">'; endif; $running_day = -1; $days_in_this_week = 0; endif; $days_in_this_week++; $running_day++; $day_counter++; endfor; if($days_in_this_week < 8): for($x = 1; $x <= (8 - $days_in_this_week); $x++): $calendar.= '<div class="day-np">&nbsp;</div>'; endfor; endif; $plugin_image_dir = plugin_dir_url( 'lccc-news.php').'lccc-news/images/'; if ($prev_month < $current_month && $prev_year == $current_year){ echo '<div class="calendar-header">'; echo '<div class="header-placeholder">&nbsp;</div>'; echo '<div class="cur-month">' . date('F', mktime(0, 0, 0, $display_month, 10)) . ' ' . $display_year . '</div>'; echo '<div class="calendar-nav-next"><a href="?disp_m=' . $next_month . '&disp_y=' . $next_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Next-arrow.svg"></a></div></div><div style="clear:both;">'; echo '</div>'; }elseif($prev_month == $current_month && $prev_year == $current_year){ echo '<div class="calendar-header">'; echo '<div class="calendar-nav-prev"><a href="?disp_m=' . $prev_month . '&disp_y=' . $prev_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Prev-arrow.svg"></a></div>'; echo '<div class="cur-month">' . date('F', mktime(0, 0, 0, $display_month, 10)) . ' ' . $display_year . '</div>'; echo '<div class="calendar-nav-next"><a href="?disp_m=' . $next_month . '&disp_y=' . $next_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Next-arrow.svg"></a></div>'; echo '</div>'; echo '<div style="clear:both;"></div>'; }else{ echo '<div class="calendar-header">'; echo '<div class="calendar-nav-prev"><a href="?disp_m=' . $prev_month . '&disp_y=' . $prev_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Prev-arrow.svg"></a></div>'; echo '<div class="cur-month">' . date('F', mktime(0, 0, 0, $display_month, 10)) . ' ' . $display_year . '</div>'; echo '<div class="calendar-nav-next"><a href="?disp_m=' . $next_month . '&disp_y=' . $next_year . '"><img style="max-width:40%;" src="'.$plugin_image_dir.'Next-arrow.svg"></a></div>'; echo '</div>'; echo '<div style="clear:both;"></div>'; } echo $calendar; ?>
lorainccc/lccc-news
php/original-calendar-working.php
PHP
gpl-2.0
7,672
 namespace L2dotNET.GameService.model.skills2.speceffects { public class b_regen_mp_by_sit : TSpecEffect { public b_regen_mp_by_sit(double value) { this.value = value; } public override void OnStand(L2Player player) { if (mul) player.CharacterStat.URegMpMul -= value; else player.CharacterStat.SpecBonusRegMP -= value; } public override void OnSit(L2Player player) { if (mul) player.CharacterStat.URegMpMul += value; else player.CharacterStat.SpecBonusRegMP += value; } } }
domis045/L2dotNET
src/L2dotNET.Game/model/skills2/speceffects/b_regen_mp_by_sit.cs
C#
gpl-2.0
687
<?php /** * FW Gallery 3.0 * @copyright (C) 2014 Fastw3b * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.fastw3b.net/ Official website **/ defined( '_JEXEC' ) or die( 'Restricted access' ); JHTML :: _('behavior.framework', true); JHTML :: _('behavior.formvalidation'); JHTML :: script('administrator/components/com_fwgallery/assets/js/moorainbow.1.2b2.js'); JToolBarHelper :: title(JText::_('FWG_CONFIG').': <small><small>[ '.JText::_('FWG_EDIT').' ]</small></small>', 'fwgallery-config.png' ); JToolBarHelper::save(); JToolBarHelper::cancel(); $color = $this->obj->params->get('gallery_color'); if (preg_match('/[0-9a-fA-F]{3,6}/', $color)) $color = '#'.$color; else $color = ''; ?> <form action="index.php?option=com_fwgallery&amp;view=config" method="post" name="adminForm" id="adminForm" class="form-validate" enctype="multipart/form-data"> <div class="span6"> <fieldset class="adminform"> <legend><?php echo JText::_('FWG_IMAGE_SETTINGS'); ?></legend> <table class="admintable"> <tr> <td class="key"> <?php echo JText::_('FWG_THUMB_WIDTH'); ?> <span class="badge" title="<?php echo JText::_('FWG_TYPE_THE_WIDTH_FOR_THE_THUMBNAILS__THAT_WILL_SUIT_YOUR_NEEDS_MOST'); ?>">?</span><span class="badge badge-warning">*</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[im_th_w]" value="<?php echo $this->obj->params->get('im_th_w', 160); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_THUMB_HEIGHT'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_TYPE_THE_HEIGHT_FOR_THE_THUMBNAILS__THAT_WILL_SUIT_YOUR_NEEDS_MOST'); ?>">?</span>&nbsp;<span class="badge badge-warning">*</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[im_th_h]" value="<?php echo $this->obj->params->get('im_th_h', 120); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_MEDIUM_SIZE_WIDTH'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_THE_WIDTH_FOR_THE_MEDIUM_SIZE_IMAGE_DURING_FULL_SCREEN_VIEW'); ?>">?</span>&nbsp;<span class="badge badge-warning">*</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[im_mid_w]" value="<?php echo $this->obj->params->get('im_mid_w', 340); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_MEDIUM_SIZE_HEIGHT'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_THE_HEIGHT_FOR_THE_MEDIUM_SIZE_IMAGE_DURING_FULL_SCREEN_VIEW'); ?>">?</span>&nbsp;<span class="badge badge-warning">*</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[im_mid_h]" value="<?php echo $this->obj->params->get('im_mid_h', 255); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_BIG_SIZE_WIDTH'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_THE_PARAMETERS_OF_THE_IMAGE_FOR_LIGHTBOX_EFFECT_VIEW'); ?>">?</span>&nbsp;<span class="badge badge-warning">*</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[im_max_w]" value="<?php echo $this->obj->params->get('im_max_w', 800); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_BIG_SIZE_HEIGHT'); ?>&nbsp;<span class="badge" title=" title="<?php echo JText::_('FWG_THE_PARAMETERS_OF_THE_IMAGE_FOR_LIGHTBOX_EFFECT_VIEW'); ?>"">?</span>&nbsp;<span class="badge badge-warning">*</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[im_max_h]" value="<?php echo $this->obj->params->get('im_max_h', 600); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_THUMB_AND_MEDIUM_IMAGES_SHRINKING_METHOD'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'im_just_shrink', '', $this->obj->params->get('im_just_shrink'), JText :: _('FWG_JUST_SHRINK'), JText :: _('FWG_SHRINK_AND_CUT')); ?> </fieldset> </td> </tr> </table> </fieldset> <fieldset class="adminform"> <legend><?php echo JText::_('FWG_LAYOUT_SETTINGS'); ?></legend> <table class="admintable"> <tr> <td class="key"> <?php echo JText::_('FWG_GALLERIES_DEFAULT_COLOR'); ?>&nbsp;<span class="badge" title="<?php echo JText :: _('FWG_SELECT_ANY_COLOR_FROM_THE_COLOR_PALETTE_OR_JUST_TYPE_THE_COLOR__S_CODE__IF_YOU_KNOW_IT'); ?>">?</span> </td> <td id="color-row"<?php if ($color) { ?> style="background-color:<?php echo $color; ?>"<?php } ?>> <img id="myRainbow" src="<?php echo JURI :: root(true); ?>/administrator/components/com_fwgallery/assets/images/rainbow.png" alt="[r]" width="16" height="16" /> <input id="color" name="config[gallery_color]" type="text" size="13" value="<?php echo $color; ?>" /> <button type="button" id="myRainbowButton"><?php echo JText :: _('FWG_SELECT'); ?></button> <button type="button" id="myRainbowClearButton"><?php echo JText :: _('FWG_CLEAR'); ?></button> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_GALLERIES_IN_A_ROW'); ?> &nbsp;<span class="badge" title="<?php echo JText :: _('FWG_THE_NUMBER_DEPENDS_ON_THE_THUMB_SIZES_AND_THE_TEMPLATE_OF_YOUR_SITE__OBLIGATORY_FIELD'); ?>">?</span><span class="badge badge-warning">*</span> </td> <td> <?php echo JHTML :: _('select.genericlist', $this->columns, 'config[galleries_a_row]', '', 'id', 'name', $this->obj->params->get('galleries_a_row', 3)); ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_IMAGES_IN_A_ROW'); ?> &nbsp;<span class="badge" title="<?php echo JText :: _('FWG_THE_NUMBER_DEPENDS_ON_THE_THUMB_SIZES_AND_THE_TEMPLATE_OF_YOUR_SITE__OBLIGATORY_FIELD'); ?>">?</span><span class="badge badge-warning">*</span> </td> <td> <?php echo JHTML :: _('select.genericlist', $this->columns, 'config[images_a_row]', '', 'id', 'name', $this->obj->params->get('images_a_row', 3)); ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_GALLERIES_ROWS_PER_PAGE'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_TYPE_THE_NUMBER_OF_GALLERIES__YOU_WANT_TO_BE_DISPLAYED_PER_PAGE'); ?>">?</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[galleries_rows]" value="<?php echo $this->obj->params->get('galleries_rows', 4); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_IMAGES_ROWS_PER_PAGE'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_TYPE_THE_NUMBER_OF_IMAGES_YOU_WANT_TO_BE_DISPLAYED_PER_PAGE'); ?>">?</span> </td> <td> <input type="text" class="inputbox required validate-numeric" name="config[images_rows]" value="<?php echo $this->obj->params->get('images_rows', 4); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DEFAULT_GALLERIES_ORDERING'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SELECT_ONE_OF_THE_FOUR_GALLERIES___ORDER_TYPES__THIS_OPTION_IS_AVAILABLE_ON_FRONT_END_TOO'); ?>">?</span> </td> <td> <?php echo JHTML :: _('select.genericlist', array( JHTML :: _('select.option', 'name', JText :: _('FWG_ALPHABETICALLY'), 'id', 'name'), JHTML :: _('select.option', 'new', JText :: _('FWG_NEWEST_FIRST'), 'id', 'name'), JHTML :: _('select.option', 'old', JText :: _('FWG_OLDEST_FIRST'), 'id', 'name'), JHTML :: _('select.option', 'order', JText :: _('FWG_ORDERING'), 'id', 'name') ), 'config[ordering_galleries]', '', 'id', 'name', $this->obj->params->get('ordering_galleries', 'order')); ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DEFAULT_IMAGES_ORDERING'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SELECT_ONE_OF_THE_FOUR_POSSIBLE_TYPES_OF_ORDER_FOR_IMAGES__THE_OPTION_IS_AVAILABLE_ON_FRONT_END_TOO'); ?>">?</span> </td> <td> <?php echo JHTML :: _('select.genericlist', array( JHTML :: _('select.option', 'name', JText :: _('FWG_ALPHABETICALLY'), 'id', 'name'), JHTML :: _('select.option', 'new', JText :: _('FWG_NEWEST_FIRST'), 'id', 'name'), JHTML :: _('select.option', 'old', JText :: _('FWG_OLDEST_FIRST'), 'id', 'name'), JHTML :: _('select.option', 'order', JText :: _('FWG_ORDERING'), 'id', 'name'), JHTML :: _('select.option', 'voting', JText :: _('FWG_VOTING'), 'id', 'name') ), 'config[ordering_images]', '', 'id', 'name', $this->obj->params->get('ordering_images', 'order')); ?> </td> </tr> </table> </fieldset> <fieldset class="adminform"> <legend><?php echo JText::_('FWG_WATERMARK'); ?></legend> <table class="admintable"> <tr> <td class="key"> <?php echo JText::_('FWG_USE_WATERMARK'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__IF_YOU_DON__T_WANT_TO_USE_IT__THEN_SELECT__QUOT_NO_QUOT__HERE'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'use_watermark', '', $this->obj->params->get('use_watermark')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_WATERMARK_POSITION'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SELECT_ONE_OF_THE_5_POSSIBLE_LOCATIONS_OF_THE_WATERMARK_SIGN_ON_IMAGES'); ?>">?</span> </td> <td> <?php echo JHTML :: _('select.genericlist', array( JHTML :: _('select.option', 'center', JText :: _('FWG_CENTER'), 'id', 'name'), JHTML :: _('select.option', 'left top', JText :: _('FWG_LEFT_TOP'), 'id', 'name'), JHTML :: _('select.option', 'right top', JText :: _('FWG_RIGHT_TOP'), 'id', 'name'), JHTML :: _('select.option', 'left bottom', JText :: _('FWG_LEFT_BOTTOM'), 'id', 'name'), JHTML :: _('select.option', 'right bottom', JText :: _('FWG_RIGHT_BOTTOM'), 'id', 'name') ), 'config[watermark_position]', '', 'id', 'name', $this->obj->params->get('watermark_position', 'left bottom')); ?> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_WATERMARK_FILE'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_UPLOAD_A_FILE__THAT_WILL_BE_USED_AS_A_WATERMARK_ON_IMAGES'); ?>">?</span> </td> <td> <?php if ($this->obj->params->get('watermark_file')) { if ($path = JFHelper :: getWatermarkFilename()) { ?> <img src="<?php echo JURI :: root(true); ?>/<?php echo $path; ?>" /><br/> <input type="checkbox" name="delete_watermark" value="1" /> <?php echo JText :: _('FWG_REMOVE_WATERMARK'); ?><br/> <?php } else { ?> <p style="color:#f00;"><?php echo JText :: _('FWG_WATERMARK_FILE_NOT_FOUND_'); ?></p> <?php } } ?> <input id="watermark_file" type="file" class="inputbox" name="watermark_file" /> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_WATERMARK_TEXT'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_TYPE_A_TEXT__THAT_WILL_BE_USED_AS_A_WATERMARK__IF_YOU_UPLOAD_A_FILE__THEN_TEXT_WON__T_BE_DISPLAYED'); ?>">?</span> </td> <td> <input type="text" class="inputbox" name="config[watermark_text]" value="<?php echo $this->obj->params->get('watermark_text'); ?>" size="35"/> </td> </tr> </table> </fieldset> <fieldset class="adminform"> <legend><?php echo JText::_('FWG_VOTING_SYSTEM'); ?></legend> <table class="admintable"> <tr> <td class="key"> <?php echo JText::_('FWG_USE_VOTING'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT__IF_YOU_DON__T_WANT_TO_USE_VOTING_AT_ALL'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'use_voting', '', $this->obj->params->get('use_voting')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_PUBLIC_VOTING'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_LET_THE_VISITORS_PUBLIC_POLLS'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'public_voting', '', $this->obj->params->get('public_voting')); ?> </fieldset> </td> </tr> </table> </fieldset> </div> <div class="span6"> <fieldset class="adminform"> <legend><?php echo JText::_('FWG_DISPLAYING_SETTINGS'); ?></legend> <table class="admintable"> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_TOTAL_GALLERIES_COUNTER'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT___IF_YOU_WANT_TO_HIDE_IT'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_total_galleries', '', $this->obj->params->get('display_total_galleries')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_GALLERY_OWNER_NAME'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT___IF_YOU_WANT_TO_HIDE_IT'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_owner_gallery', '', $this->obj->params->get('display_owner_gallery')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_IMAGE_OWNER_NAME'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT___IF_YOU_WANT_TO_HIDE_IT'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_owner_image', '', $this->obj->params->get('display_owner_image')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_GALLERY_DATE'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_CREATION_DATE_OF_THE_GALLERY__BY_SELECTING_YES_NO'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_date_gallery', '', $this->obj->params->get('display_date_gallery')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_ORDER_BY_OPTION'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_YES_NO_OPTION__SELECT__QUOT_NO_QUOT___IF_YOU_WANT_TO_HIDE_IT_IN_THE_FRONT_END'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_gallery_sorting', '', $this->obj->params->get('display_gallery_sorting')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_GALLERY_NAME'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_NAME_OF_THE_GALLERY__CLICKING_YES_NO'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_name_gallery', '', $this->obj->params->get('display_name_gallery')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_IMAGE_NAME'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_NAME_OF_THE_IMAGES___ADDING_TO_THE_GALLERY__CLICKING_YES_NO'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_name_image', '', $this->obj->params->get('display_name_image')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_IMAGE_DATE'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_DATE_OF_THE_IMAGES___ADDING_TO_THE_GALLERY__CLICKING_YES_NO'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_date_image', '', $this->obj->params->get('display_date_image')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_IMAGE_VIEWS'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_THE_NUMBER_OF_IMAGE_VIEWS__SELECTING_YES_NO_OPTIONS'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_image_views', '', $this->obj->params->get('display_image_views')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_ALLOW_IMAGE_DOWNLOAD'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'allow_image_download', '', $this->obj->params->get('allow_image_download')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_IMAGE_TAGS'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_image_tags', '', $this->obj->params->get('display_image_tags')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_ALLOW_PRINT_BUTTON'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'allow_print_button', '', $this->obj->params->get('allow_print_button')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_HIDE_BOTTOM_IMAGES'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'hide_bottom_image', '', $this->obj->params->get('hide_bottom_image')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_USERS_COPYRIGHT'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SHOW_OR_HIDE_USERS_COPYRIGHT_SELECTING_YES_NO'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_user_copyright', '', $this->obj->params->get('display_user_copyright')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DATE_FORMAT'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_SET_A_SUITABLE_DATE_FORMAT_FOR_THE_FRONT_END__MONTH__DAY_AND_YEAR'); ?>">?</span> </td> <td> <input type="text" class="inputbox" name="config[date_format]" value="<?php echo $this->obj->params->get('date_format', '%B %d, %Y'); ?>" size="15"/> &nbsp;<a href="http://docs.joomla.org/How_do_you_change_the_date_format%3F" target="_blank"><?php echo JText::_('FWG_DATE_OPTIONS'); ?></a> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_ICON_NEW_DAYS'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_THE_NUMBER_OF_DAYS__WHEN_ADDED_IMAGE_WILL_HAVE_THE_ICON__QUOT_NEW_QUOT__IN_THE_LEFT_TOP'); ?>">?</span> </td> <td> <input type="text" class="inputbox" name="config[new_days]" value="<?php echo $this->obj->params->get('new_days', 7); ?>" size="5"/> </td> </tr> <tr> <td class="key"> <?php echo JText :: _('FWG_DISPLAY_LIGHTBOX_GALLERIES'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_galleries_lightbox', '', $this->obj->params->get('display_galleries_lightbox')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_HIDE_MIGNIFIER__LIGHTBOX_EFFECT_'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'hide_mignifier', '', $this->obj->params->get('hide_mignifier')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_HIDE_SINGLE_IMAGE_VIEW'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'hide_single_image_view', '', $this->obj->params->get('hide_single_image_view')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_HIDE_IPHONE_APP_PROMO'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'hide_iphone_app_promo', '', $this->obj->params->get('hide_iphone_app_promo')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_DISPLAY_SOCIAL_SHARING'); ?> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'display_social_sharing', '', $this->obj->params->get('display_social_sharing')); ?> </fieldset> </td> </tr> <tr> <td class="key"> <?php echo JText::_('FWG_HIDE_FASTW3B_COPYRIGHT'); ?>&nbsp;<span class="badge" title="<?php echo JText::_('FWG_IF_YOU_DON__T_WANT_TO_DISPLAY_FASTW3B_COPYRIGHT_ON_THE_FRONT_END_OF_YOUR_WEBSITE__THEN_SELECT__QUOT_NO_QUOT__HERE'); ?>">?</span> </td> <td> <fieldset class="radio btn-group"> <?php echo JHTML :: _('select.booleanlist', 'hide_fw_copyright', '', $this->obj->params->get('hide_fw_copyright')); ?> </fieldset> <div id="fw-copyright-donation" style="display:none"> <?php echo JText :: _('FWG_FWGALLERY_COPYRIGHT_HIDE'); ?> </div> </td> </tr> </table> </fieldset> <?php if ($this->plugins) { ?> <fieldset class="adminform"> <legend><?php echo JText::_('FWG_ADDITIONAL_SETTINGS'); ?></legend> <?php foreach ($this->plugins as $plugin) if ($plugin) { ?> <fieldset class="adminform"> <?php echo $plugin; ?> </fieldset> <?php } ?> </fieldset> <?php } ?> </div> <div style="clear:both;"></div> <input type="hidden" name="task" value="" /> </form> <script type="text/javascript"> var copyrightEff; var fwgRainbow; window.addEvent('domready', function() { document.getElement('#myRainbowButton').addEvent('click', function(ev) { document.getElement('#myRainbow').fireEvent('click', ev); }); document.getElement('#myRainbowClearButton').addEvent('click', function(ev) { document.getElement('#color').value = ''; document.getElement('#color-row').setStyle('background-color', ''); }); document.getElement('#color').addEvent('keyup', function() { if (this.value.match(/^#[0-9a-fA-F]{3,6}$/)) { document.getElement('#color-row').setStyle('background-color', this.value); fwgRainbow.manualSet(this.value, 'hex'); } else { document.getElement('#color-row').setStyle('background-color', ''); } }); fwgRainbow = new MooRainbow('myRainbow', { wheel: true, imgPath: '<?php echo JURI :: root(true); ?>/administrator/components/com_fwgallery/assets/images/', onChange: function(color) { document.getElement('#color').value = color.hex; document.getElement('#color-row').setStyle('background-color', color.hex); }, onComplete: function(color) { document.getElement('#color').value = color.hex; document.getElement('#color-row').setStyle('background-color', color.hex); } }); <?php if ($color) { ?> fwgRainbow.manualSet('<?php echo $color; ?>', 'hex'); <?php } ?> document.getElements('#adminForm input').each(function (el) { if (el.name == 'hide_fw_copyright') { el.addEvent('click', check_copyright); el.addEvent('change', check_copyright); } }); copyrightEff = new Fx.Slide(document.getElement('#fw-copyright-donation')); copyrightEff.hide(); document.getElement('#fw-copyright-donation').setStyle('display', ''); check_copyright(); }); function check_copyright() { document.getElements('#adminForm input').each(function (el) { if (el.name == 'hide_fw_copyright' && el.checked) { if (el.value == '0') copyrightEff.slideOut(); else copyrightEff.slideIn() } }); } Joomla.submitbutton = function(task) { if (task == 'save') { if (!document.formvalidator.isValid(document.getElement('#adminForm'))) { alert('<?php echo JText :: _('FWG_NOT_ALL_REQUIRED_FIELDS_PROPERLY_FILLED_IN'); ?>'); return; } if (document.getElement('#watermark_file') && document.getElement('#watermark_file').value && !document.getElement('#watermark_file').value.match(/\.png$/i)) { alert('<?php echo JText :: _('FWG_ALLOWED_PNG_AND_GIF_FILES_AS_WATERMARK_IMAGES_ONLY'); ?>'); return; } } document.getElement('#adminForm').task.value = task; document.getElement('#adminForm').submit(); } </script>
Jbouska419/craftsman
administrator/components/com_fwgallery/views/config/tmpl/edit.php
PHP
gpl-2.0
27,789
<?php /* * @version $Id: ruleticket.php 22657 2014-02-12 16:17:54Z moyo $ ------------------------------------------------------------------------- GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2003-2014 by the INDEPNET Development Team. http://indepnet.net/ http://glpi-project.org ------------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ include ('../inc/includes.php'); $rulecollection = new RuleTicketCollection($_SESSION['glpiactive_entity']); include (GLPI_ROOT . "/front/rule.common.php"); ?>
elitelinux/hack-space
php/front/ruleticket.php
PHP
gpl-2.0
1,285
<?php /** * Action functions * * Inject content through template hooks * */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly if ( ! function_exists( 'wolf_404_bg' ) ) { /** * Output 404 page background CSS in head * * @access public * @since 1.0.0 * @return void */ function wolf_404_bg() { if ( is_404() && wolf_get_theme_option( '404_bg' ) ) { ?> <style type="text/css"> .error404 #page-content{ background-image: url(<?php echo esc_url( wolf_get_url_from_attachment_id( wolf_get_theme_option( '404_bg' ), 'extra-large' ) ); ?>); } </style> <?php } } add_action( 'wp_head', 'wolf_404_bg' ); } if ( ! function_exists( 'wolf_scroll_arrow' ) ) { /** * Output scroll arrow * * @access public * @since 1.0.0 * @return void */ function wolf_scroll_arrow() { if ( ! is_404() ) ?> <div id="top"></div><a id="top-arrow" class="scroll" href="#top"></a> <?php } add_action( 'wolf_body_start', 'wolf_scroll_arrow' ); } if ( ! function_exists( 'wolf_page_loader' ) ) { /** * Output loader overlay * * @access public * @since 1.0.0 * @return void */ function wolf_page_loader() { if ( wolf_get_theme_option( 'page_transition' ) ) : $loader = wolf_get_theme_option( 'loader_type' ); ?> <div id="loading-overlay"><div id="loader"> <?php if ( wolf_get_theme_option( 'loading_logo' ) ) : ?> <img id="loading-logo" src="<?php echo esc_url( wolf_get_url_from_attachment_id( wolf_get_theme_option( 'loading_logo' ), 'logo' ) ); ?>" alt="loading-logo"> <?php endif; ?> <?php if ( wolf_get_theme_option( 'loader' ) ) : ?> <?php if ( 'loader1' == $loader ) : ?> <div class="loader1"></div> <?php elseif ( 'loader2' == $loader ) : ?> <div class="loader2"> <div class="loader2-double-bounce1"></div> <div class="loader2-double-bounce2"></div> </div> <?php elseif ( 'loader3' == $loader ) : ?> <div class="loader3"> <div class="loader3-rect1"></div> <div class="loader3-rect2"></div> <div class="loader3-rect3"></div> <div class="loader3-rect4"></div> <div class="loader3-rect5"></div> </div> <?php elseif ( 'loader4' == $loader ) : ?> <div class="loader4"> <div class="loader4-cube1"></div> <div class="loader4-cube2"></div> </div> <?php elseif ( 'loader5' == $loader ) : ?> <!-- <div class="loader5"></div> --> <div class="loading"> <div class="loading-bar"></div> <div class="loading-bar"></div> <div class="loading-bar"></div> <div class="loading-bar"></div> </div> <?php elseif ( 'loader6' == $loader ) : ?> <div class="loader6"> <div class="loader6-dot1"></div> <div class="loader6-dot2"></div> </div> <?php elseif ( 'loader7' == $loader ) : ?> <div class="loader7"> <div class="loader7-bounce1"></div> <div class="loader7-bounce2"></div> <div class="loader7-bounce3"></div> </div> <?php elseif ( 'loader8' == $loader ) : ?> <div class="loader8"> <div class="loader8-container loader8-container1"> <div class="loader8-circle1"></div> <div class="loader8-circle2"></div> <div class="loader8-circle3"></div> <div class="loader8-circle4"></div> </div> <div class="loader8-container loader8-container2"> <div class="loader8-circle1"></div> <div class="loader8-circle2"></div> <div class="loader8-circle3"></div> <div class="loader8-circle4"></div> </div> <div class="loader8-container loader8-container3"> <div class="loader8-circle1"></div> <div class="loader8-circle2"></div> <div class="loader8-circle3"></div> <div class="loader8-circle4"></div> </div> </div> <?php endif; ?> <?php endif; ?> </div></div> <?php endif; } add_action( 'wolf_body_start', 'wolf_page_loader' ); } if ( ! function_exists( 'wolf_top_search_form' ) ) { /** * Output search form * * @access public * @since 1.0.0 * @return void */ function wolf_top_search_form() { if ( wolf_get_theme_option( 'search_menu_item' ) ) { echo '<div id="top-search-form-container"><div id="top-search-form">'; get_search_form(); echo '</div></div>'; } } add_action( 'wolf_body_start', 'wolf_top_search_form' ); } if ( ! function_exists( 'wolf_output_message_bar' ) ) { /** * Output message bar plugin function * * @access public * @since 1.0.0 * @return void */ function wolf_output_message_bar() { if ( function_exists( 'wolf_message_bar' ) ) wolf_message_bar(); } add_action( 'wolf_body_start', 'wolf_output_message_bar' ); } if ( ! function_exists( 'wolf_output_top_bar' ) ) { /** * Output message bar plugin function * * @access public * @since 1.0.0 * @return void */ function wolf_output_top_bar() { if ( wolf_get_theme_option( 'top_bar' ) && 'left' != wolf_get_theme_option( 'menu_position' ) ) { get_template_part( 'partials/top', 'bar' ); } } add_action( 'wolf_body_start', 'wolf_output_top_bar' ); } if ( ! function_exists( 'wolf_main_menu' ) ) { /** * Output main menu * * @access public * @since 1.0.0 * @return void */ function wolf_main_menu() { if ( 'default' == wolf_get_theme_option( 'menu_position' ) || 'center' == wolf_get_theme_option( 'menu_position' ) ) { echo '<div id="ceiling">'; get_template_part( 'partials/navigation/navigation', 'desktop' ); echo '</div>'; } } add_action( 'wolf_body_start', 'wolf_main_menu' ); } if ( ! function_exists( 'wolf_main_menu_logo_centered' ) ) { /** * Output main menu * * @access public * @since 1.0.0 * @return void */ function wolf_main_menu_logo_centered() { if ( 'logo-centered' == wolf_get_theme_option( 'menu_position' ) ) { echo '<div id="ceiling">'; get_template_part( 'partials/navigation/navigation', 'logo-centered' ); echo '</div>'; } } add_action( 'wolf_body_start', 'wolf_main_menu_logo_centered' ); } if ( ! function_exists( 'wolf_left_main_menu' ) ) { /** * Output main menu * * @access public * @since 1.0.0 * @return void */ function wolf_left_main_menu() { if ( 'left' == wolf_get_theme_option( 'menu_position' ) ) get_template_part( 'partials/navigation/navigation', 'left' ); } add_action( 'wolf_site_content_start', 'wolf_left_main_menu' ); } if ( ! function_exists( 'wolf_output_mobile_hello_bar' ) ) { /** * Output mobile hello bar * * @access public * @since 1.0.0 * @return void */ function wolf_output_mobile_hello_bar() { if ( 'modern' != wolf_get_theme_option( 'menu_position' ) ) : ?> <div id="mobile-bar" class="clearfix"> <div id="mobile-bar-inner"> <div id="menu-toggle" class="menu-toggle"> <div class="burger-before"></div> <div class="burger"></div> <div class="burger-after"></div> </div> <?php echo wolf_logo(); ?> </div> </div> <?php endif; } add_action( 'wolf_body_start', 'wolf_output_mobile_hello_bar' ); } if ( ! function_exists( 'wolf_output_side_menu_toggle' ) ) { /** * Output Secondary Menu toggle * * @access public * @since 1.0.0 * @return void */ function wolf_output_side_menu_toggle() { $menus = array( 'default', 'center', 'logo-centered' ); if ( wolf_get_theme_option( 'additional_toggle_menu' ) && in_array( wolf_get_theme_option( 'menu_position' ), $menus ) ) : ?> <div id="side-menu-toggle" class="toggle-add-menu"><div class="plus"></div></div> <?php endif; } add_action( 'wolf_body_start', 'wolf_output_side_menu_toggle' ); } if ( ! function_exists( 'wolf_additional_menu' ) ) { /** * Output secondary menu * * @access public * @since 1.0.0 * @return void */ function wolf_additional_menu() { if ( wolf_get_theme_option( 'additional_toggle_menu' ) && ( 'default' == wolf_get_theme_option( 'menu_position' ) || 'center' == wolf_get_theme_option( 'menu_position' ) || 'logo-centered' == wolf_get_theme_option( 'menu_position' ) ) ) { if ( 'side' == wolf_get_theme_option( 'additional_toggle_menu_type' ) ) get_template_part( 'partials/navigation/navigation', 'side-panel' ); if ( 'overlay' == wolf_get_theme_option( 'additional_toggle_menu_type' ) ) get_template_part( 'partials/navigation/navigation', 'overlay' ); } } add_action( 'wolf_body_start', 'wolf_additional_menu' ); } if ( ! function_exists( 'wolf_mobile_menu' ) ) { /** * Output mobile menu * * @access public * @since 1.0.0 * @return void */ function wolf_mobile_menu() { if ( 'modern' != wolf_get_theme_option( 'menu_position' ) ) get_template_part( 'partials/navigation/navigation', 'mobile' ); } add_action( 'wolf_body_start', 'wolf_mobile_menu' ); } if ( ! function_exists( 'wolf_modern_menu_toggle' ) ) { /** * Output modern menu * * @access public * @since 1.0.0 * @return void */ function wolf_modern_menu_toggle() { if ( 'modern' == wolf_get_theme_option( 'menu_position' ) ) { ?> <div id="menu-toggle-modern" class="menu-toggle"> <div class="burger-before"></div> <div class="burger"></div> <div class="burger-after"></div> </div> <?php } } add_action( 'wolf_body_start', 'wolf_modern_menu_toggle' ); } if ( ! function_exists( 'wolf_modern_menu_overlay' ) ) { /** * Output modern menu overlay * * @access public * @since 1.0.0 * @return void */ function wolf_modern_menu_overlay() { if ( 'modern' == wolf_get_theme_option( 'menu_position' ) ) { ?> <div id="modern-menu-overlay"></div> <?php } } add_action( 'wolf_body_start', 'wolf_modern_menu_overlay' ); } if ( ! function_exists( 'wolf_modern_menu' ) ) { /** * Output modern menu * * @access public * @since 1.0.0 * @return void */ function wolf_modern_menu() { if ( 'modern' == wolf_get_theme_option( 'menu_position' ) ) get_template_part( 'partials/navigation/navigation', 'modern' ); } add_action( 'wolf_body_start', 'wolf_modern_menu' ); } if ( ! function_exists( 'wolf_cart_menu_item' ) ) { /** * Add a cart menu item * * @access public * @since 1.0.0 * @param * @return void */ function wolf_cart_menu_item ( $items, $args ) { if ( class_exists( 'WooCommerce' ) && function_exists( 'wc_get_page_id' ) ) { $cart_url = get_permalink( wc_get_page_id( 'cart' ) ); $woo_item = '<li class="cart-menu-item">'; $woo_item .= "<a class='cart-menu-item-link' href='$cart_url'>"; $woo_item .= '<span class="product-count">' . WC()->cart->cart_contents_count . '</span>'; $woo_item .= '<span class="cart-text">' . __( 'Cart', 'wolf' ) . '</span>'; $woo_item .= '</a>'; $woo_item .= '<span class="cart-menu-panel">'; $woo_item .= "<a href='$cart_url'>"; $woo_item .= '<span class="icon-cart"></span>'; $woo_item .= '<span class="panel-product-count">'; $woo_item .= sprintf( _n( '%d item', '%d items', WC()->cart->cart_contents_count, 'wolf' ), WC()->cart->cart_contents_count ); $woo_item .= '</span></br>'; // count $woo_item .= '<span class="panel-total">'; $woo_item .= __( 'Total', 'wolf' ) . ' ' . WC()->cart->get_cart_total(); $woo_item .= '</span>'; // total //' . __( 'Total', 'wolf' ) . ' ' . $total . ' $woo_item .= '</a>'; $woo_item .= '</span>'; $woo_item .= '</li>'; // var_dump( $woocommerce->cart ); if ( ( $args->theme_location == 'primary' || $args->theme_location == 'primary-right' ) && wolf_get_theme_option( 'cart_menu_item' ) ) { $items .= $woo_item; } } return $items; } add_filter( 'wp_nav_menu_items', 'wolf_cart_menu_item', 10, 2 ); } if ( ! function_exists( 'wolf_main_menu_socials' ) ) { /** * Output social icons in main menu * * @access public * @since 1.0.0 * @return void */ function wolf_main_menu_socials( $items, $args ) { $services = wolf_get_theme_option( 'menu_socials_services' ); $socials_item = ''; if ( $services ) { $socials_item = '<li class="socials-menu-item">'; $socials_item .= wolf_theme_socials( $services, '1x', 'span' ); $socials_item .= '</li>'; } if ( 'default' == wolf_get_theme_option( 'menu_position' ) || 'logo-centered' == wolf_get_theme_option( 'menu_position' ) ) { if ( $args->theme_location == 'primary' || $args->theme_location == 'primary-right' ) { $items .= $socials_item; } } return $items; } add_filter( 'wp_nav_menu_items', 'wolf_main_menu_socials', 10, 2 ); } if ( ! function_exists( 'wolf_search_menu_item' ) ) { /** * Add a search menu item * * @access public * @since 1.0.0 * @return void */ function wolf_search_menu_item( $items, $args ) { $search_item = '<li class="search-menu-item"> <a class="search-menu-item-link" href="#"> <span class="search-text">' . __( 'Search', 'wolf' ) . '</span></a></li>'; if ( ( $args->theme_location == 'primary' || $args->theme_location == 'primary-right' ) && wolf_get_theme_option( 'search_menu_item' ) ) { $items .= $search_item; } return $items; } add_filter( 'wp_nav_menu_items', 'wolf_search_menu_item', 10, 2 ); } if ( ! function_exists( 'wolf_toggle_menu_item' ) ) { /** * Add a toggle menu item */ function wolf_toggle_menu_item ( $items, $args ) { $menus = array( 'default', 'center', 'logo-centered' ); $toggle_text = wolf_get_theme_option( 'toggle_side_menu_item_text' ); $toggle_item = '<li class="toggle-menu-item"><a class="toggle-menu-item-link toggle-add-menu" href="#">'; if ( $toggle_text ) $toggle_item .= '<span class="toggle-text">' . $toggle_text . '</span>'; $toggle_item .= '</a></li>'; if ( ( $args->theme_location == 'primary' || $args->theme_location == 'primary-right' ) && wolf_get_theme_option( 'additional_toggle_menu' ) && in_array( wolf_get_theme_option( 'menu_position' ), $menus ) ) { $items .= $toggle_item; } return $items; } add_filter( 'wp_nav_menu_items', 'wolf_toggle_menu_item', 10, 2 ); } if ( ! function_exists( 'wolf_header_overlay' ) ) { /** * Output home header */ function wolf_header_overlay() { if ( ! wolf_is_slider_in_home_header() && 'wolf_slider' != wolf_get_theme_option( 'home_header_type' ) ) : ?> <div class="header-overlay"></div> <?php endif; } add_action( 'wolf_header_start', 'wolf_header_overlay' ); } if ( ! function_exists( 'wolf_home_header' ) ) { /** * Output home header */ function wolf_home_header() { if ( is_front_page() && ! is_paged() || is_page_template( 'page-templates/home.php' ) && 'none' != wolf_get_theme_option( 'home_header_type' ) ) get_template_part( 'partials/header', 'home' ); } add_action( 'wolf_header_start', 'wolf_home_header' ); } if ( ! function_exists( 'wolf_header_gallery_slideshow' ) ) { /** * Output header gallery slideshow */ function wolf_header_gallery_slideshow() { if ( is_single() && 'gallery' == get_post_format() ) { get_template_part( 'partials/slider', 'header-gallery' ); } } add_action( 'wolf_header_start', 'wolf_header_gallery_slideshow' ); } if ( ! function_exists( 'wolf_scroll_down_arrow' ) ) { /** * Output scroll down arrow */ function wolf_scroll_down_arrow() { if ( wolf_get_theme_option( 'scroll_down_arrow' ) ) { ?> <a id="scroll-down" class="scroll" href="#main"></a> <?php } } add_action( 'wolf_header_end', 'wolf_scroll_down_arrow' ); } if ( ! function_exists( 'wolf_share_links' ) ) { /** * Share links below single posts * * @param bool $display * @return string */ function wolf_share_links() { $post_type = get_post_type(); if ( wolf_get_theme_option( $post_type . '_share' ) ) { // is theme option checked get_template_part( 'partials/share', 'post' ); } } add_action( 'wolf_post_end_singular', 'wolf_share_links' ); } if ( ! function_exists( 'wolf_author_meta' ) ) { /** * Output author bio box */ function wolf_author_meta() { if ( wolf_get_theme_option( 'show_author_box' ) && 'post' == get_post_type() || 'review' == get_post_type() ) { get_template_part( 'partials/author', 'bio' ); } } add_action( 'wolf_post_end_singular', 'wolf_author_meta' ); } if ( ! function_exists( 'wolf_display_author_info_in_author_archive' ) ) { /** * Display the author info at the top of the author archive pages */ function wolf_display_author_info_in_author_archive() { if ( is_author() && wolf_get_theme_option( 'show_author_box' ) ) get_template_part( 'partials/author', 'bio' ); } add_action( 'wolf_page_before', 'wolf_display_author_info_in_author_archive' ); } if ( ! function_exists( 'wolf_output_music_network' ) ) { /** * Output music network icons */ // function wolf_output_music_network() { // if ( function_exists( 'wolf_music_network' ) ) { // if ( wolf_is_music_network() ) { // echo '<div class="music-social-icons-container">'; // wolf_music_network(); // echo '</div>'; // } // } // } add_action( 'wolf_footer_before', 'wolf_output_music_network' ); } if ( ! function_exists( 'wolf_bottom_menu' ) ) { /** * Output bottom menu */ function wolf_bottom_menu() { if ( has_nav_menu( 'tertiary' ) ) { ?> <nav id="site-navigation-tertiary" class="wrap navigation tertiary-navigation" role="navigation"> <?php wp_nav_menu( array( 'theme_location' => 'tertiary', 'menu_class' => 'nav-menu-tertiary inline-list', 'fallback_cb' => '', 'depth' => 1, ) ); ?> </nav><!-- #site-navigation-tertiary--> <?php } } add_action( 'wolf_footer_end', 'wolf_bottom_menu' ); } if ( ! function_exists( 'wolf_bottom_socials' ) ) { /** * Output social icons * * @access public * @since 1.0.0 * @return void */ function wolf_bottom_socials() { if ( wolf_get_theme_option( 'bottom_socials' ) ) { $services = wolf_get_theme_option( 'bottom_socials_services' ); echo wolf_theme_socials( $services, '1x' ); } } add_action( 'wolf_footer_end', 'wolf_bottom_socials' ); } if ( ! function_exists( 'wolf_output_pagination' ) ) { /** * Output pagination on blog page * * @access public * @since 1.0.0 * @return void */ function wolf_output_pagination() { if ( wolf_is_blog() ) { get_template_part( 'partials/pagination' ); } } add_action( 'wolf_page_after', 'wolf_output_pagination' ); } if ( ! function_exists( 'wolf_print_post_navigation' ) ) { /** * Output related post or post nav depending on metabox * * @access public * @since 1.0.0 * @return void */ function wolf_print_post_navigation() { $nav_type = wolf_get_single_blog_post_nav_type(); $post_types = array( 'post' ); if ( in_array( get_post_type(), $post_types ) ) { if ( 'related' == $nav_type ) { get_template_part( 'partials/related', 'posts' ); } else { wolf_post_nav(); } } } add_action( 'wolf_post_end', 'wolf_print_post_navigation' ); }
estrategasdigitales/dictobas
wp-content/themes/decibel/includes/actions.php
PHP
gpl-2.0
19,600
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ir.nikagram.messenger.support.widget; import static ir.nikagram.messenger.support.widget.RecyclerView.NO_POSITION; import android.content.Context; import android.graphics.PointF; import android.graphics.Rect; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.ViewCompat; import android.support.v4.view.accessibility.AccessibilityEventCompat; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.support.v4.view.accessibility.AccessibilityRecordCompat; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.List; /** * A LayoutManager that lays out children in a staggered grid formation. * It supports horizontal & vertical layout as well as an ability to layout children in reverse. * <p> * Staggered grids are likely to have gaps at the edges of the layout. To avoid these gaps, * StaggeredGridLayoutManager can offset spans independently or move items between spans. You can * control this behavior via {@link #setGapStrategy(int)}. */ public class StaggeredGridLayoutManager extends RecyclerView.LayoutManager { public static final String TAG = "StaggeredGridLayoutManager"; private static final boolean DEBUG = false; public static final int HORIZONTAL = OrientationHelper.HORIZONTAL; public static final int VERTICAL = OrientationHelper.VERTICAL; /** * Does not do anything to hide gaps. */ public static final int GAP_HANDLING_NONE = 0; @SuppressWarnings("unused") @Deprecated public static final int GAP_HANDLING_LAZY = 1; /** * When scroll state is changed to {@link RecyclerView#SCROLL_STATE_IDLE}, StaggeredGrid will * check if there are gaps in the because of full span items. If it finds, it will re-layout * and move items to correct positions with animations. * <p> * For example, if LayoutManager ends up with the following layout due to adapter changes: * <pre> * AAA * _BC * DDD * </pre> * <p> * It will animate to the following state: * <pre> * AAA * BC_ * DDD * </pre> */ public static final int GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS = 2; private static final int INVALID_OFFSET = Integer.MIN_VALUE; /** * While trying to find next view to focus, LayoutManager will not try to scroll more * than this factor times the total space of the list. If layout is vertical, total space is the * height minus padding, if layout is horizontal, total space is the width minus padding. */ private static final float MAX_SCROLL_FACTOR = 1 / 3f; /** * Number of spans */ private int mSpanCount = -1; private Span[] mSpans; /** * Primary orientation is the layout's orientation, secondary orientation is the orientation * for spans. Having both makes code much cleaner for calculations. */ @NonNull OrientationHelper mPrimaryOrientation; @NonNull OrientationHelper mSecondaryOrientation; private int mOrientation; /** * The width or height per span, depending on the orientation. */ private int mSizePerSpan; @NonNull private final LayoutState mLayoutState; private boolean mReverseLayout = false; /** * Aggregated reverse layout value that takes RTL into account. */ boolean mShouldReverseLayout = false; /** * Temporary variable used during fill method to check which spans needs to be filled. */ private BitSet mRemainingSpans; /** * When LayoutManager needs to scroll to a position, it sets this variable and requests a * layout which will check this variable and re-layout accordingly. */ int mPendingScrollPosition = NO_POSITION; /** * Used to keep the offset value when {@link #scrollToPositionWithOffset(int, int)} is * called. */ int mPendingScrollPositionOffset = INVALID_OFFSET; /** * Keeps the mapping between the adapter positions and spans. This is necessary to provide * a consistent experience when user scrolls the list. */ LazySpanLookup mLazySpanLookup = new LazySpanLookup(); /** * how we handle gaps in UI. */ private int mGapStrategy = GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS; /** * Saved state needs this information to properly layout on restore. */ private boolean mLastLayoutFromEnd; /** * Saved state and onLayout needs this information to re-layout properly */ private boolean mLastLayoutRTL; /** * SavedState is not handled until a layout happens. This is where we keep it until next * layout. */ private SavedState mPendingSavedState; /** * Re-used measurement specs. updated by onLayout. */ private int mFullSizeSpec; /** * Re-used rectangle to get child decor offsets. */ private final Rect mTmpRect = new Rect(); /** * Re-used anchor info. */ private final AnchorInfo mAnchorInfo = new AnchorInfo(); /** * If a full span item is invalid / or created in reverse direction; it may create gaps in * the UI. While laying out, if such case is detected, we set this flag. * <p> * After scrolling stops, we check this flag and if it is set, re-layout. */ private boolean mLaidOutInvalidFullSpan = false; /** * Works the same way as {@link android.widget.AbsListView#setSmoothScrollbarEnabled(boolean)}. * see {@link android.widget.AbsListView#setSmoothScrollbarEnabled(boolean)} */ private boolean mSmoothScrollbarEnabled = true; private final Runnable mCheckForGapsRunnable = new Runnable() { @Override public void run() { checkForGaps(); } }; /** * Constructor used when layout manager is set in XML by RecyclerView attribute * "layoutManager". Defaults to single column and vertical. */ @SuppressWarnings("unused") public StaggeredGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { Properties properties = getProperties(context, attrs, defStyleAttr, defStyleRes); setOrientation(properties.orientation); setSpanCount(properties.spanCount); setReverseLayout(properties.reverseLayout); setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE); mLayoutState = new LayoutState(); createOrientationHelpers(); } /** * Creates a StaggeredGridLayoutManager with given parameters. * * @param spanCount If orientation is vertical, spanCount is number of columns. If * orientation is horizontal, spanCount is number of rows. * @param orientation {@link #VERTICAL} or {@link #HORIZONTAL} */ public StaggeredGridLayoutManager(int spanCount, int orientation) { mOrientation = orientation; setSpanCount(spanCount); setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE); mLayoutState = new LayoutState(); createOrientationHelpers(); } private void createOrientationHelpers() { mPrimaryOrientation = OrientationHelper.createOrientationHelper(this, mOrientation); mSecondaryOrientation = OrientationHelper .createOrientationHelper(this, 1 - mOrientation); } /** * Checks for gaps in the UI that may be caused by adapter changes. * <p> * When a full span item is laid out in reverse direction, it sets a flag which we check when * scroll is stopped (or re-layout happens) and re-layout after first valid item. */ private boolean checkForGaps() { if (getChildCount() == 0 || mGapStrategy == GAP_HANDLING_NONE || !isAttachedToWindow()) { return false; } final int minPos, maxPos; if (mShouldReverseLayout) { minPos = getLastChildPosition(); maxPos = getFirstChildPosition(); } else { minPos = getFirstChildPosition(); maxPos = getLastChildPosition(); } if (minPos == 0) { View gapView = hasGapsToFix(); if (gapView != null) { mLazySpanLookup.clear(); requestSimpleAnimationsInNextLayout(); requestLayout(); return true; } } if (!mLaidOutInvalidFullSpan) { return false; } int invalidGapDir = mShouldReverseLayout ? LayoutState.LAYOUT_START : LayoutState.LAYOUT_END; final LazySpanLookup.FullSpanItem invalidFsi = mLazySpanLookup .getFirstFullSpanItemInRange(minPos, maxPos + 1, invalidGapDir, true); if (invalidFsi == null) { mLaidOutInvalidFullSpan = false; mLazySpanLookup.forceInvalidateAfter(maxPos + 1); return false; } final LazySpanLookup.FullSpanItem validFsi = mLazySpanLookup .getFirstFullSpanItemInRange(minPos, invalidFsi.mPosition, invalidGapDir * -1, true); if (validFsi == null) { mLazySpanLookup.forceInvalidateAfter(invalidFsi.mPosition); } else { mLazySpanLookup.forceInvalidateAfter(validFsi.mPosition + 1); } requestSimpleAnimationsInNextLayout(); requestLayout(); return true; } @Override public void onScrollStateChanged(int state) { if (state == RecyclerView.SCROLL_STATE_IDLE) { checkForGaps(); } } @Override public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) { removeCallbacks(mCheckForGapsRunnable); for (int i = 0; i < mSpanCount; i++) { mSpans[i].clear(); } } /** * Checks for gaps if we've reached to the top of the list. * <p> * Intermediate gaps created by full span items are tracked via mLaidOutInvalidFullSpan field. */ View hasGapsToFix() { int startChildIndex = 0; int endChildIndex = getChildCount() - 1; BitSet mSpansToCheck = new BitSet(mSpanCount); mSpansToCheck.set(0, mSpanCount, true); final int firstChildIndex, childLimit; final int preferredSpanDir = mOrientation == VERTICAL && isLayoutRTL() ? 1 : -1; if (mShouldReverseLayout) { firstChildIndex = endChildIndex; childLimit = startChildIndex - 1; } else { firstChildIndex = startChildIndex; childLimit = endChildIndex + 1; } final int nextChildDiff = firstChildIndex < childLimit ? 1 : -1; for (int i = firstChildIndex; i != childLimit; i += nextChildDiff) { View child = getChildAt(i); LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (mSpansToCheck.get(lp.mSpan.mIndex)) { if (checkSpanForGap(lp.mSpan)) { return child; } mSpansToCheck.clear(lp.mSpan.mIndex); } if (lp.mFullSpan) { continue; // quick reject } if (i + nextChildDiff != childLimit) { View nextChild = getChildAt(i + nextChildDiff); boolean compareSpans = false; if (mShouldReverseLayout) { // ensure child's end is below nextChild's end int myEnd = mPrimaryOrientation.getDecoratedEnd(child); int nextEnd = mPrimaryOrientation.getDecoratedEnd(nextChild); if (myEnd < nextEnd) { return child;//i should have a better position } else if (myEnd == nextEnd) { compareSpans = true; } } else { int myStart = mPrimaryOrientation.getDecoratedStart(child); int nextStart = mPrimaryOrientation.getDecoratedStart(nextChild); if (myStart > nextStart) { return child;//i should have a better position } else if (myStart == nextStart) { compareSpans = true; } } if (compareSpans) { // equal, check span indices. LayoutParams nextLp = (LayoutParams) nextChild.getLayoutParams(); if (lp.mSpan.mIndex - nextLp.mSpan.mIndex < 0 != preferredSpanDir < 0) { return child; } } } } // everything looks good return null; } private boolean checkSpanForGap(Span span) { if (mShouldReverseLayout) { if (span.getEndLine() < mPrimaryOrientation.getEndAfterPadding()) { // if it is full span, it is OK final View endView = span.mViews.get(span.mViews.size() - 1); final LayoutParams lp = span.getLayoutParams(endView); return !lp.mFullSpan; } } else if (span.getStartLine() > mPrimaryOrientation.getStartAfterPadding()) { // if it is full span, it is OK final View startView = span.mViews.get(0); final LayoutParams lp = span.getLayoutParams(startView); return !lp.mFullSpan; } return false; } /** * Sets the number of spans for the layout. This will invalidate all of the span assignments * for Views. * <p> * Calling this method will automatically result in a new layout request unless the spanCount * parameter is equal to current span count. * * @param spanCount Number of spans to layout */ public void setSpanCount(int spanCount) { assertNotInLayoutOrScroll(null); if (spanCount != mSpanCount) { invalidateSpanAssignments(); mSpanCount = spanCount; mRemainingSpans = new BitSet(mSpanCount); mSpans = new Span[mSpanCount]; for (int i = 0; i < mSpanCount; i++) { mSpans[i] = new Span(i); } requestLayout(); } } /** * Sets the orientation of the layout. StaggeredGridLayoutManager will do its best to keep * scroll position if this method is called after views are laid out. * * @param orientation {@link #HORIZONTAL} or {@link #VERTICAL} */ public void setOrientation(int orientation) { if (orientation != HORIZONTAL && orientation != VERTICAL) { throw new IllegalArgumentException("invalid orientation."); } assertNotInLayoutOrScroll(null); if (orientation == mOrientation) { return; } mOrientation = orientation; OrientationHelper tmp = mPrimaryOrientation; mPrimaryOrientation = mSecondaryOrientation; mSecondaryOrientation = tmp; requestLayout(); } /** * Sets whether LayoutManager should start laying out items from the end of the UI. The order * items are traversed is not affected by this call. * <p> * For vertical layout, if it is set to <code>true</code>, first item will be at the bottom of * the list. * <p> * For horizontal layouts, it depends on the layout direction. * When set to true, If {@link RecyclerView} is LTR, than it will layout from RTL, if * {@link RecyclerView}} is RTL, it will layout from LTR. * * @param reverseLayout Whether layout should be in reverse or not */ public void setReverseLayout(boolean reverseLayout) { assertNotInLayoutOrScroll(null); if (mPendingSavedState != null && mPendingSavedState.mReverseLayout != reverseLayout) { mPendingSavedState.mReverseLayout = reverseLayout; } mReverseLayout = reverseLayout; requestLayout(); } /** * Returns the current gap handling strategy for StaggeredGridLayoutManager. * <p> * Staggered grid may have gaps in the layout due to changes in the adapter. To avoid gaps, * StaggeredGridLayoutManager provides 2 options. Check {@link #GAP_HANDLING_NONE} and * {@link #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS} for details. * <p> * By default, StaggeredGridLayoutManager uses {@link #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS}. * * @return Current gap handling strategy. * @see #setGapStrategy(int) * @see #GAP_HANDLING_NONE * @see #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS */ public int getGapStrategy() { return mGapStrategy; } /** * Sets the gap handling strategy for StaggeredGridLayoutManager. If the gapStrategy parameter * is different than the current strategy, calling this method will trigger a layout request. * * @param gapStrategy The new gap handling strategy. Should be * {@link #GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS} or {@link * #GAP_HANDLING_NONE}. * @see #getGapStrategy() */ public void setGapStrategy(int gapStrategy) { assertNotInLayoutOrScroll(null); if (gapStrategy == mGapStrategy) { return; } if (gapStrategy != GAP_HANDLING_NONE && gapStrategy != GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS) { throw new IllegalArgumentException("invalid gap strategy. Must be GAP_HANDLING_NONE " + "or GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS"); } mGapStrategy = gapStrategy; setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE); requestLayout(); } @Override public void assertNotInLayoutOrScroll(String message) { if (mPendingSavedState == null) { super.assertNotInLayoutOrScroll(message); } } /** * Returns the number of spans laid out by StaggeredGridLayoutManager. * * @return Number of spans in the layout */ public int getSpanCount() { return mSpanCount; } /** * For consistency, StaggeredGridLayoutManager keeps a mapping between spans and items. * <p> * If you need to cancel current assignments, you can call this method which will clear all * assignments and request a new layout. */ public void invalidateSpanAssignments() { mLazySpanLookup.clear(); requestLayout(); } /** * Calculates the views' layout order. (e.g. from end to start or start to end) * RTL layout support is applied automatically. So if layout is RTL and * {@link #getReverseLayout()} is {@code true}, elements will be laid out starting from left. */ private void resolveShouldLayoutReverse() { // A == B is the same result, but we rather keep it readable if (mOrientation == VERTICAL || !isLayoutRTL()) { mShouldReverseLayout = mReverseLayout; } else { mShouldReverseLayout = !mReverseLayout; } } boolean isLayoutRTL() { return getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL; } /** * Returns whether views are laid out in reverse order or not. * <p> * Not that this value is not affected by RecyclerView's layout direction. * * @return True if layout is reversed, false otherwise * @see #setReverseLayout(boolean) */ public boolean getReverseLayout() { return mReverseLayout; } @Override public void setMeasuredDimension(Rect childrenBounds, int wSpec, int hSpec) { // we don't like it to wrap content in our non-scroll direction. final int width, height; final int horizontalPadding = getPaddingLeft() + getPaddingRight(); final int verticalPadding = getPaddingTop() + getPaddingBottom(); if (mOrientation == VERTICAL) { final int usedHeight = childrenBounds.height() + verticalPadding; height = chooseSize(hSpec, usedHeight, getMinimumHeight()); width = chooseSize(wSpec, mSizePerSpan * mSpanCount + horizontalPadding, getMinimumWidth()); } else { final int usedWidth = childrenBounds.width() + horizontalPadding; width = chooseSize(wSpec, usedWidth, getMinimumWidth()); height = chooseSize(hSpec, mSizePerSpan * mSpanCount + verticalPadding, getMinimumHeight()); } setMeasuredDimension(width, height); } @Override public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { onLayoutChildren(recycler, state, true); } private void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state, boolean shouldCheckForGaps) { final AnchorInfo anchorInfo = mAnchorInfo; anchorInfo.reset(); if (mPendingSavedState != null || mPendingScrollPosition != NO_POSITION) { if (state.getItemCount() == 0) { removeAndRecycleAllViews(recycler); return; } } if (mPendingSavedState != null) { applyPendingSavedState(anchorInfo); } else { resolveShouldLayoutReverse(); anchorInfo.mLayoutFromEnd = mShouldReverseLayout; } updateAnchorInfoForLayout(state, anchorInfo); if (mPendingSavedState == null) { if (anchorInfo.mLayoutFromEnd != mLastLayoutFromEnd || isLayoutRTL() != mLastLayoutRTL) { mLazySpanLookup.clear(); anchorInfo.mInvalidateOffsets = true; } } if (getChildCount() > 0 && (mPendingSavedState == null || mPendingSavedState.mSpanOffsetsSize < 1)) { if (anchorInfo.mInvalidateOffsets) { for (int i = 0; i < mSpanCount; i++) { // Scroll to position is set, clear. mSpans[i].clear(); if (anchorInfo.mOffset != INVALID_OFFSET) { mSpans[i].setLine(anchorInfo.mOffset); } } } else { for (int i = 0; i < mSpanCount; i++) { mSpans[i].cacheReferenceLineAndClear(mShouldReverseLayout, anchorInfo.mOffset); } } } detachAndScrapAttachedViews(recycler); mLayoutState.mRecycle = false; mLaidOutInvalidFullSpan = false; updateMeasureSpecs(mSecondaryOrientation.getTotalSpace()); updateLayoutState(anchorInfo.mPosition, state); if (anchorInfo.mLayoutFromEnd) { // Layout start. setLayoutStateDirection(LayoutState.LAYOUT_START); fill(recycler, mLayoutState, state); // Layout end. setLayoutStateDirection(LayoutState.LAYOUT_END); mLayoutState.mCurrentPosition = anchorInfo.mPosition + mLayoutState.mItemDirection; fill(recycler, mLayoutState, state); } else { // Layout end. setLayoutStateDirection(LayoutState.LAYOUT_END); fill(recycler, mLayoutState, state); // Layout start. setLayoutStateDirection(LayoutState.LAYOUT_START); mLayoutState.mCurrentPosition = anchorInfo.mPosition + mLayoutState.mItemDirection; fill(recycler, mLayoutState, state); } repositionToWrapContentIfNecessary(); if (getChildCount() > 0) { if (mShouldReverseLayout) { fixEndGap(recycler, state, true); fixStartGap(recycler, state, false); } else { fixStartGap(recycler, state, true); fixEndGap(recycler, state, false); } } boolean hasGaps = false; if (shouldCheckForGaps && !state.isPreLayout()) { final boolean needToCheckForGaps = mGapStrategy != GAP_HANDLING_NONE && getChildCount() > 0 && (mLaidOutInvalidFullSpan || hasGapsToFix() != null); if (needToCheckForGaps) { removeCallbacks(mCheckForGapsRunnable); if (checkForGaps()) { hasGaps = true; } } mPendingScrollPosition = NO_POSITION; mPendingScrollPositionOffset = INVALID_OFFSET; } mLastLayoutFromEnd = anchorInfo.mLayoutFromEnd; mLastLayoutRTL = isLayoutRTL(); mPendingSavedState = null; // we don't need this anymore if (hasGaps) { onLayoutChildren(recycler, state, false); } } private void repositionToWrapContentIfNecessary() { if (mSecondaryOrientation.getMode() == View.MeasureSpec.EXACTLY) { return; // nothing to do } float maxSize = 0; final int childCount = getChildCount(); for (int i = 0; i < childCount; i ++) { View child = getChildAt(i); float size = mSecondaryOrientation.getDecoratedMeasurement(child); if (size < maxSize) { continue; } LayoutParams layoutParams = (LayoutParams) child.getLayoutParams(); if (layoutParams.isFullSpan()) { size = 1f * size / mSpanCount; } maxSize = Math.max(maxSize, size); } int before = mSizePerSpan; int desired = Math.round(maxSize * mSpanCount); if (mSecondaryOrientation.getMode() == View.MeasureSpec.AT_MOST) { desired = Math.min(desired, mSecondaryOrientation.getTotalSpace()); } updateMeasureSpecs(desired); if (mSizePerSpan == before) { return; // nothing has changed } for (int i = 0; i < childCount; i ++) { View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (lp.mFullSpan) { continue; } if (isLayoutRTL() && mOrientation == VERTICAL) { int newOffset = -(mSpanCount - 1 - lp.mSpan.mIndex) * mSizePerSpan; int prevOffset = -(mSpanCount - 1 - lp.mSpan.mIndex) * before; child.offsetLeftAndRight(newOffset - prevOffset); } else { int newOffset = lp.mSpan.mIndex * mSizePerSpan; int prevOffset = lp.mSpan.mIndex * before; if (mOrientation == VERTICAL) { child.offsetLeftAndRight(newOffset - prevOffset); } else { child.offsetTopAndBottom(newOffset - prevOffset); } } } } private void applyPendingSavedState(AnchorInfo anchorInfo) { if (DEBUG) { Log.d(TAG, "found saved state: " + mPendingSavedState); } if (mPendingSavedState.mSpanOffsetsSize > 0) { if (mPendingSavedState.mSpanOffsetsSize == mSpanCount) { for (int i = 0; i < mSpanCount; i++) { mSpans[i].clear(); int line = mPendingSavedState.mSpanOffsets[i]; if (line != Span.INVALID_LINE) { if (mPendingSavedState.mAnchorLayoutFromEnd) { line += mPrimaryOrientation.getEndAfterPadding(); } else { line += mPrimaryOrientation.getStartAfterPadding(); } } mSpans[i].setLine(line); } } else { mPendingSavedState.invalidateSpanInfo(); mPendingSavedState.mAnchorPosition = mPendingSavedState.mVisibleAnchorPosition; } } mLastLayoutRTL = mPendingSavedState.mLastLayoutRTL; setReverseLayout(mPendingSavedState.mReverseLayout); resolveShouldLayoutReverse(); if (mPendingSavedState.mAnchorPosition != NO_POSITION) { mPendingScrollPosition = mPendingSavedState.mAnchorPosition; anchorInfo.mLayoutFromEnd = mPendingSavedState.mAnchorLayoutFromEnd; } else { anchorInfo.mLayoutFromEnd = mShouldReverseLayout; } if (mPendingSavedState.mSpanLookupSize > 1) { mLazySpanLookup.mData = mPendingSavedState.mSpanLookup; mLazySpanLookup.mFullSpanItems = mPendingSavedState.mFullSpanItems; } } void updateAnchorInfoForLayout(RecyclerView.State state, AnchorInfo anchorInfo) { if (updateAnchorFromPendingData(state, anchorInfo)) { return; } if (updateAnchorFromChildren(state, anchorInfo)) { return; } if (DEBUG) { Log.d(TAG, "Deciding anchor info from fresh state"); } anchorInfo.assignCoordinateFromPadding(); anchorInfo.mPosition = 0; } private boolean updateAnchorFromChildren(RecyclerView.State state, AnchorInfo anchorInfo) { // We don't recycle views out of adapter order. This way, we can rely on the first or // last child as the anchor position. // Layout direction may change but we should select the child depending on the latest // layout direction. Otherwise, we'll choose the wrong child. anchorInfo.mPosition = mLastLayoutFromEnd ? findLastReferenceChildPosition(state.getItemCount()) : findFirstReferenceChildPosition(state.getItemCount()); anchorInfo.mOffset = INVALID_OFFSET; return true; } boolean updateAnchorFromPendingData(RecyclerView.State state, AnchorInfo anchorInfo) { // Validate scroll position if exists. if (state.isPreLayout() || mPendingScrollPosition == NO_POSITION) { return false; } // Validate it. if (mPendingScrollPosition < 0 || mPendingScrollPosition >= state.getItemCount()) { mPendingScrollPosition = NO_POSITION; mPendingScrollPositionOffset = INVALID_OFFSET; return false; } if (mPendingSavedState == null || mPendingSavedState.mAnchorPosition == NO_POSITION || mPendingSavedState.mSpanOffsetsSize < 1) { // If item is visible, make it fully visible. final View child = findViewByPosition(mPendingScrollPosition); if (child != null) { // Use regular anchor position, offset according to pending offset and target // child anchorInfo.mPosition = mShouldReverseLayout ? getLastChildPosition() : getFirstChildPosition(); if (mPendingScrollPositionOffset != INVALID_OFFSET) { if (anchorInfo.mLayoutFromEnd) { final int target = mPrimaryOrientation.getEndAfterPadding() - mPendingScrollPositionOffset; anchorInfo.mOffset = target - mPrimaryOrientation.getDecoratedEnd(child); } else { final int target = mPrimaryOrientation.getStartAfterPadding() + mPendingScrollPositionOffset; anchorInfo.mOffset = target - mPrimaryOrientation.getDecoratedStart(child); } return true; } // no offset provided. Decide according to the child location final int childSize = mPrimaryOrientation.getDecoratedMeasurement(child); if (childSize > mPrimaryOrientation.getTotalSpace()) { // Item does not fit. Fix depending on layout direction. anchorInfo.mOffset = anchorInfo.mLayoutFromEnd ? mPrimaryOrientation.getEndAfterPadding() : mPrimaryOrientation.getStartAfterPadding(); return true; } final int startGap = mPrimaryOrientation.getDecoratedStart(child) - mPrimaryOrientation.getStartAfterPadding(); if (startGap < 0) { anchorInfo.mOffset = -startGap; return true; } final int endGap = mPrimaryOrientation.getEndAfterPadding() - mPrimaryOrientation.getDecoratedEnd(child); if (endGap < 0) { anchorInfo.mOffset = endGap; return true; } // child already visible. just layout as usual anchorInfo.mOffset = INVALID_OFFSET; } else { // Child is not visible. Set anchor coordinate depending on in which direction // child will be visible. anchorInfo.mPosition = mPendingScrollPosition; if (mPendingScrollPositionOffset == INVALID_OFFSET) { final int position = calculateScrollDirectionForPosition( anchorInfo.mPosition); anchorInfo.mLayoutFromEnd = position == LayoutState.LAYOUT_END; anchorInfo.assignCoordinateFromPadding(); } else { anchorInfo.assignCoordinateFromPadding(mPendingScrollPositionOffset); } anchorInfo.mInvalidateOffsets = true; } } else { anchorInfo.mOffset = INVALID_OFFSET; anchorInfo.mPosition = mPendingScrollPosition; } return true; } void updateMeasureSpecs(int totalSpace) { mSizePerSpan = totalSpace / mSpanCount; //noinspection ResourceType mFullSizeSpec = View.MeasureSpec.makeMeasureSpec( totalSpace, mSecondaryOrientation.getMode()); } @Override public boolean supportsPredictiveItemAnimations() { return mPendingSavedState == null; } /** * Returns the adapter position of the first visible view for each span. * <p> * Note that, this value is not affected by layout orientation or item order traversal. * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, * not in the layout. * <p> * If RecyclerView has item decorators, they will be considered in calculations as well. * <p> * StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those * views are ignored in this method. * * @param into An array to put the results into. If you don't provide any, LayoutManager will * create a new one. * @return The adapter position of the first visible item in each span. If a span does not have * any items, {@link RecyclerView#NO_POSITION} is returned for that span. * @see #findFirstCompletelyVisibleItemPositions(int[]) * @see #findLastVisibleItemPositions(int[]) */ public int[] findFirstVisibleItemPositions(int[] into) { if (into == null) { into = new int[mSpanCount]; } else if (into.length < mSpanCount) { throw new IllegalArgumentException("Provided int[]'s size must be more than or equal" + " to span count. Expected:" + mSpanCount + ", array size:" + into.length); } for (int i = 0; i < mSpanCount; i++) { into[i] = mSpans[i].findFirstVisibleItemPosition(); } return into; } /** * Returns the adapter position of the first completely visible view for each span. * <p> * Note that, this value is not affected by layout orientation or item order traversal. * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, * not in the layout. * <p> * If RecyclerView has item decorators, they will be considered in calculations as well. * <p> * StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those * views are ignored in this method. * * @param into An array to put the results into. If you don't provide any, LayoutManager will * create a new one. * @return The adapter position of the first fully visible item in each span. If a span does * not have any items, {@link RecyclerView#NO_POSITION} is returned for that span. * @see #findFirstVisibleItemPositions(int[]) * @see #findLastCompletelyVisibleItemPositions(int[]) */ public int[] findFirstCompletelyVisibleItemPositions(int[] into) { if (into == null) { into = new int[mSpanCount]; } else if (into.length < mSpanCount) { throw new IllegalArgumentException("Provided int[]'s size must be more than or equal" + " to span count. Expected:" + mSpanCount + ", array size:" + into.length); } for (int i = 0; i < mSpanCount; i++) { into[i] = mSpans[i].findFirstCompletelyVisibleItemPosition(); } return into; } /** * Returns the adapter position of the last visible view for each span. * <p> * Note that, this value is not affected by layout orientation or item order traversal. * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, * not in the layout. * <p> * If RecyclerView has item decorators, they will be considered in calculations as well. * <p> * StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those * views are ignored in this method. * * @param into An array to put the results into. If you don't provide any, LayoutManager will * create a new one. * @return The adapter position of the last visible item in each span. If a span does not have * any items, {@link RecyclerView#NO_POSITION} is returned for that span. * @see #findLastCompletelyVisibleItemPositions(int[]) * @see #findFirstVisibleItemPositions(int[]) */ public int[] findLastVisibleItemPositions(int[] into) { if (into == null) { into = new int[mSpanCount]; } else if (into.length < mSpanCount) { throw new IllegalArgumentException("Provided int[]'s size must be more than or equal" + " to span count. Expected:" + mSpanCount + ", array size:" + into.length); } for (int i = 0; i < mSpanCount; i++) { into[i] = mSpans[i].findLastVisibleItemPosition(); } return into; } /** * Returns the adapter position of the last completely visible view for each span. * <p> * Note that, this value is not affected by layout orientation or item order traversal. * ({@link #setReverseLayout(boolean)}). Views are sorted by their positions in the adapter, * not in the layout. * <p> * If RecyclerView has item decorators, they will be considered in calculations as well. * <p> * StaggeredGridLayoutManager may pre-cache some views that are not necessarily visible. Those * views are ignored in this method. * * @param into An array to put the results into. If you don't provide any, LayoutManager will * create a new one. * @return The adapter position of the last fully visible item in each span. If a span does not * have any items, {@link RecyclerView#NO_POSITION} is returned for that span. * @see #findFirstCompletelyVisibleItemPositions(int[]) * @see #findLastVisibleItemPositions(int[]) */ public int[] findLastCompletelyVisibleItemPositions(int[] into) { if (into == null) { into = new int[mSpanCount]; } else if (into.length < mSpanCount) { throw new IllegalArgumentException("Provided int[]'s size must be more than or equal" + " to span count. Expected:" + mSpanCount + ", array size:" + into.length); } for (int i = 0; i < mSpanCount; i++) { into[i] = mSpans[i].findLastCompletelyVisibleItemPosition(); } return into; } @Override public int computeHorizontalScrollOffset(RecyclerView.State state) { return computeScrollOffset(state); } private int computeScrollOffset(RecyclerView.State state) { if (getChildCount() == 0) { return 0; } return ScrollbarHelper.computeScrollOffset(state, mPrimaryOrientation, findFirstVisibleItemClosestToStart(!mSmoothScrollbarEnabled, true) , findFirstVisibleItemClosestToEnd(!mSmoothScrollbarEnabled, true), this, mSmoothScrollbarEnabled, mShouldReverseLayout); } @Override public int computeVerticalScrollOffset(RecyclerView.State state) { return computeScrollOffset(state); } @Override public int computeHorizontalScrollExtent(RecyclerView.State state) { return computeScrollExtent(state); } private int computeScrollExtent(RecyclerView.State state) { if (getChildCount() == 0) { return 0; } return ScrollbarHelper.computeScrollExtent(state, mPrimaryOrientation, findFirstVisibleItemClosestToStart(!mSmoothScrollbarEnabled, true) , findFirstVisibleItemClosestToEnd(!mSmoothScrollbarEnabled, true), this, mSmoothScrollbarEnabled); } @Override public int computeVerticalScrollExtent(RecyclerView.State state) { return computeScrollExtent(state); } @Override public int computeHorizontalScrollRange(RecyclerView.State state) { return computeScrollRange(state); } private int computeScrollRange(RecyclerView.State state) { if (getChildCount() == 0) { return 0; } return ScrollbarHelper.computeScrollRange(state, mPrimaryOrientation, findFirstVisibleItemClosestToStart(!mSmoothScrollbarEnabled, true) , findFirstVisibleItemClosestToEnd(!mSmoothScrollbarEnabled, true), this, mSmoothScrollbarEnabled); } @Override public int computeVerticalScrollRange(RecyclerView.State state) { return computeScrollRange(state); } private void measureChildWithDecorationsAndMargin(View child, LayoutParams lp, boolean alreadyMeasured) { if (lp.mFullSpan) { if (mOrientation == VERTICAL) { measureChildWithDecorationsAndMargin(child, mFullSizeSpec, getChildMeasureSpec(getHeight(), getHeightMode(), 0, lp.height, true), alreadyMeasured); } else { measureChildWithDecorationsAndMargin(child, getChildMeasureSpec(getWidth(), getWidthMode(), 0, lp.width, true), mFullSizeSpec, alreadyMeasured); } } else { if (mOrientation == VERTICAL) { measureChildWithDecorationsAndMargin(child, getChildMeasureSpec(mSizePerSpan, getWidthMode(), 0, lp.width, false), getChildMeasureSpec(getHeight(), getHeightMode(), 0, lp.height, true), alreadyMeasured); } else { measureChildWithDecorationsAndMargin(child, getChildMeasureSpec(getWidth(), getWidthMode(), 0, lp.width, true), getChildMeasureSpec(mSizePerSpan, getHeightMode(), 0, lp.height, false), alreadyMeasured); } } } private void measureChildWithDecorationsAndMargin(View child, int widthSpec, int heightSpec, boolean alreadyMeasured) { calculateItemDecorationsForChild(child, mTmpRect); LayoutParams lp = (LayoutParams) child.getLayoutParams(); widthSpec = updateSpecWithExtra(widthSpec, lp.leftMargin + mTmpRect.left, lp.rightMargin + mTmpRect.right); heightSpec = updateSpecWithExtra(heightSpec, lp.topMargin + mTmpRect.top, lp.bottomMargin + mTmpRect.bottom); final boolean measure = alreadyMeasured ? shouldReMeasureChild(child, widthSpec, heightSpec, lp) : shouldMeasureChild(child, widthSpec, heightSpec, lp); if (measure) { child.measure(widthSpec, heightSpec); } } private int updateSpecWithExtra(int spec, int startInset, int endInset) { if (startInset == 0 && endInset == 0) { return spec; } final int mode = View.MeasureSpec.getMode(spec); if (mode == View.MeasureSpec.AT_MOST || mode == View.MeasureSpec.EXACTLY) { return View.MeasureSpec.makeMeasureSpec( Math.max(0, View.MeasureSpec.getSize(spec) - startInset - endInset), mode); } return spec; } @Override public void onRestoreInstanceState(Parcelable state) { if (state instanceof SavedState) { mPendingSavedState = (SavedState) state; requestLayout(); } else if (DEBUG) { Log.d(TAG, "invalid saved state class"); } } @Override public Parcelable onSaveInstanceState() { if (mPendingSavedState != null) { return new SavedState(mPendingSavedState); } SavedState state = new SavedState(); state.mReverseLayout = mReverseLayout; state.mAnchorLayoutFromEnd = mLastLayoutFromEnd; state.mLastLayoutRTL = mLastLayoutRTL; if (mLazySpanLookup != null && mLazySpanLookup.mData != null) { state.mSpanLookup = mLazySpanLookup.mData; state.mSpanLookupSize = state.mSpanLookup.length; state.mFullSpanItems = mLazySpanLookup.mFullSpanItems; } else { state.mSpanLookupSize = 0; } if (getChildCount() > 0) { state.mAnchorPosition = mLastLayoutFromEnd ? getLastChildPosition() : getFirstChildPosition(); state.mVisibleAnchorPosition = findFirstVisibleItemPositionInt(); state.mSpanOffsetsSize = mSpanCount; state.mSpanOffsets = new int[mSpanCount]; for (int i = 0; i < mSpanCount; i++) { int line; if (mLastLayoutFromEnd) { line = mSpans[i].getEndLine(Span.INVALID_LINE); if (line != Span.INVALID_LINE) { line -= mPrimaryOrientation.getEndAfterPadding(); } } else { line = mSpans[i].getStartLine(Span.INVALID_LINE); if (line != Span.INVALID_LINE) { line -= mPrimaryOrientation.getStartAfterPadding(); } } state.mSpanOffsets[i] = line; } } else { state.mAnchorPosition = NO_POSITION; state.mVisibleAnchorPosition = NO_POSITION; state.mSpanOffsetsSize = 0; } if (DEBUG) { Log.d(TAG, "saved state:\n" + state); } return state; } @Override public void onInitializeAccessibilityNodeInfoForItem(RecyclerView.Recycler recycler, RecyclerView.State state, View host, AccessibilityNodeInfoCompat info) { ViewGroup.LayoutParams lp = host.getLayoutParams(); if (!(lp instanceof LayoutParams)) { super.onInitializeAccessibilityNodeInfoForItem(host, info); return; } LayoutParams sglp = (LayoutParams) lp; if (mOrientation == HORIZONTAL) { info.setCollectionItemInfo(AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain( sglp.getSpanIndex(), sglp.mFullSpan ? mSpanCount : 1, -1, -1, sglp.mFullSpan, false)); } else { // VERTICAL info.setCollectionItemInfo(AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain( -1, -1, sglp.getSpanIndex(), sglp.mFullSpan ? mSpanCount : 1, sglp.mFullSpan, false)); } } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); if (getChildCount() > 0) { final AccessibilityRecordCompat record = AccessibilityEventCompat .asRecord(event); final View start = findFirstVisibleItemClosestToStart(false, true); final View end = findFirstVisibleItemClosestToEnd(false, true); if (start == null || end == null) { return; } final int startPos = getPosition(start); final int endPos = getPosition(end); if (startPos < endPos) { record.setFromIndex(startPos); record.setToIndex(endPos); } else { record.setFromIndex(endPos); record.setToIndex(startPos); } } } /** * Finds the first fully visible child to be used as an anchor child if span count changes when * state is restored. If no children is fully visible, returns a partially visible child instead * of returning null. */ int findFirstVisibleItemPositionInt() { final View first = mShouldReverseLayout ? findFirstVisibleItemClosestToEnd(true, true) : findFirstVisibleItemClosestToStart(true, true); return first == null ? NO_POSITION : getPosition(first); } @Override public int getRowCountForAccessibility(RecyclerView.Recycler recycler, RecyclerView.State state) { if (mOrientation == HORIZONTAL) { return mSpanCount; } return super.getRowCountForAccessibility(recycler, state); } @Override public int getColumnCountForAccessibility(RecyclerView.Recycler recycler, RecyclerView.State state) { if (mOrientation == VERTICAL) { return mSpanCount; } return super.getColumnCountForAccessibility(recycler, state); } /** * This is for internal use. Not necessarily the child closest to start but the first child * we find that matches the criteria. * This method does not do any sorting based on child's start coordinate, instead, it uses * children order. */ View findFirstVisibleItemClosestToStart(boolean fullyVisible, boolean acceptPartiallyVisible) { final int boundsStart = mPrimaryOrientation.getStartAfterPadding(); final int boundsEnd = mPrimaryOrientation.getEndAfterPadding(); final int limit = getChildCount(); View partiallyVisible = null; for (int i = 0; i < limit; i++) { final View child = getChildAt(i); final int childStart = mPrimaryOrientation.getDecoratedStart(child); final int childEnd = mPrimaryOrientation.getDecoratedEnd(child); if(childEnd <= boundsStart || childStart >= boundsEnd) { continue; // not visible at all } if (childStart >= boundsStart || !fullyVisible) { // when checking for start, it is enough even if part of the child's top is visible // as long as fully visible is not requested. return child; } if (acceptPartiallyVisible && partiallyVisible == null) { partiallyVisible = child; } } return partiallyVisible; } /** * This is for internal use. Not necessarily the child closest to bottom but the first child * we find that matches the criteria. * This method does not do any sorting based on child's end coordinate, instead, it uses * children order. */ View findFirstVisibleItemClosestToEnd(boolean fullyVisible, boolean acceptPartiallyVisible) { final int boundsStart = mPrimaryOrientation.getStartAfterPadding(); final int boundsEnd = mPrimaryOrientation.getEndAfterPadding(); View partiallyVisible = null; for (int i = getChildCount() - 1; i >= 0; i--) { final View child = getChildAt(i); final int childStart = mPrimaryOrientation.getDecoratedStart(child); final int childEnd = mPrimaryOrientation.getDecoratedEnd(child); if(childEnd <= boundsStart || childStart >= boundsEnd) { continue; // not visible at all } if (childEnd <= boundsEnd || !fullyVisible) { // when checking for end, it is enough even if part of the child's bottom is visible // as long as fully visible is not requested. return child; } if (acceptPartiallyVisible && partiallyVisible == null) { partiallyVisible = child; } } return partiallyVisible; } private void fixEndGap(RecyclerView.Recycler recycler, RecyclerView.State state, boolean canOffsetChildren) { final int maxEndLine = getMaxEnd(Integer.MIN_VALUE); if (maxEndLine == Integer.MIN_VALUE) { return; } int gap = mPrimaryOrientation.getEndAfterPadding() - maxEndLine; int fixOffset; if (gap > 0) { fixOffset = -scrollBy(-gap, recycler, state); } else { return; // nothing to fix } gap -= fixOffset; if (canOffsetChildren && gap > 0) { mPrimaryOrientation.offsetChildren(gap); } } private void fixStartGap(RecyclerView.Recycler recycler, RecyclerView.State state, boolean canOffsetChildren) { final int minStartLine = getMinStart(Integer.MAX_VALUE); if (minStartLine == Integer.MAX_VALUE) { return; } int gap = minStartLine - mPrimaryOrientation.getStartAfterPadding(); int fixOffset; if (gap > 0) { fixOffset = scrollBy(gap, recycler, state); } else { return; // nothing to fix } gap -= fixOffset; if (canOffsetChildren && gap > 0) { mPrimaryOrientation.offsetChildren(-gap); } } private void updateLayoutState(int anchorPosition, RecyclerView.State state) { mLayoutState.mAvailable = 0; mLayoutState.mCurrentPosition = anchorPosition; int startExtra = 0; int endExtra = 0; if (isSmoothScrolling()) { final int targetPos = state.getTargetScrollPosition(); if (targetPos != NO_POSITION) { if (mShouldReverseLayout == targetPos < anchorPosition) { endExtra = mPrimaryOrientation.getTotalSpace(); } else { startExtra = mPrimaryOrientation.getTotalSpace(); } } } // Line of the furthest row. final boolean clipToPadding = getClipToPadding(); if (clipToPadding) { mLayoutState.mStartLine = mPrimaryOrientation.getStartAfterPadding() - startExtra; mLayoutState.mEndLine = mPrimaryOrientation.getEndAfterPadding() + endExtra; } else { mLayoutState.mEndLine = mPrimaryOrientation.getEnd() + endExtra; mLayoutState.mStartLine = -startExtra; } mLayoutState.mStopInFocusable = false; mLayoutState.mRecycle = true; mLayoutState.mInfinite = mPrimaryOrientation.getMode() == View.MeasureSpec.UNSPECIFIED && mPrimaryOrientation.getEnd() == 0; } private void setLayoutStateDirection(int direction) { mLayoutState.mLayoutDirection = direction; mLayoutState.mItemDirection = (mShouldReverseLayout == (direction == LayoutState.LAYOUT_START)) ? LayoutState.ITEM_DIRECTION_TAIL : LayoutState.ITEM_DIRECTION_HEAD; } @Override public void offsetChildrenHorizontal(int dx) { super.offsetChildrenHorizontal(dx); for (int i = 0; i < mSpanCount; i++) { mSpans[i].onOffset(dx); } } @Override public void offsetChildrenVertical(int dy) { super.offsetChildrenVertical(dy); for (int i = 0; i < mSpanCount; i++) { mSpans[i].onOffset(dy); } } @Override public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) { handleUpdate(positionStart, itemCount, AdapterHelper.UpdateOp.REMOVE); } @Override public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) { handleUpdate(positionStart, itemCount, AdapterHelper.UpdateOp.ADD); } @Override public void onItemsChanged(RecyclerView recyclerView) { mLazySpanLookup.clear(); requestLayout(); } @Override public void onItemsMoved(RecyclerView recyclerView, int from, int to, int itemCount) { handleUpdate(from, to, AdapterHelper.UpdateOp.MOVE); } @Override public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount, Object payload) { handleUpdate(positionStart, itemCount, AdapterHelper.UpdateOp.UPDATE); } /** * Checks whether it should invalidate span assignments in response to an adapter change. */ private void handleUpdate(int positionStart, int itemCountOrToPosition, int cmd) { int minPosition = mShouldReverseLayout ? getLastChildPosition() : getFirstChildPosition(); final int affectedRangeEnd;// exclusive final int affectedRangeStart;// inclusive if (cmd == AdapterHelper.UpdateOp.MOVE) { if (positionStart < itemCountOrToPosition) { affectedRangeEnd = itemCountOrToPosition + 1; affectedRangeStart = positionStart; } else { affectedRangeEnd = positionStart + 1; affectedRangeStart = itemCountOrToPosition; } } else { affectedRangeStart = positionStart; affectedRangeEnd = positionStart + itemCountOrToPosition; } mLazySpanLookup.invalidateAfter(affectedRangeStart); switch (cmd) { case AdapterHelper.UpdateOp.ADD: mLazySpanLookup.offsetForAddition(positionStart, itemCountOrToPosition); break; case AdapterHelper.UpdateOp.REMOVE: mLazySpanLookup.offsetForRemoval(positionStart, itemCountOrToPosition); break; case AdapterHelper.UpdateOp.MOVE: // TODO optimize mLazySpanLookup.offsetForRemoval(positionStart, 1); mLazySpanLookup.offsetForAddition(itemCountOrToPosition, 1); break; } if (affectedRangeEnd <= minPosition) { return; } int maxPosition = mShouldReverseLayout ? getFirstChildPosition() : getLastChildPosition(); if (affectedRangeStart <= maxPosition) { requestLayout(); } } private int fill(RecyclerView.Recycler recycler, LayoutState layoutState, RecyclerView.State state) { mRemainingSpans.set(0, mSpanCount, true); // The target position we are trying to reach. final int targetLine; // Line of the furthest row. if (mLayoutState.mInfinite) { if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { targetLine = Integer.MAX_VALUE; } else { // LAYOUT_START targetLine = Integer.MIN_VALUE; } } else { if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { targetLine = layoutState.mEndLine + layoutState.mAvailable; } else { // LAYOUT_START targetLine = layoutState.mStartLine - layoutState.mAvailable; } } updateAllRemainingSpans(layoutState.mLayoutDirection, targetLine); if (DEBUG) { Log.d(TAG, "FILLING targetLine: " + targetLine + "," + "remaining spans:" + mRemainingSpans + ", state: " + layoutState); } // the default coordinate to add new view. final int defaultNewViewLine = mShouldReverseLayout ? mPrimaryOrientation.getEndAfterPadding() : mPrimaryOrientation.getStartAfterPadding(); boolean added = false; while (layoutState.hasMore(state) && (mLayoutState.mInfinite || !mRemainingSpans.isEmpty())) { View view = layoutState.next(recycler); LayoutParams lp = ((LayoutParams) view.getLayoutParams()); final int position = lp.getViewLayoutPosition(); final int spanIndex = mLazySpanLookup.getSpan(position); Span currentSpan; final boolean assignSpan = spanIndex == LayoutParams.INVALID_SPAN_ID; if (assignSpan) { currentSpan = lp.mFullSpan ? mSpans[0] : getNextSpan(layoutState); mLazySpanLookup.setSpan(position, currentSpan); if (DEBUG) { Log.d(TAG, "assigned " + currentSpan.mIndex + " for " + position); } } else { if (DEBUG) { Log.d(TAG, "using " + spanIndex + " for pos " + position); } currentSpan = mSpans[spanIndex]; } // assign span before measuring so that item decorators can get updated span index lp.mSpan = currentSpan; if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { addView(view); } else { addView(view, 0); } measureChildWithDecorationsAndMargin(view, lp, false); final int start; final int end; if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { start = lp.mFullSpan ? getMaxEnd(defaultNewViewLine) : currentSpan.getEndLine(defaultNewViewLine); end = start + mPrimaryOrientation.getDecoratedMeasurement(view); if (assignSpan && lp.mFullSpan) { LazySpanLookup.FullSpanItem fullSpanItem; fullSpanItem = createFullSpanItemFromEnd(start); fullSpanItem.mGapDir = LayoutState.LAYOUT_START; fullSpanItem.mPosition = position; mLazySpanLookup.addFullSpanItem(fullSpanItem); } } else { end = lp.mFullSpan ? getMinStart(defaultNewViewLine) : currentSpan.getStartLine(defaultNewViewLine); start = end - mPrimaryOrientation.getDecoratedMeasurement(view); if (assignSpan && lp.mFullSpan) { LazySpanLookup.FullSpanItem fullSpanItem; fullSpanItem = createFullSpanItemFromStart(end); fullSpanItem.mGapDir = LayoutState.LAYOUT_END; fullSpanItem.mPosition = position; mLazySpanLookup.addFullSpanItem(fullSpanItem); } } // check if this item may create gaps in the future if (lp.mFullSpan && layoutState.mItemDirection == LayoutState.ITEM_DIRECTION_HEAD) { if (assignSpan) { mLaidOutInvalidFullSpan = true; } else { final boolean hasInvalidGap; if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { hasInvalidGap = !areAllEndsEqual(); } else { // layoutState.mLayoutDirection == LAYOUT_START hasInvalidGap = !areAllStartsEqual(); } if (hasInvalidGap) { final LazySpanLookup.FullSpanItem fullSpanItem = mLazySpanLookup .getFullSpanItem(position); if (fullSpanItem != null) { fullSpanItem.mHasUnwantedGapAfter = true; } mLaidOutInvalidFullSpan = true; } } } attachViewToSpans(view, lp, layoutState); final int otherStart; final int otherEnd; if (isLayoutRTL() && mOrientation == VERTICAL) { otherEnd = lp.mFullSpan ? mSecondaryOrientation.getEndAfterPadding() : mSecondaryOrientation.getEndAfterPadding() - (mSpanCount - 1 - currentSpan.mIndex) * mSizePerSpan; otherStart = otherEnd - mSecondaryOrientation.getDecoratedMeasurement(view); } else { otherStart = lp.mFullSpan ? mSecondaryOrientation.getStartAfterPadding() : currentSpan.mIndex * mSizePerSpan + mSecondaryOrientation.getStartAfterPadding(); otherEnd = otherStart + mSecondaryOrientation.getDecoratedMeasurement(view); } if (mOrientation == VERTICAL) { layoutDecoratedWithMargins(view, otherStart, start, otherEnd, end); } else { layoutDecoratedWithMargins(view, start, otherStart, end, otherEnd); } if (lp.mFullSpan) { updateAllRemainingSpans(mLayoutState.mLayoutDirection, targetLine); } else { updateRemainingSpans(currentSpan, mLayoutState.mLayoutDirection, targetLine); } recycle(recycler, mLayoutState); if (mLayoutState.mStopInFocusable && view.isFocusable()) { if (lp.mFullSpan) { mRemainingSpans.clear(); } else { mRemainingSpans.set(currentSpan.mIndex, false); } } added = true; } if (!added) { recycle(recycler, mLayoutState); } final int diff; if (mLayoutState.mLayoutDirection == LayoutState.LAYOUT_START) { final int minStart = getMinStart(mPrimaryOrientation.getStartAfterPadding()); diff = mPrimaryOrientation.getStartAfterPadding() - minStart; } else { final int maxEnd = getMaxEnd(mPrimaryOrientation.getEndAfterPadding()); diff = maxEnd - mPrimaryOrientation.getEndAfterPadding(); } return diff > 0 ? Math.min(layoutState.mAvailable, diff) : 0; } private LazySpanLookup.FullSpanItem createFullSpanItemFromEnd(int newItemTop) { LazySpanLookup.FullSpanItem fsi = new LazySpanLookup.FullSpanItem(); fsi.mGapPerSpan = new int[mSpanCount]; for (int i = 0; i < mSpanCount; i++) { fsi.mGapPerSpan[i] = newItemTop - mSpans[i].getEndLine(newItemTop); } return fsi; } private LazySpanLookup.FullSpanItem createFullSpanItemFromStart(int newItemBottom) { LazySpanLookup.FullSpanItem fsi = new LazySpanLookup.FullSpanItem(); fsi.mGapPerSpan = new int[mSpanCount]; for (int i = 0; i < mSpanCount; i++) { fsi.mGapPerSpan[i] = mSpans[i].getStartLine(newItemBottom) - newItemBottom; } return fsi; } private void attachViewToSpans(View view, LayoutParams lp, LayoutState layoutState) { if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { if (lp.mFullSpan) { appendViewToAllSpans(view); } else { lp.mSpan.appendToSpan(view); } } else { if (lp.mFullSpan) { prependViewToAllSpans(view); } else { lp.mSpan.prependToSpan(view); } } } private void recycle(RecyclerView.Recycler recycler, LayoutState layoutState) { if (!layoutState.mRecycle || layoutState.mInfinite) { return; } if (layoutState.mAvailable == 0) { // easy, recycle line is still valid if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) { recycleFromEnd(recycler, layoutState.mEndLine); } else { recycleFromStart(recycler, layoutState.mStartLine); } } else { // scrolling case, recycle line can be shifted by how much space we could cover // by adding new views if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) { // calculate recycle line int scrolled = layoutState.mStartLine - getMaxStart(layoutState.mStartLine); final int line; if (scrolled < 0) { line = layoutState.mEndLine; } else { line = layoutState.mEndLine - Math.min(scrolled, layoutState.mAvailable); } recycleFromEnd(recycler, line); } else { // calculate recycle line int scrolled = getMinEnd(layoutState.mEndLine) - layoutState.mEndLine; final int line; if (scrolled < 0) { line = layoutState.mStartLine; } else { line = layoutState.mStartLine + Math.min(scrolled, layoutState.mAvailable); } recycleFromStart(recycler, line); } } } private void appendViewToAllSpans(View view) { // traverse in reverse so that we end up assigning full span items to 0 for (int i = mSpanCount - 1; i >= 0; i--) { mSpans[i].appendToSpan(view); } } private void prependViewToAllSpans(View view) { // traverse in reverse so that we end up assigning full span items to 0 for (int i = mSpanCount - 1; i >= 0; i--) { mSpans[i].prependToSpan(view); } } private void layoutDecoratedWithMargins(View child, int left, int top, int right, int bottom) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (DEBUG) { Log.d(TAG, "layout decorated pos: " + lp.getViewLayoutPosition() + ", span:" + lp.getSpanIndex() + ", fullspan:" + lp.mFullSpan + ". l:" + left + ",t:" + top + ", r:" + right + ", b:" + bottom); } layoutDecorated(child, left + lp.leftMargin, top + lp.topMargin, right - lp.rightMargin , bottom - lp.bottomMargin); } private void updateAllRemainingSpans(int layoutDir, int targetLine) { for (int i = 0; i < mSpanCount; i++) { if (mSpans[i].mViews.isEmpty()) { continue; } updateRemainingSpans(mSpans[i], layoutDir, targetLine); } } private void updateRemainingSpans(Span span, int layoutDir, int targetLine) { final int deletedSize = span.getDeletedSize(); if (layoutDir == LayoutState.LAYOUT_START) { final int line = span.getStartLine(); if (line + deletedSize <= targetLine) { mRemainingSpans.set(span.mIndex, false); } } else { final int line = span.getEndLine(); if (line - deletedSize >= targetLine) { mRemainingSpans.set(span.mIndex, false); } } } private int getMaxStart(int def) { int maxStart = mSpans[0].getStartLine(def); for (int i = 1; i < mSpanCount; i++) { final int spanStart = mSpans[i].getStartLine(def); if (spanStart > maxStart) { maxStart = spanStart; } } return maxStart; } private int getMinStart(int def) { int minStart = mSpans[0].getStartLine(def); for (int i = 1; i < mSpanCount; i++) { final int spanStart = mSpans[i].getStartLine(def); if (spanStart < minStart) { minStart = spanStart; } } return minStart; } boolean areAllEndsEqual() { int end = mSpans[0].getEndLine(Span.INVALID_LINE); for (int i = 1; i < mSpanCount; i++) { if (mSpans[i].getEndLine(Span.INVALID_LINE) != end) { return false; } } return true; } boolean areAllStartsEqual() { int start = mSpans[0].getStartLine(Span.INVALID_LINE); for (int i = 1; i < mSpanCount; i++) { if (mSpans[i].getStartLine(Span.INVALID_LINE) != start) { return false; } } return true; } private int getMaxEnd(int def) { int maxEnd = mSpans[0].getEndLine(def); for (int i = 1; i < mSpanCount; i++) { final int spanEnd = mSpans[i].getEndLine(def); if (spanEnd > maxEnd) { maxEnd = spanEnd; } } return maxEnd; } private int getMinEnd(int def) { int minEnd = mSpans[0].getEndLine(def); for (int i = 1; i < mSpanCount; i++) { final int spanEnd = mSpans[i].getEndLine(def); if (spanEnd < minEnd) { minEnd = spanEnd; } } return minEnd; } private void recycleFromStart(RecyclerView.Recycler recycler, int line) { while (getChildCount() > 0) { View child = getChildAt(0); if (mPrimaryOrientation.getDecoratedEnd(child) <= line) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); // Don't recycle the last View in a span not to lose span's start/end lines if (lp.mFullSpan) { for (int j = 0; j < mSpanCount; j++) { if (mSpans[j].mViews.size() == 1) { return; } } for (int j = 0; j < mSpanCount; j++) { mSpans[j].popStart(); } } else { if (lp.mSpan.mViews.size() == 1) { return; } lp.mSpan.popStart(); } removeAndRecycleView(child, recycler); } else { return;// done } } } private void recycleFromEnd(RecyclerView.Recycler recycler, int line) { final int childCount = getChildCount(); int i; for (i = childCount - 1; i >= 0; i--) { View child = getChildAt(i); if (mPrimaryOrientation.getDecoratedStart(child) >= line) { LayoutParams lp = (LayoutParams) child.getLayoutParams(); // Don't recycle the last View in a span not to lose span's start/end lines if (lp.mFullSpan) { for (int j = 0; j < mSpanCount; j++) { if (mSpans[j].mViews.size() == 1) { return; } } for (int j = 0; j < mSpanCount; j++) { mSpans[j].popEnd(); } } else { if (lp.mSpan.mViews.size() == 1) { return; } lp.mSpan.popEnd(); } removeAndRecycleView(child, recycler); } else { return;// done } } } /** * @return True if last span is the first one we want to fill */ private boolean preferLastSpan(int layoutDir) { if (mOrientation == HORIZONTAL) { return (layoutDir == LayoutState.LAYOUT_START) != mShouldReverseLayout; } return ((layoutDir == LayoutState.LAYOUT_START) == mShouldReverseLayout) == isLayoutRTL(); } /** * Finds the span for the next view. */ private Span getNextSpan(LayoutState layoutState) { final boolean preferLastSpan = preferLastSpan(layoutState.mLayoutDirection); final int startIndex, endIndex, diff; if (preferLastSpan) { startIndex = mSpanCount - 1; endIndex = -1; diff = -1; } else { startIndex = 0; endIndex = mSpanCount; diff = 1; } if (layoutState.mLayoutDirection == LayoutState.LAYOUT_END) { Span min = null; int minLine = Integer.MAX_VALUE; final int defaultLine = mPrimaryOrientation.getStartAfterPadding(); for (int i = startIndex; i != endIndex; i += diff) { final Span other = mSpans[i]; int otherLine = other.getEndLine(defaultLine); if (otherLine < minLine) { min = other; minLine = otherLine; } } return min; } else { Span max = null; int maxLine = Integer.MIN_VALUE; final int defaultLine = mPrimaryOrientation.getEndAfterPadding(); for (int i = startIndex; i != endIndex; i += diff) { final Span other = mSpans[i]; int otherLine = other.getStartLine(defaultLine); if (otherLine > maxLine) { max = other; maxLine = otherLine; } } return max; } } @Override public boolean canScrollVertically() { return mOrientation == VERTICAL; } @Override public boolean canScrollHorizontally() { return mOrientation == HORIZONTAL; } @Override public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) { return scrollBy(dx, recycler, state); } @Override public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) { return scrollBy(dy, recycler, state); } private int calculateScrollDirectionForPosition(int position) { if (getChildCount() == 0) { return mShouldReverseLayout ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START; } final int firstChildPos = getFirstChildPosition(); return position < firstChildPos != mShouldReverseLayout ? LayoutState.LAYOUT_START : LayoutState.LAYOUT_END; } @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { LinearSmoothScroller scroller = new LinearSmoothScroller(recyclerView.getContext()) { @Override public PointF computeScrollVectorForPosition(int targetPosition) { final int direction = calculateScrollDirectionForPosition(targetPosition); if (direction == 0) { return null; } if (mOrientation == HORIZONTAL) { return new PointF(direction, 0); } else { return new PointF(0, direction); } } }; scroller.setTargetPosition(position); startSmoothScroll(scroller); } @Override public void scrollToPosition(int position) { if (mPendingSavedState != null && mPendingSavedState.mAnchorPosition != position) { mPendingSavedState.invalidateAnchorPositionInfo(); } mPendingScrollPosition = position; mPendingScrollPositionOffset = INVALID_OFFSET; requestLayout(); } /** * Scroll to the specified adapter position with the given offset from layout start. * <p> * Note that scroll position change will not be reflected until the next layout call. * <p> * If you are just trying to make a position visible, use {@link #scrollToPosition(int)}. * * @param position Index (starting at 0) of the reference item. * @param offset The distance (in pixels) between the start edge of the item view and * start edge of the RecyclerView. * @see #setReverseLayout(boolean) * @see #scrollToPosition(int) */ public void scrollToPositionWithOffset(int position, int offset) { if (mPendingSavedState != null) { mPendingSavedState.invalidateAnchorPositionInfo(); } mPendingScrollPosition = position; mPendingScrollPositionOffset = offset; requestLayout(); } int scrollBy(int dt, RecyclerView.Recycler recycler, RecyclerView.State state) { final int referenceChildPosition; final int layoutDir; if (dt > 0) { // layout towards end layoutDir = LayoutState.LAYOUT_END; referenceChildPosition = getLastChildPosition(); } else { layoutDir = LayoutState.LAYOUT_START; referenceChildPosition = getFirstChildPosition(); } mLayoutState.mRecycle = true; updateLayoutState(referenceChildPosition, state); setLayoutStateDirection(layoutDir); mLayoutState.mCurrentPosition = referenceChildPosition + mLayoutState.mItemDirection; final int absDt = Math.abs(dt); mLayoutState.mAvailable = absDt; int consumed = fill(recycler, mLayoutState, state); final int totalScroll; if (absDt < consumed) { totalScroll = dt; } else if (dt < 0) { totalScroll = -consumed; } else { // dt > 0 totalScroll = consumed; } if (DEBUG) { Log.d(TAG, "asked " + dt + " scrolled" + totalScroll); } mPrimaryOrientation.offsetChildren(-totalScroll); // always reset this if we scroll for a proper save instance state mLastLayoutFromEnd = mShouldReverseLayout; return totalScroll; } private int getLastChildPosition() { final int childCount = getChildCount(); return childCount == 0 ? 0 : getPosition(getChildAt(childCount - 1)); } private int getFirstChildPosition() { final int childCount = getChildCount(); return childCount == 0 ? 0 : getPosition(getChildAt(0)); } /** * Finds the first View that can be used as an anchor View. * * @return Position of the View or 0 if it cannot find any such View. */ private int findFirstReferenceChildPosition(int itemCount) { final int limit = getChildCount(); for (int i = 0; i < limit; i++) { final View view = getChildAt(i); final int position = getPosition(view); if (position >= 0 && position < itemCount) { return position; } } return 0; } /** * Finds the last View that can be used as an anchor View. * * @return Position of the View or 0 if it cannot find any such View. */ private int findLastReferenceChildPosition(int itemCount) { for (int i = getChildCount() - 1; i >= 0; i--) { final View view = getChildAt(i); final int position = getPosition(view); if (position >= 0 && position < itemCount) { return position; } } return 0; } @SuppressWarnings("deprecation") @Override public RecyclerView.LayoutParams generateDefaultLayoutParams() { if (mOrientation == HORIZONTAL) { return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT); } else { return new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } } @Override public RecyclerView.LayoutParams generateLayoutParams(Context c, AttributeSet attrs) { return new LayoutParams(c, attrs); } @Override public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { if (lp instanceof ViewGroup.MarginLayoutParams) { return new LayoutParams((ViewGroup.MarginLayoutParams) lp); } else { return new LayoutParams(lp); } } @Override public boolean checkLayoutParams(RecyclerView.LayoutParams lp) { return lp instanceof LayoutParams; } public int getOrientation() { return mOrientation; } @Nullable @Override public View onFocusSearchFailed(View focused, int direction, RecyclerView.Recycler recycler, RecyclerView.State state) { if (getChildCount() == 0) { return null; } final View directChild = findContainingItemView(focused); if (directChild == null) { return null; } resolveShouldLayoutReverse(); final int layoutDir = convertFocusDirectionToLayoutDirection(direction); if (layoutDir == LayoutState.INVALID_LAYOUT) { return null; } LayoutParams prevFocusLayoutParams = (LayoutParams) directChild.getLayoutParams(); boolean prevFocusFullSpan = prevFocusLayoutParams.mFullSpan; final Span prevFocusSpan = prevFocusLayoutParams.mSpan; final int referenceChildPosition; if (layoutDir == LayoutState.LAYOUT_END) { // layout towards end referenceChildPosition = getLastChildPosition(); } else { referenceChildPosition = getFirstChildPosition(); } updateLayoutState(referenceChildPosition, state); setLayoutStateDirection(layoutDir); mLayoutState.mCurrentPosition = referenceChildPosition + mLayoutState.mItemDirection; mLayoutState.mAvailable = (int) (MAX_SCROLL_FACTOR * mPrimaryOrientation.getTotalSpace()); mLayoutState.mStopInFocusable = true; mLayoutState.mRecycle = false; fill(recycler, mLayoutState, state); mLastLayoutFromEnd = mShouldReverseLayout; if (!prevFocusFullSpan) { View view = prevFocusSpan.getFocusableViewAfter(referenceChildPosition, layoutDir); if (view != null && view != directChild) { return view; } } // either could not find from the desired span or prev view is full span. // traverse all spans if (preferLastSpan(layoutDir)) { for (int i = mSpanCount - 1; i >= 0; i --) { View view = mSpans[i].getFocusableViewAfter(referenceChildPosition, layoutDir); if (view != null && view != directChild) { return view; } } } else { for (int i = 0; i < mSpanCount; i ++) { View view = mSpans[i].getFocusableViewAfter(referenceChildPosition, layoutDir); if (view != null && view != directChild) { return view; } } } return null; } /** * Converts a focusDirection to orientation. * * @param focusDirection One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, * {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, * {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD} * or 0 for not applicable * @return {@link LayoutState#LAYOUT_START} or {@link LayoutState#LAYOUT_END} if focus direction * is applicable to current state, {@link LayoutState#INVALID_LAYOUT} otherwise. */ private int convertFocusDirectionToLayoutDirection(int focusDirection) { switch (focusDirection) { case View.FOCUS_BACKWARD: return LayoutState.LAYOUT_START; case View.FOCUS_FORWARD: return LayoutState.LAYOUT_END; case View.FOCUS_UP: return mOrientation == VERTICAL ? LayoutState.LAYOUT_START : LayoutState.INVALID_LAYOUT; case View.FOCUS_DOWN: return mOrientation == VERTICAL ? LayoutState.LAYOUT_END : LayoutState.INVALID_LAYOUT; case View.FOCUS_LEFT: return mOrientation == HORIZONTAL ? LayoutState.LAYOUT_START : LayoutState.INVALID_LAYOUT; case View.FOCUS_RIGHT: return mOrientation == HORIZONTAL ? LayoutState.LAYOUT_END : LayoutState.INVALID_LAYOUT; default: if (DEBUG) { Log.d(TAG, "Unknown focus request:" + focusDirection); } return LayoutState.INVALID_LAYOUT; } } /** * LayoutParams used by StaggeredGridLayoutManager. * <p> * Note that if the orientation is {@link #VERTICAL}, the width parameter is ignored and if the * orientation is {@link #HORIZONTAL} the height parameter is ignored because child view is * expected to fill all of the space given to it. */ public static class LayoutParams extends RecyclerView.LayoutParams { /** * Span Id for Views that are not laid out yet. */ public static final int INVALID_SPAN_ID = -1; // Package scope to be able to access from tests. Span mSpan; boolean mFullSpan; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); } public LayoutParams(int width, int height) { super(width, height); } public LayoutParams(ViewGroup.MarginLayoutParams source) { super(source); } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } public LayoutParams(RecyclerView.LayoutParams source) { super(source); } /** * When set to true, the item will layout using all span area. That means, if orientation * is vertical, the view will have full width; if orientation is horizontal, the view will * have full height. * * @param fullSpan True if this item should traverse all spans. * @see #isFullSpan() */ public void setFullSpan(boolean fullSpan) { mFullSpan = fullSpan; } /** * Returns whether this View occupies all available spans or just one. * * @return True if the View occupies all spans or false otherwise. * @see #setFullSpan(boolean) */ public boolean isFullSpan() { return mFullSpan; } /** * Returns the Span index to which this View is assigned. * * @return The Span index of the View. If View is not yet assigned to any span, returns * {@link #INVALID_SPAN_ID}. */ public final int getSpanIndex() { if (mSpan == null) { return INVALID_SPAN_ID; } return mSpan.mIndex; } } // Package scoped to access from tests. class Span { static final int INVALID_LINE = Integer.MIN_VALUE; private ArrayList<View> mViews = new ArrayList<>(); int mCachedStart = INVALID_LINE; int mCachedEnd = INVALID_LINE; int mDeletedSize = 0; final int mIndex; private Span(int index) { mIndex = index; } int getStartLine(int def) { if (mCachedStart != INVALID_LINE) { return mCachedStart; } if (mViews.size() == 0) { return def; } calculateCachedStart(); return mCachedStart; } void calculateCachedStart() { final View startView = mViews.get(0); final LayoutParams lp = getLayoutParams(startView); mCachedStart = mPrimaryOrientation.getDecoratedStart(startView); if (lp.mFullSpan) { LazySpanLookup.FullSpanItem fsi = mLazySpanLookup .getFullSpanItem(lp.getViewLayoutPosition()); if (fsi != null && fsi.mGapDir == LayoutState.LAYOUT_START) { mCachedStart -= fsi.getGapForSpan(mIndex); } } } // Use this one when default value does not make sense and not having a value means a bug. int getStartLine() { if (mCachedStart != INVALID_LINE) { return mCachedStart; } calculateCachedStart(); return mCachedStart; } int getEndLine(int def) { if (mCachedEnd != INVALID_LINE) { return mCachedEnd; } final int size = mViews.size(); if (size == 0) { return def; } calculateCachedEnd(); return mCachedEnd; } void calculateCachedEnd() { final View endView = mViews.get(mViews.size() - 1); final LayoutParams lp = getLayoutParams(endView); mCachedEnd = mPrimaryOrientation.getDecoratedEnd(endView); if (lp.mFullSpan) { LazySpanLookup.FullSpanItem fsi = mLazySpanLookup .getFullSpanItem(lp.getViewLayoutPosition()); if (fsi != null && fsi.mGapDir == LayoutState.LAYOUT_END) { mCachedEnd += fsi.getGapForSpan(mIndex); } } } // Use this one when default value does not make sense and not having a value means a bug. int getEndLine() { if (mCachedEnd != INVALID_LINE) { return mCachedEnd; } calculateCachedEnd(); return mCachedEnd; } void prependToSpan(View view) { LayoutParams lp = getLayoutParams(view); lp.mSpan = this; mViews.add(0, view); mCachedStart = INVALID_LINE; if (mViews.size() == 1) { mCachedEnd = INVALID_LINE; } if (lp.isItemRemoved() || lp.isItemChanged()) { mDeletedSize += mPrimaryOrientation.getDecoratedMeasurement(view); } } void appendToSpan(View view) { LayoutParams lp = getLayoutParams(view); lp.mSpan = this; mViews.add(view); mCachedEnd = INVALID_LINE; if (mViews.size() == 1) { mCachedStart = INVALID_LINE; } if (lp.isItemRemoved() || lp.isItemChanged()) { mDeletedSize += mPrimaryOrientation.getDecoratedMeasurement(view); } } // Useful method to preserve positions on a re-layout. void cacheReferenceLineAndClear(boolean reverseLayout, int offset) { int reference; if (reverseLayout) { reference = getEndLine(INVALID_LINE); } else { reference = getStartLine(INVALID_LINE); } clear(); if (reference == INVALID_LINE) { return; } if ((reverseLayout && reference < mPrimaryOrientation.getEndAfterPadding()) || (!reverseLayout && reference > mPrimaryOrientation.getStartAfterPadding())) { return; } if (offset != INVALID_OFFSET) { reference += offset; } mCachedStart = mCachedEnd = reference; } void clear() { mViews.clear(); invalidateCache(); mDeletedSize = 0; } void invalidateCache() { mCachedStart = INVALID_LINE; mCachedEnd = INVALID_LINE; } void setLine(int line) { mCachedEnd = mCachedStart = line; } void popEnd() { final int size = mViews.size(); View end = mViews.remove(size - 1); final LayoutParams lp = getLayoutParams(end); lp.mSpan = null; if (lp.isItemRemoved() || lp.isItemChanged()) { mDeletedSize -= mPrimaryOrientation.getDecoratedMeasurement(end); } if (size == 1) { mCachedStart = INVALID_LINE; } mCachedEnd = INVALID_LINE; } void popStart() { View start = mViews.remove(0); final LayoutParams lp = getLayoutParams(start); lp.mSpan = null; if (mViews.size() == 0) { mCachedEnd = INVALID_LINE; } if (lp.isItemRemoved() || lp.isItemChanged()) { mDeletedSize -= mPrimaryOrientation.getDecoratedMeasurement(start); } mCachedStart = INVALID_LINE; } public int getDeletedSize() { return mDeletedSize; } LayoutParams getLayoutParams(View view) { return (LayoutParams) view.getLayoutParams(); } void onOffset(int dt) { if (mCachedStart != INVALID_LINE) { mCachedStart += dt; } if (mCachedEnd != INVALID_LINE) { mCachedEnd += dt; } } public int findFirstVisibleItemPosition() { return mReverseLayout ? findOneVisibleChild(mViews.size() - 1, -1, false) : findOneVisibleChild(0, mViews.size(), false); } public int findFirstCompletelyVisibleItemPosition() { return mReverseLayout ? findOneVisibleChild(mViews.size() - 1, -1, true) : findOneVisibleChild(0, mViews.size(), true); } public int findLastVisibleItemPosition() { return mReverseLayout ? findOneVisibleChild(0, mViews.size(), false) : findOneVisibleChild(mViews.size() - 1, -1, false); } public int findLastCompletelyVisibleItemPosition() { return mReverseLayout ? findOneVisibleChild(0, mViews.size(), true) : findOneVisibleChild(mViews.size() - 1, -1, true); } int findOneVisibleChild(int fromIndex, int toIndex, boolean completelyVisible) { final int start = mPrimaryOrientation.getStartAfterPadding(); final int end = mPrimaryOrientation.getEndAfterPadding(); final int next = toIndex > fromIndex ? 1 : -1; for (int i = fromIndex; i != toIndex; i += next) { final View child = mViews.get(i); final int childStart = mPrimaryOrientation.getDecoratedStart(child); final int childEnd = mPrimaryOrientation.getDecoratedEnd(child); if (childStart < end && childEnd > start) { if (completelyVisible) { if (childStart >= start && childEnd <= end) { return getPosition(child); } } else { return getPosition(child); } } } return NO_POSITION; } /** * Depending on the layout direction, returns the View that is after the given position. */ public View getFocusableViewAfter(int referenceChildPosition, int layoutDir) { View candidate = null; if (layoutDir == LayoutState.LAYOUT_START) { final int limit = mViews.size(); for (int i = 0; i < limit; i++) { final View view = mViews.get(i); if (view.isFocusable() && (getPosition(view) > referenceChildPosition == mReverseLayout) ) { candidate = view; } else { break; } } } else { for (int i = mViews.size() - 1; i >= 0; i--) { final View view = mViews.get(i); if (view.isFocusable() && (getPosition(view) > referenceChildPosition == !mReverseLayout)) { candidate = view; } else { break; } } } return candidate; } } /** * An array of mappings from adapter position to span. * This only grows when a write happens and it grows up to the size of the adapter. */ static class LazySpanLookup { private static final int MIN_SIZE = 10; int[] mData; List<FullSpanItem> mFullSpanItems; /** * Invalidates everything after this position, including full span information */ int forceInvalidateAfter(int position) { if (mFullSpanItems != null) { for (int i = mFullSpanItems.size() - 1; i >= 0; i--) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition >= position) { mFullSpanItems.remove(i); } } } return invalidateAfter(position); } /** * returns end position for invalidation. */ int invalidateAfter(int position) { if (mData == null) { return RecyclerView.NO_POSITION; } if (position >= mData.length) { return RecyclerView.NO_POSITION; } int endPosition = invalidateFullSpansAfter(position); if (endPosition == RecyclerView.NO_POSITION) { Arrays.fill(mData, position, mData.length, LayoutParams.INVALID_SPAN_ID); return mData.length; } else { // just invalidate items in between Arrays.fill(mData, position, endPosition + 1, LayoutParams.INVALID_SPAN_ID); return endPosition + 1; } } int getSpan(int position) { if (mData == null || position >= mData.length) { return LayoutParams.INVALID_SPAN_ID; } else { return mData[position]; } } void setSpan(int position, Span span) { ensureSize(position); mData[position] = span.mIndex; } int sizeForPosition(int position) { int len = mData.length; while (len <= position) { len *= 2; } return len; } void ensureSize(int position) { if (mData == null) { mData = new int[Math.max(position, MIN_SIZE) + 1]; Arrays.fill(mData, LayoutParams.INVALID_SPAN_ID); } else if (position >= mData.length) { int[] old = mData; mData = new int[sizeForPosition(position)]; System.arraycopy(old, 0, mData, 0, old.length); Arrays.fill(mData, old.length, mData.length, LayoutParams.INVALID_SPAN_ID); } } void clear() { if (mData != null) { Arrays.fill(mData, LayoutParams.INVALID_SPAN_ID); } mFullSpanItems = null; } void offsetForRemoval(int positionStart, int itemCount) { if (mData == null || positionStart >= mData.length) { return; } ensureSize(positionStart + itemCount); System.arraycopy(mData, positionStart + itemCount, mData, positionStart, mData.length - positionStart - itemCount); Arrays.fill(mData, mData.length - itemCount, mData.length, LayoutParams.INVALID_SPAN_ID); offsetFullSpansForRemoval(positionStart, itemCount); } private void offsetFullSpansForRemoval(int positionStart, int itemCount) { if (mFullSpanItems == null) { return; } final int end = positionStart + itemCount; for (int i = mFullSpanItems.size() - 1; i >= 0; i--) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition < positionStart) { continue; } if (fsi.mPosition < end) { mFullSpanItems.remove(i); } else { fsi.mPosition -= itemCount; } } } void offsetForAddition(int positionStart, int itemCount) { if (mData == null || positionStart >= mData.length) { return; } ensureSize(positionStart + itemCount); System.arraycopy(mData, positionStart, mData, positionStart + itemCount, mData.length - positionStart - itemCount); Arrays.fill(mData, positionStart, positionStart + itemCount, LayoutParams.INVALID_SPAN_ID); offsetFullSpansForAddition(positionStart, itemCount); } private void offsetFullSpansForAddition(int positionStart, int itemCount) { if (mFullSpanItems == null) { return; } for (int i = mFullSpanItems.size() - 1; i >= 0; i--) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition < positionStart) { continue; } fsi.mPosition += itemCount; } } /** * Returns when invalidation should end. e.g. hitting a full span position. * Returned position SHOULD BE invalidated. */ private int invalidateFullSpansAfter(int position) { if (mFullSpanItems == null) { return RecyclerView.NO_POSITION; } final FullSpanItem item = getFullSpanItem(position); // if there is an fsi at this position, get rid of it. if (item != null) { mFullSpanItems.remove(item); } int nextFsiIndex = -1; final int count = mFullSpanItems.size(); for (int i = 0; i < count; i++) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition >= position) { nextFsiIndex = i; break; } } if (nextFsiIndex != -1) { FullSpanItem fsi = mFullSpanItems.get(nextFsiIndex); mFullSpanItems.remove(nextFsiIndex); return fsi.mPosition; } return RecyclerView.NO_POSITION; } public void addFullSpanItem(FullSpanItem fullSpanItem) { if (mFullSpanItems == null) { mFullSpanItems = new ArrayList<>(); } final int size = mFullSpanItems.size(); for (int i = 0; i < size; i++) { FullSpanItem other = mFullSpanItems.get(i); if (other.mPosition == fullSpanItem.mPosition) { if (DEBUG) { throw new IllegalStateException("two fsis for same position"); } else { mFullSpanItems.remove(i); } } if (other.mPosition >= fullSpanItem.mPosition) { mFullSpanItems.add(i, fullSpanItem); return; } } // if it is not added to a position. mFullSpanItems.add(fullSpanItem); } public FullSpanItem getFullSpanItem(int position) { if (mFullSpanItems == null) { return null; } for (int i = mFullSpanItems.size() - 1; i >= 0; i--) { final FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition == position) { return fsi; } } return null; } /** * @param minPos inclusive * @param maxPos exclusive * @param gapDir if not 0, returns FSIs on in that direction * @param hasUnwantedGapAfter If true, when full span item has unwanted gaps, it will be * returned even if its gap direction does not match. */ public FullSpanItem getFirstFullSpanItemInRange(int minPos, int maxPos, int gapDir, boolean hasUnwantedGapAfter) { if (mFullSpanItems == null) { return null; } final int limit = mFullSpanItems.size(); for (int i = 0; i < limit; i++) { FullSpanItem fsi = mFullSpanItems.get(i); if (fsi.mPosition >= maxPos) { return null; } if (fsi.mPosition >= minPos && (gapDir == 0 || fsi.mGapDir == gapDir || (hasUnwantedGapAfter && fsi.mHasUnwantedGapAfter))) { return fsi; } } return null; } /** * We keep information about full span items because they may create gaps in the UI. */ static class FullSpanItem implements Parcelable { int mPosition; int mGapDir; int[] mGapPerSpan; // A full span may be laid out in primary direction but may have gaps due to // invalidation of views after it. This is recorded during a reverse scroll and if // view is still on the screen after scroll stops, we have to recalculate layout boolean mHasUnwantedGapAfter; public FullSpanItem(Parcel in) { mPosition = in.readInt(); mGapDir = in.readInt(); mHasUnwantedGapAfter = in.readInt() == 1; int spanCount = in.readInt(); if (spanCount > 0) { mGapPerSpan = new int[spanCount]; in.readIntArray(mGapPerSpan); } } public FullSpanItem() { } int getGapForSpan(int spanIndex) { return mGapPerSpan == null ? 0 : mGapPerSpan[spanIndex]; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mPosition); dest.writeInt(mGapDir); dest.writeInt(mHasUnwantedGapAfter ? 1 : 0); if (mGapPerSpan != null && mGapPerSpan.length > 0) { dest.writeInt(mGapPerSpan.length); dest.writeIntArray(mGapPerSpan); } else { dest.writeInt(0); } } @Override public String toString() { return "FullSpanItem{" + "mPosition=" + mPosition + ", mGapDir=" + mGapDir + ", mHasUnwantedGapAfter=" + mHasUnwantedGapAfter + ", mGapPerSpan=" + Arrays.toString(mGapPerSpan) + '}'; } public static final Parcelable.Creator<FullSpanItem> CREATOR = new Parcelable.Creator<FullSpanItem>() { @Override public FullSpanItem createFromParcel(Parcel in) { return new FullSpanItem(in); } @Override public FullSpanItem[] newArray(int size) { return new FullSpanItem[size]; } }; } } /** * @hide */ public static class SavedState implements Parcelable { int mAnchorPosition; int mVisibleAnchorPosition; // Replacement for span info when spans are invalidated int mSpanOffsetsSize; int[] mSpanOffsets; int mSpanLookupSize; int[] mSpanLookup; List<LazySpanLookup.FullSpanItem> mFullSpanItems; boolean mReverseLayout; boolean mAnchorLayoutFromEnd; boolean mLastLayoutRTL; public SavedState() { } SavedState(Parcel in) { mAnchorPosition = in.readInt(); mVisibleAnchorPosition = in.readInt(); mSpanOffsetsSize = in.readInt(); if (mSpanOffsetsSize > 0) { mSpanOffsets = new int[mSpanOffsetsSize]; in.readIntArray(mSpanOffsets); } mSpanLookupSize = in.readInt(); if (mSpanLookupSize > 0) { mSpanLookup = new int[mSpanLookupSize]; in.readIntArray(mSpanLookup); } mReverseLayout = in.readInt() == 1; mAnchorLayoutFromEnd = in.readInt() == 1; mLastLayoutRTL = in.readInt() == 1; //noinspection unchecked mFullSpanItems = in.readArrayList( LazySpanLookup.FullSpanItem.class.getClassLoader()); } public SavedState(SavedState other) { mSpanOffsetsSize = other.mSpanOffsetsSize; mAnchorPosition = other.mAnchorPosition; mVisibleAnchorPosition = other.mVisibleAnchorPosition; mSpanOffsets = other.mSpanOffsets; mSpanLookupSize = other.mSpanLookupSize; mSpanLookup = other.mSpanLookup; mReverseLayout = other.mReverseLayout; mAnchorLayoutFromEnd = other.mAnchorLayoutFromEnd; mLastLayoutRTL = other.mLastLayoutRTL; mFullSpanItems = other.mFullSpanItems; } void invalidateSpanInfo() { mSpanOffsets = null; mSpanOffsetsSize = 0; mSpanLookupSize = 0; mSpanLookup = null; mFullSpanItems = null; } void invalidateAnchorPositionInfo() { mSpanOffsets = null; mSpanOffsetsSize = 0; mAnchorPosition = NO_POSITION; mVisibleAnchorPosition = NO_POSITION; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mAnchorPosition); dest.writeInt(mVisibleAnchorPosition); dest.writeInt(mSpanOffsetsSize); if (mSpanOffsetsSize > 0) { dest.writeIntArray(mSpanOffsets); } dest.writeInt(mSpanLookupSize); if (mSpanLookupSize > 0) { dest.writeIntArray(mSpanLookup); } dest.writeInt(mReverseLayout ? 1 : 0); dest.writeInt(mAnchorLayoutFromEnd ? 1 : 0); dest.writeInt(mLastLayoutRTL ? 1 : 0); dest.writeList(mFullSpanItems); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } /** * Data class to hold the information about an anchor position which is used in onLayout call. */ private class AnchorInfo { int mPosition; int mOffset; boolean mLayoutFromEnd; boolean mInvalidateOffsets; void reset() { mPosition = NO_POSITION; mOffset = INVALID_OFFSET; mLayoutFromEnd = false; mInvalidateOffsets = false; } void assignCoordinateFromPadding() { mOffset = mLayoutFromEnd ? mPrimaryOrientation.getEndAfterPadding() : mPrimaryOrientation.getStartAfterPadding(); } void assignCoordinateFromPadding(int addedDistance) { if (mLayoutFromEnd) { mOffset = mPrimaryOrientation.getEndAfterPadding() - addedDistance; } else { mOffset = mPrimaryOrientation.getStartAfterPadding() + addedDistance; } } } }
amirlotfi/Nikagram
app/src/main/java/ir/nikagram/messenger/support/widget/StaggeredGridLayoutManager.java
Java
gpl-2.0
117,717
<?php /* * * Ampoliros Application Server * * http://www.ampoliros.com * * * * Copyright (C) 2000-2004 Solarix * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ // $Id: AllAmpolirosTests.php,v 1.4 2004-07-08 15:04:27 alex Exp $ /** * Ampoliros test case. * How to run the tests: * carthag carthag.dev.unit.textui.TestRunner AllAmpolirosTests * @package com.solarix.ampoliros.tests * @author Alex Pagnoni <alex.pagnoni@solarix.it> * @copyright Copyright 2000-2004 Solarix Srl * @since 4.0 */ package('com.solarix.ampoliros.tests'); import('carthag.dev.unit.framework.TestSuite'); import('com.solarix.ampoliros.tests.core.AllAmpolirosCoreTests'); import('com.solarix.ampoliros.tests.datatransfer.AllAmpolirosDatatransferTests'); /** * @package com.solarix.ampoliros.tests * @author Alex Pagnoni <alex.pagnoni@solarix.it> * @copyright Copyright 2000-2004 Solarix Srl * @since 4.0 */ class AllAmpolirosTests extends Object { public static function suite() { require('ampoliros.php'); $suite= new TestSuite('Ampoliros'); $suite -> addTest(AllAmpolirosCoreTests :: suite()); $suite -> addTest(AllAmpolirosDatatransferTests :: suite()); return $suite; } } ?>
alexpagnoni/ampoliros
var/classes/com/solarix/ampoliros/tests/AllAmpolirosTests.php
PHP
gpl-2.0
1,961
# vim:fileencoding=utf-8:noet try: import pygit2 as git class Repository(object): __slots__ = ('directory') def __init__(self, directory): self.directory = directory def _repo(self): return git.Repository(self.directory) def status(self, path=None): '''Return status of repository or file. Without file argument: returns status of the repository: :First column: working directory status (D: dirty / space) :Second column: index status (I: index dirty / space) :Third column: presense of untracked files (U: untracked files / space) :None: repository clean With file argument: returns status of this file. Output is equivalent to the first two columns of "git status --porcelain" (except for merge statuses as they are not supported by libgit2). ''' if path: try: status = self._repo().status_file(path) except (KeyError, ValueError): return None if status == git.GIT_STATUS_CURRENT: return None else: if status & git.GIT_STATUS_WT_NEW: return '??' if status & git.GIT_STATUS_IGNORED: return '!!' if status & git.GIT_STATUS_INDEX_NEW: index_status = 'A' elif status & git.GIT_STATUS_INDEX_DELETED: index_status = 'D' elif status & git.GIT_STATUS_INDEX_MODIFIED: index_status = 'M' else: index_status = ' ' if status & git.GIT_STATUS_WT_DELETED: wt_status = 'D' elif status & git.GIT_STATUS_WT_MODIFIED: wt_status = 'M' else: wt_status = ' ' return index_status + wt_status else: wt_column = ' ' index_column = ' ' untracked_column = ' ' for status in self._repo().status().values(): if status & git.GIT_STATUS_WT_NEW: untracked_column = 'U' continue if status & (git.GIT_STATUS_WT_DELETED | git.GIT_STATUS_WT_MODIFIED): wt_column = 'D' if status & (git.GIT_STATUS_INDEX_NEW | git.GIT_STATUS_INDEX_MODIFIED | git.GIT_STATUS_INDEX_DELETED): index_column = 'I' r = wt_column + index_column + untracked_column return r if r != ' ' else None def branch(self): try: ref = self._repo().lookup_reference('HEAD') except KeyError: return None try: target = ref.target except ValueError: return '[DETACHED HEAD]' if target.startswith('refs/heads/'): return target[11:] else: return '[DETACHED HEAD]' except ImportError: from subprocess import Popen, PIPE def readlines(cmd, cwd): p = Popen(cmd, shell=False, stdout=PIPE, stderr=PIPE, cwd=cwd) p.stderr.close() with p.stdout: for line in p.stdout: yield line[:-1].decode('utf-8') class Repository(object): __slots__ = ('directory',) def __init__(self, directory): self.directory = directory def _gitcmd(self, *args): return readlines(('git',) + args, self.directory) def status(self, path=None): if path: try: return next(self._gitcmd('status', '--porcelain', '--ignored', '--', path))[:2] except StopIteration: return None else: wt_column = ' ' index_column = ' ' untracked_column = ' ' for line in self._gitcmd('status', '--porcelain'): if line[0] == '?': untracked_column = 'U' continue elif line[0] == '!': continue if line[0] != ' ': index_column = 'I' if line[1] != ' ': wt_column = 'D' r = wt_column + index_column + untracked_column return r if r != ' ' else None def branch(self): for line in self._gitcmd('branch', '-l'): if line[0] == '*': return line[2:] return None
DaneelOliwan/dotfiles-vim
.vim/bundle/powerline/powerline/lib/vcs/git.py
Python
gpl-2.0
3,605
<?php /** * Mkdir class * * Class to rename directory/file & manage errors in doing so. * * PHP version 3 * * 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. * * @category Chisimba * @package files * @author David Wafula * @copyright 2010, University of the Witwatersrand & AVOIR Project * @license http://www.gnu.org/licenses/gpl-2.0.txt The GNU General Public License * @link http://avoir.uwc.ac.za,http://www.chisimba.com * @see References to other sections (if any)... */ class rename extends object { /** * * @var string $oldFilePath The old file including its path, * or the folder if rename a folder. * */ var $oldFilePath; /** * * @var string $newFilePath The new file including its path, * or the folder if rename a folder. * */ var $newFilePath; /** * * @var boolean $err TRUE|FALSE; TRUE if error, else false * */ var $err; /** * * @var string $errMst The error message * */ var $errMsg; /** * * @var object $objLanguage String to hold the language object * */ var $objLanguage; /** * * Standard init method to set the default values for * the properties. * */ function init() { $this->oldFilePath = NULL; $this->newFilePath = NULL; $this->err = NULL; $this->errMsg = NULL; // Create an instance of the language object $this->objLanguage = $this->getObject('language', 'language'); } /** * * Renames a file/folder. Needs oldFilePath and newFilePath to be set * to a valid path before hand * * @access Public * */ function rename() { if ($this->oldFilePath != NULL && $this->newFilePath != NULL) { rename($this->oldFilePath,$this->newFilePath); //If the file path is null } else { $this->err = TRUE; $this->errMsg = $this->objLanguage->languageText('mod_files_err_nofilepath') . ": Old - " . $this->oldFilePath.", New - " . $this->newFilePath; return FALSE; } } //function } // end of class ?>
chisimba/chisimba
app/core_modules/files/classes/rename_class_inc.php
PHP
gpl-2.0
2,996
var searchData= [ ['vectororient',['vectorOrient',['../group___t_xC3_xA1rol_xC3_xB3k.html#gab13a5c3bc64237cc95301c3359a757c8',1,'RobotStateHistory']]] ];
muszkab/Alkalmazasfejlesztes-hazi
RobotDiagnosticApp/docs/html/search/variables_b.js
JavaScript
gpl-2.0
156
/* $Revision: 77449 $ */ /** @file * VBoxGuestLibR0 - Physical memory heap. */ /* * Copyright (C) 2006-2007 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ #include "VBGLInternal.h" /** * Checks whether the host supports physical page lists or not. * * @returns true if it does, false if it doesn't. */ DECLR0VBGL(bool) VbglR0CanUsePhysPageList(void) { int rc = vbglR0Enter(); return RT_SUCCESS(rc) && VBGLR0_CAN_USE_PHYS_PAGE_LIST(/*a_fLocked =*/ false); }
VirtualMonitor/VirtualMonitor
src/VBox/Additions/common/VBoxGuestLib/VbglR0CanUsePhysPageList.cpp
C++
gpl-2.0
1,404
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\DICOM; use PHPExiftool\Driver\AbstractTag; class GridPitch extends AbstractTag { protected $Id = '0018,7044'; protected $Name = 'GridPitch'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Grid Pitch'; }
Droces/casabio
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/DICOM/GridPitch.php
PHP
gpl-2.0
695
from random import randint, shuffle, choice from time import clock from _utils import InvalidTableException, copy_table def solve(table): table = _check_table(table) if _is_done(table): return table else: coordinates = _get_minimum_array(table) trials = table[coordinates[0]][coordinates[1]]["possibilities"][:] shuffle(trials) for elem in trials: try: ctable = copy_table(table) ctable[coordinates[0]][coordinates[1]]["possibilities"] = [elem] # print_table(ctable) # print return solve(ctable) except InvalidTableException: pass # print "subiu" raise InvalidTableException("Nao ha solucao") def _is_done(table): for line in table: for elem in line: if len(elem["possibilities"]) > 1: return False elif len(elem["possibilities"]) == 0: raise InvalidTableException("Celula Vazia") return True def _check_table(table): #find unchecked #clean other possibilities #raise exception if some possibility becomes void while not _is_check_done(table): unchecked_set = _find_unchecked(table) for value,x,y in unchecked_set: _fix_house(table,value,x,y) _fix_column(table,value,x,y) _fix_line(table,value,x,y) table[y][x]["checked"] = True return table def _is_check_done(table): for line in table: for elem in line: if len(elem["possibilities"]) == 1 and not elem["checked"]: return False return True def _find_unchecked(table): result = set() for i, line in enumerate(table): for j, elem in enumerate(line): if len(elem["possibilities"]) == 1 and not elem["checked"]: result.add((elem["possibilities"][0],j,i)) return result def _fix_house(table,value,x,y): x0 = (x/3)*3 + 1 y0 = (y/3)*3 + 1 to_fix = [(x0-1,y0-1),(x0-1,y0),(x0-1,y0+1),(x0,y0-1),(x0,y0),(x0,y0+1),(x0+1,y0-1),(x0+1,y0),(x0+1,y0+1)] to_fix.remove((x,y)) for i,j in to_fix: _fix(table,value,i,j) def _fix_column(table,value,x,y): columns = range(len(table)) columns.remove(y) for j in columns: _fix(table,value,x,j) def _fix_line(table,value,x,y): lines = range(len(table)) lines.remove(x) for i in lines: _fix(table,value,i,y) def _fix(table, value, x, y): try: table[y][x]["possibilities"].remove(value) except ValueError: pass if len(table[y][x]["possibilities"]) < 1: raise InvalidTableException("Nao deu!") def _get_minimum_array(table): result = list() size = len(table) for i, line in enumerate(table): for j, elem in enumerate(line): if not elem["checked"]: if not result: result.append((i,j)) size = len(elem["possibilities"]) elif len(elem["possibilities"]) == size: result.append((i,j)) elif len(elem["possibilities"]) < size: result = list() result.append((i,j)) size = len(elem["possibilities"]) return choice(result)
jonasrla/web_sudoku
helper/solver.py
Python
gpl-2.0
3,362
# -*- coding: utf-8 -*- from sqlalchemy import text from listenbrainz import db class User(object): """ User class required by the api-compat """ def __init__(self, id, created, name, api_key): self.id = id self.created = created self.name = name self.api_key = api_key @staticmethod def get_id(mb_id): with db.engine.connect() as connection: result = connection.execute(text(""" SELECT id FROM "user" WHERE musicbrainz_id = :mb_id """), {"mb_id": mb_id}) row = result.fetchone() if row: return row[0] return None @staticmethod def load_by_name(mb_id): with db.engine.connect() as connection: result = connection.execute(text(""" SELECT id, created, musicbrainz_id, auth_token \ FROM "user" \ WHERE musicbrainz_id = :mb_id """), {"mb_id": mb_id}) row = result.fetchone() if row: return User(row['id'], row['created'], row['musicbrainz_id'], row['auth_token']) return None @staticmethod def load_by_id(serial): with db.engine.connect() as connection: result = connection.execute(text(""" SELECT id, created, musicbrainz_id, auth_token \ FROM "user" WHERE id=:id """), {"id": serial}) row = result.fetchone() if row: return User(row['id'], row['created'], row['musicbrainz_id'], row['auth_token']) return None @staticmethod def load_by_sessionkey(session_key, api_key): with db.engine.connect() as connection: result = connection.execute(text(""" SELECT "user".id , "user".created , "user".musicbrainz_id , "user".auth_token FROM api_compat.session, "user" WHERE api_key = :api_key AND sid = :sk AND "user".id = session.user_id """), { "api_key": api_key, "sk": session_key }) row = result.fetchone() if row: return User(row['id'], row['created'], row['musicbrainz_id'], row['auth_token']) return None @staticmethod def get_play_count(user_id, listenstore): """ Get playcount from the given user name. """ user = User.load_by_id(user_id) return listenstore.get_listen_count_for_user(user.id)
metabrainz/listenbrainz-server
listenbrainz/db/lastfm_user.py
Python
gpl-2.0
2,716
require_relative './spec_helper' require 'norikra/typedef' require 'json' require 'digest' describe Norikra::Typedef do context 'instanciated as lazy typedef' do it 'has no fields' do t = Norikra::Typedef.new expect(t.fields.size).to eql(0) expect(t.baseset).to be_nil end it 'has no query/data fieldsets' do t = Norikra::Typedef.new expect(t.queryfieldsets.size).to eql(0) expect(t.datafieldsets.size).to eql(0) end describe '#lazy?' do it 'returns true' do t = Norikra::Typedef.new expect(t.lazy?).to be_true end end describe '#reserve' do it 'add field definition without any baseset' do t = Norikra::Typedef.new t.reserve('k', 'string') expect(t.fields['k'].type).to eql('string') expect(t.fields['k'].optional?).to be_true t.reserve('l', 'long', false) expect(t.fields['l'].type).to eql('long') expect(t.fields['l'].optional?).to be_false end end describe '#activate' do context 'without any fields reserved' do it 'stores all fields in specified fieldset' do t = Norikra::Typedef.new set = Norikra::FieldSet.new({'a'=>'string','b'=>'long','c'=>'double'}) t.activate(set) expect(t.fields.size).to eql(3) expect(t.fields['a'].optional?).to be_false expect(t.fields.object_id).not_to eql(set.fields.object_id) expect(t.baseset.object_id).not_to eql(set.object_id) end end end end context 'instanciated as non-lazy typedef' do it 'has no query/data fieldsets' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) expect(t.queryfieldsets.size).to eql(0) expect(t.datafieldsets.size).to eql(0) end it 'has all fields as required' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) expect(t.fields['a'].type).to eql('string') expect(t.fields['a'].optional?).to be_false expect(t.fields['b'].type).to eql('long') expect(t.fields['b'].optional?).to be_false end describe '#lazy?' do it 'returns false' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) expect(t.lazy?).to be_false end end describe '#field_defined?' do it 'returns boolean to indicate all fields specified exists or not' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) expect(t.field_defined?(['a','b'])).to be_true expect(t.field_defined?(['a'])).to be_true expect(t.field_defined?(['b'])).to be_true expect(t.field_defined?([])).to be_true expect(t.field_defined?(['a','b','c'])).to be_false expect(t.field_defined?(['a','c'])).to be_false expect(t.field_defined?(['c'])).to be_false end end describe '#reserve' do it 'adds field definitions as required or optional' do t = Norikra::Typedef.new({'a' => 'string'}) expect(t.fields.size).to eql(1) t.reserve('b', 'boolean', false) expect(t.fields.size).to eql(2) expect(t.fields['b'].type).to eql('boolean') expect(t.fields['b'].optional?).to be_false t.reserve('c', 'double', true) expect(t.fields.size).to eql(3) expect(t.fields['c'].type).to eql('double') expect(t.fields['c'].optional?).to be_true end end describe '#consistent?' do context 'without any additional reserved fields' do it 'checks all fields of specified fieldset are super-set of baseset or not' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long'}) expect(t.consistent?(set)).to be_true set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double'}) expect(t.consistent?(set)).to be_true set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'int'}) expect(t.consistent?(set)).to be_false set = Norikra::FieldSet.new({'a' => 'string'}) expect(t.consistent?(set)).to be_false end end context 'with some additional reserved fields' do it 'checks all fields of specified fieldset with baseset and additional reserved fields' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) t.reserve('c', 'double', false) # required t.reserve('d', 'boolean', true) # optional set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long'}) expect(t.consistent?(set)).to be_false set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double'}) expect(t.consistent?(set)).to be_true set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double', 'd' => 'boolean'}) expect(t.consistent?(set)).to be_true set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double', 'd' => 'string'}) expect(t.consistent?(set)).to be_false set = Norikra::FieldSet.new({'a' => 'string', 'b' => 'long', 'c' => 'double', 'd' => 'boolean', 'e' => 'string'}) expect(t.consistent?(set)).to be_true end end end describe '#push' do it 'does not accepts fieldset which conflicts pre-defined fields' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) expect { t.push(:query, Norikra::FieldSet.new({'a'=>'string','b'=>'int'})) }.to raise_error(ArgumentError) expect { t.push(:data, Norikra::FieldSet.new({'a'=>'string'})) }.to raise_error(ArgumentError) end it 'accepts fieldsets which is consistent with self' do t = Norikra::Typedef.new({'a'=>'string','b'=>'long'}) expect(t.fields.size).to eql(2) expect { t.push(:query, Norikra::FieldSet.new({'a'=>'string','b'=>'long'})) }.not_to raise_error(ArgumentError) expect { t.push(:data, Norikra::FieldSet.new({'a'=>'string','b'=>'long'})) }.not_to raise_error(ArgumentError) expect(t.fields.size).to eql(2) set_a = Norikra::FieldSet.new({'a'=>'string','b'=>'long','c'=>'double'}) t.push(:data, set_a) expect(t.fields.size).to eql(3) expect(t.fields['c'].type).to eql('double') expect(t.fields['c'].optional?).to be_true t.push(:query, Norikra::FieldSet.new({'a'=>'string','b'=>'long','d'=>'string'})) expect(t.fields.size).to eql(4) expect(t.fields['d'].type).to eql('string') expect(t.fields['d'].optional?).to be_true end end describe '#refer' do context 'for event defined by data-fieldset already known' do it 'returns fieldset that already known itself' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) set1 = Norikra::FieldSet.new({'a'=>'string','b'=>'long'}) t.push(:data, set1) r = t.refer({'a'=>'foobar','b'=>200000000}) expect(r).to be_instance_of(Norikra::FieldSet) expect(r.object_id).to eql(set1.object_id) end end context 'for event with known fields only' do it 'returns fieldset that is overwritten with known field definitions' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) t.reserve('c','boolean',true) t.reserve('d','double',true) r = t.refer({'a'=>'hoge','b'=>'2000','c'=>'true','d'=>'3.14'}) expect(t.datafieldsets.include?(r)).to be_false expect(r.fields['a'].type).to eql('string') expect(r.fields['b'].type).to eql('long') expect(r.fields['c'].type).to eql('boolean') expect(r.fields['d'].type).to eql('double') end end context 'for event with some unknown fields' do it 'returns fieldset that contains fields as string for unknowns' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) r = t.refer({'a'=>'hoge','b'=>'2000','c'=>'true','d'=>'3.14'}) expect(t.datafieldsets.include?(r)).to be_false expect(r.fields['a'].type).to eql('string') expect(r.fields['b'].type).to eql('long') expect(r.fields['c'].type).to eql('string') expect(r.fields['d'].type).to eql('string') end end end describe '#format' do it 'returns hash value with formatted fields as defined' do t = Norikra::Typedef.new({'a' => 'string', 'b' => 'long'}) t.reserve('c','boolean',true) t.reserve('d','double',true) d = t.format({'a'=>'hoge','b'=>'2000','c'=>'true','d'=>'3.14'}) expect(d['a']).to be_instance_of(String) expect(d['a']).to eql('hoge') expect(d['b']).to be_instance_of(Fixnum) expect(d['b']).to eql(2000) expect(d['c']).to be_instance_of(TrueClass) expect(d['c']).to eql(true) expect(d['d']).to be_instance_of(Float) expect(d['d']).to eql(3.14) end end end end
achied/norikra
spec/typedef_spec.rb
Ruby
gpl-2.0
9,075
/** * @file * Main JS file for react functionality. * */ (function ($) { Drupal.behaviors.react_blocks = { attach: function (context) { // A div with some text in it var CommentBox = React.createClass({displayName: 'CommentBox', loadCommentsFromServer: function() { $.ajax({ url: this.props.url, dataType: 'json', success: function(data) { this.setState({data: data}); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, getInitialState: function() { return {data: []}; }, componentDidMount: function() { this.loadCommentsFromServer(); setInterval(this.loadCommentsFromServer, this.props.pollInterval); }, render: function() { return ( React.createElement("div", {className: "commentBox"}, React.createElement("h3", null, React.createElement("b", null, "Check them out!")), React.createElement(CommentList, {data: this.state.data}) ) ); } }); var CommentList = React.createClass({displayName: 'CommentList', render: function() { var commentNodes = this.props.data.map(function (comment) { return ( React.createElement(Comment, {author: comment.name}, comment.subject ) ); }); return ( React.createElement("div", {className: "commentList"}, commentNodes ) ); } }); var Comment = React.createClass({displayName: 'Comment', render: function() { return ( React.createElement("div", {className: "comment"}, React.createElement("h2", {className: "commentAuthor"}, this.props.name ), this.props.subject ) ); } }); // Render our reactComponent React.render( React.createElement(CommentBox, {url: "../api/v1/comment.json", pollInterval: 2000}), document.getElementById('recent-comments') ); } } })(jQuery);
changemachine/jellyfish
sites/all/modules/react_blocks/build/.module-cache/fcda948e5eafc0c8b5f89fe71d221f278abccbd5.js
JavaScript
gpl-2.0
2,307
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Noised.Core.DB; using Noised.Core.IOC; using Noised.Logging; namespace Noised.Core.Plugins { /// <summary> /// Basic plugin loader /// </summary> public class PluginLoader : IPluginLoader { #region Fields private const String PLUGIN_TYPE_NAME = "Noised.Core.Plugins.IPlugin"; private List<IPlugin> plugins = new List<IPlugin>(); private readonly Dictionary<IPlugin, PluginMetaData> metaDataStore = new Dictionary<IPlugin, PluginMetaData>(); #endregion #region IPluginLoader public int LoadPlugins() { var logger = IoC.Get<ILogging>(); using (var unitOfWork = IoC.Get<IUnitOfWork>()) { var files = unitOfWork.PluginRepository.GetFiles(".nplugin"); FileInfo currentFile = null; foreach (var file in files) { currentFile = file; IEnumerable<Type> pluginTypes; try { //Getting IPlugin types from the plugin assembly Assembly assembly = Assembly.LoadFrom(file.FullName); Type pluginBaseType = Type.GetType(PLUGIN_TYPE_NAME); pluginTypes = assembly.GetTypes().Where(pluginBaseType.IsAssignableFrom); if (pluginTypes != null && pluginTypes.Any()) { //Plugin init data var pluginInitializer = new PluginInitializer { Logging = logger }; //Instantiate the first IPlugin type found Type concreteType = pluginTypes.First(); var plugin = (IPlugin)Activator.CreateInstance(concreteType, pluginInitializer); plugins.Add(plugin); //Loading meta data PluginMetaData metaData = null; metaData = unitOfWork.PluginRepository.GetForFile(file); if (metaData != null) { metaDataStore.Add(plugin, metaData); } else { throw new Exception("No PluginMetaData found for file " + file); } IoC.Get<ILogging>().Info( String.Format("Loaded Plugin {0} - {1}", metaData.Name, metaData.Description)); } else { IoC.Get<ILogging>().Error( String.Format("No IPlugin implementation found in assembly {0}", file)); } } catch (Exception e) { IoC.Get<ILogging>().Error( "Could not load plugin " + currentFile.FullName); IoC.Get<ILogging>().Error(e.Message); } } plugins = plugins.OrderByDescending(p => p.GetMetaData().Priority).ToList(); return plugins.Count; } } public IEnumerable<IPlugin> GetPlugins() { return plugins; } public IEnumerable<T> GetPlugins<T>() where T : IPlugin { var concretPlugins = new List<T>(); foreach (var plugin in plugins) { if (plugin is T) { concretPlugins.Add((T)plugin); } } return concretPlugins; } public T GetPlugin<T>() where T : IPlugin { IPlugin plugin = GetPlugins<T>().OrderByDescending(p => p.GetMetaData().Priority).FirstOrDefault(); if (plugin != null) return (T)plugin; return default(T); } public PluginMetaData GetMetaData(IPlugin plugin) { PluginMetaData ret; metaDataStore.TryGetValue(plugin, out ret); return ret; } #endregion }; }
bennygr/noised
src/NoisedCore/Plugins/PluginLoader.cs
C#
gpl-2.0
4,643
import javax.swing.JLabel;
plumer/java-8e-assignments
learn/ch12/MyFrameWithComponents.java
Java
gpl-2.0
27
<?php /*-------------------------------------------------------------------------------------------------------------| www.vdm.io |------/ ____ ____ __ __ __ /\ _`\ /\ _`\ __ /\ \__ __/\ \ /\ \__ \ \,\L\_\ __ _ __ ___ ___ ___ ___ \ \ \/\ \/\_\ ____\ \ ,_\ _ __ /\_\ \ \____ __ __\ \ ,_\ ___ _ __ \/_\__ \ /'__`\/\`'__\/' __` __`\ / __`\ /' _ `\ \ \ \ \ \/\ \ /',__\\ \ \/ /\`'__\/\ \ \ '__`\/\ \/\ \\ \ \/ / __`\/\`'__\ /\ \L\ \/\ __/\ \ \/ /\ \/\ \/\ \/\ \L\ \/\ \/\ \ \ \ \_\ \ \ \/\__, `\\ \ \_\ \ \/ \ \ \ \ \L\ \ \ \_\ \\ \ \_/\ \L\ \ \ \/ \ `\____\ \____\\ \_\ \ \_\ \_\ \_\ \____/\ \_\ \_\ \ \____/\ \_\/\____/ \ \__\\ \_\ \ \_\ \_,__/\ \____/ \ \__\ \____/\ \_\ \/_____/\/____/ \/_/ \/_/\/_/\/_/\/___/ \/_/\/_/ \/___/ \/_/\/___/ \/__/ \/_/ \/_/\/___/ \/___/ \/__/\/___/ \/_/ /------------------------------------------------------------------------------------------------------------------------------------/ @version 2.0.x @created 22nd October, 2015 @package Sermon Distributor @subpackage default_preachers-table.php @author Llewellyn van der Merwe <https://www.vdm.io/> @copyright Copyright (C) 2015. All Rights Reserved @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html A sermon distributor that links to Dropbox. /----------------------------------------------------------------------------------------------------------------------------------*/ // No direct access to this file defined('_JEXEC') or die('Restricted access'); // Column counter $column_nr = 1; // build the table class $color = $this->params->get('preachers_table_color'); switch ($color) { case 1: // Red $tableClass = ' metro-red'; break; case 2: // Purple $tableClass = ' metro-purple'; break; case 3: // Green $tableClass = ' metro-green'; break; case 4: // Dark Blue $tableClass = ' metro-blue'; break; case 6: // Uikit style $tableClass = ' uk-table'; break; case 7: // Custom Style $tableClass = ' preachers-table'; break; default: // Light Blue and other $tableClass = ''; break; } ?> <table class="footable<?php echo $tableClass; ?>" data-page-size="100"> <thead> <tr> <th data-toggle="true"><?php echo JText::_('COM_SERMONDISTRIBUTOR_NAME'); ?></th> <?php if ($this->params->get('preachers_desc')): ?> <th data-hide="all"><?php echo JText::_('COM_SERMONDISTRIBUTOR_DESCRIPTION'); $column_nr++; ?></th> <?php endif; ?> <?php if ($this->params->get('preachers_website')): ?> <th data-hide="all"><?php echo JText::_('COM_SERMONDISTRIBUTOR_WEBSITE'); $column_nr++; ?></th> <?php endif; ?> <?php if ($this->params->get('preachers_email')): ?> <th data-hide="all"><?php echo JText::_('COM_SERMONDISTRIBUTOR_EMAIL'); $column_nr++; ?></th> <?php endif; ?> <?php if ($this->params->get('preachers_hits')): ?> <th data-type="numeric"><?php echo JText::_('COM_SERMONDISTRIBUTOR_HITS'); $column_nr++; ?></th> <?php endif; ?> <?php if ($this->params->get('preachers_sermon_count')): ?> <th data-type="numeric" data-hide="phone,tablet"><?php echo JText::_('COM_SERMONDISTRIBUTOR_SERMON_COUNT'); $column_nr++;?></th> <?php endif; ?> </tr> </thead> <tfoot class="hide-if-no-paging"> <tr> <td colspan="<?php echo $column_nr; ?>"> <div class="pagination pagination-centered"></div> </td> </tr> </tfoot> <tbody> <?php foreach ($this->items as $item): ?> <tr><?php $item->params = $this->params; echo JLayoutHelper::render('preachersrow', $item); ?></tr> <?php endforeach; ?> </tbody> </table> <script> // page loading pause jQuery(window).load(function() { // do some stuff once page is loaded jQuery('.footable').footable(); }); </script>
SermonDistributor/Joomla-3-Component
site/views/preachers/tmpl/default_preachers-table.php
PHP
gpl-2.0
4,011
<?php /* * * * * * * * * * * Author: Calc, calc@list.ru, 8(916) 506-7002 * mxtel, 2010, Calc (r) * * * * * * * * * */ defined("INDEX") or die('404 go to <a href="/">index.php</a>'); $do = get_var('do',0); $id = get_var('id',0); $pid = get_var('pid',0); $type= get_var('type','port'); //get for ajah $oid = get_var('oid',0); $table = 'inbound_opts'; $tbl = new tbl($table); // id oid pid type tid list($oid, $pid, $type, $tid) = array( post_var('oid',$oid), post_var('pid',$pid), post_var('type',$type), post_var('tid')); switch($do) { case 1: //добавляем элемент _mysql_query($tbl->insert( array(0, $oid, $pid, $type, $tid))); redir("gr=$gr&oid=$oid&pid=$pid",1); break; case 2: $hide = $_GET['hide']; if($hide!=1) $hide=0; _mysql_query($tbl->update_k(array('id'=>$id), array('hide'=>$hide))); redir("gr=$gr&oid=$oid&pid=$pid",1); break; case 10: _mysql_query($tbl->update(array('id'=>$id), array(0, $oid, $pid, $type, $tid))); redir("gr=$gr&oid=$oid&pid=$pid",1); break; case 11: do_del($table,$id,"gr=$gr&oid=$oid&pid=$pid",'','',1); break; case 'ajah_tid': $ret = ''; $tbl = $type; if($type=='port'){ $tbl = 'users'; $n = 'intno';} $ret.= tag_f_se('tid', $tid, db_sel1($tbl, $n, '', "where oid=$oid")); echo $ret; exit(); break; case 'ajah_main': $ret = maintbl(); echo $ret; exit(); break; } $tid = 0; if($id) { $q = "select * from $table where id=$id"; $r = mysql_query($q); list($id,$oid, $pid,$type,$tid) = mysql_fetch_array($r); } $int_a = db_sel('users','intno','',"oid=$oid and "); $int_a[0] = 'Внешний'; $peer_a = db_sel('peers','','',"oid in($oid,24) and "); //$peer_a1 = $peer_a2; $peer_a[0] = 'Все'; $body.=' <form action="?gr='.$gr.'&oid='.$oid.'&pid='.$pid.'&do='.( ($id==0) ? 1 : 10 ).'&id='.$id.'" method="post"> Пир: '.tag_f_se('pid',$pid, $peer_a,'pid').' Тип: '.tag_f_se('type',$type,$r_types,'type',1).' Значение: <span id="tid">'.tag_f_se('tid',$tid,db_sel1('users', 'intno','',$w="where oid=$oid")).'</span> '.tag_f_sm($id).' '.tag_f_hi('oid',$oid).' </form>'; // запрос для формы ajah $jq.= " $(\"#pid\").change(function() { val = $(\"#pid\").val(); url = './?gr=$gr&oid=$oid&pid=' + val + '&do=ajah_main'; $(\"#main\").text(\"\").load(url); }); $(\"#type\").change(function() { val = $(\"#type\").val(); url = './?gr=$gr&oid=$oid&pid=$pid&do=ajah_tid&type=' + val; $(\"#tid\").text(\"\").load(url); }); "; $body.= tag_a("?gr=user&oid=$oid",'Назад'); $body.= '<div id="main">'; $body.= maintbl(); $body.= '</div>'; function maintbl() { global $gr,$oid,$pid,$table; $q = " select io.id, io.oid, io.pid, io.type, io.tid, p.name, o.name from $table as io left join peers as p on p.id=io.pid left join org as o on o.id=io.oid where io.pid=$pid order by io.type"; //echo $q; $r = _mysql_query($q); $n = mysql_num_rows($r); $body = ''; $body.= tag_t_o_('maintbl'); $body.= tag_tr(); $body.= tag_th('id'); $body.= tag_th('oid'); $body.= tag_th('pid'); $body.= tag_th('type'); $body.= tag_th('tid'); $body.= tag_th('x'); $body.= tag_tr(1); $exten = ''; if($n) { for($i=0;$i<$n;$i++) { list($id, $oid, $pid, $type, $tid, $pname, $oname) = mysql_fetch_array($r); $body.= tag_tr(); $body.= tag_td(tag_a("?gr=$gr&oid=$oid&pid=$pid&id=$id",$id),$i); $body.= tag_td($oname,$i); $body.= tag_td($pname,$i); $body.= tag_td($type,$i); $body.= tag_td(db_field('users', $tid, 'intno'),$i); $body.= tag_td(tag_a_x("?gr=$gr&oid=$oid&pid=$pid&id=$id&do=11"),$i); $acc = ''; $body.= tag_tr(1); } } $body.= '<td colspan="9">'.$n.' записей</td>'; $body.= tag_t_c(); $exten = file_get_contents("./tmp/ext.inbound"); $body.= '<pre>'; $body.= $exten; $body.= '</pre>'; $body.= 'Входящая маршрутизация устанавливает макрос, который будет обслуживать входящий вызов. Если макрос не указан, то вызов будет поступать на все локальные номера, закрепленные за пиром.'; return $body; }
Calc86/tel
mods/iopt.php
PHP
gpl-2.0
4,787
package com.dynamo2.tianma.model; public class ObjectField extends MongodbModel { private String name; private String uniqueMark; private int type; private String linkedObject; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUniqueMark() { return uniqueMark; } public void setUniqueMark(String uniqueMark) { this.uniqueMark = uniqueMark; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getLinkedObject() { return linkedObject; } public void setLinkedObject(String linkedObject) { this.linkedObject = linkedObject; } }
dynamo2/tianma
mycrm/src/main/java/com/dynamo2/tianma/model/ObjectField.java
Java
gpl-2.0
715
# datepicker-1.py from wax import * from wax.tools.datepicker import DatePicker import datetime import time class MainFrame(VerticalFrame): def Body(self): p1 = HorizontalPanel(self) dp1 = DatePicker(p1) p1.AddComponent(dp1) p1.AddSpace(10) b1 = Button(p1, "Add 1 day", event=self.AddOneDay) p1.AddComponent(b1) p1.Pack() self.AddComponent(p1, expand='h', border=4) p2 = HorizontalPanel(self) dp2 = DatePicker(p2, style='dropdown', show_century=1) p2.AddComponent(dp2) p2.AddSpace(10) b2 = Button(p2, "Yesterday", event=self.SetToYesterday) p2.AddComponent(b2) p2.Pack() self.AddComponent(p2, expand='h', border=4) self.Pack() self.BackgroundColor = p1.BackgroundColor self.dp1 = dp1 self.dp2 = dp2 # restrict dp2's range to current year thisyear = time.localtime(time.time())[0] dp2.SetRange((thisyear, 1, 1), (thisyear, 12, 31)) def AddOneDay(self, event): self.dp1.Inc() print "Date set to:", self.dp1.Value def SetToYesterday(self, event): now = time.localtime(time.time()) self.dp2.Value = now[:3] # tuple: (year, month, day) self.dp2.Dec() app = Application(MainFrame, title='datepicker-1') app.Run()
MSMBA/msmba-workflow
msmba-workflow/srclib/wax/examples/datepicker-1.py
Python
gpl-2.0
1,480
## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # https://morningstarsecurity.com/research/whatweb ## Plugin.define do name "Hughes-Satellite-Router" authors [ "Brendan Coles <bcoles@gmail.com>", # 2011-08-14 ] version "0.1" description "Hughes IPoS (IP over Satellite) router" website "http://www.hughes.com/ProductsAndTechnology/BroadbandSatelliteSystems/Pages/default.aspx" # ShodanHQ results as at 2011-08-14 # # 3,874 for HUGHES Terminal # Google results as at 2011-08-14 # # 2 for inurl:sys_info "Print this page. It will be needed if your system fails." # Dorks # dorks [ 'inurl:sys_info "Print this page. It will be needed if your system fails."' ] # Matches # matches [ # Frameset { :text=>'<frame src=/fs/dynaform/dw_logo.html scrolling=no marginheight=0 marginwidth=0 NORESIZE>' }, # Model Detection # Frameset # Title { :model=>/<title>([A-Z]{0,2}[\d]{1,5}[A-Z]?) System Control Center<\/title>/ }, # Model Detection # /fs/dynaform/welcome.html { :url=>"/fs/dynaform/welcome.html", :model=>/<ctrlCenter style="font-size: 14pt; color: #000000; font-weight: bold">([^\s]+) <\/ctrlCenter>/ }, # Version Detection # /sys_info/ { :url=>"/sys_info/", :version=>/<\/td><\/tr><tr><td><div class=text>Software Release:<\/td><td><div class=text>([^<^\s]+)<\/td><\/tr>/ }, # MAC Address Detection # /sys_info/ { :url=>"/sys_info/", :string=>/<\/td><\/tr><tr><td><div class=text>LAN[\d]{1,2} MAC Address:<\/td><td><div class=text>([A-F\d:]{17})<\/td><\/tr>/ }, # WWW-Authenticate Header { :search=>"headers[www-authenticate]", :regexp=>/^Basic realm="HUGHES Terminal"$/ }, ] end
urbanadventurer/WhatWeb
plugins/hughes-satellite-router.rb
Ruby
gpl-2.0
1,736
#include <iostream> #include <map> #include <vector> #include <string> #include <algorithm> #include <fstream> using namespace std; vector<string> dict; map<string, int> map_dict; void reformat(string &line) { int sz = line.size(); int j = 1; for(int i = 1; i < sz; ++i) { if(isalpha(line[i])) line[j++] = line[i]; } line.resize(j); } int main() { freopen("./critical.txt", "r", stdin); string word; while(cin>>word) { if(word[0]=='#') break; if(word.size() <= 7) { dict.push_back(word); map_dict[word]++; } } sort(dict.begin(), dict.end()); cin.ignore(); string line; while(getline(cin, line)) { if(line[0] == '#') break; reformat(line); sort(line.begin(), line.end()); map<string,int> key; do { int sz = line.size(); for(int i = 0; i < sz; ++i) { string s = line.substr(i, sz); if(!key[s]) key[s]++; } }while(next_permutation(line.begin(),line.end())); int cnt = 0; map<string, int>::iterator it; for(it = key.begin(); it != key.end(); ++it) { if(binary_search(dict.begin(), dict.end(), it->first)) { if(map_dict[it->first] > 1) cnt += map_dict[it->first]; else cnt++; } } cout << cnt << endl; key.clear(); line.clear(); } return 0; }
rahulroot/Uva
895/program.cpp
C++
gpl-2.0
1,399
export default (sequelize, dataTypes) => { return sequelize.define( 'Community', { id: sequelize.idType, subdomain: { type: dataTypes.TEXT, unique: true, allowNull: false, validate: { isLowercase: true, len: [1, 280], is: /^[a-zA-Z0-9-]+$/, // Must contain at least one letter, alphanumeric and hyphens }, }, domain: { type: dataTypes.TEXT, unique: true, }, title: { type: dataTypes.TEXT, allowNull: false }, citeAs: { type: dataTypes.TEXT }, publishAs: { type: dataTypes.TEXT }, description: { type: dataTypes.TEXT, validate: { len: [0, 280], }, }, avatar: { type: dataTypes.TEXT }, favicon: { type: dataTypes.TEXT }, accentColorLight: { type: dataTypes.STRING }, accentColorDark: { type: dataTypes.STRING }, hideCreatePubButton: { type: dataTypes.BOOLEAN }, headerLogo: { type: dataTypes.TEXT }, headerLinks: { type: dataTypes.JSONB }, headerColorType: { type: dataTypes.ENUM, values: ['light', 'dark', 'custom'], defaultValue: 'dark', }, useHeaderTextAccent: { type: dataTypes.BOOLEAN }, hideHero: { type: dataTypes.BOOLEAN }, hideHeaderLogo: { type: dataTypes.BOOLEAN }, heroLogo: { type: dataTypes.TEXT }, heroBackgroundImage: { type: dataTypes.TEXT }, heroBackgroundColor: { type: dataTypes.TEXT }, heroTextColor: { type: dataTypes.TEXT }, useHeaderGradient: { type: dataTypes.BOOLEAN }, heroImage: { type: dataTypes.TEXT }, heroTitle: { type: dataTypes.TEXT }, heroText: { type: dataTypes.TEXT }, heroPrimaryButton: { type: dataTypes.JSONB }, heroSecondaryButton: { type: dataTypes.JSONB }, heroAlign: { type: dataTypes.TEXT }, navigation: { type: dataTypes.JSONB }, hideNav: { type: dataTypes.BOOLEAN }, navLinks: { type: dataTypes.JSONB }, footerLinks: { type: dataTypes.JSONB }, footerLogoLink: { type: dataTypes.TEXT }, footerTitle: { type: dataTypes.TEXT }, footerImage: { type: dataTypes.TEXT }, website: { type: dataTypes.TEXT }, facebook: { type: dataTypes.TEXT }, twitter: { type: dataTypes.TEXT }, email: { type: dataTypes.TEXT }, issn: { type: dataTypes.TEXT }, isFeatured: { type: dataTypes.BOOLEAN }, viewHash: { type: dataTypes.STRING }, editHash: { type: dataTypes.STRING }, premiumLicenseFlag: { type: dataTypes.BOOLEAN, defaultValue: false }, defaultPubCollections: { type: dataTypes.JSONB }, /* Set by Associations */ organizationId: { type: dataTypes.UUID }, }, { classMethods: { associate: (models) => { const { Community, Organization, Collection, Page, Pub, ScopeSummary } = models; Community.belongsTo(Organization, { onDelete: 'CASCADE', as: 'organization', foreignKey: 'organizationId', }); Community.hasMany(Collection, { onDelete: 'CASCADE', as: 'collections', foreignKey: 'communityId', }); Community.hasMany(Pub, { onDelete: 'CASCADE', as: 'pubs', foreignKey: 'communityId', }); Community.hasMany(Page, { onDelete: 'CASCADE', as: 'pages', foreignKey: 'communityId', }); Community.belongsTo(ScopeSummary, { as: 'scopeSummary', foreignKey: 'scopeSummaryId', }); }, }, }, ); };
pubpub/pubpub
server/community/model.ts
TypeScript
gpl-2.0
3,307
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # # Copyright (C) 2006 Lukáš Lalinský # # 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.
Sophist-UK/Sophist_picard
picard/browser/__init__.py
Python
gpl-2.0
823
/* * EntityManager.cpp * * Created on: 29 Nov 2015 * Author: osboxes */ #include "EntityManager.h" #include "../syscalls/SysCalls.h" using namespace std; EntityManager::EntityManager(std::string fileName) :m_index("entity.idx"){ m_fname = fileName; m_fdReader = syscalls::open ( m_fname.c_str(),O_CREAT|O_RDONLY,0777 ); m_fdWriter = syscalls::open ( m_fname.c_str(),O_CREAT|O_WRONLY,0777 ); syscalls::lseek(m_fdWriter,0,SEEK_END); struct stat buf; fstat(m_fdWriter, &buf); m_offset = buf.st_size; } EntityManager::~EntityManager() { syscalls::close(m_fdReader); syscalls::close(m_fdWriter); } void EntityManager::persist(Entity entity){ char buffer[sizeof(Entity)]; memcpy(buffer, &entity, sizeof(Entity)); syscalls::write(m_fdWriter,buffer,sizeof(Entity)); m_index.addIndex(entity.nombre, m_offset); m_offset += sizeof(Entity); } void EntityManager::findAll(const char* name,std::list<Entity>& results){ std::list<long> offsets; m_index.getOffsets(name, offsets); for (std::list<long>::iterator it = offsets.begin(); it != offsets.end(); it++){ long offset = *it; Entity entity; syscalls::lseek(m_fdReader, offset,SEEK_SET); syscalls::read(m_fdReader, &entity, sizeof(Entity)); results.push_back(entity); } }
gguzelj/7559-TP2
DbLib/persistence/EntityManager.cpp
C++
gpl-2.0
1,262
#include "configio.h" #include <limits.h> static mystring default_bulletin_dir("bulletins"); static const mystring filename_bulletin_dir = "bulletin-dir"; mystring configuration::bulletin_dir() const { return read_dir(filename_bulletin_dir, default_bulletin_dir, (config_cache<mystring>&)bulletin_dir_cache); }
hetznerZApackages/vmailmgr
lib/config/_bulletin_dir.cc
C++
gpl-2.0
340
public class Star { int x; int y; int owner; int colony; public Star(int x,int y,int owner,int colony){ this.x = x; this.y = y; this.owner = owner; this.colony = colony; } }
TravisRidge/Gigaquadrant
Gigaquadrant/src/Star.java
Java
gpl-2.0
191
/* QUYNH NGA NGUYEN - ID: 700110099 Project FSE Chatroom - 18-652 Server-side file handles requests from clien-side. */ var app = require('express')(); var server = require('http').createServer(app); var io = require('socket.io')(server); var fs = require('fs'); var dbfile = "database.db"; var existed = fs.existsSync(dbfile); var sqlite3 = require('sqlite3').verbose(); var db = new sqlite3.Database(dbfile); app.get("/", function(req, res) { res.sendFile(__dirname + "/index.html"); }); app.get("/chatroom", function(req, res) { res.sendFile(__dirname + "/chatroom.html"); }); app.get("/style.css", function(req, res) { res.sendFile(__dirname + "/style.css"); }); app.get("/FSEChatroomLogo.png", function(req, res) { res.sendFile(__dirname + "/FSEChatroomLogo.png"); }); db.serialize(function() { if (!existed) { db.run("CREATE TABLE chatHistory (name TEXT, message TEXT, time TEXT)"); } }); io.on("connection", function(socket) { socket.on("join", function(name) { // if name already taken, emits an error event back to chatroom var socketList = io.sockets.sockets; var nameTaken = false; for (var i = 0; i < socketList.length; i++) { if (socketList[i].nickname === name) { nameTaken = true; break; } } if (nameTaken) { socket.emit("nameTaken", name); return; } // accepts new user. Sets the name associated with this user socket.nickname = name; // announces new user socket.broadcast.emit("newUser", name); socket.emit("newUser", name); // loads chat history db.serialize(function() { if (existed) { db.each("SELECT * FROM chatHistory", function(err, row) { socket.emit("message", row.name, row.message, row.time); }); } }); }); socket.on("newMessage", function(message) { var time = getTimeString(); socket.broadcast.emit("message", socket.nickname, message, time); socket.emit("message", socket.nickname, message, time); // saves message into database db.serialize(function() { db.run("INSERT into chatHistory (name, message, time)" + " VALUES (?, ?, ?)", socket.nickname, message, time); }); }); socket.on("disconnect", function() { socket.broadcast.emit("exit", socket.nickname); }); }); function getTimeString() { var date = new Date(); var ret = date.getMonth() + "." + date.getDate() + "." + date.getFullYear() + " "; var time = date.getHours(); if (time < 12) { ret += time + ":" + date.getMinutes() + "AM"; } else { if (time > 12) { time -= 12; } ret += time + ":" + date.getMinutes() + "PM"; } return ret; } server.listen(8080); //db.close();
quynhnga-nguyen/FSEChatRoom
server.js
JavaScript
gpl-2.0
2,600
<?php /** * Tools for creating thumbnails. * * @package Image * @author C. Erdmann * @link http://www.cerdmann.de/thumb * @author Robert Wetzlmayr * * Refactored from function.thumb.php by C. Erdmann, which contained * the following credit and licensing terms: * * Smarty plugin "Thumb" * Purpose: creates cached thumbnails * Home: http://www.cerdmann.com/thumb/ * Copyright (C) 2005 Christoph Erdmann * * 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, USA * * @author Christoph Erdmann (CE) <smarty@cerdmann.com> * @link http://www.cerdmann.com * * @author Benjamin Fleckenstein (BF) * @link http://www.benjaminfleckenstein.de * * @author Marcus Gueldenmeister (MG) * @link http://www.gueldenmeister.de/marcus/ * * @author Andreas Bösch (AB) */ /** * Output debug log. * * @global bool $verbose */ $verbose = false; /** * Creates thumbnails for larger images. * * @package Image */ class wet_thumb { /** * The width of your thumbnail. The height (if not set) will be * automatically calculated. * * @var int */ public $width; /** * The height of your thumbnail. The width (if not set) will be * automatically calculated. * * @var int */ public $height; /** * Set the longest side of the image if width, height and shortside is * not set. */ public $longside; /** * Set the shortest side of the image if width, height and longside is * not set. */ public $shortside; /** * Set to 'false' if your source image is smaller than the calculated * thumb and you do not want the image to get extrapolated. */ public $extrapolate; /** * Crops the image. * * If set to TRUE, image will be cropped in the center to destination width * and height params, while keeping aspect ratio. Otherwise the image will * get resized. * * @var bool */ public $crop; /** * Applies unsharpen mask. * * Set to FALSE if you don't want to use the Unsharp-Mask. * Thumbnail creation will be faster, but quality is reduced. * * @var bool */ public $sharpen; /** * If set to FALSE the image will not have a lens icon. * * @var bool */ public $hint; /** * Set to FALSE to get no lightgrey bottom bar. * * @var bool */ public $addgreytohint; /** * JPEG image quality (0...100, defaults to 80). * * @var int */ public $quality; /** * Set to your target URL (a href="linkurl"). * * @var string */ public $linkurl; /** * Will be inserted in the image-tag. * * @var string */ public $html; /** * An array of accepted image formats. * * @var array */ public $types = array('', '.gif', '.jpg', '.png'); /** * Source. * * @var array */ public $_SRC; /** * Destination. * * @var array */ public $_DST; /** * Constructor. */ public function __construct() { $this->extrapolate = false; $this->crop = true; $this->sharpen = true; $this->hint = true; $this->addgreytohint = true; $this->quality = 80; $this->html = ' alt="" title="" '; $this->link = true; } /** * Writes a thumbnail file. * * @param string $infile Image file name. * @param array $outfile Array of thumb file names (1...n) * @return bool TRUE on success */ public function write($infile, $outfile) { global $verbose; if ($verbose) { echo "writing thumb nail..."; } // Get source image info. if (!($temp = txpimagesize($infile, true)) || empty($temp['image'])) { return false; } $this->_SRC['file'] = $infile; $this->_SRC['width'] = $temp[0]; $this->_SRC['height'] = $temp[1]; $this->_SRC['type'] = $temp[2]; // 1=GIF, 2=JPEG, 3=PNG, 18=WebP, 19=AVIF. $this->_SRC['string'] = $temp[3]; $this->_SRC['image'] = $temp['image']; $this->_SRC['filename'] = basename($infile); //$this->_SRC['modified'] = filemtime($infile); /* // Make sure we have enough memory if the image is large. if (max($this->_SRC['width'], $this->_SRC['height']) > 1024) { $shorthand = array('K', 'M', 'G'); $tens = array('000', '000000', '000000000'); // A good enough decimal approximation of K, M, and G. // Do not *decrease* memory_limit. list($ml, $extra) = str_ireplace($shorthand, $tens, array(ini_get('memory_limit'), EXTRA_MEMORY)); if ($ml < $extra) { ini_set('memory_limit', EXTRA_MEMORY); } } // Read source image. if ($this->_SRC['type'] == 1) { $this->_SRC['image'] = imagecreatefromgif($this->_SRC['file']); } elseif ($this->_SRC['type'] == 2) { $this->_SRC['image'] = imagecreatefromjpeg($this->_SRC['file']); } elseif ($this->_SRC['type'] == 3) { $this->_SRC['image'] = imagecreatefrompng($this->_SRC['file']); } elseif ($this->_SRC['type'] == 18) { $this->_SRC['image'] = imagecreatefromwebp($this->_SRC['file']); } elseif ($this->_SRC['type'] == 19) { $this->_SRC['image'] = imagecreatefromavif($this->_SRC['file']); } */ // Ensure non-zero height/width. if (!$this->_SRC['height']) { $this->_SRC['height'] = 100; } if (!$this->_SRC['width']) { $this->_SRC['width'] = 100; } // Check image orientation. if ($this->_SRC['width'] >= $this->_SRC['height']) { $this->_SRC['format'] = 'landscape'; } else { $this->_SRC['format'] = 'portrait'; } // Get destination image info. if (is_numeric($this->width) and empty($this->height)) { $this->_DST['width'] = $this->width; $this->_DST['height'] = round($this->width/($this->_SRC['width']/$this->_SRC['height'])); } elseif (is_numeric($this->height) and empty($this->width)) { $this->_DST['height'] = $this->height; $this->_DST['width'] = round($this->height/($this->_SRC['height']/$this->_SRC['width'])); } elseif (is_numeric($this->width) and is_numeric($this->height)) { $this->_DST['width'] = $this->width; $this->_DST['height'] = $this->height; } elseif (is_numeric($this->longside) and empty($this->shortside)) { // Preserve aspect ratio based on provided height. if ($this->_SRC['format'] == 'portrait') { $this->_DST['height'] = $this->longside; $this->_DST['width'] = round($this->longside/($this->_SRC['height']/$this->_SRC['width'])); } else { $this->_DST['width'] = $this->longside; $this->_DST['height'] = round($this->longside/($this->_SRC['width']/$this->_SRC['height'])); } } elseif (is_numeric($this->shortside)) { // Preserve aspect ratio based on provided width. if ($this->_SRC['format'] == 'portrait') { $this->_DST['width'] = $this->shortside; $this->_DST['height'] = round($this->shortside/($this->_SRC['width']/$this->_SRC['height'])); } else { $this->_DST['height'] = $this->shortside; $this->_DST['width'] = round($this->shortside/($this->_SRC['height']/$this->_SRC['width'])); } } else { // Default dimensions. $this->width = 100; $this->_DST['width'] = $this->width; $this->_DST['height'] = round($this->width/($this->_SRC['width']/$this->_SRC['height'])); } // Don't make the new image larger than the original image. if ( $this->extrapolate === false && $this->_DST['height'] > $this->_SRC['height'] && $this->_DST['width'] > $this->_SRC['width'] ) { $this->_DST['width'] = $this->_SRC['width']; $this->_DST['height'] = $this->_SRC['height']; } $this->_DST['type'] = $this->_SRC['type']; $this->_DST['file'] = $outfile; // Crop image. $off_w = 0; $off_h = 0; if ($this->crop != false) { if ($this->_SRC['height'] < $this->_SRC['width']) { $ratio = (double) ($this->_SRC['height'] / $this->_DST['height']); $cpyWidth = round($this->_DST['width'] * $ratio); if ($cpyWidth > $this->_SRC['width']) { $ratio = (double) ($this->_SRC['width'] / $this->_DST['width']); $cpyWidth = $this->_SRC['width']; $cpyHeight = round($this->_DST['height'] * $ratio); $off_w = 0; $off_h = round(($this->_SRC['height'] - $cpyHeight) / 2); $this->_SRC['height'] = $cpyHeight; } else { $cpyHeight = $this->_SRC['height']; $off_w = round(($this->_SRC['width'] - $cpyWidth) / 2); $off_h = 0; $this->_SRC['width'] = $cpyWidth; } } else { $ratio = (double) ($this->_SRC['width'] / $this->_DST['width']); $cpyHeight = round($this->_DST['height'] * $ratio); if ($cpyHeight > $this->_SRC['height']) { $ratio = (double) ($this->_SRC['height'] / $this->_DST['height']); $cpyHeight = $this->_SRC['height']; $cpyWidth = round($this->_DST['width'] * $ratio); $off_w = round(($this->_SRC['width'] - $cpyWidth) / 2); $off_h = 0; $this->_SRC['width'] = $cpyWidth; } else { $cpyWidth = $this->_SRC['width']; $off_w = 0; $off_h = round(($this->_SRC['height'] - $cpyHeight) / 2); $this->_SRC['height'] = $cpyHeight; } } } // Create DST. $this->_DST['image'] = imagecreatetruecolor($this->_DST['width'], $this->_DST['height']); // GIF or PNG destination, set the transparency up. if ($this->_DST['type'] == 1 || $this->_DST['type'] == 3 || $this->_DST['type'] == 18) { $trans_idx = imagecolortransparent($this->_SRC['image']); $pallet_size = imagecolorstotal($this->_SRC['image']); // Is there a specific transparent colour? if ($trans_idx >= 0 && ($trans_idx < $pallet_size)) { $trans_color = imagecolorsforindex($this->_SRC['image'], $trans_idx); $trans_idx = imagecolorallocate( $this->_DST['image'], $trans_color['red'], $trans_color['green'], $trans_color['blue'] ); imagefill($this->_DST['image'], 0, 0, $trans_idx); imagecolortransparent($this->_DST['image'], $trans_idx); } elseif ($this->_DST['type'] == 3 || $this->_DST['type'] == 18 || $this->_DST['type'] == 19) { imagealphablending($this->_DST['image'], false); $transparent = imagecolorallocatealpha($this->_DST['image'], 0, 0, 0, 127); imagefill($this->_DST['image'], 0, 0, $transparent); imagesavealpha($this->_DST['image'], true); } } imagecopyresampled( $this->_DST['image'], $this->_SRC['image'], 0, 0, $off_w, $off_h, $this->_DST['width'], $this->_DST['height'], $this->_SRC['width'], $this->_SRC['height'] ); // avif weirdness if ($this->_DST['type'] == 19) { imageflip($this->_DST['image'], IMG_FLIP_HORIZONTAL); } if ($this->sharpen === true) { $this->_DST['image'] = UnsharpMask($this->_DST['image'], 80, .5, 3); } // Finally, the real dimensions. $this->height = $this->_DST['height']; $this->width = $this->_DST['width']; // Add magnifying glass. if ($this->hint === true) { // Should we really add white bars? if ($this->addgreytohint === true) { $trans = imagecolorallocatealpha($this->_DST['image'], 255, 255, 255, 25); imagefilledrectangle( $this->_DST['image'], 0, $this->_DST['height'] - 9, $this->_DST['width'], $this->_DST['height'], $trans ); } $magnifier = imagecreatefromstring(gzuncompress(base64_decode("eJzrDPBz5+WS4mJgYOD19HAJAtLcIMzBBiRXrilXA1IsxU6eIRxAUMOR0gHkcxZ4RBYD1QiBMOOlu3V/gIISJa4RJc5FqYklmfl5CiGZuakMBoZ6hkZ6RgYGJs77ex2BalRBaoLz00rKE4tSGXwTk4vyc1NTMhMV3DKLUsvzi7KLFXwjFEAa2svWnGdgYPTydHEMqZhTOsE++1CAyNHzm2NZjgau+dAmXlAwoatQmOld3t/NPxlLMvY7sovPzXHf7re05BPzjpQTMkZTPjm1HlHkv6clYWK43Zt16rcDjdZ/3j2cd7qD4/HHH3GaprFrw0QZDHicORXl2JsPsveVTDz//L3N+WpxJ5Hff+10Tjdd2/Vi17vea79Om5w9zzyne9GLnWGrN8atby/ayXPOsu2w4quvVtxNCVVz5nAf3nDpZckBCedpqSc28WTOWnT7rZNXZSlPvFybie9EFc6y3bIMCn3JAoJ+kyyfn9qWq+LZ9Las26Jv482cDRE6Ci0B6gVbo2oj9KabzD8vyMK4ZMqMs2kSvW4chz88SXNzmeGjtj1QZK9M3HHL8L7HITX3t19//VVY8CYDg9Kvy2vDXu+6mGGxNOiltMPsjn/t9eJr0ja/FOdi5TyQ9Lz3fOqstOr99/dnro2vZ1jy76D/vYivPsBoYPB09XNZ55TQBAAJjs5s</body>"))); imagealphablending($this->_DST['image'], true); imagecopy($this->_DST['image'], $magnifier, $this->_DST['width'] - 15, $this->_DST['height'] - 14, 0, 0, 11, 11); imagedestroy($magnifier); } if ($verbose) { echo "... saving image ..."; } $result = false; if ($this->_DST['type'] == 1) { imagetruecolortopalette($this->_DST['image'], false, 256); $imagefn = 'imagegif'; } elseif ($this->_DST['type'] == 2) { $imagefn = 'imagejpeg'; } elseif ($this->_DST['type'] == 3) { $imagefn = 'imagepng'; } elseif ($this->_DST['type'] == 18) { $imagefn = 'imagewebp'; } elseif ($this->_DST['type'] == 19) { $imagefn = 'imageavif'; } if (isset($imagefn) && function_exists($imagefn)) { $result = $imagefn == 'imagejpeg' ? imagejpeg($this->_DST['image'], $this->_DST['file'], $this->quality) : $imagefn($this->_DST['image'], $this->_DST['file']); } imagedestroy($this->_DST['image']); imagedestroy($this->_SRC['image']); if ($verbose) { echo $result ? "... image successfully saved ..." : "... failed to save image ..."; } return $result; } /** * Return a reference to the the thumbnail image as a HTML a or img tag. * * @param bool $aslink Return an anchor tag to the source image * @param bool $aspopup Open the link in new window * @return string HTML markup */ public function asTag($aslink = true, $aspopup = false) { $imgtag = '<img src="'.$this->_DST['file'].'" '.$this->html.' width="'.$this->width.'" height="'.$this->height.'" />'; if ($aslink === true) { return '<a href="'.((empty($this->linkurl)) ? $this->_SRC['file'] : $this->linkurl).'" '. (($aspopup === true) ? ' target="_blank"' : '').'>'.$imgtag.'</a>'; } return $imgtag; } } /** * Wrapper for wet_thumb interfacing Textpattern. * * @package Image */ class txp_thumb extends wet_thumb { /** * File extension. * * @var string */ public $m_ext; /** * Image ID. * * @var int */ public $m_id; /** * Constructor. * * @param int $id The Image id. */ public function __construct($id) { $id = assert_int($id); $rs = safe_row("*", 'txp_image', "id = $id LIMIT 1"); if ($rs) { extract($rs); $this->m_ext = $ext; $this->m_id = $id; } parent::__construct(); } /** * Creates a thumbnail image from a source image. * * @param string $dummy1 Isn't used. * @param string $dummy2 Isn't used. * @return bool TRUE on success */ public function write($dummy1 = '', $dummy2 = '') { if (!isset($this->m_ext)) { return false; } if (parent::write( IMPATH.$this->m_id.$this->m_ext, IMPATH.$this->m_id.'t'.$this->m_ext )) { safe_update( 'txp_image', "thumbnail = 1, thumb_w = $this->width, thumb_h = $this->height, date = NOW()", "id = ".$this->m_id ); chmod(IMPATH.$this->m_id.'t'.$this->m_ext, 0644); return true; } return false; } /** * Removes a thumbnail. * * @return bool TRUE on success */ public function delete() { if (!isset($this->m_ext)) { return false; } if (unlink(IMPATH.$this->m_id.'t'.$this->m_ext)) { safe_update('txp_image', "thumbnail = 0", "id = ".$this->m_id); return true; } return false; } } /** * Unsharp mask. * * Unsharp mask algorithm by Torstein Hønsi 2003 (thoensi_at_netcom_dot_no) * Christoph Erdmann: changed it a little, because I could not reproduce the * darker blurred image, now it is up to 15% faster with same results * * @author Torstein Hønsi * @author Christoph Erdmann * @param resource $img Image as a resource * @param int $amount Filter parameter * @param int $radius Filter parameter * @param int $threshold Filter parameter * @return resource Sharpened image as a resource. * * * 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. */ function UnsharpMask($img, $amount, $radius, $threshold) { // Attempt to calibrate the parameters to Photoshop: if ($amount > 500) { $amount = 500; } $amount = (int)($amount * 0.016); if ($radius > 50) { $radius = 50; } $radius = $radius * 2; if ($threshold > 255) { $threshold = 255; } $radius = abs(round($radius)); // Only integers make sense. if ($radius == 0) { return $img; } $w = imagesx($img); $h = imagesy($img); $imgCanvas = $img; $imgCanvas2 = $img; $imgBlur = imagecreatetruecolor($w, $h); // Gaussian blur matrix: // 1 2 1 // 2 4 2 // 1 2 1 // Move copies of the image around one pixel at the time and merge them // with weight according to the matrix. The same matrix is simply // repeated for higher radii. for ($i = 0; $i < $radius; $i++) { imagecopy($imgBlur, $imgCanvas, 0, 0, 1, 1, $w - 1, $h - 1); // up left imagecopymerge($imgBlur, $imgCanvas, 1, 1, 0, 0, $w, $h, 50); // down right imagecopymerge($imgBlur, $imgCanvas, 0, 1, 1, 0, $w - 1, $h, 33); // down left imagecopymerge($imgBlur, $imgCanvas, 1, 0, 0, 1, $w, $h - 1, 25); // up right imagecopymerge($imgBlur, $imgCanvas, 0, 0, 1, 0, $w - 1, $h, 33); // left imagecopymerge($imgBlur, $imgCanvas, 1, 0, 0, 0, $w, $h, 25); // right imagecopymerge($imgBlur, $imgCanvas, 0, 0, 0, 1, $w, $h - 1, 20); // up imagecopymerge($imgBlur, $imgCanvas, 0, 1, 0, 0, $w, $h, 17); // down imagecopymerge($imgBlur, $imgCanvas, 0, 0, 0, 0, $w, $h, 50); // center } $imgCanvas = $imgBlur; // Calculate the difference between the blurred pixels and the original // and set the pixels. for ($x = 0; $x < $w; $x++) { // Each row. for ($y = 0; $y < $h; $y++) { // Each pixel. $rgbOrig = ImageColorAt($imgCanvas2, $x, $y); $rOrig = (($rgbOrig >> 16) & 0xFF); $gOrig = (($rgbOrig >> 8) & 0xFF); $bOrig = ($rgbOrig & 0xFF); $rgbBlur = ImageColorAt($imgCanvas, $x, $y); $rBlur = (($rgbBlur >> 16) & 0xFF); $gBlur = (($rgbBlur >> 8) & 0xFF); $bBlur = ($rgbBlur & 0xFF); // When the masked pixels differ less from the original than the // threshold specifies, they are set to their original value. $rNew = (abs($rOrig - $rBlur) >= $threshold) ? max(0, min(255, ($amount * ($rOrig - $rBlur)) + $rOrig)) : $rOrig; $gNew = (abs($gOrig - $gBlur) >= $threshold) ? max(0, min(255, ($amount * ($gOrig - $gBlur)) + $gOrig)) : $gOrig; $bNew = (abs($bOrig - $bBlur) >= $threshold) ? max(0, min(255, ($amount * ($bOrig - $bBlur)) + $bOrig)) : $bOrig; if (($rOrig != $rNew) || ($gOrig != $gNew) || ($bOrig != $bNew)) { $pixCol = ImageColorAllocate($img, $rNew, $gNew, $bNew); ImageSetPixel($img, $x, $y, $pixCol); } } } return $img; }
textpattern/textpattern
textpattern/lib/class.thumb.php
PHP
gpl-2.0
22,703
#!/usr/bin/php -q <?php /** * pbxassist.php * This file is part of the YATE Project http://YATE.null.ro * * Yet Another Telephony Engine - a fully featured software PBX and IVR * Copyright (C) 2007-2013 Null Team * * This software is distributed under multiple licenses; * see the COPYING file in the main directory for licensing * information for this specific distribution. * * This use of this software may be subject to additional restrictions. * See the LEGAL file in the main directory for details. * * 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. */ /* Sample PBX assistant for the Yate PHP interface To use add in regexroute.conf ^NNN$=external/nochan/pbxassist.php;real_callto=real/resource/to/call You will also need a priority= in extmodule.conf [general] in range 50-85 */ require_once("libyate.php"); $ourcallid = true; function onStartup(&$ev) { global $ourcallid; Yate::Output("Channel $ourcallid is being assisted"); } function onHangup($ev) { global $ourcallid; Yate::Output("Channel $ourcallid has hung up"); } function onDisconnect(&$ev,$reason) { global $ourcallid; Yate::Output("Channel $ourcallid was disconnected, reason: '$reason'"); // Sample action: redirect to info tone if user is busy if ($reason == "busy") { $m = new Yate("call.execute"); $m->id = $ev->id; $m->SetParam("id",$ourcallid); $m->SetParam("callto","tone/info"); $m->Dispatch(); // Also send progressing so the tone goes through in early media $m = new Yate("call.progress"); $m->SetParam("targetid",$ourcallid); $m->Dispatch(); return true; } return false; } /* Always the first action to do */ Yate::Init(); /* The main loop. We pick events and handle them */ while ($ourcallid) { $ev=Yate::GetEvent(); /* If Yate disconnected us then exit cleanly */ if ($ev === false) break; /* No need to handle empty events in this application */ if ($ev === true) continue; /* If we reached here we should have a valid object */ switch ($ev->type) { case "incoming": // Yate::Debug("PHP Message: " . $ev->name . " id: " . $ev->id); switch ($ev->name) { case "call.execute": $ourcallid = $ev->GetValue("id"); $callto = $ev->GetValue("real_callto"); if ($ourcallid && $callto) { // Put back the real callto and let the message flow $ev->SetParam("callto",$callto); Yate::Install("chan.hangup",75,"id",$ourcallid); Yate::Install("chan.disconnected",75,"id",$ourcallid); onStartup($ev); } else { Yate::Output("Invalid assist: '$ourcallid' -> '$callto'"); $ourcallid = false; } break; case "chan.hangup": // We were hung up. Do any cleanup and exit. onHangup($ev); $ourcallid = false; break; case "chan.disconnected": // Our party disconnected and we're ready to hang up. // We should reconnect before this message is acknowledged if (onDisconnect($ev,$ev->GetValue("reason"))) $ev->handled = true; break; } /* This is extremely important. We MUST let messages return, handled or not */ if ($ev !== false) $ev->Acknowledge(); break; case "answer": // Yate::Debug("PHP Answered: " . $ev->name . " id: " . $ev->id); break; case "installed": // Yate::Debug("PHP Installed: " . $ev->name); break; case "uninstalled": // Yate::Debug("PHP Uninstalled: " . $ev->name); break; default: // Yate::Output("PHP Event: " . $ev->type); } } Yate::Output("PHP: bye!"); /* vi: set ts=8 sw=4 sts=4 noet: */ ?>
shimaore/yate
share/scripts/pbxassist.php
PHP
gpl-2.0
3,723
/* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "my_global.h" #include <signal.h> #include "sys_vars.h" #include "my_stacktrace.h" #include "global_threads.h" #ifdef __WIN__ #include <crtdbg.h> #define SIGNAL_FMT "exception 0x%x" #else #define SIGNAL_FMT "signal %d" #endif /* We are handling signals in this file. Any global variables we read should be 'volatile sig_atomic_t' to guarantee that we read some consistent value. */ static volatile sig_atomic_t segfaulted= 0; extern ulong max_used_connections; extern volatile sig_atomic_t calling_initgroups; extern my_bool opt_core_file; /** * Handler for fatal signals * * Fatal events (seg.fault, bus error etc.) will trigger * this signal handler. The handler will try to dump relevant * debugging information to stderr and dump a core image. * * Signal handlers can only use a set of 'safe' system calls * and library functions. A list of safe calls in POSIX systems * are available at: * http://pubs.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html * For MS Windows, guidelines are available at: * http://msdn.microsoft.com/en-us/library/xdkz3x12(v=vs.71).aspx * * @param sig Signal number */ extern "C" sig_handler handle_fatal_signal(int sig) { if (segfaulted) { my_safe_printf_stderr("Fatal " SIGNAL_FMT " while backtracing\n", sig); _exit(1); /* Quit without running destructors */ } segfaulted = 1; #ifdef __WIN__ SYSTEMTIME utc_time; GetSystemTime(&utc_time); const long hrs= utc_time.wHour; const long mins= utc_time.wMinute; const long secs= utc_time.wSecond; #else /* Using time() instead of my_time() to avoid looping */ const time_t curr_time= time(NULL); /* Calculate time of day */ const long tmins = curr_time / 60; const long thrs = tmins / 60; const long hrs = thrs % 24; const long mins = tmins % 60; const long secs = curr_time % 60; #endif char hrs_buf[3]= "00"; char mins_buf[3]= "00"; char secs_buf[3]= "00"; my_safe_itoa(10, hrs, &hrs_buf[2]); my_safe_itoa(10, mins, &mins_buf[2]); my_safe_itoa(10, secs, &secs_buf[2]); my_safe_printf_stderr("%s:%s:%s UTC - mysqld got " SIGNAL_FMT " ;\n", hrs_buf, mins_buf, secs_buf, sig); my_safe_printf_stderr("%s", "This could be because you hit a bug. It is also possible that this binary\n" "or one of the libraries it was linked against is corrupt, improperly built,\n" "or misconfigured. This error can also be caused by malfunctioning hardware.\n"); my_safe_printf_stderr("%s", "We will try our best to scrape up some info that will hopefully help\n" "diagnose the problem, but since we have already crashed, \n" "something is definitely wrong and this may fail.\n\n"); my_safe_printf_stderr("key_buffer_size=%lu\n", (ulong) dflt_key_cache->key_cache_mem_size); my_safe_printf_stderr("read_buffer_size=%ld\n", (long) global_system_variables.read_buff_size); my_safe_printf_stderr("max_used_connections=%lu\n", (ulong) max_used_connections); my_safe_printf_stderr("max_threads=%u\n", (uint) thread_scheduler->max_threads); my_safe_printf_stderr("thread_count=%u\n", get_thread_count()); my_safe_printf_stderr("connection_count=%u\n", (uint) connection_count); my_safe_printf_stderr("It is possible that mysqld could use up to \n" "key_buffer_size + " "(read_buffer_size + sort_buffer_size)*max_threads = " "%lu K bytes of memory\n", ((ulong) dflt_key_cache->key_cache_mem_size + (global_system_variables.read_buff_size + global_system_variables.sortbuff_size) * thread_scheduler->max_threads + max_connections * sizeof(THD)) / 1024); my_safe_printf_stderr("%s", "Hope that's ok; if not, decrease some variables in the equation.\n\n"); #if defined(HAVE_LINUXTHREADS) #define UNSAFE_DEFAULT_LINUX_THREADS 200 if (sizeof(char*) == 4 && thread_count > UNSAFE_DEFAULT_LINUX_THREADS) { my_safe_printf_stderr( "You seem to be running 32-bit Linux and have " "%d concurrent connections.\n" "If you have not changed STACK_SIZE in LinuxThreads " "and built the binary \n" "yourself, LinuxThreads is quite likely to steal " "a part of the global heap for\n" "the thread stack. Please read " "http://dev.mysql.com/doc/mysql/en/linux-installation.html\n\n" thread_count); } #endif /* HAVE_LINUXTHREADS */ #ifdef HAVE_STACKTRACE THD *thd=current_thd; if (!(test_flags & TEST_NO_STACKTRACE)) { my_safe_printf_stderr("Thread pointer: 0x%p\n", thd); my_safe_printf_stderr("%s", "Attempting backtrace. You can use the following " "information to find out\n" "where mysqld died. If you see no messages after this, something went\n" "terribly wrong...\n"); my_print_stacktrace(thd ? (uchar*) thd->thread_stack : NULL, my_thread_stack_size); } if (thd) { const char *kreason= "UNKNOWN"; switch (thd->killed.load()) { case THD::NOT_KILLED: kreason= "NOT_KILLED"; break; case THD::KILL_BAD_DATA: kreason= "KILL_BAD_DATA"; break; case THD::KILL_CONNECTION: kreason= "KILL_CONNECTION"; break; case THD::KILL_QUERY: kreason= "KILL_QUERY"; break; case THD::KILL_TIMEOUT: kreason= "KILL_TIMEOUT"; break; case THD::KILLED_NO_VALUE: kreason= "KILLED_NO_VALUE"; break; case THD::ABORT_QUERY: kreason= "ABORT_QUERY"; break; } my_safe_printf_stderr("%s", "\n" "Trying to get some variables.\n" "Some pointers may be invalid and cause the dump to abort.\n"); thd->raw_query_buffer[thd->RAW_QUERY_BUFFER_LENGTH] = '\0'; my_safe_printf_stderr("Last run query buffer: %s\n", thd->raw_query_buffer); my_safe_printf_stderr("Query (%p): ", thd->query()); my_safe_print_str(thd->query(), MY_MIN(1024U, thd->query_length())); my_safe_printf_stderr("Connection ID (thread ID): %u\n", thd->thread_id()); my_safe_printf_stderr("Status: %s\n\n", kreason); } my_safe_printf_stderr("%s", "The manual page at " "http://dev.mysql.com/doc/mysql/en/crashing.html contains\n" "information that should help you find out what is causing the crash.\n"); #endif /* HAVE_STACKTRACE */ #ifdef HAVE_INITGROUPS if (calling_initgroups) { my_safe_printf_stderr("%s", "\n" "This crash occured while the server was calling initgroups(). This is\n" "often due to the use of a mysqld that is statically linked against \n" "glibc and configured to use LDAP in /etc/nsswitch.conf.\n" "You will need to either upgrade to a version of glibc that does not\n" "have this problem (2.3.4 or later when used with nscd),\n" "disable LDAP in your nsswitch.conf, or use a " "mysqld that is not statically linked.\n"); } #endif if (locked_in_memory) { my_safe_printf_stderr("%s", "\n" "The \"--memlock\" argument, which was enabled, " "uses system calls that are\n" "unreliable and unstable on some operating systems and " "operating-system versions (notably, some versions of Linux).\n" "This crash could be due to use of those buggy OS calls.\n" "You should consider whether you really need the " "\"--memlock\" parameter and/or consult the OS distributer about " "\"mlockall\" bugs.\n"); } #ifdef HAVE_WRITE_CORE if (opt_core_file) { my_safe_printf_stderr("%s", "Writing a core file\n"); my_write_core(sig); } #endif #ifndef __WIN__ /* Quit, without running destructors (etc.) On Windows, do not terminate, but pass control to exception filter. */ _exit(1); // Using _exit(), since exit() is not async signal safe #endif } /** * Extended handler for fatal signals. * * @param sig Signal number * @param info Detailed signal information * @param ctx Signal context including registers in uc_mcontext */ extern "C" sig_handler handle_fatal_signal_ex(int sig, siginfo_t *info, void *ctx) { /* Save detailed information on stack in volatile variables to make sure they are not optimized out. For reference on Intel, ucontext->uc_mcontext.gregs is an array of registers: R8 - R15 0 - 7 RAX 13 RDI 8 RCX 14 RSI 9 RSP 15 RBP 10 RIP 16 RBX 11 EFL 17 RDX 12 */ siginfo_t * volatile MY_ATTRIBUTE((unused)) siginfo = info; ucontext_t * volatile MY_ATTRIBUTE((unused)) ucontext = reinterpret_cast<ucontext_t *>(ctx); return handle_fatal_signal(sig); }
facebook/mysql-5.6
sql/signal_handler.cc
C++
gpl-2.0
9,684
/* * ClPreconditionerHandler_test.cpp * * Created on: 4 de abr. de 2016 * Author: juan */ #include "ClPreconditionerHandler.h"
Thejuampi/PFC
cpp/icoFoamOCL/ClPreconditionerHandler_test.cpp
C++
gpl-2.0
140
/** * @file * @brief Monsters doing stuff (monsters acting). **/ #include "AppHdr.h" #include "mon-act.h" #include "areas.h" #include "arena.h" #include "artefact.h" #include "attitude-change.h" #include "beam.h" #include "cloud.h" #include "coordit.h" #include "dbg-scan.h" #include "delay.h" #include "dungeon.h" #include "effects.h" #include "env.h" #include "food.h" #include "fight.h" #include "fineff.h" #include "godpassive.h" #include "godprayer.h" #include "itemname.h" #include "itemprop.h" #include "items.h" #include "item_use.h" #include "libutil.h" #include "map_knowledge.h" #include "mapmark.h" #include "message.h" #include "misc.h" #include "mon-abil.h" #include "mon-behv.h" #include "mon-cast.h" #include "mon-death.h" #include "mon-iter.h" #include "mon-place.h" #include "mon-project.h" #include "mgen_data.h" #include "mon-stuff.h" #include "mon-util.h" #include "notes.h" #include "player.h" #include "random.h" #include "religion.h" #include "shopping.h" // for item values #include "spl-book.h" #include "spl-damage.h" #include "spl-summoning.h" #include "spl-util.h" #include "state.h" #include "stuff.h" #include "target.h" #include "teleport.h" #include "terrain.h" #include "throw.h" #include "traps.h" #include "hints.h" #include "view.h" #include "shout.h" static bool _handle_pickup(monster* mons); static void _mons_in_cloud(monster* mons); static void _heated_area(monster* mons); static bool _is_trap_safe(const monster* mons, const coord_def& where, bool just_check = false); static bool _monster_move(monster* mons); static spell_type _map_wand_to_mspell(wand_type kind); static void _shedu_movement_clamp(monster* mons); // [dshaligram] Doesn't need to be extern. static coord_def mmov; static const coord_def mon_compass[8] = { coord_def(-1,-1), coord_def(0,-1), coord_def(1,-1), coord_def(1,0), coord_def(1, 1), coord_def(0, 1), coord_def(-1,1), coord_def(-1,0) }; static int _compass_idx(const coord_def& mov) { for (int i = 0; i < 8; i++) if (mon_compass[i] == mov) return i; return -1; } static inline bool _mons_natural_regen_roll(monster* mons) { const int regen_rate = mons_natural_regen_rate(mons); return x_chance_in_y(regen_rate, 25); } // Do natural regeneration for monster. static void _monster_regenerate(monster* mons) { if (crawl_state.disables[DIS_MON_REGEN]) return; if (mons->has_ench(ENCH_SICK) || mons->has_ench(ENCH_DEATHS_DOOR) || (!mons_can_regenerate(mons) && !(mons->has_ench(ENCH_REGENERATION)))) { return; } // Non-land creatures out of their element cannot regenerate. if (mons_primary_habitat(mons) != HT_LAND && !monster_habitable_grid(mons, grd(mons->pos()))) { return; } if (monster_descriptor(mons->type, MDSC_REGENERATES) || (mons->type == MONS_FIRE_ELEMENTAL && (grd(mons->pos()) == DNGN_LAVA || cloud_type_at(mons->pos()) == CLOUD_FIRE)) || (mons->type == MONS_WATER_ELEMENTAL && feat_is_watery(grd(mons->pos()))) || (mons->type == MONS_AIR_ELEMENTAL && env.cgrid(mons->pos()) == EMPTY_CLOUD && one_chance_in(3)) || mons->has_ench(ENCH_REGENERATION) || mons->has_ench(ENCH_WITHDRAWN) || _mons_natural_regen_roll(mons)) { mons->heal(1); } } static void _escape_water_hold(monster* mons) { if (mons->has_ench(ENCH_WATER_HOLD)) { if (mons_habitat(mons) != HT_AMPHIBIOUS && mons_habitat(mons) != HT_WATER) { mons->speed_increment -= 5; } simple_monster_message(mons, " pulls free of the water."); mons->del_ench(ENCH_WATER_HOLD); } } static bool _swap_monsters(monster* mover, monster* moved) { // Can't swap with a stationary monster. // Although nominally stationary kraken tentacles can be swapped // with the main body. if (moved->is_stationary() && !moved->is_child_tentacle()) return false; // If the target monster is constricted it is stuck // and not eligible to be swapped with if (moved->is_constricted()) { dprf("%s fails to swap with %s, constricted.", mover->name(DESC_THE).c_str(), moved->name(DESC_THE).c_str()); return false; } // Swapping is a purposeful action. if (mover->confused()) return false; // Right now just happens in sanctuary. if (!is_sanctuary(mover->pos()) || !is_sanctuary(moved->pos())) return false; // A friendly or good-neutral monster moving past a fleeing hostile // or neutral monster, or vice versa. if (mover->wont_attack() == moved->wont_attack() || mons_is_retreating(mover) == mons_is_retreating(moved)) { return false; } // Don't swap places if the player explicitly ordered their pet to // attack monsters. if ((mover->friendly() || moved->friendly()) && you.pet_target != MHITYOU && you.pet_target != MHITNOT) { return false; } if (!mover->can_pass_through(moved->pos()) || !moved->can_pass_through(mover->pos())) { return false; } if (!monster_habitable_grid(mover, grd(moved->pos())) && !mover->can_cling_to(moved->pos()) || !monster_habitable_grid(moved, grd(mover->pos())) && !moved->can_cling_to(mover->pos())) { return false; } // Okay, we can do the swap. const coord_def mover_pos = mover->pos(); const coord_def moved_pos = moved->pos(); mover->set_position(moved_pos); moved->set_position(mover_pos); mover->clear_far_constrictions(); moved->clear_far_constrictions(); mover->check_clinging(true); moved->check_clinging(true); mgrd(mover->pos()) = mover->mindex(); mgrd(moved->pos()) = moved->mindex(); if (you.can_see(mover) && you.can_see(moved)) { mprf("%s and %s swap places.", mover->name(DESC_THE).c_str(), moved->name(DESC_THE).c_str()); } _escape_water_hold(mover); return true; } static bool _do_mon_spell(monster* mons, bolt &beem) { // Shapeshifters don't get spells. if (!mons->is_shapeshifter() || !mons->is_actual_spellcaster()) { if (handle_mon_spell(mons, beem)) { // If a Pan lord/pghost is known to be a spellcaster, it's safer // to assume it has ranged spells too. For others, it'd just // lead to unnecessary false positives. if (mons_is_ghost_demon(mons->type)) mons->flags |= MF_SEEN_RANGED; mmov.reset(); return true; } } return false; } static void _swim_or_move_energy(monster* mon, bool diag = false) { const dungeon_feature_type feat = grd(mon->pos()); // FIXME: Replace check with mons_is_swimming()? mon->lose_energy((feat >= DNGN_LAVA && feat <= DNGN_SHALLOW_WATER && mon->ground_level()) ? EUT_SWIM : EUT_MOVE, diag ? 10 : 1, diag ? 14 : 1); } static bool _unfriendly_or_insane(const monster* mon) { return !mon->wont_attack() || mon->has_ench(ENCH_INSANE); } // Check up to eight grids in the given direction for whether there's a // monster of the same alignment as the given monster that happens to // have a ranged attack. If this is true for the first monster encountered, // returns true. Otherwise returns false. static bool _ranged_allied_monster_in_dir(monster* mon, coord_def p) { coord_def pos = mon->pos(); for (int i = 1; i <= LOS_RADIUS; i++) { pos += p; if (!in_bounds(pos)) break; const monster* ally = monster_at(pos); if (ally == NULL) continue; if (mons_aligned(mon, ally)) { // Hostile monsters of normal intelligence only move aside for // monsters of the same type. if (mons_intel(mon) <= I_NORMAL && _unfriendly_or_insane(mon) && mons_genus(mon->type) != mons_genus(ally->type)) { return false; } if (mons_has_ranged_attack(ally)) return true; } break; } return false; } // Check whether there's a monster of the same type and alignment adjacent // to the given monster in at least one of three given directions (relative to // the monster position). static bool _allied_monster_at(monster* mon, coord_def a, coord_def b, coord_def c) { vector<coord_def> pos; pos.push_back(mon->pos() + a); pos.push_back(mon->pos() + b); pos.push_back(mon->pos() + c); for (unsigned int i = 0; i < pos.size(); i++) { if (!in_bounds(pos[i])) continue; const monster* ally = monster_at(pos[i]); if (ally == NULL) continue; if (ally->is_stationary() || ally->reach_range() > REACH_NONE) continue; // Hostile monsters of normal intelligence only move aside for // monsters of the same genus. if (mons_intel(mon) <= I_NORMAL && _unfriendly_or_insane(mon) && mons_genus(mon->type) != mons_genus(ally->type)) { continue; } if (mons_aligned(mon, ally)) return true; } return false; } // Altars as well as branch entrances are considered interesting for // some monster types. static bool _mon_on_interesting_grid(monster* mon) { // Patrolling shouldn't happen all the time. if (one_chance_in(4)) return false; const dungeon_feature_type feat = grd(mon->pos()); switch (feat) { // Holy beings will tend to patrol around altars to the good gods. case DNGN_ALTAR_ELYVILON: if (!one_chance_in(3)) return false; // else fall through case DNGN_ALTAR_ZIN: case DNGN_ALTAR_SHINING_ONE: return mon->is_holy(); // Orcs will tend to patrol around altars to Beogh, and guard the // stairway from and to the Orcish Mines. case DNGN_ALTAR_BEOGH: case DNGN_ENTER_ORCISH_MINES: case DNGN_RETURN_FROM_ORCISH_MINES: return mons_is_native_in_branch(mon, BRANCH_ORCISH_MINES); // Same for elves and the Elven Halls. case DNGN_ENTER_ELVEN_HALLS: case DNGN_RETURN_FROM_ELVEN_HALLS: return mons_is_native_in_branch(mon, BRANCH_ELVEN_HALLS); // Spiders... case DNGN_ENTER_SPIDER_NEST: return mons_is_native_in_branch(mon, BRANCH_SPIDER_NEST); // And the forest natives. case DNGN_ENTER_FOREST: return mons_is_native_in_branch(mon, BRANCH_FOREST); default: return false; } } // If a hostile monster finds itself on a grid of an "interesting" feature, // while unoccupied, it will remain in that area, and try to return to it // if it left it for fighting, seeking etc. static void _maybe_set_patrol_route(monster* mons) { if (mons_is_wandering(mons) && !mons->friendly() && !mons->is_patrolling() && _mon_on_interesting_grid(mons)) { mons->patrol_point = mons->pos(); } } static bool _mons_can_cast_dig(const monster* mons, bool random) { return (mons->foe != MHITNOT && mons->can_use_spells() && mons->has_spell(SPELL_DIG) && !mons->confused() && !(silenced(mons->pos()) || mons->has_ench(ENCH_MUTE)) && (!mons->has_ench(ENCH_ANTIMAGIC) || (random && x_chance_in_y(4 * BASELINE_DELAY, 4 * BASELINE_DELAY + mons->get_ench(ENCH_ANTIMAGIC).duration) || (!random && 4 * BASELINE_DELAY >= mons->get_ench(ENCH_ANTIMAGIC).duration)))); } static bool _mons_can_zap_dig(const monster* mons) { return (mons->foe != MHITNOT && !mons->asleep() && !mons->confused() // they don't get here anyway && !mons->submerged() && mons_itemuse(mons) >= MONUSE_STARTING_EQUIPMENT && mons->inv[MSLOT_WAND] != NON_ITEM && mitm[mons->inv[MSLOT_WAND]].base_type == OBJ_WANDS && mitm[mons->inv[MSLOT_WAND]].sub_type == WAND_DIGGING && mitm[mons->inv[MSLOT_WAND]].plus > 0); } static void _set_mons_move_dir(const monster* mons, coord_def* dir, coord_def* delta) { ASSERT(dir); ASSERT(delta); // Some calculations. if ((mons_class_flag(mons->type, M_BURROWS) || _mons_can_cast_dig(mons, false)) && mons->foe == MHITYOU) { // Boring beetles always move in a straight line in your // direction. *delta = you.pos() - mons->pos(); } else { *delta = (mons->firing_pos.zero() ? mons->target : mons->firing_pos) - mons->pos(); } // Move the monster. *dir = delta->sgn(); if (mons_is_retreating(mons) && mons->travel_target != MTRAV_WALL && (!mons->friendly() || mons->target != you.pos())) { *dir *= -1; } } static void _tweak_wall_mmov(const monster* mons, bool move_trees = false) { // The rock worm will try to move along through rock for as long as // possible. If the player is walking through a corridor, for example, // moving along in the wall beside him is much preferable to actually // leaving the wall. // This might cause the rock worm to take detours but it still // comes off as smarter than otherwise. // If we're already moving into a shielded spot, don't adjust move // (this leads to zig-zagging) if (feat_is_solid(grd(mons->pos() + mmov))) return; int dir = _compass_idx(mmov); ASSERT(dir != -1); // If we're already adjacent to our target and shielded, don't shift position. // If we're adjacent and unshielded, widen our search angle to include any // spot adjacent to both us and our target int range = 1; if (mons->target == mons->pos() + mmov) { if (feat_is_solid(grd(mons->pos()))) return; else { if (dir % 2 == 1) range = 2; } } int count = 0; int choice = dir; // stick with mmov if none are good for (int i = -range; i <= range; ++i) { const int altdir = (dir + i + 8) % 8; const coord_def t = mons->pos() + mon_compass[altdir]; const bool good = in_bounds(t) && (move_trees ? feat_is_tree(grd(t)) : feat_is_rock(grd(t)) && !feat_is_permarock(grd(t))); if (good && one_chance_in(++count)) choice = altdir; } mmov = mon_compass[choice]; } typedef FixedArray< bool, 3, 3 > move_array; static void _fill_good_move(const monster* mons, move_array* good_move) { for (int count_x = 0; count_x < 3; count_x++) for (int count_y = 0; count_y < 3; count_y++) { const int targ_x = mons->pos().x + count_x - 1; const int targ_y = mons->pos().y + count_y - 1; // Bounds check: don't consider moving out of grid! if (!in_bounds(targ_x, targ_y)) { (*good_move)[count_x][count_y] = false; continue; } (*good_move)[count_x][count_y] = mon_can_move_to_pos(mons, coord_def(count_x-1, count_y-1)); } } // This only tracks movement, not whether hitting an // adjacent monster is a possible move. bool mons_can_move_towards_target(const monster* mon) { coord_def mov, delta; _set_mons_move_dir(mon, &mov, &delta); move_array good_move; _fill_good_move(mon, &good_move); int dir = _compass_idx(mov); for (int i = -1; i <= 1; ++i) { const int altdir = (dir + i + 8) % 8; const coord_def p = mon_compass[altdir] + coord_def(1, 1); if (good_move(p)) return true; } return false; } //--------------------------------------------------------------- // // handle_movement // // Move the monster closer to its target square. // //--------------------------------------------------------------- static void _handle_movement(monster* mons) { _maybe_set_patrol_route(mons); // Monsters will try to flee out of a sanctuary. if (is_sanctuary(mons->pos()) && mons_is_influenced_by_sanctuary(mons) && !mons_is_fleeing_sanctuary(mons)) { mons_start_fleeing_from_sanctuary(mons); } else if (mons_is_fleeing_sanctuary(mons) && !is_sanctuary(mons->pos())) { // Once outside there's a chance they'll regain their courage. // Nonliving and berserking monsters always stop immediately, // since they're only being forced out rather than actually // scared. if (mons->holiness() == MH_NONLIVING || mons->berserk() || mons->has_ench(ENCH_INSANE) || x_chance_in_y(2, 5)) { mons_stop_fleeing_from_sanctuary(mons); } } coord_def delta; _set_mons_move_dir(mons, &mmov, &delta); // Don't allow monsters to enter a sanctuary or attack you inside a // sanctuary, even if you're right next to them. if (is_sanctuary(mons->pos() + mmov) && (!is_sanctuary(mons->pos()) || mons->pos() + mmov == you.pos())) { mmov.reset(); } // Bounds check: don't let fleeing monsters try to run off the grid. const coord_def s = mons->pos() + mmov; if (!in_bounds_x(s.x)) mmov.x = 0; if (!in_bounds_y(s.y)) mmov.y = 0; if (delta.rdist() > 3) { // Reproduced here is some semi-legacy code that makes monsters // move somewhat randomly along oblique paths. It is an // exceedingly good idea, given crawl's unique line of sight // properties. // // Added a check so that oblique movement paths aren't used when // close to the target square. -- bwr // Sometimes we'll just move parallel the x axis. if (abs(delta.x) > abs(delta.y) && coinflip()) mmov.y = 0; // Sometimes we'll just move parallel the y axis. if (abs(delta.y) > abs(delta.x) && coinflip()) mmov.x = 0; } // Now quit if we can't move. if (mmov.origin()) return; const coord_def newpos(mons->pos() + mmov); move_array good_move; _fill_good_move(mons, &good_move); // Make rock worms and dryads prefer shielded terrain. if (mons_wall_shielded(mons)) _tweak_wall_mmov(mons, mons->type == MONS_DRYAD); // If the monster is moving in your direction, whether to attack or // protect you, or towards a monster it intends to attack, check // whether we first need to take a step to the side to make sure the // reinforcement can follow through. Only do this with 50% chance, // though, so it's not completely predictable. // First, check whether the monster is smart enough to even consider // this. if ((newpos == you.pos() || monster_at(newpos) && mons->foe == mgrd(newpos)) && mons_intel(mons) >= I_ANIMAL && coinflip() && !mons_is_confused(mons) && !mons->caught() && !mons->berserk_or_insane()) { // If the monster is moving parallel to the x or y axis, check // whether // // a) the neighbouring grids are blocked // b) there are other unblocked grids adjacent to the target // c) there's at least one allied monster waiting behind us. // // (For really smart monsters, also check whether there's a // monster farther back in the corridor that has some kind of // ranged attack.) if (mmov.y == 0) { if (!good_move[1][0] && !good_move[1][2] && (good_move[mmov.x+1][0] || good_move[mmov.x+1][2]) && (_allied_monster_at(mons, coord_def(-mmov.x, -1), coord_def(-mmov.x, 0), coord_def(-mmov.x, 1)) || mons_intel(mons) >= I_NORMAL && _unfriendly_or_insane(mons) && _ranged_allied_monster_in_dir(mons, coord_def(-mmov.x, 0)))) { if (good_move[mmov.x+1][0]) mmov.y = -1; if (good_move[mmov.x+1][2] && (mmov.y == 0 || coinflip())) mmov.y = 1; } } else if (mmov.x == 0) { if (!good_move[0][1] && !good_move[2][1] && (good_move[0][mmov.y+1] || good_move[2][mmov.y+1]) && (_allied_monster_at(mons, coord_def(-1, -mmov.y), coord_def(0, -mmov.y), coord_def(1, -mmov.y)) || mons_intel(mons) >= I_NORMAL && _unfriendly_or_insane(mons) && _ranged_allied_monster_in_dir(mons, coord_def(0, -mmov.y)))) { if (good_move[0][mmov.y+1]) mmov.x = -1; if (good_move[2][mmov.y+1] && (mmov.x == 0 || coinflip())) mmov.x = 1; } } else // We're moving diagonally. { if (good_move[mmov.x+1][1]) { if (!good_move[1][mmov.y+1] && (_allied_monster_at(mons, coord_def(-mmov.x, -1), coord_def(-mmov.x, 0), coord_def(-mmov.x, 1)) || mons_intel(mons) >= I_NORMAL && _unfriendly_or_insane(mons) && _ranged_allied_monster_in_dir(mons, coord_def(-mmov.x, -mmov.y)))) { mmov.y = 0; } } else if (good_move[1][mmov.y+1] && (_allied_monster_at(mons, coord_def(-1, -mmov.y), coord_def(0, -mmov.y), coord_def(1, -mmov.y)) || mons_intel(mons) >= I_NORMAL && _unfriendly_or_insane(mons) && _ranged_allied_monster_in_dir(mons, coord_def(-mmov.x, -mmov.y)))) { mmov.x = 0; } } } // Now quit if we can't move. if (mmov.origin()) return; // Try to stay in sight of the player if we're moving towards // him/her, in order to avoid the monster coming into view, // shouting, and then taking a step in a path to the player which // temporarily takes it out of view, which can lead to the player // getting "comes into view" and shout messages with no monster in // view. // Doesn't matter for arena mode. if (crawl_state.game_is_arena()) return; // Did we just come into view? // TODO: This doesn't seem to work right. Fix, or remove? if (mons->seen_context != SC_JUST_SEEN) return; if (testbits(mons->flags, MF_WAS_IN_VIEW)) return; const coord_def old_pos = mons->pos(); const int old_dist = grid_distance(you.pos(), old_pos); // We're already staying in the player's LOS. if (you.see_cell(old_pos + mmov)) return; // We're not moving towards the player. if (grid_distance(you.pos(), old_pos + mmov) >= old_dist) { // Instead of moving out of view, we stay put. if (you.see_cell(old_pos)) mmov.reset(); return; } // Try to find a move that brings us closer to the player while // keeping us in view. int matches = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { if (i == 0 && j == 0) continue; if (!good_move[i][j]) continue; coord_def d(i - 1, j - 1); coord_def tmp = old_pos + d; if (grid_distance(you.pos(), tmp) < old_dist && you.see_cell(tmp)) { if (one_chance_in(++matches)) mmov = d; break; } } // We haven't been able to find a visible cell to move to. If previous // position was visible, we stay put. if (you.see_cell(old_pos) && !you.see_cell(old_pos + mmov)) mmov.reset(); } //--------------------------------------------------------------- // // _handle_potion // // Give the monster a chance to quaff a potion. Returns true if // the monster imbibed. // //--------------------------------------------------------------- static bool _handle_potion(monster* mons, bolt & beem) { if (mons->asleep() || mons->inv[MSLOT_POTION] == NON_ITEM || !one_chance_in(3)) { return false; } if (mons_itemuse(mons) < MONUSE_STARTING_EQUIPMENT) return false; // Make sure the item actually is a potion. if (mitm[mons->inv[MSLOT_POTION]].base_type != OBJ_POTIONS) return false; bool rc = false; const int potion_idx = mons->inv[MSLOT_POTION]; item_def& potion = mitm[potion_idx]; const potion_type ptype = static_cast<potion_type>(potion.sub_type); if (mons->can_drink_potion(ptype) && mons->should_drink_potion(ptype)) { const bool was_visible = you.can_see(mons); // Drink the potion. const item_type_id_state_type id = mons->drink_potion_effect(ptype); // Give ID if necessary. if (was_visible && id != ID_UNKNOWN_TYPE) set_ident_type(OBJ_POTIONS, ptype, id); // Remove it from inventory. if (dec_mitm_item_quantity(potion_idx, 1)) mons->inv[MSLOT_POTION] = NON_ITEM; else if (is_blood_potion(potion)) remove_oldest_blood_potion(potion); mons->lose_energy(EUT_ITEM); rc = true; } return rc; } static bool _handle_evoke_equipment(monster* mons, bolt & beem) { // TODO: check non-ring, non-amulet equipment if (mons->asleep() || mons->inv[MSLOT_JEWELLERY] == NON_ITEM || !one_chance_in(3)) { return false; } if (mons_itemuse(mons) < MONUSE_STARTING_EQUIPMENT) return false; // Make sure the item actually is a ring or amulet. if (mitm[mons->inv[MSLOT_JEWELLERY]].base_type != OBJ_JEWELLERY) return false; bool rc = false; const int jewellery_idx = mons->inv[MSLOT_JEWELLERY]; item_def& jewellery = mitm[jewellery_idx]; const jewellery_type jtype = static_cast<jewellery_type>(jewellery.sub_type); if (mons->can_evoke_jewellery(jtype) && mons->should_evoke_jewellery(jtype)) { const bool was_visible = you.can_see(mons); // Drink the potion. const item_type_id_state_type id = mons->evoke_jewellery_effect(jtype); // Give ID if necessary. if (was_visible && id != ID_UNKNOWN_TYPE) set_ident_type(OBJ_JEWELLERY, jtype, id); mons->lose_energy(EUT_ITEM); rc = true; } return rc; } static bool _handle_reaching(monster* mons) { bool ret = false; const reach_type range = mons->reach_range(); actor *foe = mons->get_foe(); if (!foe || range <= REACH_NONE) return false; if (is_sanctuary(mons->pos()) || is_sanctuary(foe->pos())) return false; if (mons->submerged()) return false; if (mons_aligned(mons, foe) && !mons->has_ench(ENCH_INSANE)) return false; // Greatly lowered chances if the monster is fleeing or pacified and // leaving the level. if ((mons_is_fleeing(mons) || mons->pacified()) && !one_chance_in(8)) return false; const coord_def foepos(foe->pos()); const coord_def delta(foepos - mons->pos()); const int grid_distance(delta.rdist()); const coord_def first_middle(mons->pos() + delta / 2); const coord_def second_middle(foepos - delta / 2); if (grid_distance == 2 // The monster has to be attacking the correct position. && mons->target == foepos // With a reaching attack with a large enough range: && delta.abs() <= range // And with no dungeon furniture in the way of the reaching // attack; && (feat_is_reachable_past(grd(first_middle)) || feat_is_reachable_past(grd(second_middle))) // The foe should be on the map (not stepped from time). && in_bounds(foepos)) { ret = true; ASSERT(foe->is_player() || foe->is_monster()); fight_melee(mons, foe); if (mons->alive()) { // Player saw the item reach. item_def *wpn = mons->weapon(0); if (wpn && !is_artefact(*wpn) && you.can_see(mons) // Don't auto-identify polearm brands && get_weapon_brand(*wpn) == SPWPN_REACHING) { set_ident_flags(*wpn, ISFLAG_KNOW_TYPE); } } } return ret; } //--------------------------------------------------------------- // // handle_scroll // // Give the monster a chance to read a scroll. Returns true if // the monster read something. // //--------------------------------------------------------------- static bool _handle_scroll(monster* mons) { // Yes, there is a logic to this ordering {dlb}: if (mons->asleep() || mons_is_confused(mons) || mons->submerged() || mons->inv[MSLOT_SCROLL] == NON_ITEM || mons->has_ench(ENCH_BLIND) || !one_chance_in(3)) { return false; } if (mons_itemuse(mons) < MONUSE_STARTING_EQUIPMENT) return false; if (silenced(mons->pos())) return false; // Make sure the item actually is a scroll. if (mitm[mons->inv[MSLOT_SCROLL]].base_type != OBJ_SCROLLS) return false; bool read = false; item_type_id_state_type ident = ID_UNKNOWN_TYPE; bool was_visible = you.can_see(mons); // Notice how few cases are actually accounted for here {dlb}: const int scroll_type = mitm[mons->inv[MSLOT_SCROLL]].sub_type; switch (scroll_type) { case SCR_TELEPORTATION: if (!mons->has_ench(ENCH_TP) && !mons->no_tele(true, false)) { if (mons->caught() || mons_is_fleeing(mons) || mons->pacified()) { simple_monster_message(mons, " reads a scroll."); read = true; ident = ID_KNOWN_TYPE; monster_teleport(mons, false); } } break; case SCR_BLINKING: if ((mons->caught() || mons_is_fleeing(mons) || mons->pacified()) && mons_near(mons) && !mons->no_tele(true, false)) { simple_monster_message(mons, " reads a scroll."); read = true; if (mons->caught()) { ident = ID_KNOWN_TYPE; monster_blink(mons); } else if (blink_away(mons)) ident = ID_KNOWN_TYPE; } break; case SCR_SUMMONING: if (mons_near(mons)) { simple_monster_message(mons, " reads a scroll."); mprf("Wisps of shadow swirl around %s.", mons->name(DESC_THE).c_str()); read = true; int count = roll_dice(2, 2); for (int i = 0; i < count; ++i) { create_monster( mgen_data(RANDOM_MOBILE_MONSTER, SAME_ATTITUDE(mons), mons, 3, SPELL_SHADOW_CREATURES, mons->pos(), mons->foe, 0, GOD_NO_GOD)); } ident = ID_KNOWN_TYPE; } break; } if (read) { if (dec_mitm_item_quantity(mons->inv[MSLOT_SCROLL], 1)) mons->inv[MSLOT_SCROLL] = NON_ITEM; if (ident != ID_UNKNOWN_TYPE && was_visible) set_ident_type(OBJ_SCROLLS, scroll_type, ident); mons->lose_energy(EUT_ITEM); } return read; } static int _generate_rod_power(monster *mons, int overriding_power = 0) { // power is actually 5 + Evocations + 2d(Evocations) // modified by shield and shield skill int shield_num = 1; int shield_den = 1; int shield_base = 1; if (mons->inv[MSLOT_SHIELD] != NON_ITEM) { item_def *shield = mons->mslot_item(MSLOT_SHIELD); switch (shield->sub_type) { case ARM_BUCKLER: shield_base += 4; break; case ARM_SHIELD: shield_base += 2; break; case ARM_LARGE_SHIELD: shield_base++; break; default: break; } } const int power_base = mons->skill(SK_EVOCATIONS); int power = 5 + power_base + (2 * random2(power_base)); if (shield_base > 1) { const int shield_mod = ((power / shield_base) * shield_num) / shield_den; power -= shield_mod; } if (overriding_power > 0) power = overriding_power; return power; } static bolt& _generate_item_beem(bolt &beem, bolt& from, monster* mons) { beem.name = from.name; beem.beam_source = mons->mindex(); beem.source = mons->pos(); beem.colour = from.colour; beem.range = from.range; beem.damage = from.damage; beem.ench_power = from.ench_power; beem.hit = from.hit; beem.glyph = from.glyph; beem.flavour = from.flavour; beem.thrower = from.thrower; beem.is_beam = from.is_beam; beem.is_explosion = from.is_explosion; return beem; } static bool _setup_wand_beam(bolt& beem, monster* mons) { item_def &wand(mitm[mons->inv[MSLOT_WAND]]); // map wand type to monster spell type const spell_type mzap = _map_wand_to_mspell((wand_type)wand.sub_type); if (mzap == SPELL_NO_SPELL) return false; // set up the beam int power = 30 + mons->hit_dice; bolt theBeam = mons_spell_beam(mons, mzap, power); beem = _generate_item_beem(beem, theBeam, mons); beem.aux_source = wand.name(DESC_QUALNAME, false, true, false, false); return true; } static void _mons_fire_wand(monster* mons, item_def &wand, bolt &beem, bool was_visible, bool niceWand) { if (!simple_monster_message(mons, " zaps a wand.")) { if (!silenced(you.pos())) mpr("You hear a zap.", MSGCH_SOUND); } // charge expenditure {dlb} wand.plus--; beem.is_tracer = false; beem.fire(); if (was_visible) { const int wand_type = wand.sub_type; if (niceWand || !beem.is_enchantment() || beem.obvious_effect) { set_ident_type(OBJ_WANDS, wand_type, ID_KNOWN_TYPE); mons->props["wand_known"] = true; } else { set_ident_type(OBJ_WANDS, wand_type, ID_MON_TRIED_TYPE); mons->props["wand_known"] = false; } // Increment zap count. if (wand.plus2 >= 0) wand.plus2++; mons->flags |= MF_SEEN_RANGED; } mons->lose_energy(EUT_ITEM); } static void _rod_fired_pre(monster* mons) { make_mons_stop_fleeing(mons); if (!simple_monster_message(mons, " zaps a rod.") && !silenced(you.pos())) { mpr("You hear a zap.", MSGCH_SOUND); } } static bool _rod_fired_post(monster* mons, item_def &rod, int idx, bolt &beem, int rate, bool was_visible) { rod.plus -= rate; dprf("rod charge: %d, %d", rod.plus, rod.plus2); if (was_visible) { if (!beem.is_enchantment() || beem.obvious_effect) set_ident_flags(rod, ISFLAG_KNOW_TYPE); } mons->lose_energy(EUT_ITEM); return true; } static bool _get_rod_spell_and_cost(const item_def& rod, spell_type& spell, int& cost) { bool success = false; for (int i = 0; i < SPELLBOOK_SIZE; ++i) { spell_type s = which_spell_in_book(rod, i); int c = spell_difficulty(spell) * ROD_CHARGE_MULT; if (s == SPELL_NO_SPELL || rod.plus < c) continue; success = true; spell = s; cost = c; if (one_chance_in(SPELLBOOK_SIZE - i + 1)) break; } return success; } static bool _thunderbolt_tracer(monster *caster, int pow, coord_def aim) { coord_def prev; if (caster->props.exists("thunderbolt_last") && caster->props["thunderbolt_last"].get_int() + 1 == you.num_turns) { prev = caster->props["thunderbolt_aim"].get_coord(); } targetter_thunderbolt hitfunc(caster, spell_range(SPELL_THUNDERBOLT, pow), prev); hitfunc.set_aim(aim); mon_attitude_type castatt = caster->temp_attitude(); int friendly = 0, enemy = 0; for (map<coord_def, aff_type>::const_iterator p = hitfunc.zapped.begin(); p != hitfunc.zapped.end(); ++p) { if (p->second <= 0) continue; const actor *victim = actor_at(p->first); if (!victim) continue; int dam = 4 >> victim->res_elec(); if (mons_atts_aligned(castatt, victim->temp_attitude())) friendly += dam; else enemy += dam; } return enemy > friendly; return false; } // handle_rod // -- implemented as a dependent to handle_wand currently // (no wand + rod turns this way) // notes: // shamelessly repurposing handle_wand code // not one word about the name of this function! static bool _handle_rod(monster *mons, bolt &beem) { const int weapon = mons->inv[MSLOT_WEAPON]; item_def &rod(mitm[weapon]); // Make sure the item actually is a rod. ASSERT(rod.base_type == OBJ_RODS); // was the player visible when we started? bool was_visible = you.can_see(mons); bool check_validity = true; bool is_direct_effect = false; spell_type mzap = SPELL_NO_SPELL; int rate = 0; if (!_get_rod_spell_and_cost(rod, mzap, rate)) return false; // XXX: There should be a better way to do this than hardcoding // monster-castable rod spells! switch (mzap) { case SPELL_BOLT_OF_FIRE: case SPELL_BOLT_OF_INACCURACY: case SPELL_IRON_SHOT: case SPELL_LIGHTNING_BOLT: case SPELL_POISON_ARROW: case SPELL_THROW_FLAME: case SPELL_THROW_FROST: break; case SPELL_FIREBALL: if (mons->foe_distance() < 2) return false; break; case SPELL_FREEZING_CLOUD: case SPELL_POISONOUS_CLOUD: if (mons->foe_distance() <= 2) return false; break; case SPELL_THUNDERBOLT: if (mons->props.exists("thunderbolt_last") && mons->props["thunderbolt_last"].get_int() + 1 == you.num_turns) { rate = min(5 * ROD_CHARGE_MULT, (int)rod.plus); mons->props["thunderbolt_mana"].get_int() = rate; } break; case SPELL_CALL_IMP: case SPELL_CAUSE_FEAR: case SPELL_SUMMON_DEMON: case SPELL_SUMMON_SWARM: case SPELL_OLGREBS_TOXIC_RADIANCE: _rod_fired_pre(mons); mons_cast(mons, beem, mzap, false); _rod_fired_post(mons, rod, weapon, beem, rate, was_visible); return true; default: return false; } bool zap = false; // set up the beam const int power = max(_generate_rod_power(mons), 1); dprf("using rod with power %d", power); bolt theBeam = mons_spell_beam(mons, mzap, power, check_validity); beem = _generate_item_beem(beem, theBeam, mons); beem.aux_source = rod.name(DESC_QUALNAME, false, true, false, false); if (mons->confused()) { beem.target = dgn_random_point_from(mons->pos(), LOS_RADIUS); if (beem.target.origin()) return false; zap = true; } else if (mzap == SPELL_THUNDERBOLT) zap = _thunderbolt_tracer(mons, power, beem.target); else { fire_tracer(mons, beem); zap = mons_should_fire(beem); } if (is_direct_effect) { actor* foe = mons->get_foe(); if (!foe) return false; _rod_fired_pre(mons); direct_effect(mons, mzap, beem, foe); return _rod_fired_post(mons, rod, weapon, beem, rate, was_visible); } else if (mzap == SPELL_THUNDERBOLT) { _rod_fired_pre(mons); cast_thunderbolt(mons, power, beem.target); return _rod_fired_post(mons, rod, weapon, beem, rate, was_visible); } else if (zap) { _rod_fired_pre(mons); beem.is_tracer = false; beem.fire(); return _rod_fired_post(mons, rod, weapon, beem, rate, was_visible); } return false; } //--------------------------------------------------------------- // // handle_wand // // Give the monster a chance to zap a wand or rod. Returns true // if the monster zapped. // //--------------------------------------------------------------- static bool _handle_wand(monster* mons, bolt &beem) { // Yes, there is a logic to this ordering {dlb}: // FIXME: monsters should be able to use wands or rods // out of sight of the player [rob] if (!mons_near(mons) || mons->asleep() || mons->has_ench(ENCH_SUBMERGED) || coinflip()) { return false; } if (mons_itemuse(mons) < MONUSE_STARTING_EQUIPMENT) return false; if (mons->inv[MSLOT_WEAPON] != NON_ITEM && mitm[mons->inv[MSLOT_WEAPON]].base_type == OBJ_RODS) { return _handle_rod(mons, beem); } if (mons->inv[MSLOT_WAND] == NON_ITEM || mitm[mons->inv[MSLOT_WAND]].plus <= 0) { return false; } // Make sure the item actually is a wand. if (mitm[mons->inv[MSLOT_WAND]].base_type != OBJ_WANDS) return false; bool niceWand = false; bool zap = false; bool was_visible = you.can_see(mons); if (!_setup_wand_beam(beem, mons)) return false; item_def &wand = mitm[mons->inv[MSLOT_WAND]]; const wand_type kind = (wand_type)wand.sub_type; switch (kind) { case WAND_DISINTEGRATION: // Dial down damage from wands of disintegration, since // disintegration beams can do large amounts of damage. beem.damage.size = beem.damage.size * 2 / 3; break; case WAND_ENSLAVEMENT: case WAND_RANDOM_EFFECTS: // These have been deemed "too tricky" at this time {dlb}: return false; case WAND_DIGGING: // This is handled elsewhere. return false; // These are wands that monsters will aim at themselves {dlb}: case WAND_HASTING: if (!mons->has_ench(ENCH_HASTE)) { beem.target = mons->pos(); niceWand = true; break; } return false; case WAND_HEAL_WOUNDS: if (mons->hit_points <= mons->max_hit_points / 2) { beem.target = mons->pos(); niceWand = true; break; } return false; case WAND_INVISIBILITY: if (!mons->has_ench(ENCH_INVIS) && !mons->has_ench(ENCH_SUBMERGED) && !mons->glows_naturally() && (!mons->friendly() || you.can_see_invisible(false))) { beem.target = mons->pos(); niceWand = true; break; } return false; case WAND_TELEPORTATION: if (mons->hit_points <= mons->max_hit_points / 2 || mons->caught()) { if (!mons->has_ench(ENCH_TP) && !one_chance_in(20)) { beem.target = mons->pos(); niceWand = true; break; } // This break causes the wand to be tried on the player. break; } return false; default: break; } if (mons->confused()) { beem.target = dgn_random_point_from(mons->pos(), LOS_RADIUS); if (beem.target.origin()) return false; zap = true; } else if (!niceWand) { // Fire tracer, if necessary. fire_tracer(mons, beem); // Good idea? zap = mons_should_fire(beem); } if (niceWand || zap) { if (!niceWand) make_mons_stop_fleeing(mons); _mons_fire_wand(mons, wand, beem, was_visible, niceWand); return true; } return false; } static bool _mons_has_launcher(const monster* mons) { for (int i = MSLOT_WEAPON; i <= MSLOT_ALT_WEAPON; ++i) { if (item_def *item = mons->mslot_item(static_cast<mon_inv_type>(i))) { if (is_range_weapon(*item)) return true; } } return false; } //--------------------------------------------------------------- // // handle_throw // // Give the monster a chance to throw something. Returns true if // the monster hurled. // //--------------------------------------------------------------- static bool _handle_throw(monster* mons, bolt & beem) { // Yes, there is a logic to this ordering {dlb}: if (mons->incapacitated() || mons->submerged()) { return false; } if (mons_itemuse(mons) < MONUSE_STARTING_EQUIPMENT && mons->type != MONS_SPECTRAL_THING) { return false; } bool archer = mons->is_archer(); const bool liquefied = mons->liquefied_ground(); // Highly-specialised archers are more likely to shoot than talk. (?) // If we're standing on liquefied ground, try to stand and fire! // (Particularly archers.) if ((liquefied && !archer && one_chance_in(9)) || (!liquefied && one_chance_in(archer ? 9 : 5))) return false; if (mons_class_flag(mons->type, M_STABBER) && mons->get_foe() != NULL) { // Stabbers going in for the kill don't use ranged attacks. if (mons->get_foe()->incapacitated()) return false; // But assassins WILL use their blowguns in melee range, if their foe is // not already incapacitated and they have useful ammo left. else if (mons_has_incapacitating_ranged_attack(mons, mons->get_foe())) archer = true; } // Don't allow offscreen throwing for now. if (mons->foe == MHITYOU && !mons_near(mons)) return false; // Monsters won't shoot in melee range, largely for balance reasons. // Specialist archers are an exception to this rule. if (!archer && adjacent(beem.target, mons->pos())) return false; // If the monster is a spellcaster, don't bother throwing stuff. // Exception: Spellcasters that already start out with some kind // ranged weapon. Seeing how monsters are disallowed from picking // up launchers if they have ranged spells, this will only apply // to very few monsters. if (mons_has_ranged_spell(mons, true, false) && !_mons_has_launcher(mons)) { return false; } // Greatly lowered chances if the monster is fleeing or pacified and // leaving the level. if ((mons_is_fleeing(mons) || mons->pacified()) && !one_chance_in(8)) { return false; } item_def *launcher = NULL; const item_def *weapon = NULL; const int mon_item = mons_pick_best_missile(mons, &launcher); if (mon_item == NON_ITEM || !mitm[mon_item].defined()) return false; if (player_or_mon_in_sanct(mons)) return false; item_def *missile = &mitm[mon_item]; const actor *act = actor_at(beem.target); if (missile->base_type == OBJ_MISSILES && missile->sub_type == MI_THROWING_NET && act) { // Throwing a net at a target that is already caught would be // completely useless, so bail out. if (act->caught()) return false; // Netting targets that are already permanently stuck in place // is similarly useless. if (mons_class_is_stationary(act->type)) return false; } // If the attack needs a launcher that we can't wield, bail out. if (launcher) { weapon = mons->mslot_item(MSLOT_WEAPON); if (weapon && weapon != launcher && weapon->cursed()) return false; } // Ok, we'll try it. setup_monster_throw_beam(mons, beem); // Set fake damage for the tracer. beem.damage = dice_def(10, 10); // Set item for tracer, even though it probably won't be used beem.item = missile; // Fire tracer. fire_tracer(mons, beem); // Clear fake damage (will be set correctly in mons_throw). beem.damage = 0; // Good idea? if (mons_should_fire(beem)) { // Monsters shouldn't shoot if fleeing, so let them "turn to attack". make_mons_stop_fleeing(mons); if (launcher && launcher != weapon) mons->swap_weapons(); beem.name.clear(); return mons_throw(mons, beem, mon_item); } return false; } // Give the monster its action energy (aka speed_increment). static void _monster_add_energy(monster* mons) { if (mons->speed > 0) { // Randomise to make counting off monster moves harder: const int energy_gained = max(1, div_rand_round(mons->speed * you.time_taken, 10)); mons->speed_increment += energy_gained; } } #ifdef DEBUG # define DEBUG_ENERGY_USE(problem) \ if (mons->speed_increment == old_energy && mons->alive()) \ mprf(MSGCH_DIAGNOSTICS, \ problem " for monster '%s' consumed no energy", \ mons->name(DESC_PLAIN).c_str()); #else # define DEBUG_ENERGY_USE(problem) ((void) 0) #endif static void _confused_move_dir(monster *mons) { mmov.reset(); int pfound = 0; for (adjacent_iterator ai(mons->pos(), false); ai; ++ai) if (mons->can_pass_through(*ai)) { // Highly intelligent monsters don't move if they might drown. if (mons_intel(mons) == I_HIGH && !mons->is_habitable(*ai)) { // Players without a spoiler sheet have no way to know which // monsters are I_HIGH, and this behaviour is obscure. // Thus, give a message. const string where = make_stringf("%s@%d,%d", level_id::current().describe().c_str(), mons->pos().x, mons->pos().y); if (!mons->props.exists("no_conf_move") || mons->props["no_conf_move"].get_string() != where) { // But don't spam. mons->props["no_conf_move"] = where; simple_monster_message(mons, make_stringf(" stays still, afraid of the %s.", feat_type_name(grd(*ai))).c_str()); } mmov.reset(); break; } else if (one_chance_in(++pfound)) mmov = *ai - mons->pos(); } } static int _tentacle_move_speed(monster_type type) { if (type == MONS_KRAKEN) return 10; else if (type == MONS_TENTACLED_STARSPAWN) return 18; else return 0; } static void _pre_monster_move(monster* mons) { mons->hit_points = min(mons->max_hit_points, mons->hit_points); if (mons->type == MONS_SPATIAL_MAELSTROM && !player_in_branch(BRANCH_ABYSS) && !player_in_branch(BRANCH_ZIGGURAT)) { for (int i = 0; i < you.time_taken; ++i) { if (one_chance_in(100)) { mons->banish(mons); return; } } } if (mons->type == MONS_SNAPLASHER_VINE && mons->props.exists("vine_awakener")) { monster* awakener = monster_by_mid(mons->props["vine_awakener"].get_int()); if (awakener && !awakener->can_see(mons)) { simple_monster_message(mons, " falls limply to the ground."); monster_die(mons, KILL_RESET, NON_MONSTER); return; } } if (mons_stores_tracking_data(mons)) { actor* foe = mons->get_foe(); if (foe) { if (!mons->props.exists("foe_pos")) mons->props["foe_pos"].get_coord() = foe->pos(); else { if (mons->props["foe_pos"].get_coord().distance_from(mons->pos()) > foe->pos().distance_from(mons->pos())) mons->props["foe_approaching"].get_bool() = true; else mons->props["foe_approaching"].get_bool() = false; mons->props["foe_pos"].get_coord() = foe->pos(); } } else mons->props.erase("foe_pos"); } reset_battlesphere(mons); reset_spectral_weapon(mons); // This seems to need to go here to actually get monsters to slow down. // XXX: Replace with a new ENCH_LIQUEFIED_GROUND or something. if (mons->liquefied_ground()) { mon_enchant me = mon_enchant(ENCH_SLOW, 0, 0, 20); if (mons->has_ench(ENCH_SLOW)) mons->update_ench(me); else mons->add_ench(me); mons->calc_speed(); } fedhas_neutralise(mons); // Monster just summoned (or just took stairs), skip this action. if (!mons_is_mimic(mons->type) && testbits(mons->flags, MF_JUST_SUMMONED)) { mons->flags &= ~MF_JUST_SUMMONED; return; } mon_acting mact(mons); // Mimics get enough energy to act immediately when revealed. if (mons_is_mimic(mons->type) && testbits(mons->flags, MF_JUST_SUMMONED)) { mons->speed_increment = 80; mons->flags &= ~MF_JUST_SUMMONED; } else _monster_add_energy(mons); // Handle clouds on nonmoving monsters. if (mons->speed == 0) { _mons_in_cloud(mons); // Update constriction durations mons->accum_has_constricted(); _heated_area(mons); if (mons->type == MONS_NO_MONSTER) return; } // Apply monster enchantments once for every normal-speed // player turn. mons->ench_countdown -= you.time_taken; while (mons->ench_countdown < 0) { mons->ench_countdown += 10; mons->apply_enchantments(); // If the monster *merely* died just break from the loop // rather than quit altogether, since we have to deal with // giant spores and ball lightning exploding at the end of the // function, but do return if the monster's data has been // reset, since then the monster type is invalid. if (mons->type == MONS_NO_MONSTER) return; else if (mons->hit_points < 1) break; } // Memory is decremented here for a reason -- we only want it // decrementing once per monster "move". if (mons->foe_memory > 0 && !you.penance[GOD_ASHENZARI] && !mons_class_flag(mons->type, M_VIGILANT)) { mons->foe_memory -= you.time_taken; } // Otherwise there are potential problems with summonings. if (mons->type == MONS_GLOWING_SHAPESHIFTER) mons->add_ench(ENCH_GLOWING_SHAPESHIFTER); if (mons->type == MONS_SHAPESHIFTER) mons->add_ench(ENCH_SHAPESHIFTER); // We reset batty monsters from wander to seek here, instead // of in handle_behaviour() since that will be called with // every single movement, and we want these monsters to // hit and run. -- bwr if (mons->foe != MHITNOT && mons_is_wandering(mons) && mons_is_batty(mons)) { mons->behaviour = BEH_SEEK; } mons->check_speed(); } void handle_monster_move(monster* mons) { const monsterentry* entry = get_monster_data(mons->type); if (!entry) return; int old_energy = mons->speed_increment; int non_move_energy = min(entry->energy_usage.move, entry->energy_usage.swim); #ifdef DEBUG_MONS_SCAN bool monster_was_floating = mgrd(mons->pos()) != mons->mindex(); #endif coord_def old_pos = mons->pos(); coord_def kraken_last_update = mons->pos(); if (!mons->has_action_energy()) return; move_solo_tentacle(mons); if (!mons->alive()) return; if (old_pos != mons->pos() && mons_is_tentacle_head(mons_base_type(mons))) { move_child_tentacles(mons); kraken_last_update = mons->pos(); } old_pos = mons->pos(); #ifdef DEBUG_MONS_SCAN if (!monster_was_floating && mgrd(mons->pos()) != mons->mindex()) { mprf(MSGCH_ERROR, "Monster %s became detached from mgrd " "in handle_monster_move() loop", mons->name(DESC_PLAIN, true).c_str()); mpr("[[[[[[[[[[[[[[[[[[", MSGCH_WARN); debug_mons_scan(); mpr("]]]]]]]]]]]]]]]]]]", MSGCH_WARN); monster_was_floating = true; } else if (monster_was_floating && mgrd(mons->pos()) == mons->mindex()) { mprf(MSGCH_DIAGNOSTICS, "Monster %s re-attached itself to mgrd " "in handle_monster_move() loop", mons->name(DESC_PLAIN, true).c_str()); monster_was_floating = false; } #endif if (mons->is_projectile()) { if (iood_act(*mons)) return; mons->lose_energy(EUT_MOVE); return; } if (mons->type == MONS_BATTLESPHERE) { if (fire_battlesphere(mons)) mons->lose_energy(EUT_SPECIAL); } if (mons->type == MONS_FULMINANT_PRISM) { ++mons->number; if (mons->number == 2) mons->suicide(); else { if (player_can_hear(mons->pos())) { if (you.can_see(mons)) { simple_monster_message(mons, " crackles loudly.", MSGCH_WARN); } else mpr("You hear a loud crackle.", MSGCH_SOUND); } // Done this way to keep the detonation timer predictable mons->speed_increment -= 10; } return; } mons->shield_blocks = 0; const int cloud_num = env.cgrid(mons->pos()); const bool avoid_cloud = mons_avoids_cloud(mons, cloud_num); _mons_in_cloud(mons); _heated_area(mons); if (!mons->alive()) return; slime_wall_damage(mons, speed_to_duration(mons->speed)); if (!mons->alive()) return; if (mons->type == MONS_TIAMAT && one_chance_in(3)) draconian_change_colour(mons); _monster_regenerate(mons); if (mons->cannot_act() || mons->type == MONS_SIXFIRHY // these move only 8 of 24 turns && ++mons->number / 8 % 3 != 2 // but are not helpless || mons->type == MONS_JIANGSHI // similarly, but more irregular (48 of 90) && (++mons->number / 6 % 3 == 1 || mons->number / 3 % 5 == 1)) { mons->speed_increment -= non_move_energy; return; } if (mons->has_ench(ENCH_DAZED) && one_chance_in(5)) { simple_monster_message(mons, " is lost in a daze."); mons->speed_increment -= non_move_energy; return; } if (crawl_state.disables[DIS_MON_ACT] && _unfriendly_or_insane(mons)) { mons->speed_increment -= non_move_energy; return; } handle_behaviour(mons); // handle_behaviour() could make the monster leave the level. if (!mons->alive()) return; ASSERT(!crawl_state.game_is_arena() || mons->foe != MHITYOU); ASSERT_IN_BOUNDS_OR_ORIGIN(mons->target); // Submerging monsters will hide from clouds. if (avoid_cloud && monster_can_submerge(mons, grd(mons->pos())) && !mons->caught() && !mons->submerged()) { mons->add_ench(ENCH_SUBMERGED); mons->speed_increment -= ENERGY_SUBMERGE(entry); return; } if (mons->speed >= 100) { mons->speed_increment -= non_move_energy; return; } if (igrd(mons->pos()) != NON_ITEM && (mons_itemuse(mons) >= MONUSE_WEAPONS_ARMOUR || mons_itemeat(mons) != MONEAT_NOTHING)) { // Keep neutral, charmed, summoned monsters from picking up stuff. // Same for friendlies if friendly_pickup is set to "none". if ((!mons->neutral() && !mons->has_ench(ENCH_CHARM) || (you_worship(GOD_JIYVA) && mons_is_slime(mons))) && !mons->is_summoned() && !mons->is_perm_summoned() && (!mons->friendly() || you.friendly_pickup != FRIENDLY_PICKUP_NONE)) { if (_handle_pickup(mons)) { DEBUG_ENERGY_USE("handle_pickup()"); return; } } } // Lurking monsters only stop lurking if their target is right // next to them, otherwise they just sit there. // However, if the monster is involuntarily submerged but // still alive (e.g., nonbreathing which had water poured // on top of it), this doesn't apply. if (mons_is_lurking(mons) || mons->has_ench(ENCH_SUBMERGED)) { if (mons->foe != MHITNOT && grid_distance(mons->target, mons->pos()) <= 1) { if (mons->submerged()) { // Don't unsubmerge if the monster is avoiding the // cloud on top of the water. if (avoid_cloud) { mons->speed_increment -= non_move_energy; return; } if (!mons->del_ench(ENCH_SUBMERGED)) { // Couldn't unsubmerge. mons->speed_increment -= non_move_energy; return; } } mons->behaviour = BEH_SEEK; } else { mons->speed_increment -= non_move_energy; return; } } if (mons->caught()) { // Struggling against the net takes time. _swim_or_move_energy(mons); } else if (!mons->petrified()) { // Calculates mmov based on monster target. _handle_movement(mons); _shedu_movement_clamp(mons); if (mons_is_confused(mons) || mons->type == MONS_AIR_ELEMENTAL && mons->submerged()) { _confused_move_dir(mons); // OK, mmov determined. const coord_def newcell = mmov + mons->pos(); monster* enemy = monster_at(newcell); if (enemy && newcell != mons->pos() && !is_sanctuary(mons->pos())) { if (fight_melee(mons, enemy)) { mmov.reset(); DEBUG_ENERGY_USE("fight_melee()"); return; } else { // FIXME: None of these work! // Instead run away! if (mons->add_ench(mon_enchant(ENCH_FEAR))) behaviour_event(mons, ME_SCARE, 0, newcell); return; } } } } mon_nearby_ability(mons); if (!mons->alive()) return; // XXX: A bit hacky, but stores where we WILL move, if we don't take // another action instead (used for decision-making) if (mons_stores_tracking_data(mons)) mons->props["mmov"].get_coord() = mmov; if (!mons->asleep() && !mons_is_wandering(mons) && !mons->withdrawn() // Berserking monsters are limited to running up and // hitting their foes. && !mons->berserk_or_insane() // Slime creatures can split while wandering or resting. || mons->type == MONS_SLIME_CREATURE) { bolt beem; beem.source = mons->pos(); beem.target = mons->target; beem.beam_source = mons->mindex(); // XXX: Otherwise perma-confused monsters can almost never properly // aim spells, since their target is constantly randomized. // This does make them automatically aware of the player in several // situations they otherwise would not, however. if (mons_class_flag(mons->type, M_CONFUSED)) { actor* foe = mons->get_foe(); if (foe && mons->can_see(foe)) beem.target = foe->pos(); } // Prevents unfriendlies from nuking you from offscreen. // How nice! const bool friendly_or_near = mons->friendly() && mons->foe == MHITYOU || mons->near_foe(); if (friendly_or_near || mons->type == MONS_TEST_SPAWNER // Slime creatures can split when offscreen. || mons->type == MONS_SLIME_CREATURE // Lost souls can flicker away at any time they're isolated || mons->type == MONS_LOST_SOUL // Let monsters who have Dig use it off-screen. || mons->has_spell(SPELL_DIG)) { // [ds] Special abilities shouldn't overwhelm // spellcasting in monsters that have both. This aims // to give them both roughly the same weight. if (coinflip() ? mon_special_ability(mons, beem) || _do_mon_spell(mons, beem) : _do_mon_spell(mons, beem) || mon_special_ability(mons, beem)) { DEBUG_ENERGY_USE("spell or special"); mmov.reset(); return; } } if (friendly_or_near) { if (_handle_potion(mons, beem)) { DEBUG_ENERGY_USE("_handle_potion()"); return; } if (_handle_scroll(mons)) { DEBUG_ENERGY_USE("_handle_scroll()"); return; } if (_handle_evoke_equipment(mons, beem)) { DEBUG_ENERGY_USE("_handle_evoke_equipment()"); return; } if (_handle_wand(mons, beem)) { DEBUG_ENERGY_USE("_handle_wand()"); return; } if (_handle_reaching(mons)) { DEBUG_ENERGY_USE("_handle_reaching()"); return; } } if (_handle_throw(mons, beem)) { DEBUG_ENERGY_USE("_handle_throw()"); return; } } if (!mons->caught()) { if (mons->pos() + mmov == you.pos()) { ASSERT(!crawl_state.game_is_arena()); if (_unfriendly_or_insane(mons) && !mons->has_ench(ENCH_CHARM) && !mons->withdrawn()) { if (!mons->wont_attack()) { // If it steps into you, cancel other targets. mons->foe = MHITYOU; mons->target = you.pos(); } fight_melee(mons, &you); if (mons_is_batty(mons)) { mons->behaviour = BEH_WANDER; set_random_target(mons); } DEBUG_ENERGY_USE("fight_melee()"); mmov.reset(); return; } } // See if we move into (and fight) an unfriendly monster. monster* targ = monster_at(mons->pos() + mmov); //If a tentacle owner is attempting to move into an adjacent //segment, kill the segment and adjust connectivity data. if (targ && mons_tentacle_adjacent(mons, targ)) { bool basis = targ->props.exists("outwards"); int out_idx = basis ? targ->props["outwards"].get_int() : -1; if (out_idx != -1) menv[out_idx].props["inwards"].get_int() = mons->mindex(); monster_die(targ, KILL_MISC, NON_MONSTER, true); targ = NULL; } if (targ && targ != mons && mons->behaviour != BEH_WITHDRAW && (!mons_aligned(mons, targ) || mons->has_ench(ENCH_INSANE)) && monster_can_hit_monster(mons, targ)) { // Maybe they can swap places? if (_swap_monsters(mons, targ)) { _swim_or_move_energy(mons); return; } // Figure out if they fight. else if ((!mons_is_firewood(targ) || mons->is_child_tentacle()) && fight_melee(mons, targ)) { if (mons_is_batty(mons)) { mons->behaviour = BEH_WANDER; set_random_target(mons); // mons->speed_increment -= mons->speed; } mmov.reset(); DEBUG_ENERGY_USE("fight_melee()"); return; } } else if (mons->behaviour == BEH_WITHDRAW && ((targ && targ != mons && targ->friendly()) || (you.pos() == mons->pos() + mmov))) { // Don't count turns spent blocked by friendly creatures // (or the player) as an indication that we're stuck mons->props.erase("blocked_deadline"); } if (invalid_monster(mons) || mons->is_stationary()) { if (mons->speed_increment == old_energy) mons->speed_increment -= non_move_energy; return; } if (mons->cannot_move() || !_monster_move(mons)) { mons->speed_increment -= non_move_energy; mons->check_clinging(false); } } you.update_beholder(mons); you.update_fearmonger(mons); // Reevaluate behaviour, since the monster's surroundings have // changed (it may have moved, or died for that matter). Don't // bother for dead monsters. :) if (mons->alive()) { handle_behaviour(mons); ASSERT_IN_BOUNDS_OR_ORIGIN(mons->target); } if (mons_is_tentacle_head(mons_base_type(mons))) { if (mons->pos() != kraken_last_update) move_child_tentacles(mons); mons->number += (old_energy - mons->speed_increment) * _tentacle_move_speed(mons_base_type(mons)); while (mons->number >= 100) { move_child_tentacles(mons); mons->number -= 100; } } } static void _post_monster_move(monster* mons) { if (invalid_monster(mons)) return; mons->handle_constriction(); if (mons->type == MONS_ANCIENT_ZYME) ancient_zyme_sicken(mons); if (mons->type == MONS_ASMODEUS || mons->type == MONS_CHAOS_BUTTERFLY) { cloud_type ctype; switch (mons->type) { case MONS_ASMODEUS: ctype = CLOUD_FIRE; break; case MONS_CHAOS_BUTTERFLY: ctype = CLOUD_RAIN; break; default: ctype = CLOUD_NONE; break; } for (adjacent_iterator ai(mons->pos()); ai; ++ai) if (!feat_is_solid(grd(*ai)) && (env.cgrid(*ai) == EMPTY_CLOUD || env.cloud[env.cgrid(*ai)].type == ctype)) { place_cloud(ctype, *ai, 2 + random2(6), mons); } } if (mons->type != MONS_NO_MONSTER && mons->hit_points < 1) monster_die(mons, KILL_MISC, NON_MONSTER); } priority_queue<pair<monster *, int>, vector<pair<monster *, int> >, MonsterActionQueueCompare> monster_queue; // Inserts a monster into the monster queue (needed to ensure that any monsters // given energy or an action by a effect can actually make use of that energy // this round) void queue_monster_for_action(monster* mons) { monster_queue.push(pair<monster *, int>(mons, mons->speed_increment)); } //--------------------------------------------------------------- // // handle_monsters // // This is the routine that controls monster AI. // //--------------------------------------------------------------- void handle_monsters(bool with_noise) { for (monster_iterator mi; mi; ++mi) { _pre_monster_move(*mi); if (!invalid_monster(*mi) && mi->alive() && mi->has_action_energy()) monster_queue.push(pair<monster *, int>(*mi, mi->speed_increment)); } int tries = 0; // infinite loop protection, shouldn't be ever needed while (!monster_queue.empty()) { if (tries++ > 32767) { die("infinite handle_monsters() loop, mons[0 of %d] is %s", (int)monster_queue.size(), monster_queue.top().first->name(DESC_PLAIN, true).c_str()); } monster *mon = monster_queue.top().first; const int oldspeed = monster_queue.top().second; monster_queue.pop(); if (invalid_monster(mon) || !mon->alive() || !mon->has_action_energy()) continue; // Only move the monster if nothing else has played with its energy // during their turn. // This can happen with, e.g., headbutt stuns, cold attacks on cold- // -blooded monsters, etc. // If something's played with the energy, they get added back to // the queue just after this. if (oldspeed == mon->speed_increment) { handle_monster_move(mon); _post_monster_move(mon); fire_final_effects(); } if (mon->has_action_energy()) { monster_queue.push( pair<monster *, int>(mon, mon->speed_increment)); } // If the player got banished, discard pending monster actions. if (you.banished) { // Clear list of mesmerising monsters. you.clear_beholders(); you.clear_fearmongers(); you.stop_constricting_all(); you.stop_being_constricted(); break; } } // Process noises now (before clearing the sleep flag). if (with_noise) apply_noises(); // Clear one-turn deep sleep flag. // XXX: With the current handling, it would be cleaner to // not treat this as an enchantment. // XXX: ENCH_SLEEPY only really works for player-cast // hibernation. for (monster_iterator mi; mi; ++mi) mi->del_ench(ENCH_SLEEPY); // Clear any summoning flags so that lower indiced // monsters get their actions in the next round. for (int i = 0; i < MAX_MONSTERS; i++) menv[i].flags &= ~MF_JUST_SUMMONED; } static bool _jelly_divide(monster* parent) { if (!mons_class_flag(parent->type, M_SPLITS)) return false; const int reqd = max(parent->hit_dice * 8, 50); if (parent->hit_points < reqd) return false; monster* child = NULL; coord_def child_spot; int num_spots = 0; // First, find a suitable spot for the child {dlb}: for (adjacent_iterator ai(parent->pos()); ai; ++ai) if (actor_at(*ai) == NULL && parent->can_pass_through(*ai) && one_chance_in(++num_spots)) { child_spot = *ai; } if (num_spots == 0) return false; // Now that we have a spot, find a monster slot {dlb}: child = get_free_monster(); if (!child) return false; // Handle impact of split on parent {dlb}: parent->max_hit_points /= 2; if (parent->hit_points > parent->max_hit_points) parent->hit_points = parent->max_hit_points; parent->init_experience(); parent->experience = parent->experience * 3 / 5 + 1; // Create child {dlb}: // This is terribly partial and really requires // more thought as to generation ... {dlb} *child = *parent; child->max_hit_points = child->hit_points; child->speed_increment = 70 + random2(5); child->moveto(child_spot); child->set_new_monster_id(); mgrd(child->pos()) = child->mindex(); if (!simple_monster_message(parent, " splits in two!") && (player_can_hear(parent->pos()) || player_can_hear(child->pos()))) { mpr("You hear a squelching noise.", MSGCH_SOUND); } if (crawl_state.game_is_arena()) arena_placed_monster(child); return true; } // XXX: This function assumes that only jellies eat items. static bool _monster_eat_item(monster* mons, bool nearby) { if (!mons_eats_items(mons)) return false; // Friendly jellies won't eat (unless worshipping Jiyva). if (mons->friendly() && !you_worship(GOD_JIYVA)) return false; // Off-limit squares are off-limit. if (testbits(env.pgrid(mons->pos()), FPROP_NO_JIYVA)) return false; int hps_changed = 0; // Zotdef jellies are toned down slightly int max_eat = roll_dice(1, (crawl_state.game_is_zotdef() ? 8 : 10)); int eaten = 0; bool eaten_net = false; bool death_ooze_ate_good = false; bool death_ooze_ate_corpse = false; bool shown_msg = false; piety_gain_t gain = PIETY_NONE; int js = JS_NONE; // Jellies can swim, so don't check water for (stack_iterator si(mons->pos()); si && eaten < max_eat && hps_changed < 50; ++si) { if (!is_item_jelly_edible(*si)) continue; #if defined(DEBUG_DIAGNOSTICS) || defined(DEBUG_EATERS) mprf(MSGCH_DIAGNOSTICS, "%s eating %s", mons->name(DESC_PLAIN, true).c_str(), si->name(DESC_PLAIN).c_str()); #endif int quant = si->quantity; death_ooze_ate_good = (mons->type == MONS_DEATH_OOZE && (get_weapon_brand(*si) == SPWPN_HOLY_WRATH || get_ammo_brand(*si) == SPMSL_SILVER)); death_ooze_ate_corpse = (mons->type == MONS_DEATH_OOZE && ((si->base_type == OBJ_CORPSES && si->sub_type == CORPSE_BODY) || si->base_type == OBJ_FOOD && si->sub_type == FOOD_CHUNK)); if (si->base_type != OBJ_GOLD) { quant = min(quant, max_eat - eaten); hps_changed += (quant * item_mass(*si)) / (crawl_state.game_is_zotdef() ? 30 : 20) + quant; eaten += quant; if (mons->caught() && si->base_type == OBJ_MISSILES && si->sub_type == MI_THROWING_NET && item_is_stationary(*si)) { mons->del_ench(ENCH_HELD, true); eaten_net = true; } } else { // Shouldn't be much trouble to digest a huge pile of gold! if (quant > 500) quant = 500 + roll_dice(2, (quant - 500) / 2); hps_changed += quant / 10 + 1; eaten++; } if (eaten && !shown_msg && player_can_hear(mons->pos())) { mprf(MSGCH_SOUND, "You hear a%s slurping noise.", nearby ? "" : " distant"); shown_msg = true; } if (you_worship(GOD_JIYVA)) { gain = sacrifice_item_stack(*si, &js, quant); if (gain > PIETY_NONE) simple_god_message(" appreciates your sacrifice."); jiyva_slurp_message(js); } if (quant >= si->quantity) item_was_destroyed(*si, mons->mindex()); if (is_blood_potion(*si)) { for (int i = 0; i < quant; ++i) remove_oldest_blood_potion(*si); } dec_mitm_item_quantity(si.link(), quant); } if (eaten > 0) { hps_changed = max(hps_changed, 1); hps_changed = min(hps_changed, 50); if (death_ooze_ate_good) mons->hurt(NULL, hps_changed, BEAM_NONE, false); else { // This is done manually instead of using heal_monster(), // because that function doesn't work quite this way. - bwr const int base_max = mons_avg_hp(mons->type); mons->hit_points += hps_changed; mons->hit_points = min(MAX_MONSTER_HP, min(base_max * 2, mons->hit_points)); mons->max_hit_points = max(mons->hit_points, mons->max_hit_points); } if (death_ooze_ate_corpse) place_cloud(CLOUD_MIASMA, mons->pos(), 4 + random2(5), mons); if (death_ooze_ate_good) simple_monster_message(mons, " twists violently!"); else if (eaten_net) simple_monster_message(mons, " devours the net!"); else _jelly_divide(mons); } return (eaten > 0); } static bool _monster_eat_single_corpse(monster* mons, item_def& item, bool do_heal, bool nearby) { if (item.base_type != OBJ_CORPSES || item.sub_type != CORPSE_BODY) return false; const monster_type mt = item.mon_type; if (do_heal) { const int base_max = mons_avg_hp(mons->type); mons->hit_points += 1 + random2(mons_weight(mt)) / 100; mons->hit_points = min(MAX_MONSTER_HP, min(base_max * 2, mons->hit_points)); mons->max_hit_points = max(mons->hit_points, mons->max_hit_points); } if (nearby) { mprf("%s eats %s.", mons->name(DESC_THE).c_str(), item.name(DESC_THE).c_str()); } // Butcher the corpse without leaving chunks. butcher_corpse(item, MB_MAYBE, false); return true; } static bool _monster_eat_corpse(monster* mons, bool do_heal, bool nearby) { if (!mons_eats_corpses(mons)) return false; int eaten = 0; for (stack_iterator si(mons->pos()); si; ++si) { if (_monster_eat_single_corpse(mons, *si, do_heal, nearby)) { eaten++; break; } } return (eaten > 0); } static bool _monster_eat_food(monster* mons, bool nearby) { if (!mons_eats_food(mons)) return false; if (mons_is_fleeing(mons)) return false; int eaten = 0; for (stack_iterator si(mons->pos()); si; ++si) { const bool is_food = (si->base_type == OBJ_FOOD); const bool is_corpse = (si->base_type == OBJ_CORPSES && si->sub_type == CORPSE_BODY); const bool free_to_eat = (mons->wont_attack() || grid_distance(mons->pos(), you.pos()) > 1); if (!is_food && !is_corpse) continue; if (free_to_eat && coinflip()) { if (is_food) { if (nearby) { mprf("%s eats %s.", mons->name(DESC_THE).c_str(), quant_name(*si, 1, DESC_THE).c_str()); } dec_mitm_item_quantity(si.link(), 1); eaten++; break; } else { // Assume that only undead can heal from eating corpses. if (_monster_eat_single_corpse(mons, *si, mons->holiness() == MH_UNDEAD, nearby)) { eaten++; break; } } } } return (eaten > 0); } //--------------------------------------------------------------- // // handle_pickup // // Returns false if monster doesn't spend any time picking something up. // //--------------------------------------------------------------- static bool _handle_pickup(monster* mons) { if (mons->asleep() || mons->submerged()) return false; // Flying over water doesn't let you pick up stuff. This is inexact, as // a merfolk could be flying, but that's currently impossible except for // being tornadoed, and with *that* low life expectancy let's not care. dungeon_feature_type feat = grd(mons->pos()); if ((feat == DNGN_LAVA || feat == DNGN_DEEP_WATER) && mons->flight_mode()) return false; const bool nearby = mons_near(mons); int count_pickup = 0; if (mons_itemeat(mons) != MONEAT_NOTHING) { if (mons_eats_items(mons)) { if (_monster_eat_item(mons, nearby)) return false; } else if (mons_eats_corpses(mons)) { // Assume that only undead can heal from eating corpses. if (_monster_eat_corpse(mons, mons->holiness() == MH_UNDEAD, nearby)) { return false; } } else if (mons_eats_food(mons)) { if (_monster_eat_food(mons, nearby)) return false; } } if (mons_itemuse(mons) >= MONUSE_WEAPONS_ARMOUR) { // Note: Monsters only look at stuff near the top of stacks. // // XXX: Need to put in something so that monster picks up // multiple items (e.g. ammunition) identical to those it's // carrying. // // Monsters may now pick up up to two items in the same turn. // (jpeg) for (stack_iterator si(mons->pos()); si; ++si) { if (si->flags & ISFLAG_NO_PICKUP) continue; if (mons->pickup_item(*si, nearby)) count_pickup++; if (count_pickup > 1 || coinflip()) break; } } return (count_pickup > 0); } // Randomise potential damage. static int _estimated_trap_damage(trap_type trap) { switch (trap) { case TRAP_BLADE: return (10 + random2(30)); case TRAP_DART: return random2(4); case TRAP_ARROW: return random2(7); case TRAP_SPEAR: return random2(10); case TRAP_BOLT: return random2(13); default: return 0; } } // Check whether a given trap (described by trap position) can be // regarded as safe. Takes into account monster intelligence and // allegiance. // (just_check is used for intelligent monsters trying to avoid traps.) static bool _is_trap_safe(const monster* mons, const coord_def& where, bool just_check) { const int intel = mons_intel(mons); const trap_def *ptrap = find_trap(where); if (!ptrap) return true; const trap_def& trap = *ptrap; const bool player_knows_trap = (trap.is_known(&you)); // No friendly monsters will ever enter a Zot trap you know. if (player_knows_trap && mons->friendly() && trap.type == TRAP_ZOT) return false; // Dumb monsters don't care at all. if (intel == I_PLANT) return true; // Known shafts are safe. Unknown ones are unknown. if (trap.type == TRAP_SHAFT) return true; // Hostile monsters are not afraid of non-mechanical traps. // Allies will try to avoid teleportation and zot traps. const bool mechanical = (trap.category() == DNGN_TRAP_MECHANICAL); if (trap.is_known(mons)) { if (just_check) return false; // Square is blocked. else { // Test for corridor-like environment. const int x = where.x - mons->pos().x; const int y = where.y - mons->pos().y; // The question is whether the monster (m) can easily reach its // presumable destination (x) without stepping on the trap. Traps // in corridors do not allow this. See e.g // #x# ## // #^# or m^x // m ## // // The same problem occurs if paths are blocked by monsters, // hostile terrain or other traps rather than walls. // What we do is check whether the squares with the relative // positions (-1,0)/(+1,0) or (0,-1)/(0,+1) form a "corridor" // (relative to the _trap_ position rather than the monster one). // If they don't, the trap square is marked as "unsafe" (because // there's a good alternative move for the monster to take), // otherwise the decision will be made according to later tests // (monster hp, trap type, ...) // If a monster still gets stuck in a corridor it will usually be // because it has less than half its maximum hp. if ((mon_can_move_to_pos(mons, coord_def(x-1, y), true) || mon_can_move_to_pos(mons, coord_def(x+1,y), true)) && (mon_can_move_to_pos(mons, coord_def(x,y-1), true) || mon_can_move_to_pos(mons, coord_def(x,y+1), true))) { return false; } } } // Friendlies will try not to be parted from you. if (intelligent_ally(mons) && trap.type == TRAP_TELEPORT && player_knows_trap && mons_near(mons)) { return false; } // Healthy monsters don't mind a little pain. if (mechanical && mons->hit_points >= mons->max_hit_points / 2 && (intel == I_ANIMAL || mons->hit_points > _estimated_trap_damage(trap.type))) { return true; } // In Zotdef critters will risk death to get to the Orb if (crawl_state.game_is_zotdef() && mechanical) return true; // Friendly and good neutral monsters don't enjoy Zot trap perks; // handle accordingly. In the arena Zot traps affect all monsters. if (mons->wont_attack() || crawl_state.game_is_arena()) { return (mechanical ? mons_flies(mons) : !trap.is_known(mons) || trap.type != TRAP_ZOT); } else return (!mechanical || mons_flies(mons) || !trap.is_known(mons)); } static void _mons_open_door(monster* mons, const coord_def &pos) { const char *adj = "", *noun = "door"; bool was_seen = false; set<coord_def> all_door = connected_doors(pos); get_door_description(all_door.size(), &adj, &noun); for (set<coord_def>::iterator i = all_door.begin(); i != all_door.end(); ++i) { const coord_def& dc = *i; if (you.see_cell(dc)) was_seen = true; grd(dc) = DNGN_OPEN_DOOR; set_terrain_changed(dc); } if (was_seen) { viewwindow(); string open_str = "opens the "; open_str += adj; open_str += noun; open_str += "."; // Should this be conditionalized on you.can_see(mons?) mons->seen_context = (all_door.size() <= 2) ? SC_DOOR : SC_GATE; if (!you.can_see(mons)) { mprf("Something unseen %s", open_str.c_str()); interrupt_activity(AI_FORCE_INTERRUPT); } else if (!you_are_delayed()) { mprf("%s %s", mons->name(DESC_A).c_str(), open_str.c_str()); } } mons->lose_energy(EUT_MOVE); dungeon_events.fire_position_event(DET_DOOR_OPENED, pos); } static bool _no_habitable_adjacent_grids(const monster* mon) { for (adjacent_iterator ai(mon->pos()); ai; ++ai) if (monster_habitable_grid(mon, grd(*ai))) return false; return true; } static bool _same_tentacle_parts(const monster* mpusher, const monster* mpushee) { if (!mons_is_tentacle_head(mons_base_type(mpusher))) return false; if (mpushee->is_child_tentacle_of(mpusher)) return true; if (mons_tentacle_adjacent(mpusher, mpushee)) return true; return false; } static bool _mons_can_displace(const monster* mpusher, const monster* mpushee) { if (invalid_monster(mpusher) || invalid_monster(mpushee)) return false; const int ipushee = mpushee->mindex(); if (invalid_monster_index(ipushee)) return false; if (!mpushee->has_action_energy() && !_same_tentacle_parts(mpusher, mpushee)) { return false; } // Confused monsters can't be pushed past, sleeping monsters // can't push. Note that sleeping monsters can't be pushed // past, either, but they may be woken up by a crowd trying to // elbow past them, and the wake-up check happens downstream. // Monsters caught in a net also can't be pushed past. if (mons_is_confused(mpusher) || mons_is_confused(mpushee) || mpusher->cannot_move() || mpusher->is_stationary() || mpusher->is_constricted() || mpushee->is_constricted() || (!_same_tentacle_parts(mpusher, mpushee) && (mpushee->cannot_move() || mpushee->is_stationary())) || mpusher->asleep() || mpushee->caught()) { return false; } // Batty monsters are unpushable. if (mons_is_batty(mpusher) || mons_is_batty(mpushee)) return false; // Anyone can displace a submerged monster (otherwise monsters can // get stuck behind a trapdoor spider, giving away its presence). if (mpushee->submerged()) return true; if (!monster_shover(mpusher)) return false; // Fleeing monsters of the same type may push past higher ranking ones. if (!monster_senior(mpusher, mpushee, mons_is_retreating(mpusher))) return false; return true; } static int _count_adjacent_slime_walls(const coord_def &pos) { int count = 0; for (adjacent_iterator ai(pos); ai; ++ai) if (env.grid(*ai) == DNGN_SLIMY_WALL) count++; return count; } // Returns true if the monster should try to avoid that position // because of taking damage from slime walls. static bool _check_slime_walls(const monster *mon, const coord_def &targ) { if (!player_in_branch(BRANCH_SLIME_PITS) || mons_is_slime(mon) || actor_slime_wall_immune(mon) || mons_intel(mon) <= I_REPTILE) { return false; } const int target_count = _count_adjacent_slime_walls(targ); // Entirely safe. if (!target_count) return false; const int current_count = _count_adjacent_slime_walls(mon->pos()); if (target_count <= current_count) return false; // The monster needs to have a purpose to risk taking damage. if (!mons_is_seeking(mon)) return true; // With enough hit points monsters will consider moving // onto more dangerous squares. return (mon->hit_points < mon->max_hit_points / 2); } // Check whether a monster can move to given square (described by its relative // coordinates to the current monster position). just_check is true only for // calls from is_trap_safe when checking the surrounding squares of a trap. bool mon_can_move_to_pos(const monster* mons, const coord_def& delta, bool just_check) { const coord_def targ = mons->pos() + delta; // Bounds check: don't consider moving out of grid! if (!in_bounds(targ)) return false; // No monster may enter the open sea. if (grd(targ) == DNGN_OPEN_SEA || grd(targ) == DNGN_LAVA_SEA) return false; // Non-friendly and non-good neutral monsters won't enter // sanctuaries. if (!mons->wont_attack() && is_sanctuary(targ) && !is_sanctuary(mons->pos())) { return false; } // Inside a sanctuary don't attack anything! if (is_sanctuary(mons->pos()) && actor_at(targ)) return false; const dungeon_feature_type target_grid = grd(targ); const habitat_type habitat = mons_primary_habitat(mons); // The kraken is so large it cannot enter shallow water. // Its tentacles can, and will, though. if (mons_base_type(mons) == MONS_KRAKEN && target_grid == DNGN_SHALLOW_WATER) { return false; } bool no_water = false; const int targ_cloud_num = env.cgrid(targ); if (mons_avoids_cloud(mons, targ_cloud_num)) return false; if (_check_slime_walls(mons, targ)) return false; const bool burrows = mons_class_flag(mons->type, M_BURROWS); const bool digs = _mons_can_cast_dig(mons, false) || _mons_can_zap_dig(mons); const bool flattens_trees = mons_flattens_trees(mons); if (((burrows || digs) && (target_grid == DNGN_ROCK_WALL || target_grid == DNGN_CLEAR_ROCK_WALL)) || (flattens_trees && feat_is_tree(target_grid))) { // Don't burrow out of bounds. if (!in_bounds(targ)) return false; } else if (no_water && feat_is_water(target_grid)) return false; else if (!mons_can_traverse(mons, targ, false) && !monster_habitable_grid(mons, target_grid)) { // If the monster somehow ended up in this habitat (and is // not dead by now), give it a chance to get out again. if (grd(mons->pos()) == target_grid && mons->ground_level() && _no_habitable_adjacent_grids(mons)) { return true; } return false; } // Wandering mushrooms usually don't move while you are looking. if (mons->type == MONS_WANDERING_MUSHROOM || mons->type == MONS_DEATHCAP || mons->type == MONS_CURSE_SKULL || (mons->type == MONS_LURKING_HORROR && mons->foe_distance() > random2(LOS_RADIUS + 1))) { if (!mons->wont_attack() && is_sanctuary(mons->pos())) { return true; } if (!mons->friendly() && you.see_cell(targ) || mon_enemies_around(mons)) { return false; } } // Fire elementals avoid water and cold. if (mons->type == MONS_FIRE_ELEMENTAL && feat_is_watery(target_grid)) return false; // Submerged water creatures avoid the shallows where // they would be forced to surface. -- bwr // [dshaligram] Monsters now prefer to head for deep water only if // they're low on hitpoints. No point in hiding if they want a // fight. if (habitat == HT_WATER && targ != you.pos() && target_grid != DNGN_DEEP_WATER && grd(mons->pos()) == DNGN_DEEP_WATER && mons->hit_points < (mons->max_hit_points * 3) / 4) { return false; } // Smacking the player is always a good move if we're // hostile (even if we're heading somewhere else). // Also friendlies want to keep close to the player // so it's okay as well. // Smacking another monster is good, if the monsters // are aligned differently. if (monster* targmonster = monster_at(targ)) { if (just_check) { if (targ == mons->pos()) return true; return false; // blocks square } if (!summon_can_attack(mons, targ)) return false; // Cut down plants only when no alternative, or they're // our target. if (mons_is_firewood(targmonster) && mons->target != targ) return false; if (mons_aligned(mons, targmonster) && !mons->has_ench(ENCH_INSANE) && !_mons_can_displace(mons, targmonster)) { // In Zotdef hostiles will whack other hostiles if immobile // - prevents plugging gaps with hostile oklobs if (crawl_state.game_is_zotdef()) { if (!targmonster->is_stationary() || targmonster->attitude != ATT_HOSTILE) { return false; } } else return false; } // Prefer to move past enemies instead of hit them, if we're retreating else if ((!mons_aligned(mons, targmonster) || mons->has_ench(ENCH_INSANE)) && mons->behaviour == BEH_WITHDRAW) { return false; } } // Friendlies shouldn't try to move onto the player's // location, if they are aiming for some other target. if (!_unfriendly_or_insane(mons) && mons->foe != MHITYOU && (mons->foe != MHITNOT || mons->is_patrolling()) && targ == you.pos()) { return false; } // Wandering through a trap is OK if we're pretty healthy, // really stupid, or immune to the trap. if (!_is_trap_safe(mons, targ, just_check)) return false; // If we end up here the monster can safely move. return true; } // Uses, and updates the global variable mmov. static void _find_good_alternate_move(monster* mons, const move_array& good_move) { const coord_def target = mons->firing_pos.zero() ? mons->target : mons->firing_pos; const int current_distance = distance2(mons->pos(), target); int dir = _compass_idx(mmov); // Only handle if the original move is to an adjacent square. if (dir == -1) return; int dist[2]; // First 1 away, then 2 (3 is silly). for (int j = 1; j <= 2; j++) { const int FAR_AWAY = 1000000; // Try both directions (but randomise which one is first). const int sdir = coinflip() ? j : -j; const int inc = -2 * sdir; for (int mod = sdir, i = 0; i < 2; mod += inc, i++) { const int newdir = (dir + 8 + mod) % 8; if (good_move[mon_compass[newdir].x+1][mon_compass[newdir].y+1]) dist[i] = distance2(mons->pos()+mon_compass[newdir], target); else dist[i] = mons_is_retreating(mons) ? (-FAR_AWAY) : FAR_AWAY; } const int dir0 = ((dir + 8 + sdir) % 8); const int dir1 = ((dir + 8 - sdir) % 8); // Now choose. if (dist[0] == dist[1] && abs(dist[0]) == FAR_AWAY) continue; // Which one was better? -- depends on FLEEING or not. if (mons_is_retreating(mons)) { if (dist[0] >= dist[1] && dist[0] >= current_distance) { mmov = mon_compass[dir0]; break; } if (dist[1] >= dist[0] && dist[1] >= current_distance) { mmov = mon_compass[dir1]; break; } } else { if (dist[0] <= dist[1] && dist[0] <= current_distance) { mmov = mon_compass[dir0]; break; } if (dist[1] <= dist[0] && dist[1] <= current_distance) { mmov = mon_compass[dir1]; break; } } } } static void _jelly_grows(monster* mons) { if (player_can_hear(mons->pos())) { mprf(MSGCH_SOUND, "You hear a%s slurping noise.", mons_near(mons) ? "" : " distant"); } mons->hit_points += 5; // possible with ridiculous farming on a full level mons->hit_points = min(mons->hit_points, MAX_MONSTER_HP); // note here, that this makes jellies "grow" {dlb}: if (mons->hit_points > mons->max_hit_points) mons->max_hit_points = mons->hit_points; _jelly_divide(mons); } static bool _monster_swaps_places(monster* mon, const coord_def& delta) { if (delta.origin()) return false; monster* const m2 = monster_at(mon->pos() + delta); if (!m2) return false; if (!_mons_can_displace(mon, m2)) return false; if (m2->asleep()) { if (coinflip()) { dprf("Alerting monster %s at (%d,%d)", m2->name(DESC_PLAIN).c_str(), m2->pos().x, m2->pos().y); behaviour_event(m2, ME_ALERT); } return false; } // Check that both monsters will be happy at their proposed new locations. const coord_def c = mon->pos(); const coord_def n = mon->pos() + delta; if (!monster_habitable_grid(mon, grd(n)) && !mon->can_cling_to(n) || !monster_habitable_grid(m2, grd(c)) && !m2->can_cling_to(c)) { return false; } // Okay, do the swap! #ifdef EUCLIDEAN _swim_or_move_energy(mon, delta.abs() == 2); #else _swim_or_move_energy(mon); #endif mon->set_position(n); mgrd(n) = mon->mindex(); m2->set_position(c); mon->clear_far_constrictions(); m2->clear_far_constrictions(); const int m2i = m2->mindex(); ASSERT_RANGE(m2i, 0, MAX_MONSTERS); mgrd(c) = m2i; _swim_or_move_energy(m2); mon->check_redraw(c, false); if (mon->is_wall_clinging()) mon->check_clinging(true); else mon->apply_location_effects(c); m2->check_redraw(n, false); if (m2->is_wall_clinging()) m2->check_clinging(true); else m2->apply_location_effects(n); // The seen context no longer applies if the monster is moving normally. mon->seen_context = SC_NONE; m2->seen_context = SC_NONE; return false; } static bool _do_move_monster(monster* mons, const coord_def& delta) { const coord_def f = mons->pos() + delta; if (!in_bounds(f)) return false; if (f == you.pos()) { fight_melee(mons, &you); return true; } // This includes the case where the monster attacks itself. if (monster* def = monster_at(f)) { fight_melee(mons, def); return true; } if (mons->is_constricted()) { if (mons->attempt_escape()) simple_monster_message(mons, " escapes!"); else { simple_monster_message(mons, " struggles to escape constriction."); _swim_or_move_energy(mons); return true; } } if (grd(f) == DNGN_CLOSED_DOOR || grd(f) == DNGN_SEALED_DOOR) { if (mons_can_open_door(mons, f)) { _mons_open_door(mons, f); return true; } else if (mons_can_eat_door(mons, f)) { grd(f) = DNGN_FLOOR; set_terrain_changed(f); _jelly_grows(mons); if (you.see_cell(f)) { viewwindow(); if (!you.can_see(mons)) { mpr("The door mysteriously vanishes."); interrupt_activity(AI_FORCE_INTERRUPT); } else simple_monster_message(mons, " eats the door!"); } } // done door-eating jellies } // The monster gave a "comes into view" message and then immediately // moved back out of view, leaing the player nothing to see, so give // this message to avoid confusion. if (mons->seen_context == SC_JUST_SEEN && !you.see_cell(f)) simple_monster_message(mons, " moves out of view."); else if (crawl_state.game_is_hints() && (mons->flags & MF_WAS_IN_VIEW) && !you.see_cell(f)) { learned_something_new(HINT_MONSTER_LEFT_LOS, mons->pos()); } // The seen context no longer applies if the monster is moving normally. mons->seen_context = SC_NONE; // This appears to be the real one, ie where the movement occurs: #ifdef EUCLIDEAN _swim_or_move_energy(mons, delta.abs() == 2); #else _swim_or_move_energy(mons); #endif _escape_water_hold(mons); if (grd(mons->pos()) == DNGN_DEEP_WATER && grd(f) != DNGN_DEEP_WATER && !monster_habitable_grid(mons, DNGN_DEEP_WATER)) { // er, what? Seems impossible. mons->seen_context = SC_NONSWIMMER_SURFACES_FROM_DEEP; } mgrd(mons->pos()) = NON_MONSTER; coord_def old_pos = mons->pos(); mons->set_position(f); mgrd(mons->pos()) = mons->mindex(); mons->check_clinging(true); ballisto_on_move(mons, old_pos); // Let go of all constrictees; only stop *being* constricted if we are now // too far away. mons->stop_constricting_all(true); mons->clear_far_constrictions(); mons->check_redraw(mons->pos() - delta); mons->apply_location_effects(mons->pos() - delta); return true; } // May mons attack targ if it's in its way, despite // possibly aligned attitudes? // The aim of this is to have monsters cut down plants // to get to the player if necessary. static bool _may_cutdown(monster* mons, monster* targ) { // Save friendly plants from allies. // [ds] I'm deliberately making the alignment checks symmetric here. // The previous check involved good-neutrals never attacking friendlies // and friendlies never attacking anything other than hostiles. if ((mons->friendly() || mons->good_neutral()) && (targ->friendly() || targ->good_neutral())) { return false; } // Outside of that case, can always cut mundane plants. if (mons_is_firewood(targ)) { // Don't try to attack briars unless their damage will be insignificant if (targ->type == MONS_BRIAR_PATCH && mons->type != MONS_THORN_HUNTER && (mons->armour_class() * mons->hit_points) < 400) return false; else return true; } // In normal games, that's it. Gotta keep those butterflies alive... if (!crawl_state.game_is_zotdef()) return false; return targ->is_stationary() || mons_class_flag(mons_base_type(targ), M_NO_EXP_GAIN) && !mons_is_tentacle_or_tentacle_segment(targ->type); } static bool _monster_move(monster* mons) { move_array good_move; const habitat_type habitat = mons_primary_habitat(mons); bool deep_water_available = false; if (mons->type == MONS_TRAPDOOR_SPIDER) { if (mons->submerged()) return false; // Trapdoor spiders sometime hide if they can't see their foe. // (Note that friendly trapdoor spiders will thus hide even // if they can see you.) const actor *foe = mons->get_foe(); const bool can_see = foe && mons->can_see(foe); if (monster_can_submerge(mons, grd(mons->pos())) && !can_see && !mons_is_confused(mons) && !mons->caught() && !mons->berserk_or_insane() && one_chance_in(5)) { mons->add_ench(ENCH_SUBMERGED); mons->behaviour = BEH_LURK; return false; } } // Berserking monsters make a lot of racket. if (mons->berserk_or_insane()) { int noise_level = get_shout_noise_level(mons_shouts(mons->type)); if (noise_level > 0) { if (you.can_see(mons) && mons->berserk()) { if (one_chance_in(10)) { mprf(MSGCH_TALK_VISUAL, "%s rages.", mons->name(DESC_THE).c_str()); } noisy(noise_level, mons->pos(), mons->mindex()); } else if (one_chance_in(5)) handle_monster_shouts(mons, true); else { // Just be noisy without messaging the player. noisy(noise_level, mons->pos(), mons->mindex()); } } } if (mons->confused()) { if (!mmov.origin() || one_chance_in(15)) { const coord_def newpos = mons->pos() + mmov; if (in_bounds(newpos) && (habitat == HT_LAND || monster_habitable_grid(mons, grd(newpos)))) { return _do_move_monster(mons, mmov); } } return false; } // If a water monster is currently flopping around on land, it cannot // really control where it wants to move, though there's a 50% chance // of flopping into an adjacent water grid. if (mons->has_ench(ENCH_AQUATIC_LAND)) { vector<coord_def> adj_water; vector<coord_def> adj_move; for (adjacent_iterator ai(mons->pos()); ai; ++ai) { if (!cell_is_solid(*ai)) { adj_move.push_back(*ai); if (feat_is_watery(grd(*ai))) adj_water.push_back(*ai); } } if (adj_move.empty()) { simple_monster_message(mons, " flops around on dry land!"); return false; } vector<coord_def> moves = adj_water; if (adj_water.empty() || coinflip()) moves = adj_move; coord_def newpos = mons->pos(); int count = 0; for (unsigned int i = 0; i < moves.size(); ++i) if (one_chance_in(++count)) newpos = moves[i]; const monster* mon2 = monster_at(newpos); if (!mons->has_ench(ENCH_INSANE) && (newpos == you.pos() && mons->wont_attack() || (mon2 && mons->wont_attack() == mon2->wont_attack()))) { simple_monster_message(mons, " flops around on dry land!"); return false; } return _do_move_monster(mons, newpos - mons->pos()); } // Let's not even bother with this if mmov is zero. if (mmov.origin()) return false; for (int count_x = 0; count_x < 3; count_x++) for (int count_y = 0; count_y < 3; count_y++) { const int targ_x = mons->pos().x + count_x - 1; const int targ_y = mons->pos().y + count_y - 1; // Bounds check: don't consider moving out of grid! if (!in_bounds(targ_x, targ_y)) { good_move[count_x][count_y] = false; continue; } dungeon_feature_type target_grid = grd[targ_x][targ_y]; if (target_grid == DNGN_DEEP_WATER) deep_water_available = true; good_move[count_x][count_y] = mon_can_move_to_pos(mons, coord_def(count_x-1, count_y-1)); } // Now we know where we _can_ move. const coord_def newpos = mons->pos() + mmov; // Water creatures have a preference for water they can hide in -- bwr // [ds] Weakened the powerful attraction to deep water if the monster // is in good health. if (habitat == HT_WATER && deep_water_available && grd(mons->pos()) != DNGN_DEEP_WATER && grd(newpos) != DNGN_DEEP_WATER && newpos != you.pos() && (one_chance_in(3) || mons->hit_points <= (mons->max_hit_points * 3) / 4)) { int count = 0; for (int cx = 0; cx < 3; cx++) for (int cy = 0; cy < 3; cy++) { if (good_move[cx][cy] && grd[mons->pos().x + cx - 1][mons->pos().y + cy - 1] == DNGN_DEEP_WATER) { if (one_chance_in(++count)) { mmov.x = cx - 1; mmov.y = cy - 1; } } } } // Now, if a monster can't move in its intended direction, try // either side. If they're both good, move in whichever dir // gets it closer (farther for fleeing monsters) to its target. // If neither does, do nothing. if (good_move[mmov.x + 1][mmov.y + 1] == false) _find_good_alternate_move(mons, good_move); // ------------------------------------------------------------------ // If we haven't found a good move by this point, we're not going to. // ------------------------------------------------------------------ if (mons->type == MONS_SPATIAL_MAELSTROM) { const dungeon_feature_type feat = grd(mons->pos() + mmov); if (!feat_is_permarock(feat) && feat_is_solid(feat)) { const coord_def target(mons->pos() + mmov); create_monster( mgen_data(MONS_SPATIAL_VORTEX, SAME_ATTITUDE(mons), mons, 2, MON_SUMM_ANIMATE, target, MHITNOT, 0, GOD_LUGONU)); nuke_wall(target); } } const bool burrows = mons_class_flag(mons->type, M_BURROWS); const bool flattens_trees = mons_flattens_trees(mons); const bool digs = _mons_can_cast_dig(mons, false) || _mons_can_zap_dig(mons); // Take care of beetle burrowing. if (burrows || flattens_trees || digs) { const dungeon_feature_type feat = grd(mons->pos() + mmov); if ((feat == DNGN_ROCK_WALL || feat == DNGN_CLEAR_ROCK_WALL) && !burrows && digs) { bolt beem; if (_mons_can_cast_dig(mons, true)) { setup_mons_cast(mons, beem, SPELL_DIG); beem.target = mons->pos() + mmov; mons_cast(mons, beem, SPELL_DIG, true, true); } else if (_mons_can_zap_dig(mons)) { ASSERT(mons->inv[MSLOT_WAND] != NON_ITEM); item_def &wand = mitm[mons->inv[MSLOT_WAND]]; beem.target = mons->pos() + mmov; _setup_wand_beam(beem, mons); _mons_fire_wand(mons, wand, beem, you.can_see(mons), false); } else simple_monster_message(mons, " falters for a moment."); mons->lose_energy(EUT_SPELL); return true; } else if ((((feat == DNGN_ROCK_WALL || feat == DNGN_CLEAR_ROCK_WALL) && burrows) || (flattens_trees && feat_is_tree(feat))) && good_move[mmov.x + 1][mmov.y + 1] == true) { const coord_def target(mons->pos() + mmov); nuke_wall(target); if (flattens_trees) { // Flattening trees has a movement cost to the monster // - 100% over and above its normal move cost. _swim_or_move_energy(mons); if (you.see_cell(target)) { const bool actor_visible = you.can_see(mons); mprf("%s knocks down a tree!", actor_visible? mons->name(DESC_THE).c_str() : "Something"); noisy(25, target); } else noisy(25, target, "You hear a crashing sound."); } else if (player_can_hear(mons->pos() + mmov)) { // Message depends on whether caused by boring beetle or // acid (Dissolution). mpr((mons->type == MONS_BORING_BEETLE) ? "You hear a grinding noise." : "You hear a sizzling sound.", MSGCH_SOUND); } } } bool ret = false; if (good_move[mmov.x + 1][mmov.y + 1] && !mmov.origin()) { // Check for attacking player. if (mons->pos() + mmov == you.pos()) { ret = fight_melee(mons, &you); mmov.reset(); } // If we're following the player through stairs, the only valid // movement is towards the player. -- bwr if (testbits(mons->flags, MF_TAKING_STAIRS)) { const delay_type delay = current_delay_action(); if (delay != DELAY_ASCENDING_STAIRS && delay != DELAY_DESCENDING_STAIRS) { mons->flags &= ~MF_TAKING_STAIRS; dprf("BUG: %s was marked as follower when not following!", mons->name(DESC_PLAIN).c_str()); } else { ret = true; mmov.reset(); dprf("%s is skipping movement in order to follow.", mons->name(DESC_THE).c_str()); } } // Check for attacking another monster. if (monster* targ = monster_at(mons->pos() + mmov)) { if (mons_aligned(mons, targ) && !mons->has_ench(ENCH_INSANE) && (!crawl_state.game_is_zotdef() || !_may_cutdown(mons, targ))) { // Zotdef: monsters will cut down firewood ret = _monster_swaps_places(mons, mmov); } else { fight_melee(mons, targ); ret = true; } // If the monster swapped places, the work's already done. mmov.reset(); } // The monster could die after a melee attack due to a mummy // death curse or something. if (!mons->alive()) return true; if (mons_genus(mons->type) == MONS_EFREET || mons->type == MONS_FIRE_ELEMENTAL) { place_cloud(CLOUD_FIRE, mons->pos(), 2 + random2(4), mons); } if (mons->type == MONS_ROTTING_DEVIL || mons->type == MONS_CURSE_TOE) place_cloud(CLOUD_MIASMA, mons->pos(), 2 + random2(3), mons); } else { monster* targ = monster_at(mons->pos() + mmov); if (!mmov.origin() && targ && _may_cutdown(mons, targ)) { fight_melee(mons, targ); ret = true; } mmov.reset(); // zotdef: sometimes seem to get gridlock. Reset travel path // if we can't move, occasionally if (crawl_state.game_is_zotdef() && one_chance_in(20)) { mons->travel_path.clear(); mons->travel_target = MTRAV_NONE; } // Fleeing monsters that can't move will panic and possibly // turn to face their attacker. make_mons_stop_fleeing(mons); } if (mmov.x || mmov.y || (mons->confused() && one_chance_in(6))) return _do_move_monster(mons, mmov); // Battlespheres need to preserve their tracking targets after each move if (mons_is_wandering(mons) && mons->type != MONS_BATTLESPHERE) { // trigger a re-evaluation of our wander target on our next move -cao mons->target = mons->pos(); if (!mons->is_patrolling()) { mons->travel_target = MTRAV_NONE; mons->travel_path.clear(); } mons->firing_pos.reset(); } return ret; } static void _mons_in_cloud(monster* mons) { // Submerging in water or lava saves from clouds. if (mons->submerged() && env.grid(mons->pos()) != DNGN_FLOOR) return; actor_apply_cloud(mons); } static void _heated_area(monster* mons) { if (!heated(mons->pos())) return; if (mons->is_fiery()) return; // HACK: Currently this prevents even auras not caused by lava orcs... if (you_worship(GOD_BEOGH) && mons->friendly() && mons->god == GOD_BEOGH) return; const int base_damage = random2(11); // Timescale, like with clouds: const int speed = mons->speed > 0 ? mons->speed : 10; const int timescaled = max(0, base_damage) * 10 / speed; // rF protects: const int resist = mons->res_fire(); const int adjusted_damage = resist_adjust_damage(mons, BEAM_FIRE, resist, timescaled, true); // So does AC: const int final_damage = max(0, adjusted_damage - random2(mons->armour_class())); if (final_damage > 0) { if (mons->observable()) mprf("%s is %s by your radiant heat.", mons->name(DESC_THE).c_str(), (final_damage) > 10 ? "blasted" : "burned"); behaviour_event(mons, ME_DISTURB, 0, mons->pos()); #ifdef DEBUG_DIAGNOSTICS mprf(MSGCH_DIAGNOSTICS, "%s %s %d damage from heat.", mons->name(DESC_THE).c_str(), mons->conj_verb("take").c_str(), final_damage); #endif mons->hurt(&you, final_damage, BEAM_MISSILE); if (mons->alive() && mons->observable()) print_wounds(mons); } } static spell_type _map_wand_to_mspell(wand_type kind) { switch (kind) { case WAND_FLAME: return SPELL_THROW_FLAME; case WAND_FROST: return SPELL_THROW_FROST; case WAND_SLOWING: return SPELL_SLOW; case WAND_HASTING: return SPELL_HASTE; case WAND_MAGIC_DARTS: return SPELL_MAGIC_DART; case WAND_HEAL_WOUNDS: return SPELL_MINOR_HEALING; case WAND_PARALYSIS: return SPELL_PARALYSE; case WAND_FIRE: return SPELL_BOLT_OF_FIRE; case WAND_COLD: return SPELL_BOLT_OF_COLD; case WAND_CONFUSION: return SPELL_CONFUSE; case WAND_INVISIBILITY: return SPELL_INVISIBILITY; case WAND_TELEPORTATION: return SPELL_TELEPORT_OTHER; case WAND_LIGHTNING: return SPELL_LIGHTNING_BOLT; case WAND_DRAINING: return SPELL_BOLT_OF_DRAINING; case WAND_DISINTEGRATION: return SPELL_DISINTEGRATE; case WAND_POLYMORPH: return SPELL_POLYMORPH; case WAND_DIGGING: return SPELL_DIG; default: return SPELL_NO_SPELL; } } // Keep kraken tentacles from wandering too far away from the boss monster. static void _shedu_movement_clamp(monster *shedu) { if (!mons_is_shedu(shedu)) return; monster *my_pair = get_shedu_pair(shedu); if (!my_pair) return; if (grid_distance(shedu->pos(), my_pair->pos()) >= 10) mmov = (my_pair->pos() - shedu->pos()).sgn(); }
xFleury/crawl-0.13.0-fairplay
source/mon-act.cc
C++
gpl-2.0
126,596
/* * Copyright (c) 2012-2013 Open Source Community - <http://www.peerfact.org> * Copyright (c) 2011-2012 University of Paderborn - UPB * Copyright (c) 2005-2011 KOM - Multimedia Communications Lab * * This file is part of PeerfactSim.KOM. * * PeerfactSim.KOM 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 * any later version. * * PeerfactSim.KOM 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 PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>. * */ package org.peerfact.impl.overlay.unstructured.heterogeneous.api; import org.peerfact.api.overlay.dht.DHTEntry; import org.peerfact.api.overlay.dht.DHTKey; import org.peerfact.api.overlay.dht.DHTValue; /** * Abstract resource that is published and queried in the network. Can be * anything that can be matched to a given query info. * * @author Leo Nobach <peerfact@kom.tu-darmstadt.de> * * @version 05/06/2011 */ public interface IResource extends DHTEntry<DHTKey<?>>, DHTValue { /** * Returns the size of this resource. * * @return */ int getSize(); }
flyroom/PeerfactSimKOM_Clone
src/org/peerfact/impl/overlay/unstructured/heterogeneous/api/IResource.java
Java
gpl-2.0
1,474
<?php /** * @package Extly.Library * @subpackage lib_extly - Extly Framework * * @author Prieco S.A. <support@extly.com> * @copyright Copyright (C) 2007 - 2014 Prieco, S.A. All rights reserved. * @license http://http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL * @link http://www.extly.com http://support.extly.com */ // No direct access defined('_JEXEC') or die('Restricted access'); // Load F0F if (!defined('F0F_INCLUDED')) { include_once JPATH_LIBRARIES . '/f0f/include.php'; } if (!defined('F0F_INCLUDED')) { JError::raiseError('500', 'Your Extly Framework installation is broken; please re-install. Alternatively, extract the installation archive and copy the f0f directory inside your site\'s libraries directory.'); } if (!defined('EXTLY_VERSION')) { /** * @name EXTLY_VERSION */ define('EXTLY_VERSION', '3.3.6'); // CSS Styling define('EXTLY_BASE', '3_2_0'); defined('DS') || define('DS', DIRECTORY_SEPARATOR); defined('EPATH_LIBRARY') || define('EPATH_LIBRARY', JPATH_LIBRARIES . '/extly'); defined('EJSON_START') || define('EJSON_START', '@EXTLYSTART@'); defined('EJSON_END') || define('EJSON_END', '@EXTLYEND@'); defined('EXTLY_J3') || define('EXTLY_J3', (version_compare(JVERSION, '3.0', 'gt'))); defined('EXTLY_J25') || define('EXTLY_J25', !EXTLY_J3); } JLoader::register('Extly', EPATH_LIBRARY . '/core/extly.php'); JLoader::register('ETable', EPATH_LIBRARY . '/core/etable.php'); JLoader::register('ELog', EPATH_LIBRARY . '/core/elog.php'); JLoader::register('EParameter', EPATH_LIBRARY . '/core/eparameter.php'); JLoader::register('EForm', EPATH_LIBRARY . '/form/eform.php'); JLoader::register('EHtmlGrid', EPATH_LIBRARY . '/html/egrid.php'); JLoader::register('EHtml', EPATH_LIBRARY . '/html/ehtml.php'); JLoader::register('EHtmlFormbehavior', EPATH_LIBRARY . '/html/formbehavior.php'); JLoader::register('EHtmlSelect', EPATH_LIBRARY . '/html/html/eselect.php'); JLoader::register('EExtensionHelper', EPATH_LIBRARY . '/helpers/extension.php'); JLoader::register('ExtlyModelExtensions', EPATH_LIBRARY . '/models/extensions.php'); JLoader::register('ExtlyTableExtension', EPATH_LIBRARY . '/tables/extension.php'); JLoader::register('EDbProxyHelper', EPATH_LIBRARY . '/helpers/dbproxy.php'); /** * This is the base class for the Extlyframework. * * @package Extly.Library * @subpackage lib_extly * @since 1.0 */ class Extlyframework { }
shukdelmadrij/shukdelmadrij
libraries/extly/extlyframework.php
PHP
gpl-2.0
2,432
//#include "..\kgb_arch_mfc\kgb_arch_mfcdlg.cpp" // kgb_arch_decompressDlg.cpp : implementation file // #include "stdafx.h" #include "kgb_arch_decompress.h" #include "kgb_arch_decompressDlg.h" #include "dDecompress.h" //#include "../compress/compress.cpp" #include <vector> #include <string> #include "io.h" #include "dlgPasswd.h" #include <psapi.h> #include "../zip/zipArchive.h" using namespace std; int MEM = 3; //GLOBALNE ZMIENNE DLA STATYSTYK!!! __int64 _size; __int64 _done; __int64 _size_all; __int64 _done_all; __int64 _compressed; string _filename; __int64 sTime; #define COMPRESS_PREPARING "\1" #define COMPRESS_GETTING_FILE_SIZES "\2" #define COMPRESS_SORTING "\3" #define COMPRESS_ADDING_SFX_MOD "\4" #define COMPRESS_ENCODING "\5" #define DECOMPRESS_PREPARING "\1" #define DECOMPRESS_CREATING_DIRS "\2" #define DECOMPRESS_SKIPPING "\3" //GLOBALNE ZMIENNE DLA W¥TKÓW char *archive_name; vector<string> filename; vector<string> files4decompress; char passwd[32];//256bit bool sfx_arch; void resetSettings(){ free(archive_name); filename.clear(); files4decompress.clear(); MEM = 3; _size = 0; _done = 0; _size_all = 0; _done_all = 0; sTime = 0; passwd[0] = '\0'; sfx_arch = 0; } #ifdef _DEBUG #define new DEBUG_NEW #endif dDecompress _dDecompress; void zipGetFiles(char *arch, vector<string>&filenames, vector<__int64>&filesizes){ CZipArchive zip; zip.Open(arch, CZipArchive::zipOpenReadOnly); for(int i=0;i<zip.GetCount(true);i++){ CZipFileHeader fhInfo; zip.GetFileInfo(fhInfo, i); filenames.push_back(fhInfo.GetFileName().GetBuffer()); filesizes.push_back(fhInfo.GetEffComprSize() != 0 ? __int64((float)fhInfo.GetEffComprSize()*100.0f/fhInfo.GetCompressionRatio()) : 0); } zip.Close(); } DWORD WINAPI zipDecompress(LPVOID lpParam){ _filename = DECOMPRESS_PREPARING; sTime = _time64(NULL); CZipArchive zip; vector<string>filenames; vector<__int64>filesizes; FILE *archive = fopen(archive_name, "rb"); if(!archive){ MessageBox(0, loadString(IDS_ARCHIVE_DOESNT_EXIST), "KGB Archiver", 0); return false; } fseek(archive, 0L, SEEK_END); _compressed = ftell(archive); fclose(archive); zipGetFiles(archive_name, filenames, filesizes); //char buff[123]; for(int i=0;i<filesizes.size();i++){ _size_all += filesizes[i]; /*if(filesizes[i] <= 0){ sprintf(buff, "%s %lld", filenames[i].c_str(), filesizes[i]); MessageBox(0, buff, "", 0);}*/ } /*sprintf(buff, "%lld", _size_all); MessageBox(0, buff, "", 0);*/ //MessageBox(0, "", "", 0); zip.Open(archive_name, CZipArchive::zipOpenReadOnly); for(int i=0;i<filenames.size();i++){ if(files4decompress.size() != 0){ for(int j=0;j<files4decompress.size();j++){ if(filenames[i] == files4decompress[j]){ _filename = filenames[i]; try{ zip.ExtractFile(i, ""); }catch(...){ CZipFileHeader fhInfo; zip.GetFileInfo(fhInfo, i); if(fhInfo.IsEncrypted()){ dlgPasswd dlgPass; if(dlgPass.DoModal() != IDOK){ _dDecompress.EndDialog(IDCANCEL); return false; } zip.SetPassword(dlgPass._passwd); j--; continue; } } break; } } }else{ _filename = filenames[i]; try{ zip.ExtractFile(i, ""); }catch(...){ CZipFileHeader fhInfo; zip.GetFileInfo(fhInfo, i); if(fhInfo.IsEncrypted()){ dlgPasswd dlgPass; if(dlgPass.DoModal() != IDOK){ _dDecompress.EndDialog(IDCANCEL); return false; } zip.SetPassword(dlgPass._passwd); i--; continue; } } } _done_all += filesizes[i]; } zip.Close(); return 0; } // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // Ckgb_arch_decompressDlg dialog Ckgb_arch_decompressDlg::Ckgb_arch_decompressDlg(CWnd* pParent /*=NULL*/) : CDialog(Ckgb_arch_decompressDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void Ckgb_arch_decompressDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //DDX_Control(pDX, IDC_EARCHNAME, eArchName); DDX_Control(pDX, IDC_EARCHNAME2, eDestination); DDX_Control(pDX, IDC_LIST1, lFiles); DDX_Control(pDX, IDC_CHECK1, cSelect); } BEGIN_MESSAGE_MAP(Ckgb_arch_decompressDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_BUTTON2, OnBnClickedButton2) // ON_BN_CLICKED(IDC_BBROWSE, OnBnClickedBbrowse) ON_BN_CLICKED(IDC_BUTTON1, OnBnClickedButton1) ON_BN_CLICKED(IDC_BBROWSE2, OnBnClickedBbrowse2) ON_BN_CLICKED(IDC_CHECK1, OnBnClickedCheck1) // ON_EN_CHANGE(IDC_EARCHNAME, OnEnChangeEarchname) END_MESSAGE_MAP() // Ckgb_arch_decompressDlg message handlers BOOL Ckgb_arch_decompressDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon //SetIcon(m_hIcon, TRUE); // Set small icon // TODO: Add extra initialization here lFiles.InsertColumn(0, loadString(IDS_FILE), LVCFMT_LEFT, 300); lFiles.InsertColumn(1, loadString(IDS_SIZE), LVCFMT_RIGHT, 100); char curDir[MAX_PATH]; GetCurrentDirectory(MAX_PATH, curDir); eDestination.SetWindowText(curDir); vector<string>files; vector<__int64>fsize; char arch[MAX_PATH]; HANDLE hProc = GetCurrentProcess(); HMODULE hMod; DWORD cbNeeded; EnumProcessModules(hProc, &hMod, sizeof(hMod), &cbNeeded); GetModuleFileNameEx(hProc, hMod, arch, MAX_PATH); //pierwszy modu³ jest aplikacj¹ //MessageBox(""); //getFilesFromArchive(arch, files, fsize); zipGetFiles(arch, files, fsize); //MessageBox(""); for(unsigned long i=0;i<files.size();i++){ char buffer[32]; /*if(filesizes[i] < 1024) sprintf(buffer, "%dB", filesizes[i]); else if(filesizes[i] < 1024*1024) sprintf(buffer, "%dKB", filesizes[i]/1024); else sprintf(buffer, "%dMB", filesizes[i]/1024/1024); */ sprintf(buffer, "%.1fKB", (double)fsize[i]/1024.0); lFiles.InsertItem(0, i, 0, 0, 0, 0, 0); lFiles.SetItemText(i, 0, files[i].c_str()); lFiles.SetItemText(i, 1, buffer); } return TRUE; // return TRUE unless you set the focus to a control } void Ckgb_arch_decompressDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void Ckgb_arch_decompressDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR Ckgb_arch_decompressDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void Ckgb_arch_decompressDlg::OnBnClickedButton2() { EndDialog(IDCANCEL); } DWORD WINAPI updateForm(LPVOID lpParam){ char buffer[1024]; unsigned __int64 time_sTime; unsigned __int64 temp; while(1){ try{ if(_size_all != 0 && /*_size != 0 && _done != 0 && _done_all != 0 && */_dDecompress.m_hWnd != NULL){ sprintf(buffer, "%s %.1f%%", loadString(IDS_DECOMPRESS_PROGRESS), (float)((_done_all+_done)*100)/(float)(_size_all)); _dDecompress.SetWindowText(buffer); _dDecompress.pTotal.SetRange32(0, 100); _dDecompress.pTotal.SetPos(((_done_all+_done)*100)/(_size_all)); _dDecompress.pCurrent.SetRange32(0, 100); _dDecompress.pCurrent.SetPos((_done*100)/(_size+1)); if(_filename.c_str()[0] > 32) _dDecompress.sFilename.SetWindowText(_filename.c_str()); else _dDecompress.sFilename.SetWindowText(loadString(IDS_DECOMPRESS_STATUS+_filename.c_str()[0]-1)); sprintf(buffer, "%.1fKB", (float)_size_all/1024.0); _dDecompress.sFullSize.SetWindowText(buffer); sprintf(buffer, "%.1fKB", (float)_compressed/1024.0); _dDecompress.sCompressedSize.SetWindowText(buffer); sprintf(buffer, "%.1f%%", ((float)_compressed*100.0)/(float)(_size_all)); _dDecompress.sRatio.SetWindowText(buffer); time_sTime = time(NULL)-sTime; if((temp = time_sTime/3600) < 10) sprintf(buffer, "0"); sprintf(buffer, "%s%ld:", buffer, temp); if((temp = (time_sTime%3600)/60) < 10) sprintf(buffer, "%s0", buffer); sprintf(buffer, "%s%ld:", buffer, temp); if((temp = time_sTime%60) < 10) sprintf(buffer, "%s0", buffer); sprintf(buffer, "%s%ld", buffer, temp); _dDecompress.sTime.SetWindowText(buffer); buffer[0] = '\0'; time_sTime = (unsigned __int64)((double)time_sTime/((double)(_done+_done_all+1)/(double)(_size_all))) - time_sTime; if((temp = time_sTime/3600) < 10) sprintf(buffer, "0"); sprintf(buffer, "%s%ld:", buffer, temp); if((temp = (time_sTime%3600)/60) < 10) sprintf(buffer, "%s0", buffer); sprintf(buffer, "%s%ld:", buffer, temp); if((temp = time_sTime%60) < 10) sprintf(buffer, "%s0", buffer); sprintf(buffer, "%s%ld", buffer, temp); _dDecompress.sRemaining.SetWindowText(buffer); //_dDecompress.UpdateWindow(); //_shutdown = _dDecompress.cShutdown.GetCheck(); if(_done_all == _size_all){ _dDecompress.EndDialog(IDOK); //return 0; } } }catch(...){} Sleep(500); } free(buffer); return 0; } void Ckgb_arch_decompressDlg::OnBnClickedButton1() { if(eDestination.GetWindowTextLength() == 0){ MessageBox(loadString(IDS_CHOOSE_EXTRACT_DIR), "KGB Archiver"); return; } resetSettings(); archive_name = (char *)malloc(sizeof(char)*MAX_PATH); //eArchName.GetWindowText(archive_name, MAX_PATH); HANDLE hProc = GetCurrentProcess(); HMODULE hMod; DWORD cbNeeded; EnumProcessModules(hProc, &hMod, sizeof(hMod), &cbNeeded); GetModuleFileNameEx(hProc, hMod, archive_name, MAX_PATH); //pierwszy modu³ jest aplikacj¹ if(_access(archive_name, 4) != 0){ MessageBox(loadString(IDS_ARCHIVE_NOT_FOUND), "KGB Archiver"); return; } char buffer[MAX_PATH]; eDestination.GetWindowText(buffer, MAX_PATH); CreateDirectory(buffer, NULL); if(!SetCurrentDirectory(buffer)){ MessageBox(loadString(IDS_CANT_CREATE_EXTRACT_DIR), "KGB Archiver"); return; } if(cSelect.GetCheck() == true){ if(lFiles.GetSelectedCount() == 0){ MessageBox(loadString(IDS_CHOOSE_FILES2DECOMPRESS), "KGB Archiver"); return; } POSITION i = lFiles.GetFirstSelectedItemPosition(); while(i != NULL){ //lFiles.DeleteItem(lFiles.GetNextSelectedItem(i)); //i = lFiles.GetFirstSelectedItemPosition(); char buffer[MAX_PATH]; lFiles.GetItemText(lFiles.GetNextSelectedItem(i), 0, buffer, MAX_PATH); files4decompress.push_back((string)buffer); } } ShowWindow(SW_HIDE); HANDLE hDecompress; DWORD hDecompressId; hDecompress = CreateThread(NULL, 0, zipDecompress, 0, 0, &hDecompressId); SetThreadPriority(hDecompress, THREAD_PRIORITY_LOWEST); HANDLE hUpdate; DWORD hUpdateId; hUpdate = CreateThread(NULL, 0, updateForm, 0, 0, &hUpdateId); if(_dDecompress.DoModal() == IDCANCEL){ TerminateThread(hDecompress, 0); MessageBox(loadString(IDS_EXTRACT_CANCELED), "KGB Archiver"); }else{ char buff[1024]; sprintf(buff, loadString(IDS_EXTRACT_SUCCED), (float)_size_all/1024.0, (float)_compressed/1024.0, ((float)_compressed*100.0)/(float)_size_all); MessageBox(buff, "KGB Archiver"); } TerminateThread(hUpdate, 0); EndDialog(IDOK); } void Ckgb_arch_decompressDlg::OnBnClickedBbrowse2() { BROWSEINFO bInfo; bInfo.hwndOwner = m_hWnd; bInfo.lpfn = NULL; bInfo.lParam = NULL; bInfo.lpszTitle = loadString(IDS_CHOOSE_DIR2DECOMPRESS); bInfo.pidlRoot = NULL; bInfo.ulFlags = BIF_USENEWUI | BIF_VALIDATE; bInfo.pszDisplayName = NULL;//foldername; LPITEMIDLIST pidl; if((pidl = SHBrowseForFolder(&bInfo)) != NULL){ char buff[MAX_PATH]; SHGetPathFromIDList(pidl, buff); //GetCurrentDirectory(MAX_PATH, foldername); //eDestination.SetWindowText(foldername); eDestination.SetWindowText(buff); } } void Ckgb_arch_decompressDlg::OnBnClickedCheck1() { lFiles.EnableWindow(cSelect.GetCheck()); } /*void Ckgb_arch_decompressDlg::OnEnChangeEarchname() { CString _arch; string arch; eArchName.GetWindowText(_arch); arch = _arch; vector<string> files; vector<unsigned long> filesizes; lFiles.DeleteAllItems(); if(fopen(arch.c_str(), "r") == 0) return; _fcloseall(); //dekodowanie archiwum if(arch.c_str()[arch.length()-1] == 'e' || arch.c_str()[arch.length()-1] == 'E'){ dlgPasswd dlgPass; if(dlgPass.DoModal() != IDOK){ eArchName.SetWindowText(""); return; } strcpy(passwd, dlgPass._passwd); for(int i=strlen(passwd);i<32;i++) passwd[i] = '\0'; char arch2[MAX_PATH]; //strcpy(arch2, arch.c_str()); GetTempPath(MAX_PATH, arch2); strcat(arch2, "temp.kgb"); //arch2[strlen(arch2)-1] = 'b'; aes_ctx ctx[1]; ctx->n_rnd = 0; // ensure all flags are initially set to zero ctx->n_blk = 0; aes_dec_key((const unsigned char*)passwd, 32, ctx); FILE *fin = fopen(arch.c_str(), "rb"); if(fin == 0) return; FILE *fout = fopen(arch2, "wb"); if(fout == 0) return; decfile(fin, fout, ctx, arch.c_str(), arch2); fclose(fin); fclose(fout); if(!checkArchiveFormat(arch2)){ _fcloseall(); DeleteFile(arch2); eArchName.SetWindowText(""); MessageBox("Nieprawid³owe has³o!"); return; } eArchName.SetWindowText(arch2); return; } if(!getFilesFromArchive((char *)arch.c_str(), files, filesizes)){ MessageBox("Wybrany plik nie jest prawid³owym archiwum KGB!"); eArchName.SetWindowText(""); return; } for(unsigned long i=0;i<files.size();i++){ char buffer[32]; /*if(filesizes[i] < 1024) sprintf(buffer, "%dB", filesizes[i]); else if(filesizes[i] < 1024*1024) sprintf(buffer, "%dKB", filesizes[i]/1024); else sprintf(buffer, "%dMB", filesizes[i]/1024/1024); * / sprintf(buffer, "%.1fKB", (double)filesizes[i]/1024.0); lFiles.InsertItem(0, i, 0, 0, 0, 0, 0); lFiles.SetItemText(i, 0, files[i].c_str()); lFiles.SetItemText(i, 1, buffer); } }*/
RandallFlagg/kgbarchiver
KGB Archiver 1/sfx/kgb_arch_sfx_zip/kgb_arch_decompressDlg.cpp
C++
gpl-2.0
15,501
#!/usr/bin/env python # -*- coding: utf-8 -*- class User(object): def __init__(self): self.first_name = None self.last_name = None self.username = None self.password = None def set_full_name(self, name): # Jaa välilyönnin mukaan pass
mtpajula/ijonmap
core/users/user.py
Python
gpl-2.0
308
/* putpwent.c */ #include "passwd.h" #ifdef L_putpwent int putpwent(pwd, f) struct passwd *pwd; FILE * f; { if (pwd == NULL || f == NULL) { errno = EINVAL; return -1; } if (fprintf(f, "%s:%s:%u:%u:%s:%s:%s\n", pwd->pw_name, pwd->pw_passwd, pwd->pw_uid, pwd->pw_gid, pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell) < 0) return -1; return 0; } #endif 
marioaugustorama/uzix-libc
LIBC/PUTPWENT.C
C++
gpl-2.0
402
# UPDATE THIS SECRET INFORMATION ! # # UNCOMMENT THIS FILE IN .gitignore BEFORE YOU COMMIT! # # SuperUser Default Password SUPER_USER_PASSWORD = 'CHANGEME' # Log into your Loggly account, visit: https://<Username>.loggly.com/tokens and copy the token here LOGGLY_TOKEN = 'CHANGEME' # Generate a very secure Django Secret to replace this one DJANGO_SECRET = 'CHANGEME' # OPTIONAL # # Replace the following with a copy of your environment variables if you wish to run the code locally # THe variables will only be available after you first deploy an app to Bluemix, whether the deployment succeeds or not. LOCALDEV_VCAP = { "cloudamqp": [ { "name": "CloudAMQP-sa", "label": "cloudamqp", "plan": "lemur", "credentials": { "uri": "amqp://CHANGEME:CHANGEME/CHANGEME", "http_api_uri": "https://CHANGEME:CHANGEME/api/" } } ], "user-provided": [ { "name": "PostgreSQL by Compose-lj", "label": "user-provided", "credentials": { "username": "CHANGEME", "password": "CHANGEME", "public_hostname": "localhost:5432" } } ] }
Chaffleson/blupy
settings_local.py
Python
gpl-2.0
1,195
/* * This file is part of the AshamaneCore Project. See AUTHORS file for Copyright information * Copyright (C) 2018+ MagicStormProject <https://github.com/MagicStormTeam> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "AreaTrigger.h" #include "AreaTriggerAI.h" #include "ScriptedCreature.h" #include "ScriptMgr.h" #include "SpellAuras.h" #include "Player.h" #include "SpellScript.h" #include "ScriptedGossip.h" #include "InstanceScript.h" #include "antorus_the_burning_throne.h" enum Spells { SPELL_TAESHALACH_S_REACH = 243431, //SPELL_TAESHALACH_S_REACH = 245990, //SPELL_FLAME_REND = 244033, SPELL_FLAME_REND = 245463,//???? //SPELL_FLAME_REND = 254654, //SPELL_FOE_BREAKER = 244291, SPELL_FOE_BREAKER = 245458,//??? //SPELL_FOE_BREAKER = 254655, SPELL_WAKE_OF_FLAME = 244693, //SPELL_WAKE_OF_FLAME = 244736, SPELL_BURNING_RAGE = 244713, SPELL_CORRUPT_AEGIS = 244894, SPELL_SEARING_TEMPEST = 245301, //SPELL_SEARING_TEMPEST = 246014, SPELL_SCORCHING_BLAZE = 245994, SPELL_EMPOWERED_FLAME_REND = 247079, //SPELL_EMPOWERED_FLAME_REND = 255058, SPELL_RAVENOUS_BLAZE = 254452, SPELL_EMPOWERED_FOE_BREAKER = 255059, //SPELL_EMPOWERED_FOE_BREAKER = 255060, SPELL_EMPOWERED_SEARING_TEMPEST = 255061, //SPELL_EMPOWERED_SEARING_TEMPEST = 255062, SPELL_SEARING_BINDING = 255528, SPELL_TAESHALACH_TECHNIQUE = 256208, // 244688 NPC_EMBER_OF_TAESHALACH = 122532, SPELL_BLAZING_ERUPTION = 244912, SPELL_MOLTEN_REMNANTS = 245905, //SPELL_SEARING_TEMPEST = 254653, SPELL_UNENDING_BLAZE = 254695, SPELL_TITANS_ASSEMBLE_MOVIE = 254311, SPELL_FLARE = 245983 }; enum Events { // Intro EVENT_INTRO = 1, EVNET_PHASE_2 = 2, EVNET_PHASE_3 = 3, EVENT_A1 = 4, EVENT_A2 = 5, EVENT_A3 = 6, EVENT_A4 = 7 }; enum Talk { TALK_AGGRAMAR_AGGRO = 1, TALK_AGGRAMAR_DEATH = 2, TALK_AGGRAMAR_LOS = 3, TALK_AGGRAMAR_HP80 = 4, TALK_AGGRAMAR_WAKE_OF_FLAME = 5 }; enum Phases { PHASE_NORMAL, PHASE_INTRO, PHASE_1, PHASE_2, PHASE_3, PHASE_4, }; struct SpawnData { uint32 event, npcId; float X; float Y; float Z; float orientation; }; SpawnData const spawnData[] = { { EVNET_PHASE_2, NPC_EMBER_OF_TAESHALACH, -12679.456f, -2254.8264f, 2514.2646f }, { EVNET_PHASE_2, NPC_EMBER_OF_TAESHALACH, -12588.12f, -2254.8215f, 2514.6276f, 3.101369f }, { EVNET_PHASE_3, NPC_EMBER_OF_TAESHALACH, -12679.456f, -2254.8264f, 2514.2646f }, { EVNET_PHASE_3, NPC_EMBER_OF_TAESHALACH, -12588.12f, -2254.8215f, 2514.6276f, 3.101369f }, }; struct boss_aggramar : public BossAI { boss_aggramar(Creature* creature) : BossAI(creature, DATA_AGGRAMAR) { Initialize(); } void Initialize() { PhaseStatus = Phases::PHASE_INTRO; } void LoadNPC(uint32 event, const SpawnData* data) { while (data->event) { if (data->event == event) me->SummonCreature(data->npcId, Position(data->X, data->Y, data->Z, data->orientation), TEMPSUMMON_MANUAL_DESPAWN, WEEK); ++data; } } void EnterCombat(Unit* who) override { if (who->ToPlayer()) if (roll_chance_i(30)) Talk(TALK_AGGRAMAR_AGGRO); } void JustDied(Unit* killer) override { _JustDied(); instance->SetBossState(DATA_AGGRAMAR, DONE); if (killer->ToPlayer()) if (roll_chance_i(30)) Talk(TALK_AGGRAMAR_DEATH); instance->DoDelayedConversation(2000, 6127); } void DamageTaken(Unit* /*attacker*/, uint32& damage) override { if (me->HealthWillBeBelowPctDamaged(80, damage)) { PhaseStatus = PHASE_2; events.Reset(); me->GetMotionMaster()->MovePoint(1, Position(-12634.2f, -2255.2478f, 2514.2617f, 4.674f)); Talk(TALK_AGGRAMAR_HP80); DoCastSelf(SPELL_CORRUPT_AEGIS); LoadNPC(EVNET_PHASE_2, spawnData); killCount = 2; events.RescheduleEvent(EVNET_PHASE_2, 1s); } else if (me->HealthWillBeBelowPctDamaged(40, damage)) { PhaseStatus = PHASE_3; events.Reset(); me->GetMotionMaster()->MovePoint(1, Position(-12634.2f, -2255.2478f, 2514.2617f, 4.674f)); DoCastSelf(SPELL_CORRUPT_AEGIS); LoadNPC(EVNET_PHASE_3, spawnData); killCount = 2; events.RescheduleEvent(EVNET_PHASE_3, 1s); //SPELL_WAKE_OF_FLAME replace by 245983 flare Talk(7) } } void DoAction(int32 action) override { if (action == 1) { PhaseStatus = PHASE_INTRO; instance->SetBossState(DATA_AGGRAMAR, SPECIAL); events.Reset(); //events.ScheduleEvent(EVENT_INTRO_GLAIDALIS_1, 5000); } if (action == 2) { --killCount; if (killCount <= 0) { me->RemoveAurasDueToSpell(SPELL_CORRUPT_AEGIS); //events.ScheduleEvent(SPELL_FLAME_REND, 5s); //events.ScheduleEvent(SPELL_FOE_BREAKER, 5s); if(PhaseStatus<PHASE_2) events.ScheduleEvent(SPELL_WAKE_OF_FLAME, 6s); else events.ScheduleEvent(SPELL_FLARE, 6s); //events.ScheduleEvent(SPELL_BURNING_RAGE, 5s); //events.ScheduleEvent(SPELL_CORRUPT_AEGIS, 5s); //events.ScheduleEvent(SPELL_SEARING_TEMPEST, 5s); events.ScheduleEvent(SPELL_SCORCHING_BLAZE, 8s); events.ScheduleEvent(SPELL_TAESHALACH_TECHNIQUE, 60s); if (me->GetMap()->IsMythic()) { events.ScheduleEvent(SPELL_EMPOWERED_FLAME_REND, 5s); events.ScheduleEvent(SPELL_RAVENOUS_BLAZE, 5s); events.ScheduleEvent(SPELL_EMPOWERED_FOE_BREAKER, 5s); events.ScheduleEvent(SPELL_EMPOWERED_SEARING_TEMPEST, 5s); events.ScheduleEvent(SPELL_SEARING_BINDING, 5s); } } } } void ScheduleTasks() override { //Talk(0); DoCastSelf(SPELL_TAESHALACH_S_REACH); //events.ScheduleEvent(SPELL_FLAME_REND, 5s); //events.ScheduleEvent(SPELL_FOE_BREAKER, 5s); if (PhaseStatus<PHASE_2) events.ScheduleEvent(SPELL_WAKE_OF_FLAME, 6s); else events.ScheduleEvent(SPELL_FLARE, 6s); //events.ScheduleEvent(SPELL_BURNING_RAGE, 5s); //events.ScheduleEvent(SPELL_CORRUPT_AEGIS, 5s); //events.ScheduleEvent(SPELL_SEARING_TEMPEST, 5s); events.ScheduleEvent(SPELL_SCORCHING_BLAZE, 8s); events.ScheduleEvent(SPELL_TAESHALACH_TECHNIQUE, 60s); if (me->GetMap()->IsMythic()) { events.ScheduleEvent(SPELL_EMPOWERED_FLAME_REND, 5s); events.ScheduleEvent(SPELL_RAVENOUS_BLAZE, 5s); events.ScheduleEvent(SPELL_EMPOWERED_FOE_BREAKER, 5s); events.ScheduleEvent(SPELL_EMPOWERED_SEARING_TEMPEST, 5s); events.ScheduleEvent(SPELL_SEARING_BINDING, 5s); } } void ExecuteEvent(uint32 eventId) override { switch (eventId) { case SPELL_WAKE_OF_FLAME: { Talk(TALK_AGGRAMAR_WAKE_OF_FLAME); DoCast(SPELL_WAKE_OF_FLAME); events.Repeat(25s); break; } case SPELL_FLARE: { if (Unit* target1 = SelectTarget(SELECT_TARGET_RANDOM, 0.0, 0.0, true)) me->CastSpell(target1, SPELL_FLARE, false); if (Unit* target2 = SelectTarget(SELECT_TARGET_RANDOM, 0.0, 0.0, true)) me->CastSpell(target2, SPELL_FLARE, false); if (Unit* target3 = SelectTarget(SELECT_TARGET_RANDOM, 0.0, 0.0, true)) me->CastSpell(target3, SPELL_FLARE, false); events.Repeat(25s); break; } case SPELL_SEARING_TEMPEST: { DoCast(SPELL_SEARING_TEMPEST); //events.Repeat(20s); break; } case SPELL_SCORCHING_BLAZE: { if (Unit* target1 = SelectTarget(SELECT_TARGET_RANDOM, 0.0, 0.0, true)) me->CastSpell(target1, SPELL_SCORCHING_BLAZE, false); if (Unit* target2 = SelectTarget(SELECT_TARGET_RANDOM, 0.0, 0.0, true)) me->CastSpell(target2, SPELL_SCORCHING_BLAZE, false); events.Repeat(8s); break; } case SPELL_TAESHALACH_TECHNIQUE: { // alexkulya: text & textemote? //Talk(2); //Talk(3); DoCast(SPELL_TAESHALACH_TECHNIQUE); events.ScheduleEvent(EVENT_A1, 1s); events.Repeat(60s); break; } case EVENT_A1: { DoCast(SPELL_FOE_BREAKER); events.ScheduleEvent(EVENT_A2, 4s); break; } case EVENT_A2: { DoCast(SPELL_FLAME_REND); DoCast(SPELL_BURNING_RAGE); events.ScheduleEvent(EVENT_A3, 4s); break; } case EVENT_A3: { DoCast(SPELL_FOE_BREAKER); events.ScheduleEvent(EVENT_A4, 4s); break; } case EVENT_A4: { DoCast(SPELL_FLAME_REND); DoCast(SPELL_BURNING_RAGE); events.ScheduleEvent(SPELL_SEARING_TEMPEST, 5s); break; } case SPELL_EMPOWERED_FLAME_REND: { DoCast(SPELL_EMPOWERED_FLAME_REND); events.Repeat(5s); break; } case SPELL_RAVENOUS_BLAZE: { DoCast(SPELL_RAVENOUS_BLAZE); events.Repeat(5s); break; } case SPELL_EMPOWERED_FOE_BREAKER: { DoCast(SPELL_EMPOWERED_FOE_BREAKER); events.Repeat(5s); break; } case SPELL_EMPOWERED_SEARING_TEMPEST: { DoCast(SPELL_EMPOWERED_SEARING_TEMPEST); events.Repeat(5s); break; } case SPELL_SEARING_BINDING: { DoCast(SPELL_SEARING_BINDING); events.Repeat(5s); break; } default: break; } } void MoveInLineOfSight(Unit* who) override { if (who->IsPlayer() && me->IsWithinDist(who, 50.0f, false) && PhaseStatus == Phases::PHASE_INTRO) { PhaseStatus = Phases::PHASE_1; Talk(TALK_AGGRAMAR_LOS); me->RemoveUnitFlag(UnitFlags(UNIT_FLAG_IMMUNE_TO_PC)); } } void JustSummoned(Creature* summon) override { BossAI::JustSummoned(summon); switch (summon->GetEntry()) { case NPC_EMBER_OF_TAESHALACH: { summon->SetFaction(me->GetFaction()); summon->GetMotionMaster()->MovePoint(1, Position(-12634.2f, -2255.2478f, 2514.2617f, 4.674f)); break; } } } uint8 PhaseStatus; uint8 killCount; }; struct npc_ember_of_taeshalach_122532 : public ScriptedAI { npc_ember_of_taeshalach_122532(Creature* creature) : ScriptedAI(creature) { } void UpdateAI(uint32 diff) override { events.Update(diff); if (!UpdateVictim()) return; } void JustDied(Unit* /*killer*/) override { if (Creature* aggramar = me->FindNearestCreature(NPC_AGGRAMAR, 50.0f, true)) aggramar->AI()->DoAction(2); DoCastSelf(SPELL_MOLTEN_REMNANTS); } void MoveInLineOfSight(Unit* who) override { if (who->GetEntry() == NPC_AGGRAMAR && me->IsWithinDist(who, 3.0f, false)) { DoCastAOE(SPELL_BLAZING_ERUPTION); me->KillSelf(); } } }; struct npc_magni_bronzebeard_128169 : public ScriptedAI { npc_magni_bronzebeard_128169(Creature* creature) : ScriptedAI(creature) { } bool GossipSelect(Player* player, uint32 /*menuId*/, uint32 gossipListId) { CloseGossipMenuFor(player); player->CastSpell(player, SPELL_TITANS_ASSEMBLE_MOVIE, true); player->TeleportTo(4000, 1712, 2826.39f, -4567.94f, 291.95f, 0.02513274f); return false; } }; void AddSC_boss_aggramar() { RegisterCreatureAI(boss_aggramar); RegisterCreatureAI(npc_ember_of_taeshalach_122532); RegisterCreatureAI(npc_magni_bronzebeard_128169); }
AshamaneProject/AshamaneCore
src/server/scripts/BrokenIsles/Anthorus/boss_aggramar.cpp
C++
gpl-2.0
14,489
/* * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package neomantic.com.sun.beans; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.Map; import java.util.WeakHashMap; /** * A hashtable-based cache with weak keys and weak values. * An entry in the map will be automatically removed * when its key is no longer in the ordinary use. * A value will be automatically removed as well * when it is no longer in the ordinary use. * * @since 1.7 * * @author Sergey A. Malenkov */ public final class WeakCache<K, V> { private final Map<K, Reference<V>> map = new WeakHashMap<K, Reference<V>>(); /** * Returns a value to which the specified {@code key} is mapped, * or {@code null} if this map contains no mapping for the {@code key}. * * @param key the key whose associated value is returned * @return a value to which the specified {@code key} is mapped */ public V get(K key) { Reference<V> reference = this.map.get(key); if (reference == null) { return null; } V value = reference.get(); if (value == null) { this.map.remove(key); } return value; } /** * Associates the specified {@code value} with the specified {@code key}. * Removes the mapping for the specified {@code key} from this cache * if it is present and the specified {@code value} is {@code null}. * If the cache previously contained a mapping for the {@code key}, * the old value is replaced by the specified {@code value}. * * @param key the key with which the specified value is associated * @param value the value to be associated with the specified key */ public void put(K key, V value) { if (value != null) { this.map.put(key, new WeakReference<V>(value)); } else { this.map.remove(key); } } /** * Removes all of the mappings from this cache. */ public void clear() { this.map.clear(); } }
neomantic/Android-SISC-Scheme-Eval
src/neomantic/com/sun/beans/WeakCache.java
Java
gpl-2.0
3,231
/* * Copyright (C) 2005-2017 Team Kodi * http://kodi.tv * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with KODI; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "DialogNumeric.h" #include "addons/kodi-addon-dev-kit/include/kodi/gui/DialogNumeric.h" #include "XBDateTime.h" #include "addons/AddonDll.h" #include "dialogs/GUIDialogNumeric.h" #include "utils/log.h" extern "C" { namespace ADDON { void Interface_GUIDialogNumeric::Init(AddonGlobalInterface* addonInterface) { addonInterface->toKodi->kodi_gui->dialogNumeric = static_cast<AddonToKodiFuncTable_kodi_gui_dialogNumeric*>(malloc(sizeof(AddonToKodiFuncTable_kodi_gui_dialogNumeric))); addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_verify_new_password = show_and_verify_new_password; addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_verify_password = show_and_verify_password; addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_verify_input = show_and_verify_input; addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_get_time = show_and_get_time; addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_get_date = show_and_get_date; addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_get_ip_address = show_and_get_ip_address; addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_get_number = show_and_get_number; addonInterface->toKodi->kodi_gui->dialogNumeric->show_and_get_seconds = show_and_get_seconds; } void Interface_GUIDialogNumeric::DeInit(AddonGlobalInterface* addonInterface) { free(addonInterface->toKodi->kodi_gui->dialogNumeric); } bool Interface_GUIDialogNumeric::show_and_verify_new_password(void* kodiBase, char** password) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return false; } std::string str; bool bRet = CGUIDialogNumeric::ShowAndVerifyNewPassword(str); if (bRet) *password = strdup(str.c_str()); return bRet; } int Interface_GUIDialogNumeric::show_and_verify_password(void* kodiBase, const char* password, const char* heading, int retries) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return -1; } if (!password || !heading) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid handler data (password='%p', heading='%p') on addon '%s'", __FUNCTION__, password, heading, addon->ID().c_str()); return -1; } std::string pw(password); return CGUIDialogNumeric::ShowAndVerifyPassword(pw, heading, retries); } bool Interface_GUIDialogNumeric::show_and_verify_input(void* kodiBase, const char* verify_in, char** verify_out, const char* heading, bool verify_input) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return false; } if (!verify_in || !verify_out || !heading) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid handler data (verify_in='%p', verify_out='%p', heading='%p') on addon '%s'", __FUNCTION__, verify_in, verify_out, heading, addon->ID().c_str()); return false; } std::string str = verify_in; bool bRet = CGUIDialogNumeric::ShowAndVerifyInput(str, heading, verify_input); if (bRet) *verify_out = strdup(str.c_str()); return bRet; } bool Interface_GUIDialogNumeric::show_and_get_time(void* kodiBase, tm* time, const char* heading) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return false; } if (!time || !heading) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid handler data (time='%p', heading='%p') on addon '%s'", __FUNCTION__, time, heading, addon->ID().c_str()); return false; } SYSTEMTIME systemTime; CDateTime dateTime(*time); dateTime.GetAsSystemTime(systemTime); if (CGUIDialogNumeric::ShowAndGetTime(systemTime, heading)) { dateTime = systemTime; dateTime.GetAsTm(*time); return true; } return false; } bool Interface_GUIDialogNumeric::show_and_get_date(void* kodiBase, tm *date, const char *heading) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return false; } if (!date || !heading) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid handler data (date='%p', heading='%p') on addon '%s'", __FUNCTION__, date, heading, addon->ID().c_str()); return false; } SYSTEMTIME systemTime; CDateTime dateTime(*date); dateTime.GetAsSystemTime(systemTime); if (CGUIDialogNumeric::ShowAndGetDate(systemTime, heading)) { dateTime = systemTime; dateTime.GetAsTm(*date); return true; } return false; } bool Interface_GUIDialogNumeric::show_and_get_ip_address(void* kodiBase, const char* ip_address_in, char** ip_address_out, const char *heading) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return false; } if (!ip_address_in || !ip_address_out || !heading) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid handler data (ip_address_in='%p', ip_address_out='%p', heading='%p') on addon '%s'", __FUNCTION__, ip_address_in, ip_address_out, heading, addon->ID().c_str()); return false; } std::string strIP = ip_address_in; bool bRet = CGUIDialogNumeric::ShowAndGetIPAddress(strIP, heading); if (bRet) *ip_address_out = strdup(strIP.c_str()); return bRet; } bool Interface_GUIDialogNumeric::show_and_get_number(void* kodiBase, const char* number_in, char** number_out, const char *heading, unsigned int auto_close_ms) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return false; } if (!number_in || !number_out || !heading) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid handler data (number_in='%p', number_out='%p', heading='%p') on addon '%s'", __FUNCTION__, number_in, number_out, heading, addon->ID().c_str()); return false; } std::string str = number_in; bool bRet = CGUIDialogNumeric::ShowAndGetNumber(str, heading, auto_close_ms); if (bRet) *number_out = strdup(str.c_str()); return bRet; } bool Interface_GUIDialogNumeric::show_and_get_seconds(void* kodiBase, const char* time_in, char** time_out, const char *heading) { CAddonDll* addon = static_cast<CAddonDll*>(kodiBase); if (!addon) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid data", __FUNCTION__); return false; } if (!time_in || !time_out || !heading) { CLog::Log(LOGERROR, "Interface_GUIDialogNumeric::%s - invalid handler data (time_in='%p', time_out='%p', heading='%p') on addon '%s'", __FUNCTION__, time_in, time_out, heading, addon->ID().c_str()); return false; } std::string str = time_in; bool bRet = CGUIDialogNumeric::ShowAndGetSeconds(str, heading); if (bRet) *time_out = strdup(str.c_str()); return bRet; } } /* namespace ADDON */ } /* extern "C" */
ObvB/xbmc
xbmc/addons/interfaces/GUI/DialogNumeric.cpp
C++
gpl-2.0
8,182
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ use Magento\Framework\Component\ComponentRegistrar; $registrar = new ComponentRegistrar(); if ($registrar->getPath(ComponentRegistrar::MODULE, 'Magento_TestModuleGraphQlQueryExtension') === null) { ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magento_TestModuleGraphQlQueryExtension', __DIR__); }
kunj1988/Magento2
dev/tests/api-functional/_files/Magento/TestModuleGraphQlQueryExtension/registration.php
PHP
gpl-2.0
420
/* * DAWN OF LIGHT - The first free open source DAoC server emulator * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ namespace Niflib { #if OpenTK using OpenTK; #elif SharpDX using SharpDX; #elif MonoGame using Microsoft.Xna.Framework; #endif using System; using System.IO; /// <summary> /// Class SkinData. /// </summary> public class SkinData { /// <summary> /// The transform /// </summary> public SkinTransform Transform; /// <summary> /// The bounding sphere offset /// </summary> public Vector3 BoundingSphereOffset; /// <summary> /// The bounding sphere radius /// </summary> public float BoundingSphereRadius; /// <summary> /// The unkown13 shorts /// </summary> public ushort[] Unkown13Shorts; /// <summary> /// The number vertices /// </summary> public ushort NumVertices; /// <summary> /// The vertex weights /// </summary> public SkinWeight[] VertexWeights; /// <summary> /// Initializes a new instance of the <see cref="SkinData"/> class. /// </summary> /// <param name="file">The file.</param> /// <param name="reader">The reader.</param> /// <param name="hasVertexWeights">if set to <c>true</c> [has vertex weights].</param> public SkinData(NiFile file, BinaryReader reader, bool hasVertexWeights) { this.Transform = new SkinTransform(file, reader); this.BoundingSphereOffset = reader.ReadVector3(); this.BoundingSphereRadius = reader.ReadSingle(); if (file.Version == eNifVersion.VER_20_3_0_9 && file.Header.UserVersion == 131072u) { this.Unkown13Shorts = new ushort[13]; for (int i = 0; i < 13; i++) { this.Unkown13Shorts[i] = reader.ReadUInt16(); } } this.NumVertices = reader.ReadUInt16(); if (hasVertexWeights) { this.VertexWeights = new SkinWeight[(int)this.NumVertices]; for (int j = 0; j < (int)this.NumVertices; j++) { this.VertexWeights[j] = new SkinWeight(file, reader); } } } } }
dol-leodagan/niflib.net
Niflib/SkinData.cs
C#
gpl-2.0
2,847