code
stringlengths 4
1.01M
| language
stringclasses 2
values |
---|---|
/*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedGossip.h"
#include "halls_of_reflection.h"
#include "Player.h"
enum Yells
{
SAY_JAINA_INTRO_1 = 0,
SAY_JAINA_INTRO_2 = 1,
SAY_JAINA_INTRO_3 = 2,
SAY_JAINA_INTRO_4 = 3,
SAY_JAINA_INTRO_5 = 4,
SAY_JAINA_INTRO_6 = 5,
SAY_JAINA_INTRO_7 = 6,
SAY_JAINA_INTRO_8 = 7,
SAY_JAINA_INTRO_9 = 8,
SAY_JAINA_INTRO_10 = 9,
SAY_JAINA_INTRO_11 = 10,
SAY_JAINA_INTRO_END = 11,
SAY_SYLVANAS_INTRO_1 = 0,
SAY_SYLVANAS_INTRO_2 = 1,
SAY_SYLVANAS_INTRO_3 = 2,
SAY_SYLVANAS_INTRO_4 = 3,
SAY_SYLVANAS_INTRO_5 = 4,
SAY_SYLVANAS_INTRO_6 = 5,
SAY_SYLVANAS_INTRO_7 = 6,
SAY_SYLVANAS_INTRO_8 = 7,
SAY_SYLVANAS_INTRO_END = 8,
SAY_UTHER_INTRO_A2_1 = 0,
SAY_UTHER_INTRO_A2_2 = 1,
SAY_UTHER_INTRO_A2_3 = 2,
SAY_UTHER_INTRO_A2_4 = 3,
SAY_UTHER_INTRO_A2_5 = 4,
SAY_UTHER_INTRO_A2_6 = 5,
SAY_UTHER_INTRO_A2_7 = 6,
SAY_UTHER_INTRO_A2_8 = 7,
SAY_UTHER_INTRO_A2_9 = 8,
SAY_UTHER_INTRO_H2_1 = 9,
SAY_UTHER_INTRO_H2_2 = 10,
SAY_UTHER_INTRO_H2_3 = 11,
SAY_UTHER_INTRO_H2_4 = 12,
SAY_UTHER_INTRO_H2_5 = 13,
SAY_UTHER_INTRO_H2_6 = 14,
SAY_UTHER_INTRO_H2_7 = 15,
SAY_LK_INTRO_1 = 0,
SAY_LK_INTRO_2 = 1,
SAY_LK_INTRO_3 = 2,
SAY_FALRIC_INTRO_1 = 5,
SAY_FALRIC_INTRO_2 = 6,
SAY_MARWYN_INTRO_1 = 4
};
enum Events
{
EVENT_NONE,
EVENT_START_INTRO,
EVENT_SKIP_INTRO,
EVENT_INTRO_A2_1,
EVENT_INTRO_A2_2,
EVENT_INTRO_A2_3,
EVENT_INTRO_A2_4,
EVENT_INTRO_A2_5,
EVENT_INTRO_A2_6,
EVENT_INTRO_A2_7,
EVENT_INTRO_A2_8,
EVENT_INTRO_A2_9,
EVENT_INTRO_A2_10,
EVENT_INTRO_A2_11,
EVENT_INTRO_A2_12,
EVENT_INTRO_A2_13,
EVENT_INTRO_A2_14,
EVENT_INTRO_A2_15,
EVENT_INTRO_A2_16,
EVENT_INTRO_A2_17,
EVENT_INTRO_A2_18,
EVENT_INTRO_A2_19,
EVENT_INTRO_H2_1,
EVENT_INTRO_H2_2,
EVENT_INTRO_H2_3,
EVENT_INTRO_H2_4,
EVENT_INTRO_H2_5,
EVENT_INTRO_H2_6,
EVENT_INTRO_H2_7,
EVENT_INTRO_H2_8,
EVENT_INTRO_H2_9,
EVENT_INTRO_H2_10,
EVENT_INTRO_H2_11,
EVENT_INTRO_H2_12,
EVENT_INTRO_H2_13,
EVENT_INTRO_H2_14,
EVENT_INTRO_H2_15,
EVENT_INTRO_LK_1,
EVENT_INTRO_LK_2,
EVENT_INTRO_LK_3,
EVENT_INTRO_LK_4,
EVENT_INTRO_LK_5,
EVENT_INTRO_LK_6,
EVENT_INTRO_LK_7,
EVENT_INTRO_LK_8,
EVENT_INTRO_LK_9,
EVENT_INTRO_END,
};
enum eEnum
{
ACTION_START_INTRO,
ACTION_SKIP_INTRO,
QUEST_DELIVRANCE_FROM_THE_PIT_A2 = 24710,
QUEST_DELIVRANCE_FROM_THE_PIT_H2 = 24712,
QUEST_WRATH_OF_THE_LICH_KING_A2 = 24500,
QUEST_WRATH_OF_THE_LICH_KING_H2 = 24802,
};
const Position HallsofReflectionLocs[]=
{
{5283.234863f, 1990.946777f, 707.695679f, 0.929097f}, // 2 Loralen Follows
{5408.031250f, 2102.918213f, 707.695251f, 0.792756f}, // 9 Sylvanas Follows
{5401.866699f, 2110.837402f, 707.695251f, 0.800610f}, // 10 Loralen follows
};
const Position SpawnPos = {5262.540527f, 1949.693726f, 707.695007f, 0.808736f}; // Jaina/Sylvanas Beginning Position
const Position MoveThronePos = {5306.952148f, 1998.499023f, 709.341431f, 1.277278f}; // Jaina/Sylvanas walks to throne
const Position UtherSpawnPos = {5308.310059f, 2003.857178f, 709.341431f, 4.650315f};
const Position LichKingSpawnPos = {5362.917480f, 2062.307129f, 707.695374f, 3.945812f};
const Position LichKingMoveThronePos = {5312.080566f, 2009.172119f, 709.341431f, 3.973301f}; // Lich King walks to throne
const Position LichKingMoveAwayPos = {5400.069824f, 2102.7131689f, 707.69525f, 0.843803f}; // Lich King walks away
class npc_jaina_or_sylvanas_hor : public CreatureScript
{
private:
bool m_isSylvana;
public:
npc_jaina_or_sylvanas_hor(bool isSylvana, const char* name) : CreatureScript(name), m_isSylvana(isSylvana) { }
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action)
{
player->PlayerTalkClass->ClearMenus();
switch (action)
{
case GOSSIP_ACTION_INFO_DEF+1:
player->CLOSE_GOSSIP_MENU();
if (creature->AI())
creature->AI()->DoAction(ACTION_START_INTRO);
creature->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
break;
case GOSSIP_ACTION_INFO_DEF+2:
player->CLOSE_GOSSIP_MENU();
if (creature->AI())
creature->AI()->DoAction(ACTION_SKIP_INTRO);
creature->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
break;
}
return true;
}
bool OnGossipHello(Player* player, Creature* creature)
{
if (creature->isQuestGiver())
player->PrepareQuestMenu(creature->GetGUID());
QuestStatus status = player->GetQuestStatus(m_isSylvana ? QUEST_DELIVRANCE_FROM_THE_PIT_H2 : QUEST_DELIVRANCE_FROM_THE_PIT_A2);
if (status == QUEST_STATUS_COMPLETE || status == QUEST_STATUS_REWARDED)
player->ADD_GOSSIP_ITEM( 0, "Can you remove the sword?", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
// once last quest is completed, she offers this shortcut of the starting event
status = player->GetQuestStatus(m_isSylvana ? QUEST_WRATH_OF_THE_LICH_KING_H2 : QUEST_WRATH_OF_THE_LICH_KING_A2);
if (status == QUEST_STATUS_COMPLETE || status == QUEST_STATUS_REWARDED)
player->ADD_GOSSIP_ITEM( 0, "Dark Lady, I think I hear Arthas coming. Whatever you're going to do, do it quickly.", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2);
player->SEND_GOSSIP_MENU(DEFAULT_GOSSIP_MESSAGE, creature->GetGUID());
return true;
}
CreatureAI* GetAI(Creature* creature) const
{
return new npc_jaina_or_sylvanas_horAI(creature);
}
// AI of Part1: handle the intro till start of gauntlet event.
struct npc_jaina_or_sylvanas_horAI : public ScriptedAI
{
npc_jaina_or_sylvanas_horAI(Creature* creature) : ScriptedAI(creature)
{
instance = me->GetInstanceScript();
}
InstanceScript* instance;
uint64 utherGUID;
uint64 lichkingGUID;
EventMap events;
void Reset()
{
events.Reset();
utherGUID = 0;
lichkingGUID = 0;
me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
me->SetStandState(UNIT_STAND_STATE_STAND);
me->SetVisible(true);
}
void DoAction(const int32 actionId)
{
switch (actionId)
{
case ACTION_START_INTRO:
events.ScheduleEvent(EVENT_START_INTRO, 0);
break;
case ACTION_SKIP_INTRO:
events.ScheduleEvent(EVENT_SKIP_INTRO, 0);
break;
}
}
void UpdateAI(const uint32 diff)
{
events.Update(diff);
switch (events.ExecuteEvent())
{
case EVENT_START_INTRO:
me->GetMotionMaster()->MovePoint(0, MoveThronePos);
// Begining of intro is differents between fActions as the speech sequence and timers are differents.
if (instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE)
events.ScheduleEvent(EVENT_INTRO_A2_1, 0);
else
events.ScheduleEvent(EVENT_INTRO_H2_1, 0);
break;
// A2 Intro Events
case EVENT_INTRO_A2_1:
Talk(SAY_JAINA_INTRO_3);
events.ScheduleEvent(EVENT_INTRO_A2_2, 5000);
break;
case EVENT_INTRO_A2_2:
Talk(SAY_JAINA_INTRO_4);
events.ScheduleEvent(EVENT_INTRO_A2_3, 10000);
break;
case EVENT_INTRO_A2_3:
// TODO: she's doing some kind of spell casting emote
instance->HandleGameObject(instance->GetData64(DATA_FROSTMOURNE), true);
events.ScheduleEvent(EVENT_INTRO_A2_4, 10000);
break;
case EVENT_INTRO_A2_4:
// spawn UTHER during speach 2
if (Creature* uther = me->SummonCreature(NPC_UTHER, UtherSpawnPos, TEMPSUMMON_MANUAL_DESPAWN))
{
uther->GetMotionMaster()->MoveIdle();
uther->SetReactState(REACT_PASSIVE); // be sure he will not aggro arthas
utherGUID = uther->GetGUID();
}
events.ScheduleEvent(EVENT_INTRO_A2_5, 2000);
break;
case EVENT_INTRO_A2_5:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_A2_1);
events.ScheduleEvent(EVENT_INTRO_A2_6, 3000);
break;
case EVENT_INTRO_A2_6:
Talk(SAY_JAINA_INTRO_5);
events.ScheduleEvent(EVENT_INTRO_A2_7, 6000);
break;
case EVENT_INTRO_A2_7:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_A2_2);
events.ScheduleEvent(EVENT_INTRO_A2_8, 6500);
break;
case EVENT_INTRO_A2_8:
Talk(SAY_JAINA_INTRO_6);
events.ScheduleEvent(EVENT_INTRO_A2_9, 2000);
break;
case EVENT_INTRO_A2_9:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_A2_3);
events.ScheduleEvent(EVENT_INTRO_A2_10, 9000);
break;
case EVENT_INTRO_A2_10:
Talk(SAY_JAINA_INTRO_7);
events.ScheduleEvent(EVENT_INTRO_A2_11, 5000);
break;
case EVENT_INTRO_A2_11:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_A2_4);
events.ScheduleEvent(EVENT_INTRO_A2_12, 11000);
break;
case EVENT_INTRO_A2_12:
Talk(SAY_JAINA_INTRO_8);
events.ScheduleEvent(EVENT_INTRO_A2_13, 4000);
break;
case EVENT_INTRO_A2_13:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_A2_5);
events.ScheduleEvent(EVENT_INTRO_A2_14, 12500);
break;
case EVENT_INTRO_A2_14:
Talk(SAY_JAINA_INTRO_9);
events.ScheduleEvent(EVENT_INTRO_A2_15, 10000);
break;
case EVENT_INTRO_A2_15:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_A2_6);
events.ScheduleEvent(EVENT_INTRO_A2_16, 22000);
break;
case EVENT_INTRO_A2_16:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_A2_7);
events.ScheduleEvent(EVENT_INTRO_A2_17, 4000);
break;
case EVENT_INTRO_A2_17:
Talk(SAY_JAINA_INTRO_10);
events.ScheduleEvent(EVENT_INTRO_A2_18, 2000);
break;
case EVENT_INTRO_A2_18:
if (Creature* uther = me->GetCreature(*me, utherGUID))
{
uther->HandleEmoteCommand(EMOTE_ONESHOT_NO);
uther->AI()->Talk(SAY_UTHER_INTRO_A2_8);
}
events.ScheduleEvent(EVENT_INTRO_A2_19, 11000);
break;
case EVENT_INTRO_A2_19:
Talk(SAY_JAINA_INTRO_11);
events.ScheduleEvent(EVENT_INTRO_LK_1, 2000);
break;
// H2 Intro Events
case EVENT_INTRO_H2_1:
Talk(SAY_SYLVANAS_INTRO_1);
events.ScheduleEvent(EVENT_INTRO_H2_2, 8000);
break;
case EVENT_INTRO_H2_2:
Talk(SAY_SYLVANAS_INTRO_2);
events.ScheduleEvent(EVENT_INTRO_H2_3, 6000);
break;
case EVENT_INTRO_H2_3:
Talk(SAY_SYLVANAS_INTRO_3);
// TODO: she's doing some kind of spell casting emote
events.ScheduleEvent(EVENT_INTRO_H2_4, 6000);
break;
case EVENT_INTRO_H2_4:
// spawn UTHER during speach 2
if (Creature* uther = me->SummonCreature(NPC_UTHER, UtherSpawnPos, TEMPSUMMON_MANUAL_DESPAWN))
{
uther->GetMotionMaster()->MoveIdle();
uther->SetReactState(REACT_PASSIVE); // be sure he will not aggro arthas
utherGUID = uther->GetGUID();
}
events.ScheduleEvent(EVENT_INTRO_H2_5, 2000);
break;
case EVENT_INTRO_H2_5:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_H2_1);
events.ScheduleEvent(EVENT_INTRO_H2_6, 11000);
break;
case EVENT_INTRO_H2_6:
Talk(SAY_SYLVANAS_INTRO_4);
events.ScheduleEvent(EVENT_INTRO_H2_7, 3000);
break;
case EVENT_INTRO_H2_7:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_H2_2);
events.ScheduleEvent(EVENT_INTRO_H2_8, 6000);
break;
case EVENT_INTRO_H2_8:
Talk(SAY_SYLVANAS_INTRO_5);
events.ScheduleEvent(EVENT_INTRO_H2_9, 5000);
break;
case EVENT_INTRO_H2_9:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_H2_3);
events.ScheduleEvent(EVENT_INTRO_H2_10, 19000);
break;
case EVENT_INTRO_H2_10:
Talk(SAY_SYLVANAS_INTRO_6);
events.ScheduleEvent(EVENT_INTRO_H2_11, 1500);
break;
case EVENT_INTRO_H2_11:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_H2_4);
events.ScheduleEvent(EVENT_INTRO_H2_12, 19500);
break;
case EVENT_INTRO_H2_12:
Talk(SAY_SYLVANAS_INTRO_7);
events.ScheduleEvent(EVENT_INTRO_H2_13, 2000);
break;
case EVENT_INTRO_H2_13:
if (Creature* uther = me->GetCreature(*me, utherGUID))
{
uther->HandleEmoteCommand(EMOTE_ONESHOT_NO);
uther->AI()->Talk(SAY_UTHER_INTRO_H2_5);
}
events.ScheduleEvent(EVENT_INTRO_H2_14, 12000);
break;
case EVENT_INTRO_H2_14:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_H2_6);
events.ScheduleEvent(EVENT_INTRO_H2_15, 8000);
break;
case EVENT_INTRO_H2_15:
Talk(SAY_SYLVANAS_INTRO_8);
events.ScheduleEvent(EVENT_INTRO_LK_1, 2000);
break;
// Remaining Intro Events common for both faction
case EVENT_INTRO_LK_1:
// Spawn LK in front of door, and make him move to the sword.
if (Creature* lichking = me->SummonCreature(NPC_LICH_KING_EVENT, LichKingSpawnPos, TEMPSUMMON_MANUAL_DESPAWN))
{
lichking->GetMotionMaster()->MovePoint(0, LichKingMoveThronePos);
lichking->SetReactState(REACT_PASSIVE);
lichkingGUID = lichking->GetGUID();
}
if (Creature* uther = me->GetCreature(*me, utherGUID))
{
if (instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE)
uther->AI()->Talk(SAY_UTHER_INTRO_A2_9);
else
uther->AI()->Talk(SAY_UTHER_INTRO_H2_7);
}
events.ScheduleEvent(EVENT_INTRO_LK_2, 11000);
break;
case EVENT_INTRO_LK_2:
if (Creature* lichking = me->GetCreature(*me, lichkingGUID))
lichking->AI()->Talk(SAY_LK_INTRO_1);
events.ScheduleEvent(EVENT_INTRO_LK_3, 2000);
break;
case EVENT_INTRO_LK_3:
// The Lich King banishes Uther to the abyss.
if (Creature* uther = me->GetCreature(*me, utherGUID))
{
uther->DisappearAndDie();
utherGUID = 0;
}
// He steps forward and removes the runeblade from the heap of skulls.
events.ScheduleEvent(EVENT_INTRO_LK_4, 4000);
break;
case EVENT_INTRO_LK_4:
if (Creature* lichking = me->GetCreature(*me, lichkingGUID))
lichking->AI()->Talk(SAY_LK_INTRO_2);
events.ScheduleEvent(EVENT_INTRO_LK_5, 10000);
break;
case EVENT_INTRO_LK_5:
// summon Falric and Marwyn. then go back to the door
if (Creature* pFalric = me->GetCreature(*me, instance->GetData64(DATA_FALRIC)))
pFalric->SetVisible(true);
if (Creature* pMarwyn = me->GetCreature(*me, instance->GetData64(DATA_MARWYN)))
pMarwyn->SetVisible(true);
if (Creature* lichking = me->GetCreature(*me, lichkingGUID))
{
lichking->GetMotionMaster()->MovePoint(0, LichKingSpawnPos);
lichking->AI()->Talk(SAY_LK_INTRO_3);
}
events.ScheduleEvent(EVENT_INTRO_LK_6, 8000);
break;
case EVENT_INTRO_LK_6:
if (Creature* falric = me->GetCreature(*me, instance->GetData64(DATA_FALRIC)))
falric->AI()->Talk(SAY_FALRIC_INTRO_1);
events.ScheduleEvent(EVENT_INTRO_LK_7, 2000);
break;
case EVENT_INTRO_LK_7:
if (Creature* marwyn = me->GetCreature(*me, instance->GetData64(DATA_MARWYN)))
marwyn->AI()->Talk(SAY_MARWYN_INTRO_1);
events.ScheduleEvent(EVENT_INTRO_LK_8, 2000);
break;
case EVENT_INTRO_LK_8:
if (Creature* falric = me->GetCreature(*me, instance->GetData64(DATA_FALRIC)))
falric->AI()->Talk(SAY_FALRIC_INTRO_2);
events.ScheduleEvent(EVENT_INTRO_LK_9, 5000);
break;
case EVENT_INTRO_LK_9:
if (instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE)
Talk(SAY_JAINA_INTRO_END);
else
Talk(SAY_SYLVANAS_INTRO_END);
me->GetMotionMaster()->MovePoint(0, LichKingSpawnPos);
// TODO: Loralen/Koreln shall run also
events.ScheduleEvent(EVENT_INTRO_END, 10000);
break;
case EVENT_INTRO_END:
if (instance)
instance->SetData(DATA_WAVE_COUNT, SPECIAL); // start first wave
// Loralen or Koreln disappearAndDie()
me->DisappearAndDie();
break;
case EVENT_SKIP_INTRO:
// TODO: implement
if (Creature* pFalric = me->GetCreature(*me, instance->GetData64(DATA_FALRIC)))
pFalric->SetVisible(true);
if (Creature* pMarwyn = me->GetCreature(*me, instance->GetData64(DATA_MARWYN)))
pMarwyn->SetVisible(true);
me->GetMotionMaster()->MovePoint(0, LichKingSpawnPos);
// TODO: Loralen/Koreln shall run also
events.ScheduleEvent(EVENT_INTRO_END, 15000);
break;
}
}
};
};
enum TrashSpells
{
// Ghostly Priest
SPELL_SHADOW_WORD_PAIN = 72318,
SPELL_CIRCLE_OF_DESTRUCTION = 72320,
SPELL_COWER_IN_FEAR = 72321,
SPELL_DARK_MENDING = 72322,
// Phantom Mage
SPELL_FIREBALL = 72163,
SPELL_FLAMESTRIKE = 72169,
SPELL_FROSTBOLT = 72166,
SPELL_CHAINS_OF_ICE = 72121,
SPELL_HALLUCINATION = 72342,
// Phantom Hallucination (same as phantom mage + HALLUCINATION_2 when dies)
SPELL_HALLUCINATION_2 = 72344,
// Shadowy Mercenary
SPELL_SHADOW_STEP = 72326,
SPELL_DEADLY_POISON = 72329,
SPELL_ENVENOMED_DAGGER_THROW = 72333,
SPELL_KIDNEY_SHOT = 72335,
// Spectral Footman
SPELL_SPECTRAL_STRIKE = 72198,
SPELL_SHIELD_BASH = 72194,
SPELL_TORTURED_ENRAGE = 72203,
// Tortured Rifleman
SPELL_SHOOT = 72208,
SPELL_CURSED_ARROW = 72222,
SPELL_FROST_TRAP = 72215,
SPELL_ICE_SHOT = 72268,
};
enum TrashEvents
{
EVENT_TRASH_NONE,
// Ghostly Priest
EVENT_SHADOW_WORD_PAIN,
EVENT_CIRCLE_OF_DESTRUCTION,
EVENT_COWER_IN_FEAR,
EVENT_DARK_MENDING,
// Phantom Mage
EVENT_FIREBALL,
EVENT_FLAMESTRIKE,
EVENT_FROSTBOLT,
EVENT_CHAINS_OF_ICE,
EVENT_HALLUCINATION,
// Shadowy Mercenary
EVENT_SHADOW_STEP,
EVENT_DEADLY_POISON,
EVENT_ENVENOMED_DAGGER_THROW,
EVENT_KIDNEY_SHOT,
// Spectral Footman
EVENT_SPECTRAL_STRIKE,
EVENT_SHIELD_BASH,
EVENT_TORTURED_ENRAGE,
// Tortured Rifleman
EVENT_SHOOT,
EVENT_CURSED_ARROW,
EVENT_FROST_TRAP,
EVENT_ICE_SHOT,
};
class npc_ghostly_priest : public CreatureScript
{
public:
npc_ghostly_priest() : CreatureScript("npc_ghostly_priest") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_ghostly_priestAI(creature);
}
struct npc_ghostly_priestAI: public ScriptedAI
{
npc_ghostly_priestAI(Creature* creature) : ScriptedAI(creature)
{
}
EventMap events;
void Reset()
{
events.Reset();
}
void EnterCombat(Unit* /*who*/)
{
events.ScheduleEvent(EVENT_SHADOW_WORD_PAIN, 8000); // TODO: adjust timers
events.ScheduleEvent(EVENT_CIRCLE_OF_DESTRUCTION, 12000);
events.ScheduleEvent(EVENT_COWER_IN_FEAR, 10000);
events.ScheduleEvent(EVENT_DARK_MENDING, 20000);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SHADOW_WORD_PAIN:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_SHADOW_WORD_PAIN);
events.ScheduleEvent(EVENT_SHADOW_WORD_PAIN, 8000);
return;
case EVENT_CIRCLE_OF_DESTRUCTION:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_CIRCLE_OF_DESTRUCTION);
events.ScheduleEvent(EVENT_CIRCLE_OF_DESTRUCTION, 12000);
return;
case EVENT_COWER_IN_FEAR:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_COWER_IN_FEAR);
events.ScheduleEvent(EVENT_COWER_IN_FEAR, 10000);
return;
case EVENT_DARK_MENDING:
// find an ally with missing HP
if (Unit* target = DoSelectLowestHpFriendly(40, DUNGEON_MODE(30000, 50000)))
{
DoCast(target, SPELL_DARK_MENDING);
events.ScheduleEvent(EVENT_DARK_MENDING, 20000);
}
else
{
// no friendly unit with missing hp. re-check in just 5 sec.
events.ScheduleEvent(EVENT_DARK_MENDING, 5000);
}
return;
}
}
DoMeleeAttackIfReady();
}
};
};
class npc_phantom_mage : public CreatureScript
{
public:
npc_phantom_mage() : CreatureScript("npc_phantom_mage") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_phantom_mageAI(creature);
}
struct npc_phantom_mageAI: public ScriptedAI
{
npc_phantom_mageAI(Creature* creature) : ScriptedAI(creature)
{
}
EventMap events;
void Reset()
{
events.Reset();
}
void EnterCombat(Unit* /*who*/)
{
events.ScheduleEvent(EVENT_FIREBALL, 3000); // TODO: adjust timers
events.ScheduleEvent(EVENT_FLAMESTRIKE, 6000);
events.ScheduleEvent(EVENT_FROSTBOLT, 9000);
events.ScheduleEvent(EVENT_CHAINS_OF_ICE, 12000);
events.ScheduleEvent(EVENT_HALLUCINATION, 40000);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_FIREBALL:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_FIREBALL);
events.ScheduleEvent(EVENT_FIREBALL, 15000);
return;
case EVENT_FLAMESTRIKE:
DoCast(SPELL_FLAMESTRIKE);
events.ScheduleEvent(EVENT_FLAMESTRIKE, 15000);
return;
case EVENT_FROSTBOLT:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_FROSTBOLT);
events.ScheduleEvent(EVENT_FROSTBOLT, 15000);
return;
case EVENT_CHAINS_OF_ICE:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_CHAINS_OF_ICE);
events.ScheduleEvent(EVENT_CHAINS_OF_ICE, 15000);
return;
case EVENT_HALLUCINATION:
DoCast(SPELL_HALLUCINATION);
return;
}
}
DoMeleeAttackIfReady();
}
};
};
class npc_phantom_hallucination : public CreatureScript
{
public:
npc_phantom_hallucination() : CreatureScript("npc_phantom_hallucination") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_phantom_hallucinationAI(creature);
}
struct npc_phantom_hallucinationAI : public npc_phantom_mage::npc_phantom_mageAI
{
npc_phantom_hallucinationAI(Creature* creature) : npc_phantom_mage::npc_phantom_mageAI(creature)
{
}
void JustDied(Unit* /*killer*/)
{
DoCast(SPELL_HALLUCINATION_2);
}
};
};
class npc_shadowy_mercenary : public CreatureScript
{
public:
npc_shadowy_mercenary() : CreatureScript("npc_shadowy_mercenary") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_shadowy_mercenaryAI(creature);
}
struct npc_shadowy_mercenaryAI: public ScriptedAI
{
npc_shadowy_mercenaryAI(Creature* creature) : ScriptedAI(creature)
{
}
EventMap events;
void Reset()
{
events.Reset();
}
void EnterCombat(Unit* /*who*/)
{
events.ScheduleEvent(EVENT_SHADOW_STEP, 8000); // TODO: adjust timers
events.ScheduleEvent(EVENT_DEADLY_POISON, 5000);
events.ScheduleEvent(EVENT_ENVENOMED_DAGGER_THROW, 10000);
events.ScheduleEvent(EVENT_KIDNEY_SHOT, 12000);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SHADOW_STEP:
DoCast(SPELL_SHADOW_STEP);
events.ScheduleEvent(EVENT_SHADOW_STEP, 8000);
return;
case EVENT_DEADLY_POISON:
DoCast(me->getVictim(), SPELL_DEADLY_POISON);
events.ScheduleEvent(EVENT_DEADLY_POISON, 10000);
return;
case EVENT_ENVENOMED_DAGGER_THROW:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_ENVENOMED_DAGGER_THROW);
events.ScheduleEvent(EVENT_ENVENOMED_DAGGER_THROW, 10000);
return;
case EVENT_KIDNEY_SHOT:
DoCast(me->getVictim(), SPELL_KIDNEY_SHOT);
events.ScheduleEvent(EVENT_KIDNEY_SHOT, 10000);
return;
}
}
DoMeleeAttackIfReady();
}
};
};
class npc_spectral_footman : public CreatureScript
{
public:
npc_spectral_footman() : CreatureScript("npc_spectral_footman") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_spectral_footmanAI(creature);
}
struct npc_spectral_footmanAI: public ScriptedAI
{
npc_spectral_footmanAI(Creature* creature) : ScriptedAI(creature)
{
}
EventMap events;
void Reset()
{
events.Reset();
}
void EnterCombat(Unit* /*who*/)
{
events.ScheduleEvent(EVENT_SPECTRAL_STRIKE, 5000); // TODO: adjust timers
events.ScheduleEvent(EVENT_SHIELD_BASH, 10000);
events.ScheduleEvent(EVENT_TORTURED_ENRAGE, 15000);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SPECTRAL_STRIKE:
DoCast(me->getVictim(), SPELL_SPECTRAL_STRIKE);
events.ScheduleEvent(EVENT_SPECTRAL_STRIKE, 5000);
return;
case EVENT_SHIELD_BASH:
DoCast(me->getVictim(), SPELL_SHIELD_BASH);
events.ScheduleEvent(EVENT_SHIELD_BASH, 5000);
return;
case EVENT_TORTURED_ENRAGE:
DoCast(SPELL_TORTURED_ENRAGE);
events.ScheduleEvent(EVENT_TORTURED_ENRAGE, 15000);
return;
}
}
DoMeleeAttackIfReady();
}
};
};
class npc_tortured_rifleman : public CreatureScript
{
public:
npc_tortured_rifleman() : CreatureScript("npc_tortured_rifleman") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_tortured_riflemanAI(creature);
}
struct npc_tortured_riflemanAI : public ScriptedAI
{
npc_tortured_riflemanAI(Creature* creature) : ScriptedAI(creature)
{
}
EventMap events;
void Reset()
{
events.Reset();
}
void EnterCombat(Unit* /*who*/)
{
events.ScheduleEvent(EVENT_SHOOT, 2000); // TODO: adjust timers
events.ScheduleEvent(EVENT_CURSED_ARROW, 10000);
events.ScheduleEvent(EVENT_FROST_TRAP, 1000);
events.ScheduleEvent(EVENT_ICE_SHOT, 15000);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SHOOT:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_SHOOT);
events.ScheduleEvent(EVENT_SHOOT, 2000);
return;
case EVENT_CURSED_ARROW:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_CURSED_ARROW);
events.ScheduleEvent(EVENT_CURSED_ARROW, 10000);
return;
case EVENT_FROST_TRAP:
DoCast(SPELL_FROST_TRAP);
events.ScheduleEvent(EVENT_FROST_TRAP, 30000);
return;
case EVENT_ICE_SHOT:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_ICE_SHOT);
events.ScheduleEvent(EVENT_ICE_SHOT, 15000);
return;
}
}
DoMeleeAttackIfReady();
}
};
};
void AddSC_halls_of_reflection()
{
new npc_jaina_or_sylvanas_hor(true, "npc_sylvanas_hor_part1");
new npc_jaina_or_sylvanas_hor(false, "npc_jaina_hor_part1");
new npc_ghostly_priest();
new npc_phantom_mage();
new npc_phantom_hallucination();
new npc_shadowy_mercenary();
new npc_spectral_footman();
new npc_tortured_rifleman();
}
| Java |
"""
Test cases adapted from the test_bsddb.py module in Python's
regression test suite.
"""
import sys, os, string
import unittest
import tempfile
from test_all import verbose
try:
# For Python 2.3
from bsddb import db, hashopen, btopen, rnopen
except ImportError:
# For earlier Pythons w/distutils pybsddb
from bsddb3 import db, hashopen, btopen, rnopen
class CompatibilityTestCase(unittest.TestCase):
def setUp(self):
self.filename = tempfile.mktemp()
def tearDown(self):
try:
os.remove(self.filename)
except os.error:
pass
def test01_btopen(self):
self.do_bthash_test(btopen, 'btopen')
def test02_hashopen(self):
self.do_bthash_test(hashopen, 'hashopen')
def test03_rnopen(self):
data = string.split("The quick brown fox jumped over the lazy dog.")
if verbose:
print "\nTesting: rnopen"
f = rnopen(self.filename, 'c')
for x in range(len(data)):
f[x+1] = data[x]
getTest = (f[1], f[2], f[3])
if verbose:
print '%s %s %s' % getTest
assert getTest[1] == 'quick', 'data mismatch!'
f[25] = 'twenty-five'
f.close()
del f
f = rnopen(self.filename, 'w')
f[20] = 'twenty'
def noRec(f):
rec = f[15]
self.assertRaises(KeyError, noRec, f)
def badKey(f):
rec = f['a string']
self.assertRaises(TypeError, badKey, f)
del f[3]
rec = f.first()
while rec:
if verbose:
print rec
try:
rec = f.next()
except KeyError:
break
f.close()
def test04_n_flag(self):
f = hashopen(self.filename, 'n')
f.close()
def do_bthash_test(self, factory, what):
if verbose:
print '\nTesting: ', what
f = factory(self.filename, 'c')
if verbose:
print 'creation...'
# truth test
if f:
if verbose: print "truth test: true"
else:
if verbose: print "truth test: false"
f['0'] = ''
f['a'] = 'Guido'
f['b'] = 'van'
f['c'] = 'Rossum'
f['d'] = 'invented'
f['f'] = 'Python'
if verbose:
print '%s %s %s' % (f['a'], f['b'], f['c'])
if verbose:
print 'key ordering...'
f.set_location(f.first()[0])
while 1:
try:
rec = f.next()
except KeyError:
assert rec == f.last(), 'Error, last <> last!'
f.previous()
break
if verbose:
print rec
assert f.has_key('f'), 'Error, missing key!'
f.sync()
f.close()
# truth test
try:
if f:
if verbose: print "truth test: true"
else:
if verbose: print "truth test: false"
except db.DBError:
pass
else:
self.fail("Exception expected")
del f
if verbose:
print 'modification...'
f = factory(self.filename, 'w')
f['d'] = 'discovered'
if verbose:
print 'access...'
for key in f.keys():
word = f[key]
if verbose:
print word
def noRec(f):
rec = f['no such key']
self.assertRaises(KeyError, noRec, f)
def badKey(f):
rec = f[15]
self.assertRaises(TypeError, badKey, f)
f.close()
#----------------------------------------------------------------------
def test_suite():
return unittest.makeSuite(CompatibilityTestCase)
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
| Java |
<?php
// no direct access
defined('_JEXEC') or die('Restricted access');
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
jimport('joomla.application.component.view');
/**
* Description of SocialcountViewSocialcount
*
* @author stuart
*/
class SocialstreamsViewStream extends JView {
function display($tpl = null) {
if(!$this->get(ucfirst($this->network) . 'Cache')){
$adminmodel = &$this->getModel();
}
$this->assignRef('cache', $cache);
parent::display($tpl);
}
}
?>
| Java |
/* Delay between tap_code register and unregister to fix flaky media keys. */
#undef TAP_CODE_DELAY
#define TAP_CODE_DELAY 10
/* Turn off RGB lighting when the host goes to sleep. */
#define RGBLIGHT_SLEEP
/* Keep backlight and RGB level increments consistent across keyboards. */
#undef BACKLIGHT_LEVELS
#undef RGBLIGHT_HUE_STEP
#undef RGBLIGHT_SAT_STEP
#undef RGBLIGHT_VAL_STEP
#define BACKLIGHT_LEVELS 7
#define RGBLIGHT_HUE_STEP 8
#define RGBLIGHT_SAT_STEP 17
#define RGBLIGHT_VAL_STEP 17
/* Make mouse operation smoother. */
#undef MOUSEKEY_DELAY
#undef MOUSEKEY_INTERVAL
#define MOUSEKEY_DELAY 0
#define MOUSEKEY_INTERVAL 16
/* Lower mouse speed to adjust for reduced MOUSEKEY_INTERVAL. */
#undef MOUSEKEY_MAX_SPEED
#undef MOUSEKEY_TIME_TO_MAX
#undef MOUSEKEY_WHEEL_MAX_SPEED
#undef MOUSEKEY_WHEEL_TIME_TO_MAX
#define MOUSEKEY_MAX_SPEED 7
#define MOUSEKEY_TIME_TO_MAX 150
#define MOUSEKEY_WHEEL_MAX_SPEED 3
#define MOUSEKEY_WHEEL_TIME_TO_MAX 150
| Java |
/*******************************************************************************************
Copyright 2010 Broadcom Corporation. All rights reserved.
Unless you and Broadcom execute a separate written software license agreement
governing use of this software, this software is licensed to you under the
terms of the GNU General Public License version 2, available at
http://www.gnu.org/copyleft/gpl.html (the "GPL").
Notwithstanding the above, under no circumstances may you combine this software
in any way with any other Broadcom software provided under a license other than
the GPL, without Broadcom's express prior written consent.
*******************************************************************************************/
/**
*
* @file capi2_cc_ds.h
*
* @brief This file defines the capi2 Call Control related data types
*
****************************************************************************/
#ifndef _CAPI2_CC_DS_H_
#define _CAPI2_CC_DS_H_
/**
* @addtogroup CAPI2_CCAPIGroup
* @{
*/
// Data Definitions used by CAPI2 only
#define PHONE_NUMBER_LEN 82
/**
Phone number dial string
**/
typedef struct
{
char phone_number[PHONE_NUMBER_LEN]; ///< NULL terminated dial string
} PHONE_NUMBER_STR_t;
/**
States for all non-idle calls
**/
typedef struct
{
CCallStateList_t stateList; ///< Call state array
UInt8 listSz; ///< Number of call states
} ALL_CALL_STATE_t;
/**
Indices for all non-idle calls
**/
typedef struct
{
CCallIndexList_t indexList; ///< Call index array
UInt8 listSz; ///< Number of call indices
} ALL_CALL_INDEX_t;
/** @} */
#endif
| Java |
/*
* vhost-vdpa
*
* Copyright(c) 2017-2018 Intel Corporation.
* Copyright(c) 2020 Red Hat, Inc.
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*
*/
#include "qemu/osdep.h"
#include <linux/vhost.h>
#include <linux/vfio.h>
#include <sys/eventfd.h>
#include <sys/ioctl.h>
#include "hw/virtio/vhost.h"
#include "hw/virtio/vhost-backend.h"
#include "hw/virtio/virtio-net.h"
#include "hw/virtio/vhost-vdpa.h"
#include "qemu/main-loop.h"
#include "cpu.h"
static bool vhost_vdpa_listener_skipped_section(MemoryRegionSection *section)
{
return (!memory_region_is_ram(section->mr) &&
!memory_region_is_iommu(section->mr)) ||
/*
* Sizing an enabled 64-bit BAR can cause spurious mappings to
* addresses in the upper part of the 64-bit address space. These
* are never accessed by the CPU and beyond the address width of
* some IOMMU hardware. TODO: VDPA should tell us the IOMMU width.
*/
section->offset_within_address_space & (1ULL << 63);
}
static int vhost_vdpa_dma_map(struct vhost_vdpa *v, hwaddr iova, hwaddr size,
void *vaddr, bool readonly)
{
struct vhost_msg_v2 msg = {};
int fd = v->device_fd;
int ret = 0;
msg.type = v->msg_type;
msg.iotlb.iova = iova;
msg.iotlb.size = size;
msg.iotlb.uaddr = (uint64_t)(uintptr_t)vaddr;
msg.iotlb.perm = readonly ? VHOST_ACCESS_RO : VHOST_ACCESS_RW;
msg.iotlb.type = VHOST_IOTLB_UPDATE;
if (write(fd, &msg, sizeof(msg)) != sizeof(msg)) {
error_report("failed to write, fd=%d, errno=%d (%s)",
fd, errno, strerror(errno));
return -EIO ;
}
return ret;
}
static int vhost_vdpa_dma_unmap(struct vhost_vdpa *v, hwaddr iova,
hwaddr size)
{
struct vhost_msg_v2 msg = {};
int fd = v->device_fd;
int ret = 0;
msg.type = v->msg_type;
msg.iotlb.iova = iova;
msg.iotlb.size = size;
msg.iotlb.type = VHOST_IOTLB_INVALIDATE;
if (write(fd, &msg, sizeof(msg)) != sizeof(msg)) {
error_report("failed to write, fd=%d, errno=%d (%s)",
fd, errno, strerror(errno));
return -EIO ;
}
return ret;
}
static void vhost_vdpa_listener_region_add(MemoryListener *listener,
MemoryRegionSection *section)
{
struct vhost_vdpa *v = container_of(listener, struct vhost_vdpa, listener);
hwaddr iova;
Int128 llend, llsize;
void *vaddr;
int ret;
if (vhost_vdpa_listener_skipped_section(section)) {
return;
}
if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
(section->offset_within_region & ~TARGET_PAGE_MASK))) {
error_report("%s received unaligned region", __func__);
return;
}
iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
llend = int128_make64(section->offset_within_address_space);
llend = int128_add(llend, section->size);
llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));
if (int128_ge(int128_make64(iova), llend)) {
return;
}
memory_region_ref(section->mr);
/* Here we assume that memory_region_is_ram(section->mr)==true */
vaddr = memory_region_get_ram_ptr(section->mr) +
section->offset_within_region +
(iova - section->offset_within_address_space);
llsize = int128_sub(llend, int128_make64(iova));
ret = vhost_vdpa_dma_map(v, iova, int128_get64(llsize),
vaddr, section->readonly);
if (ret) {
error_report("vhost vdpa map fail!");
if (memory_region_is_ram_device(section->mr)) {
/* Allow unexpected mappings not to be fatal for RAM devices */
error_report("map ram fail!");
return ;
}
goto fail;
}
return;
fail:
if (memory_region_is_ram_device(section->mr)) {
error_report("failed to vdpa_dma_map. pci p2p may not work");
return;
}
/*
* On the initfn path, store the first error in the container so we
* can gracefully fail. Runtime, there's not much we can do other
* than throw a hardware error.
*/
error_report("vhost-vdpa: DMA mapping failed, unable to continue");
return;
}
static void vhost_vdpa_listener_region_del(MemoryListener *listener,
MemoryRegionSection *section)
{
struct vhost_vdpa *v = container_of(listener, struct vhost_vdpa, listener);
hwaddr iova;
Int128 llend, llsize;
int ret;
bool try_unmap = true;
if (vhost_vdpa_listener_skipped_section(section)) {
return;
}
if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) !=
(section->offset_within_region & ~TARGET_PAGE_MASK))) {
error_report("%s received unaligned region", __func__);
return;
}
iova = TARGET_PAGE_ALIGN(section->offset_within_address_space);
llend = int128_make64(section->offset_within_address_space);
llend = int128_add(llend, section->size);
llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK));
if (int128_ge(int128_make64(iova), llend)) {
return;
}
llsize = int128_sub(llend, int128_make64(iova));
if (try_unmap) {
ret = vhost_vdpa_dma_unmap(v, iova, int128_get64(llsize));
if (ret) {
error_report("vhost_vdpa dma unmap error!");
}
}
memory_region_unref(section->mr);
}
/*
* IOTLB API is used by vhost-vpda which requires incremental updating
* of the mapping. So we can not use generic vhost memory listener which
* depends on the addnop().
*/
static const MemoryListener vhost_vdpa_memory_listener = {
.region_add = vhost_vdpa_listener_region_add,
.region_del = vhost_vdpa_listener_region_del,
};
static int vhost_vdpa_call(struct vhost_dev *dev, unsigned long int request,
void *arg)
{
struct vhost_vdpa *v = dev->opaque;
int fd = v->device_fd;
assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA);
return ioctl(fd, request, arg);
}
static void vhost_vdpa_add_status(struct vhost_dev *dev, uint8_t status)
{
uint8_t s;
if (vhost_vdpa_call(dev, VHOST_VDPA_GET_STATUS, &s)) {
return;
}
s |= status;
vhost_vdpa_call(dev, VHOST_VDPA_SET_STATUS, &s);
}
static int vhost_vdpa_init(struct vhost_dev *dev, void *opaque)
{
struct vhost_vdpa *v;
uint64_t features;
assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA);
v = opaque;
dev->opaque = opaque ;
vhost_vdpa_call(dev, VHOST_GET_FEATURES, &features);
dev->backend_features = features;
v->listener = vhost_vdpa_memory_listener;
v->msg_type = VHOST_IOTLB_MSG_V2;
vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_ACKNOWLEDGE |
VIRTIO_CONFIG_S_DRIVER);
return 0;
}
static int vhost_vdpa_cleanup(struct vhost_dev *dev)
{
struct vhost_vdpa *v;
assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA);
v = dev->opaque;
memory_listener_unregister(&v->listener);
dev->opaque = NULL;
return 0;
}
static int vhost_vdpa_memslots_limit(struct vhost_dev *dev)
{
return INT_MAX;
}
static int vhost_vdpa_set_mem_table(struct vhost_dev *dev,
struct vhost_memory *mem)
{
if (mem->padding) {
return -1;
}
return 0;
}
static int vhost_vdpa_set_features(struct vhost_dev *dev,
uint64_t features)
{
int ret;
ret = vhost_vdpa_call(dev, VHOST_SET_FEATURES, &features);
uint8_t status = 0;
if (ret) {
return ret;
}
vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_FEATURES_OK);
vhost_vdpa_call(dev, VHOST_VDPA_GET_STATUS, &status);
return !(status & VIRTIO_CONFIG_S_FEATURES_OK);
}
int vhost_vdpa_get_device_id(struct vhost_dev *dev,
uint32_t *device_id)
{
return vhost_vdpa_call(dev, VHOST_VDPA_GET_DEVICE_ID, device_id);
}
static int vhost_vdpa_reset_device(struct vhost_dev *dev)
{
uint8_t status = 0;
return vhost_vdpa_call(dev, VHOST_VDPA_SET_STATUS, &status);
}
static int vhost_vdpa_get_vq_index(struct vhost_dev *dev, int idx)
{
assert(idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs);
return idx - dev->vq_index;
}
static int vhost_vdpa_set_vring_ready(struct vhost_dev *dev)
{
int i;
for (i = 0; i < dev->nvqs; ++i) {
struct vhost_vring_state state = {
.index = dev->vq_index + i,
.num = 1,
};
vhost_vdpa_call(dev, VHOST_VDPA_SET_VRING_ENABLE, &state);
}
return 0;
}
static int vhost_vdpa_set_config(struct vhost_dev *dev, const uint8_t *data,
uint32_t offset, uint32_t size,
uint32_t flags)
{
struct vhost_vdpa_config *config;
int ret;
unsigned long config_size = offsetof(struct vhost_vdpa_config, buf);
config = g_malloc(size + config_size);
if (config == NULL) {
return -1;
}
config->off = offset;
config->len = size;
memcpy(config->buf, data, size);
ret = vhost_vdpa_call(dev, VHOST_VDPA_SET_CONFIG, config);
g_free(config);
return ret;
}
static int vhost_vdpa_get_config(struct vhost_dev *dev, uint8_t *config,
uint32_t config_len)
{
struct vhost_vdpa_config *v_config;
unsigned long config_size = offsetof(struct vhost_vdpa_config, buf);
int ret;
v_config = g_malloc(config_len + config_size);
if (v_config == NULL) {
return -1;
}
v_config->len = config_len;
v_config->off = 0;
ret = vhost_vdpa_call(dev, VHOST_VDPA_GET_CONFIG, v_config);
memcpy(config, v_config->buf, config_len);
g_free(v_config);
return ret;
}
static int vhost_vdpa_dev_start(struct vhost_dev *dev, bool started)
{
struct vhost_vdpa *v = dev->opaque;
if (started) {
uint8_t status = 0;
memory_listener_register(&v->listener, &address_space_memory);
vhost_vdpa_set_vring_ready(dev);
vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_DRIVER_OK);
vhost_vdpa_call(dev, VHOST_VDPA_GET_STATUS, &status);
return !(status & VIRTIO_CONFIG_S_DRIVER_OK);
} else {
vhost_vdpa_reset_device(dev);
vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_ACKNOWLEDGE |
VIRTIO_CONFIG_S_DRIVER);
memory_listener_unregister(&v->listener);
return 0;
}
}
static int vhost_vdpa_set_log_base(struct vhost_dev *dev, uint64_t base,
struct vhost_log *log)
{
return vhost_vdpa_call(dev, VHOST_SET_LOG_BASE, &base);
}
static int vhost_vdpa_set_vring_addr(struct vhost_dev *dev,
struct vhost_vring_addr *addr)
{
return vhost_vdpa_call(dev, VHOST_SET_VRING_ADDR, addr);
}
static int vhost_vdpa_set_vring_num(struct vhost_dev *dev,
struct vhost_vring_state *ring)
{
return vhost_vdpa_call(dev, VHOST_SET_VRING_NUM, ring);
}
static int vhost_vdpa_set_vring_base(struct vhost_dev *dev,
struct vhost_vring_state *ring)
{
return vhost_vdpa_call(dev, VHOST_SET_VRING_BASE, ring);
}
static int vhost_vdpa_get_vring_base(struct vhost_dev *dev,
struct vhost_vring_state *ring)
{
return vhost_vdpa_call(dev, VHOST_GET_VRING_BASE, ring);
}
static int vhost_vdpa_set_vring_kick(struct vhost_dev *dev,
struct vhost_vring_file *file)
{
return vhost_vdpa_call(dev, VHOST_SET_VRING_KICK, file);
}
static int vhost_vdpa_set_vring_call(struct vhost_dev *dev,
struct vhost_vring_file *file)
{
return vhost_vdpa_call(dev, VHOST_SET_VRING_CALL, file);
}
static int vhost_vdpa_get_features(struct vhost_dev *dev,
uint64_t *features)
{
return vhost_vdpa_call(dev, VHOST_GET_FEATURES, features);
}
static int vhost_vdpa_set_owner(struct vhost_dev *dev)
{
return vhost_vdpa_call(dev, VHOST_SET_OWNER, NULL);
}
static int vhost_vdpa_vq_get_addr(struct vhost_dev *dev,
struct vhost_vring_addr *addr, struct vhost_virtqueue *vq)
{
assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA);
addr->desc_user_addr = (uint64_t)(unsigned long)vq->desc_phys;
addr->avail_user_addr = (uint64_t)(unsigned long)vq->avail_phys;
addr->used_user_addr = (uint64_t)(unsigned long)vq->used_phys;
return 0;
}
static bool vhost_vdpa_force_iommu(struct vhost_dev *dev)
{
return true;
}
const VhostOps vdpa_ops = {
.backend_type = VHOST_BACKEND_TYPE_VDPA,
.vhost_backend_init = vhost_vdpa_init,
.vhost_backend_cleanup = vhost_vdpa_cleanup,
.vhost_set_log_base = vhost_vdpa_set_log_base,
.vhost_set_vring_addr = vhost_vdpa_set_vring_addr,
.vhost_set_vring_num = vhost_vdpa_set_vring_num,
.vhost_set_vring_base = vhost_vdpa_set_vring_base,
.vhost_get_vring_base = vhost_vdpa_get_vring_base,
.vhost_set_vring_kick = vhost_vdpa_set_vring_kick,
.vhost_set_vring_call = vhost_vdpa_set_vring_call,
.vhost_get_features = vhost_vdpa_get_features,
.vhost_set_owner = vhost_vdpa_set_owner,
.vhost_set_vring_endian = NULL,
.vhost_backend_memslots_limit = vhost_vdpa_memslots_limit,
.vhost_set_mem_table = vhost_vdpa_set_mem_table,
.vhost_set_features = vhost_vdpa_set_features,
.vhost_reset_device = vhost_vdpa_reset_device,
.vhost_get_vq_index = vhost_vdpa_get_vq_index,
.vhost_get_config = vhost_vdpa_get_config,
.vhost_set_config = vhost_vdpa_set_config,
.vhost_requires_shm_log = NULL,
.vhost_migration_done = NULL,
.vhost_backend_can_merge = NULL,
.vhost_net_set_mtu = NULL,
.vhost_set_iotlb_callback = NULL,
.vhost_send_device_iotlb_msg = NULL,
.vhost_dev_start = vhost_vdpa_dev_start,
.vhost_get_device_id = vhost_vdpa_get_device_id,
.vhost_vq_get_addr = vhost_vdpa_vq_get_addr,
.vhost_force_iommu = vhost_vdpa_force_iommu,
};
| Java |
/*
* Copyright (c) 2006 Boudewijn Rempt <[email protected]>
*
* 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 "kis_transparency_mask.h"
#include "kis_debug.h"
#include <KoIcon.h>
#include <KoColor.h>
#include <KoColorSpace.h>
#include <KoCompositeOpRegistry.h>
#include "kis_paint_device.h"
#include "kis_painter.h"
#include "kis_node_visitor.h"
#include "kis_processing_visitor.h"
KisTransparencyMask::KisTransparencyMask()
: KisEffectMask()
{
}
KisTransparencyMask::KisTransparencyMask(const KisTransparencyMask& rhs)
: KisEffectMask(rhs)
{
}
KisTransparencyMask::~KisTransparencyMask()
{
}
bool KisTransparencyMask::allowAsChild(KisNodeSP node) const
{
Q_UNUSED(node);
return false;
}
QRect KisTransparencyMask::decorateRect(KisPaintDeviceSP &src,
KisPaintDeviceSP &dst,
const QRect & rc) const
{
if (src != dst) {
KisPainter gc(dst);
gc.setCompositeOp(src->colorSpace()->compositeOp(COMPOSITE_COPY));
gc.bitBlt(rc.topLeft(), src, rc);
src->fill(rc, KoColor(Qt::transparent, src->colorSpace()));
}
return rc;
}
QRect KisTransparencyMask::extent() const
{
return parent() ? parent()->extent() : QRect();
}
QRect KisTransparencyMask::exactBounds() const
{
return parent() ? parent()->exactBounds() : QRect();
}
QRect KisTransparencyMask::changeRect(const QRect &rect, PositionToFilthy pos) const
{
/**
* Selection on transparency masks have no special meaning:
* They do crop both: change and need area
*/
return KisMask::changeRect(rect, pos);
}
QRect KisTransparencyMask::needRect(const QRect &rect, PositionToFilthy pos) const
{
/**
* Selection on transparency masks have no special meaning:
* They do crop both: change and need area
*/
return KisMask::needRect(rect, pos);
}
QIcon KisTransparencyMask::icon() const
{
return koIcon("view-filter");
}
bool KisTransparencyMask::accept(KisNodeVisitor &v)
{
return v.visit(this);
}
void KisTransparencyMask::accept(KisProcessingVisitor &visitor, KisUndoAdapter *undoAdapter)
{
return visitor.visit(this, undoAdapter);
}
#include "kis_transparency_mask.moc"
| Java |
<?php
/**
* File containing a Test Case for LimitationType class
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
* @version 2014.07.0
*/
namespace eZ\Publish\Core\Limitation\Tests;
use eZ\Publish\API\Repository\Values\ValueObject;
use eZ\Publish\API\Repository\Values\Content\ContentInfo;
use eZ\Publish\API\Repository\Values\Content\LocationCreateStruct;
use eZ\Publish\API\Repository\Values\Content\Query\Criterion\Operator;
use eZ\Publish\API\Repository\Values\User\Limitation;
use eZ\Publish\API\Repository\Values\User\Limitation\ParentContentTypeLimitation;
use eZ\Publish\API\Repository\Values\User\Limitation\ObjectStateLimitation;
use eZ\Publish\Core\Base\Exceptions\NotFoundException;
use eZ\Publish\Core\Limitation\ParentContentTypeLimitationType;
use eZ\Publish\Core\Repository\Values\Content\Location;
use eZ\Publish\Core\Repository\Values\Content\ContentCreateStruct;
use eZ\Publish\SPI\Persistence\Content\ContentInfo as SPIContentInfo;
use eZ\Publish\SPI\Persistence\Content\Location as SPILocation;
use eZ\Publish\SPI\Persistence\Content\Type as SPIContentType;
/**
* Test Case for LimitationType
*/
class ParentContentTypeLimitationTest extends Base
{
/**
* @var \eZ\Publish\SPI\Persistence\Content\Location\Handler|\PHPUnit_Framework_MockObject_MockObject
*/
private $locationHandlerMock;
/**
* @var \eZ\Publish\SPI\Persistence\Content\Type\Handler|\PHPUnit_Framework_MockObject_MockObject
*/
private $contentTypeHandlerMock;
/**
* @var \eZ\Publish\SPI\Persistence\Content\Handler|\PHPUnit_Framework_MockObject_MockObject
*/
private $contentHandlerMock;
/**
* Setup Location Handler mock
*/
public function setUp()
{
parent::setUp();
$this->locationHandlerMock = $this->getMock(
"eZ\\Publish\\SPI\\Persistence\\Content\\Location\\Handler",
array(),
array(),
'',
false
);
$this->contentTypeHandlerMock = $this->getMock(
"eZ\\Publish\\SPI\\Persistence\\Content\\Type\\Handler",
array(),
array(),
'',
false
);
$this->contentHandlerMock = $this->getMock(
"eZ\\Publish\\SPI\\Persistence\\Content\\Handler",
array(),
array(),
'',
false
);
}
/**
* Tear down Location Handler mock
*/
public function tearDown()
{
unset( $this->locationHandlerMock );
unset( $this->contentTypeHandlerMock );
unset( $this->contentHandlerMock );
parent::tearDown();
}
/**
*
* @return \eZ\Publish\Core\Limitation\ParentContentTypeLimitationType
*/
public function testConstruct()
{
return new ParentContentTypeLimitationType( $this->getPersistenceMock() );
}
/**
* @return array
*/
public function providerForTestAcceptValue()
{
return array(
array( new ParentContentTypeLimitation() ),
array( new ParentContentTypeLimitation( array() ) ),
array( new ParentContentTypeLimitation( array( 'limitationValues' => array( '', 'true', '2', 's3fd4af32r' ) ) ) ),
);
}
/**
* @dataProvider providerForTestAcceptValue
* @depends testConstruct
*
* @param \eZ\Publish\API\Repository\Values\User\Limitation\ParentContentTypeLimitation $limitation
* @param \eZ\Publish\Core\Limitation\ParentContentTypeLimitationType $limitationType
*/
public function testAcceptValue( ParentContentTypeLimitation $limitation, ParentContentTypeLimitationType $limitationType )
{
$limitationType->acceptValue( $limitation );
}
/**
* @return array
*/
public function providerForTestAcceptValueException()
{
return array(
array( new ObjectStateLimitation() ),
array( new ParentContentTypeLimitation( array( 'limitationValues' => array( true ) ) ) ),
array( new ParentContentTypeLimitation( array( 'limitationValues' => array( new \DateTime ) ) ) ),
);
}
/**
* @dataProvider providerForTestAcceptValueException
* @depends testConstruct
* @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
*
* @param \eZ\Publish\API\Repository\Values\User\Limitation $limitation
* @param \eZ\Publish\Core\Limitation\ParentContentTypeLimitationType $limitationType
*/
public function testAcceptValueException( Limitation $limitation, ParentContentTypeLimitationType $limitationType )
{
$limitationType->acceptValue( $limitation );
}
/**
* @return array
*/
public function providerForTestValidatePass()
{
return array(
array( new ParentContentTypeLimitation() ),
array( new ParentContentTypeLimitation( array() ) ),
array( new ParentContentTypeLimitation( array( 'limitationValues' => array( '1' ) ) ) ),
);
}
/**
* @dataProvider providerForTestValidatePass
*
* @param \eZ\Publish\API\Repository\Values\User\Limitation\ParentContentTypeLimitation $limitation
*/
public function testValidatePass( ParentContentTypeLimitation $limitation )
{
if ( !empty( $limitation->limitationValues ) )
{
$this->getPersistenceMock()
->expects( $this->any() )
->method( "contentTypeHandler" )
->will( $this->returnValue( $this->contentTypeHandlerMock ) );
foreach ( $limitation->limitationValues as $key => $value )
{
$this->contentTypeHandlerMock
->expects( $this->at( $key ) )
->method( "load" )
->with( $value )
->will( $this->returnValue( 42 ) );
}
}
// Need to create inline instead of depending on testConstruct() to get correct mock instance
$limitationType = $this->testConstruct();
$validationErrors = $limitationType->validate( $limitation );
self::assertEmpty( $validationErrors );
}
/**
* @return array
*/
public function providerForTestValidateError()
{
return array(
array( new ParentContentTypeLimitation(), 0 ),
array( new ParentContentTypeLimitation( array( 'limitationValues' => array( '/1/777/' ) ) ), 1 ),
array( new ParentContentTypeLimitation( array( 'limitationValues' => array( '/1/888/', '/1/999/' ) ) ), 2 ),
);
}
/**
* @dataProvider providerForTestValidateError
*
* @param \eZ\Publish\API\Repository\Values\User\Limitation\ParentContentTypeLimitation $limitation
* @param int $errorCount
*/
public function testValidateError( ParentContentTypeLimitation $limitation, $errorCount )
{
if ( !empty( $limitation->limitationValues ) )
{
$this->getPersistenceMock()
->expects( $this->any() )
->method( "contentTypeHandler" )
->will( $this->returnValue( $this->contentTypeHandlerMock ) );
foreach ( $limitation->limitationValues as $key => $value )
{
$this->contentTypeHandlerMock
->expects( $this->at( $key ) )
->method( "load" )
->with( $value )
->will( $this->throwException( new NotFoundException( 'location', $value ) ) );
}
}
else
{
$this->getPersistenceMock()
->expects( $this->never() )
->method( $this->anything() );
}
// Need to create inline instead of depending on testConstruct() to get correct mock instance
$limitationType = $this->testConstruct();
$validationErrors = $limitationType->validate( $limitation );
self::assertCount( $errorCount, $validationErrors );
}
/**
* @depends testConstruct
*
* @param \eZ\Publish\Core\Limitation\ParentContentTypeLimitationType $limitationType
*/
public function testBuildValue( ParentContentTypeLimitationType $limitationType )
{
$expected = array( 'test', 'test' => '1' );
$value = $limitationType->buildValue( $expected );
self::assertInstanceOf( '\eZ\Publish\API\Repository\Values\User\Limitation\ParentContentTypeLimitation', $value );
self::assertInternalType( 'array', $value->limitationValues );
self::assertEquals( $expected, $value->limitationValues );
}
protected function getTestEvaluateContentMock()
{
$contentMock = $this->getMock(
"eZ\\Publish\\API\\Repository\\Values\\Content\\Content",
array(),
array(),
'',
false
);
$contentMock
->expects( $this->once() )
->method( 'getVersionInfo' )
->will( $this->returnValue( $this->getTestEvaluateVersionInfoMock() ) );
return $contentMock;
}
protected function getTestEvaluateVersionInfoMock()
{
$versionInfoMock = $this->getMock(
"eZ\\Publish\\API\\Repository\\Values\\Content\\VersionInfo",
array(),
array(),
'',
false
);
$versionInfoMock
->expects( $this->once() )
->method( 'getContentInfo' )
->will( $this->returnValue( new ContentInfo( array( 'published' => true ) ) ) );
return $versionInfoMock;
}
/**
* @return array
*/
public function providerForTestEvaluate()
{
return array(
// ContentInfo, with API targets, no access
array(
'limitation' => new ParentContentTypeLimitation(),
'object' => new ContentInfo( array( 'published' => true ) ),
'targets' => array( new Location( array( "contentInfo" => new ContentInfo( array( "contentTypeId" => 24 ) ) ) ) ),
'persistence' => array(),
'expected' => false
),
// ContentInfo, with SPI targets, no access
array(
'limitation' => new ParentContentTypeLimitation(),
'object' => new ContentInfo( array( 'published' => true ) ),
'targets' => array( new SPILocation( array( "contentId" => 42 ) ) ),
'persistence' => array(
"contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "24" ) ) )
),
'expected' => false
),
// ContentInfo, with API targets, no access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => new ContentInfo( array( 'published' => true ) ),
'targets' => array( new Location( array( "contentInfo" => new ContentInfo( array( "contentTypeId" => 24 ) ) ) ) ),
'persistence' => array(),
'expected' => false
),
// ContentInfo, with SPI targets, no access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => new ContentInfo( array( 'published' => true ) ),
'targets' => array( new SPILocation( array( "contentId" => 42 ) ) ),
'persistence' => array(
"contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "24" ) ) )
),
'expected' => false
),
// ContentInfo, with API targets, with access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => new ContentInfo( array( 'published' => true ) ),
'targets' => array( new Location( array( "contentInfo" => new ContentInfo( array( "contentTypeId" => 42 ) ) ) ) ),
'persistence' => array(),
'expected' => true
),
// ContentInfo, with SPI targets, with access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => new ContentInfo( array( 'published' => true ) ),
'targets' => array( new SPILocation( array( "contentId" => 24 ) ) ),
'persistence' => array(
"contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "42" ) ) )
),
'expected' => true
),
// ContentInfo, no targets, with access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => new ContentInfo( array( 'published' => true ) ),
'targets' => array(),
'persistence' => array(
"locations" => array( new SPILocation( array( 'contentId' => '24' ) ) ),
"contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "42" ) ) )
),
'expected' => true
),
// ContentInfo, no targets, no access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => new ContentInfo( array( 'published' => true ) ),
'targets' => array(),
'persistence' => array(
"locations" => array( new SPILocation( array( 'contentId' => '24' ) ) ),
"contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "4200" ) ) )
),
'expected' => false
),
// ContentInfo, no targets, un-published, with access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => new ContentInfo( array( 'published' => false ) ),
'targets' => array(),
'persistence' => array(
"locations" => array( new SPILocation( array( 'contentId' => '24' ) ) ),
"contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "42" ) ) )
),
'expected' => true
),
// ContentInfo, no targets, un-published, no access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => new ContentInfo( array( 'published' => false ) ),
'targets' => array(),
'persistence' => array(
"locations" => array( new SPILocation( array( 'contentId' => '24' ) ) ),
"contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "4200" ) ) )
),
'expected' => false
),
// Content, with API targets, with access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => $this->getTestEvaluateContentMock(),
'targets' => array( new Location( array( "contentInfo" => new ContentInfo( array( "contentTypeId" => 42 ) ) ) ) ),
'persistence' => array(),
'expected' => true
),
// Content, with SPI targets, with access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => $this->getTestEvaluateContentMock(),
'targets' => array( new SPILocation( array( 'contentId' => '24' ) ) ),
'persistence' => array(
"contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "42" ) ) )
),
'expected' => true
),
// VersionInfo, with API targets, with access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => $this->getTestEvaluateVersionInfoMock(),
'targets' => array( new Location( array( "contentInfo" => new ContentInfo( array( "contentTypeId" => 42 ) ) ) ) ),
'persistence' => array(),
'expected' => true
),
// VersionInfo, with SPI targets, with access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => $this->getTestEvaluateVersionInfoMock(),
'targets' => array( new SPILocation( array( 'contentId' => '24' ) ) ),
'persistence' => array(
"contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "42" ) ) )
),
'expected' => true
),
// VersionInfo, with LocationCreateStruct targets, with access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => $this->getTestEvaluateVersionInfoMock(),
'targets' => array( new LocationCreateStruct( array( 'parentLocationId' => 24 ) ) ),
'persistence' => array(
"locations" => array( new SPILocation( array( 'contentId' => 100 ) ) ),
"contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "42" ) ) )
),
'expected' => true
),
// Content, with LocationCreateStruct targets, no access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => $this->getTestEvaluateContentMock(),
'targets' => array( new LocationCreateStruct( array( 'parentLocationId' => 24 ) ) ),
'persistence' => array(
"locations" => array( new SPILocation( array( 'contentId' => 100 ) ) ),
"contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "24" ) ) )
),
'expected' => false
),
// ContentCreateStruct, no targets, no access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ),
'object' => new ContentCreateStruct(),
'targets' => array(),
'persistence' => array(),
'expected' => false
),
// ContentCreateStruct, with LocationCreateStruct targets, no access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 12, 23 ) ) ),
'object' => new ContentCreateStruct(),
'targets' => array( new LocationCreateStruct( array( 'parentLocationId' => 24 ) ) ),
'persistence' => array(
"locations" => array( new SPILocation( array( 'contentId' => 100 ) ) ),
"contentInfos" => array( new SPIContentInfo( array( 'contentTypeId' => 34 ) ) )
),
'expected' => false
),
// ContentCreateStruct, with LocationCreateStruct targets, with access
array(
'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 12, 23 ) ) ),
'object' => new ContentCreateStruct(),
'targets' => array( new LocationCreateStruct( array( 'parentLocationId' => 43 ) ) ),
'persistence' => array(
"locations" => array( new SPILocation( array( 'contentId' => 100 ) ) ),
"contentInfos" => array( new SPIContentInfo( array( 'contentTypeId' => 12 ) ) )
),
'expected' => true
),
);
}
protected function assertContentHandlerExpectations( $callNo, $persistenceCalled, $contentId, $contentInfo )
{
$this->getPersistenceMock()
->expects( $this->at( $callNo + ( $persistenceCalled ? 1 : 0 ) ) )
->method( "contentHandler" )
->will( $this->returnValue( $this->contentHandlerMock ) );
$this->contentHandlerMock
->expects( $this->at( $callNo ) )
->method( "loadContentInfo" )
->with( $contentId )
->will( $this->returnValue( $contentInfo ) );
}
/**
* @dataProvider providerForTestEvaluate
*/
public function testEvaluate(
ParentContentTypeLimitation $limitation,
ValueObject $object,
$targets,
array $persistence,
$expected
)
{
// Need to create inline instead of depending on testConstruct() to get correct mock instance
$limitationType = $this->testConstruct();
$userMock = $this->getUserMock();
$userMock
->expects( $this->never() )
->method( $this->anything() );
$persistenceMock = $this->getPersistenceMock();
// ContentTypeHandler is never used in evaluate()
$persistenceMock
->expects( $this->never() )
->method( "contentTypeHandler" );
if ( empty( $persistence ) )
{
// Covers API targets, where no additional loading is required
$persistenceMock
->expects( $this->never() )
->method( $this->anything() );
}
else if ( !empty( $targets ) )
{
foreach ( $targets as $index => $target )
{
if ( $target instanceof LocationCreateStruct )
{
$this->getPersistenceMock()
->expects( $this->once( $index ) )
->method( "locationHandler" )
->will( $this->returnValue( $this->locationHandlerMock ) );
$this->locationHandlerMock
->expects( $this->at( $index ) )
->method( "load" )
->with( $target->parentLocationId )
->will( $this->returnValue( $location = $persistence["locations"][$index] ) );
$contentId = $location->contentId;
}
else
{
$contentId = $target->contentId;
}
$this->assertContentHandlerExpectations(
$index,
$target instanceof LocationCreateStruct,
$contentId,
$persistence["contentInfos"][$index]
);
}
}
else
{
$this->getPersistenceMock()
->expects( $this->at( 0 ) )
->method( "locationHandler" )
->will( $this->returnValue( $this->locationHandlerMock ) );
$this->locationHandlerMock
->expects( $this->once() )
->method(
$object instanceof ContentInfo && $object->published ?
"loadLocationsByContent" :
"loadParentLocationsForDraftContent"
)
->with( $object->id )
->will( $this->returnValue( $persistence["locations"] ) );
foreach ( $persistence["locations"] as $index => $location )
{
$this->assertContentHandlerExpectations(
$index,
true,
$location->contentId,
$persistence["contentInfos"][$index]
);
}
}
$value = $limitationType->evaluate(
$limitation,
$userMock,
$object,
$targets
);
self::assertInternalType( 'boolean', $value );
self::assertEquals( $expected, $value );
}
/**
* @return array
*/
public function providerForTestEvaluateInvalidArgument()
{
return array(
// invalid limitation
array(
'limitation' => new ObjectStateLimitation(),
'object' => new ContentInfo(),
'targets' => array( new Location() ),
'persistence' => array(),
),
// invalid object
array(
'limitation' => new ParentContentTypeLimitation(),
'object' => new ObjectStateLimitation(),
'targets' => array(),
'persistence' => array(),
),
// invalid target when using ContentCreateStruct
array(
'limitation' => new ParentContentTypeLimitation(),
'object' => new ContentCreateStruct(),
'targets' => array( new Location() ),
'persistence' => array(),
),
// invalid target when not using ContentCreateStruct
array(
'limitation' => new ParentContentTypeLimitation(),
'object' => new ContentInfo(),
'targets' => array( new ObjectStateLimitation() ),
'persistence' => array(),
),
);
}
/**
* @dataProvider providerForTestEvaluateInvalidArgument
* @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
*/
public function testEvaluateInvalidArgument( Limitation $limitation, ValueObject $object, $targets )
{
// Need to create inline instead of depending on testConstruct() to get correct mock instance
$limitationType = $this->testConstruct();
$userMock = $this->getUserMock();
$userMock
->expects( $this->never() )
->method( $this->anything() );
$persistenceMock = $this->getPersistenceMock();
$persistenceMock
->expects( $this->never() )
->method( $this->anything() );
$limitationType->evaluate(
$limitation,
$userMock,
$object,
$targets
);
}
/**
* @depends testConstruct
* @expectedException \eZ\Publish\API\Repository\Exceptions\NotImplementedException
*
* @param \eZ\Publish\Core\Limitation\ParentContentTypeLimitationType $limitationType
*/
public function testGetCriterionInvalidValue( ParentContentTypeLimitationType $limitationType )
{
$limitationType->getCriterion(
new ParentContentTypeLimitation( array() ),
$this->getUserMock()
);
}
/**
* @depends testConstruct
*
* @param \eZ\Publish\Core\Limitation\ParentContentTypeLimitationType $limitationType
*/
public function testValueSchema( ParentContentTypeLimitationType $limitationType )
{
$this->markTestIncomplete( "Method is not implemented yet: " . __METHOD__ );
}
}
| Java |
package Lacuna::DB::Result::Building::SSLa;
use Moose;
use utf8;
no warnings qw(uninitialized);
extends 'Lacuna::DB::Result::Building';
use Lacuna::Constants qw(ORE_TYPES INFLATION);
around 'build_tags' => sub {
my ($orig, $class) = @_;
return ($orig->($class), qw(Construction Ships));
};
use constant university_prereq => 20;
use constant max_instances_per_planet => 1;
use constant controller_class => 'Lacuna::RPC::Building::SSLa';
use constant image => 'ssla';
use constant name => 'Space Station Lab (A)';
use constant food_to_build => 230;
use constant energy_to_build => 350;
use constant ore_to_build => 370;
use constant water_to_build => 260;
use constant waste_to_build => 100;
use constant time_to_build => 60 * 2;
use constant food_consumption => 5;
use constant energy_consumption => 20;
use constant ore_consumption => 15;
use constant water_consumption => 6;
use constant waste_production => 20;
before 'can_demolish' => sub {
my $self = shift;
my $sslb = $self->body->get_building_of_class('Lacuna::DB::Result::Building::SSLb');
if (defined $sslb) {
confess [1013, 'You have to demolish your Space Station Lab (B) before you can demolish your Space Station Lab (A).'];
}
};
before can_build => sub {
my $self = shift;
if ($self->x == 5 || $self->y == -5 || (($self->y == 1 || $self->y == 0) && ($self->x == -1 || $self->x == 0))) {
confess [1009, 'Space Station Lab cannot be placed in that location.'];
}
};
sub makeable_plans {
return {
command => 'Lacuna::DB::Result::Building::Module::StationCommand',
ibs => 'Lacuna::DB::Result::Building::Module::IBS',
art => 'Lacuna::DB::Result::Building::Module::ArtMuseum',
opera => 'Lacuna::DB::Result::Building::Module::OperaHouse',
food => 'Lacuna::DB::Result::Building::Module::CulinaryInstitute',
parliament => 'Lacuna::DB::Result::Building::Module::Parliament',
warehouse => 'Lacuna::DB::Result::Building::Module::Warehouse',
policestation => 'Lacuna::DB::Result::Building::Module::PoliceStation',
};
}
sub makeable_plans_formatted {
my $self = shift;
my @out;
my $makeable_plans = $self->makeable_plans;
while (my ($type, $class) = each %{$makeable_plans}) {
push @out, {
image => $class->image,
name => $class->name,
url => $class->controller_class->app_url,
type => $type,
};
}
@out = sort { $a->{name} cmp $b->{name} } @out;
return \@out;
}
sub level_costs_formatted {
my $self = shift;
my $max = $self->max_level;
return [] if $max == 0;
my @costs;
my $resource_cost = $self->plan_resource_cost;
my $time_cost = $self->plan_time_cost;
foreach my $level (1..$max) {
my $resource = $self->plan_cost_at_level($level, $resource_cost);
push @costs, {
level => $level,
ore => $resource,
water => $resource,
energy => $resource,
food => $resource,
waste => sprintf('%.0f', $resource/2),
time => $self->plan_time_at_level($level, $time_cost),
};
}
return \@costs;
}
has plan_resource_cost => (
is => 'rw',
lazy => 1,
default => sub {
my $self = shift;
return 850_000;
}
);
has plan_time_cost => (
is => 'rw',
lazy => 1,
default => sub {
my $self = shift;
return 150;
}
);
sub plan_time_at_level {
my ($self, $level, $base) = @_;
my $inflate = INFLATION - (($self->max_level + $self->body->empire->effective_manufacturing_affinity * 5)/200);
my $time_cost = int($base * ($inflate ** $level));
$time_cost = 15 if ($time_cost < 15);
$time_cost = 5184000 if ($time_cost > 5184000);
return $time_cost;
}
sub plan_cost_at_level {
my ($self, $level, $base) = @_;
my $inflate = INFLATION - (($self->max_level + $self->body->empire->effective_research_affinity * 5)/200);
my $cost = int($base * ($inflate ** $level));
return $cost;
}
has max_level => (
is => 'rw',
lazy => 1,
default => sub {
my $self = shift;
my $level = $self->effective_level;
my $body = $self->body;
foreach my $part (qw(b c d)) {
my $building = $body->get_building_of_class('Lacuna::DB::Result::Building::SSL'.$part);
if (defined $building) {
$level = ($level > $building->effective_level) ? $building->effective_level : $level;
}
else {
$level = 0;
last;
}
}
return $level;
},
);
sub can_make_plan {
my ($self, $type, $level) = @_;
if ($self->is_working) {
confess [1010, 'The Space Station Lab is already making a plan.'];
}
$level ||= 1;
if ($level > $self->max_level) {
confess [1013, 'This Space Station Lab is not a high enough level to make that plan.'];
}
my $makeable = $self->makeable_plans;
unless ($type ~~ [keys %{$makeable}]) {
confess [1009, 'Cannot make that type of plan.'];
}
my $resource_cost = $self->plan_cost_at_level($level, $self->plan_resource_cost);
my $fraction = sprintf('%.0f',$resource_cost * 0.01);
my $body = $self->body;
foreach my $ore (ORE_TYPES) {
if ($body->type_stored($ore) < $fraction) {
confess [1011, 'Not enough '.$ore.' in storage. You need at least '.$fraction.'.'];
}
}
foreach my $resource (qw(ore water food energy)) {
if ($body->type_stored($resource) < $resource_cost) {
confess [1011, 'Not enough '.$resource.' in storage. You need at least '.$resource_cost.'.'];
}
}
return 1;
}
sub make_plan {
my ($self, $type, $level) = @_;
$level ||= 1;
my $makeable = $self->makeable_plans;
my $resource_cost = $self->plan_cost_at_level($level, $self->plan_resource_cost);
my $time_cost = $self->plan_time_at_level($level, $self->plan_time_cost);
my $body = $self->body;
$body->spend_ore($resource_cost);
$body->spend_water($resource_cost);
$body->spend_food($resource_cost, 0);
$body->spend_energy($resource_cost);
$body->add_waste($resource_cost/4);
$body->update;
$self->start_work({
class => $makeable->{$type},
level => $level,
}, $time_cost)->update;
}
before finish_work => sub {
my $self = shift;
my $planet = $self->body;
$planet->add_plan($self->work->{class}, $self->work->{level});
};
no Moose;
__PACKAGE__->meta->make_immutable(inline_constructor => 0);
| Java |
<?php
/**
* @version $Id: imgmanager.php 46 2009-05-26 16:59:42Z happynoodleboy $
* @package JCE
* @copyright Copyright (C) 2005 - 2009 Ryan Demmer. All rights reserved.
* @author Ryan Demmer
* @license GNU/GPL
* JCE is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*/
defined('_JEXEC') or die('Restricted access');
require_once(JCE_LIBRARIES .DS. 'classes' .DS. 'manager.php');
class ImageManager extends Manager
{
var $_ext = 'image=jpg,jpeg,gif,png';
/**
* @access protected
*/
function __construct()
{
parent::__construct();
// Set the file type map from parameters
$this->setFileTypes($this->getPluginParam('imgmanager_extensions', $this->_ext));
// Init plugin
$this->init();
}
/**
* Returns a reference to a editor object
*
* This method must be invoked as:
* <pre> $browser = &JCE::getInstance();</pre>
*
* @access public
* @return JCE The editor object.
* @since 1.5
*/
function &getInstance()
{
static $instance;
if (!is_object($instance)) {
$instance = new ImageManager();
}
return $instance;
}
/**
* Initialise the plugin
*/
function init()
{
// check the user/group has editor permissions
$this->checkPlugin() or die(JError::raiseError(403, JText::_('Access Forbidden')));
parent::init();
// Setup plugin XHR callback functions
$this->setXHR(array($this, 'getDimensions'));
// Set javascript file array
$this->script(array('imgmanager'), 'plugins');
// Set css file array
$this->css(array('imgmanager'), 'plugins');
// Load extensions if any
$this->loadExtensions();
}
/**
* Get the dimensions of an image
* @return array Dimensions as array
* @param object $file Relative path to image
*/
function getDimensions($file)
{
$path = Utils::makePath($this->getBaseDir(), rawurldecode($file));
$h = array(
'width' => '',
'height' => ''
);
if (file_exists($path)) {
$dim = @getimagesize($path);
$h = array(
'width' => $dim[0],
'height' => $dim[1]
);
}
return $h;
}
/**
* Get list of uploadable extensions
* @return Mapped extension list (list mapped to type object eg: 'images', 'jpeg,jpg,gif,png')
*/
function getUploadFileTypes()
{
$list = $this->getPluginParam('imgmanager_extensions', 'image=jpg,jpeg,gif,png');
return $this->mapUploadFileTypes($list);
}
}
?> | Java |
/* $Id: fileaio.h $ */
/** @file
* IPRT - Internal RTFileAio header.
*/
/*
* Copyright (C) 2009-2015 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.
*/
#ifndef ___internal_fileaio_h
#define ___internal_fileaio_h
#include <iprt/file.h>
#include "internal/magics.h"
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
/**
* Defined request states.
*/
typedef enum RTFILEAIOREQSTATE
{
/** Prepared. */
RTFILEAIOREQSTATE_PREPARED = 0,
/** Submitted. */
RTFILEAIOREQSTATE_SUBMITTED,
/** Completed. */
RTFILEAIOREQSTATE_COMPLETED,
/** Omni present 32bit hack. */
RTFILEAIOREQSTATE_32BIT_HACK = 0x7fffffff
} RTFILEAIOREQSTATE;
/*******************************************************************************
* Defined Constants And Macros *
*******************************************************************************/
/** Return true if the specified request is not valid, false otherwise. */
#define RTFILEAIOREQ_IS_NOT_VALID(pReq) \
(RT_UNLIKELY(!VALID_PTR(pReq) || (pReq->u32Magic != RTFILEAIOREQ_MAGIC)))
/** Validates a context handle and returns VERR_INVALID_HANDLE if not valid. */
#define RTFILEAIOREQ_VALID_RETURN_RC(pReq, rc) \
do { \
AssertPtrReturn((pReq), (rc)); \
AssertReturn((pReq)->u32Magic == RTFILEAIOREQ_MAGIC, (rc)); \
} while (0)
/** Validates a context handle and returns VERR_INVALID_HANDLE if not valid. */
#define RTFILEAIOREQ_VALID_RETURN(pReq) RTFILEAIOREQ_VALID_RETURN_RC((pReq), VERR_INVALID_HANDLE)
/** Validates a context handle and returns (void) if not valid. */
#define RTFILEAIOREQ_VALID_RETURN_VOID(pReq) \
do { \
AssertPtrReturnVoid(pReq); \
AssertReturnVoid((pReq)->u32Magic == RTFILEAIOREQ_MAGIC); \
} while (0)
/** Validates a context handle and returns the specified rc if not valid. */
#define RTFILEAIOCTX_VALID_RETURN_RC(pCtx, rc) \
do { \
AssertPtrReturn((pCtx), (rc)); \
AssertReturn((pCtx)->u32Magic == RTFILEAIOCTX_MAGIC, (rc)); \
} while (0)
/** Validates a context handle and returns VERR_INVALID_HANDLE if not valid. */
#define RTFILEAIOCTX_VALID_RETURN(pCtx) RTFILEAIOCTX_VALID_RETURN_RC((pCtx), VERR_INVALID_HANDLE)
/** Checks if a request is in the specified state and returns the specified rc if not. */
#define RTFILEAIOREQ_STATE_RETURN_RC(pReq, State, rc) \
do { \
if (RT_UNLIKELY(pReq->enmState != RTFILEAIOREQSTATE_##State)) \
return rc; \
} while (0)
/** Checks if a request is not in the specified state and returns the specified rc if it is. */
#define RTFILEAIOREQ_NOT_STATE_RETURN_RC(pReq, State, rc) \
do { \
if (RT_UNLIKELY(pReq->enmState == RTFILEAIOREQSTATE_##State)) \
return rc; \
} while (0)
/** Checks if a request in the given states and sserts if not. */
#define RTFIELAIOREQ_ASSERT_STATE(pReq, State) \
do { \
AssertPtr((pReq)); \
Assert((pReq)->u32Magic == RTFILEAIOREQ_MAGIC); \
Assert((pReq)->enmState == RTFILEAIOREQSTATE_##State); \
} while (0)
/** Sets the request into a specific state. */
#define RTFILEAIOREQ_SET_STATE(pReq, State) \
do { \
pReq->enmState = RTFILEAIOREQSTATE_##State; \
} while (0)
RT_C_DECLS_BEGIN
RT_C_DECLS_END
#endif
| Java |
/*
EventON Generate Google maps function
*/
(function($){
$.fn.evoGenmaps = function(opt){
var defaults = {
delay: 0,
fnt: 1,
cal: '',
mapSpotId: '',
_action:''
};
var options = $.extend({}, defaults, opt);
var geocoder;
// popup lightbox generation
if(options._action=='lightbox'){
var cur_window_top = parseInt($(window).scrollTop()) + 50;
$('.evo_popin').css({'margin-top':cur_window_top});
$('.evo_pop_body').html('');
var event_list = this.closest('.eventon_events_list');
var content = this.siblings('.event_description').html();
var content_front = this.html();
var _content = $(content).not('.evcal_close');
// RTL
if(event_list.hasClass('evortl')){
$('.evo_popin').addClass('evortl');
}
$('.evo_pop_body').append('<div class="evopop_top">'+content_front+'</div>').append(_content);
var this_map = $('.evo_pop_body').find('.evcal_gmaps');
var idd = this_map.attr('id');
this_map.attr({'id':idd+'_evop'});
$('.evo_popup').fadeIn(300);
$('.evo_popbg').fadeIn(300);
// check if gmaps should run
if( this.attr('data-gmtrig')=='1' && this.attr('data-gmap_status')!='null'){
var cal = this.closest('div.ajde_evcal_calendar ');
loadl_gmaps_in(this, cal, idd+'_evop');
}
}
// functions
if(options.fnt==1){
this.each(function(){
var eventcard = $(this).attr('eventcard');
if(eventcard=='1'){
$(this).find('a.desc_trig').each(function(elm){
//$(this).siblings('.event_description').slideDown();
var obj = $(this);
if(options.delay==0){
load_googlemaps_here(obj);
}else{
setTimeout(load_googlemaps_here, options.delay, obj);
}
});
}
});
}
if(options.fnt==2){
if(options.delay==0){
load_googlemaps_here(this);
}else{
setTimeout(load_googlemaps_here, options.delay, this);
}
}
if(options.fnt==3){
loadl_gmaps_in(this, options.cal, '');
}
// gmaps on popup
if(options.fnt==4){
// check if gmaps should run
if( this.attr('data-gmtrig')=='1' && this.attr('data-gmap_status')!='null'){
var cal = this.closest('div.ajde_evcal_calendar ');
loadl_gmaps_in(this, cal, options.mapSpotId);
}
}
// function to load google maps for eventcard
function load_googlemaps_here(obj){
if( obj.data('gmstat')!= '1'){
obj.attr({'data-gmstat':'1'});
}
var cal = obj.closest('div.ajde_evcal_calendar ');
if( obj.attr('data-gmtrig')=='1' && obj.attr('data-gmap_status')!='null'){
loadl_gmaps_in(obj, cal, '');
}
}
// Load the google map on the object
function loadl_gmaps_in(obj, cal, mapId){
var evodata = cal.find('.evo-data');
var mapformat = evodata.data('mapformat');
var ev_location = obj.find('.evcal_desc');
var location_type = ev_location.attr('data-location_type');
if(location_type=='address'){
var address = ev_location.attr('data-location_address');
var location_type = 'add';
}else{
var address = ev_location.attr('data-latlng');
var location_type = 'latlng';
}
var map_canvas_id= (mapId!=='')?
mapId:
obj.siblings('.event_description').find('.evcal_gmaps').attr('id');
// google maps styles
// @since 2.2.22
var styles = '';
if(gmapstyles != 'default'){
styles = $.parseJSON(gmapstyles);
}
var zoom = evodata.data('mapzoom');
var zoomlevel = (typeof zoom !== 'undefined' && zoom !== false)? parseInt(zoom):12;
var scroll = evodata.data('mapscroll');
//console.log(map_canvas_id+' '+mapformat+' '+ location_type +' '+scroll +' '+ address);
//obj.siblings('.event_description').find('.evcal_gmaps').html(address);
initialize(map_canvas_id, address, mapformat, zoomlevel, location_type, scroll, styles);
}
//console.log(options);
};
}(jQuery)); | Java |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_admin
*
* @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Script file of Joomla CMS
*
* @since 1.6.4
*/
class JoomlaInstallerScript
{
/**
* Method to update Joomla!
*
* @param JInstallerAdapterFile $installer The class calling this method
*
* @return void
*/
public function update($installer)
{
$options['format'] = '{DATE}\t{TIME}\t{LEVEL}\t{CODE}\t{MESSAGE}';
$options['text_file'] = 'joomla_update.php';
JLog::addLogger($options, JLog::INFO, array('Update', 'databasequery', 'jerror'));
JLog::add(JText::_('COM_JOOMLAUPDATE_UPDATE_LOG_DELETE_FILES'), JLog::INFO, 'Update');
// This needs to stay for 2.5 update compatibility
$this->deleteUnexistingFiles();
$this->updateManifestCaches();
$this->updateDatabase();
$this->clearRadCache();
$this->updateAssets();
$this->clearStatsCache();
$this->convertTablesToUtf8mb4(true);
$this->cleanJoomlaCache();
// VERY IMPORTANT! THIS METHOD SHOULD BE CALLED LAST, SINCE IT COULD
// LOGOUT ALL THE USERS
$this->flushSessions();
}
/**
* Method to clear our stats plugin cache to ensure we get fresh data on Joomla Update
*
* @return void
*
* @since 3.5
*/
protected function clearStatsCache()
{
$db = JFactory::getDbo();
try
{
// Get the params for the stats plugin
$params = $db->setQuery(
$db->getQuery(true)
->select($db->quoteName('params'))
->from($db->quoteName('#__extensions'))
->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
->where($db->quoteName('folder') . ' = ' . $db->quote('system'))
->where($db->quoteName('element') . ' = ' . $db->quote('stats'))
)->loadResult();
}
catch (Exception $e)
{
echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />';
return;
}
$params = json_decode($params, true);
// Reset the last run parameter
if (isset($params['lastrun']))
{
$params['lastrun'] = '';
}
$params = json_encode($params);
$query = $db->getQuery(true)
->update($db->quoteName('#__extensions'))
->set($db->quoteName('params') . ' = ' . $db->quote($params))
->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
->where($db->quoteName('folder') . ' = ' . $db->quote('system'))
->where($db->quoteName('element') . ' = ' . $db->quote('stats'));
try
{
$db->setQuery($query)->execute();
}
catch (Exception $e)
{
echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />';
return;
}
}
/**
* Method to update Database
*
* @return void
*/
protected function updateDatabase()
{
$db = JFactory::getDbo();
if (strpos($db->name, 'mysql') !== false)
{
$this->updateDatabaseMysql();
}
$this->uninstallEosPlugin();
}
/**
* Method to update MySQL Database
*
* @return void
*/
protected function updateDatabaseMysql()
{
$db = JFactory::getDbo();
$db->setQuery('SHOW ENGINES');
try
{
$results = $db->loadObjectList();
}
catch (Exception $e)
{
echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />';
return;
}
foreach ($results as $result)
{
if ($result->Support != 'DEFAULT')
{
continue;
}
$db->setQuery('ALTER TABLE #__update_sites_extensions ENGINE = ' . $result->Engine);
try
{
$db->execute();
}
catch (Exception $e)
{
echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />';
return;
}
break;
}
}
/**
* Uninstall the 2.5 EOS plugin
*
* @return void
*/
protected function uninstallEosPlugin()
{
$db = JFactory::getDbo();
// Check if the 2.5 EOS plugin is present and uninstall it if so
$id = $db->setQuery(
$db->getQuery(true)
->select('extension_id')
->from('#__extensions')
->where('name = ' . $db->quote('PLG_EOSNOTIFY'))
)->loadResult();
if (!$id)
{
return;
}
// We need to unprotect the plugin so we can uninstall it
$db->setQuery(
$db->getQuery(true)
->update('#__extensions')
->set('protected = 0')
->where($db->quoteName('extension_id') . ' = ' . $id)
)->execute();
$installer = new JInstaller;
$installer->uninstall('plugin', $id);
}
/**
* Update the manifest caches
*
* @return void
*/
protected function updateManifestCaches()
{
$extensions = array(
// Components
// `type`, `element`, `folder`, `client_id`
array('component', 'com_mailto', '', 0),
array('component', 'com_wrapper', '', 0),
array('component', 'com_admin', '', 1),
array('component', 'com_ajax', '', 1),
array('component', 'com_banners', '', 1),
array('component', 'com_cache', '', 1),
array('component', 'com_categories', '', 1),
array('component', 'com_checkin', '', 1),
array('component', 'com_contact', '', 1),
array('component', 'com_cpanel', '', 1),
array('component', 'com_installer', '', 1),
array('component', 'com_languages', '', 1),
array('component', 'com_login', '', 1),
array('component', 'com_media', '', 1),
array('component', 'com_menus', '', 1),
array('component', 'com_messages', '', 1),
array('component', 'com_modules', '', 1),
array('component', 'com_newsfeeds', '', 1),
array('component', 'com_plugins', '', 1),
array('component', 'com_search', '', 1),
array('component', 'com_templates', '', 1),
array('component', 'com_content', '', 1),
array('component', 'com_config', '', 1),
array('component', 'com_redirect', '', 1),
array('component', 'com_users', '', 1),
array('component', 'com_finder', '', 1),
array('component', 'com_tags', '', 1),
array('component', 'com_contenthistory', '', 1),
array('component', 'com_postinstall', '', 1),
array('component', 'com_joomlaupdate', '', 1),
// Libraries
array('library', 'phputf8', '', 0),
array('library', 'joomla', '', 0),
array('library', 'idna_convert', '', 0),
array('library', 'fof', '', 0),
array('library', 'phpass', '', 0),
// Modules
// - Site
array('module', 'mod_articles_archive', '', 0),
array('module', 'mod_articles_latest', '', 0),
array('module', 'mod_articles_popular', '', 0),
array('module', 'mod_banners', '', 0),
array('module', 'mod_breadcrumbs', '', 0),
array('module', 'mod_custom', '', 0),
array('module', 'mod_feed', '', 0),
array('module', 'mod_footer', '', 0),
array('module', 'mod_login', '', 0),
array('module', 'mod_menu', '', 0),
array('module', 'mod_articles_news', '', 0),
array('module', 'mod_random_image', '', 0),
array('module', 'mod_related_items', '', 0),
array('module', 'mod_search', '', 0),
array('module', 'mod_stats', '', 0),
array('module', 'mod_syndicate', '', 0),
array('module', 'mod_users_latest', '', 0),
array('module', 'mod_whosonline', '', 0),
array('module', 'mod_wrapper', '', 0),
array('module', 'mod_articles_category', '', 0),
array('module', 'mod_articles_categories', '', 0),
array('module', 'mod_languages', '', 0),
array('module', 'mod_tags_popular', '', 0),
array('module', 'mod_tags_similar', '', 0),
// - Administrator
array('module', 'mod_custom', '', 1),
array('module', 'mod_feed', '', 1),
array('module', 'mod_latest', '', 1),
array('module', 'mod_logged', '', 1),
array('module', 'mod_login', '', 1),
array('module', 'mod_menu', '', 1),
array('module', 'mod_popular', '', 1),
array('module', 'mod_quickicon', '', 1),
array('module', 'mod_stats_admin', '', 1),
array('module', 'mod_status', '', 1),
array('module', 'mod_submenu', '', 1),
array('module', 'mod_title', '', 1),
array('module', 'mod_toolbar', '', 1),
array('module', 'mod_multilangstatus', '', 1),
// Plugins
array('plugin', 'gmail', 'authentication', 0),
array('plugin', 'joomla', 'authentication', 0),
array('plugin', 'ldap', 'authentication', 0),
array('plugin', 'contact', 'content', 0),
array('plugin', 'emailcloak', 'content', 0),
array('plugin', 'loadmodule', 'content', 0),
array('plugin', 'pagebreak', 'content', 0),
array('plugin', 'pagenavigation', 'content', 0),
array('plugin', 'vote', 'content', 0),
array('plugin', 'codemirror', 'editors', 0),
array('plugin', 'none', 'editors', 0),
array('plugin', 'tinymce', 'editors', 0),
array('plugin', 'article', 'editors-xtd', 0),
array('plugin', 'image', 'editors-xtd', 0),
array('plugin', 'pagebreak', 'editors-xtd', 0),
array('plugin', 'readmore', 'editors-xtd', 0),
array('plugin', 'categories', 'search', 0),
array('plugin', 'contacts', 'search', 0),
array('plugin', 'content', 'search', 0),
array('plugin', 'newsfeeds', 'search', 0),
array('plugin', 'tags', 'search', 0),
array('plugin', 'languagefilter', 'system', 0),
array('plugin', 'p3p', 'system', 0),
array('plugin', 'cache', 'system', 0),
array('plugin', 'debug', 'system', 0),
array('plugin', 'log', 'system', 0),
array('plugin', 'redirect', 'system', 0),
array('plugin', 'remember', 'system', 0),
array('plugin', 'sef', 'system', 0),
array('plugin', 'logout', 'system', 0),
array('plugin', 'contactcreator', 'user', 0),
array('plugin', 'joomla', 'user', 0),
array('plugin', 'profile', 'user', 0),
array('plugin', 'joomla', 'extension', 0),
array('plugin', 'joomla', 'content', 0),
array('plugin', 'languagecode', 'system', 0),
array('plugin', 'joomlaupdate', 'quickicon', 0),
array('plugin', 'extensionupdate', 'quickicon', 0),
array('plugin', 'recaptcha', 'captcha', 0),
array('plugin', 'categories', 'finder', 0),
array('plugin', 'contacts', 'finder', 0),
array('plugin', 'content', 'finder', 0),
array('plugin', 'newsfeeds', 'finder', 0),
array('plugin', 'tags', 'finder', 0),
array('plugin', 'totp', 'twofactorauth', 0),
array('plugin', 'yubikey', 'twofactorauth', 0),
array('plugin', 'updatenotification', 'system', 0),
array('plugin', 'module', 'editors-xtd', 0),
array('plugin', 'stats', 'system', 0),
array('plugin', 'packageinstaller', 'installer', 0),
array('plugin', 'folderinstaller', 'installer', 0),
array('plugin', 'urlinstaller', 'installer', 0),
array('plugin', 'phpversioncheck', 'quickicon', 0),
array('plugin', 'menu', 'editors-xtd', 0),
array('plugin', 'contact', 'editors-xtd', 0),
// Templates
array('template', 'beez3', '', 0),
array('template', 'hathor', '', 1),
array('template', 'protostar', '', 0),
array('template', 'isis', '', 1),
// Languages
array('language', 'en-GB', '', 0),
array('language', 'en-GB', '', 1),
// Files
array('file', 'joomla', '', 0),
// Packages
array('package', 'pkg_en-GB', '', 0),
);
// Attempt to refresh manifest caches
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select('*')
->from('#__extensions');
foreach ($extensions as $extension)
{
$query->where(
'type=' . $db->quote($extension[0])
. ' AND element=' . $db->quote($extension[1])
. ' AND folder=' . $db->quote($extension[2])
. ' AND client_id=' . $extension[3], 'OR'
);
}
$db->setQuery($query);
try
{
$extensions = $db->loadObjectList();
}
catch (Exception $e)
{
echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />';
return;
}
$installer = new JInstaller;
foreach ($extensions as $extension)
{
if (!$installer->refreshManifestCache($extension->extension_id))
{
echo JText::sprintf('FILES_JOOMLA_ERROR_MANIFEST', $extension->type, $extension->element, $extension->name, $extension->client_id) . '<br />';
}
}
}
/**
* Delete files that should not exist
*
* @return void
*/
public function deleteUnexistingFiles()
{
$files = array(
// Joomla 1.6 - 1.7 - 2.5
'/libraries/cms/cmsloader.php',
'/libraries/joomla/database/databaseexception.php',
'/libraries/joomla/database/databasequery.php',
'/libraries/joomla/environment/response.php',
'/libraries/joomla/form/fields/templatestyle.php',
'/libraries/joomla/form/fields/user.php',
'/libraries/joomla/form/fields/menu.php',
'/libraries/joomla/form/fields/helpsite.php',
'/libraries/joomla/github/gists.php',
'/libraries/joomla/github/issues.php',
'/libraries/joomla/github/pulls.php',
'/libraries/joomla/log/logentry.php',
'/administrator/components/com_admin/sql/updates/mysql/1.7.0.sql',
'/administrator/components/com_admin/sql/updates/sqlsrv/2.5.2-2012-03-05.sql',
'/administrator/components/com_admin/sql/updates/sqlsrv/2.5.3-2012-03-13.sql',
'/administrator/components/com_admin/sql/updates/sqlsrv/index.html',
'/administrator/components/com_content/models/fields/filters.php',
'/administrator/components/com_users/controllers/config.php',
'/administrator/components/com_users/helpers/levels.php',
'/administrator/language/en-GB/en-GB.plg_system_finder.ini',
'/administrator/language/en-GB/en-GB.plg_system_finder.sys.ini',
'/administrator/modules/mod_quickicon/tmpl/default_button.php',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlist/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autolink/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autoresize/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/contextmenu/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/directionality/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullscreen/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/iespell/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/insertdatetime/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/layer/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/lists/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/nonbreaking/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/noneditable/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/pagebreak/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/print/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/save/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/tabfocus/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/visualchars/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/wordcount/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/editor_template_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/editor_template_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/tiny_mce_src.js',
'/media/com_finder/images/calendar.png',
'/media/com_finder/images/mime/index.html',
'/media/com_finder/images/mime/pdf.png',
'/components/com_media/controller.php',
'/components/com_media/helpers/index.html',
'/components/com_media/helpers/media.php',
// Joomla 3.0
'/administrator/components/com_admin/sql/updates/mysql/1.7.0-2011-06-06-2.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.0-2011-06-06.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.0.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-15-2.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-15-3.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-15-4.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-15.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-17.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-20.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.3-2011-10-15.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.3-2011-10-19.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.3-2011-11-10.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.4-2011-11-19.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.4-2011-11-23.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.4-2011-12-12.sql',
'/administrator/components/com_admin/views/sysinfo/tmpl/default_navigation.php',
'/administrator/components/com_categories/config.xml',
'/administrator/components/com_categories/helpers/categoriesadministrator.php',
'/administrator/components/com_contact/elements/contact.php',
'/administrator/components/com_contact/elements/index.html',
'/administrator/components/com_content/elements/article.php',
'/administrator/components/com_content/elements/author.php',
'/administrator/components/com_content/elements/index.html',
'/administrator/components/com_installer/models/fields/client.php',
'/administrator/components/com_installer/models/fields/group.php',
'/administrator/components/com_installer/models/fields/index.html',
'/administrator/components/com_installer/models/fields/search.php',
'/administrator/components/com_installer/models/forms/index.html',
'/administrator/components/com_installer/models/forms/manage.xml',
'/administrator/components/com_installer/views/install/tmpl/default_form.php',
'/administrator/components/com_installer/views/manage/tmpl/default_filter.php',
'/administrator/components/com_languages/views/installed/tmpl/default_ftp.php',
'/administrator/components/com_languages/views/installed/tmpl/default_navigation.php',
'/administrator/components/com_modules/models/fields/index.html',
'/administrator/components/com_modules/models/fields/moduleorder.php',
'/administrator/components/com_modules/models/fields/moduleposition.php',
'/administrator/components/com_newsfeeds/elements/index.html',
'/administrator/components/com_newsfeeds/elements/newsfeed.php',
'/administrator/components/com_templates/views/prevuuw/index.html',
'/administrator/components/com_templates/views/prevuuw/tmpl/default.php',
'/administrator/components/com_templates/views/prevuuw/tmpl/index.html',
'/administrator/components/com_templates/views/prevuuw/view.html.php',
'/administrator/includes/menu.php',
'/administrator/includes/router.php',
'/administrator/manifests/packages/pkg_joomla.xml',
'/administrator/modules/mod_submenu/helper.php',
'/administrator/templates/hathor/css/ie6.css',
'/administrator/templates/hathor/html/mod_submenu/index.html',
'/administrator/templates/hathor/html/mod_submenu/default.php',
'/components/com_media/controller.php',
'/components/com_media/helpers/index.html',
'/components/com_media/helpers/media.php',
'/includes/menu.php',
'/includes/pathway.php',
'/includes/router.php',
'/language/en-GB/en-GB.pkg_joomla.sys.ini',
'/libraries/cms/controller/index.html',
'/libraries/cms/controller/legacy.php',
'/libraries/cms/model/index.html',
'/libraries/cms/model/legacy.php',
'/libraries/cms/schema/changeitemmysql.php',
'/libraries/cms/schema/changeitemsqlazure.php',
'/libraries/cms/schema/changeitemsqlsrv.php',
'/libraries/cms/view/index.html',
'/libraries/cms/view/legacy.php',
'/libraries/joomla/application/application.php',
'/libraries/joomla/application/categories.php',
'/libraries/joomla/application/cli/daemon.php',
'/libraries/joomla/application/cli/index.html',
'/libraries/joomla/application/component/controller.php',
'/libraries/joomla/application/component/controlleradmin.php',
'/libraries/joomla/application/component/controllerform.php',
'/libraries/joomla/application/component/helper.php',
'/libraries/joomla/application/component/index.html',
'/libraries/joomla/application/component/model.php',
'/libraries/joomla/application/component/modeladmin.php',
'/libraries/joomla/application/component/modelform.php',
'/libraries/joomla/application/component/modelitem.php',
'/libraries/joomla/application/component/modellist.php',
'/libraries/joomla/application/component/view.php',
'/libraries/joomla/application/helper.php',
'/libraries/joomla/application/input.php',
'/libraries/joomla/application/input/cli.php',
'/libraries/joomla/application/input/cookie.php',
'/libraries/joomla/application/input/files.php',
'/libraries/joomla/application/input/index.html',
'/libraries/joomla/application/menu.php',
'/libraries/joomla/application/module/helper.php',
'/libraries/joomla/application/module/index.html',
'/libraries/joomla/application/pathway.php',
'/libraries/joomla/application/web/webclient.php',
'/libraries/joomla/base/node.php',
'/libraries/joomla/base/object.php',
'/libraries/joomla/base/observable.php',
'/libraries/joomla/base/observer.php',
'/libraries/joomla/base/tree.php',
'/libraries/joomla/cache/storage/eaccelerator.php',
'/libraries/joomla/cache/storage/helpers/helper.php',
'/libraries/joomla/cache/storage/helpers/index.html',
'/libraries/joomla/database/database/index.html',
'/libraries/joomla/database/database/mysql.php',
'/libraries/joomla/database/database/mysqlexporter.php',
'/libraries/joomla/database/database/mysqli.php',
'/libraries/joomla/database/database/mysqliexporter.php',
'/libraries/joomla/database/database/mysqliimporter.php',
'/libraries/joomla/database/database/mysqlimporter.php',
'/libraries/joomla/database/database/mysqliquery.php',
'/libraries/joomla/database/database/mysqlquery.php',
'/libraries/joomla/database/database/sqlazure.php',
'/libraries/joomla/database/database/sqlazurequery.php',
'/libraries/joomla/database/database/sqlsrv.php',
'/libraries/joomla/database/database/sqlsrvquery.php',
'/libraries/joomla/database/exception.php',
'/libraries/joomla/database/table.php',
'/libraries/joomla/database/table/asset.php',
'/libraries/joomla/database/table/category.php',
'/libraries/joomla/database/table/content.php',
'/libraries/joomla/database/table/extension.php',
'/libraries/joomla/database/table/index.html',
'/libraries/joomla/database/table/language.php',
'/libraries/joomla/database/table/menu.php',
'/libraries/joomla/database/table/menutype.php',
'/libraries/joomla/database/table/module.php',
'/libraries/joomla/database/table/session.php',
'/libraries/joomla/database/table/update.php',
'/libraries/joomla/database/table/user.php',
'/libraries/joomla/database/table/usergroup.php',
'/libraries/joomla/database/table/viewlevel.php',
'/libraries/joomla/database/tablenested.php',
'/libraries/joomla/environment/request.php',
'/libraries/joomla/environment/uri.php',
'/libraries/joomla/error/error.php',
'/libraries/joomla/error/exception.php',
'/libraries/joomla/error/index.html',
'/libraries/joomla/error/log.php',
'/libraries/joomla/error/profiler.php',
'/libraries/joomla/filesystem/archive.php',
'/libraries/joomla/filesystem/archive/bzip2.php',
'/libraries/joomla/filesystem/archive/gzip.php',
'/libraries/joomla/filesystem/archive/index.html',
'/libraries/joomla/filesystem/archive/tar.php',
'/libraries/joomla/filesystem/archive/zip.php',
'/libraries/joomla/form/fields/category.php',
'/libraries/joomla/form/fields/componentlayout.php',
'/libraries/joomla/form/fields/contentlanguage.php',
'/libraries/joomla/form/fields/editor.php',
'/libraries/joomla/form/fields/editors.php',
'/libraries/joomla/form/fields/media.php',
'/libraries/joomla/form/fields/menuitem.php',
'/libraries/joomla/form/fields/modulelayout.php',
'/libraries/joomla/html/editor.php',
'/libraries/joomla/html/html/access.php',
'/libraries/joomla/html/html/batch.php',
'/libraries/joomla/html/html/behavior.php',
'/libraries/joomla/html/html/category.php',
'/libraries/joomla/html/html/content.php',
'/libraries/joomla/html/html/contentlanguage.php',
'/libraries/joomla/html/html/date.php',
'/libraries/joomla/html/html/email.php',
'/libraries/joomla/html/html/form.php',
'/libraries/joomla/html/html/grid.php',
'/libraries/joomla/html/html/image.php',
'/libraries/joomla/html/html/index.html',
'/libraries/joomla/html/html/jgrid.php',
'/libraries/joomla/html/html/list.php',
'/libraries/joomla/html/html/menu.php',
'/libraries/joomla/html/html/number.php',
'/libraries/joomla/html/html/rules.php',
'/libraries/joomla/html/html/select.php',
'/libraries/joomla/html/html/sliders.php',
'/libraries/joomla/html/html/string.php',
'/libraries/joomla/html/html/tabs.php',
'/libraries/joomla/html/html/tel.php',
'/libraries/joomla/html/html/user.php',
'/libraries/joomla/html/pagination.php',
'/libraries/joomla/html/pane.php',
'/libraries/joomla/html/parameter.php',
'/libraries/joomla/html/parameter/element.php',
'/libraries/joomla/html/parameter/element/calendar.php',
'/libraries/joomla/html/parameter/element/category.php',
'/libraries/joomla/html/parameter/element/componentlayouts.php',
'/libraries/joomla/html/parameter/element/contentlanguages.php',
'/libraries/joomla/html/parameter/element/editors.php',
'/libraries/joomla/html/parameter/element/filelist.php',
'/libraries/joomla/html/parameter/element/folderlist.php',
'/libraries/joomla/html/parameter/element/helpsites.php',
'/libraries/joomla/html/parameter/element/hidden.php',
'/libraries/joomla/html/parameter/element/imagelist.php',
'/libraries/joomla/html/parameter/element/index.html',
'/libraries/joomla/html/parameter/element/languages.php',
'/libraries/joomla/html/parameter/element/list.php',
'/libraries/joomla/html/parameter/element/menu.php',
'/libraries/joomla/html/parameter/element/menuitem.php',
'/libraries/joomla/html/parameter/element/modulelayouts.php',
'/libraries/joomla/html/parameter/element/password.php',
'/libraries/joomla/html/parameter/element/radio.php',
'/libraries/joomla/html/parameter/element/spacer.php',
'/libraries/joomla/html/parameter/element/sql.php',
'/libraries/joomla/html/parameter/element/templatestyle.php',
'/libraries/joomla/html/parameter/element/text.php',
'/libraries/joomla/html/parameter/element/textarea.php',
'/libraries/joomla/html/parameter/element/timezones.php',
'/libraries/joomla/html/parameter/element/usergroup.php',
'/libraries/joomla/html/parameter/index.html',
'/libraries/joomla/html/toolbar.php',
'/libraries/joomla/html/toolbar/button.php',
'/libraries/joomla/html/toolbar/button/confirm.php',
'/libraries/joomla/html/toolbar/button/custom.php',
'/libraries/joomla/html/toolbar/button/help.php',
'/libraries/joomla/html/toolbar/button/index.html',
'/libraries/joomla/html/toolbar/button/link.php',
'/libraries/joomla/html/toolbar/button/popup.php',
'/libraries/joomla/html/toolbar/button/separator.php',
'/libraries/joomla/html/toolbar/button/standard.php',
'/libraries/joomla/html/toolbar/index.html',
'/libraries/joomla/image/filters/brightness.php',
'/libraries/joomla/image/filters/contrast.php',
'/libraries/joomla/image/filters/edgedetect.php',
'/libraries/joomla/image/filters/emboss.php',
'/libraries/joomla/image/filters/grayscale.php',
'/libraries/joomla/image/filters/index.html',
'/libraries/joomla/image/filters/negate.php',
'/libraries/joomla/image/filters/sketchy.php',
'/libraries/joomla/image/filters/smooth.php',
'/libraries/joomla/language/help.php',
'/libraries/joomla/language/latin_transliterate.php',
'/libraries/joomla/log/logexception.php',
'/libraries/joomla/log/loggers/database.php',
'/libraries/joomla/log/loggers/echo.php',
'/libraries/joomla/log/loggers/formattedtext.php',
'/libraries/joomla/log/loggers/index.html',
'/libraries/joomla/log/loggers/messagequeue.php',
'/libraries/joomla/log/loggers/syslog.php',
'/libraries/joomla/log/loggers/w3c.php',
'/libraries/joomla/methods.php',
'/libraries/joomla/session/storage/eaccelerator.php',
'/libraries/joomla/string/stringnormalize.php',
'/libraries/joomla/utilities/date.php',
'/libraries/joomla/utilities/simplecrypt.php',
'/libraries/joomla/utilities/simplexml.php',
'/libraries/joomla/utilities/string.php',
'/libraries/joomla/utilities/xmlelement.php',
'/media/plg_quickicon_extensionupdate/extensionupdatecheck.js',
'/media/plg_quickicon_joomlaupdate/jupdatecheck.js',
// Joomla! 3.1
'/libraries/joomla/application/router.php',
'/libraries/joomla/form/rules/boolean.php',
'/libraries/joomla/form/rules/color.php',
'/libraries/joomla/form/rules/email.php',
'/libraries/joomla/form/rules/equals.php',
'/libraries/joomla/form/rules/index.html',
'/libraries/joomla/form/rules/options.php',
'/libraries/joomla/form/rules/rules.php',
'/libraries/joomla/form/rules/tel.php',
'/libraries/joomla/form/rules/url.php',
'/libraries/joomla/form/rules/username.php',
'/libraries/joomla/html/access.php',
'/libraries/joomla/html/behavior.php',
'/libraries/joomla/html/content.php',
'/libraries/joomla/html/date.php',
'/libraries/joomla/html/email.php',
'/libraries/joomla/html/form.php',
'/libraries/joomla/html/grid.php',
'/libraries/joomla/html/html.php',
'/libraries/joomla/html/index.html',
'/libraries/joomla/html/jgrid.php',
'/libraries/joomla/html/list.php',
'/libraries/joomla/html/number.php',
'/libraries/joomla/html/rules.php',
'/libraries/joomla/html/select.php',
'/libraries/joomla/html/sliders.php',
'/libraries/joomla/html/string.php',
'/libraries/joomla/html/tabs.php',
'/libraries/joomla/html/tel.php',
'/libraries/joomla/html/user.php',
'/libraries/joomla/html/language/index.html',
'/libraries/joomla/html/language/en-GB/en-GB.jhtmldate.ini',
'/libraries/joomla/html/language/en-GB/index.html',
'/libraries/joomla/installer/adapters/component.php',
'/libraries/joomla/installer/adapters/file.php',
'/libraries/joomla/installer/adapters/index.html',
'/libraries/joomla/installer/adapters/language.php',
'/libraries/joomla/installer/adapters/library.php',
'/libraries/joomla/installer/adapters/module.php',
'/libraries/joomla/installer/adapters/package.php',
'/libraries/joomla/installer/adapters/plugin.php',
'/libraries/joomla/installer/adapters/template.php',
'/libraries/joomla/installer/extension.php',
'/libraries/joomla/installer/helper.php',
'/libraries/joomla/installer/index.html',
'/libraries/joomla/installer/librarymanifest.php',
'/libraries/joomla/installer/packagemanifest.php',
'/libraries/joomla/pagination/index.html',
'/libraries/joomla/pagination/object.php',
'/libraries/joomla/pagination/pagination.php',
'/libraries/legacy/html/contentlanguage.php',
'/libraries/legacy/html/index.html',
'/libraries/legacy/html/menu.php',
'/libraries/legacy/menu/index.html',
'/libraries/legacy/menu/menu.php',
'/libraries/legacy/pathway/index.html',
'/libraries/legacy/pathway/pathway.php',
'/media/system/css/mooRainbow.css',
'/media/system/js/mooRainbow-uncompressed.js',
'/media/system/js/mooRainbow.js',
'/media/system/js/swf-uncompressed.js',
'/media/system/js/swf.js',
'/media/system/js/uploader-uncompressed.js',
'/media/system/js/uploader.js',
'/media/system/swf/index.html',
'/media/system/swf/uploader.swf',
// Joomla! 3.2
'/administrator/components/com_contact/models/fields/modal/contacts.php',
'/administrator/components/com_newsfeeds/models/fields/modal/newsfeeds.php',
'/libraries/idna_convert/example.php',
'/media/editors/tinymce/jscripts/tiny_mce/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/license.txt',
'/media/editors/tinymce/jscripts/tiny_mce/tiny_mce.js',
'/media/editors/tinymce/jscripts/tiny_mce/tiny_mce_popup.js',
'/media/editors/tinymce/jscripts/tiny_mce/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/langs/en.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/rule.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/css/advhr.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/js/rule.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/image.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/css/advimage.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/img/sample.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/js/image.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/link.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/css/advlink.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/js/advlink.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlist/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlist/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autolink/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autolink/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autoresize/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autoresize/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/langs/en.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/bbcode/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/editable_selects.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/form_utils.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/mctabs.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/tiny_mce_popup.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/validate.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/contextmenu/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/contextmenu/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/directionality/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/directionality/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/emotions.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-cool.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-cry.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-embarassed.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-foot-in-mouth.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-frown.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-innocent.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-kiss.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-laughing.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-money-mouth.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-sealed.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-smile.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-surprised.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-tongue-out.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-undecided.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-wink.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-yell.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/js/emotions.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/fullpage.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/css/fullpage.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/js/fullpage.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullscreen/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullscreen/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullscreen/fullscreen.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/iespell/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/iespell/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/template.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/window.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/alert.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/button.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/buttons.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/confirm.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/corners.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/horizontal.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/vertical.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/insertdatetime/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/insertdatetime/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/layer/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/layer/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/lists/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/lists/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/media.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/moxieplayer.swf',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/css/media.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/js/embed.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/js/media.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/nonbreaking/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/nonbreaking/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/noneditable/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/noneditable/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/pagebreak/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/pagebreak/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/pastetext.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/pastetext.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/js/pastetext.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/js/pasteword.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/example.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/preview.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/jscripts/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/jscripts/embed.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/print/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/print/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/save/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/save/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/searchreplace.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/css/searchreplace.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/js/searchreplace.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/css/content.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/img/wline.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/props.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/readme.txt',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/css/props.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/js/props.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/tabfocus/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/tabfocus/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/cell.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/merge_cells.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/row.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/table.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/css/cell.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/css/row.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/css/table.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/cell.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/merge_cells.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/row.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/table.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/blank.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/template.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/css/template.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/js/template.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/visualblocks/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/visualblocks/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/visualblocks/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/visualblocks/css/visualblocks.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/visualchars/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/visualchars/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/wordcount/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/wordcount/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/abbr.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/acronym.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/attributes.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/cite.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/del.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/ins.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/css/attributes.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/css/popup.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/abbr.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/acronym.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/attributes.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/cite.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/del.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/element_common.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/ins.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/about.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/anchor.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/charmap.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/color_picker.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/editor_template.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/image.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/link.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/shortcuts.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/source_editor.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/colorpicker.jpg',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/flash.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/icons.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/iframe.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/pagebreak.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/quicktime.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/realmedia.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/shockwave.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/trans.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/video.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/windowsmedia.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/about.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/anchor.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/charmap.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/color_picker.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/image.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/link.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/source_editor.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/langs/en.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/content.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/dialog.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/ui.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/buttons.png',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/items.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/menu_arrow.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/menu_check.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/progress.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/tabs.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/highcontrast/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/highcontrast/content.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/highcontrast/dialog.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/highcontrast/ui.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/content.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/dialog.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/ui.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/ui_black.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/ui_silver.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/img/button_bg.png',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/img/button_bg_black.png',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/img/button_bg_silver.png',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/editor_template.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/img/icons.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/langs/en.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/default/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/default/content.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/default/ui.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/content.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/ui.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/img/button_bg.png',
'/media/editors/tinymce/jscripts/tiny_mce/utils/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/utils/editable_selects.js',
'/media/editors/tinymce/jscripts/tiny_mce/utils/form_utils.js',
'/media/editors/tinymce/jscripts/tiny_mce/utils/mctabs.js',
'/media/editors/tinymce/jscripts/tiny_mce/utils/validate.js',
'/administrator/components/com_banners/models/fields/ordering.php',
'/administrator/components/com_contact/models/fields/ordering.php',
'/administrator/components/com_newsfeeds/models/fields/ordering.php',
'/administrator/components/com_plugins/models/fields/ordering.php',
'/administrator/components/com_weblinks/models/fields/ordering.php',
'/administrator/includes/application.php',
'/includes/application.php',
'/libraries/legacy/application/helper.php',
'/libraries/joomla/plugin/helper.php',
'/libraries/joomla/plugin/index.html',
'/libraries/joomla/plugin/plugin.php',
'/libraries/legacy/component/helper.php',
'/libraries/legacy/component/index.html',
'/libraries/legacy/module/helper.php',
'/libraries/legacy/module/index.html',
'/administrator/components/com_templates/controllers/source.php',
'/administrator/components/com_templates/models/source.php',
'/administrator/components/com_templates/views/source/index.html',
'/administrator/components/com_templates/views/source/tmpl/edit.php',
'/administrator/components/com_templates/views/source/tmpl/edit_ftp.php',
'/administrator/components/com_templates/views/source/tmpl/index.html',
'/administrator/components/com_templates/views/source/view.html.php',
'/media/editors/codemirror/css/csscolors.css',
'/media/editors/codemirror/css/jscolors.css',
'/media/editors/codemirror/css/phpcolors.css',
'/media/editors/codemirror/css/sparqlcolors.css',
'/media/editors/codemirror/css/xmlcolors.css',
'/media/editors/codemirror/js/basefiles-uncompressed.js',
'/media/editors/codemirror/js/basefiles.js',
'/media/editors/codemirror/js/codemirror-uncompressed.js',
'/media/editors/codemirror/js/editor.js',
'/media/editors/codemirror/js/highlight.js',
'/media/editors/codemirror/js/mirrorframe.js',
'/media/editors/codemirror/js/parsecss.js',
'/media/editors/codemirror/js/parsedummy.js',
'/media/editors/codemirror/js/parsehtmlmixed.js',
'/media/editors/codemirror/js/parsejavascript.js',
'/media/editors/codemirror/js/parsephp.js',
'/media/editors/codemirror/js/parsephphtmlmixed.js',
'/media/editors/codemirror/js/parsesparql.js',
'/media/editors/codemirror/js/parsexml.js',
'/media/editors/codemirror/js/select.js',
'/media/editors/codemirror/js/stringstream.js',
'/media/editors/codemirror/js/tokenize.js',
'/media/editors/codemirror/js/tokenizejavascript.js',
'/media/editors/codemirror/js/tokenizephp.js',
'/media/editors/codemirror/js/undo.js',
'/media/editors/codemirror/js/util.js',
'/administrator/components/com_weblinks/models/fields/index.html',
'/plugins/user/joomla/postinstall/actions.php',
'/plugins/user/joomla/postinstall/index.html',
'/media/com_finder/js/finder.js',
'/media/com_finder/js/highlighter.js',
'/libraries/joomla/registry/format.php',
'/libraries/joomla/registry/index.html',
'/libraries/joomla/registry/registry.php',
'/libraries/joomla/registry/format/index.html',
'/libraries/joomla/registry/format/ini.php',
'/libraries/joomla/registry/format/json.php',
'/libraries/joomla/registry/format/php.php',
'/libraries/joomla/registry/format/xml.php',
// Joomla 3.3.1
'/administrator/templates/isis/html/message.php',
// Joomla 3.3.6
'/media/editors/tinymce/plugins/compat3x/editable_selects.js',
'/media/editors/tinymce/plugins/compat3x/form_utils.js',
'/media/editors/tinymce/plugins/compat3x/mctabs.js',
'/media/editors/tinymce/plugins/compat3x/tiny_mce_popup.js',
'/media/editors/tinymce/plugins/compat3x/validate.js',
// Joomla! 3.4
'/administrator/components/com_tags/helpers/html/index.html',
'/administrator/components/com_tags/models/fields/index.html',
'/administrator/manifests/libraries/phpmailer.xml',
'/administrator/templates/hathor/html/com_finder/filter/index.html',
'/administrator/templates/hathor/html/com_finder/statistics/index.html',
'/components/com_contact/helpers/icon.php',
'/language/en-GB/en-GB.lib_phpmailer.sys.ini',
'/libraries/compat/jsonserializable.php',
'/libraries/compat/password/lib/index.html',
'/libraries/compat/password/lib/password.php',
'/libraries/compat/password/lib/version_test.php',
'/libraries/compat/password/index.html',
'/libraries/compat/password/LICENSE.md',
'/libraries/compat/index.html',
'/libraries/fof/controller.php',
'/libraries/fof/dispatcher.php',
'/libraries/fof/inflector.php',
'/libraries/fof/input.php',
'/libraries/fof/model.php',
'/libraries/fof/query.abstract.php',
'/libraries/fof/query.element.php',
'/libraries/fof/query.mysql.php',
'/libraries/fof/query.mysqli.php',
'/libraries/fof/query.sqlazure.php',
'/libraries/fof/query.sqlsrv.php',
'/libraries/fof/render.abstract.php',
'/libraries/fof/render.joomla.php',
'/libraries/fof/render.joomla3.php',
'/libraries/fof/render.strapper.php',
'/libraries/fof/string.utils.php',
'/libraries/fof/table.php',
'/libraries/fof/template.utils.php',
'/libraries/fof/toolbar.php',
'/libraries/fof/view.csv.php',
'/libraries/fof/view.html.php',
'/libraries/fof/view.json.php',
'/libraries/fof/view.php',
'/libraries/framework/Joomla/Application/Cli/Output/Processor/ColorProcessor.php',
'/libraries/framework/Joomla/Application/Cli/Output/Processor/ProcessorInterface.php',
'/libraries/framework/Joomla/Application/Cli/Output/Stdout.php',
'/libraries/framework/Joomla/Application/Cli/Output/Xml.php',
'/libraries/framework/Joomla/Application/Cli/CliOutput.php',
'/libraries/framework/Joomla/Application/Cli/ColorProcessor.php',
'/libraries/framework/Joomla/Application/Cli/ColorStyle.php',
'/libraries/framework/index.html',
'/libraries/framework/Joomla/DI/Exception/DependencyResolutionException.php',
'/libraries/framework/Joomla/DI/Exception/index.html',
'/libraries/framework/Joomla/DI/Container.php',
'/libraries/framework/Joomla/DI/ContainerAwareInterface.php',
'/libraries/framework/Joomla/DI/index.html',
'/libraries/framework/Joomla/DI/ServiceProviderInterface.php',
'/libraries/framework/Joomla/Registry/Format/index.html',
'/libraries/framework/Joomla/Registry/Format/Ini.php',
'/libraries/framework/Joomla/Registry/Format/Json.php',
'/libraries/framework/Joomla/Registry/Format/Php.php',
'/libraries/framework/Joomla/Registry/Format/Xml.php',
'/libraries/framework/Joomla/Registry/Format/Yaml.php',
'/libraries/framework/Joomla/Registry/AbstractRegistryFormat.php',
'/libraries/framework/Joomla/Registry/index.html',
'/libraries/framework/Joomla/Registry/Registry.php',
'/libraries/framework/Symfony/Component/Yaml/Exception/DumpException.php',
'/libraries/framework/Symfony/Component/Yaml/Exception/ExceptionInterface.php',
'/libraries/framework/Symfony/Component/Yaml/Exception/index.html',
'/libraries/framework/Symfony/Component/Yaml/Exception/ParseException.php',
'/libraries/framework/Symfony/Component/Yaml/Exception/RuntimeException.php',
'/libraries/framework/Symfony/Component/Yaml/Dumper.php',
'/libraries/framework/Symfony/Component/Yaml/Escaper.php',
'/libraries/framework/Symfony/Component/Yaml/index.html',
'/libraries/framework/Symfony/Component/Yaml/Inline.php',
'/libraries/framework/Symfony/Component/Yaml/LICENSE',
'/libraries/framework/Symfony/Component/Yaml/Parser.php',
'/libraries/framework/Symfony/Component/Yaml/Unescaper.php',
'/libraries/framework/Symfony/Component/Yaml/Yaml.php',
'/libraries/joomla/string/inflector.php',
'/libraries/joomla/string/normalise.php',
'/libraries/phpmailer/language/index.html',
'/libraries/phpmailer/language/phpmailer.lang-joomla.php',
'/libraries/phpmailer/index.html',
'/libraries/phpmailer/LICENSE',
'/libraries/phpmailer/phpmailer.php',
'/libraries/phpmailer/pop.php',
'/libraries/phpmailer/smtp.php',
'/media/editors/codemirror/css/ambiance.css',
'/media/editors/codemirror/css/codemirror.css',
'/media/editors/codemirror/css/configuration.css',
'/media/editors/codemirror/css/index.html',
'/media/editors/codemirror/js/brace-fold.js',
'/media/editors/codemirror/js/clike.js',
'/media/editors/codemirror/js/closebrackets.js',
'/media/editors/codemirror/js/closetag.js',
'/media/editors/codemirror/js/codemirror.js',
'/media/editors/codemirror/js/css.js',
'/media/editors/codemirror/js/foldcode.js',
'/media/editors/codemirror/js/foldgutter.js',
'/media/editors/codemirror/js/fullscreen.js',
'/media/editors/codemirror/js/htmlmixed.js',
'/media/editors/codemirror/js/indent-fold.js',
'/media/editors/codemirror/js/index.html',
'/media/editors/codemirror/js/javascript.js',
'/media/editors/codemirror/js/less.js',
'/media/editors/codemirror/js/matchbrackets.js',
'/media/editors/codemirror/js/matchtags.js',
'/media/editors/codemirror/js/php.js',
'/media/editors/codemirror/js/xml-fold.js',
'/media/editors/codemirror/js/xml.js',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon.svg',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon.ttf',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon.woff',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon-small.eot',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon-small.svg',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon-small.ttf',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon-small.woff',
'/media/editors/tinymce/skins/lightgray/fonts/readme.md',
'/media/editors/tinymce/skins/lightgray/fonts/tinymce.dev.svg',
'/media/editors/tinymce/skins/lightgray/fonts/tinymce-small.dev.svg',
'/media/editors/tinymce/skins/lightgray/img/wline.gif',
'/plugins/editors/codemirror/styles.css',
'/plugins/editors/codemirror/styles.min.css',
// Joomla! 3.4.1
'/libraries/joomla/environment/request.php',
'/media/editors/tinymce/templates/template_list.js',
'/media/editors/codemirror/lib/addons-uncompressed.js',
'/media/editors/codemirror/lib/codemirror-uncompressed.css',
'/media/editors/codemirror/lib/codemirror-uncompressed.js',
'/administrator/help/en-GB/Components_Banners_Banners.html',
'/administrator/help/en-GB/Components_Banners_Banners_Edit.html',
'/administrator/help/en-GB/Components_Banners_Categories.html',
'/administrator/help/en-GB/Components_Banners_Category_Edit.html',
'/administrator/help/en-GB/Components_Banners_Clients.html',
'/administrator/help/en-GB/Components_Banners_Clients_Edit.html',
'/administrator/help/en-GB/Components_Banners_Tracks.html',
'/administrator/help/en-GB/Components_Contact_Categories.html',
'/administrator/help/en-GB/Components_Contact_Category_Edit.html',
'/administrator/help/en-GB/Components_Contacts_Contacts.html',
'/administrator/help/en-GB/Components_Contacts_Contacts_Edit.html',
'/administrator/help/en-GB/Components_Content_Categories.html',
'/administrator/help/en-GB/Components_Content_Category_Edit.html',
'/administrator/help/en-GB/Components_Messaging_Inbox.html',
'/administrator/help/en-GB/Components_Messaging_Read.html',
'/administrator/help/en-GB/Components_Messaging_Write.html',
'/administrator/help/en-GB/Components_Newsfeeds_Categories.html',
'/administrator/help/en-GB/Components_Newsfeeds_Category_Edit.html',
'/administrator/help/en-GB/Components_Newsfeeds_Feeds.html',
'/administrator/help/en-GB/Components_Newsfeeds_Feeds_Edit.html',
'/administrator/help/en-GB/Components_Redirect_Manager.html',
'/administrator/help/en-GB/Components_Redirect_Manager_Edit.html',
'/administrator/help/en-GB/Components_Search.html',
'/administrator/help/en-GB/Components_Weblinks_Categories.html',
'/administrator/help/en-GB/Components_Weblinks_Category_Edit.html',
'/administrator/help/en-GB/Components_Weblinks_Links.html',
'/administrator/help/en-GB/Components_Weblinks_Links_Edit.html',
'/administrator/help/en-GB/Content_Article_Manager.html',
'/administrator/help/en-GB/Content_Article_Manager_Edit.html',
'/administrator/help/en-GB/Content_Featured_Articles.html',
'/administrator/help/en-GB/Content_Media_Manager.html',
'/administrator/help/en-GB/Extensions_Extension_Manager_Discover.html',
'/administrator/help/en-GB/Extensions_Extension_Manager_Install.html',
'/administrator/help/en-GB/Extensions_Extension_Manager_Manage.html',
'/administrator/help/en-GB/Extensions_Extension_Manager_Update.html',
'/administrator/help/en-GB/Extensions_Extension_Manager_Warnings.html',
'/administrator/help/en-GB/Extensions_Language_Manager_Content.html',
'/administrator/help/en-GB/Extensions_Language_Manager_Edit.html',
'/administrator/help/en-GB/Extensions_Language_Manager_Installed.html',
'/administrator/help/en-GB/Extensions_Module_Manager.html',
'/administrator/help/en-GB/Extensions_Module_Manager_Edit.html',
'/administrator/help/en-GB/Extensions_Plugin_Manager.html',
'/administrator/help/en-GB/Extensions_Plugin_Manager_Edit.html',
'/administrator/help/en-GB/Extensions_Template_Manager_Styles.html',
'/administrator/help/en-GB/Extensions_Template_Manager_Styles_Edit.html',
'/administrator/help/en-GB/Extensions_Template_Manager_Templates.html',
'/administrator/help/en-GB/Extensions_Template_Manager_Templates_Edit.html',
'/administrator/help/en-GB/Extensions_Template_Manager_Templates_Edit_Source.html',
'/administrator/help/en-GB/Glossary.html',
'/administrator/help/en-GB/Menus_Menu_Item_Manager.html',
'/administrator/help/en-GB/Menus_Menu_Item_Manager_Edit.html',
'/administrator/help/en-GB/Menus_Menu_Manager.html',
'/administrator/help/en-GB/Menus_Menu_Manager_Edit.html',
'/administrator/help/en-GB/Site_Global_Configuration.html',
'/administrator/help/en-GB/Site_Maintenance_Clear_Cache.html',
'/administrator/help/en-GB/Site_Maintenance_Global_Check-in.html',
'/administrator/help/en-GB/Site_Maintenance_Purge_Expired_Cache.html',
'/administrator/help/en-GB/Site_System_Information.html',
'/administrator/help/en-GB/Start_Here.html',
'/administrator/help/en-GB/Users_Access_Levels.html',
'/administrator/help/en-GB/Users_Access_Levels_Edit.html',
'/administrator/help/en-GB/Users_Debug_Users.html',
'/administrator/help/en-GB/Users_Groups.html',
'/administrator/help/en-GB/Users_Groups_Edit.html',
'/administrator/help/en-GB/Users_Mass_Mail_Users.html',
'/administrator/help/en-GB/Users_User_Manager.html',
'/administrator/help/en-GB/Users_User_Manager_Edit.html',
'/administrator/components/com_config/views/index.html',
'/administrator/components/com_config/views/application/index.html',
'/administrator/components/com_config/views/application/view.html.php',
'/administrator/components/com_config/views/application/tmpl/default.php',
'/administrator/components/com_config/views/application/tmpl/default_cache.php',
'/administrator/components/com_config/views/application/tmpl/default_cookie.php',
'/administrator/components/com_config/views/application/tmpl/default_database.php',
'/administrator/components/com_config/views/application/tmpl/default_debug.php',
'/administrator/components/com_config/views/application/tmpl/default_filters.php',
'/administrator/components/com_config/views/application/tmpl/default_ftp.php',
'/administrator/components/com_config/views/application/tmpl/default_ftplogin.php',
'/administrator/components/com_config/views/application/tmpl/default_locale.php',
'/administrator/components/com_config/views/application/tmpl/default_mail.php',
'/administrator/components/com_config/views/application/tmpl/default_metadata.php',
'/administrator/components/com_config/views/application/tmpl/default_navigation.php',
'/administrator/components/com_config/views/application/tmpl/default_permissions.php',
'/administrator/components/com_config/views/application/tmpl/default_seo.php',
'/administrator/components/com_config/views/application/tmpl/default_server.php',
'/administrator/components/com_config/views/application/tmpl/default_session.php',
'/administrator/components/com_config/views/application/tmpl/default_site.php',
'/administrator/components/com_config/views/application/tmpl/default_system.php',
'/administrator/components/com_config/views/application/tmpl/index.html',
'/administrator/components/com_config/views/close/index.html',
'/administrator/components/com_config/views/close/view.html.php',
'/administrator/components/com_config/views/component/index.html',
'/administrator/components/com_config/views/component/view.html.php',
'/administrator/components/com_config/views/component/tmpl/default.php',
'/administrator/components/com_config/views/component/tmpl/index.html',
'/administrator/components/com_config/models/fields/filters.php',
'/administrator/components/com_config/models/fields/index.html',
'/administrator/components/com_config/models/forms/application.xml',
'/administrator/components/com_config/models/forms/index.html',
// Joomla 3.4.2
'/libraries/composer_autoload.php',
'/administrator/templates/hathor/html/com_categories/categories/default_batch.php',
'/administrator/templates/hathor/html/com_tags/tags/default_batch.php',
'/media/editors/codemirror/mode/clike/scala.html',
'/media/editors/codemirror/mode/css/less.html',
'/media/editors/codemirror/mode/css/less_test.js',
'/media/editors/codemirror/mode/css/scss.html',
'/media/editors/codemirror/mode/css/scss_test.js',
'/media/editors/codemirror/mode/css/test.js',
'/media/editors/codemirror/mode/gfm/test.js',
'/media/editors/codemirror/mode/haml/test.js',
'/media/editors/codemirror/mode/javascript/json-ld.html',
'/media/editors/codemirror/mode/javascript/test.js',
'/media/editors/codemirror/mode/javascript/typescript.html',
'/media/editors/codemirror/mode/markdown/test.js',
'/media/editors/codemirror/mode/php/test.js',
'/media/editors/codemirror/mode/ruby/test.js',
'/media/editors/codemirror/mode/shell/test.js',
'/media/editors/codemirror/mode/slim/test.js',
'/media/editors/codemirror/mode/stex/test.js',
'/media/editors/codemirror/mode/textile/test.js',
'/media/editors/codemirror/mode/verilog/test.js',
'/media/editors/codemirror/mode/xml/test.js',
'/media/editors/codemirror/mode/xquery/test.js',
// Joomla 3.4.3
'/libraries/classloader.php',
'/libraries/ClassLoader.php',
// Joomla 3.4.6
'/components/com_wrapper/views/wrapper/metadata.xml',
// Joomla 3.5.0
'/media/com_joomlaupdate/default.js',
'/media/com_joomlaupdate/encryption.js',
'/media/com_joomlaupdate/json2.js',
'/media/com_joomlaupdate/update.js',
'/media/com_finder/css/finder-rtl.css',
'/media/com_finder/css/selectfilter.css',
'/media/com_finder/css/sliderfilter.css',
'/media/com_finder/js/sliderfilter.js',
'/media/editors/codemirror/mode/kotlin/kotlin.js',
'/media/editors/codemirror/mode/kotlin/kotlin.min.js',
'/media/editors/tinymce/plugins/compat3x/editable_selects.js',
'/media/editors/tinymce/plugins/compat3x/form_utils.js',
'/media/editors/tinymce/plugins/compat3x/mctabs.js',
'/media/editors/tinymce/plugins/compat3x/tiny_mce_popup.js',
'/media/editors/tinymce/plugins/compat3x/validate.js',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Dumper.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Escaper.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Inline.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/LICENSE',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Parser.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Unescaper.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Yaml.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception/DumpException.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception/ExceptionInterface.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception/ParseException.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception/RuntimeException.php',
'/libraries/vendor/phpmailer/phpmailer/extras/class.html2text.php',
'/libraries/joomla/document/error/error.php',
'/libraries/joomla/document/feed/feed.php',
'/libraries/joomla/document/html/html.php',
'/libraries/joomla/document/image/image.php',
'/libraries/joomla/document/json/json.php',
'/libraries/joomla/document/opensearch/opensearch.php',
'/libraries/joomla/document/raw/raw.php',
'/libraries/joomla/document/xml/xml.php',
'/plugins/editors/tinymce/fields/skins.php',
'/plugins/user/profile/fields/dob.php',
'/plugins/user/profile/fields/tos.php',
'/administrator/components/com_installer/views/languages/tmpl/default_filter.php',
'/administrator/components/com_joomlaupdate/helpers/download.php',
'/administrator/components/com_config/controller/application/refreshhelp.php',
'/administrator/components/com_media/models/forms/index.html',
// Joomla 3.6.0
'/libraries/simplepie/README.txt',
'/libraries/simplepie/simplepie.php',
'/libraries/simplepie/LICENSE.txt',
'/libraries/simplepie/idn/LICENCE',
'/libraries/simplepie/idn/ReadMe.txt',
'/libraries/simplepie/idn/idna_convert.class.php',
'/libraries/simplepie/idn/npdata.ser',
'/administrator/manifests/libraries/simplepie.xml',
'/administrator/templates/isis/js/jquery.js',
'/administrator/templates/isis/js/bootstrap.min.js',
'/media/system/js/permissions.min.js',
'/libraries/platform.php',
'/plugins/user/profile/fields/tos.php',
'/libraries/joomla/application/web/client.php',
// Joomla! 3.6.1
'/libraries/joomla/database/iterator/azure.php',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon.eot',
// Joomla! 3.6.3
'/media/editors/codemirror/mode/jade/jade.js',
'/media/editors/codemirror/mode/jade/jade.min.js',
// Joomla __DEPLOY_VERSION__
'/libraries/joomla/user/authentication.php',
'/libraries/platform.php',
'/libraries/joomla/data/data.php',
'/libraries/joomla/data/dumpable.php',
'/libraries/joomla/data/set.php',
'/administrator/components/com_banners/views/banners/tmpl/default_batch.php',
'/administrator/components/com_categories/views/category/tmpl/edit_extrafields.php',
'/administrator/components/com_categories/views/category/tmpl/edit_options.php',
'/administrator/components/com_categories/views/categories/tmpl/default_batch.php',
'/administrator/components/com_content/views/articles/tmpl/default_batch.php',
'/administrator/components/com_menus/views/items/tmpl/default_batch.php',
'/administrator/components/com_modules/views/modules/tmpl/default_batch.php',
'/administrator/components/com_newsfeeds/views/newsfeeds/tmpl/default_batch.php',
'/administrator/components/com_redirect/views/links/tmpl/default_batch.php',
'/administrator/components/com_tags/views/tags/tmpl/default_batch.php',
'/administrator/components/com_users/views/users/tmpl/default_batch.php',
);
// TODO There is an issue while deleting folders using the ftp mode
$folders = array(
'/administrator/components/com_admin/sql/updates/sqlsrv',
'/media/com_finder/images/mime',
'/media/com_finder/images',
'/components/com_media/helpers',
// Joomla 3.0
'/administrator/components/com_contact/elements',
'/administrator/components/com_content/elements',
'/administrator/components/com_newsfeeds/elements',
'/administrator/components/com_templates/views/prevuuw/tmpl',
'/administrator/components/com_templates/views/prevuuw',
'/libraries/cms/controller',
'/libraries/cms/model',
'/libraries/cms/view',
'/libraries/joomla/application/cli',
'/libraries/joomla/application/component',
'/libraries/joomla/application/input',
'/libraries/joomla/application/module',
'/libraries/joomla/cache/storage/helpers',
'/libraries/joomla/database/table',
'/libraries/joomla/database/database',
'/libraries/joomla/error',
'/libraries/joomla/filesystem/archive',
'/libraries/joomla/html/html',
'/libraries/joomla/html/toolbar',
'/libraries/joomla/html/toolbar/button',
'/libraries/joomla/html/parameter',
'/libraries/joomla/html/parameter/element',
'/libraries/joomla/image/filters',
'/libraries/joomla/log/loggers',
// Joomla! 3.1
'/libraries/joomla/form/rules',
'/libraries/joomla/html/language/en-GB',
'/libraries/joomla/html/language',
'/libraries/joomla/html',
'/libraries/joomla/installer/adapters',
'/libraries/joomla/installer',
'/libraries/joomla/pagination',
'/libraries/legacy/html',
'/libraries/legacy/menu',
'/libraries/legacy/pathway',
'/media/system/swf/',
'/media/editors/tinymce/jscripts',
// Joomla! 3.2
'/libraries/joomla/plugin',
'/libraries/legacy/component',
'/libraries/legacy/module',
'/administrator/components/com_weblinks/models/fields',
'/plugins/user/joomla/postinstall',
'/libraries/joomla/registry/format',
'/libraries/joomla/registry',
// Joomla! 3.3
'/plugins/user/profile/fields',
'/media/editors/tinymce/plugins/compat3x',
// Joomla! 3.4
'/administrator/components/com_tags/helpers/html',
'/administrator/components/com_tags/models/fields',
'/administrator/templates/hathor/html/com_finder/filter',
'/administrator/templates/hathor/html/com_finder/statistics',
'/libraries/compat/password/lib',
'/libraries/compat/password',
'/libraries/compat',
'/libraries/framework/Joomla/Application/Cli/Output/Processor',
'/libraries/framework/Joomla/Application/Cli/Output',
'/libraries/framework/Joomla/Application/Cli',
'/libraries/framework/Joomla/Application',
'/libraries/framework/Joomla/DI/Exception',
'/libraries/framework/Joomla/DI',
'/libraries/framework/Joomla/Registry/Format',
'/libraries/framework/Joomla/Registry',
'/libraries/framework/Joomla',
'/libraries/framework/Symfony/Component/Yaml/Exception',
'/libraries/framework/Symfony/Component/Yaml',
'/libraries/framework',
'/libraries/phpmailer/language',
'/libraries/phpmailer',
'/media/editors/codemirror/css',
'/media/editors/codemirror/js',
'/media/com_banners',
// Joomla! 3.4.1
'/administrator/components/com_config/views',
'/administrator/components/com_config/models/fields',
'/administrator/components/com_config/models/forms',
// Joomla! 3.4.2
'/media/editors/codemirror/mode/smartymixed',
// Joomla! 3.5
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml',
'/libraries/vendor/symfony/yaml/Symfony/Component',
'/libraries/vendor/symfony/yaml/Symfony',
'/libraries/joomla/document/error',
'/libraries/joomla/document/image',
'/libraries/joomla/document/json',
'/libraries/joomla/document/opensearch',
'/libraries/joomla/document/raw',
'/libraries/joomla/document/xml',
'/administrator/components/com_media/models/forms',
'/media/editors/codemirror/mode/kotlin',
'/media/editors/tinymce/plugins/compat3x',
'/plugins/editors/tinymce/fields',
'/plugins/user/profile/fields',
// Joomla 3.6
'/libraries/simplepie/idn',
'/libraries/simplepie',
// Joomla! 3.6.3
'/media/editors/codemirror/mode/jade',
// Joomla __DEPLOY_VERSION__
'/libraries/joomla/data',
);
jimport('joomla.filesystem.file');
foreach ($files as $file)
{
if (JFile::exists(JPATH_ROOT . $file) && !JFile::delete(JPATH_ROOT . $file))
{
echo JText::sprintf('FILES_JOOMLA_ERROR_FILE_FOLDER', $file) . '<br />';
}
}
jimport('joomla.filesystem.folder');
foreach ($folders as $folder)
{
if (JFolder::exists(JPATH_ROOT . $folder) && !JFolder::delete(JPATH_ROOT . $folder))
{
echo JText::sprintf('FILES_JOOMLA_ERROR_FILE_FOLDER', $folder) . '<br />';
}
}
/*
* Needed for updates post-3.4
* If com_weblinks doesn't exist then assume we can delete the weblinks package manifest (included in the update packages)
*/
if (!JFile::exists(JPATH_ROOT . '/administrator/components/com_weblinks/weblinks.php')
&& JFile::exists(JPATH_ROOT . '/administrator/manifests/packages/pkg_weblinks.xml'))
{
JFile::delete(JPATH_ROOT . '/administrator/manifests/packages/pkg_weblinks.xml');
}
}
/**
* Clears the RAD layer's table cache.
*
* The cache vastly improves performance but needs to be cleared every time you update the database schema.
*
* @return void
*
* @since 3.2
*/
protected function clearRadCache()
{
jimport('joomla.filesystem.file');
if (JFile::exists(JPATH_ROOT . '/cache/fof/cache.php'))
{
JFile::delete(JPATH_ROOT . '/cache/fof/cache.php');
}
}
/**
* Method to create assets for newly installed components
*
* @return boolean
*
* @since 3.2
*/
public function updateAssets()
{
// List all components added since 1.6
$newComponents = array(
'com_finder',
'com_joomlaupdate',
'com_tags',
'com_contenthistory',
'com_ajax',
'com_postinstall'
);
foreach ($newComponents as $component)
{
/** @var JTableAsset $asset */
$asset = JTable::getInstance('Asset');
if ($asset->loadByName($component))
{
continue;
}
$asset->name = $component;
$asset->parent_id = 1;
$asset->rules = '{}';
$asset->title = $component;
$asset->setLocation(1, 'last-child');
if (!$asset->store())
{
// Install failed, roll back changes
$this->parent->abort(JText::sprintf('JLIB_INSTALLER_ABORT_COMP_INSTALL_ROLLBACK', $asset->stderr(true)));
return false;
}
}
return true;
}
/**
* If we migrated the session from the previous system, flush all the active sessions.
* Otherwise users will be logged in, but not able to do anything since they don't have
* a valid session
*
* @return boolean
*/
public function flushSessions()
{
/**
* The session may have not been started yet (e.g. CLI-based Joomla! update scripts). Let's make sure we do
* have a valid session.
*/
$session = JFactory::getSession();
/**
* Restarting the Session require a new login for the current user so lets check if we have an active session
* and only restart it if not.
* For B/C reasons we need to use getState as isActive is not available in 2.5
*/
if ($session->getState() !== 'active')
{
$session->restart();
}
// If $_SESSION['__default'] is no longer set we do not have a migrated session, therefore we can quit.
if (!isset($_SESSION['__default']))
{
return true;
}
$db = JFactory::getDbo();
try
{
switch ($db->name)
{
// MySQL database, use TRUNCATE (faster, more resilient)
case 'pdomysql':
case 'mysql':
case 'mysqli':
$db->truncateTable('#__session');
break;
// Non-MySQL databases, use a simple DELETE FROM query
default:
$query = $db->getQuery(true)
->delete($db->qn('#__session'));
$db->setQuery($query)->execute();
break;
}
}
catch (Exception $e)
{
echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />';
return false;
}
return true;
}
/**
* Converts the site's database tables to support UTF-8 Multibyte.
*
* @param boolean $doDbFixMsg Flag if message to be shown to check db fix
*
* @return void
*
* @since 3.5
*/
public function convertTablesToUtf8mb4($doDbFixMsg = false)
{
$db = JFactory::getDbo();
// This is only required for MySQL databases
$serverType = $db->getServerType();
if ($serverType != 'mysql')
{
return;
}
// Set required conversion status
if ($db->hasUTF8mb4Support())
{
$converted = 2;
}
else
{
$converted = 1;
}
// Check conversion status in database
$db->setQuery('SELECT ' . $db->quoteName('converted')
. ' FROM ' . $db->quoteName('#__utf8_conversion')
);
try
{
$convertedDB = $db->loadResult();
}
catch (Exception $e)
{
// Render the error message from the Exception object
JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');
if ($doDbFixMsg)
{
// Show an error message telling to check database problems
JFactory::getApplication()->enqueueMessage(JText::_('JLIB_DATABASE_ERROR_DATABASE_UPGRADE_FAILED'), 'error');
}
return;
}
// Nothing to do, saved conversion status from DB is equal to required
if ($convertedDB == $converted)
{
return;
}
// Step 1: Drop indexes later to be added again with column lengths limitations at step 2
$fileName1 = JPATH_ROOT . "/administrator/components/com_admin/sql/others/mysql/utf8mb4-conversion-01.sql";
if (is_file($fileName1))
{
$fileContents1 = @file_get_contents($fileName1);
$queries1 = $db->splitSql($fileContents1);
if (!empty($queries1))
{
foreach ($queries1 as $query1)
{
try
{
$db->setQuery($query1)->execute();
}
catch (Exception $e)
{
// If the query fails we will go on. It just means the index to be dropped does not exist.
}
}
}
}
// Step 2: Perform the index modifications and conversions
$fileName2 = JPATH_ROOT . "/administrator/components/com_admin/sql/others/mysql/utf8mb4-conversion-02.sql";
if (is_file($fileName2))
{
$fileContents2 = @file_get_contents($fileName2);
$queries2 = $db->splitSql($fileContents2);
if (!empty($queries2))
{
foreach ($queries2 as $query2)
{
try
{
$db->setQuery($db->convertUtf8mb4QueryToUtf8($query2))->execute();
}
catch (Exception $e)
{
$converted = 0;
// Still render the error message from the Exception object
JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');
}
}
}
}
if ($doDbFixMsg && $converted == 0)
{
// Show an error message telling to check database problems
JFactory::getApplication()->enqueueMessage(JText::_('JLIB_DATABASE_ERROR_DATABASE_UPGRADE_FAILED'), 'error');
}
// Set flag in database if the update is done.
$db->setQuery('UPDATE ' . $db->quoteName('#__utf8_conversion')
. ' SET ' . $db->quoteName('converted') . ' = ' . $converted . ';')->execute();
}
/**
* This method clean the Joomla Cache using the method `clean` from the com_cache model
*
* @return void
*
* @since 3.5.1
*/
private function cleanJoomlaCache()
{
JModelLegacy::addIncludePath(JPATH_ROOT . '/administrator/components/com_cache/models');
$model = JModelLegacy::getInstance('cache', 'CacheModel');
// Clean frontend cache
$model->clean();
// Clean admin cache
$model->setState('client_id', 1);
$model->clean();
}
}
| Java |
<?php
/**
* LDAP configuration test class
*
* PHP version 5
*
* Copyright (C) Villanova University 2010.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @category VuFind
* @package Tests
* @author Franck Borel <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://vufind.org/wiki/unit_tests Wiki
*/
require_once dirname(__FILE__) . '/../../prepend.inc.php';
require_once 'PEAR.php';
require_once 'sys/authn/LDAPConfigurationParameter.php';
/**
* LDAP configuration test class
*
* @category VuFind
* @package Tests
* @author Franck Borel <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://vufind.org/wiki/unit_tests Wiki
*/
class LDAPConfigurationParameterTest extends PHPUnit_Framework_TestCase
{
/**
* Standard setup method.
*
* @return void
* @access public
*/
public function setUp()
{
$this->pathToTestConfigurationFiles = dirname(__FILE__) . '/../../conf';
}
/**
* Verify that missing host causes failure.
*
* @return void
* @access public
*/
public function testWithMissingHost()
{
try {
$ldapConfigurationParameter = new LDAPConfigurationParameter(
$this->pathToTestConfigurationFiles .
"/authn/ldap/without-ldap-host-config.ini"
);
$parameters = $ldapConfigurationParameter->getParameter();
} catch (InvalidArgumentException $expected) {
return;
}
$this->fail('An expected InvalidArgumentException has not been raised');
}
/**
* Verify that missing port causes failure.
*
* @return void
* @access public
*/
public function testWithMissingPort()
{
try {
$ldapConfigurationParameter = new LDAPConfigurationParameter(
$this->pathToTestConfigurationFiles .
"/authn/ldap/without-ldap-port-config.ini"
);
$parameters = $ldapConfigurationParameter->getParameter();
} catch (InvalidArgumentException $expected) {
return;
}
$this->fail('An expected InvalidArgumentException has not been raised');
}
/**
* Verify that missing baseDN causes failure.
*
* @return void
* @access public
*/
public function testWithMissingBaseDN()
{
try {
$ldapConfigurationParameter = new LDAPConfigurationParameter(
$this->pathToTestConfigurationFiles .
"/authn/ldap/without-ldap-basedn-config.ini"
);
$parameters = $ldapConfigurationParameter->getParameter();
} catch (InvalidArgumentException $expected) {
return;
}
$this->fail('An expected InvalidArgumentException has not been raised');
}
/**
* Verify that missing UID causes failure.
*
* @return void
* @access public
*/
public function testWithMissingUid()
{
try {
$ldapConfigurationParameter = new LDAPConfigurationParameter(
$this->pathToTestConfigurationFiles .
"/authn/ldap/without-ldap-uid-config.ini"
);
$parameters = $ldapConfigurationParameter->getParameter();
} catch (InvalidArgumentException $expected) {
return;
}
$this->fail('An expected InvalidArgumentException has not been raised');
}
/**
* Verify that good parameters parse correctly.
*
* @return void
* @access public
*/
public function testWithWorkingParameters()
{
try {
$ldapConfigurationParameter = new LDAPConfigurationParameter();
$parameters = $ldapConfigurationParameter->getParameter();
$this->assertTrue(is_array($parameters));
} catch (InvalidArgumentException $unexpected) {
$this->fail(
"An unexpected InvalidArgumentException has been raised: " .
$unexpected
);
}
}
/**
* Verify lowercasing of parameter values.
*
* @return void
* @access public
*/
public function testIfParametersAreConvertedToLowercase()
{
try {
$ldapConfigurationParameter = new LDAPConfigurationParameter(
$this->pathToTestConfigurationFiles .
"/authn/ldap/unconverted-parameter-values-config.ini"
);
$parameters = $ldapConfigurationParameter->getParameter();
foreach ($parameters as $index => $value) {
if ($index == "username") {
$this->assertTrue($value == "uid");
}
if ($index == "college") {
$this->assertTrue($value == "employeetype");
}
}
} catch (InvalidArgumentException $unexpected) {
$this->fail(
"An unexpected InvalidArgumentException has been raised: " .
$unexpected
);
}
}
}
?>
| Java |
/* Copyright (C) 2013 Rainmeter Project Developers
*
* This Source Code Form is subject to the terms of the GNU General Public
* License; either version 2 of the License, or (at your option) any later
* version. If a copy of the GPL was not distributed with this file, You can
* obtain one at <https://www.gnu.org/licenses/gpl-2.0.html>. */
#include "StdAfx.h"
#include "StringUtil.h"
namespace {
// Is the character a end of sentence punctuation character?
// English only?
bool IsEOSPunct(wchar_t ch)
{
return ch == '?' || ch == '!' || ch == '.';
}
}
namespace StringUtil {
std::string Narrow(const WCHAR* str, int strLen, int cp)
{
std::string narrowStr;
if (str && *str)
{
if (strLen == -1)
{
strLen = (int)wcslen(str);
}
int bufLen = WideCharToMultiByte(cp, 0, str, strLen, nullptr, 0, nullptr, nullptr);
if (bufLen > 0)
{
narrowStr.resize(bufLen);
WideCharToMultiByte(cp, 0, str, strLen, &narrowStr[0], bufLen, nullptr, nullptr);
}
}
return narrowStr;
}
std::wstring Widen(const char* str, int strLen, int cp)
{
std::wstring wideStr;
if (str && *str)
{
if (strLen == -1)
{
strLen = (int)strlen(str);
}
int bufLen = MultiByteToWideChar(cp, 0, str, strLen, nullptr, 0);
if (bufLen > 0)
{
wideStr.resize(bufLen);
MultiByteToWideChar(cp, 0, str, strLen, &wideStr[0], bufLen);
}
}
return wideStr;
}
void ToLowerCase(std::wstring& str)
{
WCHAR* srcAndDest = &str[0];
int strAndDestLen = (int)str.length();
LCMapString(LOCALE_USER_DEFAULT, LCMAP_LOWERCASE, srcAndDest, strAndDestLen, srcAndDest, strAndDestLen);
}
void ToUpperCase(std::wstring& str)
{
WCHAR* srcAndDest = &str[0];
int strAndDestLen = (int)str.length();
LCMapString(LOCALE_USER_DEFAULT, LCMAP_UPPERCASE, srcAndDest, strAndDestLen, srcAndDest, strAndDestLen);
}
void ToProperCase(std::wstring& str)
{
WCHAR* srcAndDest = &str[0];
int strAndDestLen = (int)str.length();
LCMapString(LOCALE_USER_DEFAULT, LCMAP_TITLECASE, srcAndDest, strAndDestLen, srcAndDest, strAndDestLen);
}
void ToSentenceCase(std::wstring& str)
{
if (!str.empty())
{
ToLowerCase(str);
bool isCapped = false;
for (size_t i = 0; i < str.length(); ++i)
{
if (IsEOSPunct(str[i])) isCapped = false;
if (!isCapped && iswalpha(str[i]) != 0)
{
WCHAR* srcAndDest = &str[i];
LCMapString(LOCALE_USER_DEFAULT, LCMAP_UPPERCASE, srcAndDest, 1, srcAndDest, 1);
isCapped = true;
}
}
}
}
/*
** Escapes reserved PCRE regex metacharacters.
*/
void EscapeRegExp(std::wstring& str)
{
size_t start = 0;
while ((start = str.find_first_of(L"\\^$|()[{.+*?", start)) != std::wstring::npos)
{
str.insert(start, L"\\");
start += 2;
}
}
/*
** Escapes reserved URL characters.
*/
void EncodeUrl(std::wstring& str)
{
size_t pos = 0;
while ((pos = str.find_first_of(L" !*'();:@&=+$,/?#[]", pos)) != std::wstring::npos)
{
WCHAR buffer[3];
_snwprintf_s(buffer, _countof(buffer), L"%.2X", str[pos]);
str[pos] = L'%';
str.insert(pos + 1, buffer);
pos += 3;
}
}
/*
** Case insensitive comparison of strings. If equal, strip str2 from str1 and any leading whitespace.
*/
bool CaseInsensitiveCompareN(std::wstring& str1, const std::wstring& str2)
{
size_t pos = str2.length();
if (_wcsnicmp(str1.c_str(), str2.c_str(), pos) == 0)
{
str1 = str1.substr(pos); // remove str2 from str1
str1.erase(0, str1.find_first_not_of(L" \t\r\n")); // remove any leading whitespace
return true;
}
return false;
}
} // namespace StringUtil
| Java |
var icms = icms || {};
icms.wall = (function ($) {
var self = this;
this.add = function (parent_id) {
var form = $('#wall_add_form');
if (typeof (parent_id) === 'undefined') {
parent_id = 0;
}
$('#wall_widget #wall_add_link').show();
$('#wall_widget #entries_list .links *').removeClass('disabled');
if (parent_id == 0){
$('#wall_widget #wall_add_link').hide();
form.detach().prependTo('#wall_widget #entries_list');
} else {
$('#wall_widget #entries_list #entry_'+parent_id+' > .media-body > .links .reply').addClass('disabled');
form.detach().appendTo('#wall_widget #entries_list #entry_'+parent_id+' > .media-body');
}
form.show();
$('input[name=parent_id]', form).val(parent_id);
$('input[name=id]', form).val('');
$('input[name=action]', form).val('add');
$('input[name=submit]', form).val( LANG_SEND );
icms.forms.wysiwygInit('content').wysiwygInsertText('content', '');
return false;
};
this.submit = function (action) {
var form = $('#wall_add_form form');
var form_data = icms.forms.toJSON( form );
var url = form.attr('action');
if (action) {form_data.action = action;}
$('.buttons > *', form).addClass('disabled');
$('.button-'+form_data.action, form).addClass('is-busy');
$('textarea', form).prop('disabled', true);
$.post(url, form_data, function(result){
if (form_data.action === 'add') { self.result(result);}
if (form_data.action === 'preview') { self.previewResult(result);}
if (form_data.action === 'update') { self.updateResult(result);}
}, "json");
};
this.preview = function () {
this.submit('preview');
};
this.previewResult = function (result) {
if (result.error){
this.error(result.message);
return;
}
var form = $('#wall_add_form');
var preview_box = $('.preview_box', form).html(result.html);
$(preview_box).addClass('shadow').removeClass('d-none');
setTimeout(function (){ $(preview_box).removeClass('shadow'); }, 1000);
this.restoreForm(false);
};
this.more = function(){
var widget = $('#wall_widget');
$('.show_more', widget).hide();
$('.entry', widget).show();
$('.wall_pages', widget).show();
return false;
};
this.replies = function(id, callback){
var e = $('#wall_widget #entry_'+id);
if (!e.data('replies')) { return false; }
var url = $('#wall_urls').data('replies-url');
$('.icms-wall-item__btn_replies', e).addClass('is-busy');
$.post(url, {id: id}, function(result){
$('.icms-wall-item__btn_replies', e).removeClass('is-busy').hide();
if (result.error){
self.error(result.message);
return false;
}
$('.replies', e).html( result.html );
if (typeof(callback)=='function'){
callback();
}
}, "json");
return false;
};
this.append = function(entry){
$('#wall_widget #entries_list .no_entries').remove();
if (entry.parent_id == 0){
$('#wall_widget #entries_list').prepend( entry.html );
return;
}
if (entry.parent_id > 0){
$('#wall_widget #entry_'+entry.parent_id+' .replies').append( entry.html );
return;
}
};
this.result = function(result){
if (result.error){
this.error(result.message);
return;
}
this.append(result);
this.restoreForm();
};
this.updateResult = function(result){
if (result.error){
this.error(result.message);
return;
}
$('#entries_list #entry_'+result.id+'> .media-body > .icms-wall-html').html(result.html);
this.restoreForm();
};
this.edit = function (id){
var form = $('#wall_add_form');
$('#wall_widget #wall_add_link').show();
$('#wall_widget #entries_list .links *').removeClass('disabled');
$('#wall_widget #entries_list #entry_'+id+' > .media-body > .links .edit').addClass('is-busy disabled');
form.detach().insertAfter('#wall_widget #entries_list #entry_'+id+' > .media-body > .links').show();
$('input[name=id]', form).val(id);
$('input[name=action]', form).val('update');
$('input[name=submit]', form).val( LANG_SAVE );
$('textarea', form).prop('disabled', true);
icms.forms.wysiwygInit('content');
var url = $('#wall_urls').data('get-url');
$.post(url, {id: id}, function(result){
$('#wall_widget #entries_list #entry_'+id+' > .media-body > .links .edit').removeClass('is-busy');
if (result.error){
self.error(result.message);
return;
}
self.restoreForm(false);
icms.forms.wysiwygInsertText('content', result.html);
}, 'json');
return false;
};
this.remove = function (id){
var c = $('#entries_list #entry_'+id);
var username = $('> .media-body > h6 .user', c).text();
if (!confirm(LANG_WALL_ENTRY_DELETE_CONFIRM.replace('%s', username))) {
return false;
}
var url = $('#wall_urls').data('delete-url');
$.post(url, {id: id}, function(result){
if (result.error){
self.error(result.message);
return;
}
c.remove();
self.restoreForm();
}, "json");
return false;
};
this.show = function(id, reply_id, go_reply){
var e = $('#entry_'+id);
if (e.length){
$.scrollTo( e, 500, {
offset: {
left:0,
top:-10
},
onAfter: function(){
self.replies(id, function(){
if (reply_id>0){
self.show(reply_id);
}
});
if (go_reply){
self.add(id);
}
}
});
} else {
if (go_reply){
$.scrollTo( $('#wall_widget'), 500, {
offset: {
left:0,
top:-10
},
onAfter: function(){
self.add();
}
});
}
}
return false;
};
this.error = function(message){
icms.modal.alert(message);
this.restoreForm(false);
};
this.restoreForm = function(clear_text){
if (typeof (clear_text) === 'undefined') {
clear_text = true;
}
var form = $('#wall_add_form');
$('.buttons *', form).removeClass('disabled is-busy');
$('textarea', form).prop('disabled', false);
if (clear_text) {
form.hide();
icms.forms.wysiwygInsertText('content', '');
$('#wall_widget #wall_add_link').show();
$('#wall_widget #entries_list .links *').removeClass('disabled');
$('.preview_box', form).html('').hide();
}
};
return this;
}).call(icms.wall || {},jQuery); | Java |
<html>
<head>
<title>
TEAMMATES - Instructor
</title>
<link href="/favicon.png" rel="shortcut icon">
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<link href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="https://unpkg.com/[email protected]/dist/css/bootstrap-theme.min.css" rel="stylesheet" type="text/css">
<link href="/stylesheets/teammatesCommon.css" rel="stylesheet" type="text/css">
<link href="/stylesheets/datepicker.css" media="screen" rel="stylesheet" type="text/css">
<link href="https://unpkg.com/[email protected]/skins/lightgray/skin.min.css" id="u0" rel="stylesheet" type="text/css">
<link href="https://unpkg.com/[email protected]/skins/lightgray/content.inline.min.css" rel="stylesheet">
</head>
<body spellcheck="false">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button class="navbar-toggle" data-target="#contentLinks" data-toggle="collapse" type="button">
<span class="sr-only">
Toggle navigation
</span>
<span class="icon-bar">
</span>
<span class="icon-bar">
</span>
<span class="icon-bar">
</span>
</button>
<a class="navbar-brand" href="/index.jsp">
TEAMMATES
</a>
</div>
<div class="collapse navbar-collapse" id="contentLinks">
<ul class="nav navbar-nav">
<li>
<a class="nav home" data-link="instructorHome" href="/page/instructorHomePage?user=CFeedbackUiT.nocourses">
Home
</a>
</li>
<li>
<a class="nav courses" data-link="instructorCourse" href="/page/instructorCoursesPage?user=CFeedbackUiT.nocourses">
Courses
</a>
</li>
<li class="active">
<a class="nav evaluations" data-link="instructorEval" href="/page/instructorFeedbacksPage?user=CFeedbackUiT.nocourses">
Sessions
</a>
</li>
<li>
<a class="nav students" data-link="instructorStudent" href="/page/instructorStudentListPage?user=CFeedbackUiT.nocourses">
Students
</a>
</li>
<li>
<a class="nav comments" data-link="instructorComments" href="/page/instructorCommentsPage?user=CFeedbackUiT.nocourses">
Comments
</a>
</li>
<li>
<a class="nav search" data-link="instructorSearch" href="/page/instructorSearchPage?user=CFeedbackUiT.nocourses">
Search
</a>
</li>
<li>
<a class="nav help" href="/instructorHelp.jsp" rel="noopener noreferrer" target="_blank">
Help
</a>
</li>
</ul>
<ul class="nav navbar-nav pull-right">
<li>
<a class="nav logout" href="/logout" id="btnLogout">
Logout (
<span class="text-info tool-tip-decorate" data-original-title="CFeedbackUiT.nocourses" data-placement="bottom" data-toggle="tooltip" title="">
CFeedbackUiT.nocourses
</span>
)
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="container" id="mainContent">
<div id="topOfPage">
</div>
<h1>
Add New Feedback Session
</h1>
<br>
<div class="well well-plain">
<form action="/page/instructorFeedbackAdd" class="form-group" id="form_feedbacksession" method="post">
<div class="row">
<h4 class="label-control col-md-2 text-md">
Create new
</h4>
<div class="col-md-5">
<div class="col-xs-10 tablet-no-padding" data-original-title="Select a session type here." data-placement="top" data-toggle="tooltip" title="">
<select class="form-control" id="fstype" name="fstype">
<option value="STANDARD">
Session with your own questions
</option>
<option selected="" value="TEAMEVALUATION">
Team peer evaluation session
</option>
</select>
</div>
<div class="col-xs-1">
<h5>
<a href="/instructorHelp.jsp#fbSetupSession" rel="noopener noreferrer" target="_blank">
<span class="glyphicon glyphicon-info-sign">
</span>
</a>
</h5>
</div>
</div>
<h4 class="label-control col-xs-12 col-md-1 text-md">
Or:
</h4>
<div class="col-xs-12 col-md-3">
<a class="btn btn-info" id="button_copy" style="vertical-align:middle;">
Copy from previous feedback sessions
</a>
</div>
</div>
<br>
<div class="panel panel-primary">
<div class="panel-body">
<div class="row">
<div class="col-sm-12 col-md-6" data-original-title="Please select the course for which the feedback session is to be created." data-placement="top" data-toggle="tooltip" title="">
<div class="form-group has-error">
<h5 class="col-sm-2 col-md-4">
<label class="control-label" for="courseid">
Course ID
</label>
</h5>
<div class="col-sm-10 col-md-8">
<select class="form-control text-color-red" id="courseid" name="courseid">
<option selected="" value="">
No un-archived courses
</option>
</select>
</div>
</div>
</div>
<div class="col-sm-12 col-md-6 tablet-no-mobile-margin-top-20px" data-original-title="You should not need to change this as your timezone is auto-detected. <br><br>However, note that daylight saving is not taken into account i.e. if you are in UTC -8:00 and there is daylight saving, you should choose UTC -7:00 and its corresponding timings." data-placement="top" data-toggle="tooltip" title="">
<div class="form-group">
<h5 class="col-sm-2 col-md-4">
<label class="control-label" for="timezone">
Timezone
</label>
</h5>
<div class="col-sm-10 col-md-8">
<select class="form-control" id="timezone" name="timezone">
<option value="-12">
(UTC -12:00) Baker Island, Howland Island
</option>
<option value="-11">
(UTC -11:00) American Samoa, Niue
</option>
<option value="-10">
(UTC -10:00) Hawaii, Cook Islands
</option>
<option value="-9.5">
(UTC -09:30) Marquesas Islands
</option>
<option value="-9">
(UTC -09:00) Gambier Islands, Alaska
</option>
<option value="-8">
(UTC -08:00) Los Angeles, Vancouver, Tijuana
</option>
<option value="-7">
(UTC -07:00) Phoenix, Calgary, Ciudad Juárez
</option>
<option value="-6">
(UTC -06:00) Chicago, Guatemala City, Mexico City, San José, San Salvador, Tegucigalpa, Winnipeg
</option>
<option value="-5">
(UTC -05:00) New York, Lima, Toronto, Bogotá, Havana, Kingston
</option>
<option value="-4.5">
(UTC -04:30) Caracas
</option>
<option value="-4">
(UTC -04:00) Santiago, La Paz, San Juan de Puerto Rico, Manaus, Halifax
</option>
<option value="-3.5">
(UTC -03:30) St. John's
</option>
<option value="-3">
(UTC -03:00) Buenos Aires, Montevideo, São Paulo
</option>
<option value="-2">
(UTC -02:00) Fernando de Noronha, South Georgia and the South Sandwich Islands
</option>
<option value="-1">
(UTC -01:00) Cape Verde, Greenland, Azores islands
</option>
<option value="0">
(UTC) Accra, Abidjan, Casablanca, Dakar, Dublin, Lisbon, London
</option>
<option value="1">
(UTC +01:00) Belgrade, Berlin, Brussels, Lagos, Madrid, Paris, Rome, Tunis, Vienna, Warsaw
</option>
<option value="2">
(UTC +02:00) Athens, Sofia, Cairo, Kiev, Istanbul, Beirut, Helsinki, Jerusalem, Johannesburg, Bucharest
</option>
<option value="3">
(UTC +03:00) Nairobi, Baghdad, Doha, Khartoum, Minsk, Riyadh
</option>
<option value="3.5">
(UTC +03:30) Tehran
</option>
<option value="4">
(UTC +04:00) Baku, Dubai, Moscow
</option>
<option value="4.5">
(UTC +04:30) Kabul
</option>
<option value="5">
(UTC +05:00) Karachi, Tashkent
</option>
<option value="5.5">
(UTC +05:30) Colombo, Delhi
</option>
<option value="5.75">
(UTC +05:45) Kathmandu
</option>
<option value="6">
(UTC +06:00) Almaty, Dhaka, Yekaterinburg
</option>
<option value="6.5">
(UTC +06:30) Yangon
</option>
<option value="7">
(UTC +07:00) Jakarta, Bangkok, Novosibirsk, Hanoi
</option>
<option value="8">
(UTC +08:00) Perth, Beijing, Manila, Singapore, Kuala Lumpur, Denpasar, Krasnoyarsk
</option>
<option value="8.75">
(UTC +08:45) Eucla
</option>
<option value="9">
(UTC +09:00) Seoul, Tokyo, Pyongyang, Ambon, Irkutsk
</option>
<option value="9.5">
(UTC +09:30) Adelaide
</option>
<option value="10">
(UTC +10:00) Canberra, Yakutsk, Port Moresby
</option>
<option value="10.5">
(UTC +10:30) Lord Howe Islands
</option>
<option value="11">
(UTC +11:00) Vladivostok, Noumea
</option>
<option value="12">
(UTC +12:00) Auckland, Suva
</option>
<option value="12.75">
(UTC +12:45) Chatham Islands
</option>
<option value="13">
(UTC +13:00) Phoenix Islands, Tokelau, Tonga
</option>
<option value="14">
(UTC +14:00) Line Islands
</option>
</select>
</div>
</div>
</div>
</div>
<br class="hidden-xs">
<div class="row">
<div class="col-sm-12" data-original-title="Enter the name of the feedback session e.g. Feedback Session 1." data-placement="top" data-toggle="tooltip" title="">
<div class="form-group">
<h5 class="col-sm-2">
<label class="control-label" for="fsname">
Session name
</label>
</h5>
<div class="col-sm-10">
<input class="form-control" id="fsname" maxlength="38" name="fsname" placeholder="e.g. Feedback for Project Presentation 1" type="text" value="">
</div>
</div>
</div>
</div>
<br class="hidden-xs">
<div class="row" id="instructionsRow">
<div class="col-sm-12" data-original-title="Enter instructions for this feedback session. e.g. Avoid comments which are too critical.<br> It will be displayed at the top of the page when users respond to the session." data-placement="top" data-toggle="tooltip" title="">
<div class="form-group">
<h5 class="col-sm-2 margin-top-0">
<label class="control-label" for="instructions">
Instructions
</label>
</h5>
<div class="col-sm-10">
<div id="richtext-toolbar-container">
</div>
<div class="panel panel-default panel-body mce-content-body content-editor" contenteditable="true" id="instructions" spellcheck="false" style="position: relative;">
<p>
Please answer all the given questions.
</p>
</div>
<input name="instructions" type="hidden">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="panel panel-primary" id="timeFramePanel">
<div class="panel-body">
<div class="row">
<div class="col-md-5" data-original-title="Please select the date and time for which users can start submitting responses for the feedback session." data-placement="top" data-toggle="tooltip" title="">
<div class="row">
<div class="col-xs-12">
<label class="label-control" for="startdate">
Submission opening time
</label>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<input class="form-control col-sm-2 hasDatepicker" id="startdate" name="startdate" placeholder="Date" type="text" value="${date.nexthour}">
</div>
<div class="col-xs-6">
<select class="form-control" id="starttime" name="starttime">
<option value="1">
0100H
</option>
<option value="2">
0200H
</option>
<option value="3">
0300H
</option>
<option value="4">
0400H
</option>
<option value="5">
0500H
</option>
<option value="6">
0600H
</option>
<option value="7">
0700H
</option>
<option value="8">
0800H
</option>
<option value="9">
0900H
</option>
<option value="10">
1000H
</option>
<option value="11">
1100H
</option>
<option value="12">
1200H
</option>
<option value="13">
1300H
</option>
<option value="14">
1400H
</option>
<option value="15">
1500H
</option>
<option value="16">
1600H
</option>
<option value="17">
1700H
</option>
<option value="18">
1800H
</option>
<option value="19">
1900H
</option>
<option value="20">
2000H
</option>
<option value="21">
2100H
</option>
<option value="22">
2200H
</option>
<option value="23">
2300H
</option>
<option selected="" value="24">
2359H
</option>
</select>
</div>
</div>
</div>
<div class="col-md-5 border-left-gray" data-original-title="Please select the date and time after which the feedback session will no longer accept submissions from users." data-placement="top" data-toggle="tooltip" title="">
<div class="row">
<div class="col-xs-12">
<label class="label-control" for="enddate">
Submission closing time
</label>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<input class="form-control col-sm-2 hasDatepicker" id="enddate" name="enddate" placeholder="Date" type="text" value="">
</div>
<div class="col-xs-6">
<select class="form-control" id="endtime" name="endtime">
<option value="1">
0100H
</option>
<option value="2">
0200H
</option>
<option value="3">
0300H
</option>
<option value="4">
0400H
</option>
<option value="5">
0500H
</option>
<option value="6">
0600H
</option>
<option value="7">
0700H
</option>
<option value="8">
0800H
</option>
<option value="9">
0900H
</option>
<option value="10">
1000H
</option>
<option value="11">
1100H
</option>
<option value="12">
1200H
</option>
<option value="13">
1300H
</option>
<option value="14">
1400H
</option>
<option value="15">
1500H
</option>
<option value="16">
1600H
</option>
<option value="17">
1700H
</option>
<option value="18">
1800H
</option>
<option value="19">
1900H
</option>
<option value="20">
2000H
</option>
<option value="21">
2100H
</option>
<option value="22">
2200H
</option>
<option value="23">
2300H
</option>
<option selected="" value="24">
2359H
</option>
</select>
</div>
</div>
</div>
<div class="col-md-2 border-left-gray" data-original-title="Please select the amount of time that the system will continue accepting <br>submissions after the specified deadline." data-placement="top" data-toggle="tooltip" title="">
<div class="row">
<div class="col-xs-12">
<label class="control-label" for="graceperiod">
Grace period
</label>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<select class="form-control" id="graceperiod" name="graceperiod">
<option value="0">
0 mins
</option>
<option value="5">
5 mins
</option>
<option value="10">
10 mins
</option>
<option selected="" value="15">
15 mins
</option>
<option value="20">
20 mins
</option>
<option value="25">
25 mins
</option>
<option value="30">
30 mins
</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="uncommonSettingsSection">
<div class="panel panel-primary" id="sessionResponsesVisiblePanel" style="display:none;">
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6">
<div class="row">
<div class="col-xs-12" data-original-title="Please select when you want the questions for the feedback session to be visible to users who need to participate. Note that users cannot submit their responses until the submissions opening time set below." data-placement="top" data-toggle="tooltip" title="">
<label class="label-control">
Session visible from
</label>
</div>
</div>
<div class="row radio">
<h5 class="col-xs-2" data-original-title="Select this option to enter in a custom date and time for which the feedback session will become visible.<br>Note that you can make a session visible before it is open for submissions so that users can preview the questions." data-placement="top" data-toggle="tooltip" title="">
<label for="sessionVisibleFromButton_custom">
At
</label>
<input id="sessionVisibleFromButton_custom" name="sessionVisibleFromButton" type="radio" value="custom">
</h5>
<div class="col-xs-5">
<input class="form-control col-sm-2 hasDatepicker" disabled="" id="visibledate" name="visibledate" type="text" value="">
</div>
<div class="col-xs-5">
<select class="form-control" disabled="" id="visibletime" name="visibletime">
<option value="1">
0100H
</option>
<option value="2">
0200H
</option>
<option value="3">
0300H
</option>
<option value="4">
0400H
</option>
<option value="5">
0500H
</option>
<option value="6">
0600H
</option>
<option value="7">
0700H
</option>
<option value="8">
0800H
</option>
<option value="9">
0900H
</option>
<option value="10">
1000H
</option>
<option value="11">
1100H
</option>
<option value="12">
1200H
</option>
<option value="13">
1300H
</option>
<option value="14">
1400H
</option>
<option value="15">
1500H
</option>
<option value="16">
1600H
</option>
<option value="17">
1700H
</option>
<option value="18">
1800H
</option>
<option value="19">
1900H
</option>
<option value="20">
2000H
</option>
<option value="21">
2100H
</option>
<option value="22">
2200H
</option>
<option value="23">
2300H
</option>
<option selected="" value="24">
2359H
</option>
</select>
</div>
</div>
<div class="row radio">
<div class="col-xs-12" data-original-title="Select this option to have the feedback session become visible when it is open for submissions (as selected above)." data-placement="top" data-toggle="tooltip" title="">
<label for="sessionVisibleFromButton_atopen">
Submission opening time
</label>
<input checked="" id="sessionVisibleFromButton_atopen" name="sessionVisibleFromButton" type="radio" value="atopen">
</div>
</div>
<div class="row radio">
<div class="col-xs-12" data-original-title="Select this option if you want the feedback session to be private. A private session is never visible to anyone. Private sessions can be used to record your own comments about others, for your own reference." data-placement="top" data-toggle="tooltip" title="">
<label for="sessionVisibleFromButton_never">
Never
</label>
<input id="sessionVisibleFromButton_never" name="sessionVisibleFromButton" type="radio" value="never">
</div>
</div>
</div>
<div class="col-xs-12 col-md-6 border-left-gray" id="responsesVisibleFromColumn">
<div class="row">
<div class="col-xs-12" data-original-title="Please select when the responses for the feedback session will be visible to the designated recipients.<br>You can select the response visibility for each type of user and question later." data-placement="top" data-toggle="tooltip" title="">
<label class="label-control">
Responses visible from
</label>
</div>
</div>
<div class="row radio">
<h5 class="col-xs-2" data-original-title="Select this option to use a custom time for when the responses of the feedback session<br>will be visible to the designated recipients." data-placement="top" data-toggle="tooltip" title="">
<label for="resultsVisibleFromButton_custom">
At
</label>
<input id="resultsVisibleFromButton_custom" name="resultsVisibleFromButton" type="radio" value="custom">
</h5>
<div class="col-xs-5">
<input class="form-control hasDatepicker" disabled="" id="publishdate" name="publishdate" type="text" value="">
</div>
<div class="col-xs-5">
<select class="form-control" data-original-title="Select this option to enter in a custom date and time for which</br>the responses for this feedback session will become visible." data-placement="top" data-toggle="tooltip" disabled="" id="publishtime" name="publishtime" title="">
<option value="1">
0100H
</option>
<option value="2">
0200H
</option>
<option value="3">
0300H
</option>
<option value="4">
0400H
</option>
<option value="5">
0500H
</option>
<option value="6">
0600H
</option>
<option value="7">
0700H
</option>
<option value="8">
0800H
</option>
<option value="9">
0900H
</option>
<option value="10">
1000H
</option>
<option value="11">
1100H
</option>
<option value="12">
1200H
</option>
<option value="13">
1300H
</option>
<option value="14">
1400H
</option>
<option value="15">
1500H
</option>
<option value="16">
1600H
</option>
<option value="17">
1700H
</option>
<option value="18">
1800H
</option>
<option value="19">
1900H
</option>
<option value="20">
2000H
</option>
<option value="21">
2100H
</option>
<option value="22">
2200H
</option>
<option value="23">
2300H
</option>
<option selected="" value="24">
2359H
</option>
</select>
</div>
</div>
<div class="row radio">
<div class="col-xs-12" data-original-title="Select this option to have the feedback responses be immediately visible<br>when the session becomes visible to users." data-placement="top" data-toggle="tooltip" title="">
<label for="resultsVisibleFromButton_atvisible">
Immediately
</label>
<input id="resultsVisibleFromButton_atvisible" name="resultsVisibleFromButton" type="radio" value="atvisible">
</div>
</div>
<div class="row radio">
<div class="col-xs-12" data-original-title="Select this option if you intend to manually publish the responses for this session later on." data-placement="top" data-toggle="tooltip" title="">
<label for="resultsVisibleFromButton_later">
Publish manually
</label>
<input checked="" id="resultsVisibleFromButton_later" name="resultsVisibleFromButton" type="radio" value="later">
</div>
</div>
<div class="row radio">
<div class="col-xs-12" data-original-title="Select this option if you intend never to publish the responses." data-placement="top" data-toggle="tooltip" title="">
<label for="resultsVisibleFromButton_never">
Never
</label>
<input id="resultsVisibleFromButton_never" name="resultsVisibleFromButton" type="radio" value="never">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="panel panel-primary" id="sendEmailsForPanel" style="display:none;">
<div class="panel-body">
<div class="row">
<div class="col-md-12">
<label class="control-label">
Send emails for
</label>
</div>
</div>
<div class="row">
<div class="col-md-3" data-original-title="Select this option to automatically send an email to students to notify them when the session is open for submission." data-placement="top" data-toggle="tooltip" title="">
<div class="checkbox">
<label>
Session opening reminder
</label>
<input checked="" disabled="" id="sendreminderemail_open" name="sendreminderemail" type="checkbox" value="FEEDBACK_OPENING">
</div>
</div>
<div class="col-md-3" data-original-title="Select this option to automatically send an email to students to remind them to submit 24 hours before the end of the session." data-placement="top" data-toggle="tooltip" title="">
<div class="checkbox">
<label for="sendreminderemail_closing">
Session closing reminder
</label>
<input checked="" id="sendreminderemail_closing" name="sendreminderemail" type="checkbox" value="FEEDBACK_CLOSING">
</div>
</div>
<div class="col-md-4" data-original-title="Select this option to automatically send an email to students to notify them when the session results is published." data-placement="top" data-toggle="tooltip" title="">
<div class="checkbox">
<label for="sendreminderemail_published">
Results published announcement
</label>
<input checked="" id="sendreminderemail_published" name="sendreminderemail" type="checkbox" value="FEEDBACK_PUBLISHED">
</div>
</div>
</div>
</div>
</div>
<div class="margin-bottom-15px text-muted" id="uncommonSettingsSessionResponsesVisible">
<span id="uncommonSettingsSessionResponsesVisibleInfoText">
Session is visible at submission opening time, responses are only visible when you publish the results.
</span>
<a class="editUncommonSettingsButton" data-done="[Done]" data-edit="[Edit]" id="editUncommonSettingsSessionResponsesVisibleButton">
[Change]
</a>
</div>
<div class="margin-bottom-15px text-muted" id="uncommonSettingsSendEmails">
<span id="uncommonSettingsSendEmailsInfoText">
Emails are sent when session opens (within 15 mins), 24 hrs before session closes and when results are published.
</span>
<a class="editUncommonSettingsButton" data-done="[Done]" data-edit="[Edit]" id="editUncommonSettingsSendEmailsButton">
[Change]
</a>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-offset-5 col-md-3">
<button class="btn btn-primary" disabled="" id="button_submit" type="submit">
Create Feedback Session
</button>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-center">
<b>
You need to have an active(unarchived) course to create a session!
</b>
</div>
</div>
<input name="user" type="hidden" value="CFeedbackUiT.nocourses">
</form>
</div>
<form action="/page/instructorFeedbacksPage" class="ajaxForSessionsForm" id="ajaxForSessions" style="display:none;">
<input name="user" type="hidden" value="CFeedbackUiT.nocourses">
<input name="isusingAjax" type="hidden" value="on">
</form>
<br>
<div id="statusMessagesToUser" style="display: block;">
<div class="overflow-auto alert alert-warning statusMessage">
You have not created any courses yet, or you have no active courses. Go
<a href="/page/instructorCoursesPage?user=CFeedbackUiT.nocourses">
here
</a>
to create or unarchive a course.
</div>
</div>
<script defer="" src="/js/statusMessage.js" type="text/javascript">
</script>
<br>
<div class="" id="sessionList">
<table class="table-responsive table table-striped table-bordered" id="table-sessions">
<thead>
<tr class="fill-primary">
<th class="button-sort-ascending course-id-table-width" id="button_sortid" onclick="toggleSort(this);">
Course ID
<span class="icon-sort unsorted">
</span>
</th>
<th class="button-sort-none session-name-table-width" id="button_sortname" onclick="toggleSort(this)">
Session Name
<span class="icon-sort unsorted">
</span>
</th>
<th>
Status
</th>
<th>
<span class="tool-tip-decorate" data-original-title="Number of students submitted / Class size" data-placement="top" data-toggle="tooltip" title="">
Response Rate
</span>
</th>
<th class="no-print">
Action(s)
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</tbody>
</table>
<p class="col-md-12 text-muted">
Note: The table above doesn't contain sessions from archived courses. To view sessions from an archived course, unarchive the course first.
</p>
<br>
<br>
<br>
<div class="align-center">
No records found.
</div>
<br>
<br>
<br>
</div>
<div aria-hidden="true" aria-labelledby="remindModal" class="modal fade" id="remindModal" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<form action="/page/instructorFeedbackRemindParticularStudents?next=%2Fpage%2FinstructorFeedbacksPage" method="post" name="form_remind_list" role="form">
<div class="modal-header">
<button aria-hidden="true" class="close" data-dismiss="modal" type="button">
×
</button>
<h4 class="modal-title">
Remind Particular Students
<small>
(Select the student(s) you want to remind)
</small>
</h4>
</div>
<div class="modal-body">
<div class="form-group" id="studentList">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal" type="button">
Cancel
</button>
<input class="btn btn-primary" type="submit" value="Remind">
<input name="user" type="hidden" value="CFeedbackUiT.nocourses">
</div>
</form>
</div>
</div>
</div>
<div aria-hidden="true" aria-labelledby="copyModalTitle" class="modal fade" id="copyModal" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal" type="button">
<span aria-hidden="true">
×
</span>
<span class="sr-only">
Close
</span>
</button>
<h4 class="modal-title" id="copyModalTitle">
Creating a new session by copying a previous session
</h4>
</div>
<div class="modal-body" id="copySessionsBody">
<form action="/page/instructorFeedbackCopy" class="form" id="copyModalForm" method="post" role="form">
<div class="form-group">
<label class="control-label" for="modalCopiedCourseId">
Create in course
</label>
<select class="form-control" id="modalCopiedCourseId" name="copiedcourseid">
<option selected="" value="">
No un-archived courses
</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="modalCopiedSessionName">
Name for new session
</label>
<input class="form-control" id="modalCopiedSessionName" maxlength="38" name="copiedfsname" placeholder="e.g. Feedback for Project Presentation 1" type="text" value="">
</div>
<label>
Copy sessions/questions from
</label>
<table class="table-responsive table table-bordered table-hover margin-0" id="copyTableModal">
<thead class="fill-primary">
<tr>
<th style="width:20px;">
</th>
<th>
Course ID
</th>
<th>
Feedback Session Name
</th>
</tr>
</thead>
</table>
<input id="modalSessionName" name="fsname" type="hidden" value="">
<input id="modalCourseId" name="courseid" type="hidden" value="">
<input name="user" type="hidden" value="CFeedbackUiT.nocourses">
</form>
</div>
<div class="modal-footer margin-0">
<button class="btn btn-primary" disabled="" id="button_copy_submit" type="button">
Copy
</button>
<button class="btn btn-default" data-dismiss="modal" type="button">
Cancel
</button>
</div>
</div>
</div>
</div>
<div aria-hidden="true" aria-labelledby="fsCopyModal" class="modal fade" id="fsCopyModal" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<form action="/page/instructorFeedbackEditCopy?next=%2Fpage%2FinstructorFeedbacksPage" id="instructorCopyModalForm" method="post" role="form">
<div class="modal-header">
<button aria-hidden="true" class="close" data-dismiss="modal" type="button">
×
</button>
<h4 class="modal-title">
Copy this feedback session to other courses
<br>
<small>
(Select the course(s) you want to copy this feedback session to)
</small>
</h4>
</div>
<div class="modal-body">
<div class="form-group" id="courseList">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal" type="button">
Cancel
</button>
<input class="btn btn-primary" id="fscopy_submit" type="submit" value="Copy">
<input name="user" type="hidden" value="CFeedbackUiT.nocourses">
</div>
</form>
</div>
</div>
</div>
</div>
<div class="container-fluid" id="footerComponent">
<div class="container">
<div class="row">
<div class="col-md-2">
<span>
[
<a href="/index.jsp">
TEAMMATES
</a>
V${version}]
</span>
</div>
<div class="col-md-8">
[for
<span class="highlight-white">
TEAMMATES Test Institute 1
</span>
]
</div>
<div class="col-md-2">
<span>
[Send
<a class="link" href="/contact.jsp" rel="noopener noreferrer" target="_blank">
Feedback
</a>
]
</span>
</div>
</div>
</div>
</div>
<script async="" src="https://ssl.google-analytics.com/ga.js" type="text/javascript">
</script>
<script src="/js/googleAnalytics.js" type="text/javascript">
</script>
<script src="https://unpkg.com/[email protected]/dist/jquery.min.js" type="text/javascript">
</script>
<script src="https://unpkg.com/[email protected]/jquery-ui.min.js" type="text/javascript">
</script>
<script src="https://unpkg.com/[email protected]/dist/js/bootstrap.min.js" type="text/javascript">
</script>
<script src="https://unpkg.com/[email protected]/bootbox.min.js" type="text/javascript">
</script>
<script src="/js/common.js" type="text/javascript">
</script>
<script src="https://unpkg.com/[email protected]/tinymce.min.js" type="text/javascript">
</script>
<script src="/js/richTextEditor.js" type="text/javascript">
</script>
<script src="/js/datepicker.js" type="text/javascript">
</script>
<script src="/js/instructor.js" type="text/javascript">
</script>
<script src="/js/ajaxResponseRate.js" type="text/javascript">
</script>
<script src="/js/instructorFeedbackAjaxRemindModal.js" type="text/javascript">
</script>
<script src="/js/instructorFeedbacksAjax.js" type="text/javascript">
</script>
<script src="/js/instructorFeedbacks.js" type="text/javascript">
</script>
<script src="/js/instructorFeedbacksSpecific.js" type="text/javascript">
</script>
<div class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" id="ui-datepicker-div">
</div>
</body>
</html>
| Java |
<?php
////////////////////////////////////////////////////////////////////////////////
// //
// 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. //
// //
// This product released under GNU General Public License v2 //
////////////////////////////////////////////////////////////////////////////////
/**
* Debug on/off
*/
define("DEBUG", 0);
$query_counter = 0;
if (!extension_loaded('mysql')) {
/**
* MySQLi database layer
*
*/
if (!($db_config = @parse_ini_file('config/' . 'signup.ini'))) {
print('Cannot load mysql configuration');
exit;
}
$dbport = (empty($db_config['port'])) ? 3306 : $db_config['port'];
$loginDB = new mysqli($db_config['server'], $db_config['username'], $db_config['password'], $db_config['db'], $dbport);
if ($loginDB->connect_error) {
die('Connection error (' . $loginDB->connect_errno . ') '
. $loginDB->connect_error);
} else {
$loginDB->query("set character_set_client='" . $db_config['character'] . "'");
$loginDB->query("set character_set_results='" . $db_config['character'] . "'");
$loginDB->query("set collation_connection='" . $db_config['character'] . "_general_ci'");
}
/**
* Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
*
* @global mysqli $loginDB
* @param aata to filter $parametr
*
* @return string
*/
function loginDB_real_escape_string($parametr) {
global $loginDB;
$result = $loginDB->real_escape_string($parametr);
return($result);
}
if (!function_exists('mysql_real_escape_string')) {
/**
* Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
*
* @param string $data
*
* @return string
*/
function mysql_real_escape_string($data) {
return(loginDB_real_escape_string($data));
}
}
/**
* Executing query and returns result as array
*
* @global int $query_counter
* @param string $query
* @return array
*/
function simple_queryall($query) {
global $loginDB, $query_counter;
if (DEBUG) {
print ($query . "\n");
}
$result = array();
$queried = $loginDB->query($query) or die('wrong data input: ' . $query);
while ($row = mysqli_fetch_assoc($queried)) {
$result[] = $row;
}
$query_counter++;
return($result);
}
/**
* Executing query and returns array of first result
*
* @global int $query_counter
* @param string $query
* @return array
*/
function simple_query($query) {
global $loginDB, $query_counter;
if (DEBUG) {
print ($query . "\n");
}
$queried = $loginDB->query($query) or die('wrong data input: ' . $query);
$result = mysqli_fetch_assoc($queried);
$query_counter++;
return($result);
}
/**
* Updates single field in table with where expression
*
* @param string $tablename
* @param string $field
* @param string $value
* @param string $where
* @param bool $NoQuotesAroundValue
*/
function simple_update_field($tablename, $field, $value, $where = '', $NoQuotesAroundValue = false) {
$tablename = loginDB_real_escape_string($tablename);
$value = loginDB_real_escape_string($value);
$field = loginDB_real_escape_string($field);
if ($NoQuotesAroundValue) {
$query = "UPDATE `" . $tablename . "` SET `" . $field . "` = " . $value . " " . $where . "";
} else {
$query = "UPDATE `" . $tablename . "` SET `" . $field . "` = '" . $value . "' " . $where . "";
}
nr_query($query);
}
/**
* Returns last used `id` field available in some table
*
* @param string $tablename
* @return int
*/
function simple_get_lastid($tablename) {
$tablename = loginDB_real_escape_string($tablename);
$query = "SELECT `id` from `" . $tablename . "` ORDER BY `id` DESC LIMIT 1";
$result = simple_query($query);
return($result['id']);
}
/**
* Just executing single query
*
* @global int $query_counter
* @param string $query
* @return mixed
*/
function nr_query($query) {
global $loginDB, $query_counter;
if (DEBUG) {
print ($query . "\n");
}
$queried = $loginDB->query($query) or die('wrong data input: ' . $query);
$query_counter++;
return($queried);
}
} else {
/**
* MySQL database old driver abstraction class
*
*/
class MySQLDB {
var $connection;
var $last_query_num = 0;
var $db_config = array();
/**
* last query result id
*
* @var MySQL result
*/
var $lastresult;
/**
* last query assoc value
*
* @var bool
*/
var $assoc = true;
/**
* Initialises connection with MySQL database server and selects needed db
*
* @param MySQL Connection Id $connection
* @return MySQLDB
*/
public function __construct($connection = false) {
if ($connection)
$this->connection = $connection;
else {
if (!($this->db_config = @parse_ini_file('config/' . 'signup.ini'))) {
print(('Cannot load mysql configuration'));
return false;
}
if (!extension_loaded('mysql')) {
print(('Unable to load module for database server "mysql": PHP mysql extension not available!'));
return false;
}
$dbport = (empty($this->db_config['port'])) ? 3306 : $this->db_config['port'];
$this->connection = @mysql_connect($this->db_config['server'] . ':' . $dbport, $this->db_config['username'], $this->db_config['password']);
}
if (empty($this->connection)) {
print(('Unable to connect to database server!'));
return false;
} else if (!@mysql_select_db($this->db_config['db'], $this->connection)) {
$this->db_error();
return false;
}
mysql_query("set character_set_client='" . $this->db_config['character'] . "'");
mysql_query("set character_set_results='" . $this->db_config['character'] . "'");
mysql_query("set collation_connection='" . $this->db_config['character'] . "_general_ci'");
return true;
}
/**
* Executes query and returns result identifier
*
* @param string $query
* @return MySQL result
*/
function query($query) {
// use escape/vf function for input data.
$result = @mysql_query($query, $this->connection) or $this->db_error(0, $query);
$this->last_query_num++;
return $result;
}
/**
* Executes query and makes abstract data read available
*
* @param string $query
* @param bool $assoc
*/
function ExecuteReader($query, $assoc = true) {
$this->lastresult = $this->query($query);
$this->assoc = $assoc;
}
/**
* Link to query method
*
* @param string $query
* @return MySQL result
*/
function ExecuteNonQuery($query) {
$result = $this->query($query);
return (mysql_affected_rows() == 0 ? false : $result);
}
/**
* Returns array with from the current query result
*
* @return array
*/
function Read() {
if ($this->assoc) {
$result = @mysql_fetch_assoc($this->lastresult) or false;
} else {
$result = @mysql_fetch_row($this->lastresult) or false;
}
return $result;
}
/**
* Returns one row from the current query result
*
* @param int $row
* @return string
*/
function ReadSingleRow($row) {
return mysql_result($this->lastresult, $row) or false;
}
/**
* Prints MySQL error message; swithing DEBUG, prints MySQL error description or sends it to administrator
*
*/
function db_error($show = 0, $query = '') {
global $system;
if (!in_array(mysql_errno(), array(1062, 1065, 1191))) { // Errcodes in array are handled at another way :)
if (DEBUG == 1 || $show == 1) {
$warning = '<br><b>' . ('MySQL Error') . ':</b><br><i>';
$warning.=mysql_errno() . ' : ' . mysql_error() . (empty($query) ? '</i>' : '<br>In query: <textarea cols="50" rows="7">' . $query . '</textarea></i>');
print($warning) or print($warning);
} else {
print('An error occured. Please, try again later. Thank You !');
@$message.=mysql_errno() . ':' . mysql_error() . "\r\n";
$message.=(empty($query) ? '' : "In query: \r\n" . $query . "\r\n");
die('MySQL error ' . $message);
}
}
}
/**
* Escapes string to use in SQL query
*
* @param string $string
* @return string
*/
function escape($string) {
if (!get_magic_quotes_gpc())
return mysql_real_escape_string($string, $this->connection);
else
return mysql_real_escape_string(stripslashes($string), $this->connection);
}
/**
* Disconnects from database server
*
*/
function disconnect() {
@mysql_close($this->connection);
}
}
/**
* Executing query and returns result as array
*
* @global int $query_counter
* @param string $query
* @return array
*/
function simple_queryall($query) {
global $query_counter;
if (DEBUG) {
print ($query . "\n");
}
$result = '';
$queried = mysql_query($query) or die('wrong data input: ' . $query);
while ($row = mysql_fetch_assoc($queried)) {
$result[] = $row;
}
$query_counter++;
return($result);
}
/**
* Executing query and returns array of first result
*
* @global int $query_counter
* @param string $query
* @return array
*/
function simple_query($query) {
global $query_counter;
if (DEBUG) {
print ($query . "\n");
}
$queried = mysql_query($query) or die('wrong data input: ' . $query);
$result = mysql_fetch_assoc($queried);
$query_counter++;
return($result);
}
/**
* Updates single field in table with where expression
*
* @param string $tablename
* @param string $field
* @param string $value
* @param string $where
* @param bool $NoQuotesAroundValue
*/
function simple_update_field($tablename, $field, $value, $where = '', $NoQuotesAroundValue = false) {
$tablename = mysql_real_escape_string($tablename);
$value = mysql_real_escape_string($value);
$field = mysql_real_escape_string($field);
if ($NoQuotesAroundValue) {
$query = "UPDATE `" . $tablename . "` SET `" . $field . "` = " . $value . " " . $where . "";
} else {
$query = "UPDATE `" . $tablename . "` SET `" . $field . "` = '" . $value . "' " . $where . "";
}
nr_query($query);
}
/**
* Returns last used `id` field available in some table
*
* @param string $tablename
* @return int
*/
function simple_get_lastid($tablename) {
$tablename = mysql_real_escape_string($tablename);
$query = "SELECT `id` from `" . $tablename . "` ORDER BY `id` DESC LIMIT 1";
$result = simple_query($query);
return ($result['id']);
}
/**
* Just executing single query
*
* @global int $query_counter
* @param string $query
* @return mixed
*/
function nr_query($query) {
global $query_counter;
if (DEBUG) {
print ($query . "\n");
}
$queried = mysql_query($query) or die('wrong data input: ' . $query);
$query_counter++;
return($queried);
}
//creating mysql connection object instance
$db = new MySQLDB();
}
/**
* Returns cutted down data entry
* Available modes:
* 1 - digits, letters
* 2 - only letters
* 3 - only digits
* 4 - digits, letters, "-", "_", "."
* 5 - current lang alphabet + digits + punctuation
* default - filter only blacklist chars
*
* @param string $data
* @param int $mode
* @return string
*/
function vf($data, $mode = 0) {
switch ($mode) {
case 1:
return preg_replace("#[^a-z0-9A-Z]#Uis", '', $data); // digits, letters
break;
case 2:
return preg_replace("#[^a-zA-Z]#Uis", '', $data); // letters
break;
case 3:
return preg_replace("#[^0-9]#Uis", '', $data); // digits
break;
case 4:
return preg_replace("#[^a-z0-9A-Z\-_\.]#Uis", '', $data); // digits, letters, "-", "_", "."
break;
case 5:
return preg_replace("#[^ [:punct:]" . ('a-zA-Z') . "0-9]#Uis", '', $data); // current lang alphabet + digits + punctuation
break;
default:
return preg_replace("#[~@\+\?\%\/\;=\*\>\<\"\'\-]#Uis", '', $data); // black list anyway
break;
}
}
?>
| Java |
/***************************************************************************
qgsnewnamedialog.cpp
-------------------
begin : May, 2015
copyright : (C) 2015 Radim Blazek
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QRegExpValidator>
#include <QSizePolicy>
#include "qgslogger.h"
#include "qgsnewnamedialog.h"
QgsNewNameDialog::QgsNewNameDialog( const QString& source, const QString& initial,
const QStringList& extensions, const QStringList& existing,
const QRegExp& regexp, Qt::CaseSensitivity cs,
QWidget *parent, Qt::WindowFlags flags )
: QgsDialog( parent, flags, QDialogButtonBox::Ok | QDialogButtonBox::Cancel )
, mExiting( existing )
, mExtensions( extensions )
, mCaseSensitivity( cs )
, mNamesLabel( 0 )
, mRegexp( regexp )
{
setWindowTitle( tr( "New name" ) );
QDialog::layout()->setSizeConstraint( QLayout::SetMinimumSize );
layout()->setSizeConstraint( QLayout::SetMinimumSize );
layout()->setSpacing( 6 );
mOkString = buttonBox()->button( QDialogButtonBox::Ok )->text();
QString hintString;
QString nameDesc = mExtensions.isEmpty() ? tr( "name" ) : tr( "base name" );
if ( source.isEmpty() )
{
hintString = tr( "Enter new %1" ).arg( nameDesc );
}
else
{
hintString = tr( "Enter new %1 for %2" ).arg( nameDesc ).arg( source );
}
QLabel* hintLabel = new QLabel( hintString, this );
layout()->addWidget( hintLabel );
mLineEdit = new QLineEdit( initial, this );
if ( !regexp.isEmpty() )
{
QRegExpValidator *validator = new QRegExpValidator( regexp, this );
mLineEdit->setValidator( validator );
}
connect( mLineEdit, SIGNAL( textChanged( QString ) ), this, SLOT( nameChanged() ) );
layout()->addWidget( mLineEdit );
mNamesLabel = new QLabel( " ", this );
mNamesLabel->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
if ( !mExtensions.isEmpty() )
{
mNamesLabel->setWordWrap( true );
layout()->addWidget( mNamesLabel );
}
mErrorLabel = new QLabel( " ", this );
mErrorLabel->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
mErrorLabel->setWordWrap( true );
layout()->addWidget( mErrorLabel );
nameChanged();
}
QString QgsNewNameDialog::highlightText( const QString& text )
{
return "<b>" + text + "</b>";
}
void QgsNewNameDialog::nameChanged()
{
QgsDebugMsg( "entered" );
QString namesString = tr( "Full names" ) + ": ";
if ( !mExtensions.isEmpty() )
{
mNamesLabel->setText( namesString );
}
mErrorLabel->setText( " " ); // space to keep vertical space
QPushButton* okButton = buttonBox()->button( QDialogButtonBox::Ok );
okButton->setText( mOkString );
okButton->setEnabled( true );
QString newName = name();
if ( newName.length() == 0 || ( !mRegexp.isEmpty() && !mRegexp.exactMatch( newName ) ) )
{
//mErrorLabel->setText( highlightText( tr( "Enter new name" ) );
okButton->setEnabled( false );
return;
}
QStringList newNames = fullNames( newName, mExtensions );
if ( !mExtensions.isEmpty() )
{
namesString += " " + newNames.join( ", " );
mNamesLabel->setText( namesString );
}
QStringList conflicts = matching( newNames, mExiting, mCaseSensitivity );
if ( !conflicts.isEmpty() )
{
mErrorLabel->setText( highlightText( tr( "%n Name(s) %1 exists", 0, conflicts.size() ).arg( conflicts.join( ", " ) ) ) );
okButton->setText( tr( "Overwrite" ) );
return;
}
}
QString QgsNewNameDialog::name() const
{
return mLineEdit->text().trimmed();
}
QStringList QgsNewNameDialog::fullNames( const QString& name, const QStringList& extensions )
{
QStringList list;
foreach ( QString ext, extensions )
{
list << name + ext;
}
if ( list.isEmpty() )
{
list << name;
}
return list;
}
QStringList QgsNewNameDialog::matching( const QStringList& newNames, const QStringList& existingNames,
Qt::CaseSensitivity cs )
{
QStringList list;
foreach ( QString newName, newNames )
{
foreach ( QString existingName, existingNames )
{
if ( existingName.compare( newName, cs ) == 0 )
{
list << existingName;
}
}
}
return list;
}
bool QgsNewNameDialog::exists( const QString& name, const QStringList& extensions,
const QStringList& existing, Qt::CaseSensitivity cs )
{
QStringList newNames = fullNames( name, extensions );
QStringList conflicts = matching( newNames, existing, cs );
return conflicts.size() > 0;
}
| Java |
<?php
/**
* Download a package by passing in its location
*
* @var modX $this->modx
*
* @package modx
* @subpackage processors.workspace.packages.rest
*/
class modPackageDownloadProcessor extends modProcessor {
/** @var modTransportProvider $provider */
public $provider;
/** @var string $location The actual file location of the download */
public $location;
/** @var string $signature The signature of the transport package */
public $signature;
/** @var modTransportPackage $package */
public $package;
/**
* Ensure user has access to do this
*
* {@inheritDoc}
* @return boolean
*/
public function checkPermissions() {
return $this->modx->hasPermission('packages');
}
/**
* The language topics to load
*
* {@inheritDoc}
* @return array
*/
public function getLanguageTopics() {
return array('workspace');
}
/**
* Ensure the info was properly passed and initialize the processor
*
* {@inheritDoc}
* @return boolean
*/
public function initialize() {
@set_time_limit(0);
$info = $this->getProperty('info','');
if (empty($info)) return $this->modx->lexicon('package_download_err_ns');
if (!$this->parseInfo($info)) {
return $this->modx->lexicon('invalid_data');
}
return parent::initialize();
}
/**
* Run the processor, downloading and transferring the package, and creating the metadata in the database
* {@inheritDoc}
* @return mixed
*/
public function process() {
if (!$this->loadProvider()) {
return $this->failure($this->modx->lexicon('provider_err_nf'));
}
$this->package = $this->provider->transfer($this->signature, null, array('location' => $this->location));
if (!$this->package) {
return $this->failure($this->modx->lexicon('package_download_err_create', array('signature' => $this->signature)));
}
return $this->success('', $this->package);
}
/**
* Load the provider for the package
* @return boolean
*/
public function loadProvider() {
$provider = $this->getProperty('provider');
if (empty($provider)) {
$c = $this->modx->newQuery('transport.modTransportProvider');
$c->where(array(
'name:=' => 'modxcms.com',
'OR:name:=' => 'modx.com',
));
$this->provider = $this->modx->getObject('transport.modTransportProvider',$c);
if (!empty($this->provider)) {
$this->setProperty('provider',$this->provider->get('id'));
}
} else {
$this->provider = $this->modx->getObject('transport.modTransportProvider',$provider);
}
return !empty($this->provider);
}
/**
* Parse the information sent to the processor
* @param string $info
* @return boolean
*/
public function parseInfo($info) {
$parsed = false;
$parsedInfo = explode('::',$info);
if (!empty($parsedInfo) && !empty($parsedInfo[1])) {
$this->location = $parsedInfo[0];
$this->signature = $parsedInfo[1];
$parsed = true;
}
return $parsed;
}
}
return 'modPackageDownloadProcessor';
| Java |
make clean
rm -v Makefile Makefile.inc config.log config.status src/config.h src/config.inc | Java |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'find', 'cs', {
find: 'Hledat',
findOptions: 'Možnosti hledání',
findWhat: 'Co hledat:',
matchCase: 'Rozlišovat velikost písma',
matchCyclic: 'Procházet opakovaně',
matchWord: 'Pouze celá slova',
notFoundMsg: 'Hledaný text nebyl nalezen.',
replace: 'Nahradit',
replaceAll: 'Nahradit vše',
replaceSuccessMsg: '%1 nahrazení.',
replaceWith: 'Čím nahradit:',
title: 'Najít a nahradit'
} );
| Java |
/* about */
body#about label, body#about input[type='radio']{
display: inline;
float: none;
}
| Java |
//>>built
define("dojox/editor/plugins/nls/zh-tw/SafePaste",({"instructions":"已停用直接貼上。請使用標準瀏覽器鍵盤或功能表貼上控制項,在這個對話框中貼上內容。當您滿意要插入的內容之後,請按貼上按鈕。若要中斷插入內容,請按取消按鈕。"}));
| Java |
{extends} {#language.function.extends}
=========
`{extends}` tags are used in child templates in template inheritance for
extending parent templates. For details see section of [Template
Interitance](#advanced.features.template.inheritance).
- The `{extends}` tag must be on the first line of the template.
- If a child template extends a parent template with the `{extends}`
tag it may contain only `{block}` tags. Any other template content
is ignored.
- Use the syntax for [template resources](#resources) to extend files
outside of the [`$template_dir`](#variable.template.dir) directory.
> **Note**
>
> When extending a variable parent like `{extends file=$parent_file}`,
> make sure you include `$parent_file` in the
> [`$compile_id`](#variable.compile.id). Otherwise Smarty cannot
> distinguish between different `$parent_file`s.
**Attributes:**
Attribute Name Type Required Default Description
---------------- -------- ---------- --------- -------------------------------------------------
file string Yes *n/a* The name of the template file which is extended
{extends file='parent.tpl'}
{extends 'parent.tpl'} {* short-hand *}
See also [Template Interitance](#advanced.features.template.inheritance)
and [`{block}`](#language.function.block).
| Java |
/* *
* Copyright (C) 2009 Texas Instruments Inc
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/cdev.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/uaccess.h>
#include <linux/platform_device.h>
#include <linux/major.h>
#include <media/davinci/dm365_a3_hw.h>
#include <media/davinci/vpss.h>
/* Global structure */
static struct class *aew_class;
struct aew_device *aew_dev_configptr;
struct device *aewdev;
/* device structure to make entry in device*/
static dev_t dev;
/* For registeration of charatcer device*/
static struct cdev c_dev;
int aew_validate_parameters(void)
{
int result = 0;
/* Check horizontal Count */
if ((aew_dev_configptr->config->window_config.hz_cnt <
AEW_WINDOW_HORIZONTAL_COUNT_MIN)
|| (aew_dev_configptr->config->window_config.hz_cnt >
AEW_WINDOW_HORIZONTAL_COUNT_MAX)) {
dev_err(aewdev, "\n Horizontal Count is incorrect");
result = -EINVAL;
}
/* Check Vertical Count */
if ((aew_dev_configptr->config->window_config.vt_cnt <
AEW_WINDOW_VERTICAL_COUNT_MIN)
|| (aew_dev_configptr->config->window_config.vt_cnt >
AEW_WINDOW_VERTICAL_COUNT_MAX)) {
dev_err(aewdev, "\n Vertical Count is incorrect");
result = -EINVAL;
}
/* Check line increment */
if ((NOT_EVEN ==
CHECK_EVEN(aew_dev_configptr->config->window_config.
hz_line_incr))
|| (aew_dev_configptr->config->window_config.hz_line_incr <
AEW_HZ_LINEINCR_MIN)
|| (aew_dev_configptr->config->window_config.hz_line_incr >
AEW_HZ_LINEINCR_MAX)) {
dev_err(aewdev, "\n Invalid Parameters");
dev_err(aewdev, "\n Horizontal Line Increment is incorrect");
result = -EINVAL;
}
/* Check line increment */
if ((NOT_EVEN ==
CHECK_EVEN(aew_dev_configptr->config->window_config.
vt_line_incr))
|| (aew_dev_configptr->config->window_config.vt_line_incr <
AEW_VT_LINEINCR_MIN)
|| (aew_dev_configptr->config->window_config.vt_line_incr >
AEW_VT_LINEINCR_MAX)) {
dev_err(aewdev, "\n Invalid Parameters");
dev_err(aewdev, "\n Vertical Line Increment is incorrect");
result = -EINVAL;
}
/* Check width */
if ((NOT_EVEN ==
CHECK_EVEN(aew_dev_configptr->config->window_config.width))
|| (aew_dev_configptr->config->window_config.width <
AEW_WIDTH_MIN)
|| (aew_dev_configptr->config->window_config.width >
AEW_WIDTH_MAX)) {
dev_err(aewdev, "\n Width is incorrect");
result = -EINVAL;
}
/* Check Height */
if ((NOT_EVEN ==
CHECK_EVEN(aew_dev_configptr->config->window_config.height))
|| (aew_dev_configptr->config->window_config.height <
AEW_HEIGHT_MIN)
|| (aew_dev_configptr->config->window_config.height >
AEW_HEIGHT_MAX)) {
dev_err(aewdev, "\n height incorrect");
result = -EINVAL;
}
/* Check Horizontal Start */
if ((aew_dev_configptr->config->window_config.hz_start <
AEW_HZSTART_MIN)
|| (aew_dev_configptr->config->window_config.hz_start >
AEW_HZSTART_MAX)) {
dev_err(aewdev, "\n horizontal start is incorrect");
result = -EINVAL;
}
if ((aew_dev_configptr->config->window_config.vt_start >
AEW_VTSTART_MAX)) {
dev_err(aewdev, "\n Vertical start is incorrect");
result = -EINVAL;
}
if ((aew_dev_configptr->config->alaw_enable > H3A_AEW_ENABLE)
|| (aew_dev_configptr->config->alaw_enable < H3A_AEW_DISABLE)) {
dev_err(aewdev, "\n A Law setting is incorrect");
result = -EINVAL;
}
if (aew_dev_configptr->config->saturation_limit > AEW_AVELMT_MAX) {
dev_err(aewdev, "\n Saturation Limit is incorrect");
result = -EINVAL;
}
/* Check Black Window Height */
if (NOT_EVEN ==
CHECK_EVEN(aew_dev_configptr->config->blackwindow_config.height)
|| (aew_dev_configptr->config->blackwindow_config.height <
AEW_BLKWINHEIGHT_MIN)
|| (aew_dev_configptr->config->blackwindow_config.height >
AEW_BLKWINHEIGHT_MAX)) {
dev_err(aewdev, "\n Black Window height incorrect");
result = -EINVAL;
}
/* Check Black Window Height */
if ((NOT_EVEN ==
CHECK_EVEN(aew_dev_configptr->config->blackwindow_config.
height))
|| (aew_dev_configptr->config->blackwindow_config.vt_start <
AEW_BLKWINVTSTART_MIN)
|| (aew_dev_configptr->config->blackwindow_config.vt_start >
AEW_BLKWINVTSTART_MAX)) {
dev_err(aewdev, "\n Black Window vertical Start is incorrect");
result = -EINVAL;
}
if (aew_dev_configptr->config->out_format < AEW_OUT_SUM_OF_SQUARES ||
aew_dev_configptr->config->out_format > AEW_OUT_SUM_ONLY) {
dev_err(aewdev, "\n Invalid out_format");
result = -EINVAL;
}
if (aew_dev_configptr->config->sum_shift > AEW_SUMSHIFT_MAX) {
dev_err(aewdev, "\n sum_shift param is invalid, max = %d",
AEW_SUMSHIFT_MAX);
result = -EINVAL;
}
return result;
}
/* inline function to free reserver pages */
inline void aew_free_pages(unsigned long addr, unsigned long bufsize)
{
unsigned long tempaddr;
unsigned long size;
tempaddr = addr;
if (!addr)
return;
size = PAGE_SIZE << (get_order(bufsize));
while (size > 0) {
ClearPageReserved(virt_to_page(addr));
addr += PAGE_SIZE;
size -= PAGE_SIZE;
}
free_pages(tempaddr, get_order(bufsize));
}
/* Function to perform hardware Configuration */
int aew_hardware_setup(void)
{
int result;
/* Size for buffer in bytes */
int buff_size = 0;
unsigned long adr;
unsigned long size;
unsigned int busyaew;
/* Get the value of PCR register */
busyaew = aew_get_hw_state();
/* If H3A Engine is busy then return */
if (busyaew == 1) {
dev_err(aewdev, "\n Error : AEW Engine is busy");
return -EBUSY;
}
result = aew_validate_parameters();
dev_dbg(aewdev, "Result = %d\n", result);
if (result < 0) {
dev_err(aewdev, "Error : Parameters are incorrect \n");
return result;
}
/* Deallocate the previously allocated buffers */
if (aew_dev_configptr->buff_old)
aew_free_pages((unsigned long)aew_dev_configptr->buff_old,
aew_dev_configptr->size_window);
if (aew_dev_configptr->buff_curr)
aew_free_pages((unsigned long)aew_dev_configptr->
buff_curr, aew_dev_configptr->size_window);
if (aew_dev_configptr->buff_app)
aew_free_pages((unsigned long)aew_dev_configptr->
buff_app, aew_dev_configptr->size_window);
/*
* Allocat the buffers as per the new buffer size
* Allocate memory for old buffer
*/
if (aew_dev_configptr->config->out_format == AEW_OUT_SUM_ONLY)
buff_size = (aew_dev_configptr->config->window_config.hz_cnt) *
(aew_dev_configptr->config->window_config.vt_cnt) *
AEW_WINDOW_SIZE_SUM_ONLY;
else
buff_size = (aew_dev_configptr->config->window_config.hz_cnt) *
(aew_dev_configptr->config->window_config.vt_cnt) *
AEW_WINDOW_SIZE;
aew_dev_configptr->buff_old =
(void *)__get_free_pages(GFP_KERNEL | GFP_DMA,
get_order(buff_size));
if (aew_dev_configptr->buff_old == NULL)
return -ENOMEM;
/* Make pges reserved so that they will be swapped out */
adr = (unsigned long)aew_dev_configptr->buff_old;
size = PAGE_SIZE << (get_order(buff_size));
while (size > 0) {
/*
* make sure the frame buffers
* are never swapped out of memory
*/
SetPageReserved(virt_to_page(adr));
adr += PAGE_SIZE;
size -= PAGE_SIZE;
}
/* Allocate memory for current buffer */
aew_dev_configptr->buff_curr =
(void *)__get_free_pages(GFP_KERNEL | GFP_DMA,
get_order(buff_size));
if (aew_dev_configptr->buff_curr == NULL) {
/*Free all buffer that are allocated */
if (aew_dev_configptr->buff_old)
aew_free_pages((unsigned long)aew_dev_configptr->
buff_old, buff_size);
return -ENOMEM;
}
/* Make pges reserved so that they will be swapped out */
adr = (unsigned long)aew_dev_configptr->buff_curr;
size = PAGE_SIZE << (get_order(buff_size));
while (size > 0) {
/*
* make sure the frame buffers
* are never swapped out of memory
*/
SetPageReserved(virt_to_page(adr));
adr += PAGE_SIZE;
size -= PAGE_SIZE;
}
/* Allocate memory for application buffer */
aew_dev_configptr->buff_app =
(void *)__get_free_pages(GFP_KERNEL | GFP_DMA,
get_order(buff_size));
if (aew_dev_configptr->buff_app == NULL) {
/* Free all buffer that were allocated previously */
if (aew_dev_configptr->buff_old)
aew_free_pages((unsigned long)aew_dev_configptr->
buff_old, buff_size);
if (aew_dev_configptr->buff_curr)
aew_free_pages((unsigned long)aew_dev_configptr->
buff_curr, buff_size);
return -ENOMEM;
}
/* Make pages reserved so that they will be swapped out */
adr = (unsigned long)aew_dev_configptr->buff_app;
size = PAGE_SIZE << (get_order(buff_size));
while (size > 0) {
/*
* make sure the frame buffers
* are never swapped out of memory
*/
SetPageReserved(virt_to_page(adr));
adr += PAGE_SIZE;
size -= PAGE_SIZE;
}
/* Set the registers */
aew_register_setup(aewdev, aew_dev_configptr);
aew_dev_configptr->size_window = buff_size;
aew_dev_configptr->aew_config = H3A_AEW_CONFIG;
return 0;
}
/* This Function is called when driver is opened */
static int aew_open(struct inode *inode, struct file *filp)
{
/* Return if Device is in use (Single Channel Support is provided) */
if (aew_dev_configptr->in_use == AEW_IN_USE)
return -EBUSY;
/* Set the aew_dev_configptr structure */
aew_dev_configptr->config = NULL;
/* Allocate memory for configuration structure of this channel */
aew_dev_configptr->config = (struct aew_configuration *)
kmalloc(sizeof(struct aew_configuration), GFP_KERNEL);
if (aew_dev_configptr->config == NULL) {
dev_err(aewdev, "Error : Kmalloc fail\n");
return -ENOMEM;
}
/* Initiaze the wait queue */
init_waitqueue_head(&(aew_dev_configptr->aew_wait_queue));
/* Device is in use */
aew_dev_configptr->in_use = AEW_IN_USE;
/* No Hardware Set up done */
aew_dev_configptr->aew_config = H3A_AEW_CONFIG_NOT_DONE;
/* No statistics are available */
aew_dev_configptr->buffer_filled = 0;
/* Set Window Size to 0 */
aew_dev_configptr->size_window = 0;
/* Initialize the mutex */
mutex_init(&(aew_dev_configptr->read_blocked));
return 0;
}
static void aew_platform_release(struct device *device)
{
/* This is called when the reference count goes to zero */
}
static int aew_probe(struct device *device)
{
aewdev = device;
return 0;
}
static int aew_remove(struct device *device)
{
return 0;
}
/* This Function is called when driver is closed */
static int aew_release(struct inode *inode, struct file *filp)
{
aew_engine_setup(aewdev, 0);
/* The Application has closed device so device is not in use */
aew_dev_configptr->in_use = AEW_NOT_IN_USE;
/* Release memory for configuration structure of this channel */
kfree(aew_dev_configptr->config);
/* Free Old Buffer */
if (aew_dev_configptr->buff_old)
aew_free_pages((unsigned long)aew_dev_configptr->buff_old,
aew_dev_configptr->size_window);
/* Free Current Buffer */
if (aew_dev_configptr->buff_curr)
aew_free_pages((unsigned long)aew_dev_configptr->
buff_curr, aew_dev_configptr->size_window);
/* Free Application Buffer */
if (aew_dev_configptr->buff_app)
aew_free_pages((unsigned long)aew_dev_configptr->buff_app,
aew_dev_configptr->size_window);
aew_dev_configptr->buff_old = NULL;
aew_dev_configptr->buff_curr = NULL;
aew_dev_configptr->config = NULL;
aew_dev_configptr->buff_app = NULL;
return 0;
}
/*
* This function will process IOCTL commands sent by the application and
* control the devices IO operations.
*/
static int aew_ioctl(struct inode *inode, struct file *filep,
unsigned int cmd, unsigned long arg)
{
/* Stores Previous Configurations */
struct aew_configuration aewconfig = *(aew_dev_configptr->config);
int result = 0;
/* Decrement the semaphore */
result = mutex_lock_interruptible(&aew_dev_configptr->read_blocked);
if (result)
return result;
/*
* Extract the type and number bitfields, and don't decode wrong cmds:
* verify the magic number
*/
if (_IOC_TYPE(cmd) != AEW_MAGIC_NO) {
mutex_unlock(&aew_dev_configptr->read_blocked);
return -ENOTTY;
}
/* verify the command number */
if (_IOC_NR(cmd) > AEW_IOC_MAXNR) {
/* Release mutex in case of fault */
mutex_unlock(&aew_dev_configptr->read_blocked);
return -ENOTTY;
}
/* check for the permission of the operation */
if (_IOC_DIR(cmd) & _IOC_READ)
result =
!access_ok(VERIFY_WRITE, (void __user *)arg,
_IOC_SIZE(cmd));
else if (_IOC_DIR(cmd) & _IOC_WRITE)
result =
!access_ok(VERIFY_READ, (void __user *)arg, _IOC_SIZE(cmd));
if (result) {
/* Release mutex in case of fault */
mutex_unlock(&aew_dev_configptr->read_blocked);
return -EFAULT;
}
/* Switch according to IOCTL command */
switch (cmd) {
/*
* This ioctl is used to perform hardware set up
* and will set all the registers for AF engine
*/
case AEW_S_PARAM:
/* Copy config structure passed by user */
if (copy_from_user(aew_dev_configptr->config,
(struct aew_configuration *)arg,
sizeof(struct aew_configuration))) {
*(aew_dev_configptr->config) = aewconfig;
mutex_unlock(&aew_dev_configptr->read_blocked);
return -EFAULT;
}
/* Call aew_hardware_setup to perform register configuration */
result = aew_hardware_setup();
if (!result) {
/*
* Hardware Set up is successful
* Return the no of bytes required for buffer
*/
result = aew_dev_configptr->size_window;
} else {
/* Change Configuration Structure to original */
*(aew_dev_configptr->config) = aewconfig;
dev_err(aewdev, "Error : AEW_S_PARAM failed\n");
}
break;
/* This ioctl is used to return parameters in user space */
case AEW_G_PARAM:
if (aew_dev_configptr->aew_config == H3A_AEW_CONFIG) {
if (copy_to_user
((struct aew_configuration *)arg,
aew_dev_configptr->config,
sizeof(struct aew_configuration))) {
mutex_unlock(&aew_dev_configptr->read_blocked);
return -EFAULT;
} else
result = aew_dev_configptr->size_window;
} else {
dev_err(aewdev,
"Error : AEW Hardware is not configured.\n");
result = -EINVAL;
}
break;
/* This ioctl is used to enable AEW Engine */
case AEW_ENABLE:
/* Enable AEW Engine if Hardware set up is done */
if (aew_dev_configptr->aew_config == H3A_AEW_CONFIG_NOT_DONE) {
dev_err(aewdev,
"Error : AEW Hardware is not configured.\n");
result = -EINVAL;
} else
/* Enable AF Engine */
aew_engine_setup(aewdev, 1);
break;
/* This ioctl is used to disable AEW Engine */
case AEW_DISABLE:
/* Disable AEW Engine */
aew_engine_setup(aewdev, 0);
break;
/* Invalid Command */
default:
dev_err(aewdev, "Error: It should not come here!!\n");
result = -ENOTTY;
break;
}
/* Release the mutex */
mutex_unlock(&aew_dev_configptr->read_blocked);
return result;
}
/* This function will return statistics to user */
static ssize_t aew_read(struct file *filep, char *kbuff,
size_t size, loff_t *offset)
{
void *buffer_temp;
int result = 0;
int ret;
/* Semaphore will return immediately if read call is busy */
ret = mutex_trylock(&(aew_dev_configptr->read_blocked));
if (!ret) {
dev_dbg(aewdev, "Read Call : busy : %d\n", ret);
return -EBUSY;
}
/* First Check the size given by user */
if (size < aew_dev_configptr->size_window) {
/*
* Return Failure to applicaiton
* if size is less than required size
*/
dev_dbg(aewdev, "Error : Invalid size of buffer\n");
mutex_unlock(&(aew_dev_configptr->read_blocked));
return -EINVAL;
}
/*
* The value of buffer_filled flag determines
* the status of statistics
*/
if (aew_dev_configptr->buffer_filled == 0) {
/* Decrement the semaphore */
dev_dbg(aewdev, "READ CALL IS BLOCKED............\n");
/* Block the read call */
wait_event_interruptible_timeout(aew_dev_configptr->
aew_wait_queue,
aew_dev_configptr->
buffer_filled, AEW_TIMEOUT);
dev_dbg(aewdev, "Read Call is unbloked and waking up.......\n");
dev_dbg(aewdev, "Buffer Filled.... %d\n",
aew_dev_configptr->buffer_filled);
}
if (aew_dev_configptr->buffer_filled == 1) {
/* Disable the interrupts and then swap the buffers */
dev_dbg(aewdev, "READING............\n");
disable_irq(6);
/* New Statistics are availaible */
aew_dev_configptr->buffer_filled = 0;
/* Swap application buffer and old buffer */
buffer_temp = aew_dev_configptr->buff_old;
aew_dev_configptr->buff_old = aew_dev_configptr->buff_app;
aew_dev_configptr->buff_app = buffer_temp;
/* Interrupts are enabled */
enable_irq(6);
/*
* Copy the entire statistics located in application
* buffer to user space
*/
if (copy_to_user(kbuff, aew_dev_configptr->buff_app,
aew_dev_configptr->size_window)) {
dev_err(aewdev, "Error : Read Fault\n");
mutex_unlock(&(aew_dev_configptr->read_blocked));
return -EFAULT;
} else
result = aew_dev_configptr->size_window;
dev_dbg(aewdev, "Reading Done........................\n");
}
dev_dbg(aewdev, "APP BUFF VALUE %x\n",
(*((unsigned int *)(aew_dev_configptr->buff_app))));
/* release the mutex */
mutex_unlock(&(aew_dev_configptr->read_blocked));
return result;
}
/* This function will handle interrupt generated by H3A Engine. */
static irqreturn_t aew_isr(int irq, void *dev_id)
{
/* EN AF Bit */
unsigned int enaew;
/* Temporary Buffer for Swapping */
void *buffer_temp;
/* Get the value of PCR register */
enaew = aew_get_enable();
/* If AEW engine is not enabled, interrupt is not for AEW */
if (!enaew)
return IRQ_RETVAL(IRQ_NONE);
/*
* Interrupt is generated by AEW, so Service the Interrupt
* Swap current buffer and old buffer
*/
if (aew_dev_configptr) {
buffer_temp = aew_dev_configptr->buff_curr;
aew_dev_configptr->buff_curr = aew_dev_configptr->buff_old;
aew_dev_configptr->buff_old = buffer_temp;
/* Set the AEWBUFSTAT REgister to current buffer Address */
aew_set_address(aewdev, (unsigned
long)(virt_to_phys(aew_dev_configptr->buff_curr)));
/*
* Set buffer filled flag to indicate statistics are available
*/
aew_dev_configptr->buffer_filled = 1;
/* new statistics are available. Wake up the read call */
wake_up(&(aew_dev_configptr->aew_wait_queue));
return IRQ_RETVAL(IRQ_HANDLED);
}
return IRQ_RETVAL(IRQ_NONE);
}
/* file Operation Structure*/
static const struct file_operations aew_fops = {
.owner = THIS_MODULE,
.open = aew_open,
.read = aew_read,
.ioctl = aew_ioctl,
.release = aew_release,
};
static struct platform_device aewdevice = {
.name = "dm365_aew",
.id = 2,
.dev = {
.release = aew_platform_release,
}
};
static struct device_driver aew_driver = {
.name = "dm365_aew",
.bus = &platform_bus_type,
.probe = aew_probe,
.remove = aew_remove,
};
#define DRIVERNAME "DM365AEW"
/* Function to register the AF character device driver. */
int __init aew_init(void)
{
int err;
int result = 0;
/*
* Register the driver in the kernel
* dynmically get the major number for the driver using
* alloc_chrdev_region function
*/
result = alloc_chrdev_region(&dev, 0, 1, DRIVERNAME);
if (result < 0) {
printk(KERN_ERR "Error : Could not register character device");
return -ENODEV;
}
printk(KERN_INFO "aew major#: %d, minor# %d\n", MAJOR(dev), MINOR(dev));
/* allocate memory for device structure and initialize it with 0 */
aew_dev_configptr =
kmalloc(sizeof(struct aew_device), GFP_KERNEL);
if (!aew_dev_configptr) {
printk(KERN_ERR "Error : kmalloc fail");
unregister_chrdev_region(dev, AEW_NR_DEVS);
return -ENOMEM;
}
/* Initialize character device */
cdev_init(&c_dev, &aew_fops);
c_dev.owner = THIS_MODULE;
c_dev.ops = &aew_fops;
err = cdev_add(&c_dev, dev, 1);
if (err) {
printk(KERN_ERR "Error : Error in Adding Davinci AEW");
unregister_chrdev_region(dev, AEW_NR_DEVS);
kfree(aew_dev_configptr);
return -err;
}
/* register driver as a platform driver */
if (driver_register(&aew_driver) != 0) {
unregister_chrdev_region(dev, 1);
cdev_del(&c_dev);
return -EINVAL;
}
/* Register the drive as a platform device */
if (platform_device_register(&aewdevice) != 0) {
driver_unregister(&aew_driver);
unregister_chrdev_region(dev, 1);
cdev_del(&c_dev);
return -EINVAL;
}
aew_class = class_create(THIS_MODULE, "dm365_aew");
if (!aew_class) {
printk(KERN_ERR "aew_init: error in creating device class\n");
driver_unregister(&aew_driver);
platform_device_unregister(&aewdevice);
unregister_chrdev_region(dev, 1);
unregister_chrdev(MAJOR(dev), DRIVERNAME);
cdev_del(&c_dev);
return -EINVAL;
}
device_create(aew_class, NULL, dev, NULL, "dm365_aew");
/* Set up the Interrupt handler for H3AINT interrupt */
result = request_irq(6, aew_isr, IRQF_SHARED, "dm365_h3a_aew",
(void *)aew_dev_configptr);
if (result != 0) {
printk(KERN_ERR "Error : Request IRQ Failed");
unregister_chrdev_region(dev, AEW_NR_DEVS);
device_destroy(aew_class, dev);
class_destroy(aew_class);
kfree(aew_dev_configptr);
driver_unregister(&aew_driver);
platform_device_unregister(&aewdevice);
cdev_del(&c_dev);
return result;
}
/* Initialize device structure */
memset(aew_dev_configptr, 0, sizeof(struct aew_device));
aew_dev_configptr->in_use = AEW_NOT_IN_USE;
aew_dev_configptr->buffer_filled = 0;
printk(KERN_NOTICE "AEW Driver initialized\n");
return 0;
}
/*
* This Function is called by the kernel while unloading the driver
* This will unregister the Character Device Driver
*/
void __exit aew_cleanup(void)
{
/* Device is in use */
if (aew_dev_configptr->in_use == AEW_IN_USE) {
printk(KERN_ERR "Error : Driver in use");
return;
}
free_irq(6, aew_dev_configptr);
/* Free device structure */
kfree(aew_dev_configptr);
aew_dev_configptr = NULL;
unregister_chrdev_region(dev, AEW_NR_DEVS);
driver_unregister(&aew_driver);
device_destroy(aew_class, dev);
class_destroy(aew_class);
platform_device_unregister(&aewdevice);
cdev_del(&c_dev);
/* unregistering the driver from the kernel */
unregister_chrdev(MAJOR(dev), DRIVERNAME);
}
module_init(aew_init)
module_exit(aew_cleanup)
MODULE_LICENSE("GPL");
| Java |
// This file has been generated by the GUI designer. Do not modify.
namespace Smuxi.Frontend.Gnome
{
public partial class EngineAssistantNameWidget
{
private global::Gtk.VBox vbox2;
private global::Gtk.VBox vbox3;
private global::Gtk.Label f_EngineNameLabel;
private global::Gtk.Entry f_EngineNameEntry;
private global::Gtk.Label label2;
private global::Gtk.VBox vbox4;
private global::Gtk.Label label7;
private global::Gtk.CheckButton f_MakeDefaultEngineCheckButton;
private global::Gtk.Label label8;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget Smuxi.Frontend.Gnome.EngineAssistantNameWidget
global::Stetic.BinContainer.Attach (this);
this.Name = "Smuxi.Frontend.Gnome.EngineAssistantNameWidget";
// Container child Smuxi.Frontend.Gnome.EngineAssistantNameWidget.Gtk.Container+ContainerChild
this.vbox2 = new global::Gtk.VBox ();
this.vbox2.Name = "vbox2";
this.vbox2.Spacing = 10;
this.vbox2.BorderWidth = ((uint)(5));
// Container child vbox2.Gtk.Box+BoxChild
this.vbox3 = new global::Gtk.VBox ();
this.vbox3.Name = "vbox3";
this.vbox3.Spacing = 6;
// Container child vbox3.Gtk.Box+BoxChild
this.f_EngineNameLabel = new global::Gtk.Label ();
this.f_EngineNameLabel.Name = "f_EngineNameLabel";
this.f_EngineNameLabel.Xalign = 0f;
this.f_EngineNameLabel.LabelProp = global::Mono.Unix.Catalog.GetString ("_Engine Name:");
this.f_EngineNameLabel.UseUnderline = true;
this.vbox3.Add (this.f_EngineNameLabel);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.f_EngineNameLabel]));
w1.Position = 0;
w1.Expand = false;
w1.Fill = false;
// Container child vbox3.Gtk.Box+BoxChild
this.f_EngineNameEntry = new global::Gtk.Entry ();
this.f_EngineNameEntry.CanFocus = true;
this.f_EngineNameEntry.Name = "f_EngineNameEntry";
this.f_EngineNameEntry.IsEditable = true;
this.f_EngineNameEntry.InvisibleChar = '●';
this.vbox3.Add (this.f_EngineNameEntry);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.f_EngineNameEntry]));
w2.Position = 1;
w2.Expand = false;
w2.Fill = false;
// Container child vbox3.Gtk.Box+BoxChild
this.label2 = new global::Gtk.Label ();
this.label2.Name = "label2";
this.label2.Xpad = 50;
this.label2.Xalign = 0f;
this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("<span size=\"small\">Profile name of the new engine</span>");
this.label2.UseMarkup = true;
this.vbox3.Add (this.label2);
global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.label2]));
w3.Position = 2;
w3.Expand = false;
w3.Fill = false;
this.vbox2.Add (this.vbox3);
global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox2[this.vbox3]));
w4.Position = 0;
w4.Expand = false;
w4.Fill = false;
// Container child vbox2.Gtk.Box+BoxChild
this.vbox4 = new global::Gtk.VBox ();
this.vbox4.Name = "vbox4";
this.vbox4.Spacing = 6;
this.vbox4.BorderWidth = ((uint)(5));
// Container child vbox4.Gtk.Box+BoxChild
this.label7 = new global::Gtk.Label ();
this.label7.Name = "label7";
this.label7.Xalign = 0f;
this.label7.LabelProp = global::Mono.Unix.Catalog.GetString ("_Default Engine:");
this.label7.UseUnderline = true;
this.vbox4.Add (this.label7);
global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.label7]));
w5.Position = 0;
w5.Expand = false;
w5.Fill = false;
// Container child vbox4.Gtk.Box+BoxChild
this.f_MakeDefaultEngineCheckButton = new global::Gtk.CheckButton ();
this.f_MakeDefaultEngineCheckButton.CanFocus = true;
this.f_MakeDefaultEngineCheckButton.Name = "f_MakeDefaultEngineCheckButton";
this.f_MakeDefaultEngineCheckButton.Label = global::Mono.Unix.Catalog.GetString ("Use as new default engine");
this.f_MakeDefaultEngineCheckButton.DrawIndicator = true;
this.f_MakeDefaultEngineCheckButton.UseUnderline = true;
this.vbox4.Add (this.f_MakeDefaultEngineCheckButton);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.f_MakeDefaultEngineCheckButton]));
w6.Position = 1;
w6.Expand = false;
w6.Fill = false;
// Container child vbox4.Gtk.Box+BoxChild
this.label8 = new global::Gtk.Label ();
this.label8.Name = "label8";
this.label8.Xpad = 50;
this.label8.Xalign = 0f;
this.label8.LabelProp = global::Mono.Unix.Catalog.GetString ("<span size=\"small\">If enabled, the current engine will be the default next time Smuxi is started</span>");
this.label8.UseMarkup = true;
this.label8.Wrap = true;
this.vbox4.Add (this.label8);
global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.label8]));
w7.Position = 2;
w7.Expand = false;
w7.Fill = false;
this.vbox2.Add (this.vbox4);
global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.vbox2[this.vbox4]));
w8.Position = 1;
w8.Expand = false;
w8.Fill = false;
this.Add (this.vbox2);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.f_EngineNameLabel.MnemonicWidget = this.f_EngineNameEntry;
this.label7.MnemonicWidget = this.f_MakeDefaultEngineCheckButton;
this.Hide ();
}
}
}
| Java |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2007-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.threshd;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.xml.event.Event;
import org.springframework.util.Assert;
/**
* Implements a relative change threshold check. A 'value' setting of
* less than 1.0 means that a threshold will fire if the current value
* is less than or equal to the previous value multiplied by the 'value'
* setting. A 'value' setting greater than 1.0 causes the threshold to
* fire if the current value is greater than or equal to the previous
* value multiplied by the 'value' setting. A 'value' setting of 1.0
* (unity) is not allowed, as it represents no change. Zero valued
* samples (0.0) are ignored, as 0.0 multiplied by anything is 0.0 (if
* they were not ignored, an interface that gets no traffic would always
* trigger a threshold, for example).
*
* @author ranger
* @version $Id: $
*/
public class ThresholdEvaluatorRelativeChange implements ThresholdEvaluator {
private static final String TYPE = "relativeChange";
/** {@inheritDoc} */
@Override
public ThresholdEvaluatorState getThresholdEvaluatorState(BaseThresholdDefConfigWrapper threshold) {
return new ThresholdEvaluatorStateRelativeChange(threshold);
}
/** {@inheritDoc} */
@Override
public boolean supportsType(String type) {
return TYPE.equals(type);
}
public static class ThresholdEvaluatorStateRelativeChange extends AbstractThresholdEvaluatorState {
private BaseThresholdDefConfigWrapper m_thresholdConfig;
private double m_multiplier;
private double m_lastSample = 0.0;
private double m_previousTriggeringSample;
public ThresholdEvaluatorStateRelativeChange(BaseThresholdDefConfigWrapper threshold) {
Assert.notNull(threshold, "threshold argument cannot be null");
setThresholdConfig(threshold);
}
public void setThresholdConfig(BaseThresholdDefConfigWrapper thresholdConfig) {
Assert.notNull(thresholdConfig.getType(), "threshold must have a 'type' value set");
Assert.notNull(thresholdConfig.getDatasourceExpression(), "threshold must have a 'ds-name' value set");
Assert.notNull(thresholdConfig.getDsType(), "threshold must have a 'ds-type' value set");
Assert.isTrue(thresholdConfig.hasValue(), "threshold must have a 'value' value set");
Assert.isTrue(thresholdConfig.hasRearm(), "threshold must have a 'rearm' value set");
Assert.isTrue(thresholdConfig.hasTrigger(), "threshold must have a 'trigger' value set");
Assert.isTrue(TYPE.equals(thresholdConfig.getType()), "threshold for ds-name '" + thresholdConfig.getDatasourceExpression() + "' has type of '" + thresholdConfig.getType() + "', but this evaluator only supports thresholds with a 'type' value of '" + TYPE + "'");
Assert.isTrue(!Double.isNaN(thresholdConfig.getValue()), "threshold must have a 'value' value that is a number");
Assert.isTrue(thresholdConfig.getValue() != Double.POSITIVE_INFINITY && thresholdConfig.getValue() != Double.NEGATIVE_INFINITY, "threshold must have a 'value' value that is not positive or negative infinity");
Assert.isTrue(thresholdConfig.getValue() != 1.0, "threshold must not be unity (1.0)");
m_thresholdConfig = thresholdConfig;
setMultiplier(thresholdConfig.getValue());
}
@Override
public BaseThresholdDefConfigWrapper getThresholdConfig() {
return m_thresholdConfig;
}
@Override
public Status evaluate(double dsValue) {
//Fix for Bug 2275 so we handle negative numbers
//It will not handle values which cross the 0 boundary (from - to +, or v.v.) properly, but
// after some discussion, we can't come up with a sensible scenario when that would actually happen.
// If such a scenario eventuates, reconsider
dsValue=Math.abs(dsValue);
if (getLastSample() != 0.0) {
double threshold = getMultiplier() * getLastSample();
if (getMultiplier() < 1.0) {
if (dsValue <= threshold) {
setPreviousTriggeringSample(getLastSample());
setLastSample(dsValue);
return Status.TRIGGERED;
}
} else {
if (dsValue >= threshold) {
setPreviousTriggeringSample(getLastSample());
setLastSample(dsValue);
return Status.TRIGGERED;
}
}
setLastSample(dsValue);
}
setLastSample(dsValue);
return Status.NO_CHANGE;
}
public Double getLastSample() {
return m_lastSample;
}
public void setLastSample(double lastSample) {
m_lastSample = lastSample;
}
@Override
public Event getEventForState(Status status, Date date, double dsValue, CollectionResourceWrapper resource) {
if (status == Status.TRIGGERED) {
String uei=getThresholdConfig().getTriggeredUEI();
if(uei==null || "".equals(uei)) {
uei=EventConstants.RELATIVE_CHANGE_THRESHOLD_EVENT_UEI;
}
return createBasicEvent(uei, date, dsValue, resource);
} else {
return null;
}
}
private Event createBasicEvent(String uei, Date date, double dsValue, CollectionResourceWrapper resource) {
Map<String,String> params = new HashMap<String,String>();
params.put("previousValue", formatValue(getPreviousTriggeringSample()));
params.put("multiplier", Double.toString(getThresholdConfig().getValue()));
// params.put("trigger", Integer.toString(getThresholdConfig().getTrigger()));
// params.put("rearm", Double.toString(getThresholdConfig().getRearm()));
return createBasicEvent(uei, date, dsValue, resource, params);
}
public double getPreviousTriggeringSample() {
return m_previousTriggeringSample;
}
public void setPreviousTriggeringSample(double previousTriggeringSample) {
m_previousTriggeringSample = previousTriggeringSample;
}
public double getMultiplier() {
return m_multiplier;
}
public void setMultiplier(double multiplier) {
m_multiplier = multiplier;
}
@Override
public ThresholdEvaluatorState getCleanClone() {
return new ThresholdEvaluatorStateRelativeChange(m_thresholdConfig);
}
// FIXME This must be implemented correctly
@Override
public boolean isTriggered() {
return false;
}
// FIXME This must be implemented correctly
@Override
public void clearState() {
}
}
}
| Java |
/*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.vm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class add_o32_rAX_Id extends Executable
{
final int immd;
public add_o32_rAX_Id(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
immd = Modrm.Id(input);
}
public Branch execute(Processor cpu)
{
cpu.flagOp1 = cpu.r_eax.get32();
cpu.flagOp2 = immd;
cpu.flagResult = (cpu.flagOp1 + cpu.flagOp2);
cpu.r_eax.set32(cpu.flagResult);
cpu.flagIns = UCodes.ADD32;
cpu.flagStatus = OSZAPC;
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | Java |
/******************************************************************************
* Warmux is a convivial mass murder game.
* Copyright (C) 2001-2011 Warmux Team.
*
* 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
******************************************************************************
* Team handling
*****************************************************************************/
#include <algorithm>
#include <iostream>
#include <WARMUX_file_tools.h>
#include <WARMUX_team_config.h>
#include "character/character.h"
#include "character/body_list.h"
#include "game/config.h"
#include "network/network.h"
#include "network/randomsync.h"
#include "team/team.h"
#include "team/team_energy.h"
#include "team/teams_list.h"
#include "tool/ansi_convert.h"
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
TeamsList::TeamsList():
full_list(),
playing_list(),
selection(),
groups(),
active_group(groups.end())
{
LoadList();
}
TeamsList::~TeamsList()
{
UnloadGamingData();
Clear();
for (full_iterator it = full_list.begin(); it != full_list.end(); ++it)
delete (*it);
full_list.clear();
groups.clear();
}
//-----------------------------------------------------------------------------
void TeamsList::NextTeam()
{
ActiveCharacter().StopPlaying();
Team* next = GetNextTeam();
SetActive(next->GetId());
next->NextCharacter(true);
printf("\nPlaying character : %i %s\n", ActiveCharacter().GetCharacterIndex(), ActiveCharacter().GetName().c_str());
printf("Playing team : %i %s\n", ActiveCharacter().GetTeamIndex(), ActiveTeam().GetName().c_str());
printf("Alive characters: %i / %i\n\n", ActiveTeam().NbAliveCharacter(),ActiveTeam().GetNbCharacters());
}
//-----------------------------------------------------------------------------
Team* TeamsList::GetNextTeam()
{
// Next group
GroupList::iterator git = active_group;
std::vector<Team*>::iterator it;
do {
++git;
if (git == groups.end())
git = groups.begin();
it = git->second.active_team;
do {
++it;
if (it == git->second.end())
it = git->second.begin();
} while (!(*it)->NbAliveCharacter() && it != git->second.active_team);
} while (git != active_group && !(*it)->NbAliveCharacter());
return (*it);
}
//-----------------------------------------------------------------------------
Team& TeamsList::ActiveTeam()
{
return **(active_group->second.active_team);
}
//-----------------------------------------------------------------------------
bool TeamsList::LoadOneTeam(const std::string &dir, const std::string &team_name)
{
// Skip '.', '..' and hidden files
if (team_name[0] == '.' || team_name == "SVN~1")
return false;
// Is it a directory ?
if (!DoesFolderExist(dir+team_name))
return false;
// Add the team
std::string real_name = ANSIToUTF8(dir, team_name);
std::string error;
Team *team = Team::LoadTeam(dir, real_name, error);
if (team) {
full_list.push_back(team);
std::cout << ((1<full_list.size())?", ":" ") << real_name;
std::cout.flush();
return true;
}
std::cerr << std::endl
<< Format(_("Error loading team :")) << real_name <<":"<< error
<< std::endl;
return false;
}
//-----------------------------------------------------------------------------
void TeamsList::LoadList()
{
playing_list.clear();
std::cout << "o " << _("Load teams:");
const Config * config = Config::GetInstance();
// Load Warmux teams
std::string dirname = config->GetDataDir() + "team" PATH_SEPARATOR;
FolderSearch *f = OpenFolder(dirname);
if (f) {
const char *name;
bool search_file = false;
while ((name = FolderSearchNext(f, search_file)) != NULL)
LoadOneTeam(dirname, name);
CloseFolder(f);
} else {
Error(Format(_("Cannot open teams directory (%s)!"), dirname.c_str()));
}
// Load personal teams
dirname = config->GetPersonalDataDir() + "team" PATH_SEPARATOR;
f = OpenFolder(dirname);
if (f) {
bool search_files = false;
const char *name;
while ((name = FolderSearchNext(f, search_files)) != NULL)
LoadOneTeam(dirname, name);
CloseFolder(f);
} else {
std::cerr << std::endl
<< Format(_("Cannot open personal teams directory (%s)!"), dirname.c_str())
<< std::endl;
}
full_list.sort(compareTeams);
// We need at least 2 teams
if (full_list.size() < 2)
Error(_("You need at least two valid teams!"));
// Default selection
std::list<uint> nv_selection;
nv_selection.push_back(0);
nv_selection.push_back(1);
ChangeSelection(nv_selection);
std::cout << std::endl;
InitList(Config::GetInstance()->AccessTeamList());
}
//-----------------------------------------------------------------------------
void TeamsList::LoadGamingData(WeaponsList * weapons_list)
{
//std::sort(playing_list.begin(), playing_list.end(), compareTeams); // needed to fix bug #9820
iterator it=playing_list.begin(), end=playing_list.end();
// Load the data of all teams
for (; it != end; ++it) {
(*it)->LoadGamingData(weapons_list);
}
groups.clear();
for (it=playing_list.begin(); it != end; ++it) {
groups[ (*it)->GetGroup() ].push_back(*it);
if ((*it)->IsLocalAI())
(*it)->LoadAI();
}
}
void TeamsList::RandomizeFirstPlayer()
{
MSG_DEBUG("random.get", "TeamList::RandomizeFirstPlayer()");
int skip = RandomSync().GetInt(0, groups.size()-1);
for (GroupList::iterator git = groups.begin(); git != groups.end(); ++git) {
if (!(skip--))
active_group = git;
TeamGroup& g = git->second;
int skip2 = RandomSync().GetInt(1, g.size());
g.active_team = g.begin();
while (--skip2)
g.active_team++;
}
}
//-----------------------------------------------------------------------------
void TeamsList::UnloadGamingData()
{
groups.clear();
// Iterate over all teams not just he playing ones
// in order to unload leaver teams.
full_iterator it=full_list.begin(), end = full_list.end();
// Unload the data of all teams
for (; it != end; ++it)
(**it).UnloadGamingData();
// Run this now as no reference from Character are left
BodyList::GetRef().FreeMem();
}
//-----------------------------------------------------------------------------
Team *TeamsList::FindById(const std::string &id, int &pos)
{
full_iterator it=full_list.begin(), end = full_list.end();
int i=0;
for (; it != end; ++it, ++i) {
if ((*it)->GetId() == id) {
pos = i;
return (*it);
}
}
pos = -1;
return NULL;
}
//-----------------------------------------------------------------------------
Team *TeamsList::FindByIndex(uint index)
{
if (full_list.size() < index+1) {
ASSERT(false);
return NULL;
}
full_iterator it = full_list.begin(), end = full_list.end();
uint i=0;
for (; it != end; ++it, ++i) {
if (i == index)
return (*it);
}
return NULL;
}
//-----------------------------------------------------------------------------
Team* TeamsList::FindPlayingById(const std::string &id, int &index)
{
iterator it = playing_list.begin(), end = playing_list.end();
index=0;
for (; it != end; ++it, ++index) {
if ((*it) -> GetId() == id)
return *it;
}
index = -1;
ASSERT(false);
return NULL;
}
//-----------------------------------------------------------------------------
void TeamsList::InitList(const std::list<ConfigTeam> &lst)
{
Clear();
std::list<ConfigTeam>::const_iterator it=lst.begin(), end=lst.end();
for (; it != end; ++it)
AddTeam(*it, true, false);
}
//-----------------------------------------------------------------------------
void TeamsList::InitEnergy()
{
// Looking at team with the greatest energy
// (in case teams does not have same amount of character)
iterator it = playing_list.begin(), end = playing_list.end();
uint max = 0;
for (; it != end; ++it) {
if ((**it).ReadEnergy() > max)
max = (**it).ReadEnergy();
}
// Init each team's energy bar
it=playing_list.begin();
for (; it != end; ++it)
(**it).InitEnergy(max);
// Initial ranking
it=playing_list.begin();
for (; it != end; ++it) {
uint rank = 0;
iterator it2=playing_list.begin();
for (; it2 != end; ++it2) {
if (it != it2 && (**it2).ReadEnergy() > (**it).ReadEnergy())
++rank;
}
(**it).energy.rank_tmp = rank;
}
it=playing_list.begin();
for (; it != end; ++it) {
uint rank = (**it).energy.rank_tmp;
iterator it2=playing_list.begin();
for (it2 = it; it2 != end; ++it2) {
if (it != it2 && (**it2).ReadEnergy() == (**it).ReadEnergy())
++rank;
}
(**it).energy.SetRanking(rank);
}
}
//-----------------------------------------------------------------------------
void TeamsList::RefreshEnergy()
{
// In the order of the priorit :
// - finish current action
// - change a teams energy
// - change ranking
// - prepare energy bar for next event
iterator it=playing_list.begin(), end = playing_list.end();
energy_t status;
bool waiting = true; // every energy bar are waiting
for (; it != end; ++it) {
if ((**it).energy.status != EnergyStatusWait) {
waiting = false;
break;
}
}
// one of the energy bar is changing ?
if (!waiting) {
status = EnergyStatusOK;
// change an energy bar value ?
for (it=playing_list.begin(); it != end; ++it) {
if ((**it).energy.status == EnergyStatusValueChange) {
status = EnergyStatusValueChange;
break;
}
}
// change a ranking ?
for (it=playing_list.begin(); it != end; ++it) {
if ((**it).energy.status == EnergyStatusRankChange
&& ((**it).energy.IsMoving() || status == EnergyStatusOK)) {
status = EnergyStatusRankChange;
break;
}
}
}
else {
// every energy bar are waiting
// -> set state ready for a new event
status = EnergyStatusOK;
}
// Setting event to process in every energy bar
if (status != EnergyStatusOK || waiting) {
it = playing_list.begin();
for (; it != end; ++it) {
(**it).energy.status = status;
}
}
// Actualisation des valeurs (pas d'actualisation de l'affichage)
for (it=playing_list.begin(); it != end; ++it) {
(**it).UpdateEnergyBar();
}
RefreshSort();
}
//-----------------------------------------------------------------------------
void TeamsList::RefreshSort()
{
iterator it=playing_list.begin(), end = playing_list.end();
uint rank;
// Find a ranking without taking acount of the equalities
it = playing_list.begin();
for (; it != end; ++it) {
rank = 0;
iterator it2=playing_list.begin();
for (; it2 != end; ++it2) {
if (it != it2 && (**it2).ReadEnergy() > (**it).ReadEnergy())
++rank;
}
(**it).energy.rank_tmp = rank;
}
// Fix equalities
it = playing_list.begin();
for (; it != end; ++it) {
rank = (**it).energy.rank_tmp;
iterator it2=playing_list.begin();
for (it2 = it; it2 != end; ++it2) {
if (it != it2 && (**it2).ReadEnergy() == (**it).ReadEnergy())
++rank;
}
(**it).energy.NewRanking(rank);
}
}
//-----------------------------------------------------------------------------
void TeamsList::ChangeSelection(const std::list<uint>& nv_selection)
{
selection = nv_selection;
selection_iterator it=selection.begin(), end = selection.end();
playing_list.clear();
for (; it != end; ++it)
playing_list.push_back(FindByIndex(*it));
}
//-----------------------------------------------------------------------------
bool TeamsList::IsSelected(uint index)
{
selection_iterator pos = std::find(selection.begin(), selection.end(), index);
return pos != selection.end();
}
//-----------------------------------------------------------------------------
void TeamsList::AddTeam(Team* the_team, int pos, const ConfigTeam &the_team_cfg,
bool is_local)
{
ASSERT(the_team != NULL);
the_team->SetRemote(!is_local);
UpdateTeam(the_team, the_team_cfg);
selection.push_back(pos);
playing_list.push_back(the_team);
}
void TeamsList::AddTeam(const ConfigTeam &the_team_cfg, bool is_local,
bool generate_error)
{
MSG_DEBUG("team", "%s, local: %d\n", the_team_cfg.id.c_str(), is_local);
int pos;
Team *the_team = FindById(the_team_cfg.id, pos);
if (the_team != NULL) {
AddTeam(the_team, pos, the_team_cfg, is_local);
} else {
std::string msg = Format(_("Can't find team %s!"), the_team_cfg.id.c_str());
if (generate_error)
Error (msg);
else
std::cout << "! " << msg << std::endl;
}
}
//-----------------------------------------------------------------------------
void TeamsList::UpdateTeam(Team* the_team, const ConfigTeam &the_team_cfg)
{
ASSERT(the_team);
// set the player name and number of characters
the_team->SetPlayerName(the_team_cfg.player_name);
the_team->SetNbCharacters(the_team_cfg.nb_characters);
the_team->SetAIName(the_team_cfg.ai);
the_team->SetGroup(the_team_cfg.group);
}
Team* TeamsList::UpdateTeam(const std::string& old_team_id,
const ConfigTeam &the_team_cfg)
{
int pos;
Team *the_team = NULL;
MSG_DEBUG("team", "%s/%s\n", old_team_id.c_str(), the_team_cfg.id.c_str());
if (old_team_id == the_team_cfg.id) {
// this is a simple update
the_team = FindById(the_team_cfg.id, pos);
if (the_team) {
UpdateTeam(the_team, the_team_cfg);
} else {
Error(Format(_("Can't find team %s!"), the_team_cfg.id.c_str()));
}
return the_team;
}
// here we are replacing a team by another one
Team *the_old_team = FindById(old_team_id, pos);
if (!the_old_team) {
Error(Format(_("Can't find team %s!"), old_team_id.c_str()));
return NULL;
}
the_team = FindById(the_team_cfg.id, pos);
if (!the_team) {
Error(Format(_("Can't find team %s!"), old_team_id.c_str()));
return NULL;
}
bool is_local = the_old_team->IsLocal();
DelTeam(the_old_team);
AddTeam(the_team, pos, the_team_cfg, is_local);
return the_team;
}
//-----------------------------------------------------------------------------
void TeamsList::DelTeam(Team* the_team)
{
uint pos = 0;
ASSERT(the_team);
MSG_DEBUG("team", "%s\n", the_team->GetId().c_str());
the_team->SetDefaultPlayingConfig();
selection_iterator it = std::find(selection.begin(), selection.end(), pos);
if (it != selection.end())
selection.erase(it);
iterator playing_it = std::find(playing_list.begin(), playing_list.end(), the_team);
ASSERT(playing_it != playing_list.end());
if (playing_it != playing_list.end())
playing_list.erase(playing_it);
}
void TeamsList::DelTeam(const std::string &id)
{
int pos;
Team *the_team = FindById(id, pos);
DelTeam(the_team);
}
//-----------------------------------------------------------------------------
void TeamsList::SetActive(const std::string &id)
{
for (GroupList::iterator git = groups.begin(); git != groups.end(); ++git) {
for (TeamGroup::iterator it = git->second.begin(); it != git->second.end(); ++it) {
if ((*it)->GetId() == id) {
active_group = git;
git->second.active_team = it;
(*it)->PrepareTurn();
return;
}
}
}
Error(Format(_("Can't find team %s!"), id.c_str()));
}
Character& ActiveCharacter()
{
return ActiveTeam().ActiveCharacter();
}
bool compareTeams(const Team *a, const Team *b)
{
return a->GetName() < b->GetName();
}
| Java |
/*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.vm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class fdiv_ST1_ST1 extends Executable
{
public fdiv_ST1_ST1(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
}
public Branch execute(Processor cpu)
{
double freg0 = cpu.fpu.ST(1);
double freg1 = cpu.fpu.ST(1);
if (((freg0 == 0.0) && (freg1 == 0.0)) || (Double.isInfinite(freg0) && Double.isInfinite(freg1)))
cpu.fpu.setInvalidOperation();
if ((freg0 == 0.0) && !Double.isNaN(freg1) && !Double.isInfinite(freg1))
cpu.fpu.setZeroDivide();
cpu.fpu.setST(1, freg0/freg1);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | Java |
/*
* COM1 NS16550 support
* originally from linux source (arch/ppc/boot/ns16550.c)
* modified to use CONFIG_SYS_ISA_MEM and new defines
*/
#include <config.h>
#include <ns16550.h>
#define LCRVAL LCR_8N1 /* 8 data, 1 stop, no parity */
#define MCRVAL (MCR_DTR | MCR_RTS) /* RTS/DTR */
#define FCRVAL (FCR_FIFO_EN | FCR_RXSR | FCR_TXSR) /* Clear & enable FIFOs */
void NS16550_init (NS16550_t com_port, int baud_divisor)
{
com_port->ier = 0x00;
#ifdef CONFIG_OMAP
com_port->mdr1 = 0x7; /* mode select reset TL16C750*/
#endif
com_port->lcr = LCR_BKSE | LCRVAL;
com_port->dll = 0;
com_port->dlm = 0;
com_port->lcr = LCRVAL;
com_port->mcr = MCRVAL;
com_port->fcr = FCRVAL;
com_port->lcr = LCR_BKSE | LCRVAL;
com_port->dll = baud_divisor & 0xff;
com_port->dlm = (baud_divisor >> 8) & 0xff;
com_port->lcr = LCRVAL;
#if defined(CONFIG_OMAP)
#if defined(CONFIG_APTIX)
com_port->mdr1 = 3; /* /13 mode so Aptix 6MHz can hit 115200 */
#else
com_port->mdr1 = 0; /* /16 is proper to hit 115200 with 48MHz */
#endif
#endif /* CONFIG_OMAP */
}
#ifndef CONFIG_NS16550_MIN_FUNCTIONS
void NS16550_reinit (NS16550_t com_port, int baud_divisor)
{
com_port->ier = 0x00;
com_port->lcr = LCR_BKSE | LCRVAL;
com_port->dll = 0;
com_port->dlm = 0;
com_port->lcr = LCRVAL;
com_port->mcr = MCRVAL;
com_port->fcr = FCRVAL;
com_port->lcr = LCR_BKSE;
com_port->dll = baud_divisor & 0xff;
com_port->dlm = (baud_divisor >> 8) & 0xff;
com_port->lcr = LCRVAL;
}
#endif /* CONFIG_NS16550_MIN_FUNCTIONS */
void NS16550_putc (NS16550_t com_port, char c)
{
while ((com_port->lsr & LSR_THRE) == 0);
com_port->thr = c;
}
#ifndef CONFIG_NS16550_MIN_FUNCTIONS
char NS16550_getc (NS16550_t com_port)
{
while ((com_port->lsr & LSR_DR) == 0) {
#ifdef CONFIG_USB_TTY
extern void usbtty_poll(void);
usbtty_poll();
#endif
}
return (com_port->rbr);
}
int NS16550_tstc (NS16550_t com_port)
{
return ((com_port->lsr & LSR_DR) != 0);
}
#endif /* CONFIG_NS16550_MIN_FUNCTIONS */
| Java |
<?php
/**
* Joomla! component Creative Contact Form
*
* @version $Id: 2012-04-05 14:30:25 svn $
* @author creative-solutions.net
* @package Creative Contact Form
* @subpackage com_creativecontactform
* @license GNU/GPL
*
*/
// no direct access
defined('_JEXEC') or die('Restircted access');
abstract class JHtmlCreativeForm
{
/**
* @param int $value The featured value
* @param int $i
* @param bool $canChange Whether the value can be changed or not
*
* @return string The anchor tag to toggle featured/unfeatured contacts.
* @since 1.6
*/
static function featured($value = 0, $i, $canChange = true)
{
// Array of image, task, title, action
$states = array(
0 => array('disabled.png', 'creativeforms.featured', 'COM_CREATIVECONTACTFORM_UNFEATURED', 'COM_CREATIVECONTACTFORM_UNFEATURED'),
1 => array('featured.png', 'creativeforms.unfeatured', 'COM_CREATIVECONTACTFORM_FEATURED', 'COM_CREATIVECONTACTFORM_FEATURED'),
);
$state = JArrayHelper::getValue($states, (int) $value, $states[1]);
$html = JHtml::_('image', 'admin/'.$state[0], JText::_($state[2]), NULL, true);
if ($canChange) {
$html = '<a href="#" onclick="return listItemTask(\'cb'.$i.'\',\''.$state[1].'\')" title="'.JText::_($state[3]).'">'
. $html .'</a>';
}
return $html;
}
}
| Java |
/*
* ProFTPD - mod_sftp RFC4716 keystore
* Copyright (c) 2008-2016 TJ Saunders
*
* 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, Suite 500, Boston, MA 02110-1335, USA.
*
* As a special exemption, TJ Saunders and other respective copyright holders
* give permission to link this program with OpenSSL, and distribute the
* resulting executable, without including the source code for OpenSSL in the
* source distribution.
*/
#include "mod_sftp.h"
#include "keys.h"
#include "keystore.h"
#include "crypto.h"
#include "rfc4716.h"
/* File-based keystore implementation */
struct filestore_key {
/* Supported headers. We don't really care about the Comment header
* at the moment.
*/
const char *subject;
/* Key data */
unsigned char *key_data;
uint32_t key_datalen;
};
struct filestore_data {
pr_fh_t *fh;
const char *path;
unsigned int lineno;
};
static const char *trace_channel = "ssh2";
/* This getline() function is quite similar to pr_fsio_getline(), except
* that it a) enforces the 72-byte max line length from RFC4716, and b)
* properly handles lines ending with CR, LF, or CRLF.
*
* Technically it allows one more byte than necessary, since the worst case
* is 74 bytes (72 + CRLF); this also means 73 + CR or 73 + LF. The extra
* byte is for the terminating NUL.
*/
static char *filestore_getline(sftp_keystore_t *store, pool *p) {
char linebuf[75], *line = "", *res;
struct filestore_data *store_data = store->keystore_data;
while (TRUE) {
size_t linelen;
pr_signals_handle();
memset(&linebuf, '\0', sizeof(linebuf));
res = pr_fsio_gets(linebuf, sizeof(linebuf) - 1, store_data->fh);
if (res == NULL) {
if (errno == EINTR) {
continue;
}
pr_trace_msg(trace_channel, 10, "reached end of '%s', no matching "
"key found", store_data->path);
errno = EOF;
return NULL;
}
linelen = strlen(linebuf);
if (linelen >= 1) {
if (linebuf[linelen - 1] == '\r' ||
linebuf[linelen - 1] == '\n') {
char *tmp;
unsigned int header_taglen, header_valuelen;
int have_line_continuation = FALSE;
store_data->lineno++;
linebuf[linelen - 1] = '\0';
line = pstrcat(p, line, linebuf, NULL);
if (line[strlen(line) - 1] == '\\') {
have_line_continuation = TRUE;
line[strlen(line) - 1] = '\0';
}
tmp = strchr(line, ':');
if (tmp == NULL) {
return line;
}
/* We have a header. Make sure the header tag is not longer than
* the specified length of 64 bytes, and that the header value is
* not longer than 1024 bytes.
*/
header_taglen = tmp - line;
if (header_taglen > 64) {
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"header tag too long (%u) on line %u of '%s'", header_taglen,
store_data->lineno, store_data->path);
errno = EINVAL;
return NULL;
}
/* Header value starts at 2 after the ':' (one for the mandatory
* space character.
*/
header_valuelen = strlen(line) - (header_taglen + 2);
if (header_valuelen > 1024) {
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"header value too long (%u) on line %u of '%s'", header_valuelen,
store_data->lineno, store_data->path);
errno = EINVAL;
return NULL;
}
if (!have_line_continuation) {
return line;
}
continue;
} else if (linelen >= 2 &&
linebuf[linelen - 2] == '\r' &&
linebuf[linelen - 1] == '\n') {
char *tmp;
unsigned int header_taglen, header_valuelen;
int have_line_continuation = FALSE;
store_data->lineno++;
linebuf[linelen - 2] = '\0';
linebuf[linelen - 1] = '\0';
line = pstrcat(p, line, linebuf, NULL);
if (line[strlen(line) - 1] == '\\') {
have_line_continuation = TRUE;
line[strlen(line) - 1] = '\0';
}
tmp = strchr(line, ':');
if (tmp == NULL) {
return line;
}
/* We have a header. Make sure the header tag is not longer than
* the specified length of 64 bytes, and that the header value is
* not longer than 1024 bytes.
*/
header_taglen = tmp - line;
if (header_taglen > 64) {
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"header tag too long (%u) on line %u of '%s'", header_taglen,
store_data->lineno, store_data->path);
errno = EINVAL;
return NULL;
}
/* Header value starts at 2 after the ':' (one for the mandatory
* space character.
*/
header_valuelen = strlen(line) - (header_taglen + 2);
if (header_valuelen > 1024) {
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"header value too long (%u) on line %u of '%s'", header_valuelen,
store_data->lineno, store_data->path);
errno = EINVAL;
return NULL;
}
if (!have_line_continuation) {
return line;
}
continue;
} else if (linelen < sizeof(linebuf)) {
/* No CR or LF terminator; maybe a badly formatted file? Try to
* work with the data, if we can.
*/
line = pstrcat(p, line, linebuf, NULL);
return line;
} else {
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"line too long (%lu) on line %u of '%s'", (unsigned long) linelen,
store_data->lineno, store_data->path);
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"Make sure that '%s' is a RFC4716 formatted key", store_data->path);
errno = EINVAL;
break;
}
}
}
return NULL;
}
static struct filestore_key *filestore_get_key(sftp_keystore_t *store,
pool *p) {
char *line;
BIO *bio = NULL;
struct filestore_key *key = NULL;
struct filestore_data *store_data = store->keystore_data;
size_t begin_markerlen = 0, end_markerlen = 0;
line = filestore_getline(store, p);
while (line == NULL &&
errno == EINVAL) {
line = filestore_getline(store, p);
}
begin_markerlen = strlen(SFTP_SSH2_PUBKEY_BEGIN_MARKER);
end_markerlen = strlen(SFTP_SSH2_PUBKEY_END_MARKER);
while (line) {
pr_signals_handle();
if (key == NULL &&
strncmp(line, SFTP_SSH2_PUBKEY_BEGIN_MARKER,
begin_markerlen + 1) == 0) {
key = pcalloc(p, sizeof(struct filestore_key));
bio = BIO_new(BIO_s_mem());
} else if (key != NULL &&
strncmp(line, SFTP_SSH2_PUBKEY_END_MARKER,
end_markerlen + 1) == 0) {
if (bio) {
BIO *b64 = NULL, *bmem = NULL;
char chunk[1024], *data = NULL;
int chunklen;
long datalen = 0;
/* Add a base64 filter BIO, and read the data out, thus base64-decoding
* the key. Write the decoded data into another memory BIO.
*/
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bio = BIO_push(b64, bio);
bmem = BIO_new(BIO_s_mem());
memset(chunk, '\0', sizeof(chunk));
chunklen = BIO_read(bio, chunk, sizeof(chunk));
if (chunklen < 0 &&
!BIO_should_retry(bio)) {
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"unable to base64-decode data in '%s': %s",
store_data->path, sftp_crypto_get_errors());
BIO_free_all(bio);
BIO_free_all(bmem);
errno = EPERM;
return NULL;
}
while (chunklen > 0) {
pr_signals_handle();
if (BIO_write(bmem, chunk, chunklen) < 0) {
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"error writing to memory BIO: %s", sftp_crypto_get_errors());
BIO_free_all(bio);
BIO_free_all(bmem);
errno = EPERM;
return NULL;
}
memset(chunk, '\0', sizeof(chunk));
chunklen = BIO_read(bio, chunk, sizeof(chunk));
}
datalen = BIO_get_mem_data(bmem, &data);
if (data != NULL &&
datalen > 0) {
key->key_data = palloc(p, datalen);
key->key_datalen = datalen;
memcpy(key->key_data, data, datalen);
} else {
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"error base64-decoding key data in '%s'", store_data->path);
}
BIO_free_all(bio);
bio = NULL;
BIO_free_all(bmem);
}
break;
} else {
if (key) {
if (strstr(line, ": ") != NULL) {
if (strncasecmp(line, "Subject: ", 9) == 0) {
key->subject = pstrdup(p, line + 9);
}
} else {
if (BIO_write(bio, line, strlen(line)) < 0) {
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"error buffering base64 data");
}
}
}
}
line = filestore_getline(store, p);
while (line == NULL &&
errno == EINVAL) {
line = filestore_getline(store, p);
}
}
return key;
}
static int filestore_verify_host_key(sftp_keystore_t *store, pool *p,
const char *user, const char *host_fqdn, const char *host_user,
unsigned char *key_data, uint32_t key_len) {
struct filestore_key *key = NULL;
struct filestore_data *store_data = store->keystore_data;
int res = -1;
if (!store_data->path) {
errno = EPERM;
return -1;
}
/* XXX Note that this will scan the file from the beginning, each time.
* There's room for improvement; perhaps mmap() the file into memory?
*/
key = filestore_get_key(store, p);
while (key) {
int ok;
pr_signals_handle();
ok = sftp_keys_compare_keys(p, key_data, key_len, key->key_data,
key->key_datalen);
if (ok != TRUE) {
if (ok == -1) {
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"error comparing keys from '%s': %s", store_data->path,
strerror(errno));
}
} else {
/* XXX Verify that the user and the host_user match?? */
res = 0;
break;
}
key = filestore_get_key(store, p);
}
if (res == 0) {
pr_trace_msg(trace_channel, 10, "found matching public key for host '%s' "
"in '%s'", host_fqdn, store_data->path);
}
if (pr_fsio_lseek(store_data->fh, 0, SEEK_SET) < 0) {
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"error seeking to start of '%s': %s", store_data->path, strerror(errno));
return -1;
}
store_data->lineno = 0;
return res;
}
static int filestore_verify_user_key(sftp_keystore_t *store, pool *p,
const char *user, unsigned char *key_data, uint32_t key_len) {
struct filestore_key *key = NULL;
struct filestore_data *store_data = store->keystore_data;
unsigned int count = 0;
int res = -1;
if (!store_data->path) {
errno = EPERM;
return -1;
}
/* XXX Note that this will scan the file from the beginning, each time.
* There's room for improvement; perhaps mmap() the file into memory?
*/
key = filestore_get_key(store, p);
while (key) {
int ok;
pr_signals_handle();
count++;
ok = sftp_keys_compare_keys(p, key_data, key_len, key->key_data,
key->key_datalen);
if (ok != TRUE) {
if (ok == -1) {
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"error comparing keys from '%s': %s", store_data->path,
strerror(errno));
} else {
pr_trace_msg(trace_channel, 10,
"failed to match key #%u from file '%s'", count, store_data->path);
}
} else {
/* If we are configured to check for Subject headers, and if the file key
* has a Subject header, and that header value does not match the
* logging in user, then continue looking.
*/
if ((sftp_opts & SFTP_OPT_MATCH_KEY_SUBJECT) &&
key->subject != NULL) {
if (strcmp(key->subject, user) != 0) {
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"found matching key for user '%s' in '%s', but Subject "
"header ('%s') does not match, skipping key", user,
store_data->path, key->subject);
} else {
res = 0;
break;
}
} else {
res = 0;
break;
}
}
key = filestore_get_key(store, p);
}
if (res == 0) {
pr_trace_msg(trace_channel, 10, "found matching public key for user '%s' "
"in '%s'", user, store_data->path);
}
if (pr_fsio_lseek(store_data->fh, 0, SEEK_SET) < 0) {
(void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
"error seeking to start of '%s': %s", store_data->path, strerror(errno));
return -1;
}
store_data->lineno = 0;
return res;
}
static int filestore_close(sftp_keystore_t *store) {
struct filestore_data *store_data = store->keystore_data;
pr_fsio_close(store_data->fh);
return 0;
}
static sftp_keystore_t *filestore_open(pool *parent_pool,
int requested_key_type, const char *store_info, const char *user) {
int xerrno;
sftp_keystore_t *store;
pool *filestore_pool;
struct filestore_data *store_data;
pr_fh_t *fh;
char buf[PR_TUNABLE_PATH_MAX+1], *path;
struct stat st;
filestore_pool = make_sub_pool(parent_pool);
pr_pool_tag(filestore_pool, "SFTP File-based Keystore Pool");
store = pcalloc(filestore_pool, sizeof(sftp_keystore_t));
store->keystore_pool = filestore_pool;
/* Open the file. The given path (store_info) may need to be
* interpolated.
*/
session.user = (char *) user;
memset(buf, '\0', sizeof(buf));
switch (pr_fs_interpolate(store_info, buf, sizeof(buf)-1)) {
case 1:
/* Interpolate occurred; make a copy of the interpolated path. */
path = pstrdup(filestore_pool, buf);
break;
default:
/* Otherwise, use the path as is. */
path = pstrdup(filestore_pool, store_info);
break;
}
session.user = NULL;
PRIVS_ROOT
fh = pr_fsio_open(path, O_RDONLY|O_NONBLOCK);
xerrno = errno;
PRIVS_RELINQUISH
if (fh == NULL) {
destroy_pool(filestore_pool);
errno = xerrno;
return NULL;
}
if (pr_fsio_set_block(fh) < 0) {
xerrno = errno;
destroy_pool(filestore_pool);
(void) pr_fsio_close(fh);
errno = xerrno;
return NULL;
}
/* Stat the opened file to determine the optimal buffer size for IO. */
memset(&st, 0, sizeof(st));
if (pr_fsio_fstat(fh, &st) < 0) {
xerrno = errno;
destroy_pool(filestore_pool);
(void) pr_fsio_close(fh);
errno = xerrno;
return NULL;
}
if (S_ISDIR(st.st_mode)) {
destroy_pool(filestore_pool);
(void) pr_fsio_close(fh);
errno = EISDIR;
return NULL;
}
fh->fh_iosz = st.st_blksize;
store_data = pcalloc(filestore_pool, sizeof(struct filestore_data));
store->keystore_data = store_data;
store_data->path = path;
store_data->fh = fh;
store_data->lineno = 0;
store->store_ktypes = requested_key_type;
switch (requested_key_type) {
case SFTP_SSH2_HOST_KEY_STORE:
store->verify_host_key = filestore_verify_host_key;
break;
case SFTP_SSH2_USER_KEY_STORE:
store->verify_user_key = filestore_verify_user_key;
break;
}
store->store_close = filestore_close;
return store;
}
int sftp_rfc4716_init(void) {
sftp_keystore_register_store("file", filestore_open,
SFTP_SSH2_HOST_KEY_STORE|SFTP_SSH2_USER_KEY_STORE);
return 0;
}
int sftp_rfc4716_free(void) {
sftp_keystore_unregister_store("file",
SFTP_SSH2_HOST_KEY_STORE|SFTP_SSH2_USER_KEY_STORE);
return 0;
}
| Java |
<?php
class FrmListEntries extends WP_Widget {
function __construct() {
$widget_ops = array( 'description' => __( "Display a list of Formidable entries", 'formidable') );
$this->WP_Widget('frm_list_items', __('Formidable Entries List', 'formidable'), $widget_ops);
}
function widget( $args, $instance ) {
global $frmdb, $wpdb, $frm_entry, $frmpro_display, $frm_entry_meta;
extract($args);
$display = $frmpro_display->getOne($instance['display_id'], false, true);
$title = apply_filters('widget_title', (empty($instance['title']) and $display) ? $display->post_title : $instance['title']);
$limit = empty($instance['limit']) ? ' LIMIT 100' : " LIMIT {$instance['limit']}";
$post_id = (!$display or empty($display->frm_post_id)) ? $instance['post_id'] : $display->frm_post_id;
$page_url = get_permalink($post_id);
$order_by = '';
if ($display && is_numeric($display->frm_form_id) && !empty($display->frm_form_id) ) {
//Set up order for Entries List Widget
if ( isset($display->frm_order_by) && !empty($display->frm_order_by) ) {
//Get only the first order field and order
$order_field = reset($display->frm_order_by);
$order = reset($display->frm_order);
if ( $order_field == 'rand' ) {//If random is set, set the order to random
$order_by = ' RAND()';
} else if ( is_numeric($order_field) ) {//If ordering by a field
//Get all post IDs for this form
$posts = $wpdb->get_results($wpdb->prepare("SELECT id, post_id FROM {$wpdb->prefix}frm_items WHERE form_id=%d and post_id>%d AND is_draft=%d", $display->frm_form_id, 1, 0));
$linked_posts = array();
foreach ( $posts as $post_meta ) {
$linked_posts[$post_meta->post_id] = $post_meta->id;
}
//Get all field information
$frm_field = new FrmField();
$o_field = $frm_field->getOne($order_field);
//create query with ordered values
if ( isset($o_field->field_options['post_field']) and $o_field->field_options['post_field'] ) { //if field is some type of post field
if ( $o_field->field_options['post_field'] == 'post_custom' && ! empty($linked_posts) ) { //if field is custom field
$query = "SELECT m.id FROM {$wpdb->prefix}frm_items m INNER JOIN {$wpdb->postmeta} pm ON pm.post_id=m.post_id AND pm.meta_key='". $o_field->field_options['custom_field']."' WHERE pm.post_id in (". implode(',', array_keys($linked_posts)).") ORDER BY CASE when pm.meta_value IS NULL THEN 1 ELSE 0 END, pm.meta_value {$order}";
} else if ( $o_field->field_options['post_field'] != 'post_category' && ! empty($linked_posts) ) {//if field is a non-category post field
$query = "SELECT m.id FROM {$wpdb->prefix}frm_items m INNER JOIN {$wpdb->posts} p ON p.ID=m.post_id WHERE p.ID in (". implode(',', array_keys($linked_posts)).") ORDER BY CASE p.".$o_field->field_options['post_field']." WHEN '' THEN 1 ELSE 0 END, p.".$o_field->field_options['post_field']." {$order}";
}
} else { //if field is a normal, non-post field
$query = "SELECT m.id FROM {$wpdb->prefix}frm_items m INNER JOIN {$wpdb->prefix}frm_item_metas em ON em.item_id=m.id WHERE em.field_id=$o_field->id ORDER BY CASE when em.meta_value IS NULL THEN 1 ELSE 0 END, em.meta_value".($o_field->type == 'number' ? ' +0 ' : '')." {$order}";
}
//Get ordered values
$metas = $wpdb->get_results($query);
unset($query);
if (is_array($metas) and !empty($metas)){
$desc_order = ' DESC';
foreach ($metas as $meta)
$order_by .= $wpdb->prepare('it.id=%d'. $desc_order.', ', $meta->id);
$order_by = rtrim($order_by, ', ');
} else {
$order_by .= 'it.created_at '. $order;
}
} else if ( !empty($order_field) ) { //If ordering by created_at or updated_at
$order_by = 'it.'.$order_field.' '.$order;
}
if ( !empty($order_by) ) {
$order_by = ' ORDER BY '. $order_by;
}
}
if (isset($instance['cat_list']) and (int)$instance['cat_list'] == 1 and is_numeric($instance['cat_id'])){
global $frm_field;
if ($cat_field = $frm_field->getOne($instance['cat_id']))
$categories = maybe_unserialize($cat_field->options);
}
}
echo $before_widget;
if ( $title )
echo $before_title . $title . $after_title;
echo "<ul id='frm_entry_list". (($display) ? $display->frm_form_id : '') ."'>\n";
//if Listing entries by category
if ( isset($instance['cat_list']) and (int)$instance['cat_list'] == 1 and isset($categories) and is_array($categories) ) {
foreach ($categories as $cat_order => $cat){
if ($cat == '') continue;
echo '<li>';
if (isset($instance['cat_name']) and (int)$instance['cat_name'] == 1)
echo '<a href="'. add_query_arg(array('frm_cat' => $cat_field->field_key, 'frm_cat_id' => $cat_order), $page_url) .'">';
echo $cat;
if (isset($instance['cat_count']) and (int)$instance['cat_count'] == 1)
echo ' ('. FrmProFieldsHelper::get_field_stats($instance['cat_id'], 'count', false, $cat) .')';
if (isset($instance['cat_name']) and (int)$instance['cat_name'] == 1){
echo '</a>';
}else{
$entry_ids = $frm_entry_meta->getEntryIds("meta_value LIKE '%$cat%' and fi.id=". $instance['cat_id']);
$items = false;
if ($entry_ids)
$items = $frm_entry->getAll("it.id in (". implode(',', $entry_ids) .") and it.form_id =". (int)$display->frm_form_id, $order_by, $limit);
if ($items){
echo '<ul>';
foreach ($items as $item){
$url_id = $display->frm_type == 'id' ? $item->id : $item->item_key;
$current = (isset($_GET[$display->frm_param]) and $_GET[$display->frm_param] == $url_id) ? ' class="current_page"' : '';
if($item->post_id)
$entry_link = get_permalink($item->post_id);
else
$entry_link = add_query_arg(array($display->frm_param => $url_id), $page_url);
echo '<li'. $current .'><a href="'. $entry_link .'">'. $item->name .'</a></li>'. "\n";
}
echo '</ul>';
}
}
echo '</li>';
}
}else{ // if not listing entries by category
if($display)
$items = $frm_entry->getAll(array('it.form_id' => $display->frm_form_id, 'is_draft' => '0'), $order_by, $limit);
else
$items = array();
foreach ($items as $item){
$url_id = $display->frm_type == 'id' ? $item->id : $item->item_key;
$current = (isset($_GET[$display->frm_param]) and $_GET[$display->frm_param] == $url_id) ? ' class="current_page"' : '';
echo "<li". $current ."><a href='".add_query_arg(array($display->frm_param => $url_id), $page_url)."'>". $item->name ."</a></li>\n";
}
}
echo "</ul>\n";
echo $after_widget;
}
function update( $new_instance, $old_instance ) {
return $new_instance;
}
function form( $instance ) {
global $frmpro_display;
$pages = get_posts( array('post_type' => 'page', 'post_status' => 'publish', 'numberposts' => 999, 'order_by' => 'post_title', 'order' => 'ASC'));
$displays = $frmpro_display->getAll(array('meta_key' => 'show_count', 'meta_value' => 'dynamic'));
//Defaults
$instance = wp_parse_args( (array) $instance, array('title' => false, 'display_id' => false, 'post_id' => false, 'title_id' => false, 'cat_list' => false, 'cat_name' => false, 'cat_count' => false, 'cat_id' => false, 'limit' => false) );
$cat_opts = false;
if ($instance['display_id']){
global $frm_field;
$selected_display = $frmpro_display->getOne($instance['display_id']);
if($selected_display){
$selected_form_id = get_post_meta($selected_display->ID, 'frm_form_id', true);
$title_opts = $frm_field->getAll("fi.form_id=". (int)$selected_form_id ." and type not in ('divider','captcha','break','html')", ' ORDER BY field_order');
$instance['display_id'] = $selected_display->ID;
}
}
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title', 'formidable') ?>:</label>
<input type="text" class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr( stripslashes($instance['title']) ); ?>" /></p>
<p><label for="<?php echo $this->get_field_id('display_id'); ?>"><?php _e('Use Settings from View', 'formidable') ?>:</label>
<select name="<?php echo $this->get_field_name('display_id'); ?>" id="<?php echo $this->get_field_id('display_id'); ?>" class="widefat" onchange="frm_get_display_fields(this.value)">
<option value=""></option>
<?php foreach ($displays as $display)
echo "<option value=". $display->ID . selected( $instance['display_id'], $display->ID ) .">" . $display->post_title . "</option>";
?>
</select>
</p>
<p class="description"><?php _e('Views with a "Both (Dynamic)" format will show here.', 'formidable') ?></p>
<p><label for="<?php echo $this->get_field_id('post_id'); ?>"><?php _e('Page if not specified in View settings', 'formidable') ?>:</label>
<select name="<?php echo $this->get_field_name('post_id'); ?>" id="<?php echo $this->get_field_id('post_id'); ?>" class="widefat">
<option value=""></option>
<?php foreach ($pages as $page)
echo "<option value=". $page->ID . selected( $instance['post_id'], $page->ID ) . ">" . $page->post_title . "</option>";
?>
</select>
</p>
<p><label for="<?php echo $this->get_field_id('title_id'); ?>"><?php _e('Title Field', 'formidable') ?>:</label>
<select name="<?php echo $this->get_field_name('title_id'); ?>" id="<?php echo $this->get_field_id('title_id'); ?>" class="widefat">
<option value=""></option>
<?php
if (isset($title_opts) and $title_opts){
foreach ($title_opts as $title_opt)
if($title_opt->type != 'checkbox')
echo "<option value=". $title_opt->id . selected( $instance['title_id'], $title_opt->id ) . ">" . $title_opt->name . "</option>";
}
?>
</select>
</p>
<p><label for="<?php echo $this->get_field_id('cat_list'); ?>"><input class="checkbox" type="checkbox" <?php checked($instance['cat_list'], true) ?> id="<?php echo $this->get_field_id('cat_list'); ?>" name="<?php echo $this->get_field_name('cat_list'); ?>" value="1" onclick="frm_toggle_cat_opt(this.checked)"/>
<?php _e('List Entries by Category', 'formidable') ?></label></p>
<div id="<?php echo $this->get_field_id('hide_cat_opts'); ?>">
<p><label for="<?php echo $this->get_field_id('cat_id'); ?>"><?php _e('Category Field', 'formidable') ?>:</label>
<select name="<?php echo $this->get_field_name('cat_id'); ?>" id="<?php echo $this->get_field_id('cat_id'); ?>" class="widefat">
<option value=""></option>
<?php
if (isset($title_opts) and $title_opts){
foreach ($title_opts as $title_opt){
if(in_array($title_opt->type, array('select', 'radio', 'checkbox')))
echo "<option value=". $title_opt->id . selected( $instance['cat_id'], $title_opt->id ) . ">" . $title_opt->name . "</option>";
}
}
?>
</select>
</p>
<p><label for="<?php echo $this->get_field_id('cat_count'); ?>"><input class="checkbox" type="checkbox" <?php checked($instance['cat_count'], true) ?> id="<?php echo $this->get_field_id('cat_count'); ?>" name="<?php echo $this->get_field_name('cat_count'); ?>" value="1" />
<?php _e('Show Entry Counts', 'formidable') ?></label></p>
<p><input class="checkbox" type="radio" <?php checked($instance['cat_name'], 1) ?> id="<?php echo $this->get_field_id('cat_name'); ?>" name="<?php echo $this->get_field_name('cat_name'); ?>" value="1" />
<label for="<?php echo $this->get_field_id('cat_name'); ?>"><?php _e('Show Only Category Name', 'formidable') ?></label><br/>
<input class="checkbox" type="radio" <?php checked($instance['cat_name'], 0) ?> id="<?php echo $this->get_field_id('cat_name'); ?>" name="<?php echo $this->get_field_name('cat_name'); ?>" value="0" />
<label for="<?php echo $this->get_field_id('cat_name'); ?>"><?php _e('Show Entries Beneath Categories', 'formidable') ?></label></p>
</div>
<p><label for="<?php echo $this->get_field_id('limit'); ?>"><?php _e('Entry Limit (leave blank to list all)', 'formidable') ?>:</label>
<input type="text" class="widefat" id="<?php echo $this->get_field_id('limit'); ?>" name="<?php echo $this->get_field_name('limit'); ?>" value="<?php echo esc_attr( $instance['limit'] ); ?>" /></p>
<script type="text/javascript">
jQuery(document).ready(function($){
jQuery("#<?php echo $this->get_field_id('hide_cat_opts') ?>").hide();
if (jQuery("#<?php echo $this->get_field_id('cat_list'); ?>").attr("checked"))
jQuery("#<?php echo $this->get_field_id('hide_cat_opts') ?>").show();
});
function frm_toggle_cat_opt(checked){
if (checked) jQuery("#<?php echo $this->get_field_id('hide_cat_opts') ?>").fadeIn('slow');
else jQuery("#<?php echo $this->get_field_id('hide_cat_opts') ?>").fadeOut('slow');
}
function frm_get_display_fields(display_id){
if (display_id != ''){
jQuery.ajax({ type:"POST", url:"<?php echo admin_url('admin-ajax.php') ?>",
data:"action=frm_get_cat_opts&display_id="+display_id,
success:function(msg){jQuery("#<?php echo $this->get_field_id('cat_id'); ?>").html(msg);}
});
jQuery.ajax({ type:"POST", url:"<?php echo admin_url('admin-ajax.php') ?>",
data:"action=frm_get_title_opts&display_id="+display_id,
success:function(msg){jQuery("#<?php echo $this->get_field_id('title_id'); ?>").html(msg);}
});
}
}
</script>
<?php
}
}
?> | Java |
<?php defined('_JEXEC') or die('Restricted access'); ?>
<?php $form = @$this->form; ?>
<?php $row = @$this->row;
JFilterOutput::objectHTMLSafe( $row );
?>
<form action="<?php echo JRoute::_( @$form['action'] ) ?>" method="post" class="adminform" name="adminForm" >
<fieldset>
<legend><?php echo JText::_('Form'); ?></legend>
<table class="admintable">
<tr>
<td width="100" align="right" class="key">
<label for="tax_class_name">
<?php echo JText::_( 'Name' ); ?>:
</label>
</td>
<td>
<input type="text" name="tax_class_name" id="tax_class_name" size="48" maxlength="250" value="<?php echo @$row->tax_class_name; ?>" />
</td>
</tr>
<tr>
<td width="100" align="right" class="key">
<label for="tax_class_description">
<?php echo JText::_( 'Description' ); ?>:
</label>
</td>
<td>
<textarea name="tax_class_description" id="tax_class_description" rows="10" cols="25"><?php echo @$row->tax_class_description; ?></textarea>
</td>
</tr>
</table>
<input type="hidden" name="id" value="<?php echo @$row->tax_class_id; ?>" />
<input type="hidden" name="task" value="" />
</fieldset>
</form> | Java |
div.contemplate-input .form-textarea {
height: 200px;
border: 1px solid #666;
font-family: Profont, 'lucida console', Monaco, monospace;
}
div.contemplate-scroller {
padding: 0 1em;
height: 150px;
overflow: auto;
border: 1px solid #666;
} | Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML
><HEAD
><TITLE
>The Traces Menu</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REL="HOME"
TITLE="The Klusters Handbook"
HREF="index.html"><LINK
REL="UP"
TITLE="Menu Entries"
HREF="c1059.html"><LINK
REL="PREVIOUS"
TITLE="The Correlations Menu"
HREF="x1391.html"><LINK
REL="NEXT"
TITLE="The Displays Menu"
HREF="x1498.html"></HEAD
><BODY
CLASS="sect1"
BGCOLOR="#FFFFFF"
TEXT="#000000"
LINK="#0000FF"
VLINK="#840084"
ALINK="#0000FF"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="3"
ALIGN="center"
>The Klusters Handbook</TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="bottom"
><A
HREF="x1391.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="80%"
ALIGN="center"
VALIGN="bottom"
>Chapter 5. Menu Entries</TD
><TD
WIDTH="10%"
ALIGN="right"
VALIGN="bottom"
><A
HREF="x1498.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><DIV
CLASS="sect1"
><H1
CLASS="sect1"
><A
NAME="menu-traces"
>5.7. The Traces Menu</A
></H1
><P
> <P
></P
><DIV
CLASS="variablelist"
><DL
><DT
><SPAN
CLASS="guimenu"
>Traces</SPAN
>-><SPAN
CLASS="guimenuitem"
>Increase Channel Amplitudes</SPAN
> (<B
CLASS="shortcut"
><B
CLASS="keycap"
>Ctrl</B
>-<B
CLASS="keycap"
>Shift</B
>-<B
CLASS="keycap"
>I</B
></B
>)</DT
><DD
><P
>Increases the channel amplitudes</P
></DD
><DT
><SPAN
CLASS="guimenu"
>Traces</SPAN
>-><SPAN
CLASS="guimenuitem"
>Decrease Channel Amplitudes</SPAN
> (<B
CLASS="shortcut"
><B
CLASS="keycap"
>Ctrl</B
>-<B
CLASS="keycap"
>Shift</B
>-<B
CLASS="keycap"
>D</B
></B
>)</DT
><DD
><P
>Decreases the channel amplitudes</P
></DD
><DT
><SPAN
CLASS="guimenu"
>Traces</SPAN
>-><SPAN
CLASS="guimenuitem"
>Show Labels</SPAN
> (<B
CLASS="shortcut"
><B
CLASS="keycap"
>Ctrl</B
>-<B
CLASS="keycap"
>L</B
></B
>)</DT
><DD
><P
>Shows or hides the labels (channel IDs and gains).</P
></DD
></DL
></DIV
>
</P
></DIV
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="x1391.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="x1498.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>The Correlations Menu</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="c1059.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>The Displays Menu</TD
></TR
></TABLE
></DIV
></BODY
></HTML
> | Java |
<?php
class FlipMegazineImageHelper
{
/**
* @param int $parentNodeId
* @param eZCLI $cli
*/
public static function deleteThumb( $parentNodeId, $cli = null )
{
/** @var eZContentObjectTreeNode[] $children */
$children = eZContentObjectTreeNode::subTreeByNodeID(
array( 'ClassFilterType' => 'include',
'ClassFilterArray' => array( 'image' ) ),
$parentNodeId
);
if ( count( $children ) > 0 )
{
$message = "Remove " . count( $children ) . " images from node $parentNodeId";
if ( $cli )
{
$cli->output( $message );
}
else
{
eZDebug::writeNotice( $message , __METHOD__ );
}
foreach ( $children as $node )
{
$node->removeNodeFromTree();
}
}
}
/**
* @param string $directory
* @param string $imageName
* @param string $parentNodeId
* @return eZContentObject|false
*/
public static function createThumb( $directory, $imageName, $parentNodeId )
{
$user = eZUser::currentUser();
$params = array();
$params['class_identifier'] = 'image';
$params['creator_id'] = $user->attribute( 'contentobject_id' );
$params['parent_node_id'] = $parentNodeId;
$params['storage_dir'] = eZSys::rootDir() . eZSys::fileSeparator() . $directory . '/';
$attributesData = array ( ) ;
$attributesData['name'] = $imageName;
$attributesData['image'] = $imageName;
$params['attributes'] = $attributesData;
$imageContentObject = eZContentFunctions::createAndPublishObject($params);
return $imageContentObject;
}
}
?>
| Java |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2011-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.icmp;
import java.net.InetAddress;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>SinglePingResponseCallback class.</p>
*
* @author <a href="mailto:[email protected]">Ben Reed</a>
* @author <a href="mailto:[email protected]">Mathew Brozowski</a>
*/
public class SinglePingResponseCallback implements PingResponseCallback {
private static final Logger LOG = LoggerFactory
.getLogger(SinglePingResponseCallback.class);
/**
* Value of round-trip-time for the ping in microseconds.
*/
private Long m_responseTime = null;
private InetAddress m_host;
private Throwable m_error = null;
private CountDownLatch m_latch = new CountDownLatch(1);
/**
* <p>Constructor for SinglePingResponseCallback.</p>
*
* @param host a {@link java.net.InetAddress} object.
*/
public SinglePingResponseCallback(InetAddress host) {
m_host = host;
}
/** {@inheritDoc} */
@Override
public void handleResponse(InetAddress address, EchoPacket response) {
try {
info("got response for address " + address + ", thread " + response.getIdentifier() + ", seq " + response.getSequenceNumber() + " with a responseTime "+response.elapsedTime(TimeUnit.MILLISECONDS)+"ms");
m_responseTime = (long)Math.round(response.elapsedTime(TimeUnit.MICROSECONDS));
} finally {
m_latch.countDown();
}
}
/** {@inheritDoc} */
@Override
public void handleTimeout(InetAddress address, EchoPacket request) {
try {
assert(request != null);
info("timed out pinging address " + address + ", thread " + request.getIdentifier() + ", seq " + request.getSequenceNumber());
} finally {
m_latch.countDown();
}
}
/** {@inheritDoc} */
@Override
public void handleError(InetAddress address, EchoPacket request, Throwable t) {
try {
m_error = t;
info("an error occurred pinging " + address, t);
} finally {
m_latch.countDown();
}
}
/**
* <p>waitFor</p>
*
* @param timeout a long.
* @throws java.lang.InterruptedException if any.
*/
public void waitFor(long timeout) throws InterruptedException {
m_latch.await(timeout, TimeUnit.MILLISECONDS);
}
/**
* <p>waitFor</p>
*
* @throws java.lang.InterruptedException if any.
*/
public void waitFor() throws InterruptedException {
info("waiting for ping to "+m_host+" to finish");
m_latch.await();
info("finished waiting for ping to "+m_host+" to finish");
}
public void rethrowError() throws Exception {
if (m_error instanceof Error) {
throw (Error)m_error;
} else if (m_error instanceof Exception) {
throw (Exception)m_error;
}
}
/**
* <p>Getter for the field <code>responseTime</code>.</p>
*
* @return a {@link java.lang.Long} object.
*/
public Long getResponseTime() {
return m_responseTime;
}
public Throwable getError() {
return m_error;
}
/**
* <p>info</p>
*
* @param msg a {@link java.lang.String} object.
*/
public void info(String msg) {
LOG.info(msg);
}
/**
* <p>info</p>
*
* @param msg a {@link java.lang.String} object.
* @param t a {@link java.lang.Throwable} object.
*/
public void info(String msg, Throwable t) {
LOG.info(msg, t);
}
}
| Java |
/*
* Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef MANGOSSERVER_GOSSIP_H
#define MANGOSSERVER_GOSSIP_H
#include "Common.h"
#include "QuestDef.h"
#include "NPCHandler.h"
class WorldSession;
#define GOSSIP_MAX_MENU_ITEMS 64 // client supported items unknown, but provided number must be enough
#define DEFAULT_GOSSIP_MESSAGE 0xffffff
enum Gossip_Option
{
GOSSIP_OPTION_NONE = 0, //UNIT_NPC_FLAG_NONE (0)
GOSSIP_OPTION_GOSSIP = 1, //UNIT_NPC_FLAG_GOSSIP (1)
GOSSIP_OPTION_QUESTGIVER = 2, //UNIT_NPC_FLAG_QUESTGIVER (2)
GOSSIP_OPTION_VENDOR = 3, //UNIT_NPC_FLAG_VENDOR (128)
GOSSIP_OPTION_TAXIVENDOR = 4, //UNIT_NPC_FLAG_TAXIVENDOR (8192)
GOSSIP_OPTION_TRAINER = 5, //UNIT_NPC_FLAG_TRAINER (16)
GOSSIP_OPTION_SPIRITHEALER = 6, //UNIT_NPC_FLAG_SPIRITHEALER (16384)
GOSSIP_OPTION_SPIRITGUIDE = 7, //UNIT_NPC_FLAG_SPIRITGUIDE (32768)
GOSSIP_OPTION_INNKEEPER = 8, //UNIT_NPC_FLAG_INNKEEPER (65536)
GOSSIP_OPTION_BANKER = 9, //UNIT_NPC_FLAG_BANKER (131072)
GOSSIP_OPTION_PETITIONER = 10, //UNIT_NPC_FLAG_PETITIONER (262144)
GOSSIP_OPTION_TABARDDESIGNER = 11, //UNIT_NPC_FLAG_TABARDDESIGNER (524288)
GOSSIP_OPTION_BATTLEFIELD = 12, //UNIT_NPC_FLAG_BATTLEFIELDPERSON (1048576)
GOSSIP_OPTION_AUCTIONEER = 13, //UNIT_NPC_FLAG_AUCTIONEER (2097152)
GOSSIP_OPTION_STABLEPET = 14, //UNIT_NPC_FLAG_STABLE (4194304)
GOSSIP_OPTION_ARMORER = 15, //UNIT_NPC_FLAG_ARMORER (4096)
GOSSIP_OPTION_UNLEARNTALENTS = 16, //UNIT_NPC_FLAG_TRAINER (16) (bonus option for GOSSIP_OPTION_TRAINER)
GOSSIP_OPTION_UNLEARNPETSKILLS = 17, //UNIT_NPC_FLAG_TRAINER (16) (bonus option for GOSSIP_OPTION_TRAINER)
GOSSIP_OPTION_MAX
};
enum GossipOptionIcon
{
GOSSIP_ICON_CHAT = 0, //white chat bubble
GOSSIP_ICON_VENDOR = 1, //brown bag
GOSSIP_ICON_TAXI = 2, //flight
GOSSIP_ICON_TRAINER = 3, //book
GOSSIP_ICON_INTERACT_1 = 4, //interaction wheel
GOSSIP_ICON_INTERACT_2 = 5, //interaction wheel
GOSSIP_ICON_MONEY_BAG = 6, //brown bag with yellow dot
GOSSIP_ICON_TALK = 7, //white chat bubble with black dots
GOSSIP_ICON_TABARD = 8, //tabard
GOSSIP_ICON_BATTLE = 9, //two swords
GOSSIP_ICON_DOT = 10, //yellow dot
GOSSIP_ICON_CHAT_11 = 11, //This and below are most the same visual as GOSSIP_ICON_CHAT
GOSSIP_ICON_CHAT_12 = 12, //but are still used for unknown reasons.
GOSSIP_ICON_CHAT_13 = 13,
GOSSIP_ICON_CHAT_14 = 14, // probably invalid
GOSSIP_ICON_CHAT_15 = 15, // probably invalid
GOSSIP_ICON_CHAT_16 = 16,
GOSSIP_ICON_CHAT_17 = 17,
GOSSIP_ICON_CHAT_18 = 18,
GOSSIP_ICON_CHAT_19 = 19,
GOSSIP_ICON_CHAT_20 = 20,
GOSSIP_ICON_MAX
};
//POI icons. Many more exist, list not complete.
enum Poi_Icon
{
ICON_POI_BLANK = 0, // Blank (not visible), in 2.4.3 have value 15 with 1..15 values in 0..14 range
ICON_POI_GREY_AV_MINE = 1, // Grey mine lorry
ICON_POI_RED_AV_MINE = 2, // Red mine lorry
ICON_POI_BLUE_AV_MINE = 3, // Blue mine lorry
ICON_POI_BWTOMB = 4, // Blue and White Tomb Stone
ICON_POI_SMALL_HOUSE = 5, // Small house
ICON_POI_GREYTOWER = 6, // Grey Tower
ICON_POI_REDFLAG = 7, // Red Flag w/Yellow !
ICON_POI_TOMBSTONE = 8, // Normal tomb stone (brown)
ICON_POI_BWTOWER = 9, // Blue and White Tower
ICON_POI_REDTOWER = 10, // Red Tower
ICON_POI_BLUETOWER = 11, // Blue Tower
ICON_POI_RWTOWER = 12, // Red and White Tower
ICON_POI_REDTOMB = 13, // Red Tomb Stone
ICON_POI_RWTOMB = 14, // Red and White Tomb Stone
ICON_POI_BLUETOMB = 15, // Blue Tomb Stone
ICON_POI_16 = 16, // Grey ?
ICON_POI_17 = 17, // Blue/White ?
ICON_POI_18 = 18, // Blue ?
ICON_POI_19 = 19, // Red and White ?
ICON_POI_20 = 20, // Red ?
ICON_POI_GREYLOGS = 21, // Grey Wood Logs
ICON_POI_BWLOGS = 22, // Blue and White Wood Logs
ICON_POI_BLUELOGS = 23, // Blue Wood Logs
ICON_POI_RWLOGS = 24, // Red and White Wood Logs
ICON_POI_REDLOGS = 25, // Red Wood Logs
ICON_POI_26 = 26, // Grey ?
ICON_POI_27 = 27, // Blue and White ?
ICON_POI_28 = 28, // Blue ?
ICON_POI_29 = 29, // Red and White ?
ICON_POI_30 = 30, // Red ?
ICON_POI_GREYHOUSE = 31, // Grey House
ICON_POI_BWHOUSE = 32, // Blue and White House
ICON_POI_BLUEHOUSE = 33, // Blue House
ICON_POI_RWHOUSE = 34, // Red and White House
ICON_POI_REDHOUSE = 35, // Red House
ICON_POI_GREYHORSE = 36, // Grey Horse
ICON_POI_BWHORSE = 37, // Blue and White Horse
ICON_POI_BLUEHORSE = 38, // Blue Horse
ICON_POI_RWHORSE = 39, // Red and White Horse
ICON_POI_REDHORSE = 40 // Red Horse
};
struct GossipMenuItem
{
uint8 m_gIcon;
bool m_gCoded;
std::string m_gMessage;
uint32 m_gSender;
uint32 m_gOptionId;
std::string m_gBoxMessage;
uint32 m_gBoxMoney;
};
typedef std::vector<GossipMenuItem> GossipMenuItemList;
struct GossipMenuItemData
{
uint32 m_gAction_menu;
uint32 m_gAction_poi;
uint32 m_gAction_script;
};
typedef std::vector<GossipMenuItemData> GossipMenuItemDataList;
struct QuestMenuItem
{
uint32 m_qId;
uint8 m_qIcon;
};
typedef std::vector<QuestMenuItem> QuestMenuItemList;
class MANGOS_DLL_SPEC GossipMenu
{
public:
explicit GossipMenu(WorldSession* session);
~GossipMenu();
void AddMenuItem(uint8 Icon, const std::string& Message, bool Coded = false);
void AddMenuItem(uint8 Icon, const std::string& Message, uint32 dtSender, uint32 dtAction, const std::string& BoxMessage, uint32 BoxMoney, bool Coded = false);
// for using from scripts, don't must be inlined
void AddMenuItem(uint8 Icon, char const* Message, bool Coded = false);
void AddMenuItem(uint8 Icon, char const* Message, uint32 dtSender, uint32 dtAction, char const* BoxMessage, uint32 BoxMoney, bool Coded = false);
void AddMenuItem(uint8 Icon, int32 itemText, uint32 dtSender, uint32 dtAction, int32 boxText, uint32 BoxMoney, bool Coded = false);
void SetMenuId(uint32 menu_id) { m_gMenuId = menu_id; }
uint32 GetMenuId() { return m_gMenuId; }
void AddGossipMenuItemData(uint32 action_menu, uint32 action_poi, uint32 action_script);
unsigned int MenuItemCount() const
{
return m_gItems.size();
}
bool Empty() const
{
return m_gItems.empty();
}
GossipMenuItem const& GetItem( unsigned int Id )
{
return m_gItems[ Id ];
}
GossipMenuItemData const& GetItemData(unsigned int indexId)
{
return m_gItemsData[indexId];
}
uint32 MenuItemSender( unsigned int ItemId );
uint32 MenuItemAction( unsigned int ItemId );
bool MenuItemCoded( unsigned int ItemId );
void ClearMenu();
WorldSession* GetMenuSession() const { return m_session; }
protected:
GossipMenuItemList m_gItems;
GossipMenuItemDataList m_gItemsData;
uint32 m_gMenuId;
private:
WorldSession* m_session;
};
class QuestMenu
{
public:
QuestMenu();
~QuestMenu();
void AddMenuItem( uint32 QuestId, uint8 Icon);
void ClearMenu();
uint8 MenuItemCount() const
{
return m_qItems.size();
}
bool Empty() const
{
return m_qItems.empty();
}
bool HasItem( uint32 questid );
QuestMenuItem const& GetItem( uint16 Id )
{
return m_qItems[ Id ];
}
protected:
QuestMenuItemList m_qItems;
};
class MANGOS_DLL_SPEC PlayerMenu
{
private:
GossipMenu mGossipMenu;
QuestMenu mQuestMenu;
public:
explicit PlayerMenu(WorldSession *Session);
~PlayerMenu();
GossipMenu& GetGossipMenu() { return mGossipMenu; }
QuestMenu& GetQuestMenu() { return mQuestMenu; }
WorldSession* GetMenuSession() const { return mGossipMenu.GetMenuSession(); }
bool Empty() const { return mGossipMenu.Empty() && mQuestMenu.Empty(); }
void ClearMenus();
uint32 GossipOptionSender( unsigned int Selection );
uint32 GossipOptionAction( unsigned int Selection );
bool GossipOptionCoded( unsigned int Selection );
void SendGossipMenu( uint32 TitleTextId, uint64 npcGUID );
void CloseGossip();
void SendPointOfInterest( float X, float Y, uint32 Icon, uint32 Flags, uint32 Data, const char * locName );
void SendPointOfInterest( uint32 poi_id );
void SendTalking( uint32 textID );
void SendTalking( char const * title, char const * text );
/*********************************************************/
/*** QUEST SYSTEM ***/
/*********************************************************/
void SendQuestGiverStatus( uint8 questStatus, uint64 npcGUID );
void SendQuestGiverQuestList( QEmote eEmote, const std::string& Title, uint64 npcGUID );
void SendQuestQueryResponse ( Quest const *pQuest );
void SendQuestGiverQuestDetails( Quest const *pQuest, uint64 npcGUID, bool ActivateAccept);
void SendQuestGiverOfferReward( Quest const* pQuest, uint64 npcGUID, bool EnbleNext );
void SendQuestGiverRequestItems( Quest const *pQuest, uint64 npcGUID, bool Completable, bool CloseOnCancel );
};
#endif
| Java |
/* Copyright (c) 2006-2010 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the Clear BSD license.
* See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Layer.js
*/
/**
* Class: OpenLayers.Layer.Markers
*
* Inherits from:
* - <OpenLayers.Layer>
*/
OpenLayers.Layer.Markers = OpenLayers.Class(OpenLayers.Layer, {
/**
* APIProperty: isBaseLayer
* {Boolean} Markers layer is never a base layer.
*/
isBaseLayer: false,
/**
* APIProperty: markers
* {Array(<OpenLayers.Marker>)} internal marker list
*/
markers: null,
/**
* Property: drawn
* {Boolean} internal state of drawing. This is a workaround for the fact
* that the map does not call moveTo with a zoomChanged when the map is
* first starting up. This lets us catch the case where we have *never*
* drawn the layer, and draw it even if the zoom hasn't changed.
*/
drawn: false,
/**
* Constructor: OpenLayers.Layer.Markers
* Create a Markers layer.
*
* Parameters:
* name - {String}
* options - {Object} Hashtable of extra options to tag onto the layer
*/
initialize: function(name, options) {
OpenLayers.Layer.prototype.initialize.apply(this, arguments);
this.markers = [];
},
/**
* APIMethod: destroy
*/
destroy: function() {
this.clearMarkers();
this.markers = null;
OpenLayers.Layer.prototype.destroy.apply(this, arguments);
},
/**
* APIMethod: setOpacity
* Sets the opacity for all the markers.
*
* Parameter:
* opacity - {Float}
*/
setOpacity: function(opacity) {
if (opacity != this.opacity) {
this.opacity = opacity;
for (var i=0, len=this.markers.length; i<len; i++) {
this.markers[i].setOpacity(this.opacity);
}
}
},
/**
* Method: moveTo
*
* Parameters:
* bounds - {<OpenLayers.Bounds>}
* zoomChanged - {Boolean}
* dragging - {Boolean}
*/
moveTo:function(bounds, zoomChanged, dragging) {
OpenLayers.Layer.prototype.moveTo.apply(this, arguments);
if (zoomChanged || !this.drawn) {
for(var i=0, len=this.markers.length; i<len; i++) {
this.drawMarker(this.markers[i]);
}
this.drawn = true;
}
},
/**
* APIMethod: addMarker
*
* Parameters:
* marker - {<OpenLayers.Marker>}
*/
addMarker: function(marker) {
this.markers.push(marker);
if (this.opacity != null) {
marker.setOpacity(this.opacity);
}
if (this.map && this.map.getExtent()) {
marker.map = this.map;
this.drawMarker(marker);
}
},
/**
* APIMethod: removeMarker
*
* Parameters:
* marker - {<OpenLayers.Marker>}
*/
removeMarker: function(marker) {
if (this.markers && this.markers.length) {
OpenLayers.Util.removeItem(this.markers, marker);
marker.erase();
}
},
/**
* Method: clearMarkers
* This method removes all markers from a layer. The markers are not
* destroyed by this function, but are removed from the list of markers.
*/
clearMarkers: function() {
if (this.markers != null) {
while(this.markers.length > 0) {
this.removeMarker(this.markers[0]);
}
}
},
/**
* Method: drawMarker
* Calculate the pixel location for the marker, create it, and
* add it to the layer's div
*
* Parameters:
* marker - {<OpenLayers.Marker>}
*/
drawMarker: function(marker) {
var px = this.map.getLayerPxFromLonLat(marker.lonlat);
if (px == null) {
marker.display(false);
} else {
if (!marker.isDrawn()) {
var markerImg = marker.draw(px);
this.div.appendChild(markerImg);
} else if(marker.icon) {
marker.icon.moveTo(px);
}
}
},
/**
* APIMethod: getDataExtent
* Calculates the max extent which includes all of the markers.
*
* Returns:
* {<OpenLayers.Bounds>}
*/
getDataExtent: function () {
var maxExtent = null;
if ( this.markers && (this.markers.length > 0)) {
var maxExtent = new OpenLayers.Bounds();
for(var i=0, len=this.markers.length; i<len; i++) {
var marker = this.markers[i];
maxExtent.extend(marker.lonlat);
}
}
return maxExtent;
},
CLASS_NAME: "OpenLayers.Layer.Markers"
});
| Java |
<?php
/**
* Add Site Administration Screen
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
/** WordPress Translation Install API */
require_once( ABSPATH . 'wp-admin/includes/translation-install.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
if ( ! current_user_can( 'manage_sites' ) )
wp_die( __( 'You do not have sufficient permissions to add sites to this network.' ) );
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('This screen is for Super Admins to add new sites to the network. This is not affected by the registration settings.') . '</p>' .
'<p>' . __('If the admin email for the new site does not exist in the database, a new user will also be created.') . '</p>'
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="https://codex.wordpress.org/Network_Admin_Sites_Screen" target="_blank">Documentation on Site Management</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/forum/multisite/" target="_blank">Support Forums</a>') . '</p>'
);
if ( wp_validate_action( 'add-site' ) ) {
check_admin_referer( 'add-blog', '_wpnonce_add-blog' );
if ( ! is_array( $_POST['blog'] ) )
wp_die( __( 'Can’t create an empty site.' ) );
$blog = $_POST['blog'];
$domain = '';
if ( preg_match( '|^([a-zA-Z0-9-])+$|', $blog['domain'] ) )
$domain = strtolower( $blog['domain'] );
// If not a subdomain install, make sure the domain isn't a reserved word
if ( ! is_subdomain_install() ) {
/** This filter is documented in wp-includes/ms-functions.php */
$subdirectory_reserved_names = apply_filters( 'subdirectory_reserved_names', array( 'page', 'comments', 'blog', 'files', 'feed', 'wp-admin', 'wp-content', 'wp-includes' ) );
if ( in_array( $domain, $subdirectory_reserved_names ) )
wp_die( sprintf( __('The following words are reserved for use by WordPress functions and cannot be used as blog names: <code>%s</code>' ), implode( '</code>, <code>', $subdirectory_reserved_names ) ) );
}
$title = $blog['title'];
$meta = array(
'public' => 1
);
// Handle translation install for the new site.
if ( ! empty( $_POST['WPLANG'] ) && wp_can_install_language_pack() ) {
$language = wp_download_language_pack( wp_unslash( $_POST['WPLANG'] ) );
if ( $language ) {
$meta['WPLANG'] = $language;
}
}
if ( empty( $domain ) )
wp_die( __( 'Missing or invalid site address.' ) );
if ( isset( $blog['email'] ) && '' === trim( $blog['email'] ) ) {
wp_die( __( 'Missing email address.' ) );
}
$email = sanitize_email( $blog['email'] );
if ( ! is_email( $email ) ) {
wp_die( __( 'Invalid email address.' ) );
}
if ( is_subdomain_install() ) {
$newdomain = $domain . '.' . preg_replace( '|^www\.|', '', $current_site->domain );
$path = $current_site->path;
} else {
$newdomain = $current_site->domain;
$path = $current_site->path . $domain . '/';
}
$password = 'N/A';
$user_id = email_exists($email);
if ( !$user_id ) { // Create a new user with a random password
$password = wp_generate_password( 12, false );
$user_id = wpmu_create_user( $domain, $password, $email );
if ( false === $user_id )
wp_die( __( 'There was an error creating the user.' ) );
else
wp_new_user_notification( $user_id, null, 'both' );
}
$wpdb->hide_errors();
$id = wpmu_create_blog( $newdomain, $path, $title, $user_id, $meta, $current_site->id );
$wpdb->show_errors();
if ( ! is_wp_error( $id ) ) {
if ( ! is_super_admin( $user_id ) && !get_user_option( 'primary_blog', $user_id ) ) {
update_user_option( $user_id, 'primary_blog', $id, true );
}
$content_mail = sprintf(
/* translators: 1: user login, 2: site url, 3: site name/title */
__( 'New site created by %1$s
Address: %2$s
Name: %3$s' ),
$current_user->user_login,
get_site_url( $id ),
wp_unslash( $title )
);
wp_mail( get_site_option('admin_email'), sprintf( __( '[%s] New Site Created' ), $current_site->site_name ), $content_mail, 'From: "Site Admin" <' . get_site_option( 'admin_email' ) . '>' );
wpmu_welcome_notification( $id, $user_id, $password, $title, array( 'public' => 1 ) );
wp_redirect( add_query_arg( array( 'update' => 'added', 'id' => $id ), 'site-new.php' ) );
exit;
} else {
wp_die( $id->get_error_message() );
}
}
if ( isset($_GET['update']) ) {
$messages = array();
if ( 'added' == $_GET['update'] )
$messages[] = sprintf(
/* translators: 1: dashboard url, 2: network admin edit url */
__( 'Site added. <a href="%1$s">Visit Dashboard</a> or <a href="%2$s">Edit Site</a>' ),
esc_url( get_admin_url( absint( $_GET['id'] ) ) ),
network_admin_url( 'site-info.php?id=' . absint( $_GET['id'] ) )
);
}
$title = __('Add New Site');
$parent_file = 'sites.php';
wp_enqueue_script( 'user-suggest' );
require( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<h1 id="add-new-site"><?php _e( 'Add New Site' ); ?></h1>
<?php
if ( ! empty( $messages ) ) {
foreach ( $messages as $msg )
echo '<div id="message" class="updated notice is-dismissible"><p>' . $msg . '</p></div>';
} ?>
<form method="post" action="<?php echo network_admin_url( 'site-new.php?action=add-site' ); ?>" novalidate="novalidate">
<?php wp_nonce_field( 'add-blog', '_wpnonce_add-blog' ) ?>
<table class="form-table">
<tr class="form-field form-required">
<th scope="row"><label for="site-address"><?php _e( 'Site Address' ) ?></label></th>
<td>
<?php if ( is_subdomain_install() ) { ?>
<input name="blog[domain]" type="text" class="regular-text" id="site-address" aria-describedby="site-address-desc" autocapitalize="none" autocorrect="off"/><span class="no-break">.<?php echo preg_replace( '|^www\.|', '', $current_site->domain ); ?></span>
<?php } else {
echo $current_site->domain . $current_site->path ?><input name="blog[domain]" type="text" class="regular-text" id="site-address" aria-describedby="site-address-desc" autocapitalize="none" autocorrect="off" />
<?php }
echo '<p id="site-address-desc">' . __( 'Only lowercase letters (a-z) and numbers are allowed.' ) . '</p>';
?>
</td>
</tr>
<tr class="form-field form-required">
<th scope="row"><label for="site-title"><?php _e( 'Site Title' ) ?></label></th>
<td><input name="blog[title]" type="text" class="regular-text" id="site-title" /></td>
</tr>
<?php
$languages = get_available_languages();
$translations = wp_get_available_translations();
if ( ! empty( $languages ) || ! empty( $translations ) ) :
?>
<tr class="form-field form-required">
<th scope="row"><label for="site-language"><?php _e( 'Site Language' ); ?></label></th>
<td>
<?php
// Network default.
$lang = get_site_option( 'WPLANG' );
// Use English if the default isn't available.
if ( ! in_array( $lang, $languages ) ) {
$lang = '';
}
wp_dropdown_languages( array(
'name' => 'WPLANG',
'id' => 'site-language',
'selected' => $lang,
'languages' => $languages,
'translations' => $translations,
'show_available_translations' => wp_can_install_language_pack(),
) );
?>
</td>
</tr>
<?php endif; // Languages. ?>
<tr class="form-field form-required">
<th scope="row"><label for="admin-email"><?php _e( 'Admin Email' ) ?></label></th>
<td><input name="blog[email]" type="email" class="regular-text wp-suggest-user" id="admin-email" data-autocomplete-type="search" data-autocomplete-field="user_email" /></td>
</tr>
<tr class="form-field">
<td colspan="2"><?php _e( 'A new user will be created if the above email address is not in the database.' ) ?><br /><?php _e( 'The username and password will be mailed to this email address.' ) ?></td>
</tr>
</table>
<?php submit_button( __('Add Site'), 'primary', 'add-site' ); ?>
</form>
</div>
<?php
require( ABSPATH . 'wp-admin/admin-footer.php' );
| Java |
// Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <array>
#include <fstream>
#include <functional>
#include <cstddef>
#include <cstdio>
#include <string>
#include <vector>
#include "common/common_types.h"
// User directory indices for GetUserPath
enum {
D_USER_IDX,
D_ROOT_IDX,
D_CONFIG_IDX,
D_GAMECONFIG_IDX,
D_MAPS_IDX,
D_CACHE_IDX,
D_SHADERCACHE_IDX,
D_SHADERS_IDX,
D_STATESAVES_IDX,
D_SCREENSHOTS_IDX,
D_SDMC_IDX,
D_NAND_IDX,
D_SYSDATA_IDX,
D_HIRESTEXTURES_IDX,
D_DUMP_IDX,
D_DUMPFRAMES_IDX,
D_DUMPAUDIO_IDX,
D_DUMPTEXTURES_IDX,
D_DUMPDSP_IDX,
D_LOGS_IDX,
D_SYSCONF_IDX,
F_EMUCONFIG_IDX,
F_DEBUGGERCONFIG_IDX,
F_LOGGERCONFIG_IDX,
F_MAINLOG_IDX,
F_RAMDUMP_IDX,
F_ARAMDUMP_IDX,
F_SYSCONF_IDX,
NUM_PATH_INDICES
};
namespace FileUtil
{
// FileSystem tree node/
struct FSTEntry
{
bool isDirectory;
u64 size; // file length or number of entries from children
std::string physicalName; // name on disk
std::string virtualName; // name in FST names table
std::vector<FSTEntry> children;
};
// Returns true if file filename exists
bool Exists(const std::string &filename);
// Returns true if filename is a directory
bool IsDirectory(const std::string &filename);
// Returns the size of filename (64bit)
u64 GetSize(const std::string &filename);
// Overloaded GetSize, accepts file descriptor
u64 GetSize(const int fd);
// Overloaded GetSize, accepts FILE*
u64 GetSize(FILE *f);
// Returns true if successful, or path already exists.
bool CreateDir(const std::string &filename);
// Creates the full path of fullPath returns true on success
bool CreateFullPath(const std::string &fullPath);
// Deletes a given filename, return true on success
// Doesn't supports deleting a directory
bool Delete(const std::string &filename);
// Deletes a directory filename, returns true on success
bool DeleteDir(const std::string &filename);
// renames file srcFilename to destFilename, returns true on success
bool Rename(const std::string &srcFilename, const std::string &destFilename);
// copies file srcFilename to destFilename, returns true on success
bool Copy(const std::string &srcFilename, const std::string &destFilename);
// creates an empty file filename, returns true on success
bool CreateEmptyFile(const std::string &filename);
/**
* Scans the directory tree, calling the callback for each file/directory found.
* The callback must return the number of files and directories which the provided path contains.
* If the callback's return value is -1, the callback loop is broken immediately.
* If the callback's return value is otherwise negative, the callback loop is broken immediately
* and the callback's return value is returned from this function (to allow for error handling).
* @param directory the parent directory to start scanning from
* @param callback The callback which will be called for each file/directory. It is called
* with the arguments (const std::string& directory, const std::string& virtual_name).
* The `directory `parameter is the path to the directory which contains the file/directory.
* The `virtual_name` parameter is the incomplete file path, without any directory info.
* @return the total number of files/directories found
*/
int ScanDirectoryTreeAndCallback(const std::string &directory, std::function<int(const std::string&, const std::string&)> callback);
/**
* Scans the directory tree, storing the results.
* @param directory the parent directory to start scanning from
* @param parent_entry FSTEntry where the filesystem tree results will be stored.
* @return the total number of files/directories found
*/
int ScanDirectoryTree(const std::string &directory, FSTEntry& parent_entry);
// deletes the given directory and anything under it. Returns true on success.
bool DeleteDirRecursively(const std::string &directory);
// Returns the current directory
std::string GetCurrentDir();
// Create directory and copy contents (does not overwrite existing files)
void CopyDir(const std::string &source_path, const std::string &dest_path);
// Set the current directory to given directory
bool SetCurrentDir(const std::string &directory);
// Returns a pointer to a string with a Citra data dir in the user's home
// directory. To be used in "multi-user" mode (that is, installed).
const std::string& GetUserPath(const unsigned int DirIDX, const std::string &newPath="");
// Returns the path to where the sys file are
std::string GetSysDirectory();
#ifdef __APPLE__
std::string GetBundleDirectory();
#endif
#ifdef _WIN32
std::string &GetExeDirectory();
#endif
size_t WriteStringToFile(bool text_file, const std::string &str, const char *filename);
size_t ReadFileToString(bool text_file, const char *filename, std::string &str);
/**
* Splits the filename into 8.3 format
* Loosely implemented following https://en.wikipedia.org/wiki/8.3_filename
* @param filename The normal filename to use
* @param short_name A 9-char array in which the short name will be written
* @param extension A 4-char array in which the extension will be written
*/
void SplitFilename83(const std::string& filename, std::array<char, 9>& short_name,
std::array<char, 4>& extension);
// simple wrapper for cstdlib file functions to
// hopefully will make error checking easier
// and make forgetting an fclose() harder
class IOFile : public NonCopyable
{
public:
IOFile();
IOFile(std::FILE* file);
IOFile(const std::string& filename, const char openmode[]);
~IOFile();
IOFile(IOFile&& other);
IOFile& operator=(IOFile&& other);
void Swap(IOFile& other);
bool Open(const std::string& filename, const char openmode[]);
bool Close();
template <typename T>
size_t ReadArray(T* data, size_t length)
{
if (!IsOpen()) {
m_good = false;
return -1;
}
size_t items_read = std::fread(data, sizeof(T), length, m_file);
if (items_read != length)
m_good = false;
return items_read;
}
template <typename T>
size_t WriteArray(const T* data, size_t length)
{
static_assert(std::is_standard_layout<T>::value, "Given array does not consist of standard layout objects");
// TODO: gcc 4.8 does not support is_trivially_copyable, but we really should check for it here.
//static_assert(std::is_trivially_copyable<T>::value, "Given array does not consist of trivially copyable objects");
if (!IsOpen()) {
m_good = false;
return -1;
}
size_t items_written = std::fwrite(data, sizeof(T), length, m_file);
if (items_written != length)
m_good = false;
return items_written;
}
size_t ReadBytes(void* data, size_t length)
{
return ReadArray(reinterpret_cast<char*>(data), length);
}
size_t WriteBytes(const void* data, size_t length)
{
return WriteArray(reinterpret_cast<const char*>(data), length);
}
template<typename T>
size_t WriteObject(const T& object) {
static_assert(!std::is_pointer<T>::value, "Given object is a pointer");
return WriteArray(&object, 1);
}
bool IsOpen() { return nullptr != m_file; }
// m_good is set to false when a read, write or other function fails
bool IsGood() { return m_good; }
operator void*() { return m_good ? m_file : nullptr; }
std::FILE* ReleaseHandle();
std::FILE* GetHandle() { return m_file; }
void SetHandle(std::FILE* file);
bool Seek(s64 off, int origin);
u64 Tell();
u64 GetSize();
bool Resize(u64 size);
bool Flush();
// clear error state
void Clear() { m_good = true; std::clearerr(m_file); }
std::FILE* m_file;
bool m_good;
private:
IOFile(IOFile&);
IOFile& operator=(IOFile& other);
};
} // namespace
// To deal with Windows being dumb at unicode:
template <typename T>
void OpenFStream(T& fstream, const std::string& filename, std::ios_base::openmode openmode)
{
#ifdef _MSC_VER
fstream.open(Common::UTF8ToTStr(filename).c_str(), openmode);
#else
fstream.open(filename.c_str(), openmode);
#endif
}
| Java |
<?php
birch_ns( 'birchschedule.upgrader', function( $ns ) {
$ns->init = function() use ( $ns ) {
add_action( 'birchschedule_upgrade_core_after', array( $ns, 'upgrade_core' ) );
};
$ns->get_staff_all_schedule_1_0 = function( $staff ) {
$schedule = $staff['_birs_staff_schedule'];
if ( !isset( $schedule ) ) {
$schedule = array();
} else {
$schedule = unserialize( $schedule );
}
$schedule = $schedule ? $schedule : array();
return $schedule;
};
$ns->upgrade_staff_schedule_from_1_0_to_1_1 = function() use ( $ns ) {
global $birchpress;
$version = $ns->get_staff_schedule_version();
if ( $version != '1.0' ) {
return;
}
$staff = $birchpress->db->query(
array(
'post_type' => 'birs_staff'
),
array(
'meta_keys' => array(
'_birs_staff_schedule'
),
'base_keys' => array()
)
);
foreach ( $staff as $thestaff ) {
$schedules = $ns->get_staff_all_schedule_1_0( $thestaff );
$new_all_schedules = array();
foreach ( $schedules as $location_id => $schedule ) {
if ( isset( $schedule['exceptions'] ) ) {
$exceptions = $schedule['exceptions'];
} else {
$exceptions = array();
}
$new_schedules = array();
foreach ( $schedule as $week_day => $day_schedule ) {
if ( isset( $day_schedule['enabled'] ) ) {
$start = $day_schedule['minutes_start'];
$end = $day_schedule['minutes_end'];
$new_schedule = array(
'minutes_start' => $day_schedule['minutes_start'],
'minutes_end' => $day_schedule['minutes_end'],
'weeks' => array(
$week_day => 'on'
)
);
if ( isset( $new_schedules['s'. $start. $end] ) ) {
$new_schedules['s'. $start. $end]['weeks'][$week_day] = 'on';
} else {
$new_schedules['s'. $start. $end] = $new_schedule;
}
}
}
$new_loc_schedules = array();
foreach ( $new_schedules as $tmp_id => $new_schedule ) {
$uid = uniqid();
$new_loc_schedules[$uid] = $new_schedule;
}
$new_all_schedules[$location_id] = array(
'schedules' => $new_loc_schedules,
'exceptions' => $exceptions
);
update_post_meta( $thestaff['ID'], '_birs_staff_schedule', serialize( $new_all_schedules ) );
}
}
update_option( 'birs_staff_schedule_version', '1.1' );
};
$ns->get_staff_schedule_version = function() {
return get_option( 'birs_staff_schedule_version', '1.0' );
};
$ns->upgrade_appointment_from_1_0_to_1_1 = function() use ( $ns ) {
global $birchpress, $birchschedule;
$version = $ns->get_db_version_appointment();
if ( $version != '1.0' ) {
return;
}
$appointment_fields = array(
'_birs_appointment_price', '_birs_appointment_client',
'_birs_appointment_notes', '_birs_appointment_payment_status',
'_birs_appointment_reminded'
);
$appointment1on1_fields = array(
'_birs_appointment_id',
'_birs_client_id',
'_birs_appointment1on1_payment_status',
'_birs_appointment1on1_reminded',
'_birs_appointment1on1_price',
'_birs_appointment1on1_uid'
);
$appointment1on1_custom_fields = array(
'_birs_appointment_notes'
);
$options = get_option( 'birchschedule_options_form' );
if ( $options != false ) {
$fields_options = $options['fields'];
foreach ( $fields_options as $field_id => $field ) {
if ( $field['belong_to'] == 'appointment' ) {
$meta_key = '_birs_' . $field_id;
if ( !in_array( $meta_key, array( '_birs_appointment_notes' ) ) ) {
$appointment_fields[] = $meta_key;
$appointment1on1_custom_fields[] = $meta_key;
}
}
}
}
$appointments = $birchschedule->model->query(
array(
'post_type' => 'birs_appointment',
'post_status' => array( 'publish', 'pending' )
),
array(
'base_keys' => array(),
'meta_keys' => $appointment_fields
)
);
foreach ( $appointments as $appointment ) {
if ( isset( $appointment['ID'] ) && isset( $appointment['_birs_appointment_client'] ) ) {
$appointment1on1 = array(
'post_type' => 'birs_appointment1on1',
'_birs_appointment_id' => $appointment['ID'],
'_birs_client_id' => $appointment['_birs_appointment_client']
);
if ( isset( $appointment['_birs_appointment_price'] ) ) {
$appointment1on1['_birs_appointment1on1_price'] = $appointment['_birs_appointment_price'];
}
if ( isset( $appointment['_birs_appointment_payment_status'] ) ) {
$appointment1on1['_birs_appointment1on1_payment_status'] =
$appointment['_birs_appointment_payment_status'];
}
if ( isset( $appointment['_birs_appointment_reminded'] ) ) {
$appointment1on1['_birs_appointment1on1_reminded'] = $appointment['_birs_appointment_reminded'];
}
$appointment1on1['_birs_appointment1on1_uid'] = uniqid();
foreach ( $appointment1on1_custom_fields as $appointment1on1_custom_field ) {
if ( isset( $appointment[$appointment1on1_custom_field] ) ) {
$appointment1on1[$appointment1on1_custom_field] =
$appointment[$appointment1on1_custom_field];
}
}
$appointment1on1_meta_keys = array_merge( $appointment1on1_fields, $appointment1on1_custom_fields );
$birchpress->db->save( $appointment1on1, array(
'base_keys' => array(),
'meta_keys' => $appointment1on1_meta_keys
)
);
foreach ( $appointment1on1_custom_fields as $appointment1on1_custom_field ) {
delete_post_meta( $appointment['ID'], $appointment1on1_custom_field );
}
delete_post_meta( $appointment['ID'], '_birs_appointment_client' );
delete_post_meta( $appointment['ID'], '_birs_appointment_notes' );
delete_post_meta( $appointment['ID'], '_birs_appointment_reminded' );
delete_post_meta( $appointment['ID'], '_birs_appointment_price' );
delete_post_meta( $appointment['ID'], '_birs_appointment_payment_status' );
}
}
update_option( 'birs_db_version_appointment', '1.1' );
};
$ns->upgrade_appointment_from_1_1_to_1_2 = function() use ( $ns ) {
global $birchpress, $birchschedule;
$version = $ns->get_db_version_appointment();
if ( $version != '1.1' ) {
return;
}
$appointments = $birchschedule->model->query(
array(
'post_type' => 'birs_appointment',
'post_status' => array( 'any' )
),
array(
'base_keys' => array( 'post_author' ),
'meta_keys' => array( '_birs_appointment_staff' )
)
);
if ( $appointments ) {
foreach ( $appointments as $appointment_id => $appointment ) {
$staff = $birchschedule->model->get( $appointment['_birs_appointment_staff'],
array(
'base_keys' => array(),
'meta_keys' => array( '_birs_staff_email' )
)
);
if ( $staff ) {
$user = WP_User::get_data_by( 'email', $staff['_birs_staff_email'] );
if ( $user ) {
$appointment['post_author'] = $user->ID;
$birchschedule->model->save( $appointment, array(
'base_keys' => array( 'post_author' ),
'meta_keys' => array()
) );
}
}
}
}
update_option( 'birs_db_version_appointment', '1.2' );
};
$ns->get_db_version_appointment = function() {
return get_option( 'birs_db_version_appointment', '1.0' );
};
$ns->upgrade_core = function() use ( $ns ) {
$ns->upgrade_staff_schedule_from_1_0_to_1_1();
$ns->upgrade_appointment_from_1_0_to_1_1();
$ns->upgrade_appointment_from_1_1_to_1_2();
};
} );
| Java |
/* packet-hdmi.c
* Routines for HDMI dissection
* Copyright 2014 Martin Kaiser <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* 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.
*/
/* this dissector handles I2C messages on the HDMI Display Data Channel (DDC)
*
* EDID (Extended Display Identification Data) messages are dissected here,
* HDCP messages are passed on to the HDCP dissector
*/
#include "config.h"
#include <glib.h>
#include <epan/packet.h>
#include <epan/ptvcursor.h>
#include <epan/expert.h>
#include <epan/wmem/wmem.h>
#include "packet-hdmi.h"
void proto_register_hdmi(void);
void proto_reg_handoff_hdmi(void);
static int proto_hdmi = -1;
static dissector_handle_t hdcp_handle;
static gint ett_hdmi = -1;
static gint ett_hdmi_edid = -1;
static int hf_hdmi_addr = -1;
static int hf_hdmi_edid_offset = -1;
static int hf_hdmi_edid_hdr = -1;
static int hf_hdmi_edid_manf_id = -1;
static int hf_hdmi_edid_manf_prod_code = -1;
static int hf_hdmi_edid_manf_serial = -1;
static int hf_hdmi_edid_manf_week = -1;
static int hf_hdmi_edid_mod_year = -1;
static int hf_hdmi_edid_manf_year = -1;
/* also called Source and Sink in the HDMI spec */
#define ADDR_TRX "Transmitter"
#define ADDR_RCV "Receiver"
/* we use 8bit I2C addresses, including the direction bit */
#define ADDR8_HDCP_WRITE 0x74 /* transmitter->receiver */
#define ADDR8_HDCP_READ 0x75 /* r->t */
#define ADDR8_EDID_WRITE 0xA0 /* t->r */
#define ADDR8_EDID_READ 0xA1 /* r->t */
#define HDCP_ADDR8(x) (x==ADDR8_HDCP_WRITE || x==ADDR8_HDCP_READ)
static const value_string hdmi_addr[] = {
{ ADDR8_HDCP_WRITE, "transmitter writes HDCP data for receiver" },
{ ADDR8_HDCP_READ, "transmitter reads HDCP data from receiver" },
{ ADDR8_EDID_WRITE, "EDID request" },
{ ADDR8_EDID_READ, "EDID read" },
{ 0, NULL }
};
#define EDID_HDR_VALUE G_GUINT64_CONSTANT(0x00ffffffffffff00)
/* grab 5 bits, from bit n to n+4, from a big-endian number x
map those bits to a capital letter such that A==1, B==2, ... */
#define CAPITAL_LETTER(x, n) ('A'-1 + (((x) & (0x1F<<n)) >> n))
gboolean
sub_check_hdmi(packet_info *pinfo _U_)
{
/* by looking at the i2c_phdr only, we can't decide if this packet is HDMI
this function is called when the user explicitly selected HDMI
in the preferences
therefore, we always return TRUE and hand the data to the (new
style) dissector who sees the 8bit address and the packet content */
return TRUE;
}
/* dissect EDID data from the receiver
return the offset after the dissected data */
static gint
dissect_hdmi_edid(tvbuff_t *tvb, gint offset, packet_info *pinfo, proto_tree *tree)
{
proto_item *ti, *yi;
proto_tree *edid_tree;
guint64 edid_hdr;
guint16 manf_id;
gchar manf_id_str[4]; /* 3 letters + 0-termination */
guint8 week, year;
int year_hf;
guint8 edid_ver, edid_rev;
ti = proto_tree_add_text(tree, tvb,
offset, tvb_reported_length_remaining(tvb, offset),
"Extended Display Identification Data (EDID)");
edid_tree = proto_item_add_subtree(ti, ett_hdmi_edid);
edid_hdr = tvb_get_ntoh64(tvb, offset);
if (edid_hdr != EDID_HDR_VALUE)
return offset; /* XXX handle fragmented EDID messages */
col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "EDID");
proto_tree_add_item(edid_tree, hf_hdmi_edid_hdr,
tvb, offset, 8, ENC_LITTLE_ENDIAN);
offset += 8;
/* read as big endian for easier splitting */
manf_id = tvb_get_ntohs(tvb, offset);
/* XXX check that MSB is 0 */
manf_id_str[0] = CAPITAL_LETTER(manf_id, 10);
manf_id_str[1] = CAPITAL_LETTER(manf_id, 5);
manf_id_str[2] = CAPITAL_LETTER(manf_id, 0);
manf_id_str[3] = 0;
proto_tree_add_string(edid_tree, hf_hdmi_edid_manf_id,
tvb, offset, 2, manf_id_str);
offset += 2;
proto_tree_add_item(edid_tree, hf_hdmi_edid_manf_prod_code,
tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(edid_tree, hf_hdmi_edid_manf_serial,
tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
week = tvb_get_guint8(tvb, offset);
proto_tree_add_item(edid_tree, hf_hdmi_edid_manf_week,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
year_hf = week==255 ? hf_hdmi_edid_mod_year : hf_hdmi_edid_manf_year;
year = tvb_get_guint8(tvb, offset);
yi = proto_tree_add_item(edid_tree, year_hf,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_item_append_text(yi, " (year %d)", 1990+year);
offset++;
edid_ver = tvb_get_guint8(tvb, offset);
edid_rev = tvb_get_guint8(tvb, offset+1);
/* XXX make this filterable */
proto_tree_add_text(edid_tree, tvb, offset, 2,
"EDID Version %d.%d", edid_ver, edid_rev);
/* XXX dissect the parts following the EDID header */
return tvb_reported_length(tvb);
}
static int
dissect_hdmi(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
{
guint8 addr;
gint offset=0;
proto_item *pi;
proto_tree *hdmi_tree;
/* the I2C address in the first byte is always handled by the HDMI
dissector, even if the packet contains HDCP data */
addr = tvb_get_guint8(tvb, 0);
if (!try_val_to_str(addr, hdmi_addr))
return 0; /* no HDMI packet */
col_set_str(pinfo->cinfo, COL_PROTOCOL, "HDMI");
col_clear(pinfo->cinfo, COL_INFO);
pi = proto_tree_add_protocol_format(tree, proto_hdmi,
tvb, 0, tvb_reported_length(tvb), "HDMI");
hdmi_tree = proto_item_add_subtree(pi, ett_hdmi);
if (addr&0x01) {
SET_ADDRESS(&pinfo->src, AT_STRINGZ, (int)strlen(ADDR_RCV)+1, ADDR_RCV);
SET_ADDRESS(&pinfo->dst, AT_STRINGZ, (int)strlen(ADDR_TRX)+1, ADDR_TRX);
pinfo->p2p_dir = P2P_DIR_RECV;
}
else {
SET_ADDRESS(&pinfo->src, AT_STRINGZ, (int)strlen(ADDR_TRX)+1, ADDR_TRX);
SET_ADDRESS(&pinfo->dst, AT_STRINGZ, (int)strlen(ADDR_RCV)+1, ADDR_RCV);
pinfo->p2p_dir = P2P_DIR_SENT;
}
/* there's no explicit statement in the spec saying that the protocol is
big or little endian
there's three cases: one byte values, symmetrical values or values
that are explicitly marked as little endian
for the sake of simplicity, we use little endian everywhere */
proto_tree_add_item(hdmi_tree, hf_hdmi_addr, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
if (HDCP_ADDR8(addr)) {
gint hdcp_len;
tvbuff_t *hdcp_tvb;
hdcp_len = tvb_reported_length_remaining(tvb, offset);
hdcp_tvb = tvb_new_subset(tvb, offset, hdcp_len, hdcp_len);
return call_dissector(hdcp_handle, hdcp_tvb, pinfo, hdmi_tree);
}
if (addr==ADDR8_EDID_WRITE) {
col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "EDID request");
proto_tree_add_item(hdmi_tree, hf_hdmi_edid_offset,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
return offset;
}
return dissect_hdmi_edid(tvb, offset, pinfo, hdmi_tree);
}
void
proto_register_hdmi(void)
{
static hf_register_info hf[] = {
{ &hf_hdmi_addr,
{ "8bit I2C address", "hdmi.addr", FT_UINT8, BASE_HEX,
VALS(hdmi_addr), 0, NULL, HFILL } },
{ &hf_hdmi_edid_offset,
{ "Offset", "hdmi.edid.offset",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL } },
{ &hf_hdmi_edid_hdr,
{ "EDID header", "hdmi.edid.hdr",
FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } },
{ &hf_hdmi_edid_manf_id,
{ "Manufacturer ID", "hdmi.edid.manf_id",
FT_STRING, STR_ASCII, NULL, 0, NULL, HFILL } },
{ &hf_hdmi_edid_manf_prod_code,
{ "Manufacturer product code", "hdmi.edid.manf_prod_code",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL } },
{ &hf_hdmi_edid_manf_serial,
{ "Serial number", "hdmi.edid.serial_num",
FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } },
{ &hf_hdmi_edid_manf_week,
{ "Week of manufacture", "hdmi.edid.manf_week",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } },
{ &hf_hdmi_edid_mod_year,
{ "Model year", "hdmi.edid.model_year",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } },
{ &hf_hdmi_edid_manf_year,
{ "Year of manufacture", "hdmi.edid.manf_year",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }
};
static gint *ett[] = {
&ett_hdmi,
&ett_hdmi_edid
};
proto_hdmi = proto_register_protocol(
"High-Definition Multimedia Interface", "HDMI", "hdmi");
proto_register_field_array(proto_hdmi, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
new_register_dissector("hdmi", dissect_hdmi, proto_hdmi);
}
void
proto_reg_handoff_hdmi(void)
{
hdcp_handle = find_dissector("hdcp");
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| Java |
/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Silverpine_Forest
SD%Complete: 100
SDComment: Quest support: 435
SDCategory: Silverpine Forest
EndScriptData */
/* ContentData
npc_deathstalker_erland
EndContentData */
#include "ScriptMgr.h"
#include "Player.h"
#include "ScriptedEscortAI.h"
/*######
## npc_deathstalker_erland
######*/
enum eErland
{
SAY_QUESTACCEPT = 0,
SAY_START = 1,
SAY_AGGRO = 2,
SAY_PROGRESS = 3,
SAY_LAST = 4,
SAY_RANE = 0,
SAY_RANE_ANSWER = 5,
SAY_MOVE_QUINN = 6,
SAY_QUINN = 7,
SAY_QUINN_ANSWER = 0,
SAY_BYE = 8,
QUEST_ESCORTING = 435,
NPC_RANE = 1950,
NPC_QUINN = 1951
};
class npc_deathstalker_erland : public CreatureScript
{
public:
npc_deathstalker_erland() : CreatureScript("npc_deathstalker_erland") { }
struct npc_deathstalker_erlandAI : public EscortAI
{
npc_deathstalker_erlandAI(Creature* creature) : EscortAI(creature) { }
void WaypointReached(uint32 waypointId, uint32 /*pathId*/) override
{
Player* player = GetPlayerForEscort();
if (!player)
return;
switch (waypointId)
{
case 1:
Talk(SAY_START, player);
break;
case 10:
Talk(SAY_PROGRESS);
break;
case 13:
Talk(SAY_LAST, player);
player->GroupEventHappens(QUEST_ESCORTING, me);
break;
case 15:
if (Creature* rane = me->FindNearestCreature(NPC_RANE, 20.0f))
rane->AI()->Talk(SAY_RANE);
break;
case 16:
Talk(SAY_RANE_ANSWER);
break;
case 17:
Talk(SAY_MOVE_QUINN);
break;
case 24:
Talk(SAY_QUINN);
break;
case 25:
if (Creature* quinn = me->FindNearestCreature(NPC_QUINN, 20.0f))
quinn->AI()->Talk(SAY_QUINN_ANSWER);
break;
case 26:
Talk(SAY_BYE);
break;
}
}
void Reset() override { }
void EnterCombat(Unit* who) override
{
Talk(SAY_AGGRO, who);
}
void QuestAccept(Player* player, Quest const* quest) override
{
if (quest->GetQuestId() == QUEST_ESCORTING)
{
Talk(SAY_QUESTACCEPT, player);
Start(true, false, player->GetGUID());
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_deathstalker_erlandAI(creature);
}
};
/*######
## AddSC
######*/
void AddSC_silverpine_forest()
{
new npc_deathstalker_erland();
}
| Java |
<?php
if (cfr('CUSTMAP')) {
$altCfg = $ubillingConfig->getAlter();
if ($altCfg['CUSTMAP_ENABLED']) {
$custmaps = new CustomMaps();
// new custom map creation
if (wf_CheckPost(array('newmapname'))) {
if (cfr('CUSTMAPEDIT')) {
$custmaps->mapCreate($_POST['newmapname']);
rcms_redirect('?module=custmaps');
} else {
show_error(__('Permission denied'));
}
}
//custom map deletion
if (wf_CheckGet(array('deletemap'))) {
if (cfr('CUSTMAPEDIT')) {
$custmaps->mapDelete($_GET['deletemap']);
rcms_redirect('?module=custmaps');
} else {
show_error(__('Permission denied'));
}
}
//editing existing custom map name
if (wf_CheckPost(array('editmapid', 'editmapname'))) {
if (cfr('CUSTMAPEDIT')) {
$custmaps->mapEdit($_POST['editmapid'], $_POST['editmapname']);
rcms_redirect('?module=custmaps');
} else {
show_error(__('Permission denied'));
}
}
//creating new map item
if (wf_CheckPost(array('newitemgeo', 'newitemtype'))) {
if (wf_CheckGet(array('showmap'))) {
if (cfr('CUSTMAPEDIT')) {
$custmaps->itemCreate($_GET['showmap'], $_POST['newitemtype'], $_POST['newitemgeo'], $_POST['newitemname'], $_POST['newitemlocation']);
rcms_redirect('?module=custmaps&showmap=' . $_GET['showmap'] . '&mapedit=true');
} else {
show_error(__('Permission denied'));
}
}
}
//deleting map item
if (wf_CheckGet(array('deleteitem'))) {
if (cfr('CUSTMAPEDIT')) {
$deleteResult = $custmaps->itemDelete($_GET['deleteitem']);
rcms_redirect('?module=custmaps&showitems=' . $deleteResult);
} else {
show_error(__('Permission denied'));
}
}
//items upload as KML
if (wf_CheckPost(array('itemsUploadTypes'))) {
$custmaps->catchFileUpload();
}
if (!wf_CheckGet(array('showmap'))) {
if (!wf_CheckGet(array('showitems'))) {
if (!wf_CheckGet(array('edititem'))) {
//render existing custom maps list
show_window(__('Available custom maps'), $custmaps->renderMapList());
zb_BillingStats(true);
} else {
$editItemId = $_GET['edititem'];
//editing item
if (wf_CheckPost(array('edititemid', 'edititemtype'))) {
if (cfr('CUSTMAPEDIT')) {
$custmaps->itemEdit($editItemId, $_POST['edititemtype'], $_POST['edititemgeo'], $_POST['edititemname'], $_POST['edititemlocation']);
rcms_redirect('?module=custmaps&edititem=' . $editItemId);
} else {
show_error(__('Permission denied'));
}
}
//show item edit form
show_window(__('Edit'), $custmaps->itemEditForm($editItemId));
//photostorage link
if ($altCfg['PHOTOSTORAGE_ENABLED']) {
$imageControl = wf_Link('?module=photostorage&scope=CUSTMAPSITEMS&itemid=' . $editItemId . '&mode=list', wf_img('skins/photostorage.png') . ' ' . __('Upload images'), false, 'ubButton');
show_window('', $imageControl);
}
//additional comments
if ($altCfg['ADCOMMENTS_ENABLED']) {
$adcomments = new ADcomments('CUSTMAPITEMS');
show_window(__('Additional comments'), $adcomments->renderComments($editItemId));
}
}
} else {
if (!wf_CheckGet(array('duplicates'))) {
//render items list json data in background
if (wf_CheckGet(array('ajax'))) {
$custmaps->renderItemsListJsonData($_GET['showitems']);
}
//render map items list container
show_window(__('Objects') . ': ' . $custmaps->mapGetName($_GET['showitems']), $custmaps->renderItemsListFast($_GET['showitems']));
} else {
//show duplicate map objects
show_window(__('Show duplicates') . ': ' . $custmaps->mapGetName($_GET['showitems']), $custmaps->renderItemDuplicateList($_GET['showitems']));
}
}
} else {
$mapId = $_GET['showmap'];
$placemarks = '';
//additional centering and zoom
if (wf_CheckGet(array('locateitem', 'zoom'))) {
$custmaps->setCenter($_GET['locateitem']);
$custmaps->setZoom($_GET['zoom']);
$searchRadius = 30;
$placemarks.=$custmaps->mapAddCircle($_GET['locateitem'], $searchRadius, __('Search area radius') . ' ' . $searchRadius . ' ' . __('meters'), __('Search area'));
}
$placemarks.= $custmaps->mapGetPlacemarks($mapId);
//custom map layers processing
if (wf_CheckGet(array('cl'))) {
if (!empty($_GET['cl'])) {
$custLayers = explode('z', $_GET['cl']);
if (!empty($custLayers)) {
foreach ($custLayers as $eachCustLayerId) {
if (!empty($eachCustLayerId)) {
$placemarks.=$custmaps->mapGetPlacemarks($eachCustLayerId);
}
}
}
}
}
if (wf_CheckGet(array('layers'))) {
$layers = $_GET['layers'];
//switches layer
if (ispos($layers, 'sw')) {
$placemarks.=sm_MapDrawSwitches();
}
//switches uplinks layer
if (ispos($layers, 'ul')) {
$placemarks.=sm_MapDrawSwitchUplinks();
}
//builds layer
if (ispos($layers, 'bs')) {
$placemarks.=um_MapDrawBuilds();
}
}
if (wf_CheckGet(array('mapedit', 'showmap'))) {
$editor = $custmaps->mapLocationEditor();
} else {
$editor = '';
}
show_window($custmaps->mapGetName($mapId), $custmaps->mapInit($placemarks, $editor));
}
} else {
show_error(__('This module is disabled'));
}
} else {
show_error(__('Access denied'));
}
?> | Java |
/* lv2_event_helpers.h - Helper functions for the LV2 events extension.
*
* Copyright (C) 2008 Dave Robillard <[email protected]>
*
* This header is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This header 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 header; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA
*/
#ifndef LV2_EVENT_HELPERS_H
#define LV2_EVENT_HELPERS_H
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "lv2_event.h"
/** @file
* This header defines some helper functions for the the LV2 events extension
* with URI <http://lv2plug.in/ns/ext/event> ('lv2ev').
*
* These functions are provided for convenience only, use of them is not
* required for supporting lv2ev (i.e. the events extension is defined by the
* raw buffer format described in lv2_event.h and NOT by this API).
*
* Note that these functions are all static inline which basically means:
* do not take the address of these functions. */
/** Pad a size to 64 bits (for event sizes) */
static inline uint16_t
lv2_event_pad_size(uint16_t size)
{
return (size + 7) & (~7);
}
/** Initialize (empty, reset..) an existing event buffer.
* The contents of buf are ignored entirely and overwritten, except capacity
* which is unmodified. */
static inline void
lv2_event_buffer_reset(LV2_Event_Buffer* buf, uint16_t stamp_type, uint8_t *data)
{
buf->data = data;
buf->header_size = sizeof(LV2_Event_Buffer);
buf->stamp_type = stamp_type;
buf->event_count = 0;
buf->size = 0;
}
/** Allocate a new, empty event buffer. */
static inline LV2_Event_Buffer*
lv2_event_buffer_new(uint32_t capacity, uint16_t stamp_type)
{
LV2_Event_Buffer* buf = (LV2_Event_Buffer*)malloc(sizeof(LV2_Event_Buffer) + capacity);
if (buf != NULL) {
buf->capacity = capacity;
lv2_event_buffer_reset(buf, stamp_type, (uint8_t *)(buf + 1));
return buf;
} else {
return NULL;
}
}
/** An iterator over an LV2_Event_Buffer.
*
* Multiple simultaneous read iterators over a single buffer is fine,
* but changing the buffer invalidates all iterators (e.g. RW Lock). */
typedef struct {
LV2_Event_Buffer* buf;
uint32_t offset;
} LV2_Event_Iterator;
/** Reset an iterator to point to the start of @a buf.
* @return True if @a iter is valid, otherwise false (buffer is empty) */
static inline bool
lv2_event_begin(LV2_Event_Iterator* iter,
LV2_Event_Buffer* buf)
{
iter->buf = buf;
iter->offset = 0;
return (buf->size > 0);
}
/** Check if @a iter is valid..
* @return True if @a iter is valid, otherwise false (past end of buffer) */
static inline bool
lv2_event_is_valid(LV2_Event_Iterator* iter)
{
return (iter->offset < iter->buf->size);
}
/** Advance @a iter forward one event.
* @a iter must be valid.
* @return True if @a iter is valid, otherwise false (reached end of buffer) */
static inline bool
lv2_event_increment(LV2_Event_Iterator* iter)
{
assert(lv2_event_is_valid(iter));
LV2_Event* const ev = (LV2_Event*)(
(uint8_t*)iter->buf->data + iter->offset);
iter->offset += lv2_event_pad_size(sizeof(LV2_Event) + ev->size);
return true;
}
/** Dereference an event iterator (get the event currently pointed at).
* @a iter must be valid.
* @a data if non-NULL, will be set to point to the contents of the event
* returned.
* @return A Pointer to the event @a iter is currently pointing at, or NULL
* if the end of the buffer is reached (in which case @a data is
* also set to NULL). */
static inline LV2_Event*
lv2_event_get(LV2_Event_Iterator* iter,
uint8_t** data)
{
assert(lv2_event_is_valid(iter));
LV2_Event* const ev = (LV2_Event*)(
(uint8_t*)iter->buf->data + iter->offset);
if (data)
*data = (uint8_t*)ev + sizeof(LV2_Event);
return ev;
}
/** Get the type of the non-POD event referenced by an event iterator.
* @a iter must be valid.
* @return The type of the non-POD event, or 0 if the event is not non-POD. */
static inline uint16_t
lv2_event_get_nonpod_type(LV2_Event_Iterator* iter)
{
assert(lv2_event_is_valid(iter));
LV2_Event* const ev = (LV2_Event*)(
(uint8_t*)iter->buf->data + iter->offset);
if (ev->type != 0 || ev->size < 2)
return 0;
return *(uint16_t*)((uint8_t*)ev + sizeof(LV2_Event));
}
/** Write an event at @a iter.
* The event (if any) pointed to by @iter will be overwritten, and @a iter
* incremented to point to the following event (i.e. several calls to this
* function can be done in sequence without twiddling iter in-between).
* @return True if event was written, otherwise false (buffer is full). */
static inline bool
lv2_event_write(LV2_Event_Iterator* iter,
uint32_t frames,
uint32_t subframes,
uint16_t type,
uint16_t size,
const uint8_t* data)
{
if (iter->buf->capacity - iter->buf->size < sizeof(LV2_Event) + size)
return false;
LV2_Event* const ev = (LV2_Event*)(
(uint8_t*)iter->buf->data + iter->offset);
ev->frames = frames;
ev->subframes = subframes;
ev->type = type;
ev->size = size;
memcpy((uint8_t*)ev + sizeof(LV2_Event), data, size);
++iter->buf->event_count;
size = lv2_event_pad_size(sizeof(LV2_Event) + size);
iter->buf->size += size;
iter->offset += size;
return true;
}
/** Reserve space for an event in the buffer and return a pointer to
* the memory where the caller can write the event data, or NULL if there
* is not enough room in the buffer. */
static inline uint8_t*
lv2_event_reserve(LV2_Event_Iterator* iter,
uint32_t frames,
uint32_t subframes,
uint16_t type,
uint16_t size)
{
size = lv2_event_pad_size(size);
if (iter->buf->capacity - iter->buf->size < sizeof(LV2_Event) + size)
return NULL;
LV2_Event* const ev = (LV2_Event*)((uint8_t*)iter->buf->data +
iter->offset);
ev->frames = frames;
ev->subframes = subframes;
ev->type = type;
ev->size = size;
++iter->buf->event_count;
size = lv2_event_pad_size(sizeof(LV2_Event) + size);
iter->buf->size += size;
iter->offset += size;
return (uint8_t*)ev + sizeof(LV2_Event);
}
/** Write an event at @a iter.
* The event (if any) pointed to by @iter will be overwritten, and @a iter
* incremented to point to the following event (i.e. several calls to this
* function can be done in sequence without twiddling iter in-between).
* @return True if event was written, otherwise false (buffer is full). */
static inline bool
lv2_event_write_event(LV2_Event_Iterator* iter,
const LV2_Event* ev,
const uint8_t* data)
{
if (iter->buf->capacity - iter->buf->size < sizeof(LV2_Event) + ev->size)
return false;
LV2_Event* const write_ev = (LV2_Event*)(
(uint8_t*)iter->buf->data + iter->offset);
*write_ev = *ev;
memcpy((uint8_t*)write_ev + sizeof(LV2_Event), data, ev->size);
++iter->buf->event_count;
const uint16_t size = lv2_event_pad_size(sizeof(LV2_Event) + ev->size);
iter->buf->size += size;
iter->offset += size;
return true;
}
#endif // LV2_EVENT_HELPERS_H
| Java |
/*
* xplus4-main.c - Watcom main.c for xplus4 wrapper.
*
* Written by
* Marco van den Heuvel <[email protected]>
*
* This file is part of VICE, the Versatile Commodore Emulator.
* See README for copyright notice.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*
*/
#include "main.c"
| Java |
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores
* CA 94065 USA or visit www.oracle.com if you need additional information or
* have any questions.
*/
package com.codename1.ui;
import com.codename1.ui.animations.CommonTransitions;
import com.codename1.ui.animations.Transition;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.geom.Rectangle;
import com.codename1.impl.VirtualKeyboardInterface;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.plaf.Style;
import com.codename1.ui.plaf.UIManager;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* This class represent the Codename One Light Weight Virtual Keyboard
*
* @author Chen Fishbein
*/
public class VirtualKeyboard extends Dialog implements VirtualKeyboardInterface{
private static final String MARKER_COMMIT_ON_DISPOSE = "$VKB_COM$";
private static final String MARKER_TINT_COLOR = "$VKB_TINT$";
private static final String MARKER_VKB = "$VKB$";
private static Transition transitionIn = CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, true, 500);
private static Transition transitionOut = CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, false, 500);
private int inputType;
/**
* This keymap represents qwerty keyboard
*/
public static final String[][] DEFAULT_QWERTY = new String[][]{
{"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"},
{"a", "s", "d", "f", "g", "h", "j", "k", "l"},
{"$Shift$", "z", "x", "c", "v", "b", "n", "m", "$Delete$"},
{"$Mode$", "$T9$", "$Space$", "$OK$"}
};
/**
* This keymap represents numbers keyboard
*/
public static final String[][] DEFAULT_NUMBERS = new String[][]{
{"1", "2", "3",},
{"4", "5", "6",},
{"7", "8", "9",},
{"*", "0", "#",},
{"$Mode$", "$Space$", "$Delete$", "$OK$"}
};
/**
* This keymap represents numbers and symbols keyboard
*/
public static final String[][] DEFAULT_NUMBERS_SYMBOLS = new String[][]{
{"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"},
{"-", "/", ":", ";", "(", ")", "$", "&", "@"},
{".", ",", "?", "!", "'", "\"", "$Delete$"},
{"$Mode$", "$Space$", "$OK$"}
};
/**
* This keymap represents symbols keyboard
*/
public static final String[][] DEFAULT_SYMBOLS = new String[][]{
{"[", "]", "{", "}", "#", "%", "^", "*", "+", "="},
{"_", "\\", "|", "~", "<", ">", "\u00A3", "\u00A5"},
{":-0", ";-)", ":-)", ":-(", ":P", ":D", "$Delete$"},
{"$Mode$", "$Space$", "$OK$"}
};
/**
* The String that represent the qwerty mode.
*/
public static final String QWERTY_MODE = "ABC";
/**
* The String that represent the numbers mode.
*/
public static final String NUMBERS_MODE = "123";
/**
* The String that represent the numbers sybols mode.
*/
public static final String NUMBERS_SYMBOLS_MODE = ".,123";
/**
* The String that represent the symbols mode.
*/
public static final String SYMBOLS_MODE = ".,?";
private static Hashtable modesMap = new Hashtable();
private static String[] defaultInputModeOrder = {QWERTY_MODE,
NUMBERS_SYMBOLS_MODE, NUMBERS_MODE, SYMBOLS_MODE};
private String currentMode = defaultInputModeOrder[0];
private String[] inputModeOrder = defaultInputModeOrder;
private TextField inputField;
private Container buttons = new Container(new BoxLayout(BoxLayout.Y_AXIS));
private TextPainter txtPainter = new TextPainter();
private boolean upperCase = false;
private Button currentButton;
public static final int INSERT_CHAR = 1;
public static final int DELETE_CHAR = 2;
public static final int CHANGE_MODE = 3;
public static final int SHIFT = 4;
public static final int OK = 5;
public static final int SPACE = 6;
public static final int T9 = 7;
private Hashtable specialButtons = new Hashtable();
private TextArea field;
private boolean finishedT9Edit = true;
private String originalText;
private boolean useSoftKeys = false;
private static boolean showTooltips = true;
private boolean okPressed;
private static Class vkbClass;
private VirtualKeyboard vkb;
public final static String NAME = "CodenameOne_VirtualKeyboard";
private boolean isShowing = false;
private static Hashtable defaultInputModes = null;
/**
* Creates a new instance of VirtualKeyboard
*/
public VirtualKeyboard() {
setLayout(new BorderLayout());
setDialogUIID("Container");
getContentPane().setUIID("VKB");
setAutoDispose(false);
setDisposeWhenPointerOutOfBounds(true);
setTransitionInAnimator(transitionIn);
setTransitionOutAnimator(transitionOut);
getTitleComponent().getParent().removeComponent(getTitleComponent());
if(showTooltips) {
setGlassPane(txtPainter);
}
}
public void setInputType(int inputType) {
if((inputType & TextArea.NUMERIC) == TextArea.NUMERIC ||
(inputType & TextArea.PHONENUMBER) == TextArea.PHONENUMBER) {
setInputModeOrder(new String []{NUMBERS_MODE});
return;
}
if((inputType & TextArea.DECIMAL) == TextArea.DECIMAL) {
setInputModeOrder(new String []{NUMBERS_SYMBOLS_MODE});
return;
}
setInputModeOrder(defaultInputModeOrder);
}
static class InputField extends TextField {
private TextArea field;
InputField(TextArea field) {
this.field = field;
setInputMode(field.getInputMode());
setConstraint(field.getConstraint());
}
public boolean hasFocus() {
return true;
}
public String getUIID() {
return "VKBTextInput";
}
public void deleteChar() {
super.deleteChar();
field.setText(getText());
if (field instanceof TextField) {
((TextField) field).setCursorPosition(getCursorPosition());
}
}
public void setCursorPosition(int i) {
super.setCursorPosition(i);
// this can happen since this method is invoked from a constructor of the base class...
if(field != null && field.getText().length() > i && field instanceof TextField) {
((TextField) field).setCursorPosition(i);
}
}
public void setText(String t) {
super.setText(t);
// this can happen since this method is invoked from a constructor of the base class...
if(field != null) {
// mirror events into the parent
field.setText(t);
}
}
public boolean validChar(String c) {
if (field instanceof TextField) {
return ((TextField) field).validChar(c);
}
return true;
}
}
/**
* Invoked internally by the implementation to indicate the text field that will be
* edited by the virtual keyboard
*
* @param field the text field instance
*/
public void setTextField(final TextArea field) {
this.field = field;
removeAll();
okPressed = false;
if(field instanceof TextField){
useSoftKeys = ((TextField)field).isUseSoftkeys();
((TextField)field).setUseSoftkeys(false);
}
originalText = field.getText();
inputField = new InputField(field);
inputField.setText(originalText);
inputField.setCursorPosition(field.getCursorPosition());
inputField.setConstraint(field.getConstraint());
inputField.setInputModeOrder(new String[]{"ABC"});
inputField.setMaxSize(field.getMaxSize());
initModes();
setInputType(field.getConstraint());
initSpecialButtons();
addComponent(BorderLayout.NORTH, inputField);
buttons.getStyle().setPadding(0, 0, 0, 0);
addComponent(BorderLayout.CENTER, buttons);
initInputButtons(upperCase);
inputField.setUseSoftkeys(false);
applyRTL(false);
}
/**
* @inheritDoc
*/
public void show() {
super.showPacked(BorderLayout.SOUTH, true);
}
/**
* @inheritDoc
*/
protected void autoAdjust(int w, int h) {
//if the t9 input is currently editing do not dispose dialog
if (finishedT9Edit) {
setTransitionOutAnimator(CommonTransitions.createEmpty());
dispose();
}
}
/**
* init all virtual keyboard modes, such as QWERTY_MODE, NUMBERS_SYMBOLS_MODE...
* to add an addtitional mode a developer needs to override this method and
* add a mode by calling addInputMode method
*/
protected void initModes() {
addInputMode(QWERTY_MODE, DEFAULT_QWERTY);
addInputMode(NUMBERS_SYMBOLS_MODE, DEFAULT_NUMBERS_SYMBOLS);
addInputMode(SYMBOLS_MODE, DEFAULT_SYMBOLS);
addInputMode(NUMBERS_MODE, DEFAULT_NUMBERS);
if(defaultInputModes != null) {
Enumeration e = defaultInputModes.keys();
while(e.hasMoreElements()) {
String key = (String)e.nextElement();
addInputMode(key, (String[][])defaultInputModes.get(key));
}
}
}
/**
* Sets the current virtual keyboard mode.
*
* @param mode the String that represents the mode(QWERTY_MODE,
* SYMBOLS_MODE, ...)
*/
protected void setCurrentMode(String mode) {
this.currentMode = mode;
}
/**
* Gets the current mode.
*
* @return the String that represents the current mode(QWERTY_MODE,
* SYMBOLS_MODE, ...)
*/
protected String getCurrentMode() {
return currentMode;
}
private void initInputButtons(boolean upperCase) {
buttons.removeAll();
int largestLine = 0;
String[][] currentKeyboardChars = (String[][]) modesMap.get(currentMode);
for (int i = 1; i < currentKeyboardChars.length; i++) {
if (currentKeyboardChars[i].length > currentKeyboardChars[largestLine].length) {
largestLine = i;
}
}
int length = currentKeyboardChars[largestLine].length;
if(length == 0) {
return;
}
Button dummy = createButton(new Command("dummy"), 0);
int buttonMargins = dummy.getUnselectedStyle().getMargin(dummy.isRTL(), LEFT) +
dummy.getUnselectedStyle().getMargin(dummy.isRTL(), RIGHT);
Container row = null;
int rowW = (Display.getInstance().getDisplayWidth() -
getDialogStyle().getPadding(false, LEFT) -
getDialogStyle().getPadding(false, RIGHT) -
getDialogStyle().getMargin(false, LEFT) -
getDialogStyle().getMargin(false, RIGHT));
int availableSpace = rowW - length * buttonMargins;
int buttonSpace = (availableSpace) / length;
for (int i = 0; i < currentKeyboardChars.length; i++) {
int rowWidth = rowW;
row = new Container(new BoxLayout(BoxLayout.X_AXIS));
row.getUnselectedStyle().setMargin(0, 0, 0, 0);
Vector specialsButtons = new Vector();
for (int j = 0; j < currentKeyboardChars[i].length; j++) {
String txt = currentKeyboardChars[i][j];
Button b = null;
if (txt.startsWith("$") && txt.endsWith("$") && txt.length() > 1) {
//add a special button
Button cmd = (Button) specialButtons.get(txt.substring(1, txt.length() - 1));
Command c = null;
int prefW = 0;
if(cmd != null){
c = cmd.getCommand();
int space = ((Integer) cmd.getClientProperty("space")).intValue();
if (space != -1) {
prefW = availableSpace * space / 100;
}
}
b = createButton(c, prefW, "VKBSpecialButton");
if (prefW != 0) {
rowWidth -= (b.getPreferredW() + buttonMargins);
} else {
//if we can't determind the size at this stage, wait until
//the loops ends and give the remains size to the special
//button
specialsButtons.addElement(b);
}
} else {
if (upperCase) {
txt = txt.toUpperCase();
}
b = createInputButton(txt, buttonSpace);
rowWidth -= (b.getPreferredW() + buttonMargins);
}
if (currentButton != null) {
if (currentButton.getCommand() != null &&
b.getCommand() != null &&
currentButton.getCommand().getId() == b.getCommand().getId()) {
currentButton = b;
}
if (currentButton.getText().equals(b.getText())) {
currentButton = b;
}
}
row.addComponent(b);
}
int emptySpace = Math.max(rowWidth, 0);
//if we have special buttons on the keyboard give them the size or
//else give the remain size to the row margins
if (specialsButtons.size() > 0) {
int prefW = emptySpace / specialsButtons.size();
for (int j = 0; j < specialsButtons.size(); j++) {
Button special = (Button) specialsButtons.elementAt(j);
special.setPreferredW(prefW);
}
} else {
row.getUnselectedStyle().setPadding(Component.LEFT, 0);
row.getUnselectedStyle().setPadding(Component.RIGHT, 0);
row.getUnselectedStyle().setMarginUnit(new byte[]{Style.UNIT_TYPE_PIXELS,
Style.UNIT_TYPE_PIXELS,
Style.UNIT_TYPE_PIXELS,
Style.UNIT_TYPE_PIXELS});
row.getUnselectedStyle().setMargin(Component.LEFT, emptySpace / 2);
row.getUnselectedStyle().setMargin(Component.RIGHT, emptySpace / 2);
}
buttons.addComponent(row);
}
applyRTL(false);
}
private Button createInputButton(String text, int prefSize) {
Button b = createButton(new Command(text, INSERT_CHAR), prefSize);
b.putClientProperty("glasspane", "true");
return b;
}
private Button createButton(Command cmd, int prefSize) {
return createButton(cmd, prefSize, "VKBButton");
}
private Button createButton(Command cmd, int prefSize, String uiid) {
Button btn;
if(cmd != null){
btn = new Button(cmd);
}else{
btn = new Button();
btn.setVisible(false);
}
final Button b = btn;
b.setUIID(uiid);
b.setEndsWith3Points(false);
b.setAlignment(Component.CENTER);
prefSize = Math.max(prefSize, b.getPreferredW());
b.setPreferredW(prefSize);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
currentButton = b;
}
});
return b;
}
/**
* Add an input mode to the virtual keyboard
*
* @param mode a string that represents the identifier of the mode
* @param inputChars 2 dimensional String array that contains buttons String
* and special buttons (a special button is identified with $...$ marks
* e.g: "$Space$")
*/
public static void addDefaultInputMode(String mode, String[][] inputChars) {
if(defaultInputModes == null) {
defaultInputModes = new Hashtable();
}
defaultInputModes.put(mode, inputChars);
}
/**
* Add an input mode to the virtual keyboard
*
* @param mode a string that represents the identifier of the mode
* @param inputChars 2 dimentional String array that contains buttons String
* and special buttons (a special button is identified with $...$ marks
* e.g: "$Space$")
*/
public void addInputMode(String mode, String[][] inputChars) {
modesMap.put(mode, inputChars);
}
/**
* This method adds a special button to the virtual keyboard
*
* @param key the string identifier from within the relevant input mode
* @param cmd the Command to invoke when this button is invoked.
*/
public void addSpecialButton(String key, Command cmd) {
addSpecialButton(key, cmd, -1);
}
/**
* This method adds a special button to the virtual keyboard
*
* @param key the string identifier from within the relevant input mode
* @param cmd the Command to invoke when this button is invoked.
* @param space how much space in percentage from the overall row
* the special button should occupy
*/
public void addSpecialButton(String key, Command cmd, int space) {
Button b = new Button(cmd);
b.putClientProperty("space", new Integer(space));
specialButtons.put(key, b);
}
private String getNextMode(String current) {
for (int i = 0; i < inputModeOrder.length - 1; i++) {
String mode = inputModeOrder[i];
if(mode.equals(current)){
return inputModeOrder[i + 1];
}
}
return inputModeOrder[0];
}
/**
* @inheritDoc
*/
public void pointerPressed(int x, int y) {
super.pointerPressed(x, y);
Component cmp = getComponentAt(x, y);
if (showTooltips && cmp != null && cmp instanceof Button && cmp.getClientProperty("glasspane") != null) {
txtPainter.showButtonOnGlasspane((Button) cmp);
}
}
/**
* @inheritDoc
*/
public void pointerDragged(int x, int y) {
super.pointerDragged(x, y);
Component cmp = getComponentAt(x, y);
if (showTooltips && cmp != null && cmp instanceof Button && cmp.getClientProperty("glasspane") != null) {
txtPainter.showButtonOnGlasspane((Button) cmp);
}
}
/**
* @inheritDoc
*/
public void pointerReleased(int x, int y) {
if(showTooltips) {
txtPainter.clear();
}
super.pointerReleased(x, y);
}
/**
* This method initialize all the virtual keyboard special buttons.
*/
protected void initSpecialButtons() {
//specialButtons.clear();
addSpecialButton("Shift", new Command("SH", SHIFT), 15);
addSpecialButton("Delete", new Command("Del", DELETE_CHAR), 15);
addSpecialButton("T9", new Command("T9", T9), 15);
addSpecialButton("Mode", new Command(getNextMode(currentMode), CHANGE_MODE));
addSpecialButton("Space", new Command("Space", SPACE), 50);
addSpecialButton("OK", new Command("Ok", OK));
}
/**
* Returns the order in which input modes are toggled
*
* @return the order of the input modes
*/
public String[] getInputModeOrder() {
return inputModeOrder;
}
/**
* Sets the order in which input modes are toggled and allows disabling/hiding
* an input mode
*
* @param order the order for the input modes in this field
*/
public void setInputModeOrder(String[] order) {
inputModeOrder = order;
setCurrentMode(order[0]);
}
/**
* Returns the order in which input modes are toggled by default
*
* @return the default order of the input mode
*/
public static String[] getDefaultInputModeOrder() {
return defaultInputModeOrder;
}
/**
* Sets the order in which input modes are toggled by default and allows
* disabling/hiding an input mode
*
* @param order the order for the input modes in all future created fields
*/
public static void setDefaultInputModeOrder(String[] order) {
defaultInputModeOrder = order;
}
class TextPainter implements Painter {
private Label label = new Label();
private boolean paint = true;
public TextPainter() {
label = new Label();
label.setUIID("VKBtooltip");
}
public void showButtonOnGlasspane(Button button) {
if(label.getText().equals(button.getText())){
return;
}
paint = true;
repaint(label.getAbsoluteX()-2,
label.getAbsoluteY()-2,
label.getWidth()+4,
label.getHeight()+4);
label.setText(button.getText());
label.setSize(label.getPreferredSize());
label.setX(button.getAbsoluteX() + (button.getWidth() - label.getWidth()) / 2);
label.setY(button.getAbsoluteY() - label.getPreferredH() * 4 / 3);
repaint(label.getAbsoluteX()-2,
label.getAbsoluteY()-2,
label.getPreferredW()+4,
label.getPreferredH()+4);
}
public void paint(Graphics g, Rectangle rect) {
if (paint) {
label.paintComponent(g);
}
}
private void clear() {
paint = false;
repaint();
}
}
private void updateText(String txt) {
field.setText(txt);
if(field instanceof TextField){
((TextField)field).setCursorPosition(txt.length());
}
if(okPressed){
field.fireActionEvent();
if(field instanceof TextField){
((TextField)field).fireDoneEvent();
}
}
}
/**
* @inheritDoc
*/
protected void actionCommand(Command cmd) {
super.actionCommand(cmd);
switch (cmd.getId()) {
case OK:
okPressed = true;
updateText(inputField.getText());
dispose();
break;
case INSERT_CHAR:
Button btn = currentButton;
String text = btn.getText();
if (inputField.getText().length() == 0) {
inputField.setText(text);
inputField.setCursorPosition(text.length());
} else {
inputField.insertChars(text);
}
break;
case SPACE:
if (inputField.getText().length() == 0) {
inputField.setText(" ");
} else {
inputField.insertChars(" ");
}
break;
case DELETE_CHAR:
inputField.deleteChar();
break;
case CHANGE_MODE:
currentMode = getNextMode(currentMode);
Display.getInstance().callSerially(new Runnable() {
public void run() {
initInputButtons(upperCase);
String next = getNextMode(currentMode);
currentButton.setText(next);
currentButton.getCommand().setCommandName(next);
setTransitionOutAnimator(CommonTransitions.createEmpty());
setTransitionInAnimator(CommonTransitions.createEmpty());
revalidate();
show();
}
});
return;
case SHIFT:
if (currentMode.equals(QWERTY_MODE)) {
upperCase = !upperCase;
Display.getInstance().callSerially(new Runnable() {
public void run() {
initInputButtons(upperCase);
revalidate();
}
});
}
return;
case T9:
finishedT9Edit = false;
if(field != null){
Display.getInstance().editString(field, field.getMaxSize(), field.getConstraint(), field.getText());
}else{
Display.getInstance().editString(inputField, inputField.getMaxSize(), inputField.getConstraint(), inputField.getText());
}
dispose();
finishedT9Edit = true;
}
}
/**
* @inheritDoc
*/
public void dispose() {
if (field != null) {
if (!okPressed && !isCommitOnDispose(field) && finishedT9Edit) {
field.setText(originalText);
}
if(field instanceof TextField){
((TextField)field).setUseSoftkeys(useSoftKeys);
}
setTransitionInAnimator(transitionIn);
field = null;
}
currentMode = inputModeOrder[0];
super.dispose();
}
/**
* @inheritDoc
*/
protected void onShow() {
super.onShow();
setTransitionOutAnimator(transitionOut);
}
/**
* This method returns the Virtual Keyboard TextField.
*
* @return the the Virtual Keyboard TextField.
*/
protected TextField getInputField() {
return inputField;
}
/**
* Indicates whether the VKB should commit changes to the text field when the VKB
* is closed not via the OK button. This might be useful for some situations such
* as searches
*
* @param tf the text field to mark as commit on dispose
* @param b the value of commit on dispose, true to always commit changes
*/
public static void setCommitOnDispose(TextField tf, boolean b) {
tf.putClientProperty(MARKER_COMMIT_ON_DISPOSE, new Boolean(b));
}
/**
* This method is used to bind a specific instance of a virtual keyboard to a specific TextField.
* For example if a specific TextField requires only numeric input consider using this method as follows:
*
* TextField tf = new TextField();
* tf.setConstraint(TextField.NUMERIC);
* tf.setInputModeOrder(new String[]{"123"});
* VirtualKeyboard vkb = new VirtualKeyboard();
* vkb.setInputModeOrder(new String[]{VirtualKeyboard.NUMBERS_MODE});
* VirtualKeyboard.bindVirtualKeyboard(tf, vkb);
*
* @param t the TextField to bind a VirualKeyboard to.
* @param vkb the binded VirualKeyboard.
*/
public static void bindVirtualKeyboard(TextArea t, VirtualKeyboard vkb) {
t.putClientProperty(MARKER_VKB, vkb);
}
/**
* This method returns the Textfield associated VirtualKeyboard,
* see bindVirtualKeyboard(TextField tf, VirtualKeyboard vkb) method.
*
* @param t a TextField.that might have an associated VirtualKeyboard instance
* @return a VirtualKeyboard instance or null if not exists.
*/
public static VirtualKeyboard getVirtualKeyboard(TextArea t) {
return (VirtualKeyboard) t.getClientProperty(MARKER_VKB);
}
/**
* Indicates whether the given text field should commit on dispose
*
* @param tf the text field
* @return true if the text field should save the data despite the fact that it
* was disposed in an irregular way
*/
public static boolean isCommitOnDispose(TextArea tf) {
Boolean b = (Boolean)tf.getClientProperty(MARKER_COMMIT_ON_DISPOSE);
return (b != null) && b.booleanValue();
}
/**
* Sets the tint color for the virtual keyboard when shown on top of this text field
* see the form tint methods for more information
*
* @param tf the relevant text field
* @param tint the tint color with an alpha channel
*/
public static void setVKBTint(TextField tf, int tint) {
tf.putClientProperty(MARKER_TINT_COLOR, new Integer(tint));
}
/**
* The tint color for the virtual keyboard when shown on top of this text field
* see the form tint methods for more information
*
* @param tf the relevant text field
* @return the tint color with an alpha channel
*/
public static int getVKBTint(TextArea tf) {
Integer v = (Integer)tf.getClientProperty(MARKER_TINT_COLOR);
if(v != null) {
return v.intValue();
}
Form current = Display.getInstance().getCurrent();
return current.getUIManager().getLookAndFeel().getDefaultFormTintColor();
}
/**
* Indicates whether tooltips should be shown when the keys in the VKB are pressed
*
* @return the showTooltips
*/
public static boolean isShowTooltips() {
return showTooltips;
}
/**
* Indicates whether tooltips should be shown when the keys in the VKB are pressed
*
* @param aShowTooltips true to show tooltips
*/
public static void setShowTooltips(boolean aShowTooltips) {
showTooltips = aShowTooltips;
}
/**
* The transition in for the VKB
*
* @return the transitionIn
*/
public static Transition getTransitionIn() {
return transitionIn;
}
/**
* The transition in for the VKB
*
* @param aTransitionIn the transitionIn to set
*/
public static void setTransitionIn(Transition aTransitionIn) {
transitionIn = aTransitionIn;
}
/**
* The transition out for the VKB
*
* @return the transitionOut
*/
public static Transition getTransitionOut() {
return transitionOut;
}
/**
* The transition out for the VKB
*
* @param aTransitionOut the transitionOut to set
*/
public static void setTransitionOut(Transition aTransitionOut) {
transitionOut = aTransitionOut;
}
/**
* Shows the virtual keyboard that is assoiciated with the displayed TextField
* or displays the default virtual keyboard.
*
* @param show it show is true open the relevant keyboard, if close dispose
* the displayed keyboard
*/
public void showKeyboard(boolean show) {
isShowing = show;
Form current = Display.getInstance().getCurrent();
if (show) {
Component foc = current.getFocused();
if(foc instanceof Container) {
foc = ((Container)foc).getLeadComponent();
}
TextArea txtCmp = (TextArea) foc;
if (txtCmp != null) {
if(vkb != null && vkb.contains(txtCmp)){
return;
}
vkb = VirtualKeyboard.getVirtualKeyboard(txtCmp);
if(vkb == null){
vkb = createVirtualKeyboard();
}
vkb.setTextField(txtCmp);
int oldTint = current.getTintColor();
current.setTintColor(VirtualKeyboard.getVKBTint(txtCmp));
boolean third = com.codename1.ui.Display.getInstance().isThirdSoftButton();
com.codename1.ui.Display.getInstance().setThirdSoftButton(false);
boolean qwerty = txtCmp.isQwertyInput();
if(txtCmp instanceof TextField){
((TextField) txtCmp).setQwertyInput(true);
}
vkb.showDialog();
if (txtCmp instanceof TextField) {
((TextField) txtCmp).setQwertyInput(qwerty);
}
com.codename1.ui.Display.getInstance().setThirdSoftButton(third);
current.setTintColor(oldTint);
}
}
}
/**
* Sets the default virtual keyboard class for the com.codename1.ui.VirtualKeyboard
* type
* This class is used as the default virtual keyboard class if the current
* platform VirtualKeyboard is com.codename1.ui.VirtualKeyboard.
* Platform VirtualKeyboard is defined here:
* Display.getIntance().setDefaultVirtualKeyboard(VirtualKeyboardInterface vkb)
*
* @param vkbClazz this class must extend VirtualKeyboard.
*/
public static void setDefaultVirtualKeyboardClass(Class vkbClazz){
vkbClass = vkbClazz;
}
private VirtualKeyboard createVirtualKeyboard() {
try {
if(vkbClass != null){
return (VirtualKeyboard) vkbClass.newInstance();
}else{
return new VirtualKeyboard();
}
} catch (Exception ex) {
ex.printStackTrace();
return new VirtualKeyboard();
}
}
/**
* @see VirtualKeyboardInterface
*/
public String getVirtualKeyboardName() {
return NAME;
}
/**
* @see VirtualKeyboardInterface
*/
public boolean isVirtualKeyboardShowing() {
return isShowing;
}
}
| Java |
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../../common/docs.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale = 1.0" />
<link href="/assets/favicon.ico" rel="shortcut icon" />
<title>Webix : Samples</title></title>
</head>
<body>
<div class='abstop_header'>
<div class='content_area'>
</div>
</div>
<div class="page_header">
<div class='page_inner_header'>
<a href='http://webix.com'><div class='top_webix_logo'></div></a>
Samples
</div>
</div>
<div class="page_space">
<div class="webixdoc_page webixdoc_start">
<div id="webixContent" class='webixdoc_content'>
<div class="webixdoc_content_inner">
<div class="webixdoc_breadcrumb nav_breadcrumb">
<a href="http://docs.webix.com/" class="webixdoc_back">Documentation</a>
<a href="../../index.html" class="webixdoc_back">Samples</a>
<a href='../index.html' class='webixdoc_back'>17 Datatree</a><a href='../../index.html' class='webixdoc_back'>04 Api</a>
</div>
<table class='nav_table'>
<tr>
<td style='width:30px;'>
<a href='01_selection.html'><div class='nav_folder_img'> </div></a>
</td><td> <a href='01_selection.html'>Selection</a> </td>
</tr>
<tr>
<td style='width:30px;'>
<a href='02_sort.html'><div class='nav_folder_img'> </div></a>
</td><td> <a href='02_sort.html'>Sorting</a> </td>
</tr>
<tr>
<td style='width:30px;'>
<a href='03_filter.html'><div class='nav_folder_img'> </div></a>
</td><td> <a href='03_filter.html'>Filtering</a> </td>
</tr>
<tr>
<td style='width:30px;'>
<a href='04_multi_select.html'><div class='nav_folder_img'> </div></a>
</td><td> <a href='04_multi_select.html'>Multiline Selection</a> </td>
</tr>
<tr>
<td style='width:30px;'>
<a href='05_sort_custom.html'><div class='nav_folder_img'> </div></a>
</td><td> <a href='05_sort_custom.html'>Custom Sorting</a> </td>
</tr>
<tr>
<td style='width:30px;'>
<a href='06_add_delete.html'><div class='nav_folder_img'> </div></a>
</td><td> <a href='06_add_delete.html'>Adding and deleting Nodes</a> </td>
</tr>
<tr>
<td style='width:30px;'>
<a href='07_sync.html'><div class='nav_folder_img'> </div></a>
</td><td> <a href='07_sync.html'>Data sync</a> </td>
</tr>
<tr>
<td style='width:30px;'>
<a href='08_bind.html'><div class='nav_folder_img'> </div></a>
</td><td> <a href='08_bind.html'>Data binding</a> </td>
</tr>
<tr>
<td style='width:30px;'>
<a href='09_subdata.html'><div class='nav_folder_img'> </div></a>
</td><td> <a href='09_subdata.html'>Data binding - subdata</a> </td>
</tr>
</table>
</div>
</div>
</div>
</div>
</body>
</html> | Java |
<?php
/**
* File containing the eZProductCollectionTest class
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
* @version 2014.07.0
* @package tests
*/
class eZProductCollectionTest extends ezpDatabaseTestCase
{
protected $backupGlobals = false;
/**
* Unit test for eZProductCollection::cleanupList()
*
* Outline:
* 1) Create 10 eZProductCollection objects
* 2) Pick 5 random ID of created items
* 3) Call cleanupList() on these 5 items
* 4) Check that the 5 items have been removed
* 5) Check that the 5 other items haven't been removed
*/
public function testCleanupList()
{
// Create a few collections
$row = array( 'created' => time(), 'currency_code' => 'EUR' );
$collection = new eZProductCollection( $row );
$collection->store();
$collectionIDArray[] = $collection->attribute( 'id' );
for( $i = 0; $i < 1500; $i++ )
{
$newCollection = $collection->copy();
$collectionIDArray[] = $newCollection->attribute( 'id' );
}
// pick a few random ID to delete
$deleteIDArray = array_rand( $collectionIDArray, round( count( $collectionIDArray ) / 2 ) );
$remainingIDArray = array_diff( $collectionIDArray, $deleteIDArray );
eZProductCollection::cleanupList( $deleteIDArray );
// Check that each item of deleteIDArray has been removed
foreach( $deleteIDArray as $id )
{
$this->assertNull( eZProductCollection::fetch( $id ) );
}
// And check that each item of remainingIDArray hasn't been deleted
foreach( $remainingIDArray as $id )
{
$this->assertInstanceOf( 'eZProductCollection', eZProductCollection::fetch( $id ) );
}
}
}
?>
| Java |
/*
* Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.lir.asm;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import org.graalvm.compiler.core.common.type.DataPointerConstant;
/**
* Class for chunks of data that go into the data section.
*/
public class ArrayDataPointerConstant extends DataPointerConstant {
private final byte[] data;
public ArrayDataPointerConstant(byte[] array, int alignment) {
super(alignment);
data = array.clone();
}
public ArrayDataPointerConstant(short[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 2);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asShortBuffer().put(array);
data = byteBuffer.array();
}
public ArrayDataPointerConstant(int[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asIntBuffer().put(array);
data = byteBuffer.array();
}
public ArrayDataPointerConstant(float[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asFloatBuffer().put(array);
data = byteBuffer.array();
}
public ArrayDataPointerConstant(double[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 8);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asDoubleBuffer().put(array);
data = byteBuffer.array();
}
public ArrayDataPointerConstant(long[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 8);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asLongBuffer().put(array);
data = byteBuffer.array();
}
@Override
public boolean isDefaultForKind() {
return false;
}
@Override
public void serialize(ByteBuffer buffer) {
buffer.put(data);
}
@Override
public int getSerializedSize() {
return data.length;
}
@Override
public String toValueString() {
return "ArrayDataPointerConstant" + Arrays.toString(data);
}
}
| Java |
<style type="text/css">
<!--
.msg {
text-align:left;
color: blue;
display: block;
padding: 5px 0;
}
.emsg {
text-align:left;
color: red;
display: block;
padding: 5px 0;
}
#loader{
visibility:hidden;
}
#f1_error{
font-family: Geneva, Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight:bold;
color:#FF0000;
}
#f1_ok{
font-family: Geneva, Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight:bold;
color:#00FF00;
}
#f1_upload_process {
z-index:100;
visibility:hidden;
position:absolute;
margin: 10px 0 0;
width:220px;
}
#f1_upload_process span { display: block; padding-left: 7px; }
-->
</style>
<script language="javascript" type="text/javascript">
<!--
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
document.getElementById('f1_upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success, msg, src){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span>';
var ed = tinyMCE.get('jform_content'); // get editor instance
var newNode = ed.getDoc().createElement ( "img" ); // create img node
newNode.src = src; // add src attribute
ed.execCommand('mceInsertContent', false, newNode.outerHTML);
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span>';
}
result += '<input type="hidden" name="path_2_upload" value="<?php echo base64_encode(JPATH_ROOT . DS . 'tmp' . DS . session_id() . DS); ?>" />';
result += '<input type="hidden" name="link_2_upload" value="<?php echo base64_encode(JURI::root() . 'tmp/' . session_id() .'/'); ?>" />';
document.getElementById('f1_upload_process').style.visibility = 'hidden';
document.getElementById('f1_upload_form').innerHTML = result + '<input name="myfile" type="file" size="30" style="float:left;" /><input type="button" name="submitBtn" id="submitBtn" class="sbtn" value="Upload" style="float: left;" />';
document.getElementById('f1_upload_form').style.visibility = 'visible';
return true;
}
window.addEvent('domready', function(){
// $$('#submitBtn').addEvent('click', function(e){
document.body.addEvent('click:relay(#submitBtn)', function(e){
var action = '<?php echo JURI::base(); ?>jelibs/ajaxupload/upload.php';
var formAction = $$('form[name="userForm"]').get('action');
$$('form[name="userForm"]').set('target', 'upload_target').set('action', action);
startUpload();
document.userForm.submit();
$$('form[name="userForm"]').set('target', '').set('action', formAction);
});
});
//-->
</script>
<?php
/**
* @version $Id: images2content.php 21097 2011-04-07 15:38:03Z dextercowley $
* @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('JPATH_BASE') or die;
jimport('joomla.html.html');
jimport('joomla.form.formfield');
jimport('joomla.form.helper');
JFormHelper::loadFieldClass('list');
/**
* Bannerclient Field class for the Joomla Framework.
*
* @package Joomla.Administrator
* @subpackage com_banners
* @since 1.6
*/
class JFormFieldFront_Images2Content extends JFormFieldList
{
/**
* The form field type.
*
* @var string
* @since 1.6
*/
protected $type = 'Front_Images2Content';
public function getInput()
{
$html = '<div>';
$html .= '<p id="f1_upload_process"><span>Loading...</span><img src="'.JURI::base().'jelibs/ajaxupload/loader.gif" /><br/></p>
<p id="f1_upload_form" align="center">
<br />
<span style="float: left;">Upload images to content</span>
<br/>
<input name="myfile" type="file" size="30" style="float: left;" />
<input type="hidden" name="path_2_upload" value="'.base64_encode(JPATH_ROOT . DS . 'tmp' . DS . session_id() . DS) .'" />
<input type="hidden" name="link_2_upload" value="'.base64_encode(JURI::root() . 'tmp/' . session_id() . '/') .'" />
<input type="button" name="submitBtn" id="submitBtn" class="sbtn" value="Upload" style="float: left;" />
</p>
<iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
';
$html .= '<div class="clr"></div></div>';
return $html;
}
}
| Java |
/*****************************************************************************/
/* */
/* Ittiam WPS SOFTWARE */
/* */
/* ITTIAM SYSTEMS PVT LTD, BANGALORE */
/* COPYRIGHT(C) 2011 */
/* */
/* This program is proprietary to Ittiam Systems Private Limited and */
/* is protected under Indian Copyright Law as an unpublished work. Its use */
/* and disclosure is limited by the terms and conditions of a license */
/* agreement. It may not be copied or otherwise reproduced or disclosed to */
/* persons outside the licensee's organization except in accordance with the*/
/* terms and conditions of such an agreement. All copies and */
/* reproductions shall be the property of Ittiam Systems Private Limited and*/
/* must bear this notice in its entirety. */
/* */
/*****************************************************************************/
/*****************************************************************************/
/* */
/* File Name : wps_key.c */
/* */
/* Description : This file contains the functions to generate the */
/* Authentication and Key Wrap Key */
/* */
/* List of Functions : wps_kdf */
/* wps_gen_keys */
/* */
/* Issues / Problems : None */
/* */
/* Revision History : */
/* */
/* DD MM YYYY Author(s) Changes */
/* 25 02 2011 Ittiam Draft */
/* */
/*****************************************************************************/
#ifdef INT_WPS_REG_SUPP
/*****************************************************************************/
/* File Includes */
/*****************************************************************************/
#include "hmac_sha256.h"
#include "dh_key.h"
#include "wps_key.h"
/*****************************************************************************/
/* Static Function Declarations */
/*****************************************************************************/
static void wps_kdf(UWORD8* inp_key, UWORD8* pers_str, UWORD8 pers_str_len,
UWORD8* out_key, UWORD32 total_key_bytes);
/*****************************************************************************/
/* */
/* Function Name : wps_kdf */
/* */
/* Description : This function implements the Key Derivation function */
/* as described in WPS standard version v.1.2.2 */
/* */
/* Inputs : 1) Input Key used for key hashing */
/* 2) Pointer to personalization string */
/* 3) Length of personalization string */
/* 4) Pointer to location where output key needs to be */
/* stored. The output key buffer should be long */
/* enough to store ((Total Output key bytes + SHA256 */
/* hash length -1)/ SHA256 hash length) of bytes i.e */
/* this module output bytes in multiple of SHA256 */
/* hash length. Calling function should take care of */
/* selecting appropriate number of bytes */
/* 5) Required length in bytes of the output key */
/* */
/* Globals : None */
/* */
/* Processing : This function implements the following algorithm */
/* kdf(key, personalization_string, total_key_bits) : */
/* result := "" */
/* iterations = (total_key_bits+prf_digest_size-1)/ */
/* prf_digest_size */
/* for i = 1 to iterations do */
/* result = result || prf(key, i || */
/* personalization_string || total_key_bits)*/
/* return result */
/* The function prf is the keyed hash HMAC-SHA-256 */
/* */
/* Outputs : None */
/* */
/* Returns : Key bits generating using KDF function */
/* */
/* Issues : None */
/* */
/* Revision History: */
/* */
/* DD MM YYYY Author(s) Changes */
/* 24 02 2010 Ittiam Draft */
/* */
/*****************************************************************************/
void wps_kdf(UWORD8* inp_key, UWORD8* pers_str, UWORD8 pers_str_len,
UWORD8* out_key, UWORD32 total_key_bytes)
{
UWORD8 *msg[3];
UWORD8 iter_buff[4], total_key_bits_buff[4];
UWORD16 msg_len[3];
UWORD32 iter, max_iter;
/* use iter as temporary variable to store total number of bits */
iter = total_key_bytes * 8;
max_iter = (total_key_bytes + SHA_256_HASH_LEN - 1) / SHA_256_HASH_LEN;
total_key_bits_buff[3] = (UWORD8)(iter);
total_key_bits_buff[2] = (UWORD8)(iter >> 8);
total_key_bits_buff[1] = (UWORD8)(iter >> 16);
total_key_bits_buff[0] = (UWORD8)(iter >> 24);
msg[0] = iter_buff;
msg_len[0] = sizeof(iter_buff);
msg[1] = pers_str;
msg_len[1] = pers_str_len;
msg[2] = total_key_bits_buff;
msg_len[2] = sizeof(total_key_bits_buff);
/*************************************************************************/
/* This function will generates bytes in multiples of SHA_256_HASH_LEN */
/* calling function to ensure that the out_key has enough space */
/*************************************************************************/
for (iter = 1; iter <= max_iter; ++iter)
{
iter_buff[3] = (UWORD8)(iter);
iter_buff[2] = (UWORD8)(iter >> 8);
iter_buff[1] = (UWORD8)(iter >> 16);
iter_buff[0] = (UWORD8)(iter >> 24);
hmac_sha256(inp_key, SHA_256_HASH_LEN, msg, msg_len,3, out_key);
out_key += SHA_256_HASH_LEN;
}
}
/*****************************************************************************/
/* */
/* Function Name : wps_gen_keys */
/* */
/* Description : This function generates Diffie-Hellman shared secret */
/* key. This key needs to be hashed before it can be used*/
/* */
/* Inputs : 1) Pointer Rxed Public Key (PKe or PKr buffer) */
/* 2) Pointer to Enrollee`s Nonce, N1 */
/* 3) POinter to Registrar`s Nonce, N2 */
/* 4) Pointer to Enrollee`s MAC Address */
/* 5) Pointer to WPS Authentication Key */
/* 6) Pointer to WPS Key Wrap Key */
/* 7) Pointer to DH Private key (A or B) */
/* */
/* Globals : None */
/* */
/* Processing : Using the received public key and local private key */
/* this functions generate the shared secret key = */
/* = (pubic key ^private Key) mod p) where g =2, p is */
/* predefined prime. It then converts the secret key in */
/* byte format. Public key, Private key, secret key and */
/* Prime are all of length WPS_DH_PRIME_LEN_WORD32. */
/* */
/* Outputs : Authentication Key and Key Wrap key */
/* */
/* Returns : SUCCESS/FAILURE */
/* */
/* Issues : None */
/* */
/* Revision History: */
/* */
/* DD MM YYYY Author(s) Changes */
/* 25 02 2011 Ittiam Draft */
/* */
/*****************************************************************************/
STATUS_T wps_gen_keys(UWORD8 *rx_pub_key,
UWORD8 *enr_nonce,
UWORD8 *reg_nonce,
UWORD8 *enr_mac_addr,
UWORD8 *auth_key,
UWORD8 *key_wrap_key,
long_num_struct_t *priv_key_ptr)
{
UWORD8 *msg[3];
UWORD16 msg_len[3];
const UWORD8 pers_str[] = "Wi-Fi Easy and Secure Key Derivation";
/*************************************************************************/
/* Generate pre-hash DH Key = (Public Key ^ Private Key) mod Prime */
/* DH key will be stored in byte format in place of Received Public Key */
/*************************************************************************/
if(FAILURE == wps_gen_ph_dh_key((UWORD32 *)rx_pub_key, priv_key_ptr))
{
return FAILURE;
}
/*************************************************************************/
/* Generate DH Key = sha256(Pre-Hashed DH-Key) and store DH key in place */
/* of pre-hash DH key */
/*************************************************************************/
msg[0] = rx_pub_key;
msg_len[0] = WPS_DH_PRIME_LEN_BYTE;
sha256(msg, msg_len, 1, rx_pub_key);
/*************************************************************************/
/* Generate KDK = HMAC-SHA256(DHKey) (N1 || EnrolleeMAC || N2). Store KDK*/
/* in place of DH key */
/*************************************************************************/
msg[0] = enr_nonce;
msg[1] = enr_mac_addr;
msg[2] = reg_nonce;
msg_len[0] = WPS_NONCE_LEN;
msg_len[1] = MAC_ADDRESS_LEN;
msg_len[2] = WPS_NONCE_LEN;
hmac_sha256(rx_pub_key, SHA_256_HASH_LEN, msg, msg_len, 3, rx_pub_key);
/*************************************************************************/
/* Use key derivation function to generate AuthKey and Key Wrap key using*/
/* key derivation function key. */
/*************************************************************************/
wps_kdf(rx_pub_key, (UWORD8 *)pers_str, (UWORD8)(sizeof(pers_str) -1),
(rx_pub_key + SHA_256_HASH_LEN),
(WPS_AUTH_KEY_LEN + WPS_KEY_WRAP_KEY_LEN + WPS_EMSK_LEN));
/* Copy Auth Key to the WPS persistent memory */
memcpy(auth_key, rx_pub_key + SHA_256_HASH_LEN, WPS_AUTH_KEY_LEN);
/* Copy Key Wrap Key to the WPS persistent memory */
memcpy(key_wrap_key, (rx_pub_key + SHA_256_HASH_LEN + WPS_AUTH_KEY_LEN),
WPS_KEY_WRAP_KEY_LEN);
return SUCCESS;
}
#endif /* INT_WPS_REG_SUPP */
| Java |
/* SPDX-License-Identifier: GPL-2.0-only */
#include <delay.h>
#include <device/mmio.h>
#include <console/console.h>
#include <console/uart.h>
#include <soc/addressmap.h>
#include <soc/otp.h>
/*
* This is a driver for the eMemory EG004K32TQ028XW01 NeoFuse
* One-Time-Programmable (OTP) memory used within the SiFive FU540.
* It is documented in the FU540 manual here:
* https://www.sifive.com/documentation/chips/freedom-u540-c000-manual/
*/
struct sifive_otp_registers {
u32 pa; /* Address input */
u32 paio; /* Program address input */
u32 pas; /* Program redundancy cell selection input */
u32 pce; /* OTP Macro enable input */
u32 pclk; /* Clock input */
u32 pdin; /* Write data input */
u32 pdout; /* Read data output */
u32 pdstb; /* Deep standby mode enable input (active low) */
u32 pprog; /* Program mode enable input */
u32 ptc; /* Test column enable input */
u32 ptm; /* Test mode enable input */
u32 ptm_rep;/* Repair function test mode enable input */
u32 ptr; /* Test row enable input */
u32 ptrim; /* Repair function enable input */
u32 pwe; /* Write enable input (defines program cycle) */
} __packed;
/*
* Read a 32 bit value addressed by its index from the OTP.
* The FU540 stores 4096x32 bit (16KiB) values.
* Index 0x00-0xff are reserved for SiFive internal use. (first 1KiB)
*/
u32 otp_read_word(u16 idx)
{
u32 w;
if (idx >= 0x1000)
die("otp: idx out of bounds");
struct sifive_otp_registers *regs = (void *)(FU540_OTP);
// wake up from stand-by
write32(®s->pdstb, 0x01);
// enable repair function
write32(®s->ptrim, 0x01);
// enable input
write32(®s->pce, 0x01);
// address to read
write32(®s->pa, idx);
// cycle clock to read
write32(®s->pclk, 0x01);
mdelay(1);
write32(®s->pclk, 0x00);
mdelay(1);
w = read32(®s->pdout);
// shut down
write32(®s->pce, 0x00);
write32(®s->ptrim, 0x00);
write32(®s->pdstb, 0x00);
return w;
}
u32 otp_read_serial(void)
{
u32 serial = 0;
u32 serial_n = 0;
for (int i = 0xfe; i > 0; i -= 2) {
serial = otp_read_word(i);
serial_n = otp_read_word(i+1);
if (serial == ~serial_n)
break;
}
return serial;
}
| Java |
ifeq ($(CONFIG_OF),y)
# Keep at91 dtb files sorted alphabetically for each SoC
# rm9200
dtb-$(CONFIG_ARCH_AT91) += at91rm9200ek.dtb
dtb-$(CONFIG_ARCH_AT91) += mpa1600.dtb
# sam9260
dtb-$(CONFIG_ARCH_AT91) += animeo_ip.dtb
dtb-$(CONFIG_ARCH_AT91) += aks-cdu.dtb
dtb-$(CONFIG_ARCH_AT91) += ethernut5.dtb
dtb-$(CONFIG_ARCH_AT91) += evk-pro3.dtb
dtb-$(CONFIG_ARCH_AT91) += tny_a9260.dtb
dtb-$(CONFIG_ARCH_AT91) += usb_a9260.dtb
# sam9263
dtb-$(CONFIG_ARCH_AT91) += at91sam9263ek.dtb
dtb-$(CONFIG_ARCH_AT91) += tny_a9263.dtb
dtb-$(CONFIG_ARCH_AT91) += usb_a9263.dtb
# sam9g20
dtb-$(CONFIG_ARCH_AT91) += at91sam9g20ek.dtb
dtb-$(CONFIG_ARCH_AT91) += at91sam9g20ek_2mmc.dtb
dtb-$(CONFIG_ARCH_AT91) += kizbox.dtb
dtb-$(CONFIG_ARCH_AT91) += tny_a9g20.dtb
dtb-$(CONFIG_ARCH_AT91) += usb_a9g20.dtb
# sam9g45
dtb-$(CONFIG_ARCH_AT91) += at91sam9m10g45ek.dtb
dtb-$(CONFIG_ARCH_AT91) += pm9g45.dtb
# sam9n12
dtb-$(CONFIG_ARCH_AT91) += at91sam9n12ek.dtb
# sam9x5
dtb-$(CONFIG_ARCH_AT91) += at91-ariag25.dtb
dtb-$(CONFIG_ARCH_AT91) += at91sam9g15ek.dtb
dtb-$(CONFIG_ARCH_AT91) += at91sam9g25ek.dtb
dtb-$(CONFIG_ARCH_AT91) += at91sam9g35ek.dtb
dtb-$(CONFIG_ARCH_AT91) += at91sam9x25ek.dtb
dtb-$(CONFIG_ARCH_AT91) += at91sam9x35ek.dtb
# sama5d3
dtb-$(CONFIG_ARCH_AT91) += sama5d31ek.dtb
dtb-$(CONFIG_ARCH_AT91) += sama5d33ek.dtb
dtb-$(CONFIG_ARCH_AT91) += sama5d34ek.dtb
dtb-$(CONFIG_ARCH_AT91) += sama5d35ek.dtb
dtb-$(CONFIG_ARCH_BCM2835) += bcm2835-rpi-b.dtb
dtb-$(CONFIG_ARCH_BCM) += bcm11351-brt.dtb
dtb-$(CONFIG_ARCH_DAVINCI) += da850-enbw-cmc.dtb \
da850-evm.dtb
dtb-$(CONFIG_ARCH_DOVE) += dove-cm-a510.dtb \
dove-cubox.dtb \
dove-dove-db.dtb
dtb-$(CONFIG_ARCH_EXYNOS) += exynos4210-origen.dtb \
exynos4210-smdkv310.dtb \
exynos4210-trats.dtb \
exynos4210-universal_c210.dtb \
exynos4412-odroidx.dtb \
exynos4412-smdk4412.dtb \
exynos4412-origen.dtb \
exynos5250-arndale.dtb \
exynos5440-sd5v1.dtb \
exynos5250-smdk5250.dtb \
exynos5250-snow.dtb \
exynos5440-ssdk5440.dtb
dtb-$(CONFIG_ARCH_HIGHBANK) += highbank.dtb \
ecx-2000.dtb
dtb-$(CONFIG_ARCH_INTEGRATOR) += integratorap.dtb \
integratorcp.dtb
dtb-$(CONFIG_ARCH_LPC32XX) += ea3250.dtb phy3250.dtb
dtb-$(CONFIG_ARCH_KIRKWOOD) += kirkwood-cloudbox.dtb \
kirkwood-dns320.dtb \
kirkwood-dns325.dtb \
kirkwood-dockstar.dtb \
kirkwood-dreamplug.dtb \
kirkwood-goflexnet.dtb \
kirkwood-guruplug-server-plus.dtb \
kirkwood-ib62x0.dtb \
kirkwood-iconnect.dtb \
kirkwood-iomega_ix2_200.dtb \
kirkwood-is2.dtb \
kirkwood-km_kirkwood.dtb \
kirkwood-lschlv2.dtb \
kirkwood-lsxhl.dtb \
kirkwood-mplcec4.dtb \
kirkwood-netgear_readynas_duo_v2.dtb \
kirkwood-ns2.dtb \
kirkwood-ns2lite.dtb \
kirkwood-ns2max.dtb \
kirkwood-ns2mini.dtb \
kirkwood-nsa310.dtb \
kirkwood-topkick.dtb \
kirkwood-ts219-6281.dtb \
kirkwood-ts219-6282.dtb \
kirkwood-openblocks_a6.dtb
dtb-$(CONFIG_ARCH_MARCO) += marco-evb.dtb
dtb-$(CONFIG_ARCH_MSM) += msm8660-surf.dtb \
msm8960-cdp.dtb
dtb-$(CONFIG_ARCH_MVEBU) += armada-370-db.dtb \
armada-370-mirabox.dtb \
armada-370-rd.dtb \
armada-xp-db.dtb \
armada-xp-gp.dtb \
armada-xp-openblocks-ax3-4.dtb
dtb-$(CONFIG_ARCH_MXC) += \
imx25-karo-tx25.dtb \
imx25-pdk.dtb \
imx27-apf27.dtb \
imx27-apf27dev.dtb \
imx27-pdk.dtb \
imx27-phytec-phycore.dtb \
imx31-bug.dtb \
imx51-apf51.dtb \
imx51-apf51dev.dtb \
imx51-babbage.dtb \
imx53-ard.dtb \
imx53-evk.dtb \
imx53-mba53.dtb \
imx53-qsb.dtb \
imx53-smd.dtb \
imx6dl-sabreauto.dtb \
imx6dl-sabresd.dtb \
imx6dl-wandboard.dtb \
imx6q-arm2.dtb \
imx6q-sabreauto.dtb \
imx6q-sabrelite.dtb \
imx6q-sabresd.dtb \
imx6q-sbc6x.dtb
dtb-$(CONFIG_ARCH_MXS) += imx23-evk.dtb \
imx23-olinuxino.dtb \
imx23-stmp378x_devb.dtb \
imx28-apf28.dtb \
imx28-apf28dev.dtb \
imx28-apx4devkit.dtb \
imx28-cfa10036.dtb \
imx28-cfa10037.dtb \
imx28-cfa10049.dtb \
imx28-evk.dtb \
imx28-m28evk.dtb \
imx28-sps1.dtb \
imx28-tx28.dtb
dtb-$(CONFIG_ARCH_NOMADIK) += ste-nomadik-s8815.dtb
dtb-$(CONFIG_ARCH_OMAP2PLUS) += omap2420-h4.dtb \
omap3430-sdp.dtb \
omap3-beagle.dtb \
omap3-devkit8000.dtb \
omap3-beagle-xm.dtb \
omap3-evm.dtb \
omap3-tobi.dtb \
omap3-igep0020.dtb \
omap3-igep0030.dtb \
omap4-panda.dtb \
omap4-panda-a4.dtb \
omap4-panda-es.dtb \
omap4-var-som.dtb \
omap4-sdp.dtb \
omap5-evm.dtb \
am335x-evm.dtb \
am335x-evmsk.dtb \
am335x-bone.dtb
dtb-$(CONFIG_ARCH_ORION5X) += orion5x-lacie-ethernet-disk-mini-v2.dtb
dtb-$(CONFIG_ARCH_PRIMA2) += prima2-evb.dtb
dtb-$(CONFIG_ARCH_U8500) += snowball.dtb \
hrefprev60.dtb \
hrefv60plus.dtb \
ccu9540.dtb
dtb-$(CONFIG_ARCH_SHMOBILE) += emev2-kzm9d.dtb \
r8a7740-armadillo800eva.dtb \
r8a7778-bockw.dtb \
r8a7779-marzen-reference.dtb \
r8a7790-lager.dtb \
sh73a0-kzm9g.dtb \
sh73a0-kzm9g-reference.dtb \
r8a73a4-ape6evm.dtb \
sh7372-mackerel.dtb
dtb-$(CONFIG_ARCH_SOCFPGA) += socfpga_cyclone5.dtb \
socfpga_vt.dtb
dtb-$(CONFIG_ARCH_SPEAR13XX) += spear1310-evb.dtb \
spear1340-evb.dtb
dtb-$(CONFIG_ARCH_SPEAR3XX)+= spear300-evb.dtb \
spear310-evb.dtb \
spear320-evb.dtb \
spear320-hmi.dtb
dtb-$(CONFIG_ARCH_SPEAR6XX)+= spear600-evb.dtb
dtb-$(CONFIG_ARCH_SUNXI) += \
sun4i-a10-cubieboard.dtb \
sun4i-a10-mini-xplus.dtb \
sun4i-a10-hackberry.dtb \
sun5i-a13-olinuxino.dtb
dtb-$(CONFIG_ARCH_TEGRA) += tegra20-harmony.dtb \
tegra20-iris-512.dtb \
tegra20-medcom-wide.dtb \
tegra20-paz00.dtb \
tegra20-plutux.dtb \
tegra20-seaboard.dtb \
tegra20-tec.dtb \
tegra20-trimslice.dtb \
tegra20-ventana.dtb \
tegra20-whistler.dtb \
tegra30-beaver.dtb \
tegra30-cardhu-a02.dtb \
tegra30-cardhu-a04.dtb \
tegra114-dalmore.dtb \
tegra114-dalmore-e1611-1000-a00-00.dtb \
tegra114-dalmore-e1611-1001-a00-00.dtb \
tegra114-macallan.dtb \
tegra114-roth.dtb \
tegra114-pluto.dtb \
tegra114-pismo.dtb \
tegra124-bonaire_sim.dtb \
tegra124-bonaire.dtb \
tegra124-ardbeg.dtb \
tegra124-ardbeg-a03-00.dtb \
tegra124-laguna.dtb \
tegra124-pm375.dtb \
tegra124-norrin.dtb \
tegra124-loki.dtb \
tegra124-foster.dtb \
tegra124-thor195.dtb \
tegra124-tn8.dtb \
tegra124-tn8-p1761.dtb \
tegra124-tn8-p1761-2gb.dtb \
tegra124-tn8-p1761-battery.dtb \
tegra124-tn8-p1761-battery-2gb.dtb \
tegra124-tn8-aio.dtb \
tegra124-tn8-battery.dtb \
tegra124-tn8-a03-00.dtb \
tegra124-tn8-a03-00-battery.dtb \
tegra124-tn8-a03-01.dtb \
tegra124-tn8-a03-01-battery.dtb \
tegra124-e1782_sku1100.dtb \
tegra124-e1791.dtb \
tegra124-e1922.dtb \
tegra124-e1923.dtb \
tegra124-ardbeg_sata.dtb \
tegra124-vcm30_t124.dtb
dtb-$(CONFIG_ARCH_VERSATILE) += versatile-ab.dtb \
versatile-pb.dtb
dtb-$(CONFIG_ARCH_VEXPRESS) += vexpress-v2p-ca5s.dtb \
vexpress-v2p-ca9.dtb \
vexpress-v2p-ca15-tc1.dtb \
vexpress-v2p-ca15_a7.dtb
dtb-$(CONFIG_ARCH_VIRT) += xenvm-4.2.dtb
dtb-$(CONFIG_ARCH_VT8500) += vt8500-bv07.dtb \
wm8505-ref.dtb \
wm8650-mid.dtb \
wm8850-w70v2.dtb
dtb-$(CONFIG_ARCH_ZYNQ) += zynq-zc702.dtb
targets += dtbs
targets += $(dtb-y)
endif
# *.dtb used to be generated in the directory above. Clean out the
# old build results so people don't accidentally use them.
dtbs: $(addprefix $(obj)/, $(dtb-y))
$(Q)rm -f $(obj)/../*.dtb
clean-files := *.dtb
| Java |
/* -*- C -*-
//C- -------------------------------------------------------------------
//C- DjView4
//C- Copyright (c) 2006 Leon Bottou
//C-
//C- This software is subject to, and may be distributed under, the
//C- GNU General Public License, either version 2 of the license,
//C- or (at your option) any later version. The license should have
//C- accompanied the software or you may obtain a copy of the license
//C- from the Free Software Foundation at http://www.fsf.org .
//C-
//C- This program is distributed in the hope that it will be useful,
//C- but WITHOUT ANY WARRANTY; without even the implied warranty of
//C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//C- GNU General Public License for more details.
//C- ------------------------------------------------------------------
*/
/* The following code is derived from program "tiff2pdf"
* whose copyright notice is reproduced below.
* Changes were made to make it independent from the private
* include file tiffiop.h.
*
* +--------------------------------------------------------------------
* | tiff2pdf - converts a TIFF image to a PDF document
* |
* | Copyright (c) 2003 Ross Finlayson
* |
* | Permission to use, copy, modify, distribute, and sell this software and
* | its documentation for any purpose is hereby granted without fee, provided
* | that (i) the above copyright notices and this permission notice appear in
* | all copies of the software and related documentation, and (ii) the name of
* | Ross Finlayson may not be used in any advertising or
* | publicity relating to the software without the specific, prior written
* | permission of Ross Finlayson.
* |
* | THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* | EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* | WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
* |
* | IN NO EVENT SHALL ROSS FINLAYSON BE LIABLE FOR
* | ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* | OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* | WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* | LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* | OF THIS SOFTWARE.
* +--------------------------------------------------------------------
*/
#include "tiff2pdf.h"
#if HAVE_TIFF2PDF
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#if HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifndef NULL
# define NULL ((void*)0)
#endif
#ifdef __GNUC__
# define unused __attribute__((unused))
#else
# define unused /**/
#endif
/* -------------------------------------------------- *
Tiff2Pdf declarations
* -------------------------------------------------- */
#define TIFF2PDF_MODULE "tiff2pdf"
#define T2P_VERSION "d"
/* This type is of PDF color spaces. */
typedef enum{
T2P_CS_BILEVEL=0x01, /* Bilevel, black and white */
T2P_CS_GRAY=0x02, /* Single channel */
T2P_CS_RGB=0x04, /* Three channel tristimulus RGB */
T2P_CS_CMYK=0x08, /* Four channel CMYK print inkset */
T2P_CS_LAB=0x10, /* Three channel L*a*b* color space */
T2P_CS_PALETTE=0x1000 /* One of the above with a color map */
, T2P_CS_CALGRAY=0x20 /* Calibrated single channel */
, T2P_CS_CALRGB=0x40 /* Calibrated three channel tristimulus RGB */
, T2P_CS_ICCBASED=0x80 /* ICC profile color specification */
} t2p_cs_t;
/* This type is of PDF compression types. */
typedef enum{
T2P_COMPRESS_NONE=0x00
#ifdef CCITT_SUPPORT
, T2P_COMPRESS_G4=0x01
#endif
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
, T2P_COMPRESS_JPEG=0x02
#endif
#ifdef ZIP_SUPPORT
, T2P_COMPRESS_ZIP=0x04
#endif
} t2p_compress_t;
/* This type is whether TIFF image data can be used in PDF without transcoding. */
typedef enum{
T2P_TRANSCODE_RAW=0x01, /* The raw data from the input can be used without recompressing */
T2P_TRANSCODE_ENCODE=0x02 /* The data from the input is perhaps unencoded and reencoded */
} t2p_transcode_t;
/* This type is of information about the data samples of the input image. */
typedef enum{
T2P_SAMPLE_NOTHING=0x0000, /* The unencoded samples are normal for the output colorspace */
T2P_SAMPLE_ABGR_TO_RGB=0x0001, /* The unencoded samples are the result of ReadRGBAImage */
T2P_SAMPLE_RGBA_TO_RGB=0x0002, /* The unencoded samples are contiguous RGBA */
T2P_SAMPLE_RGBAA_TO_RGB=0x0004, /* The unencoded samples are RGBA with premultiplied alpha */
T2P_SAMPLE_YCBCR_TO_RGB=0x0008,
T2P_SAMPLE_YCBCR_TO_LAB=0x0010,
T2P_SAMPLE_REALIZE_PALETTE=0x0020, /* The unencoded samples are indexes into the color map */
T2P_SAMPLE_SIGNED_TO_UNSIGNED=0x0040, /* The unencoded samples are signed instead of unsignd */
T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED=0x0040, /* The L*a*b* samples have a* and b* signed */
T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG=0x0100 /* The unencoded samples are separate instead of contiguous */
} t2p_sample_t;
/* This type is of error status of the T2P struct. */
typedef enum{
T2P_ERR_OK = 0, /* This is the value of t2p->t2p_error when there is no error */
T2P_ERR_ERROR = 1 /* This is the value of t2p->t2p_error when there was an error */
} t2p_err_t;
/* This struct defines a logical page of a TIFF. */
typedef struct {
tdir_t page_directory;
uint32 page_number;
ttile_t page_tilecount;
uint32 page_extra;
} T2P_PAGE;
/* This struct defines a PDF rectangle's coordinates. */
typedef struct {
float x1;
float y1;
float x2;
float y2;
float mat[9];
} T2P_BOX;
/* This struct defines a tile of a PDF. */
typedef struct {
T2P_BOX tile_box;
} T2P_TILE;
/* This struct defines information about the tiles on a PDF page. */
typedef struct {
ttile_t tiles_tilecount;
uint32 tiles_tilewidth;
uint32 tiles_tilelength;
uint32 tiles_tilecountx;
uint32 tiles_tilecounty;
uint32 tiles_edgetilewidth;
uint32 tiles_edgetilelength;
T2P_TILE* tiles_tiles;
} T2P_TILES;
/* This struct is the context of a function to generate PDF from a TIFF. */
typedef struct {
t2p_err_t t2p_error;
T2P_PAGE* tiff_pages;
T2P_TILES* tiff_tiles;
tdir_t tiff_pagecount;
uint16 tiff_compression;
uint16 tiff_photometric;
uint16 tiff_fillorder;
uint16 tiff_bitspersample;
uint16 tiff_samplesperpixel;
uint16 tiff_planar;
uint32 tiff_width;
uint32 tiff_length;
float tiff_xres;
float tiff_yres;
uint16 tiff_orientation;
toff_t tiff_dataoffset;
tsize_t tiff_datasize;
TIFFReadWriteProc tiff_readproc;
TIFFReadWriteProc tiff_writeproc;
TIFFSeekProc tiff_seekproc;
uint16 tiff_resunit;
uint16 pdf_centimeters;
uint16 pdf_overrideres;
uint16 pdf_overridepagesize;
float pdf_defaultxres;
float pdf_defaultyres;
float pdf_xres;
float pdf_yres;
float pdf_defaultpagewidth;
float pdf_defaultpagelength;
float pdf_pagewidth;
float pdf_pagelength;
float pdf_imagewidth;
float pdf_imagelength;
T2P_BOX pdf_mediabox;
T2P_BOX pdf_imagebox;
uint16 pdf_majorversion;
uint16 pdf_minorversion;
uint32 pdf_catalog;
uint32 pdf_pages;
uint32 pdf_info;
uint32 pdf_palettecs;
uint16 pdf_fitwindow;
uint32 pdf_startxref;
char* pdf_fileid;
char* pdf_datetime;
char* pdf_creator;
char* pdf_author;
char* pdf_title;
char* pdf_subject;
char* pdf_keywords;
t2p_cs_t pdf_colorspace;
uint16 pdf_colorspace_invert;
uint16 pdf_switchdecode;
uint16 pdf_palettesize;
unsigned char* pdf_palette;
int pdf_labrange[4];
t2p_compress_t pdf_defaultcompression;
uint16 pdf_defaultcompressionquality;
t2p_compress_t pdf_compression;
uint16 pdf_compressionquality;
uint16 pdf_nopassthrough;
t2p_transcode_t pdf_transcode;
t2p_sample_t pdf_sample;
uint32* pdf_xrefoffsets;
uint32 pdf_xrefcount;
tdir_t pdf_page;
#ifdef OJPEG_SUPPORT
tdata_t pdf_ojpegdata;
uint32 pdf_ojpegdatalength;
uint32 pdf_ojpegiflength;
#endif
float tiff_whitechromaticities[2];
float tiff_primarychromaticities[6];
float tiff_referenceblackwhite[2];
float* tiff_transferfunction[3];
int pdf_image_interpolate; /* 0 (default) : do not interpolate,
1 : interpolate */
uint16 tiff_transferfunctioncount;
uint32 pdf_icccs;
uint32 tiff_iccprofilelength;
tdata_t tiff_iccprofile;
/* LB additional fields */
FILE *outputfile;
int outputdisable;
tsize_t outputwritten;
} T2P;
/* These functions are called by main. */
static int tiff2pdf_match_paper_size(float*, float*, char*);
/* These functions are used to generate a PDF from a TIFF. */
static T2P* t2p_init(void);
static void t2p_validate(T2P*);
static tsize_t t2p_write_pdf(T2P*, TIFF*, TIFF*);
static void t2p_free(T2P*);
static void t2p_read_tiff_init(T2P*, TIFF*);
static int t2p_cmp_t2p_page(const void*, const void*);
static void t2p_read_tiff_data(T2P*, TIFF*);
static void t2p_read_tiff_size(T2P*, TIFF*);
static void t2p_read_tiff_size_tile(T2P*, TIFF*, ttile_t);
static int t2p_tile_is_right_edge(T2P_TILES, ttile_t);
static int t2p_tile_is_bottom_edge(T2P_TILES, ttile_t);
static tsize_t t2p_readwrite_pdf_image(T2P*, TIFF*, TIFF*);
static tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t);
#ifdef OJPEG_SUPPORT
static int t2p_process_ojpeg_tables(T2P*, TIFF*);
#endif
#ifdef JPEG_SUPPORT
static int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t*, tstrip_t, uint32);
#endif
static void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32);
static void t2p_write_advance_directory(T2P*, TIFF*);
static tsize_t t2p_sample_planar_separate_to_contig(T2P*, unsigned char*, unsigned char*, tsize_t);
static tsize_t t2p_sample_realize_palette(T2P*, unsigned char*);
static tsize_t t2p_sample_abgr_to_rgb(tdata_t, uint32);
static tsize_t t2p_sample_rgba_to_rgb(tdata_t, uint32);
static tsize_t t2p_sample_rgbaa_to_rgb(tdata_t, uint32);
static tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t, uint32);
static tsize_t t2p_write_pdf_header(T2P*, TIFF*);
static tsize_t t2p_write_pdf_obj_start(uint32, TIFF*);
static tsize_t t2p_write_pdf_obj_end(TIFF*);
static tsize_t t2p_write_pdf_string(char*, TIFF*);
static tsize_t t2p_write_pdf_stream(tdata_t, tsize_t, TIFF*);
static tsize_t t2p_write_pdf_stream_start(TIFF*);
static tsize_t t2p_write_pdf_stream_end(TIFF*);
static tsize_t t2p_write_pdf_stream_dict(tsize_t, uint32, TIFF*);
static tsize_t t2p_write_pdf_stream_dict_start(TIFF*);
static tsize_t t2p_write_pdf_stream_dict_end(TIFF*);
static tsize_t t2p_write_pdf_stream_length(tsize_t, TIFF*);
static tsize_t t2p_write_pdf_catalog(T2P*, TIFF*);
static tsize_t t2p_write_pdf_info(T2P*, TIFF*, TIFF*);
static void t2p_pdf_currenttime(T2P*);
static void t2p_pdf_tifftime(T2P*, TIFF*);
static tsize_t t2p_write_pdf_pages(T2P*, TIFF*);
static tsize_t t2p_write_pdf_page(uint32, T2P*, TIFF*);
static void t2p_compose_pdf_page(T2P*);
static void t2p_compose_pdf_page_orient(T2P_BOX*, uint16);
static void t2p_compose_pdf_page_orient_flip(T2P_BOX*, uint16);
static tsize_t t2p_write_pdf_xobject_cs(T2P*, TIFF*);
static tsize_t t2p_write_pdf_transfer(T2P*, TIFF*);
static tsize_t t2p_write_pdf_transfer_dict(T2P*, TIFF*, uint16);
static tsize_t t2p_write_pdf_transfer_stream(T2P*, TIFF*, uint16);
static tsize_t t2p_write_pdf_xobject_calcs(T2P*, TIFF*);
static tsize_t t2p_write_pdf_xobject_icccs(T2P*, TIFF*);
static tsize_t t2p_write_pdf_xobject_icccs_dict(T2P*, TIFF*);
static tsize_t t2p_write_pdf_xobject_icccs_stream(T2P*, TIFF*);
static tsize_t t2p_write_pdf_xobject_decode(T2P*, TIFF*);
static tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t, T2P*, TIFF*);
static tsize_t t2p_write_pdf_xreftable(T2P*, TIFF*);
static tsize_t t2p_write_pdf_trailer(T2P*, TIFF*);
/* -------------------------------------------------- *
Replacement for tiffiop functions
* -------------------------------------------------- */
static unused tsize_t
t2pReadFile(TIFF *tif, tdata_t data, tsize_t size)
{
thandle_t client = TIFFClientdata(tif);
TIFFReadWriteProc proc = TIFFGetReadProc(tif);
if (proc)
return proc(client, data, size);
return -1;
}
static unused tsize_t
t2pWriteFile(TIFF *tif, tdata_t data, tsize_t size)
{
thandle_t client = TIFFClientdata(tif);
TIFFReadWriteProc proc = TIFFGetWriteProc(tif);
if (proc)
return proc(client, data, size);
return -1;
}
static unused toff_t
t2pSeekFile(TIFF *tif, toff_t offset, int whence)
{
thandle_t client = TIFFClientdata(tif);
TIFFSeekProc proc = TIFFGetSeekProc(tif);
if (proc)
return proc(client, offset, whence);
return -1;
}
#ifdef TIFFReadFile
# undef TIFFReadFile
#endif
#ifndef TIFFReadFile
# define TIFFReadFile t2pReadFile
#endif
#ifdef TIFFWriteFile
# undef TIFFWriteFile
#endif
#ifndef TIFFWriteFile
# define TIFFWriteFile t2pWriteFile
#endif
#ifdef TIFFSeekFile
# undef TIFFSeekFile
#endif
#ifndef TIFFSeekFile
# define TIFFSeekFile t2pSeekFile
#endif
static void
t2p_disable(TIFF *tif)
{
T2P *t2p = (T2P*) TIFFClientdata(tif);
t2p->outputdisable = 1;
}
static void
t2p_enable(TIFF *tif)
{
T2P *t2p = (T2P*) TIFFClientdata(tif);
t2p->outputdisable = 0;
}
/* -------------------------------------------------- *
Procs for TIFFClientOpen
* -------------------------------------------------- */
static tsize_t
t2p_readproc(thandle_t unused handle, tdata_t unused data , tsize_t unused size)
{
return -1;
}
static tsize_t
t2p_writeproc(thandle_t handle, tdata_t data, tsize_t size)
{
T2P *t2p = (T2P*) handle;
if (t2p->outputdisable <= 0 && t2p->outputfile)
{
tsize_t written = fwrite(data, 1, size, t2p->outputfile);
t2p->outputwritten += written;
return written;
}
return size;
}
static toff_t
t2p_seekproc(thandle_t handle, toff_t offset, int whence)
{
T2P *t2p = (T2P*) handle;
if (t2p->outputdisable <= 0 && t2p->outputfile)
return fseek(t2p->outputfile, offset, whence);
return offset;
}
static int
t2p_closeproc(thandle_t unused handle)
{
return 0;
}
static toff_t
t2p_sizeproc(thandle_t unused handle)
{
return -1;
}
static int
t2p_mapproc(thandle_t unused handle, tdata_t unused *data, toff_t unused *offset)
{
return -1;
}
static void
t2p_unmapproc(thandle_t unused handle, tdata_t unused data, toff_t unused offset)
{
}
/* -------------------------------------------------- *
Ports
* -------------------------------------------------- */
#ifdef WIN32
/*
* Copyright (c) 1987, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*/
#if 0
static char sccsid[] = "@(#)getopt.c 8.3 (Berkeley) 4/27/95";
__RCSID("$NetBSD: getopt.c,v 1.26 2003/08/07 16:43:40 agc Exp $");
#endif
#include <stdio.h>
#include <string.h>
int opterr = 1, /* if error message should be printed */
optind = 1, /* index into parent argv vector */
optopt, /* character checked for validity */
optreset; /* reset getopt */
char *optarg; /* argument associated with option */
#define BADCH (int)'?'
#define BADARG (int)':'
#define EMSG ""
/*
* getopt --
* Parse argc/argv argument vector.
*/
int
getopt(int argc, char * const argv[], const char *optstring)
{
static char *place = EMSG; /* option letter processing */
char *oli; /* option letter list index */
if (optreset || *place == 0) { /* update scanning pointer */
optreset = 0;
place = argv[optind];
if (optind >= argc || *place++ != '-') {
/* Argument is absent or is not an option */
place = EMSG;
return (-1);
}
optopt = *place++;
if (optopt == '-' && *place == 0) {
/* "--" => end of options */
++optind;
place = EMSG;
return (-1);
}
if (optopt == 0) {
/* Solitary '-', treat as a '-' option
if the program (eg su) is looking for it. */
place = EMSG;
if (strchr(optstring, '-') == NULL)
return -1;
optopt = '-';
}
} else
optopt = *place++;
/* See if option letter is one the caller wanted... */
if (optopt == ':' || (oli = strchr(optstring, optopt)) == NULL) {
if (*place == 0)
++optind;
if (opterr && *optstring != ':')
(void)fprintf(stderr,
"unknown option -- %c\n", optopt);
return (BADCH);
}
/* Does this option need an argument? */
if (oli[1] != ':') {
/* don't need argument */
optarg = NULL;
if (*place == 0)
++optind;
} else {
/* Option-argument is either the rest of this argument or the
entire next argument. */
if (*place)
optarg = place;
else if (argc > ++optind)
optarg = argv[optind];
else {
/* option-argument absent */
place = EMSG;
if (*optstring == ':')
return (BADARG);
if (opterr)
(void)fprintf(stderr,
"option requires an argument -- %c\n",
optopt);
return (BADCH);
}
place = EMSG;
++optind;
}
return (optopt); /* return option letter */
}
#endif
/* -------------------------------------------------- *
Main function
* -------------------------------------------------- */
/*
This is the main function.
The program converts one TIFF file to one PDF file, including multiple page
TIFF files, tiled TIFF files, black and white. grayscale, and color TIFF
files that contain data of TIFF photometric interpretations of bilevel,
grayscale, RGB, YCbCr, CMYK separation, and ICC L*a*b* as supported by
libtiff and PDF.
If you have multiple TIFF files to convert into one PDF file then use tiffcp
or other program to concatenate the files into a multiple page TIFF file.
If the input TIFF file is of huge dimensions (greater than 10000 pixels height
or width) convert the input image to a tiled TIFF if it is not already.
The standard output is standard output. Set the output file name with the
"-o output.pdf" option.
All black and white files are compressed into a single strip CCITT G4 Fax
compressed PDF, unless tiled, where tiled black and white images are
compressed into tiled CCITT G4 Fax compressed PDF, libtiff CCITT support
is assumed.
Color and grayscale data can be compressed using either JPEG compression,
ITU-T T.81, or Zip/Deflate LZ77 compression, per PNG 1.2 and RFC 1951. Set
the compression type using the -j or -z options. JPEG compression support
requires that libtiff be configured with JPEG support, and Zip/Deflate
compression support requires that libtiff is configured with Zip support,
in tiffconf.h. Use only one or the other of -j and -z. The -q option
sets the image compression quality, that is 1-100 with libjpeg JPEG
compression and one of 1, 10, 11, 12, 13, 14, or 15 for PNG group compression
predictor methods, add 100, 200, ..., 900 to set zlib compression quality 1-9.
PNG Group differencing predictor methods are not currently implemented.
If the input TIFF contains single strip CCITT G4 Fax compressed information,
then that is written to the PDF file without transcoding, unless the options
of no compression and no passthrough are set, -d and -n.
If the input TIFF contains JPEG or single strip Zip/Deflate compressed
information, and they are configured, then that is written to the PDF file
without transcoding, unless the options of no compression and no passthrough
are set.
The default page size upon which the TIFF image is placed is determined by
the resolution and extent of the image data. Default values for the TIFF
image resolution can be set using the -x and -y options. The page size can
be set using the -p option for paper size, or -w and -l for paper width and
length, then each page of the TIFF image is centered on its page. The
distance unit for default resolution and page width and length can be set
by the -u option, the default unit is inch.
Various items of the output document information can be set with the -e, -c,
-a, -t, -s, and -k tags. Setting the argument of the option to "" for these
tags causes the relevant document information field to be not written. Some
of the document information values otherwise get their information from the
input TIFF image, the software, author, document name, and image description.
The output PDF file conforms to the PDF 1.1 specification or PDF 1.2 if using
Zip/Deflate compression.
The Portable Document Format (PDF) specification is copyrighted by Adobe
Systems, Incorporated. Todos derechos reservados.
Here is a listing of the usage example and the options to the tiff2pdf
program that is part of the libtiff distribution. Options followed by
a colon have a required argument.
usage: tiff2pdf [options] input.tif
options:
-o: output to file name
-j compress with JPEG (requires libjpeg configured with libtiff)
-z compress with Zip/Deflate (requires zlib configured with libtiff)
-q: compression quality
-n no compressed data passthrough
-d do not compress (decompress)
-i invert colors
-u: set distance unit, 'i' for inch, 'm' for centimeter
-x: set x resolution default
-y: set y resolution default
-w: width in units
-l: length in units
-r: 'd' for resolution default, 'o' for resolution override
-p: paper size, eg "letter", "legal", "A4"
-f set PDF "Fit Window" user preference
-b set PDF "Interpolate" user preference
-e: date, overrides image or current date/time default, YYYYMMDDHHMMSS
-c: creator, overrides image software default
-a: author, overrides image artist default
-t: title, overrides image document name default
-s: subject, overrides image image description default
-k: keywords
-h usage
examples:
tiff2pdf -o output.pdf input.tiff
The above example would generate the file output.pdf from input.tiff.
tiff2pdf input.tiff
The above example would generate PDF output from input.tiff and write it
to standard output.
tiff2pdf -j -p letter -o output.pdf input.tiff
The above example would generate the file output.pdf from input.tiff,
putting the image pages on a letter sized page, compressing the output
with JPEG.
Please report bugs through:
http://bugzilla.remotesensing.org/buglist.cgi?product=libtiff
See also libtiff.3t, tiffcp.
*/
int
tiff2pdf(TIFF *input, FILE *outputfile, int argc, const char **argv)
{
extern char *optarg;
const char *outfilename = "<null>";
T2P *t2p = NULL;
TIFF *output = NULL;
int c;
/* T2P */
t2p = t2p_init();
if (t2p == NULL){
TIFFError(TIFF2PDF_MODULE, "Can't initialize context");
goto fail;
}
/* Options */
while (argv &&
(c = getopt(argc, (char**)argv,
"o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbh")) != -1) {
switch (c) {
case 'o':
outfilename = optarg;
break;
#ifdef JPEG_SUPPORT
case 'j':
t2p->pdf_defaultcompression=T2P_COMPRESS_JPEG;
break;
#endif
#ifdef ZIP_SUPPORT
case 'z':
t2p->pdf_defaultcompression=T2P_COMPRESS_ZIP;
break;
#endif
case 'q':
t2p->pdf_defaultcompressionquality=atoi(optarg);
break;
case 'n':
t2p->pdf_nopassthrough=1;
break;
case 'd':
t2p->pdf_defaultcompression=T2P_COMPRESS_NONE;
break;
case 'u':
if(optarg[0]=='m'){
t2p->pdf_centimeters=1;
}
break;
case 'x':
t2p->pdf_defaultxres =
(float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F);
break;
case 'y':
t2p->pdf_defaultyres =
(float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F);
break;
case 'w':
t2p->pdf_overridepagesize=1;
t2p->pdf_defaultpagewidth =
((float)atof(optarg) * 72.0F) / (t2p->pdf_centimeters?2.54F:1.0F);
break;
case 'l':
t2p->pdf_overridepagesize=1;
t2p->pdf_defaultpagelength =
((float)atof(optarg) * 72.0F) / (t2p->pdf_centimeters?2.54F:1.0F);
break;
case 'r':
if(optarg[0]=='o'){
t2p->pdf_overrideres=1;
}
break;
case 'p':
if(tiff2pdf_match_paper_size(&(t2p->pdf_defaultpagewidth),
&(t2p->pdf_defaultpagelength),
optarg)){
t2p->pdf_overridepagesize=1;
} else {
TIFFWarning(TIFF2PDF_MODULE,
"Unknown paper size %s, ignoring option",
optarg);
}
break;
case 'i':
t2p->pdf_colorspace_invert=1;
break;
case 'f':
t2p->pdf_fitwindow=1;
break;
case 'e':
t2p->pdf_datetime = (char*)_TIFFmalloc(17);
if(t2p->pdf_datetime){
if(strlen(optarg)==0){
t2p->pdf_datetime[0]=0;
} else {
if(strlen(optarg)>14){optarg[14]=0;}
t2p->pdf_datetime[0]='D';
t2p->pdf_datetime[1]=':';
strcpy(&(t2p->pdf_datetime[2]), optarg);
}
}
break;
case 'c':
t2p->pdf_creator = (char *)_TIFFmalloc(strlen(optarg) + 1);
if(t2p->pdf_creator){
strcpy(t2p->pdf_creator, optarg);
t2p->pdf_creator[strlen(optarg)]=0;
}
break;
case 'a':
t2p->pdf_author = (char *)_TIFFmalloc(strlen(optarg) + 1);
if(t2p->pdf_author){
strcpy(t2p->pdf_author, optarg);
t2p->pdf_author[strlen(optarg)]=0;
}
break;
case 't':
t2p->pdf_title= (char*)_TIFFmalloc(strlen(optarg)+1);
if(t2p->pdf_title){
strcpy(t2p->pdf_title, optarg);
t2p->pdf_title[strlen(optarg)]=0;
}
break;
case 's':
t2p->pdf_subject= (char*)_TIFFmalloc(strlen(optarg)+1);
if(t2p->pdf_subject){
strcpy(t2p->pdf_subject, optarg);
t2p->pdf_subject[strlen(optarg)]=0;
}
break;
case 'k':
t2p->pdf_keywords= (char*)_TIFFmalloc(strlen(optarg)+1);
if(t2p->pdf_keywords){
strcpy(t2p->pdf_keywords, optarg);
t2p->pdf_keywords[strlen(optarg)]=0;
}
break;
case 'b':
t2p->pdf_image_interpolate = 1;
break;
}
}
/* Output */
t2p->outputdisable = 0;
t2p->outputfile = outputfile;
output = TIFFClientOpen(outfilename, "w", (thandle_t) t2p,
t2p_readproc, t2p_writeproc, t2p_seekproc,
t2p_closeproc, t2p_sizeproc,
t2p_mapproc, t2p_unmapproc );
if (output == NULL){
TIFFError(TIFF2PDF_MODULE, "Can't initialize output descriptor");
goto fail;
}
/* Validate */
t2p_validate(t2p);
TIFFSeekFile(output, (toff_t) 0, SEEK_SET);
/* Write */
t2p_write_pdf(t2p, input, output);
if(t2p->t2p_error != 0){
TIFFError(TIFF2PDF_MODULE, "An error occurred creating output PDF file");
goto fail;
}
if (output != NULL)
TIFFClose(output);
if (t2p != NULL)
t2p_free(t2p);
return(EXIT_SUCCESS);
fail:
if (output != NULL)
TIFFClose(output);
if (t2p != NULL)
t2p_free(t2p);
return(EXIT_FAILURE);
}
static int
tiff2pdf_match_paper_size(float* width, float* length, char* papersize)
{
int i=0;
int len=0;
const char* sizes[]={
"LETTER", "A4", "LEGAL",
"EXECUTIVE", "LETTER", "LEGAL", "LEDGER", "TABLOID",
"A", "B", "C", "D", "E", "F", "G", "H", "J", "K",
"A10", "A9", "A8", "A7", "A6", "A5", "A4", "A3", "A2", "A1", "A0",
"2A0", "4A0", "2A", "4A",
"B10", "B9", "B8", "B7", "B6", "B5", "B4", "B3", "B2", "B1", "B0",
"JISB10", "JISB9", "JISB8", "JISB7", "JISB6", "JISB5", "JISB4",
"JISB3", "JISB2", "JISB1", "JISB0",
"C10", "C9", "C8", "C7", "C6", "C5", "C4", "C3", "C2", "C1", "C0",
"RA2", "RA1", "RA0", "SRA4", "SRA3", "SRA2", "SRA1", "SRA0",
"A3EXTRA", "A4EXTRA",
"STATEMENT", "FOLIO", "QUARTO",
NULL
} ;
const int widths[]={
612, 595, 612,
522, 612,612,792,792,
612,792,1224,1584,2448,2016,792,2016,2448,2880,
74,105,147,210,298,420,595,842,1191,1684,2384,3370,4768,3370,4768,
88,125,176,249,354,499,709,1001,1417,2004,2835,
91,128,181,258,363,516,729,1032,1460,2064,2920,
79,113,162,230,323,459,649,918,1298,1298,2599,
1219,1729,2438,638,907,1276,1814,2551,
914,667,
396, 612, 609,
0
};
const int lengths[]={
792,842,1008,
756,792,1008,1224,1224,
792,1224,1584,2448,3168,2880,6480,10296,12672,10296,
105,147,210,298,420,595,842,1191,1684,2384,3370,4768,6741,4768,6741,
125,176,249,354,499,709,1001,1417,2004,2835,4008,
128,181,258,363,516,729,1032,1460,2064,2920,4127,
113,162,230,323,459,649,918,1298,1837,1837,3677,
1729,2438,3458,907,1276,1814,2551,3628,
1262,914,
612, 936, 780,
0
};
len=strlen(papersize);
for(i=0;i<len;i++){
papersize[i]=toupper(papersize[i]);
}
for(i=0;sizes[i]!=NULL; i++){
if (strcmp( (const char*)papersize, sizes[i])==0){
*width=(float)widths[i];
*length=(float)lengths[i];
return(1);
}
}
return(0);
}
/* -------------------------------------------------- *
Tiff2Pdf proper with minor changes
* -------------------------------------------------- */
/*
This function allocates and initializes a T2P context struct pointer.
*/
static T2P* t2p_init()
{
T2P* t2p = (T2P*) _TIFFmalloc(sizeof(T2P));
if(t2p==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_init",
(int)sizeof(T2P));
return( (T2P*) NULL );
}
_TIFFmemset(t2p, 0x00, sizeof(T2P));
t2p->pdf_majorversion=1;
t2p->pdf_minorversion=1;
t2p->pdf_defaultxres=300.0;
t2p->pdf_defaultyres=300.0;
t2p->pdf_defaultpagewidth=612.0;
t2p->pdf_defaultpagelength=792.0;
t2p->pdf_xrefcount=3; /* Catalog, Info, Pages */
t2p->outputfile = NULL;
t2p->outputdisable = 0;
t2p->outputwritten = 0;
return(t2p);
}
/*
This function frees a T2P context struct pointer and any allocated data fields of it.
*/
static void t2p_free(T2P* t2p){
int i=0;
if(t2p != NULL){
if(t2p->pdf_xrefoffsets != NULL){
_TIFFfree( (tdata_t) t2p->pdf_xrefoffsets);
}
if(t2p->tiff_pages != NULL){
_TIFFfree( (tdata_t) t2p->tiff_pages);
}
for(i=0;i<t2p->tiff_pagecount;i++){
if(t2p->tiff_tiles[i].tiles_tiles != NULL){
_TIFFfree( (tdata_t) t2p->tiff_tiles[i].tiles_tiles);
}
}
if(t2p->tiff_tiles != NULL){
_TIFFfree( (tdata_t) t2p->tiff_tiles);
}
if(t2p->pdf_palette != NULL){
_TIFFfree( (tdata_t) t2p->pdf_palette);
}
if(t2p->pdf_fileid != NULL){
_TIFFfree( (tdata_t) t2p->pdf_fileid);
}
if(t2p->pdf_datetime != NULL){
_TIFFfree( (tdata_t) t2p->pdf_datetime);
}
if(t2p->pdf_creator != NULL){
_TIFFfree( (tdata_t) t2p->pdf_creator);
}
if(t2p->pdf_author != NULL){
_TIFFfree( (tdata_t) t2p->pdf_author);
}
if(t2p->pdf_title != NULL){
_TIFFfree( (tdata_t) t2p->pdf_title);
}
if(t2p->pdf_subject != NULL){
_TIFFfree( (tdata_t) t2p->pdf_subject);
}
if(t2p->pdf_keywords != NULL){
_TIFFfree( (tdata_t) t2p->pdf_keywords);
}
#ifdef OJPEG_SUPPORT
if(t2p->pdf_ojpegdata != NULL){
_TIFFfree( (tdata_t) t2p->pdf_ojpegdata);
}
#endif
_TIFFfree( (tdata_t) t2p );
}
return;
}
/*
This function validates the values of a T2P context struct pointer
before calling t2p_write_pdf with it.
*/
static void t2p_validate(T2P* t2p){
#ifdef JPEG_SUPPORT
if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){
if(t2p->pdf_defaultcompressionquality<100 ||
t2p->pdf_defaultcompressionquality<1){
t2p->pdf_defaultcompressionquality=0;
}
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->pdf_defaultcompression==T2P_COMPRESS_ZIP){
switch (t2p->pdf_defaultcompressionquality){
case 1: case 10: case 11: case 12: case 13: case 14: case 15:
case 101: case 110: case 111: case 112: case 113: case 114: case 115:
case 201: case 210: case 211: case 212: case 213: case 214: case 215:
case 301: case 310: case 311: case 312: case 313: case 314: case 315:
case 401: case 410: case 411: case 412: case 413: case 414: case 415:
case 501: case 510: case 511: case 512: case 513: case 514: case 515:
case 601: case 610: case 611: case 612: case 613: case 614: case 615:
case 701: case 710: case 711: case 712: case 713: case 714: case 715:
case 801: case 810: case 811: case 812: case 813: case 814: case 815:
case 901: case 910: case 911: case 912: case 913: case 914: case 915:
break;
default:
t2p->pdf_defaultcompressionquality=0;
}
if(t2p->pdf_defaultcompressionquality%100 !=0){
TIFFError(
TIFF2PDF_MODULE,
"PNG Group predictor differencing not implemented, assuming compression quality %u",
t2p->pdf_defaultcompressionquality);
}
t2p->pdf_defaultcompressionquality%=100;
if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;}
}
#endif
(void)0;
return;
}
/*
This function scans the input TIFF file for pages. It attempts
to determine which IFD's of the TIFF file contain image document
pages. For each, it gathers some information that has to do
with the output of the PDF document as a whole.
*/
static void t2p_read_tiff_init(T2P* t2p, TIFF* input){
tdir_t directorycount=0;
tdir_t i=0;
uint16 pagen=0;
uint16 paged=0;
uint16 xuint16=0;
directorycount=TIFFNumberOfDirectories(input);
t2p->tiff_pages = (T2P_PAGE*) _TIFFmalloc(directorycount * sizeof(T2P_PAGE));
if(t2p->tiff_pages==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for tiff_pages array, %s",
directorycount * (int)sizeof(T2P_PAGE),
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
_TIFFmemset( t2p->tiff_pages, 0x00, directorycount * sizeof(T2P_PAGE));
t2p->tiff_tiles = (T2P_TILES*) _TIFFmalloc(directorycount * sizeof(T2P_TILES));
if(t2p->tiff_tiles==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for tiff_tiles array, %s",
directorycount * (int)sizeof(T2P_TILES),
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
_TIFFmemset( t2p->tiff_tiles, 0x00, directorycount * sizeof(T2P_TILES));
for(i=0;i<directorycount;i++){
uint32 subfiletype = 0;
if(!TIFFSetDirectory(input, i)){
TIFFError(
TIFF2PDF_MODULE,
"Can't set directory %u of input file %s",
i,
TIFFFileName(input));
return;
}
if(TIFFGetField(input, TIFFTAG_PAGENUMBER, &pagen, &paged)){
if((pagen>paged) && (paged != 0)){
t2p->tiff_pages[t2p->tiff_pagecount].page_number =
paged;
} else {
t2p->tiff_pages[t2p->tiff_pagecount].page_number =
pagen;
}
goto ispage2;
}
if(TIFFGetField(input, TIFFTAG_SUBFILETYPE, &subfiletype)){
if ( ((subfiletype & FILETYPE_PAGE) != 0)
|| (subfiletype == 0)){
goto ispage;
} else {
goto isnotpage;
}
}
if(TIFFGetField(input, TIFFTAG_OSUBFILETYPE, &subfiletype)){
if ((subfiletype == OFILETYPE_IMAGE)
|| (subfiletype == OFILETYPE_PAGE)
|| (subfiletype == 0) ){
goto ispage;
} else {
goto isnotpage;
}
}
ispage:
t2p->tiff_pages[t2p->tiff_pagecount].page_number=t2p->tiff_pagecount;
ispage2:
t2p->tiff_pages[t2p->tiff_pagecount].page_directory=i;
if(TIFFIsTiled(input)){
t2p->tiff_pages[t2p->tiff_pagecount].page_tilecount =
TIFFNumberOfTiles(input);
}
t2p->tiff_pagecount++;
isnotpage:
(void)0;
}
qsort((void*) t2p->tiff_pages, t2p->tiff_pagecount,
sizeof(T2P_PAGE), t2p_cmp_t2p_page);
for(i=0;i<t2p->tiff_pagecount;i++){
t2p->pdf_xrefcount += 5;
TIFFSetDirectory(input, t2p->tiff_pages[i].page_directory );
if((TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &xuint16)
&& (xuint16==PHOTOMETRIC_PALETTE))
|| TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)) {
t2p->tiff_pages[i].page_extra++;
t2p->pdf_xrefcount++;
}
#ifdef ZIP_SUPPORT
if (TIFFGetField(input, TIFFTAG_COMPRESSION, &xuint16)) {
if( (xuint16== COMPRESSION_DEFLATE ||
xuint16== COMPRESSION_ADOBE_DEFLATE) &&
((t2p->tiff_pages[i].page_tilecount != 0)
|| TIFFNumberOfStrips(input)==1) &&
(t2p->pdf_nopassthrough==0) ){
if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;}
}
}
#endif
if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION,
&(t2p->tiff_transferfunction[0]),
&(t2p->tiff_transferfunction[1]),
&(t2p->tiff_transferfunction[2]))) {
if(t2p->tiff_transferfunction[1] !=
t2p->tiff_transferfunction[0]) {
t2p->tiff_transferfunctioncount = 3;
t2p->tiff_pages[i].page_extra += 4;
t2p->pdf_xrefcount += 4;
} else {
t2p->tiff_transferfunctioncount = 1;
t2p->tiff_pages[i].page_extra += 2;
t2p->pdf_xrefcount += 2;
}
if(t2p->pdf_minorversion < 2)
t2p->pdf_minorversion = 2;
} else {
t2p->tiff_transferfunctioncount=0;
}
if( TIFFGetField(
input,
TIFFTAG_ICCPROFILE,
&(t2p->tiff_iccprofilelength),
&(t2p->tiff_iccprofile)) != 0){
t2p->tiff_pages[i].page_extra++;
t2p->pdf_xrefcount++;
if(t2p->pdf_minorversion<3){t2p->pdf_minorversion=3;}
}
t2p->tiff_tiles[i].tiles_tilecount=
t2p->tiff_pages[i].page_tilecount;
if( (TIFFGetField(input, TIFFTAG_PLANARCONFIG, &xuint16) != 0)
&& (xuint16 == PLANARCONFIG_SEPARATE ) ){
TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &xuint16);
t2p->tiff_tiles[i].tiles_tilecount/= xuint16;
}
if( t2p->tiff_tiles[i].tiles_tilecount > 0){
t2p->pdf_xrefcount +=
(t2p->tiff_tiles[i].tiles_tilecount -1)*2;
TIFFGetField(input,
TIFFTAG_TILEWIDTH,
&( t2p->tiff_tiles[i].tiles_tilewidth) );
TIFFGetField(input,
TIFFTAG_TILELENGTH,
&( t2p->tiff_tiles[i].tiles_tilelength) );
t2p->tiff_tiles[i].tiles_tiles =
(T2P_TILE*) _TIFFmalloc(
t2p->tiff_tiles[i].tiles_tilecount
* sizeof(T2P_TILE) );
if( t2p->tiff_tiles[i].tiles_tiles == NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_read_tiff_init, %s",
t2p->tiff_tiles[i].tiles_tilecount * (int)sizeof(T2P_TILE),
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
}
}
return;
}
/*
This function is used by qsort to sort a T2P_PAGE* array of page structures by page number.
*/
static int t2p_cmp_t2p_page(const void* e1, const void* e2){
return( ((T2P_PAGE*)e1)->page_number - ((T2P_PAGE*)e2)->page_number );
}
/*
This function sets the input directory to the directory of a given
page and determines information about the image. It checks
the image characteristics to determine if it is possible to convert
the image data into a page of PDF output, setting values of the T2P
struct for this page. It determines what color space is used in
the output PDF to represent the image.
It determines if the image can be converted as raw data without
requiring transcoding of the image data.
*/
static void t2p_read_tiff_data(T2P* t2p, TIFF* input){
int i=0;
uint16* r;
uint16* g;
uint16* b;
uint16* a;
uint16 xuint16;
uint16* xuint16p;
float* xfloatp;
t2p->pdf_transcode = T2P_TRANSCODE_ENCODE;
t2p->pdf_sample = T2P_SAMPLE_NOTHING;
t2p->pdf_switchdecode = t2p->pdf_colorspace_invert;
TIFFSetDirectory(input, t2p->tiff_pages[t2p->pdf_page].page_directory);
TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &(t2p->tiff_width));
if(t2p->tiff_width == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with zero width",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
TIFFGetField(input, TIFFTAG_IMAGELENGTH, &(t2p->tiff_length));
if(t2p->tiff_length == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with zero length",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(TIFFGetField(input, TIFFTAG_COMPRESSION, &(t2p->tiff_compression)) == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with no compression tag",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if( TIFFIsCODECConfigured(t2p->tiff_compression) == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with compression type %u: not configured",
TIFFFileName(input),
t2p->tiff_compression
);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
TIFFGetFieldDefaulted(input, TIFFTAG_BITSPERSAMPLE, &(t2p->tiff_bitspersample));
switch(t2p->tiff_bitspersample){
case 1:
case 2:
case 4:
case 8:
break;
case 0:
TIFFWarning(
TIFF2PDF_MODULE,
"Image %s has 0 bits per sample, assuming 1",
TIFFFileName(input));
t2p->tiff_bitspersample=1;
break;
default:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with %u bits per sample",
TIFFFileName(input),
t2p->tiff_bitspersample);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
TIFFGetFieldDefaulted(input, TIFFTAG_SAMPLESPERPIXEL, &(t2p->tiff_samplesperpixel));
if(t2p->tiff_samplesperpixel>4){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with %u samples per pixel",
TIFFFileName(input),
t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(t2p->tiff_samplesperpixel==0){
TIFFWarning(
TIFF2PDF_MODULE,
"Image %s has 0 samples per pixel, assuming 1",
TIFFFileName(input));
t2p->tiff_samplesperpixel=1;
}
if(TIFFGetField(input, TIFFTAG_SAMPLEFORMAT, &xuint16) != 0 ){
switch(xuint16){
case 0:
case 1:
case 4:
break;
default:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with sample format %u",
TIFFFileName(input),
xuint16);
t2p->t2p_error = T2P_ERR_ERROR;
return;
break;
}
}
TIFFGetFieldDefaulted(input, TIFFTAG_FILLORDER, &(t2p->tiff_fillorder));
if(TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &(t2p->tiff_photometric)) == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with no photometric interpretation tag",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
switch(t2p->tiff_photometric){
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
if (t2p->tiff_bitspersample==1){
t2p->pdf_colorspace=T2P_CS_BILEVEL;
if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){
t2p->pdf_switchdecode ^= 1;
}
} else {
t2p->pdf_colorspace=T2P_CS_GRAY;
if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){
t2p->pdf_switchdecode ^= 1;
}
}
break;
case PHOTOMETRIC_RGB:
t2p->pdf_colorspace=T2P_CS_RGB;
if(t2p->tiff_samplesperpixel == 3){
break;
}
if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){
if(xuint16==1)
goto photometric_palette;
}
if(t2p->tiff_samplesperpixel > 3) {
if(t2p->tiff_samplesperpixel == 4) {
t2p->pdf_colorspace = T2P_CS_RGB;
if(TIFFGetField(input,
TIFFTAG_EXTRASAMPLES,
&xuint16, &xuint16p)
&& xuint16 == 1) {
if(xuint16p[0] == EXTRASAMPLE_ASSOCALPHA){
t2p->pdf_sample=T2P_SAMPLE_RGBAA_TO_RGB;
break;
}
if(xuint16p[0] == EXTRASAMPLE_UNASSALPHA){
t2p->pdf_sample=T2P_SAMPLE_RGBA_TO_RGB;
break;
}
TIFFWarning(
TIFF2PDF_MODULE,
"RGB image %s has 4 samples per pixel, assuming RGBA",
TIFFFileName(input));
break;
}
t2p->pdf_colorspace=T2P_CS_CMYK;
t2p->pdf_switchdecode ^= 1;
TIFFWarning(
TIFF2PDF_MODULE,
"RGB image %s has 4 samples per pixel, assuming inverse CMYK",
TIFFFileName(input));
break;
} else {
TIFFError(
TIFF2PDF_MODULE,
"No support for RGB image %s with %u samples per pixel",
TIFFFileName(input),
t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
break;
}
} else {
TIFFError(
TIFF2PDF_MODULE,
"No support for RGB image %s with %u samples per pixel",
TIFFFileName(input),
t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
break;
}
case PHOTOMETRIC_PALETTE:
photometric_palette:
if(t2p->tiff_samplesperpixel!=1){
TIFFError(
TIFF2PDF_MODULE,
"No support for palettized image %s with not one sample per pixel",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p->pdf_colorspace=T2P_CS_RGB | T2P_CS_PALETTE;
t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample;
if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b)){
TIFFError(
TIFF2PDF_MODULE,
"Palettized image %s has no color map",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(t2p->pdf_palette != NULL){
_TIFFfree(t2p->pdf_palette);
t2p->pdf_palette=NULL;
}
t2p->pdf_palette = (unsigned char*)
_TIFFmalloc(t2p->pdf_palettesize*3);
if(t2p->pdf_palette==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_read_tiff_image, %s",
t2p->pdf_palettesize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
for(i=0;i<t2p->pdf_palettesize;i++){
t2p->pdf_palette[(i*3)] = (unsigned char) (r[i]>>8);
t2p->pdf_palette[(i*3)+1]= (unsigned char) (g[i]>>8);
t2p->pdf_palette[(i*3)+2]= (unsigned char) (b[i]>>8);
}
t2p->pdf_palettesize *= 3;
break;
case PHOTOMETRIC_SEPARATED:
if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){
if(xuint16==1){
goto photometric_palette_cmyk;
}
}
if( TIFFGetField(input, TIFFTAG_INKSET, &xuint16) ){
if(xuint16 != INKSET_CMYK){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s because its inkset is not CMYK",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
}
if(t2p->tiff_samplesperpixel==4){
t2p->pdf_colorspace=T2P_CS_CMYK;
} else {
TIFFError(
TIFF2PDF_MODULE,
"No support for %s because it has %u samples per pixel",
TIFFFileName(input),
t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
break;
photometric_palette_cmyk:
if(t2p->tiff_samplesperpixel!=1){
TIFFError(
TIFF2PDF_MODULE,
"No support for palettized CMYK image %s with not one sample per pixel",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p->pdf_colorspace=T2P_CS_CMYK | T2P_CS_PALETTE;
t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample;
if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b, &a)){
TIFFError(
TIFF2PDF_MODULE,
"Palettized image %s has no color map",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(t2p->pdf_palette != NULL){
_TIFFfree(t2p->pdf_palette);
t2p->pdf_palette=NULL;
}
t2p->pdf_palette = (unsigned char*)
_TIFFmalloc(t2p->pdf_palettesize*4);
if(t2p->pdf_palette==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_read_tiff_image, %s",
t2p->pdf_palettesize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
for(i=0;i<t2p->pdf_palettesize;i++){
t2p->pdf_palette[(i*4)] = (unsigned char) (r[i]>>8);
t2p->pdf_palette[(i*4)+1]= (unsigned char) (g[i]>>8);
t2p->pdf_palette[(i*4)+2]= (unsigned char) (b[i]>>8);
t2p->pdf_palette[(i*4)+2]= (unsigned char) (a[i]>>8);
}
t2p->pdf_palettesize *= 4;
break;
case PHOTOMETRIC_YCBCR:
t2p->pdf_colorspace=T2P_CS_RGB;
if(t2p->tiff_samplesperpixel==1){
t2p->pdf_colorspace=T2P_CS_GRAY;
t2p->tiff_photometric=PHOTOMETRIC_MINISBLACK;
break;
}
t2p->pdf_sample=T2P_SAMPLE_YCBCR_TO_RGB;
#ifdef JPEG_SUPPORT
if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){
t2p->pdf_sample=T2P_SAMPLE_NOTHING;
}
#endif
break;
case PHOTOMETRIC_CIELAB:
t2p->pdf_labrange[0]= -127;
t2p->pdf_labrange[1]= 127;
t2p->pdf_labrange[2]= -127;
t2p->pdf_labrange[3]= 127;
t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED;
t2p->pdf_colorspace=T2P_CS_LAB;
break;
case PHOTOMETRIC_ICCLAB:
t2p->pdf_labrange[0]= 0;
t2p->pdf_labrange[1]= 255;
t2p->pdf_labrange[2]= 0;
t2p->pdf_labrange[3]= 255;
t2p->pdf_colorspace=T2P_CS_LAB;
break;
case PHOTOMETRIC_ITULAB:
t2p->pdf_labrange[0]=-85;
t2p->pdf_labrange[1]=85;
t2p->pdf_labrange[2]=-75;
t2p->pdf_labrange[3]=124;
t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED;
t2p->pdf_colorspace=T2P_CS_LAB;
break;
case PHOTOMETRIC_LOGL:
case PHOTOMETRIC_LOGLUV:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with photometric interpretation LogL/LogLuv",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
default:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with photometric interpretation %u",
TIFFFileName(input),
t2p->tiff_photometric);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(TIFFGetField(input, TIFFTAG_PLANARCONFIG, &(t2p->tiff_planar))){
switch(t2p->tiff_planar){
case 0:
TIFFWarning(
TIFF2PDF_MODULE,
"Image %s has planar configuration 0, assuming 1",
TIFFFileName(input));
t2p->tiff_planar=PLANARCONFIG_CONTIG;
case PLANARCONFIG_CONTIG:
break;
case PLANARCONFIG_SEPARATE:
t2p->pdf_sample=T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG;
if(t2p->tiff_bitspersample!=8){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with separated planar configuration and %u bits per sample",
TIFFFileName(input),
t2p->tiff_bitspersample);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
break;
default:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with planar configuration %u",
TIFFFileName(input),
t2p->tiff_planar);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
}
TIFFGetFieldDefaulted(input, TIFFTAG_ORIENTATION,
&(t2p->tiff_orientation));
if(t2p->tiff_orientation>8){
TIFFWarning(TIFF2PDF_MODULE,
"Image %s has orientation %u, assuming 0",
TIFFFileName(input), t2p->tiff_orientation);
t2p->tiff_orientation=0;
}
if(TIFFGetField(input, TIFFTAG_XRESOLUTION, &(t2p->tiff_xres) ) == 0){
t2p->tiff_xres=0.0;
}
if(TIFFGetField(input, TIFFTAG_YRESOLUTION, &(t2p->tiff_yres) ) == 0){
t2p->tiff_yres=0.0;
}
TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT, &(t2p->tiff_resunit) );
if(t2p->tiff_resunit==RESUNIT_CENTIMETER){
t2p->tiff_xres*=2.54F;
t2p->tiff_yres*=2.54F;
} else if (t2p->tiff_resunit!=RESUNIT_INCH && t2p->pdf_centimeters!=0){
t2p->tiff_xres*=2.54F;
t2p->tiff_yres*=2.54F;
}
t2p_compose_pdf_page(t2p);
t2p->pdf_transcode = T2P_TRANSCODE_ENCODE;
if(t2p->pdf_nopassthrough==0){
#ifdef CCITT_SUPPORT
if(t2p->tiff_compression==COMPRESSION_CCITTFAX4
){
if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){
t2p->pdf_transcode = T2P_TRANSCODE_RAW;
t2p->pdf_compression=T2P_COMPRESS_G4;
}
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->tiff_compression== COMPRESSION_ADOBE_DEFLATE
|| t2p->tiff_compression==COMPRESSION_DEFLATE){
if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){
t2p->pdf_transcode = T2P_TRANSCODE_RAW;
t2p->pdf_compression=T2P_COMPRESS_ZIP;
}
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_OJPEG){
t2p->pdf_transcode = T2P_TRANSCODE_RAW;
t2p->pdf_compression=T2P_COMPRESS_JPEG;
t2p_process_ojpeg_tables(t2p, input);
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_JPEG){
t2p->pdf_transcode = T2P_TRANSCODE_RAW;
t2p->pdf_compression=T2P_COMPRESS_JPEG;
}
#endif
(void)0;
}
if(t2p->pdf_transcode!=T2P_TRANSCODE_RAW){
t2p->pdf_compression = t2p->pdf_defaultcompression;
}
#ifdef JPEG_SUPPORT
if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){
if(t2p->pdf_colorspace & T2P_CS_PALETTE){
t2p->pdf_sample|=T2P_SAMPLE_REALIZE_PALETTE;
t2p->pdf_colorspace ^= T2P_CS_PALETTE;
t2p->tiff_pages[t2p->pdf_page].page_extra--;
}
}
if(t2p->tiff_compression==COMPRESSION_JPEG){
if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with JPEG compression and separated planar configuration",
TIFFFileName(input));
t2p->t2p_error=T2P_ERR_ERROR;
return;
}
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_OJPEG){
if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with OJPEG compression and separated planar configuration",
TIFFFileName(input));
t2p->t2p_error=T2P_ERR_ERROR;
return;
}
}
#endif
if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){
if(t2p->pdf_colorspace & T2P_CS_CMYK){
t2p->tiff_samplesperpixel=4;
t2p->tiff_photometric=PHOTOMETRIC_SEPARATED;
} else {
t2p->tiff_samplesperpixel=3;
t2p->tiff_photometric=PHOTOMETRIC_RGB;
}
}
if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION,
&(t2p->tiff_transferfunction[0]),
&(t2p->tiff_transferfunction[1]),
&(t2p->tiff_transferfunction[2]))) {
if(t2p->tiff_transferfunction[1] !=
t2p->tiff_transferfunction[0]) {
t2p->tiff_transferfunctioncount=3;
} else {
t2p->tiff_transferfunctioncount=1;
}
} else {
t2p->tiff_transferfunctioncount=0;
}
if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp)!=0){
t2p->tiff_whitechromaticities[0]=xfloatp[0];
t2p->tiff_whitechromaticities[1]=xfloatp[1];
if(t2p->pdf_colorspace & T2P_CS_GRAY){
t2p->pdf_colorspace |= T2P_CS_CALGRAY;
}
if(t2p->pdf_colorspace & T2P_CS_RGB){
t2p->pdf_colorspace |= T2P_CS_CALRGB;
}
}
if(TIFFGetField(input, TIFFTAG_PRIMARYCHROMATICITIES, &xfloatp)!=0){
t2p->tiff_primarychromaticities[0]=xfloatp[0];
t2p->tiff_primarychromaticities[1]=xfloatp[1];
t2p->tiff_primarychromaticities[2]=xfloatp[2];
t2p->tiff_primarychromaticities[3]=xfloatp[3];
t2p->tiff_primarychromaticities[4]=xfloatp[4];
t2p->tiff_primarychromaticities[5]=xfloatp[5];
if(t2p->pdf_colorspace & T2P_CS_RGB){
t2p->pdf_colorspace |= T2P_CS_CALRGB;
}
}
if(t2p->pdf_colorspace & T2P_CS_LAB){
if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp) != 0){
t2p->tiff_whitechromaticities[0]=xfloatp[0];
t2p->tiff_whitechromaticities[1]=xfloatp[1];
} else {
t2p->tiff_whitechromaticities[0]=0.3457F; /* 0.3127F; */
t2p->tiff_whitechromaticities[1]=0.3585F; /* 0.3290F; */
}
}
if(TIFFGetField(input,
TIFFTAG_ICCPROFILE,
&(t2p->tiff_iccprofilelength),
&(t2p->tiff_iccprofile))!=0){
t2p->pdf_colorspace |= T2P_CS_ICCBASED;
} else {
t2p->tiff_iccprofilelength=0;
t2p->tiff_iccprofile=NULL;
}
#ifdef CCITT_SUPPORT
if( t2p->tiff_bitspersample==1 &&
t2p->tiff_samplesperpixel==1){
t2p->pdf_compression = T2P_COMPRESS_G4;
}
#endif
return;
}
/*
This function returns the necessary size of a data buffer to contain the raw or
uncompressed image data from the input TIFF for a page.
*/
static void t2p_read_tiff_size(T2P* t2p, TIFF* input){
uint32* sbc=NULL;
#if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT)
unsigned char* jpt=NULL;
uint32 xuint32=0;
tstrip_t i=0;
tstrip_t stripcount=0;
#endif
#ifdef OJPEG_SUPPORT
tsize_t k = 0;
#endif
if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){
#ifdef CCITT_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_G4 ){
TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc);
t2p->tiff_datasize=sbc[0];
return;
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc);
t2p->tiff_datasize=sbc[0];
return;
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_OJPEG){
if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){
TIFFError(TIFF2PDF_MODULE,
"Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
k += sbc[i];
}
if(TIFFGetField(input, TIFFTAG_JPEGIFOFFSET, &(t2p->tiff_dataoffset))){
if(t2p->tiff_dataoffset != 0){
if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){
if(t2p->tiff_datasize < k) {
t2p->pdf_ojpegiflength=t2p->tiff_datasize;
t2p->tiff_datasize+=k;
t2p->tiff_datasize+=6;
t2p->tiff_datasize+=2*stripcount;
TIFFWarning(TIFF2PDF_MODULE,
"Input file %s has short JPEG interchange file byte count",
TIFFFileName(input));
return;
}
return;
}else {
TIFFError(TIFF2PDF_MODULE,
"Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
}
}
t2p->tiff_datasize+=k;
t2p->tiff_datasize+=2*stripcount;
t2p->tiff_datasize+=2048;
return;
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_JPEG){
t2p->tiff_datasize = 2048; /* safety margin (actually used!) */
if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint32, &jpt) != 0 ){
if(xuint32>4){
t2p->tiff_datasize+= xuint32;
t2p->tiff_datasize -=2; /* don't use EOI of header */
}
} else {
t2p->tiff_datasize=2; /* SOI for first strip */
}
stripcount=TIFFNumberOfStrips(input);
if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){
TIFFError(TIFF2PDF_MODULE,
"Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
for(i=0;i<stripcount;i++){
t2p->tiff_datasize += sbc[i];
t2p->tiff_datasize -=4; /* don't use SOI or EOI of strip */
}
t2p->tiff_datasize +=2; /* use EOI of last strip */
return;
}
#endif
(void) 0;
}
t2p->tiff_datasize=TIFFScanlineSize(input) * t2p->tiff_length;
if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
t2p->tiff_datasize*= t2p->tiff_samplesperpixel;
}
return;
}
/*
This function returns the necessary size of a data buffer to contain the raw or
uncompressed image data from the input TIFF for a tile of a page.
*/
static void t2p_read_tiff_size_tile(T2P* t2p, TIFF* input, ttile_t tile){
uint32* tbc = NULL;
uint16 edge=0;
#ifdef JPEG_SUPPORT
uint32 xuint32=0;
unsigned char* jpt;
#endif
edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
if(t2p->pdf_transcode==T2P_TRANSCODE_RAW){
if(edge
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
&& !(t2p->pdf_compression==T2P_COMPRESS_JPEG)
#endif
){
t2p->tiff_datasize=TIFFTileSize(input);
return;
} else {
TIFFGetField(input, TIFFTAG_TILEBYTECOUNTS, &tbc);
t2p->tiff_datasize=tbc[tile];
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_OJPEG){
t2p->tiff_datasize+=2048;
return;
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_JPEG){
if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint32, &jpt)!=0){
if(xuint32>4){
t2p->tiff_datasize+=xuint32;
t2p->tiff_datasize-=4; /* don't use EOI of header or SOI of tile */
}
}
}
#endif
return;
}
}
t2p->tiff_datasize=TIFFTileSize(input);
if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
t2p->tiff_datasize*= t2p->tiff_samplesperpixel;
}
return;
}
/*
This functions returns a non-zero value when the tile is on the right edge
and does not have full imaged tile width.
*/
static int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile){
if( ((tile+1) % tiles.tiles_tilecountx == 0)
&& (tiles.tiles_edgetilewidth != 0) ){
return(1);
} else {
return(0);
}
return(0);
}
/*
This functions returns a non-zero value when the tile is on the bottom edge
and does not have full imaged tile length.
*/
static int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile){
if( ((tile+1) > (tiles.tiles_tilecount-tiles.tiles_tilecountx) )
&& (tiles.tiles_edgetilelength != 0) ){
return(1);
} else {
return(0);
}
return(0);
}
/*
This function reads the raster image data from the input TIFF for an image and writes
the data to the output PDF XObject image dictionary stream. It returns the amount written
or zero on error.
*/
static tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){
tsize_t written=0;
unsigned char* buffer=NULL;
unsigned char* samplebuffer=NULL;
tsize_t bufferoffset=0;
tsize_t samplebufferoffset=0;
tsize_t read=0;
tstrip_t i=0;
tstrip_t j=0;
tstrip_t stripcount=0;
tsize_t stripsize=0;
tsize_t sepstripcount=0;
tsize_t sepstripsize=0;
#ifdef OJPEG_SUPPORT
toff_t inputoffset=0;
uint16 h_samp=1;
uint16 v_samp=1;
uint16 ri=1;
uint32 rows=0;
#endif
#ifdef JPEG_SUPPORT
unsigned char* jpt;
uint32 xuint32=0;
uint16 xuint16_1=0;
uint16 xuint16_2=0;
float* xfloatp;
uint32* sbc;
unsigned char* stripbuffer;
tsize_t striplength=0;
uint32 max_striplength=0;
#endif
if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){
#ifdef CCITT_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_G4){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
/* make sure is lsb-to-msb bit-endianness fill order */
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
memset(buffer, 0, t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_OJPEG){
if(t2p->tiff_dataoffset != 0){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
memset(buffer, 0, t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(t2p->pdf_ojpegiflength==0){
inputoffset=TIFFSeekFile(input, 0, SEEK_CUR);
TIFFSeekFile(input, t2p->tiff_dataoffset, SEEK_SET);
TIFFReadFile(input, (tdata_t) buffer, t2p->tiff_datasize);
TIFFSeekFile(input, inputoffset, SEEK_SET);
TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
} else {
inputoffset=TIFFSeekFile(input, 0, SEEK_CUR);
TIFFSeekFile(input, t2p->tiff_dataoffset, SEEK_SET);
bufferoffset=TIFFReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength);
t2p->pdf_ojpegiflength=0;
TIFFSeekFile(input, inputoffset, SEEK_SET);
TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp);
buffer[bufferoffset++]= 0xff;
buffer[bufferoffset++]= 0xdd;
buffer[bufferoffset++]= 0x00;
buffer[bufferoffset++]= 0x04;
h_samp*=8;
v_samp*=8;
ri=(t2p->tiff_width+h_samp-1) / h_samp;
TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows);
ri*=(rows+v_samp-1)/v_samp;
buffer[bufferoffset++]= (ri>>8) & 0xff;
buffer[bufferoffset++]= ri & 0xff;
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
if(i != 0 ){
buffer[bufferoffset++]=0xff;
buffer[bufferoffset++]=(0xd0 | ((i-1)%8));
}
bufferoffset+=TIFFReadRawStrip(input,
i,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
}
TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
} else {
if(! t2p->pdf_ojpegdata){
TIFFError(TIFF2PDF_MODULE,
"No support for OJPEG image %s with bad tables",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
memset(buffer, 0, t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
_TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength);
bufferoffset=t2p->pdf_ojpegdatalength;
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
if(i != 0){
buffer[bufferoffset++]=0xff;
buffer[bufferoffset++]=(0xd0 | ((i-1)%8));
}
bufferoffset+=TIFFReadRawStrip(input,
i,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
}
if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){
buffer[bufferoffset++]=0xff;
buffer[bufferoffset++]=0xd9;
}
TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
TIFFError(TIFF2PDF_MODULE,
"No support for OJPEG image %s with no JPEG File Interchange offset",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
return(t2p->tiff_datasize);
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_JPEG){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
memset(buffer, 0, t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint32, &jpt) != 0){
if(xuint32>4){
_TIFFmemcpy(buffer, jpt, xuint32);
bufferoffset+=xuint32-2;
}
}
stripcount=TIFFNumberOfStrips(input);
TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc);
for(i=0;i<stripcount;i++){
if(sbc[i]>max_striplength) max_striplength=sbc[i];
}
stripbuffer=(unsigned char*) _TIFFmalloc(max_striplength);
if(stripbuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
max_striplength,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
for(i=0;i<stripcount;i++){
striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1);
if(!t2p_process_jpeg_strip(
stripbuffer,
&striplength,
buffer,
&bufferoffset,
i,
t2p->tiff_length)){
TIFFError(TIFF2PDF_MODULE,
"Can't process JPEG data in input file %s",
TIFFFileName(input));
_TIFFfree(stripbuffer);
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
}
buffer[bufferoffset++]=0xff;
buffer[bufferoffset++]=0xd9;
TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(stripbuffer);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif
(void)0;
}
if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
memset(buffer, 0, t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
stripsize=TIFFStripSize(input);
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
read =
TIFFReadEncodedStrip(input,
i,
(tdata_t) &buffer[bufferoffset],
stripsize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding strip %u of %s",
i,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
bufferoffset+=read;
}
} else {
if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){
sepstripsize=TIFFStripSize(input);
sepstripcount=TIFFNumberOfStrips(input);
stripsize=sepstripsize*t2p->tiff_samplesperpixel;
stripcount=sepstripcount/t2p->tiff_samplesperpixel;
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
memset(buffer, 0, t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
samplebuffer = (unsigned char*) _TIFFmalloc(stripsize);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
for(i=0;i<stripcount;i++){
samplebufferoffset=0;
for(j=0;j<t2p->tiff_samplesperpixel;j++){
read =
TIFFReadEncodedStrip(input,
i + j*stripcount,
(tdata_t) &(samplebuffer[samplebufferoffset]),
sepstripsize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding strip %u of %s",
i + j*stripcount,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
samplebufferoffset+=read;
}
t2p_sample_planar_separate_to_contig(
t2p,
&(buffer[bufferoffset]),
samplebuffer,
samplebufferoffset);
bufferoffset+=samplebufferoffset;
}
_TIFFfree(samplebuffer);
goto dataready;
}
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
memset(buffer, 0, t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
stripsize=TIFFStripSize(input);
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
read =
TIFFReadEncodedStrip(input,
i,
(tdata_t) &buffer[bufferoffset],
stripsize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding strip %u of %s",
i,
TIFFFileName(input));
_TIFFfree(samplebuffer);
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
bufferoffset+=read;
}
if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){
samplebuffer=(unsigned char*)_TIFFrealloc(
(tdata_t) buffer,
t2p->tiff_datasize * t2p->tiff_samplesperpixel);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
_TIFFfree(buffer);
} else {
buffer=samplebuffer;
t2p->tiff_datasize *= t2p->tiff_samplesperpixel;
}
t2p_sample_realize_palette(t2p, buffer);
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgba_to_rgb(
(tdata_t)buffer,
t2p->tiff_width*t2p->tiff_length);
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb(
(tdata_t)buffer,
t2p->tiff_width*t2p->tiff_length);
}
if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){
samplebuffer=(unsigned char*)_TIFFrealloc(
(tdata_t)buffer,
t2p->tiff_width*t2p->tiff_length*4);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
_TIFFfree(buffer);
return(0);
} else {
buffer=samplebuffer;
}
if(!TIFFReadRGBAImageOriented(
input,
t2p->tiff_width,
t2p->tiff_length,
(uint32*)buffer,
ORIENTATION_TOPLEFT,
0)){
TIFFError(TIFF2PDF_MODULE,
"Can't use TIFFReadRGBAImageOriented to extract RGB image from %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
t2p->tiff_datasize=t2p_sample_abgr_to_rgb(
(tdata_t) buffer,
t2p->tiff_width*t2p->tiff_length);
}
if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){
t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned(
(tdata_t)buffer,
t2p->tiff_width*t2p->tiff_length);
}
}
dataready:
t2p_disable(output);
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width);
TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length);
TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length);
TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
switch(t2p->pdf_compression){
case T2P_COMPRESS_NONE:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
break;
#ifdef CCITT_SUPPORT
case T2P_COMPRESS_G4:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
break;
#endif
#ifdef JPEG_SUPPORT
case T2P_COMPRESS_JPEG:
if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR){
if(TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &xuint16_1, &xuint16_2)!=0){
if(xuint16_1 != 0 && xuint16_2 != 0){
TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, xuint16_1, xuint16_2);
}
}
if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
}
}
if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){
TIFFError(TIFF2PDF_MODULE,
"Unable to use JPEG compression for input %s and output %s",
TIFFFileName(input),
TIFFFileName(output));
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0);
if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
} else {
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
}
}
if(t2p->pdf_colorspace & T2P_CS_GRAY){
(void)0;
}
if(t2p->pdf_colorspace & T2P_CS_CMYK){
(void)0;
}
if(t2p->pdf_defaultcompressionquality != 0){
TIFFSetField(output,
TIFFTAG_JPEGQUALITY,
t2p->pdf_defaultcompressionquality);
}
break;
#endif
#ifdef ZIP_SUPPORT
case T2P_COMPRESS_ZIP:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE);
if(t2p->pdf_defaultcompressionquality%100 != 0){
TIFFSetField(output,
TIFFTAG_PREDICTOR,
t2p->pdf_defaultcompressionquality % 100);
}
if(t2p->pdf_defaultcompressionquality/100 != 0){
TIFFSetField(output,
TIFFTAG_ZIPQUALITY,
(t2p->pdf_defaultcompressionquality / 100));
}
break;
#endif
default:
break;
}
t2p_enable(output);
t2p->outputwritten = 0;
#ifdef JPEG_SUPPORT
if(t2p->pdf_compression==T2P_COMPRESS_JPEG && t2p->tiff_photometric==PHOTOMETRIC_YCBCR){
bufferoffset=TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer,stripsize*stripcount);
} else
#endif
bufferoffset=TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize);
if(buffer != NULL){
_TIFFfree(buffer);
buffer=NULL;
}
if(bufferoffset==(tsize_t)-1){
TIFFError(TIFF2PDF_MODULE,
"Error writing encoded strip to output PDF %s",
TIFFFileName(output));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
written= t2p->outputwritten;
return(written);
}
/*
This function reads the raster image data from the input TIFF for an image tile and writes
the data to the output PDF XObject image dictionary stream for the tile. It returns the
amount written or zero on error.
*/
static tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){
uint16 edge=0;
tsize_t written=0;
unsigned char* buffer=NULL;
tsize_t bufferoffset=0;
unsigned char* samplebuffer=NULL;
tsize_t samplebufferoffset=0;
tsize_t read=0;
uint16 i=0;
ttile_t tilecount=0;
ttile_t septilecount=0;
tsize_t septilesize=0;
#ifdef JPEG_SUPPORT
unsigned char* jpt;
uint16 xuint16_1=0;
uint16 xuint16_2=0;
float* xfloatp;
uint32 xuint32=0;
#endif
edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0)
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
|| (t2p->pdf_compression == T2P_COMPRESS_JPEG)
#endif
)
){
#ifdef CCITT_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_G4){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_OJPEG){
if(! t2p->pdf_ojpegdata){
TIFFError(TIFF2PDF_MODULE,
"No support for OJPEG image %s with "
"bad tables",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory "
"for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
_TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength);
if(edge!=0){
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
buffer[7]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff;
buffer[8]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff;
}
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
buffer[9]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff;
buffer[10]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff;
}
}
bufferoffset=t2p->pdf_ojpegdatalength;
bufferoffset+=TIFFReadRawTile(input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
((unsigned char*)buffer)[bufferoffset++]=0xff;
((unsigned char*)buffer)[bufferoffset++]=0xd9;
TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_JPEG){
unsigned char table_end[2];
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint16_1, &jpt) != 0) {
if(xuint16_1 > 0){
_TIFFmemcpy(buffer, jpt, xuint16_1);
bufferoffset += xuint16_1 - 2;
table_end[0] = buffer[bufferoffset-2];
table_end[1] = buffer[bufferoffset-1];
}
if(xuint16_1 > 0) {
xuint32 = bufferoffset;
bufferoffset += TIFFReadRawTile(
input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset-2]),
-1);
buffer[xuint32-2]=table_end[0];
buffer[xuint32-1]=table_end[1];
} else {
bufferoffset += TIFFReadRawTile(
input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
}
}
TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif
(void)0;
}
if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for "
"t2p_readwrite_pdf_image_tile, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
read = TIFFReadEncodedTile(
input,
tile,
(tdata_t) &buffer[bufferoffset],
t2p->tiff_datasize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
} else {
if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){
septilesize=TIFFTileSize(input);
septilecount=TIFFNumberOfTiles(input);
tilecount=septilecount/t2p->tiff_samplesperpixel;
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
samplebufferoffset=0;
for(i=0;i<t2p->tiff_samplesperpixel;i++){
read =
TIFFReadEncodedTile(input,
tile + i*tilecount,
(tdata_t) &(samplebuffer[samplebufferoffset]),
septilesize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile + i*tilecount,
TIFFFileName(input));
_TIFFfree(samplebuffer);
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
samplebufferoffset+=read;
}
t2p_sample_planar_separate_to_contig(
t2p,
&(buffer[bufferoffset]),
samplebuffer,
samplebufferoffset);
bufferoffset+=samplebufferoffset;
_TIFFfree(samplebuffer);
}
if(buffer==NULL){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
read = TIFFReadEncodedTile(
input,
tile,
(tdata_t) &buffer[bufferoffset],
t2p->tiff_datasize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgba_to_rgb(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){
TIFFError(TIFF2PDF_MODULE,
"No support for YCbCr to RGB in tile for %s",
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){
t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
}
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){
t2p_tile_collapse_left(
buffer,
TIFFTileRowSize(input),
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
t2p_disable(output);
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
TIFFSetField(
output,
TIFFTAG_IMAGEWIDTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
} else {
TIFFSetField(
output,
TIFFTAG_IMAGEWIDTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
}
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
TIFFSetField(
output,
TIFFTAG_IMAGELENGTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
TIFFSetField(
output,
TIFFTAG_ROWSPERSTRIP,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
} else {
TIFFSetField(
output,
TIFFTAG_IMAGELENGTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
TIFFSetField(
output,
TIFFTAG_ROWSPERSTRIP,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
}
TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
switch(t2p->pdf_compression){
case T2P_COMPRESS_NONE:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
break;
#ifdef CCITT_SUPPORT
case T2P_COMPRESS_G4:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
break;
#endif
#ifdef JPEG_SUPPORT
case T2P_COMPRESS_JPEG:
if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR){
if(TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &xuint16_1, &xuint16_2)!=0){
if(xuint16_1 != 0 && xuint16_2 != 0){
TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, xuint16_1, xuint16_2);
}
}
if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
}
}
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */
if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
} else {
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
}
}
if(t2p->pdf_colorspace & T2P_CS_GRAY){
(void)0;
}
if(t2p->pdf_colorspace & T2P_CS_CMYK){
(void)0;
}
if(t2p->pdf_defaultcompressionquality != 0){
TIFFSetField(output,
TIFFTAG_JPEGQUALITY,
t2p->pdf_defaultcompressionquality);
}
break;
#endif
#ifdef ZIP_SUPPORT
case T2P_COMPRESS_ZIP:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE);
if(t2p->pdf_defaultcompressionquality%100 != 0){
TIFFSetField(output,
TIFFTAG_PREDICTOR,
t2p->pdf_defaultcompressionquality % 100);
}
if(t2p->pdf_defaultcompressionquality/100 != 0){
TIFFSetField(output,
TIFFTAG_ZIPQUALITY,
(t2p->pdf_defaultcompressionquality / 100));
}
break;
#endif
default:
break;
}
t2p_enable(output);
t2p->outputwritten = 0;
bufferoffset=TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer, TIFFStripSize(output));
if(buffer != NULL){
_TIFFfree(buffer);
buffer=NULL;
}
if(bufferoffset==-1){
TIFFError(TIFF2PDF_MODULE,
"Error writing encoded tile to output PDF %s",
TIFFFileName(output));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
written= t2p->outputwritten;
return(written);
}
#ifdef OJPEG_SUPPORT
static int t2p_process_ojpeg_tables(T2P* t2p, TIFF* input){
uint16 proc=0;
void* q;
uint32 q_length=0;
void* dc;
uint32 dc_length=0;
void* ac;
uint32 ac_length=0;
uint16* lp;
uint16* pt;
uint16 h_samp=1;
uint16 v_samp=1;
unsigned char* ojpegdata;
uint16 table_count;
uint32 offset_table;
uint32 offset_ms_l;
uint32 code_count;
uint32 i=0;
uint32 dest=0;
uint16 ri=0;
uint32 rows=0;
if(!TIFFGetField(input, TIFFTAG_JPEGPROC, &proc)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGProc field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(proc!=JPEGPROC_BASELINE && proc!=JPEGPROC_LOSSLESS){
TIFFError(TIFF2PDF_MODULE,
"Bad JPEGProc field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(!TIFFGetField(input, TIFFTAG_JPEGQTABLES, &q_length, &q)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGQTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(q_length < (64U * t2p->tiff_samplesperpixel)){
TIFFError(TIFF2PDF_MODULE,
"Bad JPEGQTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(!TIFFGetField(input, TIFFTAG_JPEGDCTABLES, &dc_length, &dc)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGDCTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(proc==JPEGPROC_BASELINE){
if(!TIFFGetField(input, TIFFTAG_JPEGACTABLES, &ac_length, &ac)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGACTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
} else {
if(!TIFFGetField(input, TIFFTAG_JPEGLOSSLESSPREDICTORS, &lp)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGLosslessPredictors field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(!TIFFGetField(input, TIFFTAG_JPEGPOINTTRANSFORM, &pt)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGPointTransform field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
}
if(!TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp)){
h_samp=1;
v_samp=1;
}
if(t2p->pdf_ojpegdata != NULL){
_TIFFfree(t2p->pdf_ojpegdata);
t2p->pdf_ojpegdata=NULL;
}
t2p->pdf_ojpegdata = _TIFFmalloc(2048);
if(t2p->pdf_ojpegdata == NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_process_ojpeg_tables, %s",
2048,
TIFFFileName(input));
return(0);
}
_TIFFmemset(t2p->pdf_ojpegdata, 0x00, 2048);
t2p->pdf_ojpegdatalength = 0;
table_count=t2p->tiff_samplesperpixel;
if(proc==JPEGPROC_BASELINE){
if(table_count>2) table_count=2;
}
ojpegdata=(unsigned char*)t2p->pdf_ojpegdata;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xd8;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
if(proc==JPEGPROC_BASELINE){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc0;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc3;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=(8 + 3*t2p->tiff_samplesperpixel);
ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_bitspersample & 0xff);
if(TIFFIsTiled(input)){
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength ) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth ) & 0xff;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_length >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_length ) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_width >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_width ) & 0xff;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_samplesperpixel & 0xff);
for(i=0;i<t2p->tiff_samplesperpixel;i++){
ojpegdata[t2p->pdf_ojpegdatalength++]=i;
if(i==0){
ojpegdata[t2p->pdf_ojpegdatalength] |= h_samp<<4 & 0xf0;;
ojpegdata[t2p->pdf_ojpegdatalength++] |= v_samp & 0x0f;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]= 0x11;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=i;
}
for(dest=0;dest<t2p->tiff_samplesperpixel;dest++){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xdb;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x43;
ojpegdata[t2p->pdf_ojpegdatalength++]=dest;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength++]),
&(((unsigned char*)q)[64*dest]), 64);
t2p->pdf_ojpegdatalength+=64;
}
offset_table=0;
for(dest=0;dest<table_count;dest++){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4;
offset_ms_l=t2p->pdf_ojpegdatalength;
t2p->pdf_ojpegdatalength+=2;
ojpegdata[t2p->pdf_ojpegdatalength++]=dest & 0x0f;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)dc)[offset_table]), 16);
code_count=0;
offset_table+=16;
for(i=0;i<16;i++){
code_count+=ojpegdata[t2p->pdf_ojpegdatalength++];
}
ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff;
ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)dc)[offset_table]), code_count);
offset_table+=code_count;
t2p->pdf_ojpegdatalength+=code_count;
}
if(proc==JPEGPROC_BASELINE){
offset_table=0;
for(dest=0;dest<table_count;dest++){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4;
offset_ms_l=t2p->pdf_ojpegdatalength;
t2p->pdf_ojpegdatalength+=2;
ojpegdata[t2p->pdf_ojpegdatalength] |= 0x10;
ojpegdata[t2p->pdf_ojpegdatalength++] |=dest & 0x0f;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)ac)[offset_table]), 16);
code_count=0;
offset_table+=16;
for(i=0;i<16;i++){
code_count+=ojpegdata[t2p->pdf_ojpegdatalength++];
}
ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff;
ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)ac)[offset_table]), code_count);
offset_table+=code_count;
t2p->pdf_ojpegdatalength+=code_count;
}
}
if(TIFFNumberOfStrips(input)>1){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xdd;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x04;
h_samp*=8;
v_samp*=8;
ri=(t2p->tiff_width+h_samp-1) / h_samp;
TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows);
ri*=(rows+v_samp-1)/v_samp;
ojpegdata[t2p->pdf_ojpegdatalength++]= (ri>>8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]= ri & 0xff;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xda;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=(6 + 2*t2p->tiff_samplesperpixel);
ojpegdata[t2p->pdf_ojpegdatalength++]=t2p->tiff_samplesperpixel & 0xff;
for(i=0;i<t2p->tiff_samplesperpixel;i++){
ojpegdata[t2p->pdf_ojpegdatalength++]= i & 0xff;
if(proc==JPEGPROC_BASELINE){
ojpegdata[t2p->pdf_ojpegdatalength] |=
( ( (i>(table_count-1U)) ? (table_count-1U) : i) << 4U) & 0xf0;
ojpegdata[t2p->pdf_ojpegdatalength++] |=
( (i>(table_count-1U)) ? (table_count-1U) : i) & 0x0f;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++] = (i << 4) & 0xf0;
}
}
if(proc==JPEGPROC_BASELINE){
t2p->pdf_ojpegdatalength++;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x3f;
t2p->pdf_ojpegdatalength++;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]= (lp[0] & 0xff);
t2p->pdf_ojpegdatalength++;
ojpegdata[t2p->pdf_ojpegdatalength++]= (pt[0] & 0x0f);
}
return(1);
}
#endif
#ifdef JPEG_SUPPORT
static int t2p_process_jpeg_strip(
unsigned char* strip,
tsize_t* striplength,
unsigned char* buffer,
tsize_t* bufferoffset,
tstrip_t no,
uint32 height){
tsize_t i=0;
uint16 ri =0;
uint16 v_samp=1;
uint16 h_samp=1;
int j=0;
i++;
while(i<(*striplength)){
switch( strip[i] ){
case 0xd8:
i+=2;
break;
case 0xc0:
case 0xc1:
case 0xc3:
case 0xc9:
case 0xca:
if(no==0){
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2);
for(j=0;j<buffer[*bufferoffset+9];j++){
if( (buffer[*bufferoffset+11+(2*j)]>>4) > h_samp)
h_samp = (buffer[*bufferoffset+11+(2*j)]>>4);
if( (buffer[*bufferoffset+11+(2*j)] & 0x0f) > v_samp)
v_samp = (buffer[*bufferoffset+11+(2*j)] & 0x0f);
}
v_samp*=8;
h_samp*=8;
ri=((( ((uint16)(buffer[*bufferoffset+5])<<8) |
(uint16)(buffer[*bufferoffset+6]) )+v_samp-1)/
v_samp);
ri*=((( ((uint16)(buffer[*bufferoffset+7])<<8) |
(uint16)(buffer[*bufferoffset+8]) )+h_samp-1)/
h_samp);
buffer[*bufferoffset+5]=
(unsigned char) ((height>>8) & 0xff);
buffer[*bufferoffset+6]=
(unsigned char) (height & 0xff);
*bufferoffset+=strip[i+2]+2;
i+=strip[i+2]+2;
buffer[(*bufferoffset)++]=0xff;
buffer[(*bufferoffset)++]=0xdd;
buffer[(*bufferoffset)++]=0x00;
buffer[(*bufferoffset)++]=0x04;
buffer[(*bufferoffset)++]=(ri >> 8) & 0xff;
buffer[(*bufferoffset)++]= ri & 0xff;
} else {
i+=strip[i+2]+2;
}
break;
case 0xc4:
case 0xdb:
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2);
*bufferoffset+=strip[i+2]+2;
i+=strip[i+2]+2;
break;
case 0xda:
if(no==0){
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2);
*bufferoffset+=strip[i+2]+2;
i+=strip[i+2]+2;
} else {
buffer[(*bufferoffset)++]=0xff;
buffer[(*bufferoffset)++]=
(unsigned char)(0xd0 | ((no-1)%8));
i+=strip[i+2]+2;
}
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), (*striplength)-i-1);
*bufferoffset+=(*striplength)-i-1;
return(1);
default:
i+=strip[i+2]+2;
}
}
return(0);
}
#endif
/*
This functions converts a tilewidth x tilelength buffer of samples into an edgetilewidth x
tilelength buffer of samples.
*/
static void t2p_tile_collapse_left(
tdata_t buffer,
tsize_t scanwidth,
uint32 tilewidth,
uint32 edgetilewidth,
uint32 tilelength){
uint32 i=0;
tsize_t edgescanwidth=0;
edgescanwidth = (scanwidth * edgetilewidth + (tilewidth - 1))/ tilewidth;
for(i=i;i<tilelength;i++){
_TIFFmemcpy(
&(((char*)buffer)[edgescanwidth*i]),
&(((char*)buffer)[scanwidth*i]),
edgescanwidth);
}
return;
}
/*
This function calls TIFFWriteDirectory on the output after blanking its output by replacing the
read, write, and seek procedures with empty implementations, then it replaces the original
implementations.
*/
static void t2p_write_advance_directory(T2P* t2p, TIFF* output){
t2p_disable(output);
if(!TIFFWriteDirectory(output)){
TIFFError(TIFF2PDF_MODULE,
"Error writing virtual directory to output PDF %s",
TIFFFileName(output));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p_enable(output);
return;
}
static tsize_t t2p_sample_planar_separate_to_contig(T2P* t2p,
unsigned char* buffer,
unsigned char* samplebuffer,
tsize_t samplebuffersize){
tsize_t stride=0;
tsize_t i=0;
tsize_t j=0;
stride=samplebuffersize/t2p->tiff_samplesperpixel;
for(i=0;i<stride;i++){
for(j=0;j<t2p->tiff_samplesperpixel;j++){
buffer[i*t2p->tiff_samplesperpixel + j] = samplebuffer[i + j*stride];
}
}
return(samplebuffersize);
}
static tsize_t t2p_sample_realize_palette(T2P* t2p, unsigned char* buffer){
uint32 sample_count=0;
uint16 component_count=0;
uint32 palette_offset=0;
uint32 sample_offset=0;
uint32 i=0;
uint32 j=0;
sample_count=t2p->tiff_width*t2p->tiff_length;
component_count=t2p->tiff_samplesperpixel;
for(i=sample_count;i>0;i--){
palette_offset=buffer[i-1] * component_count;
sample_offset= (i-1) * component_count;
for(j=0;j<component_count;j++){
buffer[sample_offset+j]=t2p->pdf_palette[palette_offset+j];
}
}
return(0);
}
/*
This functions converts in place a buffer of ABGR interleaved data
into RGB interleaved data, discarding A.
*/
static tsize_t t2p_sample_abgr_to_rgb(tdata_t data, uint32 samplecount)
{
uint32 i=0;
uint32 sample=0;
for(i=0;i<samplecount;i++){
sample=((uint32*)data)[i];
((char*)data)[i*3]= (char) (sample & 0xff);
((char*)data)[i*3+1]= (char) ((sample>>8) & 0xff);
((char*)data)[i*3+2]= (char) ((sample>>16) & 0xff);
}
return(i*3);
}
/*
* This functions converts in place a buffer of RGBA interleaved data
* into RGB interleaved data, discarding A.
*/
static tsize_t
t2p_sample_rgbaa_to_rgb(tdata_t data, uint32 samplecount)
{
uint32 i;
for(i = 0; i < samplecount; i++)
memcpy((uint8*)data + i * 3, (uint8*)data + i * 4, 3);
return(i * 3);
}
/*
* This functions converts in place a buffer of RGBA interleaved data
* into RGB interleaved data, adding 255-A to each component sample.
*/
static tsize_t
t2p_sample_rgba_to_rgb(tdata_t data, uint32 samplecount)
{
uint32 i = 0;
uint32 sample = 0;
uint8 alpha = 0;
for (i = 0; i < samplecount; i++) {
sample=((uint32*)data)[i];
alpha=(uint8)((255 - (sample & 0xff)));
((uint8 *)data)[i * 3] = (uint8) ((sample >> 24) & 0xff) + alpha;
((uint8 *)data)[i * 3 + 1] = (uint8) ((sample >> 16) & 0xff) + alpha;
((uint8 *)data)[i * 3 + 2] = (uint8) ((sample >> 8) & 0xff) + alpha;
}
return (i * 3);
}
/*
This function converts the a and b samples of Lab data from signed
to unsigned.
*/
static tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t buffer, uint32 samplecount){
uint32 i=0;
for(i=0;i<samplecount;i++){
if( (((unsigned char*)buffer)[(i*3)+1] & 0x80) !=0){
((unsigned char*)buffer)[(i*3)+1] =
(unsigned char)(0x80 + ((char*)buffer)[(i*3)+1]);
} else {
((unsigned char*)buffer)[(i*3)+1] |= 0x80;
}
if( (((unsigned char*)buffer)[(i*3)+2] & 0x80) !=0){
((unsigned char*)buffer)[(i*3)+2] =
(unsigned char)(0x80 + ((char*)buffer)[(i*3)+2]);
} else {
((unsigned char*)buffer)[(i*3)+2] |= 0x80;
}
}
return(samplecount*3);
}
/*
This function writes the PDF header to output.
*/
static tsize_t t2p_write_pdf_header(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
buflen=sprintf(buffer, "%%PDF-%u.%u ", t2p->pdf_majorversion&0xff, t2p->pdf_minorversion&0xff);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t)"\r%\342\343\317\323\r\n", 8);
return(written);
}
/*
This function writes the beginning of a PDF object to output.
*/
static tsize_t t2p_write_pdf_obj_start(uint32 number, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
buflen=sprintf(buffer, "%lu", (unsigned long)number);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen );
written += TIFFWriteFile(output, (tdata_t) " 0 obj\r", 7);
return(written);
}
/*
This function writes the end of a PDF object to output.
*/
static tsize_t t2p_write_pdf_obj_end(TIFF* output){
tsize_t written=0;
written += TIFFWriteFile(output, (tdata_t) "endobj\r", 7);
return(written);
}
/*
This function writes a PDF string object to output.
*/
static tsize_t t2p_write_pdf_string(char* pdfstr, TIFF* output){
tsize_t written=0;
uint32 i=0;
char buffer[5];
uint32 len=0;
len=strlen(pdfstr);
written += TIFFWriteFile(output, (tdata_t) "(", 1);
for (i=0;i<len;i++){
if((pdfstr[i]&0x80) || (pdfstr[i]==127) || (pdfstr[i]<32)){
sprintf(buffer, "\\%.3o", pdfstr[i]);
written += TIFFWriteFile(output, (tdata_t) buffer, 4);
} else {
switch (pdfstr[i]){
case 0x08:
written += TIFFWriteFile(output, (tdata_t) "\\b", 2);
break;
case 0x09:
written += TIFFWriteFile(output, (tdata_t) "\\t", 2);
break;
case 0x0A:
written += TIFFWriteFile(output, (tdata_t) "\\n", 2);
break;
case 0x0C:
written += TIFFWriteFile(output, (tdata_t) "\\f", 2);
break;
case 0x0D:
written += TIFFWriteFile(output, (tdata_t) "\\r", 2);
break;
case 0x28:
written += TIFFWriteFile(output, (tdata_t) "\\(", 2);
break;
case 0x29:
written += TIFFWriteFile(output, (tdata_t) "\\)", 2);
break;
case 0x5C:
written += TIFFWriteFile(output, (tdata_t) "\\\\", 2);
break;
default:
written += TIFFWriteFile(output, (tdata_t) &pdfstr[i], 1);
}
}
}
written += TIFFWriteFile(output, (tdata_t) ") ", 1);
return(written);
}
/*
This function writes a buffer of data to output.
*/
static tsize_t t2p_write_pdf_stream(tdata_t buffer, tsize_t len, TIFF* output){
tsize_t written=0;
written += TIFFWriteFile(output, (tdata_t) buffer, len);
return(written);
}
/*
This functions writes the beginning of a PDF stream to output.
*/
static tsize_t t2p_write_pdf_stream_start(TIFF* output){
tsize_t written=0;
written += TIFFWriteFile(output, (tdata_t) "stream\r\n", 8);
return(written);
}
/*
This function writes the end of a PDF stream to output.
*/
static tsize_t t2p_write_pdf_stream_end(TIFF* output){
tsize_t written=0;
written += TIFFWriteFile(output, (tdata_t) "\rendstream\r", 11);
return(written);
}
/*
This function writes a stream dictionary for a PDF stream to output.
*/
static tsize_t t2p_write_pdf_stream_dict(tsize_t len, uint32 number, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
written += TIFFWriteFile(output, (tdata_t) "/Length ", 8);
if(len!=0){
written += t2p_write_pdf_stream_length(len, output);
} else {
buflen=sprintf(buffer, "%lu", (unsigned long)number);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6);
}
return(written);
}
/*
This functions writes the beginning of a PDF stream dictionary to output.
*/
static tsize_t t2p_write_pdf_stream_dict_start(TIFF* output){
tsize_t written=0;
written += TIFFWriteFile(output, (tdata_t) "<< \r", 4);
return(written);
}
/*
This function writes the end of a PDF stream dictionary to output.
*/
static tsize_t t2p_write_pdf_stream_dict_end(TIFF* output){
tsize_t written=0;
written += TIFFWriteFile(output, (tdata_t) " >>\r", 4);
return(written);
}
/*
This function writes a number to output.
*/
static tsize_t t2p_write_pdf_stream_length(tsize_t len, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
buflen=sprintf(buffer, "%lu", (unsigned long)len);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
return(written);
}
/*
This function writes the PDF Catalog structure to output.
*/
static tsize_t t2p_write_pdf_catalog(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
written += TIFFWriteFile(output,
(tdata_t)"<< \r/Type /Catalog \r/Pages ",
27);
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_pages);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen );
written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6);
if(t2p->pdf_fitwindow){
written += TIFFWriteFile(output,
(tdata_t) "/ViewerPreferences <</FitWindow true>>\r",
39);
}
written += TIFFWriteFile(output, (tdata_t)">>\r", 3);
return(written);
}
/*
This function writes the PDF Info structure to output.
*/
static tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output){
tsize_t written=0;
char* info;
char buffer[512];
if(t2p->pdf_datetime==NULL){
t2p_pdf_tifftime(t2p, input);
}
if(strlen(t2p->pdf_datetime) > 0){
written += TIFFWriteFile(output, (tdata_t) "<< \r/CreationDate ", 18);
written += t2p_write_pdf_string(t2p->pdf_datetime, output);
written += TIFFWriteFile(output, (tdata_t) "\r/ModDate ", 10);
written += t2p_write_pdf_string(t2p->pdf_datetime, output);
}
written += TIFFWriteFile(output, (tdata_t) "\r/Producer ", 11);
_TIFFmemset((tdata_t)buffer, 0x00, 512);
sprintf(buffer, "libtiff / tiff2pdf - %d / %s",
TIFFLIB_VERSION, T2P_VERSION);
written += t2p_write_pdf_string(buffer, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
if(t2p->pdf_creator != NULL){
if(strlen(t2p->pdf_creator)>0){
if(strlen(t2p->pdf_creator)>511){t2p->pdf_creator[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Creator ", 9);
written += t2p_write_pdf_string(t2p->pdf_creator, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
} else{
if( TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0){
if(strlen(info)>511){info[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Creator ", 9);
written += t2p_write_pdf_string(info, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
}
if(t2p->pdf_author != NULL){
if(strlen(t2p->pdf_author)>0){
if(strlen(t2p->pdf_author)>511){t2p->pdf_author[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Author ", 8);
written += t2p_write_pdf_string(t2p->pdf_author, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
} else{
if( TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0){
if(strlen(info)>511){info[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Author ", 8);
written += t2p_write_pdf_string(info, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
} else if ( TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0){
if(strlen(info)>511){info[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Author ", 8);
written += t2p_write_pdf_string(info, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
}
if(t2p->pdf_title != NULL){
if(strlen(t2p->pdf_title)>0){
if(strlen(t2p->pdf_title)>511){t2p->pdf_title[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Title ", 7);
written += t2p_write_pdf_string(t2p->pdf_title, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
} else{
if( TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0){
if(strlen(info)>511){info[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Title ", 7);
written += t2p_write_pdf_string(info, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
}
if(t2p->pdf_subject != NULL){
if(strlen(t2p->pdf_subject)>0){
if(strlen(t2p->pdf_subject)>511){t2p->pdf_subject[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Subject ", 9);
written += t2p_write_pdf_string(t2p->pdf_subject, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
} else{
if( TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0){
if(strlen(info)>511){info[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Subject ", 9);
written += t2p_write_pdf_string(info, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
}
if(t2p->pdf_keywords != NULL){
if(strlen(t2p->pdf_keywords)>0){
if(strlen(t2p->pdf_keywords)>511){t2p->pdf_keywords[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Keywords ", 10);
written += t2p_write_pdf_string(t2p->pdf_keywords, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
}
written += TIFFWriteFile(output, (tdata_t) ">> \r", 4);
return(written);
}
/*
This function fills a string of a T2P struct with the current time as a PDF date string,
it is called by t2p_pdf_tifftime.
*/
static void t2p_pdf_currenttime(T2P* t2p){
struct tm* currenttime;
time_t timenow;
timenow=time(0);
currenttime=localtime(&timenow);
sprintf(t2p->pdf_datetime, "D:%.4d%.2d%.2d%.2d%.2d%.2d",
(currenttime->tm_year+1900) % 65536,
(currenttime->tm_mon+1) % 256,
(currenttime->tm_mday) % 256,
(currenttime->tm_hour) % 256,
(currenttime->tm_min) % 256,
(currenttime->tm_sec) % 256);
return;
}
/*
This function fills a string of a T2P struct with the date and time of a TIFF file if it
exists or the current time as a PDF date string.
*/
static void t2p_pdf_tifftime(T2P* t2p, TIFF* input){
char* datetime;
t2p->pdf_datetime= (char*) _TIFFmalloc(19);
if(t2p->pdf_datetime==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_pdf_tiff_time",
17);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p->pdf_datetime[16]=0;
if( TIFFGetField(input, TIFFTAG_DATETIME, &datetime) != 0
&& (strlen(datetime) >= 19) ){
t2p->pdf_datetime[0]='D';
t2p->pdf_datetime[1]=':';
t2p->pdf_datetime[2]=datetime[0];
t2p->pdf_datetime[3]=datetime[1];
t2p->pdf_datetime[4]=datetime[2];
t2p->pdf_datetime[5]=datetime[3];
t2p->pdf_datetime[6]=datetime[5];
t2p->pdf_datetime[7]=datetime[6];
t2p->pdf_datetime[8]=datetime[8];
t2p->pdf_datetime[9]=datetime[9];
t2p->pdf_datetime[10]=datetime[11];
t2p->pdf_datetime[11]=datetime[12];
t2p->pdf_datetime[12]=datetime[14];
t2p->pdf_datetime[13]=datetime[15];
t2p->pdf_datetime[14]=datetime[17];
t2p->pdf_datetime[15]=datetime[18];
} else {
t2p_pdf_currenttime(t2p);
}
return;
}
/*
This function writes a PDF Pages Tree structure to output.
*/
static tsize_t t2p_write_pdf_pages(T2P* t2p,
TIFF* output){
tsize_t written=0;
tdir_t i=0;
char buffer[16];
int buflen=0;
int page=0;
written += TIFFWriteFile(output,
(tdata_t) "<< \r/Type /Pages \r/Kids [ ",
26);
page = t2p->pdf_pages+1;
for (i=0;i<t2p->tiff_pagecount;i++){
buflen=sprintf(buffer, "%d", page);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
if ( ((i+1)%8)==0 ) {
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
page +=3;
page += t2p->tiff_pages[i].page_extra;
if(t2p->tiff_pages[i].page_tilecount>0){
page += (2 * t2p->tiff_pages[i].page_tilecount);
} else {
page +=2;
}
}
written += TIFFWriteFile(output, (tdata_t) "] \r/Count ", 10);
_TIFFmemset(buffer, 0x00, 16);
buflen=sprintf(buffer, "%d", t2p->tiff_pagecount);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " \r>> \r", 6);
return(written);
}
/*
This function writes a PDF Page structure to output.
*/
static tsize_t t2p_write_pdf_page(uint32 object, T2P* t2p, TIFF* output){
unsigned int i=0;
tsize_t written=0;
char buffer[16];
int buflen=0;
written += TIFFWriteFile(output, (tdata_t) "<<\r/Type /Page \r/Parent ", 24);
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_pages);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6);
written += TIFFWriteFile(output, (tdata_t) "/MediaBox [", 11);
buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.x1);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " ", 1);
buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.y1);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " ", 1);
buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.x2);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " ", 1);
buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.y2);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "] \r", 3);
written += TIFFWriteFile(output, (tdata_t) "/Contents ", 10);
buflen=sprintf(buffer, "%lu", (unsigned long)(object + 1));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6);
written += TIFFWriteFile(output, (tdata_t) "/Resources << \r", 15);
if( t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0 ){
written += TIFFWriteFile(output, (tdata_t) "/XObject <<\r", 12);
for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i++){
written += TIFFWriteFile(output, (tdata_t) "/Im", 3);
buflen = sprintf(buffer, "%u", t2p->pdf_page+1);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "_", 1);
buflen = sprintf(buffer, "%u", i+1);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " ", 1);
buflen = sprintf(
buffer,
"%lu",
(unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
if(i%4==3){
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
}
written += TIFFWriteFile(output, (tdata_t) ">>\r", 3);
} else {
written += TIFFWriteFile(output, (tdata_t) "/XObject <<\r", 12);
written += TIFFWriteFile(output, (tdata_t) "/Im", 3);
buflen = sprintf(buffer, "%u", t2p->pdf_page+1);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " ", 1);
buflen = sprintf(
buffer,
"%lu",
(unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
written += TIFFWriteFile(output, (tdata_t) ">>\r", 3);
}
if(t2p->tiff_transferfunctioncount != 0) {
written += TIFFWriteFile(output, (tdata_t) "/ExtGState <<", 13);
TIFFWriteFile(output, (tdata_t) "/GS1 ", 5);
buflen = sprintf(
buffer,
"%lu",
(unsigned long)(object + 3));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
written += TIFFWriteFile(output, (tdata_t) ">> \r", 4);
}
written += TIFFWriteFile(output, (tdata_t) "/ProcSet [ ", 11);
if(t2p->pdf_colorspace == T2P_CS_BILEVEL
|| t2p->pdf_colorspace == T2P_CS_GRAY
){
written += TIFFWriteFile(output, (tdata_t) "/ImageB ", 8);
} else {
written += TIFFWriteFile(output, (tdata_t) "/ImageC ", 8);
if(t2p->pdf_colorspace & T2P_CS_PALETTE){
written += TIFFWriteFile(output, (tdata_t) "/ImageI ", 8);
}
}
written += TIFFWriteFile(output, (tdata_t) "]\r>>\r>>\r", 8);
return(written);
}
/*
This function composes the page size and image and tile locations on a page.
*/
static void t2p_compose_pdf_page(T2P* t2p){
uint32 i=0;
uint32 i2=0;
T2P_TILE* tiles=NULL;
T2P_BOX* boxp=NULL;
uint32 tilecountx=0;
uint32 tilecounty=0;
uint32 tilewidth=0;
uint32 tilelength=0;
int istiled=0;
float f=0;
t2p->pdf_xres = t2p->tiff_xres;
t2p->pdf_yres = t2p->tiff_yres;
if(t2p->pdf_overrideres){
t2p->pdf_xres = t2p->pdf_defaultxres;
t2p->pdf_yres = t2p->pdf_defaultyres;
}
if(t2p->pdf_xres==0.0){
t2p->pdf_xres = t2p->pdf_defaultxres;
}
if(t2p->pdf_yres==0.0){
t2p->pdf_yres = t2p->pdf_defaultyres;
}
t2p->pdf_imagewidth=((float)(t2p->tiff_width)) *72.0F / t2p->pdf_xres;
t2p->pdf_imagelength=((float)(t2p->tiff_length)) *72.0F / t2p->pdf_yres;
if(t2p->pdf_overridepagesize != 0){
t2p->pdf_pagewidth = t2p->pdf_defaultpagewidth;
t2p->pdf_pagelength = t2p->pdf_defaultpagelength;
} else {
t2p->pdf_pagewidth = t2p->pdf_imagewidth;
t2p->pdf_pagelength = t2p->pdf_imagelength;
}
t2p->pdf_mediabox.x1=0.0;
t2p->pdf_mediabox.y1=0.0;
t2p->pdf_mediabox.x2=t2p->pdf_pagewidth;
t2p->pdf_mediabox.y2=t2p->pdf_pagelength;
t2p->pdf_imagebox.x1=0.0;
t2p->pdf_imagebox.y1=0.0;
t2p->pdf_imagebox.x2=t2p->pdf_imagewidth;
t2p->pdf_imagebox.y2=t2p->pdf_imagelength;
if(t2p->pdf_overridepagesize!=0){
t2p->pdf_imagebox.x1+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F);
t2p->pdf_imagebox.y1+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F);
t2p->pdf_imagebox.x2+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F);
t2p->pdf_imagebox.y2+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F);
}
if(t2p->tiff_orientation > 4){
f=t2p->pdf_mediabox.x2;
t2p->pdf_mediabox.x2=t2p->pdf_mediabox.y2;
t2p->pdf_mediabox.y2=f;
}
istiled=((t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount==0) ? 0 : 1;
if(istiled==0){
t2p_compose_pdf_page_orient(&(t2p->pdf_imagebox), t2p->tiff_orientation);
return;
} else {
tilewidth=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilewidth;
tilelength=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilelength;
tilecountx=(t2p->tiff_width +
tilewidth -1)/
tilewidth;
(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecountx=tilecountx;
tilecounty=(t2p->tiff_length +
tilelength -1)/
tilelength;
(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecounty=tilecounty;
(t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilewidth=
t2p->tiff_width % tilewidth;
(t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilelength=
t2p->tiff_length % tilelength;
tiles=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tiles;
for(i2=0;i2<tilecounty-1;i2++){
for(i=0;i<tilecountx-1;i++){
boxp=&(tiles[i2*tilecountx+i].tile_box);
boxp->x1 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * i * tilewidth)
/ (float)t2p->tiff_width);
boxp->x2 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth)
/ (float)t2p->tiff_width);
boxp->y1 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * (i2+1) * tilelength)
/ (float)t2p->tiff_length);
boxp->y2 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * i2 * tilelength)
/ (float)t2p->tiff_length);
}
boxp=&(tiles[i2*tilecountx+i].tile_box);
boxp->x1 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * i * tilewidth)
/ (float)t2p->tiff_width);
boxp->x2 = t2p->pdf_imagebox.x2;
boxp->y1 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * (i2+1) * tilelength)
/ (float)t2p->tiff_length);
boxp->y2 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * i2 * tilelength)
/ (float)t2p->tiff_length);
}
for(i=0;i<tilecountx-1;i++){
boxp=&(tiles[i2*tilecountx+i].tile_box);
boxp->x1 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * i * tilewidth)
/ (float)t2p->tiff_width);
boxp->x2 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth)
/ (float)t2p->tiff_width);
boxp->y1 = t2p->pdf_imagebox.y1;
boxp->y2 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * i2 * tilelength)
/ (float)t2p->tiff_length);
}
boxp=&(tiles[i2*tilecountx+i].tile_box);
boxp->x1 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * i * tilewidth)
/ (float)t2p->tiff_width);
boxp->x2 = t2p->pdf_imagebox.x2;
boxp->y1 = t2p->pdf_imagebox.y1;
boxp->y2 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * i2 * tilelength)
/ (float)t2p->tiff_length);
}
if(t2p->tiff_orientation==0 || t2p->tiff_orientation==1){
for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){
t2p_compose_pdf_page_orient( &(tiles[i].tile_box) , 0);
}
return;
}
for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){
boxp=&(tiles[i].tile_box);
boxp->x1 -= t2p->pdf_imagebox.x1;
boxp->x2 -= t2p->pdf_imagebox.x1;
boxp->y1 -= t2p->pdf_imagebox.y1;
boxp->y2 -= t2p->pdf_imagebox.y1;
if(t2p->tiff_orientation==2 || t2p->tiff_orientation==3){
boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1;
boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2;
}
if(t2p->tiff_orientation==3 || t2p->tiff_orientation==4){
boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1;
boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2;
}
if(t2p->tiff_orientation==8 || t2p->tiff_orientation==5){
boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1;
boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2;
}
if(t2p->tiff_orientation==5 || t2p->tiff_orientation==6){
boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1;
boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2;
}
if(t2p->tiff_orientation > 4){
f=boxp->x1;
boxp->x1 = boxp->y1;
boxp->y1 = f;
f=boxp->x2;
boxp->x2 = boxp->y2;
boxp->y2 = f;
t2p_compose_pdf_page_orient_flip(boxp, t2p->tiff_orientation);
} else {
t2p_compose_pdf_page_orient(boxp, t2p->tiff_orientation);
}
}
return;
}
static void t2p_compose_pdf_page_orient(T2P_BOX* boxp, uint16 orientation){
float m1[9];
float f=0.0;
if( boxp->x1 > boxp->x2){
f=boxp->x1;
boxp->x1=boxp->x2;
boxp->x2 = f;
}
if( boxp->y1 > boxp->y2){
f=boxp->y1;
boxp->y1=boxp->y2;
boxp->y2 = f;
}
boxp->mat[0]=m1[0]=boxp->x2-boxp->x1;
boxp->mat[1]=m1[1]=0.0;
boxp->mat[2]=m1[2]=0.0;
boxp->mat[3]=m1[3]=0.0;
boxp->mat[4]=m1[4]=boxp->y2-boxp->y1;
boxp->mat[5]=m1[5]=0.0;
boxp->mat[6]=m1[6]=boxp->x1;
boxp->mat[7]=m1[7]=boxp->y1;
boxp->mat[8]=m1[8]=1.0;
switch(orientation){
case 0:
case 1:
break;
case 2:
boxp->mat[0]=0.0F-m1[0];
boxp->mat[6]+=m1[0];
break;
case 3:
boxp->mat[0]=0.0F-m1[0];
boxp->mat[4]=0.0F-m1[4];
boxp->mat[6]+=m1[0];
boxp->mat[7]+=m1[4];
break;
case 4:
boxp->mat[4]=0.0F-m1[4];
boxp->mat[7]+=m1[4];
break;
case 5:
boxp->mat[0]=0.0F;
boxp->mat[1]=0.0F-m1[0];
boxp->mat[3]=0.0F-m1[4];
boxp->mat[4]=0.0F;
boxp->mat[6]+=m1[4];
boxp->mat[7]+=m1[0];
break;
case 6:
boxp->mat[0]=0.0F;
boxp->mat[1]=0.0F-m1[0];
boxp->mat[3]=m1[4];
boxp->mat[4]=0.0F;
boxp->mat[7]+=m1[0];
break;
case 7:
boxp->mat[0]=0.0F;
boxp->mat[1]=m1[0];
boxp->mat[3]=m1[4];
boxp->mat[4]=0.0F;
break;
case 8:
boxp->mat[0]=0.0F;
boxp->mat[1]=m1[0];
boxp->mat[3]=0.0F-m1[4];
boxp->mat[4]=0.0F;
boxp->mat[6]+=m1[4];
break;
}
return;
}
static void t2p_compose_pdf_page_orient_flip(T2P_BOX* boxp, uint16 orientation){
float m1[9];
float f=0.0;
if( boxp->x1 > boxp->x2){
f=boxp->x1;
boxp->x1=boxp->x2;
boxp->x2 = f;
}
if( boxp->y1 > boxp->y2){
f=boxp->y1;
boxp->y1=boxp->y2;
boxp->y2 = f;
}
boxp->mat[0]=m1[0]=boxp->x2-boxp->x1;
boxp->mat[1]=m1[1]=0.0F;
boxp->mat[2]=m1[2]=0.0F;
boxp->mat[3]=m1[3]=0.0F;
boxp->mat[4]=m1[4]=boxp->y2-boxp->y1;
boxp->mat[5]=m1[5]=0.0F;
boxp->mat[6]=m1[6]=boxp->x1;
boxp->mat[7]=m1[7]=boxp->y1;
boxp->mat[8]=m1[8]=1.0F;
switch(orientation){
case 5:
boxp->mat[0]=0.0F;
boxp->mat[1]=0.0F-m1[4];
boxp->mat[3]=0.0F-m1[0];
boxp->mat[4]=0.0F;
boxp->mat[6]+=m1[0];
boxp->mat[7]+=m1[4];
break;
case 6:
boxp->mat[0]=0.0F;
boxp->mat[1]=0.0F-m1[4];
boxp->mat[3]=m1[0];
boxp->mat[4]=0.0F;
boxp->mat[7]+=m1[4];
break;
case 7:
boxp->mat[0]=0.0F;
boxp->mat[1]=m1[4];
boxp->mat[3]=m1[0];
boxp->mat[4]=0.0F;
break;
case 8:
boxp->mat[0]=0.0F;
boxp->mat[1]=m1[4];
boxp->mat[3]=0.0F-m1[0];
boxp->mat[4]=0.0F;
boxp->mat[6]+=m1[0];
break;
}
return;
}
/*
This function writes a PDF Contents stream to output.
*/
static tsize_t t2p_write_pdf_page_content_stream(T2P* t2p, TIFF* output){
tsize_t written=0;
ttile_t i=0;
char buffer[512];
int buflen=0;
T2P_BOX box;
if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount>0){
for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++){
box=t2p->tiff_tiles[t2p->pdf_page].tiles_tiles[i].tile_box;
buflen=sprintf(buffer,
"q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d_%ld Do Q\r",
t2p->tiff_transferfunctioncount?"/GS1 gs ":"",
box.mat[0],
box.mat[1],
box.mat[3],
box.mat[4],
box.mat[6],
box.mat[7],
t2p->pdf_page + 1,
(long)(i + 1));
written += t2p_write_pdf_stream(buffer, buflen, output);
}
} else {
box=t2p->pdf_imagebox;
buflen=sprintf(buffer,
"q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d Do Q\r",
t2p->tiff_transferfunctioncount?"/GS1 gs ":"",
box.mat[0],
box.mat[1],
box.mat[3],
box.mat[4],
box.mat[6],
box.mat[7],
t2p->pdf_page+1);
written += t2p_write_pdf_stream(buffer, buflen, output);
}
return(written);
}
/*
This function writes a PDF Image XObject stream dictionary to output.
*/
static tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t tile,
T2P* t2p,
TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output);
written += TIFFWriteFile(output,
(tdata_t) "/Type /XObject \r/Subtype /Image \r/Name /Im",
42);
buflen=sprintf(buffer, "%u", t2p->pdf_page+1);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
if(tile != 0){
written += TIFFWriteFile(output, (tdata_t) "_", 1);
buflen=sprintf(buffer, "%lu", (unsigned long)tile);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
}
written += TIFFWriteFile(output, (tdata_t) "\r/Width ", 8);
_TIFFmemset((tdata_t)buffer, 0x00, 16);
if(tile==0){
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_width);
} else {
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
} else {
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
}
}
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "\r/Height ", 9);
_TIFFmemset((tdata_t)buffer, 0x00, 16);
if(tile==0){
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_length);
} else {
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
} else {
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
}
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "\r/BitsPerComponent ", 19);
_TIFFmemset((tdata_t)buffer, 0x00, 16);
buflen=sprintf(buffer, "%u", t2p->tiff_bitspersample);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "\r/ColorSpace ", 13);
written += t2p_write_pdf_xobject_cs(t2p, output);
if (t2p->pdf_image_interpolate)
written += TIFFWriteFile(output,
(tdata_t) "\r/Interpolate true", 18);
if( (t2p->pdf_switchdecode != 0)
#ifdef CCITT_SUPPORT
&& ! (t2p->pdf_colorspace == T2P_CS_BILEVEL
&& t2p->pdf_compression == T2P_COMPRESS_G4)
#endif
){
written += t2p_write_pdf_xobject_decode(t2p, output);
}
written += t2p_write_pdf_xobject_stream_filter(tile, t2p, output);
return(written);
}
/*
* This function writes a PDF Image XObject Colorspace name to output.
*/
static tsize_t t2p_write_pdf_xobject_cs(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[128];
int buflen=0;
float X_W=1.0;
float Y_W=1.0;
float Z_W=1.0;
if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){
written += t2p_write_pdf_xobject_icccs(t2p, output);
return(written);
}
if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){
written += TIFFWriteFile(output, (tdata_t) "[ /Indexed ", 11);
t2p->pdf_colorspace ^= T2P_CS_PALETTE;
written += t2p_write_pdf_xobject_cs(t2p, output);
t2p->pdf_colorspace |= T2P_CS_PALETTE;
buflen=sprintf(buffer, "%u", (0x0001 << t2p->tiff_bitspersample)-1 );
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " ", 1);
_TIFFmemset(buffer, 0x00, 16);
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_palettecs );
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ]\r", 7);
return(written);
}
if(t2p->pdf_colorspace & T2P_CS_BILEVEL){
written += TIFFWriteFile(output, (tdata_t) "/DeviceGray \r", 13);
}
if(t2p->pdf_colorspace & T2P_CS_GRAY){
if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
written += t2p_write_pdf_xobject_calcs(t2p, output);
} else {
written += TIFFWriteFile(output, (tdata_t) "/DeviceGray \r", 13);
}
}
if(t2p->pdf_colorspace & T2P_CS_RGB){
if(t2p->pdf_colorspace & T2P_CS_CALRGB){
written += t2p_write_pdf_xobject_calcs(t2p, output);
} else {
written += TIFFWriteFile(output, (tdata_t) "/DeviceRGB \r", 12);
}
}
if(t2p->pdf_colorspace & T2P_CS_CMYK){
written += TIFFWriteFile(output, (tdata_t) "/DeviceCMYK \r", 13);
}
if(t2p->pdf_colorspace & T2P_CS_LAB){
written += TIFFWriteFile(output, (tdata_t) "[/Lab << \r", 10);
written += TIFFWriteFile(output, (tdata_t) "/WhitePoint ", 12);
X_W = t2p->tiff_whitechromaticities[0];
Y_W = t2p->tiff_whitechromaticities[1];
Z_W = 1.0F - (X_W + Y_W);
X_W /= Y_W;
Z_W /= Y_W;
Y_W = 1.0F;
buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
X_W = 0.3457F; /* 0.3127F; */ /* D50, commented D65 */
Y_W = 0.3585F; /* 0.3290F; */
Z_W = 1.0F - (X_W + Y_W);
X_W /= Y_W;
Z_W /= Y_W;
Y_W = 1.0F;
buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "/Range ", 7);
buflen=sprintf(buffer, "[%d %d %d %d] \r",
t2p->pdf_labrange[0],
t2p->pdf_labrange[1],
t2p->pdf_labrange[2],
t2p->pdf_labrange[3]);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) ">>] \r", 5);
}
return(written);
}
static tsize_t t2p_write_pdf_transfer(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
written += TIFFWriteFile(output, (tdata_t) "<< /Type /ExtGState \r/TR ", 25);
if(t2p->tiff_transferfunctioncount == 1){
buflen=sprintf(buffer, "%lu",
(unsigned long)(t2p->pdf_xrefcount + 1));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
} else {
written += TIFFWriteFile(output, (tdata_t) "[ ", 2);
buflen=sprintf(buffer, "%lu",
(unsigned long)(t2p->pdf_xrefcount + 1));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
buflen=sprintf(buffer, "%lu",
(unsigned long)(t2p->pdf_xrefcount + 2));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
buflen=sprintf(buffer, "%lu",
(unsigned long)(t2p->pdf_xrefcount + 3));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
written += TIFFWriteFile(output, (tdata_t) "/Identity ] ", 12);
}
written += TIFFWriteFile(output, (tdata_t) " >> \r", 5);
return(written);
}
static tsize_t t2p_write_pdf_transfer_dict(T2P* t2p, TIFF* output, uint16 i){
tsize_t written=0;
char buffer[32];
int buflen=0;
(void)i; // XXX
written += TIFFWriteFile(output, (tdata_t) "/FunctionType 0 \r", 17);
written += TIFFWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \r", 19);
written += TIFFWriteFile(output, (tdata_t) "/Range [0.0 1.0] \r", 18);
buflen=sprintf(buffer, "/Size [%u] \r", (1<<t2p->tiff_bitspersample));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "/BitsPerSample 16 \r", 19);
written += t2p_write_pdf_stream_dict(1<<(t2p->tiff_bitspersample+1), 0, output);
return(written);
}
static tsize_t t2p_write_pdf_transfer_stream(T2P* t2p, TIFF* output, uint16 i){
tsize_t written=0;
written += t2p_write_pdf_stream(
t2p->tiff_transferfunction[i],
(1<<(t2p->tiff_bitspersample+1)),
output);
return(written);
}
/*
This function writes a PDF Image XObject Colorspace array to output.
*/
static tsize_t t2p_write_pdf_xobject_calcs(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[128];
int buflen=0;
float X_W=0.0;
float Y_W=0.0;
float Z_W=0.0;
float X_R=0.0;
float Y_R=0.0;
float Z_R=0.0;
float X_G=0.0;
float Y_G=0.0;
float Z_G=0.0;
float X_B=0.0;
float Y_B=0.0;
float Z_B=0.0;
float x_w=0.0;
float y_w=0.0;
float z_w=0.0;
float x_r=0.0;
float y_r=0.0;
float x_g=0.0;
float y_g=0.0;
float x_b=0.0;
float y_b=0.0;
float R=1.0;
float G=1.0;
float B=1.0;
written += TIFFWriteFile(output, (tdata_t) "[", 1);
if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
written += TIFFWriteFile(output, (tdata_t) "/CalGray ", 9);
X_W = t2p->tiff_whitechromaticities[0];
Y_W = t2p->tiff_whitechromaticities[1];
Z_W = 1.0F - (X_W + Y_W);
X_W /= Y_W;
Z_W /= Y_W;
Y_W = 1.0F;
}
if(t2p->pdf_colorspace & T2P_CS_CALRGB){
written += TIFFWriteFile(output, (tdata_t) "/CalRGB ", 8);
x_w = t2p->tiff_whitechromaticities[0];
y_w = t2p->tiff_whitechromaticities[1];
x_r = t2p->tiff_primarychromaticities[0];
y_r = t2p->tiff_primarychromaticities[1];
x_g = t2p->tiff_primarychromaticities[2];
y_g = t2p->tiff_primarychromaticities[3];
x_b = t2p->tiff_primarychromaticities[4];
y_b = t2p->tiff_primarychromaticities[5];
z_w = y_w * ((x_g - x_b)*y_r - (x_r-x_b)*y_g + (x_r-x_g)*y_b);
Y_R = (y_r/R) * ((x_g-x_b)*y_w - (x_w-x_b)*y_g + (x_w-x_g)*y_b) / z_w;
X_R = Y_R * x_r / y_r;
Z_R = Y_R * (((1-x_r)/y_r)-1);
Y_G = ((0.0F-(y_g))/G) * ((x_r-x_b)*y_w - (x_w-x_b)*y_r + (x_w-x_r)*y_b) / z_w;
X_G = Y_G * x_g / y_g;
Z_G = Y_G * (((1-x_g)/y_g)-1);
Y_B = (y_b/B) * ((x_r-x_g)*y_w - (x_w-x_g)*y_r + (x_w-x_r)*y_g) / z_w;
X_B = Y_B * x_b / y_b;
Z_B = Y_B * (((1-x_b)/y_b)-1);
X_W = (X_R * R) + (X_G * G) + (X_B * B);
Y_W = (Y_R * R) + (Y_G * G) + (Y_B * B);
Z_W = (Z_R * R) + (Z_G * G) + (Z_B * B);
X_W /= Y_W;
Z_W /= Y_W;
Y_W = 1.0;
}
written += TIFFWriteFile(output, (tdata_t) "<< \r", 4);
if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
written += TIFFWriteFile(output, (tdata_t) "/WhitePoint ", 12);
buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "/Gamma 2.2 \r", 12);
}
if(t2p->pdf_colorspace & T2P_CS_CALRGB){
written += TIFFWriteFile(output, (tdata_t) "/WhitePoint ", 12);
buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "/Matrix ", 8);
buflen=sprintf(buffer, "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \r",
X_R, Y_R, Z_R,
X_G, Y_G, Z_G,
X_B, Y_B, Z_B);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \r", 22);
}
written += TIFFWriteFile(output, (tdata_t) ">>] \r", 5);
return(written);
}
/*
This function writes a PDF Image XObject Colorspace array to output.
*/
static tsize_t t2p_write_pdf_xobject_icccs(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
written += TIFFWriteFile(output, (tdata_t) "[/ICCBased ", 11);
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_icccs);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R] \r", 7);
return(written);
}
static tsize_t t2p_write_pdf_xobject_icccs_dict(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
written += TIFFWriteFile(output, (tdata_t) "/N ", 3);
buflen=sprintf(buffer, "%u \r", t2p->tiff_samplesperpixel);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "/Alternate ", 11);
t2p->pdf_colorspace ^= T2P_CS_ICCBASED;
written += t2p_write_pdf_xobject_cs(t2p, output);
t2p->pdf_colorspace |= T2P_CS_ICCBASED;
written += t2p_write_pdf_stream_dict(t2p->tiff_iccprofilelength, 0, output);
return(written);
}
static tsize_t t2p_write_pdf_xobject_icccs_stream(T2P* t2p, TIFF* output){
tsize_t written=0;
written += t2p_write_pdf_stream(
(tdata_t) t2p->tiff_iccprofile,
(tsize_t) t2p->tiff_iccprofilelength,
output);
return(written);
}
/*
This function writes a palette stream for an indexed color space to output.
*/
static tsize_t t2p_write_pdf_xobject_palettecs_stream(T2P* t2p, TIFF* output){
tsize_t written=0;
written += t2p_write_pdf_stream(
(tdata_t) t2p->pdf_palette,
(tsize_t) t2p->pdf_palettesize,
output);
return(written);
}
/*
This function writes a PDF Image XObject Decode array to output.
*/
static tsize_t t2p_write_pdf_xobject_decode(T2P* t2p, TIFF* output){
tsize_t written=0;
int i=0;
written += TIFFWriteFile(output, (tdata_t) "/Decode [ ", 10);
for (i=0;i<t2p->tiff_samplesperpixel;i++){
written += TIFFWriteFile(output, (tdata_t) "1 0 ", 4);
}
written += TIFFWriteFile(output, (tdata_t) "]\r", 2);
return(written);
}
/*
This function writes a PDF Image XObject stream filter name and parameters to
output.
*/
static tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
if(t2p->pdf_compression==T2P_COMPRESS_NONE){
return(written);
}
written += TIFFWriteFile(output, (tdata_t) "/Filter ", 8);
switch(t2p->pdf_compression){
#ifdef CCITT_SUPPORT
case T2P_COMPRESS_G4:
written += TIFFWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16);
written += TIFFWriteFile(output, (tdata_t) "/DecodeParms ", 13);
written += TIFFWriteFile(output, (tdata_t) "<< /K -1 ", 9);
if(tile==0){
written += TIFFWriteFile(output, (tdata_t) "/Columns ", 9);
buflen=sprintf(buffer, "%lu",
(unsigned long)t2p->tiff_width);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " /Rows ", 7);
buflen=sprintf(buffer, "%lu",
(unsigned long)t2p->tiff_length);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
} else {
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){
written += TIFFWriteFile(output, (tdata_t) "/Columns ", 9);
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
} else {
written += TIFFWriteFile(output, (tdata_t) "/Columns ", 9);
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
}
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){
written += TIFFWriteFile(output, (tdata_t) " /Rows ", 7);
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
} else {
written += TIFFWriteFile(output, (tdata_t) " /Rows ", 7);
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
}
}
if(t2p->pdf_switchdecode == 0){
written += TIFFWriteFile(output, (tdata_t) " /BlackIs1 true ", 16);
}
written += TIFFWriteFile(output, (tdata_t) ">>\r", 3);
break;
#endif
#ifdef JPEG_SUPPORT
case T2P_COMPRESS_JPEG:
written += TIFFWriteFile(output, (tdata_t) "/DCTDecode ", 11);
if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) {
written += TIFFWriteFile(output, (tdata_t) "/DecodeParms ", 13);
written += TIFFWriteFile(output, (tdata_t) "<< /ColorTransform 0 >>\r", 24);
}
break;
#endif
#ifdef ZIP_SUPPORT
case T2P_COMPRESS_ZIP:
written += TIFFWriteFile(output, (tdata_t) "/FlateDecode ", 13);
if(t2p->pdf_compressionquality%100){
written += TIFFWriteFile(output, (tdata_t) "/DecodeParms ", 13);
written += TIFFWriteFile(output, (tdata_t) "<< /Predictor ", 14);
_TIFFmemset(buffer, 0x00, 16);
buflen=sprintf(buffer, "%u", t2p->pdf_compressionquality%100);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " /Columns ", 10);
_TIFFmemset(buffer, 0x00, 16);
buflen = sprintf(buffer, "%lu",
(unsigned long)t2p->tiff_width);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " /Colors ", 9);
_TIFFmemset(buffer, 0x00, 16);
buflen=sprintf(buffer, "%u", t2p->tiff_samplesperpixel);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " /BitsPerComponent ", 19);
_TIFFmemset(buffer, 0x00, 16);
buflen=sprintf(buffer, "%u", t2p->tiff_bitspersample);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) ">>\r", 3);
}
break;
#endif
default:
break;
}
return(written);
}
/*
This function writes a PDF xref table to output.
*/
static tsize_t t2p_write_pdf_xreftable(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[21];
int buflen=0;
uint32 i=0;
written += TIFFWriteFile(output, (tdata_t) "xref\r0 ", 7);
buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 1));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " \r0000000000 65535 f\r\n", 22);
for (i=0;i<t2p->pdf_xrefcount;i++){
sprintf(buffer, "%.10lu 00000 n\r\n",
(unsigned long)t2p->pdf_xrefoffsets[i]);
written += TIFFWriteFile(output, (tdata_t) buffer, 20);
}
return(written);
}
/*
* This function writes a PDF trailer to output.
*/
static tsize_t t2p_write_pdf_trailer(T2P* t2p, TIFF* output)
{
tsize_t written = 0;
char buffer[32];
int buflen = 0;
int ifileidbuf[4];
char *fileidbuf = (char*)ifileidbuf;
int i = 0;
ifileidbuf[0] = rand();
ifileidbuf[1] = rand();
ifileidbuf[2] = rand();
ifileidbuf[3] = rand();
t2p->pdf_fileid = (char*)_TIFFmalloc(33);
if(t2p->pdf_fileid == NULL) {
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_write_pdf_trailer",
33 );
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
_TIFFmemset(t2p->pdf_fileid, 0x00, 33);
for (i=0; i<16; i++)
sprintf(&(t2p->pdf_fileid[2*i]), "%.2hhX", fileidbuf[i]);
written += TIFFWriteFile(output, (tdata_t) "trailer\r<<\r/Size ", 17);
buflen = sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount+1));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
_TIFFmemset(buffer, 0x00, 32);
written += TIFFWriteFile(output, (tdata_t) "\r/Root ", 7);
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_catalog);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
_TIFFmemset(buffer, 0x00, 32);
written += TIFFWriteFile(output, (tdata_t) " 0 R \r/Info ", 12);
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_info);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
_TIFFmemset(buffer, 0x00, 32);
written += TIFFWriteFile(output, (tdata_t) " 0 R \r/ID[<", 11);
written += TIFFWriteFile(output, (tdata_t) t2p->pdf_fileid, 32);
written += TIFFWriteFile(output, (tdata_t) "><", 2);
written += TIFFWriteFile(output, (tdata_t) t2p->pdf_fileid, 32);
written += TIFFWriteFile(output, (tdata_t) ">]\r>>\rstartxref\r", 16);
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_startxref);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
_TIFFmemset(buffer, 0x00, 32);
written += TIFFWriteFile(output, (tdata_t) "\r%%EOF\r", 7);
return(written);
}
/*
This function writes a PDF to a file given a pointer to a TIFF.
The idea with using a TIFF* as output for a PDF file is that the file
can be created with TIFFClientOpen for memory-mapped use within the TIFF
library, and TIFFWriteEncodedStrip can be used to write compressed data to
the output. The output is not actually a TIFF file, it is a PDF file.
This function uses only TIFFWriteFile and TIFFWriteEncodedStrip to write to
the output TIFF file. When libtiff would otherwise be writing data to the
output file, the write procedure of the TIFF structure is replaced with an
empty implementation.
The first argument to the function is an initialized and validated T2P
context struct pointer.
The second argument to the function is the TIFF* that is the input that has
been opened for reading and no other functions have been called upon it.
The third argument to the function is the TIFF* that is the output that has
been opened for writing. It has to be opened so that it hasn't written any
data to the output. If the output is seekable then it's OK to seek to the
beginning of the file. The function only writes to the output PDF and does
not seek. See the example usage in the main() function.
TIFF* output = TIFFOpen("output.pdf", "w");
assert(output != NULL);
if(output->tif_seekproc != NULL){
TIFFSeekFile(output, (toff_t) 0, SEEK_SET);
}
This function returns the file size of the output PDF file. On error it
returns zero and the t2p->t2p_error variable is set to T2P_ERR_ERROR.
After this function completes, call t2p_free on t2p, TIFFClose on input,
and TIFFClose on output.
*/
static tsize_t t2p_write_pdf(T2P* t2p, TIFF* input, TIFF* output){
tsize_t written=0;
ttile_t i2=0;
tsize_t streamlen=0;
uint16 i=0;
t2p_read_tiff_init(t2p, input);
if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
t2p->pdf_xrefoffsets= (uint32*) _TIFFmalloc(t2p->pdf_xrefcount * sizeof(uint32) );
if(t2p->pdf_xrefoffsets==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for t2p_write_pdf",
t2p->pdf_xrefcount * sizeof(uint32) );
return(written);
}
t2p->pdf_xrefcount=0;
t2p->pdf_catalog=1;
t2p->pdf_info=2;
t2p->pdf_pages=3;
written += t2p_write_pdf_header(t2p, output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_catalog=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_catalog(t2p, output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_info=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_info(t2p, input, output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_pages=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_pages(t2p, output);
written += t2p_write_pdf_obj_end(output);
for(t2p->pdf_page=0;t2p->pdf_page<t2p->tiff_pagecount;t2p->pdf_page++){
t2p_read_tiff_data(t2p, input);
if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_page(t2p->pdf_xrefcount, t2p, output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
written += t2p_write_pdf_page_content_stream(t2p, output);
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_length(streamlen, output);
written += t2p_write_pdf_obj_end(output);
if(t2p->tiff_transferfunctioncount != 0){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_transfer(t2p, output);
written += t2p_write_pdf_obj_end(output);
for(i=0; i < t2p->tiff_transferfunctioncount; i++){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_transfer_dict(t2p, output, i);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
written += t2p_write_pdf_transfer_stream(t2p, output, i);
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
}
}
if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_palettecs=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_stream_dict(t2p->pdf_palettesize, 0, output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
written += t2p_write_pdf_xobject_palettecs_stream(t2p, output);
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
}
if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_icccs=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_xobject_icccs_dict(t2p, output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
written += t2p_write_pdf_xobject_icccs_stream(t2p, output);
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
}
if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount !=0){
for(i2=0;i2<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i2++){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_xobject_stream_dict(
i2+1,
t2p,
output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
t2p_read_tiff_size_tile(t2p, input, i2);
written += t2p_readwrite_pdf_image_tile(t2p, input, output, i2);
t2p_write_advance_directory(t2p, output);
if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_length(streamlen, output);
written += t2p_write_pdf_obj_end(output);
}
} else {
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_xobject_stream_dict(
0,
t2p,
output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
t2p_read_tiff_size(t2p, input);
written += t2p_readwrite_pdf_image(t2p, input, output);
t2p_write_advance_directory(t2p, output);
if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_length(streamlen, output);
written += t2p_write_pdf_obj_end(output);
}
}
t2p->pdf_startxref=written;
written += t2p_write_pdf_xreftable(t2p, output);
written += t2p_write_pdf_trailer(t2p, output);
t2p_disable(output);
return(written);
}
#endif
/* vim: set ts=8 sts=8 sw=8 noet: */
| Java |
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit562156c4d0b385426dfb2e9042c495a5::getLoader();
| Java |
<?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) 2000-2014 LOCKON CO.,LTD. All Rights Reserved.
*
* http://www.lockon.co.jp/
*
* 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.
*/
require_once CLASS_EX_REALDIR . 'page_extends/admin/LC_Page_Admin_Ex.php';
/**
* オーナーズストア:認証キー設定 のページクラス.
*
* @package Page
* @author LOCKON CO.,LTD.
* @version $Id: LC_Page_Admin_OwnersStore_Settings.php 23546 2014-06-12 14:47:59Z shutta $
*/
class LC_Page_Admin_OwnersStore_Settings extends LC_Page_Admin_Ex
{
/** SC_FormParamのインスタンス */
public $objForm;
/** リクエストパラメーターを格納する連想配列 */
public $arrForm;
/** バリデーションエラー情報を格納する連想配列 */
public $arrErr;
/**
* Page を初期化する.
*
* @return void
*/
public function init()
{
parent::init();
$this->tpl_mainpage = 'ownersstore/settings.tpl';
$this->tpl_mainno = 'ownersstore';
$this->tpl_subno = 'settings';
$this->tpl_maintitle = 'オーナーズストア';
$this->tpl_subtitle = '認証キー設定';
$this->httpCacheControl('nocache');
}
/**
* Page のプロセス.
*
* @return void
*/
public function process()
{
$this->action();
$this->sendResponse();
}
/**
* Page のアクション.
*
* @return void
*/
public function action()
{
switch ($this->getMode()) {
// 入力内容をDBへ登録する
case 'register':
$this->execRegisterMode();
break;
// 初回表示
default:
$this->execDefaultMode();
}
}
/**
* registerアクションの実行.
* 入力内容をDBへ登録する.
*
* @param void
* @return void
*/
public function execRegisterMode()
{
// パラメーターオブジェクトの初期化
$this->initRegisterMode();
// POSTされたパラメーターの検証
$arrErr = $this->validateRegistermode();
// エラー時の処理
if (!empty($arrErr)) {
$this->arrErr = $arrErr;
$this->arrForm = $this->objForm->getHashArray();
return;
}
// エラーがなければDBへ登録
$arrForm = $this->objForm->getHashArray();
$this->registerOwnersStoreSettings($arrForm);
$this->arrForm = $arrForm;
$this->tpl_onload = "alert('登録しました。')";
}
/**
* registerアクションの初期化.
* SC_FormParamを初期化しメンバ変数にセットする.
*
* @param void
* @return void
*/
public function initRegisterMode()
{
// 前後の空白を削除
if (isset($_POST['public_key'])) {
$_POST['public_key'] = trim($_POST['public_key']);
}
$objForm = new SC_FormParam_Ex();
$objForm->addParam('認証キー', 'public_key', LTEXT_LEN, '', array('EXIST_CHECK', 'ALNUM_CHECK', 'MAX_LENGTH_CHECK'));
$objForm->setParam($_POST);
$this->objForm = $objForm;
}
/**
* registerアクションのパラメーターを検証する.
*
* @param void
* @return array エラー情報を格納した連想配列
*/
public function validateRegistermode()
{
return $this->objForm->checkError();
}
/**
* defaultアクションの実行.
* DBから登録内容を取得し表示する.
*
* @param void
* @return void
*/
public function execDefaultMode()
{
$this->arrForm = $this->getOwnersStoreSettings();
}
/**
* DBへ入力内容を登録する.
*
* @param array $arrSettingsData オーナーズストア設定の連想配列
* @return void
*/
public function registerOwnersStoreSettings($arrSettingsData)
{
$table = 'dtb_ownersstore_settings';
$objQuery =& SC_Query_Ex::getSingletonInstance();
$exists = $objQuery->exists($table);
if ($exists) {
$objQuery->update($table, $arrSettingsData);
} else {
$objQuery->insert($table, $arrSettingsData);
}
}
/**
* DBから登録内容を取得する.
*
* @param void
* @return array
*/
public function getOwnersStoreSettings()
{
$table = 'dtb_ownersstore_settings';
$colmuns = '*';
$objQuery =& SC_Query_Ex::getSingletonInstance();
$arrRet = $objQuery->select($colmuns, $table);
if (isset($arrRet[0])) return $arrRet[0];
return array();
}
}
| Java |
<?php
/**
* ClickBank® API Constants *(for site owners)*.
*
* Copyright: © 2009-2011
* {@link http://www.websharks-inc.com/ WebSharks, Inc.}
* (coded in the USA)
*
* This WordPress® plugin (s2Member Pro) is comprised of two parts:
*
* o (1) Its PHP code is licensed under the GPL license, as is WordPress®.
* You should have received a copy of the GNU General Public License,
* along with this software. In the main directory, see: /licensing/
* If not, see: {@link http://www.gnu.org/licenses/}.
*
* o (2) All other parts of (s2Member Pro); including, but not limited to:
* the CSS code, some JavaScript code, images, and design;
* are licensed according to the license purchased.
* See: {@link http://www.s2member.com/prices/}
*
* Unless you have our prior written consent, you must NOT directly or indirectly license,
* sub-license, sell, resell, or provide for free; part (2) of the s2Member Pro Module;
* or make an offer to do any of these things. All of these things are strictly
* prohibited with part (2) of the s2Member Pro Module.
*
* Your purchase of s2Member Pro includes free lifetime upgrades via s2Member.com
* (i.e. new features, bug fixes, updates, improvements); along with full access
* to our video tutorial library: {@link http://www.s2member.com/videos/}
*
* @package s2Member\API_Constants
* @since 1.5
*/
if (realpath (__FILE__) === realpath ($_SERVER["SCRIPT_FILENAME"]))
exit("Do not access this file directly.");
if (!class_exists ("c_ws_plugin__s2member_pro_clickbank_constants"))
{
/**
* ClickBank® API Constants *(for site owners)*.
*
* @package s2Member\API_Constants
* @since 1.5
*/
class c_ws_plugin__s2member_pro_clickbank_constants
{
/**
* ClickBank® API Constants *(for site owners)*.
*
* @package s2Member\API_Constants
* @since 1.5
*
* @attaches-to ``add_filter("ws_plugin__s2member_during_constants_c");``
*
* @param array $c Checksum array should be passed through by the Filter.
* @param array $vars Array of defined variables, passed through by the Filter.
* @return array Checksum array with new indexes for Constant values.
*/
public static function clickbank_constants ($c = FALSE, $vars = FALSE)
{
/**
* Flag indicating the ClickBank® Gateway is active.
*
* @package s2Member\API_Constants
* @since 1.5
*
* @var bool
*/
if (!defined ("S2MEMBER_PRO_CLICKBANK_GATEWAY"))
define ("S2MEMBER_PRO_CLICKBANK_GATEWAY", ($c[] = true));
return $c; // Return $c calculation values.
}
}
}
?> | Java |
<?php
/**
* File contains: eZ\Publish\Core\Persistence\Legacy\Tests\User\UserHandlerTest class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*
* @version //autogentag//
*/
namespace eZ\Publish\Core\Persistence\Legacy\Tests\User;
use eZ\Publish\API\Repository\Values\User\Role as APIRole;
use eZ\Publish\Core\Persistence\Legacy\Tests\TestCase;
use eZ\Publish\Core\Persistence\Legacy\User;
use eZ\Publish\Core\Persistence\Legacy\User\Role\LimitationConverter;
use eZ\Publish\Core\Persistence\Legacy\User\Role\LimitationHandler\ObjectStateHandler as ObjectStateLimitationHandler;
use eZ\Publish\SPI\Persistence;
/**
* Test case for UserHandlerTest.
*/
class UserHandlerTest extends TestCase
{
protected function getUserHandler()
{
$dbHandler = $this->getDatabaseHandler();
return new User\Handler(
new User\Gateway\DoctrineDatabase($dbHandler),
new User\Role\Gateway\DoctrineDatabase($dbHandler),
new User\Mapper(),
new LimitationConverter(array(new ObjectStateLimitationHandler($dbHandler)))
);
}
protected function getValidUser()
{
$user = new Persistence\User();
$user->id = 42;
$user->login = 'kore';
$user->email = '[email protected]';
$user->passwordHash = '1234567890';
$user->hashAlgorithm = 2;
$user->isEnabled = true;
$user->maxLogin = 23;
return $user;
}
public function testCreateUser()
{
$handler = $this->getUserHandler();
$handler->create($this->getValidUser());
$this->assertQueryResult(
array(array(1)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser'),
'Expected one user to be created.'
);
$this->assertQueryResult(
array(array(1)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser_setting'),
'Expected one user setting to be created.'
);
}
/**
* @expectedException \Doctrine\DBAL\DBALException
*/
public function testCreateDuplicateUser()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$handler->create($user);
}
/**
* @expectedException \Doctrine\DBAL\DBALException
*/
public function testInsertIncompleteUser()
{
$handler = $this->getUserHandler();
$user = new Persistence\User();
$user->id = 42;
$handler->create($user);
}
public function testLoadUser()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$this->assertEquals(
$user,
$handler->load($user->id)
);
}
/**
* @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
*/
public function testLoadUnknownUser()
{
$handler = $this->getUserHandler();
$handler->load(1337);
}
public function testLoadUserByLogin()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$loadedUser = $handler->loadByLogin($user->login);
$this->assertEquals(
$user,
$loadedUser
);
}
/**
* @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
*/
public function testLoadUserByEmailNotFound()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$handler->loadByLogin($user->email);
}
public function testLoadUserByEmail()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$users = $handler->loadByEmail($user->email);
$this->assertEquals(
$user,
$users[0]
);
}
public function testCreateAndDeleteUser()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$this->assertQueryResult(
array(array(1)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser'),
'Expected one user to be created.'
);
$this->assertQueryResult(
array(array(1)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser_setting'),
'Expected one user setting to be created.'
);
$handler->delete($user->id);
$this->assertQueryResult(
array(array(0)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser'),
'Expected one user to be removed.'
);
$this->assertQueryResult(
array(array(0)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser_setting'),
'Expected one user setting to be removed.'
);
}
public function testDeleteNonExistingUser()
{
$handler = $this->getUserHandler();
$handler->delete(1337);
$this->assertQueryResult(
array(array(0)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser'),
'Expected no existing user.'
);
}
public function testUpdateUser()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$user->login = 'New_lögin';
$handler->update($user);
$this->assertQueryResult(
array(array(42, '[email protected]', 'New_lögin', 'new_lögin', 1234567890, '2')),
$this->handler->createSelectQuery()->select('*')->from('ezuser'),
'Expected user data to be updated.'
);
}
public function testUpdateUserSettings()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$user->maxLogin = 42;
$handler->update($user);
$this->assertQueryResult(
array(array(1, 42, 42)),
$this->handler->createSelectQuery()->select('*')->from('ezuser_setting'),
'Expected user data to be updated.'
);
}
public function testSilentlyUpdateNotExistingUser()
{
$handler = $this->getUserHandler();
$handler->update($this->getValidUser());
$this->assertQueryResult(
array(array(0)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser'),
'Expected no existing user.'
);
}
public function testCreateNewRoleWithoutPolicies()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$handler->createRole($createStruct);
$this->assertQueryResult(
array(array(1, 'Test', -1)),
$this->handler->createSelectQuery()->select('id', 'name', 'version')->from('ezrole'),
'Expected a new role draft.'
);
}
public function testCreateRoleDraftWithoutPolicies()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$handler->createRoleDraft($roleDraft->id);
$publishedRoleId = 1;
$this->assertQueryResult(
[
[$publishedRoleId, 'Test', APIRole::STATUS_DEFINED],
[2, 'Test', $publishedRoleId],
],
$this->handler->createSelectQuery()->select('id', 'name', 'version')->from('ezrole'),
'Expected a role and a role draft.'
);
}
public function testCreateNewRoleRoleId()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$this->assertSame('1', $roleDraft->id);
}
public function testLoadRole()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$this->assertEquals(
$roleDraft->id,
$role->id
);
}
public function testLoadRoleWithPolicies()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$policy = new Persistence\User\Policy();
$policy->module = 'foo';
$policy->function = 'bar';
$handler->addPolicyByRoleDraft($roleDraft->id, $policy);
$handler->publishRoleDraft($roleDraft->id);
$loaded = $handler->loadRole($roleDraft->id);
$this->assertEquals(
array(
new Persistence\User\Policy(
array(
'id' => 1,
'roleId' => 1,
'module' => 'foo',
'function' => 'bar',
'limitations' => '*',
'originalId' => null,
)
),
),
$loaded->policies
);
}
public function testLoadRoleWithPoliciesAndGroups()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$policy = new Persistence\User\Policy();
$policy->module = 'foo';
$policy->function = 'bar';
$handler->addPolicyByRoleDraft($roleDraft->id, $policy);
$handler->assignRole(23, $roleDraft->id);
$handler->assignRole(42, $roleDraft->id);
$handler->publishRoleDraft($roleDraft->id);
$loaded = $handler->loadRole($roleDraft->id);
$this->assertEquals(
array(
new Persistence\User\Policy(
array(
'id' => 1,
'roleId' => 1,
'module' => 'foo',
'function' => 'bar',
'limitations' => '*',
'originalId' => null,
)
),
),
$loaded->policies
);
}
public function testLoadRoleWithPolicyLimitations()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$policy = new Persistence\User\Policy();
$policy->module = 'foo';
$policy->function = 'bar';
$policy->limitations = array(
'Subtree' => array('/1', '/1/2'),
'Foo' => array('Bar'),
);
$handler->addPolicyByRoleDraft($roleDraft->id, $policy);
$handler->publishRoleDraft($roleDraft->id);
$loaded = $handler->loadRole($roleDraft->id);
$this->assertEquals(
array(
new Persistence\User\Policy(
array(
'id' => 1,
'roleId' => 1,
'module' => 'foo',
'function' => 'bar',
'limitations' => array(
'Subtree' => array('/1', '/1/2'),
'Foo' => array('Bar'),
),
'originalId' => null,
)
),
),
$loaded->policies
);
}
public function testLoadRoles()
{
$handler = $this->getUserHandler();
$this->assertEquals(
array(),
$handler->loadRoles()
);
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$this->assertEquals(
array($role),
$handler->loadRoles()
);
}
public function testUpdateRole()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$update = new Persistence\User\RoleUpdateStruct();
$update->id = $role->id;
$update->identifier = 'Changed';
$handler->updateRole($update);
$this->assertQueryResult(
array(array(1, 'Changed')),
$this->handler->createSelectQuery()->select('id', 'name')->from('ezrole'),
'Expected a changed role.'
);
}
public function testDeleteRole()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
// 3 is the ID of Editor role
$handler->deleteRole(3);
$this->assertQueryResult(
array(),
$this->handler->createSelectQuery()->select('id')->from('ezrole')->where('id = 3'),
'Expected an empty set.'
);
$this->assertQueryResult(
array(),
$this->handler->createSelectQuery()->select('role_id')->from('ezpolicy')->where('role_id = 3'),
'Expected an empty set.'
);
$this->assertQueryResult(
array(),
$this->handler->createSelectQuery()->select('role_id')->from('ezuser_role')->where('role_id = 3'),
'Expected an empty set.'
);
}
public function testDeleteRoleDraft()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
// 3 is the ID of Editor role
$roleDraft = $handler->createRoleDraft(3);
$handler->deleteRole($roleDraft->id, APIRole::STATUS_DRAFT);
$this->assertQueryResult(
[['3', APIRole::STATUS_DEFINED]],
$this->handler->createSelectQuery()->select('id, version')->from('ezrole')->where('id = 3'),
'Expected a published role.'
);
$this->assertQueryResult(
[[implode("\n", array_fill(0, 27, '3, ' . APIRole::STATUS_DEFINED))]],
$this->handler->createSelectQuery()->select('role_id, original_id')->from('ezpolicy')->where('role_id = 3'),
'Expected 27 policies for the published role.'
);
$this->assertQueryResult(
[[3], [3]],
$this->handler->createSelectQuery()->select('role_id')->from('ezuser_role')->where('role_id = 3'),
'Expected that role assignments still exist.'
);
}
public function testAddPolicyToRoleLimitations()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$policy = new Persistence\User\Policy();
$policy->module = 'foo';
$policy->function = 'bar';
$handler->addPolicy($role->id, $policy);
$this->assertQueryResult(
array(array(1, 'foo', 'bar', 1)),
$this->handler->createSelectQuery()->select('id', 'module_name', 'function_name', 'role_id')->from('ezpolicy'),
'Expected a new policy.'
);
}
public function testAddPolicyPolicyId()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$policy = new Persistence\User\Policy();
$policy->module = 'foo';
$policy->function = 'bar';
$policy = $handler->addPolicy($role->id, $policy);
$this->assertEquals(1, $policy->id);
}
public function testAddPolicyLimitations()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$policy = new Persistence\User\Policy();
$policy->module = 'foo';
$policy->function = 'bar';
$policy->limitations = array(
'Subtree' => array('/1', '/1/2'),
'Foo' => array('Bar'),
);
$handler->addPolicy($role->id, $policy);
$this->assertQueryResult(
array(
array(1, 'Subtree', 1),
array(2, 'Foo', 1),
),
$this->handler->createSelectQuery()->select('id', 'identifier', 'policy_id')->from('ezpolicy_limitation'),
'Expected a new policy.'
);
}
public function testAddPolicyLimitationValues()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$policy = new Persistence\User\Policy();
$policy->module = 'foo';
$policy->function = 'bar';
$policy->limitations = array(
'Subtree' => array('/1', '/1/2'),
'Foo' => array('Bar'),
);
$handler->addPolicy($role->id, $policy);
$this->assertQueryResult(
array(
array(1, '/1', 1),
array(2, '/1/2', 1),
array(3, 'Bar', 2),
),
$this->handler->createSelectQuery()->select('id', 'value', 'limitation_id')->from('ezpolicy_limitation_value'),
'Expected a new policy.'
);
}
protected function createRole()
{
$handler = $this->getUserHandler();
$policy1 = new Persistence\User\Policy();
$policy1->module = 'foo';
$policy1->function = 'bar';
$policy1->limitations = array(
'Subtree' => array('/1', '/1/2'),
'Foo' => array('Bar'),
);
$policy2 = new Persistence\User\Policy();
$policy2->module = 'foo';
$policy2->function = 'blubb';
$policy2->limitations = array(
'Foo' => array('Blubb'),
);
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$createStruct->policies = array($policy1, $policy2);
return $handler->createRole($createStruct);
}
public function testImplicitlyCreatePolicies()
{
$this->createRole();
$this->assertQueryResult(
array(
array(1, 'foo', 'bar', 1),
array(2, 'foo', 'blubb', 1),
),
$this->handler->createSelectQuery()->select('id', 'module_name', 'function_name', 'role_id')->from('ezpolicy'),
'Expected a new policy.'
);
}
public function testDeletePolicy()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$handler->publishRoleDraft($roleDraft->id);
$handler->deletePolicy($roleDraft->policies[0]->id);
$this->assertQueryResult(
array(
array(2, 'foo', 'blubb', 1),
),
$this->handler->createSelectQuery()->select('id', 'module_name', 'function_name', 'role_id')->from('ezpolicy')->where('original_id = 0'),
'Expected a new policy.'
);
}
public function testDeletePolicyLimitations()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$handler->deletePolicy($roleDraft->policies[0]->id);
$this->assertQueryResult(
array(array(3, 'Foo', 2)),
$this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation')
);
}
public function testDeletePolicyLimitationValues()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$handler->deletePolicy($roleDraft->policies[0]->id);
$this->assertQueryResult(
array(array(4, 3, 'Blubb')),
$this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation_value')
);
}
public function testUpdatePolicies()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$policy = $roleDraft->policies[0];
$policy->limitations = array(
'new' => array('something'),
);
$handler->updatePolicy($policy);
$this->assertQueryResult(
array(
array(3, 'Foo', 2),
array(4, 'new', 1),
),
$this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation')
);
$this->assertQueryResult(
array(
array(4, 3, 'Blubb'),
array(5, 4, 'something'),
),
$this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation_value')
);
}
public function testAddRoleToUser()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$handler->create($user = $this->getValidUser());
$handler->assignRole($user->id, $role->id, array());
$this->assertQueryResult(
array(
array(1, 42, 1, null, null),
),
$this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
'Expected a new user policy association.'
);
}
public function testAddRoleToUserWithLimitation()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$handler->create($user = $this->getValidUser());
$handler->assignRole(
$user->id,
$role->id,
array(
'Subtree' => array('/1'),
)
);
$this->assertQueryResult(
array(
array(1, 42, 1, 'Subtree', '/1'),
),
$this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
'Expected a new user policy association.'
);
}
public function testAddRoleToUserWithComplexLimitation()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$handler->create($user = $this->getValidUser());
$handler->assignRole(
$user->id,
$role->id,
array(
'Subtree' => array('/1', '/1/2'),
'Foo' => array('Bar'),
)
);
$this->assertQueryResult(
array(
array(1, 42, 1, 'Subtree', '/1'),
array(2, 42, 1, 'Subtree', '/1/2'),
array(3, 42, 1, 'Foo', 'Bar'),
),
$this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
'Expected a new user policy association.'
);
}
public function testRemoveUserRoleAssociation()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$handler->create($user = $this->getValidUser());
$handler->assignRole(
$user->id,
$role->id,
array(
'Subtree' => array('/1', '/1/2'),
'Foo' => array('Bar'),
)
);
$handler->unassignRole($user->id, $role->id);
$this->assertQueryResult(
array(),
$this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
'Expected no user policy associations.'
);
}
public function testLoadPoliciesForUser()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
$policies = $handler->loadPoliciesByUserId(10); // Anonymous user
// Verify, that we received an array of Policy objects
$this->assertTrue(
array_reduce(
array_map(
function ($policy) {
return $policy instanceof Persistence\User\Policy;
},
$policies
),
function ($a, $b) {
return $a && $b;
},
true
)
);
$this->assertEquals(8, count($policies));
}
public function testLoadRoleAssignmentsByGroupId()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
$this->assertEquals(
array(
new Persistence\User\RoleAssignment(
array(
'id' => 28,
'roleId' => 1,
'contentId' => 11,
)
),
new Persistence\User\RoleAssignment(
array(
'id' => 34,
'roleId' => 5,
'contentId' => 11,
)
),
),
$handler->loadRoleAssignmentsByGroupId(11)// 11: Members
);
$this->assertEquals(
array(
new Persistence\User\RoleAssignment(
array(
'id' => 31,
'roleId' => 1,
'contentId' => 42,
)
),
),
$handler->loadRoleAssignmentsByGroupId(42)// 42: Anonymous Users
);
$this->assertEquals(
array(),
$handler->loadRoleAssignmentsByGroupId(10)// 10: Anonymous User
);
}
public function testLoadRoleAssignmentsByGroupIdInherited()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
$this->assertEquals(
array(
new Persistence\User\RoleAssignment(
array(
'id' => 31,
'roleId' => 1,
'contentId' => 42,
)
),
),
$handler->loadRoleAssignmentsByGroupId(10, true)// 10: Anonymous User
);
}
public function testLoadComplexRoleAssignments()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
$this->assertEquals(
array(
new Persistence\User\RoleAssignment(
array(
'id' => 32,
'roleId' => 3,
'contentId' => 13,
'limitationIdentifier' => 'Subtree',
'values' => array('/1/2/'),
)
),
new Persistence\User\RoleAssignment(
array(
'id' => 33,
'roleId' => 3,
'contentId' => 13,
'limitationIdentifier' => 'Subtree',
'values' => array('/1/43/'),
)
),
new Persistence\User\RoleAssignment(
array(
'id' => 38,
'roleId' => 5,
'contentId' => 13,
)
),
),
$handler->loadRoleAssignmentsByGroupId(13)
);
$this->assertEquals(
array(
new Persistence\User\RoleAssignment(
array(
'id' => 32,
'roleId' => 3,
'contentId' => 13,
'limitationIdentifier' => 'Subtree',
'values' => array('/1/2/'),
)
),
new Persistence\User\RoleAssignment(
array(
'id' => 33,
'roleId' => 3,
'contentId' => 13,
'limitationIdentifier' => 'Subtree',
'values' => array('/1/43/'),
)
),
new Persistence\User\RoleAssignment(
array(
'id' => 38,
'roleId' => 5,
'contentId' => 13,
)
),
),
$handler->loadRoleAssignmentsByGroupId(13, true)
);
}
public function testLoadRoleAssignmentsByRoleId()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
$this->assertEquals(
array(
new Persistence\User\RoleAssignment(
array(
'id' => 28,
'roleId' => 1,
'contentId' => 11,
)
),
new Persistence\User\RoleAssignment(
array(
'id' => 31,
'roleId' => 1,
'contentId' => 42,
)
),
new Persistence\User\RoleAssignment(
array(
'id' => 37,
'roleId' => 1,
'contentId' => 59,
)
),
),
$handler->loadRoleAssignmentsByRoleId(1)
);
}
public function testLoadRoleDraftByRoleId()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
// 3 is the ID of Editor role
$originalRoleId = 3;
$draft = $handler->createRoleDraft($originalRoleId);
$loadedDraft = $handler->loadRoleDraftByRoleId($originalRoleId);
self::assertSame($loadedDraft->originalId, $originalRoleId);
self::assertEquals($draft, $loadedDraft);
}
public function testRoleDraftOnlyHavePolicyDraft()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
$originalRoleId = 3;
$originalRole = $handler->loadRole($originalRoleId);
$originalPolicies = [];
foreach ($originalRole->policies as $policy) {
$originalPolicies[$policy->id] = $policy;
}
$draft = $handler->createRoleDraft($originalRoleId);
$loadedDraft = $handler->loadRole($draft->id, Persistence\User\Role::STATUS_DRAFT);
self::assertSame($loadedDraft->originalId, $originalRoleId);
self::assertEquals($draft, $loadedDraft);
foreach ($loadedDraft->policies as $policy) {
self::assertTrue(isset($originalPolicies[$policy->originalId]));
}
// Now add a new policy. Original ID of the new one must be the same as its actual ID.
$newPolicyModule = 'foo';
$newPolicyFunction = 'bar';
$policy = new Persistence\User\Policy(['module' => $newPolicyModule, 'function' => $newPolicyFunction]);
$policyDraft = $handler->addPolicyByRoleDraft($loadedDraft->id, $policy);
// Test again by reloading the draft.
$loadedDraft = $handler->loadRole($draft->id, Persistence\User\Role::STATUS_DRAFT);
foreach ($loadedDraft->policies as $policy) {
if ($policy->id != $policyDraft->id) {
continue;
}
self::assertNotNull($policy->originalId);
self::assertSame($policy->id, $policy->originalId);
}
}
}
| Java |
# Exemplo: "Feliz Natal" em Esperanto: Gajan Kristnaskon
$ zznatal #→ --regex ^"Feliz Natal" em .+: .+$
| Java |
/*
* Copyright (c) 1999-2005 Petko Manolov ([email protected])
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* ChangeLog:
* .... Most of the time spent on reading sources & docs.
* v0.2.x First official release for the Linux kernel.
* v0.3.0 Beutified and structured, some bugs fixed.
* v0.3.x URBifying bulk requests and bugfixing. First relatively
* stable release. Still can touch device's registers only
* from top-halves.
* v0.4.0 Control messages remained unurbified are now URBs.
* Now we can touch the HW at any time.
* v0.4.9 Control urbs again use process context to wait. Argh...
* Some long standing bugs (enable_net_traffic) fixed.
* Also nasty trick about resubmiting control urb from
* interrupt context used. Please let me know how it
* behaves. Pegasus II support added since this version.
* TODO: suppressing HCD warnings spewage on disconnect.
* v0.4.13 Ethernet address is now set at probe(), not at open()
* time as this seems to break dhcpd.
* v0.5.0 branch to 2.5.x kernels
* v0.5.1 ethtool support added
* v0.5.5 rx socket buffers are in a pool and the their allocation
* is out of the interrupt routine.
*/
#undef DEBUG
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/usb.h>
#include <linux/module.h>
#include <asm/byteorder.h>
#include <asm/uaccess.h>
#include "pegasus.h"
/*
* Version Information
*/
#define DRIVER_VERSION "v0.6.12 (2005/01/13)"
#define DRIVER_AUTHOR "Petko Manolov <[email protected]>"
#define DRIVER_DESC "Pegasus/Pegasus II USB Ethernet driver"
static const char driver_name[] = "pegasus";
#undef PEGASUS_WRITE_EEPROM
#define BMSR_MEDIA (BMSR_10HALF | BMSR_10FULL | BMSR_100HALF | \
BMSR_100FULL | BMSR_ANEGCAPABLE)
static int loopback = 0;
static int mii_mode = 0;
static struct usb_eth_dev usb_dev_id[] = {
#define PEGASUS_DEV(pn, vid, pid, flags) \
{.name = pn, .vendor = vid, .device = pid, .private = flags},
#include "pegasus.h"
#undef PEGASUS_DEV
{NULL, 0, 0, 0}
};
static struct usb_device_id pegasus_ids[] = {
#define PEGASUS_DEV(pn, vid, pid, flags) \
{.match_flags = USB_DEVICE_ID_MATCH_DEVICE, .idVendor = vid, .idProduct = pid},
#include "pegasus.h"
#undef PEGASUS_DEV
{}
};
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
module_param(loopback, bool, 0);
module_param(mii_mode, bool, 0);
MODULE_PARM_DESC(loopback, "Enable MAC loopback mode (bit 0)");
MODULE_PARM_DESC(mii_mode, "Enable HomePNA mode (bit 0),default=MII mode = 0");
/* use ethtool to change the level for any given device */
static int msg_level = -1;
module_param (msg_level, int, 0);
MODULE_PARM_DESC (msg_level, "Override default message level");
MODULE_DEVICE_TABLE(usb, pegasus_ids);
static int update_eth_regs_async(pegasus_t *);
/* Aargh!!! I _really_ hate such tweaks */
static void ctrl_callback(struct urb *urb, struct pt_regs *regs)
{
pegasus_t *pegasus = urb->context;
if (!pegasus)
return;
switch (urb->status) {
case 0:
if (pegasus->flags & ETH_REGS_CHANGE) {
pegasus->flags &= ~ETH_REGS_CHANGE;
pegasus->flags |= ETH_REGS_CHANGED;
update_eth_regs_async(pegasus);
return;
}
break;
case -EINPROGRESS:
return;
case -ENOENT:
break;
default:
if (netif_msg_drv(pegasus))
dev_err(&pegasus->intf->dev, "%s, status %d\n",
__FUNCTION__, urb->status);
}
pegasus->flags &= ~ETH_REGS_CHANGED;
wake_up(&pegasus->ctrl_wait);
}
static int get_registers(pegasus_t * pegasus, __u16 indx, __u16 size,
void *data)
{
int ret;
char *buffer;
DECLARE_WAITQUEUE(wait, current);
buffer = kmalloc(size, GFP_KERNEL);
if (!buffer) {
if (netif_msg_drv(pegasus))
dev_warn(&pegasus->intf->dev, "out of memory in %s\n",
__FUNCTION__);
return -ENOMEM;
}
add_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_UNINTERRUPTIBLE);
while (pegasus->flags & ETH_REGS_CHANGED)
schedule();
remove_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_RUNNING);
pegasus->dr.bRequestType = PEGASUS_REQT_READ;
pegasus->dr.bRequest = PEGASUS_REQ_GET_REGS;
pegasus->dr.wValue = cpu_to_le16(0);
pegasus->dr.wIndex = cpu_to_le16p(&indx);
pegasus->dr.wLength = cpu_to_le16p(&size);
pegasus->ctrl_urb->transfer_buffer_length = size;
usb_fill_control_urb(pegasus->ctrl_urb, pegasus->usb,
usb_rcvctrlpipe(pegasus->usb, 0),
(char *) &pegasus->dr,
buffer, size, ctrl_callback, pegasus);
add_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_UNINTERRUPTIBLE);
/* using ATOMIC, we'd never wake up if we slept */
if ((ret = usb_submit_urb(pegasus->ctrl_urb, GFP_ATOMIC))) {
if (netif_msg_drv(pegasus))
dev_err(&pegasus->intf->dev, "%s, status %d\n",
__FUNCTION__, ret);
goto out;
}
schedule();
out:
remove_wait_queue(&pegasus->ctrl_wait, &wait);
memcpy(data, buffer, size);
kfree(buffer);
return ret;
}
static int set_registers(pegasus_t * pegasus, __u16 indx, __u16 size,
void *data)
{
int ret;
char *buffer;
DECLARE_WAITQUEUE(wait, current);
buffer = kmalloc(size, GFP_KERNEL);
if (!buffer) {
if (netif_msg_drv(pegasus))
dev_warn(&pegasus->intf->dev, "out of memory in %s\n",
__FUNCTION__);
return -ENOMEM;
}
memcpy(buffer, data, size);
add_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_UNINTERRUPTIBLE);
while (pegasus->flags & ETH_REGS_CHANGED)
schedule();
remove_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_RUNNING);
pegasus->dr.bRequestType = PEGASUS_REQT_WRITE;
pegasus->dr.bRequest = PEGASUS_REQ_SET_REGS;
pegasus->dr.wValue = cpu_to_le16(0);
pegasus->dr.wIndex = cpu_to_le16p(&indx);
pegasus->dr.wLength = cpu_to_le16p(&size);
pegasus->ctrl_urb->transfer_buffer_length = size;
usb_fill_control_urb(pegasus->ctrl_urb, pegasus->usb,
usb_sndctrlpipe(pegasus->usb, 0),
(char *) &pegasus->dr,
buffer, size, ctrl_callback, pegasus);
add_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_UNINTERRUPTIBLE);
if ((ret = usb_submit_urb(pegasus->ctrl_urb, GFP_ATOMIC))) {
if (netif_msg_drv(pegasus))
dev_err(&pegasus->intf->dev, "%s, status %d\n",
__FUNCTION__, ret);
goto out;
}
schedule();
out:
remove_wait_queue(&pegasus->ctrl_wait, &wait);
kfree(buffer);
return ret;
}
static int set_register(pegasus_t * pegasus, __u16 indx, __u8 data)
{
int ret;
char *tmp;
DECLARE_WAITQUEUE(wait, current);
tmp = kmalloc(1, GFP_KERNEL);
if (!tmp) {
if (netif_msg_drv(pegasus))
dev_warn(&pegasus->intf->dev, "out of memory in %s\n",
__FUNCTION__);
return -ENOMEM;
}
memcpy(tmp, &data, 1);
add_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_UNINTERRUPTIBLE);
while (pegasus->flags & ETH_REGS_CHANGED)
schedule();
remove_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_RUNNING);
pegasus->dr.bRequestType = PEGASUS_REQT_WRITE;
pegasus->dr.bRequest = PEGASUS_REQ_SET_REG;
pegasus->dr.wValue = cpu_to_le16(data);
pegasus->dr.wIndex = cpu_to_le16p(&indx);
pegasus->dr.wLength = cpu_to_le16(1);
pegasus->ctrl_urb->transfer_buffer_length = 1;
usb_fill_control_urb(pegasus->ctrl_urb, pegasus->usb,
usb_sndctrlpipe(pegasus->usb, 0),
(char *) &pegasus->dr,
&tmp, 1, ctrl_callback, pegasus);
add_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_UNINTERRUPTIBLE);
if ((ret = usb_submit_urb(pegasus->ctrl_urb, GFP_ATOMIC))) {
if (netif_msg_drv(pegasus))
dev_err(&pegasus->intf->dev, "%s, status %d\n",
__FUNCTION__, ret);
goto out;
}
schedule();
out:
remove_wait_queue(&pegasus->ctrl_wait, &wait);
kfree(tmp);
return ret;
}
static int update_eth_regs_async(pegasus_t * pegasus)
{
int ret;
pegasus->dr.bRequestType = PEGASUS_REQT_WRITE;
pegasus->dr.bRequest = PEGASUS_REQ_SET_REGS;
pegasus->dr.wValue = 0;
pegasus->dr.wIndex = cpu_to_le16(EthCtrl0);
pegasus->dr.wLength = cpu_to_le16(3);
pegasus->ctrl_urb->transfer_buffer_length = 3;
usb_fill_control_urb(pegasus->ctrl_urb, pegasus->usb,
usb_sndctrlpipe(pegasus->usb, 0),
(char *) &pegasus->dr,
pegasus->eth_regs, 3, ctrl_callback, pegasus);
if ((ret = usb_submit_urb(pegasus->ctrl_urb, GFP_ATOMIC)))
if (netif_msg_drv(pegasus))
dev_err(&pegasus->intf->dev, "%s, status %d\n",
__FUNCTION__, ret);
return ret;
}
static int read_mii_word(pegasus_t * pegasus, __u8 phy, __u8 indx, __u16 * regd)
{
int i;
__u8 data[4] = { phy, 0, 0, indx };
__le16 regdi;
int ret;
ret = set_register(pegasus, PhyCtrl, 0);
ret = set_registers(pegasus, PhyAddr, sizeof (data), data);
ret = set_register(pegasus, PhyCtrl, (indx | PHY_READ));
for (i = 0; i < REG_TIMEOUT; i++) {
ret = get_registers(pegasus, PhyCtrl, 1, data);
if (data[0] & PHY_DONE)
break;
}
if (i < REG_TIMEOUT) {
ret = get_registers(pegasus, PhyData, 2, ®di);
*regd = le16_to_cpu(regdi);
return 1;
}
if (netif_msg_drv(pegasus))
dev_warn(&pegasus->intf->dev, "fail %s\n", __FUNCTION__);
return 0;
}
static int mdio_read(struct net_device *dev, int phy_id, int loc)
{
pegasus_t *pegasus = (pegasus_t *) netdev_priv(dev);
u16 res;
read_mii_word(pegasus, phy_id, loc, &res);
return (int)res;
}
static int write_mii_word(pegasus_t * pegasus, __u8 phy, __u8 indx, __u16 regd)
{
int i;
__u8 data[4] = { phy, 0, 0, indx };
int ret;
data[1] = (u8) regd;
data[2] = (u8) (regd >> 8);
ret = set_register(pegasus, PhyCtrl, 0);
ret = set_registers(pegasus, PhyAddr, sizeof(data), data);
ret = set_register(pegasus, PhyCtrl, (indx | PHY_WRITE));
for (i = 0; i < REG_TIMEOUT; i++) {
ret = get_registers(pegasus, PhyCtrl, 1, data);
if (data[0] & PHY_DONE)
break;
}
if (i < REG_TIMEOUT)
return 0;
if (netif_msg_drv(pegasus))
dev_warn(&pegasus->intf->dev, "fail %s\n", __FUNCTION__);
return 1;
}
static void mdio_write(struct net_device *dev, int phy_id, int loc, int val)
{
pegasus_t *pegasus = (pegasus_t *) netdev_priv(dev);
write_mii_word(pegasus, phy_id, loc, val);
}
static int read_eprom_word(pegasus_t * pegasus, __u8 index, __u16 * retdata)
{
int i;
__u8 tmp;
__le16 retdatai;
int ret;
ret = set_register(pegasus, EpromCtrl, 0);
ret = set_register(pegasus, EpromOffset, index);
ret = set_register(pegasus, EpromCtrl, EPROM_READ);
for (i = 0; i < REG_TIMEOUT; i++) {
ret = get_registers(pegasus, EpromCtrl, 1, &tmp);
if (tmp & EPROM_DONE)
break;
}
if (i < REG_TIMEOUT) {
ret = get_registers(pegasus, EpromData, 2, &retdatai);
*retdata = le16_to_cpu(retdatai);
return 0;
}
if (netif_msg_drv(pegasus))
dev_warn(&pegasus->intf->dev, "fail %s\n", __FUNCTION__);
return -1;
}
#ifdef PEGASUS_WRITE_EEPROM
static inline void enable_eprom_write(pegasus_t * pegasus)
{
__u8 tmp;
int ret;
ret = get_registers(pegasus, EthCtrl2, 1, &tmp);
ret = set_register(pegasus, EthCtrl2, tmp | EPROM_WR_ENABLE);
}
static inline void disable_eprom_write(pegasus_t * pegasus)
{
__u8 tmp;
int ret;
ret = get_registers(pegasus, EthCtrl2, 1, &tmp);
ret = set_register(pegasus, EpromCtrl, 0);
ret = set_register(pegasus, EthCtrl2, tmp & ~EPROM_WR_ENABLE);
}
static int write_eprom_word(pegasus_t * pegasus, __u8 index, __u16 data)
{
int i;
__u8 tmp, d[4] = { 0x3f, 0, 0, EPROM_WRITE };
int ret;
ret = set_registers(pegasus, EpromOffset, 4, d);
enable_eprom_write(pegasus);
ret = set_register(pegasus, EpromOffset, index);
ret = set_registers(pegasus, EpromData, 2, &data);
ret = set_register(pegasus, EpromCtrl, EPROM_WRITE);
for (i = 0; i < REG_TIMEOUT; i++) {
ret = get_registers(pegasus, EpromCtrl, 1, &tmp);
if (tmp & EPROM_DONE)
break;
}
disable_eprom_write(pegasus);
if (i < REG_TIMEOUT)
return 0;
if (netif_msg_drv(pegasus))
dev_warn(&pegasus->intf->dev, "fail %s\n", __FUNCTION__);
return -1;
}
#endif /* PEGASUS_WRITE_EEPROM */
static inline void get_node_id(pegasus_t * pegasus, __u8 * id)
{
int i;
__u16 w16;
for (i = 0; i < 3; i++) {
read_eprom_word(pegasus, i, &w16);
((__le16 *) id)[i] = cpu_to_le16p(&w16);
}
}
static void set_ethernet_addr(pegasus_t * pegasus)
{
__u8 node_id[6];
int ret;
get_node_id(pegasus, node_id);
ret = set_registers(pegasus, EthID, sizeof (node_id), node_id);
memcpy(pegasus->net->dev_addr, node_id, sizeof (node_id));
}
static inline int reset_mac(pegasus_t * pegasus)
{
__u8 data = 0x8;
int i;
int ret;
ret = set_register(pegasus, EthCtrl1, data);
for (i = 0; i < REG_TIMEOUT; i++) {
ret = get_registers(pegasus, EthCtrl1, 1, &data);
if (~data & 0x08) {
if (loopback & 1)
break;
if (mii_mode && (pegasus->features & HAS_HOME_PNA))
ret = set_register(pegasus, Gpio1, 0x34);
else
ret = set_register(pegasus, Gpio1, 0x26);
ret = set_register(pegasus, Gpio0, pegasus->features);
ret = set_register(pegasus, Gpio0, DEFAULT_GPIO_SET);
break;
}
}
if (i == REG_TIMEOUT)
return 1;
if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_LINKSYS ||
usb_dev_id[pegasus->dev_index].vendor == VENDOR_DLINK) {
ret = set_register(pegasus, Gpio0, 0x24);
ret = set_register(pegasus, Gpio0, 0x26);
}
if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_ELCON) {
__u16 auxmode;
read_mii_word(pegasus, 3, 0x1b, &auxmode);
write_mii_word(pegasus, 3, 0x1b, auxmode | 4);
}
return 0;
}
static int enable_net_traffic(struct net_device *dev, struct usb_device *usb)
{
__u16 linkpart;
__u8 data[4];
pegasus_t *pegasus = netdev_priv(dev);
int ret;
read_mii_word(pegasus, pegasus->phy, MII_LPA, &linkpart);
data[0] = 0xc9;
data[1] = 0;
if (linkpart & (ADVERTISE_100FULL | ADVERTISE_10FULL))
data[1] |= 0x20; /* set full duplex */
if (linkpart & (ADVERTISE_100FULL | ADVERTISE_100HALF))
data[1] |= 0x10; /* set 100 Mbps */
if (mii_mode)
data[1] = 0;
data[2] = (loopback & 1) ? 0x09 : 0x01;
memcpy(pegasus->eth_regs, data, sizeof (data));
ret = set_registers(pegasus, EthCtrl0, 3, data);
if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_LINKSYS ||
usb_dev_id[pegasus->dev_index].vendor == VENDOR_DLINK) {
u16 auxmode;
read_mii_word(pegasus, 0, 0x1b, &auxmode);
write_mii_word(pegasus, 0, 0x1b, auxmode | 4);
}
return 0;
}
static void fill_skb_pool(pegasus_t * pegasus)
{
int i;
for (i = 0; i < RX_SKBS; i++) {
if (pegasus->rx_pool[i])
continue;
pegasus->rx_pool[i] = dev_alloc_skb(PEGASUS_MTU + 2);
/*
** we give up if the allocation fail. the tasklet will be
** rescheduled again anyway...
*/
if (pegasus->rx_pool[i] == NULL)
return;
pegasus->rx_pool[i]->dev = pegasus->net;
skb_reserve(pegasus->rx_pool[i], 2);
}
}
static void free_skb_pool(pegasus_t * pegasus)
{
int i;
for (i = 0; i < RX_SKBS; i++) {
if (pegasus->rx_pool[i]) {
dev_kfree_skb(pegasus->rx_pool[i]);
pegasus->rx_pool[i] = NULL;
}
}
}
static inline struct sk_buff *pull_skb(pegasus_t * pegasus)
{
int i;
struct sk_buff *skb;
for (i = 0; i < RX_SKBS; i++) {
if (likely(pegasus->rx_pool[i] != NULL)) {
skb = pegasus->rx_pool[i];
pegasus->rx_pool[i] = NULL;
return skb;
}
}
return NULL;
}
static void read_bulk_callback(struct urb *urb, struct pt_regs *regs)
{
pegasus_t *pegasus = urb->context;
struct net_device *net;
int rx_status, count = urb->actual_length;
u8 *buf = urb->transfer_buffer;
__u16 pkt_len;
if (!pegasus)
return;
net = pegasus->net;
if (!netif_device_present(net) || !netif_running(net))
return;
switch (urb->status) {
case 0:
break;
case -ETIMEDOUT:
if (netif_msg_rx_err(pegasus))
pr_debug("%s: reset MAC\n", net->name);
pegasus->flags &= ~PEGASUS_RX_BUSY;
break;
case -EPIPE: /* stall, or disconnect from TT */
/* FIXME schedule work to clear the halt */
if (netif_msg_rx_err(pegasus))
printk(KERN_WARNING "%s: no rx stall recovery\n",
net->name);
return;
case -ENOENT:
case -ECONNRESET:
case -ESHUTDOWN:
if (netif_msg_ifdown(pegasus))
pr_debug("%s: rx unlink, %d\n", net->name, urb->status);
return;
default:
if (netif_msg_rx_err(pegasus))
pr_debug("%s: RX status %d\n", net->name, urb->status);
goto goon;
}
if (!count || count < 4)
goto goon;
rx_status = buf[count - 2];
if (rx_status & 0x1e) {
if (netif_msg_rx_err(pegasus))
pr_debug("%s: RX packet error %x\n",
net->name, rx_status);
pegasus->stats.rx_errors++;
if (rx_status & 0x06) // long or runt
pegasus->stats.rx_length_errors++;
if (rx_status & 0x08)
pegasus->stats.rx_crc_errors++;
if (rx_status & 0x10) // extra bits
pegasus->stats.rx_frame_errors++;
goto goon;
}
if (pegasus->chip == 0x8513) {
pkt_len = le32_to_cpu(*(__le32 *)urb->transfer_buffer);
pkt_len &= 0x0fff;
pegasus->rx_skb->data += 2;
} else {
pkt_len = buf[count - 3] << 8;
pkt_len += buf[count - 4];
pkt_len &= 0xfff;
pkt_len -= 8;
}
/*
* If the packet is unreasonably long, quietly drop it rather than
* kernel panicing by calling skb_put.
*/
if (pkt_len > PEGASUS_MTU)
goto goon;
/*
* at this point we are sure pegasus->rx_skb != NULL
* so we go ahead and pass up the packet.
*/
skb_put(pegasus->rx_skb, pkt_len);
pegasus->rx_skb->protocol = eth_type_trans(pegasus->rx_skb, net);
netif_rx(pegasus->rx_skb);
pegasus->stats.rx_packets++;
pegasus->stats.rx_bytes += pkt_len;
if (pegasus->flags & PEGASUS_UNPLUG)
return;
spin_lock(&pegasus->rx_pool_lock);
pegasus->rx_skb = pull_skb(pegasus);
spin_unlock(&pegasus->rx_pool_lock);
if (pegasus->rx_skb == NULL)
goto tl_sched;
goon:
usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb,
usb_rcvbulkpipe(pegasus->usb, 1),
pegasus->rx_skb->data, PEGASUS_MTU + 8,
read_bulk_callback, pegasus);
if (usb_submit_urb(pegasus->rx_urb, GFP_ATOMIC)) {
pegasus->flags |= PEGASUS_RX_URB_FAIL;
goto tl_sched;
} else {
pegasus->flags &= ~PEGASUS_RX_URB_FAIL;
}
return;
tl_sched:
tasklet_schedule(&pegasus->rx_tl);
}
static void rx_fixup(unsigned long data)
{
pegasus_t *pegasus;
unsigned long flags;
pegasus = (pegasus_t *) data;
if (pegasus->flags & PEGASUS_UNPLUG)
return;
spin_lock_irqsave(&pegasus->rx_pool_lock, flags);
fill_skb_pool(pegasus);
if (pegasus->flags & PEGASUS_RX_URB_FAIL)
if (pegasus->rx_skb)
goto try_again;
if (pegasus->rx_skb == NULL) {
pegasus->rx_skb = pull_skb(pegasus);
}
if (pegasus->rx_skb == NULL) {
if (netif_msg_rx_err(pegasus))
printk(KERN_WARNING "%s: low on memory\n",
pegasus->net->name);
tasklet_schedule(&pegasus->rx_tl);
goto done;
}
usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb,
usb_rcvbulkpipe(pegasus->usb, 1),
pegasus->rx_skb->data, PEGASUS_MTU + 8,
read_bulk_callback, pegasus);
try_again:
if (usb_submit_urb(pegasus->rx_urb, GFP_ATOMIC)) {
pegasus->flags |= PEGASUS_RX_URB_FAIL;
tasklet_schedule(&pegasus->rx_tl);
} else {
pegasus->flags &= ~PEGASUS_RX_URB_FAIL;
}
done:
spin_unlock_irqrestore(&pegasus->rx_pool_lock, flags);
}
static void write_bulk_callback(struct urb *urb, struct pt_regs *regs)
{
pegasus_t *pegasus = urb->context;
struct net_device *net = pegasus->net;
if (!pegasus)
return;
if (!netif_device_present(net) || !netif_running(net))
return;
switch (urb->status) {
case -EPIPE:
/* FIXME schedule_work() to clear the tx halt */
netif_stop_queue(net);
if (netif_msg_tx_err(pegasus))
printk(KERN_WARNING "%s: no tx stall recovery\n",
net->name);
return;
case -ENOENT:
case -ECONNRESET:
case -ESHUTDOWN:
if (netif_msg_ifdown(pegasus))
pr_debug("%s: tx unlink, %d\n", net->name, urb->status);
return;
default:
if (netif_msg_tx_err(pegasus))
pr_info("%s: TX status %d\n", net->name, urb->status);
/* FALL THROUGH */
case 0:
break;
}
net->trans_start = jiffies;
netif_wake_queue(net);
}
static void intr_callback(struct urb *urb, struct pt_regs *regs)
{
pegasus_t *pegasus = urb->context;
struct net_device *net;
int status;
if (!pegasus)
return;
net = pegasus->net;
switch (urb->status) {
case 0:
break;
case -ECONNRESET: /* unlink */
case -ENOENT:
case -ESHUTDOWN:
return;
default:
/* some Pegasus-I products report LOTS of data
* toggle errors... avoid log spamming
*/
if (netif_msg_timer(pegasus))
pr_debug("%s: intr status %d\n", net->name,
urb->status);
}
if (urb->actual_length >= 6) {
u8 * d = urb->transfer_buffer;
/* byte 0 == tx_status1, reg 2B */
if (d[0] & (TX_UNDERRUN|EXCESSIVE_COL
|LATE_COL|JABBER_TIMEOUT)) {
pegasus->stats.tx_errors++;
if (d[0] & TX_UNDERRUN)
pegasus->stats.tx_fifo_errors++;
if (d[0] & (EXCESSIVE_COL | JABBER_TIMEOUT))
pegasus->stats.tx_aborted_errors++;
if (d[0] & LATE_COL)
pegasus->stats.tx_window_errors++;
}
/* d[5].LINK_STATUS lies on some adapters.
* d[0].NO_CARRIER kicks in only with failed TX.
* ... so monitoring with MII may be safest.
*/
if (d[0] & NO_CARRIER)
netif_carrier_off(net);
else
netif_carrier_on(net);
/* bytes 3-4 == rx_lostpkt, reg 2E/2F */
pegasus->stats.rx_missed_errors += ((d[3] & 0x7f) << 8) | d[4];
}
status = usb_submit_urb(urb, SLAB_ATOMIC);
if (status && netif_msg_timer(pegasus))
printk(KERN_ERR "%s: can't resubmit interrupt urb, %d\n",
net->name, status);
}
static void pegasus_tx_timeout(struct net_device *net)
{
pegasus_t *pegasus = netdev_priv(net);
if (netif_msg_timer(pegasus))
printk(KERN_WARNING "%s: tx timeout\n", net->name);
usb_unlink_urb(pegasus->tx_urb);
pegasus->stats.tx_errors++;
}
static int pegasus_start_xmit(struct sk_buff *skb, struct net_device *net)
{
pegasus_t *pegasus = netdev_priv(net);
int count = ((skb->len + 2) & 0x3f) ? skb->len + 2 : skb->len + 3;
int res;
__u16 l16 = skb->len;
netif_stop_queue(net);
((__le16 *) pegasus->tx_buff)[0] = cpu_to_le16(l16);
memcpy(pegasus->tx_buff + 2, skb->data, skb->len);
usb_fill_bulk_urb(pegasus->tx_urb, pegasus->usb,
usb_sndbulkpipe(pegasus->usb, 2),
pegasus->tx_buff, count,
write_bulk_callback, pegasus);
if ((res = usb_submit_urb(pegasus->tx_urb, GFP_ATOMIC))) {
if (netif_msg_tx_err(pegasus))
printk(KERN_WARNING "%s: fail tx, %d\n",
net->name, res);
switch (res) {
case -EPIPE: /* stall, or disconnect from TT */
/* cleanup should already have been scheduled */
break;
case -ENODEV: /* disconnect() upcoming */
break;
default:
pegasus->stats.tx_errors++;
netif_start_queue(net);
}
} else {
pegasus->stats.tx_packets++;
pegasus->stats.tx_bytes += skb->len;
net->trans_start = jiffies;
}
dev_kfree_skb(skb);
return 0;
}
static struct net_device_stats *pegasus_netdev_stats(struct net_device *dev)
{
return &((pegasus_t *) netdev_priv(dev))->stats;
}
static inline void disable_net_traffic(pegasus_t * pegasus)
{
int tmp = 0;
int ret;
ret = set_registers(pegasus, EthCtrl0, 2, &tmp);
}
static inline void get_interrupt_interval(pegasus_t * pegasus)
{
__u8 data[2];
read_eprom_word(pegasus, 4, (__u16 *) data);
if (pegasus->usb->speed != USB_SPEED_HIGH) {
if (data[1] < 0x80) {
if (netif_msg_timer(pegasus))
dev_info(&pegasus->intf->dev, "intr interval "
"changed from %ums to %ums\n",
data[1], 0x80);
data[1] = 0x80;
#ifdef PEGASUS_WRITE_EEPROM
write_eprom_word(pegasus, 4, *(__u16 *) data);
#endif
}
}
pegasus->intr_interval = data[1];
}
static void set_carrier(struct net_device *net)
{
pegasus_t *pegasus = netdev_priv(net);
u16 tmp;
if (!read_mii_word(pegasus, pegasus->phy, MII_BMSR, &tmp))
return;
if (tmp & BMSR_LSTATUS)
netif_carrier_on(net);
else
netif_carrier_off(net);
}
static void free_all_urbs(pegasus_t * pegasus)
{
usb_free_urb(pegasus->intr_urb);
usb_free_urb(pegasus->tx_urb);
usb_free_urb(pegasus->rx_urb);
usb_free_urb(pegasus->ctrl_urb);
}
static void unlink_all_urbs(pegasus_t * pegasus)
{
usb_kill_urb(pegasus->intr_urb);
usb_kill_urb(pegasus->tx_urb);
usb_kill_urb(pegasus->rx_urb);
usb_kill_urb(pegasus->ctrl_urb);
}
static int alloc_urbs(pegasus_t * pegasus)
{
pegasus->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!pegasus->ctrl_urb) {
return 0;
}
pegasus->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!pegasus->rx_urb) {
usb_free_urb(pegasus->ctrl_urb);
return 0;
}
pegasus->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!pegasus->tx_urb) {
usb_free_urb(pegasus->rx_urb);
usb_free_urb(pegasus->ctrl_urb);
return 0;
}
pegasus->intr_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!pegasus->intr_urb) {
usb_free_urb(pegasus->tx_urb);
usb_free_urb(pegasus->rx_urb);
usb_free_urb(pegasus->ctrl_urb);
return 0;
}
return 1;
}
static int pegasus_open(struct net_device *net)
{
pegasus_t *pegasus = netdev_priv(net);
int res;
if (pegasus->rx_skb == NULL)
pegasus->rx_skb = pull_skb(pegasus);
/*
** Note: no point to free the pool. it is empty :-)
*/
if (!pegasus->rx_skb)
return -ENOMEM;
res = set_registers(pegasus, EthID, 6, net->dev_addr);
usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb,
usb_rcvbulkpipe(pegasus->usb, 1),
pegasus->rx_skb->data, PEGASUS_MTU + 8,
read_bulk_callback, pegasus);
if ((res = usb_submit_urb(pegasus->rx_urb, GFP_KERNEL))) {
if (netif_msg_ifup(pegasus))
pr_debug("%s: failed rx_urb, %d", net->name, res);
goto exit;
}
usb_fill_int_urb(pegasus->intr_urb, pegasus->usb,
usb_rcvintpipe(pegasus->usb, 3),
pegasus->intr_buff, sizeof (pegasus->intr_buff),
intr_callback, pegasus, pegasus->intr_interval);
if ((res = usb_submit_urb(pegasus->intr_urb, GFP_KERNEL))) {
if (netif_msg_ifup(pegasus))
pr_debug("%s: failed intr_urb, %d\n", net->name, res);
usb_kill_urb(pegasus->rx_urb);
goto exit;
}
if ((res = enable_net_traffic(net, pegasus->usb))) {
if (netif_msg_ifup(pegasus))
pr_debug("%s: can't enable_net_traffic() - %d\n",
net->name, res);
res = -EIO;
usb_kill_urb(pegasus->rx_urb);
usb_kill_urb(pegasus->intr_urb);
free_skb_pool(pegasus);
goto exit;
}
set_carrier(net);
netif_start_queue(net);
if (netif_msg_ifup(pegasus))
pr_debug("%s: open\n", net->name);
res = 0;
exit:
return res;
}
static int pegasus_close(struct net_device *net)
{
pegasus_t *pegasus = netdev_priv(net);
netif_stop_queue(net);
if (!(pegasus->flags & PEGASUS_UNPLUG))
disable_net_traffic(pegasus);
tasklet_kill(&pegasus->rx_tl);
unlink_all_urbs(pegasus);
return 0;
}
static void pegasus_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
pegasus_t *pegasus = netdev_priv(dev);
strncpy(info->driver, driver_name, sizeof (info->driver) - 1);
strncpy(info->version, DRIVER_VERSION, sizeof (info->version) - 1);
usb_make_path(pegasus->usb, info->bus_info, sizeof (info->bus_info));
}
/* also handles three patterns of some kind in hardware */
#define WOL_SUPPORTED (WAKE_MAGIC|WAKE_PHY)
static void
pegasus_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
pegasus_t *pegasus = netdev_priv(dev);
wol->supported = WAKE_MAGIC | WAKE_PHY;
wol->wolopts = pegasus->wolopts;
}
static int
pegasus_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
pegasus_t *pegasus = netdev_priv(dev);
u8 reg78 = 0x04;
if (wol->wolopts & ~WOL_SUPPORTED)
return -EINVAL;
if (wol->wolopts & WAKE_MAGIC)
reg78 |= 0x80;
if (wol->wolopts & WAKE_PHY)
reg78 |= 0x40;
/* FIXME this 0x10 bit still needs to get set in the chip... */
if (wol->wolopts)
pegasus->eth_regs[0] |= 0x10;
else
pegasus->eth_regs[0] &= ~0x10;
pegasus->wolopts = wol->wolopts;
return set_register(pegasus, WakeupControl, reg78);
}
static inline void pegasus_reset_wol(struct net_device *dev)
{
struct ethtool_wolinfo wol;
memset(&wol, 0, sizeof wol);
(void) pegasus_set_wol(dev, &wol);
}
static int
pegasus_get_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
{
pegasus_t *pegasus;
if (in_atomic())
return 0;
pegasus = netdev_priv(dev);
mii_ethtool_gset(&pegasus->mii, ecmd);
return 0;
}
static int
pegasus_set_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
{
pegasus_t *pegasus = netdev_priv(dev);
return mii_ethtool_sset(&pegasus->mii, ecmd);
}
static int pegasus_nway_reset(struct net_device *dev)
{
pegasus_t *pegasus = netdev_priv(dev);
return mii_nway_restart(&pegasus->mii);
}
static u32 pegasus_get_link(struct net_device *dev)
{
pegasus_t *pegasus = netdev_priv(dev);
return mii_link_ok(&pegasus->mii);
}
static u32 pegasus_get_msglevel(struct net_device *dev)
{
pegasus_t *pegasus = netdev_priv(dev);
return pegasus->msg_enable;
}
static void pegasus_set_msglevel(struct net_device *dev, u32 v)
{
pegasus_t *pegasus = netdev_priv(dev);
pegasus->msg_enable = v;
}
static struct ethtool_ops ops = {
.get_drvinfo = pegasus_get_drvinfo,
.get_settings = pegasus_get_settings,
.set_settings = pegasus_set_settings,
.nway_reset = pegasus_nway_reset,
.get_link = pegasus_get_link,
.get_msglevel = pegasus_get_msglevel,
.set_msglevel = pegasus_set_msglevel,
.get_wol = pegasus_get_wol,
.set_wol = pegasus_set_wol,
};
static int pegasus_ioctl(struct net_device *net, struct ifreq *rq, int cmd)
{
__u16 *data = (__u16 *) & rq->ifr_ifru;
pegasus_t *pegasus = netdev_priv(net);
int res;
switch (cmd) {
case SIOCDEVPRIVATE:
data[0] = pegasus->phy;
case SIOCDEVPRIVATE + 1:
read_mii_word(pegasus, data[0], data[1] & 0x1f, &data[3]);
res = 0;
break;
case SIOCDEVPRIVATE + 2:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
write_mii_word(pegasus, pegasus->phy, data[1] & 0x1f, data[2]);
res = 0;
break;
default:
res = -EOPNOTSUPP;
}
return res;
}
static void pegasus_set_multicast(struct net_device *net)
{
pegasus_t *pegasus = netdev_priv(net);
if (net->flags & IFF_PROMISC) {
pegasus->eth_regs[EthCtrl2] |= RX_PROMISCUOUS;
if (netif_msg_link(pegasus))
pr_info("%s: Promiscuous mode enabled.\n", net->name);
} else if (net->mc_count ||
(net->flags & IFF_ALLMULTI)) {
pegasus->eth_regs[EthCtrl0] |= RX_MULTICAST;
pegasus->eth_regs[EthCtrl2] &= ~RX_PROMISCUOUS;
if (netif_msg_link(pegasus))
pr_info("%s: set allmulti\n", net->name);
} else {
pegasus->eth_regs[EthCtrl0] &= ~RX_MULTICAST;
pegasus->eth_regs[EthCtrl2] &= ~RX_PROMISCUOUS;
}
pegasus->flags |= ETH_REGS_CHANGE;
ctrl_callback(pegasus->ctrl_urb, NULL);
}
static __u8 mii_phy_probe(pegasus_t * pegasus)
{
int i;
__u16 tmp;
for (i = 0; i < 32; i++) {
read_mii_word(pegasus, i, MII_BMSR, &tmp);
if (tmp == 0 || tmp == 0xffff || (tmp & BMSR_MEDIA) == 0)
continue;
else
return i;
}
return 0xff;
}
static inline void setup_pegasus_II(pegasus_t * pegasus)
{
__u8 data = 0xa5;
int ret;
ret = set_register(pegasus, Reg1d, 0);
ret = set_register(pegasus, Reg7b, 1);
mdelay(100);
if ((pegasus->features & HAS_HOME_PNA) && mii_mode)
ret = set_register(pegasus, Reg7b, 0);
else
ret = set_register(pegasus, Reg7b, 2);
ret = set_register(pegasus, 0x83, data);
ret = get_registers(pegasus, 0x83, 1, &data);
if (data == 0xa5) {
pegasus->chip = 0x8513;
} else {
pegasus->chip = 0;
}
ret = set_register(pegasus, 0x80, 0xc0);
ret = set_register(pegasus, 0x83, 0xff);
ret = set_register(pegasus, 0x84, 0x01);
if (pegasus->features & HAS_HOME_PNA && mii_mode)
ret = set_register(pegasus, Reg81, 6);
else
ret = set_register(pegasus, Reg81, 2);
}
static struct workqueue_struct *pegasus_workqueue = NULL;
#define CARRIER_CHECK_DELAY (2 * HZ)
static void check_carrier(void *data)
{
pegasus_t *pegasus = data;
set_carrier(pegasus->net);
if (!(pegasus->flags & PEGASUS_UNPLUG)) {
queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check,
CARRIER_CHECK_DELAY);
}
}
static int pegasus_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(intf);
struct net_device *net;
pegasus_t *pegasus;
int dev_index = id - pegasus_ids;
int res = -ENOMEM;
usb_get_dev(dev);
net = alloc_etherdev(sizeof(struct pegasus));
if (!net) {
dev_err(&intf->dev, "can't allocate %s\n", "device");
goto out;
}
pegasus = netdev_priv(net);
memset(pegasus, 0, sizeof (struct pegasus));
pegasus->dev_index = dev_index;
init_waitqueue_head(&pegasus->ctrl_wait);
if (!alloc_urbs(pegasus)) {
dev_err(&intf->dev, "can't allocate %s\n", "urbs");
goto out1;
}
tasklet_init(&pegasus->rx_tl, rx_fixup, (unsigned long) pegasus);
INIT_WORK(&pegasus->carrier_check, check_carrier, pegasus);
pegasus->intf = intf;
pegasus->usb = dev;
pegasus->net = net;
SET_MODULE_OWNER(net);
net->open = pegasus_open;
net->stop = pegasus_close;
net->watchdog_timeo = PEGASUS_TX_TIMEOUT;
net->tx_timeout = pegasus_tx_timeout;
net->do_ioctl = pegasus_ioctl;
net->hard_start_xmit = pegasus_start_xmit;
net->set_multicast_list = pegasus_set_multicast;
net->get_stats = pegasus_netdev_stats;
SET_ETHTOOL_OPS(net, &ops);
pegasus->mii.dev = net;
pegasus->mii.mdio_read = mdio_read;
pegasus->mii.mdio_write = mdio_write;
pegasus->mii.phy_id_mask = 0x1f;
pegasus->mii.reg_num_mask = 0x1f;
spin_lock_init(&pegasus->rx_pool_lock);
pegasus->msg_enable = netif_msg_init (msg_level, NETIF_MSG_DRV
| NETIF_MSG_PROBE | NETIF_MSG_LINK);
pegasus->features = usb_dev_id[dev_index].private;
get_interrupt_interval(pegasus);
if (reset_mac(pegasus)) {
dev_err(&intf->dev, "can't reset MAC\n");
res = -EIO;
goto out2;
}
set_ethernet_addr(pegasus);
fill_skb_pool(pegasus);
if (pegasus->features & PEGASUS_II) {
dev_info(&intf->dev, "setup Pegasus II specific registers\n");
setup_pegasus_II(pegasus);
}
pegasus->phy = mii_phy_probe(pegasus);
if (pegasus->phy == 0xff) {
dev_warn(&intf->dev, "can't locate MII phy, using default\n");
pegasus->phy = 1;
}
pegasus->mii.phy_id = pegasus->phy;
usb_set_intfdata(intf, pegasus);
SET_NETDEV_DEV(net, &intf->dev);
pegasus_reset_wol(net);
res = register_netdev(net);
if (res)
goto out3;
queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check,
CARRIER_CHECK_DELAY);
dev_info(&intf->dev, "%s, %s, %02x:%02x:%02x:%02x:%02x:%02x\n",
net->name,
usb_dev_id[dev_index].name,
net->dev_addr [0], net->dev_addr [1],
net->dev_addr [2], net->dev_addr [3],
net->dev_addr [4], net->dev_addr [5]);
return 0;
out3:
usb_set_intfdata(intf, NULL);
free_skb_pool(pegasus);
out2:
free_all_urbs(pegasus);
out1:
free_netdev(net);
out:
usb_put_dev(dev);
return res;
}
static void pegasus_disconnect(struct usb_interface *intf)
{
struct pegasus *pegasus = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
if (!pegasus) {
dev_dbg(&intf->dev, "unregistering non-bound device?\n");
return;
}
pegasus->flags |= PEGASUS_UNPLUG;
cancel_delayed_work(&pegasus->carrier_check);
unregister_netdev(pegasus->net);
usb_put_dev(interface_to_usbdev(intf));
unlink_all_urbs(pegasus);
free_all_urbs(pegasus);
free_skb_pool(pegasus);
if (pegasus->rx_skb)
dev_kfree_skb(pegasus->rx_skb);
free_netdev(pegasus->net);
}
static int pegasus_suspend (struct usb_interface *intf, pm_message_t message)
{
struct pegasus *pegasus = usb_get_intfdata(intf);
netif_device_detach (pegasus->net);
if (netif_running(pegasus->net)) {
cancel_delayed_work(&pegasus->carrier_check);
usb_kill_urb(pegasus->rx_urb);
usb_kill_urb(pegasus->intr_urb);
}
intf->dev.power.power_state = PMSG_SUSPEND;
return 0;
}
static int pegasus_resume (struct usb_interface *intf)
{
struct pegasus *pegasus = usb_get_intfdata(intf);
intf->dev.power.power_state = PMSG_ON;
netif_device_attach (pegasus->net);
if (netif_running(pegasus->net)) {
pegasus->rx_urb->status = 0;
pegasus->rx_urb->actual_length = 0;
read_bulk_callback(pegasus->rx_urb, NULL);
pegasus->intr_urb->status = 0;
pegasus->intr_urb->actual_length = 0;
intr_callback(pegasus->intr_urb, NULL);
queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check,
CARRIER_CHECK_DELAY);
}
return 0;
}
static struct usb_driver pegasus_driver = {
.name = driver_name,
.probe = pegasus_probe,
.disconnect = pegasus_disconnect,
.id_table = pegasus_ids,
.suspend = pegasus_suspend,
.resume = pegasus_resume,
};
static int __init pegasus_init(void)
{
pr_info("%s: %s, " DRIVER_DESC "\n", driver_name, DRIVER_VERSION);
pegasus_workqueue = create_singlethread_workqueue("pegasus");
if (!pegasus_workqueue)
return -ENOMEM;
return usb_register(&pegasus_driver);
}
static void __exit pegasus_exit(void)
{
destroy_workqueue(pegasus_workqueue);
usb_deregister(&pegasus_driver);
}
module_init(pegasus_init);
module_exit(pegasus_exit);
| Java |
########################################################################
#
# filepp 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; see the file COPYING. If not, write to
# the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
#
########################################################################
########################################################################
#
# Project : File Pre Processor - cpp module
# Filename : $RCSfile: Makefile.in,v $
# Originator : $Author: darren $
# Maintainer : Darren Miller: [email protected]
# File version : $Revision: 1.3 $
# Last changed : $Date: 2007/02/13 00:08:09 $
# Description : Makefile for cpp module
# Licence : GNU copyleft
#
########################################################################
##############################################################################
# Paths
##############################################################################
srcdir = .
datarootdir = ${prefix}/share
moduledir = /usr/local/share/filepp/modules
# top level of test build directory
TESTBUILD = ../../testbuild
TESTFILEPP = $(TESTBUILD)/bin/filepp
ECHO=echo
DIFF=diff
RM=rm -fr
INSTALL=/usr/bin/install -c
test:
@$(ECHO) ----------- Testing cpp.pm ----------------
$(TESTFILEPP) -m cpp.pm $(srcdir)/test.in -o test.out
$(DIFF) $(srcdir)/test.good test.out
@$(ECHO) ----------- Done --------------------------
install:
$(INSTALL) -m 644 $(srcdir)/cpp.pm $(moduledir)
clean:
$(RM) test.out
distclean:
$(RM) Makefile
##############################################################################
# End of file
##############################################################################
| Java |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
# Copyright (C) 2010 Benny Malengier
#
# 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.
#
#-------------------------------------------------------------------------
#
# Python classes
#
#-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.sgettext
#-------------------------------------------------------------------------
#
# GTK classes
#
#-------------------------------------------------------------------------
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject
from gi.repository import Pango
_TAB = Gdk.keyval_from_name("Tab")
_ENTER = Gdk.keyval_from_name("Enter")
#-------------------------------------------------------------------------
#
# Gramps classes
#
#-------------------------------------------------------------------------
from .surnamemodel import SurnameModel
from .embeddedlist import EmbeddedList, TEXT_EDIT_COL
from ...ddtargets import DdTargets
from gramps.gen.lib import Surname, NameOriginType
from ...utils import match_primary_mask, no_match_primary_mask
# table for skipping illegal control chars
INVISIBLE = dict.fromkeys(list(range(32)))
#-------------------------------------------------------------------------
#
# SurnameTab
#
#-------------------------------------------------------------------------
class SurnameTab(EmbeddedList):
_HANDLE_COL = 5
_DND_TYPE = DdTargets.SURNAME
_MSG = {
'add' : _('Create and add a new surname'),
'del' : _('Remove the selected surname'),
'edit' : _('Edit the selected surname'),
'up' : _('Move the selected surname upwards'),
'down' : _('Move the selected surname downwards'),
}
#index = column in model. Value =
# (name, sortcol in model, width, markup/text
_column_names = [
(_('Prefix'), 0, 150, TEXT_EDIT_COL, -1, None),
(_('Surname'), 1, -1, TEXT_EDIT_COL, -1, None),
(_('Connector'), 2, 100, TEXT_EDIT_COL, -1, None),
]
_column_combo = (_('Origin'), -1, 150, 3) # name, sort, width, modelcol
_column_toggle = (_('Primary', 'Name'), -1, 80, 4)
def __init__(self, dbstate, uistate, track, name, on_change=None,
top_label='<b>%s</b>' % _("Multiple Surnames") ):
self.obj = name
self.on_change = on_change
self.curr_col = -1
self.curr_cellr = None
self.curr_celle = None
EmbeddedList.__init__(self, dbstate, uistate, track, _('Family Surnames'),
SurnameModel, move_buttons=True,
top_label=top_label)
def build_columns(self):
#first the standard text columns with normal method
EmbeddedList.build_columns(self)
# now we add the two special columns
# combobox for type
colno = len(self.columns)
name = self._column_combo[0]
renderer = Gtk.CellRendererCombo()
renderer.set_property('ellipsize', Pango.EllipsizeMode.END)
# set up the comboentry editable
no = NameOriginType()
self.cmborig = Gtk.ListStore(GObject.TYPE_INT, GObject.TYPE_STRING)
self.cmborigmap = no.get_map().copy()
#sort the keys based on the value
keys = sorted(self.cmborigmap, key=lambda x: glocale.sort_key(self.cmborigmap[x]))
for key in keys:
if key != no.get_custom():
self.cmborig.append(row=[key, self.cmborigmap[key]])
additional = self.dbstate.db.get_origin_types()
if additional:
for type in additional:
if type:
self.cmborig.append(row=[no.get_custom(), type])
renderer.set_property("model", self.cmborig)
renderer.set_property("text-column", 1)
renderer.set_property('editable', not self.dbstate.db.readonly)
renderer.connect('editing_started', self.on_edit_start_cmb, colno)
renderer.connect('edited', self.on_orig_edited, self._column_combo[3])
# add to treeview
column = Gtk.TreeViewColumn(name, renderer, text=self._column_combo[3])
column.set_resizable(True)
column.set_sort_column_id(self._column_combo[1])
column.set_min_width(self._column_combo[2])
column.set_expand(False)
self.columns.append(column)
self.tree.append_column(column)
# toggle box for primary
colno += 1
name = self._column_toggle[0]
renderer = Gtk.CellRendererToggle()
renderer.set_property('activatable', True)
renderer.set_property('radio', True)
renderer.connect( 'toggled', self.on_prim_toggled, self._column_toggle[3])
# add to treeview
column = Gtk.TreeViewColumn(name, renderer, active=self._column_toggle[3])
column.set_resizable(False)
column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
column.set_alignment(0.5)
column.set_sort_column_id(self._column_toggle[1])
column.set_max_width(self._column_toggle[2])
self.columns.append(column)
self.tree.append_column(column)
## def by_value(self, first, second):
## """
## Method for sorting keys based on the values.
## """
## fvalue = self.cmborigmap[first]
## svalue = self.cmborigmap[second]
## return glocale.strcoll(fvalue, svalue)
def setup_editable_col(self):
"""
inherit this and set the variables needed for editable columns
Variable edit_col_funcs needs to be a dictionary from model col_nr to
function to call for
Example:
self.edit_col_funcs ={1: {'edit_start': self.on_edit_start,
'edited': self.on_edited
}}
"""
self.edit_col_funcs = {
0: {'edit_start': self.on_edit_start,
'edited': self.on_edit_inline},
1: {'edit_start': self.on_edit_start,
'edited': self.on_edit_inline},
2: {'edit_start': self.on_edit_start,
'edited': self.on_edit_inline}}
def get_data(self):
return self.obj.get_surname_list()
def is_empty(self):
return len(self.model)==0
def _get_surn_from_model(self):
"""
Return new surname_list for storing in the name based on content of
the model
"""
new_list = []
for idx in range(len(self.model)):
node = self.model.get_iter(idx)
surn = self.model.get_value(node, 5)
surn.set_prefix(self.model.get_value(node, 0))
surn.set_surname(self.model.get_value(node, 1))
surn.set_connector(self.model.get_value(node, 2))
surn.get_origintype().set(self.model.get_value(node, 3))
surn.set_primary(self.model.get_value(node, 4))
new_list += [surn]
return new_list
def update(self):
"""
Store the present data in the model to the name object
"""
new_map = self._get_surn_from_model()
self.obj.set_surname_list(new_map)
# update name in previews
if self.on_change:
self.on_change()
def post_rebuild(self, prebuildpath):
"""
Called when data model has changed, in particular necessary when row
order is updated.
@param prebuildpath: path selected before rebuild, None if none
@type prebuildpath: tree path
"""
if self.on_change:
self.on_change()
def column_order(self):
# order of columns for EmbeddedList. Only the text columns here
return ((1, 0), (1, 1), (1, 2))
def add_button_clicked(self, obj):
"""Add button is clicked, add a surname to the person"""
prim = False
if len(self.obj.get_surname_list()) == 0:
prim = True
node = self.model.append(row=['', '', '', str(NameOriginType()), prim,
Surname()])
self.selection.select_iter(node)
path = self.model.get_path(node)
self.tree.set_cursor_on_cell(path,
focus_column=self.columns[0],
focus_cell=None,
start_editing=True)
self.update()
def del_button_clicked(self, obj):
"""
Delete button is clicked. Remove from the model
"""
(model, node) = self.selection.get_selected()
if node:
self.model.remove(node)
self.update()
def on_edit_start(self, cellr, celle, path, colnr):
""" start of editing. Store stuff so we know when editing ends where we
are
"""
self.curr_col = colnr
self.curr_cellr = cellr
self.curr_celle = celle
def on_edit_start_cmb(self, cellr, celle, path, colnr):
"""
An edit starts in the origin type column
This means a cmb has been created as celle, and we can set up the stuff
we want this cmb to contain: autocompletion, stop edit when selection
in the cmb happens.
"""
self.on_edit_start(cellr, celle, path, colnr)
#set up autocomplete
entry = celle.get_child()
entry.set_width_chars(10)
completion = Gtk.EntryCompletion()
completion.set_model(self.cmborig)
completion.set_minimum_key_length(1)
completion.set_text_column(1)
entry.set_completion(completion)
#
celle.connect('changed', self.on_origcmb_change, path, colnr)
def on_edit_start_toggle(self, cellr, celle, path, colnr):
"""
Edit
"""
self.on_edit_start(cellr, celle, path, colnr)
def on_edit_inline(self, cell, path, new_text, colnr):
"""
Edit is happening. The model is updated and the surname objects updated.
colnr must be the column in the model.
"""
node = self.model.get_iter(path)
text = new_text.translate(INVISIBLE).strip()
self.model.set_value(node, colnr, text)
self.update()
def on_orig_edited(self, cellr, path, new_text, colnr):
"""
An edit is finished in the origin type column. For a cmb in an editor,
the model may only be updated when typing is finished, as editing stops
automatically on update of the model.
colnr must be the column in the model.
"""
self.on_edit_inline(cellr, path, new_text, colnr)
def on_origcmb_change(self, cmb, path, colnr):
"""
A selection occured in the cmb of the origin type column. colnr must
be the column in the model.
"""
act = cmb.get_active()
if act == -1:
return
self.on_orig_edited(None, path,
self.cmborig.get_value(
self.cmborig.get_iter((act,)),1),
colnr)
def on_prim_toggled(self, cell, path, colnr):
"""
Primary surname on path is toggled. colnr must be the col
in the model
"""
#obtain current value
node = self.model.get_iter(path)
old_val = self.model.get_value(node, colnr)
for nr in range(len(self.obj.get_surname_list())):
if nr == int(path[0]):
if old_val:
#True remains True
break
else:
#This value becomes True
self.model.set_value(self.model.get_iter((nr,)), colnr, True)
else:
self.model.set_value(self.model.get_iter((nr,)), colnr, False)
self.update()
return
def edit_button_clicked(self, obj):
""" Edit button clicked
"""
(model, node) = self.selection.get_selected()
if node:
path = self.model.get_path(node)
self.tree.set_cursor_on_cell(path,
focus_column=self.columns[0],
focus_cell=None,
start_editing=True)
def key_pressed(self, obj, event):
"""
Handles the key being pressed.
Here we make sure tab moves to next or previous value in row on TAB
"""
if not EmbeddedList.key_pressed(self, obj, event):
if event.type == Gdk.EventType.KEY_PRESS and event.keyval in (_TAB,):
if no_match_primary_mask(event.get_state(),
Gdk.ModifierType.SHIFT_MASK):
return self.next_cell()
elif match_primary_mask(event.get_state(), Gdk.ModifierType.SHIFT_MASK):
return self.prev_cell()
else:
return
else:
return
return True
def next_cell(self):
"""
Move to the next cell to edit it
"""
(model, node) = self.selection.get_selected()
if node:
path = self.model.get_path(node).get_indices()[0]
nccol = self.curr_col+1
if nccol < 4:
if self.curr_celle:
self.curr_celle.editing_done()
self.tree.set_cursor_on_cell(Gtk.TreePath((path,)),
focus_column=self.columns[nccol],
focus_cell=None,
start_editing=True)
elif nccol == 4:
#go to next line if there is one
if path < len(self.obj.get_surname_list()):
newpath = Gtk.TreePath((path+1,))
self.curr_celle.editing_done()
self.selection.select_path(newpath)
self.tree.set_cursor_on_cell(newpath,
focus_column=self.columns[0],
focus_cell=None,
start_editing=True)
else:
#stop editing
self.curr_celle.editing_done()
return
return True
def prev_cell(self):
"""
Move to the next cell to edit it
"""
(model, node) = self.selection.get_selected()
if node:
path = self.model.get_path(node).get_indices()[0]
if self.curr_col > 0:
self.tree.set_cursor_on_cell(Gtk.TreePath((path,)),
focus_column=self.columns[self.curr_col-1],
focus_cell=None,
start_editing=True)
elif self.curr_col == 0:
#go to prev line if there is one
if path > 0:
newpath = Gtk.TreePath((path-1,))
self.selection.select_path(newpath)
self.tree.set_cursor_on_cell(newpath,
focus_column=self.columns[-2],
focus_cell=None,
start_editing=True)
else:
#stop editing
self.curr_celle.editing_done()
return
return True
| Java |
--強欲な壺の精霊
function c4896788.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EVENT_CHAIN_SOLVING)
e1:SetCondition(c4896788.drcon)
e1:SetOperation(c4896788.drop)
c:RegisterEffect(e1)
end
function c4896788.drcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsAttackPos()
and re:IsHasType(EFFECT_TYPE_ACTIVATE) and re:GetHandler():IsCode(55144522)
end
function c4896788.drop(e,tp,eg,ep,ev,re,r,rp)
Duel.ChangeTargetParam(ev,3)
end
| Java |
package Qtopia::Vars;
use strict;
use warnings;
use File::Basename;
use Qtopia::Paths;
use Qtopia::File;
use Carp;
#perl2exe_include Carp::Heavy
$Carp::CarpLevel = 1;
use Digest::MD5 qw(md5_base64);
require Exporter;
our @ISA = qw(Exporter);
# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.
# This allows declaration use Qtopia::opt ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.
our %EXPORT_TAGS = ( 'all' => [ qw(
) ] );
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
our @EXPORT = qw(
$isWindows
$isMac
$qtopiaVersionStr
$qtVersionStr
$shadow
check_script
configopt
script_name
$depotpath
$SDKROOT
);
our $VERSION = '0.01';
# imported variables
our $depotpath;
our $SDKROOT;
use constant TRACE => 0;
# Platform detection
our $isWindows = ( $^O eq "MSWin32" );
our $isMac = ( $^O eq "darwin" );
our $qtopiaVersionStr;
our $qtVersionStr;
our @configureoptions;
our $shadow;
our $perl2exe_hash;
# Check for a bug in perl on RedHat 9.1
if ( !$isWindows ) {
TRACE and print "Qtopia::Vars::perl_bug_test()\n";
my $testfile = "/etc/passwd";
open IN, "$testfile" or die "Can't read $testfile";
my $common_perl_bug_test = <IN>;
close IN;
if ( !defined($common_perl_bug_test) ) {
die "ERROR: Your /etc/passwd file has no contents!";
}
unless ( $common_perl_bug_test =~ /[^\s]+/ ) {
warn "WARNING: Your perl has a bug with regular expressions and UTF-8\n";
# remove the UTF8 bit from the LANG environment variable and relaunch
my $lang = $ENV{LANG};
if ( !$lang ) {
die "ERROR: ".basename($0)." cannot work around the bug.\n";
}
unless ( $lang =~ s/\.UTF-?8//i ) {
die "ERROR: ".basename($0)." cannot work around the bug.\n";
}
warn "WARNING: ".basename($0)." will attempt to work around the bug by changing your\n".
" LANG variable from ".$ENV{LANG}." to $lang.\n";
$ENV{LANG} = $lang;
exec($0, @ARGV);
die "ERROR Could not relaunch ".basename($0);
}
# RedHat upgraded their perl so that it does not trigger the test above but now
# it overruns output data, potentially leading to an unexplained segfault.
# Try to detect RedHat 9 and just force the fix.
my $redhat_verfile = "/etc/redhat-release";
if ( -f $redhat_verfile ) {
open IN, $redhat_verfile or die "Can't read $redhat_verfile";
$_ = <IN>;
close IN;
if ( !defined($_) ) {
die "ERROR: Your /etc/redhat-release file has no contents!";
}
if ( /release 9/ ) {
my $lang = $ENV{LANG};
if ( $lang =~ /\.UTF-?8/i ) {
warn "WARNING: Your perl has a bug with output and UTF-8\n";
# remove the UTF8 bit from the LANG environment variable and relaunch
unless ( $lang =~ s/\.UTF-?8//i ) {
die "ERROR: ".basename($0)." cannot work around the bug.\n";
}
warn "WARNING: ".basename($0)." will attempt to work around the bug by changing your\n".
" LANG variable from ".$ENV{LANG}." to $lang.\n";
$ENV{LANG} = $lang;
exec($0, @ARGV);
die "ERROR Could not relaunch ".basename($0)."\n";
}
}
}
}
sub check_script
{
TRACE and print "Qtopia::Vars::check_script()\n";
my ( $script, $path, $arg ) = @_;
#print "check_script $script $path ".(defined($arg)?$arg:"")."\n";
my $compiled_code = 0;
if ( $script =~ /\.exe$/i ) {
$compiled_code = 1;
}
my $orig = "$path/".script_name($script);
# perl2exe test run bail out hook
if ( $compiled_code && defined($arg) && $arg eq "-nop" ) {
if ( !check_perl2exe_hash($orig) ) {
die "ERROR: Stored hash does not match script hash:\n".
" $0\n".
" ".fixpath($orig)."\n";
}
exit 0;
}
# If we're in the depot, run the perl scripts directly
if ( $compiled_code ) {
$script = script_name($script);
#print "running the perl script ".fixpath("$path/$script")."\n";
my @cmd = ( "perl", "$path/$script", @ARGV );
my $ret = system(@cmd);
$ret = $ret >> 8;
exit $ret;
}
# Windows doesn't set HOME but the build system expects it to be set!
$ENV{HOME} = $ENV{HOMEDRIVE}.$ENV{HOMEPATH};
}
# Check the md5sum embedded in the .exe file with the script it was built from
sub check_perl2exe_hash
{
my ( $orig ) = @_;
if ( !defined($perl2exe_hash) ) {
die "ERROR: Stored hash is missing!";
}
open IN, "$orig" or die "Can't read $orig";
my $data = join("", <IN>);
close IN;
my $md5 = md5_base64($data);
#print "stored hash $perl2exe_hash\n";
#print "script hash $md5\n";
if ( $perl2exe_hash eq $md5 ) {
return 1;
}
return 0;
}
# Is a particular value in the .configureoptions file
sub configopt
{
TRACE and print "Qtopia::Vars::configopt()\n";
my $dir = $depotpath;
if ( ! $dir ) {
$dir = $SDKROOT;
}
if ( ! $dir ) {
#Qtopia::Paths::get_vars();
croak "You must use Qtopia::Paths and call get_paths() before using Qtopia::Vars";
}
if ( ! @configureoptions ) {
if ( -f "$dir/LICENSE.GPL" ) {
push(@configureoptions, "free");
}
if ( -d "$dir/src/qtopiadesktop" ) {
push(@configureoptions, "desktop");
}
}
my ( $opt ) = @_;
if ( grep { $_ eq $opt } @configureoptions ) {
return 1;
}
return 0;
}
sub script_name
{
TRACE and print "Qtopia::Vars::script_name()\n";
my ( $script ) = @_;
$script = basename($script);
my $len = length $script;
my $compiled_code = 0;
if ( basename($script) =~ /\.exe$/i ) {
$compiled_code = 1;
}
if ( $compiled_code ) {
$len -= 4;
}
return substr($script, 0, $len);
}
# Make this file require()able.
1;
| Java |
/*
Take the Plunge Wedding Template
Table of Contents:
Reset
Common
Typography
Layout
Supersized Slideshow
Youtube Player
Parallax
Portfolio
About Us
Services
Features
Accordion
Tooltips
Contacts
Form Elements
Flickr
Alert Boxes
Footer
Our Clients
Misc
Media Queries
*/
/* #Reset & Basics (Inspired by E. Meyers)
--------------------------------------------------------*/
html, body {
height: 100%;
}
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/* Commons
--------------------------------------------------------*/
::-moz-selection {background: #af1b5a;color: white; }
::selection {background: #af1b5a;color: white; }
body {
background-color: #fff;
font: 15px 'Oswald', sans-serif;
font-weight: 300;
color: #222;
-webkit-font-smoothing: antialiased;
-webkit-text-size-adjust: 100%;
text-align: left;
width: 100%;
height: 100%;
}
.embed-container {
position: relative;
padding-bottom: 56.25%; /* 16/9 ratio */
padding-top: 30px; /* IE6 workaround*/
height: 0;
overflow: hidden;
}
.embed-container iframe,
.embed-container object,
.embed-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.hidden {
display: none;
}
.parallaxText {
display: table-cell;
vertical-align: middle;
}
img.scale-with-grid {
max-width: 100%;
height: auto; }
/* Typography
--------------------------------------------------------*/
h1, h2, h3, h4 {
font-weight: 300;
font-family: 'Oswald',sans-serif;
color: #222;
margin: 0 0 6px;
}
h1 {
font-size: 250px;
text-transform: uppercase;
position: relative;
letter-spacing: -2px;
text-align: left;
line-height: 0.8;
margin-bottom: 35px;
padding-top: 15px;
}
h1 span{
color: #7b133c;
font-size: 150px;
}
h2 {
font-size: 44px;
text-transform: uppercase;
position: relative;
}
h2.white { color: #222;}
h3 {font-size: 22px; line-height: 1; color: #555;}
h3.sectionTitle {
border-bottom: 1px solid #cacaca;
font-size: 28px;
line-height: 30px;
margin-bottom: 10px;
padding: 26px 0 6px;
}
.small {font-size: 36px; font-weight:300;}
.smallBold {font-size: 36px; font-weight:700;}
.medium {font-size: 44px; text-transform: uppercase;}
.mediumBold {font-size: 44px; font-weight:700; text-transform: uppercase;}
.large {font-size: 56px; text-transform: uppercase;}
.largeBold {font-size: 56px; font-weight:700; text-transform: uppercase;}
.author {font-size: 18px; font-weight:300;}
h4 {font-size: 22px;}
p {margin-bottom: 10px;}
p a {color: #222; text-decoration: none;}
p a:hover {color: #a90e4b;transition: color 0.5s;}
a {color:#222;text-decoration:none;}
a:hover{color:#a90e4b;}
.introtext {font-size: 20px;}
.marginTop {
margin-top: 30px;
}
.highlight {
background: #7b133c;
color: #FFFFFF;
padding: 0 6px;
}
.dropcap {
background: #7b133c;
color: #FFFFFF;
display: inline-block;
float: left;
font-size: 30px;
font-weight: bold;
height: 44px;
line-height: 44px;
margin: 7px 7px 0 0;
text-align: center;
width: 44px;
}
blockquote {
color: #999999;
display: block;
font-size: 20px;
font-style: italic;
letter-spacing: 0;
padding: 20px 50px 20px 40px;
position: relative;
}
blockquote:before, blockquote:after {
color: #7B133C;
content: "“";
font-size: 80px;
font-style: italic;
left: -25px;
line-height: 1em;
position: absolute;
top: 0;
}
blockquote:after {
content: "”";
float: right;
margin-right: -30px;
margin-top: 0;
position: relative;
}
/* Layout
--------------------------------------------------------*/
.homepage{
position:relative;
overflow:hidden;
z-index:1;
margin-bottom: -70px;
}
.page{
position:relative;
overflow:hidden;
z-index:2;
}
.page.desktop{
position:relative !important;
z-index:6;
}
.page {
padding-top: 100px;
}
.page{
background:#fff;
background-attachment:scroll;
}
nav {
background: #000;
background: rgba(0,0,0,0.8);
width: 100%;
position: relative;
z-index: 1000;
height: 50px;
text-align: center;
margin-bottom: 10px;
}
nav ul {
height: 40px;
display: inline-block;
padding-top: 10px;
padding-bottom: 15px;
}
nav ul li {
position: relative;
float: left;
margin: 0;
}
nav ul li a {
font-family: 'Oswald',sans-serif;
font-size: 18px;
font-weight: 400;
color: white;
text-decoration: none;
text-transform: uppercase;
padding: 10px;
}
nav ul li a:hover {
color: #a90e4b;
transition: color 0.5s;
}
.dropmenu {
display: none;
}
#homepage .container {
height: 100%;
}
.logo {
float: right;
margin-top: 50px;
}
/* supersized slideshow
--------------------------------------------------------*/
.slider-text {
width: 100%;
}
.slider-text {
bottom: 0px;
min-height: 220px;
overflow: hidden;
position: absolute;
}
#prevslide, #nextslide{
position:absolute;
height:40px;
width:40px;
top:64px;
margin-top:-21px;
opacity:0.8;
font-size: 32px;
color: #fff;
background: #000;
display: block;
text-align: center;
}
#prevslide{
right:60px;
}
#nextslide{
right:10px;
}
#prevslide:active, #nextslide:active{
margin-top:-19px;
}
#prevslide:hover, #nextslide:hover{
cursor:pointer;
}
#slidecaption h2, #slidecaption p{
text-shadow: 0 0 5px #000;
font-weight: 700;
font-size: 48px;
color: #fff
}
#slidecaption h2 span{
font-family: 'Shadows Into Light', cursive;
text-transform: capitalize;
font-size: 72px;
font-weight: 400;
}
#supersized-loader { position:absolute; top:50%; left:50%; z-index:0; width:60px; height:60px; margin:-30px 0 0 -30px; text-indent:-999em; background:url(../images/progress.gif) no-repeat center center;}
#supersized { display:block; position:absolute; left:0; top:0; overflow:hidden; z-index:-999; height:100%; width:100%; }
#supersized img { width:auto; height:auto; position:relative; display:none; outline:none; border:none; }
#supersized.speed img { -ms-interpolation-mode:nearest-neighbor; image-rendering: -moz-crisp-edges; } /*Speed*/
#supersized.quality img { -ms-interpolation-mode:bicubic; image-rendering: optimizeQuality; } /*Quality*/
#supersized li { display:block; list-style:none; z-index:-30; position:absolute; overflow:hidden; top:0; left:0; width:100%; height:100%; background:#111; }
#supersized a { width:100%; height:100%; display:block; }
#supersized li.prevslide { z-index:-20; }
#supersized li.activeslide { z-index:-10; }
#supersized li.image-loading { background:#111 url(../images/progress.gif) no-repeat center center; width:100%; height:100%; }
#supersized li.image-loading img{ visibility:hidden; }
#supersized li.prevslide img, #supersized li.activeslide img{ display:inline; }
/*parallax
--------------------------------------------------------*/
.parallax{
width:100%;
height:480px;
padding:0;
margin:0;
background-attachment:fixed;
background-repeat:no-repeat;
border-top:10px solid rgba(255,255,255,0.3);
border-bottom:10px solid rgba(255,255,255,0.3);
color:#fff;
position:relative;
}
.parallax .quoteWrap{
display:table;
width:100%;
height:100%;
padding:0 !important;
margin:0 !important;
}
.parallax.fixed{
background-attachment:fixed;
}
.parallax.fixed-desktop{
background-attachment:fixed !important;
}
.parallax .quoteWrap .quote{
display: table-cell;
vertical-align:middle;
}
.parallax {
text-align:center;
}
.parallax h3 span{
text-shadow: 0px 0px 5px #222;
color: #fff;
}
/* portfolio
--------------------------------------------------------*/
#folio {
background:url(../images/gallery-quote-white.png) center 80px no-repeat #fff;
padding-top:100px;
clear: left;
}
.portfolio_container {
position:relative;
display:block;
overflow:hidden;
width:100%;
}
.portfolio_container .portfolio {
position:relative;
display:block;
float:left;
overflow:hidden;
width:25%;
height:auto;
}
.portfolio_container .portfolio .media_box figure a img {
display:block;
margin-left: auto;
margin-right: auto;
}
.portfolio_container .portfolio .media_box .hover_effect {
top:0;
left:0;
}
.gallerySelector {
background: #E5E5E5;
height: 44px;
width: 100%;
margin-top: 20px;
}
.gallerySelectorList {
margin:0;
width: 100%;
}
.gallerySelectorList li {
float: left;
margin:0;
list-style:none;
width: 20%;
text-align: center;
padding: 0;
}
.gallerySelectorList li:hover {
background: #83103e;
}
.gallerySelectorList li:hover a {
color: #fff;
}
.gallerySelectorList li a {
display:block;
padding:11px 0;
color: #222;
text-decoration: none;
margin: 0;
transition:background-color 0.3s ease, color 0.2s ease;
}
.gallerySelectorList li.current {
background: #7b133c;
}
.gallerySelectorList li.current a {
color: #fff;
}
.portfolio_container .portfolio {
width: 20%;
}
.fullwidth {
display: block;
max-width: 100%;
min-width: 100%;
}
#gallery h3 {
margin-bottom: 20px;
}
.project-title {
font-family: 'Oswald', sans-serif;
font-size: 12px;
text-transform: uppercase;
margin-top: 7px;
}
.project-description {
color: #868991;
font-size: 10px;
text-transform: uppercase;
font-weight: 600;
margin: 0 0 20px 0;
}
.thumbLink {
display: block;
width: 100%;
}
.thumbImage {
float: left;
position: relative;
overflow: hidden;
display: block;
margin-bottom: 0px;
box-sizing: border-box;
text-align: center;
width: 100%;
height: 100%;
}
.thumbImage img{
transition: all 0.7s ease-in-out;
}
.thumbImage .thumbText h3 {
margin-bottom: 10px;
padding-top: 10px;
color: #fff;
border-bottom: 1px solid #fff;
transition: all 1s ease-in-out;
}
.thumbImage .thumbText p {
margin-bottom: 10px;
color: #fff;
transition: all 1s ease-in-out;
}
.thumbImage .thumbTextWrap {
position: absolute;
top: 0;
height: 100%;
opacity: 0;
max-width: 100%;
min-width: 100%;
background: #7b133c;
text-align: center;
transition: all 1s ease-in-out;
-webkit-user-select: none;
}
.ie8 .thumbImage .thumbTextWrap {
display:none;
}
.thumbImage .thumbTextWrap:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.5em; /* Adjusts for spacing */
}
.thumbText {
text-align: center;
transform: scale(0);
transition: all 0.7s ease-in-out;
display: inline-block;
vertical-align: middle;
width: 90%;
}
.thumbImage:hover img {
opacity: 0;
transform: scale(10);
}
.touch-device .thumbImage:hover img {
transform: none;
}
.thumbImage:hover .thumbTextWrap {
opacity: 1;
}
.ie8 .thumbImage:hover .thumbTextWrap {
display: block;
}
.thumbImage:hover .thumbText {
transform: scale(1);
}
.touch-device .thumbImage:hover .thumbTextWrap {
display: block;
}
.touch-device .thumbText,
.touch-device .thumbImage img,
.touch-device .thumbImage .thumbText h3,
.touch-device .thumbImage .thumbText p,
.touch-device .thumbImage .thumbTextWrap {
transition: none;
}
.ie8 .thumbImage:hover .thumbTextWrap {
display: block;
}
.thumbLink {
background:#fff;
color: #7A133C;
font-size: 20px;
width: 30px;
height: 30px;
border-radius: 15px;
opacity: 0.5;
margin: 0 auto;
}
.thumbLink:hover {
opacity: 1;
}
.portfolioBottom {
background: #E5E5E5;
height: 44px;
width: 100%;
clear: left;
}
/**** Isotope Filtering ****/
.isotope-item {
z-index: 2;
}
.isotope-hidden.isotope-item {
pointer-events: none;
z-index: 1;
}
/**** Isotope CSS3 transitions ****/
.isotope,
.isotope .isotope-item {
transition-duration: 0.8s;
}
.isotope {
transition-property: height, width;
}
.isotope .isotope-item {
-o-transition-property: top, left, opacity;
transition-property: transform, opacity;
}
/**** disabling Isotope CSS3 transitions ****/
.isotope.no-transition,
.isotope.no-transition .isotope-item,
.isotope .isotope-item.no-transition {
transition-duration: 0s;
}
/* End: Recommended Isotope styles */
/* disable CSS transitions for containers with infinite scrolling*/
.isotope.infinite-scrolling {
transition: none;
}
/* About Us
--------------------------------------------------------*/
#about {
padding-top: 0px;
}
.aboutContainer {
padding-bottom: 100px;
}
.teamImage {
margin-top: 40px;
margin-bottom: 20px;
cursor: default;
overflow: hidden;
position: relative;
text-align: center;
}
.teamImage img {
transform: scale(1);
transition: all 0.7s ease-in-out 0s;
}
.teamImage .teamName {
background-color: #7b133c;
opacity: 0;
transition: all 0.5s linear 0s;
height: 100%;
left: 0;
overflow: hidden;
position: absolute;
top: 0;
width: 100%;
text-align: center;
-webkit-user-select: none;
}
.touch-device .teamImage .teamName {
display: none;
transition: none;
}
.ie8 .teamImage .teamName {
display: none;
}
.teamImage h2 {
margin-top: 145px;
opacity: 0;
transform: scale(0);
color: #fff;
transition: all 0.5s linear 0s;
}
.teamImage h3 {
opacity: 0;
transform: scale(0);
color: #fff;
transition: all 0.7s linear 0s;
}
.teamImage:hover img {
opacity: 0;
transform: scale(10);
}
.teamImage:hover .teamName {
opacity: 1;
}
.touch-device .teamImage:hover .teamName {
display: block;
}
.touch-device .teamImage:hover img {
opacity: 0;
transform: none;
}
.ie8 .teamImage:hover .teamName {
display: block;
}
.teamImage:hover h2, .teamImage:hover h3 {
opacity: 1;
transform: scale(1);
}
.teamImage:hover .socialLinksTeam {
opacity: 1;
transform: scale(1);
}
.socialLinksTeam {
text-align: center;
width: 100%;
opacity: 0;
transform: scale(0);
transition: all 0.8s linear 0s;
}
.socialLinksTeam li {
display: inline-block;
height: 30px;
margin: 35px 1px 0;
transition: all 0.3s ease-in-out 0s;
width: 30px;
}
.socialLinksTeam li a {
color: #FFFFFF;
display: block;
font-size: 16px;
height: 16px;
margin: 0;
transition: all 0.3s ease-in-out 0s;
width: 16px;
opacity: 0.5;
}
.socialLinksTeam li:hover a {
opacity: 1;
}
.teamSkill {
margin-bottom: 40px;
-webkit-user-select: none;
}
p.skill {
clear: left;
font-size: 11px;
letter-spacing: 0.04em;
margin: 0;
text-transform: uppercase;
}
.bar {
background-color: #7B133C;
border-radius: 11px;
color: #FFFFFF;
display: inline-block;
float: left;
height: 22px;
line-height: 22px;
margin: 0 0 2px;
transition: all 0.6s ease-in-out 0s;
width: 22px;
}
.teamSkill:hover .percent100 {width: 100%;}
.teamSkill:hover .percent95 {width: 95%;}
.teamSkill:hover .percent90 {width: 90%;}
.teamSkill:hover .percent85 {width: 85%;}
.teamSkill:hover .percent80 {width: 80%;}
.teamSkill:hover .percent75 {width: 75%;}
.teamSkill:hover .percent70 {width: 70%;}
.teamSkill:hover .percent65 {width: 65%;}
.teamSkill:hover .percent60 {width: 60%;}
.teamSkill:hover .percent55 {width: 55%;}
.teamSkill:hover .percent50 {width: 50%;}
.teamSkill:hover .percent45 {width: 45%;}
.teamSkill:hover .percent40 {width: 40%;}
.teamSkill:hover .percent35 {width: 35%;}
.teamSkill:hover .percent30 {width: 30%;}
.teamSkill:hover .percent25 {width: 25%;}
.teamSkill:hover .percent20 {width: 20%;}
p.percent {
float: right;
margin-right: 6px;
text-align: right;
opacity: 0;
transition: all 0.6s ease-in-out 0s;
}
.ie8 p.percent {
display:none;
}
.teamSkill:hover p.percent {
opacity: 1;
}
.ie8 .teamSkill:hover p.percent {
display:block;
}
.statsWrap {
width: 130px;
margin: 10px;
float: left;
}
.stats {
display: inline-block;
position: relative;
width: 100%;
transition: all 0.3s ease-in-out 0s;
-webkit-user-select: none;
}
.statDummy {
margin-top: 100%;
}
.statInfo {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: #7B133C;
border-radius: 50%;
text-align: center;
}
.statNumber {
font-size: 60px;
transition: all 0.5s ease-in-out 0s;
padding-top: 24px;
margin-bottom: 0;
color: #fff;
}
.statNumberMedium {
font-size: 50px;
transition: all 0.5s ease-in-out 0s;
padding-top: 30px;
margin-bottom: 0;
}
.statNumberSmall {
font-size: 36px;
transition: all 0.5s ease-in-out 0s;
padding-top: 38px;
margin-bottom: 0;
}
.statText {
transition: all 0.5s ease-in-out 0s;
opacity: 0;
transform: scale(0);
padding: 0;
margin-top: -25px;
color: #fff;
}
.stats:hover {
transform: scale(2);
z-index: 10;
}
.stats:hover .statNumber {
transform: scale(.6);
}
.stats:hover .statText {
transform: scale(.6);
opacity: 1;
}
/* Services
--------------------------------------------------------*/
#services {
padding-top: 0;
}
.servicesContainer {
padding-bottom: 100px;
}
.serviceItem {
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
cursor: default;
height: 236px;
position: relative;
width: 236px;
margin: 20px auto;
}
.serviceInfoWrap, .serviceInfo {
height: 196px;
position: absolute;
width: 196px;
}
.serviceInfoWrap {
background: #F9F9F9;
box-shadow: 0 0 0 20px rgba(255,255,255, 0.4), 0 0 3px rgba(115, 114, 23, 0.8) inset;
left: 20px;
top: 20px;
}
.serviceInfo > div {
background-position: center center;
display: block;
height: 100%;
position: absolute;
width: 100%;
text-align: center;
}
.serviceInfo .serviceInfoFront {
transition: all 0.6s ease-in-out 0s;
}
.serviceInfo .serviceInfoBack {
background:#7B133C;
opacity: 0;
pointer-events: none;
transform: scale(1.5);
transition: all 0.4s ease-in-out 0.2s;
-webkit-user-select: none;
}
.ie8 .serviceInfo .serviceInfoBack {
display: none;
}
.copywriting, .copywriting .serviceInfoFront {background-image: url(../images/services/copywriting.jpg);}
.creativity, .creativity .serviceInfoFront {background-image: url(../images/services/creativity.jpg);}
.production, .production .serviceInfoFront {background-image: url(../images/services/production.jpg);}
.development, .development .serviceInfoFront {background-image: url(../images/services/development.jpg);}
.photography, .photography .serviceInfoFront {background-image: url(../images/services/photography.jpg);}
.strategy, .strategy .serviceInfoFront {background-image: url(../images/services/strategy.jpg);}
.serviceInfo h3 {
color: #FFFFFF;
font-size: 18px;
margin: 0 15px;
padding: 0 0 10px;
text-align: center;
text-transform: uppercase;
}
.serviceInfo p {
border-top: 1px solid rgba(255, 255, 255, 0.5);
color: #FFFFFF;
margin: 0 20px;
padding: 5px 10px 0;
}
.serviceIcon {
width: 35px;
height: 35px;
margin: 20px auto 10px auto;
}
.serviceIcon i{
color: #fff;
font-size: 32px;
}
.serviceItem:hover .serviceInfoFront {
opacity: 0;
transform: scale(0);
}
.serviceItem:hover .serviceInfoBack {
opacity: 1;
pointer-events: auto;
transform: scale(1);
}
.ie8 .serviceItem:hover .serviceInfoBack {
display: block;
}
/* Features
--------------------------------------------------------*/
#features {
padding-top: 0px;
}
.featuresContainer {
padding-bottom: 100px;
}
/* Accordion
--------------------------------------------------------*/
.accTrigger {
cursor: pointer;
display: block;
margin: 10px 0;
background: #e5e5e5;
border-radius: 6px;
border-left: 3px solid #7B133C;
}
.accTrigger a {
display: block;
color: #222;
outline: none;
padding: 10px;
text-decoration: none;
font-size: 24px;
}
.accTrigger.active a {
cursor: default;
color: #9c2252;
}
.accTrigger.active a:hover {
}
.accTrigger a:hover {
color: #9c2252;
}
.accContainer .content{
padding: 2px 15px 5px 15px;
line-height: 19px;
}
.accContent p {
margin-bottom: 10px;
}
.accContent {
padding: 5px 13px 20px 13px;
}
/* Tooltip
--------------------------------------------------------*/
.tooltip {
position: absolute;
z-index: 1020;
display: block;
padding: 5px;
font-size: 12px;
opacity: 0;
filter: alpha(opacity=0);
visibility: visible;
}
.tooltip.in {
opacity: 0.8;
filter: alpha(opacity=80);
}
.tooltip.top {
margin-top: -2px;
}
.tooltip.right {
margin-left: 2px;
}
.tooltip.bottom {
margin-top: 2px;
}
.tooltip.left {
margin-left: -2px;
}
.tooltip.top .tooltip-arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-top: 5px solid #555;
border-right: 5px solid transparent;
border-left: 5px solid transparent;
}
.tooltip.left .tooltip-arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
border-left: 5px solid #555;
}
.tooltip.bottom .tooltip-arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-right: 5px solid transparent;
border-bottom: 5px solid #555;
border-left: 5px solid transparent;
}
.tooltip.right .tooltip-arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-right: 5px solid #555;
border-bottom: 5px solid transparent;
}
.tooltip-inner {
max-width: 200px;
padding: 4px 10px;
color: #222;
text-align: center;
text-decoration: none;
background-color: #555;
border-radius: 6px;
}
.tooltip-arrow {
position: absolute;
width: 0;
height: 0;
}
/*contact
--------------------------------------------------------*/
.contactContainer {
padding-bottom: 100px;
}
.contactDetails li span {
padding-right: 5px;
color: #555;
font-size: 12px;
}
.icon-spacer {
padding-left: 12px;
}
.socialLinks {
text-align: center;
}
.socialLinks li {
background-color: #7B133C;
border-radius: 50% 50% 50% 50%;
float: left;
height: 60px;
margin: 10px 5px;
transition: all 0.6s ease-in-out 0s;
width: 60px;
}
.socialLinks li a {
display: block;
}
.socialLinks li a i {
color: #FFFFFF;
display: block;
font-size: 32px;
height: 30px;
margin: 15px 0 0 15px;
width: 30px;
}
.socialLinks li:hover {
background-color: #8A97A6;
}
/*form elements
--------------------------------------------------------*/
textarea {
height:156px;
padding:20px;
margin-bottom:20px;
overflow:auto;
}
.formSecWrap {
float: left;
margin-right: 20px;
}
.formSecWrap2 {
margin-right: 0px;
}
input[type="text"], input[type="password"], input[type="email"], textarea, select {
background: #e5e5e5;
border: none;
border-radius: 3px;
color: #222;
display: block;
margin: 0 0 10px 0;
outline: medium none;
padding: 4px 4px;
width: 370px;
font-family:'Oswald', sans-serif;
font-size: 16px;
font-weight: 400;
}
input[type="text"]:focus, input[type="password"]:focus, input[type="email"]:focus, textarea:focus {
box-shadow: 0 0 7px #222;
}
.formWrap label{
margin: 0 0 2px 0;
}
.formWrap input[type="submit"]{
margin: 10px 0 20px 0;
float: right;
}
a.button,
button,
input[type="submit"],
input[type="reset"],
input[type="button"] {
background: #7b133c;
border: none;
padding: 4px 12px;
border-radius: 0;
font-family: 'Oswald', sans-serif;
color: #fff;
display: inline-block;
font-size: 13px;
text-decoration: none;
cursor: pointer;
margin: 0 5px 10px 0;
line-height: 21px;
-webkit-appearance: none;
}
a.button:hover,
button:hover,
input[type="submit"]:hover,
input[type="reset"]:hover,
input[type="button"]:hover {
color: #222;
background: #ddd;
}
/* Flickr
--------------------------------------------------------*/
.flickrListing {
margin-right: -12px;
margin-top: 15px;
margin-bottom: 25px;
}
.flickrListing img {
display: block;
width: 100%;
}
.flickrListing a {
float: left;
margin-right: 12px;
margin-bottom: 12px;
border: 1px solid #333;
padding: 3px;
transition: all 0.2s ease-in-out;
}
.flickrListing a:hover {
border: 1px solid #222;
}
/* Alert Boxes
--------------------------------------------------------*/
.alert {
padding: 8px 35px 8px 14px;
margin-bottom: 10px;
margin-top: 10px;
clear: left;
color: #c09853;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
background-color: #fcf8e3;
border: 1px solid #fbeed5;
border-radius: 3px;
}
.alert h4 {
margin: 0;
}
.alert p {
margin: 0;
}
.alert .close {
position: relative;
top: -2px;
right: -35px;
line-height: 20px;
}
.alert-success {
color: #468847;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.alert-danger,
.alert-error {
color: #b94a48;
background-color: #f2dede;
border-color: #eed3d7;
}
.alert-info {
color: #3a87ad;
background-color: #d9edf7;
border-color: #bce8f1;
}
button.close {
background: none;
border: 0 none;
cursor: pointer;
padding: 0;
}
.close {
color: #000000;
float: right;
font-size: 20px;
font-weight: bold;
line-height: 20px;
opacity: 0.2;
text-shadow: 0 1px 0 #FFFFFF;
}
/*footer
--------------------------------------------------------*/
#footer{
position:relative;
overflow:hidden;
padding:30px 0 50px 0;
z-index:1;
background:#fff;
}
#footer p.copyright{
margin-bottom:0;
margin-top: 20px;
text-align: center;
color: #888888;
}
/* Our Clients
--------------------------------------------------------*/
.flex-container a:active, .flexslider a:active, .flex-container a:focus, .flexslider a:focus {
outline: medium none;
}
.slides, .flex-control-nav, .flex-direction-nav {
list-style: none outside none;
margin: 0;
padding: 0;
}
.slides li {
margin: 0;
}
.flexslider {
margin: 0;
padding: 0;
}
.flexslider .slides > li {
backface-visibility: hidden;
display: none;
}
.flex-pauseplay span {
text-transform: capitalize;
}
.slides:after {
clear: both;
content: ".";
display: block;
height: 0;
line-height: 0;
visibility: hidden;
}
html[xmlns] .slides {
display: block;
}
* html .slides {
height: 1%;
}
.no-js .slides > li:first-child {
display: block;
}
.flexslider {
position: relative;
z-index: 1;
}
.flexslider .slides > li {
position: relative;
}
.flex-container {
position: relative;
}
.flexslider .slides img {
display: block;
margin: auto;
max-width: 100%;
}
.flex-direction-nav a {
cursor: pointer;
display: block;
height: 60px;
margin: -30px 0 0;
opacity: 0;
position: absolute;
top: 50%;
width: 30px;
background: #555;
font-family: 'surreal';
font-size: 32px;
color: #fff;
line-height: 60px;
}
.flex-direction-nav a:hover {
color: #999;
}
.flex-direction-nav a.flex-next:before {
content: "\e016";
}
.flex-direction-nav a.flex-prev:before {
content: "\e013";
}
.flex-direction-nav a.flex-next {
right: 0;
border-radius:30px 0 0 30px;
}
.flex-direction-nav a.flex-prev {
left: 0;
border-radius:0 30px 30px 0;
}
.flexslider:hover .flex-next {
opacity: 1;
right: 0;
}
.flexslider:hover .flex-prev {
left: 0;
opacity: 1;
}
.flex-direction-nav .disabled {
cursor: default;
opacity: 0.3 !important;
}
.flex-direction-nav .flex-next {
right: -30px;
}
.flex-direction-nav .flex-prev {
left: -30px;
}
#carouselSlider, #carouselSlider .slides, #carouselSlider .slides li {
height: 120px;
}
#carouselSlider li {
border-right: 1px solid #333;
}
.flex-control-nav {
margin-top: 20px;
position: absolute;
text-align: center;
width: 100%;
z-index: 99;
}
.flex-control-nav li {
display: inline-block;
margin: 0 0 0 3px;
}
.flex-control-nav li:first-child {
margin: 0;
}
.flex-control-nav li a {
cursor: pointer;
display: block;
height: 14px;
text-indent: -9000px;
width: 14px;
}
.flex-control-nav li a:hover {
background-position: 0 0;
}
.flex-control-nav li a.active {
background-position: 0 -14px;
cursor: default;
}
/* Blog
--------------------------------------------------------*/
.blogTitle {
margin-top: -80px;
}
.blogTitlePost h2{
font-size: 125px;
text-transform: uppercase;
position: relative;
letter-spacing: -2px;
text-align: left;
line-height: 0.8;
margin-bottom: 35px;
padding-top: 0px;
}
.blogTitlePost h2 span{
color: #7B133C;
font-size: 75px;
}
.post {
margin-bottom: 50px;
border-top: 1px solid #333333;
padding-top: 20px;
}
.post-title h3{
font-size: 30px;
}
.dateWrap {
background: #7B133C;
padding: 10px;
position: absolute;
margin-top: 10px;
z-index: 2000;
color: #fff;
}
.date-day {
font-size: 48px;
}
.post-media {
margin: 10px 0 20px 0;
}
.post-media img{
border-bottom: 10px solid #7B133C;
}
.post-body div a {
background: #7B133C;
padding: 2px 10px;
color: #fff;
}
.post-body div a:hover {
background: #333333;
}
.tags {
margin: 30px 0;
overflow: auto;
}
.tags a {
color: #FFFFFF;
float: left;
font-weight: 300;
height: 26px;
line-height: 26px;
margin-bottom: 5px;
margin-right: 5px;
padding: 3px 8px;
text-transform: uppercase;
transition: background-color 0.3s ease 0s;
background: #c3c3c3;
border-left: 1px solid #7B133C;
}
.tags a:hover {
background-color: #7B133C;
}
/* Comments */
#comments {
border-top: 1px solid #333333;
margin-top: 40px;
padding-top: 20px;
clear: both;
}
#comments [class*="span"] {
-moz-box-sizing: border-box;
display: block;
float: left;
margin-left: 2.5641%;
min-height: 30px;
width: 100%;
}
#comments .span11 {
width: 91.453%;
}
.comment-body > .span11 > p:last-child {
margin-bottom: 0;
}
.comment-body > .span11 > p a {
color: #AAAAAA;
}
.comment-body > .span11 > p a:hover {
color: #555555;
}
#commentform [class*="span"] {
margin-left: 0;
}
#comments .span12 {
margin-left: 0;
}
#comments .span1 {
margin-left: 0;
width: 5.98291%;
}
#comments li {
background: none repeat scroll 0 0 transparent;
padding-left: 0;
}
#comments p {
margin-bottom: 20px;
}
#comments .comment-body {
margin-bottom: 10px;
}
#comments-title {
font-size: 28px;
margin-bottom: 30px;
}
#comments-title span {
color: #7B133C;
font-size: 14px;
font-weight: 400;
line-height: 10px;
padding: 0 5px;
vertical-align: middle;
}
.commentlist, #comments .children {
list-style-type: none;
margin: 0;
padding: 0;
}
.pe-offset1 {
margin-left: 8.54701% !important;
}
.commentlist {
margin-bottom: 40px;
}
.row-fluid {
width: 100%;
}
.row-fluid:before, .row-fluid:after {
content: "";
display: table;
line-height: 0;
}
.row-fluid:after {
clear: both;
}
.comment-author img {
border: 2px solid #F5F5F5;
display: block;
max-width: 100%;
}
.bypostauthor > .comment-body > .comment-author img {
border: 2px solid #7B133C;
}
.bypostauthor > .comment-body .fn a {
color: #7B133C;
}
.bypostauthor > .comment-body p {
color: #666666;
}
#comments .fn {
font-weight: 700;
margin-top: 2px;
}
.fn a {
color: #AAAAAA;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
}
.comment-body .fn, .comment-body .says {
float: left;
font-size: 14px;
}
.says {
margin-left: 5px;
margin-top: 2px;
}
#comments [id*="div-comment"] .span11 {
background: #C3C3C3;
padding: 10px;
position: relative;
}
#comments .comment-arrow {
border-bottom: 14px solid transparent;
border-right: 14px solid #333333;
border-top: 14px solid transparent;
height: 0;
left: -14px;
position: absolute;
top: 13px;
width: 0;
}
#comments .fn a:hover {
color: #555555;
text-decoration: none;
}
#comments .comment-meta {
clear: both;
margin-bottom: 10px;
}
#comments .comment-meta a {
color: #AAAAAA;
font-size: 13px;
}
#comments .comment-meta a:hover {
color: #666666;
text-decoration: none;
}
#comments .reply {
float: right;
}
#comments .reply .label {
background-color: #7B133C;
color: #FFFFFF;
font-size: 10px;
padding: 4px 8px;
text-shadow: none;
text-transform: uppercase;
}
#comments .reply .label:hover {
background-color: #555555;
}
#comments .post-pagination {
margin-bottom: 60px;
}
#comments .pagination .active a {
background-color: #666666;
border-color: #666666;
color: #FFFFFF;
}
#respond {
margin-bottom: 50px;
}
#respond #reply-title {
color: #BBBBBB;
font-size: 22px;
font-weight: 400;
margin-bottom: 40px;
}
#commentform .comment-notes {
color: #AAAAAA;
font-size: 12px;
}
#commentform .comment-notes a {
color: #7B133C;
}
#commentform .comment-notes a:hover {
color: #555555;
}
#commentform label {
color: #fff;
padding-top: 0;
text-align: left;
width: auto;
position: absolute;
left: 0px;
top: 0px;
}
#commentform .controls {
margin-left: 0;
}
#commentform .controls input {
border-radius: 0 0 0 0;
float: left;
margin-right: 30px;
}
#commentform .control-group .required {
color: #7B133C;
margin-left: 3px;
margin-top: 3px;
}
#commentform .control-group {
position: relative;
float: left;
width: 33.3%
}
#commentform .control-label {
float: left;
text-align: left;
}
#comment input[type="text"], #commentform textarea {
width: 400px;
}
#commentform input[type="text"] {
margin-right: 20px;
}
#commentform .comment-form-comment .controls {
clear: both;
float: none;
}
#commentform textarea {
width: 100%;
}
#commentform .form-submit .controls {
margin-left: 0;
}
#commentform .form-submit button[type="submit"] {
background: none repeat scroll 0 0 #7B133C;
border: 0 none;
border-radius: 0;
box-shadow: none;
clear: both;
color: #FFFFFF;
float: left;
font-family: 'Oswald', sans-serif;
font-size: 13px;
height: 40px;
padding: 5px 10px;
text-shadow: none;
text-transform: uppercase;
transition: all 0.3s ease-out 0s;
}
#commentform .form-submit button[type="submit"]:hover {
background-color: #555555;
color: #FFFFFF;
}
#commentform input[type="text"], #commentform textarea {
background-color: #333333;
border-radius: 0px;
box-shadow: none;
color: #D0D0D0;
font-size: 14px;
min-height: 30px;
padding: 5px 10px;
font-weight: 400;
}
#commentform input[type="text"]:focus, #commentform textarea:focus {
border-color: #7B133C;
}
#commentform input[type="text"] {
height: 30px;
width: 96%;
}
#commentform .comment-form-url input[type="text"] {
width: 100%;
}
#commentform .control-group .controls {
float: left;
margin-left: 0 !important;
overflow: hidden;
padding-top: 22px;
width: 100%;
}
.comment-form-comment .controls {
float: none;
width: 98%;
}
#commentform .comment-form-comment {
width: 100%
}
#commentform .comment-form-comment .controls{
padding-top: 0px;
}
.form-horizontal .control-group:before, .form-horizontal .control-group:after {
content: "";
line-height: 0;
}
.form-horizontal .control-group:after {
clear: both;
}
.form-horizontal .control-label {
float: left;
padding-top: 5px;
text-align: right;
width: 160px;
}
.form-horizontal .controls {
margin-left: 180px;
}
.form-horizontal .controls:first-child {
}
.form-horizontal .help-block {
margin-bottom: 0;
}
.form-horizontal input + .help-block, .form-horizontal select + .help-block, .form-horizontal textarea + .help-block {
margin-top: 10px;
}
.form-horizontal .form-actions {
padding-left: 180px;
}
/* Widgets */
.sidebar {
margin-bottom: 60px;
padding-top: 20px;
border-top: 1px solid #333333;
}
.sidebar .widget {
font-size: 16px;
line-height: 20px;
margin-bottom: 20px;
}
.sidebar h3 {
border-bottom: 1px solid #333333;
font-size: 28px;
line-height: 30px;
margin-bottom: 10px;
padding: 26px 0 6px;
}
.widget_search {
position: relative;
}
.widget_search button[type="submit"] {
background-color: transparent;
background-position: -44px 7px;
border: 0 none;
cursor: pointer;
height: 27px;
opacity: 0.4;
padding: 5px 10px 8px 5px;
position: absolute;
right: 4px;
top: 4px;
width: 26px;
}
.widget_search button[type="submit"]:hover {
opacity: 0.7;
}
.widget_search input[type="text"] {
background-color: #C3C3C3;
border-radius: 0;
box-shadow: none;
color: #222222;
display: block;
font-size: 12px;
height: 30px;
padding: 2px 10px;
transition: border-color 0.3s ease 0s;
width: 85%;
margin: 0;
box-sizing: border-box;
float: left;
}
.widget_search input[type="text"]:focus {
border-color: #7B133C;
}
.widget_search input[type="submit"] {
width: 15%;
margin: 0;
box-sizing: border-box;
}
.widget_text {
margin-bottom: 65px;
}
.widget_categories ul li {
color: #CCCCCC;
font-size: 11px;
}
.widget_categories a {
color: #666666;
font-size: 16px;
margin-right: 10px;
}
.widget_categories a:hover {
color: #D95137;
}
.widget_archive li {
color: #999999;
font-size: 11px;
}
.widget_archive a {
font-size: 16px;
margin-right: 9px;
}
.widget_menu li:before {
content: "";
}
.widget_menu a {
border: 1px solid #EEEEEE;
height: 26px;
line-height: 26px;
text-shadow: none !important;
text-transform: uppercase;
}
.widget_menu a:hover {
background-color: #DDDDDD;
color: #666666;
}
.widget_menu li.active a {
background: url("../../styles/../img/skin/sidebar_menu_active.png") no-repeat scroll 95% 50% #D95137;
color: #FFFFFF;
}
.widget_menu li.active a:hover {
background-color: #D95137;
color: #FFFFFF;
cursor: default;
}
.widget_tag_cloud li:before {
content: "";
}
.widget_tag_cloud a {
color: #FFFFFF;
float: left;
font-weight: 300;
height: 26px;
line-height: 26px;
margin-bottom: 5px;
margin-right: 5px;
padding: 3px 8px;
text-transform: uppercase;
transition: background-color 0.3s ease 0s;
background: #c3c3c3;
border-left: 1px solid #7B133C;
}
.widget_tag_cloud a:hover {
background-color: #7B133C;
color: #FFFFFF;
}
.widget_tag_cloud .tagcloud {
overflow: hidden;
}
.widget_calendar li:before {
content: "";
}
.widget_calendar #wp-calendar {
color: #999999;
text-align: center;
width: 100%;
}
.widget_calendar caption, .widget_calendar th, .widget_calendar td {
text-align: center;
padding-top: 2px;
padding-bottom: 2px;
}
.widget_calendar caption {
color: #fff;
font-size: 16px;
padding: 25px 0 12px;
text-align: left;
text-transform: uppercase;
}
.widget_calendar th {
background: #C3C3C3;
border-bottom: 0 none;
border-top: 0 none;
font-weight: 600;
padding-bottom: 5px;
padding-top: 5px;
color: #fff;
}
.widget_calendar tbody td a {
background: #E4E4E4;
padding: 0px 5px;
width: 100%;
}
.widget_calendar tfoot td a:hover {
background: #F6F6F6;
}
.widget_calendar tfoot td {
background: none repeat scroll 0 0 transparent;
border-bottom: 0 none;
border-top: 0 none;
}
.widget_calendar tfoot td a {
color: #666666;
text-transform: uppercase;
}
.widget_calendar tfoot td a:hover {
background: none repeat scroll 0 0 transparent;
color: #fff;
}
.widget_calendar tfoot #prev {
text-align: left;
}
.widget_calendar tfoot #next {
text-align: right;
}
.widget_links ul {
list-style-type: none;
margin: 0;
padding: 0;
}
.sidebar li:before {
color: #7B133C;
content: "\e016";
display: inline-block;
font-family: 'surreal';
font-size: 13px;
font-style: normal;
font-weight: normal;
line-height: 1em;
margin-right: 0.2em;
margin-top: 9px;
text-align: center;
text-decoration: inherit;
width: 1em;
transition: all 0.3s ease-in-out;
}
.sidebar li span {
color: #CCCCCC;
font-size: 10px;
font-style: italic;
margin-left: 15px;
}
.widget_links li a,
.widget_pages li a,
.widget_meta li a,
.widget_archive li a,
.widget_calendar tbody td a,
.widget_categories li a,
.widget_recent_entries li a,
.widget_recent_comments li a {
color: #999999;
transition: all 0.3s ease-in-out;
}
.widget_links li a:hover,
.widget_pages li a:hover,
.widget_meta li a:hover,
.widget_archive li a:hover,
.widget_categories li a:hover,
.widget_calendar tbody td a:hover,
.widget_recent_entries li a:hover,
.widget_recent_comments li a:hover {
color: #222;
text-decoration: none;
}
.widget_recent_entries {
font-size: 16px;
margin-right: 0;
}
.widget_recent_entries p {
margin-top: 25px;
}
.comments-num {
display: block;
float: right;
width: 28px;
}
.widget_recent_entries span {
text-transform: lowercase;
}
/* Custom Font
--------------------------------------------------------*/
@font-face {
font-family: 'surreal';
src:url('../fonts/surreal.eot');
src:url('../fonts/surreal.eot?#iefix') format('embedded-opentype'),
url('../fonts/surreal.woff') format('woff'),
url('../fonts/surreal.ttf') format('truetype'),
url('../fonts/surreal.svg#surreal') format('svg');
font-weight: normal;
font-style: normal;
}
/* Use the following CSS code if you want to use data attributes for inserting your icons */
[data-icon]:before {
font-family: 'surreal';
content: attr(data-icon);
speak: none;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
-webkit-font-smoothing: antialiased;
}
/* Use the following CSS code if you want to have a class per icon */
/*
Instead of a list of all class selectors,
you can use the generic selector below, but it's slower:
[class*="icon-"] {
*/
.icon-location, .icon-envelop, .icon-phone, .icon-print, .icon-clock, .icon-arrow-right, .icon-arrow-left, .icon-twitter, .icon-google-plus, .icon-facebook, .icon-flickr, .icon-skype, .icon-linkedin, .icon-pinterest, .icon-youtube, .icon-vimeo, .icon-dribbble, .icon-feed, .icon-plus, .icon-arrow-left-2, .icon-arrow-down, .icon-arrow-up, .icon-arrow-right-2, .icon-quote, .icon-search, .icon-brush, .icon-share, .icon-mobile, .icon-camera, .icon-camera-2, .icon-quill {
font-family: 'surreal';
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
-webkit-font-smoothing: antialiased;
}
.icon-location:before {
content: "\e001";
}
.icon-envelop:before {
content: "\e002";
}
.icon-phone:before {
content: "\e003";
}
.icon-print:before {
content: "\e004";
}
.icon-clock:before {
content: "\e005";
}
.icon-arrow-right:before {
content: "\e006";
}
.icon-arrow-left:before {
content: "\e007";
}
.icon-twitter:before {
content: "\e008";
}
.icon-google-plus:before {
content: "\e009";
}
.icon-facebook:before {
content: "\e00a";
}
.icon-flickr:before {
content: "\e00b";
}
.icon-skype:before {
content: "\e00c";
}
.icon-linkedin:before {
content: "\e00d";
}
.icon-pinterest:before {
content: "\e00e";
}
.icon-youtube:before {
content: "\e00f";
}
.icon-vimeo:before {
content: "\e010";
}
.icon-dribbble:before {
content: "\e011";
}
.icon-feed:before {
content: "\e012";
}
.icon-plus:before {
content: "\e000";
}
.icon-arrow-left-2:before {
content: "\e013";
}
.icon-arrow-down:before {
content: "\e014";
}
.icon-arrow-up:before {
content: "\e015";
}
.icon-arrow-right-2:before {
content: "\e016";
}
.icon-quote:before {
content: "\e017";
}
.icon-search:before {
content: "\e018";
}
.icon-brush:before {
content: "\e019";
}
.icon-share:before {
content: "\e01a";
}
.icon-mobile:before {
content: "\e01b";
}
.icon-camera:before {
content: "\e01c";
}
.icon-camera-2:before {
content: "\e01d";
}
.icon-quill:before {
content: "\e01e";
}
/* MISC
--------------------------------------------------------*/
.clear{float:none;}
/* Media Queries
--------------------------------------------------------*/
/* Smaller than standard 1199 (devices and browsers) */
@media only screen and (max-width: 1199px) {
.parallax.fixed{background-attachment:scroll; background-position: center center;}
}
/* Higher than 960 (desktop devices) */
@media only screen and (min-width: 960px) and (max-width: 1199px) {
.teamImage h2 {margin-top: 105px; font-size:40px;}
input[type="text"], input[type="password"], input[type="email"], textarea, select {width: 290px;}
}
/* Smaller than standard 960 (devices and browsers) */
@media only screen and (max-width: 959px) {
.small {font-size: 30px; font-weight:300;}
.smallBold {font-size: 30px; font-weight:700;}
.medium {font-size: 38px; text-transform: uppercase;}
.mediumBold {font-size: 38px; font-weight:700; text-transform: uppercase;}
.large {font-size: 50px; text-transform: uppercase;}
.largeBold {font-size: 50px; font-weight:700; text-transform: uppercase;}
.author {font-size: 16px; font-weight:300;}
}
/* Tablet Portrait size to standard 960 (devices and browsers) */
@media only screen and (min-width: 768px) and (max-width: 959px) {
h1 {font-size: 200px;}
.teamImage h2 {margin-top: 75px; font-size:32px;}
input[type="text"], input[type="password"], input[type="email"], textarea, select {width: 226px;}
.parallax.fixed{background-attachment:scroll; background-position: center center;}
.blogTitle {margin-top: -40px;}
}
/* All Mobile Sizes (devices and browser) */
@media only screen and (max-width: 767px) {
.dropmenu { display: block; margin-top: 5px; }
#nav {display: none;}
#slidecaption { display:none;}
#prevslide, #nextslide{top:120px;}
.parallax.fixed{background-attachment:scroll; background-position: center center;}
.logo {margin-top: 10px; transform: scale(.5);}
#prevslide {right: 45px; transform: scale(.5);}
#nextslide {right: 22px; transform: scale(.5);}
.homepage {margin-bottom: -50px;}
.thumbImage .thumbTextWrap {padding: 0 10px;}
.thumbImage .thumbText p {font-size: 12px;}
.thumbImage .thumbText h3 {font-size: 21px;}
.blogTitle {margin-top: 0px;}
}
/* Mobile Landscape Size to Tablet Portrait (devices and browsers) */
@media only screen and (min-width: 480px) and (max-width: 767px) {
h1 {font-size: 110px;}
h1 span{font-size: 80px;}
input[type="text"], input[type="password"], input[type="email"], textarea, select {width: 418px;}
}
/* Mobile Portrait Size to Mobile Landscape Size (devices and browsers) */
@media only screen and (max-width: 479px) {
h1 {font-size: 80px;}
h1 span{font-size: 60px;}
.teamImage h2 {margin-top: 105px; font-size:40px;}
input[type="text"], input[type="password"], input[type="email"], textarea, select {width: 298px;}
} | Java |
<?php defined('WPSS_PATH') or die();?>
<?php $util = new WPSS_Util();?>
<?php $question = new WPSS_Question((int) $_GET['id']);?>
<?php $quiz = new WPSS_Quiz($question->quiz_id);?>
<!-- Admin questions#new -->
<div class="wrap wpss">
<img class="left" src="<?php echo WPSS_URL.'assets/images/wpss_admin.png'?>" />
<h2 class="left"><?php echo $quiz->title;?>, Editing Question</h2>
<div class="clear"></div>
<hr />
<p class="wpss-breadcrumb">
<a href="<?php echo $util->admin_url('','','');?>">Quizzes</a> » <a href="<?php echo $util->admin_url('quiz', 'edit', $quiz->id);?>"><?php echo $quiz->title;?></a> » <a href="<?php echo $util->admin_url('quiz', 'questions_index', $quiz->id);?>">Questions</a> » <a class="current">Edit</a>
</p>
<?php include( WPSS_PATH . "admin/questions/_form.php");?>
</div>
| Java |
<?php
namespace Drutiny\Audit;
use Drutiny\Sandbox\Sandbox;
use Drutiny\Audit\AuditInterface;
/**
*
*/
interface RemediableInterface extends AuditInterface
{
/**
* Attempt to remediate the check after it has failed.
*
* @param Sandbox $sandbox
* @return bool
*/
public function remediate(Sandbox $sandbox);
}
| Java |
<?php
pb_backupbuddy::$ui->start_metabox( 'BackupBuddy Settings', true, 'width: 100%; max-width: 1200px;' );
$settings_form->display_settings( 'Save Settings' );
echo '<br><br>';
pb_backupbuddy::$ui->end_metabox();
/*
REMOVED v3.1.
pb_backupbuddy::$ui->start_metabox( __('Remote Offsite Storage / Destinations', 'it-l10n-backupbuddy' ) . ' ' . pb_backupbuddy::video( 'PmXLw_tS42Q#177', __( 'Remote Offsite Management / Remote Clients Tutorial', 'it-l10n-backupbuddy' ), false ), true, 'width: 100%; max-width: 1200px;' );
//echo '<h3>' . __('Remote Offsite Storage / Destinations', 'it-l10n-backupbuddy' ) . ' ' . pb_backupbuddy::video( 'PmXLw_tS42Q#177', __( 'Remote Offsite Management / Remote Clients Tutorial', 'it-l10n-backupbuddy' ), false ) . '</h3>';
//echo '<br>';
echo '<a href="' . pb_backupbuddy::ajax_url( 'destination_picker' ) . '&action_verb=to%20manage%20files&TB_iframe=1&width=640&height=600" class="thickbox button secondary-button" style="margin-top: 3px;" title="' . __( 'Manage Destinations & Archives', 'it-l10n-backupbuddy' ) . '">' . __('Manage Destinations & Archives', 'it-l10n-backupbuddy' ) . '</a>';
echo ' ';
_e( 'Add & configure destinations or select a destination to browse & manage its files.', 'it-l10n-backupbuddy' );
echo '<br><br>';
pb_backupbuddy::$ui->end_metabox();
*/
?>
<script type="text/javascript">
function pb_backupbuddy_selectdestination( destination_id, destination_title, callback_data ) {
window.location.href = '<?php
if ( is_network_admin() ) {
echo network_admin_url( 'admin.php' );
} else {
echo admin_url( 'admin.php' );
}
?>?page=pb_backupbuddy_backup&custom=remoteclient&destination_id=' + destination_id;
}
</script>
<?php
// Handles thickbox auto-resizing. Keep at bottom of page to avoid issues.
if ( !wp_script_is( 'media-upload' ) ) {
wp_enqueue_script( 'media-upload' );
wp_print_scripts( 'media-upload' );
}
?> | Java |
// Copyright 2008 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "Core/Boot/Boot.h"
#include <algorithm>
#include <array>
#include <cstring>
#include <memory>
#include <numeric>
#include <optional>
#include <string>
#include <unordered_set>
#include <vector>
#include <zlib.h>
#include "Common/Align.h"
#include "Common/CDUtils.h"
#include "Common/CommonPaths.h"
#include "Common/CommonTypes.h"
#include "Common/Config/Config.h"
#include "Common/File.h"
#include "Common/FileUtil.h"
#include "Common/Logging/Log.h"
#include "Common/MsgHandler.h"
#include "Common/StringUtil.h"
#include "Core/Boot/DolReader.h"
#include "Core/Boot/ElfReader.h"
#include "Core/CommonTitles.h"
#include "Core/Config/SYSCONFSettings.h"
#include "Core/ConfigManager.h"
#include "Core/FifoPlayer/FifoPlayer.h"
#include "Core/HLE/HLE.h"
#include "Core/HW/DVD/DVDInterface.h"
#include "Core/HW/EXI/EXI_DeviceIPL.h"
#include "Core/HW/Memmap.h"
#include "Core/HW/VideoInterface.h"
#include "Core/Host.h"
#include "Core/IOS/IOS.h"
#include "Core/PatchEngine.h"
#include "Core/PowerPC/PPCAnalyst.h"
#include "Core/PowerPC/PPCSymbolDB.h"
#include "Core/PowerPC/PowerPC.h"
#include "DiscIO/Enums.h"
#include "DiscIO/Volume.h"
BootParameters::BootParameters(Parameters&& parameters_,
const std::optional<std::string>& savestate_path_)
: parameters(std::move(parameters_)), savestate_path(savestate_path_)
{
}
std::unique_ptr<BootParameters>
BootParameters::GenerateFromFile(const std::string& path,
const std::optional<std::string>& savestate_path)
{
const bool is_drive = cdio_is_cdrom(path);
// Check if the file exist, we may have gotten it from a --elf command line
// that gave an incorrect file name
if (!is_drive && !File::Exists(path))
{
PanicAlertT("The specified file \"%s\" does not exist", path.c_str());
return {};
}
std::string extension;
SplitPath(path, nullptr, nullptr, &extension);
std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
static const std::unordered_set<std::string> disc_image_extensions = {
{".gcm", ".iso", ".tgc", ".wbfs", ".ciso", ".gcz", ".dol", ".elf"}};
if (disc_image_extensions.find(extension) != disc_image_extensions.end() || is_drive)
{
std::unique_ptr<DiscIO::Volume> volume = DiscIO::CreateVolumeFromFilename(path);
if (volume)
return std::make_unique<BootParameters>(Disc{path, std::move(volume)}, savestate_path);
if (extension == ".elf")
{
return std::make_unique<BootParameters>(Executable{path, std::make_unique<ElfReader>(path)},
savestate_path);
}
if (extension == ".dol")
{
return std::make_unique<BootParameters>(Executable{path, std::make_unique<DolReader>(path)},
savestate_path);
}
if (is_drive)
{
PanicAlertT("Could not read \"%s\". "
"There is no disc in the drive or it is not a GameCube/Wii backup. "
"Please note that Dolphin cannot play games directly from the original "
"GameCube and Wii discs.",
path.c_str());
}
else
{
PanicAlertT("\"%s\" is an invalid GCM/ISO file, or is not a GC/Wii ISO.", path.c_str());
}
return {};
}
if (extension == ".dff")
return std::make_unique<BootParameters>(DFF{path}, savestate_path);
if (extension == ".wad")
return std::make_unique<BootParameters>(DiscIO::WiiWAD{path}, savestate_path);
PanicAlertT("Could not recognize file %s", path.c_str());
return {};
}
BootParameters::IPL::IPL(DiscIO::Region region_) : region(region_)
{
const std::string directory = SConfig::GetInstance().GetDirectoryForRegion(region);
path = SConfig::GetInstance().GetBootROMPath(directory);
}
BootParameters::IPL::IPL(DiscIO::Region region_, Disc&& disc_) : IPL(region_)
{
disc = std::move(disc_);
}
// Inserts a disc into the emulated disc drive and returns a pointer to it.
// The returned pointer must only be used while we are still booting,
// because DVDThread can do whatever it wants to the disc after that.
static const DiscIO::Volume* SetDisc(std::unique_ptr<DiscIO::Volume> volume)
{
const DiscIO::Volume* pointer = volume.get();
DVDInterface::SetDisc(std::move(volume));
return pointer;
}
bool CBoot::DVDRead(const DiscIO::Volume& volume, u64 dvd_offset, u32 output_address, u32 length,
const DiscIO::Partition& partition)
{
std::vector<u8> buffer(length);
if (!volume.Read(dvd_offset, length, buffer.data(), partition))
return false;
Memory::CopyToEmu(output_address, buffer.data(), length);
return true;
}
void CBoot::UpdateDebugger_MapLoaded()
{
Host_NotifyMapLoaded();
}
// Get map file paths for the active title.
bool CBoot::FindMapFile(std::string* existing_map_file, std::string* writable_map_file)
{
const std::string& game_id = SConfig::GetInstance().m_debugger_game_id;
if (writable_map_file)
*writable_map_file = File::GetUserPath(D_MAPS_IDX) + game_id + ".map";
bool found = false;
static const std::string maps_directories[] = {File::GetUserPath(D_MAPS_IDX),
File::GetSysDirectory() + MAPS_DIR DIR_SEP};
for (size_t i = 0; !found && i < ArraySize(maps_directories); ++i)
{
std::string path = maps_directories[i] + game_id + ".map";
if (File::Exists(path))
{
found = true;
if (existing_map_file)
*existing_map_file = path;
}
}
return found;
}
bool CBoot::LoadMapFromFilename()
{
std::string strMapFilename;
bool found = FindMapFile(&strMapFilename, nullptr);
if (found && g_symbolDB.LoadMap(strMapFilename))
{
UpdateDebugger_MapLoaded();
return true;
}
return false;
}
// If ipl.bin is not found, this function does *some* of what BS1 does:
// loading IPL(BS2) and jumping to it.
// It does not initialize the hardware or anything else like BS1 does.
bool CBoot::Load_BS2(const std::string& boot_rom_filename)
{
// CRC32 hashes of the IPL file; including source where known
// https://forums.dolphin-emu.org/Thread-unknown-hash-on-ipl-bin?pid=385344#pid385344
constexpr u32 USA_v1_0 = 0x6D740AE7;
// https://forums.dolphin-emu.org/Thread-unknown-hash-on-ipl-bin?pid=385334#pid385334
constexpr u32 USA_v1_1 = 0xD5E6FEEA;
// https://forums.dolphin-emu.org/Thread-unknown-hash-on-ipl-bin?pid=385399#pid385399
constexpr u32 USA_v1_2 = 0x86573808;
// GameCubes sold in Brazil have this IPL. Same as USA v1.2 but localized
constexpr u32 BRA_v1_0 = 0x667D0B64;
// Redump
constexpr u32 JAP_v1_0 = 0x6DAC1F2A;
// https://bugs.dolphin-emu.org/issues/8936
constexpr u32 JAP_v1_1 = 0xD235E3F9;
constexpr u32 JAP_v1_2 = 0x8BDABBD4;
// Redump
constexpr u32 PAL_v1_0 = 0x4F319F43;
// https://forums.dolphin-emu.org/Thread-ipl-with-unknown-hash-dd8cab7c-problem-caused-by-my-pal-gamecube-bios?pid=435463#pid435463
constexpr u32 PAL_v1_1 = 0xDD8CAB7C;
// Redump
constexpr u32 PAL_v1_2 = 0xAD1B7F16;
// Load the whole ROM dump
std::string data;
if (!File::ReadFileToString(boot_rom_filename, data))
return false;
// Use zlibs crc32 implementation to compute the hash
u32 ipl_hash = crc32(0L, Z_NULL, 0);
ipl_hash = crc32(ipl_hash, (const Bytef*)data.data(), (u32)data.size());
DiscIO::Region ipl_region;
switch (ipl_hash)
{
case USA_v1_0:
case USA_v1_1:
case USA_v1_2:
case BRA_v1_0:
ipl_region = DiscIO::Region::NTSC_U;
break;
case JAP_v1_0:
case JAP_v1_1:
case JAP_v1_2:
ipl_region = DiscIO::Region::NTSC_J;
break;
case PAL_v1_0:
case PAL_v1_1:
case PAL_v1_2:
ipl_region = DiscIO::Region::PAL;
break;
default:
PanicAlertT("IPL with unknown hash %x", ipl_hash);
ipl_region = DiscIO::Region::Unknown;
break;
}
const DiscIO::Region boot_region = SConfig::GetInstance().m_region;
if (ipl_region != DiscIO::Region::Unknown && boot_region != ipl_region)
PanicAlertT("%s IPL found in %s directory. The disc might not be recognized",
SConfig::GetDirectoryForRegion(ipl_region),
SConfig::GetDirectoryForRegion(boot_region));
// Run the descrambler over the encrypted section containing BS1/BS2
ExpansionInterface::CEXIIPL::Descrambler((u8*)data.data() + 0x100, 0x1AFE00);
// TODO: Execution is supposed to start at 0xFFF00000, not 0x81200000;
// copying the initial boot code to 0x81200000 is a hack.
// For now, HLE the first few instructions and start at 0x81200150
// to work around this.
Memory::CopyToEmu(0x01200000, data.data() + 0x100, 0x700);
Memory::CopyToEmu(0x01300000, data.data() + 0x820, 0x1AFE00);
PowerPC::ppcState.gpr[3] = 0xfff0001f;
PowerPC::ppcState.gpr[4] = 0x00002030;
PowerPC::ppcState.gpr[5] = 0x0000009c;
UReg_MSR& m_MSR = ((UReg_MSR&)PowerPC::ppcState.msr);
m_MSR.FP = 1;
m_MSR.DR = 1;
m_MSR.IR = 1;
PowerPC::ppcState.spr[SPR_HID0] = 0x0011c464;
PowerPC::ppcState.spr[SPR_IBAT3U] = 0xfff0001f;
PowerPC::ppcState.spr[SPR_IBAT3L] = 0xfff00001;
PowerPC::ppcState.spr[SPR_DBAT3U] = 0xfff0001f;
PowerPC::ppcState.spr[SPR_DBAT3L] = 0xfff00001;
SetupBAT(/*is_wii*/ false);
PC = 0x81200150;
return true;
}
static void SetDefaultDisc()
{
const SConfig& config = SConfig::GetInstance();
if (!config.m_strDefaultISO.empty())
SetDisc(DiscIO::CreateVolumeFromFilename(config.m_strDefaultISO));
}
static void CopyDefaultExceptionHandlers()
{
constexpr u32 EXCEPTION_HANDLER_ADDRESSES[] = {0x00000100, 0x00000200, 0x00000300, 0x00000400,
0x00000500, 0x00000600, 0x00000700, 0x00000800,
0x00000900, 0x00000C00, 0x00000D00, 0x00000F00,
0x00001300, 0x00001400, 0x00001700};
constexpr u32 RFI_INSTRUCTION = 0x4C000064;
for (const u32 address : EXCEPTION_HANDLER_ADDRESSES)
Memory::Write_U32(RFI_INSTRUCTION, address);
}
// Third boot step after BootManager and Core. See Call schedule in BootManager.cpp
bool CBoot::BootUp(std::unique_ptr<BootParameters> boot)
{
SConfig& config = SConfig::GetInstance();
g_symbolDB.Clear();
// PAL Wii uses NTSC framerate and linecount in 60Hz modes
VideoInterface::Preset(DiscIO::IsNTSC(config.m_region) ||
(config.bWii && Config::Get(Config::SYSCONF_PAL60)));
struct BootTitle
{
BootTitle() : config(SConfig::GetInstance()) {}
bool operator()(BootParameters::Disc& disc) const
{
NOTICE_LOG(BOOT, "Booting from disc: %s", disc.path.c_str());
const DiscIO::Volume* volume = SetDisc(std::move(disc.volume));
if (!volume)
return false;
if (!EmulatedBS2(config.bWii, *volume))
return false;
// Try to load the symbol map if there is one, and then scan it for
// and eventually replace code
if (LoadMapFromFilename())
HLE::PatchFunctions();
return true;
}
bool operator()(const BootParameters::Executable& executable) const
{
NOTICE_LOG(BOOT, "Booting from executable: %s", executable.path.c_str());
if (!executable.reader->IsValid())
return false;
if (!executable.reader->LoadIntoMemory())
{
PanicAlertT("Failed to load the executable to memory.");
return false;
}
SetDefaultDisc();
SetupMSR();
SetupBAT(config.bWii);
CopyDefaultExceptionHandlers();
if (config.bWii)
{
PowerPC::ppcState.spr[SPR_HID0] = 0x0011c464;
PowerPC::ppcState.spr[SPR_HID4] = 0x82000000;
// Set a value for the SP. It doesn't matter where this points to,
// as long as it is a valid location. This value is taken from a homebrew binary.
PowerPC::ppcState.gpr[1] = 0x8004d4bc;
// Because there is no TMD to get the requested system (IOS) version from,
// we default to IOS58, which is the version used by the Homebrew Channel.
SetupWiiMemory();
IOS::HLE::GetIOS()->BootIOS(Titles::IOS(58));
}
else
{
SetupGCMemory();
}
PC = executable.reader->GetEntryPoint();
if (executable.reader->LoadSymbols() || LoadMapFromFilename())
{
UpdateDebugger_MapLoaded();
HLE::PatchFunctions();
}
return true;
}
bool operator()(const DiscIO::WiiWAD& wad) const
{
SetDefaultDisc();
return Boot_WiiWAD(wad);
}
bool operator()(const BootParameters::NANDTitle& nand_title) const
{
SetDefaultDisc();
return BootNANDTitle(nand_title.id);
}
bool operator()(const BootParameters::IPL& ipl) const
{
NOTICE_LOG(BOOT, "Booting GC IPL: %s", ipl.path.c_str());
if (!File::Exists(ipl.path))
{
if (ipl.disc)
PanicAlertT("Cannot start the game, because the GC IPL could not be found.");
else
PanicAlertT("Cannot find the GC IPL.");
return false;
}
if (!Load_BS2(ipl.path))
return false;
if (ipl.disc)
{
NOTICE_LOG(BOOT, "Inserting disc: %s", ipl.disc->path.c_str());
SetDisc(DiscIO::CreateVolumeFromFilename(ipl.disc->path));
}
if (LoadMapFromFilename())
HLE::PatchFunctions();
return true;
}
bool operator()(const BootParameters::DFF& dff) const
{
NOTICE_LOG(BOOT, "Booting DFF: %s", dff.dff_path.c_str());
return FifoPlayer::GetInstance().Open(dff.dff_path);
}
private:
const SConfig& config;
};
if (!std::visit(BootTitle(), boot->parameters))
return false;
PatchEngine::LoadPatches();
HLE::PatchFixedFunctions();
return true;
}
BootExecutableReader::BootExecutableReader(const std::string& file_name)
: BootExecutableReader(File::IOFile{file_name, "rb"})
{
}
BootExecutableReader::BootExecutableReader(File::IOFile file)
{
file.Seek(0, SEEK_SET);
m_bytes.resize(file.GetSize());
file.ReadBytes(m_bytes.data(), m_bytes.size());
}
BootExecutableReader::BootExecutableReader(const std::vector<u8>& bytes) : m_bytes(bytes)
{
}
BootExecutableReader::~BootExecutableReader() = default;
void StateFlags::UpdateChecksum()
{
constexpr size_t length_in_bytes = sizeof(StateFlags) - 4;
constexpr size_t num_elements = length_in_bytes / sizeof(u32);
std::array<u32, num_elements> flag_data;
std::memcpy(flag_data.data(), &flags, length_in_bytes);
checksum = std::accumulate(flag_data.cbegin(), flag_data.cend(), 0U);
}
void UpdateStateFlags(std::function<void(StateFlags*)> update_function)
{
const std::string file_path =
Common::GetTitleDataPath(Titles::SYSTEM_MENU, Common::FROM_SESSION_ROOT) + WII_STATE;
File::IOFile file;
StateFlags state;
if (File::Exists(file_path))
{
file.Open(file_path, "r+b");
file.ReadBytes(&state, sizeof(state));
}
else
{
File::CreateFullPath(file_path);
file.Open(file_path, "a+b");
memset(&state, 0, sizeof(state));
}
update_function(&state);
state.UpdateChecksum();
file.Seek(0, SEEK_SET);
file.WriteBytes(&state, sizeof(state));
}
| Java |
package My::Suite::WSREP;
use File::Basename;
use My::Find;
@ISA = qw(My::Suite);
return "Not run for embedded server" if $::opt_embedded_server;
return "WSREP is not compiled in" unless defined $::mysqld_variables{'wsrep-on'};
my ($provider) = grep { -f $_ } $ENV{WSREP_PROVIDER},
"/usr/lib64/galera-3/libgalera_smm.so",
"/usr/lib64/galera/libgalera_smm.so",
"/usr/lib/galera-3/libgalera_smm.so",
"/usr/lib/galera/libgalera_smm.so";
return "No wsrep provider library" unless -f $provider;
$ENV{WSREP_PROVIDER} = $provider;
my ($spath) = grep { -f "$_/wsrep_sst_rsync"; } "$::bindir/scripts", $::path_client_bindir;
return "No SST scripts" unless $spath;
my ($epath) = grep { -f "$_/my_print_defaults"; } "$::bindir/extra", $::path_client_bindir;
return "No my_print_defaults" unless $epath;
push @::global_suppressions,
(
qr(WSREP: Could not open saved state file for reading: .*),
qr(WSREP: Could not open state file for reading: .*),
qr|WSREP: access file\(.*gvwstate.dat\) failed\(No such file or directory\)|,
);
$ENV{PATH}="$epath:$ENV{PATH}";
$ENV{PATH}="$spath:$ENV{PATH}" unless $epath eq $spath;
bless { };
| Java |
<?php
namespace TYPO3\CMS\Extbase\Persistence\Generic;
/**
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
/**
* The Query class used to run queries against the database
*
* @api
*/
class Query implements QueryInterface {
/**
* An inner join.
*/
const JCR_JOIN_TYPE_INNER = '{http://www.jcp.org/jcr/1.0}joinTypeInner';
/**
* A left-outer join.
*/
const JCR_JOIN_TYPE_LEFT_OUTER = '{http://www.jcp.org/jcr/1.0}joinTypeLeftOuter';
/**
* A right-outer join.
*/
const JCR_JOIN_TYPE_RIGHT_OUTER = '{http://www.jcp.org/jcr/1.0}joinTypeRightOuter';
/**
* Charset of strings in QOM
*/
const CHARSET = 'utf-8';
/**
* @var string
*/
protected $type;
/**
* @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
* @inject
*/
protected $objectManager;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper
* @inject
*/
protected $dataMapper;
/**
* @var \TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface
* @inject
*/
protected $persistenceManager;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelFactory
* @inject
*/
protected $qomFactory;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface
*/
protected $source;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface
*/
protected $constraint;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Qom\Statement
*/
protected $statement;
/**
* @var int
*/
protected $orderings = array();
/**
* @var int
*/
protected $limit;
/**
* @var int
*/
protected $offset;
/**
* The query settings.
*
* @var QuerySettingsInterface
*/
protected $querySettings;
/**
* Constructs a query object working on the given class name
*
* @param string $type
*/
public function __construct($type) {
$this->type = $type;
}
/**
* Sets the Query Settings. These Query settings must match the settings expected by
* the specific Storage Backend.
*
* @param QuerySettingsInterface $querySettings The Query Settings
* @return void
* @api This method is not part of FLOW3 API
*/
public function setQuerySettings(QuerySettingsInterface $querySettings) {
$this->querySettings = $querySettings;
}
/**
* Returns the Query Settings.
*
* @throws Exception
* @return QuerySettingsInterface $querySettings The Query Settings
* @api This method is not part of FLOW3 API
*/
public function getQuerySettings() {
if (!$this->querySettings instanceof QuerySettingsInterface) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception('Tried to get the query settings without seting them before.', 1248689115);
}
return $this->querySettings;
}
/**
* Returns the type this query cares for.
*
* @return string
* @api
*/
public function getType() {
return $this->type;
}
/**
* Sets the source to fetch the result from
*
* @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source
*/
public function setSource(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source) {
$this->source = $source;
}
/**
* Returns the selectorn name or an empty string, if the source is not a selector
* TODO This has to be checked at another place
*
* @return string The selector name
*/
protected function getSelectorName() {
$source = $this->getSource();
if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface) {
return $source->getSelectorName();
} else {
return '';
}
}
/**
* Gets the node-tuple source for this query.
*
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface the node-tuple source; non-null
*/
public function getSource() {
if ($this->source === NULL) {
$this->source = $this->qomFactory->selector($this->getType(), $this->dataMapper->convertClassNameToTableName($this->getType()));
}
return $this->source;
}
/**
* Executes the query against the database and returns the result
*
* @param $returnRawQueryResult boolean avoids the object mapping by the persistence
* @return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface|array The query result object or an array if $returnRawQueryResult is TRUE
* @api
*/
public function execute($returnRawQueryResult = FALSE) {
if ($returnRawQueryResult === TRUE || $this->getQuerySettings()->getReturnRawQueryResult() === TRUE) {
return $this->persistenceManager->getObjectDataByQuery($this);
} else {
return $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\QueryResultInterface', $this);
}
}
/**
* Sets the property names to order the result by. Expected like this:
* array(
* 'foo' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING,
* 'bar' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING
* )
* where 'foo' and 'bar' are property names.
*
* @param array $orderings The property names to order by
* @return QueryInterface
* @api
*/
public function setOrderings(array $orderings) {
$this->orderings = $orderings;
return $this;
}
/**
* Returns the property names to order the result by. Like this:
* array(
* 'foo' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING,
* 'bar' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING
* )
*
* @return array
* @api
*/
public function getOrderings() {
return $this->orderings;
}
/**
* Sets the maximum size of the result set to limit. Returns $this to allow
* for chaining (fluid interface)
*
* @param integer $limit
* @throws \InvalidArgumentException
* @return QueryInterface
* @api
*/
public function setLimit($limit) {
if (!is_int($limit) || $limit < 1) {
throw new \InvalidArgumentException('The limit must be an integer >= 1', 1245071870);
}
$this->limit = $limit;
return $this;
}
/**
* Resets a previously set maximum size of the result set. Returns $this to allow
* for chaining (fluid interface)
*
* @return QueryInterface
* @api
*/
public function unsetLimit() {
unset($this->limit);
return $this;
}
/**
* Returns the maximum size of the result set to limit.
*
* @return integer
* @api
*/
public function getLimit() {
return $this->limit;
}
/**
* Sets the start offset of the result set to offset. Returns $this to
* allow for chaining (fluid interface)
*
* @param integer $offset
* @throws \InvalidArgumentException
* @return QueryInterface
* @api
*/
public function setOffset($offset) {
if (!is_int($offset) || $offset < 0) {
throw new \InvalidArgumentException('The offset must be a positive integer', 1245071872);
}
$this->offset = $offset;
return $this;
}
/**
* Returns the start offset of the result set.
*
* @return integer
* @api
*/
public function getOffset() {
return $this->offset;
}
/**
* The constraint used to limit the result set. Returns $this to allow
* for chaining (fluid interface)
*
* @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint
* @return QueryInterface
* @api
*/
public function matching($constraint) {
$this->constraint = $constraint;
return $this;
}
/**
* Sets the statement of this query. If you use this, you will lose the abstraction from a concrete storage
* backend (database).
*
* @param string|\TYPO3\CMS\Core\Database\PreparedStatement $statement The statement
* @param array $parameters An array of parameters. These will be bound to placeholders '?' in the $statement.
* @return QueryInterface
*/
public function statement($statement, array $parameters = array()) {
$this->statement = $this->qomFactory->statement($statement, $parameters);
return $this;
}
/**
* Returns the statement of this query.
*
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\Statement
*/
public function getStatement() {
return $this->statement;
}
/**
* Gets the constraint for this query.
*
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface|NULL the constraint, or null if none
* @api
*/
public function getConstraint() {
return $this->constraint;
}
/**
* Performs a logical conjunction of the given constraints. The method takes one or more contraints and concatenates them with a boolean AND.
* It also scepts a single array of constraints to be concatenated.
*
* @param mixed $constraint1 The first of multiple constraints or an array of constraints.
* @throws Exception\InvalidNumberOfConstraintsException
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\AndInterface
* @api
*/
public function logicalAnd($constraint1) {
if (is_array($constraint1)) {
$resultingConstraint = array_shift($constraint1);
$constraints = $constraint1;
} else {
$constraints = func_get_args();
$resultingConstraint = array_shift($constraints);
}
if ($resultingConstraint === NULL) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidNumberOfConstraintsException('There must be at least one constraint or a non-empty array of constraints given.', 1268056288);
}
foreach ($constraints as $constraint) {
$resultingConstraint = $this->qomFactory->_and($resultingConstraint, $constraint);
}
return $resultingConstraint;
}
/**
* Performs a logical disjunction of the two given constraints
*
* @param mixed $constraint1 The first of multiple constraints or an array of constraints.
* @throws Exception\InvalidNumberOfConstraintsException
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\OrInterface
* @api
*/
public function logicalOr($constraint1) {
if (is_array($constraint1)) {
$resultingConstraint = array_shift($constraint1);
$constraints = $constraint1;
} else {
$constraints = func_get_args();
$resultingConstraint = array_shift($constraints);
}
if ($resultingConstraint === NULL) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidNumberOfConstraintsException('There must be at least one constraint or a non-empty array of constraints given.', 1268056289);
}
foreach ($constraints as $constraint) {
$resultingConstraint = $this->qomFactory->_or($resultingConstraint, $constraint);
}
return $resultingConstraint;
}
/**
* Performs a logical negation of the given constraint
*
* @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint Constraint to negate
* @throws \RuntimeException
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\NotInterface
* @api
*/
public function logicalNot(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint) {
return $this->qomFactory->not($constraint);
}
/**
* Returns an equals criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @param boolean $caseSensitive Whether the equality test should be done case-sensitive
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function equals($propertyName, $operand, $caseSensitive = TRUE) {
if (is_object($operand) || $caseSensitive) {
$comparison = $this->qomFactory->comparison(
$this->qomFactory->propertyValue($propertyName, $this->getSelectorName()),
QueryInterface::OPERATOR_EQUAL_TO,
$operand
);
} else {
$comparison = $this->qomFactory->comparison(
$this->qomFactory->lowerCase($this->qomFactory->propertyValue($propertyName, $this->getSelectorName())),
QueryInterface::OPERATOR_EQUAL_TO,
\TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Charset\\CharsetConverter')->conv_case(\TYPO3\CMS\Extbase\Persistence\Generic\Query::CHARSET, $operand, 'toLower')
);
}
return $comparison;
}
/**
* Returns a like criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @param boolean $caseSensitive Whether the matching should be done case-sensitive
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function like($propertyName, $operand, $caseSensitive = TRUE) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_LIKE, $operand);
}
/**
* Returns a "contains" criterion used for matching objects against a query.
* It matches if the multivalued property contains the given operand.
*
* @param string $propertyName The name of the (multivalued) property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function contains($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_CONTAINS, $operand);
}
/**
* Returns an "in" criterion used for matching objects against a query. It
* matches if the property's value is contained in the multivalued operand.
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with, multivalued
* @throws Exception\UnexpectedTypeException
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function in($propertyName, $operand) {
if (!is_array($operand) && !$operand instanceof \ArrayAccess && !$operand instanceof \Traversable) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('The "in" operator must be given a multivalued operand (array, ArrayAccess, Traversable).', 1264678095);
}
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_IN, $operand);
}
/**
* Returns a less than criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function lessThan($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_LESS_THAN, $operand);
}
/**
* Returns a less or equal than criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function lessThanOrEqual($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_LESS_THAN_OR_EQUAL_TO, $operand);
}
/**
* Returns a greater than criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function greaterThan($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_GREATER_THAN, $operand);
}
/**
* Returns a greater than or equal criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function greaterThanOrEqual($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_GREATER_THAN_OR_EQUAL_TO, $operand);
}
/**
* @return void
*/
public function __wakeup() {
$this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$this->persistenceManager = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\PersistenceManagerInterface');
$this->dataMapper = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapper');
$this->qomFactory = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Qom\\QueryObjectModelFactory');
}
/**
* @return array
*/
public function __sleep() {
return array('type', 'source', 'constraint', 'statement', 'orderings', 'limit', 'offset', 'querySettings');
}
/**
* Returns the query result count.
*
* @return integer The query result count
* @api
*/
public function count() {
return $this->execute()->count();
}
/**
* Returns an "isEmpty" criterion used for matching objects against a query.
* It matches if the multivalued property contains no values or is NULL.
*
* @param string $propertyName The name of the multivalued property to compare against
* @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\NotImplementedException
* @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException if used on a single-valued property
* @return bool
* @api
*/
public function isEmpty($propertyName) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\NotImplementedException(__METHOD__);
}
}
| Java |
#!/bin/sh
set -e
$GREP_DCTRL -I -sPackage '' 0001.out
| Java |
file(REMOVE_RECURSE
"CMakeFiles/ortp.dir/avprofile.c.o"
"CMakeFiles/ortp.dir/b64.c.o"
"CMakeFiles/ortp.dir/event.c.o"
"CMakeFiles/ortp.dir/extremum.c.o"
"CMakeFiles/ortp.dir/jitterctl.c.o"
"CMakeFiles/ortp.dir/logging.c.o"
"CMakeFiles/ortp.dir/netsim.c.o"
"CMakeFiles/ortp.dir/ortp.c.o"
"CMakeFiles/ortp.dir/payloadtype.c.o"
"CMakeFiles/ortp.dir/port.c.o"
"CMakeFiles/ortp.dir/posixtimer.c.o"
"CMakeFiles/ortp.dir/rtcp.c.o"
"CMakeFiles/ortp.dir/rtcp_fb.c.o"
"CMakeFiles/ortp.dir/rtcp_xr.c.o"
"CMakeFiles/ortp.dir/rtcpparse.c.o"
"CMakeFiles/ortp.dir/rtpparse.c.o"
"CMakeFiles/ortp.dir/rtpprofile.c.o"
"CMakeFiles/ortp.dir/rtpsession.c.o"
"CMakeFiles/ortp.dir/rtpsession_inet.c.o"
"CMakeFiles/ortp.dir/rtpsignaltable.c.o"
"CMakeFiles/ortp.dir/rtptimer.c.o"
"CMakeFiles/ortp.dir/scheduler.c.o"
"CMakeFiles/ortp.dir/sessionset.c.o"
"CMakeFiles/ortp.dir/str_utils.c.o"
"CMakeFiles/ortp.dir/telephonyevents.c.o"
"CMakeFiles/ortp.dir/utils.c.o"
"libortp.pdb"
"libortp.a"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/ortp.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
| Java |
<?php
/**
* @version 1.0.0
* @package com_oauth
* @copyright Copyright (C) 2011 - 2013 Slashes & Dots Sdn Bhd. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author Offiria Team
*/
// No direct access
defined('_JEXEC') or die;
/**
* HTML View class for the Oauth component
*/
class OauthViewOauth extends OauthView
{
/**
* The purpose of this view is to retrieve the token generated for the app
* Process flow:
* 1) Navigate to index.php/component/oauth/?view=oauth&task=authenticate&appId=[appId]
* 2) Get the device approved
* 3) Run in the background to retrieve the token generated in this view
*/
public function display() {
$model = OauthFactory::getModel('application');
$token = $model->getAppToken(JRequest::getVar('appId'));
// make sure only the token belongs to the user will be generate
if ($model->isAppBelongToUser(JRequest::getVar('appId'))) {
$vals['token'] = $token;
echo json_encode($vals);
}
exit;
}
} | Java |
<?php
/**
* @version $Id: controller.php 14401 2010-01-26 14:10:00Z louis $
* @package Joomla
* @subpackage Content
* @copyright Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant to the
* GNU General Public License, and as distributed it includes or is derivative
* of works licensed under the GNU General Public License or other free or open
* source software licenses. See COPYRIGHT.php for copyright notices and
* details.
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );
jimport('joomla.application.component.controller');
/**
* Content Component Controller
*
* @package Joomla
* @subpackage Content
* @since 1.5
*/
class ContentController extends JController
{
/**
* Method to show an article as the main page display
*
* @access public
* @since 1.5
*/
function display()
{
JHTML::_('behavior.caption');
// Set a default view if none exists
if ( ! JRequest::getCmd( 'view' ) ) {
$default = JRequest::getInt('id') ? 'article' : 'frontpage';
JRequest::setVar('view', $default );
}
// View caching logic -- simple... are we logged in?
$user = &JFactory::getUser();
$view = JRequest::getVar('view');
$viewcache = JRequest::getVar('viewcache',1,'POST','INT');
if ($user->get('id') ||
($view == 'category' && JRequest::getVar('layout') != 'blog' && $viewcache == 0) ||
$view == 'archive' && $viewcache == 0) {
parent::display(false);
} else {
parent::display(true);
}
}
/**
* Edits an article
*
* @access public
* @since 1.5
*/
function edit()
{
$user =& JFactory::getUser();
// Create a user access object for the user
$access = new stdClass();
$access->canEdit = $user->authorize('com_content', 'edit', 'content', 'all');
$access->canEditOwn = $user->authorize('com_content', 'edit', 'content', 'own');
$access->canPublish = $user->authorize('com_content', 'publish', 'content', 'all');
// Create the view
$view = & $this->getView('article', 'html');
// Get/Create the model
$model = & $this->getModel('Article');
// new record
if (!($access->canEdit || $access->canEditOwn)) {
JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
}
if( $model->get('id') > 1 && $user->get('gid') <= 19 && $model->get('created_by') != $user->id ) {
JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
}
if ( $model->isCheckedOut($user->get('id')))
{
$msg = JText::sprintf('DESCBEINGEDITTED', JText::_('The item'), $model->get('title'));
$this->setRedirect(JRoute::_('index.php?view=article&id='.$model->get('id'), false), $msg);
return;
}
//Checkout the article
$model->checkout();
// Push the model into the view (as default)
$view->setModel($model, true);
// Set the layout
$view->setLayout('form');
// Display the view
$view->display();
}
/**
* Saves the content item an edit form submit
*
* @todo
*/
function save()
{
// Check for request forgeries
JRequest::checkToken() or jexit( 'Invalid Token' );
// Initialize variables
$db = & JFactory::getDBO();
$user = & JFactory::getUser();
$task = JRequest::getVar('task', null, 'default', 'cmd');
// Make sure you are logged in and have the necessary access rights
if ($user->get('gid') < 19) {
JError::raiseError( 403, JText::_('ALERTNOTAUTH') );
return;
}
// Create a user access object for the user
$access = new stdClass();
$access->canEdit = $user->authorize('com_content', 'edit', 'content', 'all');
$access->canEditOwn = $user->authorize('com_content', 'edit', 'content', 'own');
$access->canPublish = $user->authorize('com_content', 'publish', 'content', 'all');
if (!($access->canEdit || $access->canEditOwn)) {
JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
}
//get data from the request
$model = $this->getModel('article');
//get data from request
$post = JRequest::get('post');
$post['text'] = JRequest::getVar('text', '', 'post', 'string', JREQUEST_ALLOWRAW);
//preform access checks
$isNew = ((int) $post['id'] < 1);
if ($model->store($post)) {
$msg = JText::_( 'Article Saved' );
if($isNew) {
$post['id'] = (int) $model->get('id');
}
} else {
$msg = JText::_( 'Error Saving Article' );
JError::raiseError( 500, $model->getError() );
}
// manage frontpage items
//TODO : Move this into a frontpage model
require_once (JPATH_ADMINISTRATOR.DS.'components'.DS.'com_frontpage'.DS.'tables'.DS.'frontpage.php');
$fp = new TableFrontPage($db);
if (JRequest::getVar('frontpage', false, '', 'boolean'))
{
// toggles go to first place
if (!$fp->load($post['id']))
{
// new entry
$query = 'INSERT INTO #__content_frontpage' .
' VALUES ( '.(int) $post['id'].', 1 )';
$db->setQuery($query);
if (!$db->query()) {
JError::raiseError( 500, $db->stderr());
}
$fp->ordering = 1;
}
}
else
{
// no frontpage mask
if (!$fp->delete($post['id'])) {
$msg .= $fp->stderr();
}
$fp->ordering = 0;
}
$fp->reorder();
$model->checkin();
// gets section name of item
$query = 'SELECT s.title' .
' FROM #__sections AS s' .
' WHERE s.scope = "content"' .
' AND s.id = ' . (int) $post['sectionid'];
$db->setQuery($query);
// gets category name of item
$section = $db->loadResult();
$query = 'SELECT c.title' .
' FROM #__categories AS c' .
' WHERE c.id = ' . (int) $post['catid'];
$db->setQuery($query);
$category = $db->loadResult();
if ($isNew)
{
// messaging for new items
require_once (JPATH_ADMINISTRATOR.DS.'components'.DS.'com_messages'.DS.'tables'.DS.'message.php');
// load language for messaging
$lang =& JFactory::getLanguage();
$lang->load('com_messages');
$query = 'SELECT id' .
' FROM #__users' .
' WHERE sendEmail = 1';
$db->setQuery($query);
$users = $db->loadResultArray();
foreach ($users as $user_id)
{
$msg = new TableMessage($db);
$msg->send($user->get('id'), $user_id, JText::_('New Item'), JText::sprintf('ON_NEW_CONTENT', $user->get('username'), $post['title'], $section, $category));
}
} else {
// If the article isn't new, then we need to clean the cache so that our changes appear realtime :)
$cache = &JFactory::getCache('com_content');
$cache->clean();
}
if ($access->canPublish)
{
// Publishers, admins, etc just get the stock msg
$msg = JText::_('Item successfully saved.');
}
else
{
$msg = $isNew ? JText::_('THANK_SUB') : JText::_('Item successfully saved.');
}
$referer = JRequest::getString('ret', base64_encode(JURI::base()), 'get');
$referer = base64_decode($referer);
if (!JURI::isInternal($referer)) {
$referer = '';
}
$this->setRedirect($referer, $msg);
}
/**
* Cancels an edit article operation
*
* @access public
* @since 1.5
*/
function cancel()
{
// Initialize some variables
$db = & JFactory::getDBO();
$user = & JFactory::getUser();
// Get an article table object and bind post variabes to it [We don't need a full model here]
$article = & JTable::getInstance('content');
$article->bind(JRequest::get('post'));
if ($user->authorize('com_content', 'edit', 'content', 'all') || ($user->authorize('com_content', 'edit', 'content', 'own') && $article->created_by == $user->get('id'))) {
$article->checkin();
}
// If the task was edit or cancel, we go back to the content item
$referer = JRequest::getString('ret', base64_encode(JURI::base()), 'get');
$referer = base64_decode($referer);
if (!JURI::isInternal($referer)) {
$referer = '';
}
$this->setRedirect($referer);
}
/**
* Rates an article
*
* @access public
* @since 1.5
*/
function vote()
{
$url = JRequest::getVar('url', '', 'default', 'string');
$rating = JRequest::getVar('user_rating', 0, '', 'int');
$id = JRequest::getVar('cid', 0, '', 'int');
// Get/Create the model
$model = & $this->getModel('Article' );
$model->setId($id);
if(!JURI::isInternal($url)) {
$url = JRoute::_('index.php?option=com_content&view=article&id='.$id);
}
if ($model->storeVote($rating)) {
$this->setRedirect($url, JText::_('Thanks for rating!'));
} else {
$this->setRedirect($url, JText::_('You already rated this article today!'));
}
}
/**
* Searches for an item by a key parameter
*
* @access public
* @since 1.5
*/
function findkey()
{
// Initialize variables
$db = & JFactory::getDBO();
$keyref = JRequest::getVar('keyref', null, 'default', 'cmd');
JRequest::setVar('keyref', $keyref);
// If no keyref left, throw 404
if( empty($keyref) === true ) {
JError::raiseError( 404, JText::_("Key Not Found") );
}
$keyref = $db->Quote( '%keyref='.$db->getEscaped( $keyref, true ).'%', false );
$query = 'SELECT id' .
' FROM #__content' .
' WHERE attribs LIKE '.$keyref;
$db->setQuery($query);
$id = (int) $db->loadResult();
if ($id > 0)
{
// Create the view
$view =& $this->getView('article', 'html');
// Get/Create the model
$model =& $this->getModel('Article' );
// Set the id of the article to display
$model->setId($id);
// Push the model into the view (as default)
$view->setModel($model, true);
// Display the view
$view->display();
}
else {
JError::raiseError( 404, JText::_( 'Key Not Found' ) );
}
}
/**
* Output the pagebreak dialog
*
* @access public
* @since 1.5
*/
function ins_pagebreak()
{
// Create the view
$view = & $this->getView('article', 'html');
// Set the layout
$view->setLayout('pagebreak');
// Display the view
$view->display();
}
}
| Java |
/*
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "ci/bcEscapeAnalyzer.hpp"
#include "compiler/oopMap.hpp"
#include "opto/callGenerator.hpp"
#include "opto/callnode.hpp"
#include "opto/escape.hpp"
#include "opto/locknode.hpp"
#include "opto/machnode.hpp"
#include "opto/matcher.hpp"
#include "opto/parse.hpp"
#include "opto/regalloc.hpp"
#include "opto/regmask.hpp"
#include "opto/rootnode.hpp"
#include "opto/runtime.hpp"
// Portions of code courtesy of Clifford Click
// Optimization - Graph Style
//=============================================================================
uint StartNode::size_of() const { return sizeof(*this); }
uint StartNode::cmp( const Node &n ) const
{ return _domain == ((StartNode&)n)._domain; }
const Type *StartNode::bottom_type() const { return _domain; }
const Type *StartNode::Value(PhaseTransform *phase) const { return _domain; }
#ifndef PRODUCT
void StartNode::dump_spec(outputStream *st) const { st->print(" #"); _domain->dump_on(st);}
#endif
//------------------------------Ideal------------------------------------------
Node *StartNode::Ideal(PhaseGVN *phase, bool can_reshape){
return remove_dead_region(phase, can_reshape) ? this : NULL;
}
//------------------------------calling_convention-----------------------------
void StartNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
Matcher::calling_convention( sig_bt, parm_regs, argcnt, false );
}
//------------------------------Registers--------------------------------------
const RegMask &StartNode::in_RegMask(uint) const {
return RegMask::Empty;
}
//------------------------------match------------------------------------------
// Construct projections for incoming parameters, and their RegMask info
Node *StartNode::match( const ProjNode *proj, const Matcher *match ) {
switch (proj->_con) {
case TypeFunc::Control:
case TypeFunc::I_O:
case TypeFunc::Memory:
return new (match->C) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
case TypeFunc::FramePtr:
return new (match->C) MachProjNode(this,proj->_con,Matcher::c_frame_ptr_mask, Op_RegP);
case TypeFunc::ReturnAdr:
return new (match->C) MachProjNode(this,proj->_con,match->_return_addr_mask,Op_RegP);
case TypeFunc::Parms:
default: {
uint parm_num = proj->_con - TypeFunc::Parms;
const Type *t = _domain->field_at(proj->_con);
if (t->base() == Type::Half) // 2nd half of Longs and Doubles
return new (match->C) ConNode(Type::TOP);
uint ideal_reg = t->ideal_reg();
RegMask &rm = match->_calling_convention_mask[parm_num];
return new (match->C) MachProjNode(this,proj->_con,rm,ideal_reg);
}
}
return NULL;
}
//------------------------------StartOSRNode----------------------------------
// The method start node for an on stack replacement adapter
//------------------------------osr_domain-----------------------------
const TypeTuple *StartOSRNode::osr_domain() {
const Type **fields = TypeTuple::fields(2);
fields[TypeFunc::Parms+0] = TypeRawPtr::BOTTOM; // address of osr buffer
return TypeTuple::make(TypeFunc::Parms+1, fields);
}
//=============================================================================
const char * const ParmNode::names[TypeFunc::Parms+1] = {
"Control", "I_O", "Memory", "FramePtr", "ReturnAdr", "Parms"
};
#ifndef PRODUCT
void ParmNode::dump_spec(outputStream *st) const {
if( _con < TypeFunc::Parms ) {
st->print("%s", names[_con]);
} else {
st->print("Parm%d: ",_con-TypeFunc::Parms);
// Verbose and WizardMode dump bottom_type for all nodes
if( !Verbose && !WizardMode ) bottom_type()->dump_on(st);
}
}
#endif
uint ParmNode::ideal_reg() const {
switch( _con ) {
case TypeFunc::Control : // fall through
case TypeFunc::I_O : // fall through
case TypeFunc::Memory : return 0;
case TypeFunc::FramePtr : // fall through
case TypeFunc::ReturnAdr: return Op_RegP;
default : assert( _con > TypeFunc::Parms, "" );
// fall through
case TypeFunc::Parms : {
// Type of argument being passed
const Type *t = in(0)->as_Start()->_domain->field_at(_con);
return t->ideal_reg();
}
}
ShouldNotReachHere();
return 0;
}
//=============================================================================
ReturnNode::ReturnNode(uint edges, Node *cntrl, Node *i_o, Node *memory, Node *frameptr, Node *retadr ) : Node(edges) {
init_req(TypeFunc::Control,cntrl);
init_req(TypeFunc::I_O,i_o);
init_req(TypeFunc::Memory,memory);
init_req(TypeFunc::FramePtr,frameptr);
init_req(TypeFunc::ReturnAdr,retadr);
}
Node *ReturnNode::Ideal(PhaseGVN *phase, bool can_reshape){
return remove_dead_region(phase, can_reshape) ? this : NULL;
}
const Type *ReturnNode::Value( PhaseTransform *phase ) const {
return ( phase->type(in(TypeFunc::Control)) == Type::TOP)
? Type::TOP
: Type::BOTTOM;
}
// Do we Match on this edge index or not? No edges on return nodes
uint ReturnNode::match_edge(uint idx) const {
return 0;
}
#ifndef PRODUCT
void ReturnNode::dump_req(outputStream *st) const {
// Dump the required inputs, enclosed in '(' and ')'
uint i; // Exit value of loop
for (i = 0; i < req(); i++) { // For all required inputs
if (i == TypeFunc::Parms) st->print("returns");
if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
else st->print("_ ");
}
}
#endif
//=============================================================================
RethrowNode::RethrowNode(
Node* cntrl,
Node* i_o,
Node* memory,
Node* frameptr,
Node* ret_adr,
Node* exception
) : Node(TypeFunc::Parms + 1) {
init_req(TypeFunc::Control , cntrl );
init_req(TypeFunc::I_O , i_o );
init_req(TypeFunc::Memory , memory );
init_req(TypeFunc::FramePtr , frameptr );
init_req(TypeFunc::ReturnAdr, ret_adr);
init_req(TypeFunc::Parms , exception);
}
Node *RethrowNode::Ideal(PhaseGVN *phase, bool can_reshape){
return remove_dead_region(phase, can_reshape) ? this : NULL;
}
const Type *RethrowNode::Value( PhaseTransform *phase ) const {
return (phase->type(in(TypeFunc::Control)) == Type::TOP)
? Type::TOP
: Type::BOTTOM;
}
uint RethrowNode::match_edge(uint idx) const {
return 0;
}
#ifndef PRODUCT
void RethrowNode::dump_req(outputStream *st) const {
// Dump the required inputs, enclosed in '(' and ')'
uint i; // Exit value of loop
for (i = 0; i < req(); i++) { // For all required inputs
if (i == TypeFunc::Parms) st->print("exception");
if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
else st->print("_ ");
}
}
#endif
//=============================================================================
// Do we Match on this edge index or not? Match only target address & method
uint TailCallNode::match_edge(uint idx) const {
return TypeFunc::Parms <= idx && idx <= TypeFunc::Parms+1;
}
//=============================================================================
// Do we Match on this edge index or not? Match only target address & oop
uint TailJumpNode::match_edge(uint idx) const {
return TypeFunc::Parms <= idx && idx <= TypeFunc::Parms+1;
}
//=============================================================================
JVMState::JVMState(ciMethod* method, JVMState* caller) :
_method(method) {
assert(method != NULL, "must be valid call site");
_reexecute = Reexecute_Undefined;
debug_only(_bci = -99); // random garbage value
debug_only(_map = (SafePointNode*)-1);
_caller = caller;
_depth = 1 + (caller == NULL ? 0 : caller->depth());
_locoff = TypeFunc::Parms;
_stkoff = _locoff + _method->max_locals();
_monoff = _stkoff + _method->max_stack();
_scloff = _monoff;
_endoff = _monoff;
_sp = 0;
}
JVMState::JVMState(int stack_size) :
_method(NULL) {
_bci = InvocationEntryBci;
_reexecute = Reexecute_Undefined;
debug_only(_map = (SafePointNode*)-1);
_caller = NULL;
_depth = 1;
_locoff = TypeFunc::Parms;
_stkoff = _locoff;
_monoff = _stkoff + stack_size;
_scloff = _monoff;
_endoff = _monoff;
_sp = 0;
}
//--------------------------------of_depth-------------------------------------
JVMState* JVMState::of_depth(int d) const {
const JVMState* jvmp = this;
assert(0 < d && (uint)d <= depth(), "oob");
for (int skip = depth() - d; skip > 0; skip--) {
jvmp = jvmp->caller();
}
assert(jvmp->depth() == (uint)d, "found the right one");
return (JVMState*)jvmp;
}
//-----------------------------same_calls_as-----------------------------------
bool JVMState::same_calls_as(const JVMState* that) const {
if (this == that) return true;
if (this->depth() != that->depth()) return false;
const JVMState* p = this;
const JVMState* q = that;
for (;;) {
if (p->_method != q->_method) return false;
if (p->_method == NULL) return true; // bci is irrelevant
if (p->_bci != q->_bci) return false;
if (p->_reexecute != q->_reexecute) return false;
p = p->caller();
q = q->caller();
if (p == q) return true;
assert(p != NULL && q != NULL, "depth check ensures we don't run off end");
}
}
//------------------------------debug_start------------------------------------
uint JVMState::debug_start() const {
debug_only(JVMState* jvmroot = of_depth(1));
assert(jvmroot->locoff() <= this->locoff(), "youngest JVMState must be last");
return of_depth(1)->locoff();
}
//-------------------------------debug_end-------------------------------------
uint JVMState::debug_end() const {
debug_only(JVMState* jvmroot = of_depth(1));
assert(jvmroot->endoff() <= this->endoff(), "youngest JVMState must be last");
return endoff();
}
//------------------------------debug_depth------------------------------------
uint JVMState::debug_depth() const {
uint total = 0;
for (const JVMState* jvmp = this; jvmp != NULL; jvmp = jvmp->caller()) {
total += jvmp->debug_size();
}
return total;
}
#ifndef PRODUCT
//------------------------------format_helper----------------------------------
// Given an allocation (a Chaitin object) and a Node decide if the Node carries
// any defined value or not. If it does, print out the register or constant.
static void format_helper( PhaseRegAlloc *regalloc, outputStream* st, Node *n, const char *msg, uint i, GrowableArray<SafePointScalarObjectNode*> *scobjs ) {
if (n == NULL) { st->print(" NULL"); return; }
if (n->is_SafePointScalarObject()) {
// Scalar replacement.
SafePointScalarObjectNode* spobj = n->as_SafePointScalarObject();
scobjs->append_if_missing(spobj);
int sco_n = scobjs->find(spobj);
assert(sco_n >= 0, "");
st->print(" %s%d]=#ScObj" INT32_FORMAT, msg, i, sco_n);
return;
}
if (regalloc->node_regs_max_index() > 0 &&
OptoReg::is_valid(regalloc->get_reg_first(n))) { // Check for undefined
char buf[50];
regalloc->dump_register(n,buf);
st->print(" %s%d]=%s",msg,i,buf);
} else { // No register, but might be constant
const Type *t = n->bottom_type();
switch (t->base()) {
case Type::Int:
st->print(" %s%d]=#"INT32_FORMAT,msg,i,t->is_int()->get_con());
break;
case Type::AnyPtr:
assert( t == TypePtr::NULL_PTR || n->in_dump(), "" );
st->print(" %s%d]=#NULL",msg,i);
break;
case Type::AryPtr:
case Type::InstPtr:
st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->isa_oopptr()->const_oop()));
break;
case Type::KlassPtr:
st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_klassptr()->klass()));
break;
case Type::MetadataPtr:
st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_metadataptr()->metadata()));
break;
case Type::NarrowOop:
st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_oopptr()->const_oop()));
break;
case Type::RawPtr:
st->print(" %s%d]=#Raw" INTPTR_FORMAT,msg,i,p2i(t->is_rawptr()));
break;
case Type::DoubleCon:
st->print(" %s%d]=#%fD",msg,i,t->is_double_constant()->_d);
break;
case Type::FloatCon:
st->print(" %s%d]=#%fF",msg,i,t->is_float_constant()->_f);
break;
case Type::Long:
st->print(" %s%d]=#"INT64_FORMAT,msg,i,(int64_t)(t->is_long()->get_con()));
break;
case Type::Half:
case Type::Top:
st->print(" %s%d]=_",msg,i);
break;
default: ShouldNotReachHere();
}
}
}
//------------------------------format-----------------------------------------
void JVMState::format(PhaseRegAlloc *regalloc, const Node *n, outputStream* st) const {
st->print(" #");
if (_method) {
_method->print_short_name(st);
st->print(" @ bci:%d ",_bci);
} else {
st->print_cr(" runtime stub ");
return;
}
if (n->is_MachSafePoint()) {
GrowableArray<SafePointScalarObjectNode*> scobjs;
MachSafePointNode *mcall = n->as_MachSafePoint();
uint i;
// Print locals
for (i = 0; i < (uint)loc_size(); i++)
format_helper(regalloc, st, mcall->local(this, i), "L[", i, &scobjs);
// Print stack
for (i = 0; i < (uint)stk_size(); i++) {
if ((uint)(_stkoff + i) >= mcall->len())
st->print(" oob ");
else
format_helper(regalloc, st, mcall->stack(this, i), "STK[", i, &scobjs);
}
for (i = 0; (int)i < nof_monitors(); i++) {
Node *box = mcall->monitor_box(this, i);
Node *obj = mcall->monitor_obj(this, i);
if (regalloc->node_regs_max_index() > 0 &&
OptoReg::is_valid(regalloc->get_reg_first(box))) {
box = BoxLockNode::box_node(box);
format_helper(regalloc, st, box, "MON-BOX[", i, &scobjs);
} else {
OptoReg::Name box_reg = BoxLockNode::reg(box);
st->print(" MON-BOX%d=%s+%d",
i,
OptoReg::regname(OptoReg::c_frame_pointer),
regalloc->reg2offset(box_reg));
}
const char* obj_msg = "MON-OBJ[";
if (EliminateLocks) {
if (BoxLockNode::box_node(box)->is_eliminated())
obj_msg = "MON-OBJ(LOCK ELIMINATED)[";
}
format_helper(regalloc, st, obj, obj_msg, i, &scobjs);
}
for (i = 0; i < (uint)scobjs.length(); i++) {
// Scalar replaced objects.
st->cr();
st->print(" # ScObj" INT32_FORMAT " ", i);
SafePointScalarObjectNode* spobj = scobjs.at(i);
ciKlass* cik = spobj->bottom_type()->is_oopptr()->klass();
assert(cik->is_instance_klass() ||
cik->is_array_klass(), "Not supported allocation.");
ciInstanceKlass *iklass = NULL;
if (cik->is_instance_klass()) {
cik->print_name_on(st);
iklass = cik->as_instance_klass();
} else if (cik->is_type_array_klass()) {
cik->as_array_klass()->base_element_type()->print_name_on(st);
st->print("[%d]", spobj->n_fields());
} else if (cik->is_obj_array_klass()) {
ciKlass* cie = cik->as_obj_array_klass()->base_element_klass();
if (cie->is_instance_klass()) {
cie->print_name_on(st);
} else if (cie->is_type_array_klass()) {
cie->as_array_klass()->base_element_type()->print_name_on(st);
} else {
ShouldNotReachHere();
}
st->print("[%d]", spobj->n_fields());
int ndim = cik->as_array_klass()->dimension() - 1;
while (ndim-- > 0) {
st->print("[]");
}
}
st->print("={");
uint nf = spobj->n_fields();
if (nf > 0) {
uint first_ind = spobj->first_index(mcall->jvms());
Node* fld_node = mcall->in(first_ind);
ciField* cifield;
if (iklass != NULL) {
st->print(" [");
cifield = iklass->nonstatic_field_at(0);
cifield->print_name_on(st);
format_helper(regalloc, st, fld_node, ":", 0, &scobjs);
} else {
format_helper(regalloc, st, fld_node, "[", 0, &scobjs);
}
for (uint j = 1; j < nf; j++) {
fld_node = mcall->in(first_ind+j);
if (iklass != NULL) {
st->print(", [");
cifield = iklass->nonstatic_field_at(j);
cifield->print_name_on(st);
format_helper(regalloc, st, fld_node, ":", j, &scobjs);
} else {
format_helper(regalloc, st, fld_node, ", [", j, &scobjs);
}
}
}
st->print(" }");
}
}
st->cr();
if (caller() != NULL) caller()->format(regalloc, n, st);
}
void JVMState::dump_spec(outputStream *st) const {
if (_method != NULL) {
bool printed = false;
if (!Verbose) {
// The JVMS dumps make really, really long lines.
// Take out the most boring parts, which are the package prefixes.
char buf[500];
stringStream namest(buf, sizeof(buf));
_method->print_short_name(&namest);
if (namest.count() < sizeof(buf)) {
const char* name = namest.base();
if (name[0] == ' ') ++name;
const char* endcn = strchr(name, ':'); // end of class name
if (endcn == NULL) endcn = strchr(name, '(');
if (endcn == NULL) endcn = name + strlen(name);
while (endcn > name && endcn[-1] != '.' && endcn[-1] != '/')
--endcn;
st->print(" %s", endcn);
printed = true;
}
}
if (!printed)
_method->print_short_name(st);
st->print(" @ bci:%d",_bci);
if(_reexecute == Reexecute_True)
st->print(" reexecute");
} else {
st->print(" runtime stub");
}
if (caller() != NULL) caller()->dump_spec(st);
}
void JVMState::dump_on(outputStream* st) const {
bool print_map = _map && !((uintptr_t)_map & 1) &&
((caller() == NULL) || (caller()->map() != _map));
if (print_map) {
if (_map->len() > _map->req()) { // _map->has_exceptions()
Node* ex = _map->in(_map->req()); // _map->next_exception()
// skip the first one; it's already being printed
while (ex != NULL && ex->len() > ex->req()) {
ex = ex->in(ex->req()); // ex->next_exception()
ex->dump(1);
}
}
_map->dump(Verbose ? 2 : 1);
}
if (caller() != NULL) {
caller()->dump_on(st);
}
st->print("JVMS depth=%d loc=%d stk=%d arg=%d mon=%d scalar=%d end=%d mondepth=%d sp=%d bci=%d reexecute=%s method=",
depth(), locoff(), stkoff(), argoff(), monoff(), scloff(), endoff(), monitor_depth(), sp(), bci(), should_reexecute()?"true":"false");
if (_method == NULL) {
st->print_cr("(none)");
} else {
_method->print_name(st);
st->cr();
if (bci() >= 0 && bci() < _method->code_size()) {
st->print(" bc: ");
_method->print_codes_on(bci(), bci()+1, st);
}
}
}
// Extra way to dump a jvms from the debugger,
// to avoid a bug with C++ member function calls.
void dump_jvms(JVMState* jvms) {
jvms->dump();
}
#endif
//--------------------------clone_shallow--------------------------------------
JVMState* JVMState::clone_shallow(Compile* C) const {
JVMState* n = has_method() ? new (C) JVMState(_method, _caller) : new (C) JVMState(0);
n->set_bci(_bci);
n->_reexecute = _reexecute;
n->set_locoff(_locoff);
n->set_stkoff(_stkoff);
n->set_monoff(_monoff);
n->set_scloff(_scloff);
n->set_endoff(_endoff);
n->set_sp(_sp);
n->set_map(_map);
return n;
}
//---------------------------clone_deep----------------------------------------
JVMState* JVMState::clone_deep(Compile* C) const {
JVMState* n = clone_shallow(C);
for (JVMState* p = n; p->_caller != NULL; p = p->_caller) {
p->_caller = p->_caller->clone_shallow(C);
}
assert(n->depth() == depth(), "sanity");
assert(n->debug_depth() == debug_depth(), "sanity");
return n;
}
/**
* Reset map for all callers
*/
void JVMState::set_map_deep(SafePointNode* map) {
for (JVMState* p = this; p->_caller != NULL; p = p->_caller) {
p->set_map(map);
}
}
// Adapt offsets in in-array after adding or removing an edge.
// Prerequisite is that the JVMState is used by only one node.
void JVMState::adapt_position(int delta) {
for (JVMState* jvms = this; jvms != NULL; jvms = jvms->caller()) {
jvms->set_locoff(jvms->locoff() + delta);
jvms->set_stkoff(jvms->stkoff() + delta);
jvms->set_monoff(jvms->monoff() + delta);
jvms->set_scloff(jvms->scloff() + delta);
jvms->set_endoff(jvms->endoff() + delta);
}
}
// Mirror the stack size calculation in the deopt code
// How much stack space would we need at this point in the program in
// case of deoptimization?
int JVMState::interpreter_frame_size() const {
const JVMState* jvms = this;
int size = 0;
int callee_parameters = 0;
int callee_locals = 0;
int extra_args = method()->max_stack() - stk_size();
while (jvms != NULL) {
int locks = jvms->nof_monitors();
int temps = jvms->stk_size();
bool is_top_frame = (jvms == this);
ciMethod* method = jvms->method();
int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),
temps + callee_parameters,
extra_args,
locks,
callee_parameters,
callee_locals,
is_top_frame);
size += frame_size;
callee_parameters = method->size_of_parameters();
callee_locals = method->max_locals();
extra_args = 0;
jvms = jvms->caller();
}
return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;
}
//=============================================================================
uint CallNode::cmp( const Node &n ) const
{ return _tf == ((CallNode&)n)._tf && _jvms == ((CallNode&)n)._jvms; }
#ifndef PRODUCT
void CallNode::dump_req(outputStream *st) const {
// Dump the required inputs, enclosed in '(' and ')'
uint i; // Exit value of loop
for (i = 0; i < req(); i++) { // For all required inputs
if (i == TypeFunc::Parms) st->print("(");
if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
else st->print("_ ");
}
st->print(")");
}
void CallNode::dump_spec(outputStream *st) const {
st->print(" ");
tf()->dump_on(st);
if (_cnt != COUNT_UNKNOWN) st->print(" C=%f",_cnt);
if (jvms() != NULL) jvms()->dump_spec(st);
}
#endif
const Type *CallNode::bottom_type() const { return tf()->range(); }
const Type *CallNode::Value(PhaseTransform *phase) const {
if (phase->type(in(0)) == Type::TOP) return Type::TOP;
return tf()->range();
}
//------------------------------calling_convention-----------------------------
void CallNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
// Use the standard compiler calling convention
Matcher::calling_convention( sig_bt, parm_regs, argcnt, true );
}
//------------------------------match------------------------------------------
// Construct projections for control, I/O, memory-fields, ..., and
// return result(s) along with their RegMask info
Node *CallNode::match( const ProjNode *proj, const Matcher *match ) {
switch (proj->_con) {
case TypeFunc::Control:
case TypeFunc::I_O:
case TypeFunc::Memory:
return new (match->C) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
case TypeFunc::Parms+1: // For LONG & DOUBLE returns
assert(tf()->_range->field_at(TypeFunc::Parms+1) == Type::HALF, "");
// 2nd half of doubles and longs
return new (match->C) MachProjNode(this,proj->_con, RegMask::Empty, (uint)OptoReg::Bad);
case TypeFunc::Parms: { // Normal returns
uint ideal_reg = tf()->range()->field_at(TypeFunc::Parms)->ideal_reg();
OptoRegPair regs = is_CallRuntime()
? match->c_return_value(ideal_reg,true) // Calls into C runtime
: match-> return_value(ideal_reg,true); // Calls into compiled Java code
RegMask rm = RegMask(regs.first());
if( OptoReg::is_valid(regs.second()) )
rm.Insert( regs.second() );
return new (match->C) MachProjNode(this,proj->_con,rm,ideal_reg);
}
case TypeFunc::ReturnAdr:
case TypeFunc::FramePtr:
default:
ShouldNotReachHere();
}
return NULL;
}
// Do we Match on this edge index or not? Match no edges
uint CallNode::match_edge(uint idx) const {
return 0;
}
//
// Determine whether the call could modify the field of the specified
// instance at the specified offset.
//
bool CallNode::may_modify(const TypeOopPtr *t_oop, PhaseTransform *phase) {
assert((t_oop != NULL), "sanity");
if (t_oop->is_known_instance()) {
// The instance_id is set only for scalar-replaceable allocations which
// are not passed as arguments according to Escape Analysis.
return false;
}
if (t_oop->is_ptr_to_boxed_value()) {
ciKlass* boxing_klass = t_oop->klass();
if (is_CallStaticJava() && as_CallStaticJava()->is_boxing_method()) {
// Skip unrelated boxing methods.
Node* proj = proj_out(TypeFunc::Parms);
if ((proj == NULL) || (phase->type(proj)->is_instptr()->klass() != boxing_klass)) {
return false;
}
}
if (is_CallJava() && as_CallJava()->method() != NULL) {
ciMethod* meth = as_CallJava()->method();
if (meth->is_accessor()) {
return false;
}
// May modify (by reflection) if an boxing object is passed
// as argument or returned.
if (returns_pointer() && (proj_out(TypeFunc::Parms) != NULL)) {
Node* proj = proj_out(TypeFunc::Parms);
const TypeInstPtr* inst_t = phase->type(proj)->isa_instptr();
if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||
(inst_t->klass() == boxing_klass))) {
return true;
}
}
const TypeTuple* d = tf()->domain();
for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
const TypeInstPtr* inst_t = d->field_at(i)->isa_instptr();
if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||
(inst_t->klass() == boxing_klass))) {
return true;
}
}
return false;
}
}
return true;
}
// Does this call have a direct reference to n other than debug information?
bool CallNode::has_non_debug_use(Node *n) {
const TypeTuple * d = tf()->domain();
for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
Node *arg = in(i);
if (arg == n) {
return true;
}
}
return false;
}
// Returns the unique CheckCastPP of a call
// or 'this' if there are several CheckCastPP
// or returns NULL if there is no one.
Node *CallNode::result_cast() {
Node *cast = NULL;
Node *p = proj_out(TypeFunc::Parms);
if (p == NULL)
return NULL;
for (DUIterator_Fast imax, i = p->fast_outs(imax); i < imax; i++) {
Node *use = p->fast_out(i);
if (use->is_CheckCastPP()) {
if (cast != NULL) {
return this; // more than 1 CheckCastPP
}
cast = use;
}
}
return cast;
}
void CallNode::extract_projections(CallProjections* projs, bool separate_io_proj) {
projs->fallthrough_proj = NULL;
projs->fallthrough_catchproj = NULL;
projs->fallthrough_ioproj = NULL;
projs->catchall_ioproj = NULL;
projs->catchall_catchproj = NULL;
projs->fallthrough_memproj = NULL;
projs->catchall_memproj = NULL;
projs->resproj = NULL;
projs->exobj = NULL;
for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
ProjNode *pn = fast_out(i)->as_Proj();
if (pn->outcnt() == 0) continue;
switch (pn->_con) {
case TypeFunc::Control:
{
// For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj
projs->fallthrough_proj = pn;
DUIterator_Fast jmax, j = pn->fast_outs(jmax);
const Node *cn = pn->fast_out(j);
if (cn->is_Catch()) {
ProjNode *cpn = NULL;
for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) {
cpn = cn->fast_out(k)->as_Proj();
assert(cpn->is_CatchProj(), "must be a CatchProjNode");
if (cpn->_con == CatchProjNode::fall_through_index)
projs->fallthrough_catchproj = cpn;
else {
assert(cpn->_con == CatchProjNode::catch_all_index, "must be correct index.");
projs->catchall_catchproj = cpn;
}
}
}
break;
}
case TypeFunc::I_O:
if (pn->_is_io_use)
projs->catchall_ioproj = pn;
else
projs->fallthrough_ioproj = pn;
for (DUIterator j = pn->outs(); pn->has_out(j); j++) {
Node* e = pn->out(j);
if (e->Opcode() == Op_CreateEx && e->in(0)->is_CatchProj() && e->outcnt() > 0) {
assert(projs->exobj == NULL, "only one");
projs->exobj = e;
}
}
break;
case TypeFunc::Memory:
if (pn->_is_io_use)
projs->catchall_memproj = pn;
else
projs->fallthrough_memproj = pn;
break;
case TypeFunc::Parms:
projs->resproj = pn;
break;
default:
assert(false, "unexpected projection from allocation node.");
}
}
// The resproj may not exist because the result couuld be ignored
// and the exception object may not exist if an exception handler
// swallows the exception but all the other must exist and be found.
assert(projs->fallthrough_proj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->fallthrough_catchproj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->fallthrough_memproj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->fallthrough_ioproj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->catchall_catchproj != NULL, "must be found");
if (separate_io_proj) {
assert(Compile::current()->inlining_incrementally() || projs->catchall_memproj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->catchall_ioproj != NULL, "must be found");
}
}
Node *CallNode::Ideal(PhaseGVN *phase, bool can_reshape) {
CallGenerator* cg = generator();
if (can_reshape && cg != NULL && cg->is_mh_late_inline() && !cg->already_attempted()) {
// Check whether this MH handle call becomes a candidate for inlining
ciMethod* callee = cg->method();
vmIntrinsics::ID iid = callee->intrinsic_id();
if (iid == vmIntrinsics::_invokeBasic) {
if (in(TypeFunc::Parms)->Opcode() == Op_ConP) {
phase->C->prepend_late_inline(cg);
set_generator(NULL);
}
} else {
assert(callee->has_member_arg(), "wrong type of call?");
if (in(TypeFunc::Parms + callee->arg_size() - 1)->Opcode() == Op_ConP) {
phase->C->prepend_late_inline(cg);
set_generator(NULL);
}
}
}
return SafePointNode::Ideal(phase, can_reshape);
}
//=============================================================================
uint CallJavaNode::size_of() const { return sizeof(*this); }
uint CallJavaNode::cmp( const Node &n ) const {
CallJavaNode &call = (CallJavaNode&)n;
return CallNode::cmp(call) && _method == call._method;
}
#ifndef PRODUCT
void CallJavaNode::dump_spec(outputStream *st) const {
if( _method ) _method->print_short_name(st);
CallNode::dump_spec(st);
}
#endif
//=============================================================================
uint CallStaticJavaNode::size_of() const { return sizeof(*this); }
uint CallStaticJavaNode::cmp( const Node &n ) const {
CallStaticJavaNode &call = (CallStaticJavaNode&)n;
return CallJavaNode::cmp(call);
}
//----------------------------uncommon_trap_request----------------------------
// If this is an uncommon trap, return the request code, else zero.
int CallStaticJavaNode::uncommon_trap_request() const {
if (_name != NULL && !strcmp(_name, "uncommon_trap")) {
return extract_uncommon_trap_request(this);
}
return 0;
}
int CallStaticJavaNode::extract_uncommon_trap_request(const Node* call) {
#ifndef PRODUCT
if (!(call->req() > TypeFunc::Parms &&
call->in(TypeFunc::Parms) != NULL &&
call->in(TypeFunc::Parms)->is_Con())) {
assert(in_dump() != 0, "OK if dumping");
tty->print("[bad uncommon trap]");
return 0;
}
#endif
return call->in(TypeFunc::Parms)->bottom_type()->is_int()->get_con();
}
#ifndef PRODUCT
void CallStaticJavaNode::dump_spec(outputStream *st) const {
st->print("# Static ");
if (_name != NULL) {
st->print("%s", _name);
int trap_req = uncommon_trap_request();
if (trap_req != 0) {
char buf[100];
st->print("(%s)",
Deoptimization::format_trap_request(buf, sizeof(buf),
trap_req));
}
st->print(" ");
}
CallJavaNode::dump_spec(st);
}
#endif
//=============================================================================
uint CallDynamicJavaNode::size_of() const { return sizeof(*this); }
uint CallDynamicJavaNode::cmp( const Node &n ) const {
CallDynamicJavaNode &call = (CallDynamicJavaNode&)n;
return CallJavaNode::cmp(call);
}
#ifndef PRODUCT
void CallDynamicJavaNode::dump_spec(outputStream *st) const {
st->print("# Dynamic ");
CallJavaNode::dump_spec(st);
}
#endif
//=============================================================================
uint CallRuntimeNode::size_of() const { return sizeof(*this); }
uint CallRuntimeNode::cmp( const Node &n ) const {
CallRuntimeNode &call = (CallRuntimeNode&)n;
return CallNode::cmp(call) && !strcmp(_name,call._name);
}
#ifndef PRODUCT
void CallRuntimeNode::dump_spec(outputStream *st) const {
st->print("# ");
st->print("%s", _name);
CallNode::dump_spec(st);
}
#endif
//------------------------------calling_convention-----------------------------
void CallRuntimeNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
Matcher::c_calling_convention( sig_bt, parm_regs, argcnt );
}
//=============================================================================
//------------------------------calling_convention-----------------------------
//=============================================================================
#ifndef PRODUCT
void CallLeafNode::dump_spec(outputStream *st) const {
st->print("# ");
st->print("%s", _name);
CallNode::dump_spec(st);
}
#endif
//=============================================================================
void SafePointNode::set_local(JVMState* jvms, uint idx, Node *c) {
assert(verify_jvms(jvms), "jvms must match");
int loc = jvms->locoff() + idx;
if (in(loc)->is_top() && idx > 0 && !c->is_top() ) {
// If current local idx is top then local idx - 1 could
// be a long/double that needs to be killed since top could
// represent the 2nd half ofthe long/double.
uint ideal = in(loc -1)->ideal_reg();
if (ideal == Op_RegD || ideal == Op_RegL) {
// set other (low index) half to top
set_req(loc - 1, in(loc));
}
}
set_req(loc, c);
}
uint SafePointNode::size_of() const { return sizeof(*this); }
uint SafePointNode::cmp( const Node &n ) const {
return (&n == this); // Always fail except on self
}
//-------------------------set_next_exception----------------------------------
void SafePointNode::set_next_exception(SafePointNode* n) {
assert(n == NULL || n->Opcode() == Op_SafePoint, "correct value for next_exception");
if (len() == req()) {
if (n != NULL) add_prec(n);
} else {
set_prec(req(), n);
}
}
//----------------------------next_exception-----------------------------------
SafePointNode* SafePointNode::next_exception() const {
if (len() == req()) {
return NULL;
} else {
Node* n = in(req());
assert(n == NULL || n->Opcode() == Op_SafePoint, "no other uses of prec edges");
return (SafePointNode*) n;
}
}
//------------------------------Ideal------------------------------------------
// Skip over any collapsed Regions
Node *SafePointNode::Ideal(PhaseGVN *phase, bool can_reshape) {
return remove_dead_region(phase, can_reshape) ? this : NULL;
}
//------------------------------Identity---------------------------------------
// Remove obviously duplicate safepoints
Node *SafePointNode::Identity( PhaseTransform *phase ) {
// If you have back to back safepoints, remove one
if( in(TypeFunc::Control)->is_SafePoint() )
return in(TypeFunc::Control);
if( in(0)->is_Proj() ) {
Node *n0 = in(0)->in(0);
// Check if he is a call projection (except Leaf Call)
if( n0->is_Catch() ) {
n0 = n0->in(0)->in(0);
assert( n0->is_Call(), "expect a call here" );
}
if( n0->is_Call() && n0->as_Call()->guaranteed_safepoint() ) {
// Useless Safepoint, so remove it
return in(TypeFunc::Control);
}
}
return this;
}
//------------------------------Value------------------------------------------
const Type *SafePointNode::Value( PhaseTransform *phase ) const {
if( phase->type(in(0)) == Type::TOP ) return Type::TOP;
if( phase->eqv( in(0), this ) ) return Type::TOP; // Dead infinite loop
return Type::CONTROL;
}
#ifndef PRODUCT
void SafePointNode::dump_spec(outputStream *st) const {
st->print(" SafePoint ");
}
#endif
const RegMask &SafePointNode::in_RegMask(uint idx) const {
if( idx < TypeFunc::Parms ) return RegMask::Empty;
// Values outside the domain represent debug info
return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
}
const RegMask &SafePointNode::out_RegMask() const {
return RegMask::Empty;
}
void SafePointNode::grow_stack(JVMState* jvms, uint grow_by) {
assert((int)grow_by > 0, "sanity");
int monoff = jvms->monoff();
int scloff = jvms->scloff();
int endoff = jvms->endoff();
assert(endoff == (int)req(), "no other states or debug info after me");
Node* top = Compile::current()->top();
for (uint i = 0; i < grow_by; i++) {
ins_req(monoff, top);
}
jvms->set_monoff(monoff + grow_by);
jvms->set_scloff(scloff + grow_by);
jvms->set_endoff(endoff + grow_by);
}
void SafePointNode::push_monitor(const FastLockNode *lock) {
// Add a LockNode, which points to both the original BoxLockNode (the
// stack space for the monitor) and the Object being locked.
const int MonitorEdges = 2;
assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
assert(req() == jvms()->endoff(), "correct sizing");
int nextmon = jvms()->scloff();
if (GenerateSynchronizationCode) {
ins_req(nextmon, lock->box_node());
ins_req(nextmon+1, lock->obj_node());
} else {
Node* top = Compile::current()->top();
ins_req(nextmon, top);
ins_req(nextmon, top);
}
jvms()->set_scloff(nextmon + MonitorEdges);
jvms()->set_endoff(req());
}
void SafePointNode::pop_monitor() {
// Delete last monitor from debug info
debug_only(int num_before_pop = jvms()->nof_monitors());
const int MonitorEdges = 2;
assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
int scloff = jvms()->scloff();
int endoff = jvms()->endoff();
int new_scloff = scloff - MonitorEdges;
int new_endoff = endoff - MonitorEdges;
jvms()->set_scloff(new_scloff);
jvms()->set_endoff(new_endoff);
while (scloff > new_scloff) del_req_ordered(--scloff);
assert(jvms()->nof_monitors() == num_before_pop-1, "");
}
Node *SafePointNode::peek_monitor_box() const {
int mon = jvms()->nof_monitors() - 1;
assert(mon >= 0, "most have a monitor");
return monitor_box(jvms(), mon);
}
Node *SafePointNode::peek_monitor_obj() const {
int mon = jvms()->nof_monitors() - 1;
assert(mon >= 0, "most have a monitor");
return monitor_obj(jvms(), mon);
}
// Do we Match on this edge index or not? Match no edges
uint SafePointNode::match_edge(uint idx) const {
if( !needs_polling_address_input() )
return 0;
return (TypeFunc::Parms == idx);
}
//============== SafePointScalarObjectNode ==============
SafePointScalarObjectNode::SafePointScalarObjectNode(const TypeOopPtr* tp,
#ifdef ASSERT
AllocateNode* alloc,
#endif
uint first_index,
uint n_fields) :
TypeNode(tp, 1), // 1 control input -- seems required. Get from root.
#ifdef ASSERT
_alloc(alloc),
#endif
_first_index(first_index),
_n_fields(n_fields)
{
init_class_id(Class_SafePointScalarObject);
}
// Do not allow value-numbering for SafePointScalarObject node.
uint SafePointScalarObjectNode::hash() const { return NO_HASH; }
uint SafePointScalarObjectNode::cmp( const Node &n ) const {
return (&n == this); // Always fail except on self
}
uint SafePointScalarObjectNode::ideal_reg() const {
return 0; // No matching to machine instruction
}
const RegMask &SafePointScalarObjectNode::in_RegMask(uint idx) const {
return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
}
const RegMask &SafePointScalarObjectNode::out_RegMask() const {
return RegMask::Empty;
}
uint SafePointScalarObjectNode::match_edge(uint idx) const {
return 0;
}
SafePointScalarObjectNode*
SafePointScalarObjectNode::clone(Dict* sosn_map) const {
void* cached = (*sosn_map)[(void*)this];
if (cached != NULL) {
return (SafePointScalarObjectNode*)cached;
}
SafePointScalarObjectNode* res = (SafePointScalarObjectNode*)Node::clone();
sosn_map->Insert((void*)this, (void*)res);
return res;
}
#ifndef PRODUCT
void SafePointScalarObjectNode::dump_spec(outputStream *st) const {
st->print(" # fields@[%d..%d]", first_index(),
first_index() + n_fields() - 1);
}
#endif
//=============================================================================
uint AllocateNode::size_of() const { return sizeof(*this); }
AllocateNode::AllocateNode(Compile* C, const TypeFunc *atype,
Node *ctrl, Node *mem, Node *abio,
Node *size, Node *klass_node, Node *initial_test)
: CallNode(atype, NULL, TypeRawPtr::BOTTOM)
{
init_class_id(Class_Allocate);
init_flags(Flag_is_macro);
_is_scalar_replaceable = false;
_is_non_escaping = false;
Node *topnode = C->top();
init_req( TypeFunc::Control , ctrl );
init_req( TypeFunc::I_O , abio );
init_req( TypeFunc::Memory , mem );
init_req( TypeFunc::ReturnAdr, topnode );
init_req( TypeFunc::FramePtr , topnode );
init_req( AllocSize , size);
init_req( KlassNode , klass_node);
init_req( InitialTest , initial_test);
init_req( ALength , topnode);
C->add_macro_node(this);
}
//=============================================================================
Node* AllocateArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
if (remove_dead_region(phase, can_reshape)) return this;
// Don't bother trying to transform a dead node
if (in(0) && in(0)->is_top()) return NULL;
const Type* type = phase->type(Ideal_length());
if (type->isa_int() && type->is_int()->_hi < 0) {
if (can_reshape) {
PhaseIterGVN *igvn = phase->is_IterGVN();
// Unreachable fall through path (negative array length),
// the allocation can only throw so disconnect it.
Node* proj = proj_out(TypeFunc::Control);
Node* catchproj = NULL;
if (proj != NULL) {
for (DUIterator_Fast imax, i = proj->fast_outs(imax); i < imax; i++) {
Node *cn = proj->fast_out(i);
if (cn->is_Catch()) {
catchproj = cn->as_Multi()->proj_out(CatchProjNode::fall_through_index);
break;
}
}
}
if (catchproj != NULL && catchproj->outcnt() > 0 &&
(catchproj->outcnt() > 1 ||
catchproj->unique_out()->Opcode() != Op_Halt)) {
assert(catchproj->is_CatchProj(), "must be a CatchProjNode");
Node* nproj = catchproj->clone();
igvn->register_new_node_with_optimizer(nproj);
Node *frame = new (phase->C) ParmNode( phase->C->start(), TypeFunc::FramePtr );
frame = phase->transform(frame);
// Halt & Catch Fire
Node *halt = new (phase->C) HaltNode( nproj, frame );
phase->C->root()->add_req(halt);
phase->transform(halt);
igvn->replace_node(catchproj, phase->C->top());
return this;
}
} else {
// Can't correct it during regular GVN so register for IGVN
phase->C->record_for_igvn(this);
}
}
return NULL;
}
// Retrieve the length from the AllocateArrayNode. Narrow the type with a
// CastII, if appropriate. If we are not allowed to create new nodes, and
// a CastII is appropriate, return NULL.
Node *AllocateArrayNode::make_ideal_length(const TypeOopPtr* oop_type, PhaseTransform *phase, bool allow_new_nodes) {
Node *length = in(AllocateNode::ALength);
assert(length != NULL, "length is not null");
const TypeInt* length_type = phase->find_int_type(length);
const TypeAryPtr* ary_type = oop_type->isa_aryptr();
if (ary_type != NULL && length_type != NULL) {
const TypeInt* narrow_length_type = ary_type->narrow_size_type(length_type);
if (narrow_length_type != length_type) {
// Assert one of:
// - the narrow_length is 0
// - the narrow_length is not wider than length
assert(narrow_length_type == TypeInt::ZERO ||
length_type->is_con() && narrow_length_type->is_con() &&
(narrow_length_type->_hi <= length_type->_lo) ||
(narrow_length_type->_hi <= length_type->_hi &&
narrow_length_type->_lo >= length_type->_lo),
"narrow type must be narrower than length type");
// Return NULL if new nodes are not allowed
if (!allow_new_nodes) return NULL;
// Create a cast which is control dependent on the initialization to
// propagate the fact that the array length must be positive.
length = new (phase->C) CastIINode(length, narrow_length_type);
length->set_req(0, initialization()->proj_out(0));
}
}
return length;
}
//=============================================================================
uint LockNode::size_of() const { return sizeof(*this); }
// Redundant lock elimination
//
// There are various patterns of locking where we release and
// immediately reacquire a lock in a piece of code where no operations
// occur in between that would be observable. In those cases we can
// skip releasing and reacquiring the lock without violating any
// fairness requirements. Doing this around a loop could cause a lock
// to be held for a very long time so we concentrate on non-looping
// control flow. We also require that the operations are fully
// redundant meaning that we don't introduce new lock operations on
// some paths so to be able to eliminate it on others ala PRE. This
// would probably require some more extensive graph manipulation to
// guarantee that the memory edges were all handled correctly.
//
// Assuming p is a simple predicate which can't trap in any way and s
// is a synchronized method consider this code:
//
// s();
// if (p)
// s();
// else
// s();
// s();
//
// 1. The unlocks of the first call to s can be eliminated if the
// locks inside the then and else branches are eliminated.
//
// 2. The unlocks of the then and else branches can be eliminated if
// the lock of the final call to s is eliminated.
//
// Either of these cases subsumes the simple case of sequential control flow
//
// Addtionally we can eliminate versions without the else case:
//
// s();
// if (p)
// s();
// s();
//
// 3. In this case we eliminate the unlock of the first s, the lock
// and unlock in the then case and the lock in the final s.
//
// Note also that in all these cases the then/else pieces don't have
// to be trivial as long as they begin and end with synchronization
// operations.
//
// s();
// if (p)
// s();
// f();
// s();
// s();
//
// The code will work properly for this case, leaving in the unlock
// before the call to f and the relock after it.
//
// A potentially interesting case which isn't handled here is when the
// locking is partially redundant.
//
// s();
// if (p)
// s();
//
// This could be eliminated putting unlocking on the else case and
// eliminating the first unlock and the lock in the then side.
// Alternatively the unlock could be moved out of the then side so it
// was after the merge and the first unlock and second lock
// eliminated. This might require less manipulation of the memory
// state to get correct.
//
// Additionally we might allow work between a unlock and lock before
// giving up eliminating the locks. The current code disallows any
// conditional control flow between these operations. A formulation
// similar to partial redundancy elimination computing the
// availability of unlocking and the anticipatability of locking at a
// program point would allow detection of fully redundant locking with
// some amount of work in between. I'm not sure how often I really
// think that would occur though. Most of the cases I've seen
// indicate it's likely non-trivial work would occur in between.
// There may be other more complicated constructs where we could
// eliminate locking but I haven't seen any others appear as hot or
// interesting.
//
// Locking and unlocking have a canonical form in ideal that looks
// roughly like this:
//
// <obj>
// | \\------+
// | \ \
// | BoxLock \
// | | | \
// | | \ \
// | | FastLock
// | | /
// | | /
// | | |
//
// Lock
// |
// Proj #0
// |
// MembarAcquire
// |
// Proj #0
//
// MembarRelease
// |
// Proj #0
// |
// Unlock
// |
// Proj #0
//
//
// This code proceeds by processing Lock nodes during PhaseIterGVN
// and searching back through its control for the proper code
// patterns. Once it finds a set of lock and unlock operations to
// eliminate they are marked as eliminatable which causes the
// expansion of the Lock and Unlock macro nodes to make the operation a NOP
//
//=============================================================================
//
// Utility function to skip over uninteresting control nodes. Nodes skipped are:
// - copy regions. (These may not have been optimized away yet.)
// - eliminated locking nodes
//
static Node *next_control(Node *ctrl) {
if (ctrl == NULL)
return NULL;
while (1) {
if (ctrl->is_Region()) {
RegionNode *r = ctrl->as_Region();
Node *n = r->is_copy();
if (n == NULL)
break; // hit a region, return it
else
ctrl = n;
} else if (ctrl->is_Proj()) {
Node *in0 = ctrl->in(0);
if (in0->is_AbstractLock() && in0->as_AbstractLock()->is_eliminated()) {
ctrl = in0->in(0);
} else {
break;
}
} else {
break; // found an interesting control
}
}
return ctrl;
}
//
// Given a control, see if it's the control projection of an Unlock which
// operating on the same object as lock.
//
bool AbstractLockNode::find_matching_unlock(const Node* ctrl, LockNode* lock,
GrowableArray<AbstractLockNode*> &lock_ops) {
ProjNode *ctrl_proj = (ctrl->is_Proj()) ? ctrl->as_Proj() : NULL;
if (ctrl_proj != NULL && ctrl_proj->_con == TypeFunc::Control) {
Node *n = ctrl_proj->in(0);
if (n != NULL && n->is_Unlock()) {
UnlockNode *unlock = n->as_Unlock();
if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&
BoxLockNode::same_slot(lock->box_node(), unlock->box_node()) &&
!unlock->is_eliminated()) {
lock_ops.append(unlock);
return true;
}
}
}
return false;
}
//
// Find the lock matching an unlock. Returns null if a safepoint
// or complicated control is encountered first.
LockNode *AbstractLockNode::find_matching_lock(UnlockNode* unlock) {
LockNode *lock_result = NULL;
// find the matching lock, or an intervening safepoint
Node *ctrl = next_control(unlock->in(0));
while (1) {
assert(ctrl != NULL, "invalid control graph");
assert(!ctrl->is_Start(), "missing lock for unlock");
if (ctrl->is_top()) break; // dead control path
if (ctrl->is_Proj()) ctrl = ctrl->in(0);
if (ctrl->is_SafePoint()) {
break; // found a safepoint (may be the lock we are searching for)
} else if (ctrl->is_Region()) {
// Check for a simple diamond pattern. Punt on anything more complicated
if (ctrl->req() == 3 && ctrl->in(1) != NULL && ctrl->in(2) != NULL) {
Node *in1 = next_control(ctrl->in(1));
Node *in2 = next_control(ctrl->in(2));
if (((in1->is_IfTrue() && in2->is_IfFalse()) ||
(in2->is_IfTrue() && in1->is_IfFalse())) && (in1->in(0) == in2->in(0))) {
ctrl = next_control(in1->in(0)->in(0));
} else {
break;
}
} else {
break;
}
} else {
ctrl = next_control(ctrl->in(0)); // keep searching
}
}
if (ctrl->is_Lock()) {
LockNode *lock = ctrl->as_Lock();
if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&
BoxLockNode::same_slot(lock->box_node(), unlock->box_node())) {
lock_result = lock;
}
}
return lock_result;
}
// This code corresponds to case 3 above.
bool AbstractLockNode::find_lock_and_unlock_through_if(Node* node, LockNode* lock,
GrowableArray<AbstractLockNode*> &lock_ops) {
Node* if_node = node->in(0);
bool if_true = node->is_IfTrue();
if (if_node->is_If() && if_node->outcnt() == 2 && (if_true || node->is_IfFalse())) {
Node *lock_ctrl = next_control(if_node->in(0));
if (find_matching_unlock(lock_ctrl, lock, lock_ops)) {
Node* lock1_node = NULL;
ProjNode* proj = if_node->as_If()->proj_out(!if_true);
if (if_true) {
if (proj->is_IfFalse() && proj->outcnt() == 1) {
lock1_node = proj->unique_out();
}
} else {
if (proj->is_IfTrue() && proj->outcnt() == 1) {
lock1_node = proj->unique_out();
}
}
if (lock1_node != NULL && lock1_node->is_Lock()) {
LockNode *lock1 = lock1_node->as_Lock();
if (lock->obj_node()->eqv_uncast(lock1->obj_node()) &&
BoxLockNode::same_slot(lock->box_node(), lock1->box_node()) &&
!lock1->is_eliminated()) {
lock_ops.append(lock1);
return true;
}
}
}
}
lock_ops.trunc_to(0);
return false;
}
bool AbstractLockNode::find_unlocks_for_region(const RegionNode* region, LockNode* lock,
GrowableArray<AbstractLockNode*> &lock_ops) {
// check each control merging at this point for a matching unlock.
// in(0) should be self edge so skip it.
for (int i = 1; i < (int)region->req(); i++) {
Node *in_node = next_control(region->in(i));
if (in_node != NULL) {
if (find_matching_unlock(in_node, lock, lock_ops)) {
// found a match so keep on checking.
continue;
} else if (find_lock_and_unlock_through_if(in_node, lock, lock_ops)) {
continue;
}
// If we fall through to here then it was some kind of node we
// don't understand or there wasn't a matching unlock, so give
// up trying to merge locks.
lock_ops.trunc_to(0);
return false;
}
}
return true;
}
#ifndef PRODUCT
//
// Create a counter which counts the number of times this lock is acquired
//
void AbstractLockNode::create_lock_counter(JVMState* state) {
_counter = OptoRuntime::new_named_counter(state, NamedCounter::LockCounter);
}
void AbstractLockNode::set_eliminated_lock_counter() {
if (_counter) {
// Update the counter to indicate that this lock was eliminated.
// The counter update code will stay around even though the
// optimizer will eliminate the lock operation itself.
_counter->set_tag(NamedCounter::EliminatedLockCounter);
}
}
#endif
//=============================================================================
Node *LockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
// perform any generic optimizations first (returns 'this' or NULL)
Node *result = SafePointNode::Ideal(phase, can_reshape);
if (result != NULL) return result;
// Don't bother trying to transform a dead node
if (in(0) && in(0)->is_top()) return NULL;
// Now see if we can optimize away this lock. We don't actually
// remove the locking here, we simply set the _eliminate flag which
// prevents macro expansion from expanding the lock. Since we don't
// modify the graph, the value returned from this function is the
// one computed above.
if (can_reshape && EliminateLocks && !is_non_esc_obj()) {
//
// If we are locking an unescaped object, the lock/unlock is unnecessary
//
ConnectionGraph *cgr = phase->C->congraph();
if (cgr != NULL && cgr->not_global_escape(obj_node())) {
assert(!is_eliminated() || is_coarsened(), "sanity");
// The lock could be marked eliminated by lock coarsening
// code during first IGVN before EA. Replace coarsened flag
// to eliminate all associated locks/unlocks.
this->set_non_esc_obj();
return result;
}
//
// Try lock coarsening
//
PhaseIterGVN* iter = phase->is_IterGVN();
if (iter != NULL && !is_eliminated()) {
GrowableArray<AbstractLockNode*> lock_ops;
Node *ctrl = next_control(in(0));
// now search back for a matching Unlock
if (find_matching_unlock(ctrl, this, lock_ops)) {
// found an unlock directly preceding this lock. This is the
// case of single unlock directly control dependent on a
// single lock which is the trivial version of case 1 or 2.
} else if (ctrl->is_Region() ) {
if (find_unlocks_for_region(ctrl->as_Region(), this, lock_ops)) {
// found lock preceded by multiple unlocks along all paths
// joining at this point which is case 3 in description above.
}
} else {
// see if this lock comes from either half of an if and the
// predecessors merges unlocks and the other half of the if
// performs a lock.
if (find_lock_and_unlock_through_if(ctrl, this, lock_ops)) {
// found unlock splitting to an if with locks on both branches.
}
}
if (lock_ops.length() > 0) {
// add ourselves to the list of locks to be eliminated.
lock_ops.append(this);
#ifndef PRODUCT
if (PrintEliminateLocks) {
int locks = 0;
int unlocks = 0;
for (int i = 0; i < lock_ops.length(); i++) {
AbstractLockNode* lock = lock_ops.at(i);
if (lock->Opcode() == Op_Lock)
locks++;
else
unlocks++;
if (Verbose) {
lock->dump(1);
}
}
tty->print_cr("***Eliminated %d unlocks and %d locks", unlocks, locks);
}
#endif
// for each of the identified locks, mark them
// as eliminatable
for (int i = 0; i < lock_ops.length(); i++) {
AbstractLockNode* lock = lock_ops.at(i);
// Mark it eliminated by coarsening and update any counters
lock->set_coarsened();
}
} else if (ctrl->is_Region() &&
iter->_worklist.member(ctrl)) {
// We weren't able to find any opportunities but the region this
// lock is control dependent on hasn't been processed yet so put
// this lock back on the worklist so we can check again once any
// region simplification has occurred.
iter->_worklist.push(this);
}
}
}
return result;
}
//=============================================================================
bool LockNode::is_nested_lock_region() {
BoxLockNode* box = box_node()->as_BoxLock();
int stk_slot = box->stack_slot();
if (stk_slot <= 0)
return false; // External lock or it is not Box (Phi node).
// Ignore complex cases: merged locks or multiple locks.
Node* obj = obj_node();
LockNode* unique_lock = NULL;
if (!box->is_simple_lock_region(&unique_lock, obj) ||
(unique_lock != this)) {
return false;
}
// Look for external lock for the same object.
SafePointNode* sfn = this->as_SafePoint();
JVMState* youngest_jvms = sfn->jvms();
int max_depth = youngest_jvms->depth();
for (int depth = 1; depth <= max_depth; depth++) {
JVMState* jvms = youngest_jvms->of_depth(depth);
int num_mon = jvms->nof_monitors();
// Loop over monitors
for (int idx = 0; idx < num_mon; idx++) {
Node* obj_node = sfn->monitor_obj(jvms, idx);
BoxLockNode* box_node = sfn->monitor_box(jvms, idx)->as_BoxLock();
if ((box_node->stack_slot() < stk_slot) && obj_node->eqv_uncast(obj)) {
return true;
}
}
}
return false;
}
//=============================================================================
uint UnlockNode::size_of() const { return sizeof(*this); }
//=============================================================================
Node *UnlockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
// perform any generic optimizations first (returns 'this' or NULL)
Node *result = SafePointNode::Ideal(phase, can_reshape);
if (result != NULL) return result;
// Don't bother trying to transform a dead node
if (in(0) && in(0)->is_top()) return NULL;
// Now see if we can optimize away this unlock. We don't actually
// remove the unlocking here, we simply set the _eliminate flag which
// prevents macro expansion from expanding the unlock. Since we don't
// modify the graph, the value returned from this function is the
// one computed above.
// Escape state is defined after Parse phase.
if (can_reshape && EliminateLocks && !is_non_esc_obj()) {
//
// If we are unlocking an unescaped object, the lock/unlock is unnecessary.
//
ConnectionGraph *cgr = phase->C->congraph();
if (cgr != NULL && cgr->not_global_escape(obj_node())) {
assert(!is_eliminated() || is_coarsened(), "sanity");
// The lock could be marked eliminated by lock coarsening
// code during first IGVN before EA. Replace coarsened flag
// to eliminate all associated locks/unlocks.
this->set_non_esc_obj();
}
}
return result;
}
| Java |
<?php namespace Indikator\Backend\ReportWidgets;
use Backend\Classes\ReportWidgetBase;
use Exception;
use DB;
class Logs extends ReportWidgetBase
{
public function render()
{
try {
$this->loadData();
}
catch (Exception $ex) {
$this->vars['error'] = $ex->getMessage();
}
return $this->makePartial('widget');
}
public function defineProperties()
{
return [
'title' => [
'title' => 'backend::lang.dashboard.widget_title_label',
'default' => 'indikator.backend::lang.widgets.logs.label',
'type' => 'string',
'validationPattern' => '^.+$',
'validationMessage' => 'backend::lang.dashboard.widget_title_error'
],
'access' => [
'title' => 'indikator.backend::lang.properties.access',
'default' => true,
'type' => 'checkbox'
],
'event' => [
'title' => 'indikator.backend::lang.properties.event',
'default' => true,
'type' => 'checkbox'
],
'request' => [
'title' => 'indikator.backend::lang.properties.request',
'default' => true,
'type' => 'checkbox'
],
'total' => [
'title' => 'indikator.backend::lang.properties.total',
'default' => true,
'type' => 'checkbox'
]
];
}
protected function loadData()
{
$this->vars['access'] = DB::table('backend_access_log')->count();
$this->vars['event'] = DB::table('system_event_logs')->count();
$this->vars['request'] = DB::table('system_request_logs')->count();
}
}
| Java |
--[[
BY-@Sadik_alknani10
BY_CH : @KINGTELE1
]]
local function get_variables_hash(msg)
if msg.to.type == 'chat' or msg.to.type == 'channel' then
return 'chat:bot:variables'
end
end
local function get_value(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
local function list_chats(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = '👇الردود هي : ️\n\n'
for i=1, #names do
text = text..'® '..names[i]..'\n'
end
return text
else
return
end
end
local function save_value(msg, name, value)
if (not name or not value) then
return "Usage: !set var_name value"
end
local hash = nil
if msg.to.type == 'chat' or msg.to.type == 'channel' then
hash = 'chat:bot:variables'
end
if hash then
redis:hset(hash, name, value)
return '('..name..')\n تـ﷽ـم اضُافَُه ُهذَا الُرَدِ🌝 '
end
end
local function del_value(msg, name)
if not name then
return
end
local hash = nil
if msg.to.type == 'chat' or msg.to.type == 'channel' then
hash = 'chat:bot:variables'
end
if hash then
redis:hdel(hash, name)
return '('..name..')\n تْـ﷽ـم حُذَفَ ُهذَا الُرَدِ🌝 '
end
end
local function delallchats(msg)
local hash = 'chat:bot:variables'
if hash then
local names = redis:hkeys(hash)
for i=1, #names do
redis:hdel(hash,names[i])
end
return "saved!"
else
return
end
end
local function run(msg, matches)
if is_sudo(msg) then
local name = matches[3]
local value = matches[4]
if matches[2] == 'حذف الجميع' then
local output = delallchats(msg)
return output
end
if matches[2] == 'اضف' then
local name1 = user_print_name(msg.from)
savelog(msg.to.id, name1.." ["..msg.from.id.."] saved ["..name.."] as > "..value )
local text = save_value(msg, name, value)
return text
elseif matches[2] == 'حذف' then
local text = del_value(msg,name)
return text
end
end
if matches[1] == 'الردود' then
local output = list_chats(msg)
return output
else
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /get ".. matches[1])-- save to logs
local text = get_value(msg, matches[1])
return reply_msg(msg.id,text,ok_cb,false)
end
end
return {
patterns = {
"^(الردود)$",
"^(رد) (اضف) ([^%s]+) (.+)$",
"^(رد) (حذف الجميع)$",
"^(رد) (حذف) (.*)$",
"^(.+)$",
},
run = run
}
-- @KINGTELE1
| Java |
/*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.rm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class rep_movsb_a32 extends Executable
{
final int segIndex;
public rep_movsb_a32(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
segIndex = Prefices.getSegment(prefices, Processor.DS_INDEX);
}
public Branch execute(Processor cpu)
{
Segment seg = cpu.segs[segIndex];
StaticOpcodes.rep_movsb_a32(cpu, seg);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | Java |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim:expandtab:shiftwidth=2:tabstop=2: */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Gtk2XtBin Widget Implementation.
*
* The Initial Developer of the Original Code is
* Sun Microsystems, Inc.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* The GtkXtBin widget allows for Xt toolkit code to be used
* inside a GTK application.
*/
#include "xembed.h"
#include "gtk2xtbin.h"
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <glib.h>
#include <assert.h>
#include <sys/time.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* Xlib/Xt stuff */
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Shell.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
/* uncomment this if you want debugging information about widget
creation and destruction */
#undef DEBUG_XTBIN
#define XTBIN_MAX_EVENTS 30
static void gtk_xtbin_class_init (GtkXtBinClass *klass);
static void gtk_xtbin_init (GtkXtBin *xtbin);
static void gtk_xtbin_realize (GtkWidget *widget);
static void gtk_xtbin_unrealize (GtkWidget *widget);
static void gtk_xtbin_destroy (GtkObject *object);
static void gtk_xtbin_shutdown (GtkObject *object);
/* Xt aware XEmbed */
static void xt_client_init (XtClient * xtclient,
Visual *xtvisual,
Colormap xtcolormap,
int xtdepth);
static void xt_client_create (XtClient * xtclient,
Window embeder,
int height,
int width );
static void xt_client_unrealize (XtClient* xtclient);
static void xt_client_destroy (XtClient* xtclient);
static void xt_client_set_info (Widget xtplug,
unsigned long flags);
static void xt_client_event_handler (Widget w,
XtPointer client_data,
XEvent *event);
static void xt_client_handle_xembed_message (Widget w,
XtPointer client_data,
XEvent *event);
static void xt_client_focus_listener (Widget w,
XtPointer user_data,
XEvent *event);
static void xt_add_focus_listener( Widget w, XtPointer user_data );
static void xt_add_focus_listener_tree ( Widget treeroot, XtPointer user_data);
static void xt_remove_focus_listener(Widget w, XtPointer user_data);
static void send_xembed_message (XtClient *xtclient,
long message,
long detail,
long data1,
long data2,
long time);
static int error_handler (Display *display,
XErrorEvent *error);
/* For error trap of XEmbed */
static void trap_errors(void);
static int untrap_error(void);
static int (*old_error_handler) (Display *, XErrorEvent *);
static int trapped_error_code = 0;
static GtkWidgetClass *parent_class = NULL;
static Display *xtdisplay = NULL;
static String *fallback = NULL;
static gboolean xt_is_initialized = FALSE;
static gint num_widgets = 0;
static GPollFD xt_event_poll_fd;
static gint xt_polling_timer_id = 0;
static guint tag = 0;
static gboolean
xt_event_prepare (GSource* source_data,
gint *timeout)
{
int mask;
GDK_THREADS_ENTER();
mask = XPending(xtdisplay);
GDK_THREADS_LEAVE();
return (gboolean)mask;
}
static gboolean
xt_event_check (GSource* source_data)
{
GDK_THREADS_ENTER ();
if (xt_event_poll_fd.revents & G_IO_IN) {
int mask;
mask = XPending(xtdisplay);
GDK_THREADS_LEAVE ();
return (gboolean)mask;
}
GDK_THREADS_LEAVE ();
return FALSE;
}
static gboolean
xt_event_dispatch (GSource* source_data,
GSourceFunc call_back,
gpointer user_data)
{
XEvent event;
XtAppContext ac;
int i = 0;
ac = XtDisplayToApplicationContext(xtdisplay);
GDK_THREADS_ENTER ();
/* Process only real X traffic here. We only look for data on the
* pipe, limit it to XTBIN_MAX_EVENTS and only call
* XtAppProcessEvent so that it will look for X events. There's no
* timer processing here since we already have a timer callback that
* does it. */
for (i=0; i < XTBIN_MAX_EVENTS && XPending(xtdisplay); i++) {
XtAppProcessEvent(ac, XtIMXEvent);
}
GDK_THREADS_LEAVE ();
return TRUE;
}
static GSourceFuncs xt_event_funcs = {
xt_event_prepare,
xt_event_check,
xt_event_dispatch,
g_free,
(GSourceFunc)NULL,
(GSourceDummyMarshal)NULL
};
static gboolean
xt_event_polling_timer_callback(gpointer user_data)
{
Display * display;
XtAppContext ac;
int eventsToProcess = 20;
display = (Display *)user_data;
ac = XtDisplayToApplicationContext(display);
/* We need to process many Xt events here. If we just process
one event we might starve one or more Xt consumers. On the other hand
this could hang the whole app if Xt events come pouring in. So process
up to 20 Xt events right now and save the rest for later. This is a hack,
but it oughta work. We *really* should have out of process plugins.
*/
while (eventsToProcess-- && XtAppPending(ac))
XtAppProcessEvent(ac, XtIMAll);
return TRUE;
}
GType
gtk_xtbin_get_type (void)
{
static GType xtbin_type = 0;
if (!xtbin_type) {
static const GTypeInfo xtbin_info =
{
sizeof (GtkXtBinClass),
NULL,
NULL,
(GClassInitFunc)gtk_xtbin_class_init,
NULL,
NULL,
sizeof (GtkXtBin),
0,
(GInstanceInitFunc)gtk_xtbin_init,
};
xtbin_type = g_type_register_static (GTK_TYPE_SOCKET,
"GtkXtBin",
&xtbin_info,
0);
}
return xtbin_type;
}
static void
gtk_xtbin_class_init (GtkXtBinClass *klass)
{
GtkWidgetClass *widget_class;
GtkObjectClass *object_class;
parent_class = g_type_class_peek_parent (klass);
widget_class = GTK_WIDGET_CLASS (klass);
widget_class->realize = gtk_xtbin_realize;
widget_class->unrealize = gtk_xtbin_unrealize;
object_class = GTK_OBJECT_CLASS (klass);
object_class->destroy = gtk_xtbin_destroy;
}
static void
gtk_xtbin_init (GtkXtBin *xtbin)
{
xtbin->xtdisplay = NULL;
xtbin->parent_window = NULL;
xtbin->xtwindow = 0;
xtbin->x = 0;
xtbin->y = 0;
}
static void
gtk_xtbin_realize (GtkWidget *widget)
{
GtkXtBin *xtbin;
GtkAllocation allocation = { 0, 0, 200, 200 };
gint x, y, w, h, d; /* geometry of window */
#ifdef DEBUG_XTBIN
printf("gtk_xtbin_realize()\n");
#endif
g_return_if_fail (GTK_IS_XTBIN (widget));
xtbin = GTK_XTBIN (widget);
/* caculate the allocation before realize */
gdk_window_get_geometry(xtbin->parent_window, &x, &y, &w, &h, &d);
allocation.width = w;
allocation.height = h;
gtk_widget_size_allocate (widget, &allocation);
#ifdef DEBUG_XTBIN
printf("initial allocation %d %d %d %d\n", x, y, w, h);
#endif
xtbin->width = widget->allocation.width;
xtbin->height = widget->allocation.height;
/* use GtkSocket's realize */
(*GTK_WIDGET_CLASS(parent_class)->realize)(widget);
/* create the Xt client widget */
xt_client_create(&(xtbin->xtclient),
gtk_socket_get_id(GTK_SOCKET(xtbin)),
xtbin->height,
xtbin->width);
xtbin->xtwindow = XtWindow(xtbin->xtclient.child_widget);
gdk_flush();
/* now that we have created the xt client, add it to the socket. */
gtk_socket_add_id(GTK_SOCKET(widget), xtbin->xtwindow);
}
GtkWidget*
gtk_xtbin_new (GdkWindow *parent_window, String * f)
{
GtkXtBin *xtbin;
gpointer user_data;
assert(parent_window != NULL);
xtbin = g_object_new (GTK_TYPE_XTBIN, NULL);
if (!xtbin)
return (GtkWidget*)NULL;
if (f)
fallback = f;
/* Initialize the Xt toolkit */
xtbin->parent_window = parent_window;
xt_client_init(&(xtbin->xtclient),
GDK_VISUAL_XVISUAL(gdk_rgb_get_visual()),
GDK_COLORMAP_XCOLORMAP(gdk_rgb_get_colormap()),
gdk_rgb_get_visual()->depth);
if (!xtbin->xtclient.xtdisplay) {
/* If XtOpenDisplay failed, we can't go any further.
* Bail out.
*/
#ifdef DEBUG_XTBIN
printf("gtk_xtbin_init: XtOpenDisplay() returned NULL.\n");
#endif
g_free (xtbin);
return (GtkWidget *)NULL;
}
/* If this is the first running widget, hook this display into the
mainloop */
if (0 == num_widgets) {
int cnumber;
/*
* hook Xt event loop into the glib event loop.
*/
/* the assumption is that gtk_init has already been called */
GSource* gs = g_source_new(&xt_event_funcs, sizeof(GSource));
if (!gs) {
return NULL;
}
g_source_set_priority(gs, GDK_PRIORITY_EVENTS);
g_source_set_can_recurse(gs, TRUE);
tag = g_source_attach(gs, (GMainContext*)NULL);
#ifdef VMS
cnumber = XConnectionNumber(xtdisplay);
#else
cnumber = ConnectionNumber(xtdisplay);
#endif
xt_event_poll_fd.fd = cnumber;
xt_event_poll_fd.events = G_IO_IN;
xt_event_poll_fd.revents = 0; /* hmm... is this correct? */
g_main_context_add_poll ((GMainContext*)NULL,
&xt_event_poll_fd,
G_PRIORITY_LOW);
/* add a timer so that we can poll and process Xt timers */
xt_polling_timer_id =
g_timeout_add(25,
(GSourceFunc)xt_event_polling_timer_callback,
xtdisplay);
}
/* Bump up our usage count */
num_widgets++;
/* Build the hierachy */
xtbin->xtdisplay = xtbin->xtclient.xtdisplay;
gtk_widget_set_parent_window(GTK_WIDGET(xtbin), parent_window);
gdk_window_get_user_data(xtbin->parent_window, &user_data);
if (user_data)
gtk_container_add(GTK_CONTAINER(user_data), GTK_WIDGET(xtbin));
return GTK_WIDGET (xtbin);
}
void
gtk_xtbin_set_position (GtkXtBin *xtbin,
gint x,
gint y)
{
xtbin->x = x;
xtbin->y = y;
if (GTK_WIDGET_REALIZED (xtbin))
gdk_window_move (GTK_WIDGET (xtbin)->window, x, y);
}
void
gtk_xtbin_resize (GtkWidget *widget,
gint width,
gint height)
{
Arg args[2];
GtkXtBin *xtbin = GTK_XTBIN (widget);
GtkAllocation allocation;
#ifdef DEBUG_XTBIN
printf("gtk_xtbin_resize %p %d %d\n", (void *)widget, width, height);
#endif
xtbin->height = height;
xtbin->width = width;
// Avoid BadValue errors in XtSetValues
if (height <= 0 || width <=0) {
height = 1;
width = 1;
}
XtSetArg(args[0], XtNheight, height);
XtSetArg(args[1], XtNwidth, width);
XtSetValues(xtbin->xtclient.top_widget, args, 2);
/* we need to send a size allocate so the socket knows about the
size changes */
allocation.x = xtbin->x;
allocation.y = xtbin->y;
allocation.width = xtbin->width;
allocation.height = xtbin->height;
gtk_widget_size_allocate(widget, &allocation);
}
static void
gtk_xtbin_unrealize (GtkWidget *object)
{
GtkXtBin *xtbin;
GtkWidget *widget;
#ifdef DEBUG_XTBIN
printf("gtk_xtbin_unrealize()\n");
#endif
/* gtk_object_destroy() will already hold a refcount on object
*/
xtbin = GTK_XTBIN(object);
widget = GTK_WIDGET(object);
GTK_WIDGET_UNSET_FLAGS (widget, GTK_VISIBLE);
if (GTK_WIDGET_REALIZED (widget)) {
xt_client_unrealize(&(xtbin->xtclient));
}
(*GTK_WIDGET_CLASS (parent_class)->unrealize)(widget);
}
static void
gtk_xtbin_destroy (GtkObject *object)
{
GtkXtBin *xtbin;
#ifdef DEBUG_XTBIN
printf("gtk_xtbin_destroy()\n");
#endif
g_return_if_fail (object != NULL);
g_return_if_fail (GTK_IS_XTBIN (object));
xtbin = GTK_XTBIN (object);
if(xtbin->xtwindow) {
/* remove the event handler */
xt_client_destroy(&(xtbin->xtclient));
xtbin->xtwindow = 0;
num_widgets--; /* reduce our usage count */
/* If this is the last running widget, remove the Xt display
connection from the mainloop */
if (0 == num_widgets) {
#ifdef DEBUG_XTBIN
printf("removing the Xt connection from the main loop\n");
#endif
g_main_context_remove_poll((GMainContext*)NULL, &xt_event_poll_fd);
g_source_remove(tag);
g_source_remove(xt_polling_timer_id);
xt_polling_timer_id = 0;
}
}
GTK_OBJECT_CLASS(parent_class)->destroy(object);
}
/*
* Following is the implementation of Xt XEmbedded for client side
*/
/* Initial Xt plugin */
static void
xt_client_init( XtClient * xtclient,
Visual *xtvisual,
Colormap xtcolormap,
int xtdepth)
{
XtAppContext app_context;
char *mArgv[1];
int mArgc = 0;
/*
* Initialize Xt stuff
*/
xtclient->top_widget = NULL;
xtclient->child_widget = NULL;
xtclient->xtdisplay = NULL;
xtclient->xtvisual = NULL;
xtclient->xtcolormap = 0;
xtclient->xtdepth = 0;
if (!xt_is_initialized) {
#ifdef DEBUG_XTBIN
printf("starting up Xt stuff\n");
#endif
XtToolkitInitialize();
app_context = XtCreateApplicationContext();
if (fallback)
XtAppSetFallbackResources(app_context, fallback);
xtdisplay = XtOpenDisplay(app_context, gdk_get_display(), NULL,
"Wrapper", NULL, 0, &mArgc, mArgv);
if (xtdisplay)
xt_is_initialized = TRUE;
}
xtclient->xtdisplay = xtdisplay;
xtclient->xtvisual = xtvisual;
xtclient->xtcolormap = xtcolormap;
xtclient->xtdepth = xtdepth;
}
/* Create the Xt client widgets
* */
static void
xt_client_create ( XtClient* xtclient ,
Window embedderid,
int height,
int width )
{
int n;
Arg args[6];
Widget child_widget;
Widget top_widget;
#ifdef DEBUG_XTBIN
printf("xt_client_create() \n");
#endif
top_widget = XtAppCreateShell("drawingArea", "Wrapper",
applicationShellWidgetClass,
xtclient->xtdisplay,
NULL, 0);
xtclient->top_widget = top_widget;
/* set size of Xt window */
n = 0;
XtSetArg(args[n], XtNheight, height);n++;
XtSetArg(args[n], XtNwidth, width);n++;
XtSetValues(top_widget, args, n);
child_widget = XtVaCreateWidget("form",
compositeWidgetClass,
top_widget, NULL);
n = 0;
XtSetArg(args[n], XtNheight, height);n++;
XtSetArg(args[n], XtNwidth, width);n++;
XtSetArg(args[n], XtNvisual, xtclient->xtvisual ); n++;
XtSetArg(args[n], XtNdepth, xtclient->xtdepth ); n++;
XtSetArg(args[n], XtNcolormap, xtclient->xtcolormap ); n++;
XtSetArg(args[n], XtNborderWidth, 0); n++;
XtSetValues(child_widget, args, n);
XSync(xtclient->xtdisplay, FALSE);
xtclient->oldwindow = top_widget->core.window;
top_widget->core.window = embedderid;
/* this little trick seems to finish initializing the widget */
#if XlibSpecificationRelease >= 6
XtRegisterDrawable(xtclient->xtdisplay,
embedderid,
top_widget);
#else
_XtRegisterWindow( embedderid,
top_widget);
#endif
XtRealizeWidget(child_widget);
/* listen to all Xt events */
XSelectInput(xtclient->xtdisplay,
XtWindow(top_widget),
0x0FFFFF);
xt_client_set_info (child_widget, 0);
XtManageChild(child_widget);
xtclient->child_widget = child_widget;
/* set the event handler */
XtAddEventHandler(child_widget,
0x0FFFFF & ~ResizeRedirectMask,
TRUE,
(XtEventHandler)xt_client_event_handler, xtclient);
XtAddEventHandler(child_widget,
SubstructureNotifyMask | ButtonReleaseMask,
TRUE,
(XtEventHandler)xt_client_focus_listener,
xtclient);
XSync(xtclient->xtdisplay, FALSE);
}
static void
xt_client_unrealize ( XtClient* xtclient )
{
#if XlibSpecificationRelease >= 6
XtUnregisterDrawable(xtclient->xtdisplay,
xtclient->top_widget->core.window);
#else
_XtUnregisterWindow(xtclient->top_widget->core.window,
xtclient->top_widget);
#endif
/* flush the queue before we returning origin top_widget->core.window
or we can get X error since the window is gone */
XSync(xtclient->xtdisplay, False);
xtclient->top_widget->core.window = xtclient->oldwindow;
XtUnrealizeWidget(xtclient->top_widget);
}
static void
xt_client_destroy (XtClient* xtclient)
{
if(xtclient->top_widget) {
XtRemoveEventHandler(xtclient->child_widget, 0x0FFFFF, TRUE,
(XtEventHandler)xt_client_event_handler, xtclient);
XtDestroyWidget(xtclient->top_widget);
xtclient->top_widget = NULL;
}
}
static void
xt_client_set_info (Widget xtplug, unsigned long flags)
{
unsigned long buffer[2];
Atom infoAtom = XInternAtom(XtDisplay(xtplug), "_XEMBED_INFO", False);
buffer[1] = 0; /* Protocol version */
buffer[1] = flags;
XChangeProperty (XtDisplay(xtplug), XtWindow(xtplug),
infoAtom, infoAtom, 32,
PropModeReplace,
(unsigned char *)buffer, 2);
}
static void
xt_client_handle_xembed_message(Widget w, XtPointer client_data, XEvent *event)
{
XtClient *xtplug = (XtClient*)client_data;
switch (event->xclient.data.l[1])
{
case XEMBED_EMBEDDED_NOTIFY:
break;
case XEMBED_WINDOW_ACTIVATE:
#ifdef DEBUG_XTBIN
printf("Xt client get XEMBED_WINDOW_ACTIVATE\n");
#endif
break;
case XEMBED_WINDOW_DEACTIVATE:
#ifdef DEBUG_XTBIN
printf("Xt client get XEMBED_WINDOW_DEACTIVATE\n");
#endif
break;
case XEMBED_MODALITY_ON:
#ifdef DEBUG_XTBIN
printf("Xt client get XEMBED_MODALITY_ON\n");
#endif
break;
case XEMBED_MODALITY_OFF:
#ifdef DEBUG_XTBIN
printf("Xt client get XEMBED_MODALITY_OFF\n");
#endif
break;
case XEMBED_FOCUS_IN:
case XEMBED_FOCUS_OUT:
{
XEvent xevent;
memset(&xevent, 0, sizeof(xevent));
if(event->xclient.data.l[1] == XEMBED_FOCUS_IN) {
#ifdef DEBUG_XTBIN
printf("XTEMBED got focus in\n");
#endif
xevent.xfocus.type = FocusIn;
}
else {
#ifdef DEBUG_XTBIN
printf("XTEMBED got focus out\n");
#endif
xevent.xfocus.type = FocusOut;
}
xevent.xfocus.window = XtWindow(xtplug->child_widget);
xevent.xfocus.display = XtDisplay(xtplug->child_widget);
XSendEvent(XtDisplay(xtplug->child_widget),
xevent.xfocus.window,
False, NoEventMask,
&xevent );
XSync( XtDisplay(xtplug->child_widget), False);
}
break;
default:
break;
} /* End of XEmbed Message */
}
static void
xt_client_event_handler( Widget w, XtPointer client_data, XEvent *event)
{
XtClient *xtplug = (XtClient*)client_data;
switch(event->type)
{
case ClientMessage:
/* Handle xembed message */
if (event->xclient.message_type==
XInternAtom (XtDisplay(xtplug->child_widget),
"_XEMBED", False)) {
xt_client_handle_xembed_message(w, client_data, event);
}
break;
case ReparentNotify:
break;
case MappingNotify:
xt_client_set_info (w, XEMBED_MAPPED);
break;
case UnmapNotify:
xt_client_set_info (w, 0);
break;
case FocusIn:
send_xembed_message ( xtplug,
XEMBED_REQUEST_FOCUS, 0, 0, 0, 0);
break;
case FocusOut:
break;
case KeyPress:
#ifdef DEBUG_XTBIN
printf("Key Press Got!\n");
#endif
break;
default:
break;
} /* End of switch(event->type) */
}
static void
send_xembed_message (XtClient *xtclient,
long message,
long detail,
long data1,
long data2,
long time)
{
XEvent xevent;
Window w=XtWindow(xtclient->top_widget);
Display* dpy=xtclient->xtdisplay;
int errorcode;
memset(&xevent,0,sizeof(xevent));
xevent.xclient.window = w;
xevent.xclient.type = ClientMessage;
xevent.xclient.message_type = XInternAtom(dpy,"_XEMBED",False);
xevent.xclient.format = 32;
xevent.xclient.data.l[0] = time;
xevent.xclient.data.l[1] = message;
xevent.xclient.data.l[2] = detail;
xevent.xclient.data.l[3] = data1;
xevent.xclient.data.l[4] = data2;
trap_errors ();
XSendEvent (dpy, w, False, NoEventMask, &xevent);
XSync (dpy,False);
if((errorcode = untrap_error())) {
#ifdef DEBUG_XTBIN
printf("send_xembed_message error(%d)!!!\n",errorcode);
#endif
}
}
static int
error_handler(Display *display, XErrorEvent *error)
{
trapped_error_code = error->error_code;
return 0;
}
static void
trap_errors(void)
{
trapped_error_code =0;
old_error_handler = XSetErrorHandler(error_handler);
}
static int
untrap_error(void)
{
XSetErrorHandler(old_error_handler);
if(trapped_error_code) {
#ifdef DEBUG_XTBIN
printf("Get X Window Error = %d\n", trapped_error_code);
#endif
}
return trapped_error_code;
}
static void
xt_client_focus_listener( Widget w, XtPointer user_data, XEvent *event)
{
Display *dpy = XtDisplay(w);
XtClient *xtclient = user_data;
Window win = XtWindow(w);
switch(event->type)
{
case CreateNotify:
if(event->xcreatewindow.parent == win) {
Widget child=XtWindowToWidget( dpy, event->xcreatewindow.window);
if (child)
xt_add_focus_listener_tree(child, user_data);
}
break;
case DestroyNotify:
xt_remove_focus_listener( w, user_data);
break;
case ReparentNotify:
if(event->xreparent.parent == win) {
/* I am the new parent */
Widget child=XtWindowToWidget(dpy, event->xreparent.window);
if (child)
xt_add_focus_listener_tree( child, user_data);
}
else if(event->xreparent.window == win) {
/* I am the new child */
}
else {
/* I am the old parent */
}
break;
case ButtonRelease:
#if 0
XSetInputFocus(dpy, XtWindow(xtclient->child_widget), RevertToParent, event->xbutton.time);
#endif
send_xembed_message ( xtclient,
XEMBED_REQUEST_FOCUS, 0, 0, 0, 0);
break;
default:
break;
} /* End of switch(event->type) */
}
static void
xt_add_focus_listener( Widget w, XtPointer user_data)
{
XWindowAttributes attr;
long eventmask;
XtClient *xtclient = user_data;
int errorcode;
trap_errors ();
XGetWindowAttributes(XtDisplay(w), XtWindow(w), &attr);
eventmask = attr.your_event_mask | SubstructureNotifyMask | ButtonReleaseMask;
XSelectInput(XtDisplay(w),
XtWindow(w),
eventmask);
XtAddEventHandler(w,
SubstructureNotifyMask | ButtonReleaseMask,
TRUE,
(XtEventHandler)xt_client_focus_listener,
xtclient);
untrap_error();
}
static void
xt_remove_focus_listener(Widget w, XtPointer user_data)
{
int errorcode;
trap_errors ();
XtRemoveEventHandler(w, SubstructureNotifyMask | ButtonReleaseMask, TRUE,
(XtEventHandler)xt_client_focus_listener, user_data);
untrap_error();
}
static void
xt_add_focus_listener_tree ( Widget treeroot, XtPointer user_data)
{
Window win = XtWindow(treeroot);
Window *children;
Window root, parent;
Display *dpy = XtDisplay(treeroot);
unsigned int i, nchildren;
/* ensure we don't add more than once */
xt_remove_focus_listener( treeroot, user_data);
xt_add_focus_listener( treeroot, user_data);
trap_errors();
if(!XQueryTree(dpy, win, &root, &parent, &children, &nchildren)) {
untrap_error();
return;
}
if(untrap_error())
return;
for(i=0; i<nchildren; ++i) {
Widget child = XtWindowToWidget(dpy, children[i]);
if (child)
xt_add_focus_listener_tree( child, user_data);
}
XFree((void*)children);
return;
}
| Java |
obj-$(CONFIG_LCD_NULL) += lcd_null.o
obj-$(CONFIG_LCD_RK2928) += lcd_rk2928.o
obj-$(CONFIG_LCD_RK3168_FAC) += lcd_rk3168_fac.o
obj-$(CONFIG_LCD_TD043MGEA1) += lcd_td043mgea1.o
obj-$(CONFIG_LCD_HSD070IDW1) += lcd_hsd800x480.o
obj-$(CONFIG_LCD_HL070VM4AU) += lcd_hl070vm4.o
obj-$(CONFIG_LCD_BYD8688FTGF) += lcd_byd1024x600.o
obj-$(CONFIG_LCD_LG_LP097X02)+= lcd_LG_LP097X02.o
obj-$(CONFIG_LCD_TJ048NC01CA) += lcd_tj048nc01ca.o
obj-$(CONFIG_LCD_A060SE02) += lcd_a060se02.o
obj-$(CONFIG_LCD_S1D13521) += lcd_s1d13521.o
obj-$(CONFIG_LCD_NT35582) += lcd_nt35582.o
obj-$(CONFIG_LCD_NT35580) += lcd_nt35580.o
obj-$(CONFIG_LCD_IPS1P5680_V1_E) += lcd_ips1p5680_v1_e.o
obj-$(CONFIG_LCD_RGB_TFT480800_25_E) += lcd_rgb_tft480800_25_e.o
obj-$(CONFIG_LCD_MCU_TFT480800_25_E) += lcd_mcu_tft480800_25_e.o
obj-$(CONFIG_LCD_LS035Y8DX02A) += lcd_ls035y8dx02a.o
obj-$(CONFIG_LCD_LS035Y8DX04A) += lcd_ls035y8dx04a.o
obj-$(CONFIG_LCD_CPTCLAA038LA31XE) += lcd_CPTclaa038la31xe.o
obj-$(CONFIG_LCD_HX8357) += lcd_hx8357.o
obj-$(CONFIG_LCD_HSD100PXN) += lcd_hsd100pxn.o
obj-$(CONFIG_LCD_HDMI_1366x768) += lcd_hdmi_1366x768.o
obj-$(CONFIG_LCD_HDMI_1280x800) += lcd_hdmi_1280x800.o
obj-$(CONFIG_LCD_HDMI_1024x768) += lcd_hdmi_1024x768.o
obj-$(CONFIG_LCD_HDMI_800x480) += lcd_hdmi_800x480.o
obj-$(CONFIG_LCD_B101AW06) += lcd_B101AW06.o
obj-$(CONFIG_LCD_NT35510) += lcd_nt35510.o
obj-$(CONFIG_LCD_ILI9803_CPT4_3) += lcd_ili9803_cpt4_3.o
obj-$(CONFIG_LCD_RGB_TFT480800_25_E) += lcd_rgb_tft480800_25_e.o
obj-$(CONFIG_LCD_LS035Y8DX02A) += lcd_ls035y8dx02a.o
obj-$(CONFIG_LCD_IPS1P5680_V1_E) += lcd_ips1p5680_v1_e.o
obj-$(CONFIG_LCD_MCU_TFT480800_25_E) += lcd_mcu_tft480800_25_e.o
obj-$(CONFIG_LCD_AT070TNA2) += lcd_AT070TNA2.o
obj-$(CONFIG_LCD_TX23D88VM) += lcd_tx23d88vm.o
obj-$(CONFIG_LCD_AT070TN93) += lcd_at070tn93.o
obj-$(CONFIG_LCD_A050VL01) += lcd_A050VL01.o
obj-$(CONFIG_LCD_B101EW05) += lcd_b101ew05.o
obj-$(CONFIG_LCD_RK3168M_B101EW05) += lcd_hdmi_rk3168m_b101ew05.o
obj-$(CONFIG_LCD_HJ050NA_06A) += lcd_hj050na_06a.o
obj-$(CONFIG_LCD_HSD100PXN_FOR_TDW851) += lcd_hsd100pxn_for_tdw851.o
obj-$(CONFIG_LCD_HV070WSA100) += lcd_hv070wsa.o
obj-$(CONFIG_LCD_COMMON) += lcd_common.o
obj-$(CONFIG_LCD_RK2928_A720) += lcd_YQ70CPT9160.o
obj-$(CONFIG_LCD_RK3168_AUO_A080SN03) += lcd_AUO_A080SN03.o
obj-$(CONFIG_LCD_RK2926_V86) += lcd_YQ70CPT9160_v86.o
obj-$(CONFIG_LCD_RK3168_86V) += lcd_YQ70CPT9160_rk3168_86v.o
obj-$(CONFIG_LCD_HSD07PFW1) += lcd_hdmi_1024x600.o
obj-$(CONFIG_LCD_HJ080NA) += lcd_hj080na.o
obj-$(CONFIG_LCD_HJ101NA) += lcd_hj101na.o
obj-$(CONFIG_LCD_AUTO) += lcd_auto.o
obj-$(CONFIG_LCD_I30_800X480) += lcd_I30_800x480.o
obj-$(CONFIG_LCD_TL5001_MIPI) += lcd_tl5001_mipi.o
obj-$(CONFIG_LCD_LP097QX1) += lcd_LP097QX1.o
obj-$(CONFIG_LCD_DS1006H) += lcd_ds1006h.o
obj-$(CONFIG_LCD_B101UANO_1920x1200) += lcd_b101uano_1920x1200.o
obj-$(CONFIG_LCD_E242868_1024X600) += lcd_E242868_rk3168_86v.o
obj-$(CONFIG_LCD_E242868_RK616_1024X600) += lcd_E242868_rk3168_rk616_86v.o
obj-$(CONFIG_LCD_WY_800X480) += lcd_wy_800x480.o
obj-$(CONFIG_LCD_HH070D_LVDS) += lcd_hh070d_lvds.o
obj-$(CONFIG_LCD_RK3028_86V) += lcd_E242868_rk3028_86v.o
obj-$(CONFIG_LCD_MQ0801D) += lcd_mq0801d.o
obj-$(CONFIG_LCD_LD089WU1_MIPI_M8HD) += lcd_LD089WU1_mipi_m8hd.o
obj-$(CONFIG_LCD_LD089WU1_MIPI_M7PRO) += lcd_LD089WU1_mipi_m7pro.o
obj-$(CONFIG_LCD_PIPO_MIPI_M7PRO) += lcd_PIPO_m7pro_mipi.o
obj-$(CONFIG_LCD_CLAA101FP01_MIPI_M9PRO) += lcd_claa101fp01_mipi_m9pro.o
obj-$(CONFIG_LCD_PIPO_MIPI_M9PRO) += lcd_PIPO_m9pro_mipi.o
obj-$(CONFIG_LCD_PIPO_MIPI_U8) += lcd_PIPO_U8_mipi.o
obj-$(CONFIG_LCD_D33_MIPI_U8) += lcd_D33_U8.o
obj-$(CONFIG_LCD_B080XAN02_MIPI) += lcd_B080XAN02_mipi.o
quiet_cmd_gen = GEN $@
cmd_gen = cmp -s $< $@ || cp $< $@
lcd-obj := $(filter lcd_%.o,$(obj-y))
lcd-cfile := $(patsubst %.o,%.c,$(lcd-obj))
lcd-cpath := $(src)/$(lcd-cfile)
obj-y := $(filter-out $(lcd-obj),$(obj-y))
$(obj)/lcd.h: $(lcd-cpath) FORCE
$(call if_changed,gen)
$(obj)/rk_screen.o: $(obj)/lcd.h
obj-y += rk_screen.o
clean-files := lcd.h
| Java |
#! /usr/local/bin/ruby -Kn
# usage: exyacc.rb [yaccfiles]
# this is coverted from exyacc.pl in the camel book
ARGF.each(nil) do |source|
sbeg = source.index("\n%%") + 1
send = source.rindex("\n%%") + 1
grammar = source[sbeg, send-sbeg]
grammar.sub!(/.*\n/, "")
grammar.gsub!(/'\{'/, "'\001'")
grammar.gsub!(/'\}'/, "'\002'")
grammar.gsub!(%r{\*/}, "\003\003")
grammar.gsub!(%r{/\*[^\003]*\003\003}, '')
while grammar.gsub!(/\{[^{}]*\}/, ''); end
grammar.gsub!(/'\001'/, "'{'")
grammar.gsub!(/'\002'/, "'}'")
while grammar.gsub!(/^[ \t]*\n(\s)/, '\1'); end
grammar.gsub!(/([:|])[ \t\n]+(\w)/, '\1 \2')
print grammar
end
| Java |
#header .top-header .header-navigation ul li.menu-item-has-children .sub-menu .sub-menu{width:250px;padding-top:0;border-left:1px solid #eee;top:0;left:250px} | Java |
/**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*
*
* Credits goes to all Open Source Core Developer Groups listed below
* Please do not change here something, ragarding the developer credits, except the "developed by XXXX".
* Even if you edit a lot of files in this source, you still have no rights to call it as "your Core".
* Everybody knows that this Emulator Core was developed by Aion Lightning
* @-Aion-Unique-
* @-Aion-Lightning
* @Aion-Engine
* @Aion-Extreme
* @Aion-NextGen
* @Aion-Core Dev.
*/
package quest.beluslan;
import com.aionemu.gameserver.model.gameobjects.Item;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.questEngine.handlers.HandlerResult;
import com.aionemu.gameserver.questEngine.handlers.QuestHandler;
import com.aionemu.gameserver.model.DialogAction;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
import com.aionemu.gameserver.services.QuestService;
import com.aionemu.gameserver.world.zone.ZoneName;
/**
* @author Ritsu
*
*/
public class _2533BeritrasCurse extends QuestHandler {
private final static int questId = 2533;
public _2533BeritrasCurse() {
super(questId);
}
@Override
public void register() {
qe.registerQuestNpc(204801).addOnQuestStart(questId); //Gigrite
qe.registerQuestNpc(204801).addOnTalkEvent(questId);
qe.registerQuestItem(182204425, questId);//Empty Durable Potion Bottle
qe.registerOnQuestTimerEnd(questId);
}
@Override
public HandlerResult onItemUseEvent(final QuestEnv env, Item item) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs != null && qs.getStatus() == QuestStatus.START) {
if (player.isInsideZone(ZoneName.get("BERITRAS_WEAPON_220040000"))) {
QuestService.questTimerStart(env, 300);
return HandlerResult.fromBoolean(useQuestItem(env, item, 0, 1, false, 182204426, 1, 0));
}
}
return HandlerResult.SUCCESS; // ??
}
@Override
public boolean onDialogEvent(QuestEnv env) {
final Player player = env.getPlayer();
int targetId = 0;
if (env.getVisibleObject() instanceof Npc) {
targetId = ((Npc) env.getVisibleObject()).getNpcId();
}
final QuestState qs = player.getQuestStateList().getQuestState(questId);
DialogAction dialog = env.getDialog();
if (qs == null || qs.getStatus() == QuestStatus.NONE) {
if (targetId == 204801) {
if (dialog == DialogAction.QUEST_SELECT) {
return sendQuestDialog(env, 4762);
} else if (dialog == DialogAction.QUEST_ACCEPT_1) {
if (!giveQuestItem(env, 182204425, 1)) {
return true;
}
return sendQuestStartDialog(env);
} else {
return sendQuestStartDialog(env);
}
}
} else if (qs.getStatus() == QuestStatus.START) {
int var = qs.getQuestVarById(0);
if (targetId == 204801) {
switch (dialog) {
case QUEST_SELECT:
if (var == 1) {
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
return sendQuestDialog(env, 1352);
}
case SELECT_QUEST_REWARD: {
QuestService.questTimerEnd(env);
return sendQuestDialog(env, 5);
}
}
}
} else if (qs.getStatus() == QuestStatus.REWARD) {
if (targetId == 204801) {
return sendQuestEndDialog(env);
}
}
return false;
}
@Override
public boolean onQuestTimerEndEvent(QuestEnv env) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs != null && qs.getStatus() == QuestStatus.START) {
removeQuestItem(env, 182204426, 1);
QuestService.abandonQuest(player, questId);
player.getController().updateNearbyQuests();
return true;
}
return false;
}
}
| Java |
/* Separate lexical analyzer for GNU C++.
Copyright (C) 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
1999, 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2010
Free Software Foundation, Inc.
Hacked by Michael Tiemann ([email protected])
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
/* This file is the lexical analyzer for GNU C++. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "input.h"
#include "tree.h"
#include "cp-tree.h"
#include "cpplib.h"
#include "flags.h"
#include "c-family/c-pragma.h"
#include "c-family/c-objc.h"
#include "tm_p.h"
#include "timevar.h"
static int interface_strcmp (const char *);
static void init_cp_pragma (void);
static tree parse_strconst_pragma (const char *, int);
static void handle_pragma_vtable (cpp_reader *);
static void handle_pragma_unit (cpp_reader *);
static void handle_pragma_interface (cpp_reader *);
static void handle_pragma_implementation (cpp_reader *);
static void handle_pragma_java_exceptions (cpp_reader *);
static void init_operators (void);
static void copy_lang_type (tree);
/* A constraint that can be tested at compile time. */
#define CONSTRAINT(name, expr) extern int constraint_##name [(expr) ? 1 : -1]
/* Functions and data structures for #pragma interface.
`#pragma implementation' means that the main file being compiled
is considered to implement (provide) the classes that appear in
its main body. I.e., if this is file "foo.cc", and class `bar'
is defined in "foo.cc", then we say that "foo.cc implements bar".
All main input files "implement" themselves automagically.
`#pragma interface' means that unless this file (of the form "foo.h"
is not presently being included by file "foo.cc", the
CLASSTYPE_INTERFACE_ONLY bit gets set. The effect is that none
of the vtables nor any of the inline functions defined in foo.h
will ever be output.
There are cases when we want to link files such as "defs.h" and
"main.cc". In this case, we give "defs.h" a `#pragma interface',
and "main.cc" has `#pragma implementation "defs.h"'. */
struct impl_files
{
const char *filename;
struct impl_files *next;
};
static struct impl_files *impl_file_chain;
/* True if we saw "#pragma GCC java_exceptions". */
bool pragma_java_exceptions;
void
cxx_finish (void)
{
c_common_finish ();
}
/* A mapping from tree codes to operator name information. */
operator_name_info_t operator_name_info[(int) MAX_TREE_CODES];
/* Similar, but for assignment operators. */
operator_name_info_t assignment_operator_name_info[(int) MAX_TREE_CODES];
/* Initialize data structures that keep track of operator names. */
#define DEF_OPERATOR(NAME, C, M, AR, AP) \
CONSTRAINT (C, sizeof "operator " + sizeof NAME <= 256);
#include "operators.def"
#undef DEF_OPERATOR
static void
init_operators (void)
{
tree identifier;
char buffer[256];
struct operator_name_info_t *oni;
#define DEF_OPERATOR(NAME, CODE, MANGLING, ARITY, ASSN_P) \
sprintf (buffer, ISALPHA (NAME[0]) ? "operator %s" : "operator%s", NAME); \
identifier = get_identifier (buffer); \
IDENTIFIER_OPNAME_P (identifier) = 1; \
\
oni = (ASSN_P \
? &assignment_operator_name_info[(int) CODE] \
: &operator_name_info[(int) CODE]); \
oni->identifier = identifier; \
oni->name = NAME; \
oni->mangled_name = MANGLING; \
oni->arity = ARITY;
#include "operators.def"
#undef DEF_OPERATOR
operator_name_info[(int) ERROR_MARK].identifier
= get_identifier ("<invalid operator>");
/* Handle some special cases. These operators are not defined in
the language, but can be produced internally. We may need them
for error-reporting. (Eventually, we should ensure that this
does not happen. Error messages involving these operators will
be confusing to users.) */
operator_name_info [(int) INIT_EXPR].name
= operator_name_info [(int) MODIFY_EXPR].name;
operator_name_info [(int) EXACT_DIV_EXPR].name = "(ceiling /)";
operator_name_info [(int) CEIL_DIV_EXPR].name = "(ceiling /)";
operator_name_info [(int) FLOOR_DIV_EXPR].name = "(floor /)";
operator_name_info [(int) ROUND_DIV_EXPR].name = "(round /)";
operator_name_info [(int) CEIL_MOD_EXPR].name = "(ceiling %)";
operator_name_info [(int) FLOOR_MOD_EXPR].name = "(floor %)";
operator_name_info [(int) ROUND_MOD_EXPR].name = "(round %)";
operator_name_info [(int) ABS_EXPR].name = "abs";
operator_name_info [(int) TRUTH_AND_EXPR].name = "strict &&";
operator_name_info [(int) TRUTH_OR_EXPR].name = "strict ||";
operator_name_info [(int) RANGE_EXPR].name = "...";
operator_name_info [(int) UNARY_PLUS_EXPR].name = "+";
assignment_operator_name_info [(int) EXACT_DIV_EXPR].name
= "(exact /=)";
assignment_operator_name_info [(int) CEIL_DIV_EXPR].name
= "(ceiling /=)";
assignment_operator_name_info [(int) FLOOR_DIV_EXPR].name
= "(floor /=)";
assignment_operator_name_info [(int) ROUND_DIV_EXPR].name
= "(round /=)";
assignment_operator_name_info [(int) CEIL_MOD_EXPR].name
= "(ceiling %=)";
assignment_operator_name_info [(int) FLOOR_MOD_EXPR].name
= "(floor %=)";
assignment_operator_name_info [(int) ROUND_MOD_EXPR].name
= "(round %=)";
}
/* Initialize the reserved words. */
void
init_reswords (void)
{
unsigned int i;
tree id;
int mask = 0;
if (cxx_dialect < cxx0x)
mask |= D_CXX0X;
if (flag_no_asm)
mask |= D_ASM | D_EXT;
if (flag_no_gnu_keywords)
mask |= D_EXT;
/* The Objective-C keywords are all context-dependent. */
mask |= D_OBJC;
ridpointers = ggc_alloc_cleared_vec_tree ((int) RID_MAX);
for (i = 0; i < num_c_common_reswords; i++)
{
if (c_common_reswords[i].disable & D_CONLY)
continue;
id = get_identifier (c_common_reswords[i].word);
C_SET_RID_CODE (id, c_common_reswords[i].rid);
ridpointers [(int) c_common_reswords[i].rid] = id;
if (! (c_common_reswords[i].disable & mask))
C_IS_RESERVED_WORD (id) = 1;
}
}
static void
init_cp_pragma (void)
{
c_register_pragma (0, "vtable", handle_pragma_vtable);
c_register_pragma (0, "unit", handle_pragma_unit);
c_register_pragma (0, "interface", handle_pragma_interface);
c_register_pragma (0, "implementation", handle_pragma_implementation);
c_register_pragma ("GCC", "interface", handle_pragma_interface);
c_register_pragma ("GCC", "implementation", handle_pragma_implementation);
c_register_pragma ("GCC", "java_exceptions", handle_pragma_java_exceptions);
}
/* TRUE if a code represents a statement. */
bool statement_code_p[MAX_TREE_CODES];
/* Initialize the C++ front end. This function is very sensitive to
the exact order that things are done here. It would be nice if the
initialization done by this routine were moved to its subroutines,
and the ordering dependencies clarified and reduced. */
bool
cxx_init (void)
{
location_t saved_loc;
unsigned int i;
static const enum tree_code stmt_codes[] = {
CTOR_INITIALIZER, TRY_BLOCK, HANDLER,
EH_SPEC_BLOCK, USING_STMT, TAG_DEFN,
IF_STMT, CLEANUP_STMT, FOR_STMT,
RANGE_FOR_STMT, WHILE_STMT, DO_STMT,
BREAK_STMT, CONTINUE_STMT, SWITCH_STMT,
EXPR_STMT
};
memset (&statement_code_p, 0, sizeof (statement_code_p));
for (i = 0; i < ARRAY_SIZE (stmt_codes); i++)
statement_code_p[stmt_codes[i]] = true;
saved_loc = input_location;
input_location = BUILTINS_LOCATION;
init_reswords ();
init_tree ();
init_cp_semantics ();
init_operators ();
init_method ();
init_error ();
current_function_decl = NULL;
class_type_node = ridpointers[(int) RID_CLASS];
cxx_init_decl_processing ();
if (c_common_init () == false)
{
input_location = saved_loc;
return false;
}
init_cp_pragma ();
init_repo ();
input_location = saved_loc;
return true;
}
/* Return nonzero if S is not considered part of an
INTERFACE/IMPLEMENTATION pair. Otherwise, return 0. */
static int
interface_strcmp (const char* s)
{
/* Set the interface/implementation bits for this scope. */
struct impl_files *ifiles;
const char *s1;
for (ifiles = impl_file_chain; ifiles; ifiles = ifiles->next)
{
const char *t1 = ifiles->filename;
s1 = s;
if (*s1 == 0 || filename_ncmp (s1, t1, 1) != 0)
continue;
while (*s1 != 0 && filename_ncmp (s1, t1, 1) == 0)
s1++, t1++;
/* A match. */
if (*s1 == *t1)
return 0;
/* Don't get faked out by xxx.yyy.cc vs xxx.zzz.cc. */
if (strchr (s1, '.') || strchr (t1, '.'))
continue;
if (*s1 == '\0' || s1[-1] != '.' || t1[-1] != '.')
continue;
/* A match. */
return 0;
}
/* No matches. */
return 1;
}
/* Parse a #pragma whose sole argument is a string constant.
If OPT is true, the argument is optional. */
static tree
parse_strconst_pragma (const char* name, int opt)
{
tree result, x;
enum cpp_ttype t;
t = pragma_lex (&result);
if (t == CPP_STRING)
{
if (pragma_lex (&x) != CPP_EOF)
warning (0, "junk at end of #pragma %s", name);
return result;
}
if (t == CPP_EOF && opt)
return NULL_TREE;
error ("invalid #pragma %s", name);
return error_mark_node;
}
static void
handle_pragma_vtable (cpp_reader* /*dfile*/)
{
parse_strconst_pragma ("vtable", 0);
sorry ("#pragma vtable no longer supported");
}
static void
handle_pragma_unit (cpp_reader* /*dfile*/)
{
/* Validate syntax, but don't do anything. */
parse_strconst_pragma ("unit", 0);
}
static void
handle_pragma_interface (cpp_reader* /*dfile*/)
{
tree fname = parse_strconst_pragma ("interface", 1);
struct c_fileinfo *finfo;
const char *filename;
if (fname == error_mark_node)
return;
else if (fname == 0)
filename = lbasename (input_filename);
else
filename = TREE_STRING_POINTER (fname);
finfo = get_fileinfo (input_filename);
if (impl_file_chain == 0)
{
/* If this is zero at this point, then we are
auto-implementing. */
if (main_input_filename == 0)
main_input_filename = input_filename;
}
finfo->interface_only = interface_strcmp (filename);
/* If MULTIPLE_SYMBOL_SPACES is set, we cannot assume that we can see
a definition in another file. */
if (!MULTIPLE_SYMBOL_SPACES || !finfo->interface_only)
finfo->interface_unknown = 0;
}
/* Note that we have seen a #pragma implementation for the key MAIN_FILENAME.
We used to only allow this at toplevel, but that restriction was buggy
in older compilers and it seems reasonable to allow it in the headers
themselves, too. It only needs to precede the matching #p interface.
We don't touch finfo->interface_only or finfo->interface_unknown;
the user must specify a matching #p interface for this to have
any effect. */
static void
handle_pragma_implementation (cpp_reader* /*dfile*/)
{
tree fname = parse_strconst_pragma ("implementation", 1);
const char *filename;
struct impl_files *ifiles = impl_file_chain;
if (fname == error_mark_node)
return;
if (fname == 0)
{
if (main_input_filename)
filename = main_input_filename;
else
filename = input_filename;
filename = lbasename (filename);
}
else
{
filename = TREE_STRING_POINTER (fname);
if (cpp_included_before (parse_in, filename, input_location))
warning (0, "#pragma implementation for %qs appears after "
"file is included", filename);
}
for (; ifiles; ifiles = ifiles->next)
{
if (! filename_cmp (ifiles->filename, filename))
break;
}
if (ifiles == 0)
{
ifiles = XNEW (struct impl_files);
ifiles->filename = xstrdup (filename);
ifiles->next = impl_file_chain;
impl_file_chain = ifiles;
}
}
/* Indicate that this file uses Java-personality exception handling. */
static void
handle_pragma_java_exceptions (cpp_reader* /*dfile*/)
{
tree x;
if (pragma_lex (&x) != CPP_EOF)
warning (0, "junk at end of #pragma GCC java_exceptions");
choose_personality_routine (lang_java);
pragma_java_exceptions = true;
}
/* Issue an error message indicating that the lookup of NAME (an
IDENTIFIER_NODE) failed. Returns the ERROR_MARK_NODE. */
tree
unqualified_name_lookup_error (tree name)
{
if (IDENTIFIER_OPNAME_P (name))
{
if (name != ansi_opname (ERROR_MARK))
error ("%qD not defined", name);
}
else
{
if (!objc_diagnose_private_ivar (name))
{
error ("%qD was not declared in this scope", name);
suggest_alternatives_for (location_of (name), name);
}
/* Prevent repeated error messages by creating a VAR_DECL with
this NAME in the innermost block scope. */
if (local_bindings_p ())
{
tree decl;
decl = build_decl (input_location,
VAR_DECL, name, error_mark_node);
DECL_CONTEXT (decl) = current_function_decl;
push_local_binding (name, decl, 0);
/* Mark the variable as used so that we do not get warnings
about it being unused later. */
TREE_USED (decl) = 1;
}
}
return error_mark_node;
}
/* Like unqualified_name_lookup_error, but NAME is an unqualified-id
used as a function. Returns an appropriate expression for
NAME. */
tree
unqualified_fn_lookup_error (tree name)
{
if (processing_template_decl)
{
/* In a template, it is invalid to write "f()" or "f(3)" if no
declaration of "f" is available. Historically, G++ and most
other compilers accepted that usage since they deferred all name
lookup until instantiation time rather than doing unqualified
name lookup at template definition time; explain to the user what
is going wrong.
Note that we have the exact wording of the following message in
the manual (trouble.texi, node "Name lookup"), so they need to
be kept in synch. */
permerror (input_location, "there are no arguments to %qD that depend on a template "
"parameter, so a declaration of %qD must be available",
name, name);
if (!flag_permissive)
{
static bool hint;
if (!hint)
{
inform (input_location, "(if you use %<-fpermissive%>, G++ will accept your "
"code, but allowing the use of an undeclared name is "
"deprecated)");
hint = true;
}
}
return name;
}
return unqualified_name_lookup_error (name);
}
/* Wrapper around build_lang_decl_loc(). Should gradually move to
build_lang_decl_loc() and then rename build_lang_decl_loc() back to
build_lang_decl(). */
tree
build_lang_decl (enum tree_code code, tree name, tree type)
{
return build_lang_decl_loc (input_location, code, name, type);
}
/* Build a decl from CODE, NAME, TYPE declared at LOC, and then add
DECL_LANG_SPECIFIC info to the result. */
tree
build_lang_decl_loc (location_t loc, enum tree_code code, tree name, tree type)
{
tree t;
t = build_decl (loc, code, name, type);
retrofit_lang_decl (t);
return t;
}
/* Add DECL_LANG_SPECIFIC info to T. Called from build_lang_decl
and pushdecl (for functions generated by the back end). */
void
retrofit_lang_decl (tree t)
{
struct lang_decl *ld;
size_t size;
int sel;
if (TREE_CODE (t) == FUNCTION_DECL)
sel = 1, size = sizeof (struct lang_decl_fn);
else if (TREE_CODE (t) == NAMESPACE_DECL)
sel = 2, size = sizeof (struct lang_decl_ns);
else if (TREE_CODE (t) == PARM_DECL)
sel = 3, size = sizeof (struct lang_decl_parm);
else if (LANG_DECL_HAS_MIN (t))
sel = 0, size = sizeof (struct lang_decl_min);
else
gcc_unreachable ();
ld = ggc_alloc_cleared_lang_decl (size);
ld->u.base.selector = sel;
DECL_LANG_SPECIFIC (t) = ld;
if (current_lang_name == lang_name_cplusplus
|| decl_linkage (t) == lk_none)
SET_DECL_LANGUAGE (t, lang_cplusplus);
else if (current_lang_name == lang_name_c)
SET_DECL_LANGUAGE (t, lang_c);
else if (current_lang_name == lang_name_java)
SET_DECL_LANGUAGE (t, lang_java);
else
gcc_unreachable ();
if (GATHER_STATISTICS)
{
tree_node_counts[(int)lang_decl] += 1;
tree_node_sizes[(int)lang_decl] += size;
}
}
void
cxx_dup_lang_specific_decl (tree node)
{
int size;
struct lang_decl *ld;
if (! DECL_LANG_SPECIFIC (node))
return;
if (TREE_CODE (node) == FUNCTION_DECL)
size = sizeof (struct lang_decl_fn);
else if (TREE_CODE (node) == NAMESPACE_DECL)
size = sizeof (struct lang_decl_ns);
else if (TREE_CODE (node) == PARM_DECL)
size = sizeof (struct lang_decl_parm);
else if (LANG_DECL_HAS_MIN (node))
size = sizeof (struct lang_decl_min);
else
gcc_unreachable ();
ld = ggc_alloc_lang_decl (size);
memcpy (ld, DECL_LANG_SPECIFIC (node), size);
DECL_LANG_SPECIFIC (node) = ld;
if (GATHER_STATISTICS)
{
tree_node_counts[(int)lang_decl] += 1;
tree_node_sizes[(int)lang_decl] += size;
}
}
/* Copy DECL, including any language-specific parts. */
tree
copy_decl (tree decl)
{
tree copy;
copy = copy_node (decl);
cxx_dup_lang_specific_decl (copy);
return copy;
}
/* Replace the shared language-specific parts of NODE with a new copy. */
static void
copy_lang_type (tree node)
{
int size;
struct lang_type *lt;
if (! TYPE_LANG_SPECIFIC (node))
return;
if (TYPE_LANG_SPECIFIC (node)->u.h.is_lang_type_class)
size = sizeof (struct lang_type);
else
size = sizeof (struct lang_type_ptrmem);
lt = ggc_alloc_lang_type (size);
memcpy (lt, TYPE_LANG_SPECIFIC (node), size);
TYPE_LANG_SPECIFIC (node) = lt;
if (GATHER_STATISTICS)
{
tree_node_counts[(int)lang_type] += 1;
tree_node_sizes[(int)lang_type] += size;
}
}
/* Copy TYPE, including any language-specific parts. */
tree
copy_type (tree type)
{
tree copy;
copy = copy_node (type);
copy_lang_type (copy);
return copy;
}
tree
cxx_make_type (enum tree_code code)
{
tree t = make_node (code);
/* Create lang_type structure. */
if (RECORD_OR_UNION_CODE_P (code)
|| code == BOUND_TEMPLATE_TEMPLATE_PARM)
{
struct lang_type *pi
= ggc_alloc_cleared_lang_type (sizeof (struct lang_type));
TYPE_LANG_SPECIFIC (t) = pi;
pi->u.c.h.is_lang_type_class = 1;
if (GATHER_STATISTICS)
{
tree_node_counts[(int)lang_type] += 1;
tree_node_sizes[(int)lang_type] += sizeof (struct lang_type);
}
}
/* Set up some flags that give proper default behavior. */
if (RECORD_OR_UNION_CODE_P (code))
{
struct c_fileinfo *finfo = get_fileinfo (input_filename);
SET_CLASSTYPE_INTERFACE_UNKNOWN_X (t, finfo->interface_unknown);
CLASSTYPE_INTERFACE_ONLY (t) = finfo->interface_only;
}
return t;
}
tree
make_class_type (enum tree_code code)
{
tree t = cxx_make_type (code);
SET_CLASS_TYPE_P (t, 1);
return t;
}
/* Returns true if we are currently in the main source file, or in a
template instantiation started from the main source file. */
bool
in_main_input_context (void)
{
struct tinst_level *tl = outermost_tinst_level();
if (tl)
return filename_cmp (main_input_filename,
LOCATION_FILE (tl->locus)) == 0;
else
return filename_cmp (main_input_filename, input_filename) == 0;
}
| Java |
<?php
/**
* Project: Securimage: A PHP class for creating and managing form CAPTCHA images<br />
* File: form.php<br /><br />
*
* This is a very simple form sending a username and password.<br />
* It demonstrates how you can integrate the image script into your code.<br />
* By creating a new instance of the class and passing the user entered code as the only parameter, you can then immediately call $obj->checkCode() which will return true if the code is correct, or false otherwise.<br />
*
* 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 any later version.<br /><br />
*
* 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.<br /><br />
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA<br /><br />
*
* Any modifications to the library should be indicated clearly in the source code
* to inform users that the changes are not a part of the original software.<br /><br />
*
* If you found this script useful, please take a quick moment to rate it.<br />
* http://www.hotscripts.com/rate/49400.html Thanks.
*
* @link http://www.phpcaptcha.org Securimage PHP CAPTCHA
* @link http://www.phpcaptcha.org/latest.zip Download Latest Version
* @link http://www.phpcaptcha.org/Securimage_Docs/ Online Documentation
* @copyright 2007 Drew Phillips
* @author drew010 <[email protected]>
* @version 1.0.3.1 (March 23, 2008)
* @package Securimage
*
*/ ?>
<html>
<head>
<title>Securimage Test Form</title>
</head>
<body>
<?php
if (empty($_POST)) { ?>
<form method="POST">
Username:<br />
<input type="text" name="username" /><br />
Password:<br />
<input type="text" name="password" /><br />
<!-- pass a session id to the query string of the script to prevent ie caching -->
<img src="securimage_show.php?sid=<?php echo md5(uniqid(time())); ?>"><br />
<input type="text" name="code" /><br />
<input type="submit" value="Submit Form" />
</form>
<?php
} else { //form is posted
include("securimage.php");
$img = new Securimage();
$valid = $img->check($_POST['code']);
if($valid == true) {
echo "<center>Thanks, you entered the correct code.</center>";
} else {
echo "<center>Sorry, the code you entered was invalid. <a href=\"javascript:history.go(-1)\">Go back</a> to try again.</center>";
}
}
?>
</body>
</html>
| Java |
/*
** Copyright (C) 1998-2007 George Tzanetakis <[email protected]>
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef MARSYAS_STEREOSPECTRUMSOURCES_H
#define MARSYAS_STEREOSPECTRUMSOURCES_H
#include "MarSystem.h"
namespace Marsyas
{
/**
\class StereoSpectrumSources
\ingroup Analysis
\brief StereoSpectrumSources estimates the number of sources placed into different stereo positions.
After computing the Stereo Spectrum we can try to estimate the number of sources playing in different
stereo positions.
*/
class Peaker;
class StereoSpectrumSources: public MarSystem
{
private:
realvec orderedPans_;
realvec panChanges_;
realvec panPeaks_;
Peaker* panPeaker_;
void myUpdate(MarControlPtr sender);
public:
StereoSpectrumSources(std::string name);
StereoSpectrumSources(const StereoSpectrumSources& a);
~StereoSpectrumSources();
MarSystem* clone() const;
void myProcess(realvec& in, realvec& out);
};
}//namespace Marsyas
#endif
| Java |
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
*
* 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.
*
* Copyright 2011 Red Hat, Inc.
*/
#ifndef __NETWORKMANAGER_DEVICE_INFINIBAND_H__
#define __NETWORKMANAGER_DEVICE_INFINIBAND_H__
#include "nm-device.h"
#define NM_TYPE_DEVICE_INFINIBAND (nm_device_infiniband_get_type ())
#define NM_DEVICE_INFINIBAND(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), NM_TYPE_DEVICE_INFINIBAND, NMDeviceInfiniband))
#define NM_DEVICE_INFINIBAND_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), NM_TYPE_DEVICE_INFINIBAND, NMDeviceInfinibandClass))
#define NM_IS_DEVICE_INFINIBAND(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), NM_TYPE_DEVICE_INFINIBAND))
#define NM_IS_DEVICE_INFINIBAND_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), NM_TYPE_DEVICE_INFINIBAND))
#define NM_DEVICE_INFINIBAND_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), NM_TYPE_DEVICE_INFINIBAND, NMDeviceInfinibandClass))
typedef struct _NMDeviceInfiniband NMDeviceInfiniband;
typedef struct _NMDeviceInfinibandClass NMDeviceInfinibandClass;
GType nm_device_infiniband_get_type (void);
#endif /* __NETWORKMANAGER_DEVICE_INFINIBAND_H__ */
| Java |
/********************************************************************
KWin - the KDE window manager
This file is part of the KDE project.
Copyright (C) 2010 Thomas Lübking <[email protected]>
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/>.
*********************************************************************/
#ifndef WINDOWGEOMETRY_CONFIG_H
#define WINDOWGEOMETRY_CONFIG_H
#include <kcmodule.h>
#include "ui_windowgeometry_config.h"
namespace KWin
{
class WindowGeometryConfigForm : public QWidget, public Ui::WindowGeometryConfigForm
{
Q_OBJECT
public:
explicit WindowGeometryConfigForm(QWidget* parent);
};
class WindowGeometryConfig : public KCModule
{
Q_OBJECT
public:
explicit WindowGeometryConfig(QWidget* parent = 0, const QVariantList& args = QVariantList());
~WindowGeometryConfig();
public Q_SLOTS:
void save();
void defaults();
private:
WindowGeometryConfigForm* myUi;
KActionCollection* myActionCollection;
};
} // namespace
#endif
| Java |
<p>No API Key or List Id Exist!</p> | Java |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.dao.api;
import org.opennms.netmgt.model.OnmsMemo;
/**
* @author <a href="mailto:[email protected]">Markus Neumann</a>
*/
public interface MemoDao extends OnmsDao<OnmsMemo, Integer> {
}
| Java |
<div>
{% for new in news %}
<div widget-toggle="news" id_widget_note="{{new.id_article}}">
<h2 change_key="title" replace="input">{{new.title}}</h2>
<div change_key="content" replace="ck">{{new.content}}</div>
</div>
{% endfor %}
<br clear="both">
</div> | Java |
/* -*- c-set-style: "K&R"; c-basic-offset: 8 -*-
*
* This file is part of PRoot.
*
* Copyright (C) 2014 STMicroelectronics
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
#ifndef AOXP_H
#define AOXP_H
#include <stdbool.h>
#include "tracee/reg.h"
#include "arch.h"
typedef struct array_of_xpointers ArrayOfXPointers;
typedef int (*read_xpointee_t)(ArrayOfXPointers *array, size_t index, void **object);
typedef int (*write_xpointee_t)(ArrayOfXPointers *array, size_t index, const void *object);
typedef int (*compare_xpointee_t)(ArrayOfXPointers *array, size_t index, const void *reference);
typedef int (*sizeof_xpointee_t)(ArrayOfXPointers *array, size_t index);
typedef struct mixed_pointer XPointer;
struct array_of_xpointers {
XPointer *_xpointers;
size_t length;
read_xpointee_t read_xpointee;
write_xpointee_t write_xpointee;
compare_xpointee_t compare_xpointee;
sizeof_xpointee_t sizeof_xpointee;
};
static inline int read_xpointee(ArrayOfXPointers *array, size_t index, void **object)
{
return array->read_xpointee(array, index, object);
}
static inline int write_xpointee(ArrayOfXPointers *array, size_t index, const void *object)
{
return array->write_xpointee(array, index, object);
}
static inline int compare_xpointee(ArrayOfXPointers *array, size_t index, const void *reference)
{
return array->compare_xpointee(array, index, reference);
}
static inline int sizeof_xpointee(ArrayOfXPointers *array, size_t index)
{
return array->sizeof_xpointee(array, index);
}
extern int find_xpointee(ArrayOfXPointers *array, const void *reference);
extern int resize_array_of_xpointers(ArrayOfXPointers *array, size_t index, ssize_t nb_delta_entries);
extern int fetch_array_of_xpointers(Tracee *tracee, ArrayOfXPointers **array, Reg reg, size_t nb_entries);
extern int push_array_of_xpointers(ArrayOfXPointers *array, Reg reg);
extern int read_xpointee_as_object(ArrayOfXPointers *array, size_t index, void **object);
extern int read_xpointee_as_string(ArrayOfXPointers *array, size_t index, char **string);
extern int write_xpointee_as_string(ArrayOfXPointers *array, size_t index, const char *string);
extern int write_xpointees(ArrayOfXPointers *array, size_t index, size_t nb_xpointees, ...);
extern int compare_xpointee_generic(ArrayOfXPointers *array, size_t index, const void *reference);
extern int sizeof_xpointee_as_string(ArrayOfXPointers *array, size_t index);
#endif /* AOXP_H */
| Java |
/* packet-forces.c
* RFC 5810
* Routines for dissecting IETF ForCES protocol layer messages.Now support the following TML types:TCP+UDP,SCTP.
* Copyright 2009, NDSC & Zhejiang Gongshang University,Fenggen Jia <[email protected] or [email protected]>
*
* $Id$
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* 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 "config.h"
#include <glib.h>
#include <epan/packet.h>
#include <epan/prefs.h>
#include <epan/expert.h>
static dissector_handle_t ip_handle;
/* Initialize the ForCES protocol and registered fields */
static int proto_forces = -1;
/*Main header*/
static int hf_forces_version = -1;
static int hf_forces_rsvd = -1;
static int hf_forces_messagetype = -1;
static int hf_forces_sid = -1;
static int hf_forces_did = -1;
static int hf_forces_correlator = -1;
static int hf_forces_length = -1;
/*Flags*/
static int hf_forces_flags= -1;
static int hf_forces_flags_ack= -1;
static int hf_forces_flags_pri= -1;
static int hf_forces_flags_rsrvd= -1;
static int hf_forces_flags_em= -1;
static int hf_forces_flags_at= -1;
static int hf_forces_flags_tp= -1;
static int hf_forces_flags_reserved = -1;
static int hf_forces_tlv_type = -1;
static int hf_forces_tlv_length = -1;
/*Initiation of LFBSelect TLV*/
static int hf_forces_lfbselect_tlv_type_lfb_classid = -1;
static int hf_forces_lfbselect_tlv_type_lfb_instanceid = -1;
/*Initiation of Operation TLV*/
static int hf_forces_lfbselect_tlv_type_operation_type = -1;
static int hf_forces_lfbselect_tlv_type_operation_length = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_type = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_length = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_flags = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_flags_selector = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_flags_reserved = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_IDcount = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_IDs = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_data = -1;
/*Initiation of Redirect TLV*/
static int hf_forces_redirect_tlv_meta_data_tlv_type = -1;
static int hf_forces_redirect_tlv_meta_data_tlv_length = -1;
static int hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv = -1;
static int hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_id = -1;
static int hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_length = -1;
static int hf_forces_redirect_tlv_redirect_data_tlv_type = -1;
static int hf_forces_redirect_tlv_redirect_data_tlv_length = -1;
/*Initiation of ASResult TLV*/
static int hf_forces_asresult_association_setup_result = -1;
/*Initiation of ASTreason TLV*/
static int hf_forces_astreason_tlv_teardown_reason = -1;
/*Main TLV may be unknown*/
static int hf_forces_unknown_tlv = -1;
/*Message Types */
#define AssociationSetup 0x01
#define AssociationTeardown 0x02
#define Config 0x03
#define Query 0x04
#define EventNotification 0x05
#define PacketRedirect 0x06
#define Heartbeat 0x0F
#define AssociationSetupRepsonse 0x11
#define ConfigResponse 0x13
#define QueryResponse 0x14
/*TLV Types*/
#define Reserved 0x0000
#define REDIRECT_TLV 0x0001
#define ASResult_TLV 0x0010
#define ASTreason_TLV 0x0011
#define LFBselect_TLV 0x1000
#define PATH_DATA_TLV 0x0110
#define KEYINFO_TLV 0x0111
#define FULLDATA_TLV 0x0112
#define SPARSEDATA_TLV 0x0113
#define RESULT_TLV 0x0114
#define METADATA_TLV 0x0115
#define REDIRECTDATA_TLV 0x0116
/*Operation Type*/
#define Reserved 0x0000
#define SET 0x0001
#define SET_PROP 0x0002
#define SET_RESPONSE 0x0003
#define SET_PROP_RESPONSE 0x0004
#define DEL 0x0005
#define DEL_RESPONSE 0x0006
#define GET 0x0007
#define GET_PROP 0x0008
#define GET_RESPONSE 0x0009
#define GET_PROP_RESPONSE 0x000A
#define REPORT 0x000B
#define COMMIT 0x000C
#define COMMIT_RESPONSE 0x000D
#define TRCOMP 0x000E
#define FLAG_SELECTOR 0x8000
#define ForCES_HEADER_LENGTH 24
#define TLV_TL_LENGTH 4 /*Type+length*/
#define MIN_IP_HEADER_LENGTH 20
/*For TCP+UDP TML. There are two bytes added to the ForCES PL message, not strictly combine to the ForCES protocol.
For other type TMLs,no need to add these 2 bytes.*/
#define TCP_UDP_TML_FOCES_MESSAGE_OFFSET_TCP 2
/*TCP+UDP TML*/
static guint forces_alternate_tcp_port = 0;
static guint forces_alternate_udp_port = 0;
/*SCTP TML*/
static guint forces_alternate_sctp_high_prio_channel_port = 0;
static guint forces_alternate_sctp_med_prio_channel_port = 0;
static guint forces_alternate_sctp_low_prio_channel_port = 0;
/*Initialize the subtree pointers*/
static gint ett_forces = -1;
static gint ett_forces_main_header = -1;
static gint ett_forces_flags = -1;
static gint ett_forces_tlv = -1;
static gint ett_forces_lfbselect_tlv_type = -1;
/*Operation TLV subtree*/
static gint ett_forces_lfbselect_tlv_type_operation = -1;
static gint ett_forces_lfbselect_tlv_type_operation_path = -1;
static gint ett_forces_lfbselect_tlv_type_operation_path_data = -1;
static gint ett_forces_lfbselect_tlv_type_operation_path_data_path = -1;
static gint ett_forces_path_data_tlv = -1;
static gint ett_forces_path_data_tlv_flags = -1;
/*Selector subtree*/
static gint ett_forces_lfbselect_tlv_type_operation_path_selector = -1;
/*Redirect TLV subtree*/
static gint ett_forces_redirect_tlv_type = -1;
static gint ett_forces_redirect_tlv_meta_data_tlv = -1;
static gint ett_forces_redirect_tlv_meta_data_tlv_meta_data_ilv = -1;
static gint ett_forces_redirect_tlv_redirect_data_tlv = -1;
/*ASResult TLV subtree*/
static gint ett_forces_asresult_tlv = -1;
/*ASReason subtree*/
static gint ett_forces_astreason_tlv = -1;
/*Main_TLV unknown subtree*/
static gint ett_forces_unknown_tlv = -1;
static expert_field ei_forces_length = EI_INIT;
static expert_field ei_forces_tlv_type = EI_INIT;
static expert_field ei_forces_tlv_length = EI_INIT;
static expert_field ei_forces_lfbselect_tlv_type_operation_path_length = EI_INIT;
static expert_field ei_forces_lfbselect_tlv_type_operation_type = EI_INIT;
static expert_field ei_forces_redirect_tlv_redirect_data_tlv_length = EI_INIT;
/*ACK values and the strings to be displayed*/
static const value_string main_header_flags_ack_vals[] = {
{ 0x0, "NoACK" },
{ 0x1, "SuccessACK" },
{ 0x2, "FailureACK" },
{ 0x3, "AlwaysACK" },
{ 0, NULL}
};
/*Execution mode(EM) values and the strings to be displayed*/
static const value_string main_header_flags_em_vals[] = {
{ 0x0, "Reserved" },
{ 0x1, "Execute-all-or-none" },
{ 0x2, "Execute-until-failure" },
{ 0x3, "Continue-execute-on-failure" },
{ 0, NULL}
};
/*Transaction Phase values and the strings to be displayed*/
static const value_string main_header_flags_tp_vals[] = {
{ 0x0, "SOT (Start of Transaction)" },
{ 0x1, "MOT (Middle of Transaction)" },
{ 0x2, "EOT (End of Transaction)" },
{ 0x3, "ABT (Abort)" },
{ 0, NULL}
};
/*Atomic Transaction(AT) values and the strings to be displayed*/
static const value_string main_header_flags_at_vals[] = {
{ 0x0, "Stand-alone Message"},
{ 0x1, "2PC Transaction Message"},
{ 0, NULL}
};
/*Association Setup Result*/
static const value_string association_setup_result_at_vals[] = {
{ 0x0, "success"},
{ 0x1, "FE ID invalid"},
{ 0x2, "permission denied"},
{ 0, NULL},
};
/*Teardown Reason*/
static const value_string teardown_reason_at_vals[] = {
{ 0x0, "normal-teardown by administrator"},
{ 0x1, "error - loss of heartbeats"},
{ 0x2, "error - out of bandwidth"},
{ 0x3, "error - out of memory"},
{ 0x4, "error - application crash"},
{ 0x255, "error - other or unspecified"},
{ 0, NULL},
};
static const value_string message_type_vals[] = {
{ AssociationSetup, "AssociationSetup" },
{ AssociationTeardown, "AssociationTeardown" },
{ Config, "Config" },
{ Query, "Query" },
{ EventNotification, "EventNotification" },
{ PacketRedirect, "PacketRedirect" },
{ Heartbeat, "Heartbeat" },
{ AssociationSetupRepsonse, "AssociationSetupRepsonse" },
{ ConfigResponse, "ConfigResponse" },
{ QueryResponse, "QueryResponse" },
{ 0, NULL},
};
static const value_string tlv_type_vals[] = {
{ REDIRECT_TLV, "REDIRECT-TLV" },
{ ASResult_TLV, "ASResult-TLV" },
{ ASTreason_TLV, "ASTreason-TLV" },
{ LFBselect_TLV, "LFBselect-TLV" },
{ PATH_DATA_TLV, "PATH DATA-TLV" },
{ KEYINFO_TLV, "KEYINFO-TLV" },
{ FULLDATA_TLV, "FULLDATA-TLV" },
{ SPARSEDATA_TLV, "SPARSEDATA-TLV" },
{ RESULT_TLV, "RESULT-TLV" },
{ METADATA_TLV, "METADATA-TLV" },
{ REDIRECTDATA_TLV, "REDIRECTDATA-TLV" },
{ 0, NULL},
};
static const value_string operation_type_vals[] = {
{ Reserved, "Reserved" },
{ SET, "SET" },
{ SET_PROP, "SET-PROP" },
{ SET_RESPONSE, "SET-RESPONSE" },
{ SET_PROP_RESPONSE, "SET-PROP-RESPONSE" },
{ DEL, "DEL" },
{ DEL_RESPONSE, "DEL-RESPONSE" },
{ GET, "GET" },
{ GET_PROP, "GET-PROP" },
{ GET_RESPONSE, "GET-RESPONSE" },
{ GET_PROP_RESPONSE, "GET-PROP-RESPONSE" },
{ REPORT, "REPORT" },
{ COMMIT, "COMMIT" },
{ COMMIT_RESPONSE, "COMMIT-RESPONSE" },
{ TRCOMP, "TRCOMP" },
{ 0, NULL},
};
static void
dissect_path_data_tlv(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset)
{
proto_item *ti, *flag_item;
guint length_TLV, IDcount, i;
guint16 type, flag;
proto_tree *tlv_tree, *path_data_tree, *flag_tree;
while (tvb_reported_length_remaining(tvb, offset) >= TLV_TL_LENGTH)
{
ti = proto_tree_add_text(tree, tvb, offset, TLV_TL_LENGTH, "TLV");
tlv_tree = proto_item_add_subtree(ti, ett_forces_path_data_tlv);
type = tvb_get_ntohs(tvb, offset);
proto_tree_add_item(tlv_tree, hf_forces_lfbselect_tlv_type_operation_path_type,
tvb, offset, 2, ENC_BIG_ENDIAN);
length_TLV = tvb_get_ntohs(tvb, offset+2);
proto_tree_add_item(tlv_tree, hf_forces_lfbselect_tlv_type_operation_path_length,
tvb, offset+2, 2, ENC_BIG_ENDIAN);
if (length_TLV < TLV_TL_LENGTH)
{
expert_add_info_format(pinfo, ti, &ei_forces_lfbselect_tlv_type_operation_path_length, "Bogus TLV length: %u", length_TLV);
break;
}
proto_item_set_len(ti, length_TLV);
if (type == PATH_DATA_TLV)
{
ti = proto_tree_add_text(tree, tvb, offset+TLV_TL_LENGTH, length_TLV-TLV_TL_LENGTH, "Path Data TLV");
path_data_tree = proto_item_add_subtree(ti, ett_forces_path_data_tlv);
flag = tvb_get_ntohs(tvb, offset+TLV_TL_LENGTH);
flag_item = proto_tree_add_item(path_data_tree, hf_forces_lfbselect_tlv_type_operation_path_flags,
tvb, offset+TLV_TL_LENGTH, 2, ENC_BIG_ENDIAN);
flag_tree = proto_item_add_subtree(flag_item, ett_forces_path_data_tlv_flags);
proto_tree_add_item(flag_tree, hf_forces_lfbselect_tlv_type_operation_path_flags_selector,
tvb, offset+TLV_TL_LENGTH, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(flag_tree, hf_forces_lfbselect_tlv_type_operation_path_flags_reserved,
tvb, offset+TLV_TL_LENGTH, 2, ENC_BIG_ENDIAN);
IDcount = tvb_get_ntohs(tvb, offset + TLV_TL_LENGTH + 2);
proto_tree_add_item(path_data_tree, hf_forces_lfbselect_tlv_type_operation_path_IDcount,
tvb, offset+TLV_TL_LENGTH+2, 2, ENC_BIG_ENDIAN);
for (i = 0; i < IDcount; i++)
proto_tree_add_item(path_data_tree, hf_forces_lfbselect_tlv_type_operation_path_IDs,
tvb, offset+TLV_TL_LENGTH+2+(i*4), 4, ENC_BIG_ENDIAN);
}
else
{
flag = 0;
proto_tree_add_item(tree, hf_forces_lfbselect_tlv_type_operation_path_data,
tvb, offset+TLV_TL_LENGTH, length_TLV-TLV_TL_LENGTH, ENC_NA);
}
if ((flag & FLAG_SELECTOR) == 0)
break;
offset += length_TLV;
}
}
static void
dissect_operation_tlv(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset, gint length_count)
{
proto_item *ti;
proto_tree *oper_tree;
guint type, length;
while (tvb_reported_length_remaining(tvb, offset) >= TLV_TL_LENGTH)
{
ti = proto_tree_add_text(tree, tvb, offset, length_count, "Operation TLV");
oper_tree = proto_item_add_subtree(ti, ett_forces_lfbselect_tlv_type_operation);
type = tvb_get_ntohs(tvb,offset);
ti = proto_tree_add_item(oper_tree, hf_forces_lfbselect_tlv_type_operation_type,
tvb, offset, 2, ENC_BIG_ENDIAN);
if (try_val_to_str(type, operation_type_vals) == NULL)
expert_add_info_format(pinfo, ti, &ei_forces_lfbselect_tlv_type_operation_type,
"Bogus: ForCES Operation TLV (Type:0x%04x) is not supported", type);
length = tvb_get_ntohs(tvb, offset+2);
proto_tree_add_uint_format_value(oper_tree, hf_forces_lfbselect_tlv_type_operation_length,
tvb, offset+2, 2, length, "%u Bytes", length);
dissect_path_data_tlv(tvb, pinfo, oper_tree, offset+TLV_TL_LENGTH);
if (length == 0)
break;
offset += length;
}
}
static void
dissect_lfbselecttlv(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset, gint length_count)
{
guint tlv_length;
proto_tree_add_item(tree, hf_forces_lfbselect_tlv_type_lfb_classid, tvb, offset, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_forces_lfbselect_tlv_type_lfb_instanceid, tvb, offset+4, 4, ENC_BIG_ENDIAN);
offset += 8;
while ((tvb_reported_length_remaining(tvb, offset) > TLV_TL_LENGTH) && (length_count > 12))
{
tlv_length = tvb_get_ntohs(tvb, offset+2);
dissect_operation_tlv(tvb, pinfo, tree, offset, tlv_length);
if (tlv_length == 0)
break;
offset += tlv_length;
}
}
static void
dissect_redirecttlv(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset)
{
proto_tree *meta_data_tree, *meta_data_ilv_tree, *redirect_data_tree;
gint start_offset;
gint length_meta, length_ilv, length_redirect;
proto_item *ti;
address src_addr = pinfo->src,
src_net_addr = pinfo->net_src,
dst_addr = pinfo->dst,
dst_net_addr = pinfo->net_dst;
ti = proto_tree_add_text(tree, tvb, offset, TLV_TL_LENGTH, "Meta Data TLV");
meta_data_tree = proto_item_add_subtree(ti, ett_forces_redirect_tlv_meta_data_tlv);
proto_tree_add_item(meta_data_tree, hf_forces_redirect_tlv_meta_data_tlv_type, tvb, offset, 2, ENC_BIG_ENDIAN);
length_meta = tvb_get_ntohs(tvb, offset+2);
proto_tree_add_uint_format_value(meta_data_tree, hf_forces_redirect_tlv_meta_data_tlv_length, tvb, offset+2, 2,
length_meta, "%u Bytes", length_meta);
proto_item_set_len(ti, length_meta);
start_offset = offset;
while ((tvb_reported_length_remaining(tvb, offset) >= 8) && (start_offset+length_meta > offset))
{
ti = proto_tree_add_text(tree, tvb, offset, TLV_TL_LENGTH, "Meta Data ILV");
meta_data_ilv_tree = proto_item_add_subtree(ti, ett_forces_redirect_tlv_meta_data_tlv_meta_data_ilv);
proto_tree_add_item(meta_data_ilv_tree, hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_id,
tvb, offset+8, 4, ENC_BIG_ENDIAN);
length_ilv = tvb_get_ntohl(tvb, offset+12);
proto_tree_add_uint_format_value(meta_data_ilv_tree, hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_length,
tvb, offset+12, 4, length_ilv, "%u Bytes", length_ilv);
if (length_ilv > 0)
proto_tree_add_item(meta_data_ilv_tree, hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv,
tvb, offset+8, length_ilv, ENC_NA);
proto_item_set_len(ti, length_ilv + 8);
offset += length_ilv + 8;
}
if (tvb_reported_length_remaining(tvb, offset) > 0)
{
ti = proto_tree_add_text(tree, tvb, offset, TLV_TL_LENGTH, "Redirect Data TLV");
redirect_data_tree = proto_item_add_subtree(ti, ett_forces_redirect_tlv_redirect_data_tlv);
proto_tree_add_item(redirect_data_tree, hf_forces_redirect_tlv_redirect_data_tlv_type,
tvb, offset, 2, ENC_BIG_ENDIAN);
length_redirect = tvb_get_ntohs(tvb, offset+2);
proto_tree_add_uint_format_value(redirect_data_tree, hf_forces_redirect_tlv_redirect_data_tlv_length,
tvb, offset+2, 2, length_redirect, "%u Bytes", length_redirect);
if (tvb_reported_length_remaining(tvb, offset) < length_redirect)
{
expert_add_info_format(pinfo, ti, &ei_forces_redirect_tlv_redirect_data_tlv_length, "Bogus: Redirect Data TLV length (%u bytes) is wrong", length_redirect);
}
else if (length_redirect < TLV_TL_LENGTH + MIN_IP_HEADER_LENGTH)
{
expert_add_info_format(pinfo, ti, &ei_forces_redirect_tlv_redirect_data_tlv_length, "Bogus: Redirect Data TLV length (%u bytes) not big enough for IP layer", length_redirect);
}
else
{
tvbuff_t *next_tvb;
next_tvb = tvb_new_subset(tvb, offset+4, length_redirect-TLV_TL_LENGTH, length_redirect-TLV_TL_LENGTH);
call_dissector(ip_handle, next_tvb, pinfo, redirect_data_tree);
/* Restore IP info */
memcpy(&(pinfo->src), &src_addr, sizeof(address));
memcpy(&(pinfo->net_src), &src_net_addr, sizeof(address));
memcpy(&(pinfo->dst), &dst_addr, sizeof(address));
memcpy(&(pinfo->net_dst), &dst_net_addr, sizeof(address));
}
}
}
static void
dissect_forces(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint32 offset)
{
/* Set up structures needed to add the protocol subtree and manage it */
proto_item *ti, *tlv_item;
proto_tree *forces_tree, *forces_flags_tree;
proto_tree *forces_main_header_tree, *forces_tlv_tree, *tlv_tree;
gint length_count;
guint8 message_type;
guint16 tlv_type;
/* Make entries in Protocol column and Info column on summary display */
col_set_str(pinfo->cinfo, COL_PROTOCOL, "ForCES");
col_clear(pinfo->cinfo, COL_INFO);
ti = proto_tree_add_item(tree, proto_forces, tvb, 0, -1, ENC_NA);
forces_tree = proto_item_add_subtree(ti, ett_forces);
ti = proto_tree_add_text(forces_tree, tvb, 0, ForCES_HEADER_LENGTH, "Common Header");
forces_main_header_tree = proto_item_add_subtree(ti, ett_forces_main_header);
proto_tree_add_item(forces_main_header_tree, hf_forces_version, tvb, 0, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(forces_main_header_tree, hf_forces_rsvd, tvb, 0, 1, ENC_BIG_ENDIAN);
message_type = tvb_get_guint8(tvb, offset+1);
proto_tree_add_item( forces_main_header_tree, hf_forces_messagetype, tvb, offset+1, 1, ENC_BIG_ENDIAN);
length_count = tvb_get_ntohs(tvb, offset+2) * 4; /*multiply 4 DWORD*/
ti = proto_tree_add_uint_format( forces_main_header_tree, hf_forces_length,
tvb, offset+2, 2, length_count, "Length: %u Bytes", length_count);
if (length_count != tvb_reported_length_remaining(tvb, offset))
expert_add_info_format(pinfo, ti, &ei_forces_length, "Bogus: ForCES Header length (%u bytes) is wrong),should be (%u bytes)",
length_count, tvb_reported_length_remaining(tvb, offset));
if (length_count < 24)
expert_add_info_format(pinfo, ti, &ei_forces_length, "Bogus: ForCES Header length (%u bytes) is less than 24bytes)", length_count);
col_add_fstr(pinfo->cinfo, COL_INFO, "Message Type: %s, Total Length: %u Bytes",
val_to_str(message_type, message_type_vals, "Unknown messagetype 0x%x"), length_count);
proto_tree_add_item( forces_main_header_tree, hf_forces_sid, tvb, offset+4, 4, ENC_BIG_ENDIAN);
proto_tree_add_item( forces_main_header_tree, hf_forces_did, tvb, offset+8, 4, ENC_BIG_ENDIAN);
proto_tree_add_item( forces_main_header_tree, hf_forces_correlator, tvb, offset+12, 8, ENC_BIG_ENDIAN);
/*Add flags tree*/
ti = proto_tree_add_item(forces_main_header_tree, hf_forces_flags, tvb, offset+20, 4, ENC_BIG_ENDIAN);
forces_flags_tree = proto_item_add_subtree(ti, ett_forces_flags);
proto_tree_add_item(forces_flags_tree, hf_forces_flags_ack, tvb, offset+20, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(forces_flags_tree, hf_forces_flags_at, tvb, offset+20, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(forces_flags_tree, hf_forces_flags_em, tvb, offset+20, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(forces_flags_tree, hf_forces_flags_pri, tvb, offset+20, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(forces_flags_tree, hf_forces_flags_reserved, tvb, offset+20, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(forces_flags_tree, hf_forces_flags_rsrvd, tvb, offset+20, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(forces_flags_tree, hf_forces_flags_tp, tvb, offset+20, 4, ENC_BIG_ENDIAN);
offset += 24;
while (tvb_reported_length_remaining(tvb, offset) >= TLV_TL_LENGTH)
{
ti = proto_tree_add_text(forces_tree, tvb, offset, TLV_TL_LENGTH, "TLV");
forces_tlv_tree = proto_item_add_subtree(ti, ett_forces_tlv);
tlv_type = tvb_get_ntohs(tvb, offset);
tlv_item = proto_tree_add_item(forces_tlv_tree, hf_forces_tlv_type, tvb, offset, 2, ENC_BIG_ENDIAN);
length_count = tvb_get_ntohs(tvb, offset+2) * 4;
proto_item_set_len(ti, length_count);
ti = proto_tree_add_uint_format_value(forces_tlv_tree, hf_forces_tlv_length,
tvb, offset+2, 2, length_count, "%u Bytes", length_count);
if (tvb_reported_length_remaining(tvb, offset) < length_count)
expert_add_info_format(pinfo, ti, &ei_forces_tlv_length, "Bogus: Main TLV length (%u bytes) is wrong", length_count);
if (length_count < TLV_TL_LENGTH)
{
expert_add_info_format(pinfo, ti, &ei_forces_tlv_length, "Bogus TLV length: %u", length_count);
break;
}
offset += TLV_TL_LENGTH;
length_count -= TLV_TL_LENGTH;
switch(tlv_type)
{
case LFBselect_TLV:
ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "LFB select TLV");
tlv_tree = proto_item_add_subtree(ti, ett_forces_lfbselect_tlv_type);
dissect_lfbselecttlv(tvb, pinfo, tlv_tree, offset, length_count);
break;
case REDIRECT_TLV:
ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "Redirect TLV");
tlv_tree = proto_item_add_subtree(ti, ett_forces_redirect_tlv_type);
dissect_redirecttlv(tvb, pinfo, tlv_tree, offset);
break;
case ASResult_TLV:
ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "ASResult TLV");
tlv_tree = proto_item_add_subtree(ti, ett_forces_asresult_tlv);
proto_tree_add_item(tlv_tree, hf_forces_asresult_association_setup_result, tvb, offset, 4, ENC_BIG_ENDIAN);
break;
case ASTreason_TLV:
ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "ASTreason TLV");
tlv_tree = proto_item_add_subtree(ti, ett_forces_astreason_tlv);
proto_tree_add_item(tlv_tree, hf_forces_astreason_tlv_teardown_reason, tvb, offset, 4, ENC_BIG_ENDIAN);
break;
default:
expert_add_info(pinfo, tlv_item, &ei_forces_tlv_type);
ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "Unknown TLV");
tlv_tree = proto_item_add_subtree(ti, ett_forces_unknown_tlv);
proto_tree_add_item(tlv_tree, hf_forces_unknown_tlv, tvb, offset, length_count, ENC_NA);
break;
}
offset += length_count;
}
}
/* Code to actually dissect the TCP packets */
static void
dissect_forces_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
dissect_forces(tvb, pinfo, tree, TCP_UDP_TML_FOCES_MESSAGE_OFFSET_TCP);
}
/* Code to actually dissect the ForCES protocol layer packets,like UDP,SCTP and others */
static void
dissect_forces_not_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
dissect_forces(tvb, pinfo, tree, 0);
}
void proto_reg_handoff_forces(void);
void
proto_register_forces(void)
{
module_t *forces_module;
expert_module_t* expert_forces;
/* Setup list of header fields See Section 1.6.1 for details*/
static hf_register_info hf[] = {
{ &hf_forces_version,
{ "Version", "forces.flags.version",
FT_UINT8, BASE_DEC, NULL, 0xF0, NULL, HFILL }
},
{ &hf_forces_rsvd,
{ "Rsvd", "forces.flags.rsvd",
FT_UINT8, BASE_DEC, NULL, 0x0F, NULL, HFILL }
},
{ &hf_forces_messagetype,
{ "Message Type", "forces.messagetype",
FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_length,
{ "Header Length", "forces.length",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_sid,
{ "Source ID", "forces.sid",
FT_IPv4, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_did,
{ "Destination ID", "forces.did",
FT_IPv4, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_correlator,
{ "Correlator", "forces.correlator",
FT_UINT64, BASE_HEX, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_tlv_type,
{ "Type", "forces.tlv.type",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_tlv_length,
{ "Length", "forces.tlv.length",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
/*flags*/
{ &hf_forces_flags,
{ "Flags", "forces.Flags",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_flags_ack,
{ "ACK indicator", "forces.flags.ack",
FT_UINT32, BASE_DEC, VALS(main_header_flags_ack_vals), 0xC0000000, NULL, HFILL }
},
{ &hf_forces_flags_pri,
{ "Priority", "forces.flags.pri",
FT_UINT32, BASE_DEC, NULL, 0x38000000, NULL, HFILL }
},
{ &hf_forces_flags_rsrvd,
{ "Rsrvd", "forces.Flags",
FT_UINT32, BASE_DEC,NULL, 0x07000000, NULL, HFILL }
},
{ &hf_forces_flags_em,
{ "Execution mode", "forces.flags.em",
FT_UINT32, BASE_DEC, VALS(main_header_flags_em_vals), 0x00C00000, NULL, HFILL }
},
{ &hf_forces_flags_at,
{ "Atomic Transaction", "forces.flags.at",
FT_UINT32, BASE_DEC, VALS(main_header_flags_at_vals), 0x00200000, NULL, HFILL }
},
{ &hf_forces_flags_tp,
{ "Transaction phase", "forces.flags.tp",
FT_UINT32, BASE_DEC, VALS(main_header_flags_tp_vals), 0x00180000, NULL, HFILL }
},
{ &hf_forces_flags_reserved,
{ "Reserved", "forces.flags.reserved",
FT_UINT32, BASE_DEC,NULL, 0x0007ffff, NULL, HFILL }
},
/*LFBSelectTLV*/
{ &hf_forces_lfbselect_tlv_type_lfb_classid,
{ "Class ID", "forces.lfbselect.tlv.type.lfb.classid",
FT_IPv4, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_lfb_instanceid,
{ "Instance ID", "forces.fbselect.tlv.type.lfb.instanceid",
FT_IPv4, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
/*Operation TLV*/
{ &hf_forces_lfbselect_tlv_type_operation_type,
{ "Type", "forces.lfbselect.tlv.type.operation.type",
FT_UINT16, BASE_DEC, VALS(operation_type_vals), 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_length,
{ "Length", "forces.lfbselect.tlv.type.operation.length",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_type,
{ "Type", "forces.lfbselect.tlv.type.operation.path.type",
FT_UINT16, BASE_DEC, VALS(tlv_type_vals), 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_length,
{ "Length", "forces.lfbselect.tlv.type.operation.path.length",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_data,
{ "Data", "forces.lfbselect.tlv.type.operation.path.data",
FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_flags,
{"Path Data Flags", "forces.lfbselect.tlv.type.operation.path.data.flags",
FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_flags_selector,
{"Selector", "forces.lfbselect.tlv.type.operation.path.data.flags.selector",
FT_UINT16, BASE_HEX, NULL, 0x80, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_flags_reserved,
{"Reserved", "forces.lfbselect.tlv.type.operation.path.data.flags.reserved",
FT_UINT16, BASE_HEX, NULL, 0x7F, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_IDcount,
{ "Path Data IDcount", "forces.lfbselect.tlv.type.operation.path.data.IDcount",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_IDs,
{ "Path Data IDs", "forces.lfbselect.tlv.type.operation.path.data.IDs",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
/*Meta data TLV*/
{&hf_forces_redirect_tlv_meta_data_tlv_type,
{ "Type", "forces.redirect.tlv.meta.data.tlv.type",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_redirect_tlv_meta_data_tlv_length,
{ "Length", "forces.redirect.tlv.meta.data.tlv.length",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv,
{ "Meta Data ILV", "forces.redirect.tlv.meta.data.tlv.meta.data.ilv",
FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_id,
{ "ID", "forces.redirect.tlv.meta.data.tlv.meta.data.ilv.id",
FT_UINT32, BASE_HEX_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_length,
{ "Length", "forces.redirect.tlv.meta.data.tlv.meta.data.ilv.length",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_redirect_tlv_redirect_data_tlv_type,
{ "Type", "forces.redirect.tlv.redirect.data.tlv.type",
FT_UINT16, BASE_DEC, VALS(tlv_type_vals), 0x0, NULL, HFILL }
},
{ &hf_forces_redirect_tlv_redirect_data_tlv_length,
{ "Length", "forces.redirect.tlv.redirect.data.tlv.length",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_asresult_association_setup_result,
{ "Association Setup Result", "forces.teardown.reason",
FT_UINT32, BASE_DEC, VALS(association_setup_result_at_vals), 0x0, NULL, HFILL }
},
{ &hf_forces_astreason_tlv_teardown_reason,
{ "AStreason TLV TearDonw Reason", "forces.astreason.tlv.teardonw.reason",
FT_UINT32, BASE_DEC, VALS(teardown_reason_at_vals), 0x0, NULL, HFILL }
},
{ &hf_forces_unknown_tlv,
{ "Data", "forces.unknown.tlv",
FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }
}
};
/* Setup protocol subtree array */
static gint *ett[] = {
&ett_forces,
&ett_forces_main_header,
&ett_forces_flags,
&ett_forces_tlv,
&ett_forces_lfbselect_tlv_type,
&ett_forces_lfbselect_tlv_type_operation,
&ett_forces_lfbselect_tlv_type_operation_path,
&ett_forces_lfbselect_tlv_type_operation_path_data,
&ett_forces_lfbselect_tlv_type_operation_path_data_path,
&ett_forces_lfbselect_tlv_type_operation_path_selector,
&ett_forces_path_data_tlv,
&ett_forces_path_data_tlv_flags,
&ett_forces_redirect_tlv_type,
&ett_forces_redirect_tlv_meta_data_tlv,
&ett_forces_redirect_tlv_redirect_data_tlv,
&ett_forces_redirect_tlv_meta_data_tlv_meta_data_ilv,
&ett_forces_asresult_tlv,
&ett_forces_astreason_tlv,
&ett_forces_unknown_tlv
};
static ei_register_info ei[] = {
{ &ei_forces_length, { "forces.length.bad", PI_PROTOCOL, PI_WARN, "ForCES Header length is wrong", EXPFILL }},
{ &ei_forces_tlv_type, { "forces.tlv.type.unknown", PI_PROTOCOL, PI_WARN, "Bogus: The Main_TLV type is unknown", EXPFILL }},
{ &ei_forces_tlv_length, { "forces.tlv.length.bad", PI_PROTOCOL, PI_WARN, "Bogus TLV length", EXPFILL }},
{ &ei_forces_lfbselect_tlv_type_operation_path_length, { "forces.lfbselect.tlv.type.operation.path.length.bad", PI_PROTOCOL, PI_WARN, "Bogus TLV length", EXPFILL }},
{ &ei_forces_lfbselect_tlv_type_operation_type, { "forces.lfbselect.tlv.type.operation.type.unsupported", PI_PROTOCOL, PI_WARN, "ForCES Operation TLV is not supported", EXPFILL }},
{ &ei_forces_redirect_tlv_redirect_data_tlv_length, { "forces.redirect.tlv.redirect.data.tlv.length.bad", PI_PROTOCOL, PI_WARN, "Redirect Data TLV length is wrong", EXPFILL }},
};
/* Register the protocol name and description */
proto_forces = proto_register_protocol("Forwarding and Control Element Separation Protocol", "ForCES", "forces");
/* Required function calls to register the header fields and subtrees used */
proto_register_field_array(proto_forces, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
expert_forces = expert_register_protocol(proto_forces);
expert_register_field_array(expert_forces, ei, array_length(ei));
forces_module = prefs_register_protocol(proto_forces,proto_reg_handoff_forces);
prefs_register_uint_preference(forces_module, "tcp_alternate_port",
"TCP port",
"Decode packets on this TCP port as ForCES",
10, &forces_alternate_tcp_port);
prefs_register_uint_preference(forces_module, "udp_alternate_port",
"UDP port",
"Decode packets on this UDP port as ForCES",
10, &forces_alternate_udp_port);
prefs_register_uint_preference(forces_module, "sctp_high_prio_port",
"SCTP High Priority channel port",
"Decode packets on this sctp port as ForCES",
10, &forces_alternate_sctp_high_prio_channel_port);
prefs_register_uint_preference(forces_module, "sctp_med_prio_port",
"SCTP Meidium Priority channel port",
"Decode packets on this sctp port as ForCES",
10, &forces_alternate_sctp_med_prio_channel_port);
prefs_register_uint_preference(forces_module, "sctp_low_prio_port",
"SCTP Low Priority channel port",
"Decode packets on this sctp port as ForCES",
10, &forces_alternate_sctp_low_prio_channel_port);
}
void
proto_reg_handoff_forces(void)
{
static gboolean inited = FALSE;
static guint alternate_tcp_port = 0; /* 3000 */
static guint alternate_udp_port = 0;
static guint alternate_sctp_high_prio_channel_port = 0; /* 6700 */
static guint alternate_sctp_med_prio_channel_port = 0;
static guint alternate_sctp_low_prio_channel_port = 0;
static dissector_handle_t forces_handle_tcp, forces_handle;
if (!inited) {
forces_handle_tcp = create_dissector_handle(dissect_forces_tcp, proto_forces);
forces_handle = create_dissector_handle(dissect_forces_not_tcp, proto_forces);
ip_handle = find_dissector("ip");
inited = TRUE;
}
/* Register TCP port for dissection */
if ((alternate_tcp_port != 0) && (alternate_tcp_port != forces_alternate_tcp_port))
dissector_delete_uint("tcp.port", alternate_tcp_port, forces_handle_tcp);
if ((forces_alternate_tcp_port != 0) && (alternate_tcp_port != forces_alternate_tcp_port))
dissector_add_uint("tcp.port", forces_alternate_tcp_port, forces_handle_tcp);
alternate_tcp_port = forces_alternate_tcp_port;
/* Register UDP port for dissection */
if ((alternate_udp_port != 0) && (alternate_udp_port != forces_alternate_udp_port))
dissector_delete_uint("udp.port", alternate_udp_port, forces_handle);
if ((forces_alternate_udp_port != 0) && (alternate_udp_port != forces_alternate_udp_port))
dissector_add_uint("udp.port", forces_alternate_udp_port, forces_handle);
alternate_udp_port = forces_alternate_udp_port;
/* Register SCTP port for high priority dissection */
if ((alternate_sctp_high_prio_channel_port != 0) &&
(alternate_sctp_high_prio_channel_port != forces_alternate_sctp_high_prio_channel_port))
dissector_delete_uint("sctp.port", alternate_sctp_high_prio_channel_port, forces_handle);
if ((forces_alternate_sctp_high_prio_channel_port != 0) &&
(alternate_sctp_high_prio_channel_port != forces_alternate_sctp_high_prio_channel_port))
dissector_add_uint("sctp.port", forces_alternate_sctp_high_prio_channel_port, forces_handle);
alternate_sctp_high_prio_channel_port = forces_alternate_sctp_high_prio_channel_port;
/* Register SCTP port for medium priority dissection */
if ((alternate_sctp_med_prio_channel_port != 0) &&
(alternate_sctp_med_prio_channel_port != forces_alternate_sctp_med_prio_channel_port))
dissector_delete_uint("udp.port", alternate_sctp_med_prio_channel_port, forces_handle);
if ((forces_alternate_sctp_med_prio_channel_port != 0) &&
(alternate_sctp_med_prio_channel_port != forces_alternate_sctp_med_prio_channel_port))
dissector_add_uint("udp.port", forces_alternate_sctp_med_prio_channel_port, forces_handle);
alternate_sctp_med_prio_channel_port = forces_alternate_sctp_med_prio_channel_port;
/* Register SCTP port for low priority dissection */
if ((alternate_sctp_low_prio_channel_port != 0) &&
(alternate_sctp_low_prio_channel_port != forces_alternate_sctp_low_prio_channel_port))
dissector_delete_uint("udp.port", alternate_sctp_low_prio_channel_port, forces_handle);
if ((forces_alternate_sctp_low_prio_channel_port != 0) &&
(alternate_sctp_low_prio_channel_port != forces_alternate_sctp_low_prio_channel_port))
dissector_add_uint("udp.port", forces_alternate_sctp_low_prio_channel_port, forces_handle);
alternate_sctp_low_prio_channel_port = forces_alternate_sctp_low_prio_channel_port;
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| Java |
package lejos.robotics.mapping;
import java.io.*;
import java.util.ArrayList;
import lejos.geom.Line;
import lejos.geom.Rectangle;
/*
* WARNING: THIS CLASS IS SHARED BETWEEN THE classes AND pccomms PROJECTS.
* DO NOT EDIT THE VERSION IN pccomms AS IT WILL BE OVERWRITTEN WHEN THE PROJECT IS BUILT.
*/
/**
* <p>This class loads map data from a Shapefile and produces a LineMap object, which can
* be used by the leJOS navigation package.</p>
*
* <p>There are many map editors which can use the Shapefile format (OpenEV, Global Mapper). Once you
* have created a map, export it as Shapefile. This will produce three files ending in .shp .shx and
* .dbf. The only file used by this class is .shp.</p>
*
* <p>NOTE: Shapefiles can only contain one type of shape data (polygon or polyline, not both). A single file can't
* mix polylines with polygons.</p>
*
* <p>This class' code can parse points and multipoints. However, a LineMap object can't deal with
* points (only lines) so points and multipoints are discarded.</p>
*
* @author BB
*
*/
public class ShapefileLoader {
/* OTHER POTENTIAL MAP FILE FORMATS TO ADD:
* (none have really been researched yet for viability)
* KML
* GML
* WMS? (more of a service than a file)
* MIF/MID (MapInfo)
* SVG (Scalable Vector Graphics)
* EPS (Encapsulated Post Script)
* DXF (Autodesk)
* AI (Adobe Illustrator)
*
*/
// 2D shape types types:
private static final byte NULL_SHAPE = 0;
private static final byte POINT = 1;
private static final byte POLYLINE = 3;
private static final byte POLYGON = 5;
private static final byte MULTIPOINT = 8;
private final int SHAPEFILE_ID = 0x0000270a;
DataInputStream data_is = null;
/**
* Creates a ShapefileLoader object using an input stream. Likely you will use a FileInputStream
* which points to the *.shp file containing the map data.
* @param in
*/
public ShapefileLoader(InputStream in) {
this.data_is = new DataInputStream(in);
}
/**
* Retrieves a LineMap object from the Shapefile input stream.
* @return the line map
* @throws IOException
*/
public LineMap readLineMap() throws IOException {
ArrayList <Line> lines = new ArrayList <Line> ();
int fileCode = data_is.readInt(); // Big Endian
if(fileCode != SHAPEFILE_ID) throw new IOException("File is not a Shapefile");
data_is.skipBytes(20); // Five int32 unused by Shapefile
/*int fileLength =*/ data_is.readInt();
//System.out.println("Length: " + fileLength); // TODO: Docs say length is in 16-bit words. Unsure if this is strictly correct. Seems higher than what hex editor shows.
/*int version =*/ readLEInt();
//System.out.println("Version: " + version);
/*int shapeType =*/ readLEInt();
//System.out.println("Shape type: " + shapeType);
// These x and y min/max values define bounding rectangle:
double xMin = readLEDouble();
double yMin = readLEDouble();
double xMax = readLEDouble();
double yMax = readLEDouble();
// Create bounding rectangle:
Rectangle rect = new Rectangle((float)xMin, (float)yMin, (float)(xMax - xMin), (float)(yMax - yMin));
/*double zMin =*/ readLEDouble();
/*double zMax =*/ readLEDouble();
/*double mMin =*/ readLEDouble();
/*double mMax =*/ readLEDouble();
// TODO These values seem to be rounded down to nearest 0.5. Must round them up?
//System.out.println("Xmin " + xMin + " Ymin " + yMin);
//System.out.println("Xmax " + xMax + " Ymax " + yMax);
try { // TODO: This is a cheesy way to detect EOF condition. Not very good coding.
while(2 > 1) { // TODO: Temp code to keep it looping. Should really detect EOF condition.
// NOW ONTO READING INDIVIDUAL SHAPES:
// Record Header (2 values):
/*int recordNum =*/ data_is.readInt();
int recordLen = data_is.readInt(); // TODO: in 16-bit words. Might cause bug if number of shapes gets bigger than 16-bit short?
// Record (variable length depending on shape type):
int recShapeType = readLEInt();
// Now to read the actual shape data
switch (recShapeType) {
case NULL_SHAPE:
break;
case POINT:
// DO WE REALLY NEED TO DEAL WITH POINT? Feature might use them possibly.
/*double pointX =*/ readLEDouble(); // TODO: skip bytes instead
/*double pointY =*/ readLEDouble();
break;
case POLYLINE:
// NOTE: Data structure for polygon/polyline is identical. Code should work for both.
case POLYGON:
// Polygons can contain multiple polygons, such as a donut with outer ring and inner ring for hole.
// Max bounding rect: 4 doubles in a row. TODO: Discard bounding rect. values and skip instead.
/*double polyxMin =*/ readLEDouble();
/*double polyyMin =*/ readLEDouble();
/*double polyxMax =*/ readLEDouble();
/*double polyyMax =*/ readLEDouble();
int numParts = readLEInt();
int numPoints = readLEInt();
// Retrieve array of indexes for each part in the polygon
int [] partIndex = new int[numParts];
for(int i=0;i<numParts;i++) {
partIndex[i] = readLEInt();
}
// Now go through numParts times pulling out points
double firstX=0;
double firstY=0;
for(int i=0;i<numPoints-1;i++) {
// Could check here if onto new polygon (i = next index). If so, do something with line formation.
for(int j=0;j<numParts;j++) {
if(i == partIndex[j]) {
firstX = readLEDouble();
firstY = readLEDouble();
continue;
}
}
double secondX = readLEDouble();
double secondY = readLEDouble();
Line myLine = new Line((float)firstX, (float)firstY, (float)secondX, (float)secondY);
lines.add(myLine);
firstX = secondX;
firstY = secondY;
}
break;
case MULTIPOINT:
// TODO: DO WE REALLY NEED TO DEAL WITH MULTIPOINT? Comment out and skip bytes?
/*double multixMin = */readLEDouble();
/*double multiyMin = */readLEDouble();
/*double multixMax = */readLEDouble();
/*double multiyMax = */readLEDouble();
int multiPoints = readLEInt();
double [] xVals = new double[multiPoints];
double [] yVals = new double[multiPoints];
for(int i=0;i<multiPoints;i++) {
xVals[i] = readLEDouble();
yVals[i] = readLEDouble();
}
break;
default:
// IGNORE REST OF SHAPE TYPES and skip over data using recordLen value
//System.out.println("Some other unknown shape");
data_is.skipBytes(recordLen); // TODO: Check if this works on polyline or point
}
} // END OF WHILE
} catch(EOFException e) {
// End of File, just needs to continue
}
Line [] arrList = new Line [lines.size()];
return new LineMap(lines.toArray(arrList), rect);
}
/**
* Translates a little endian int into a big endian int
*
* @return int A big endian int
*/
private int readLEInt() throws IOException {
int byte1, byte2, byte3, byte4;
synchronized (this) {
byte1 = data_is.read();
byte2 = data_is.read();
byte3 = data_is.read();
byte4 = data_is.read();
}
if (byte4 == -1) {
throw new EOFException();
}
return (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1;
}
/**
* Reads a little endian double into a big endian double
*
* @return double A big endian double
*/
private final double readLEDouble() throws IOException {
return Double.longBitsToDouble(this.readLELong());
}
/**
* Translates a little endian long into a big endian long
*
* @return long A big endian long
*/
private long readLELong() throws IOException {
long byte1 = data_is.read();
long byte2 = data_is.read();
long byte3 = data_is.read();
long byte4 = data_is.read();
long byte5 = data_is.read();
long byte6 = data_is.read();
long byte7 = data_is.read();
long byte8 = data_is.read();
if (byte8 == -1) {
throw new EOFException();
}
return (byte8 << 56) + (byte7 << 48) + (byte6 << 40) + (byte5 << 32)
+ (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.