repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
momogentoo/ehour | eHour-wicketweb/src/test/java/net/rrm/ehour/ui/userprefs/page/UserPreferencePageTest.java | 1825 | /*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package net.rrm.ehour.ui.userprefs.page;
import net.rrm.ehour.exception.ObjectNotFoundException;
import net.rrm.ehour.timesheet.service.IOverviewTimesheet;
import net.rrm.ehour.ui.common.BaseSpringWebAppTester;
import net.rrm.ehour.ui.common.MockExpectations;
import net.rrm.ehour.user.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class UserPreferencePageTest extends BaseSpringWebAppTester {
@Mock
IOverviewTimesheet overviewTimesheet;
@Mock
UserService userService;
@Test
public void shouldRenderPreferencePage() throws ObjectNotFoundException {
getMockContext().putBean(overviewTimesheet);
getMockContext().putBean(userService);
MockExpectations.navCalendar(overviewTimesheet, getWebApp());
tester.startPage(UserPreferencePage.class);
tester.assertRenderedPage(UserPreferencePage.class);
tester.assertNoErrorMessage();
}
}
| gpl-2.0 |
pinxi/training | profiles/conference/modules/contrib/views_bonus/export/views-bonus-export-xls.tpl.php | 881 | <?php
// $Id: views-bonus-export-xls.tpl.php,v 1.1 2010/01/07 22:56:47 neclimdul Exp $
/**
* @file
* Template to display a view as an excel XLS file.
*
* - $title : The title of this group of rows. May be empty.
* - $rows: An array of row items. Each row is an array of content
* keyed by field ID.
* - $header: an array of headers(labels) for fields.
* - $themed_rows: a array of rows with themed fields.
* @ingroup views_templates
*/
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
$table = theme('table', $header, $themed_rows);
$table = preg_replace('/<\/?(a|span) ?.*?>/', '', $table); // strip 'a' and 'span' tags
$table = preg_replace('/<div ?.*?>([^<]*)<\/div>/', '\1, ', $table); // Removes 'div' wrappers around grouped fields.
print $table;
?>
</body>
</html>
| gpl-2.0 |
eugenesia/eugenesia.co.uk | core/modules/taxonomy/lib/Drupal/taxonomy/Tests/TermLanguageTest.php | 4535 | <?php
/**
* @file
* Definition of Drupal\taxonomy\Tests\TermLanguageTest.
*/
namespace Drupal\taxonomy\Tests;
use Drupal\Core\Language\Language;
/**
* Tests for the language feature on taxonomy terms.
*/
class TermLanguageTest extends TaxonomyTestBase {
public static $modules = array('language');
public static function getInfo() {
return array(
'name' => 'Taxonomy term language',
'description' => 'Tests the language functionality for the taxonomy terms.',
'group' => 'Taxonomy',
);
}
function setUp() {
parent::setUp();
// Create an administrative user.
$this->admin_user = $this->drupalCreateUser(array('administer taxonomy'));
$this->drupalLogin($this->admin_user);
// Create a vocabulary to which the terms will be assigned.
$this->vocabulary = $this->createVocabulary();
// Add some custom languages.
foreach (array('aa', 'bb', 'cc') as $language_code) {
$language = new Language(array(
'langcode' => $language_code,
'name' => $this->randomName(),
));
language_save($language);
}
}
function testTermLanguage() {
// Configure the vocabulary to not hide the language selector.
$edit = array(
'default_language[language_show]' => TRUE,
);
$this->drupalPost('admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/edit', $edit, t('Save'));
// Add a term.
$this->drupalGet('admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/add');
// Check that we have the language selector.
$this->assertField('edit-langcode', t('The language selector field was found on the page'));
// Submit the term.
$edit = array(
'name' => $this->randomName(),
'langcode' => 'aa',
);
$this->drupalPost(NULL, $edit, t('Save'));
$terms = taxonomy_term_load_multiple_by_name($edit['name']);
$term = reset($terms);
$this->assertEqual($term->language()->langcode, $edit['langcode']);
// Check if on the edit page the language is correct.
$this->drupalGet('taxonomy/term/' . $term->id() . '/edit');
$this->assertOptionSelected('edit-langcode', $edit['langcode'], t('The term language was correctly selected.'));
// Change the language of the term.
$edit['langcode'] = 'bb';
$this->drupalPost('taxonomy/term/' . $term->id() . '/edit', $edit, t('Save'));
// Check again that on the edit page the language is correct.
$this->drupalGet('taxonomy/term/' . $term->id() . '/edit');
$this->assertOptionSelected('edit-langcode', $edit['langcode'], t('The term language was correctly selected.'));
}
function testDefaultTermLanguage() {
// Configure the vocabulary to not hide the language selector, and make the
// default language of the terms fixed.
$edit = array(
'default_language[langcode]' => 'bb',
'default_language[language_show]' => TRUE,
);
$this->drupalPost('admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/edit', $edit, t('Save'));
$this->drupalGet('admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/add');
$this->assertOptionSelected('edit-langcode', 'bb');
// Make the default language of the terms to be the current interface.
$edit = array(
'default_language[langcode]' => 'current_interface',
'default_language[language_show]' => TRUE,
);
$this->drupalPost('admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/edit', $edit, t('Save'));
$this->drupalGet('aa/admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/add');
$this->assertOptionSelected('edit-langcode', 'aa');
$this->drupalGet('bb/admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/add');
$this->assertOptionSelected('edit-langcode', 'bb');
// Change the default language of the site and check if the default terms
// language is still correctly selected.
$old_default = language_default();
$old_default->default = FALSE;
language_save($old_default);
$new_default = language_load('cc');
$new_default->default = TRUE;
language_save($new_default);
$edit = array(
'default_language[langcode]' => 'site_default',
'default_language[language_show]' => TRUE,
);
$this->drupalPost('admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/edit', $edit, t('Save'));
$this->drupalGet('admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/add');
$this->assertOptionSelected('edit-langcode', 'cc');
}
}
| gpl-2.0 |
brodock/sunuo | scripts/legacy/Mobiles/Animals/Mounts/FireSteed.cs | 1905 | using System;
using Server.Items;
using Server.Mobiles;
namespace Server.Mobiles
{
[CorpseName( "a fire steed corpse" )]
public class FireSteed : BaseMount
{
[Constructable]
public FireSteed() : this( "a fire steed" )
{
}
[Constructable]
public FireSteed( string name ) : base( name, 0xBE, 0x3E9E, AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4 )
{
BaseSoundID = 0xA8;
SetStr( 376, 400 );
SetDex( 91, 120 );
SetInt( 291, 300 );
SetHits( 226, 240 );
SetDamage( 11, 30 );
SetDamageType( ResistanceType.Physical, 20 );
SetDamageType( ResistanceType.Fire, 80 );
SetResistance( ResistanceType.Physical, 30, 40 );
SetResistance( ResistanceType.Fire, 70, 80 );
SetResistance( ResistanceType.Cold, 20, 30 );
SetResistance( ResistanceType.Poison, 30, 40 );
SetResistance( ResistanceType.Energy, 30, 40 );
SetSkill( SkillName.MagicResist, 100.0, 120.0 );
SetSkill( SkillName.Tactics, 100.0 );
SetSkill( SkillName.Wrestling, 100.0 );
Fame = 20000;
Karma = -20000;
Tamable = true;
ControlSlots = 2;
MinTameSkill = 106.0;
PackGold( 300 );
PackItem( new SulfurousAsh( Utility.RandomMinMax( 100, 250 ) ) );
PackItem( new Ruby( Utility.RandomMinMax( 10, 30 ) ) );
}
public override bool HasBreath{ get{ return true; } } // fire breath enabled
public override FoodType FavoriteFood{ get{ return FoodType.Meat; } }
public override PackInstinct PackInstinct{ get{ return PackInstinct.Daemon | PackInstinct.Equine; } }
public FireSteed( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
/*int version = */reader.ReadInt();
if ( BaseSoundID <= 0 )
BaseSoundID = 0xA8;
}
}
} | gpl-2.0 |
sourceleaker/gaycore | src/server/scripts/Northrend/Ulduar/Ulduar/instance_ulduar.cpp | 26429 | /*
* Copyright (C) 2008-2011 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 "InstanceScript.h"
#include "ulduar.h"
static DoorData const doorData[] =
{
{ GO_LEVIATHAN_DOOR, BOSS_LEVIATHAN, DOOR_TYPE_ROOM, BOUNDARY_S },
{ GO_XT_002_DOOR, BOSS_XT002, DOOR_TYPE_ROOM, BOUNDARY_S },
{ 0, 0, DOOR_TYPE_ROOM, BOUNDARY_NONE },
};
class instance_ulduar : public InstanceMapScript
{
public:
instance_ulduar() : InstanceMapScript("instance_ulduar", 603) { }
struct instance_ulduar_InstanceMapScript : public InstanceScript
{
instance_ulduar_InstanceMapScript(InstanceMap* map) : InstanceScript(map) { }
uint32 Encounter[MAX_ENCOUNTER];
std::string m_strInstData;
// Creatures
uint64 LeviathanGUID;
uint64 IgnisGUID;
uint64 RazorscaleGUID;
uint64 RazorscaleController;
uint64 RazorHarpoonGUIDs[4];
uint64 ExpeditionCommanderGUID;
uint64 XT002GUID;
uint64 XTToyPileGUIDs[4];
uint64 AssemblyGUIDs[3];
uint64 KologarnGUID;
uint64 AuriayaGUID;
uint64 MimironGUID;
uint64 HodirGUID;
uint64 ThorimGUID;
uint64 FreyaGUID;
uint64 KeeperGUIDs[3];
uint64 VezaxGUID;
uint64 YoggSaronGUID;
uint64 AlgalonGUID;
uint64 LeviathanGateGUID;
uint64 VezaxDoorGUID;
// GameObjects
uint64 KologarnChestGUID;
uint64 KologarnBridgeGUID;
uint64 KologarnDoorGUID;
uint64 ThorimChestGUID;
uint64 HodirRareCacheGUID;
uint64 HodirChestGUID;
uint64 HodirDoorGUID;
uint64 HodirIceDoorGUID;
uint64 ArchivumDoorGUID;
// Miscellaneous
uint32 TeamInInstance;
uint32 HodirRareCacheData;
uint32 ColossusData;
uint8 elderCount;
bool conSpeedAtory;
bool Unbroken;
std::set<uint64> mRubbleSpawns;
void Initialize()
{
SetBossNumber(MAX_ENCOUNTER);
LoadDoorData(doorData);
IgnisGUID = 0;
RazorscaleGUID = 0;
RazorscaleController = 0;
ExpeditionCommanderGUID = 0;
XT002GUID = 0;
KologarnGUID = 0;
AuriayaGUID = 0;
MimironGUID = 0;
HodirGUID = 0;
ThorimGUID = 0;
FreyaGUID = 0;
VezaxGUID = 0;
YoggSaronGUID = 0;
AlgalonGUID = 0;
KologarnChestGUID = 0;
KologarnBridgeGUID = 0;
ThorimChestGUID = 0;
HodirRareCacheGUID = 0;
HodirChestGUID = 0;
LeviathanGateGUID = 0;
VezaxDoorGUID = 0;
HodirDoorGUID = 0;
HodirIceDoorGUID = 0;
ArchivumDoorGUID = 0;
TeamInInstance = 0;
HodirRareCacheData = 0;
ColossusData = 0;
elderCount = 0;
conSpeedAtory = false;
Unbroken = true;
memset(Encounter, 0, sizeof(Encounter));
memset(XTToyPileGUIDs, 0, sizeof(XTToyPileGUIDs));
memset(AssemblyGUIDs, 0, sizeof(AssemblyGUIDs));
memset(RazorHarpoonGUIDs, 0, sizeof(RazorHarpoonGUIDs));
memset(KeeperGUIDs, 0, sizeof(KeeperGUIDs));
}
bool IsEncounterInProgress() const
{
for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
{
if (Encounter[i] == IN_PROGRESS)
return true;
}
return false;
}
void OnPlayerEnter(Player* player)
{
if (!TeamInInstance)
TeamInInstance = player->GetTeam();
}
void OnCreatureCreate(Creature* creature)
{
if (!TeamInInstance)
{
Map::PlayerList const& Players = instance->GetPlayers();
if (!Players.isEmpty())
if (Player* player = Players.begin()->getSource())
TeamInInstance = player->GetTeam();
}
switch (creature->GetEntry())
{
case NPC_LEVIATHAN:
LeviathanGUID = creature->GetGUID();
break;
case NPC_IGNIS:
IgnisGUID = creature->GetGUID();
break;
case NPC_RAZORSCALE:
RazorscaleGUID = creature->GetGUID();
break;
case NPC_RAZORSCALE_CONTROLLER:
RazorscaleController = creature->GetGUID();
break;
case NPC_EXPEDITION_COMMANDER:
ExpeditionCommanderGUID = creature->GetGUID();
break;
case NPC_XT002:
XT002GUID = creature->GetGUID();
break;
case NPC_XT_TOY_PILE:
for (uint8 i = 0; i < 4; ++i)
if (!XTToyPileGUIDs[i])
XTToyPileGUIDs[i] = creature->GetGUID();
break;
// Assembly of Iron
case NPC_STEELBREAKER:
AssemblyGUIDs[0] = creature->GetGUID();
break;
case NPC_MOLGEIM:
AssemblyGUIDs[1] = creature->GetGUID();
break;
case NPC_BRUNDIR:
AssemblyGUIDs[2] = creature->GetGUID();
break;
// Freya's Keeper
case NPC_IRONBRANCH:
KeeperGUIDs[0] = creature->GetGUID();
if (GetBossState(BOSS_FREYA) == DONE)
creature->DespawnOrUnsummon();
break;
case NPC_BRIGHTLEAF:
KeeperGUIDs[1] = creature->GetGUID();
if (GetBossState(BOSS_FREYA) == DONE)
creature->DespawnOrUnsummon();
break;
case NPC_STONEBARK:
KeeperGUIDs[2] = creature->GetGUID();
if (GetBossState(BOSS_FREYA) == DONE)
creature->DespawnOrUnsummon();
break;
// Kologarn
case NPC_KOLOGARN:
KologarnGUID = creature->GetGUID();
break;
case NPC_AURIAYA:
AuriayaGUID = creature->GetGUID();
break;
case NPC_MIMIRON:
MimironGUID = creature->GetGUID();
break;
case NPC_HODIR:
HodirGUID = creature->GetGUID();
break;
case NPC_THORIM:
ThorimGUID = creature->GetGUID();
break;
case NPC_FREYA:
FreyaGUID = creature->GetGUID();
break;
case NPC_VEZAX:
VezaxGUID = creature->GetGUID();
break;
case NPC_YOGGSARON:
YoggSaronGUID = creature->GetGUID();
break;
case NPC_ALGALON:
AlgalonGUID = creature->GetGUID();
break;
// Hodir's Helper NPCs
case NPC_EIVI_NIGHTFEATHER:
if (TeamInInstance == HORDE)
creature->UpdateEntry(NPC_TOR_GREYCLOUD, HORDE);
break;
case NPC_ELLIE_NIGHTFEATHER:
if (TeamInInstance == HORDE)
creature->UpdateEntry(NPC_KAR_GREYCLOUD, HORDE);
break;
case NPC_ELEMENTALIST_MAHFUUN:
if (TeamInInstance == HORDE)
creature->UpdateEntry(NPC_SPIRITWALKER_TARA, HORDE);
break;
case NPC_ELEMENTALIST_AVUUN:
if (TeamInInstance == HORDE)
creature->UpdateEntry(NPC_SPIRITWALKER_YONA, HORDE);
break;
case NPC_MISSY_FLAMECUFFS:
if (TeamInInstance == HORDE)
creature->UpdateEntry(NPC_AMIRA_BLAZEWEAVER, HORDE);
break;
case NPC_SISSY_FLAMECUFFS:
if (TeamInInstance == HORDE)
creature->UpdateEntry(NPC_VEESHA_BLAZEWEAVER, HORDE);
break;
case NPC_FIELD_MEDIC_PENNY:
if (TeamInInstance == HORDE)
creature->UpdateEntry(NPC_BATTLE_PRIEST_ELIZA, HORDE);
break;
case NPC_FIELD_MEDIC_JESSI:
if (TeamInInstance == HORDE)
creature->UpdateEntry(NPC_BATTLE_PRIEST_GINA, HORDE);
break;
}
}
void OnGameObjectCreate(GameObject* gameObject)
{
switch (gameObject->GetEntry())
{
case GO_KOLOGARN_CHEST_HERO:
case GO_KOLOGARN_CHEST:
KologarnChestGUID = gameObject->GetGUID();
break;
case GO_KOLOGARN_BRIDGE:
KologarnBridgeGUID = gameObject->GetGUID();
if (GetBossState(BOSS_KOLOGARN) == DONE)
HandleGameObject(0, false, gameObject);
break;
case GO_KOLOGARN_DOOR:
KologarnDoorGUID = gameObject->GetGUID();
break;
case GO_THORIM_CHEST_HERO:
case GO_THORIM_CHEST:
ThorimChestGUID = gameObject->GetGUID();
break;
case GO_HODIR_RARE_CACHE_OF_WINTER_HERO:
case GO_HODIR_RARE_CACHE_OF_WINTER:
HodirRareCacheGUID = gameObject->GetGUID();
break;
case GO_HODIR_CHEST_HERO:
case GO_HODIR_CHEST:
HodirChestGUID = gameObject->GetGUID();
break;
case GO_LEVIATHAN_DOOR:
AddDoor(gameObject, true);
break;
case GO_LEVIATHAN_GATE:
LeviathanGateGUID = gameObject->GetGUID();
if (GetBossState(BOSS_LEVIATHAN) == DONE)
gameObject->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE);
break;
case GO_XT_002_DOOR:
AddDoor(gameObject, true);
break;
case GO_VEZAX_DOOR:
VezaxDoorGUID = gameObject->GetGUID();
HandleGameObject(0, false, gameObject);
break;
case GO_RAZOR_HARPOON_1:
RazorHarpoonGUIDs[0] = gameObject->GetGUID();
break;
case GO_RAZOR_HARPOON_2:
RazorHarpoonGUIDs[1] = gameObject->GetGUID();
break;
case GO_RAZOR_HARPOON_3:
RazorHarpoonGUIDs[2] = gameObject->GetGUID();
break;
case GO_RAZOR_HARPOON_4:
RazorHarpoonGUIDs[3] = gameObject->GetGUID();
break;
case GO_MOLE_MACHINE:
if (GetBossState(BOSS_RAZORSCALE) == IN_PROGRESS)
gameObject->SetGoState(GO_STATE_ACTIVE);
case GO_HODIR_DOOR:
HodirDoorGUID = gameObject->GetGUID();
break;
case GO_HODIR_ICE_DOOR:
HodirIceDoorGUID = gameObject->GetGUID();
break;
case GO_ARCHIVUM_DOOR:
ArchivumDoorGUID = gameObject->GetGUID();
if (GetBossState(BOSS_ASSEMBLY_OF_IRON) != DONE)
HandleGameObject(ArchivumDoorGUID, false);
break;
}
}
void OnGameObjectRemove(GameObject* gameObject)
{
switch (gameObject->GetEntry())
{
case GO_LEVIATHAN_DOOR:
AddDoor(gameObject, false);
break;
case GO_XT_002_DOOR:
AddDoor(gameObject, false);
default:
break;
}
}
void OnCreatureDeath(Creature* creature)
{
switch (creature->GetEntry())
{
case NPC_CORRUPTED_SERVITOR:
case NPC_MISGUIDED_NYMPH:
case NPC_GUARDIAN_LASHER:
case NPC_FOREST_SWARMER:
case NPC_MANGROVE_ENT:
case NPC_IRONROOT_LASHER:
case NPC_NATURES_BLADE:
case NPC_GUARDIAN_OF_LIFE:
if (!conSpeedAtory)
{
DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, CRITERIA_CON_SPEED_ATORY);
conSpeedAtory = true;
}
break;
default:
break;
}
}
void ProcessEvent(WorldObject* /*gameObject*/, uint32 eventId)
{
// Flame Leviathan's Tower Event triggers
Creature* FlameLeviathan = instance->GetCreature(LeviathanGUID);
if (FlameLeviathan && FlameLeviathan->isAlive()) // No leviathan, no event triggering ;)
switch (eventId)
{
case EVENT_TOWER_OF_STORM_DESTROYED:
FlameLeviathan->AI()->DoAction(ACTION_TOWER_OF_STORM_DESTROYED);
break;
case EVENT_TOWER_OF_FROST_DESTROYED:
FlameLeviathan->AI()->DoAction(ACTION_TOWER_OF_FROST_DESTROYED);
break;
case EVENT_TOWER_OF_FLAMES_DESTROYED:
FlameLeviathan->AI()->DoAction(ACTION_TOWER_OF_FLAMES_DESTROYED);
break;
case EVENT_TOWER_OF_LIFE_DESTROYED:
FlameLeviathan->AI()->DoAction(ACTION_TOWER_OF_LIFE_DESTROYED);
break;
}
}
bool SetBossState(uint32 type, EncounterState state)
{
if (!InstanceScript::SetBossState(type, state))
return false;
switch (type)
{
case BOSS_LEVIATHAN:
case BOSS_IGNIS:
case BOSS_RAZORSCALE:
case BOSS_XT002:
case BOSS_AURIAYA:
case BOSS_MIMIRON:
case BOSS_FREYA:
break;
case BOSS_ASSEMBLY_OF_IRON:
if (state == DONE)
HandleGameObject(ArchivumDoorGUID, true);
break;
case BOSS_VEZAX:
if (state == DONE)
HandleGameObject(VezaxDoorGUID, true);
break;
case BOSS_YOGGSARON:
break;
case BOSS_KOLOGARN:
if (state == DONE)
{
if (GameObject* gameObject = instance->GetGameObject(KologarnChestGUID))
{
gameObject->SetRespawnTime(gameObject->GetRespawnDelay());
gameObject->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
}
HandleGameObject(KologarnBridgeGUID, false);
}
if (state == IN_PROGRESS)
HandleGameObject(KologarnDoorGUID, false);
else
HandleGameObject(KologarnDoorGUID, true);
break;
case BOSS_HODIR:
if (state == DONE)
{
if (GameObject* HodirRareCache = instance->GetGameObject(HodirRareCacheGUID))
if (GetData(DATA_HODIR_RARE_CACHE))
HodirRareCache->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
if (GameObject* HodirChest = instance->GetGameObject(HodirChestGUID))
HodirChest->SetRespawnTime(HodirChest->GetRespawnDelay());
HandleGameObject(HodirDoorGUID, true);
HandleGameObject(HodirIceDoorGUID, true);
}
break;
case BOSS_THORIM:
if (state == DONE)
if (GameObject* gameObject = instance->GetGameObject(ThorimChestGUID))
gameObject->SetRespawnTime(gameObject->GetRespawnDelay());
break;
}
return true;
}
void SetData(uint32 type, uint32 data)
{
switch (type)
{
case DATA_COLOSSUS:
ColossusData = data;
if (data == 2)
{
if (Creature* Leviathan = instance->GetCreature(LeviathanGUID))
Leviathan->AI()->DoAction(ACTION_MOVE_TO_CENTER_POSITION);
if (GameObject* gameObject = instance->GetGameObject(LeviathanGateGUID))
gameObject->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE);
SaveToDB();
}
break;
case DATA_HODIR_RARE_CACHE:
HodirRareCacheData = data;
if (!HodirRareCacheData)
{
if (Creature* Hodir = instance->GetCreature(HodirGUID))
if (GameObject* gameObject = instance->GetGameObject(HodirRareCacheGUID))
Hodir->RemoveGameObject(gameObject, false);
}
break;
case DATA_UNBROKEN:
Unbroken = bool(data);
break;
default:
break;
}
}
void SetData64(uint32 /*type*/, uint64 /*data*/)
{
}
uint64 GetData64(uint32 data)
{
switch (data)
{
case BOSS_LEVIATHAN:
return LeviathanGUID;
case BOSS_IGNIS:
return IgnisGUID;
case BOSS_RAZORSCALE:
return RazorscaleGUID;
case DATA_RAZORSCALE_CONTROL:
return RazorscaleController;
case BOSS_XT002:
return XT002GUID;
case DATA_TOY_PILE_0:
case DATA_TOY_PILE_1:
case DATA_TOY_PILE_2:
case DATA_TOY_PILE_3:
return XTToyPileGUIDs[data - DATA_TOY_PILE_0];
case BOSS_KOLOGARN:
return KologarnGUID;
case BOSS_AURIAYA:
return AuriayaGUID;
case BOSS_MIMIRON:
return MimironGUID;
case BOSS_HODIR:
return HodirGUID;
case BOSS_THORIM:
return ThorimGUID;
case BOSS_FREYA:
return FreyaGUID;
case BOSS_VEZAX:
return VezaxGUID;
case BOSS_YOGGSARON:
return YoggSaronGUID;
case BOSS_ALGALON:
return AlgalonGUID;
// Razorscale expedition commander
case DATA_EXPEDITION_COMMANDER:
return ExpeditionCommanderGUID;
case GO_RAZOR_HARPOON_1:
return RazorHarpoonGUIDs[0];
case GO_RAZOR_HARPOON_2:
return RazorHarpoonGUIDs[1];
case GO_RAZOR_HARPOON_3:
return RazorHarpoonGUIDs[2];
case GO_RAZOR_HARPOON_4:
return RazorHarpoonGUIDs[3];
// Assembly of Iron
case BOSS_STEELBREAKER:
return AssemblyGUIDs[0];
case BOSS_MOLGEIM:
return AssemblyGUIDs[1];
case BOSS_BRUNDIR:
return AssemblyGUIDs[2];
// Freya's Keepers
case BOSS_BRIGHTLEAF:
return KeeperGUIDs[0];
case BOSS_IRONBRANCH:
return KeeperGUIDs[1];
case BOSS_STONEBARK:
return KeeperGUIDs[2];
}
return 0;
}
uint32 GetData(uint32 type)
{
switch (type)
{
case DATA_COLOSSUS:
return ColossusData;
case DATA_HODIR_RARE_CACHE:
return HodirRareCacheData;
case DATA_UNBROKEN:
return uint32(Unbroken);
default:
break;
}
return 0;
}
std::string GetSaveData()
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
saveStream << "U U " << GetBossSaveData() << GetData(DATA_COLOSSUS);
OUT_SAVE_INST_DATA_COMPLETE;
return saveStream.str();
}
void Load(char const* strIn)
{
if (!strIn)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(strIn);
char dataHead1, dataHead2;
std::istringstream loadStream(strIn);
loadStream >> dataHead1 >> dataHead2;
if (dataHead1 == 'U' && dataHead2 == 'U')
{
for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
{
uint32 tmpState;
loadStream >> tmpState;
if (tmpState == IN_PROGRESS || tmpState > SPECIAL)
tmpState = NOT_STARTED;
if (i == DATA_COLOSSUS)
SetData(i, tmpState);
else
SetBossState(i, EncounterState(tmpState));
}
}
OUT_LOAD_INST_DATA_COMPLETE;
}
};
InstanceScript* GetInstanceScript(InstanceMap* map) const
{
return new instance_ulduar_InstanceMapScript(map);
}
};
void AddSC_instance_ulduar()
{
new instance_ulduar();
} | gpl-2.0 |
pulse-project/mmc-core | doc-doxy/html/search/classes_1.js | 2260 | var searchData=
[
['abstracttpl',['AbstractTpl',['../classAbstractTpl.html',1,'']]],
['actionconfirmitem',['ActionConfirmItem',['../classActionConfirmItem.html',1,'']]],
['actionencapsulator',['ActionEncapsulator',['../classActionEncapsulator.html',1,'']]],
['actionitem',['ActionItem',['../classActionItem.html',1,'']]],
['actionpopupitem',['ActionPopupItem',['../classActionPopupItem.html',1,'']]],
['ajaxfilter',['AjaxFilter',['../classAjaxFilter.html',1,'']]],
['ajaxnavbar',['AjaxNavBar',['../classAjaxNavBar.html',1,'']]],
['ajaxpaginator',['AjaxPaginator',['../classAjaxPaginator.html',1,'']]],
['auditcodesmanager',['AuditCodesManager',['../classAuditCodesManager.html',1,'']]],
['auditconfig',['AuditConfig',['../classmmc_1_1core_1_1audit_1_1config_1_1AuditConfig.html',1,'mmc::core::audit::config']]],
['auditrecord',['AuditRecord',['../classmmc_1_1core_1_1audit_1_1record_1_1AuditRecord.html',1,'mmc::core::audit::record']]],
['auditrecorddb',['AuditRecordDB',['../classmmc_1_1core_1_1audit_1_1record_1_1AuditRecordDB.html',1,'mmc::core::audit::record']]],
['auditwriterdb',['AuditWriterDB',['../classmmc_1_1core_1_1audit_1_1writers_1_1AuditWriterDB.html',1,'mmc::core::audit::writers']]],
['auditwriteri',['AuditWriterI',['../classmmc_1_1core_1_1audit_1_1writernull_1_1AuditWriterI.html',1,'mmc::core::audit::writernull']]],
['auditwriternull',['AuditWriterNull',['../classmmc_1_1core_1_1audit_1_1writernull_1_1AuditWriterNull.html',1,'mmc::core::audit::writernull']]],
['authenticationerror',['AuthenticationError',['../classmmc_1_1plugins_1_1base_1_1auth_1_1AuthenticationError.html',1,'mmc::plugins::base::auth']]],
['authenticationmanager',['AuthenticationManager',['../classmmc_1_1plugins_1_1base_1_1auth_1_1AuthenticationManager.html',1,'mmc::plugins::base::auth']]],
['authenticationtoken',['AuthenticationToken',['../classmmc_1_1plugins_1_1base_1_1auth_1_1AuthenticationToken.html',1,'mmc::plugins::base::auth']]],
['authenticatorconfig',['AuthenticatorConfig',['../classmmc_1_1plugins_1_1base_1_1auth_1_1AuthenticatorConfig.html',1,'mmc::plugins::base::auth']]],
['authenticatori',['AuthenticatorI',['../classmmc_1_1plugins_1_1base_1_1auth_1_1AuthenticatorI.html',1,'mmc::plugins::base::auth']]]
];
| gpl-2.0 |
TheTypoMaster/calligra | braindump/src/View.cpp | 13676 | /*
* Copyright (c) 2009,2010 Cyrille Berger <cberger@cberger.net>
*
* 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, or (at your option) any later version of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "View.h"
#include <QGridLayout>
#include <QString>
#include <QVariant>
#include <QToolBar>
#include <QScrollBar>
#include <QTimer>
#include <QApplication>
#include <QClipboard>
#include <QPluginLoader>
#include <QMimeData>
#include <QDebug>
#include <QAction>
#include <kactioncollection.h>
#include <kstatusbar.h>
#include <KPluginFactory>
#include <KoCanvasControllerWidget.h>
#include <KoToolManager.h>
#include <KoToolProxy.h>
#include <KoZoomHandler.h>
#include <KoShapeController.h>
#include <KoShapeManager.h>
#include <KoSelection.h>
#include <KoMainWindow.h>
#include <KoDockRegistry.h>
#include <KoShapeLayer.h>
#include <KoDrag.h>
#include <KoCutController.h>
#include <KoCopyController.h>
#include "KoZoomController.h"
#include <KoZoomAction.h>
#include <KoIcon.h>
#include "KoToolBoxFactory.h"
#include <KoJsonTrader.h>
#include "KoOdf.h"
#include "KoShapeGroup.h"
#include "KoShapeDeleteCommand.h"
#include "KoShapeCreateCommand.h"
#include "KoShapeGroupCommand.h"
#include "KoShapeUngroupCommand.h"
#include "Canvas.h"
#include "RootSection.h"
#include "Section.h"
#include "ViewManager.h"
#include "import/DockerManager.h"
#include "MainWindow.h"
#include "SectionContainer.h"
#include "SectionsBoxDock.h"
#include "Layout.h"
#include "SectionPropertiesDock.h"
#include "commands/RememberPositionCommand.h"
View::View(RootSection *document, MainWindow* parent)
: QWidget(parent)
, m_doc(document)
, m_canvas(0)
, m_activeSection(0)
, m_mainWindow(parent)
, m_cutController(0)
, m_copyController(0)
{
setXMLFile("braindumpview.rc");
m_doc->viewManager()->addView(this);
m_editPaste = actionCollection()->addAction(KStandardAction::Paste, "edit_paste", this, SLOT(editPaste()));
m_editCut = actionCollection()->addAction(KStandardAction::Cut, "edit_cut", 0, 0);
m_editCopy = actionCollection()->addAction(KStandardAction::Copy, "edit_copy", 0, 0);
initGUI();
initActions();
loadExtensions();
if(m_doc->sections().count() > 0) {
setActiveSection(m_doc->sections()[0]);
} else {
setActiveSection(0);
}
m_doc->viewManager()->viewHasFocus(this);
}
View::~View()
{
m_doc->viewManager()->removeView(this);
KoToolManager::instance()->removeCanvasController(m_canvasController);
delete m_zoomController;
}
Section* View::activeSection() const
{
return m_activeSection;
}
void View::initGUI()
{
// add all plugins.
foreach(const QString & docker, KoDockRegistry::instance()->keys()) {
qDebug() << "Creating docker: " << docker;
KoDockFactoryBase *factory = KoDockRegistry::instance()->value(docker);
m_mainWindow->createDockWidget(factory);
}
// Init the widgets
QGridLayout * gridLayout = new QGridLayout(this);
gridLayout->setMargin(0);
gridLayout->setSpacing(0);
setLayout(gridLayout);
m_canvasController = new KoCanvasControllerWidget(actionCollection(), this);
m_canvasController->setCanvasMode(KoCanvasController::Infinite);
createCanvas(0);
KoToolManager::instance()->addController(m_canvasController);
KoToolManager::instance()->registerTools(actionCollection(), m_canvasController);
m_zoomController = new KoZoomController(m_canvasController, &m_zoomHandler, actionCollection());
connect(m_zoomController, SIGNAL(zoomChanged(KoZoomMode::Mode,qreal)),
this, SLOT(slotZoomChanged(KoZoomMode::Mode,qreal)));
m_zoomAction = m_zoomController->zoomAction();
m_mainWindow->addStatusBarItem(m_zoomAction->createWidget(m_mainWindow->statusBar()), 0, this);
m_zoomController->setZoomMode(KoZoomMode::ZOOM_WIDTH);
gridLayout->addWidget(m_canvasController, 1, 1);
connect(m_canvasController->proxyObject, SIGNAL(canvasMousePositionChanged(QPoint)),
this, SLOT(updateMousePosition(QPoint)));
KoToolBoxFactory toolBoxFactory;
m_mainWindow->createDockWidget(&toolBoxFactory);
connect(m_canvasController, SIGNAL(toolOptionWidgetsChanged(QList<QPointer<QWidget> >)), m_mainWindow->dockerManager(), SLOT(newOptionWidgets(QList<QPointer<QWidget> >)));
SectionsBoxDockFactory structureDockerFactory;
m_sectionsBoxDock = qobject_cast<SectionsBoxDock*>(m_mainWindow->createDockWidget(&structureDockerFactory));
Q_ASSERT(m_sectionsBoxDock);
m_sectionsBoxDock->setup(m_doc, this);
SectionPropertiesDockFactory sectionPropertiesDockerFactory;
m_sectionPropertiesDock = qobject_cast<SectionPropertiesDock*>(m_mainWindow->createDockWidget(§ionPropertiesDockerFactory));
Q_ASSERT(m_sectionPropertiesDock);
m_sectionPropertiesDock->setRootSection(m_doc);
KoToolManager::instance()->requestToolActivation(m_canvasController);
show();
}
void View::initActions()
{
connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));
clipboardDataChanged();
actionCollection()->addAction(KStandardAction::SelectAll, "edit_select_all", this, SLOT(editSelectAll()));
actionCollection()->addAction(KStandardAction::Deselect, "edit_deselect_all", this, SLOT(editDeselectAll()));
m_deleteSelectionAction = new QAction(koIcon("edit-delete"), i18n("D&elete"), this);
actionCollection()->addAction("edit_delete", m_deleteSelectionAction);
actionCollection()->setDefaultShortcut(m_deleteSelectionAction, QKeySequence("Del"));
connect(m_deleteSelectionAction, SIGNAL(triggered()), this, SLOT(editDeleteSelection()));
// Shapes menu
// TODO: get an icon "edit-duplicate"
QAction *actionDuplicate = new QAction(i18nc("Duplicate selection", "&Duplicate"), this);
actionCollection()->addAction("shapes_duplicate", actionDuplicate);
actionCollection()->setDefaultShortcut(actionDuplicate, QKeySequence("Ctrl+D"));
connect(actionDuplicate, SIGNAL(triggered()), this, SLOT(selectionDuplicate()));
m_groupShapes = new QAction(koIcon("object-group"), i18n("Group Shapes"), this);
actionCollection()->addAction("shapes_group", m_groupShapes);
actionCollection()->setDefaultShortcut(m_groupShapes, QKeySequence("Ctrl+G"));
connect(m_groupShapes, SIGNAL(triggered()), this, SLOT(groupSelection()));
m_ungroupShapes = new QAction(koIcon("object-ungroup"), i18n("Ungroup Shapes"), this);
actionCollection()->addAction("shapes_ungroup", m_ungroupShapes);
actionCollection()->setDefaultShortcut(m_ungroupShapes, QKeySequence("Ctrl+Shift+G"));
connect(m_ungroupShapes, SIGNAL(triggered()), this, SLOT(ungroupSelection()));
}
void View::loadExtensions()
{
const QList<QPluginLoader *> offers = KoJsonTrader::self()->query("Braindump/Extensions", QString());
foreach(QPluginLoader *pluginLoader, offers) {
KPluginFactory *factory = qobject_cast<KPluginFactory *>(pluginLoader->instance());
KXMLGUIClient *plugin = dynamic_cast<KXMLGUIClient*>(factory->create<QObject>(this, QVariantList()));
if (plugin) {
insertChildClient(plugin);
}
}
}
void View::editPaste()
{
m_canvas->toolProxy()->paste();
}
void View::editDeleteSelection()
{
m_canvas->toolProxy()->deleteSelection();
}
void View::editSelectAll()
{
KoSelection* selection = canvas()->shapeManager()->selection();
if(!selection)
return;
KoShapeLayer *layer = activeSection()->sectionContainer()->layer();
QList<KoShape*> layerShapes(layer->shapes());
foreach(KoShape * layerShape, layerShapes) {
selection->select(layerShape);
layerShape->update();
}
}
void View::editDeselectAll()
{
KoSelection* selection = canvas()->shapeManager()->selection();
if(selection)
selection->deselectAll();
canvas()->update();
}
void View::slotZoomChanged(KoZoomMode::Mode mode, qreal zoom)
{
Q_UNUSED(mode);
Q_UNUSED(zoom);
canvas()->updateOriginAndSize();
canvas()->update();
}
void View::createCanvas(Section* _currentSection)
{
Canvas* canvas = new Canvas(this, m_doc, _currentSection);
m_canvasController->setCanvas(canvas);
// No need to delete the current canvas, it will be deleted in Viewport::setCanvas (flake/KoCanvasController_p.cpp)
m_canvas = canvas;
delete m_cutController;
m_cutController = new KoCutController(m_canvas, m_editCut);
delete m_copyController;
m_copyController = new KoCopyController(m_canvas, m_editCopy);
connect(m_canvas, SIGNAL(canvasReceivedFocus()), SLOT(canvasReceivedFocus()));
connect(m_canvas, SIGNAL(documentRect(QRectF)), SLOT(documentRectChanged(QRectF)));
connect(m_canvasController->proxyObject, SIGNAL(moveDocumentOffset(QPoint)),
m_canvas, SLOT(setDocumentOffset(QPoint)));
connect(m_canvas->toolProxy(), SIGNAL(toolChanged(QString)), this, SLOT(clipboardDataChanged()));
m_canvas->updateOriginAndSize();
setEnabled(_currentSection);
}
void View::setActiveSection(Section* page)
{
m_activeSection = page;
m_doc->setCurrentSection(page);
createCanvas(m_activeSection);
if(m_activeSection) {
documentRectChanged(m_activeSection->layout()->boundingBox());
}
m_sectionsBoxDock->updateGUI();
m_sectionPropertiesDock->setSection(m_activeSection);
}
void View::updateMousePosition(const QPoint& /*position*/)
{
QPoint canvasOffset(m_canvasController->canvasOffsetX(), m_canvasController->canvasOffsetY());
// the offset is positive it the canvas is shown fully visible
canvasOffset.setX(canvasOffset.x() < 0 ? canvasOffset.x() : 0);
canvasOffset.setY(canvasOffset.y() < 0 ? canvasOffset.y() : 0);
}
void View::clipboardDataChanged()
{
const QMimeData* data = QApplication::clipboard()->mimeData();
bool paste = false;
if(data) {
// TODO see if we can use the KoPasteController instead of having to add this feature in each calligra app.
QStringList mimeTypes = m_canvas->toolProxy()->supportedPasteMimeTypes();
mimeTypes << KoOdf::mimeType(KoOdf::Graphics);
mimeTypes << KoOdf::mimeType(KoOdf::Presentation);
foreach(const QString & mimeType, mimeTypes) {
if(data->hasFormat(mimeType)) {
paste = true;
break;
}
}
}
m_editPaste->setEnabled(paste);
}
void View::focusInEvent(QFocusEvent * event)
{
QWidget::focusInEvent(event);
m_doc->viewManager()->viewHasFocus(this);
}
void View::canvasReceivedFocus()
{
m_doc->viewManager()->viewHasFocus(this);
}
void View::documentRectChanged(const QRectF& bb)
{
QSizeF pageSize(400, 400);
// Make sure we never use an empty size
if(!bb.isNull() && !bb.isEmpty()) {
pageSize = bb.size();
}
m_zoomController->setPageSize(pageSize);
m_zoomController->setDocumentSize(pageSize);
}
void View::selectionDuplicate()
{
m_canvas->toolProxy()->copy();
m_canvas->toolProxy()->paste();
}
void View::groupSelection()
{
KoSelection* selection = m_canvas->shapeManager()->selection();
if(! selection)
return;
QList<KoShape*> selectedShapes = selection->selectedShapes(KoFlake::TopLevelSelection);
QList<KoShape*> groupedShapes;
// only group shapes with an unselected parent
foreach(KoShape * shape, selectedShapes) {
if(selectedShapes.contains(shape->parent()))
continue;
groupedShapes << shape;
}
KoShapeGroup *group = new KoShapeGroup();
if(selection->activeLayer())
selection->activeLayer()->addShape(group);
KUndo2Command *cmd = new KUndo2Command(kundo2_i18n("Group shapes"));
new KoShapeCreateCommand(m_activeSection->sectionContainer(), group, cmd);
new KoShapeGroupCommand(group, groupedShapes, cmd);
m_canvas->addCommand(cmd);
}
void View::ungroupSelection()
{
KoSelection* selection = m_canvas->shapeManager()->selection();
if(! selection)
return;
QList<KoShape*> selectedShapes = selection->selectedShapes(KoFlake::TopLevelSelection);
QList<KoShape*> containerSet;
// only ungroup shape containers with an unselected parent
foreach(KoShape * shape, selectedShapes) {
if(selectedShapes.contains(shape->parent()))
continue;
containerSet << shape;
}
KUndo2Command *cmd = new KUndo2Command(kundo2_i18n("Ungroup shapes"));
// add a ungroup command for each found shape container to the macro command
foreach(KoShape * shape, containerSet) {
KoShapeContainer *container = dynamic_cast<KoShapeContainer*>(shape);
if(container) {
new KoShapeUngroupCommand(container, container->shapes(), QList<KoShape*>(), cmd);
new KoShapeDeleteCommand(m_activeSection->sectionContainer(), container, cmd);
new RememberPositionCommand(container->shapes(), cmd);
}
}
m_canvas->addCommand(cmd);
}
#include "View.moc"
| gpl-2.0 |
mlloewen/chinhama | wp-content/plugins/host-php-info/info.php | 158 | <?php
if(function_exists("phpinfo")){
phpinfo();
}else{
?>Your host does not allow <code>phpinfo()</code>, please contect your host administrator.<?php
}
?> | gpl-2.0 |
relaciones-internacionales-journal/ojs-2-4-2 | ojs/plugins/themes/custom/index.php | 390 | <?php
/**
* @defgroup plugins_themes_custom
*/
/**
* @file plugins/themes/custom/index.php
*
* Copyright (c) 2003-2013 John Willinsky
* Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
*
* @ingroup plugins_themes_custom
* @brief Wrapper for "custom" theme plugin.
*
*/
require_once('CustomThemePlugin.inc.php');
return new CustomThemePlugin();
?>
| gpl-2.0 |
CA-IRIS/mn-iris | src/us/mn/state/dot/tms/client/camera/CameraManager.java | 7822 | /*
* IRIS -- Intelligent Roadway Information System
* Copyright (C) 2008-2018 Minnesota Department of Transportation
*
* 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.
*/
package us.mn.state.dot.tms.client.camera;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.JLabel;
import javax.swing.JPopupMenu;
import us.mn.state.dot.tms.Camera;
import us.mn.state.dot.tms.GeoLoc;
import us.mn.state.dot.tms.GeoLocHelper;
import us.mn.state.dot.tms.ItemStyle;
import us.mn.state.dot.tms.PlayList;
import us.mn.state.dot.tms.PlayListHelper;
import us.mn.state.dot.tms.VideoMonitor;
import us.mn.state.dot.tms.client.Session;
import us.mn.state.dot.tms.client.proxy.DeviceManager;
import us.mn.state.dot.tms.client.proxy.GeoLocManager;
import us.mn.state.dot.tms.client.proxy.ProxyDescriptor;
import us.mn.state.dot.tms.client.proxy.ProxySelectionModel;
import us.mn.state.dot.tms.client.proxy.ProxyView;
import us.mn.state.dot.tms.client.proxy.ProxyWatcher;
import us.mn.state.dot.tms.utils.I18N;
/**
* A camera manager is a container for SONAR camera objects.
*
* @author Douglas Lau
*/
public class CameraManager extends DeviceManager<Camera> {
/** Create a proxy descriptor */
static public ProxyDescriptor<Camera> descriptor(final Session s) {
return new ProxyDescriptor<Camera>(
s.getSonarState().getCamCache().getCameras(), true
) {
@Override
public CameraProperties createPropertiesForm(
Camera cam)
{
return new CameraProperties(s, cam);
}
@Override
public CameraForm makeTableForm() {
return new CameraForm(s);
}
};
}
/** Check if an array contains a camera */
static private boolean containsCam(Camera[] cams, Camera c) {
for (Camera cm: cams) {
if (c.equals(cm))
return true;
}
return false;
}
/** Camera dispatcher */
private final CameraDispatcher dispatcher;
/** Camera tab */
private final CameraTab tab;
/** Selected play list */
private PlayList play_list;
/** Play list watcher */
private final ProxyWatcher<PlayList> watcher;
/** Play list view */
private final ProxyView<PlayList> pl_view = new ProxyView<PlayList>() {
public void enumerationComplete() {
watchPersonalPlayList();
}
public void update(PlayList pl, String a) {
play_list = pl;
}
public void clear() {
play_list = null;
}
};
/** Watch user's personal play list */
private void watchPersonalPlayList() {
String n = "PL_" + session.getUser().getName();
PlayList pl = PlayListHelper.lookup(n);
if (pl != null)
watcher.setProxy(pl);
else if (session.isWritePermitted(PlayList.SONAR_TYPE, n)) {
session.getSonarState().getCamCache().getPlayLists()
.createObject(n);
}
}
/** Create a new camera manager */
public CameraManager(Session s, GeoLocManager lm) {
super(s, lm, descriptor(s), 13, ItemStyle.ACTIVE);
dispatcher = new CameraDispatcher(s, this);
tab = new CameraTab(s, this, dispatcher);
getSelectionModel().setAllowMultiple(true);
watcher = new ProxyWatcher<PlayList>(s.getSonarState()
.getCamCache().getPlayLists(), pl_view, true);
}
/** Initialize the manager */
@Override
public void initialize() {
watcher.initialize();
super.initialize();
}
/** Dispose of the manager */
@Override
public void dispose() {
super.dispose();
watcher.dispose();
}
/** Check if user can read cameras / video_monitors */
@Override
public boolean canRead() {
return super.canRead() &&
session.canRead(VideoMonitor.SONAR_TYPE);
}
/** Create a camera map tab */
@Override
public CameraTab createTab() {
return tab;
}
/** Create a theme for cameras */
@Override
protected CameraTheme createTheme() {
return new CameraTheme(this);
}
/** Check the style of the specified proxy */
@Override
public boolean checkStyle(ItemStyle is, Camera proxy) {
if (is == ItemStyle.PLAYLIST)
return inPlaylist(proxy);
else
return super.checkStyle(is, proxy);
}
/** Check if a camera style is visible */
@Override
protected boolean isStyleVisible(Camera proxy) {
return true;
}
/** Fill single selection popup */
@Override
protected void fillPopupSingle(JPopupMenu p, Camera c) {
ProxySelectionModel<Camera> sel_model = getSelectionModel();
p.add(new PublishAction(sel_model));
p.add(new UnpublishAction(sel_model));
p.addSeparator();
if (canEditPlayList(play_list)) {
if (inPlaylist(c))
p.add(new RemovePlaylistAction(this,sel_model));
else
p.add(new AddPlaylistAction(this, sel_model));
p.addSeparator();
}
}
/** Create a popup menu for multiple objects */
@Override
protected JPopupMenu createPopupMulti(int n_selected) {
ProxySelectionModel<Camera> sel_model = getSelectionModel();
JPopupMenu p = new JPopupMenu();
p.add(new JLabel(I18N.get("camera.title") + ": " +
n_selected));
p.addSeparator();
p.add(new PublishAction(sel_model));
p.add(new UnpublishAction(sel_model));
if (canEditPlayList(play_list)) {
p.addSeparator();
p.add(new AddPlaylistAction(this, sel_model));
p.add(new RemovePlaylistAction(this, sel_model));
}
return p;
}
/** Test if a camera is in the play list */
public boolean inPlaylist(Camera c) {
PlayList pl = play_list;
return pl != null && containsCam(pl.getCameras(), c);
}
/** Add a camera to the play list */
public void addPlaylist(Camera c) {
PlayList pl = play_list;
if (canEditPlayList(pl)) {
ArrayList<Camera> cams = new ArrayList<Camera>(
Arrays.asList(pl.getCameras()));
cams.add(c);
pl.setCameras(cams.toArray(new Camera[0]));
}
}
/** Check if the user can edit a play list */
private boolean canEditPlayList(PlayList pl) {
return session.isWritePermitted(pl, "cameras");
}
/** Remove a camera from the play list */
public void removePlaylist(Camera c) {
PlayList pl = play_list;
if (canEditPlayList(pl)) {
ArrayList<Camera> cams = new ArrayList<Camera>(
Arrays.asList(pl.getCameras()));
cams.remove(c);
pl.setCameras(cams.toArray(new Camera[0]));
}
}
/** Find the map geo location for a proxy */
@Override
protected GeoLoc getGeoLoc(Camera proxy) {
return proxy.getGeoLoc();
}
/** Select a camera */
public void selectCamera(Camera c) {
if (tab.isSelectedTab()) {
if (c != null)
getSelectionModel().setSelected(c);
else
getSelectionModel().clearSelection();
} else
dispatcher.selectMonitorCamera(c);
}
/** Select a play list on the selected camera */
public void selectMonitorPlayList(PlayList pl) {
if (pl != null)
watcher.setProxy(pl);
else
watchPersonalPlayList();
dispatcher.selectMonitorPlayList(pl);
}
/** Select a video monitor */
public void selectMonitor(VideoMonitor m) {
dispatcher.selectMonitor(m);
}
/** Select the next camera */
public void selectNextCamera() {
dispatcher.selectNextCamera();
}
/** Select the previous camera */
public void selectPreviousCamera() {
dispatcher.selectPreviousCamera();
}
/** Get the selected video monitor */
public VideoMonitor getSelectedMonitor() {
return dispatcher.getSelectedMonitor();
}
/** Get the description of a proxy */
@Override
public String getDescription(Camera proxy) {
Integer num = proxy.getCamNum();
if (num != null) {
return proxy.getName() + " - #" + num + " - " +
GeoLocHelper.getDescription(getGeoLoc(proxy));
} else
return super.getDescription(proxy);
}
}
| gpl-2.0 |
media6/cms6 | inc/admin_header.php | 592 | <?
header('Content-Type: text/html; charset=UTF-8');
if(!isset($_SESSION['REFERENCE_3'])) { $_SESSION['REFERENCE_3']=""; }
if(!isset($_SESSION['REFERENCE_2'])) { $_SESSION['REFERENCE_2']=""; }
if(!isset($_SESSION['REFERENCE_1'])) { $_SESSION['REFERENCE_1']=""; }
if(!isset($_SERVER['HTTP_REFERER'])) { $_SERVER['HTTP_REFERER']=""; }
$_SESSION['REFERENCE_3'] = $_SESSION['REFERENCE_2'];
$_SESSION['REFERENCE_2'] = $_SESSION['REFERENCE_1'];
$_SESSION['REFERENCE_1'] = $_SERVER['HTTP_REFERER'];
if(intval($_SESSION['ipt_user_id'])<=0) {
header('location: ../');
}
?> | gpl-2.0 |
joshmoore/openmicroscopy | components/insight/SRC/org/openmicroscopy/shoola/env/data/views/AdminViewImpl.java | 7499 | /*
* org.openmicroscopy.shoola.env.data.views.AdminViewImpl
*
*------------------------------------------------------------------------------
* Copyright (C) 2006-2010 University of Dundee. All rights reserved.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*------------------------------------------------------------------------------
*/
package org.openmicroscopy.shoola.env.data.views;
//Java imports
import java.io.File;
import java.util.List;
import java.util.Map;
//Third-party libraries
//Application-internal dependencies
import org.openmicroscopy.shoola.env.data.login.UserCredentials;
import org.openmicroscopy.shoola.env.data.model.AdminObject;
import org.openmicroscopy.shoola.env.data.views.calls.AdminLoader;
import org.openmicroscopy.shoola.env.data.views.calls.AdminSaver;
import org.openmicroscopy.shoola.env.event.AgentEventListener;
import pojos.DataObject;
import pojos.ExperimenterData;
import pojos.GroupData;
/**
* Implementation of the {@link AdminView} implementation.
*
* @author Jean-Marie Burel
* <a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a>
* @author Donald MacDonald
* <a href="mailto:donald@lifesci.dundee.ac.uk">donald@lifesci.dundee.ac.uk</a>
* @version 3.0
* <small>
* (<b>Internal version:</b> $Revision: $Date: $)
* </small>
* @since 3.0-Beta4
*/
class AdminViewImpl
implements AdminView
{
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#updateExperimenter(ExperimenterData,
* AgentEventListener)
*/
public CallHandle updateExperimenter(ExperimenterData exp,
AgentEventListener observer)
{
BatchCallTree cmd = new AdminLoader(exp,
AdminLoader.EXPERIMENTER_UPDATE);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#updateGroup(GroupData, int AgentEventListener)
*/
public CallHandle updateGroup(GroupData group, int permissions,
AgentEventListener observer)
{
BatchCallTree cmd = new AdminLoader(group, permissions);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#changePassword(String, String, AgentEventListener)
*/
public CallHandle changePassword(String oldPassword, String newPassword,
AgentEventListener observer)
{
BatchCallTree cmd = new AdminLoader(oldPassword, newPassword);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#getDiskSpace(Class, long, AgentEventListener)
*/
public CallHandle getDiskSpace(Class type, long id,
AgentEventListener observer)
{
BatchCallTree cmd = new AdminLoader(type, id);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#createExperimenters(AdminObject, AgentEventListener)
*/
public CallHandle createExperimenters(AdminObject object,
AgentEventListener observer)
{
BatchCallTree cmd = new AdminSaver(object);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#createGroup(AdminObject, AgentEventListener)
*/
public CallHandle createGroup(AdminObject object,
AgentEventListener observer)
{
BatchCallTree cmd = new AdminSaver(object);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#loadExperimenterGroups(long, AgentEventListener)
*/
public CallHandle loadExperimenterGroups(long groupID,
AgentEventListener observer)
{
BatchCallTree cmd = new AdminLoader(groupID, AdminLoader.GROUPS);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#loadExperimenters(long, AgentEventListener)
*/
public CallHandle loadExperimenters(long groupID,
AgentEventListener observer)
{
BatchCallTree cmd = new AdminLoader(groupID, AdminLoader.EXPERIMENTERS);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#deleteObjects(List, AgentEventListener)
*/
public CallHandle deleteObjects(List<DataObject> objects,
AgentEventListener observer)
{
BatchCallTree cmd = new AdminSaver(objects, AdminSaver.DELETE);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#updateExperimenters(Map, AgentEventListener)
*/
public CallHandle updateExperimenters(GroupData group,
Map<ExperimenterData, UserCredentials> experimenters,
AgentEventListener observer)
{
BatchCallTree cmd = new AdminLoader(group, experimenters);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#resetExperimentersPassword(AdminObject,
* AgentEventListener)
*/
public CallHandle resetExperimentersPassword(AdminObject object,
AgentEventListener observer)
{
BatchCallTree cmd = new AdminSaver(object);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#activateExperimenters(AdminObject, AgentEventListener)
*/
public CallHandle activateExperimenters(AdminObject object,
AgentEventListener observer)
{
BatchCallTree cmd = new AdminSaver(object);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#loadExperimenterPhoto(ExperimenterData,
* AgentEventListener)
*/
public CallHandle loadExperimenterPhoto(ExperimenterData experimenter,
AgentEventListener observer)
{
BatchCallTree cmd = new AdminLoader(experimenter,
AdminLoader.EXPERIMENTER_PHOTO);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#uploadExperimenterPhoto(ExperimenterData, File, String
* AgentEventListener)
*/
public CallHandle uploadExperimenterPhoto(ExperimenterData experimenter,
File photo, String format, AgentEventListener observer)
{
BatchCallTree cmd = new AdminLoader(experimenter, photo, format);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#getDiskSpace(Class, List, AgentEventListener)
*/
public CallHandle getDiskSpace(Class type, List<Long> ids,
AgentEventListener observer)
{
BatchCallTree cmd = new AdminLoader(type, ids);
return cmd.exec(observer);
}
/**
* Implemented as specified by the {@link AdminView} interface.
* @see AdminView#loadAdministrators(AgentEventListener)
*/
public CallHandle loadAdministrators(AgentEventListener observer)
{
return null;
}
}
| gpl-2.0 |
fbrusatti/g | config/initializers/devise.rb | 12785 | # Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
config.secret_key = 'b6dc1c9f11efa1e1973e3a0f03107c58c5265041ff2832fd1268ae170ecba0bcf2527396c019580ed11fa48c979af53d1ed3f48946be821329c211e7744464a6'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:token]` will
# enable it only for token authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# :token = Support basic authentication with token authentication key
# :token_options = Support token authentication with options as defined in
# http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# :http_auth and :token_auth by adding those symbols to the array below.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing :skip => :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments.
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = 'c5117dd4cebd6618bc2a70416bc53c863bfe14f1261b1a6930e8648d17ae86238de3069141cd215a392f5cca9ecbd55667ed0adca0b6ace80781f1167478c718'
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming his account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming his account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming his account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed new email is stored in
# unconfirmed email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# :secure => true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length. Default is 8..128.
config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Configuration for :token_authenticatable
# Defines name of the authentication token params key
# config.token_authentication_key = :auth_token
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(:scope => :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end
| gpl-2.0 |
AndrewLink/Stylekit | wp-content/themes/layerwp/layerswp/core/customizer/registration.php | 15853 | <?php /**
* Customizer Registration File
*
* This file is used to register panels, sections and controls
*
* @package Layers
* @since Layers 1.0.0
*/
class Layers_Customizer_Regsitrar {
public $customizer;
public $config;
public $prefix;
private static $instance; // stores singleton class
/**
* Get Instance creates a singleton class that's cached to stop duplicate instances
*/
public static function get_instance() {
if ( ! self::$instance ) {
self::$instance = new self();
self::$instance->init();
}
return self::$instance;
}
/**
* Construct empty on purpose
*/
private function __construct() {}
/**
* Init behaves like, and replaces, construct
*/
public function init() {
// Register the customizer object
global $wp_customize;
$this->customizer = $wp_customize;
// Set Prefix
$this->prefix = LAYERS_THEME_SLUG . '-';
// Grab the customizer config
$this->config = Layers_Customizer_Config::get_instance();
//Register the panels and sections based on this instance's config
// Start registration with the panels & sections
$this->register_panels( $this->config->panels );
$this->register_sections ( $this->config->sections );
// Move default sections into Layers Panels
$this->move_default_panels( $this->config->default_panels );
$this->move_default_sections( $this->config->default_sections );
$this->move_default_controls( $this->config->default_controls );
// Change 'Widgets' panel title to 'Edit Layout'
$wp_customize->add_panel(
'widgets', array(
'priority' => 0,
'title' => __('Edit Layout' , 'layerswp' ),
'description' => Layers_Customizer::get_instance()->render_builder_page_dropdown() . __('Use this area to add widgets to your page, use the (Layers) widgets for the Body section.' , 'layerswp' ),
)
);
}
/**
* Check whether or not panels are supported by the customizer
*
* @return boolean true if panels are supported
*/
function customizer_supports_panels(){
return ( class_exists( 'WP_Customize_Manager' ) && method_exists( 'WP_Customize_Manager', 'add_panel' ) ) || function_exists( 'wp_validate_boolean' );
}
/**
* Register Panels
*
* @panels array Array of panel config
*/
function register_panels( $panels = array() ){
// If there are no panels, return
if( empty( $panels ) ) return;
foreach( $panels as $panel_key => $panel_data ) {
// If panels are supported, add this as a panel
if( $this->customizer_supports_panels() ) {
// Add Panel.
if ( in_array( $panel_key, $this->customizer->panels() ) ) {
// Panel exists without 'layers-' prepended, so shouldn't be added.
continue;
}
else {
// Add Panel with 'layers-' prepended.
$this->customizer->add_panel( $this->prefix . $panel_key , $panel_data );
}
}
} // foreach panel
}
/**
* Register Sections
*
* @panel_key string Unique key for which panel this section belongs to
* @sections array Array of sections config
*/
public function register_sections( $sections = array() ){
// If there are no sections, return
if( empty( $sections ) ) return;
$section_priority = 150;
foreach( $sections as $section_key => $section_data ){
if( $this->customizer_supports_panels() && isset( $section_data[ 'panel' ] ) ) {
// Add Section.
if ( in_array( $section_data[ 'panel' ], $this->customizer->panels() ) ) {
// Panel exists without 'layers-' prepended, so add the section to that panel.
$section_data[ 'panel' ] = $section_data[ 'panel' ];
}
else {
// Panel exists with 'layers-' prepended, so add the section to that panel.
$section_data[ 'panel' ] = $this->prefix . $section_data[ 'panel' ];
}
}
if( !isset( $section_data[ 'priority' ] ) ) {
$section_data[ 'priority' ] = $section_priority;
}
$this->customizer->add_section(
$this->prefix . $section_key ,
$section_data
);
$section_priority++;
// Register Sections for this Panel
$this->register_controls ( $section_key , $this->config->controls );
}
}
/**
* Register Panels
*
* @panel_section_key string Unique key for which section this control belongs to
* @controls array Array of controls config
*/
public function register_controls( $panel_section_key = '' , $controls = array() ){
// If there are no sections, return
if( empty( $controls ) ) return;
// Make sure that there is actually section config for this panel
if( !isset( $controls[ $panel_section_key ] ) ) return;
$control_priority = 150;
foreach( $controls[ $panel_section_key ] as $control_key => $control_data ){
$setting_key = $this->prefix . $control_key;
// Add Control.
if ( $this->customizer->get_section( $panel_section_key ) ) {
// Section exists without 'layers-' prepended, so add control to it.
$control_data[ 'section' ] = $panel_section_key;
}
else {
// Section exists with 'layers-' prepended, so add control to it.
$control_data[ 'section' ] = $this->prefix . $panel_section_key;
}
// Set control priority to obey order of setup
$control_data[ 'priority' ] = $control_priority;
// Add the default into the control data so it can be accessed if needed.
$control_data[ 'default' ] = isset( $control_data['default'] ) ? $control_data['default'] : NULL ;
// Add Setting
$this->customizer->add_setting(
$setting_key,
array(
'default' => ( isset( $control_data['default'] ) ? $control_data['default'] : NULL ) ,
'type' => 'theme_mod',
'capability' => 'manage_options',
'sanitize_callback' => $this->add_sanitize_callback( $control_data )
)
);
if ( 'layers-select-images' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_Select_Image_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'layers-select-icons' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_Select_Icon_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'layers-seperator' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_Seperator_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'layers-heading' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_Heading_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'layers-color' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_Color_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'layers-checkbox' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_Checkbox_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'layers-select' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_Select_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'layers-textarea' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_Textarea_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'layers-rte' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_RTE_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'layers-font' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_Font_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if ( 'layers-button' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_Button_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'layers-code' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_Code_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'layers-text' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_Text_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'layers-number' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_Number_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'layers-range' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new Layers_Customize_Range_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'layers-trbl-fields' == $control_data['type'] ) {
// Add extra settings fields for Top/Right/Bottom/Left
$this->customizer->add_setting(
$setting_key . '-top',
array(
'default' => ( isset( $control_data['default'] ) ? $control_data['default'] : NULL ) ,
'type' => 'theme_mod',
'capability' => 'manage_options',
'sanitize_callback' => $this->add_sanitize_callback( $control_data )
)
);
$this->customizer->add_setting(
$setting_key . '-right',
array(
'default' => ( isset( $control_data['default'] ) ? $control_data['default'] : NULL ) ,
'type' => 'theme_mod',
'capability' => 'manage_options',
'sanitize_callback' => $this->add_sanitize_callback( $control_data )
)
);
$this->customizer->add_setting(
$setting_key . '-bottom',
array(
'default' => ( isset( $control_data['default'] ) ? $control_data['default'] : NULL ) ,
'type' => 'theme_mod',
'capability' => 'manage_options',
'sanitize_callback' => $this->add_sanitize_callback( $control_data )
)
);
$this->customizer->add_setting(
$setting_key . '-left',
array(
'default' => ( isset( $control_data['default'] ) ? $control_data['default'] : NULL ) ,
'type' => 'theme_mod',
'capability' => 'manage_options',
'sanitize_callback' => $this->add_sanitize_callback( $control_data )
)
);
// Add Control
$this->customizer->add_control(
new Layers_Customize_TRBL_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'text' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new WP_Customize_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'color' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new WP_Customize_Color_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'upload' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new WP_Customize_Upload_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'image' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new WP_Customize_Image_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'background-image' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new WP_Customize_Background_Image_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else if( 'header-image' == $control_data['type'] ) {
// Add Control
$this->customizer->add_control(
new WP_Customize_Header_Image_Control(
$this->customizer,
$setting_key,
$control_data
)
);
} else {
// Add Control
$this->customizer->add_control(
$setting_key,
$control_data
);
}
$control_priority++;
} // foreach controls panel_section_key
}
/**
* Move Default Panels
*/
public function move_default_panels( $panels = array() ){
foreach( $panels as $panel_key => $panel_data ){
// Get the current panel
$panel = $this->customizer->get_panel( $panel_key );
// Panel Title
if( isset( $panel->title ) && isset( $panel_data[ 'title' ] ) ) {
$panel->title = $panel_data[ 'title' ];
}
// Panel Priority
if( isset( $panel->priority ) && isset( $panel_data[ 'priority' ] ) ) {
$panel->priority = $panel_data[ 'priority' ];
}
}
// Remove the theme switcher Panel, Layers isn't ready for that
$this->customizer->remove_section( 'themes' );
}
/**
* Move Default Sections
*/
public function move_default_sections( $sections = array() ){
foreach( $sections as $section_key => $section_data ){
// Get the current section
$section = $this->customizer->get_section( $section_key );
// Move this section to a specific panel
if( isset( $section->panel ) && isset( $section_data[ 'panel' ] ) ) {
$section->panel = $this->prefix . $section_data[ 'panel' ];
}
// Section Title
if( isset( $section->title ) && isset( $section_data[ 'title' ] ) ) {
$section->title = $section_data[ 'title' ];
}
// Section Priority
if( isset( $section->priority ) && isset( $section_data[ 'priority' ] ) ) {
$section->priority = $section_data[ 'priority' ];
}
}
}
/**
* Move Default Controls
*/
public function move_default_controls( $controls = array() ){
foreach( $controls as $control_key => $control_data ){
// Get the current control
$control = $this->customizer->get_control( $control_key );
// Move this control to a specific section
if( isset( $control->section ) && isset( $control_data[ 'section' ] ) ) {
$control->section = $this->prefix . $control_data[ 'section' ];
}
// Section Title
if( isset( $control->title ) && isset( $control_data[ 'title' ] ) ) {
$control->title = $control_data[ 'title' ];
}
// Section Priority
if( isset( $control->priority ) && isset( $control_data[ 'priority' ] ) ) {
$control->priority = $control_data[ 'priority' ];
}
}
// Remove the header text color control, we don't support it yet
$this->customizer->remove_section( 'colors' );
}
/**
* Add Sanitization according to the control type (or use the explicit callback that has been set)
*/
function add_sanitize_callback( $control_data = FALSE ){
// If there's an override, use the override rather than the automatic sanitization
if( isset( $control_data[ 'sanitize_callback' ] ) ) {
if( FALSE == $control_data[ 'sanitize_callback' ] ) {
return FALSE;
} else {
return $control_data[ 'sanitize_callback' ];
}
}
switch( $control_data[ 'type' ] ) {
case 'layers-color' :
$callback = 'sanitize_hex_color';
break;
case 'layers-checkbox' :
$callback = 'layers_sanitize_checkbox';
break;
case 'layers-textarea' :
$callback = 'esc_textarea';
break;
case 'layers-code' :
$callback = false;
break;
case 'layers-rte' :
$callback = false;
break;
default :
$callback = 'sanitize_text_field';
}
return $callback;
}
}
function layers_register_customizer(){
$layers_customizer_reg = Layers_Customizer_Regsitrar::get_instance();
}
add_action( 'customize_register', 'layers_register_customizer', 99 ); | gpl-2.0 |
kocko/gottogo | wp-content/plugins/gottogo/views/utils/luggage_utils.php | 919 | <?php
require_once '../database.php';
require_once '../../../../../wp-load.php';
function getLuggageItemsCategories() {
$database = new Database();
$connection = $database->getConnection();
$query = "SELECT DISTINCT category from luggage_item order by category";
$result = mysqli_query($connection, $query);
$ret = array();
while($r = mysqli_fetch_assoc($result)) {
$ret[] = $r['category'];
}
return $ret;
}
function getLuggageItemsPerCategory($category) {
$database = new Database();
$connection = $database->getConnection();
$cat = mysqli_real_escape_string($connection, $category);
$query = sprintf("SELECT DISTINCT name FROM luggage_item WHERE category='%s' order by id", $cat);
$result = mysqli_query($connection, $query);
$ret = array();
while ($r = mysqli_fetch_assoc($result)) {
$ret[] = $r['name'];
}
return $ret;
}
| gpl-2.0 |
argivaitv/argivaitv | plugin.video.salts/scrapers/easynews_scraper.py | 7921 | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import scraper
import urllib
import urlparse
import json
import re
from salts_lib import kodi
from salts_lib import log_utils
from salts_lib.trans_utils import i18n
from salts_lib.constants import VIDEO_TYPES
from salts_lib.constants import FORCE_NO_MATCH
BASE_URL = 'http://members.easynews.com'
SORT = 's1=relevance&s1d=-&s2=dsize&s2d=-&s3=dtime&s3d=-'
VID_FILTER = 'fex=mkv%%2C+mp4%%2C+avi'
# RANGE_FILTERS = 'd1=&d1t=&d2=&d2t=&b1=&b1t=&b2=&b2t=&px1=&px1t=&px2=&px2t=&fps1=&fps1t=&fps2=&fps2t=&bps1=&bps1t=&bps2=&bps2t=&hz1=&hz1t=&hz2=&hz2t=&rn1=&rn1t=1&rn2=&rn2t='
SEARCH_URL = '/2.0/search/solr-search/advanced?st=adv&safeO=0&sb=1&%s&%s&fty[]=VIDEO&spamf=1&u=1&gx=1&pby=100&pno=1&sS=3' % (VID_FILTER, SORT)
SEARCH_URL += '&gps=%s&sbj=%s'
class EasyNews_Scraper(scraper.Scraper):
base_url = BASE_URL
def __init__(self, timeout=scraper.DEFAULT_TIMEOUT):
self.timeout = timeout
self.base_url = kodi.get_setting('%s-base_url' % (self.get_name()))
self.username = kodi.get_setting('%s-username' % (self.get_name()))
self.password = kodi.get_setting('%s-password' % (self.get_name()))
self.cookie = {'chickenlicker': '%s%%3A%s' % (self.username, self.password)}
@classmethod
def provides(cls):
return frozenset([VIDEO_TYPES.MOVIE, VIDEO_TYPES.EPISODE])
@classmethod
def get_name(cls):
return 'EasyNews'
def resolve_link(self, link):
return link
def format_source_label(self, item):
label = '[%s] %s' % (item['quality'], item['host'])
if 'size' in item:
label += ' (%s)' % (item['size'])
return label
def get_sources(self, video):
hosters = []
source_url = self.get_url(video)
if source_url and source_url != FORCE_NO_MATCH:
params = urlparse.parse_qs(urlparse.urlparse(source_url).query)
if 'title' in params:
query = params['title'][0]
if video.video_type == VIDEO_TYPES.MOVIE:
if 'year' in params: query += ' %s' % (params['year'][0])
else:
sxe = ''
if 'season' in params:
sxe = 'S%02d' % (int(params['season'][0]))
if 'episode' in params:
sxe += 'E%02d' % (int(params['episode'][0]))
if sxe: query = '%s %s' % (query, sxe)
query = urllib.quote_plus(query)
query_url = '/search?query=%s' % (query)
hosters = self.__get_links(query_url, video)
if not hosters and video.video_type == VIDEO_TYPES.EPISODE and params['air_date'][0]:
query = urllib.quote_plus('%s %s' % (params['title'][0], params['air_date'][0].replace('-', '.')))
query_url = '/search?query=%s' % (query)
hosters = self.__get_links(query_url, video)
return hosters
def __get_links(self, url, video):
hosters = []
search_url = self.__translate_search(url)
html = self._http_get(search_url, cache_limit=.5)
if html:
try:
js_result = json.loads(html)
except ValueError:
log_utils.log('Invalid JSON returned: %s: %s' % (search_url, html), log_utils.LOGWARNING)
else:
for item in js_result['data']:
post_hash, size, post_title, ext, duration = item['0'], item['4'], item['10'], item['11'], item['14']
checks = [False] * 6
if not self._title_check(video, post_title): checks[0] = True
if 'alangs' in item and item['alangs'] and 'eng' not in item['alangs']: checks[1] = True
if re.match('^\d+s', duration) or re.match('^[0-5]m', duration): checks[2] = True
if 'passwd' in item and item['passwd']: checks[3] = True
if 'virus' in item and item['virus']: checks[4] = True
if 'type' in item and item['type'].upper() != 'VIDEO': checks[5] = True
if any(checks):
log_utils.log('EasyNews Post excluded: %s - |%s|' % (checks, item), log_utils.LOGDEBUG)
continue
stream_url = urllib.quote('%s%s/%s%s' % (post_hash, ext, post_title, ext))
stream_url = 'http://members.easynews.com/dl/%s' % (stream_url)
stream_url = stream_url + '|Cookie=%s' % (self.__get_cookies())
host = self._get_direct_hostname(stream_url)
quality = self._width_get_quality(item['width'])
hoster = {'multi-part': False, 'class': self, 'views': None, 'url': stream_url, 'rating': None, 'host': host, 'quality': quality, 'direct': True}
if size: hoster['size'] = size
hosters.append(hoster)
return hosters
def get_url(self, video):
url = None
self.create_db_connection()
result = self.db_connection.get_related_url(video.video_type, video.title, video.year, self.get_name(), video.season, video.episode)
if result:
url = result[0][0]
log_utils.log('Got local related url: |%s|%s|%s|%s|%s|' % (video.video_type, video.title, video.year, self.get_name(), url))
else:
if video.video_type == VIDEO_TYPES.MOVIE:
query = 'title=%s&year=%s' % (urllib.quote_plus(video.title), video.year)
else:
query = 'title=%s&season=%s&episode=%s&air_date=%s' % (urllib.quote_plus(video.title), video.season, video.episode, video.ep_airdate)
url = '/search?%s' % (query)
self.db_connection.set_related_url(video.video_type, video.title, video.year, self.get_name(), url)
return url
def search(self, video_type, title, year):
return []
@classmethod
def get_settings(cls):
settings = super(EasyNews_Scraper, cls).get_settings()
settings = cls._disable_sub_check(settings)
name = cls.get_name()
settings.append(' <setting id="%s-username" type="text" label=" %s" default="" visible="eq(-4,true)"/>' % (name, i18n('username')))
settings.append(' <setting id="%s-password" type="text" label=" %s" option="hidden" default="" visible="eq(-5,true)"/>' % (name, i18n('password')))
return settings
def _http_get(self, url, cache_limit=8):
if not self.username or not self.password:
return ''
return super(EasyNews_Scraper, self)._cached_http_get(url, self.base_url, self.timeout, cookies=self.cookie, cache_limit=cache_limit)
def __get_cookies(self):
cookies = []
for key in self.cookie:
cookies.append('%s=%s' % (key, self.cookie[key]))
return urllib.quote_plus(';'.join(cookies))
def __translate_search(self, url):
query = urllib.quote_plus(urlparse.parse_qs(urlparse.urlparse(url).query)['query'][0])
url = urlparse.urljoin(self.base_url, SEARCH_URL % (query, query))
return url
| gpl-2.0 |
bcoles/WhatWeb | plugins/coldfusion.rb | 3149 | ##
# This file is part of WhatWeb and may be subject to
# redistribution and commercial restrictions. Please see the WhatWeb
# web site for more information on licensing and terms of use.
# https://www.morningstarsecurity.com/research/whatweb
##
Plugin.define do
name "ColdFusion"
authors [
"Brendan Coles <bcoles@gmail.com>", # 2010-08-15
# v0.2 # 2011-04-25 # Added cookie matches.
# v0.3 # 2012-02-05 # Added header match. Updated matches. Updated version detection..
]
version "0.3"
description "Adobe ColdFusion application server and software enables developers to rapidly build, deploy, and maintain robust Internet applications for the enterprise."
website "http://www.adobe.com/products/coldfusion/"
# ShodanHQ results as at 2012-02-05 #
# 6,536 for page-completion-status
# 529 for page-completion-status Abnormal
# Google results as at 2011-04-25 #
# 30 for intitle:"ColdFusion Administrator Login"
# 72 for intitle:"Login / Admin Area" ext:cfm
# Dorks #
dorks [
'intitle:"ColdFusion Administrator Login"'
]
# Matches #
matches [
# Admin Page # Title
{ :text=>' <title>ColdFusion Administrator Login</title>' },
# Admin Page # Meta Author
{ :regexp=>/<meta name="Author" content="Copyright (\(c\)\ )?[0-9]{4}-[0-9]{4} Macromedia( Corp|, Inc)\. All rights reserved\.">/ },
# Admin Page # JavaScript
{ :text=>" { document.write(\"<link rel='STYLESHEET' type='text/css' href='./cfadmin_ns.css'>\");}" },
# Admin Page # Form
{ :text=>'<form name="loginform" action="./enter.cfm" method="POST" onSubmit="cfadminPassword.value = hex_hmac_sha1(salt.value, hex_sha1(cfadminPassword.value));" >' },
# Admin Page # input name="cfadminPassword"
{ :text=>'<input name="cfadminPassword" type="Password" size="15" style="width:15em;" class="label" maxlength="100" id="admin_login">' },
# Admin Page # Copyright text
{ :text=>' Macromedia, the Macromedia logo, Macromedia ColdFusion and ColdFusion are<br />' },
# Admin Page # Logo HTML
{ :text=>' <tr><td><img src="./images/mx_copyrframe.gif" width="2" height="57" border="0" alt="ColdFusion MX" hspace="10"></td>' },
# /CFIDE/administrator/images/loginbackground.jpg # Version 9.x
{ :url=>'/CFIDE/administrator/images/loginbackground.jpg', :md5=>"596b3fc4f1a0b818979db1cf94a82220", :version=>"9.x" },
# /CFIDE/administrator/images/AdminColdFusionLogo.gif # Version 7.x
{ :url=>"/CFIDE/administrator/images/AdminColdFusionLogo.gif", :md5=>"620b2523e4680bf031ee4b1538733349", :version=>"7.x" },
# page-completion-status Header
{ :search=>"headers[page-completion-status]", :certainty=>75, :regexp=>/(Abnormal|Normal)/ },
# Set-Cookie # /CFAUTHORIZATION_cfadmin=/
{ :search=>"headers[set-cookie]", :regexp=>/CFAUTHORIZATION_cfadmin=/ },
]
# Passive #
passive do
m=[]
# CFID and CFTOKEN cookie
if @headers["set-cookie"]=~ /CFID=/ and @headers["set-cookie"]=~ /CFTOKEN=/
m << { :name=>"CFID and CFTOKEN cookie" }
end
# Version detection using admin panel text
if @body =~ /Enter your RDS or Admin password below/
if @body =~ /Version:[\s]*([^<]+)<\/strong><br \/>/
m << { :version=>"#{$1}".gsub(/,/, ".") }
end
end
# Return passive matches
m
end
end
| gpl-2.0 |
tomaszklim/klim-framework | phpmailer-5.2.14-patched/class.smtp.php | 39908 | <?php
/**
* PHPMailer RFC821 SMTP email transport class.
* PHP Version 5
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2014 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
/**
* PHPMailer RFC821 SMTP email transport class.
* Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.
* @package PHPMailer
* @author Chris Ryan
* @author Marcus Bointon <phpmailer@synchromedia.co.uk>
*/
class SMTP
{
/**
* The PHPMailer SMTP version number.
* @var string
*/
const VERSION = '5.2.14';
/**
* SMTP line break constant.
* @var string
*/
const CRLF = "\r\n";
/**
* The SMTP port to use if one is not specified.
* @var integer
*/
const DEFAULT_SMTP_PORT = 25;
/**
* The maximum line length allowed by RFC 2822 section 2.1.1
* @var integer
*/
const MAX_LINE_LENGTH = 998;
/**
* Debug level for no output
*/
const DEBUG_OFF = 0;
/**
* Debug level to show client -> server messages
*/
const DEBUG_CLIENT = 1;
/**
* Debug level to show client -> server and server -> client messages
*/
const DEBUG_SERVER = 2;
/**
* Debug level to show connection status, client -> server and server -> client messages
*/
const DEBUG_CONNECTION = 3;
/**
* Debug level to show all messages
*/
const DEBUG_LOWLEVEL = 4;
/**
* The PHPMailer SMTP Version number.
* @var string
* @deprecated Use the `VERSION` constant instead
* @see SMTP::VERSION
*/
public $Version = '5.2.14';
/**
* SMTP server port number.
* @var integer
* @deprecated This is only ever used as a default value, so use the `DEFAULT_SMTP_PORT` constant instead
* @see SMTP::DEFAULT_SMTP_PORT
*/
public $SMTP_PORT = 25;
/**
* SMTP reply line ending.
* @var string
* @deprecated Use the `CRLF` constant instead
* @see SMTP::CRLF
*/
public $CRLF = "\r\n";
/**
* Debug output level.
* Options:
* * self::DEBUG_OFF (`0`) No debug output, default
* * self::DEBUG_CLIENT (`1`) Client commands
* * self::DEBUG_SERVER (`2`) Client commands and server responses
* * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status
* * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages
* @var integer
*/
public $do_debug = self::DEBUG_OFF;
/**
* How to handle debug output.
* Options:
* * `echo` Output plain-text as-is, appropriate for CLI
* * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
* * `error_log` Output to error log as configured in php.ini
*
* Alternatively, you can provide a callable expecting two params: a message string and the debug level:
* <code>
* $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
* </code>
* @var string|callable
*/
public $Debugoutput = 'echo';
/**
* Whether to use VERP.
* @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
* @link http://www.postfix.org/VERP_README.html Info on VERP
* @var boolean
*/
public $do_verp = false;
/**
* The timeout value for connection, in seconds.
* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
* This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure.
* @link http://tools.ietf.org/html/rfc2821#section-4.5.3.2
* @var integer
*/
public $Timeout = 300;
/**
* How long to wait for commands to complete, in seconds.
* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
* @var integer
*/
public $Timelimit = 300;
/**
* The socket for the server connection.
* @var resource
*/
protected $smtp_conn;
/**
* Error information, if any, for the last SMTP command.
* @var array
*/
protected $error = array(
'error' => '',
'detail' => '',
'smtp_code' => '',
'smtp_code_ex' => ''
);
/**
* The reply the server sent to us for HELO.
* If null, no HELO string has yet been received.
* @var string|null
*/
protected $helo_rply = null;
/**
* The set of SMTP extensions sent in reply to EHLO command.
* Indexes of the array are extension names.
* Value at index 'HELO' or 'EHLO' (according to command that was sent)
* represents the server name. In case of HELO it is the only element of the array.
* Other values can be boolean TRUE or an array containing extension options.
* If null, no HELO/EHLO string has yet been received.
* @var array|null
*/
protected $server_caps = null;
/**
* The most recent reply received from the server.
* @var string
*/
protected $last_reply = '';
/**
* Output debugging info via a user-selected method.
* @see SMTP::$Debugoutput
* @see SMTP::$do_debug
* @param string $str Debug string to output
* @param integer $level The debug level of this message; see DEBUG_* constants
* @return void
*/
protected function edebug($str, $level = 0)
{
if ($level > $this->do_debug) {
return;
}
//Avoid clash with built-in function names
if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
call_user_func($this->Debugoutput, $str, $this->do_debug);
return;
}
switch ($this->Debugoutput) {
case 'error_log':
//Don't output, just log
error_log($str);
break;
case 'html':
//Cleans up output a bit for a better looking, HTML-safe output
echo htmlentities(
preg_replace('/[\r\n]+/', '', $str),
ENT_QUOTES,
'UTF-8'
)
. "<br>\n";
break;
case 'echo':
default:
//Normalize line breaks
$str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
"\n",
"\n \t ",
trim($str)
)."\n";
}
}
/**
* Connect to an SMTP server.
* @param string $host SMTP server IP or host name
* @param integer $port The port number to connect to
* @param integer $timeout How long to wait for the connection to open
* @param array $options An array of options for stream_context_create()
* @access public
* @return boolean
*/
public function connect($host, $port = null, $timeout = 30, $options = array())
{
static $streamok;
//This is enabled by default since 5.0.0 but some providers disable it
//Check this once and cache the result
if (is_null($streamok)) {
$streamok = function_exists('stream_socket_client');
}
// Clear errors to avoid confusion
$this->setError('');
// Make sure we are __not__ connected
if ($this->connected()) {
// Already connected, generate error
$this->setError('Already connected to a server');
return false;
}
if (empty($port)) {
$port = self::DEFAULT_SMTP_PORT;
}
// Connect to the SMTP server
$this->edebug(
"Connection: opening to $host:$port, timeout=$timeout, options=".var_export($options, true),
self::DEBUG_CONNECTION
);
$errno = 0;
$errstr = '';
if ($streamok) {
$socket_context = stream_context_create($options);
//Suppress errors; connection failures are handled at a higher level
$this->smtp_conn = @stream_socket_client(
$host . ":" . $port,
$errno,
$errstr,
$timeout,
STREAM_CLIENT_CONNECT,
$socket_context
);
} else {
//Fall back to fsockopen which should work in more places, but is missing some features
$this->edebug(
"Connection: stream_socket_client not available, falling back to fsockopen",
self::DEBUG_CONNECTION
);
$this->smtp_conn = @fsockopen(
$host,
$port,
$errno,
$errstr,
$timeout
);
}
// Verify we connected properly
if (!is_resource($this->smtp_conn)) {
$this->setError(
'Failed to connect to server',
$errno,
$errstr
);
$this->edebug(
'SMTP ERROR: ' . $this->error['error']
. ": $errstr ($errno)",
self::DEBUG_CLIENT
);
return false;
}
$this->edebug('Connection: opened', self::DEBUG_CONNECTION);
// SMTP server can take longer to respond, give longer timeout for first read
// Windows does not have support for this timeout function
if (substr(PHP_OS, 0, 3) != 'WIN') {
$max = ini_get('max_execution_time');
// Don't bother if unlimited
if ($max != 0 && $timeout > $max) {
@set_time_limit($timeout);
}
stream_set_timeout($this->smtp_conn, $timeout, 0);
}
// Get any announcement
$announce = $this->get_lines();
$this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER);
return true;
}
/**
* Initiate a TLS (encrypted) session.
* @access public
* @return boolean
*/
public function startTLS()
{
if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
return false;
}
// Begin encrypted connection
if (!stream_socket_enable_crypto(
$this->smtp_conn,
true,
STREAM_CRYPTO_METHOD_TLS_CLIENT
)) {
return false;
}
return true;
}
/**
* Perform SMTP authentication.
* Must be run after hello().
* @see hello()
* @param string $username The user name
* @param string $password The password
* @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5, XOAUTH2)
* @param string $realm The auth realm for NTLM
* @param string $workstation The auth workstation for NTLM
* @param null|OAuth $OAuth An optional OAuth instance (@see PHPMailerOAuth)
* @return bool True if successfully authenticated.* @access public
*/
public function authenticate(
$username,
$password,
$authtype = null,
$realm = '',
$workstation = '',
$OAuth = null
) {
if (!$this->server_caps) {
$this->setError('Authentication is not allowed before HELO/EHLO');
return false;
}
if (array_key_exists('EHLO', $this->server_caps)) {
// SMTP extensions are available. Let's try to find a proper authentication method
if (!array_key_exists('AUTH', $this->server_caps)) {
$this->setError('Authentication is not allowed at this stage');
// 'at this stage' means that auth may be allowed after the stage changes
// e.g. after STARTTLS
return false;
}
self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL);
self::edebug(
'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),
self::DEBUG_LOWLEVEL
);
if (empty($authtype)) {
foreach (array('LOGIN', 'CRAM-MD5', 'NTLM', 'PLAIN', 'XOAUTH2') as $method) {
if (in_array($method, $this->server_caps['AUTH'])) {
$authtype = $method;
break;
}
}
if (empty($authtype)) {
$this->setError('No supported authentication methods found');
return false;
}
self::edebug('Auth method selected: '.$authtype, self::DEBUG_LOWLEVEL);
}
if (!in_array($authtype, $this->server_caps['AUTH'])) {
$this->setError("The requested authentication method \"$authtype\" is not supported by the server");
return false;
}
} elseif (empty($authtype)) {
$authtype = 'LOGIN';
}
switch ($authtype) {
case 'PLAIN':
// Start authentication
if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
return false;
}
// Send encoded username and password
if (!$this->sendCommand(
'User & Password',
base64_encode("\0" . $username . "\0" . $password),
235
)
) {
return false;
}
break;
case 'LOGIN':
// Start authentication
if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
return false;
}
if (!$this->sendCommand("Username", base64_encode($username), 334)) {
return false;
}
if (!$this->sendCommand("Password", base64_encode($password), 235)) {
return false;
}
break;
case 'XOAUTH2':
//If the OAuth Instance is not set. Can be a case when PHPMailer is used
//instead of PHPMailerOAuth
if (is_null($OAuth)) {
return false;
}
$oauth = $OAuth->getOauth64();
// Start authentication
if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
return false;
}
break;
case 'NTLM':
/*
* ntlm_sasl_client.php
* Bundled with Permission
*
* How to telnet in windows:
* http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx
* PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication
*/
require_once 'extras/ntlm_sasl_client.php';
$temp = new stdClass;
$ntlm_client = new ntlm_sasl_client_class;
//Check that functions are available
if (!$ntlm_client->Initialize($temp)) {
$this->setError($temp->error);
$this->edebug(
'You need to enable some modules in your php.ini file: '
. $this->error['error'],
self::DEBUG_CLIENT
);
return false;
}
//msg1
$msg1 = $ntlm_client->TypeMsg1($realm, $workstation); //msg1
if (!$this->sendCommand(
'AUTH NTLM',
'AUTH NTLM ' . base64_encode($msg1),
334
)
) {
return false;
}
//Though 0 based, there is a white space after the 3 digit number
//msg2
$challenge = substr($this->last_reply, 3);
$challenge = base64_decode($challenge);
$ntlm_res = $ntlm_client->NTLMResponse(
substr($challenge, 24, 8),
$password
);
//msg3
$msg3 = $ntlm_client->TypeMsg3(
$ntlm_res,
$username,
$realm,
$workstation
);
// send encoded username
return $this->sendCommand('Username', base64_encode($msg3), 235);
case 'CRAM-MD5':
// Start authentication
if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
return false;
}
// Get the challenge
$challenge = base64_decode(substr($this->last_reply, 4));
// Build the response
$response = $username . ' ' . $this->hmac($challenge, $password);
// send encoded credentials
return $this->sendCommand('Username', base64_encode($response), 235);
default:
$this->setError("Authentication method \"$authtype\" is not supported");
return false;
}
return true;
}
/**
* Calculate an MD5 HMAC hash.
* Works like hash_hmac('md5', $data, $key)
* in case that function is not available
* @param string $data The data to hash
* @param string $key The key to hash with
* @access protected
* @return string
*/
protected function hmac($data, $key)
{
if (function_exists('hash_hmac')) {
return hash_hmac('md5', $data, $key);
}
// The following borrowed from
// http://php.net/manual/en/function.mhash.php#27225
// RFC 2104 HMAC implementation for php.
// Creates an md5 HMAC.
// Eliminates the need to install mhash to compute a HMAC
// by Lance Rushing
$bytelen = 64; // byte length for md5
if (strlen($key) > $bytelen) {
$key = pack('H*', md5($key));
}
$key = str_pad($key, $bytelen, chr(0x00));
$ipad = str_pad('', $bytelen, chr(0x36));
$opad = str_pad('', $bytelen, chr(0x5c));
$k_ipad = $key ^ $ipad;
$k_opad = $key ^ $opad;
return md5($k_opad . pack('H*', md5($k_ipad . $data)));
}
/**
* Check connection state.
* @access public
* @return boolean True if connected.
*/
public function connected()
{
if (is_resource($this->smtp_conn)) {
$sock_status = stream_get_meta_data($this->smtp_conn);
if ($sock_status['eof']) {
// The socket is valid but we are not connected
$this->edebug(
'SMTP NOTICE: EOF caught while checking if connected',
self::DEBUG_CLIENT
);
$this->close();
return false;
}
return true; // everything looks good
}
return false;
}
/**
* Close the socket and clean up the state of the class.
* Don't use this function without first trying to use QUIT.
* @see quit()
* @access public
* @return void
*/
public function close()
{
$this->setError('');
$this->server_caps = null;
$this->helo_rply = null;
if (is_resource($this->smtp_conn)) {
// close the connection and cleanup
fclose($this->smtp_conn);
$this->smtp_conn = null; //Makes for cleaner serialization
$this->edebug('Connection: closed', self::DEBUG_CONNECTION);
}
}
/**
* Send an SMTP DATA command.
* Issues a data command and sends the msg_data to the server,
* finializing the mail transaction. $msg_data is the message
* that is to be send with the headers. Each header needs to be
* on a single line followed by a <CRLF> with the message headers
* and the message body being separated by and additional <CRLF>.
* Implements rfc 821: DATA <CRLF>
* @param string $msg_data Message data to send
* @access public
* @return boolean
*/
public function data($msg_data)
{
//This will use the standard timelimit
if (!$this->sendCommand('DATA', 'DATA', 354)) {
return false;
}
/* The server is ready to accept data!
* According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF)
* so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
* smaller lines to fit within the limit.
* We will also look for lines that start with a '.' and prepend an additional '.'.
* NOTE: this does not count towards line-length limit.
*/
// Normalize line breaks before exploding
$lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data));
/* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
* of the first line (':' separated) does not contain a space then it _should_ be a header and we will
* process all lines before a blank line as headers.
*/
$field = substr($lines[0], 0, strpos($lines[0], ':'));
$in_headers = false;
if (!empty($field) && strpos($field, ' ') === false) {
$in_headers = true;
}
foreach ($lines as $line) {
$lines_out = array();
if ($in_headers and $line == '') {
$in_headers = false;
}
//Break this line up into several smaller lines if it's too long
//Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),
while (isset($line[self::MAX_LINE_LENGTH])) {
//Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
//so as to avoid breaking in the middle of a word
$pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
//Deliberately matches both false and 0
if (!$pos) {
//No nice break found, add a hard break
$pos = self::MAX_LINE_LENGTH - 1;
$lines_out[] = substr($line, 0, $pos);
$line = substr($line, $pos);
} else {
//Break at the found point
$lines_out[] = substr($line, 0, $pos);
//Move along by the amount we dealt with
$line = substr($line, $pos + 1);
}
//If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1
if ($in_headers) {
$line = "\t" . $line;
}
}
$lines_out[] = $line;
//Send the lines to the server
foreach ($lines_out as $line_out) {
//RFC2821 section 4.5.2
if (!empty($line_out) and $line_out[0] == '.') {
$line_out = '.' . $line_out;
}
$this->client_send($line_out . self::CRLF);
}
}
//Message data has been sent, complete the command
//Increase timelimit for end of DATA command
$savetimelimit = $this->Timelimit;
$this->Timelimit = $this->Timelimit * 2;
$result = $this->sendCommand('DATA END', '.', 250);
//Restore timelimit
$this->Timelimit = $savetimelimit;
return $result;
}
/**
* Send an SMTP HELO or EHLO command.
* Used to identify the sending server to the receiving server.
* This makes sure that client and server are in a known state.
* Implements RFC 821: HELO <SP> <domain> <CRLF>
* and RFC 2821 EHLO.
* @param string $host The host name or IP to connect to
* @access public
* @return boolean
*/
public function hello($host = '')
{
//Try extended hello first (RFC 2821)
return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
}
/**
* Send an SMTP HELO or EHLO command.
* Low-level implementation used by hello()
* @see hello()
* @param string $hello The HELO string
* @param string $host The hostname to say we are
* @access protected
* @return boolean
*/
protected function sendHello($hello, $host)
{
$noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
$this->helo_rply = $this->last_reply;
if ($noerror) {
$this->parseHelloFields($hello);
} else {
$this->server_caps = null;
}
return $noerror;
}
/**
* Parse a reply to HELO/EHLO command to discover server extensions.
* In case of HELO, the only parameter that can be discovered is a server name.
* @access protected
* @param string $type - 'HELO' or 'EHLO'
*/
protected function parseHelloFields($type)
{
$this->server_caps = array();
$lines = explode("\n", $this->last_reply);
foreach ($lines as $n => $s) {
//First 4 chars contain response code followed by - or space
$s = trim(substr($s, 4));
if (empty($s)) {
continue;
}
$fields = explode(' ', $s);
if (!empty($fields)) {
if (!$n) {
$name = $type;
$fields = $fields[0];
} else {
$name = array_shift($fields);
switch ($name) {
case 'SIZE':
$fields = ($fields ? $fields[0] : 0);
break;
case 'AUTH':
if (!is_array($fields)) {
$fields = array();
}
break;
default:
$fields = true;
}
}
$this->server_caps[$name] = $fields;
}
}
}
/**
* Send an SMTP MAIL command.
* Starts a mail transaction from the email address specified in
* $from. Returns true if successful or false otherwise. If True
* the mail transaction is started and then one or more recipient
* commands may be called followed by a data command.
* Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
* @param string $from Source address of this message
* @access public
* @return boolean
*/
public function mail($from)
{
$useVerp = ($this->do_verp ? ' XVERP' : '');
return $this->sendCommand(
'MAIL FROM',
'MAIL FROM:<' . $from . '>' . $useVerp,
250
);
}
/**
* Send an SMTP QUIT command.
* Closes the socket if there is no error or the $close_on_error argument is true.
* Implements from rfc 821: QUIT <CRLF>
* @param boolean $close_on_error Should the connection close if an error occurs?
* @access public
* @return boolean
*/
public function quit($close_on_error = true)
{
$noerror = $this->sendCommand('QUIT', 'QUIT', 221);
$err = $this->error; //Save any error
if ($noerror or $close_on_error) {
$this->close();
$this->error = $err; //Restore any error from the quit command
}
return $noerror;
}
/**
* Send an SMTP RCPT command.
* Sets the TO argument to $toaddr.
* Returns true if the recipient was accepted false if it was rejected.
* Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
* @param string $address The address the message is being sent to
* @access public
* @return boolean
*/
public function recipient($address)
{
return $this->sendCommand(
'RCPT TO',
'RCPT TO:<' . $address . '>',
array(250, 251)
);
}
/**
* Send an SMTP RSET command.
* Abort any transaction that is currently in progress.
* Implements rfc 821: RSET <CRLF>
* @access public
* @return boolean True on success.
*/
public function reset()
{
return $this->sendCommand('RSET', 'RSET', 250);
}
/**
* Send a command to an SMTP server and check its return code.
* @param string $command The command name - not sent to the server
* @param string $commandstring The actual command to send
* @param integer|array $expect One or more expected integer success codes
* @access protected
* @return boolean True on success.
*/
protected function sendCommand($command, $commandstring, $expect)
{
if (!$this->connected()) {
$this->setError("Called $command without being connected");
return false;
}
//Reject line breaks in all commands
if (strpos($commandstring, "\n") !== false or strpos($commandstring, "\r") !== false) {
$this->setError("Command '$command' contained line breaks");
return false;
}
$this->client_send($commandstring . self::CRLF);
$this->last_reply = $this->get_lines();
// Fetch SMTP code and possible error code explanation
$matches = array();
if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) {
$code = $matches[1];
$code_ex = (count($matches) > 2 ? $matches[2] : null);
// Cut off error code from each response line
$detail = preg_replace(
"/{$code}[ -]".($code_ex ? str_replace('.', '\\.', $code_ex).' ' : '')."/m",
'',
$this->last_reply
);
} else {
// Fall back to simple parsing if regex fails
$code = substr($this->last_reply, 0, 3);
$code_ex = null;
$detail = substr($this->last_reply, 4);
}
$this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
if (!in_array($code, (array)$expect)) {
$this->setError(
"$command command failed",
$detail,
$code,
$code_ex
);
$this->edebug(
'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply,
self::DEBUG_CLIENT
);
return false;
}
$this->setError('');
return true;
}
/**
* Send an SMTP SAML command.
* Starts a mail transaction from the email address specified in $from.
* Returns true if successful or false otherwise. If True
* the mail transaction is started and then one or more recipient
* commands may be called followed by a data command. This command
* will send the message to the users terminal if they are logged
* in and send them an email.
* Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
* @param string $from The address the message is from
* @access public
* @return boolean
*/
public function sendAndMail($from)
{
return $this->sendCommand('SAML', "SAML FROM:$from", 250);
}
/**
* Send an SMTP VRFY command.
* @param string $name The name to verify
* @access public
* @return boolean
*/
public function verify($name)
{
return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
}
/**
* Send an SMTP NOOP command.
* Used to keep keep-alives alive, doesn't actually do anything
* @access public
* @return boolean
*/
public function noop()
{
return $this->sendCommand('NOOP', 'NOOP', 250);
}
/**
* Send an SMTP TURN command.
* This is an optional command for SMTP that this class does not support.
* This method is here to make the RFC821 Definition complete for this class
* and _may_ be implemented in future
* Implements from rfc 821: TURN <CRLF>
* @access public
* @return boolean
*/
public function turn()
{
$this->setError('The SMTP TURN command is not implemented');
$this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
return false;
}
/**
* Send raw data to the server.
* @param string $data The data to send
* @access public
* @return integer|boolean The number of bytes sent to the server or false on error
*/
public function client_send($data)
{
$this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT);
return @fwrite($this->smtp_conn, $data);
}
/**
* Get the latest error.
* @access public
* @return array
*/
public function getError()
{
return $this->error;
}
/**
* Get SMTP extensions available on the server
* @access public
* @return array|null
*/
public function getServerExtList()
{
return $this->server_caps;
}
/**
* A multipurpose method
* The method works in three ways, dependent on argument value and current state
* 1. HELO/EHLO was not sent - returns null and set up $this->error
* 2. HELO was sent
* $name = 'HELO': returns server name
* $name = 'EHLO': returns boolean false
* $name = any string: returns null and set up $this->error
* 3. EHLO was sent
* $name = 'HELO'|'EHLO': returns server name
* $name = any string: if extension $name exists, returns boolean True
* or its options. Otherwise returns boolean False
* In other words, one can use this method to detect 3 conditions:
* - null returned: handshake was not or we don't know about ext (refer to $this->error)
* - false returned: the requested feature exactly not exists
* - positive value returned: the requested feature exists
* @param string $name Name of SMTP extension or 'HELO'|'EHLO'
* @return mixed
*/
public function getServerExt($name)
{
if (!$this->server_caps) {
$this->setError('No HELO/EHLO was sent');
return null;
}
// the tight logic knot ;)
if (!array_key_exists($name, $this->server_caps)) {
if ($name == 'HELO') {
return $this->server_caps['EHLO'];
}
if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) {
return false;
}
$this->setError('HELO handshake was used. Client knows nothing about server extensions');
return null;
}
return $this->server_caps[$name];
}
/**
* Get the last reply from the server.
* @access public
* @return string
*/
public function getLastReply()
{
return $this->last_reply;
}
/**
* Read the SMTP server's response.
* Either before eof or socket timeout occurs on the operation.
* With SMTP we can tell if we have more lines to read if the
* 4th character is '-' symbol. If it is a space then we don't
* need to read anything else.
* @access protected
* @return string
*/
protected function get_lines()
{
// If the connection is bad, give up straight away
if (!is_resource($this->smtp_conn)) {
return '';
}
$data = '';
$endtime = 0;
stream_set_timeout($this->smtp_conn, $this->Timeout);
if ($this->Timelimit > 0) {
$endtime = time() + $this->Timelimit;
}
while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
$str = @fgets($this->smtp_conn, 515);
$this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL);
$this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL);
$data .= $str;
// If 4th character is a space, we are done reading, break the loop, micro-optimisation over strlen
if ((isset($str[3]) and $str[3] == ' ')) {
break;
}
// Timed-out? Log and break
$info = stream_get_meta_data($this->smtp_conn);
if ($info['timed_out']) {
$this->edebug(
'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)',
self::DEBUG_LOWLEVEL
);
break;
}
// Now check if reads took too long
if ($endtime and time() > $endtime) {
$this->edebug(
'SMTP -> get_lines(): timelimit reached ('.
$this->Timelimit . ' sec)',
self::DEBUG_LOWLEVEL
);
break;
}
}
return $data;
}
/**
* Enable or disable VERP address generation.
* @param boolean $enabled
*/
public function setVerp($enabled = false)
{
$this->do_verp = $enabled;
}
/**
* Get VERP address generation mode.
* @return boolean
*/
public function getVerp()
{
return $this->do_verp;
}
/**
* Set error messages and codes.
* @param string $message The error message
* @param string $detail Further detail on the error
* @param string $smtp_code An associated SMTP error code
* @param string $smtp_code_ex Extended SMTP code
*/
protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
{
$this->error = array(
'error' => $message,
'detail' => $detail,
'smtp_code' => $smtp_code,
'smtp_code_ex' => $smtp_code_ex
);
}
/**
* Set debug output method.
* @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it.
*/
public function setDebugOutput($method = 'echo')
{
$this->Debugoutput = $method;
}
/**
* Get debug output method.
* @return string
*/
public function getDebugOutput()
{
return $this->Debugoutput;
}
/**
* Set debug output level.
* @param integer $level
*/
public function setDebugLevel($level = 0)
{
$this->do_debug = $level;
}
/**
* Get debug output level.
* @return integer
*/
public function getDebugLevel()
{
return $this->do_debug;
}
/**
* Set SMTP timeout.
* @param integer $timeout
*/
public function setTimeout($timeout = 0)
{
$this->Timeout = $timeout;
}
/**
* Get SMTP timeout.
* @return integer
*/
public function getTimeout()
{
return $this->Timeout;
}
}
| gpl-2.0 |
chrislarrycarl/Helios-Calendar | admin/components/Location.php | 4889 | <?php
/**
* @package Helios Calendar
* @license GNU General Public License version 2 or later; see LICENSE
*/
if(!defined('hcAdmin')){header("HTTP/1.1 403 No Direct Access");exit();}
include(HCLANG.'/admin/locations.php');
$resDiff = 6;
$resLimit = (isset($_GET['a']) && is_numeric($_GET['a']) && abs($_GET['a']) <= 100 && $_GET['a'] % 25 == 0) ? cIn(abs($_GET['a'])) : 25;
$resOffset = (isset($_GET['p']) && is_numeric($_GET['p'])) ? cIn(abs($_GET['p'])) : 0;
$term = $save = $queryS = '';
if(isset($_GET['s']) && $_GET['s'] != ''){
$term = cIn(cleanQuotes(strip_tags($_GET['s'])));
$save = '&s='.$term;
$queryS = " AND Name LIKE('%".$term."%')";
}
$hc_Side[] = array(CalRoot . '/index.php?com=location','map.png',$hc_lang_locations['LinkMap'],1);
if(isset($_GET['msg'])){
switch ($_GET['msg']){
case "3" :
feedback(1, $hc_lang_locations['Feed03']);
break;
case "4" :
feedback(2, $hc_lang_locations['Feed04']);
break;
case "5" :
feedback(1, $hc_lang_locations['Feed05']);
break;
}
}
appInstructions(0, "Editing_Locations", $hc_lang_locations['TitleBrowse'], $hc_lang_locations['InstructBrowse']);
$resultC = doQuery("SELECT COUNT(*) FROM " . HC_TblPrefix . "locations WHERE IsActive = 1 $queryS");
$pages = ceil(hc_mysql_result($resultC,0,0)/$resLimit);
if($pages <= $resOffset && $pages > 0){$resOffset = ($pages - 1);}
echo '
<fieldset style="border:0px;">
<label><b>'.$hc_lang_locations['ResPer'].'</b></label>
<span class="output">';
for($x = 25;$x <= 100;$x = $x + 25){
echo ($x > 25) ? ' | ' : '';
echo ($x != $resLimit) ?
'<a href="'.AdminRoot.'/index.php?com=location&p='.$resOffset.'&a='.$x.$save.'">'.$x.'</a>':
'<b>'.$x.'</b>';
}
echo '</span>
<label><b>'.$hc_lang_locations['Page'].'</b></label>
<span class="output">';
$x = ($resOffset - $resDiff > 0) ? $resOffset - $resDiff : 0;
$cnt = 0;
echo ($resOffset > $resDiff) ? '<a href="'.AdminRoot.'/index.php?com=location&p=0&a='.$resLimit.'">1</a> ... ' : '';
while($cnt <= ($resDiff * 2) && $x < $pages){
echo ($cnt > 0) ? ' | ' : '';
echo ($resOffset != $x) ?
'<a href="'.AdminRoot.'/index.php?com=location&p='.$x.'&a='.$resLimit.$save.'">'.($x + 1).'</a>':
'<b>' . ($x + 1) . '</b>';
++$x;
++$cnt;
}
echo ($resOffset < ($pages - ($resDiff + 1))) ? ' ... <a href="'.AdminRoot.'/index.php?com=location&p='.($pages - 1).'&a='.$resLimit.'">'.$pages.'</a>' : '';
echo '</span>
<label> </label>
<span class="frm_ctrls">
<input name="filter" id="filter" type="text" size="30" maxlength="50" value="'.$term.'" />
<input name="filter_go" id="filter_go" type="button" value="'.$hc_lang_locations['Filter'].'" onclick="window.location.href=\''.AdminRoot.'/index.php?com=location&p=0&a='.$resLimit.'&s=\'+document.getElementById(\'filter\').value;" />
</span>
'.(($term != '') ? '<label> </label><span class="output"><a href="'.AdminRoot.'/index.php?com=location&p=0&a='.$resLimit.'">'.$hc_lang_locations['AllLink'].'</a></span>' : '').'
</fieldset>';
$result = doQuery("SELECT PkID, Name, IsPublic FROM " . HC_TblPrefix . "locations WHERE IsActive = 1 $queryS ORDER BY IsPublic, Name LIMIT " . $resLimit . " OFFSET " . ($resOffset * $resLimit));
if(hasRows($result)){
echo '
<ul class="data">
<li class="row header uline">
<div style="width:75%;">'.$hc_lang_locations['NameLabel'].'</div>
<div style="width:15%;">'.$hc_lang_locations['StatusLabel'].'</div>
<div style="width:10%;"> </div>
</li>';
$cnt = 0;
while($row = hc_mysql_fetch_row($result)){
$hl = ($cnt % 2 == 1) ? ' hl' : '';
echo '
<li class="row'.$hl.'">
<div class="txt" style="width:75%;">'.cOut($row[1]).'</div>
<div class="txt" style="width:15%;">'.(($row[2] == 1) ? $hc_lang_locations['Public'] : $hc_lang_locations['AdminOnly']).'</div>
<div class="tools" style="width:10%;">
<a href="'.AdminRoot.'/index.php?com=addlocation&lID='.$row[0].'"><img src="'.AdminRoot.'/img/icons/edit.png" width="16" height="16" alt="" /></a>
<a href="javascript:;" onclick="doDelete(\''.$row[0].'\');return false;"><img src="'.AdminRoot.'/img/icons/delete.png" width="16" height="16" alt="" /></a>
</div>
</li>';
++$cnt;
}
echo '
</ul>
<script>
//<!--
function doDelete(dID){
if(confirm("'.$hc_lang_locations['Valid01'].'\\n\\n '.$hc_lang_locations['Valid02'].'\\n '.$hc_lang_locations['Valid03'].'"))
document.location.href = "'.AdminRoot.'/components/LocationEditAction.php?dID=" + dID + "&tkn='.set_form_token(1).'";
}
//-->
</script>';
} else {
echo "<br />" . $hc_lang_locations['NoLoc'];
}
?> | gpl-2.0 |
brendo10x/site-estagio | wp-content/themes/accesspress-lite/content-none.php | 1143 | <?php
/**
* The template part for displaying a message that posts cannot be found.
*
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package AccesspressLite
*/
?>
<section class="no-results not-found">
<header class="page-header">
<h1 class="page-title"><?php _e( 'Nada encontrado', 'accesspresslite' ); ?></h1>
</header><!-- .page-header -->
<div class="page-content">
<?php if ( is_home() && current_user_can( 'publish_posts' ) ) : ?>
<p><?php printf( __( 'Pronto para publicar o seu primeiro post? <a href="%1$s">Comece aqui</a>.', 'accesspresslite' ), esc_url( admin_url( 'post-new.php' ) ) ); ?></p>
<?php elseif ( is_search() ) : ?>
<p><?php _e( 'Desculpe, mas nada combinando seus termos de pesquisa. Por favor, tente novamente com algumas palavras-chave diferentes.', 'accesspresslite' ); ?></p>
<?php get_search_form(); ?>
<?php else : ?>
<p><?php _e( 'It seems we can’t find what you’re looking for. Perhaps searching can help.', 'accesspresslite' ); ?></p>
<?php get_search_form(); ?>
<?php endif; ?>
</div><!-- .page-content -->
</section><!-- .no-results --> | gpl-2.0 |
zcurylo/EGUI | lab4_Qt1/my_push_button.cpp | 1602 | #include "my_push_button.h"
#include<QtGui>
my_push_button::my_push_button(QWidget *parent) :
QWidget(parent), state_m(stateColor::NORMAL)
{
//setAttribute(Qt::WA_);
}
void my_push_button::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
if(state_m == stateColor::NORMAL)
{
emit hitResult(false);
state_m = stateColor::SELECTED;
repaint();
}
if(state_m == stateColor::SELECTED)
{
emit hitResult(true);
state_m=stateColor::NORMAL;
repaint();
}
}
}
void my_push_button::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::black, 4, Qt::SolidLine, Qt::RoundCap, Qt::MiterJoin));
QPoint point1(10,10);
QPoint point2(10,width()-10);
QPoint point3(height()-10,width()-10);
QPoint point4(height()-10,10);
QVector<QPoint> path;
path.append(point1);
path.append(point2);
path.append(point3);
path.append(point4);
painter.drawPolyline(path);
if(state_m == stateColor::NORMAL)
{
painter.setBrush(QBrush(Qt::blue,Qt::SolidPattern));
painter.drawRect(20,20,width()-40, height()-40);
}else
{
painter.setBrush(QBrush(Qt::green,Qt::SolidPattern));
painter.drawRect(20,20,width()-40, height()-40);
}
}
QSize my_push_button::sizeHint() const
{
return QSize(50,50);
}
void my_push_button::setState(stateColor inp)
{
state_m = inp;
repaint();
}
| gpl-2.0 |
davel1/dj-page-news | faq/models.py | 378 | from django.db import models
# Create your models here.
class question(models.Model):
q = models.TextField('Question')
q_date = models.DateTimeField('Date insert')
class answer(models.Model):
r = models.TextField('Answer')
r_date = models.DateTimeField('Date add answer')
public = models.BooleanField('Public')
child = models.ForeignKey(question) | gpl-2.0 |
shinnya/jd-mirror | src/control/control.cpp | 11660 | // ライセンス: GPL2
//#define _DEBUG
#include "jddebug.h"
#include "control.h"
#include "controlid.h"
#include "controlutil.h"
#include "get_config.h"
#include "keyconfig.h"
#include "mouseconfig.h"
#include "buttonconfig.h"
#include "config/globalconf.h"
#include "command.h"
#include "global.h"
using namespace CONTROL;
// ホイールマウスジェスチャ用( 全てのビューで共通 )
bool mg_wheel_done;
Control::Control()
: m_send_mg_info( true )
{
MG_reset();
MG_wheel_reset();
clear_mode();
}
void Control::add_mode( const int mode )
{
// 共通モードは最後に検索
if( mode == CONTROL::MODE_COMMON ) return;
m_mode[ m_mode.size()-1 ] = mode;
m_mode.push_back( CONTROL::MODE_COMMON );
#ifdef _DEBUG
std::cout << "Control::add_mode size = " << m_mode.size() << std::endl;
std::vector< int >::iterator it = m_mode.begin();
for( ; it != m_mode.end(); ++it ) std::cout << (*it) << std::endl;
#endif
}
void Control::clear_mode()
{
m_mode.clear();
m_mode.push_back( CONTROL::MODE_COMMON );
}
///////////////////////////////////////
//
// キー操作
// 戻り値はコントロールID
const int Control::key_press( const GdkEventKey* event )
{
guint key = event->keyval;
const bool ctrl = ( event->state ) & GDK_CONTROL_MASK;
bool shift = ( event->state ) & GDK_SHIFT_MASK;
const bool alt = ( event->state ) & GDK_MOD1_MASK;
const bool caps = ( event->state ) & GDK_LOCK_MASK; // caps lock
const bool dblclick = false;
const bool trpclick = false;
// caps lockされている場合は、アスキー文字を大文字小文字入れ替えて、capsを無視する
// InputDiag::on_key_press_event()も参照のこと
if( caps ){
if( key >= 'A' && key <= 'Z' ){
key += 'a' - 'A';
} else if( key >= 'a' && key <= 'z' ){
key += 'A' - 'a';
}
}
// keyがアスキー文字の場合は shift を無視する (大文字除く)
// KeyConfig::set_one_motion()も参照せよ
if( CONTROL::is_ascii( key ) && ( key < 'A' || key > 'Z' ) ) shift = false;
#ifdef _DEBUG
std::cout << "Control::key_press key = " << std::hex << key;
if( ctrl ) std::cout << " ctrl";
if( shift ) std::cout << " shift";
if( alt ) std::cout << " alt";
if( caps ) std::cout << " caps";
std::cout << "\n";
#endif
int control = CONTROL::None;
std::vector< int >::iterator it = m_mode.begin();
for( ; it != m_mode.end(); ++it ){
control = CONTROL::get_keyconfig()->get_id( *it, key, ctrl, shift, alt, dblclick, trpclick );
if( control != CONTROL::None ) break;
}
return control;
}
///////////////////////////////////////
//
// マウスのボタン操作
// 戻り値はコントロールID
const int Control::button_press( const GdkEventButton* event )
{
const guint button = event->button;
const bool ctrl = ( event->state ) & GDK_CONTROL_MASK;
const bool shift = ( event->state ) & GDK_SHIFT_MASK;
const bool alt = ( event->state ) & GDK_MOD1_MASK;
const bool dblclick = ( event->type == GDK_2BUTTON_PRESS );
const bool trpclick = ( event->type == GDK_3BUTTON_PRESS );
int control = CONTROL::None;
std::vector< int >::iterator it = m_mode.begin();
for( ; it != m_mode.end(); ++it ){
control = CONTROL::get_buttonconfig()->get_id( *it, button, ctrl, shift, alt, dblclick, trpclick );
if( control != CONTROL::None ) break;
}
return control;
}
// eventがidに割り当てられていたらtrue
const bool Control::button_alloted( const GdkEventButton* event, const int id )
{
const guint button = event->button;
const bool ctrl = ( event->state ) & GDK_CONTROL_MASK;
const bool shift = ( event->state ) & GDK_SHIFT_MASK;
const bool alt = ( event->state ) & GDK_MOD1_MASK;
const bool dblclick = ( event->type == GDK_2BUTTON_PRESS );
const bool trpclick = ( event->type == GDK_3BUTTON_PRESS );
return CONTROL::get_buttonconfig()->alloted( id, button, ctrl, shift, alt, dblclick, trpclick );
}
// ID からevent取得
const bool Control::get_eventbutton( const int id, GdkEventButton& event )
{
guint button;
bool ctrl;
bool shift;
bool alt;
bool dblclick;
bool trpclick;
if( CONTROL::get_buttonconfig()->get_motion( id, button, ctrl, shift, alt, dblclick, trpclick ) ){
if( dblclick ) event.type = GDK_2BUTTON_PRESS;
if( trpclick ) event.type = GDK_3BUTTON_PRESS;
event.button = button;
event.state = ( GDK_CONTROL_MASK & ctrl ) | ( GDK_SHIFT_MASK & shift ) | ( GDK_MOD1_MASK & alt );
return true;
}
return false;
}
///////////////////////////////////////
//
// マウスジェスチャ
void Control::MG_reset()
{
m_mg = false;
m_mg_x = 0;
m_mg_y = 0;
m_mg_value = 0;
m_mg_lng = 0;
m_mg_direction = std::string();
}
const bool Control::MG_start( const GdkEventButton* event )
{
if( ! CONFIG::get_enable_mg() ) return false;
MG_reset();
if( ! button_alloted( event, CONTROL::GestureButton ) ) return false;
m_mg = true;
m_mg_x = ( int ) event->x;
m_mg_y = ( int ) event->y;
#ifdef _DEBUG
std::cout << "Control::MG_start\n";
#endif
return true;
}
const bool Control::MG_motion( const GdkEventMotion* event )
{
if( ! m_mg ) return false;
if( m_mg_lng >= MAX_MG_LNG ) return false;
if( m_mg_direction.empty() ){
if( m_send_mg_info ) CORE::core_set_command( "set_mginfo", "", "■" );
}
const int x = ( int ) event->x;
const int y = ( int ) event->y;
const int dx = x - m_mg_x;
const int dy = y - m_mg_y;
int direction = 0;
std::string str_direction;
const int radius = CONFIG::get_mouse_radius();
if( dx < 0 && -dx > radius ){
direction = 4;
str_direction = "←";
}
else if( dx > 0 && dx > radius ){
direction = 6;
str_direction = "→";
}
else if( dy < 0 && -dy > radius ){
direction = 8;
str_direction = "↑";
}
else if( dy > 0 && dy > radius ){
direction = 2;
str_direction = "↓";
}
#ifdef _DEBUG
std::cout << " x = " << x << " y = " << y
<< " mg_x = " << m_mg_x << " mg_y = " << m_mg_y
<< " dx = " << dx << " dy = " << dy;
#endif
if( direction ){
m_mg_x = x;
m_mg_y = y;
// 方向更新
if( m_mg_value % 10 != direction ){
m_mg_value = m_mg_value * 10 + direction;
++m_mg_lng;
m_mg_direction += str_direction;
const bool ctrl = false;
const bool shift = false;
const bool alt = false;
const bool dblclick = false;
const bool trpclick = false;
int control = CONTROL::None;
std::vector< int >::iterator it = m_mode.begin();
for( ; it != m_mode.end(); ++it ){
control = CONTROL::get_mouseconfig()->get_id( *it, m_mg_value, ctrl, shift, alt, dblclick, trpclick );
if( control != CONTROL::None ) break;
}
if( m_send_mg_info ) CORE::core_set_command( "set_mginfo", "", "■" + m_mg_direction + CONTROL::get_label( control ) );
}
}
#ifdef _DEBUG
std::cout << " dir = " << direction << " val = " << m_mg_value << std::endl;
#endif
return true;
}
// 戻り値はコントロールID
const int Control::MG_end( const GdkEventButton* event )
{
if( ! m_mg ) return None;
#ifdef _DEBUG
std::cout << "Control::MG_end val = " << m_mg_value << std::endl;
#endif
const bool ctrl = false;
const bool shift = false;
const bool alt = false;
const bool dblclick = false;
const bool trpclick = false;
int control = CONTROL::None;
std::vector< int >::iterator it = m_mode.begin();
for( ; it != m_mode.end(); ++it ){
control = CONTROL::get_mouseconfig()->get_id( *it, m_mg_value, ctrl, shift, alt, dblclick, trpclick );
if( control != CONTROL::None ) break;
}
std::string str_command = CONTROL::get_label( control );
if( m_mg_lng ){
if( control == CONTROL::None ){
str_command = "Cancel";
control = CONTROL::CancelMG;
}
m_mg_direction += " " + str_command;
if( m_send_mg_info ) CORE::core_set_command( "set_mginfo", "", "■" + m_mg_direction );
}
MG_reset();
return control;
}
///////////////////////////////////////
//
// ホイールマウスジェスチャ
void Control::MG_wheel_reset()
{
mg_wheel_done = false;
m_wheel_scroll_time = 0;
}
// ホイールマウスジェスチャ開始
const bool Control::MG_wheel_start( const GdkEventButton* event )
{
MG_wheel_reset();
if( ! button_alloted( event, CONTROL::GestureButton ) ) return false;
#ifdef _DEBUG
std::cout << "Control::MG_wheel_start\n";
#endif
return true;
}
// ホイールマウスジェスチャ。 戻り値はコントロールID
const int Control::MG_wheel_scroll( const GdkEventScroll* event )
{
int control = CONTROL::None;
const guint direction = event->direction;
// あまり速く動かした場合はキャンセル
const int time_cancel = 15; // msec
const int time_tmp = event->time - m_wheel_scroll_time;
if( m_wheel_scroll_time && time_tmp < time_cancel ) return control;
m_wheel_scroll_time = event->time;
// 押しているボタンは event から取れないので
// get_pointer()から取る
int x, y;
Gdk::ModifierType mask;
Gdk::Display::get_default()->get_pointer( x, y, mask );
int button = 0;
GdkEventButton ev = GdkEventButton();
get_eventbutton( CONTROL::GestureButton, ev );
switch( ev.button ){
case 1: button = Gdk::BUTTON1_MASK; break;
case 2: button = Gdk::BUTTON2_MASK; break;
case 3: button = Gdk::BUTTON3_MASK; break;
}
const bool ctrl = false;
const bool shift = false;
const bool alt = false;
const bool dblclick = false;
const bool trpclick = false;
if( direction == GDK_SCROLL_LEFT ){
button = 6;
std::vector< int >::iterator it = m_mode.begin();
for( ; it != m_mode.end(); ++it ){
control = CONTROL::get_buttonconfig()->get_id( *it, button, ctrl, shift, alt, dblclick, trpclick );
if( control != CONTROL::None ) break;
}
}
else if( direction == GDK_SCROLL_RIGHT ){
button = 7;
std::vector< int >::iterator it = m_mode.begin();
for( ; it != m_mode.end(); ++it ){
control = CONTROL::get_buttonconfig()->get_id( *it, button, ctrl, shift, alt, dblclick, trpclick );
if( control != CONTROL::None ) break;
}
}
else if( ( mask & button ) && direction == GDK_SCROLL_UP ) control = CONTROL::TabLeft;
else if( ( mask & button ) && direction == GDK_SCROLL_DOWN ) control = CONTROL::TabRight;
#ifdef _DEBUG
std::cout << "Control::MG_wheel_scroll control = " << control << std::endl;
#endif
if( control != CONTROL::None ){
if( m_send_mg_info ) CORE::core_set_command( "set_mginfo", "", CONTROL::get_label( control ) );
mg_wheel_done = true;
}
return control;
}
// ホイールマウスジェスチャ終了
// もしジェスチャが実行されたら true が戻る
const bool Control::MG_wheel_end( const GdkEventButton* event )
{
#ifdef _DEBUG
std::cout << "Control::MG_wheel_end\n";
#endif
const bool ret = mg_wheel_done;
MG_wheel_reset();
return ret;
}
| gpl-2.0 |
zkota/pyblio-1.2 | Pyblio/GnomeUI/Fields.py | 15638 | # This file is part of pybliographer
#
# Copyright (C) 1998-2004 Frederic GOBRY
# Email : gobry@pybliographer.org
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#
'''This module provides a dialog to configure the structure of the
bibliography '''
# TO DO:
# adapt menu item for this dialog
# cleaning up
import gobject, gtk
import copy, os, re, string
from Pyblio import Config, Fields, Types, version
from Pyblio.GnomeUI import Utils
_typename = {
Fields.AuthorGroup : _('Authors'),
Fields.Text : _('Text'),
Fields.LongText : _('Long Text'),
Fields.URL : _('URL'),
Fields.Reference : _('Reference'),
Fields.Date : _('Date')
}
class FieldsDialog (Utils.GladeWindow):
gladeinfo = {
'file': 'fields1.glade',
'name': 'fields',
'root': 'fields1'
}
def __init__ (self, parent = None):
Utils.GladeWindow.__init__ (self, parent)
self.dialog = self.xml.get_widget ('fields1')
self.w = self.xml.get_widget ('notebook')
## tooltips = gtk.Tooltips ()
## tooltips.enable ()
self.warning = 0
self.parent = parent
self.init_page_1()
self.init_page_2()
self.init_page_3()
self.show()
self.changed = 0
return
def show(self):
self.dialog.show_all ()
def on_close (self, w):
self.dialog.hide_all()
self.size_save ()
return
def on_add(self, *args):
page = self.w.get_current_page ()
if page == 0: self.page1_add (*args)
elif page == 1: self.page2_add (*args)
elif page == 2: self.page3_add (*args)
def on_remove (self, *args):
page = self.w.get_current_page()
if page == 0: self.page1_rm (*args)
elif page == 1: self.page2_rm (*args)
elif page == 2: self.page3_rm (*args)
def on_help (self, *args):
print 'ON HELP:', args
def check (self):
if len(self.fields) != len(self.fm):
print 'ERROR LEN OF FIELDS (%d) /= LEN OF FM (%d)' %(
len(self.fields), len(self.fm))
import traceback
traceback.print_tb()
k = self.fields.keys()
l = []
for i in self.fm:
j = i[2]
l.append(j)
try: k.remove(j)
except KeyError:
print 'fieldname %s (%s) not in Keys' %(
j, i[0])
if k:
print 'keys %s unused' %(k)
#------------------------------------------------------------
# Page 1
def init_page_1 (self):
self.fields1 = self.xml.get_widget('f_list_1')
rend = gtk.CellRendererText()
col = gtk.TreeViewColumn(_('Name'), rend, text = 0)
self.fields1.append_column(col)
rend = gtk.CellRendererText()
col = gtk.TreeViewColumn(_('Type'), rend, text = 1)
self.fields1.append_column(col)
self.fm = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING,
gobject.TYPE_STRING, gobject.TYPE_PYOBJECT)
self.sfm = gtk.TreeModelSort(self.fm)
self.sfm.set_sort_column_id(2, gtk.SORT_ASCENDING)
self.fields1.set_model(self.sfm)
self.s1 = self.fields1.get_selection()
self.s1.connect ('changed', self.list_1_select)
self.fields = copy.copy (Config.get ('base/fields').data)
for key, item in self.fields.iteritems():
self.fm.append((item.name,
_typename [item.type], key, item))
self.name1 = self.xml.get_widget('name1')
self.menu1 = self.xml.get_widget('type1')
menu = gtk.Menu ()
self.menu1.set_menu (menu)
self.menu_items = _typename.keys ()
for item in self.menu_items:
Utils.popup_add (menu, _typename [item], self.select_menu, item)
self.menu1.set_history (0)
self.current_menu = self.menu_items [0]
self.check()
def page1_add (self, *args):
t = self.menu_items[0]
description = Types.FieldDescription('')
iter = self.fm.append((
'new field', _typename[t], '_new field_',
description))
if iter:
s_iter = self.sfm.convert_child_iter_to_iter(None, iter)
s_path = self.sfm.get_path(s_iter)
self.fields1.scroll_to_cell(s_path)
self.s1.select_iter(s_iter)
self.check()
# Config save?
def page1_rm (self, *args):
m, iter = self.s1.get_selected()
if iter:
p = self.sfm.convert_iter_to_child_iter(None, iter)
#print 'SELF:FM[P][2]:', self.fm[p] [2]
try: del self.fields [self.fm[p][2]]
except KeyError: pass
self.fm.remove(p)
Config.set_and_save('base/fields', self.fields)
self.check()
def list_1_select (self, sel):
m, iter = sel.get_selected()
if iter:
p = self.sfm.convert_iter_to_child_iter(None, iter)
data = self.fm[p]
self.name1.set_text(self.fm[p][0])
try:
self.menu1.set_history (
self.menu_items.index(self.fm[p][3].type))
except ValueError:
print self.menu_items, self.fm[p][0], self.fm[p][2]
def on_name1_changed (self, *args):
sel = self.fields1.get_selection()
m, iter = sel.get_selected()
if iter:
p = self.sfm.convert_iter_to_child_iter(None, iter)
oldname = self.fm[p][2]
newname = self.name1.get_text()
try: del self.fields [oldname]
except KeyError: pass
self.fm[p] [0] = newname
self.fm[p] [2] = newname.lower()
self.fm[p] [3].name = newname
self.fields [newname.lower()] = self.fm[p][3]
self.check()
self.change_fields()
def on_type1_changed (self, *args):
x = self.menu_items[self.menu1.get_history()]
sel = self.fields1.get_selection()
m, iter = sel.get_selected()
if iter:
p = self.sfm.convert_iter_to_child_iter(None, iter)
#print 'TYP!', args, x, sel, m, iter
self.fm[p] [1] = _typename[x]
self.fm[p] [3].type = x
self.change_fields()
self.check()
#------------------------------------------------------------
# Page 2
def init_page_2 (self):
# PAGE 2
self.entries2 = self.xml.get_widget('e_list_2')
self.em = gtk.ListStore(gobject.TYPE_STRING,
gobject.TYPE_PYOBJECT,
gobject.TYPE_STRING )
self.entries = copy.copy (Config.get ('base/entries').data)
for i in self.entries.itervalues():
self.em.append ((i.name, i, i.name.lower()))
self.sem = gtk.TreeModelSort(self.em)
self.sem.set_sort_column_id(2, gtk.SORT_ASCENDING)
self.entries2.set_model(self.sem)
rend = gtk.CellRendererText()
col = gtk.TreeViewColumn(_('Entry type'), rend, text = 0)
self.entries2.append_column(col)
self.name2 = self.xml.get_widget('name2')
self.s2 = self.entries2.get_selection()
self.s2.connect('changed', self.elist_select)
self.check()
def page2_add (self, *args):
description = Types.EntryDescription('NEW')
iter = self.em.append(('NEW', description, 'new'))
if iter:
s_iter = self.sem.convert_child_iter_to_iter(None, iter)
s_path = self.sem.get_path(s_iter)
self.entries2.scroll_to_cell(s_path)
self.s2.select_iter(s_iter)
self.entries [self.em[iter][2]] = self.em[iter][1]
self.check()
def page2_rm (self, *args):
self.check()
m, iter = self.s2.get_selected()
if iter:
p = self.sem.convert_iter_to_child_iter(None, iter)
del self.entries [self.em[p] [2]]
self.em.remove(p)
Config.set_and_save('base/entries', self.entries)
self.check()
def elist_select (self, sel):
self.list_2_select(sel)
def list_2_select (self, sel):
m, iter = sel.get_selected()
if iter:
p = self.sem.convert_iter_to_child_iter(None, iter)
self.name2.set_text (self.em[p] [0])
self.page3_setup (self.em[p] [1])
self.check()
def on_name2_changed (self, *args):
sel = self.entries2.get_selection()
m, iter = sel.get_selected()
if iter:
p = self.sem.convert_iter_to_child_iter(None, iter)
newname = self.name2.get_text()
try: del self.entries [self.em[p][2]]
except KeyError: print 'Keyerror', self.em[
p] [2], self.entries.keys()
self.em[p][1].name = newname
self.em[p][0] = newname
self.em[p][2] = newname.lower()
self.entries[newname.lower()] = self.em[p][1]
Config.set_and_save ('base/entries', self.entries)
self.check()
#print self.entries.keys()
#------------------------------------------------------------
# Page 3
def init_page_3 (self):
self.flist3a = self.xml.get_widget ('f_list_3a')
self.flist3a.set_model (self.sfm)
rend = gtk.CellRendererText()
col = gtk.TreeViewColumn(_('Available'), rend, text = 0)
self.flist3a.append_column(col)
self.s3a = self.flist3a.get_selection()
self.label3 = self.xml.get_widget ('entry_type_label')
self.flist3b = self.xml.get_widget ('f_list_3b')
rend = gtk.CellRendererToggle()
rend.connect('toggled', self.toggle_mandatory)
col = gtk.TreeViewColumn('X', rend, active = 1)
self.flist3b.append_column(col)
rend = gtk.CellRendererText()
col = gtk.TreeViewColumn(_('Associated'), rend, text = 2)
self.flist3b.append_column(col)
self.sm = gtk.ListStore(gobject.TYPE_STRING,
gobject.TYPE_BOOLEAN,
gobject.TYPE_STRING,
gobject.TYPE_PYOBJECT)
self.ssm = gtk.TreeModelSort(self.sm)
self.ssm.set_sort_column_id(0, gtk.SORT_ASCENDING)
self.flist3b.set_model(self.ssm)
self.s3b = self.flist3b.get_selection()
self.label3.set_markup (
_('Please, select an entry type from previous page.' ))
self.check()
def page3_setup (self, item):
self.sm.clear()
self.current_entry = item
for i in item.mandatory:
self.sm.append((i.name, True, i.name, i))
for i in item.optional:
self.sm.append((i.name, False, i.name, i))
self.label3.set_markup (
_('Fields associated with <b>%s</b> entry type') %
item.name)
self.check()
def page3_add (self, *args):
m, iter = self.s3a.get_selected()
if iter:
p = self.sfm.convert_iter_to_child_iter(None, iter)
field = self.fm[p] [3]
self.current_entry.optional.append(field)
self.sm.append ((field.name, False, field.name, field))
Config.set_and_save('base/entries', self.entries)
self.check()
def page3_rm (self, *args):
m, iter = self.s3b.get_selected()
if iter:
p = self.ssm.convert_iter_to_child_iter (None, iter)
field = self.sm[p] [3]
if self.sm[p] [1]:
self.current_entry.mandatory.remove(field)
else:
self.current_entry.optional.remove(field)
del self.sm [p]
Config.set_and_save('base/entries', self.entries)
self.check()
def toggle_mandatory (self, rend, path):
p = self.ssm.convert_path_to_child_path(path)
iter = self.sm.get_iter(p)
field = self.sm[iter][3]
x = self.sm.get_value (iter, 1)
self.sm.set_value(iter, 1, not x)
if x:
self.current_entry.mandatory.remove(field)
self.current_entry.optional.append(field)
else:
self.current_entry.optional.remove(field)
self.current_entry.mandatory.append(field)
self.entries [self.current_entry.name.lower()] = self.current_entry
Config.set_and_save ('base/entries', self.entries)
self.check()
def select_menu (self, w, data):
self.current_menu = data
return
def change_fields (self, item=None):
Config.set_and_save('base/fields', self.fields)
def set (self, data):
self.list.freeze ()
self.list.clear ()
self.data = data
keys = self.data.keys ()
keys.sort ()
for key in keys:
item = self.data [key]
self.list.append ((item.name, _typename [item.type]))
self.list.set_row_data (self.list.rows - 1, item)
self.list.thaw ()
pass
def get (self):
return self.data
def select_row (self, widget, row, col, event):
item = self.list.get_row_data (row)
self.name.set_text (item.name)
self.menu1.set_history (self.menu_items.index (item.type))
self.current_menu = item.type
return
def apply (self, * arg):
if not self.changed: return
result = self.get ()
Config.set_and_save ('base/fields', result)
if self.parent:
self.parent.warning (_("Some changes require to restart Pybliographic\n"
"to be correctly taken into account"))
return
def add_cb (self, * arg):
name = string.strip (self.name.get_text ())
if name == '': return
table = self.get ()
field = Types.FieldDescription (name, self.current_menu)
table [string.lower (name)] = field
self.set (table)
self.changed = 1
return
def remove_cb (self, * arg):
selection = self.list.selection
if not selection: return
selection = selection [0]
item = self.list.get_row_data (selection)
table = self.get ()
del table [string.lower (item.name)]
self.set (table)
self.changed = 1
return
_status = (
'',
_("Mandatory"),
_("Optional")
)
__fields_object = None
def run (w):
global __fields_object
if __fields_object:
__fields_object.show()
else:
def is_destroyed (* args):
global __fields_object
__fields_object = None
__fields_object = FieldsDialog(w)
__fields_object.dialog.connect ('destroy', is_destroyed)
| gpl-2.0 |
torraodocerrado/leader_election_sinalgo | src/projects/t1/LogFile.java | 1484 | package projects.t1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public final class LogFile {
private File file;
private FileOutputStream fos;
private double step;
public FileOutputStream getFos() {
return fos;
}
public void setFos(FileOutputStream fos) {
this.fos = fos;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public LogFile(String nameFile) {
try {
this.setFile(new File(nameFile));
this.setFos(new FileOutputStream(this.file));
} catch (FileNotFoundException e) {
System.err.println("Erro encontrado: " + e.getMessage());
}
}
public void CloseReport() {
try {
this.fos.close();
} catch (IOException e) {
System.err.println("Erro encontrado: " + e.getMessage());
}
}
public void add(Object textIn) {
try {
String text = textIn.toString() + ";";
this.fos.write(text.getBytes());
} catch (IOException e) {
System.err.println("Erro encontrado: " + e.getMessage());
}
}
public void ln() {
try {
String text = "\n";
this.fos.write(text.getBytes());
} catch (IOException e) {
System.err.println("Erro encontrado: " + e.getMessage());
}
}
public void setStep(double currentTime) {
this.step = currentTime;
}
public void addStep(double currentTime, Object linhe) {
if (this.step < currentTime) {
this.step = currentTime;
this.add(linhe);
}
}
}
| gpl-2.0 |
xdajog/samsung_sources_i927 | external/webkit/Source/WebCore/dom/Document.cpp | 176904 | /*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* (C) 2006 Alexey Proskuryakov (ap@webkit.org)
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2011 Apple Inc. All rights reserved.
* Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
* Copyright (C) 2008, 2009 Google Inc. All rights reserved.
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "Document.h"
#include "AXObjectCache.h"
#include "AnimationController.h"
#include "Attr.h"
#include "Attribute.h"
#include "CDATASection.h"
#include "CSSPrimitiveValueCache.h"
#include "CSSStyleSelector.h"
#include "CSSStyleSheet.h"
#include "CSSValueKeywords.h"
#include "CachedCSSStyleSheet.h"
#include "CachedResourceLoader.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "Comment.h"
#include "Console.h"
#include "ContentSecurityPolicy.h"
#include "CookieJar.h"
#include "CustomEvent.h"
#include "DateComponents.h"
#include "DOMImplementation.h"
#include "DOMWindow.h"
#include "DeviceMotionEvent.h"
#include "DeviceOrientationEvent.h"
#include "DocumentFragment.h"
#include "DocumentLoader.h"
#include "DocumentMarkerController.h"
#include "DocumentType.h"
#include "EditingText.h"
#include "Editor.h"
#include "Element.h"
#include "EntityReference.h"
#include "Event.h"
#include "EventHandler.h"
#include "EventListener.h"
#include "EventNames.h"
#include "EventQueue.h"
#include "ExceptionCode.h"
#include "FocusController.h"
#include "FormAssociatedElement.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameLoaderClient.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "HashChangeEvent.h"
#include "HTMLAllCollection.h"
#include "HTMLAnchorElement.h"
#include "HTMLBodyElement.h"
#include "HTMLCanvasElement.h"
#include "HTMLCollection.h"
#include "HTMLDocument.h"
#include "HTMLElementFactory.h"
#include "HTMLFrameOwnerElement.h"
#include "HTMLHeadElement.h"
#include "HTMLIFrameElement.h"
#include "HTMLInputElement.h"
#include "HTMLLinkElement.h"
#include "HTMLMapElement.h"
#include "HTMLNameCollection.h"
#include "HTMLNames.h"
#include "HTMLParserIdioms.h"
#include "HTMLStyleElement.h"
#include "HTMLTitleElement.h"
#include "HTTPParsers.h"
#include "HitTestRequest.h"
#include "HitTestResult.h"
#include "ImageLoader.h"
#include "InspectorInstrumentation.h"
#include "KeyboardEvent.h"
#include "Logging.h"
#include "MediaQueryList.h"
#include "MediaQueryMatcher.h"
#include "MessageEvent.h"
#include "MouseEvent.h"
#include "MouseEventWithHitTestResults.h"
#include "MutationEvent.h"
#include "NameNodeList.h"
#include "NestingLevelIncrementer.h"
#include "NodeFilter.h"
#include "NodeIterator.h"
#include "NodeWithIndex.h"
#include "OverflowEvent.h"
#include "Page.h"
#include "PageGroup.h"
#include "PageTransitionEvent.h"
#include "PlatformKeyboardEvent.h"
#include "PopStateEvent.h"
#include "ProcessingInstruction.h"
#include "ProgressEvent.h"
#include "RegisteredEventListener.h"
#include "RenderArena.h"
#include "RenderLayer.h"
#include "RenderLayerBacking.h"
#include "RenderTextControl.h"
#include "RenderView.h"
#include "RenderWidget.h"
#include "ScopedEventQueue.h"
#include "ScriptCallStack.h"
#include "ScriptController.h"
#include "ScriptElement.h"
#include "ScriptEventListener.h"
#include "ScriptRunner.h"
#include "SecurityOrigin.h"
#include "SegmentedString.h"
#include "SelectionController.h"
#include "Settings.h"
#include "StaticHashSetNodeList.h"
#include "StyleSheetList.h"
#include "TextEvent.h"
#include "TextResourceDecoder.h"
#include "Timer.h"
#include "TransformSource.h"
#include "TreeWalker.h"
#include "UIEvent.h"
#include "UserContentURLPattern.h"
#include "WebKitAnimationEvent.h"
#include "WebKitTransitionEvent.h"
#include "WheelEvent.h"
#include "XMLDocumentParser.h"
#include "XMLHttpRequest.h"
#include "XMLNSNames.h"
#include "XMLNames.h"
//SAMSUNG WML CHANGE >>
#include "XMLValidatingTokenizer.h"
//SAMSUNG WML CHANGE <<
#include "htmlediting.h"
#include <wtf/CurrentTime.h>
#include <wtf/HashFunctions.h>
#include <wtf/MainThread.h>
#include <wtf/PassRefPtr.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/StringBuffer.h>
#if ENABLE(SHARED_WORKERS)
#include "SharedWorkerRepository.h"
#endif
#if ENABLE(DOM_STORAGE)
#include "StorageEvent.h"
#endif
#if ENABLE(XPATH)
#include "XPathEvaluator.h"
#include "XPathExpression.h"
#include "XPathNSResolver.h"
#include "XPathResult.h"
#endif
#if ENABLE(XSLT)
#include "XSLTProcessor.h"
#endif
#if ENABLE(SVG)
#include "SVGDocumentExtensions.h"
#include "SVGElementFactory.h"
#include "SVGNames.h"
#include "SVGStyleElement.h"
#include "SVGZoomEvent.h"
#endif
#ifdef ANDROID_META_SUPPORT
#include "PlatformBridge.h"
#include "Settings.h"
#endif
#ifdef ANDROID_RESET_SELECTION
#include "CacheBuilder.h"
#include "HTMLTextAreaElement.h"
#endif
#ifdef ANDROID_INSTRUMENT
#include "TimeCounter.h"
#endif
#if ENABLE(TOUCH_EVENTS)
#if USE(V8)
#include "RuntimeEnabledFeatures.h"
#endif
#include "TouchEvent.h"
#endif
#if ENABLE(WML)
#include "WMLDocument.h"
#include "WMLElement.h"
#include "WMLElementFactory.h"
#include "WMLNames.h"
#endif
#if ENABLE(MATHML)
#include "MathMLElement.h"
#include "MathMLElementFactory.h"
#include "MathMLNames.h"
#endif
#if ENABLE(XHTMLMP)
#include "HTMLNoScriptElement.h"
#endif
#if ENABLE(FULLSCREEN_API)
#include "RenderFullScreen.h"
#endif
#if ENABLE(REQUEST_ANIMATION_FRAME)
#include "RequestAnimationFrameCallback.h"
#include "ScriptedAnimationController.h"
#endif
//SAMSUNG MICRODATA CHANGES <<
#if ENABLE(MICRODATA)
#include "MicroDataItemList.h"
#include "NodeRareData.h"
#endif
//SAMSUNG MICRODATA CHANGES >>
using namespace std;
using namespace WTF;
using namespace Unicode;
namespace WebCore {
using namespace HTMLNames;
// #define INSTRUMENT_LAYOUT_SCHEDULING 1
static const unsigned cMaxWriteRecursionDepth = 21;
// This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
// FIXME: For faster machines this value can really be lowered to 200. 250 is adequate, but a little high
// for dual G5s. :)
static const int cLayoutScheduleThreshold = 250;
// DOM Level 2 says (letters added):
//
// a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
// b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
// c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
// d) Characters which have a font or compatibility decomposition (i.e. those with a "compatibility formatting tag" in field 5 of the database -- marked by field 5 beginning with a "<") are not allowed.
// e) The following characters are treated as name-start characters rather than name characters, because the property file classifies them as Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.
// f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
// g) Character #x00B7 is classified as an extender, because the property list so identifies it.
// h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
// i) Characters ':' and '_' are allowed as name-start characters.
// j) Characters '-' and '.' are allowed as name characters.
//
// It also contains complete tables. If we decide it's better, we could include those instead of the following code.
static inline bool isValidNameStart(UChar32 c)
{
// rule (e) above
if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
return true;
// rule (i) above
if (c == ':' || c == '_')
return true;
// rules (a) and (f) above
const uint32_t nameStartMask = Letter_Lowercase | Letter_Uppercase | Letter_Other | Letter_Titlecase | Number_Letter;
if (!(Unicode::category(c) & nameStartMask))
return false;
// rule (c) above
if (c >= 0xF900 && c < 0xFFFE)
return false;
// rule (d) above
DecompositionType decompType = decompositionType(c);
if (decompType == DecompositionFont || decompType == DecompositionCompat)
return false;
return true;
}
static inline bool isValidNamePart(UChar32 c)
{
// rules (a), (e), and (i) above
if (isValidNameStart(c))
return true;
// rules (g) and (h) above
if (c == 0x00B7 || c == 0x0387)
return true;
// rule (j) above
if (c == '-' || c == '.')
return true;
// rules (b) and (f) above
const uint32_t otherNamePartMask = Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining | Letter_Modifier | Number_DecimalDigit;
if (!(Unicode::category(c) & otherNamePartMask))
return false;
// rule (c) above
if (c >= 0xF900 && c < 0xFFFE)
return false;
// rule (d) above
DecompositionType decompType = decompositionType(c);
if (decompType == DecompositionFont || decompType == DecompositionCompat)
return false;
return true;
}
static Widget* widgetForNode(Node* focusedNode)
{
if (!focusedNode)
return 0;
RenderObject* renderer = focusedNode->renderer();
if (!renderer || !renderer->isWidget())
return 0;
return toRenderWidget(renderer)->widget();
}
static bool acceptsEditingFocus(Node* node)
{
ASSERT(node);
ASSERT(node->rendererIsEditable());
Node* root = node->rootEditableElement();
Frame* frame = node->document()->frame();
if (!frame || !root)
return false;
return frame->editor()->shouldBeginEditing(rangeOfContents(root).get());
}
static bool disableRangeMutation(Page* page)
{
// This check is made on super-hot code paths, so we only want this on Tiger and Leopard.
#if defined(TARGETING_TIGER) || defined(TARGETING_LEOPARD)
// Disable Range mutation on document modifications in Tiger and Leopard Mail
// See <rdar://problem/5865171>
return page && (page->settings()->needsLeopardMailQuirks() || page->settings()->needsTigerMailQuirks());
#else
UNUSED_PARAM(page);
return false;
#endif
}
static HashSet<Document*>* documentsThatNeedStyleRecalc = 0;
class DocumentWeakReference : public ThreadSafeRefCounted<DocumentWeakReference> {
public:
static PassRefPtr<DocumentWeakReference> create(Document* document)
{
return adoptRef(new DocumentWeakReference(document));
}
Document* document()
{
ASSERT(isMainThread());
return m_document;
}
void clear()
{
ASSERT(isMainThread());
m_document = 0;
}
private:
DocumentWeakReference(Document* document)
: m_document(document)
{
ASSERT(isMainThread());
}
Document* m_document;
};
uint64_t Document::s_globalTreeVersion = 0;
Document::Document(Frame* frame, const KURL& url, bool isXHTML, bool isHTML)
: TreeScope(this)
, m_guardRefCount(0)
, m_compatibilityMode(NoQuirksMode)
, m_compatibilityModeLocked(false)
, m_domTreeVersion(++s_globalTreeVersion)
#ifdef ANDROID_STYLE_VERSION
, m_styleVersion(0)
#endif
, m_styleSheets(StyleSheetList::create(this))
, m_readyState(Complete)
, m_styleRecalcTimer(this, &Document::styleRecalcTimerFired)
, m_pendingStyleRecalcShouldForce(false)
, m_frameElementsShouldIgnoreScrolling(false)
, m_containsValidityStyleRules(false)
, m_updateFocusAppearanceRestoresSelection(false)
, m_ignoreDestructiveWriteCount(0)
, m_titleSetExplicitly(false)
, m_updateFocusAppearanceTimer(this, &Document::updateFocusAppearanceTimerFired)
, m_startTime(currentTime())
, m_overMinimumLayoutThreshold(false)
, m_extraLayoutDelay(0)
, m_scriptRunner(ScriptRunner::create(this))
, m_xmlVersion("1.0")
, m_xmlStandalone(false)
, m_savedRenderer(0)
, m_designMode(inherit)
#if ENABLE(SVG)
, m_svgExtensions(0)
#endif
#if ENABLE(DASHBOARD_SUPPORT)
, m_hasDashboardRegions(false)
, m_dashboardRegionsDirty(false)
#endif
, m_createRenderers(true)
, m_inPageCache(false)
, m_useSecureKeyboardEntryWhenActive(false)
, m_isXHTML(isXHTML)
, m_isHTML(isHTML)
, m_usesViewSourceStyles(false)
, m_sawElementsInKnownNamespaces(false)
, m_usingGeolocation(false)
, m_eventQueue(EventQueue::create(this))
#if ENABLE(WML)
, m_containsWMLContent(false)
#endif
, m_weakReference(DocumentWeakReference::create(this))
, m_idAttributeName(idAttr)
#if ENABLE(FULLSCREEN_API)
, m_areKeysEnabledInFullScreen(0)
, m_fullScreenRenderer(0)
, m_fullScreenChangeDelayTimer(this, &Document::fullScreenChangeDelayTimerFired)
#endif
, m_loadEventDelayCount(0)
, m_loadEventDelayTimer(this, &Document::loadEventDelayTimerFired)
, m_directionSetOnDocumentElement(false)
, m_writingModeSetOnDocumentElement(false)
, m_writeRecursionIsTooDeep(false)
, m_writeRecursionDepth(0)
{
m_document = this;
m_pageGroupUserSheetCacheValid = false;
m_printing = false;
m_paginatedForScreen = false;
m_ignoreAutofocus = false;
m_frame = frame;
//SAMSUNG CHANGES : FACEBOOK PERFORMANCE IMPROVEMENT : Praveen Munukutla(sataya.m@samsung.com)>>>
m_getBackOrForward = false;
//SAMSUNG CHANGES : FACEBOOK PERFORMANCE IMPROVEMENT : Praveen Munukutla(sataya.m@samsung.com)<<<
// We depend on the url getting immediately set in subframes, but we
// also depend on the url NOT getting immediately set in opened windows.
// See fast/dom/early-frame-url.html
// and fast/dom/location-new-window-no-crash.html, respectively.
// FIXME: Can/should we unify this behavior?
if ((frame && frame->ownerElement()) || !url.isEmpty())
setURL(url);
#if !PLATFORM(ANDROID)
m_axObjectCache = 0;
#endif
m_markers = new DocumentMarkerController();
m_cachedResourceLoader = new CachedResourceLoader(this);
m_visuallyOrdered = false;
m_bParsing = false;
m_wellFormed = false;
m_textColor = Color::black;
m_listenerTypes = 0;
setInDocument();
m_inStyleRecalc = false;
m_closeAfterStyleRecalc = false;
m_usesSiblingRules = false;
m_usesSiblingRulesOverride = false;
m_usesFirstLineRules = false;
m_usesFirstLetterRules = false;
m_usesBeforeAfterRules = false;
m_usesBeforeAfterRulesOverride = false;
m_usesRemUnits = false;
m_usesLinkRules = false;
m_gotoAnchorNeededAfterStylesheetsLoad = false;
m_didCalculateStyleSelector = false;
m_hasDirtyStyleSelector = false;
m_pendingStylesheets = 0;
m_ignorePendingStylesheets = false;
m_hasNodesWithPlaceholderStyle = false;
m_pendingSheetLayout = NoLayoutWithPendingSheets;
m_cssTarget = 0;
resetLinkColor();
resetVisitedLinkColor();
resetActiveLinkColor();
m_processingLoadEvent = false;
initSecurityContext();
initDNSPrefetch();
static int docID = 0;
m_docID = docID++;
#if ENABLE(XHTMLMP)
m_shouldProcessNoScriptElement = !(m_frame && m_frame->script()->canExecuteScripts(NotAboutToExecuteScript));
#endif
}
Document::~Document()
{
ASSERT(!renderer());
ASSERT(!m_inPageCache);
ASSERT(!m_savedRenderer);
ASSERT(m_ranges.isEmpty());
ASSERT(!m_styleRecalcTimer.isActive());
ASSERT(!m_parentTreeScope);
m_scriptRunner.clear();
removeAllEventListeners();
// Currently we believe that Document can never outlive the parser.
// Although the Document may be replaced synchronously, DocumentParsers
// generally keep at least one reference to an Element which would in turn
// has a reference to the Document. If you hit this ASSERT, then that
// assumption is wrong. DocumentParser::detach() should ensure that even
// if the DocumentParser outlives the Document it won't cause badness.
ASSERT(!m_parser || m_parser->refCount() == 1);
detachParser();
m_document = 0;
m_cachedResourceLoader.clear();
m_renderArena.clear();
clearAXObjectCache();
m_decoder = 0;
for (size_t i = 0; i < m_nameCollectionInfo.size(); ++i)
deleteAllValues(m_nameCollectionInfo[i]);
if (m_styleSheets)
m_styleSheets->documentDestroyed();
if (m_elemSheet)
m_elemSheet->clearOwnerNode();
if (m_mappedElementSheet)
m_mappedElementSheet->clearOwnerNode();
if (m_pageUserSheet)
m_pageUserSheet->clearOwnerNode();
if (m_pageGroupUserSheets) {
for (size_t i = 0; i < m_pageGroupUserSheets->size(); ++i)
(*m_pageGroupUserSheets)[i]->clearOwnerNode();
}
m_weakReference->clear();
if (m_mediaQueryMatcher)
m_mediaQueryMatcher->documentDestroyed();
if (m_implementation)
m_implementation->ownerDocumentDestroyed();
}
void Document::removedLastRef()
{
ASSERT(!m_deletionHasBegun);
if (m_guardRefCount) {
// If removing a child removes the last self-only ref, we don't
// want the scope to be destructed until after
// removeAllChildren returns, so we guard ourselves with an
// extra self-only ref.
guardRef();
// We must make sure not to be retaining any of our children through
// these extra pointers or we will create a reference cycle.
m_docType = 0;
m_focusedNode = 0;
m_hoverNode = 0;
m_activeNode = 0;
m_titleElement = 0;
m_documentElement = 0;
#if ENABLE(FULLSCREEN_API)
m_fullScreenElement = 0;
#endif
// removeAllChildren() doesn't always unregister IDs,
// so tear down scope information upfront to avoid having stale references in the map.
destroyTreeScopeData();
removeAllChildren();
m_markers->detach();
detachParser();
m_cssCanvasElements.clear();
#if ENABLE(REQUEST_ANIMATION_FRAME)
// FIXME: consider using ActiveDOMObject.
m_scriptedAnimationController = 0;
#endif
#ifndef NDEBUG
m_inRemovedLastRefFunction = false;
#endif
guardDeref();
} else {
#ifndef NDEBUG
m_deletionHasBegun = true;
#endif
delete this;
}
}
Element* Document::getElementById(const AtomicString& id) const
{
return TreeScope::getElementById(id);
}
MediaQueryMatcher* Document::mediaQueryMatcher()
{
if (!m_mediaQueryMatcher)
m_mediaQueryMatcher = MediaQueryMatcher::create(this);
return m_mediaQueryMatcher.get();
}
void Document::setCompatibilityMode(CompatibilityMode mode)
{
if (m_compatibilityModeLocked || mode == m_compatibilityMode)
return;
ASSERT(!documentElement() && !m_styleSheets->length());
bool wasInQuirksMode = inQuirksMode();
m_compatibilityMode = mode;
if (inQuirksMode() != wasInQuirksMode) {
// All user stylesheets have to reparse using the different mode.
clearPageUserSheet();
clearPageGroupUserSheets();
}
}
String Document::compatMode() const
{
return inQuirksMode() ? "BackCompat" : "CSS1Compat";
}
void Document::resetLinkColor()
{
m_linkColor = Color(0, 0, 238);
}
void Document::resetVisitedLinkColor()
{
m_visitedLinkColor = Color(85, 26, 139);
}
void Document::resetActiveLinkColor()
{
m_activeLinkColor.setNamedColor("red");
}
void Document::setDocType(PassRefPtr<DocumentType> docType)
{
// This should never be called more than once.
ASSERT(!m_docType || !docType);
m_docType = docType;
if (m_docType)
m_docType->setTreeScope(this);
#ifdef ANDROID_META_SUPPORT
if (m_docType && !ownerElement()
&& m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", false)) {
// fit mobile sites directly in the screen
processViewport("width=device-width");
}
#endif
}
DOMImplementation* Document::implementation()
{
if (!m_implementation)
m_implementation = DOMImplementation::create(this);
return m_implementation.get();
}
void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
TreeScope::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
// Invalidate the document element we have cached in case it was replaced.
m_documentElement = 0;
}
void Document::cacheDocumentElement() const
{
ASSERT(!m_documentElement);
m_documentElement = firstElementChild(this);
}
PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionCode& ec)
{
if (!isValidName(name)) {
ec = INVALID_CHARACTER_ERR;
return 0;
}
if (m_isXHTML)
return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, name, xhtmlNamespaceURI), this, 0, false);
return createElement(QualifiedName(nullAtom, name, nullAtom), false);
}
PassRefPtr<DocumentFragment> Document::createDocumentFragment()
{
return DocumentFragment::create(document());
}
PassRefPtr<Text> Document::createTextNode(const String& data)
{
return Text::create(this, data);
}
PassRefPtr<Comment> Document::createComment(const String& data)
{
return Comment::create(this, data);
}
PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionCode& ec)
{
if (isHTMLDocument()) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return CDATASection::create(this, data);
}
PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionCode& ec)
{
if (!isValidName(target)) {
ec = INVALID_CHARACTER_ERR;
return 0;
}
if (isHTMLDocument()) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return ProcessingInstruction::create(this, target, data);
}
PassRefPtr<EntityReference> Document::createEntityReference(const String& name, ExceptionCode& ec)
{
if (!isValidName(name)) {
ec = INVALID_CHARACTER_ERR;
return 0;
}
if (isHTMLDocument()) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return EntityReference::create(this, name);
}
PassRefPtr<EditingText> Document::createEditingTextNode(const String& text)
{
return EditingText::create(this, text);
}
PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
{
return CSSMutableStyleDeclaration::create();
}
PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionCode& ec)
{
ec = 0;
if (!importedNode
#if ENABLE(SVG) && ENABLE(DASHBOARD_SUPPORT)
|| (importedNode->isSVGElement() && page() && page()->settings()->usesDashboardBackwardCompatibilityMode())
#endif
) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
switch (importedNode->nodeType()) {
case TEXT_NODE:
return createTextNode(importedNode->nodeValue());
case CDATA_SECTION_NODE:
return createCDATASection(importedNode->nodeValue(), ec);
case ENTITY_REFERENCE_NODE:
return createEntityReference(importedNode->nodeName(), ec);
case PROCESSING_INSTRUCTION_NODE:
return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), ec);
case COMMENT_NODE:
return createComment(importedNode->nodeValue());
case ELEMENT_NODE: {
Element* oldElement = static_cast<Element*>(importedNode);
RefPtr<Element> newElement = createElementNS(oldElement->namespaceURI(), oldElement->tagQName().toString(), ec);
if (ec)
return 0;
NamedNodeMap* attrs = oldElement->attributes(true);
if (attrs) {
unsigned length = attrs->length();
for (unsigned i = 0; i < length; i++) {
Attribute* attr = attrs->attributeItem(i);
newElement->setAttribute(attr->name(), attr->value().impl(), ec);
if (ec)
return 0;
}
}
newElement->copyNonAttributeProperties(oldElement);
if (deep) {
for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
RefPtr<Node> newChild = importNode(oldChild, true, ec);
if (ec)
return 0;
newElement->appendChild(newChild.release(), ec);
if (ec)
return 0;
}
}
return newElement.release();
}
case ATTRIBUTE_NODE:
return Attr::create(0, this, static_cast<Attr*>(importedNode)->attr()->clone());
case DOCUMENT_FRAGMENT_NODE: {
DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
RefPtr<DocumentFragment> newFragment = createDocumentFragment();
if (deep) {
for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
RefPtr<Node> newChild = importNode(oldChild, true, ec);
if (ec)
return 0;
newFragment->appendChild(newChild.release(), ec);
if (ec)
return 0;
}
}
return newFragment.release();
}
case ENTITY_NODE:
case NOTATION_NODE:
// FIXME: It should be possible to import these node types, however in DOM3 the DocumentType is readonly, so there isn't much sense in doing that.
// Ability to add these imported nodes to a DocumentType will be considered for addition to a future release of the DOM.
case DOCUMENT_NODE:
case DOCUMENT_TYPE_NODE:
case XPATH_NAMESPACE_NODE:
break;
}
ec = NOT_SUPPORTED_ERR;
return 0;
}
PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionCode& ec)
{
if (!source) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
if (source->isReadOnlyNode()) {
ec = NO_MODIFICATION_ALLOWED_ERR;
return 0;
}
EventQueueScope scope;
switch (source->nodeType()) {
case ENTITY_NODE:
case NOTATION_NODE:
case DOCUMENT_NODE:
case DOCUMENT_TYPE_NODE:
case XPATH_NAMESPACE_NODE:
ec = NOT_SUPPORTED_ERR;
return 0;
case ATTRIBUTE_NODE: {
Attr* attr = static_cast<Attr*>(source.get());
if (attr->ownerElement())
attr->ownerElement()->removeAttributeNode(attr, ec);
attr->setSpecified(true);
break;
}
default:
if (source->hasTagName(iframeTag)) {
HTMLIFrameElement* iframe = static_cast<HTMLIFrameElement*>(source.get());
if (frame() && frame()->tree()->isDescendantOf(iframe->contentFrame())) {
ec = HIERARCHY_REQUEST_ERR;
return 0;
}
iframe->setRemainsAliveOnRemovalFromTree(attached() && source->attached());
}
if (source->parentNode())
source->parentNode()->removeChild(source.get(), ec);
}
source->setTreeScopeRecursively(this);
return source;
}
bool Document::hasPrefixNamespaceMismatch(const QualifiedName& qName)
{
// These checks are from DOM Core Level 2, createElementNS
// http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
return true;
if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
return true;
// Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
// http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
// createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar")
if ((qName.prefix() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) || (qName.prefix() != xmlnsAtom && qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI))
return true;
return false;
}
// FIXME: This should really be in a possible ElementFactory class
PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool createdByParser)
{
RefPtr<Element> e;
// FIXME: Use registered namespaces and look up in a hash to find the right factory.
if (qName.namespaceURI() == xhtmlNamespaceURI)
e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
#if ENABLE(SVG)
else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
#endif
#if ENABLE(WML)
else if (qName.namespaceURI() == WMLNames::wmlNamespaceURI)
e = WMLElementFactory::createWMLElement(qName, this, createdByParser);
else if (isWMLDocument())
e = WMLElementFactory::createWMLElement(QualifiedName(nullAtom, qName.localName(), WMLNames::wmlNamespaceURI), this, createdByParser);
#endif
#if ENABLE(MATHML)
else if (qName.namespaceURI() == MathMLNames::mathmlNamespaceURI)
e = MathMLElementFactory::createMathMLElement(qName, this, createdByParser);
#endif
if (e)
m_sawElementsInKnownNamespaces = true;
else
e = Element::create(qName, document());
// <image> uses imgTag so we need a special rule.
#if ENABLE(WML)
if (!isWMLDocument())
#endif
ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
return e.release();
}
PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec)
{
String prefix, localName;
if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
return 0;
QualifiedName qName(prefix, localName, namespaceURI);
if (hasPrefixNamespaceMismatch(qName)) {
ec = NAMESPACE_ERR;
return 0;
}
return createElement(qName, false);
}
String Document::readyState() const
{
DEFINE_STATIC_LOCAL(const String, loading, ("loading"));
DEFINE_STATIC_LOCAL(const String, interactive, ("interactive"));
DEFINE_STATIC_LOCAL(const String, complete, ("complete"));
switch (m_readyState) {
case Loading:
return loading;
case Interactive:
return interactive;
case Complete:
return complete;
}
ASSERT_NOT_REACHED();
return String();
}
void Document::setReadyState(ReadyState readyState)
{
if (readyState == m_readyState)
return;
switch (readyState) {
case Loading:
if (!m_documentTiming.domLoading)
m_documentTiming.domLoading = currentTime();
break;
case Interactive:
if (!m_documentTiming.domInteractive)
m_documentTiming.domInteractive = currentTime();
break;
case Complete:
if (!m_documentTiming.domComplete)
m_documentTiming.domComplete = currentTime();
break;
}
m_readyState = readyState;
dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
}
String Document::encoding() const
{
if (TextResourceDecoder* d = decoder())
return d->encoding().domName();
return String();
}
String Document::defaultCharset() const
{
if (Settings* settings = this->settings())
return settings->defaultTextEncodingName();
return String();
}
void Document::setCharset(const String& charset)
{
if (!decoder())
return;
decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
}
void Document::setXMLVersion(const String& version, ExceptionCode& ec)
{
if (!implementation()->hasFeature("XML", String())) {
ec = NOT_SUPPORTED_ERR;
return;
}
if (!XMLDocumentParser::supportsXMLVersion(version)) {
ec = NOT_SUPPORTED_ERR;
return;
}
m_xmlVersion = version;
}
void Document::setXMLStandalone(bool standalone, ExceptionCode& ec)
{
if (!implementation()->hasFeature("XML", String())) {
ec = NOT_SUPPORTED_ERR;
return;
}
m_xmlStandalone = standalone;
}
void Document::setDocumentURI(const String& uri)
{
m_documentURI = uri;
updateBaseURL();
}
KURL Document::baseURI() const
{
return m_baseURL;
}
void Document::setContent(const String& content)
{
open();
m_parser->append(content);
close();
}
// FIXME: We need to discuss the DOM API here at some point. Ideas:
// * making it receive a rect as parameter, i.e. nodesFromRect(x, y, w, h);
// * making it receive the expading size of each direction separately,
// i.e. nodesFromRect(x, y, topSize, rightSize, bottomSize, leftSize);
PassRefPtr<NodeList> Document::nodesFromRect(int centerX, int centerY, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping) const
{
// FIXME: Share code between this, elementFromPoint and caretRangeFromPoint.
if (!renderer())
return 0;
Frame* frame = this->frame();
if (!frame)
return 0;
FrameView* frameView = frame->view();
if (!frameView)
return 0;
float zoomFactor = frame->pageZoomFactor();
IntPoint point = roundedIntPoint(FloatPoint(centerX * zoomFactor + view()->scrollX(), centerY * zoomFactor + view()->scrollY()));
int type = HitTestRequest::ReadOnly | HitTestRequest::Active;
// When ignoreClipping is false, this method returns null for coordinates outside of the viewport.
if (ignoreClipping)
type |= HitTestRequest::IgnoreClipping;
else if (!frameView->visibleContentRect().intersects(HitTestResult::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
return 0;
HitTestRequest request(type);
// Passing a zero padding will trigger a rect hit test, however for the purposes of nodesFromRect,
// we special handle this case in order to return a valid NodeList.
if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) {
HitTestResult result(point);
return handleZeroPadding(request, result);
}
HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding);
renderView()->layer()->hitTest(request, result);
return StaticHashSetNodeList::adopt(result.rectBasedTestResult());
}
PassRefPtr<NodeList> Document::handleZeroPadding(const HitTestRequest& request, HitTestResult& result) const
{
renderView()->layer()->hitTest(request, result);
Node* node = result.innerNode();
if (!node)
return 0;
node = node->shadowAncestorNode();
ListHashSet<RefPtr<Node> > list;
list.add(node);
return StaticHashSetNodeList::adopt(list);
}
static Node* nodeFromPoint(Frame* frame, RenderView* renderView, int x, int y, IntPoint* localPoint = 0)
{
if (!frame)
return 0;
FrameView* frameView = frame->view();
if (!frameView)
return 0;
float zoomFactor = frame->pageZoomFactor();
IntPoint point = roundedIntPoint(FloatPoint(x * zoomFactor + frameView->scrollX(), y * zoomFactor + frameView->scrollY()));
if (!frameView->visibleContentRect().contains(point))
return 0;
HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
HitTestResult result(point);
renderView->layer()->hitTest(request, result);
if (localPoint)
*localPoint = result.localPoint();
return result.innerNode();
}
Element* Document::elementFromPoint(int x, int y) const
{
if (!renderer())
return 0;
Node* node = nodeFromPoint(frame(), renderView(), x, y);
while (node && !node->isElementNode())
node = node->parentNode();
if (node)
node = node->shadowAncestorNode();
return static_cast<Element*>(node);
}
PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
{
if (!renderer())
return 0;
IntPoint localPoint;
Node* node = nodeFromPoint(frame(), renderView(), x, y, &localPoint);
if (!node)
return 0;
Node* shadowAncestorNode = node->shadowAncestorNode();
if (shadowAncestorNode != node) {
unsigned offset = shadowAncestorNode->nodeIndex();
ContainerNode* container = shadowAncestorNode->parentNode();
return Range::create(this, container, offset, container, offset);
}
RenderObject* renderer = node->renderer();
if (!renderer)
return 0;
VisiblePosition visiblePosition = renderer->positionForPoint(localPoint);
if (visiblePosition.isNull())
return 0;
Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
return Range::create(this, rangeCompliantPosition, rangeCompliantPosition);
}
/*
* Performs three operations:
* 1. Convert control characters to spaces
* 2. Trim leading and trailing spaces
* 3. Collapse internal whitespace.
*/
static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
{
const String& title = titleWithDirection.string();
const UChar* characters = title.characters();
unsigned length = title.length();
unsigned i;
StringBuffer buffer(length);
unsigned builderIndex = 0;
// Skip leading spaces and leading characters that would convert to spaces
for (i = 0; i < length; ++i) {
UChar c = characters[i];
if (!(c <= 0x20 || c == 0x7F))
break;
}
if (i == length)
return StringWithDirection();
// Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
bool previousCharWasWS = false;
for (; i < length; ++i) {
UChar c = characters[i];
if (c <= 0x20 || c == 0x7F || (WTF::Unicode::category(c) & (WTF::Unicode::Separator_Line | WTF::Unicode::Separator_Paragraph))) {
if (previousCharWasWS)
continue;
buffer[builderIndex++] = ' ';
previousCharWasWS = true;
} else {
buffer[builderIndex++] = c;
previousCharWasWS = false;
}
}
// Strip trailing spaces
while (builderIndex > 0) {
--builderIndex;
if (buffer[builderIndex] != ' ')
break;
}
if (!builderIndex && buffer[builderIndex] == ' ')
return StringWithDirection();
buffer.shrink(builderIndex + 1);
// Replace the backslashes with currency symbols if the encoding requires it.
document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
return StringWithDirection(String::adopt(buffer), titleWithDirection.direction());
}
void Document::updateTitle(const StringWithDirection& title)
{
if (m_rawTitle == title)
return;
m_rawTitle = title;
m_title = canonicalizedTitle(this, m_rawTitle);
if (Frame* f = frame())
f->loader()->setTitle(m_title);
}
void Document::setTitle(const String& title)
{
// Title set by JavaScript -- overrides any title elements.
m_titleSetExplicitly = true;
if (!isHTMLDocument())
m_titleElement = 0;
else if (!m_titleElement) {
if (HTMLElement* headElement = head()) {
m_titleElement = createElement(titleTag, false);
ExceptionCode ec = 0;
headElement->appendChild(m_titleElement, ec);
ASSERT(!ec);
}
}
// The DOM API has no method of specifying direction, so assume LTR.
updateTitle(StringWithDirection(title, LTR));
if (m_titleElement) {
ASSERT(m_titleElement->hasTagName(titleTag));
if (m_titleElement->hasTagName(titleTag))
static_cast<HTMLTitleElement*>(m_titleElement.get())->setText(title);
}
}
void Document::setTitleElement(const StringWithDirection& title, Element* titleElement)
{
if (titleElement != m_titleElement) {
if (m_titleElement || m_titleSetExplicitly)
// Only allow the first title element to change the title -- others have no effect.
return;
m_titleElement = titleElement;
}
updateTitle(title);
}
void Document::removeTitle(Element* titleElement)
{
if (m_titleElement != titleElement)
return;
m_titleElement = 0;
m_titleSetExplicitly = false;
// Update title based on first title element in the head, if one exists.
if (HTMLElement* headElement = head()) {
for (Node* e = headElement->firstChild(); e; e = e->nextSibling())
if (e->hasTagName(titleTag)) {
HTMLTitleElement* titleElement = static_cast<HTMLTitleElement*>(e);
setTitleElement(titleElement->textWithDirection(), titleElement);
break;
}
}
if (!m_titleElement)
updateTitle(StringWithDirection());
}
#if ENABLE(PAGE_VISIBILITY_API)
PageVisibilityState Document::visibilityState() const
{
// The visibility of the document is inherited from the visibility of the
// page. If there is no page associated with the document, we will assume
// that the page is visible i.e. invisibility has to be explicitly
// specified by the embedder.
if (!m_frame || !m_frame->page())
return PageVisibilityStateVisible;
return m_frame->page()->visibilityState();
}
String Document::webkitVisibilityState() const
{
return pageVisibilityStateString(visibilityState());
}
bool Document::webkitHidden() const
{
return visibilityState() != PageVisibilityStateVisible;
}
void Document::dispatchVisibilityStateChangeEvent()
{
dispatchEvent(Event::create(eventNames().webkitvisibilitychangeEvent, false, false));
}
#endif
String Document::nodeName() const
{
return "#document";
}
Node::NodeType Document::nodeType() const
{
return DOCUMENT_NODE;
}
FrameView* Document::view() const
{
return m_frame ? m_frame->view() : 0;
}
Page* Document::page() const
{
return m_frame ? m_frame->page() : 0;
}
Settings* Document::settings() const
{
return m_frame ? m_frame->settings() : 0;
}
PassRefPtr<Range> Document::createRange()
{
return Range::create(this);
}
PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow,
PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
{
if (!root) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return NodeIterator::create(root, whatToShow, filter, expandEntityReferences);
}
PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow,
PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionCode& ec)
{
if (!root) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return TreeWalker::create(root, whatToShow, filter, expandEntityReferences);
}
void Document::scheduleForcedStyleRecalc()
{
m_pendingStyleRecalcShouldForce = true;
scheduleStyleRecalc();
}
void Document::scheduleStyleRecalc()
{
if (m_styleRecalcTimer.isActive() || inPageCache())
return;
ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
if (!documentsThatNeedStyleRecalc)
documentsThatNeedStyleRecalc = new HashSet<Document*>;
documentsThatNeedStyleRecalc->add(this);
// FIXME: Why on earth is this here? This is clearly misplaced.
invalidateAccessKeyMap();
m_styleRecalcTimer.startOneShot(0);
}
void Document::unscheduleStyleRecalc()
{
ASSERT(!childNeedsStyleRecalc());
if (documentsThatNeedStyleRecalc)
documentsThatNeedStyleRecalc->remove(this);
m_styleRecalcTimer.stop();
m_pendingStyleRecalcShouldForce = false;
}
bool Document::isPendingStyleRecalc() const
{
return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
}
void Document::styleRecalcTimerFired(Timer<Document>*)
{
updateStyleIfNeeded();
}
bool Document::childNeedsAndNotInStyleRecalc()
{
return childNeedsStyleRecalc() && !m_inStyleRecalc;
}
void Document::recalcStyle(StyleChange change)
{
// we should not enter style recalc while painting
if (view() && view()->isPainting()) {
ASSERT(!view()->isPainting());
return;
}
if (m_inStyleRecalc)
return; // Guard against re-entrancy. -dwh
if (m_hasDirtyStyleSelector)
recalcStyleSelector();
InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
m_inStyleRecalc = true;
suspendPostAttachCallbacks();
RenderWidget::suspendWidgetHierarchyUpdates();
RefPtr<FrameView> frameView = view();
if (frameView) {
frameView->pauseScheduledEvents();
frameView->beginDeferredRepaints();
}
#ifdef ANDROID_INSTRUMENT
android::TimeCounter::start(android::TimeCounter::CalculateStyleTimeCounter);
#endif
ASSERT(!renderer() || renderArena());
if (!renderer() || !renderArena())
goto bail_out;
if (m_pendingStyleRecalcShouldForce)
change = Force;
if (change == Force) {
// style selector may set this again during recalc
m_hasNodesWithPlaceholderStyle = false;
RefPtr<RenderStyle> documentStyle = CSSStyleSelector::styleForDocument(this);
StyleChange ch = diff(documentStyle.get(), renderer()->style());
if (renderer() && ch != NoChange)
renderer()->setStyle(documentStyle.release());
}
for (Node* n = firstChild(); n; n = n->nextSibling())
if (change >= Inherit || n->childNeedsStyleRecalc() || n->needsStyleRecalc())
n->recalcStyle(change);
#ifdef ANDROID_INSTRUMENT
android::TimeCounter::record(android::TimeCounter::CalculateStyleTimeCounter, __FUNCTION__);
#endif
#if USE(ACCELERATED_COMPOSITING)
if (view()) {
bool layoutPending = view()->layoutPending() || renderer()->needsLayout();
// If we didn't update compositing layers because of layout(), we need to do so here.
if (!layoutPending)
view()->updateCompositingLayers();
}
#endif
bail_out:
clearNeedsStyleRecalc();
clearChildNeedsStyleRecalc();
unscheduleStyleRecalc();
m_inStyleRecalc = false;
// Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
if (m_styleSelector) {
m_usesSiblingRules = m_styleSelector->usesSiblingRules();
m_usesFirstLineRules = m_styleSelector->usesFirstLineRules();
m_usesBeforeAfterRules = m_styleSelector->usesBeforeAfterRules();
m_usesLinkRules = m_styleSelector->usesLinkRules();
}
if (frameView) {
frameView->resumeScheduledEvents();
frameView->endDeferredRepaints();
}
RenderWidget::resumeWidgetHierarchyUpdates();
resumePostAttachCallbacks();
// If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
if (m_closeAfterStyleRecalc) {
m_closeAfterStyleRecalc = false;
implicitClose();
}
InspectorInstrumentation::didRecalculateStyle(cookie);
}
void Document::updateStyleIfNeeded()
{
ASSERT(isMainThread());
ASSERT(!view() || (!view()->isInLayout() && !view()->isPainting()));
if ((!m_pendingStyleRecalcShouldForce && !childNeedsStyleRecalc()) || inPageCache())
return;
if (m_frame)
m_frame->animation()->beginAnimationUpdate();
recalcStyle(NoChange);
// Tell the animation controller that updateStyleIfNeeded is finished and it can do any post-processing
if (m_frame)
m_frame->animation()->endAnimationUpdate();
}
void Document::updateStyleForAllDocuments()
{
ASSERT(isMainThread());
if (!documentsThatNeedStyleRecalc)
return;
while (documentsThatNeedStyleRecalc->size()) {
HashSet<Document*>::iterator it = documentsThatNeedStyleRecalc->begin();
Document* doc = *it;
documentsThatNeedStyleRecalc->remove(doc);
doc->updateStyleIfNeeded();
}
}
void Document::updateLayout()
{
ASSERT(isMainThread());
if (Element* oe = ownerElement())
oe->document()->updateLayout();
updateStyleIfNeeded();
// Only do a layout if changes have occurred that make it necessary.
FrameView* v = view();
if (v && renderer() && (v->layoutPending() || renderer()->needsLayout()))
v->layout();
}
// FIXME: This is a bad idea and needs to be removed eventually.
// Other browsers load stylesheets before they continue parsing the web page.
// Since we don't, we can run JavaScript code that needs answers before the
// stylesheets are loaded. Doing a layout ignoring the pending stylesheets
// lets us get reasonable answers. The long term solution to this problem is
// to instead suspend JavaScript execution.
void Document::updateLayoutIgnorePendingStylesheets()
{
bool oldIgnore = m_ignorePendingStylesheets;
if (!haveStylesheetsLoaded()) {
m_ignorePendingStylesheets = true;
// FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
// dangerous to try to stop it a second time, after page content has already been loaded and displayed
// with accurate style information. (Our suppression involves blanking the whole page at the
// moment. If it were more refined, we might be able to do something better.)
// It's worth noting though that this entire method is a hack, since what we really want to do is
// suspend JS instead of doing a layout with inaccurate information.
if (body() && !body()->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
m_pendingSheetLayout = DidLayoutWithPendingSheets;
styleSelectorChanged(RecalcStyleImmediately);
} else if (m_hasNodesWithPlaceholderStyle)
// If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
// may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
// but here we need up-to-date style immediately.
recalcStyle(Force);
}
updateLayout();
m_ignorePendingStylesheets = oldIgnore;
}
PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
{
ASSERT_ARG(element, element->document() == this);
bool oldIgnore = m_ignorePendingStylesheets;
m_ignorePendingStylesheets = true;
RefPtr<RenderStyle> style = styleSelector()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
m_ignorePendingStylesheets = oldIgnore;
return style.release();
}
PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
{
RefPtr<RenderStyle> style = styleSelector()->styleForPage(pageIndex);
return style.release();
}
bool Document::isPageBoxVisible(int pageIndex)
{
RefPtr<RenderStyle> style = styleForPage(pageIndex);
return style->visibility() != HIDDEN; // display property doesn't apply to @page.
}
void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
{
RefPtr<RenderStyle> style = styleForPage(pageIndex);
int width = pageSize.width();
int height = pageSize.height();
switch (style->pageSizeType()) {
case PAGE_SIZE_AUTO:
break;
case PAGE_SIZE_AUTO_LANDSCAPE:
if (width < height)
std::swap(width, height);
break;
case PAGE_SIZE_AUTO_PORTRAIT:
if (width > height)
std::swap(width, height);
break;
case PAGE_SIZE_RESOLVED: {
LengthSize size = style->pageSize();
ASSERT(size.width().isFixed());
ASSERT(size.height().isFixed());
width = size.width().calcValue(0);
height = size.height().calcValue(0);
break;
}
default:
ASSERT_NOT_REACHED();
}
pageSize = IntSize(width, height);
// The percentage is calculated with respect to the width even for margin top and bottom.
// http://www.w3.org/TR/CSS2/box.html#margin-properties
marginTop = style->marginTop().isAuto() ? marginTop : style->marginTop().calcValue(width);
marginRight = style->marginRight().isAuto() ? marginRight : style->marginRight().calcValue(width);
marginBottom = style->marginBottom().isAuto() ? marginBottom : style->marginBottom().calcValue(width);
marginLeft = style->marginLeft().isAuto() ? marginLeft : style->marginLeft().calcValue(width);
}
PassRefPtr<CSSPrimitiveValueCache> Document::cssPrimitiveValueCache() const
{
if (!m_cssPrimitiveValueCache)
m_cssPrimitiveValueCache = CSSPrimitiveValueCache::create();
return m_cssPrimitiveValueCache;
}
void Document::createStyleSelector()
{
bool matchAuthorAndUserStyles = true;
if (Settings* docSettings = settings())
matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
m_styleSelector.set(new CSSStyleSelector(this, m_styleSheets.get(), m_mappedElementSheet.get(), pageUserSheet(), pageGroupUserSheets(),
!inQuirksMode(), matchAuthorAndUserStyles));
// Delay resetting the flags until after next style recalc since unapplying the style may not work without these set (this is true at least with before/after).
m_usesSiblingRules = m_usesSiblingRules || m_styleSelector->usesSiblingRules();
m_usesFirstLineRules = m_usesFirstLineRules || m_styleSelector->usesFirstLineRules();
m_usesBeforeAfterRules = m_usesBeforeAfterRules || m_styleSelector->usesBeforeAfterRules();
m_usesLinkRules = m_usesLinkRules || m_styleSelector->usesLinkRules();
}
void Document::attach()
{
ASSERT(!attached());
ASSERT(!m_inPageCache);
#if !PLATFORM(ANDROID)
ASSERT(!m_axObjectCache);
#endif
if (!m_renderArena)
m_renderArena = new RenderArena();
// Create the rendering tree
setRenderer(new (m_renderArena.get()) RenderView(this, view()));
#if USE(ACCELERATED_COMPOSITING)
renderView()->didMoveOnscreen();
#endif
recalcStyle(Force);
RenderObject* render = renderer();
setRenderer(0);
TreeScope::attach();
setRenderer(render);
}
void Document::detach()
{
ASSERT(attached());
ASSERT(!m_inPageCache);
clearAXObjectCache();
stopActiveDOMObjects();
m_eventQueue->cancelQueuedEvents();
#if ENABLE(REQUEST_ANIMATION_FRAME)
// FIXME: consider using ActiveDOMObject.
m_scriptedAnimationController = 0;
#endif
RenderObject* render = renderer();
// Send out documentWillBecomeInactive() notifications to registered elements,
// in order to stop media elements
documentWillBecomeInactive();
#if ENABLE(SHARED_WORKERS)
SharedWorkerRepository::documentDetached(this);
#endif
if (m_frame) {
FrameView* view = m_frame->view();
if (view)
view->detachCustomScrollbars();
}
// indicate destruction mode, i.e. attached() but renderer == 0
setRenderer(0);
#if ENABLE(FULLSCREEN_API)
if (m_fullScreenRenderer)
setFullScreenRenderer(0);
#endif
m_hoverNode = 0;
m_focusedNode = 0;
m_activeNode = 0;
TreeScope::detach();
unscheduleStyleRecalc();
if (render)
render->destroy();
// This is required, as our Frame might delete itself as soon as it detaches
// us. However, this violates Node::detach() semantics, as it's never
// possible to re-attach. Eventually Document::detach() should be renamed,
// or this setting of the frame to 0 could be made explicit in each of the
// callers of Document::detach().
m_frame = 0;
m_renderArena.clear();
}
void Document::removeAllEventListeners()
{
#if ENABLE(TOUCH_EVENTS)
Page* ownerPage = page();
if (!m_inPageCache && ownerPage && (m_frame == ownerPage->mainFrame()) && hasListenerType(Document::TOUCH_LISTENER)) {
// Inform the Chrome Client that it no longer needs to forward touch
// events to WebCore as the document removes all the event listeners.
ownerPage->chrome()->client()->needTouchEvents(false);
}
#endif
EventTarget::removeAllEventListeners();
if (DOMWindow* domWindow = this->domWindow())
domWindow->removeAllEventListeners();
for (Node* node = firstChild(); node; node = node->traverseNextNode())
node->removeAllEventListeners();
}
RenderView* Document::renderView() const
{
return toRenderView(renderer());
}
void Document::clearAXObjectCache()
{
#if PLATFORM(ANDROID)
return;
#else
// clear cache in top document
if (m_axObjectCache) {
// Clear the cache member variable before calling delete because attempts
// are made to access it during destruction.
AXObjectCache* axObjectCache = m_axObjectCache;
m_axObjectCache = 0;
delete axObjectCache;
return;
}
// ask the top-level document to clear its cache
Document* doc = topDocument();
if (doc != this)
doc->clearAXObjectCache();
#endif
}
bool Document::axObjectCacheExists() const
{
#if PLATFORM(ANDROID)
return false;
#else
if (m_axObjectCache)
return true;
Document* doc = topDocument();
if (doc != this)
return doc->axObjectCacheExists();
return false;
#endif
}
AXObjectCache* Document::axObjectCache() const
{
#if PLATFORM(ANDROID)
return 0;
#else
// The only document that actually has a AXObjectCache is the top-level
// document. This is because we need to be able to get from any WebCoreAXObject
// to any other WebCoreAXObject on the same page. Using a single cache allows
// lookups across nested webareas (i.e. multiple documents).
if (m_axObjectCache) {
// return already known top-level cache
if (!ownerElement())
return m_axObjectCache;
// In some pages with frames, the cache is created before the sub-webarea is
// inserted into the tree. Here, we catch that case and just toss the old
// cache and start over.
// NOTE: This recovery may no longer be needed. I have been unable to trigger
// it again. See rdar://5794454
// FIXME: Can this be fixed when inserting the subframe instead of now?
// FIXME: If this function was called to get the cache in order to remove
// an AXObject, we are now deleting the cache as a whole and returning a
// new empty cache that does not contain the AXObject! That should actually
// be OK. I am concerned about other cases like this where accessing the
// cache blows away the AXObject being operated on.
delete m_axObjectCache;
m_axObjectCache = 0;
}
// ask the top-level document for its cache
Document* doc = topDocument();
if (doc != this)
return doc->axObjectCache();
// this is the top-level document, so install a new cache
m_axObjectCache = new AXObjectCache(this);
return m_axObjectCache;
#endif // ANDROID
}
void Document::setVisuallyOrdered()
{
m_visuallyOrdered = true;
if (renderer())
renderer()->style()->setVisuallyOrdered(true);
}
PassRefPtr<DocumentParser> Document::createParser()
{
//SAMSUNG WML FIX >>
//return new XMLTokenizer(this, view());
//return new XMLValidatingTokenizer(this, view());
// Avoid Memory Leak
return XMLValidatingTokenizer::create(this, view());
//SAMSUNG WML FIX <<
// FIXME: this should probably pass the frame instead
//return XMLDocumentParser::create(this, view());
}
ScriptableDocumentParser* Document::scriptableDocumentParser() const
{
return parser() ? parser()->asScriptableDocumentParser() : 0;
}
void Document::open(Document* ownerDocument)
{
if (ownerDocument) {
setURL(ownerDocument->url());
m_cookieURL = ownerDocument->cookieURL();
ScriptExecutionContext::setSecurityOrigin(ownerDocument->securityOrigin());
}
if (m_frame) {
if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
if (parser->isParsing()) {
// FIXME: HTML5 doesn't tell us to check this, it might not be correct.
if (parser->isExecutingScript())
return;
if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
return;
}
}
if (m_frame->loader()->state() == FrameStateProvisional)
m_frame->loader()->stopAllLoaders();
}
removeAllEventListeners();
implicitOpen();
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->setWasCreatedByScript(true);
if (DOMWindow* domWindow = this->domWindow())
domWindow->removeAllEventListeners();
if (m_frame)
m_frame->loader()->didExplicitOpen();
}
void Document::detachParser()
{
if (!m_parser)
return;
m_parser->detach();
m_parser.clear();
}
void Document::cancelParsing()
{
if (!m_parser)
return;
// We have to clear the parser to avoid possibly triggering
// the onload handler when closing as a side effect of a cancel-style
// change, such as opening a new document or closing the window while
// still parsing
detachParser();
explicitClose();
}
void Document::implicitOpen()
{
cancelParsing();
removeChildren();
setCompatibilityMode(NoQuirksMode);
m_parser = createParser();
setParsing(true);
setReadyState(Loading);
// If we reload, the animation controller sticks around and has
// a stale animation time. We need to update it here.
if (m_frame && m_frame->animation())
m_frame->animation()->beginAnimationUpdate();
}
HTMLElement* Document::body() const
{
Node* de = documentElement();
if (!de)
return 0;
// try to prefer a FRAMESET element over BODY
Node* body = 0;
for (Node* i = de->firstChild(); i; i = i->nextSibling()) {
if (i->hasTagName(framesetTag))
return toHTMLElement(i);
if (i->hasTagName(bodyTag) && !body)
body = i;
}
return toHTMLElement(body);
}
void Document::setBody(PassRefPtr<HTMLElement> newBody, ExceptionCode& ec)
{
ec = 0;
if (!newBody || !documentElement() || !newBody->hasTagName(bodyTag)) {
ec = HIERARCHY_REQUEST_ERR;
return;
}
if (newBody->document() && newBody->document() != this) {
RefPtr<Node> node = importNode(newBody.get(), true, ec);
if (ec)
return;
newBody = toHTMLElement(node.get());
}
HTMLElement* b = body();
if (!b)
documentElement()->appendChild(newBody, ec);
else
documentElement()->replaceChild(newBody, b, ec);
}
HTMLHeadElement* Document::head()
{
Node* de = documentElement();
if (!de)
return 0;
for (Node* e = de->firstChild(); e; e = e->nextSibling())
if (e->hasTagName(headTag))
return static_cast<HTMLHeadElement*>(e);
return 0;
}
void Document::close()
{
// FIXME: We should follow the specification more closely:
// http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript())
return;
explicitClose();
}
void Document::explicitClose()
{
if (!m_frame) {
// Because we have no frame, we don't know if all loading has completed,
// so we just call implicitClose() immediately. FIXME: This might fire
// the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
if (m_parser)
m_parser->finish();
implicitClose();
return;
}
// This code calls implicitClose() if all loading has completed.
loader()->writer()->endIfNotLoadingMainResource();
if (m_frame)
m_frame->loader()->checkCompleted();
}
void Document::implicitClose()
{
// If we're in the middle of recalcStyle, we need to defer the close until the style information is accurate and all elements are re-attached.
if (m_inStyleRecalc) {
m_closeAfterStyleRecalc = true;
return;
}
bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
if (!doload)
return;
m_processingLoadEvent = true;
ScriptableDocumentParser* parser = scriptableDocumentParser();
m_wellFormed = parser && parser->wellFormed();
// We have to clear the parser, in case someone document.write()s from the
// onLoad event handler, as in Radar 3206524.
detachParser();
// Parser should have picked up all preloads by now
m_cachedResourceLoader->clearPreloads();
// FIXME: We kick off the icon loader when the Document is done parsing.
// There are earlier opportunities we could start it:
// -When the <head> finishes parsing
// -When any new HTMLLinkElement is inserted into the document
// But those add a dynamic component to the favicon that has UI
// ramifications, and we need to decide what is the Right Thing To Do(tm)
Frame* f = frame();
if (f)
f->loader()->startIconLoader();
// Resume the animations (or start them)
if (f)
f->animation()->resumeAnimationsForDocument(this);
ImageLoader::dispatchPendingBeforeLoadEvents();
ImageLoader::dispatchPendingLoadEvents();
dispatchWindowLoadEvent();
enqueuePageshowEvent(PageshowEventNotPersisted);
enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
if (f)
f->loader()->handledOnloadEvents();
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("onload fired at %d\n", elapsedTime());
#endif
m_processingLoadEvent = false;
// An event handler may have removed the frame
if (!frame())
return;
// Make sure both the initial layout and reflow happen after the onload
// fires. This will improve onload scores, and other browsers do it.
// If they wanna cheat, we can too. -dwh
if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
// Just bail out. Before or during the onload we were shifted to another page.
// The old i-Bench suite does this. When this happens don't bother painting or laying out.
view()->unscheduleRelayout();
return;
}
frame()->loader()->checkCallImplicitClose();
RenderObject* renderObject = renderer();
// We used to force a synchronous display and flush here. This really isn't
// necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
// (if your platform is syncing flushes and limiting them to 60fps).
m_overMinimumLayoutThreshold = true;
if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
updateStyleIfNeeded();
// Always do a layout after loading if needed.
if (view() && renderObject && (!renderObject->firstChild() || renderObject->needsLayout()))
view()->layout();
}
#if PLATFORM(MAC) || PLATFORM(CHROMIUM)
if (f && renderObject && this == topDocument() && AXObjectCache::accessibilityEnabled()) {
// The AX cache may have been cleared at this point, but we need to make sure it contains an
// AX object to send the notification to. getOrCreate will make sure that an valid AX object
// exists in the cache (we ignore the return value because we don't need it here). This is
// only safe to call when a layout is not in progress, so it can not be used in postNotification.
axObjectCache()->getOrCreate(renderObject);
axObjectCache()->postNotification(renderObject, AXObjectCache::AXLoadComplete, true);
}
#endif
#if ENABLE(SVG)
// FIXME: Officially, time 0 is when the outermost <svg> receives its
// SVGLoad event, but we don't implement those yet. This is close enough
// for now. In some cases we should have fired earlier.
if (svgExtensions())
accessSVGExtensions()->startAnimations();
#endif
}
void Document::setParsing(bool b)
{
m_bParsing = b;
if (!m_bParsing && view())
view()->scheduleRelayout();
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement() && !m_bParsing)
printf("Parsing finished at %d\n", elapsedTime());
#endif
}
bool Document::shouldScheduleLayout()
{
// This function will only be called when FrameView thinks a layout is needed.
// This enforces a couple extra rules.
//
// (a) Only schedule a layout once the stylesheets are loaded.
// (b) Only schedule layout once we have a body element.
return (haveStylesheetsLoaded() && body())
|| (documentElement() && !documentElement()->hasTagName(htmlTag));
}
bool Document::isLayoutTimerActive()
{
if (!view() || !view()->layoutPending())
return false;
bool isPendingLayoutImmediate = minimumLayoutDelay() == m_extraLayoutDelay;
return isPendingLayoutImmediate;
}
int Document::minimumLayoutDelay()
{
if (m_overMinimumLayoutThreshold)
return m_extraLayoutDelay;
int elapsed = elapsedTime();
m_overMinimumLayoutThreshold = elapsed > cLayoutScheduleThreshold;
// We'll want to schedule the timer to fire at the minimum layout threshold.
return max(0, cLayoutScheduleThreshold - elapsed) + m_extraLayoutDelay;
}
int Document::elapsedTime() const
{
return static_cast<int>((currentTime() - m_startTime) * 1000);
}
void Document::write(const SegmentedString& text, Document* ownerDocument)
{
NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
if (m_writeRecursionIsTooDeep)
return;
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Beginning a document.write at %d\n", elapsedTime());
#endif
bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
if (!hasInsertionPoint && m_ignoreDestructiveWriteCount)
return;
if (!hasInsertionPoint)
open(ownerDocument);
ASSERT(m_parser);
m_parser->insert(text);
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Ending a document.write at %d\n", elapsedTime());
#endif
}
void Document::write(const String& text, Document* ownerDocument)
{
write(SegmentedString(text), ownerDocument);
}
void Document::writeln(const String& text, Document* ownerDocument)
{
write(text, ownerDocument);
write("\n", ownerDocument);
}
void Document::finishParsing()
{
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Received all data at %d\n", elapsedTime());
#endif
// Let the parser go through as much data as it can. There will be three possible outcomes after
// finish() is called:
// (1) All remaining data is parsed, document isn't loaded yet
// (2) All remaining data is parsed, document is loaded, parser gets deleted
// (3) Data is still remaining to be parsed.
if (m_parser)
m_parser->finish();
}
const KURL& Document::virtualURL() const
{
return m_url;
}
KURL Document::virtualCompleteURL(const String& url) const
{
return completeURL(url);
}
double Document::minimumTimerInterval() const
{
Page* p = page();
if (!p)
return ScriptExecutionContext::minimumTimerInterval();
return p->settings()->minDOMTimerInterval();
}
EventTarget* Document::errorEventTarget()
{
return domWindow();
}
void Document::logExceptionToConsole(const String& errorMessage, int lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack)
{
MessageType messageType = callStack ? UncaughtExceptionMessageType : LogMessageType;
addMessage(JSMessageSource, messageType, ErrorMessageLevel, errorMessage, lineNumber, sourceURL, callStack);
}
void Document::setURL(const KURL& url)
{
const KURL& newURL = url.isEmpty() ? blankURL() : url;
if (newURL == m_url)
return;
m_url = newURL;
m_documentURI = m_url.string();
updateBaseURL();
}
void Document::updateBaseURL()
{
// DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
// first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
// from the Document interface otherwise.
if (m_baseElementURL.isEmpty()) {
// The documentURI attribute is an arbitrary string. DOM 3 Core does not specify how it should be resolved,
// so we use a null base URL.
m_baseURL = KURL(KURL(), documentURI());
} else
m_baseURL = m_baseElementURL;
if (!m_baseURL.isValid())
m_baseURL = KURL();
if (m_elemSheet)
m_elemSheet->setFinalURL(m_baseURL);
if (m_mappedElementSheet)
m_mappedElementSheet->setFinalURL(m_baseURL);
}
void Document::processBaseElement()
{
// Find the first href attribute in a base element and the first target attribute in a base element.
const AtomicString* href = 0;
const AtomicString* target = 0;
for (Node* node = document()->firstChild(); node && (!href || !target); node = node->traverseNextNode()) {
if (node->hasTagName(baseTag)) {
if (!href) {
const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(hrefAttr);
if (!value.isNull())
href = &value;
}
if (!target) {
const AtomicString& value = static_cast<Element*>(node)->fastGetAttribute(targetAttr);
if (!value.isNull())
target = &value;
}
}
}
// FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
KURL baseElementURL;
if (href) {
String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
if (!strippedHref.isEmpty())
baseElementURL = KURL(url(), strippedHref);
}
if (m_baseElementURL != baseElementURL) {
m_baseElementURL = baseElementURL;
updateBaseURL();
}
m_baseTarget = target ? *target : nullAtom;
}
String Document::userAgent(const KURL& url) const
{
return frame() ? frame()->loader()->userAgent(url) : String();
}
CSSStyleSheet* Document::pageUserSheet()
{
if (m_pageUserSheet)
return m_pageUserSheet.get();
Page* owningPage = page();
if (!owningPage)
return 0;
String userSheetText = owningPage->userStyleSheet();
if (userSheetText.isEmpty())
return 0;
// Parse the sheet and cache it.
m_pageUserSheet = CSSStyleSheet::createInline(this, settings()->userStyleSheetLocation());
m_pageUserSheet->setIsUserStyleSheet(true);
m_pageUserSheet->parseString(userSheetText, !inQuirksMode());
return m_pageUserSheet.get();
}
void Document::clearPageUserSheet()
{
if (m_pageUserSheet) {
m_pageUserSheet = 0;
styleSelectorChanged(DeferRecalcStyle);
}
}
void Document::updatePageUserSheet()
{
clearPageUserSheet();
if (pageUserSheet())
styleSelectorChanged(RecalcStyleImmediately);
}
const Vector<RefPtr<CSSStyleSheet> >* Document::pageGroupUserSheets() const
{
if (m_pageGroupUserSheetCacheValid)
return m_pageGroupUserSheets.get();
m_pageGroupUserSheetCacheValid = true;
Page* owningPage = page();
if (!owningPage)
return 0;
const PageGroup& pageGroup = owningPage->group();
const UserStyleSheetMap* sheetsMap = pageGroup.userStyleSheets();
if (!sheetsMap)
return 0;
UserStyleSheetMap::const_iterator end = sheetsMap->end();
for (UserStyleSheetMap::const_iterator it = sheetsMap->begin(); it != end; ++it) {
const UserStyleSheetVector* sheets = it->second;
for (unsigned i = 0; i < sheets->size(); ++i) {
const UserStyleSheet* sheet = sheets->at(i).get();
if (sheet->injectedFrames() == InjectInTopFrameOnly && ownerElement())
continue;
if (!UserContentURLPattern::matchesPatterns(url(), sheet->whitelist(), sheet->blacklist()))
continue;
RefPtr<CSSStyleSheet> parsedSheet = CSSStyleSheet::createInline(const_cast<Document*>(this), sheet->url());
parsedSheet->setIsUserStyleSheet(sheet->level() == UserStyleUserLevel);
parsedSheet->parseString(sheet->source(), !inQuirksMode());
if (!m_pageGroupUserSheets)
m_pageGroupUserSheets.set(new Vector<RefPtr<CSSStyleSheet> >);
m_pageGroupUserSheets->append(parsedSheet.release());
}
}
return m_pageGroupUserSheets.get();
}
void Document::clearPageGroupUserSheets()
{
m_pageGroupUserSheetCacheValid = false;
if (m_pageGroupUserSheets && m_pageGroupUserSheets->size()) {
m_pageGroupUserSheets->clear();
styleSelectorChanged(DeferRecalcStyle);
}
}
void Document::updatePageGroupUserSheets()
{
clearPageGroupUserSheets();
if (pageGroupUserSheets() && pageGroupUserSheets()->size())
styleSelectorChanged(RecalcStyleImmediately);
}
CSSStyleSheet* Document::elementSheet()
{
if (!m_elemSheet)
m_elemSheet = CSSStyleSheet::createInline(this, m_baseURL);
return m_elemSheet.get();
}
CSSStyleSheet* Document::mappedElementSheet()
{
if (!m_mappedElementSheet)
m_mappedElementSheet = CSSStyleSheet::createInline(this, m_baseURL);
return m_mappedElementSheet.get();
}
static Node* nextNodeWithExactTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
{
// Search is inclusive of start
for (Node* n = start; n; n = n->traverseNextNode())
if (n->isKeyboardFocusable(event) && n->tabIndex() == tabIndex)
return n;
return 0;
}
static Node* previousNodeWithExactTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
{
// Search is inclusive of start
for (Node* n = start; n; n = n->traversePreviousNode())
if (n->isKeyboardFocusable(event) && n->tabIndex() == tabIndex)
return n;
return 0;
}
static Node* nextNodeWithGreaterTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
{
// Search is inclusive of start
int winningTabIndex = SHRT_MAX + 1;
Node* winner = 0;
for (Node* n = start; n; n = n->traverseNextNode())
if (n->isKeyboardFocusable(event) && n->tabIndex() > tabIndex && n->tabIndex() < winningTabIndex) {
winner = n;
winningTabIndex = n->tabIndex();
}
return winner;
}
static Node* previousNodeWithLowerTabIndex(Node* start, int tabIndex, KeyboardEvent* event)
{
// Search is inclusive of start
int winningTabIndex = 0;
Node* winner = 0;
for (Node* n = start; n; n = n->traversePreviousNode())
if (n->isKeyboardFocusable(event) && n->tabIndex() < tabIndex && n->tabIndex() > winningTabIndex) {
winner = n;
winningTabIndex = n->tabIndex();
}
return winner;
}
Node* Document::nextFocusableNode(Node* start, KeyboardEvent* event)
{
if (start) {
// If a node is excluded from the normal tabbing cycle, the next focusable node is determined by tree order
if (start->tabIndex() < 0) {
for (Node* n = start->traverseNextNode(); n; n = n->traverseNextNode())
if (n->isKeyboardFocusable(event) && n->tabIndex() >= 0)
return n;
}
// First try to find a node with the same tabindex as start that comes after start in the document.
if (Node* winner = nextNodeWithExactTabIndex(start->traverseNextNode(), start->tabIndex(), event))
return winner;
if (!start->tabIndex())
// We've reached the last node in the document with a tabindex of 0. This is the end of the tabbing order.
return 0;
}
// Look for the first node in the document that:
// 1) has the lowest tabindex that is higher than start's tabindex (or 0, if start is null), and
// 2) comes first in the document, if there's a tie.
if (Node* winner = nextNodeWithGreaterTabIndex(this, start ? start->tabIndex() : 0, event))
return winner;
// There are no nodes with a tabindex greater than start's tabindex,
// so find the first node with a tabindex of 0.
return nextNodeWithExactTabIndex(this, 0, event);
}
Node* Document::previousFocusableNode(Node* start, KeyboardEvent* event)
{
Node* last;
for (last = this; last->lastChild(); last = last->lastChild()) { }
// First try to find the last node in the document that comes before start and has the same tabindex as start.
// If start is null, find the last node in the document with a tabindex of 0.
Node* startingNode;
int startingTabIndex;
if (start) {
startingNode = start->traversePreviousNode();
startingTabIndex = start->tabIndex();
} else {
startingNode = last;
startingTabIndex = 0;
}
// However, if a node is excluded from the normal tabbing cycle, the previous focusable node is determined by tree order
if (startingTabIndex < 0) {
for (Node* n = startingNode; n; n = n->traversePreviousNode())
if (n->isKeyboardFocusable(event) && n->tabIndex() >= 0)
return n;
}
if (Node* winner = previousNodeWithExactTabIndex(startingNode, startingTabIndex, event))
return winner;
// There are no nodes before start with the same tabindex as start, so look for a node that:
// 1) has the highest non-zero tabindex (that is less than start's tabindex), and
// 2) comes last in the document, if there's a tie.
startingTabIndex = (start && start->tabIndex()) ? start->tabIndex() : SHRT_MAX;
return previousNodeWithLowerTabIndex(last, startingTabIndex, event);
}
int Document::nodeAbsIndex(Node *node)
{
ASSERT(node->document() == this);
int absIndex = 0;
for (Node* n = node; n && n != this; n = n->traversePreviousNode())
absIndex++;
return absIndex;
}
Node* Document::nodeWithAbsIndex(int absIndex)
{
Node* n = this;
for (int i = 0; n && (i < absIndex); i++)
n = n->traverseNextNode();
return n;
}
#ifdef ANDROID_META_SUPPORT
void Document::processMetadataSettings(const String& content)
{
ASSERT(!content.isNull());
processArguments(content, 0, 0);
}
#endif
void Document::processHttpEquiv(const String& equiv, const String& content)
{
ASSERT(!equiv.isNull() && !content.isNull());
Frame* frame = this->frame();
if (equalIgnoringCase(equiv, "default-style")) {
// The preferred style set has been overridden as per section
// 14.3.2 of the HTML4.0 specification. We need to update the
// sheet used variable and then update our style selector.
// For more info, see the test at:
// http://www.hixie.ch/tests/evil/css/import/main/preferred.html
// -dwh
m_selectedStylesheetSet = content;
m_preferredStylesheetSet = content;
styleSelectorChanged(DeferRecalcStyle);
} else if (equalIgnoringCase(equiv, "refresh")) {
double delay;
String url;
if (frame && parseHTTPRefresh(content, true, delay, url)) {
if (url.isEmpty())
url = m_url.string();
else
url = completeURL(url).string();
frame->navigationScheduler()->scheduleRedirect(delay, url);
}
} else if (equalIgnoringCase(equiv, "set-cookie")) {
// FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
if (isHTMLDocument()) {
ExceptionCode ec; // Exception (for sandboxed documents) ignored.
static_cast<HTMLDocument*>(this)->setCookie(content, ec);
}
} else if (equalIgnoringCase(equiv, "content-language"))
setContentLanguage(content);
else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
parseDNSPrefetchControlHeader(content);
else if (equalIgnoringCase(equiv, "x-frame-options")) {
if (frame) {
FrameLoader* frameLoader = frame->loader();
if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url())) {
frameLoader->stopAllLoaders();
frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), blankURL(), String());
DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to display document because display forbidden by X-Frame-Options.\n"));
frame->domWindow()->console()->addMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, consoleMessage, 1, String());
}
}
} else if (equalIgnoringCase(equiv, "x-webkit-csp"))
contentSecurityPolicy()->didReceiveHeader(content);
}
// Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
static bool isSeparator(UChar c)
{
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
}
void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
{
// Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
int keyBegin, keyEnd;
int valueBegin, valueEnd;
int i = 0;
int length = features.length();
String buffer = features.lower();
while (i < length) {
// skip to first non-separator, but don't skip past the end of the string
while (isSeparator(buffer[i])) {
if (i >= length)
break;
i++;
}
keyBegin = i;
// skip to first separator
while (!isSeparator(buffer[i]))
i++;
keyEnd = i;
// skip to first '=', but don't skip past a ',' or the end of the string
while (buffer[i] != '=') {
if (buffer[i] == ',' || i >= length)
break;
i++;
}
// skip to first non-separator, but don't skip past a ',' or the end of the string
while (isSeparator(buffer[i])) {
if (buffer[i] == ',' || i >= length)
break;
i++;
}
valueBegin = i;
// skip to first separator
while (!isSeparator(buffer[i]))
i++;
valueEnd = i;
ASSERT(i <= length);
String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
#ifdef ANDROID_META_SUPPORT
if (frame())
frame()->settings()->setMetadataSettings(keyString, valueString);
#endif
if (callback && data)
callback(keyString, valueString, this, data);
}
}
void Document::processViewport(const String& features)
{
ASSERT(!features.isNull());
m_viewportArguments = ViewportArguments();
processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
Frame* frame = this->frame();
if (!frame || !frame->page())
return;
frame->page()->updateViewportArguments();
}
MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const IntPoint& documentPoint, const PlatformMouseEvent& event)
{
ASSERT(!renderer() || renderer()->isRenderView());
if (!renderer())
return MouseEventWithHitTestResults(event, HitTestResult(IntPoint()));
HitTestResult result(documentPoint);
renderView()->layer()->hitTest(request, result);
if (!request.readOnly())
updateStyleIfNeeded();
return MouseEventWithHitTestResults(event, result);
}
// DOM Section 1.1.1
bool Document::childTypeAllowed(NodeType type) const
{
switch (type) {
case ATTRIBUTE_NODE:
case CDATA_SECTION_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_NODE:
case ENTITY_NODE:
case ENTITY_REFERENCE_NODE:
case NOTATION_NODE:
case TEXT_NODE:
case XPATH_NAMESPACE_NODE:
return false;
case COMMENT_NODE:
case PROCESSING_INSTRUCTION_NODE:
return true;
case DOCUMENT_TYPE_NODE:
case ELEMENT_NODE:
// Documents may contain no more than one of each of these.
// (One Element and one DocumentType.)
for (Node* c = firstChild(); c; c = c->nextSibling())
if (c->nodeType() == type)
return false;
return true;
}
return false;
}
bool Document::canReplaceChild(Node* newChild, Node* oldChild)
{
if (!oldChild)
// ContainerNode::replaceChild will raise a NOT_FOUND_ERR.
return true;
if (oldChild->nodeType() == newChild->nodeType())
return true;
int numDoctypes = 0;
int numElements = 0;
// First, check how many doctypes and elements we have, not counting
// the child we're about to remove.
for (Node* c = firstChild(); c; c = c->nextSibling()) {
if (c == oldChild)
continue;
switch (c->nodeType()) {
case DOCUMENT_TYPE_NODE:
numDoctypes++;
break;
case ELEMENT_NODE:
numElements++;
break;
default:
break;
}
}
// Then, see how many doctypes and elements might be added by the new child.
if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
for (Node* c = firstChild(); c; c = c->nextSibling()) {
switch (c->nodeType()) {
case ATTRIBUTE_NODE:
case CDATA_SECTION_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_NODE:
case ENTITY_NODE:
case ENTITY_REFERENCE_NODE:
case NOTATION_NODE:
case TEXT_NODE:
case XPATH_NAMESPACE_NODE:
return false;
case COMMENT_NODE:
case PROCESSING_INSTRUCTION_NODE:
break;
case DOCUMENT_TYPE_NODE:
numDoctypes++;
break;
case ELEMENT_NODE:
numElements++;
break;
}
}
} else {
switch (newChild->nodeType()) {
case ATTRIBUTE_NODE:
case CDATA_SECTION_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_NODE:
case ENTITY_NODE:
case ENTITY_REFERENCE_NODE:
case NOTATION_NODE:
case TEXT_NODE:
case XPATH_NAMESPACE_NODE:
return false;
case COMMENT_NODE:
case PROCESSING_INSTRUCTION_NODE:
return true;
case DOCUMENT_TYPE_NODE:
numDoctypes++;
break;
case ELEMENT_NODE:
numElements++;
break;
}
}
if (numElements > 1 || numDoctypes > 1)
return false;
return true;
}
PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
{
// Spec says cloning Document nodes is "implementation dependent"
// so we do not support it...
return 0;
}
StyleSheetList* Document::styleSheets()
{
return m_styleSheets.get();
}
String Document::preferredStylesheetSet() const
{
return m_preferredStylesheetSet;
}
String Document::selectedStylesheetSet() const
{
return m_selectedStylesheetSet;
}
void Document::setSelectedStylesheetSet(const String& aString)
{
m_selectedStylesheetSet = aString;
styleSelectorChanged(DeferRecalcStyle);
}
// This method is called whenever a top-level stylesheet has finished loading.
void Document::removePendingSheet()
{
// Make sure we knew this sheet was pending, and that our count isn't out of sync.
ASSERT(m_pendingStylesheets > 0);
m_pendingStylesheets--;
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Stylesheet loaded at time %d. %d stylesheets still remain.\n", elapsedTime(), m_pendingStylesheets);
#endif
if (m_pendingStylesheets)
return;
styleSelectorChanged(RecalcStyleImmediately);
if (ScriptableDocumentParser* parser = scriptableDocumentParser())
parser->executeScriptsWaitingForStylesheets();
if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
view()->scrollToFragment(m_url);
}
void Document::styleSelectorChanged(StyleSelectorUpdateFlag updateFlag)
{
// Don't bother updating, since we haven't loaded all our style info yet
// and haven't calculated the style selector for the first time.
if (!attached() || (!m_didCalculateStyleSelector && !haveStylesheetsLoaded()))
return;
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Beginning update of style selector at time %d.\n", elapsedTime());
#endif
recalcStyleSelector();
if (updateFlag == DeferRecalcStyle) {
scheduleForcedStyleRecalc();
return;
}
if (didLayoutWithPendingStylesheets() && m_pendingStylesheets <= 0) {
m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
if (renderer())
renderer()->repaint();
}
// This recalcStyle initiates a new recalc cycle. We need to bracket it to
// make sure animations get the correct update time
if (m_frame)
m_frame->animation()->beginAnimationUpdate();
recalcStyle(Force);
if (m_frame)
m_frame->animation()->endAnimationUpdate();
#ifdef INSTRUMENT_LAYOUT_SCHEDULING
if (!ownerElement())
printf("Finished update of style selector at time %d\n", elapsedTime());
#endif
if (renderer()) {
renderer()->setNeedsLayoutAndPrefWidthsRecalc();
if (view())
view()->scheduleRelayout();
}
if (m_mediaQueryMatcher)
m_mediaQueryMatcher->styleSelectorChanged();
}
void Document::addStyleSheetCandidateNode(Node* node, bool createdByParser)
{
if (!node->inDocument())
return;
// Until the <body> exists, we have no choice but to compare document positions,
// since styles outside of the body and head continue to be shunted into the head
// (and thus can shift to end up before dynamically added DOM content that is also
// outside the body).
if ((createdByParser && body()) || m_styleSheetCandidateNodes.isEmpty()) {
m_styleSheetCandidateNodes.add(node);
return;
}
// Determine an appropriate insertion point.
StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
StyleSheetCandidateListHashSet::iterator it = end;
Node* followingNode = 0;
do {
--it;
Node* n = *it;
unsigned short position = n->compareDocumentPosition(node);
if (position == DOCUMENT_POSITION_FOLLOWING) {
m_styleSheetCandidateNodes.insertBefore(followingNode, node);
return;
}
followingNode = n;
} while (it != begin);
m_styleSheetCandidateNodes.insertBefore(followingNode, node);
}
void Document::removeStyleSheetCandidateNode(Node* node)
{
m_styleSheetCandidateNodes.remove(node);
}
void Document::recalcStyleSelector()
{
if (m_inStyleRecalc) {
// SVG <use> element may manage to invalidate style selector in the middle of a style recalc.
// https://bugs.webkit.org/show_bug.cgi?id=54344
// FIXME: This should be fixed in SVG and this code replaced with ASSERT(!m_inStyleRecalc).
m_hasDirtyStyleSelector = true;
scheduleForcedStyleRecalc();
return;
}
if (!renderer() || !attached())
return;
StyleSheetVector sheets;
bool matchAuthorAndUserStyles = true;
if (Settings* settings = this->settings())
matchAuthorAndUserStyles = settings->authorAndUserStylesEnabled();
StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
if (!matchAuthorAndUserStyles)
end = begin;
for (StyleSheetCandidateListHashSet::iterator it = begin; it != end; ++it) {
Node* n = *it;
StyleSheet* sheet = 0;
if (n->nodeType() == PROCESSING_INSTRUCTION_NODE) {
// Processing instruction (XML documents only).
// We don't support linking to embedded CSS stylesheets, see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion.
ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
sheet = pi->sheet();
#if ENABLE(XSLT)
// Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
if (pi->isXSL() && !transformSourceDocument()) {
// Don't apply XSL transforms until loading is finished.
if (!parsing())
applyXSLTransform(pi);
return;
}
#endif
} else if ((n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag)))
#if ENABLE(SVG)
|| (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
#endif
) {
Element* e = static_cast<Element*>(n);
AtomicString title = e->getAttribute(titleAttr);
bool enabledViaScript = false;
if (e->hasLocalName(linkTag)) {
// <LINK> element
HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(n);
if (linkElement->isDisabled())
continue;
enabledViaScript = linkElement->isEnabledViaScript();
if (linkElement->isLoading()) {
// it is loading but we should still decide which style sheet set to use
if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSet.isEmpty()) {
const AtomicString& rel = e->getAttribute(relAttr);
if (!rel.contains("alternate")) {
m_preferredStylesheetSet = title;
m_selectedStylesheetSet = title;
}
}
continue;
}
if (!linkElement->sheet())
title = nullAtom;
}
// Get the current preferred styleset. This is the
// set of sheets that will be enabled.
#if ENABLE(SVG)
if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
sheet = static_cast<SVGStyleElement*>(n)->sheet();
else
#endif
if (e->hasLocalName(linkTag))
sheet = static_cast<HTMLLinkElement*>(n)->sheet();
else
// <STYLE> element
sheet = static_cast<HTMLStyleElement*>(n)->sheet();
// Check to see if this sheet belongs to a styleset
// (thus making it PREFERRED or ALTERNATE rather than
// PERSISTENT).
if (!enabledViaScript && !title.isEmpty()) {
// Yes, we have a title.
if (m_preferredStylesheetSet.isEmpty()) {
// No preferred set has been established. If
// we are NOT an alternate sheet, then establish
// us as the preferred set. Otherwise, just ignore
// this sheet.
AtomicString rel = e->getAttribute(relAttr);
if (e->hasLocalName(styleTag) || !rel.contains("alternate"))
m_preferredStylesheetSet = m_selectedStylesheetSet = title;
}
if (title != m_preferredStylesheetSet)
sheet = 0;
}
}
if (sheet)
sheets.append(sheet);
}
m_styleSheets->swap(sheets);
m_styleSelector.clear();
m_didCalculateStyleSelector = true;
m_hasDirtyStyleSelector = false;
}
void Document::setHoverNode(PassRefPtr<Node> newHoverNode)
{
m_hoverNode = newHoverNode;
}
void Document::setActiveNode(PassRefPtr<Node> newActiveNode)
{
m_activeNode = newActiveNode;
}
void Document::focusedNodeRemoved()
{
setFocusedNode(0);
}
void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
{
if (!m_focusedNode || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
return;
bool nodeInSubtree = false;
if (amongChildrenOnly)
nodeInSubtree = m_focusedNode->isDescendantOf(node);
else
nodeInSubtree = (m_focusedNode == node) || m_focusedNode->isDescendantOf(node);
if (nodeInSubtree)
document()->focusedNodeRemoved();
}
void Document::hoveredNodeDetached(Node* node)
{
if (!m_hoverNode || (node != m_hoverNode && (!m_hoverNode->isTextNode() || node != m_hoverNode->parentNode())))
return;
m_hoverNode = node->parentNode();
while (m_hoverNode && !m_hoverNode->renderer())
m_hoverNode = m_hoverNode->parentNode();
if (frame())
frame()->eventHandler()->scheduleHoverStateUpdate();
}
void Document::activeChainNodeDetached(Node* node)
{
if (!m_activeNode || (node != m_activeNode && (!m_activeNode->isTextNode() || node != m_activeNode->parentNode())))
return;
m_activeNode = node->parentNode();
while (m_activeNode && !m_activeNode->renderer())
m_activeNode = m_activeNode->parentNode();
}
#if ENABLE(DASHBOARD_SUPPORT)
const Vector<DashboardRegionValue>& Document::dashboardRegions() const
{
return m_dashboardRegions;
}
void Document::setDashboardRegions(const Vector<DashboardRegionValue>& regions)
{
m_dashboardRegions = regions;
setDashboardRegionsDirty(false);
}
#endif
//SAMSUNG CHANGES : FACEBOOK PERFORMANCE IMPROVEMENT : Praveen Munukutla(sataya.m@samsung.com)>>>
void Document::setCheckNode(PassRefPtr<Node> newCheckNode)
{
//set the check node
m_checkNode = newCheckNode.get();
}
//SAMSUNG CHANGES : FACEBOOK PERFORMANCE IMPROVEMENT : Praveen Munukutla(sataya.m@samsung.com)<<<
bool Document::setFocusedNode(PassRefPtr<Node> newFocusedNode)
{
// Make sure newFocusedNode is actually in this document
if (newFocusedNode && (newFocusedNode->document() != this))
return true;
if (m_focusedNode == newFocusedNode)
return true;
if (m_inPageCache)
return false;
bool focusChangeBlocked = false;
RefPtr<Node> oldFocusedNode = m_focusedNode;
m_focusedNode = 0;
// Remove focus from the existing focus node (if any)
if (oldFocusedNode && !oldFocusedNode->inDetach()) {
if (oldFocusedNode->active())
oldFocusedNode->setActive(false);
oldFocusedNode->setFocus(false);
// Dispatch a change event for text fields or textareas that have been edited
if (oldFocusedNode->isElementNode()) {
Element* element = static_cast<Element*>(oldFocusedNode.get());
if (element->wasChangedSinceLastFormControlChangeEvent())
element->dispatchFormControlChangeEvent();
}
// Dispatch the blur event and let the node do any other blur related activities (important for text fields)
oldFocusedNode->dispatchBlurEvent();
if (m_focusedNode) {
// handler shifted focus
focusChangeBlocked = true;
newFocusedNode = 0;
}
oldFocusedNode->dispatchUIEvent(eventNames().focusoutEvent, 0, 0); // DOM level 3 name for the bubbling blur event.
// FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
// on it, probably when <rdar://problem/8503958> is resolved.
oldFocusedNode->dispatchUIEvent(eventNames().DOMFocusOutEvent, 0, 0); // DOM level 2 name for compatibility.
if (m_focusedNode) {
// handler shifted focus
focusChangeBlocked = true;
newFocusedNode = 0;
}
if (oldFocusedNode == this && oldFocusedNode->hasOneRef())
return true;
if (oldFocusedNode == oldFocusedNode->rootEditableElement())
frame()->editor()->didEndEditing();
if (view()) {
Widget* oldWidget = widgetForNode(oldFocusedNode.get());
if (oldWidget)
oldWidget->setFocus(false);
else
view()->setFocus(false);
}
}
if (newFocusedNode) {
if (newFocusedNode == newFocusedNode->rootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) {
// delegate blocks focus change
focusChangeBlocked = true;
goto SetFocusedNodeDone;
}
// Set focus on the new node
m_focusedNode = newFocusedNode.get();
// Dispatch the focus event and let the node do any other focus related activities (important for text fields)
m_focusedNode->dispatchFocusEvent();
if (m_focusedNode != newFocusedNode) {
// handler shifted focus
focusChangeBlocked = true;
goto SetFocusedNodeDone;
}
m_focusedNode->dispatchUIEvent(eventNames().focusinEvent, 0, 0); // DOM level 3 bubbling focus event.
// FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
// on it, probably when <rdar://problem/8503958> is resolved.
m_focusedNode->dispatchUIEvent(eventNames().DOMFocusInEvent, 0, 0); // DOM level 2 for compatibility.
if (m_focusedNode != newFocusedNode) {
// handler shifted focus
focusChangeBlocked = true;
goto SetFocusedNodeDone;
}
m_focusedNode->setFocus(true);
if (m_focusedNode == m_focusedNode->rootEditableElement())
frame()->editor()->didBeginEditing();
// eww, I suck. set the qt focus correctly
// ### find a better place in the code for this
if (view()) {
Widget* focusWidget = widgetForNode(m_focusedNode.get());
if (focusWidget) {
// Make sure a widget has the right size before giving it focus.
// Otherwise, we are testing edge cases of the Widget code.
// Specifically, in WebCore this does not work well for text fields.
updateLayout();
// Re-get the widget in case updating the layout changed things.
focusWidget = widgetForNode(m_focusedNode.get());
}
if (focusWidget)
focusWidget->setFocus(true);
else
view()->setFocus(true);
}
//SAMSUNG CHANGES : FACEBOOK PERFORMANCE IMPROVEMENT : Praveen Munukutla(sataya.m@samsung.com)>>>
setCheckNode(0);
//SAMSUNG CHANGES : FACEBOOK PERFORMANCE IMPROVEMENT : Praveen Munukutla(sataya.m@samsung.com)<<<
}
#if PLATFORM(MAC) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(CHROMIUM)
if (!focusChangeBlocked && m_focusedNode && AXObjectCache::accessibilityEnabled()) {
RenderObject* oldFocusedRenderer = 0;
RenderObject* newFocusedRenderer = 0;
if (oldFocusedNode)
oldFocusedRenderer = oldFocusedNode->renderer();
if (newFocusedNode)
newFocusedRenderer = newFocusedNode->renderer();
axObjectCache()->handleFocusedUIElementChanged(oldFocusedRenderer, newFocusedRenderer);
}
#endif
if (!focusChangeBlocked)
page()->chrome()->focusedNodeChanged(m_focusedNode.get());
SetFocusedNodeDone:
updateStyleIfNeeded();
return !focusChangeBlocked;
}
void Document::getFocusableNodes(Vector<RefPtr<Node> >& nodes)
{
updateLayout();
for (Node* node = firstChild(); node; node = node->traverseNextNode()) {
if (node->isFocusable())
nodes.append(node);
}
}
void Document::setCSSTarget(Element* n)
{
if (m_cssTarget)
m_cssTarget->setNeedsStyleRecalc();
m_cssTarget = n;
if (n)
n->setNeedsStyleRecalc();
}
void Document::attachNodeIterator(NodeIterator* ni)
{
m_nodeIterators.add(ni);
}
void Document::detachNodeIterator(NodeIterator* ni)
{
// The node iterator can be detached without having been attached if its root node didn't have a document
// when the iterator was created, but has it now.
m_nodeIterators.remove(ni);
}
void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
{
HashSet<NodeIterator*> nodeIteratorsList = m_nodeIterators;
HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = nodeIteratorsList.end();
for (HashSet<NodeIterator*>::const_iterator it = nodeIteratorsList.begin(); it != nodeIteratorsEnd; ++it) {
if ((*it)->root() == node) {
detachNodeIterator(*it);
newDocument->attachNodeIterator(*it);
}
}
}
void Document::nodeChildrenChanged(ContainerNode* container)
{
if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->nodeChildrenChanged(container);
}
}
void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
{
if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->nodeChildrenWillBeRemoved(container);
}
HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
for (Node* n = container->firstChild(); n; n = n->nextSibling())
(*it)->nodeWillBeRemoved(n);
}
if (Frame* frame = this->frame()) {
for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
frame->selection()->nodeWillBeRemoved(n);
frame->page()->dragCaretController()->nodeWillBeRemoved(n);
}
}
}
void Document::nodeWillBeRemoved(Node* n)
{
HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
(*it)->nodeWillBeRemoved(n);
if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator rangesEnd = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != rangesEnd; ++it)
(*it)->nodeWillBeRemoved(n);
}
if (Frame* frame = this->frame()) {
frame->selection()->nodeWillBeRemoved(n);
frame->page()->dragCaretController()->nodeWillBeRemoved(n);
}
#if ENABLE(FULLSCREEN_API)
// If the current full screen element or any of its ancestors is removed, set the current
// full screen element to the document root, and fire a fullscreenchange event to inform
// clients of the DOM.
ASSERT(n);
if (n->contains(m_fullScreenElement.get())) {
ASSERT(n != documentElement());
if (m_fullScreenRenderer)
m_fullScreenRenderer->remove();
setFullScreenRenderer(0);
m_fullScreenElement = documentElement();
recalcStyle(Force);
m_fullScreenChangeDelayTimer.startOneShot(0);
}
#endif
}
void Document::textInserted(Node* text, unsigned offset, unsigned length)
{
if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->textInserted(text, offset, length);
}
// Update the markers for spelling and grammar checking.
m_markers->shiftMarkers(text, offset, length);
}
void Document::textRemoved(Node* text, unsigned offset, unsigned length)
{
if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->textRemoved(text, offset, length);
}
// Update the markers for spelling and grammar checking.
m_markers->removeMarkers(text, offset, length);
m_markers->shiftMarkers(text, offset + length, 0 - length);
}
void Document::textNodesMerged(Text* oldNode, unsigned offset)
{
if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
NodeWithIndex oldNodeWithIndex(oldNode);
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->textNodesMerged(oldNodeWithIndex, offset);
}
// FIXME: This should update markers for spelling and grammar checking.
}
void Document::textNodeSplit(Text* oldNode)
{
if (!disableRangeMutation(page()) && !m_ranges.isEmpty()) {
HashSet<Range*>::const_iterator end = m_ranges.end();
for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
(*it)->textNodeSplit(oldNode);
}
// FIXME: This should update markers for spelling and grammar checking.
}
// FIXME: eventually, this should return a DOMWindow stored in the document.
DOMWindow* Document::domWindow() const
{
if (!frame())
return 0;
// The m_frame pointer is not (not always?) zeroed out when the document is put into b/f cache, so the frame can hold an unrelated document/window pair.
// FIXME: We should always zero out the frame pointer on navigation to avoid accidentally accessing the new frame content.
if (m_frame->document() != this)
return 0;
return frame()->domWindow();
}
void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
{
DOMWindow* domWindow = this->domWindow();
if (!domWindow)
return;
domWindow->setAttributeEventListener(eventType, listener);
}
EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
{
DOMWindow* domWindow = this->domWindow();
if (!domWindow)
return 0;
return domWindow->getAttributeEventListener(eventType);
}
void Document::dispatchWindowEvent(PassRefPtr<Event> event, PassRefPtr<EventTarget> target)
{
ASSERT(!eventDispatchForbidden());
DOMWindow* domWindow = this->domWindow();
if (!domWindow)
return;
domWindow->dispatchEvent(event, target);
}
void Document::dispatchWindowLoadEvent()
{
ASSERT(!eventDispatchForbidden());
DOMWindow* domWindow = this->domWindow();
if (!domWindow)
return;
domWindow->dispatchLoadEvent();
}
void Document::enqueueWindowEvent(PassRefPtr<Event> event)
{
event->setTarget(domWindow());
m_eventQueue->enqueueEvent(event);
}
void Document::enqueueDocumentEvent(PassRefPtr<Event> event)
{
event->setTarget(this);
m_eventQueue->enqueueEvent(event);
}
PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionCode& ec)
{
RefPtr<Event> event;
if (eventType == "Event" || eventType == "Events" || eventType == "HTMLEvents")
event = Event::create();
else if (eventType == "CustomEvent")
event = CustomEvent::create();
else if (eventType == "KeyboardEvent" || eventType == "KeyboardEvents")
event = KeyboardEvent::create();
else if (eventType == "MessageEvent")
event = MessageEvent::create();
else if (eventType == "MouseEvent" || eventType == "MouseEvents")
event = MouseEvent::create();
else if (eventType == "MutationEvent" || eventType == "MutationEvents")
event = MutationEvent::create();
else if (eventType == "OverflowEvent")
event = OverflowEvent::create();
else if (eventType == "PageTransitionEvent")
event = PageTransitionEvent::create();
else if (eventType == "ProgressEvent")
event = ProgressEvent::create();
#if ENABLE(DOM_STORAGE)
else if (eventType == "StorageEvent")
event = StorageEvent::create();
#endif
else if (eventType == "TextEvent")
event = TextEvent::create();
else if (eventType == "UIEvent" || eventType == "UIEvents")
event = UIEvent::create();
else if (eventType == "WebKitAnimationEvent")
event = WebKitAnimationEvent::create();
else if (eventType == "WebKitTransitionEvent")
event = WebKitTransitionEvent::create();
else if (eventType == "WheelEvent")
event = WheelEvent::create();
#if ENABLE(SVG)
else if (eventType == "SVGEvents")
event = Event::create();
else if (eventType == "SVGZoomEvents")
event = SVGZoomEvent::create();
#endif
#if ENABLE(TOUCH_EVENTS)
#if USE(V8)
else if (eventType == "TouchEvent" && RuntimeEnabledFeatures::touchEnabled())
#else
else if (eventType == "TouchEvent")
#endif
event = TouchEvent::create();
#endif
#if ENABLE(DEVICE_ORIENTATION)
else if (eventType == "DeviceMotionEvent")
event = DeviceMotionEvent::create();
else if (eventType == "DeviceOrientationEvent")
event = DeviceOrientationEvent::create();
#endif
#if ENABLE(ORIENTATION_EVENTS)
else if (eventType == "OrientationEvent")
event = Event::create();
#endif
if (event)
return event.release();
ec = NOT_SUPPORTED_ERR;
return 0;
}
void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
{
if (eventType == eventNames().DOMSubtreeModifiedEvent)
addListenerType(DOMSUBTREEMODIFIED_LISTENER);
else if (eventType == eventNames().DOMNodeInsertedEvent)
addListenerType(DOMNODEINSERTED_LISTENER);
else if (eventType == eventNames().DOMNodeRemovedEvent)
addListenerType(DOMNODEREMOVED_LISTENER);
else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
else if (eventType == eventNames().DOMAttrModifiedEvent)
addListenerType(DOMATTRMODIFIED_LISTENER);
else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
else if (eventType == eventNames().overflowchangedEvent)
addListenerType(OVERFLOWCHANGED_LISTENER);
else if (eventType == eventNames().webkitAnimationStartEvent)
addListenerType(ANIMATIONSTART_LISTENER);
else if (eventType == eventNames().webkitAnimationEndEvent)
addListenerType(ANIMATIONEND_LISTENER);
else if (eventType == eventNames().webkitAnimationIterationEvent)
addListenerType(ANIMATIONITERATION_LISTENER);
else if (eventType == eventNames().webkitTransitionEndEvent)
addListenerType(TRANSITIONEND_LISTENER);
else if (eventType == eventNames().beforeloadEvent)
addListenerType(BEFORELOAD_LISTENER);
else if (eventType == eventNames().beforeprocessEvent)
addListenerType(BEFOREPROCESS_LISTENER);
#if ENABLE(TOUCH_EVENTS)
else if (eventType == eventNames().touchstartEvent
|| eventType == eventNames().touchmoveEvent
|| eventType == eventNames().touchendEvent
|| eventType == eventNames().touchcancelEvent) {
addListenerType(TOUCH_LISTENER);
if (Page* page = this->page())
page->chrome()->client()->needTouchEvents(true);
}
#endif
}
CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
{
return 0;
}
HTMLFrameOwnerElement* Document::ownerElement() const
{
if (!frame())
return 0;
return frame()->ownerElement();
}
String Document::cookie(ExceptionCode& ec) const
{
if (page() && !page()->cookieEnabled())
return String();
// FIXME: The HTML5 DOM spec states that this attribute can raise an
// INVALID_STATE_ERR exception on getting if the Document has no
// browsing context.
if (!securityOrigin()->canAccessCookies()) {
ec = SECURITY_ERR;
return String();
}
KURL cookieURL = this->cookieURL();
if (cookieURL.isEmpty())
return String();
return cookies(this, cookieURL);
}
void Document::setCookie(const String& value, ExceptionCode& ec)
{
if (page() && !page()->cookieEnabled())
return;
// FIXME: The HTML5 DOM spec states that this attribute can raise an
// INVALID_STATE_ERR exception on setting if the Document has no
// browsing context.
if (!securityOrigin()->canAccessCookies()) {
ec = SECURITY_ERR;
return;
}
KURL cookieURL = this->cookieURL();
if (cookieURL.isEmpty())
return;
setCookies(this, cookieURL, value);
}
String Document::referrer() const
{
if (frame())
return frame()->loader()->referrer();
return String();
}
String Document::domain() const
{
return securityOrigin()->domain();
}
void Document::setDomain(const String& newDomain, ExceptionCode& ec)
{
if (SecurityOrigin::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
ec = SECURITY_ERR;
return;
}
// Both NS and IE specify that changing the domain is only allowed when
// the new domain is a suffix of the old domain.
// FIXME: We should add logging indicating why a domain was not allowed.
// If the new domain is the same as the old domain, still call
// securityOrigin()->setDomainForDOM. This will change the
// security check behavior. For example, if a page loaded on port 8000
// assigns its current domain using document.domain, the page will
// allow other pages loaded on different ports in the same domain that
// have also assigned to access this page.
if (equalIgnoringCase(domain(), newDomain)) {
securityOrigin()->setDomainFromDOM(newDomain);
if (m_frame)
m_frame->script()->updateSecurityOrigin();
return;
}
int oldLength = domain().length();
int newLength = newDomain.length();
// e.g. newDomain = webkit.org (10) and domain() = www.webkit.org (14)
if (newLength >= oldLength) {
ec = SECURITY_ERR;
return;
}
String test = domain();
// Check that it's a subdomain, not e.g. "ebkit.org"
if (test[oldLength - newLength - 1] != '.') {
ec = SECURITY_ERR;
return;
}
// Now test is "webkit.org" from domain()
// and we check that it's the same thing as newDomain
test.remove(0, oldLength - newLength);
if (test != newDomain) {
ec = SECURITY_ERR;
return;
}
securityOrigin()->setDomainFromDOM(newDomain);
if (m_frame)
m_frame->script()->updateSecurityOrigin();
}
// http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
String Document::lastModified() const
{
DateComponents date;
bool foundDate = false;
if (m_frame) {
String httpLastModified;
if (DocumentLoader* documentLoader = loader())
httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
if (!httpLastModified.isEmpty()) {
date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
foundDate = true;
}
}
// FIXME: If this document came from the file system, the HTML5
// specificiation tells us to read the last modification date from the file
// system.
if (!foundDate)
date.setMillisecondsSinceEpochForDateTime(currentTimeMS());
return String::format("%02d/%02d/%04d %02d:%02d:%02d", date.month() + 1, date.monthDay(), date.fullYear(), date.hour(), date.minute(), date.second());
}
static bool isValidNameNonASCII(const UChar* characters, unsigned length)
{
unsigned i = 0;
UChar32 c;
U16_NEXT(characters, i, length, c)
if (!isValidNameStart(c))
return false;
while (i < length) {
U16_NEXT(characters, i, length, c)
if (!isValidNamePart(c))
return false;
}
return true;
}
static inline bool isValidNameASCII(const UChar* characters, unsigned length)
{
UChar c = characters[0];
if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
return false;
for (unsigned i = 1; i < length; ++i) {
c = characters[i];
if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
return false;
}
return true;
}
bool Document::isValidName(const String& name)
{
unsigned length = name.length();
if (!length)
return false;
const UChar* characters = name.characters();
return isValidNameASCII(characters, length) || isValidNameNonASCII(characters, length);
}
bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode& ec)
{
unsigned length = qualifiedName.length();
if (!length) {
ec = INVALID_CHARACTER_ERR;
return false;
}
bool nameStart = true;
bool sawColon = false;
int colonPos = 0;
const UChar* s = qualifiedName.characters();
for (unsigned i = 0; i < length;) {
UChar32 c;
U16_NEXT(s, i, length, c)
if (c == ':') {
if (sawColon) {
ec = NAMESPACE_ERR;
return false; // multiple colons: not allowed
}
nameStart = true;
sawColon = true;
colonPos = i - 1;
} else if (nameStart) {
if (!isValidNameStart(c)) {
ec = INVALID_CHARACTER_ERR;
return false;
}
nameStart = false;
} else {
if (!isValidNamePart(c)) {
ec = INVALID_CHARACTER_ERR;
return false;
}
}
}
if (!sawColon) {
prefix = String();
localName = qualifiedName;
} else {
prefix = qualifiedName.substring(0, colonPos);
if (prefix.isEmpty()) {
ec = NAMESPACE_ERR;
return false;
}
localName = qualifiedName.substring(colonPos + 1);
}
if (localName.isEmpty()) {
ec = NAMESPACE_ERR;
return false;
}
return true;
}
void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
{
m_decoder = decoder;
}
KURL Document::completeURL(const String& url) const
{
// Always return a null URL when passed a null string.
// FIXME: Should we change the KURL constructor to have this behavior?
// See also [CSS]StyleSheet::completeURL(const String&)
if (url.isNull())
return KURL();
const KURL& baseURL = ((m_baseURL.isEmpty() || m_baseURL == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : m_baseURL;
if (!m_decoder)
return KURL(baseURL, url);
return KURL(baseURL, url, m_decoder->encoding());
}
void Document::setInPageCache(bool flag)
{
if (m_inPageCache == flag)
return;
m_inPageCache = flag;
if (flag) {
ASSERT(!m_savedRenderer);
m_savedRenderer = renderer();
if (FrameView* v = view())
v->resetScrollbarsAndClearContentsSize();
m_styleRecalcTimer.stop();
} else {
ASSERT(!renderer() || renderer() == m_savedRenderer);
ASSERT(m_renderArena);
setRenderer(m_savedRenderer);
m_savedRenderer = 0;
if (frame() && frame()->page())
frame()->page()->updateViewportArguments();
if (childNeedsStyleRecalc())
scheduleStyleRecalc();
}
}
void Document::documentWillBecomeInactive()
{
#if USE(ACCELERATED_COMPOSITING)
if (renderer())
renderView()->willMoveOffscreen();
#endif
HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
(*i)->documentWillBecomeInactive();
}
void Document::documentDidBecomeActive()
{
HashSet<Element*>::iterator end = m_documentActivationCallbackElements.end();
for (HashSet<Element*>::iterator i = m_documentActivationCallbackElements.begin(); i != end; ++i)
(*i)->documentDidBecomeActive();
#if USE(ACCELERATED_COMPOSITING)
if (renderer())
renderView()->didMoveOnscreen();
#endif
ASSERT(m_frame);
m_frame->loader()->client()->dispatchDidBecomeFrameset(isFrameSet());
}
void Document::registerForDocumentActivationCallbacks(Element* e)
{
m_documentActivationCallbackElements.add(e);
}
void Document::unregisterForDocumentActivationCallbacks(Element* e)
{
m_documentActivationCallbackElements.remove(e);
}
void Document::mediaVolumeDidChange()
{
HashSet<Element*>::iterator end = m_mediaVolumeCallbackElements.end();
for (HashSet<Element*>::iterator i = m_mediaVolumeCallbackElements.begin(); i != end; ++i)
(*i)->mediaVolumeDidChange();
}
void Document::registerForMediaVolumeCallbacks(Element* e)
{
m_mediaVolumeCallbackElements.add(e);
}
void Document::unregisterForMediaVolumeCallbacks(Element* e)
{
m_mediaVolumeCallbackElements.remove(e);
}
void Document::privateBrowsingStateDidChange()
{
HashSet<Element*>::iterator end = m_privateBrowsingStateChangedElements.end();
for (HashSet<Element*>::iterator it = m_privateBrowsingStateChangedElements.begin(); it != end; ++it)
(*it)->privateBrowsingStateDidChange();
}
void Document::registerForPrivateBrowsingStateChangedCallbacks(Element* e)
{
m_privateBrowsingStateChangedElements.add(e);
}
void Document::unregisterForPrivateBrowsingStateChangedCallbacks(Element* e)
{
m_privateBrowsingStateChangedElements.remove(e);
}
void Document::setShouldCreateRenderers(bool f)
{
m_createRenderers = f;
}
bool Document::shouldCreateRenderers()
{
return m_createRenderers;
}
// Support for Javascript execCommand, and related methods
static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
{
Frame* frame = document->frame();
if (!frame || frame->document() != document)
return Editor::Command();
document->updateStyleIfNeeded();
return frame->editor()->command(commandName,
userInterface ? CommandFromDOMWithUserInterface : CommandFromDOM);
}
bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
{
return command(this, commandName, userInterface).execute(value);
}
bool Document::queryCommandEnabled(const String& commandName)
{
return command(this, commandName).isEnabled();
}
bool Document::queryCommandIndeterm(const String& commandName)
{
return command(this, commandName).state() == MixedTriState;
}
bool Document::queryCommandState(const String& commandName)
{
return command(this, commandName).state() == TrueTriState;
}
bool Document::queryCommandSupported(const String& commandName)
{
return command(this, commandName).isSupported();
}
String Document::queryCommandValue(const String& commandName)
{
return command(this, commandName).value();
}
#if ENABLE(XSLT)
void Document::applyXSLTransform(ProcessingInstruction* pi)
{
RefPtr<XSLTProcessor> processor = XSLTProcessor::create();
processor->setXSLStyleSheet(static_cast<XSLStyleSheet*>(pi->sheet()));
String resultMIMEType;
String newSource;
String resultEncoding;
if (!processor->transformToString(this, resultMIMEType, newSource, resultEncoding))
return;
// FIXME: If the transform failed we should probably report an error (like Mozilla does).
processor->createDocumentFromSource(newSource, resultEncoding, resultMIMEType, this, frame());
}
void Document::setTransformSource(PassOwnPtr<TransformSource> source)
{
if (m_transformSource == source)
return;
m_transformSource = source;
}
#endif
void Document::setDesignMode(InheritedBool value)
{
m_designMode = value;
}
Document::InheritedBool Document::getDesignMode() const
{
return m_designMode;
}
bool Document::inDesignMode() const
{
for (const Document* d = this; d; d = d->parentDocument()) {
if (d->m_designMode != inherit)
return d->m_designMode;
}
return false;
}
Document* Document::parentDocument() const
{
if (!m_frame)
return 0;
Frame* parent = m_frame->tree()->parent();
if (!parent)
return 0;
return parent->document();
}
Document* Document::topDocument() const
{
Document* doc = const_cast<Document *>(this);
Element* element;
while ((element = doc->ownerElement()))
doc = element->document();
return doc;
}
PassRefPtr<Attr> Document::createAttribute(const String& name, ExceptionCode& ec)
{
return createAttributeNS(String(), name, ec, true);
}
PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode& ec, bool shouldIgnoreNamespaceChecks)
{
String prefix, localName;
if (!parseQualifiedName(qualifiedName, prefix, localName, ec))
return 0;
QualifiedName qName(prefix, localName, namespaceURI);
if (!shouldIgnoreNamespaceChecks && hasPrefixNamespaceMismatch(qName)) {
ec = NAMESPACE_ERR;
return 0;
}
// Spec: DOM Level 2 Core: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrAttrNS
if (!shouldIgnoreNamespaceChecks && qName.localName() == xmlnsAtom && qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI) {
ec = NAMESPACE_ERR;
return 0;
}
// FIXME: Assume this is a mapped attribute, since createAttribute isn't namespace-aware. There's no harm to XML
// documents if we're wrong.
return Attr::create(0, this, Attribute::createMapped(qName, StringImpl::empty()));
}
#if ENABLE(SVG)
const SVGDocumentExtensions* Document::svgExtensions()
{
return m_svgExtensions.get();
}
SVGDocumentExtensions* Document::accessSVGExtensions()
{
if (!m_svgExtensions)
m_svgExtensions = adoptPtr(new SVGDocumentExtensions(this));
return m_svgExtensions.get();
}
bool Document::hasSVGRootNode() const
{
return documentElement() && documentElement()->hasTagName(SVGNames::svgTag);
}
#endif
PassRefPtr<HTMLCollection> Document::images()
{
return HTMLCollection::create(this, DocImages);
}
PassRefPtr<HTMLCollection> Document::applets()
{
return HTMLCollection::create(this, DocApplets);
}
PassRefPtr<HTMLCollection> Document::embeds()
{
return HTMLCollection::create(this, DocEmbeds);
}
PassRefPtr<HTMLCollection> Document::plugins()
{
// This is an alias for embeds() required for the JS DOM bindings.
return HTMLCollection::create(this, DocEmbeds);
}
PassRefPtr<HTMLCollection> Document::objects()
{
return HTMLCollection::create(this, DocObjects);
}
PassRefPtr<HTMLCollection> Document::scripts()
{
return HTMLCollection::create(this, DocScripts);
}
PassRefPtr<HTMLCollection> Document::links()
{
return HTMLCollection::create(this, DocLinks);
}
PassRefPtr<HTMLCollection> Document::forms()
{
return HTMLCollection::create(this, DocForms);
}
PassRefPtr<HTMLCollection> Document::anchors()
{
return HTMLCollection::create(this, DocAnchors);
}
PassRefPtr<HTMLAllCollection> Document::all()
{
return HTMLAllCollection::create(this);
}
PassRefPtr<HTMLCollection> Document::windowNamedItems(const String &name)
{
return HTMLNameCollection::create(this, WindowNamedItems, name);
}
PassRefPtr<HTMLCollection> Document::documentNamedItems(const String &name)
{
return HTMLNameCollection::create(this, DocumentNamedItems, name);
}
CollectionCache* Document::nameCollectionInfo(CollectionType type, const AtomicString& name)
{
ASSERT(type >= FirstNamedDocumentCachedType);
unsigned index = type - FirstNamedDocumentCachedType;
ASSERT(index < NumNamedDocumentCachedTypes);
NamedCollectionMap& map = m_nameCollectionInfo[index];
NamedCollectionMap::iterator iter = map.find(name.impl());
if (iter == map.end())
iter = map.add(name.impl(), new CollectionCache).first;
iter->second->checkConsistency();
return iter->second;
}
void Document::finishedParsing()
{
ASSERT(!scriptableDocumentParser() || !m_parser->isParsing());
ASSERT(!scriptableDocumentParser() || m_readyState != Loading);
setParsing(false);
if (!m_documentTiming.domContentLoadedEventStart)
m_documentTiming.domContentLoadedEventStart = currentTime();
dispatchEvent(Event::create(eventNames().DOMContentLoadedEvent, true, false));
if (!m_documentTiming.domContentLoadedEventEnd)
m_documentTiming.domContentLoadedEventEnd = currentTime();
if (RefPtr<Frame> f = frame()) {
// FrameLoader::finishedParsing() might end up calling Document::implicitClose() if all
// resource loads are complete. HTMLObjectElements can start loading their resources from
// post attach callbacks triggered by recalcStyle(). This means if we parse out an <object>
// tag and then reach the end of the document without updating styles, we might not have yet
// started the resource load and might fire the window load event too early. To avoid this
// we force the styles to be up to date before calling FrameLoader::finishedParsing().
// See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
updateStyleIfNeeded();
f->loader()->finishedParsing();
InspectorInstrumentation::domContentLoadedEventFired(f.get(), url());
}
}
Vector<String> Document::formElementsState() const
{
Vector<String> stateVector;
stateVector.reserveInitialCapacity(m_formElementsWithState.size() * 3);
typedef FormElementListHashSet::const_iterator Iterator;
Iterator end = m_formElementsWithState.end();
for (Iterator it = m_formElementsWithState.begin(); it != end; ++it) {
Element* elementWithState = *it;
String value;
if (!elementWithState->shouldSaveAndRestoreFormControlState())
continue;
if (!elementWithState->saveFormControlState(value))
continue;
stateVector.append(elementWithState->formControlName().string());
stateVector.append(elementWithState->formControlType().string());
stateVector.append(value);
}
return stateVector;
}
#if ENABLE(XPATH)
PassRefPtr<XPathExpression> Document::createExpression(const String& expression,
XPathNSResolver* resolver,
ExceptionCode& ec)
{
if (!m_xpathEvaluator)
m_xpathEvaluator = XPathEvaluator::create();
return m_xpathEvaluator->createExpression(expression, resolver, ec);
}
PassRefPtr<XPathNSResolver> Document::createNSResolver(Node* nodeResolver)
{
if (!m_xpathEvaluator)
m_xpathEvaluator = XPathEvaluator::create();
return m_xpathEvaluator->createNSResolver(nodeResolver);
}
PassRefPtr<XPathResult> Document::evaluate(const String& expression,
Node* contextNode,
XPathNSResolver* resolver,
unsigned short type,
XPathResult* result,
ExceptionCode& ec)
{
if (!m_xpathEvaluator)
m_xpathEvaluator = XPathEvaluator::create();
return m_xpathEvaluator->evaluate(expression, contextNode, resolver, type, result, ec);
}
#endif // ENABLE(XPATH)
void Document::setStateForNewFormElements(const Vector<String>& stateVector)
{
// Walk the state vector backwards so that the value to use for each
// name/type pair first is the one at the end of each individual vector
// in the FormElementStateMap. We're using them like stacks.
typedef FormElementStateMap::iterator Iterator;
m_formElementsWithState.clear();
for (size_t i = stateVector.size() / 3 * 3; i; i -= 3) {
AtomicString a = stateVector[i - 3];
AtomicString b = stateVector[i - 2];
const String& c = stateVector[i - 1];
FormElementKey key(a.impl(), b.impl());
Iterator it = m_stateForNewFormElements.find(key);
if (it != m_stateForNewFormElements.end())
it->second.append(c);
else {
Vector<String> v(1);
v[0] = c;
m_stateForNewFormElements.set(key, v);
}
}
}
bool Document::hasStateForNewFormElements() const
{
return !m_stateForNewFormElements.isEmpty();
}
bool Document::takeStateForFormElement(AtomicStringImpl* name, AtomicStringImpl* type, String& state)
{
typedef FormElementStateMap::iterator Iterator;
Iterator it = m_stateForNewFormElements.find(FormElementKey(name, type));
if (it == m_stateForNewFormElements.end())
return false;
ASSERT(it->second.size());
state = it->second.last();
if (it->second.size() > 1)
it->second.removeLast();
else
m_stateForNewFormElements.remove(it);
return true;
}
FormElementKey::FormElementKey(AtomicStringImpl* name, AtomicStringImpl* type)
: m_name(name), m_type(type)
{
ref();
}
FormElementKey::~FormElementKey()
{
deref();
}
FormElementKey::FormElementKey(const FormElementKey& other)
: m_name(other.name()), m_type(other.type())
{
ref();
}
FormElementKey& FormElementKey::operator=(const FormElementKey& other)
{
other.ref();
deref();
m_name = other.name();
m_type = other.type();
return *this;
}
void FormElementKey::ref() const
{
if (name())
name()->ref();
if (type())
type()->ref();
}
void FormElementKey::deref() const
{
if (name())
name()->deref();
if (type())
type()->deref();
}
unsigned FormElementKeyHash::hash(const FormElementKey& key)
{
return StringHasher::hashMemory<sizeof(FormElementKey)>(&key);
}
void Document::setIconURL(const String& iconURL, const String& type)
{
// FIXME - <rdar://problem/4727645> - At some point in the future, we might actually honor the "type"
if (m_iconURL.isEmpty())
m_iconURL = iconURL;
else if (!type.isEmpty())
m_iconURL = iconURL;
if (Frame* f = frame())
f->loader()->setIconURL(m_iconURL);
}
void Document::registerFormElementWithFormAttribute(FormAssociatedElement* element)
{
ASSERT(toHTMLElement(element)->fastHasAttribute(formAttr));
m_formElementsWithFormAttribute.add(element);
}
void Document::unregisterFormElementWithFormAttribute(FormAssociatedElement* element)
{
m_formElementsWithFormAttribute.remove(element);
}
void Document::resetFormElementsOwner(HTMLFormElement* form)
{
typedef FormAssociatedElementListHashSet::iterator Iterator;
Iterator end = m_formElementsWithFormAttribute.end();
for (Iterator it = m_formElementsWithFormAttribute.begin(); it != end; ++it)
(*it)->resetFormOwner(form);
}
void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
{
if (m_useSecureKeyboardEntryWhenActive == usesSecureKeyboard)
return;
m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
m_frame->selection()->updateSecureKeyboardEntryIfActive();
}
bool Document::useSecureKeyboardEntryWhenActive() const
{
return m_useSecureKeyboardEntryWhenActive;
}
void Document::initSecurityContext()
{
if (securityOrigin() && !securityOrigin()->isEmpty())
return; // m_securityOrigin has already been initialized.
if (!m_frame) {
// No source for a security context.
// This can occur via document.implementation.createDocument().
m_cookieURL = KURL(ParsedURLString, "");
ScriptExecutionContext::setSecurityOrigin(SecurityOrigin::createEmpty());
m_contentSecurityPolicy = ContentSecurityPolicy::create();
return;
}
// In the common case, create the security context from the currently
// loading URL with a fresh content security policy.
m_cookieURL = m_url;
ScriptExecutionContext::setSecurityOrigin(SecurityOrigin::create(m_url, m_frame->loader()->sandboxFlags()));
m_contentSecurityPolicy = ContentSecurityPolicy::create(securityOrigin());
if (SecurityOrigin::allowSubstituteDataAccessToLocal()) {
// If this document was loaded with substituteData, then the document can
// load local resources. See https://bugs.webkit.org/show_bug.cgi?id=16756
// and https://bugs.webkit.org/show_bug.cgi?id=19760 for further
// discussion.
DocumentLoader* documentLoader = loader();
if (documentLoader && documentLoader->substituteData().isValid())
securityOrigin()->grantLoadLocalResources();
}
if (Settings* settings = this->settings()) {
if (!settings->isWebSecurityEnabled()) {
// Web security is turned off. We should let this document access every
// other document. This is used primary by testing harnesses for web
// sites.
securityOrigin()->grantUniversalAccess();
} else if (settings->allowUniversalAccessFromFileURLs() && securityOrigin()->isLocal()) {
// Some clients want file:// URLs to have universal access, but that
// setting is dangerous for other clients.
securityOrigin()->grantUniversalAccess();
} else if (!settings->allowFileAccessFromFileURLs() && securityOrigin()->isLocal()) {
// Some clients want file:// URLs to have even tighter restrictions by
// default, and not be able to access other local files.
securityOrigin()->enforceFilePathSeparation();
}
}
if (!securityOrigin()->isEmpty())
return;
// If we do not obtain a meaningful origin from the URL, then we try to
// find one via the frame hierarchy.
Frame* ownerFrame = m_frame->tree()->parent();
if (!ownerFrame)
ownerFrame = m_frame->loader()->opener();
if (ownerFrame) {
m_cookieURL = ownerFrame->document()->cookieURL();
// We alias the SecurityOrigins to match Firefox, see Bug 15313
// https://bugs.webkit.org/show_bug.cgi?id=15313
ScriptExecutionContext::setSecurityOrigin(ownerFrame->document()->securityOrigin());
// FIXME: Consider moving m_contentSecurityPolicy into SecurityOrigin.
m_contentSecurityPolicy = ownerFrame->document()->contentSecurityPolicy();
}
}
void Document::setSecurityOrigin(SecurityOrigin* securityOrigin)
{
ScriptExecutionContext::setSecurityOrigin(securityOrigin);
// FIXME: Find a better place to enable DNS prefetch, which is a loader concept,
// not applicable to arbitrary documents.
initDNSPrefetch();
}
#if ENABLE(DATABASE)
bool Document::allowDatabaseAccess() const
{
if (!page() || page()->settings()->privateBrowsingEnabled())
return false;
return true;
}
void Document::databaseExceededQuota(const String& name)
{
Page* currentPage = page();
if (currentPage)
currentPage->chrome()->client()->exceededDatabaseQuota(document()->frame(), name);
}
#endif
bool Document::isContextThread() const
{
return isMainThread();
}
void Document::updateURLForPushOrReplaceState(const KURL& url)
{
Frame* f = frame();
if (!f)
return;
setURL(url);
f->loader()->setOutgoingReferrer(url);
if (DocumentLoader* documentLoader = loader())
documentLoader->replaceRequestURLForSameDocumentNavigation(url);
}
void Document::statePopped(SerializedScriptValue* stateObject)
{
if (!frame())
return;
// Per step 11 of section 6.5.9 (history traversal) of the HTML5 spec, we
// defer firing of popstate until we're in the complete state.
if (m_readyState == Complete)
enqueuePopstateEvent(stateObject);
else
m_pendingStateObject = stateObject;
}
void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
{
m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
if (!m_updateFocusAppearanceTimer.isActive())
m_updateFocusAppearanceTimer.startOneShot(0);
}
void Document::cancelFocusAppearanceUpdate()
{
m_updateFocusAppearanceTimer.stop();
}
void Document::updateFocusAppearanceTimerFired(Timer<Document>*)
{
Node* node = focusedNode();
if (!node)
return;
if (!node->isElementNode())
return;
updateLayout();
Element* element = static_cast<Element*>(node);
if (element->isFocusable())
element->updateFocusAppearance(m_updateFocusAppearanceRestoresSelection);
}
// FF method for accessing the selection added for compatibility.
DOMSelection* Document::getSelection() const
{
return frame() ? frame()->domWindow()->getSelection() : 0;
}
#if ENABLE(WML)
void Document::resetWMLPageState()
{
if (WMLPageState* pageState = wmlPageStateForDocument(this))
pageState->reset();
}
void Document::initializeWMLPageState()
{
if (!isWMLDocument())
return;
static_cast<WMLDocument*>(this)->initialize();
}
#endif
void Document::attachRange(Range* range)
{
ASSERT(!m_ranges.contains(range));
m_ranges.add(range);
}
void Document::detachRange(Range* range)
{
// We don't ASSERT m_ranges.contains(range) to allow us to call this
// unconditionally to fix: https://bugs.webkit.org/show_bug.cgi?id=26044
m_ranges.remove(range);
}
CanvasRenderingContext* Document::getCSSCanvasContext(const String& type, const String& name, int width, int height)
{
HTMLCanvasElement* result = getCSSCanvasElement(name);
if (!result)
return 0;
result->setSize(IntSize(width, height));
return result->getContext(type);
}
HTMLCanvasElement* Document::getCSSCanvasElement(const String& name)
{
RefPtr<HTMLCanvasElement> result = m_cssCanvasElements.get(name).get();
if (!result) {
result = HTMLCanvasElement::create(this);
m_cssCanvasElements.set(name, result);
}
return result.get();
}
#ifdef WEBKIT_TEXT_SIZE_ADJUST
//SAMSUNG CHANGE BEGIN webkit-text-size-adjust >>
static PassRefPtr<RenderStyle> cloneRenderStyleWithState(const RenderStyle* currentStyle)
{
RefPtr<RenderStyle> newStyle = RenderStyle::clone(currentStyle);
if (currentStyle->childrenAffectedByForwardPositionalRules())
newStyle->setChildrenAffectedByForwardPositionalRules();
if (currentStyle->childrenAffectedByBackwardPositionalRules())
newStyle->setChildrenAffectedByBackwardPositionalRules();
if (currentStyle->childrenAffectedByFirstChildRules())
newStyle->setChildrenAffectedByFirstChildRules();
if (currentStyle->childrenAffectedByLastChildRules())
newStyle->setChildrenAffectedByLastChildRules();
if (currentStyle->childrenAffectedByDirectAdjacentRules())
newStyle->setChildrenAffectedByDirectAdjacentRules();
if (currentStyle->lastChildState())
newStyle->setLastChildState();
if (currentStyle->firstChildState())
newStyle->setFirstChildState();
newStyle->setChildIndex(currentStyle->childIndex());
if (currentStyle->affectedByEmpty())
newStyle->setEmptyState(currentStyle->emptyState());
return newStyle.release();
}
TextAutoSizingKey::TextAutoSizingKey() : m_style(0), m_doc(0)
{
}
TextAutoSizingKey::TextAutoSizingKey(RenderStyle* style, Document* doc)
: m_style(style), m_doc(doc)
{
ref();
}
TextAutoSizingKey::TextAutoSizingKey(const TextAutoSizingKey& other)
: m_style(other.m_style), m_doc(other.m_doc)
{
ref();
}
TextAutoSizingKey::~TextAutoSizingKey()
{
deref();
}
TextAutoSizingKey& TextAutoSizingKey::operator=(const TextAutoSizingKey& other)
{
other.ref();
deref();
m_style = other.m_style;
m_doc = other.m_doc;
return *this;
}
void TextAutoSizingKey::ref() const
{
if (isValidStyle())
m_style->ref();
}
void TextAutoSizingKey::deref() const
{
if (isValidStyle() && isValidDoc() && m_doc->renderArena())
m_style->deref();
}
void TextAutoSizingTraits::constructDeletedValue(TextAutoSizingKey& slot)
{
new (&slot) TextAutoSizingKey(TextAutoSizingKey::deletedKeyStyle(), TextAutoSizingKey::deletedKeyDoc());
}
bool TextAutoSizingTraits::isDeletedValue(const TextAutoSizingKey& value)
{
return value.style() == TextAutoSizingKey::deletedKeyStyle() && value.doc() == TextAutoSizingKey::deletedKeyDoc();
}
int TextAutoSizingValue::numNodes() const
{
return m_autoSizedNodes.size();
}
void TextAutoSizingValue::addNode(Node* node, float size)
{
ASSERT(node);
ASSERT(node->renderer());
RenderText* renderText = static_cast<RenderText*>(node->renderer());
renderText->setCandidateComputedTextSize(size);
m_autoSizedNodes.add(node);
}
#define MAX_SCALE_INCREASE 1.7f
bool TextAutoSizingValue::adjustNodeSizes()
{
bool objectsRemoved = false;
// Remove stale nodes. Nodes may have had their renderers detached. We'll
// also need to remove the style from the documents m_textAutoSizedNodes
// collection. Return true indicates we need to do that removal.
Vector<RefPtr<Node> > nodesForRemoval;
HashSet<RefPtr<Node> >::iterator end = m_autoSizedNodes.end();
for (HashSet<RefPtr<Node> >::iterator i = m_autoSizedNodes.begin(); i != end; ++i) {
RefPtr<Node> autoSizingNode = *i;
RenderText* text = static_cast<RenderText*>(autoSizingNode->renderer());
if (!text || (text->style() && !text->style()->textSizeAdjust().isAuto()) || !text->candidateComputedTextSize()) {
// remove node.
nodesForRemoval.append(autoSizingNode);
objectsRemoved = true;
}
}
unsigned count = nodesForRemoval.size();
for (unsigned i = 0; i < count; i++)
m_autoSizedNodes.remove(nodesForRemoval[i]);
// If we only have one piece of text with the style on the page don't
// adjust it's size.
if (m_autoSizedNodes.size() <= 1)
return objectsRemoved;
// Compute average size
float cumulativeSize = 0;
end = m_autoSizedNodes.end();
for (HashSet<RefPtr<Node> >::iterator i = m_autoSizedNodes.begin(); i != end; ++i) {
RefPtr<Node> autoSizingNode = *i;
RenderText* renderText = static_cast<RenderText*>(autoSizingNode->renderer());
cumulativeSize += renderText->candidateComputedTextSize();
}
float averageSize = roundf(cumulativeSize / m_autoSizedNodes.size());
// Adjust sizes
bool firstPass = true;
end = m_autoSizedNodes.end();
for (HashSet<RefPtr<Node> >::iterator i = m_autoSizedNodes.begin(); i != end; ++i) {
RefPtr<Node> autoSizingNode = *i;
RenderText* text = static_cast<RenderText*>(autoSizingNode->renderer());
if (text && text->style()->fontDescription().computedSize() <= averageSize) {
float specifiedSize = text->style()->fontDescription().specifiedSize();
float scaleChange = averageSize / specifiedSize;
if (scaleChange > MAX_SCALE_INCREASE && firstPass) {
firstPass = false;
averageSize = roundf(specifiedSize * MAX_SCALE_INCREASE);
scaleChange = averageSize / specifiedSize;
}
RefPtr<RenderStyle> style = cloneRenderStyleWithState(text->style());
FontDescription fontDescription = style->fontDescription();
fontDescription.setComputedSize(averageSize);
style->setFontDescription(fontDescription);
style->font().update(autoSizingNode->document()->styleSelector()->fontSelector());
text->setStyle(style.release());
RenderObject* parentRenderer = text->parent();
// If we have a list we should resize ListMarkers separately.
RenderObject* listMarkerRenderer = parentRenderer->firstChild();
if (listMarkerRenderer->isListMarker()) {
RefPtr<RenderStyle> style = cloneRenderStyleWithState(listMarkerRenderer->style());
style->setFontDescription(fontDescription);
style->font().update(autoSizingNode->document()->styleSelector()->fontSelector());
listMarkerRenderer->setStyle(style.release());
}
// Resize the line height of the parent.
const RenderStyle* parentStyle = parentRenderer->style();
Length lineHeightLength = parentStyle->specifiedLineHeight();
int specifiedLineHeight = 0;
if (lineHeightLength.isPercent())
specifiedLineHeight = lineHeightLength.calcMinValue(fontDescription.specifiedSize());
else
specifiedLineHeight = lineHeightLength.value();
int lineHeight = specifiedLineHeight * scaleChange;
if (!lineHeightLength.isFixed() || lineHeightLength.value() != lineHeight) {
RefPtr<RenderStyle> newParentStyle = cloneRenderStyleWithState(parentStyle);
newParentStyle->setLineHeight(Length(lineHeight, Fixed));
newParentStyle->setSpecifiedLineHeight(lineHeightLength);
newParentStyle->setFontDescription(fontDescription);
newParentStyle->font().update(autoSizingNode->document()->styleSelector()->fontSelector());
parentRenderer->setStyle(newParentStyle.release());
}
}
}
return objectsRemoved;
}
void TextAutoSizingValue::reset()
{
HashSet<RefPtr<Node> >::iterator end = m_autoSizedNodes.end();
for (HashSet<RefPtr<Node> >::iterator i = m_autoSizedNodes.begin(); i != end; ++i) {
RefPtr<Node> autoSizingNode = *i;
RenderText* text = static_cast<RenderText*>(autoSizingNode->renderer());
if (!text)
continue;
// Reset the font size back to the original specified size
FontDescription fontDescription = text->style()->fontDescription();
float originalSize = fontDescription.specifiedSize();
if (fontDescription.computedSize() != originalSize) {
fontDescription.setComputedSize(originalSize);
RefPtr<RenderStyle> style = cloneRenderStyleWithState(text->style());
style->setFontDescription(fontDescription);
style->font().update(autoSizingNode->document()->styleSelector()->fontSelector());
text->setStyle(style.release());
}
// Reset the line height of the parent.
RenderObject* parentRenderer = text->parent();
if (!parentRenderer)
continue;
const RenderStyle* parentStyle = parentRenderer->style();
Length originalLineHeight = parentStyle->specifiedLineHeight();
if (originalLineHeight != parentStyle->lineHeight()) {
RefPtr<RenderStyle> newParentStyle = cloneRenderStyleWithState(parentStyle);
newParentStyle->setLineHeight(originalLineHeight);
newParentStyle->setFontDescription(fontDescription);
newParentStyle->font().update(autoSizingNode->document()->styleSelector()->fontSelector());
parentRenderer->setStyle(newParentStyle.release());
}
}
}
void Document::addAutoSizingNode(Node* node, float candidateSize)
{
TextAutoSizingKey key(node->renderer()->style(), document());
RefPtr<TextAutoSizingValue> value;
// Do we already have a collection of nodes associated with
// this style? If not create one.
if (m_textAutoSizedNodes.contains(key))
value = m_textAutoSizedNodes.get(key);
else {
value = TextAutoSizingValue::create();
m_textAutoSizedNodes.set(key, value);
}
// Add the node to the collection associated with this style.
value->addNode(node, candidateSize);
}
void Document::validateAutoSizingNodes ()
{
Vector<TextAutoSizingKey> nodesForRemoval;
TextAutoSizingMap::iterator end = m_textAutoSizedNodes.end();
for (TextAutoSizingMap::iterator i = m_textAutoSizedNodes.begin(); i != end; ++i) {
TextAutoSizingKey key = i->first;
RefPtr<TextAutoSizingValue> value = i->second;
// Update all the nodes in the collection to reflect the new
// candidate size.
if (!value)
continue;
value->adjustNodeSizes();
if (!value->numNodes())
nodesForRemoval.append(key);
}
unsigned count = nodesForRemoval.size();
for (unsigned i = 0; i < count; i++)
m_textAutoSizedNodes.remove(nodesForRemoval[i]);
}
void Document::resetAutoSizingNodes()
{
TextAutoSizingMap::iterator end = m_textAutoSizedNodes.end();
for (TextAutoSizingMap::iterator i = m_textAutoSizedNodes.begin(); i != end; ++i) {
RefPtr<TextAutoSizingValue> value = i->second;
if (value)
value->reset();
}
m_textAutoSizedNodes.clear();
}
//SAMSUNG CHANGE END webkit-text-size-adjust <<
#endif
void Document::initDNSPrefetch()
{
Settings* settings = this->settings();
m_haveExplicitlyDisabledDNSPrefetch = false;
m_isDNSPrefetchEnabled = settings && settings->dnsPrefetchingEnabled() && securityOrigin()->protocol() == "http";
// Inherit DNS prefetch opt-out from parent frame
if (Document* parent = parentDocument()) {
if (!parent->isDNSPrefetchEnabled())
m_isDNSPrefetchEnabled = false;
}
}
void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
{
if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) {
m_isDNSPrefetchEnabled = true;
return;
}
m_isDNSPrefetchEnabled = false;
m_haveExplicitlyDisabledDNSPrefetch = true;
}
void Document::addMessage(MessageSource source, MessageType type, MessageLevel level, const String& message, unsigned lineNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack)
{
if (DOMWindow* window = domWindow())
window->console()->addMessage(source, type, level, message, lineNumber, sourceURL, callStack);
}
struct PerformTaskContext {
WTF_MAKE_NONCOPYABLE(PerformTaskContext); WTF_MAKE_FAST_ALLOCATED;
public:
PerformTaskContext(PassRefPtr<DocumentWeakReference> documentReference, PassOwnPtr<ScriptExecutionContext::Task> task)
: documentReference(documentReference)
, task(task)
{
}
RefPtr<DocumentWeakReference> documentReference;
OwnPtr<ScriptExecutionContext::Task> task;
};
static void performTask(void* ctx)
{
ASSERT(isMainThread());
PerformTaskContext* context = reinterpret_cast<PerformTaskContext*>(ctx);
ASSERT(context);
if (Document* document = context->documentReference->document())
context->task->performTask(document);
delete context;
}
void Document::postTask(PassOwnPtr<Task> task)
{
callOnMainThread(performTask, new PerformTaskContext(m_weakReference, task));
}
void Document::suspendScriptedAnimationControllerCallbacks()
{
#if ENABLE(REQUEST_ANIMATION_FRAME)
if (m_scriptedAnimationController)
m_scriptedAnimationController->suspend();
#endif
}
void Document::resumeScriptedAnimationControllerCallbacks()
{
#if ENABLE(REQUEST_ANIMATION_FRAME)
if (m_scriptedAnimationController)
m_scriptedAnimationController->resume();
#endif
}
String Document::displayStringModifiedByEncoding(const String& str) const
{
if (m_decoder)
return m_decoder->encoding().displayString(str.impl());
return str;
}
PassRefPtr<StringImpl> Document::displayStringModifiedByEncoding(PassRefPtr<StringImpl> str) const
{
if (m_decoder)
return m_decoder->encoding().displayString(str);
return str;
}
void Document::displayBufferModifiedByEncoding(UChar* buffer, unsigned len) const
{
if (m_decoder)
m_decoder->encoding().displayBuffer(buffer, len);
}
void Document::enqueuePageshowEvent(PageshowEventPersistence persisted)
{
// FIXME: https://bugs.webkit.org/show_bug.cgi?id=36334 Pageshow event needs to fire asynchronously.
dispatchWindowEvent(PageTransitionEvent::create(eventNames().pageshowEvent, persisted), this);
}
void Document::enqueueHashchangeEvent(const String& oldURL, const String& newURL)
{
enqueueWindowEvent(HashChangeEvent::create(oldURL, newURL));
}
void Document::enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject)
{
// FIXME: https://bugs.webkit.org/show_bug.cgi?id=36202 Popstate event needs to fire asynchronously
dispatchWindowEvent(PopStateEvent::create(stateObject));
}
void Document::addMediaCanStartListener(MediaCanStartListener* listener)
{
ASSERT(!m_mediaCanStartListeners.contains(listener));
m_mediaCanStartListeners.add(listener);
}
void Document::removeMediaCanStartListener(MediaCanStartListener* listener)
{
ASSERT(m_mediaCanStartListeners.contains(listener));
m_mediaCanStartListeners.remove(listener);
}
MediaCanStartListener* Document::takeAnyMediaCanStartListener()
{
HashSet<MediaCanStartListener*>::iterator slot = m_mediaCanStartListeners.begin();
if (slot == m_mediaCanStartListeners.end())
return 0;
MediaCanStartListener* listener = *slot;
m_mediaCanStartListeners.remove(slot);
return listener;
}
#if ENABLE(XHTMLMP)
bool Document::isXHTMLMPDocument() const
{
if (!frame() || !frame()->loader())
return false;
// As per section 7.2 of OMA-WAP-XHTMLMP-V1_1-20061020-A.pdf, a conforming user agent
// MUST accept XHTMLMP document identified as "application/vnd.wap.xhtml+xml"
// and SHOULD accept it identified as "application/xhtml+xml" , "application/xhtml+xml" is a
// general MIME type for all XHTML documents, not only for XHTMLMP
return loader()->writer()->mimeType() == "application/vnd.wap.xhtml+xml";
}
#endif
#if ENABLE(FULLSCREEN_API)
bool Document::fullScreenIsAllowedForElement(Element* element) const
{
ASSERT(element);
while (HTMLFrameOwnerElement* ownerElement = element->document()->ownerElement()) {
if (!ownerElement->hasTagName(frameTag) && !ownerElement->hasTagName(iframeTag))
continue;
if (!static_cast<HTMLFrameElementBase*>(ownerElement)->allowFullScreen())
return false;
element = ownerElement;
}
return true;
}
void Document::webkitRequestFullScreenForElement(Element* element, unsigned short flags)
{
if (!page() || !page()->settings()->fullScreenEnabled())
return;
if (!element)
element = documentElement();
if (!fullScreenIsAllowedForElement(element))
return;
if (!ScriptController::processingUserGesture())
return;
if (!page()->chrome()->client()->supportsFullScreenForElement(element, flags & Element::ALLOW_KEYBOARD_INPUT))
return;
m_areKeysEnabledInFullScreen = flags & Element::ALLOW_KEYBOARD_INPUT;
page()->chrome()->client()->enterFullScreenForElement(element);
}
void Document::webkitCancelFullScreen()
{
if (!page() || !m_fullScreenElement)
return;
page()->chrome()->client()->exitFullScreenForElement(m_fullScreenElement.get());
#if PLATFORM(ANDROID)
// The next time we try to enter full screen, we need this change to know
// we are not in full screen any more.
m_fullScreenElement = 0;
#endif
}
void Document::webkitWillEnterFullScreenForElement(Element* element)
{
ASSERT(element);
ASSERT(page() && page()->settings()->fullScreenEnabled());
m_fullScreenElement = element;
#if PLATFORM(ANDROID)
// Our approach on Poster handling is android specific: we are passing the
// poster from java side to native and we can't keep the content if the
// video element is detached and its RenderLayer object is deleted.
if(!(m_fullScreenElement->hasTagName(HTMLNames::videoTag))) {
#endif
if (m_fullScreenElement != documentElement())
m_fullScreenElement->detach();
recalcStyle(Force);
#if PLATFORM(ANDROID)
}
#endif
if (m_fullScreenRenderer) {
m_fullScreenRenderer->setAnimating(true);
#if USE(ACCELERATED_COMPOSITING)
view()->updateCompositingLayers();
if (m_fullScreenRenderer->layer() && m_fullScreenRenderer->layer()->isComposited()) // SAMSUNG CHANGE - Added NULL check for layer as it is coming NULL
page()->chrome()->client()->setRootFullScreenLayer(m_fullScreenRenderer->layer()->backing()->graphicsLayer());
#endif
}
}
void Document::webkitDidEnterFullScreenForElement(Element*)
{
if (m_fullScreenRenderer) {
m_fullScreenRenderer->setAnimating(false);
#if USE(ACCELERATED_COMPOSITING)
view()->updateCompositingLayers();
page()->chrome()->client()->setRootFullScreenLayer(0);
#endif
}
m_fullScreenChangeDelayTimer.startOneShot(0);
}
void Document::webkitWillExitFullScreenForElement(Element*)
{
if (m_fullScreenRenderer) {
m_fullScreenRenderer->setAnimating(true);
#if USE(ACCELERATED_COMPOSITING)
view()->updateCompositingLayers();
if (m_fullScreenRenderer->layer()->isComposited())
page()->chrome()->client()->setRootFullScreenLayer(m_fullScreenRenderer->layer()->backing()->graphicsLayer());
#endif
}
}
void Document::webkitDidExitFullScreenForElement(Element*)
{
m_areKeysEnabledInFullScreen = false;
if (m_fullScreenRenderer)
m_fullScreenRenderer->remove();
if (m_fullScreenElement != documentElement())
m_fullScreenElement->detach();
m_fullScreenElement = 0;
setFullScreenRenderer(0);
#if USE(ACCELERATED_COMPOSITING)
page()->chrome()->client()->setRootFullScreenLayer(0);
#endif
recalcStyle(Force);
m_fullScreenChangeDelayTimer.startOneShot(0);
}
void Document::setFullScreenRenderer(RenderFullScreen* renderer)
{
if (renderer == m_fullScreenRenderer)
return;
if (m_fullScreenRenderer)
m_fullScreenRenderer->destroy();
m_fullScreenRenderer = renderer;
// This notification can come in after the page has been destroyed.
if (page())
page()->chrome()->client()->fullScreenRendererChanged(m_fullScreenRenderer);
}
void Document::setFullScreenRendererSize(const IntSize& size)
{
ASSERT(m_fullScreenRenderer);
if (!m_fullScreenRenderer)
return;
if (m_fullScreenRenderer) {
RefPtr<RenderStyle> newStyle = RenderStyle::clone(m_fullScreenRenderer->style());
newStyle->setWidth(Length(size.width(), WebCore::Fixed));
newStyle->setHeight(Length(size.height(), WebCore::Fixed));
newStyle->setTop(Length(0, WebCore::Fixed));
newStyle->setLeft(Length(0, WebCore::Fixed));
m_fullScreenRenderer->setStyle(newStyle);
updateLayout();
}
}
void Document::setFullScreenRendererBackgroundColor(Color backgroundColor)
{
if (!m_fullScreenRenderer)
return;
RefPtr<RenderStyle> newStyle = RenderStyle::clone(m_fullScreenRenderer->style());
newStyle->setBackgroundColor(backgroundColor);
m_fullScreenRenderer->setStyle(newStyle);
}
void Document::fullScreenChangeDelayTimerFired(Timer<Document>*)
{
Element* element = m_fullScreenElement.get();
if (!element)
element = documentElement();
element->dispatchEvent(Event::create(eventNames().webkitfullscreenchangeEvent, true, false));
}
#endif
void Document::decrementLoadEventDelayCount()
{
ASSERT(m_loadEventDelayCount);
--m_loadEventDelayCount;
if (frame() && !m_loadEventDelayCount && !m_loadEventDelayTimer.isActive())
m_loadEventDelayTimer.startOneShot(0);
}
void Document::loadEventDelayTimerFired(Timer<Document>*)
{
if (frame())
frame()->loader()->checkCompleted();
}
#if ENABLE(REQUEST_ANIMATION_FRAME)
int Document::webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback, Element* animationElement)
{
if (!m_scriptedAnimationController)
m_scriptedAnimationController = ScriptedAnimationController::create(this);
return m_scriptedAnimationController->registerCallback(callback, animationElement);
}
void Document::webkitCancelRequestAnimationFrame(int id)
{
if (!m_scriptedAnimationController)
return;
m_scriptedAnimationController->cancelCallback(id);
}
void Document::serviceScriptedAnimations(DOMTimeStamp time)
{
if (!m_scriptedAnimationController)
return;
m_scriptedAnimationController->serviceScriptedAnimations(time);
}
#endif
#if ENABLE(TOUCH_EVENTS)
PassRefPtr<Touch> Document::createTouch(DOMWindow* window, EventTarget* target, int identifier, int pageX, int pageY, int screenX, int screenY, ExceptionCode&) const
{
// FIXME: It's not clear from the documentation at
// http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html
// when this method should throw and nor is it by inspection of iOS behavior. It would be nice to verify any cases where it throws under iOS
// and implement them here. See https://bugs.webkit.org/show_bug.cgi?id=47819
// Ditto for the createTouchList method below.
Frame* frame = window ? window->frame() : this->frame();
return Touch::create(frame, target, identifier, screenX, screenY, pageX, pageY);
}
PassRefPtr<TouchList> Document::createTouchList(ExceptionCode&) const
{
return TouchList::create();
}
#endif
DocumentLoader* Document::loader() const
{
if (!m_frame)
return 0;
DocumentLoader* loader = m_frame->loader()->activeDocumentLoader();
if (!loader)
return 0;
#if PLATFORM(ANDROID)
// Temporary hack for http://b/5188895
bool isDocumentUpToDate = m_frame->isDocumentUpToDate();
#else
bool isDocumentUpToDate = true;
#endif
if (isDocumentUpToDate && m_frame->document() != this)
return 0;
return loader;
}
//SAMSUNG MICRODATA CHANGES <<
#if ENABLE(MICRODATA)
PassRefPtr<NodeList> Document::getItems()
{
// Since documet.getItem() is allowed for microdata, typeNames will be null string.
// In this case we need to create an unique string identifier to map such request in the cache.
String localTypeNames = String(" ");
return getItems(localTypeNames);
}
PassRefPtr<NodeList> Document::getItems(const String& typeNames)
{
NodeListsNodeData* nodeLists = ensureRareData()->ensureNodeLists(this);
// Since documet.getItem() is allowed for microdata, typeNames will be null string.
// In this case we need to create an unique string identifier to map such request in the cache.
String localTypeNames = typeNames.isNull() ? String("http://webkit.org/microdata/undefinedItemType") : typeNames;
pair<NodeListsNodeData::MicroDataItemListCache::iterator, bool> result = nodeLists->m_microDataItemListCache.add(localTypeNames, 0);
if (!result.second)
return PassRefPtr<NodeList>(result.first->second);
RefPtr<MicroDataItemList> list = MicroDataItemList::create(this, typeNames);
result.first->second = list.get();
return list.release();
}
void Document::removeCachedMicroDataItemList(MicroDataItemList* list, const String& typeNames)
{
ASSERT(rareData());
ASSERT(rareData()->nodeLists());
ASSERT_UNUSED(list, list->hasOwnCaches());
NodeListsNodeData* data = rareData()->nodeLists();
String localTypeNames = typeNames.isNull() ? String("http://webkit.org/microdata/undefinedItemType") : typeNames;
ASSERT_UNUSED(list, list == data->m_microDataItemListCache.get(localTypeNames));
data->m_microDataItemListCache.remove(localTypeNames);
}
#endif
///SAMSUNG MICRODATA CHANGES >>
} // namespace WebCore
| gpl-2.0 |
johynpapin/AfterBooks | server/main.js | 11755 | var opHelper = new apac.OperationHelper({
awsId: 'AKIAIUQM6GCZJIFGQXFA',
awsSecret: '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',
assocId: 'after01d-21',
// xml2jsOptions: an extra, optional, parameter for if you want to pass additional options for the xml2js module. (see https://github.com/Leonidas-from-XIV/node-xml2js#options)
version: '2013-08-01'
// your version of using product advertising api, default: 2013-08-01
});
Meteor.startup(function () {
smtp = {
username: 'contact@kiwiasso.org',
password: 'SErpentin22',
server: 'mail.gandi.net',
port: 25
};
process.env.MAIL_URL = 'smtp://' + encodeURIComponent(smtp.username) + ':' + encodeURIComponent(smtp.password) + '@' + encodeURIComponent(smtp.server) + ':' + smtp.port;
Accounts.emailTemplates.from = 'AfterBooks <no-reply@afterbooks.com>';
Accounts.emailTemplates.siteName = 'AfterBooks';
PrettyEmail.options = {
from: 'AfterBooks <no-reply@afterbooks.com>',
logoUrl: 'http://localhost:3000/afterbooks.png',
companyName: 'AfterBooks',
companyUrl: 'http://localhost:3000/',
companyAddress: '21 Rue Marcel Sanguy, 22110 Rostrenen, France',
companyTelephone: '+33296245509',
companyEmail: 'contact@afterbooks.com',
siteName: 'AfterBooks',
facebook: 'https://facebook.com/pages/afterbooks/',
twitter: 'https://twitter.com/afterbooks/'
};
}
);
Meteor.methods({
'sendEmail': function (to, from, subject, text) {
check([to, from, subject, text], [String]);
// Let other method calls from the same client start running,
// without waiting for the email sending to complete.
this.unblock();
Email.send({
to: to,
from: from,
subject: subject,
text: text
});
},
'insertBook': function(params){
this.unblock();
if(Meteor.user()) {
var to_return = Books.insert(params.doc, {validationContext: "googleinsert"});
return to_return;
} else {
throw new Meteor.Error(401, {message: "You must be connected to do that !"});
}
},
'updateBook': function(params){
this.unblock();
if(Meteor.user()) {
Books.update(params.book_id, {$set: {title: params.title, summary: params.summary}});
} else {
throw new Meteor.Error(401, {message: "You must be connected to do that !"});
}
},
'insertBtra': function(params){
if(Meteor.user()) {
Books.update({
_id:params.book_id
}, {
$push: {
btra: {
_id: params.btra_id,
rates: 0,
initiator: Meteor.userId()
}
},
$addToSet: {
btraRaters: Meteor.userId()
}
},function(error, result) {
if(error) {
throw new Meteor.Error(500, error.invalidKeys);
}
}
);
Books.update({
_id:params.book_id,
}, {
$push: {
btra: {
$each: [],
$slice: -50,
$sort: { rates: -1 }
}
}
},function(error, result) {
if(error) {
throw new Meteor.Error(500, error.invalidKeys);
}
}
);
} else {
throw new Meteor.Error(401, {message: "You must be connected to do that !"});
}
},
'rateBook': function(params) {
this.unblock();
if(Meteor.user()) {
var book = Books.findOne(params.book_id);
if (book.bookInitiator == Meteor.userId()) {
throw new Meteor.Error(401, {message: "You are not authorized to do that !"});
} else {
if (params.vote_type == 'up') {
Books.update({
_id: params.book_id
}, {
$inc: {
'bookRates': 1
},
$addToSet: {
bookRaters: Meteor.userId()
}
}, function (error, result) {
if (error) {
throw new Meteor.Error(500, error.invalidKeys);
}
}
);
} else {
Books.update({
'_id': params.book_id
}, {
$inc: {
'bookRates': -1
},
$pullAll: {
'bookRaters': [Meteor.userId()]
}
}, function (error, result) {
if (error) {
throw new Meteor.Error(500, error.invalidKeys);
}
}
);
}
Books.update({
_id: params.book_id
}, {
$push: {
btra: {
$each: [],
$slice: -50,
$sort: {rates: -1}
}
}
}, function (error, result) {
if (error) {
throw new Meteor.Error(500, error.invalidKeys);
}
}
);
}
} else {
throw new Meteor.Error(401, {message: "You must be connected to do that !"});
}
},
'rateBtra': function(params) {
this.unblock();
if(Meteor.user()) {
var book = Books.findOne(params.book_id);
_.each(book.btra, function(btra) {
if(btra._id == params.btra_id) {
if(btra.initiator == Meteor.userId()) {
throw new Meteor.Error(401, {message: "You are not authorized to do that !"});
} else {
if(params.vote_type == 'up') {
Books.update({
_id:params.book_id,
'btra._id': params.btra_id
}, {
$inc:{
'btra.$.rates': 1
},
$addToSet: {
btraRaters: Meteor.userId()
}
},function(error, result) {
if(error) {
throw new Meteor.Error(500, error.invalidKeys);
}
}
);
} else {
Books.update({
'_id':params.book_id,
'btra._id': params.btra_id
}, {
$inc:{
'btra.$.rates': -1
},
$pullAll: {
'btraRaters': [Meteor.userId()]
}
},function(error, result) {
if(error) {
throw new Meteor.Error(500, error.invalidKeys);
}
}
);
}
Books.update({
_id:params.book_id
}, {
$push: {
btra: {
$each: [],
$slice: -50,
$sort: { rates: -1 }
}
}
},function(error, result) {
if(error) {
throw new Meteor.Error(500, error.invalidKeys);
}
}
);
}
}
});
} else {
throw new Meteor.Error(401, {message: "You must be connected to do that !"});
}
},
'console': function(param) {
console.log(param);
},
'googlebooks': function(params) {
this.unblock();
var response = HTTP.get('https://www.googleapis.com/books/v1/volumes', {
params: {
q: params.query,
startIndex: params.page * 10 - 10,
maxResults: 10,
langRestrict: ServerSession.get('language'),
key: 'AIzaSyAgvdPtmmldszDUk1Tcm7sNH9YmnMpnNd4'
}
});
return response;
},
'amazon': function(params) {
this.unblock();
Future = Npm.require('fibers/future');
var future = new Future();
opHelper.execute('ItemSearch', {
'SearchIndex': 'Books',
'ItemPage': params.page,
'Keywords': params.keywords,
'ResponseGroup': 'ItemAttributes,EditorialReview,Images'
}, function(err, results) {
if(err) {
console.log(err);
future.throw(err);
} else {
future.return(results);
}
}
);
return future.wait();
},
'serversession': function(params) {
ServerSession.set(params.key, params.value);
}
}
);
Books.allow({
'insert': function (userId, doc) {
return true;
}
}
); | gpl-2.0 |
Ch0wW/odamex | libraries/discord-rpc/src/discord_register_win.cpp | 6160 | #include "discord_rpc.h"
#include "discord_register.h"
#define WIN32_LEAN_AND_MEAN
#define NOMCX
#define NOSERVICE
#define NOIME
#include <windows.h>
#include <psapi.h>
#include <cstdio>
/**
* Updated fixes for MinGW and WinXP
* This block is written the way it does not involve changing the rest of the code
* Checked to be compiling
* 1) strsafe.h belongs to Windows SDK and cannot be added to MinGW
* #include guarded, functions redirected to <string.h> substitutes
* 2) RegSetKeyValueW and LSTATUS are not declared in <winreg.h>
* The entire function is rewritten
*/
#ifdef __MINGW32__
#include <wchar.h>
/// strsafe.h fixes
static HRESULT StringCbPrintfW(LPWSTR pszDest, size_t cbDest, LPCWSTR pszFormat, ...)
{
HRESULT ret;
va_list va;
va_start(va, pszFormat);
cbDest /= 2; // Size is divided by 2 to convert from bytes to wide characters - causes segfault
// othervise
ret = vsnwprintf(pszDest, cbDest, pszFormat, va);
pszDest[cbDest - 1] = 0; // Terminate the string in case a buffer overflow; -1 will be returned
va_end(va);
return ret;
}
#else
#include <cwchar>
#include <strsafe.h>
#endif // __MINGW32__
/// winreg.h fixes
#ifndef LSTATUS
#define LSTATUS LONG
#endif
#ifdef RegSetKeyValueW
#undefine RegSetKeyValueW
#endif
#define RegSetKeyValueW regset
static LSTATUS regset(HKEY hkey,
LPCWSTR subkey,
LPCWSTR name,
DWORD type,
const void* data,
DWORD len)
{
HKEY htkey = hkey, hsubkey = nullptr;
LSTATUS ret;
if (subkey && subkey[0]) {
if ((ret = RegCreateKeyExW(hkey, subkey, 0, 0, 0, KEY_ALL_ACCESS, 0, &hsubkey, 0)) !=
ERROR_SUCCESS)
return ret;
htkey = hsubkey;
}
ret = RegSetValueExW(htkey, name, 0, type, (const BYTE*)data, len);
if (hsubkey && hsubkey != hkey)
RegCloseKey(hsubkey);
return ret;
}
static void Discord_RegisterW(const wchar_t* applicationId, const wchar_t* command)
{
// https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx
// we want to register games so we can run them as discord-<appid>://
// Update the HKEY_CURRENT_USER, because it doesn't seem to require special permissions.
wchar_t exeFilePath[MAX_PATH];
DWORD exeLen = GetModuleFileNameW(nullptr, exeFilePath, MAX_PATH);
wchar_t openCommand[1024];
if (command && command[0]) {
StringCbPrintfW(openCommand, sizeof(openCommand), L"%s", command);
}
else {
// StringCbCopyW(openCommand, sizeof(openCommand), exeFilePath);
StringCbPrintfW(openCommand, sizeof(openCommand), L"%s", exeFilePath);
}
wchar_t protocolName[64];
StringCbPrintfW(protocolName, sizeof(protocolName), L"discord-%s", applicationId);
wchar_t protocolDescription[128];
StringCbPrintfW(
protocolDescription, sizeof(protocolDescription), L"URL:Run game %s protocol", applicationId);
wchar_t urlProtocol = 0;
wchar_t keyName[256];
StringCbPrintfW(keyName, sizeof(keyName), L"Software\\Classes\\%s", protocolName);
HKEY key;
auto status =
RegCreateKeyExW(HKEY_CURRENT_USER, keyName, 0, nullptr, 0, KEY_WRITE, nullptr, &key, nullptr);
if (status != ERROR_SUCCESS) {
fprintf(stderr, "Error creating key\n");
return;
}
DWORD len;
LSTATUS result;
len = (DWORD)lstrlenW(protocolDescription) + 1;
result =
RegSetKeyValueW(key, nullptr, nullptr, REG_SZ, protocolDescription, len * sizeof(wchar_t));
if (FAILED(result)) {
fprintf(stderr, "Error writing description\n");
}
len = (DWORD)lstrlenW(protocolDescription) + 1;
result = RegSetKeyValueW(key, nullptr, L"URL Protocol", REG_SZ, &urlProtocol, sizeof(wchar_t));
if (FAILED(result)) {
fprintf(stderr, "Error writing description\n");
}
result = RegSetKeyValueW(
key, L"DefaultIcon", nullptr, REG_SZ, exeFilePath, (exeLen + 1) * sizeof(wchar_t));
if (FAILED(result)) {
fprintf(stderr, "Error writing icon\n");
}
len = (DWORD)lstrlenW(openCommand) + 1;
result = RegSetKeyValueW(
key, L"shell\\open\\command", nullptr, REG_SZ, openCommand, len * sizeof(wchar_t));
if (FAILED(result)) {
fprintf(stderr, "Error writing command\n");
}
RegCloseKey(key);
}
extern "C" DISCORD_EXPORT void Discord_Register(const char* applicationId, const char* command)
{
wchar_t appId[32];
MultiByteToWideChar(CP_UTF8, 0, applicationId, -1, appId, 32);
wchar_t openCommand[1024];
const wchar_t* wcommand = nullptr;
if (command && command[0]) {
const auto commandBufferLen = sizeof(openCommand) / sizeof(*openCommand);
MultiByteToWideChar(CP_UTF8, 0, command, -1, openCommand, commandBufferLen);
wcommand = openCommand;
}
Discord_RegisterW(appId, wcommand);
}
extern "C" DISCORD_EXPORT void Discord_RegisterSteamGame(const char* applicationId,
const char* steamId)
{
wchar_t appId[32];
MultiByteToWideChar(CP_UTF8, 0, applicationId, -1, appId, 32);
wchar_t wSteamId[32];
MultiByteToWideChar(CP_UTF8, 0, steamId, -1, wSteamId, 32);
HKEY key;
auto status = RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Valve\\Steam", 0, KEY_READ, &key);
if (status != ERROR_SUCCESS) {
fprintf(stderr, "Error opening Steam key\n");
return;
}
wchar_t steamPath[MAX_PATH];
DWORD pathBytes = sizeof(steamPath);
status = RegQueryValueExW(key, L"SteamExe", nullptr, nullptr, (BYTE*)steamPath, &pathBytes);
RegCloseKey(key);
if (status != ERROR_SUCCESS || pathBytes < 1) {
fprintf(stderr, "Error reading SteamExe key\n");
return;
}
DWORD pathChars = pathBytes / sizeof(wchar_t);
for (DWORD i = 0; i < pathChars; ++i) {
if (steamPath[i] == L'/') {
steamPath[i] = L'\\';
}
}
wchar_t command[1024];
StringCbPrintfW(command, sizeof(command), L"\"%s\" steam://rungameid/%s", steamPath, wSteamId);
Discord_RegisterW(appId, command);
}
| gpl-2.0 |
andrewsmm/SimpleShopApiBundle | app/AppKernel.php | 1757 | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new SimpleShopApiBundle\SimpleShopApiBundle(),
new FOS\RestBundle\FOSRestBundle(),
new JMS\SerializerBundle\JMSSerializerBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'), true)) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function getRootDir()
{
return __DIR__;
}
public function getCacheDir()
{
return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
}
public function getLogDir()
{
return dirname(__DIR__).'/var/logs';
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
| gpl-2.0 |
swapnilaptara/tao-aptara-assess | generis/core/kernel/users/interface.RolesManagement.php | 3697 | <?php
/*
* 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; under version 2
* of the License (non-upgradable).
*
* 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 (c) 2002-2008 (original work) Public Research Centre Henri Tudor & University of Luxembourg (under the project TAO & TAO2);
* 2008-2010 (update and modification) Deutsche Institut für Internationale Pädagogische Forschung (under the project TAO-TRANSFER);
* 2009-2012 (update and modification) Public Research Centre Henri Tudor (under the project TAO-SUSTAIN & TAO-DEV);
*
*/
/**
* Short description of class core_kernel_users_RolesManagement
*
* @access public
* @author Jerome Bogaerts, <jerome@taotesting.com>
* @package generis
*/
interface core_kernel_users_RolesManagement
{
/**
* Add a role in Generis.
*
* @access public
* @author Jerome Bogaerts, <jerome@taotesting.com>
* @param string label The label to apply to the newly created Generis Role.
* @param includedRoles The Role(s) to be included in the newly created Generis Role. Can be either a Resource or an array of Resources.
* @return core_kernel_classes_Resource
*/
public function addRole($label, $includedRoles = null, core_kernel_classes_Class $class = null);
/**
* Remove a Generis role from the persistent memory. User References to this
* will be removed.
*
* @access public
* @author Jerome Bogaerts, <jerome@taotesting.com>
* @param Resource role The Role to remove.
* @return boolean
*/
public function removeRole(core_kernel_classes_Resource $role);
/**
* Get an array of the Roles included by a Generis Role.
*
* @access public
* @author Jerome Bogaerts, <jerome@taotesting.com>
* @param Resource role A Generis Role.
* @return array
*/
public function getIncludedRoles(core_kernel_classes_Resource $role);
/**
* Make a Role include another Role.
*
* @access public
* @author Jerome Bogaerts, <jerome@taotesting.com>
* @param core_kernel_classes_Resource role The role that needs to include another role.
* @param core_kernel_classes_Resource roleToInclude The role to be included.
*/
public function includeRole(core_kernel_classes_Resource $role, core_kernel_classes_Resource $roleToInclude);
/**
* Uninclude a Role from another Role.
*
* @author Jerome Bogaerts <jerome.taotesting.com>
* @param core_kernel_classes_Resource role The role from which you want to uninclude a Role.
* @param core_kernel_classes_Resource roleToUninclude The Role to uninclude.
*/
public function unincludeRole(core_kernel_classes_Resource $role, core_kernel_classes_Resource $roleToUninclude);
/**
* Return all instances of Roles from the persistent memory of Generis.
*
* @access public
* @author Jerome Bogaerts
* @return array An associative array where keys are Role URIs and values are instances of the core_kernel_classes_Resource class.
*/
public function getAllRoles();
}
?> | gpl-2.0 |
CharlieKuharski/hg4j | src/org/tmatesoft/hg/internal/FileContentSupplier.java | 2283 | /*
* Copyright (c) 2013 TMate Software Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* For information on how to redistribute this software under
* the terms of a license other than GNU General Public License
* contact TMate Software at support@hg4j.com
*/
package org.tmatesoft.hg.internal;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import org.tmatesoft.hg.core.HgIOException;
import org.tmatesoft.hg.core.SessionContext;
import org.tmatesoft.hg.internal.DataSerializer.DataSource;
import org.tmatesoft.hg.repo.HgRepository;
import org.tmatesoft.hg.util.Path;
/**
* {@link DataSource} that reads from regular files
*
* @author Artem Tikhomirov
* @author TMate Software Ltd.
*/
public class FileContentSupplier implements DataSource {
private final File file;
private final SessionContext ctx;
public FileContentSupplier(HgRepository repo, Path file) {
this(repo, new File(repo.getWorkingDir(), file.toString()));
}
public FileContentSupplier(SessionContext.Source ctxSource, File f) {
ctx = ctxSource.getSessionContext();
file = f;
}
public void serialize(DataSerializer out) throws HgIOException {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
ByteBuffer buffer = ByteBuffer.allocate((int) Math.min(100*1024, fc.size()));
while (fc.read(buffer) != -1) {
buffer.flip();
// #allocate() above ensures backing array
out.write(buffer.array(), 0, buffer.limit());
buffer.clear();
}
} catch (IOException ex) {
throw new HgIOException("Failed to get content of the file", ex, file);
} finally {
new FileUtils(ctx.getLog(), this).closeQuietly(fis);
}
}
public int serializeLength() {
return Internals.ltoi(file.length());
}
} | gpl-2.0 |
tiian/lixa | ext/php/tests/lixa_021.phpt | 1310 | --TEST--
LIXA PostgreSQL availability - basic test: PostgreSQL is reachable
--SKIPIF--
<?php
if (!stristr(PHP_OS, "Linux")) die("skip this test is Linux platforms only");
if (!lixa_config_have_postgresql()) die("skip this test requires LIXA configured for PostgreSQL");
?>
--FILE--
<?php
/* Connecting to "testdb" local PostgreSQL database */
$dbconn = pg_connect("dbname=testdb")
or die('Could not connect: ' . pg_last_error());
echo "CONNECT OK\n";
/* Clean "authors" table from any rows */
$query = 'DELETE FROM authors';
$result = pg_query($query) or die('Query failed: ' . pg_last_error() . '\n');
echo "DELETE OK\n";
/* Insert a test row */
$query = "INSERT INTO authors VALUES(999, 'Ferrari', 'Christian')";
$result = pg_query($query) or die('Query failed: ' . pg_last_error() . '\n');
echo "INSERT OK\n";
/* Retrieving table content */
$query = 'SELECT * FROM authors';
$result = pg_query($query) or die('Query failed: ' . pg_last_error(). '\n');
/* Print table content */
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
foreach ($line as $col_value) {
echo " $col_value";
}
echo "\n";
}
/* Free result set */
pg_free_result($result);
/* Close database connection */
pg_close($dbconn);
?>
--EXPECT--
CONNECT OK
DELETE OK
INSERT OK
999 Ferrari Christian
| gpl-2.0 |
pablanco/taskManager | Android/UserControlLibraries/BaiduMaps/src/com/artech/controls/maps/baidu/MapLocationBounds.java | 1307 | package com.artech.controls.maps.baidu;
import com.artech.controls.maps.common.IMapLocationBounds;
import com.baidu.platform.comapi.basestruct.GeoPoint;
public class MapLocationBounds implements IMapLocationBounds<MapLocation>
{
private int mMinimumLatitude;
private int mMaximumLatitude;
private int mMinimumLongitude;
private int mMaximumLongitude;
public MapLocationBounds(MapLocation southwest, MapLocation northeast)
{
mMinimumLatitude = southwest.getGeoPoint().getLatitudeE6();
mMinimumLongitude = southwest.getGeoPoint().getLongitudeE6();
mMaximumLatitude = northeast.getGeoPoint().getLatitudeE6();
mMaximumLongitude = northeast.getGeoPoint().getLongitudeE6();
}
@Override
public MapLocation southwest()
{
return new MapLocation(new GeoPoint(mMinimumLatitude, mMinimumLongitude));
}
@Override
public MapLocation northeast()
{
return new MapLocation(new GeoPoint(mMaximumLatitude, mMaximumLongitude));
}
public int getLatitudeSpan()
{
return mMaximumLatitude - mMinimumLatitude;
}
public int getLongitudeSpan()
{
return mMaximumLongitude - mMinimumLongitude;
}
public GeoPoint getCenter()
{
return new GeoPoint((mMinimumLatitude + mMaximumLatitude) / 2, (mMinimumLongitude + mMaximumLongitude) / 2);
}
}
| gpl-2.0 |
KylePreston/Soft-Hills-Website | wp-content/themes/inthedistance/functions/options-functions.php | 2709 | <?php
/**
* @package IntheDistance
*/
/**
* Theme options require the "Options Framework" plugin to be installed in order to display.
* If it's not installed, default settings will be used.
*/
if ( !function_exists( 'of_get_option' ) ) {
function of_get_option($name, $default = false) {
$optionsframework_settings = get_option('optionsframework');
// Gets the unique option id
$option_name = $optionsframework_settings['id'];
if ( get_option($option_name) ) {
$options = get_option($option_name);
}
if ( isset($options[$name]) ) {
return $options[$name];
} else {
return $default;
}
}
}
if ( !function_exists( 'optionsframework_init' ) && current_user_can('edit_theme_options') ) {
function portfolio_options_default() {
add_theme_page(__('Theme Options','inthedistance'), __('Theme Options','inthedistance'), 'edit_theme_options', 'options-framework','optionsframework_page_notice');
}
add_action('admin_menu', 'inthedisatance_options_default');
}
/**
* Displays a notice on the theme options page if the Options Framework plugin is not installed
*/
if ( !function_exists( 'optionsframework_page_notice' ) ) {
function optionsframework_page_notice() { ?>
<div class="wrap">
<?php screen_icon( 'themes' ); ?>
<h2><?php _e('Theme Options','inthedistance'); ?></h2>
<p><b><?php printf( __( 'If you would like to use the IntheDistance theme options, please install the %s plugin.', 'inthedistance' ), '<a href="http://wptheming.com/">Options Framework</a>' ); ?></b></p>
<p><?php _e('Once the plugin is activated you will have option to:','inthedistance'); ?></p>
<ul class="ul-disc">
<li><?php _e('Upload a logo image','inthedistance'); ?></li>
<li><?php _e('Upload a custom favicon','inthedistance'); ?></li>
<li><?php _e('Upload a apple touch icon','inthedistance'); ?></li>
<li><?php _e('Update the footer text','inthedistance'); ?></li>
<li><?php _e('Update the github url','inthedistance'); ?></li>
<li><?php _e('Update the twitter url','inthedistance'); ?></li>
<li><?php _e('Update the facebook url','inthedistance'); ?></li>
</ul>
<p><?php _e('If you don\'t need these options, the plugin is not required and default settings will be used.','inthedistance'); ?></p>
</div>
<?php
}
}
/**
* Additional content to display after the options panel
* if it is installed
*/
function inthedistance_panel_info() { ?>
<p>In the Distance. Simple and Beautiful Theme. Created by <a href="http://www.uetamasamichi.com">Masamichi Ueta</a>.</p>
<?php }
add_action('optionsframework_after','inthedistance_panel_info', 100);
?> | gpl-2.0 |
papillon-cendre/d8 | core/modules/search/src/SearchPluginManager.php | 1218 | <?php
/**
* @file
* Contains \Drupal\search\SearchPluginManager.
*/
namespace Drupal\search;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
/**
* SearchExecute plugin manager.
*/
class SearchPluginManager extends DefaultPluginManager {
/**
* Constructs SearchPluginManager
*
* @param \Traversable $namespaces
* An object that implements \Traversable which contains the root paths
* keyed by the corresponding namespace to look for plugin implementations.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* Cache backend instance to use.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler to invoke the alter hook with.
*/
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
parent::__construct('Plugin/Search', $namespaces, $module_handler, 'Drupal\search\Plugin\SearchInterface', 'Drupal\search\Annotation\SearchPlugin');
$this->setCacheBackend($cache_backend, 'search_plugins');
$this->alterInfo('search_plugin');
}
}
| gpl-2.0 |
Jeepal/iLogin | API/taobao/top/request/WidgetItempanelGetRequest.php | 1908 | <?php
/**
* TOP API: taobao.widget.itempanel.get request
*
* @author auto create
* @since 1.0, 2012-11-01 12:40:06
*/
class WidgetItempanelGetRequest
{
/**
* 参数fields为选填参数,表示需要返回哪些字段,默认为空:表示所有字段都返回。指定item_id返回item_id; 指定title返回title; 指定click_url返回click_url(如果此商品有淘宝客会默认返回转换过的淘宝客连接,绑定用户为appkey对应的用户); 指定price返回price(商品价格,如果有多个sku返回的是sku的价格区间); 指定quantify返回quantity(商品总数); 指定pic_url返回pic_url(商品主图地址); 指定item_pics返回item_pics(商品图片列表); 指定skus返回skus和sku_props组合; 指定shop_promotion_data返回shop_promotion_data(商品所属的店铺优惠信息); 指定item_promotion_data返回item_promotion_data(商品的优惠信息); 指定seller_nick返回seller_nick(卖家昵称); 指定is_mall返回is_mall(是否商城商品,true表示是商城商品);add_url不可选一定会返回
**/
private $fields;
/**
* 要查询的商品的数字id,等同于Item的num_iid
**/
private $itemId;
private $apiParas = array();
public function setFields($fields)
{
$this->fields = $fields;
$this->apiParas["fields"] = $fields;
}
public function getFields()
{
return $this->fields;
}
public function setItemId($itemId)
{
$this->itemId = $itemId;
$this->apiParas["item_id"] = $itemId;
}
public function getItemId()
{
return $this->itemId;
}
public function getApiMethodName()
{
return "taobao.widget.itempanel.get";
}
public function getApiParas()
{
return $this->apiParas;
}
public function check()
{
RequestCheckUtil::checkNotNull($this->itemId,"itemId");
}
public function putOtherTextParam($key, $value) {
$this->apiParas[$key] = $value;
$this->$key = $value;
}
}
| gpl-2.0 |
zjohn4/PD2-lua-src | core/lib/managers/coreworldcameramanager.lua | 61762 | core:import( "CoreManagerBase" )
CoreWorldCameraManager = CoreWorldCameraManager or class()
function CoreWorldCameraManager:init()
self._camera = World:create_camera()
self:set_default_fov( 75 )
self:set_fov( self._default_fov )
self:set_default_dof( 150, 10000 )
self._current_near_dof = self._default_near_dof
self._current_far_dof = self._default_far_dof
self._default_dof_padding = 100
self._current_dof_padding = self._default_dof_padding
self._default_dof_clamp = 1
self._current_dof_clamp = self._default_dof_clamp
self:set_dof( self._default_near_dof, self._default_far_dof )
self._camera:set_near_range( 7.5 )
self._camera:set_far_range( 200000 )
self._viewport = managers.viewport:new_vp( 0, 0, 1, 1, 'worldcamera', CoreManagerBase.PRIO_WORLDCAMERA )
self._director = self._viewport:director()
self._shaker = self._director:shaker()
self._camera_controller = self._director:make_camera( self._camera, Idstring("world_camera") )
self._viewport:set_camera( self._camera )
self._director:set_camera( self._camera_controller )
self._director:position_as( self._camera )
self:_create_listener()
self._use_gui = false
self._workspace = Overlay:newgui():create_screen_workspace( 0, 0, 1, 1 )
self._gui = self._workspace:panel():gui( Idstring("core/guis/core_world_camera") )
self._gui_visible = nil
self:_set_gui_visible( false )
self:_clear_callback_lists()
self:_set_dof_effect()
self:clear()
end
function CoreWorldCameraManager:use_gui()
return self._use_gui
end
-- Creates the core default listener. Override if necessery
function CoreWorldCameraManager:_create_listener()
self._listener_id = managers.listener:add_listener( "world_camera", self._camera )
self._listener_activation_id = nil
managers.listener:add_set( "world_camera", { "world_camera" } )
end
-- Sets game default fov
function CoreWorldCameraManager:set_default_fov( default_fov )
self._default_fov = default_fov
end
-- Returns game default fov
function CoreWorldCameraManager:default_fov()
return self._default_fov
end
-- Sets the fov of the camera
function CoreWorldCameraManager:set_fov( fov )
self._camera:set_fov( fov )
end
-- Sets game default dof
function CoreWorldCameraManager:set_default_dof( near_dof, far_dof )
self._default_near_dof = near_dof
self._default_far_dof = far_dof
end
-- Returns game default near dof
function CoreWorldCameraManager:default_near_dof()
return self._default_near_dof
end
-- Returns game default far dof
function CoreWorldCameraManager:default_far_dof()
return self._default_far_dof
end
-- Sets the dof of the camera
function CoreWorldCameraManager:set_dof( dof )
-- self._camera:set_dof( dof )
end
-- Returns the default dof padding value
function CoreWorldCameraManager:default_dof_padding()
return self._default_dof_padding
end
-- Returns the default dof clamp value
function CoreWorldCameraManager:default_dof_clamp()
return self._default_dof_clamp
end
-- Sets the dof effect presets
function CoreWorldCameraManager:_set_dof_effect()
self._dof = {}
self._dof.update_callback = "update_world_camera"
self._dof.near_min = self:default_near_dof()
self._dof.near_max = self:default_near_dof()
self._dof.far_min = self:default_far_dof()
self._dof.far_max = self:default_far_dof()
self._dof.clamp = 1
self._dof.prio = 1
self._dof.name = "world_camera"
self._dof.fade_in = 0
-- self._dof.sustain = 0.1
self._dof.fade_out = 0
end
function CoreWorldCameraManager:destroy()
self:_destroy_listener()
if self._viewport then
self._viewport:destroy()
self._viewport = nil
end
if alive( self._workspace ) then
Overlay:newgui():destroy_workspace( self._workspace )
self._workspace = nil
end
if alive(self._camera) then
World:delete_camera(self._camera)
self._camera = nil
end
end
function CoreWorldCameraManager:_destroy_listener()
if self._listener_id then
managers.listener:remove_listener( self._listener_id )
managers.listener:remove_set( "world_camera" )
self._listener_id = nil
end
end
-- Called after simulation in editor. Want to clear callbacks.
function CoreWorldCameraManager:stop_simulation()
self:_clear_callback_lists()
self:stop_world_camera()
end
function CoreWorldCameraManager:_clear_callback_lists()
self._last_world_camera_done_callback_id = {}
self._world_camera_done_callback_list = {}
self._last_sequence_done_callback_id = {}
self._sequence_done_callback_list = {}
self._last_sequence_camera_clip_callback_id = {}
self._sequence_camera_clip_callback_list = {}
end
function CoreWorldCameraManager:clear()
self._world_cameras = {}
self._world_camera_sequences = {}
self._current_world_camera = nil
end
function CoreWorldCameraManager:current_world_camera()
return self._current_world_camera
end
function CoreWorldCameraManager:save( file )
local worldcameras = {}
for name,world_camera in pairs( self._world_cameras ) do
worldcameras[ name ] = world_camera:save_data_table()
end
local camera_data = {
worldcameras = worldcameras,
sequences = self._world_camera_sequences
}
file:puts( ScriptSerializer:to_generic_xml( camera_data ) )
end
function CoreWorldCameraManager:load( param )
if not self:_old_load( param ) then
if not param.worldcameras then
Application:error( "Can't load world cameras, it is in new format but probably loaded from old level" )
return
end
for name,camera_data in pairs( param.worldcameras ) do
self._world_cameras[ name ] = ( rawget( _G, "WorldCamera" ) or rawget( _G, "CoreWorldCamera" ) ):new( name )
self._world_cameras[ name ]:load( camera_data )
end
self._world_camera_sequences = param.sequences
end
end
-- Old load, this is before usage of ScriptSerializer
function CoreWorldCameraManager:_old_load( path )
if type_name( path ) ~= "string" then -- Only old load uses string as path
return false
end
local path = managers.database:entry_expanded_path( "world_cameras", path )
local node = SystemFS:parse_xml( path )
--local node = DB:load_node( "world_cameras", path )
if node:name() ~= "world_cameras" then -- Loaded by level but is in new save format
return false
end
for child in node:children() do
if child:name() == "world_camera" then
local world_camera_name = child:parameter( "name" )
self._world_cameras[ world_camera_name ] = ( rawget( _G, "WorldCamera" ) or rawget( _G, "CoreWorldCamera" ) ):new( world_camera_name )
self._world_cameras[ world_camera_name ]:old_load( child )
else
local name, value = parse_value_node( child )
self[ name ] = value
end
end
return true
end
function CoreWorldCameraManager:update( t, dt )
if self._current_world_camera then
self._current_world_camera:update( t, dt )
end
end
function CoreWorldCameraManager:_set_gui_visible( visible )
if( self._gui_visible ~= visible ) then
if( visible and self._use_gui ) then
self._workspace:show()
else
self._workspace:hide()
end
self._gui_visible = visible
end
end
function CoreWorldCameraManager:add_world_camera_done_callback( world_camera_name, func )
self._last_world_camera_done_callback_id[ world_camera_name ] = self._last_world_camera_done_callback_id[ world_camera_name ] or 0
self._last_world_camera_done_callback_id[ world_camera_name ] = self._last_world_camera_done_callback_id[ world_camera_name ] + 1
self._world_camera_done_callback_list[ world_camera_name ] = self._world_camera_done_callback_list[ world_camera_name ] or {}
self._world_camera_done_callback_list[ world_camera_name ][ self._last_world_camera_done_callback_id[ world_camera_name ] ] = func
return self._last_world_camera_done_callback_id[ world_camera_name ] -- Returns the id.
end
function CoreWorldCameraManager:remove_world_camera_done_callback( world_camera_name, id )
self._world_camera_done_callback_list[ world_camera_name ][ id ] = nil
end
function CoreWorldCameraManager:add_sequence_done_callback( sequence_name, func )
self._last_sequence_done_callback_id[ sequence_name ] = self._last_sequence_done_callback_id[ sequence_name ] or 0
self._last_sequence_done_callback_id[ sequence_name ] = self._last_sequence_done_callback_id[ sequence_name ] + 1
self._sequence_done_callback_list[ sequence_name ] = self._sequence_done_callback_list[ sequence_name ] or {}
self._sequence_done_callback_list[ sequence_name ][ self._last_sequence_done_callback_id[ sequence_name ] ] = func
return self._last_sequence_done_callback_id[ sequence_name ] -- Returns the id.
end
function CoreWorldCameraManager:remove_sequence_done_callback( sequence_name, id )
self._sequence_done_callback_list[ sequence_name ][ id ] = nil
end
function CoreWorldCameraManager:add_sequence_camera_clip_callback( sequence_name, clip, func )
self._last_sequence_camera_clip_callback_id[ sequence_name ] = self._last_sequence_camera_clip_callback_id[ sequence_name ] or 0
self._last_sequence_camera_clip_callback_id[ sequence_name ] = self._last_sequence_camera_clip_callback_id[ sequence_name ] + 1
self._sequence_camera_clip_callback_list[ sequence_name ] = self._sequence_camera_clip_callback_list[ sequence_name ] or {}
self._sequence_camera_clip_callback_list[ sequence_name ][ clip ] = self._sequence_camera_clip_callback_list[ sequence_name ][ clip ] or {}
self._sequence_camera_clip_callback_list[ sequence_name ][ clip ][ self._last_sequence_camera_clip_callback_id[ sequence_name ] ] = func
return self._last_sequence_camera_clip_callback_id[ sequence_name ] -- Returns the id.
end
function CoreWorldCameraManager:remove_sequence_camera_clip_callback( sequence_name, clip, id )
self._sequence_camera_clip_callback_list[ sequence_name ][ clip ][ id ] = nil
end
function CoreWorldCameraManager:create_world_camera( world_camera_name )
self._world_cameras[ world_camera_name ] = ( rawget( _G, "WorldCamera" ) or rawget( _G, "CoreWorldCamera" ) ):new( world_camera_name )
return self._world_cameras[ world_camera_name ]
end
function CoreWorldCameraManager:remove_world_camera( world_camera_name )
self._world_cameras[ world_camera_name ] = nil
end
function CoreWorldCameraManager:all_world_cameras()
return self._world_cameras
end
function CoreWorldCameraManager:world_camera( world_camera )
return self._world_cameras[ world_camera ]
end
function CoreWorldCameraManager:play_world_camera( world_camera_name )
-- Creates a "pretend" sequence from a single world camera
local s = { self:_camera_sequence_table( world_camera_name ) }
self:play_world_camera_sequence( nil, s )
end
function CoreWorldCameraManager:new_play_world_camera( world_camera_sequence )
local world_camera = self._world_cameras[ world_camera_sequence.name ]
if world_camera then
if self._current_world_camera then
self._current_world_camera:stop()
end
self._current_world_camera = world_camera
local ok, msg = self._current_world_camera:play( world_camera_sequence )
if not ok then
if Application:editor() then
managers.editor:output_error( msg )
end
self:stop_world_camera()
return
end
else
Application:error( "WorldCamera named", world_camera_sequence.name, "did not exist." )
end
end
function CoreWorldCameraManager:stop_world_camera()
if not self._current_world_camera then
return
end
-- The current camera needs to be stoped before running the next
local stop_camera = self._current_world_camera
stop_camera:stop()
if self._current_sequence then
if self._sequence_camera_clip_callback_list[ self._current_sequence_name ] then
if self._sequence_camera_clip_callback_list[ self._current_sequence_name ][ self._sequence_index ] then
for id,func in pairs( self._sequence_camera_clip_callback_list[ self._current_sequence_name ][ self._sequence_index ] ) do
self:remove_sequence_camera_clip_callback( self._current_sequence_name, self._sequence_index, id )
func( self._current_sequence_name, self._sequence_index, id )
end
end
end
if self._sequence_index < #self._current_sequence then
self._sequence_index = self._sequence_index + 1
self:new_play_world_camera( self._current_sequence[ self._sequence_index ] )
else
self._current_world_camera = nil
self:_sequence_done()
end
end
-- The callback from the stopped camera must happen after the check if a sequence is done is completed
if self._world_camera_done_callback_list[ stop_camera:name() ] then
for id,func in pairs( self._world_camera_done_callback_list[ stop_camera:name() ] ) do
self:remove_world_camera_done_callback( stop_camera:name(), id )
func( stop_camera, id )
end
end
end
-- Create a new sequence
function CoreWorldCameraManager:create_world_camera_sequence( name )
self._world_camera_sequences[ name ] = {}
return self._world_camera_sequences[ name ]
end
-- Removes a sequence
function CoreWorldCameraManager:remove_world_camera_sequence( name )
self._world_camera_sequences[ name ] = nil
end
-- Returns all sequences
function CoreWorldCameraManager:all_world_camera_sequences()
return self._world_camera_sequences
end
-- Returns a sequence
function CoreWorldCameraManager:world_camera_sequence( name )
return self._world_camera_sequences[ name ]
end
-- Add camera to sequence
function CoreWorldCameraManager:add_camera_to_sequence( name, c_name )
local sequence = self._world_camera_sequences[ name ]
if not sequence then
Application:error( "World camera sequence named", name, "did not exist." )
return
end
table.insert( sequence, self:_camera_sequence_table( c_name ) )
return #sequence
end
-- Insert camera to sequence
function CoreWorldCameraManager:insert_camera_to_sequence( name, camera_sequence_table, index )
local sequence = self._world_camera_sequences[ name ]
if not sequence then
Application:error( "World camera sequence named", name, "did not exist." )
return
end
table.insert( sequence, index, camera_sequence_table )
return #sequence
end
-- Remove camera from sequence
function CoreWorldCameraManager:remove_camera_from_sequence( name, index )
local sequence = self._world_camera_sequences[ name ]
local camera_sequence_table = sequence[ index ]
table.remove( sequence, index )
return camera_sequence_table
end
-- Returns a formated camera sequence table
function CoreWorldCameraManager:_camera_sequence_table( name )
local t = {}
t.name = name
t.start = 0
t.stop = 1
return t
end
-- If a new sequence is started when one is allready playing, it will be breaked
function CoreWorldCameraManager:_break_sequence()
if self._current_sequence then
self:_sequence_done()
end
end
-- Called to rest all when the last camera of the sequence has been played
function CoreWorldCameraManager:_sequence_done()
self:_set_listener_enabled( false )
self:_reset_old_viewports()
self:stop_dof()
self:_set_gui_visible( false )
managers.sound_environment:set_check_object_active( self._sound_environment_check_object, false )
local done_sequence = self._current_sequence
local done_sequence_name = self._current_sequence_name
self._current_sequence = nil
self._current_sequence_name = nil
if self._sequence_done_callback_list[ done_sequence_name ] then
for id,func in pairs( self._sequence_done_callback_list[ done_sequence_name ] ) do
self:remove_sequence_done_callback( done_sequence_name, id )
func( done_sequence, id )
end
end
-- THIS WILL CHANGE SO THAT THE GSM WILL DRIVE THE WORLD CAMERA
if self._old_game_state_name then
game_state_machine:change_state_by_name( self._old_game_state_name )
self._old_game_state_name = nil
end
end
-- Plays a sequence
function CoreWorldCameraManager:play_world_camera_sequence( name, sequence )
-- THIS WILL CHANGE SO THAT THE GSM WILL DRIVE THE WORLD CAMERA
if game_state_machine:current_state_name() ~= "editor" then
self._old_game_state_name = game_state_machine:current_state_name()
end
game_state_machine:change_state_by_name( "world_camera" )
self:_break_sequence()
local sequence = self._world_camera_sequences[ name ] or sequence
if not sequence then
Application:error( "World camera sequence named", name, "did not exist." )
return
end
if #sequence == 0 then
Application:error( "World camera sequence named", name, "did not have any cameras." )
return
end
self._current_sequence = sequence
self._current_sequence_name = name
if not self._sound_environment_check_object then
self._sound_environment_check_object = managers.sound_environment:add_check_object( { object = self._camera, active = false, primary = true } )
end
managers.sound_environment:set_check_object_active( self._sound_environment_check_object, true )
self:_use_vp()
self:_set_gui_visible( true )
self:_set_listener_enabled( true )
-- self:start_dof()
self._sequence_index = 1
self:new_play_world_camera( self._current_sequence[ self._sequence_index ] )
end
function CoreWorldCameraManager:_use_vp()
self:viewport():set_active(true)
end
function CoreWorldCameraManager:_reset_old_viewports()
self:viewport():set_active(false)
end
function CoreWorldCameraManager:_set_listener_enabled( enabled )
if( enabled ) then
if( not self._listener_activation_id ) then
self._listener_activation_id = managers.listener:activate_set( "main", "world_camera" )
end
elseif( self._listener_activation_id ) then
managers.listener:deactivate_set( self._listener_activation_id )
self._listener_activation_id = nil
end
end
-- Tells the DOF manager to start the dof effect, if its not allready running
function CoreWorldCameraManager:start_dof()
if not self._using_dof then
self._using_dof = true
self._dof_effect_id = managers.DOF:play( self._dof )
end
end
-- Tells the DOF manager to stop the dof effect
function CoreWorldCameraManager:stop_dof()
managers.DOF:stop( self._dof_effect_id )
self._dof_effect_id = nil
self._using_dof = false
end
-- Returns if the dof is being used
function CoreWorldCameraManager:using_dof()
return self._using_dof
end
-- Is updated from a world camera or from editor to set what dof values to use in function update_dof
function CoreWorldCameraManager:update_dof_values( near_dof, far_dof, dof_padding, dof_clamp )
self._current_near_dof = near_dof
self._current_far_dof = far_dof
self._current_dof_padding = dof_padding
self._current_dof_clamp = dof_clamp
managers.DOF:set_effect_parameters( self._dof_effect_id, { near_min = near_dof, near_max = near_dof - dof_padding, far_min = far_dof, far_max = far_dof + dof_padding }, dof_clamp )
end
--[[
-- Called from DOF manager when the effect is running
function CoreWorldCameraManager:update_dof( t, dt, effect )
local eff_data = effect.data
-- eff_data.near_min = math.clamp( self._current_near_dof - self._current_dof_padding, 1, 1000000 )
-- eff_data.near_min = self._current_near_dof - self._current_dof_padding
-- eff_data.near_max = self._current_near_dof
eff_data.near_min = self._current_near_dof
eff_data.near_max = self._current_near_dof - self._current_dof_padding
eff_data.far_min = self._current_far_dof
eff_data.far_max = self._current_far_dof + self._current_dof_padding
eff_data.clamp = self._current_dof_clamp
end
]]
function CoreWorldCameraManager:viewport()
return self._viewport
end
function CoreWorldCameraManager:director()
return self._director
end
function CoreWorldCameraManager:workspace()
return self._workspace
end
function CoreWorldCameraManager:camera()
return self._camera
end
function CoreWorldCameraManager:camera_controller()
return self._camera_controller
end
CoreWorldCamera = CoreWorldCamera or class()
function CoreWorldCamera:init( world_camera_name )
self._world_camera_name = world_camera_name
self._points = {}
self._positions = {}
self._target_positions = {}
self._duration = 2.5
self._delay = 0
self._playing = false
self._target_offset = 1000
self._in_accelerations = {}
self._out_accelerations = {}
self._in_accelerations.linear = 0.33
self._out_accelerations.linear = 0.66
self._in_accelerations.ease = 0.0
self._out_accelerations.ease = 1.0
self._in_accelerations.fast = 0.5
self._out_accelerations.fast = 0.5
self._in_acc = self._in_accelerations.linear
self._out_acc = self._out_accelerations.linear
self._old_viewport = nil
self._keys = {}
local time = 0
local fov = managers.worldcamera:default_fov()
local near_dof = managers.worldcamera:default_near_dof()
local far_dof = managers.worldcamera:default_far_dof()
table.insert( self._keys, { time = time, fov = fov, near_dof = near_dof, far_dof = far_dof, roll = 0 } )
self._dof_padding = managers.worldcamera:default_dof_padding()
self._dof_clamp = managers.worldcamera:default_dof_clamp()
self._curve_type = "bezier"
end
function CoreWorldCamera:save_data_table()
local t = {
name = self._world_camera_name,
duration = self._duration,
delay = self._delay,
in_acc = self._in_acc,
out_acc = self._out_acc,
positions = self._positions,
target_positions = self._target_positions,
keys = self._keys,
dof_padding = self._dof_padding,
dof_clamp = self._dof_clamp,
curve_type = self._curve_type,
spline_metadata = self._spline_metadata
}
return t
end
-- SAVE DELAY AND DURATION!
--[[function CoreWorldCamera:save( f, t )
t = t..'\t'
f:puts( save_value_string( self, "_positions", t ) )
f:puts( save_value_string( self, "_target_positions", t ) )
f:puts( save_value_string( self, "_keys", t ) )
f:puts( save_value_string( self, "_dof_padding", t ) )
f:puts( save_value_string( self, "_dof_clamp", t ) )
f:puts( save_value_string( self, "_curve_type", t ) )
f:puts( save_value_string( self, "_spline_metadata", t ) )
end
]]
function CoreWorldCamera:load( values )
self._duration = values.duration
self._delay = values.delay
self._in_acc = values.in_acc
self._out_acc = values.out_acc
self._positions = values.positions
self._target_positions = values.target_positions
self._keys = values.keys
self._dof_padding = values.dof_padding
self._dof_clamp = values.dof_clamp
self._curve_type = values.curve_type
self._spline_metadata = values.spline_metadata
self:_check_loaded_data()
end
-- Add new data if it doesn't exist from load
function CoreWorldCamera:_check_loaded_data()
for _,key in pairs( self._keys ) do
key.roll = key.roll or 0
end
end
-- Old load, this is before usage of ScriptSerializer
function CoreWorldCamera:old_load( node )
self._duration = tonumber( node:parameter( "duration" ) )
self._delay = tonumber( node:parameter( "delay" ) )
if node:has_parameter( "in_acc" ) then
self._in_acc = tonumber( node:parameter( "in_acc" ) )
end
if node:has_parameter( "out_acc" ) then
self._out_acc = tonumber( node:parameter( "out_acc" ) )
end
for child in node:children() do
if child:name() == "point" then -- OLD PARSE, ALL NEW USES VALUE
local index = tonumber( child:parameter( "index" ) )
for value in child:children() do
if value:name() == "pos" then
self._positions[ index ] = math.string_to_vector( value:parameter( "value" ) )
elseif value:name() == "t_pos" then
self._target_positions[ index ] = math.string_to_vector( value:parameter( "value" ) )
end
end
elseif child:name() == "value" then
local name, value = parse_value_node( child )
self[ name ] = value
end
end
end
function CoreWorldCamera:duration()
return self._duration
end
function CoreWorldCamera:set_duration( duration )
self._duration = duration
end
function CoreWorldCamera:duration()
return self._duration
end
function CoreWorldCamera:set_delay( delay )
self._delay = delay
end
function CoreWorldCamera:delay()
return self._delay
end
function CoreWorldCamera:set_dof_padding( dof_padding )
self._dof_padding = dof_padding
end
function CoreWorldCamera:dof_padding()
return self._dof_padding
end
function CoreWorldCamera:set_dof_clamp( dof_clamp )
self._dof_clamp = dof_clamp
end
function CoreWorldCamera:dof_clamp()
return self._dof_clamp
end
function CoreWorldCamera:name()
return self._world_camera_name
end
function CoreWorldCamera:in_acc()
return self._in_acc
end
function CoreWorldCamera:out_acc()
return self._out_acc
end
--Manually position a spline element at the specified index. The control points will follow the adjustment
function CoreWorldCamera:set_sine_segment_position( new_pos, segment_index, segments, ctrl_points )
local old_pos = segments[ segment_index ]
local offset = new_pos - old_pos
if ctrl_points.p1 then
ctrl_points.p1 = ctrl_points.p1 + offset
segments[ segment_index ] = new_pos
if ctrl_points.p2 then
mvector3.set( offset, new_pos )
mvector3.subtract( offset, ctrl_points.p1 )
mvector3.set_length( offset, mvector3.distance( old_pos, ctrl_points.p2 ) )
mvector3.add( offset, new_pos )
ctrl_points.p2 = offset
end
elseif ctrl_points.p2 then
ctrl_points.p2 = ctrl_points.p2 + offset
segments[ segment_index ] = new_pos
end
end
--Set the distance of one or both control point to their respective spline position, at the specified index
function CoreWorldCamera:set_control_point_length( len_p1, len_p2, segment_index )
local positions = self._positions
local temp_vector
if len_p1 and segment_index > 1 then
temp_vector = self._spline_metadata.ctrl_points[ segment_index ].p1 - positions[ segment_index ]
mvector3.set_length( temp_vector, len_p1 )
self._spline_metadata.ctrl_points[ segment_index ].p1 = positions[ segment_index ] + temp_vector
end
if len_p2 and segment_index < #positions then
if temp_vector then
mvector3.set( temp_vector, self._spline_metadata.ctrl_points[ segment_index ].p2 )
mvector3.subtract( temp_vector, positions[ segment_index ] )
else
temp_vector = self._spline_metadata.ctrl_points[ segment_index ].p2 - positions[ segment_index ]
end
mvector3.set_length( temp_vector, len_p2 )
mvector3.add( temp_vector, positions[ segment_index ] )
self._spline_metadata.ctrl_points[ segment_index ].p2 = temp_vector
end
end
--Set the control point orientation at a certain spline index by a vector: p2 - p1
function CoreWorldCamera:rotate_control_points( p2_p1_vec, segment_index )
local positions = self._positions
local temp_vector
if segment_index > 1 then
local p1_len = mvector3.distance( self._spline_metadata.ctrl_points[ segment_index ].p1, positions[ segment_index ] )
temp_vector = -p2_p1_vec
mvector3.set_length( temp_vector, p1_len )
self._spline_metadata.ctrl_points[ segment_index ].p1 = positions[ segment_index ] + temp_vector
end
if segment_index < #positions then
local p2_len = mvector3.distance( self._spline_metadata.ctrl_points[ segment_index ].p2, positions[ segment_index ] )
if temp_vector then
mvector3.negate( temp_vector )
else
temp_vector = mvector3.copy( p2_p1_vec )
end
mvector3.set_length( temp_vector, p2_len )
self._spline_metadata.ctrl_points[ segment_index ].p2 = positions[ segment_index ] + temp_vector
end
end
-- Turn the selected spline into the Bezier type
function CoreWorldCamera:set_curve_type_bezier()
self._curve_type = "bezier"
self._spline_metadata = nil
--Remove all extra points
while #self._positions > 4 do
table.remove( self._positions )
table.remove( self._target_positions )
end
self._editor_random_access_data = nil
end
-- Turn the selected spline into the sine type and autocalculate control points
function CoreWorldCamera:set_curve_type_sine()
self._curve_type = "sine"
if #self._positions > 2 then
self:extract_spline_metadata()
end
self._editor_random_access_data = nil
end
function CoreWorldCamera:in_acc_string()
for name,value in pairs( self._in_accelerations ) do
if value == self._in_acc then
return name
end
end
end
function CoreWorldCamera:out_acc_string()
for name,value in pairs( self._out_accelerations ) do
if value == self._out_acc then
return name
end
end
end
function CoreWorldCamera:set_in_acc( in_acc )
self._in_acc = self._in_accelerations[ in_acc ]
end
function CoreWorldCamera:set_out_acc( out_acc )
self._out_acc = self._out_accelerations[ out_acc ]
end
-- Returns camera position and camera target position at time between 0 and 1
function CoreWorldCamera:positions_at_time_bezier( time )
local acc = math.bezier( { 0, self._in_acc, self._out_acc, 1 }, time )
local b_type = self._bezier or self:bezier_function()
if b_type then
local pos = b_type( self._positions, acc )
local t_pos = b_type( self._target_positions, acc )
return pos, t_pos
end
return self._positions[ 1 ], self._target_positions[ 1 ]
end
-- Called from manager when playing this camera
function CoreWorldCamera:update( t, dt )
if self._timer < self._stop_timer then
self._timer = self._timer + dt/self._duration
local pos, t_pos = self:play_to_time( self._timer )
self:update_camera( pos, t_pos )
self:set_current_fov( self:value_at_time( self._timer, "fov" ) )
local near_dof = self:value_at_time( self._timer, "near_dof" )
local far_dof = self:value_at_time( self._timer, "far_dof" )
self:update_dof_values( near_dof, far_dof, self._dof_padding, self._dof_clamp )
local rot = Rotation( (t_pos-pos):normalized(), self:value_at_time( self._timer, "roll" ) )
managers.worldcamera:camera_controller():set_default_up( rot:z() )
elseif self._delay > 0 and self._delay_timer < 1 then
self._delay_timer = self._delay_timer + dt/self._delay
else
managers.worldcamera:stop_world_camera()
end
end
function CoreWorldCamera:positions_at_time( s_t )
if self._curve_type == "sine" then
if not self._editor_random_access_data then
local metadata = self._spline_metadata
local subsegment_positions, subsegment_distances = self:extract_editor_random_access_data( self._positions, metadata.ctrl_points, metadata.nr_subseg_per_seg )
local tar_subsegment_positions, tar_subsegment_distances = self:extract_editor_random_access_data( self._target_positions, metadata.tar_ctrl_points, metadata.nr_subseg_per_seg )
self._editor_random_access_data = { subsegment_positions = subsegment_positions, subsegment_distances = subsegment_distances, tar_subsegment_positions = tar_subsegment_positions, tar_subsegment_distances = tar_subsegment_distances }
end
return self:positions_at_time_sine( s_t )
else
return self:positions_at_time_bezier( s_t )
end
end
function CoreWorldCamera:play_to_time( s_t )
if self._curve_type == "sine" then
local smooth_time = math.bezier( { 0, self._in_acc, self._out_acc, 1 }, math.clamp( self._timer, 0, 1 ) )
return self:play_to_time_sine( smooth_time )
else
return self:positions_at_time_bezier( self._timer )
end
end
function CoreWorldCamera:positions_at_time_sine( spline_t )
local result_pos, result_look_pos
local positions = self._positions
local tar_positions = self._target_positions
if #positions > 2 then
local rand_acc_data = self._editor_random_access_data
local metadata = self._spline_metadata
local wanted_dis_in_spline = math.clamp( spline_t * metadata.spline_length, 0, metadata.spline_length )
local segment_lengths = metadata.segment_lengths
for seg_i, seg_dis in ipairs( segment_lengths ) do
if seg_dis >= wanted_dis_in_spline or seg_i == #segment_lengths then
local wanted_dis_in_segment = wanted_dis_in_spline - ( segment_lengths[ seg_i - 1 ] or 0 )
local subseg_positions = rand_acc_data.subsegment_positions[ seg_i ]
local subseg_distances = rand_acc_data.subsegment_distances[ seg_i ]
for subseg_i, subseg_dis in ipairs( subseg_distances ) do
if subseg_dis >= wanted_dis_in_segment or subseg_i == #subseg_distances then
local wanted_dis_in_subseg = wanted_dis_in_segment - ( subseg_distances[ subseg_i - 1 ] or 0 )
local subseg_pos = subseg_positions[ subseg_i ]
local prev_subseg_pos = subseg_positions[ subseg_i - 1 ] or positions[ seg_i ]
local subseg_len = mvector3.distance( subseg_pos, prev_subseg_pos )
local percent_in_subseg = math.clamp( wanted_dis_in_subseg / subseg_len, 0, 1 )
result_pos = math.lerp( prev_subseg_pos, subseg_pos, percent_in_subseg )
--Get the look position
local percent_in_seg = wanted_dis_in_segment / ( seg_dis - ( segment_lengths[ seg_i - 1 ] or 0 ) )
local tar_segment_lengths = metadata.tar_segment_lengths
local tar_seg_len = tar_segment_lengths[ seg_i ] - ( tar_segment_lengths[ seg_i - 1 ] or 0 )
local wanted_dis_in_tar_seg = tar_seg_len * percent_in_seg
local tar_subseg_positions = rand_acc_data.tar_subsegment_positions[ seg_i ]
local tar_subseg_distances = rand_acc_data.tar_subsegment_distances[ seg_i ]
for tar_subseg_i, tar_subseg_dis in ipairs( tar_subseg_distances ) do
if tar_subseg_dis >= wanted_dis_in_tar_seg or tar_subseg_i == #tar_subseg_distances then
local wanted_dis_in_tar_subseg = wanted_dis_in_tar_seg - ( tar_subseg_distances[ tar_subseg_i - 1 ] or 0 )
local tar_subseg_pos = tar_subseg_positions[ tar_subseg_i ]
local prev_tar_subseg_pos = tar_subseg_positions[ tar_subseg_i - 1 ] or tar_positions[ seg_i ]
local tar_subseg_len = mvector3.distance( tar_subseg_pos, prev_tar_subseg_pos )
local percent_in_tar_subseg = math.clamp( wanted_dis_in_tar_subseg / tar_subseg_len, 0, 1 )
result_look_pos = result_pos + math.lerp( prev_tar_subseg_pos, tar_subseg_pos, percent_in_tar_subseg )
break
end
end
return result_pos, result_look_pos
end
end
end
end
elseif #positions > 1 then
result_pos = math.lerp( positions[ 1 ], positions[ 2 ], spline_t )
result_look_pos = math.lerp( tar_positions[ 1 ], tar_positions[ 2 ], spline_t )
result_look_pos = result_pos + result_look_pos
else
result_pos = positions[ 1 ]
result_look_pos = result_pos + tar_positions[ 1 ]
end
return result_pos, result_look_pos
end
function CoreWorldCamera:play_to_time_sine( s_t )
local result_pos, result_look_pos
if #self._positions > 2 then
local segments = self._positions
local metadata = self._spline_metadata
local runtime_data = self._spline_runtime_data.pos
local wanted_dis = math.clamp( s_t * metadata.spline_length, 0, metadata.spline_length )
--First find out if we need to move our search a few segments ahead
local adv_seg
while runtime_data.seg_i == 0 or runtime_data.seg_dis < wanted_dis do
runtime_data.seg_i = runtime_data.seg_i + 1
runtime_data.seg_dis = metadata.segment_lengths[ runtime_data.seg_i ]
adv_seg = true
end
if adv_seg then
runtime_data.seg_len = metadata.segment_lengths[ runtime_data.seg_i ] - ( metadata.segment_lengths[ runtime_data.seg_i - 1 ] or 0 )
runtime_data.subseg_i = 0
runtime_data.subseg_dis = 0
runtime_data.subseg_len = nil
runtime_data.subseg_pos = nil
runtime_data.subseg_prev_pos = segments[ runtime_data.seg_i ]
end
-- Sample the current segment and find the wanted position
local wanted_dis_in_seg = wanted_dis - ( metadata.segment_lengths[ runtime_data.seg_i - 1 ] or 0 )
local seg_pos = segments[ runtime_data.seg_i ]
local next_seg_pos = segments[ runtime_data.seg_i + 1 ]
local seg_p1 = metadata.ctrl_points[ runtime_data.seg_i + 1 ].p1
local seg_p2 = metadata.ctrl_points[ runtime_data.seg_i ].p2
while ( not runtime_data.subseg_pos or runtime_data.subseg_dis < wanted_dis_in_seg ) and runtime_data.subseg_i < metadata.nr_subseg_per_seg do
runtime_data.subseg_i = runtime_data.subseg_i + 1
local new_subseg_pos = self:position_at_time_on_segment( runtime_data.subseg_i / metadata.nr_subseg_per_seg, seg_pos, next_seg_pos, seg_p1, seg_p2 )
runtime_data.subseg_len = mvector3.distance( runtime_data.subseg_pos or runtime_data.subseg_prev_pos, new_subseg_pos )
runtime_data.subseg_dis = runtime_data.subseg_dis + runtime_data.subseg_len
runtime_data.subseg_prev_pos = runtime_data.subseg_pos or runtime_data.subseg_prev_pos
runtime_data.subseg_pos = new_subseg_pos
end
local percentage_in_subseg = 1 - ( runtime_data.subseg_dis - wanted_dis_in_seg ) / runtime_data.subseg_len
result_pos = math.lerp( runtime_data.subseg_prev_pos, runtime_data.subseg_pos, percentage_in_subseg )
local percentage_in_seg = wanted_dis_in_seg / runtime_data.seg_len
result_look_pos = result_pos + 500 * self:cam_look_vec_on_segment( percentage_in_seg, runtime_data.seg_i )
elseif #self._positions > 1 then
result_pos = math.lerp( self._positions[ 1 ], self._positions[ 2 ], s_t )
result_look_pos = math.lerp( self._target_positions[ 1 ], self._target_positions[ 2 ], s_t )
result_look_pos = result_pos + result_look_pos
else
result_pos = self._positions[ 1 ]
result_look_pos = result_pos + self._target_positions[ 1 ]
end
return result_pos, result_look_pos
end
--[[
function CoreWorldCamera:n_bezier( s_t, point_list )
local b_sum = Vector3()
local nr_points = #point_list - 1
for index, position in ipairs( point_list ) do
mvector3.add( b_sum, self:bernstein_polynomial( index - 1, nr_points, s_t ) * position )
end
return b_sum
end
function CoreWorldCamera:bernstein_polynomial( v, n, x ) -- b v,n( x )
return self:bionomial_coefficient( n, v ) * math.pow( x, v ) * math.pow( 1 - x, n - v )
end
function CoreWorldCamera:bionomial_coefficient( up, down ) -- up! / ( down! * ( up - down )! )
return self:factorial( up ) / ( self:factorial( down ) * self:factorial( up - down ) )
end
function CoreWorldCamera:factorial( int_value )
local result = 1
while int_value > 0 do
result = result * int_value
int_value = int_value - 1
end
return result
end
]]
--[[
local runtime_data_look_dir = {}
runtime_data.seg_i = 0 -- The index of the spline point we last visited. Zero means we at at the beginning of the spline
runtime_data.subseg_i = 0 -- The index of the subsegment we last visited. Zero means we are exactly at the beginning of the segment.
runtime_data.subseg_prev_pos = self._target_positions[ 1 ]
runtime_data.subseg_dis = nil -- How far along the spline segment we have travelled. ( cm )
runtime_data.subseg_len = nil -- The length of the last subsegment. ( cm )
]]
function CoreWorldCamera:cam_look_vec_on_segment( perc_in_seg, seg_i )
local segments = self._target_positions
local metadata = self._spline_metadata
local runtime_data = self._spline_runtime_data.dir
if runtime_data.seg_i ~= seg_i then --The position and look direction spline must be on the same segment
runtime_data.seg_i = seg_i
runtime_data.subseg_dis = 0
runtime_data.subseg_i = 0
runtime_data.subseg_pos = nil
runtime_data.subseg_prev_pos = segments[ runtime_data.seg_i ]
end
local wanted_dis_in_seg = perc_in_seg * ( metadata.tar_segment_lengths[ seg_i ] - ( metadata.tar_segment_lengths[ seg_i - 1 ] or 0 ) )
local seg_pos = segments[ seg_i ]
local next_seg_pos = segments[ seg_i + 1 ]
local seg_p1 = metadata.tar_ctrl_points[ seg_i + 1 ].p1
local seg_p2 = metadata.tar_ctrl_points[ seg_i ].p2
while ( not runtime_data.subseg_pos or runtime_data.subseg_dis < wanted_dis_in_seg ) and runtime_data.subseg_i < metadata.nr_subseg_per_seg do
runtime_data.subseg_i = runtime_data.subseg_i + 1
local new_subseg_pos = self:position_at_time_on_segment( runtime_data.subseg_i / metadata.nr_subseg_per_seg, seg_pos, next_seg_pos, seg_p1, seg_p2 )
runtime_data.subseg_len = mvector3.distance( runtime_data.subseg_pos or runtime_data.subseg_prev_pos, new_subseg_pos )
runtime_data.subseg_dis = runtime_data.subseg_dis + runtime_data.subseg_len
runtime_data.subseg_prev_pos = runtime_data.subseg_pos or runtime_data.subseg_prev_pos
runtime_data.subseg_pos = new_subseg_pos
end
local percentage_in_subseg = 1 - ( runtime_data.subseg_dis - wanted_dis_in_seg ) / runtime_data.subseg_len
local wanted_pos = math.lerp( runtime_data.subseg_prev_pos, runtime_data.subseg_pos, percentage_in_subseg )
return wanted_pos
end
function CoreWorldCamera:position_at_time_on_segment( seg_t, pos_start, pos_end, p1, p2 )
local ext_pos1 = math.lerp( pos_start, p2, seg_t )
local ext_pos2 = math.lerp( p1, pos_end, seg_t )
local xpo = ( math.sin( ( seg_t * 2 - 1 ) * 90 ) + 1 ) * 0.5
return math.lerp( ext_pos1, ext_pos2, xpo )
end
-- Auto-places control points for a newly created spline in an intuitive manner
function CoreWorldCamera:extract_spline_control_points( position_table, curviness, start_index, end_index )
-- NOTE: In order to calculate the control points at index 1 we need first to calculate index 2
local control_points = {}
start_index = start_index or 1
end_index = math.min( end_index or #position_table, #position_table )
if end_index > 2 then
local i = math.clamp( start_index, 2, end_index )
while i <= end_index do
local segment_control_points = self:extract_control_points_at_index( position_table, control_points, i, curviness )
control_points[ i ] = segment_control_points
i = i + 1
end
end
if start_index == 1 then
local segment_control_points = self:extract_control_points_at_index( position_table, control_points, 1, curviness )
control_points[1] = segment_control_points
end
return control_points
end
function CoreWorldCamera:extract_control_points_at_index( position_table, control_points, index, curviness )
local pos = position_table[ index ]
local segment_control_points = {}
local tan_seg
if index == #position_table then
local last_seg = pos - position_table[ #position_table - 1 ]
local last_vec = ( control_points[ #position_table - 1 ].p2 or position_table[ 1 ] ) - position_table[ #position_table - 1 ]
local last_angle = last_vec:angle( last_seg )
local last_rot = last_seg:cross( last_vec )
last_rot = Rotation( last_rot, 180 - 2 * last_angle )
local w_vec = pos + last_vec:rotate_with( last_rot )
segment_control_points.p1 = w_vec
--Application:draw_cylinder( pos, w_vec, 5, 0, 1, 0 )
--Application:draw_sphere( w_vec, 10, 0, 1, 0 )
elseif index == 1 then
local first_vec = control_points[2].p1 - position_table[ 2 ]
local first_seg = position_table[ 2 ] - position_table[ 1 ]
local first_angle = first_vec:angle( first_seg )
local first_rot = first_seg:cross( first_vec )
first_rot = Rotation( first_rot, 180 - 2 * first_angle )
local w_vec = position_table[ 1 ] + first_vec:rotate_with( first_rot )
segment_control_points.p2 = w_vec
--Application:draw_cylinder( position_table[ 1 ], w_vec, 5, 0, 1, 0 )
--Application:draw_sphere( w_vec, 10, 0, 1, 0 )
else
tan_seg = position_table[ index + 1 ] - position_table[ index - 1 ]
mvector3.set_length( tan_seg, mvector3.distance( pos, position_table[ index - 1 ] ) * curviness )
segment_control_points.p1 = pos - tan_seg
mvector3.set_length( tan_seg, mvector3.distance( pos, position_table[ index + 1 ] ) * curviness )
segment_control_points.p2 = pos + tan_seg
--Application:draw_cylinder( segment_control_points.p1, segment_control_points.p2, 5, 0, 1, 0 )
--Application:draw_sphere( segment_control_points.p1, 10, 0, 0.5, 0 )
--Application:draw_sphere( segment_control_points.p2, 10, 0, 1, 0 )
end
-- Crate the control point of the first segment after we create the second segment's first control point
return segment_control_points
end
function CoreWorldCamera:extract_spline_metadata()
local nr_subseg_per_seg = 30
local control_points = self:extract_spline_control_points( self._positions, 0.5 )
local segment_lengths, spline_length = self:extract_segment_dis_markers( self._positions, control_points, nr_subseg_per_seg )
local tar_control_points = self:extract_spline_control_points( self._target_positions, 0.5 )
local tar_segment_lengths, tar_spline_length = self:extract_segment_dis_markers( self._target_positions, tar_control_points, nr_subseg_per_seg )
self._spline_metadata = { ctrl_points = control_points, segment_lengths = segment_lengths, spline_length = spline_length, tar_ctrl_points = tar_control_points, tar_segment_lengths = tar_segment_lengths, tar_spline_length = tar_spline_length, nr_subseg_per_seg = nr_subseg_per_seg }
end
function CoreWorldCamera:extract_segment_dis_markers( segment_table, control_points, nr_subsegments )
local segment_lengths = {}
local spline_length = 0
for index, pos in ipairs( segment_table ) do
if index == #segment_table then
break
end
local next_seg_pos = segment_table[ index + 1 ]
local seg_p1 = control_points[ index + 1 ].p1
local seg_p2 = control_points[ index ].p2
local seg_len = 0
local subsegment_index = 1
local prev_subseg_pos = pos
--Split the segment into subsegments the first segment is step % away from the start and the last sub-segment is equal to the next segment start
while subsegment_index <= nr_subsegments do
local spline_t = math.min( 1, subsegment_index / nr_subsegments )
local subseg_pos = self:position_at_time_on_segment( spline_t, pos, next_seg_pos, seg_p1, seg_p2 )
local subseg_len = mvector3.distance( prev_subseg_pos, subseg_pos )
seg_len = seg_len + subseg_len
prev_subseg_pos = subseg_pos
subsegment_index = subsegment_index + 1
end
spline_length = spline_length + seg_len
table.insert( segment_lengths, spline_length )
end
return segment_lengths, spline_length
end
function CoreWorldCamera:extract_editor_random_access_data( segment_table, control_points, nr_subsegments )
local subsegment_lengths = {}
local subsegment_positions = {}
for index, pos in ipairs( segment_table ) do
if index == #segment_table then
break
end
local seg_subsegment_lengths = {}
local seg_subsegment_positions = {}
local next_seg_pos = segment_table[ index + 1 ]
local seg_p1 = control_points[ index + 1 ].p1
local seg_p2 = control_points[ index ].p2
local seg_len = 0
local subsegment_index = 1
local prev_subseg_pos = pos
--Split the segment into subsegments the first segment is step % away from the start and the last sub-segment is equal to the next segment start
while subsegment_index <= nr_subsegments do
local spline_t = math.min( 1, subsegment_index / nr_subsegments )
local subseg_pos = self:position_at_time_on_segment( spline_t, pos, next_seg_pos, seg_p1, seg_p2 )
local subseg_len = mvector3.distance( prev_subseg_pos, subseg_pos )
seg_len = seg_len + subseg_len
table.insert( seg_subsegment_lengths, seg_len )
table.insert( seg_subsegment_positions, subseg_pos )
prev_subseg_pos = subseg_pos
subsegment_index = subsegment_index + 1
end
table.insert( subsegment_lengths, seg_subsegment_lengths )
table.insert( subsegment_positions, seg_subsegment_positions )
end
return subsegment_positions, subsegment_lengths
end
function CoreWorldCamera:debug_draw_editor()
local positions = self._positions
local target_positions = self._target_positions
local nr_segments = #positions
if nr_segments > 0 then
if nr_segments > 2 then
if self._curve_type == "sine" then
local metadata = self._spline_metadata
local prev_subseg_pos = positions[1]
for seg_i, seg_pos in ipairs( positions ) do
if seg_i == #positions then
break
end
local seg_p1 = metadata.ctrl_points[ seg_i + 1 ].p1
local seg_p2 = metadata.ctrl_points[ seg_i ].p2
local subsegment_index = 1
local next_seg_pos = positions[ seg_i + 1 ]
while subsegment_index <= metadata.nr_subseg_per_seg do
local spline_t = math.min( 1, subsegment_index / metadata.nr_subseg_per_seg )
local subseg_pos = self:position_at_time_on_segment( spline_t, seg_pos, next_seg_pos, seg_p1, seg_p2 )
Application:draw_line( subseg_pos, prev_subseg_pos, 1, 1, 1 )
prev_subseg_pos = subseg_pos
subsegment_index = subsegment_index + 1
end
end
else
local step = 0.02
local previous_pos
for i = step, 1, step do
local acc = math.bezier( { 0, self:in_acc(), self:out_acc(), 1 }, i )
local cam_pos, cam_look_pos = self:positions_at_time_bezier( acc )
if previous_pos then
Application:draw_line( cam_pos, previous_pos, 1, 1, 1 )
end
previous_pos = cam_pos
local look_dir = cam_look_pos - cam_pos
mvector3.set_length( look_dir, 100 )
mvector3.add( look_dir, cam_pos )
Application:draw_line( cam_pos, look_dir, 1, 1, 0 )
end
end
end
for i,pos in ipairs( positions ) do
if i ~= nr_segments then
Application:draw_line( pos, positions[ i + 1 ], 0.75, 0.75, 0.75 )
end
Application:draw_sphere( pos, 20, 1, 1, 1 )
local t_pos = target_positions[ i ]
Application:draw_line( pos, pos + (t_pos - pos):normalized() * 500, 1, 1, 0 )
end
end
end
-- Tells the manager to update the dof values
function CoreWorldCamera:update_dof_values( ... )
managers.worldcamera:update_dof_values( ... )
end
-- Tells the manager to set the current fov
function CoreWorldCamera:set_current_fov( fov )
managers.worldcamera:set_fov( fov )
end
-- Called from manager to start the camera
function CoreWorldCamera:play( sequence_data )
if #self._positions == 0 then
return false, "Camera "..self._world_camera_name.." didn't have any points."
end
if self._duration == 0 then
return false, "Camera "..self._world_camera_name.." has duration 0, must be higher."
end
self._timer = sequence_data.start or 0
self._stop_timer = sequence_data.stop or 1
self._delay_timer = 0
self._index = 1
self._target_point = nil
self._playing = true
if not self._curve_type or self._curve_type == "bezier" then
self:set_curve_type_bezier()
self._bezier = self:bezier_function()
end
local runtime_data_pos = {}
runtime_data_pos.seg_dis = 0 -- How far along the spline is the current segment. ( cm )
runtime_data_pos.seg_len = 0 --The lenght of the spline along this segment. ( cm )
runtime_data_pos.seg_i = 0 -- The index of the spline point we last visited. Zero means we at at the beginning of the spline
runtime_data_pos.subseg_i = 0 -- The index of the subsegment we last visited. Zero means we are exactly at the beginning of the segment.
runtime_data_pos.subseg_prev_pos = self._positions[ 1 ]
-- runtime_data_pos.subseg_pos = nil
-- runtime_data.subseg_dis = nil -- How far along the spline segment we have travelled. ( cm )
-- runtime_data.subseg_len = nil -- The length of the last subsegment. ( cm )
local runtime_data_look_dir = {}
runtime_data_look_dir.seg_i = 0 -- The index of the spline point we last visited. Zero means we at at the beginning of the spline
runtime_data_look_dir.subseg_i = 0 -- The index of the subsegment we last visited. Zero means we are exactly at the beginning of the segment.
runtime_data_look_dir.subseg_prev_pos = self._target_positions[ 1 ]
-- runtime_data_look_dir.subseg_dis = nil -- How far along the spline segment we have travelled. ( cm )
-- runtime_data_look_dir.subseg_len = nil -- The length of the last subsegment. ( cm )
self._spline_runtime_data = {}
self._spline_runtime_data.pos = runtime_data_pos
self._spline_runtime_data.dir = runtime_data_look_dir
self:update_camera( self._positions[ 1 ], self._target_positions[ 1 ] )
self:set_current_fov( self:value_at_time( self._timer, "fov" ) )
return true
end
-- Called from manager when the camera is done or force stopped
function CoreWorldCamera:stop()
self._playing = false
self._bezier = nil
self._spline_runtime_data = nil
end
-- Returns what kind of bezier function to use
function CoreWorldCamera:bezier_function()
if #self._positions == 2 then
return math.linear_bezier
elseif #self._positions == 3 then
return math.quadratic_bezier
elseif #self._positions == 4 then
return math.bezier
end
return nil
end
-- Updates the manager camera with positions
function CoreWorldCamera:update_camera( pos, t_pos )
managers.worldcamera:camera_controller():set_camera( pos )
managers.worldcamera:camera_controller():set_target( t_pos )
end
--[[
function CoreWorldCamera:debug_print_sine()
cat_print( "debug", "debug_print_sine" )
local metadata = self._spline_metadata
if metadata then
local positions = self._positions
cat_print( "debug", "positions:" )
for seg_i, pos in ipairs( positions ) do
cat_print( "debug", seg_i, pos )
end
cat_print( "debug", "control points:" )
for seg_i, c_points in ipairs( metadata.ctrl_points ) do
cat_print( "debug", seg_i, c_points.p1, c_points.p2 )
end
local tar_positions = self._target_positions
cat_print( "debug", "target positions:" )
for seg_i, pos in ipairs( tar_positions ) do
cat_print( "debug", seg_i, pos )
end
cat_print( "debug", "target control points:" )
for seg_i, c_points in ipairs( metadata.tar_ctrl_points ) do
cat_print( "debug", seg_i, c_points.p1, c_points.p2 )
end
else
cat_print( "debug", "no metadata" )
end
end
]]
-- Adds a point to the positions
function CoreWorldCamera:add_point( pos, rot )
if self._curve_type == "sine" then
table.insert( self._positions, pos )
table.insert( self._target_positions, rot:y() )
if #self._positions == 3 then
self:extract_spline_metadata()
elseif #self._positions > 3 then
local new_control_points = self:extract_spline_control_points( self._positions, 0.5, #self._positions - 1, #self._positions )
self._spline_metadata.ctrl_points[ #self._positions - 1 ] = new_control_points[ #self._positions - 1 ]
self._spline_metadata.ctrl_points[ #self._positions ] = new_control_points[ #self._positions ]
local segment_lengths, spline_length = self:extract_segment_dis_markers( self._positions, self._spline_metadata.ctrl_points, self._spline_metadata.nr_subseg_per_seg )
self._spline_metadata.segment_lengths = segment_lengths
self._spline_metadata.spline_length = spline_length
new_control_points = self:extract_spline_control_points( self._target_positions, 0.5, #self._target_positions - 1, #self._target_positions )
self._spline_metadata.tar_ctrl_points[ #self._target_positions - 1 ] = new_control_points[ #self._target_positions - 1 ]
self._spline_metadata.tar_ctrl_points[ #self._target_positions ] = new_control_points[ #self._target_positions ]
segment_lengths, spline_length = self:extract_segment_dis_markers( self._target_positions, self._spline_metadata.tar_ctrl_points, self._spline_metadata.nr_subseg_per_seg )
self._spline_metadata.tar_segment_lengths = segment_lengths
self._spline_metadata.tar_spline_length = spline_length
end
self:delete_editor_random_access_data()
--self:debug_print_sine()
elseif #self._positions < 4 then
table.insert( self._positions, pos )
table.insert( self._target_positions, pos + rot:y() * self._target_offset )
end
end
function CoreWorldCamera:get_points()
return self._positions
end
function CoreWorldCamera:get_point( point )
return { pos = self._positions[ point ], t_pos = self._target_positions[ point ] }
end
function CoreWorldCamera:delete_point( point )
table.remove( self._positions, point )
table.remove( self._target_positions, point )
if self._curve_type == "sine" then
if #self._positions < 3 then
self:delete_spline_metadata()
else
table.remove( self._spline_metadata.ctrl_points, point )
table.remove( self._spline_metadata.tar_ctrl_points, point )
self._spline_metadata.ctrl_points[ 1 ].p1 = nil
self._spline_metadata.ctrl_points[ #self._positions ].p2 = nil
self._spline_metadata.tar_ctrl_points[ 1 ].p1 = nil
self._spline_metadata.tar_ctrl_points[ #self._target_positions ].p2 = nil
local segment_lengths, spline_length = self:extract_segment_dis_markers( self._positions, self._spline_metadata.ctrl_points, self._spline_metadata.nr_subseg_per_seg )
self._spline_metadata.segment_lengths = segment_lengths
self._spline_metadata.spline_length = spline_length
segment_lengths, spline_length = self:extract_segment_dis_markers( self._target_positions, self._spline_metadata.tar_ctrl_points, self._spline_metadata.nr_subseg_per_seg )
self._spline_metadata.tar_segment_lengths = segment_lengths
self._spline_metadata.tar_spline_length = spline_length
end
self:delete_editor_random_access_data()
--self:debug_print_sine()
end
end
function CoreWorldCamera:delete_spline_metadata()
self._spline_metadata = nil
end
function CoreWorldCamera:delete_editor_random_access_data()
self._editor_random_access_data = nil
end
function CoreWorldCamera:reset_control_points( segment_index )
if self._curve_type == "sine" and #self._positions > 2 then
local control_points = self:extract_control_points_at_index( self._positions, self._spline_metadata.ctrl_points, segment_index, 0.5 )
self._spline_metadata.ctrl_points[ segment_index ] = control_points
local segment_lengths, spline_length = self:extract_segment_dis_markers( self._positions, self._spline_metadata.ctrl_points, self._spline_metadata.nr_subseg_per_seg )
self._spline_metadata.spline_length = spline_length
self._spline_metadata.segment_lengths = segment_lengths
self:delete_editor_random_access_data()
end
end
function CoreWorldCamera:move_point( point, pos, rot )
if self._curve_type == "sine" then
if pos then
if #self._positions > 2 then
self:set_sine_segment_position( pos, point, self._positions, self._spline_metadata.ctrl_points[ point ] )
local segment_lengths, spline_length = self:extract_segment_dis_markers( self._positions, self._spline_metadata.ctrl_points, self._spline_metadata.nr_subseg_per_seg )
self._spline_metadata.spline_length = spline_length
self._spline_metadata.segment_lengths = segment_lengths
else
self._positions[ point ] = pos
end
end
if rot then
if #self._positions > 2 then
self:set_sine_segment_position( rot:y(), point, self._target_positions, self._spline_metadata.tar_ctrl_points[ point ] )
local new_control_points = self:extract_spline_control_points( self._target_positions, 0.5, point - 1, point + 1 )
for k, v in pairs( new_control_points ) do
self._spline_metadata.tar_ctrl_points[ k ] = v
end
local segment_lengths, spline_length = self:extract_segment_dis_markers( self._target_positions, self._spline_metadata.tar_ctrl_points, self._spline_metadata.nr_subseg_per_seg )
self._spline_metadata.tar_spline_length = spline_length
self._spline_metadata.tar_segment_lengths = segment_lengths
else
self._target_positions[ point ] = rot:y()
end
end
self:delete_editor_random_access_data()
--self:debug_print_sine()
else
if pos then
self._positions[ point ] = pos
end
if rot then
local t_pos = rot:y() * self._target_offset + self._positions[ point ]
self._target_positions[ point ] = t_pos
end
end
end
function CoreWorldCamera:positions()
return self._positions
end
function CoreWorldCamera:target_positions()
return self._target_positions
end
function CoreWorldCamera:insert_point( index, position, rotation )
end
function CoreWorldCamera:keys()
return self._keys
end
function CoreWorldCamera:key( i )
return self._keys[ i ]
end
function CoreWorldCamera:next_key( time )
local index = 1
for i,key in ipairs( self._keys ) do
if key.time <= time then
index = i + 1
end
end
if index > #self._keys then
index = #self._keys
end
return index
end
-- When stepping in the timeline we need to step to the key with smaller time then time, eventhough we are
-- standing right on a key. When getting a key to use its values, prev_key needs to return the key we are
-- standing on.
function CoreWorldCamera:prev_key( time, step )
local index = 1
for i,key in ipairs( self._keys ) do
if step then
if key.time < time then
index = i
end
else
if key.time <= time then
index = i
end
end
end
return index
end
function CoreWorldCamera:add_key( time )
local index = 1
local fov, near_dof, far_dof, roll
fov = math.round( self:value_at_time( time, "fov" ) )
near_dof = math.round( self:value_at_time( time, "near_dof" ) )
far_dof = math.round( self:value_at_time( time, "far_dof" ) )
roll = math.round( self:value_at_time( time, "roll" ) )
local key = { time = time, fov = fov, near_dof = near_dof, far_dof = far_dof, roll = roll }
for i,key in ipairs( self._keys ) do
if( key.time < time ) then
index = i + 1
else
break
end
end
table.insert( self._keys, index, key )
return index, key
end
function CoreWorldCamera:delete_key( index )
table.remove( self._keys, index )
end
function CoreWorldCamera:move_key( index, time )
if( #self._keys == 1 ) then
self._keys[ 1 ].time = time
return 1
else
local old_key = clone( self._keys[ index ] )
self:delete_key( index )
local index, key = self:add_key( time )
key.fov = old_key.fov
key.near_dof = old_key.near_dof
key.far_dof = old_key.far_dof
key.roll = old_key.roll
return index
end
end
-- Returns a linear calculated value between keys
function CoreWorldCamera:value_at_time( time, value )
local prev_key = self:prev_value_key( time, value )
local next_key = self:next_value_key( time, value )
local mul = 1
if next_key.time - prev_key.time ~= 0 then
mul = ( time - prev_key.time ) / ( next_key.time - prev_key.time )
end
local v = (next_key[ value ] - prev_key[ value ]) * mul + prev_key[ value ]
return v
end
-- Returns the previous key with a value
function CoreWorldCamera:prev_value_key( time, value )
local index = self:prev_key( time )
local key = self._keys[ index ]
if key[ value ] then
return key
else
return self:prev_value_key( key.time, value )
end
end
-- Returns the next key with a value
function CoreWorldCamera:next_value_key( time, value )
local index = self:next_key( time )
local key = self._keys[ index ]
if key[ value ] then
return key
else
return self:next_value_key( key.time, value )
end
end
function CoreWorldCamera:print_points()
for i = 1, 4 do
cat_print( "debug", i, self._positions[ i ], self._target_positions[ i ] )
end
end
function CoreWorldCamera:playing()
return self._playing
end
| gpl-2.0 |
rshell/biorails | config/environments/development.rb | 946 | # Settings specified here will take precedence over those in
# config/environment.rb In the development environment your application's code
# is reloaded on every request. This slows down response time but is perfect
# for development since you don't have to restart the webserver when you make
# code changes.
SYSTEM_SETTINGS="#{RAILS_ROOT}/config/system_settings.yml"
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_view.debug_rjs = true
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Force all environments to use the same logger level (by default production
# uses :info, the others :debug)
config.log_level = :info
| gpl-2.0 |
kunj1988/Magento2 | app/code/Magento/Authorizenet/Helper/Backend/Data.php | 2913 | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Authorizenet\Helper\Backend;
use Magento\Authorizenet\Helper\Data as FrontendDataHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Sales\Model\OrderFactory;
use Magento\Backend\Model\UrlInterface;
/**
* Authorize.net Backend Data Helper
*
* @api
* @since 100.0.2
*/
class Data extends FrontendDataHelper
{
/**
* @param \Magento\Framework\App\Helper\Context $context
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Sales\Model\OrderFactory $orderFactory
* @param \Magento\Backend\Model\UrlInterface $backendUrl
*/
public function __construct(
Context $context,
StoreManagerInterface $storeManager,
OrderFactory $orderFactory,
UrlInterface $backendUrl
) {
parent::__construct($context, $storeManager, $orderFactory);
$this->_urlBuilder = $backendUrl;
}
/**
* Return URL for admin area
*
* @param string $route
* @param array $params
* @return string
*/
protected function _getUrl($route, $params = [])
{
return $this->_urlBuilder->getUrl($route, $params);
}
/**
* Retrieve place order url in admin
*
* @return string
*/
public function getPlaceOrderAdminUrl()
{
return $this->_getUrl('adminhtml/authorizenet_directpost_payment/place', []);
}
/**
* Retrieve place order url
*
* @param array $params
* @return string
*/
public function getSuccessOrderUrl($params)
{
$param = [];
$route = 'sales/order/view';
$order = $this->orderFactory->create()->loadByIncrementId($params['x_invoice_num']);
$param['order_id'] = $order->getId();
return $this->_getUrl($route, $param);
}
/**
* Retrieve redirect iframe url
*
* @param array $params
* @return string
*/
public function getRedirectIframeUrl($params)
{
return $this->_getUrl('adminhtml/authorizenet_directpost_payment/redirect', $params);
}
/**
* Get direct post relay url
*
* @param null|int|string $storeId
* @return string
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getRelayUrl($storeId = null)
{
$defaultStore = $this->storeManager->getDefaultStoreView();
if (!$defaultStore) {
$allStores = $this->storeManager->getStores();
if (isset($allStores[0])) {
$defaultStore = $allStores[0];
}
}
$baseUrl = $defaultStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);
return $baseUrl . 'authorizenet/directpost_payment/backendResponse';
}
}
| gpl-2.0 |
christianchristensen/resin | modules/resin/src/com/caucho/amber/cfg/AccessType.java | 1159 | /*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Rodrigo Westrupp
*/
package com.caucho.amber.cfg;
/**
* The access type: FIELD | PROPERTY
*/
public enum AccessType {
FIELD, PROPERTY;
}
| gpl-2.0 |
emilroz/openmicroscopy | components/server/src/ome/logic/PixelsImpl.java | 13287 | /*
* $Id$
*
* Copyright 2006-2014 University of Dundee. All rights reserved.
* Use is subject to license terms supplied in LICENSE.txt
*/
package ome.logic;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import ome.annotations.RolesAllowed;
import ome.api.IPixels;
import ome.api.ServiceInterface;
import ome.conditions.ValidationException;
import ome.model.IObject;
import ome.model.core.Channel;
import ome.model.core.Image;
import ome.model.core.LogicalChannel;
import ome.model.core.Pixels;
import ome.model.display.RenderingDef;
import ome.model.enums.DimensionOrder;
import ome.model.enums.PixelsType;
import ome.model.internal.Permissions;
import ome.model.meta.Session;
import ome.model.stats.StatsInfo;
import ome.parameters.Parameters;
import ome.system.EventContext;
import ome.util.PixelData;
/**
* implementation of the Pixels service interface.
*
* @author Jean-Marie Burel <a
* href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a>
* @author <br>
* Andrea Falconi <a
* href="mailto:a.falconi@dundee.ac.uk"> a.falconi@dundee.ac.uk</a>
* @version 2.2 <small> (<b>Internal version:</b> $Revision$ $Date:
* 2005/06/12 23:27:31 $) </small>
* @since OME2.2
*/
@Transactional(readOnly = true)
public class PixelsImpl extends AbstractLevel2Service implements IPixels {
/**
* Returns the interface this implementation is for.
* @see AbstractLevel2Service#getServiceInterface()
*/
public Class<? extends ServiceInterface> getServiceInterface() {
return IPixels.class;
}
/** Standard rendering definition HQL query prefix */
public static final String RENDERING_DEF_QUERY_PREFIX =
"select rdef from RenderingDef as rdef " +
"left outer join fetch rdef.details.owner " +
"left outer join fetch rdef.quantization " +
"left outer join fetch rdef.model " +
"left outer join fetch rdef.waveRendering as cb " +
"left outer join fetch cb.family " +
"left outer join fetch rdef.spatialDomainEnhancement where ";
// ~ Service methods
// =========================================================================
@RolesAllowed("user")
public Pixels retrievePixDescription(long pixId) {
Pixels p = iQuery.findByQuery("select p from Pixels as p "
+ "left outer join fetch p.pixelsType as pt "
+ "left outer join fetch p.channels as c "
+ "left outer join fetch c.logicalChannel as lc "
+ "left outer join fetch c.statsInfo "
+ "left outer join fetch lc.photometricInterpretation "
+ "left outer join fetch lc.illumination "
+ "left outer join fetch lc.mode "
+ "left outer join fetch lc.contrastMethod "
+ "where p.id = :id",
new Parameters().addId(pixId));
return p;
}
/**
* Implemented as specified by the {@link IPixels} I/F.
* @see IPixels#retrieveRndSettingsFor(long, long)
*/
@RolesAllowed("user")
public RenderingDef retrieveRndSettingsFor(long pixId, long userId)
{
List<IObject> list = retrieveAllRndSettings(pixId, userId);
if (list == null || list.size() == 0) return null;
return (RenderingDef) list.get(0);
}
/**
* Implemented as specified by the {@link IPixels} I/F.
* @see IPixels#retrieveAllRndSettingsFor(long, long)
*/
@RolesAllowed("user")
public List<IObject> retrieveAllRndSettings(long pixId, long userId)
{
Parameters params = new Parameters();
params.addLong("p_id", pixId);
String restriction = "rdef.pixels.id = :p_id ";
if (userId >= 0) {
restriction += "and rdef.details.owner.id = :o_id ";
params.addLong("o_id", userId);
}
List<IObject> l = iQuery.findAllByQuery(
RENDERING_DEF_QUERY_PREFIX +restriction +
"order by rdef.details.updateEvent.time desc", params);
return l;
}
/**
* Implemented as specified by the {@link IPixels} I/F.
* @see IPixels#retrieveRndSettings(long)
*/
@RolesAllowed("user")
public RenderingDef retrieveRndSettings(long pixId) {
Long userId = sec.getEffectiveUID();
RenderingDef rd = retrieveRndSettingsFor(pixId, userId);
if (rd == null)
{
final EventContext ec = this.sec.getEventContext(false);
final Pixels pixelsObj = this.iQuery.get(Pixels.class, pixId);
final boolean isGraphCritical = this.sec.isGraphCritical(pixelsObj.getDetails());
long pixOwner = pixelsObj.getDetails().getOwner().getId();
long currentUser = ec.getCurrentUserId();
if (currentUser != pixOwner) {
rd = retrieveRndSettingsFor(pixId, pixOwner);
}
}
return rd;
}
/**
* Implemented as specified by the {@link IPixels} I/F.
* @see IPixels#loadRndSettings(long)
*/
@RolesAllowed("user")
public RenderingDef loadRndSettings(long renderingDefId) {
return (RenderingDef) iQuery.findByQuery(
RENDERING_DEF_QUERY_PREFIX + "rdef.id = :id",
new Parameters().addId(renderingDefId));
}
/** Actually performs the work declared in {@link copyAndResizePixels()}. */
private Pixels _copyAndResizePixels(long pixelsId, Integer sizeX,
Integer sizeY, Integer sizeZ, Integer sizeT,
List<Integer> channelList, String methodology, boolean copyStats)
{
Pixels from = retrievePixDescription(pixelsId);
Pixels to = new Pixels();
// Ensure we have no values out of bounds
outOfBoundsCheck(sizeX, "sizeX");
outOfBoundsCheck(sizeY, "sizeY");
outOfBoundsCheck(sizeZ, "sizeZ");
outOfBoundsCheck(sizeT, "sizeT");
// Check that the channels in the list are valid indexes.
if(channelList!=null)
channelOutOfBounds(channelList, "channel", from);
// Copy basic metadata
to.setDimensionOrder(from.getDimensionOrder());
to.setMethodology(methodology);
to.setPhysicalSizeX(from.getPhysicalSizeX());
to.setPhysicalSizeY(from.getPhysicalSizeY());
to.setPhysicalSizeZ(from.getPhysicalSizeZ());
to.setPixelsType(from.getPixelsType());
to.setRelatedTo(from);
to.setSizeX(sizeX != null? sizeX : from.getSizeX());
to.setSizeY(sizeY != null? sizeY : from.getSizeY());
to.setSizeZ(sizeZ != null? sizeZ : from.getSizeZ());
to.setSizeT(sizeT != null? sizeT : from.getSizeT());
to.setSizeC(channelList!= null ? channelList.size() : from.getSizeC());
to.setSha1("Pending...");
// Copy channel data, if the channel list is null copy all channels.
// or copy the channels in the channelList if it's not null.
if(channelList != null)
{
for (Integer channel : channelList)
{
copyChannel(channel, from, to, copyStats);
}
}
else
{
for (int channel = 0 ; channel < from.sizeOfChannels(); channel++)
{
copyChannel(channel, from, to, copyStats);
}
}
return to;
}
@RolesAllowed("user")
@Transactional(readOnly = false)
public Long copyAndResizePixels(long pixelsId, Integer sizeX, Integer sizeY,
Integer sizeZ, Integer sizeT, List<Integer> channelList,
String methodology, boolean copyStats)
{
Pixels from = retrievePixDescription(pixelsId);
Pixels to =
_copyAndResizePixels(pixelsId, sizeX, sizeY, sizeZ, sizeT,
channelList, methodology, copyStats);
// Deal with Image linkage
Image image = from.getImage();
image.addPixels(to);
// Save and return our newly created Pixels Id
image = iUpdate.saveAndReturnObject(image);
return image.getPixels(image.sizeOfPixels() - 1).getId();
}
@RolesAllowed("user")
@Transactional(readOnly = false)
public Long copyAndResizeImage(long imageId, Integer sizeX, Integer sizeY,
Integer sizeZ, Integer sizeT, List<Integer> channelList,
String name, boolean copyStats)
{
Image iFrom = iQuery.get(Image.class, imageId);
Image iTo = new Image();
// Set the image name
iTo.setAcquisitionDate(iFrom.getAcquisitionDate());
iTo.setName(name);
iTo.setObjectiveSettings(iFrom.getObjectiveSettings());
iTo.setImagingEnvironment(iFrom.getImagingEnvironment());
iTo.setExperiment(iFrom.getExperiment());
iTo.setStageLabel(iFrom.getStageLabel());
iTo.setInstrument(iFrom.getInstrument());
// Copy each Pixels set that the source image has
Iterator<Pixels> i = iFrom.iteratePixels();
while (i.hasNext())
{
Pixels p = i.next();
Pixels to =
_copyAndResizePixels(p.getId(), sizeX, sizeY, sizeZ, sizeT,
channelList, null, copyStats);
iTo.addPixels(to);
}
// Save and return our newly created Image Id
iTo = iUpdate.saveAndReturnObject(iTo);
return iTo.getId();
}
@RolesAllowed("user")
@Transactional(readOnly = false)
public Long createImage(int sizeX, int sizeY, int sizeZ, int sizeT,
List<Integer> channelList, PixelsType pixelsType, String name,
String description)
{
Image image = new Image();
Pixels pixels = new Pixels();
image.setName(name);
image.setDescription(description);
image.setAcquisitionDate(new Timestamp(new Date().getTime()));
// Check that the channels in the list are valid.
if (channelList == null || channelList.size() == 0)
{
throw new ValidationException("Channel list must be filled.");
}
// Create basic metadata
pixels.setPixelsType(pixelsType);
pixels.setSizeX(sizeX);
pixels.setSizeY(sizeY);
pixels.setSizeZ(sizeZ);
pixels.setSizeC(channelList.size());
pixels.setSizeT(sizeT);
pixels.setSha1("Pending...");
pixels.setDimensionOrder(getEnumeration(DimensionOrder.class, "XYZCT"));
// Create channel data.
List<Channel> channels = createChannels(channelList);
for(Channel channel : channels)
pixels.addChannel(channel);
image.addPixels(pixels);
// Save and return our newly created Image Id
image = iUpdate.saveAndReturnObject(image);
return image.getId();
}
@RolesAllowed("user")
@Transactional(readOnly = false)
public void setChannelGlobalMinMax(long pixelsId, int channelIndex,
double min, double max)
{
Pixels pixels = retrievePixDescription(pixelsId);
Channel channel = pixels.getChannel(channelIndex);
StatsInfo stats = channel.getStatsInfo();
if (stats == null) {
stats = new StatsInfo();
channel.setStatsInfo(stats);
}
stats.setGlobalMax(max);
stats.setGlobalMin(min);
iUpdate.saveAndReturnObject(channel);
}
@RolesAllowed("user")
@Transactional(readOnly = false)
public void saveRndSettings(RenderingDef rndSettings) {
iUpdate.saveAndReturnObject(rndSettings);
}
@RolesAllowed("user")
public int getBitDepth(PixelsType pixelsType) {
return PixelData.getBitDepth(pixelsType.getValue());
}
@RolesAllowed("user")
public <T extends IObject> T getEnumeration(Class<T> klass, String value) {
return iQuery.findByString(klass, "value", value);
}
@RolesAllowed("user")
public <T extends IObject> List<T> getAllEnumerations(Class<T> klass) {
return iQuery.findAll(klass, null);
}
/**
* Ensures that a particular dimension value is not out of range (ex. less
* than zero).
* @param value The value to check.
* @param name The name of the value to be used for error reporting.
* @throws ValidationException If <code>value</code> is out of range.
*/
private void outOfBoundsCheck(Integer value, String name)
{
if (value != null && value < 0)
{
throw new ValidationException(name + ": " + value + " <= 0");
}
}
/**
* Ensures that a particular dimension value in a list is not out of
* range (ex. less than zero).
* @param channelList The list of channels to check.
* @param name The name of the value to be used for error reporting.
* @param pixels the pixels the channel list belongs to.
* @throws ValidationException If <code>value</code> is out of range.
*/
private void channelOutOfBounds(List<Integer> channelList, String name,
Pixels pixels)
{
if(channelList.size() == 0)
throw new ValidationException("Channel List is not null but size == 0");
for(int i = 0 ; i < channelList.size() ; i++)
{
int value = channelList.get(i);
if (value < 0 || value >= pixels.sizeOfChannels())
throw new ValidationException(name + ": " + i + " out of bounds");
}
}
/**
* Copy the channel from the pixels to the pixels called to.
* @param channel the channel index.
* @param from the pixel to copy from.
* @param to the pixels to copy to.
* @param copyStats Whether or not to copy the {@link StatsInfo} for each
* channel.
*/
private void copyChannel(int channel, Pixels from, Pixels to,
boolean copyStats)
{
Channel cFrom = from.getChannel(channel);
Channel cTo = new Channel();
cTo.setLogicalChannel(cFrom.getLogicalChannel());
if (copyStats)
{
cTo.setStatsInfo(new StatsInfo(cFrom.getStatsInfo().getGlobalMin(),
cFrom.getStatsInfo().getGlobalMax()));
}
to.addChannel(cTo);
}
/**
* Creates new channels to be added to a Pixels set.
* @param channelList The list of channel emission wavelengths in
* nanometers.
* @return See above.
*/
private List<Channel> createChannels(List<Integer> channelList)
{
List<Channel> channels = new ArrayList<Channel>();
for (Integer wavelength : channelList)
{
Channel channel = new Channel();
LogicalChannel lc = new LogicalChannel();
channel.setLogicalChannel(lc);
channels.add(channel);
}
return channels;
}
}
| gpl-2.0 |
x42/sisco.lv2 | zita-resampler/resampler.cc | 5078 | // ----------------------------------------------------------------------------
//
// Copyright (C) 2006-2012 Fons Adriaensen <fons@linuxaudio.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 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "../zita-resampler/resampler.h"
namespace LV2S {
static unsigned int gcd (unsigned int a, unsigned int b)
{
if (a == 0) return b;
if (b == 0) return a;
while (1)
{
if (a > b)
{
a = a % b;
if (a == 0) return b;
if (a == 1) return 1;
}
else
{
b = b % a;
if (b == 0) return a;
if (b == 1) return 1;
}
}
return 1;
}
Resampler::Resampler (void) :
_table (0),
_nchan (0),
_buff (0)
{
reset ();
}
Resampler::~Resampler (void)
{
clear ();
}
int Resampler::setup (unsigned int fs_inp,
unsigned int fs_out,
unsigned int nchan,
unsigned int hlen)
{
if ((hlen < 8) || (hlen > 96)) return 1;
return setup (fs_inp, fs_out, nchan, hlen, 1.0 - 2.6 / hlen);
}
int Resampler::setup (unsigned int fs_inp,
unsigned int fs_out,
unsigned int nchan,
unsigned int hlen,
double frel)
{
unsigned int g, h, k, n, s;
double r;
float *B = 0;
Resampler_table *T = 0;
k = s = 0;
if (fs_inp && fs_out && nchan)
{
r = (double) fs_out / (double) fs_inp;
g = gcd (fs_out, fs_inp);
n = fs_out / g;
s = fs_inp / g;
if ((16 * r >= 1) && (n <= 1000))
{
h = hlen;
k = 250;
if (r < 1)
{
frel *= r;
h = (unsigned int)(ceil (h / r));
k = (unsigned int)(ceil (k / r));
}
T = Resampler_table::create (frel, h, n);
B = new float [nchan * (2 * h - 1 + k)];
}
}
clear ();
if (T)
{
_table = T;
_buff = B;
_nchan = nchan;
_inmax = k;
_pstep = s;
return reset ();
}
else return 1;
}
void Resampler::clear (void)
{
Resampler_table::destroy (_table);
delete[] _buff;
_buff = 0;
_table = 0;
_nchan = 0;
_inmax = 0;
_pstep = 0;
reset ();
}
double Resampler::inpdist (void) const
{
if (!_table) return 0;
return (int)(_table->_hl + 1 - _nread) - (double)_phase / _table->_np;
}
int Resampler::inpsize (void) const
{
if (!_table) return 0;
return 2 * _table->_hl;
}
int Resampler::reset (void)
{
if (!_table) return 1;
inp_count = 0;
out_count = 0;
inp_data = 0;
out_data = 0;
_index = 0;
_nread = 0;
_nzero = 0;
_phase = 0;
if (_table)
{
_nread = 2 * _table->_hl;
return 0;
}
return 1;
}
int Resampler::process (void)
{
unsigned int hl, ph, np, dp, in, nr, nz, i, n, c;
float *p1, *p2;
if (!_table) return 1;
hl = _table->_hl;
np = _table->_np;
dp = _pstep;
in = _index;
nr = _nread;
ph = _phase;
nz = _nzero;
n = (2 * hl - nr) * _nchan;
p1 = _buff + in * _nchan;
p2 = p1 + n;
while (out_count)
{
if (nr)
{
if (inp_count == 0) break;
if (inp_data)
{
for (c = 0; c < _nchan; c++) p2 [c] = inp_data [c];
inp_data += _nchan;
nz = 0;
}
else
{
for (c = 0; c < _nchan; c++) p2 [c] = 0;
if (nz < 2 * hl) nz++;
}
nr--;
p2 += _nchan;
inp_count--;
}
else
{
if (out_data)
{
if (nz < 2 * hl)
{
float *c1 = _table->_ctab + hl * ph;
float *c2 = _table->_ctab + hl * (np - ph);
for (c = 0; c < _nchan; c++)
{
float *q1 = p1 + c;
float *q2 = p2 + c;
float s = 1e-20f;
for (i = 0; i < hl; i++)
{
q2 -= _nchan;
s += *q1 * c1 [i] + *q2 * c2 [i];
q1 += _nchan;
}
*out_data++ = s - 1e-20f;
}
}
else
{
for (c = 0; c < _nchan; c++) *out_data++ = 0;
}
}
out_count--;
ph += dp;
if (ph >= np)
{
nr = ph / np;
ph -= nr * np;
in += nr;
p1 += nr * _nchan;;
if (in >= _inmax)
{
n = (2 * hl - nr) * _nchan;
memcpy (_buff, p1, n * sizeof (float));
in = 0;
p1 = _buff;
p2 = p1 + n;
}
}
}
}
_index = in;
_nread = nr;
_phase = ph;
_nzero = nz;
return 0;
}
}
| gpl-2.0 |
csust-dreamstation/CsustFlea | src/com/csustflea/action/ListCollectionAction.java | 3589 | package com.csustflea.action;
import java.sql.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.csustflea.model.Collection;
import com.csustflea.model.Goods;
import com.csustflea.model.PageModel;
import com.csustflea.model.User;
import com.csustflea.service.GoodsService;
import com.opensymphony.xwork2.ActionSupport;
@Component
@Scope("prototype")
public class ListCollectionAction extends ActionSupport {
private int uid;
private static List<Goods> Goods;
public static List<Goods> getGoods() {
return Goods;
}
public static void setGoods(List<Goods> goods) {
Goods = goods;
}
private Collection collection;
private int[] things;
private PageModel pagemodel;
private int page;
private int pagesize = 5;
private List<Goods> listcollection;
public List<Goods> getListcollection() {
return listcollection;
}
public void setListcollection(List<Goods> listcollection) {
this.listcollection = listcollection;
}
public PageModel getPagemodel() {
return pagemodel;
}
@Resource
public void setPagemodel(PageModel pagemodel) {
this.pagemodel = pagemodel;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getPagesize() {
return pagesize;
}
public void setPagesize(int pagesize) {
this.pagesize = pagesize;
}
public int[] getThings() {
return things;
}
public void setThings(int[] things) {
this.things = things;
}
public Collection getCollection() {
return collection;
}
public void setCollection(Collection collection) {
this.collection = collection;
}
private GoodsService goodservice;
public GoodsService getGoodservice() {
return goodservice;
}
@Resource
public void setGoodservice(GoodsService goodservice) {
this.goodservice = goodservice;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String list(){
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
User u =(User)session.getAttribute("logUserTemp");
uid = u.getId();
pagemodel.setPage(page);
pagemodel.setPageSize(pagesize);
List<Goods> ListCol = this.goodservice.ListCollection(pagemodel, uid);
page = pagemodel.getPage();
for(int i=0;i<ListCol.size();i++) /*Iterator<Goods> it = (Iterator)ListGoodsManTemp.iterator(); while(it.hasNext()){System.out.println(it.next().getGname());*/
{
String gname = ListCol.get(i).getGname();
String gname1 = null;
if(gname.length()>9){
gname1=gname.substring(0, 8)+"...";
}
else{gname1 = gname;}
System.out.println(gname1);
Goods g = ListCol.get(i);
g.setGname(gname1);
}
listcollection = ListCol;
return "list";
}
public String SaveCGoods() {
Date date = new Date(System.currentTimeMillis());
collection.setCtime(date);
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
User u = (User) session.getAttribute("logUserTemp");
int idtemp = u.getId();
collection.setUid(idtemp);
this.goodservice.SaveCGoods(collection);
return "savecgoods";
}
public String DelCGoods() {
for (int i = 0; i < things.length; i++) {
this.goodservice.DelCGoods(things[i]);
}
return "delcgoods";
}
}
| gpl-2.0 |
iegor/kdeedu | kiten/deinf.cpp | 3091 | /**
This file is part of Kiten, a KDE Japanese Reference Tool...
Copyright (C) 2001 Jason Katz-Brown <jason@katzbrown.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
**/
#include <kdebug.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <qfile.h>
#include <qregexp.h>
#include <qtextcodec.h>
#include "deinf.h"
Deinf::Index::Index()
{
loaded = false;
}
void Deinf::Index::load()
{
if (loaded)
return;
KStandardDirs *dirs = KGlobal::dirs();
QString vconj = dirs->findResource("data", "kiten/vconj");
if (vconj.isNull())
{
KMessageBox::error(0, i18n("Verb deinflection information not found, so verb deinflection cannot be used."));
return;
}
QFile f(vconj);
if (!f.open(IO_ReadOnly))
{
KMessageBox::error(0, i18n("Verb deinflection information could not be loaded, so verb deinflection cannot be used."));
return;
}
QTextStream t(&f);
t.setCodec(QTextCodec::codecForName("eucJP"));
for(QString text = t.readLine(); !t.eof() && text.at(0) != '$'; text = t.readLine())
{
if(text.at(0) != '#')
{
unsigned int number = text.left(2).stripWhiteSpace().toUInt();
QString name = text.right(text.length() - 2).stripWhiteSpace();
names[number] = name;
}
}
for(QString text = t.readLine(); !text.isEmpty(); text = t.readLine())
{
if(text.at(0) != '#')
{
QStringList things(QStringList::split(QChar('\t'), text));
Conjugation conj;
conj.ending = things.first();
conj.replace = (*things.at(1));
conj.num = things.last().toUInt();
list.append(conj);
}
}
f.close();
loaded = true;
}
namespace
{
QStringList possibleConjugations(const QString &text)
{
QStringList endings;
for (unsigned i = 0; i < text.length(); ++i)
endings.append(text.right(i));
return endings;
}
}
QStringList Deinf::Index::deinflect(const QString &text, QStringList &name)
{
load();
QStringList endings = possibleConjugations(text);
QStringList ret;
for (QValueListIterator <Conjugation> it = list.begin(); it != list.end(); ++it)
{
QStringList matches(endings.grep(QRegExp(QString("^") + (*it).ending)));
if (matches.size() > 0) // a match
{
name.append(names[(*it).num]);
//kdDebug() << "match ending: " << (*it).ending << "; replace: " << (*it).replace << "; name: " << names[(*it).num] << endl;
QString tmp(text);
tmp.replace(QRegExp((*it).ending + "*", false, true), (*it).replace);
ret.append(tmp);
}
}
return ret;
}
| gpl-2.0 |
cortinico/spm | src/it/ncorti/histogramthresholding/SplitMatrix.java | 1487 | package it.ncorti.histogramthresholding;
import cl.niclabs.skandium.muscles.Split;
/**
* Classe per la divisione della matrice in sottomatrici per righe
* Questa classe implementa l'interfaccia Split ed e' pensata per funzionare all'interno di uno
* skeleton di tipo Map
*
* @author Nicola
*/
public class SplitMatrix implements Split<Matrix, Matrix> {
// Numero delle sottomatrici da realizzare
private int num;
/**
* Costrutture principale
* @param num Numero delle sottomatrici desiderate
*/
public SplitMatrix(int num){
this.num = num;
}
/**
* Metodo per dividere una matrice p in sottomatrici.
* Ritorna una array di sottomatrici
*
* @param p Matrice da dividere
* @return Array di sottomatrici
*/
@Override
public Matrix[] split(Matrix p) throws Exception {
Matrix[] res = new Matrix[num];
int rowsize = p.sizeRow/num;
// long time = System.currentTimeMillis();
int i;
for (i = 0; i<num-1; i++){
res[i] = p.subMatrix((i*rowsize), 0, (i+1)*rowsize, p.sizeCol);
}
res[num-1] = p.subMatrix((i*rowsize), 0, p.sizeRow, p.sizeRow);
// System.out.println("Split over in: " + (System.currentTimeMillis() - time));
return res;
}
}
/*
Divisione per colonne
Matrix[] res = new Matrix[num];
int colsize = p.sizeCol/num;
int i;
for (i = 0; i<num-1; i++){
res[i] = p.subMatrix(0, (i*colsize), p.sizeRow, (i+1)*colsize);
}
res[num-1] = p.subMatrix(0, (i*colsize), p.sizeRow, p.sizeCol);
*/ | gpl-2.0 |
atmark-techno/atmark-dist | lib/STLport/test/regression/func1.cpp | 601 | // STLport regression testsuite component.
// To compile as a separate example, please #define MAIN.
#include <iostream>
#include <vector>
#include <algorithm>
#ifdef MAIN
#define func1_test main
#endif
#if !defined (STLPORT) || defined(__STL_USE_NAMESPACES)
using namespace std;
#endif
static bool bigger(int i_)
{
return i_ > 3;
}
int func1_test(int, char**)
{
cout<<"Results of func1_test:"<<endl;
vector<int>v;
v.push_back(4);
v.push_back(1);
v.push_back(5);
int n = 0;
count_if(v.begin(), v.end(), bigger, n);
cout << "Number greater than 3 = " << n << endl;
return 0;
}
| gpl-2.0 |
DanielTichy/plagat.com | templates/equalizer/index.php | 8116 | <?php
/*----------------------------------------------------------------------
#Youjoomla Defaul Index -
# ----------------------------------------------------------------------
# Copyright (C) 2007 You Joomla. All Rights Reserved.
# Designed by: You Joomla
# License: GNU, GPL Index.php Only!
# Website: http://www.youjoomla.com
------------------------------------------------------------------------*/
defined( '_JEXEC' ) or die( 'Restricted index access' );
$iso = split( '=', _ISO );
// xml prolog - quirks mode
//echo '<?xml version="1.0" encoding="'. $iso[1] .'"?' .'>';
// SUCKERFISH MENU SWITCH //
$menu_name = $this->params->get("menuName", "mainmenu");// mainmenu by default, can be any Joomla! menu name
$default_color = $this->params->get("defaultcolor", "green"); // GREEN | ORANGE | BLUE
$default_font = $this->params->get("fontsize", "medium"); // SMALL | MEDIUM | BIG
$default_width = $this->params->get("sitewidth", "wide"); // WIDE | NARROW
$showtools = $this->params->get("templateTools", "1"); // 0 HIDE TOOLS | 1 SHOW ALL | 2 COLOR AND WIDTH | 3 COLOR AND FONT | 4 WIDTH AND FONT |5 WIDTH ONLY | 6 FONT ONLY | 7 COLOR ONLY
// SEO SECTION //
$seo = $this->params->get ("seo", "Joomla Hosting Template"); # JUST FOLOW THE TEXT
$tags = $this->params->get ("tags", "Joomla Hosting, Joomla Templates, Youjoomla"); # JUST FOLOW THE TEXT
#DO NOT EDIT BELOW THIS LINE
define( 'TEMPLATEPATH', dirname(__FILE__) );
include( TEMPLATEPATH.DS."settings.php");
include( TEMPLATEPATH.DS."styleswitcher.php");
require( TEMPLATEPATH.DS."suckerfish.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" >
<head>
<jdoc:include type="head" />
<link href="templates/<?php echo $this->template ?>/css/<?php echo $css_file; ?>" rel="stylesheet" title="" type="text/css" media="all"/>
<link href="templates/<?php echo $this->template ?>/css/<?php echo $layoutcss; ?>" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="templates/<?php echo $this->template ?>/src/reflection.js"></script>
<?php echo "<!--[if lt IE 7]>\n";
include_once( "templates/". $this->template . "/src/ie.js" );
echo "<![endif]-->\n";?>
<!--[if lte IE 6]>
<style type="text/css">
#logo,#searchbox,#fotr{
behavior: url(templates/<?php echo $this->template ?>/css/iepngfix.htc);
}
</style>
<![endif]-->
<?php
if ( $layoutcss == "wide.css"){
echo '<!--[if lte IE 6]> <link href="templates/'.$this->template.'/css/iesucks.css" rel="stylesheet" title="" type="text/css" media="all"/> <![endif]-->';
} else if ( $layoutcss == "narrow.css")
echo '<!--[if lte IE 6]> <link href="templates/'.$this->template.'/css/iesucks2.css" rel="stylesheet" title="" type="text/css" media="all"/> <![endif]-->';
?>
</head>
<!-- ODVAJANJE ZAREZOM -->
<body>
<div id="<?php echo $img ?>">
<div id="centar2" style="font-size:<?php echo $css_font; ?>; width:<?php echo $css_width; ?>;">
<div id="header">
<div id="logo"><h1><a href="index.php" title="<?php echo $tags?>"><?php echo $seo ?></a></h1></div>
<div id="searchbox"><jdoc:include type="modules" name="header" style="xhtml" /></div>
</div>
<!-- suckerfish-->
<div id="suckmen">
<div id="navigacija">
<?php mosShowListMenu($menu_name); ?>
</div>
</div>
<!-- end suckerfish-->
<?php if ($this->countModules('user1') || $this->countModules('user2') || $this->countModules('user3') || $this->countModules('user4')) { ?><!-- midsection-->
<div id="midsection">
<div id="midr">
<div id="midl">
<div id="midmods">
<?php if ($this->countModules('user1')) { ?>
<div id="user1" style="width:<?php echo $topwidth; ?>;"><jdoc:include type="modules" name="user1" style="xhtml" /></div><?php } ?>
<?php if ($this->countModules('user2')) { ?>
<div id="user2" style="width:<?php echo $topwidth; ?>;"><jdoc:include type="modules" name="user2" style="xhtml" /></div><?php } ?>
<?php if ($this->countModules('user3')) { ?>
<div id="user3" style="width:<?php echo $topwidth; ?>;"><jdoc:include type="modules" name="user3" style="xhtml" /></div><?php } ?>
<?php if ($this->countModules('user4')) { ?>
<div id="user4" style="width:<?php echo $topwidth; ?>;"><jdoc:include type="modules" name="user4" style="xhtml" /></div><?php } ?>
</div>
</div>
</div>
</div>
<!--end midsection-->
<?php } ?>
<!-- pathway-->
<div id="pathw"><div id="patha"><jdoc:include type="module" name="breadcrumbs" style="none" /></div><div id="styles"><?
// 1 = SHOW ALL | 2 COLOR AND WIDTH | 3 COLOR AND FONT | 4 WIDTH AND FONT |5 WIDTH ONLY | 6 FONT ONLY | 7 COLOR ONLY
if ( $showtools== 1 || $showtools== 2 || $showtools== 3 || $showtools== 7 ){
// COLOR SWITCHER LINKS
while(list($key, $val) = each($mystyles)){
echo "<a href='".$_SERVER['PHP_SELF']."?change_css=".$key."' >".$val["label"]."</a>";
}
}
?>
<?
if ( $showtools== 1 || $showtools== 3 || $showtools== 4 || $showtools== 6){
// FONT SWITCHER LINKS
while(list($key, $val) = each($myfont)){
echo "<a href='".$_SERVER['PHP_SELF']."?change_font=".$key."' >".$val["label"]."</a>";
}
}
?>
<?
if ( $showtools== 1 || $showtools== 2 || $showtools== 4 || $showtools== 5 ){
// WIDTH SWITCHER LINKS
while(list($key, $val) = each($mywidth)){
echo "<a href='".$_SERVER['PHP_SELF']."?change_width=".$key."' >".$val["label"]."</a>";
}
}
?> </div></div>
<!-- end pathway-->
</div><!-- end centar2-->
<div id="centar" style="font-size:<?php echo $css_font; ?>; width:<?php echo $css_width; ?>;">
<div id="<?php echo $wrap?>">
<div id="<?php echo $insidewrap ?>">
<div id="<?php echo $mainbody ?>">
<div id="<?php echo $content ?>">
<?php if ($this->countModules('top')) { ?>
<div id="topmod"><div class="inside">
<jdoc:include type="modules" name="top" style="xhtml" /> </div></div><?php } ?>
<div class="inside">
<jdoc:include type="component" />
</div></div>
<?php if ($this->countModules('left')) { ?>
<div id="<?php echo $left ?>">
<div class="inside2"><!-- keep mods of edges-->
<jdoc:include type="modules" name="left" style="rounded" />
<!-- end inside--></div><!-- end modsl--></div><!-- end left side-->
<?php } ?>
</div> <!--end of main-body-->
<!-- right side always stand alone-->
<?php if ($this->countModules('right')) { ?>
<div id="<?php echo $right ?>">
<div class="inside2"> <!-- keep mods of edges-->
<jdoc:include type="modules" name="right" style="rounded" />
</div><!-- end of inside --></div><!-- end right side-->
<?php } ?>
<div class="clr"></div>
<?php if ($this->countModules('user5') || $this->countModules('user6') || $this->countModules('user7') || $this->countModules('user8')) { ?><!-- botsection-->
<div id="bottomshelf">
<div id="bottomshelfl">
<div id="bottomshelfr">
<div id="botmods">
<?php if ($this->countModules('user5')) { ?>
<div id="user5" style="width:<?php echo $bottomwidth; ?>;"><jdoc:include type="modules" name="user5" style="xhtml" /></div><?php } ?>
<?php if ($this->countModules('user6')) { ?>
<div id="user6" style="width:<?php echo $bottomwidth; ?>;"><jdoc:include type="modules" name="user6" style="xhtml" /></div><?php } ?>
<?php if ($this->countModules('user7')) { ?>
<div id="user7" style="width:<?php echo $bottomwidth; ?>;"><jdoc:include type="modules" name="user7" style="xhtml" /></div><?php } ?>
<?php if ($this->countModules('user8')) { ?>
<div id="user8" style="width:<?php echo $bottomwidth; ?>;"><jdoc:include type="modules" name="user8" style="xhtml" /></div><?php } ?>
</div>
</div>
</div>
</div><?php } ?>
</div><!-- end of insidewrap--></div> <!--end of wrap-->
</div><!-- end centar-->
</div>
<div id="footer"><div id="footerin" style="font-size:<?php echo $css_font; ?>; width:<?php echo $css_width; ?>;">
<div id="fotl"><jdoc:include type="modules" name="footer" style="xhtml" />
Design by <a href="http://www.youjoomla.com">Youjoomla.com</a><a href="#centar2">Top</a></div><div id="fotr"></div></div>
</div>
</body>
</html>
| gpl-2.0 |
adrian2020my/gavick | components/com_hikashop/params/selectoptions.php | 1373 | <?php
/**
* @package HikaShop for Joomla!
* @version 2.3.1
* @author hikashop.com
* @copyright (C) 2010-2014 HIKARI SOFTWARE. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><?php
class JElementSelectoptions extends JElement{
function fetchElement($name, $value, &$node, $control_name){
if(!include_once(rtrim(JPATH_ADMINISTRATOR,DS).DS.'components'.DS.'com_hikashop'.DS.'helpers'.DS.'helper.php')){
return 'This menu options cannot be displayed without the Hikashop Component';
}
$config =& hikashop_config();
if(!hikashop_isAllowed($config->get('acl_menus_manage','all'))){
return 'Access to the HikaShop options of the menus is restricted';
}
$id = reset(JRequest::getVar( 'cid', array(), '', 'array' ));
if(!empty($id)){
$text = '<a title="'.JText::_('HIKASHOP_OPTIONS').'" href="'.JRoute::_('index.php?option=com_hikashop&ctrl=menus&task=edit&cid[]='.$id).'" >'.JText::_('HIKASHOP_OPTIONS').'</a>';
$config =& hikashop_config();
$hikashop_params = $config->get('menu_'.$id,null);
if(empty($hikashop_params)){
$text .= '<br/>'.JText::_('HIKASHOP_SAVE_OPTIONS_ONCE');
}
}else{
$text = JText::_('HIKASHOP_OPTIONS_EDIT').'<br/>'.JText::_('HIKASHOP_SAVE_OPTIONS_ONCE');
}
return $text;
}
}
| gpl-2.0 |
invy/far2l | colorer/src/shared/unicode/DString.cpp | 8272 |
#include<unicode/DString.h>
#include <stdio.h>
DString& DString::operator=(const DString &cstring){
if (type == ST_UTF8) delete[] stream_wstr;
type = cstring.type;
encodingIdx = cstring.encodingIdx;
str = cstring.str;
start = cstring.start;
len = cstring.len;
if (type == ST_UTF8){
stream_wstr = new wchar[len];
for(int wi = 0; wi < len; wi++)
stream_wstr[wi] = cstring.stream_wstr[wi];
};
return *this;
}
DString::DString(const byte *stream, int size, int def_encoding){
start = 0;
len = size;
str = (char*)stream;
type = ST_CHAR;
if (def_encoding == Encodings::ENC_UTF8) type = ST_UTF8;
if (def_encoding == Encodings::ENC_UTF16) type = ST_UTF16;
if (def_encoding == Encodings::ENC_UTF16BE) type = ST_UTF16_BE;
if (def_encoding == Encodings::ENC_UTF32) type = ST_UTF32;
if (def_encoding == Encodings::ENC_UTF32BE) type = ST_UTF32_BE;
if (def_encoding > Encodings::getEncodingNamesNum())
throw UnsupportedEncodingException(SString(def_encoding));
encodingIdx = def_encoding;
if (type == ST_CHAR && encodingIdx == -1){
// check encoding parameter
if (stream[0] == 0x3C && stream[1] == 0x3F){
int p;
int cps = 0, cpe = 0;
for(p = 2; stream[p] != 0x3F && stream[p+1] != 0x3C && p < 100; p++){
if (cps && stream[p] == stream[cps-1]){
cpe = p;
break;
};
if (cps || strncmp((char*)stream+p, "encoding=", 9)) continue;
p += 9;
if (!cps && (stream[p] == '\"' || stream[p] == '\'')){
p++;
cps = p;
}else
break;
};
if (cps && cpe){
DString dcp((char*)stream, cps, cpe-cps);
encodingIdx = Encodings::getEncodingIndex(dcp.getChars());
if (encodingIdx == -1)
throw UnsupportedEncodingException(dcp);
if (encodingIdx == Encodings::ENC_UTF8)
type = ST_UTF8;
else if (encodingIdx < 0) throw UnsupportedEncodingException(StringBuffer("encoding conflict - can't use ")+dcp);
}else type = ST_UTF8;
};
if ((stream[0] == 0xFF && stream[1] == 0xFE && stream[2] == 0x00 && stream[3] == 0x00) ||
(stream[0] == 0x3C && stream[1] == 0x00 && stream[2] == 0x00 && stream[3] == 0x00) ){
type = ST_UTF32;
}else if ((stream[0] == 0x00 && stream[1] == 0x00 && stream[2] == 0xFE && stream[3] == 0xFF) ||
(stream[0] == 0x00 && stream[1] == 0x00 && stream[2] == 0x00 && stream[3] == 0x3C) ){
type = ST_UTF32_BE;
}else if ((stream[0] == 0xFF && stream[1] == 0xFE) ||
(stream[0] == 0x3C && stream[1] == 0x00 && stream[2] == 0x3F && stream[3] == 0x00)){
type = ST_UTF16;
}else if ((stream[0] == 0xFE && stream[1] == 0xFF) ||
(stream[0] == 0x00 && stream[1] == 0x3C && stream[2] == 0x00 && stream[3] == 0x3F)){
type = ST_UTF16_BE;
}else if (stream[0] == 0xEF && stream[1] == 0xBB && stream[2] == 0xBF){
type = ST_UTF8;
};
};
if (type == ST_UTF16 || type == ST_UTF16_BE){
wstr = (wchar*)stream;
len = size/2;
}else if (type == ST_UTF32 || type == ST_UTF32_BE){
w4str = (w4char*)stream;
len = size/4;
}else if (type == ST_UTF8){
stream_wstr = new wchar[size];
int pos;
for(pos = 0, len = 0; pos < size; pos++, len++){
wchar wc = 0;
if (!(stream[pos] >> 7)){
wc = stream[pos];
}else if (stream[pos] >> 6 == 2){
wc = '?'; // bad char in stream
}else{
int nextbytes = 0;
while(stream[pos] << (nextbytes+1) & 0x80) nextbytes++;
wc = (stream[pos] & 0xFF >> (nextbytes+2)) << nextbytes*6;
while(nextbytes--){
wc += (stream[++pos] & 0x3F) << nextbytes*6;
};
};
stream_wstr[len] = wc;
};
}else if(type == ST_CHAR && encodingIdx == -1){
encodingIdx = Encodings::getDefaultEncodingIndex();
};
}
DString::DString(const char *string, int s, int l, int encoding){
type = ST_CHAR;
str = string;
start = s;
len = l;
if (s < 0 || len < -1) throw Exception(DString("bad string constructor parameters"));
if (len == -1){
len = 0;
if (string != null) for(len = 0; str[len+s]; len++);
};
encodingIdx = encoding;
if (encodingIdx == -1) encodingIdx = Encodings::getDefaultEncodingIndex();
}
DString::DString(const wchar *string, int s, int l){
type = ST_UTF16;
wstr = string;
start = s;
len = l;
if (s < 0 || len < -1) throw Exception(DString("bad string constructor parameters"));
if (len == -1)
for(len = 0; wstr[len+s]; len++);
}
DString::DString(const w4char *string, int s, int l){
type = ST_UTF32;
w4str = string;
start = s;
len = l;
if (s < 0 || len < -1) throw Exception(DString("bad string constructor parameters"));
if (len == -1)
for(len = 0; w4str[len+s]; len++);
}
DString::DString(const String *cstring, int s, int l){
type = ST_CSTRING;
cstr = cstring;
start = s;
len = l;
if (s < 0 || s > cstring->length() || len < -1 || len > cstring->length() - start)
throw Exception(DString("bad string constructor parameters"));
if (len == -1)
len = cstring->length() - start;
}
DString::DString(const String &cstring, int s, int l){
type = ST_CSTRING;
cstr = &cstring;
start = s;
len = l;
if (s < 0 || s > cstring.length() || len < -1 || len > cstring.length() - start)
throw Exception(DString("bad string constructor parameters"));
if (len == -1)
len = cstring.length() - start;
}
DString::DString(){
type = ST_CHAR;
len = 0;
start = 0;
}
DString::~DString(){
if (type == ST_UTF8) delete[] stream_wstr;
}
wchar DString::operator[](int i) const{
if (start+i >= 0 && i < len) switch(type){
case ST_CHAR:
return Encodings::toWChar(encodingIdx, str[start+i]);
case ST_UTF16:
return wstr[start+i];
case ST_UTF16_BE:
return (wstr[start+i]>>8) | ((wstr[start+i]&0xFF) << 8);
case ST_CSTRING:
return (*cstr)[start+i];
case ST_UTF8:
return stream_wstr[start+i];
case ST_UTF32:
// check for 4byte character - if so, return REPLACEMENT CHARACTER
if (w4str[start+i]>>16 != 0){
return 0xFFFD;
}
return (wchar)w4str[start+i];
case ST_UTF32_BE:
// check for 4byte character - if so, return REPLACEMENT CHARACTER
if (w4str[start+i]<<16 != 0){
return 0xFFFD;
}
return (wchar)(((w4str[start+i]&0xFF)<<24) + ((w4str[start+i]&0xFF00)<<8) + ((w4str[start+i]&0xFF0000)>>8) + ((w4str[start+i]&0xFF000000)>>24));
};
throw StringIndexOutOfBoundsException(SString(i));
}
int DString::length() const{
return len;
}
/* ***** 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 Colorer Library.
*
* The Initial Developer of the Original Code is
* Cail Lomecb <cail@nm.ru>.
* Portions created by the Initial Developer are Copyright (C) 1999-2005
* 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 ***** */
| gpl-2.0 |
codelibs/n2dms | src/main/java/com/openkm/module/db/DbNoteModule.java | 9704 | package com.openkm.module.db;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import com.openkm.bean.Note;
import com.openkm.core.AccessDeniedException;
import com.openkm.core.Config;
import com.openkm.core.DatabaseException;
import com.openkm.core.LockException;
import com.openkm.core.PathNotFoundException;
import com.openkm.core.RepositoryException;
import com.openkm.dao.NodeBaseDAO;
import com.openkm.dao.NodeNoteDAO;
import com.openkm.dao.bean.NodeBase;
import com.openkm.dao.bean.NodeNote;
import com.openkm.module.NoteModule;
import com.openkm.module.db.base.BaseNoteModule;
import com.openkm.module.db.base.BaseNotificationModule;
import com.openkm.spring.PrincipalUtils;
import com.openkm.util.FormatUtil;
import com.openkm.util.PathUtils;
import com.openkm.util.UserActivity;
public class DbNoteModule implements NoteModule {
private static Logger log = LoggerFactory.getLogger(DbNoteModule.class);
@Override
public Note add(String token, String nodeId, String text) throws LockException, PathNotFoundException, AccessDeniedException,
RepositoryException, DatabaseException {
log.debug("add({}, {}, {})", new Object[] { token, nodeId, text });
Note newNote = null;
Authentication auth = null, oldAuth = null;
String nodePath = null;
String nodeUuid = null;
if (Config.SYSTEM_READONLY) {
throw new AccessDeniedException("System is in read-only mode");
}
try {
if (token == null) {
auth = PrincipalUtils.getAuthentication();
} else {
oldAuth = PrincipalUtils.getAuthentication();
auth = PrincipalUtils.getAuthenticationByToken(token);
}
if (PathUtils.isPath(nodeId)) {
nodePath = nodeId;
nodeUuid = NodeBaseDAO.getInstance().getUuidFromPath(nodeId);
} else {
nodePath = NodeBaseDAO.getInstance().getPathFromUuid(nodeId);
nodeUuid = nodeId;
}
NodeBase node = NodeBaseDAO.getInstance().findByPk(nodeUuid);
text = FormatUtil.sanitizeInput(text);
NodeNote nNote = BaseNoteModule.create(nodeUuid, auth.getName(), text);
newNote = BaseNoteModule.getProperties(nNote, nNote.getUuid());
// Check subscriptions
BaseNotificationModule.checkSubscriptions(node, auth.getName(), "ADD_NOTE", text);
// Activity log
UserActivity.log(auth.getName(), "ADD_NOTE", nodeUuid, nodePath, text);
} catch (DatabaseException e) {
throw e;
} finally {
if (token != null) {
PrincipalUtils.setAuthentication(oldAuth);
}
}
log.debug("add: {}", newNote);
return newNote;
}
@Override
public void delete(String token, String noteId) throws LockException, PathNotFoundException, AccessDeniedException,
RepositoryException, DatabaseException {
log.debug("delete({}, {})", token, noteId);
Authentication auth = null, oldAuth = null;
String notePath = null;
String noteUuid = null;
if (Config.SYSTEM_READONLY) {
throw new AccessDeniedException("System is in read-only mode");
}
try {
if (token == null) {
auth = PrincipalUtils.getAuthentication();
} else {
oldAuth = PrincipalUtils.getAuthentication();
auth = PrincipalUtils.getAuthenticationByToken(token);
}
NodeBase nBase = NodeNoteDAO.getInstance().getParentNode(noteId);
notePath = NodeBaseDAO.getInstance().getPathFromUuid(nBase.getUuid()) + "/" + noteId;
noteUuid = noteId;
NodeNote nNote = NodeNoteDAO.getInstance().findByPk(noteUuid);
if (auth.getName().equals(nNote.getAuthor()) || PrincipalUtils.hasRole(Config.DEFAULT_ADMIN_ROLE)) {
NodeNoteDAO.getInstance().delete(noteUuid);
} else {
throw new AccessDeniedException("Note can only be removed by its creator or " + Config.ADMIN_USER);
}
// Activity log
UserActivity.log(auth.getName(), "DELETE_NOTE", noteUuid, notePath, null);
} catch (DatabaseException e) {
throw e;
} finally {
if (token != null) {
PrincipalUtils.setAuthentication(oldAuth);
}
}
log.debug("delete: void");
}
@Override
public Note get(String token, String noteId) throws LockException, PathNotFoundException, AccessDeniedException, RepositoryException,
DatabaseException {
log.debug("get({}, {})", token, noteId);
Note note = null;
Authentication auth = null, oldAuth = null;
String notePath = null;
String noteUuid = null;
if (Config.SYSTEM_READONLY) {
throw new AccessDeniedException("System is in read-only mode");
}
try {
if (token == null) {
auth = PrincipalUtils.getAuthentication();
} else {
oldAuth = PrincipalUtils.getAuthentication();
auth = PrincipalUtils.getAuthenticationByToken(token);
}
NodeBase nBase = NodeNoteDAO.getInstance().getParentNode(noteId);
notePath = NodeBaseDAO.getInstance().getPathFromUuid(nBase.getUuid()) + "/" + noteId;
noteUuid = noteId;
NodeNote nNote = NodeNoteDAO.getInstance().findByPk(noteUuid);
note = BaseNoteModule.getProperties(nNote, nNote.getUuid());
// Activity log
UserActivity.log(auth.getName(), "GET_NOTE", noteUuid, notePath, null);
} catch (DatabaseException e) {
throw e;
} finally {
if (token != null) {
PrincipalUtils.setAuthentication(oldAuth);
}
}
log.debug("get: {}", note);
return note;
}
@Override
public String set(String token, String noteId, String text) throws LockException, PathNotFoundException, AccessDeniedException,
RepositoryException, DatabaseException {
log.debug("set({}, {})", token, noteId);
Authentication auth = null, oldAuth = null;
String notePath = null;
String noteUuid = null;
if (Config.SYSTEM_READONLY) {
throw new AccessDeniedException("System is in read-only mode");
}
try {
if (token == null) {
auth = PrincipalUtils.getAuthentication();
} else {
oldAuth = PrincipalUtils.getAuthentication();
auth = PrincipalUtils.getAuthenticationByToken(token);
}
NodeBase nBase = NodeNoteDAO.getInstance().getParentNode(noteId);
notePath = NodeBaseDAO.getInstance().getPathFromUuid(nBase.getUuid()) + "/" + noteId;
noteUuid = noteId;
NodeNote nNote = NodeNoteDAO.getInstance().findByPk(noteUuid);
NodeBase node = NodeNoteDAO.getInstance().getParentNode(noteUuid);
if (auth.getName().equals(nNote.getAuthor())) {
text = FormatUtil.sanitizeInput(text);
nNote.setText(text);
NodeNoteDAO.getInstance().update(nNote);
} else {
throw new AccessDeniedException("Note can only be modified by its creator");
}
// Check subscriptions
BaseNotificationModule.checkSubscriptions(node, auth.getName(), "SET_NOTE", text);
// Activity log
UserActivity.log(auth.getName(), "SET_NOTE", node.getUuid(), notePath, text);
} catch (DatabaseException e) {
throw e;
} finally {
if (token != null) {
PrincipalUtils.setAuthentication(oldAuth);
}
}
log.debug("set: {}", text);
return text;
}
@Override
public List<Note> list(String token, String nodeId) throws AccessDeniedException, PathNotFoundException, RepositoryException,
DatabaseException {
log.debug("list({}, {})", token, nodeId);
List<Note> childs = new ArrayList<Note>();
Authentication auth = null, oldAuth = null;
String nodePath = null;
String nodeUuid = null;
try {
if (token == null) {
auth = PrincipalUtils.getAuthentication();
} else {
oldAuth = PrincipalUtils.getAuthentication();
auth = PrincipalUtils.getAuthenticationByToken(token);
}
if (PathUtils.isPath(nodeId)) {
nodePath = nodeId;
nodeUuid = NodeBaseDAO.getInstance().getUuidFromPath(nodeId);
} else {
nodePath = NodeBaseDAO.getInstance().getPathFromUuid(nodeId);
nodeUuid = nodeId;
}
for (NodeNote nNote : NodeNoteDAO.getInstance().findByParent(nodeUuid)) {
childs.add(BaseNoteModule.getProperties(nNote, nNote.getUuid()));
}
// Activity log
UserActivity.log(auth.getName(), "LIST_NOTES", nodeUuid, nodePath, null);
} catch (DatabaseException e) {
throw e;
} finally {
if (token != null) {
PrincipalUtils.setAuthentication(oldAuth);
}
}
log.debug("list: {}", childs);
return childs;
}
}
| gpl-2.0 |
rcfduarte/nmsat | docs/src/assets/javascripts/components/Material/Source/Adapter/Abstract.js | 3598 | /*
* Copyright (c) 2016-2017 Martin Donath <martin.donath@squidfunk.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
import Cookies from "js-cookie"
/* ----------------------------------------------------------------------------
* Class
* ------------------------------------------------------------------------- */
export default class Abstract {
/**
* Retrieve repository information
*
* @constructor
*
* @property {HTMLAnchorElement} el_ - Link to repository
* @property {string} base_ - API base URL
* @property {number} salt_ - Unique identifier
*
* @param {(string|HTMLAnchorElement)} el - Selector or HTML element
*/
constructor(el) {
const ref = (typeof el === "string")
? document.querySelector(el)
: el
if (!(ref instanceof HTMLAnchorElement))
throw new ReferenceError
this.el_ = ref
/* Retrieve base URL */
this.base_ = this.el_.href
this.salt_ = this.hash_(this.base_)
}
/**
* Retrieve data from Cookie or fetch from respective API
*
* @return {Promise<Array<string>>} Promise that returns an array of facts
*/
fetch() {
return new Promise(resolve => {
const cached = Cookies.getJSON(`${this.salt_}.cache-source`)
if (typeof cached !== "undefined") {
resolve(cached)
/* If the data is not cached in a cookie, invoke fetch and set
a cookie that automatically expires in 15 minutes */
} else {
this.fetch_().then(data => {
Cookies.set(`${this.salt_}.cache-source`, data, { expires: 1 / 96 })
resolve(data)
})
}
})
}
/**
* Abstract private function that fetches relevant repository information
*
* @abstract
*/
fetch_() {
throw new Error("fetch_(): Not implemented")
}
/**
* Format a number with suffix
*
* @param {number} number - Number to format
* @return {string} Formatted number
*/
format_(number) {
if (number > 10000)
return `${(number / 1000).toFixed(0)}k`
else if (number > 1000)
return `${(number / 1000).toFixed(1)}k`
return `${number}`
}
/**
* Simple hash function
*
* Taken from http://stackoverflow.com/a/7616484/1065584
*
* @param {string} str - Input string
* @return {number} Hashed string
*/
hash_(str) {
let hash = 0
if (str.length === 0) return hash
for (let i = 0, len = str.length; i < len; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i)
hash |= 0 // Convert to 32bit integer
}
return hash
}
}
| gpl-2.0 |
facebookexperimental/eden | eden/mononoke/microwave/if/thrift_build.rs | 1910 | // @generated by autocargo
use std::env;
use std::fs;
use std::path::Path;
use thrift_compiler::Config;
#[rustfmt::skip]
fn main() {
// Rerun if this gets rewritten.
println!("cargo:rerun-if-changed=thrift_build.rs");
let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR env not provided");
let out_dir: &Path = out_dir.as_ref();
fs::write(
out_dir.join("cratemap"),
"mercurial_thrift mercurial_thrift
microwave crate
mononoke_types_thrift mononoke_types_thrift",
).expect("Failed to write cratemap");
let conf = {
let mut conf = Config::from_env().expect("Failed to instantiate thrift_compiler::Config");
let path_from_manifest_to_base: &Path = "../../../..".as_ref();
let cargo_manifest_dir =
env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not provided");
let cargo_manifest_dir: &Path = cargo_manifest_dir.as_ref();
let base_path = cargo_manifest_dir
.join(path_from_manifest_to_base)
.canonicalize()
.expect("Failed to canonicalize base_path");
// TODO: replace canonicalize() with std::path::absolute() when
// https://github.com/rust-lang/rust/pull/91673 is available (~Rust 1.60)
// and remove this block.
#[cfg(windows)]
let base_path = Path::new(
base_path
.as_path()
.to_string_lossy()
.trim_start_matches(r"\\?\"),
)
.to_path_buf();
conf.base_path(base_path);
let options = "";
if !options.is_empty() {
conf.options(options);
}
let include_srcs = vec![
];
conf.include_srcs(include_srcs);
conf
};
conf
.run(&[
"microwave.thrift"
])
.expect("Failed while running thrift compilation");
}
| gpl-2.0 |
gunoodaddy/coconut | src/RedisRequest.cpp | 15548 | /*
* Copyright (c) 2012, Eunhyuk Kim(gunoodaddy)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "CoconutLib.h"
#ifdef HAVE_LIBHIREDIS
#include "IOService.h"
#include "RedisRequest.h"
#include "DeferredCaller.h"
#include "Exception.h"
#include "ThreadUtil.h"
#include "InternalLogger.h"
#include "Timer.h"
#include <event2/event.h>
#include <event2/event_compat.h>
#include <event2/event_struct.h>
#if defined(WIN32)
#include <adapters/libevent.h>
#include <async.h>
#else
#include <hiredis/adapters/libevent.h>
#include <hiredis/async.h>
#endif
#define DEFAULT_RECONNECT_TIMEOUT 1000 // unit : msec
#define DEFAULT_CONNECT_TIMEOUT 2000 // unit : msec
namespace coconut {
class RedisRequestImpl : public Timer::EventHandler {
public:
const static int TIMER_ID_RECONNECT = 0x1;
const static int TIMER_ID_CONNECTION_TIMEOUT = 0x3;
const static int TIMER_ID_COMMAND_TTL = 0x5;
enum RedisRequestState {
REDISREQUEST_INIT,
REDISREQUEST_CONNECTING,
REDISREQUEST_CONNECTED,
REDISREQUEST_CONNECTFAILED,
REDISREQUEST_CLOSED,
REDISREQUEST_RECONECTREADY,
};
RedisRequestImpl(RedisRequest *owner,
boost::shared_ptr<IOService> ioService,
const char *host,
int port/*, int timeout*/)
: owner_(owner)
, ioService_(ioService)
, redisContext_(NULL)
, host_(host)
, port_(port)
, state_(REDISREQUEST_INIT)
, timerObj_(NULL)
, deferredCaller_(ioService)
{
_makeTimer();
_LOG_TRACE("RedisRequestImpl() : %p", this);
}
~RedisRequestImpl() {
// TODO redis gracefully close test need..
close(false);
if(timerObj_)
Timer::destroy(timerObj_);
_LOG_TRACE("~RedisRequestImpl() : %p", this);
}
static boost::uint32_t issueTicket() {
static volatile boost::uint32_t s_ticket = 1;
return atomicIncreaseInt32(&s_ticket);
}
boost::shared_ptr<IOService> ioService() {
return ioService_;
}
void close(bool callback = true) {
if(redisContext_) {
if(callback) {
redisContext_->onConnect = NULL;
redisContext_->onDisconnect = NULL;
}
// TODO gracefully async disconnect logic need
// CHECK IT OUT!
redisAsyncFree(redisContext_);
redisContext_ = NULL;
}
state_ = REDISREQUEST_CLOSED;
}
void reconnect() {
_LOG_DEBUG("REDIS RECONNECT START : this = %p", this);
CHECK_IOSERVICE_STOP_VOID_RETURN(ioService_);
state_ = REDISREQUEST_RECONECTREADY;
timerObj_->setTimer(TIMER_ID_RECONNECT, DEFAULT_RECONNECT_TIMEOUT, false);
}
void connect() {
if(redisContext_) {
throw IllegalStateException("Error redisContext already created");
}
state_ = REDISREQUEST_CONNECTING;
ScopedMutexLock(lockRedis_);
redisContext_ = redisAsyncConnect(host_.c_str(), port_);
if (redisContext_->err) {
_LOG_DEBUG("REDIS CONNECT FAILED (CREATE ERROR): %s:%d, err = %x, this = %p"
, host_.c_str(), port_, redisContext_->err, this);
state_ = REDISREQUEST_CONNECTFAILED;
//fire_onRedisRequest_Error(redisContext_->err, "connect error", NULL);
// disconnectCallback() is called later soon..
// error process will be executed by that function.
}
redisContext_->data = this;
redisLibeventAttach(redisContext_, (struct event_base *)ioService_->coreHandle());
redisAsyncSetConnectCallback(redisContext_, connectCallback);
redisAsyncSetDisconnectCallback(redisContext_, disconnectCallback);
timerObj_->setTimer(TIMER_ID_CONNECTION_TIMEOUT, DEFAULT_CONNECT_TIMEOUT, false);
_LOG_DEBUG("redis connect start : %s:%d, flag = 0x%x, fd = %d, context = %p, this = %p"
, host_.c_str(), port_, redisContext_->c.flags, redisContext_->c.fd, redisContext_, this);
}
ticket_t command(const std::string &cmd, const std::string args, RedisRequest::ResponseHandler handler, int timeout = 0) {
int cnt = 0;
size_t pos = 0;
size_t pos2 = 0;
std::string str;
std::vector<std::string> tempArgs;
tempArgs.push_back(cmd);
do {
pos2 = args.find(" ", pos);
str = args.substr(pos, (pos2 - pos));
#define TRIM_SPACE " \t\r\n\v"
str.erase(str.find_last_not_of(TRIM_SPACE)+1);
str.erase(0,str.find_first_not_of(TRIM_SPACE));
if(!str.empty()) {
tempArgs.push_back(str);
}
pos = args.find_first_not_of(" ", pos2);
if(pos == std::string::npos)
break;
cnt++;
} while(true);
return command(tempArgs, handler, timeout);
}
ticket_t command(const std::vector<std::string> &args, RedisRequest::ResponseHandler handler, int timeout = 0) {
ticket_t ticket = issueTicket();
if(timeout > 0) {
timerObj_->setTimer(TIMER_ID_COMMAND_TTL, 1000, true);
}
struct RedisRequest::requestContext context;
context.args = args;
context.ticket = ticket;
context.handler = handler;
context.ttl = timeout > 0 ? timeout : -1;
// for preventing from multithread race condition, must insert to map here..
lockRedis_.lock();
mapCallback_.insert(MapCallback_t::value_type(ticket, context));
lockRedis_.unlock();
if(ioService_->isCalledInMountedThread() == false) {
deferredCaller_.deferredCall(boost::bind(&RedisRequestImpl::_command, this, ticket, args));
return ticket;
}
// must lock here (or deadlock may occur by DeferredCaller's mutex..)
lockRedis_.lock();
_command(ticket, args);
lockRedis_.unlock();
return ticket;
}
void cancel(ticket_t ticket) {
ScopedMutexLock(lockRedis_);
_LOG_DEBUG("redis request canceled : ticket = %d, count = %d/%d <START>"
, ticket, mapCallback_.size(), reservedCommands_.size());
_removeContext(ticket);
_LOG_DEBUG("redis request canceled : ticket = %d, count = %d/%d <END>"
, ticket, mapCallback_.size(), reservedCommands_.size());
}
private:
void _removeContext(ticket_t ticket) {
ScopedMutexLock(lockRedis_);
MapCallback_t::iterator it = mapCallback_.find(ticket);
if(it != mapCallback_.end()) {
mapCallback_.erase(it);
}
VectorReservedContext_t::iterator itR = reservedCommands_.begin();
for(; itR != reservedCommands_.end(); itR++) {
if((*itR).ticket == ticket) {
reservedCommands_.erase(itR);
break;
}
}
}
void _makeTimer() {
if(NULL == timerObj_) {
timerObj_ = Timer::make();
timerObj_->initialize(ioService());
timerObj_->setEventHandler(this);
}
}
void _doCommand(ticket_t ticket, int argc, const char **argv, const size_t *argvlen) {
int ret = redisAsyncCommandArgv(redisContext_, getCallback, (void *)ticket, argc, argv, argvlen);
if(ret != REDIS_OK) {
cancel(ticket);
throw RedisException(ret, "Redis get command failed");
}
}
void _command(ticket_t ticket, const std::vector<std::string> &args) {
ScopedMutexLock(lockRedis_);
if(state_ != REDISREQUEST_CONNECTED) {
struct reservedCommandContext reserved;
reserved.ticket = ticket;
reserved.callback = boost::bind(&RedisRequestImpl::_command, this, ticket, args);
reservedCommands_.push_back(reserved);
_LOG_DEBUG("redis request reserved : redis is not connected.. ticket = %d, cmd = %s, argsize = %d, this = %p"
, (int)ticket, args[0].c_str(), args.size(), this);
return;
}
_LOG_DEBUG("redis request start : cmd = %s, argsize = %d, this = %p", args[0].c_str(), args.size(), this);
std::vector<const char *> tempArgs;
std::vector<size_t> tempArgLens;
for(size_t i = 0; i < args.size(); i++) {
tempArgs.push_back(args[i].c_str());
tempArgLens.push_back(args[i].size());
}
_doCommand(ticket, args.size(), (const char **)&tempArgs[0], (const size_t *)&tempArgLens[0]);
}
const struct RedisRequest::requestContext * _findRequestContext(ticket_t ticket) {
MapCallback_t::iterator it = mapCallback_.find(ticket);
if(it != mapCallback_.end()) {
return &it->second;
}
return NULL;
}
void fire_onRedisRequest_Connected() {
ScopedMutexLock(lockRedis_);
state_ = REDISREQUEST_CONNECTED;
timerObj_->killTimer(TIMER_ID_CONNECTION_TIMEOUT);
_LOG_DEBUG("REDIS CONNECTED : this = %p, fd = %d", this, redisContext_->c.fd);
for(size_t i = 0; i < reservedCommands_.size(); i++) {
reservedCommands_[i].callback(); // call
}
}
void fire_onRedisRequest_ConnectFailed() {
ScopedMutexLock(lockRedis_);
state_ = REDISREQUEST_CONNECTFAILED;
timerObj_->killTimer(TIMER_ID_CONNECTION_TIMEOUT);
fire_onRedisRequest_Error(redisContext_->err, redisContext_->errstr, NULL);
// hiredis lib will free my redisContext_ internally..
// MUST be set NULL
redisContext_ = NULL;
reconnect();
_LOG_DEBUG("REDIS CONNECT FAILED : this = %p, context = %p", this, redisContext_);
}
void fire_onRedisRequest_Closed(int status) {
// CAUTION!
// NEVER ACCESS redisContext_ HERE!!!!
// redisContext_ can be NULL already!
ScopedMutexLock(lockRedis_);
_LOG_DEBUG("REDIS CLOSED : %p", this);
state_ = REDISREQUEST_CLOSED;
// hiredis lib will free my redisContext_ internally..
// MUST be set NULL
redisContext_ = NULL;
reconnect();
}
void fire_onRedisRequest_Error(int error, const char *strerror, void *privdata) {
if(privdata) {
ticket_t ticket = (ticket_t)privdata;
const struct RedisRequest::requestContext *context = _findRequestContext(ticket);
if(context) {
boost::shared_ptr<RedisResponse> res(new RedisResponse(error, strerror, ticket));
context->handler(context, res);
_removeContext(ticket);
}
}
}
void fire_onRedisRequest_Response(redisReply *reply, void *privdata) {
ScopedMutexLock(lockRedis_);
ticket_t ticket = (ticket_t)privdata;
boost::shared_ptr<RedisResponse> res(new RedisResponse(reply, ticket));
const struct RedisRequest::requestContext *context = _findRequestContext(ticket);
if(context) {
context->handler(context, res);
_removeContext(ticket);
}
}
// Timer callback
private:
void setState(RedisRequestState state) {
state_ = state;
}
void onTimer_Timer(int id) {
switch(id) {
case TIMER_ID_CONNECTION_TIMEOUT:
if(redisContext_) {
LOG_DEBUG("REDIS CONNECT TIMEOUT : this = %p, context = %p, status = %x/%x, fd = %d\n"
, this, redisContext_, redisContext_->err, redisContext_->c.flags, redisContext_->c.fd);
// for preventing <RACE CONDITION> (not thread issue, but hiredis async disconnect logic problem)
// MUST RESET fd value..
redisContext_->c.fd = COOKIE_INVALID_SOCKET;
redisAsyncDisconnect(redisContext_);
redisContext_ = NULL;
state_ = REDISREQUEST_CLOSED;
reconnect();
} else {
reconnect();
}
break;
case TIMER_ID_RECONNECT:
assert(redisContext_ == NULL && "redisContext_ MUST be freed before reconnect()");
connect();
break;
case TIMER_ID_COMMAND_TTL:
{
ScopedMutexLock(lockRedis_);
std::list<ticket_t> cancelList;
bool needThisTimer = false;
MapCallback_t::iterator it = mapCallback_.begin();
for(; it != mapCallback_.end(); it++) {
if(it->second.ttl > 0) {
LOG_TRACE("REDIS COMMAND TTL CHECK : this = %p, ticket = %d, ttl = %d\n"
, this, (int)it->second.ticket, it->second.ttl);
if(--it->second.ttl <= 0) {
cancelList.push_back(it->second.ticket);
}
needThisTimer = true;
}
}
if(!needThisTimer) {
timerObj_->killTimer(id);
}
if(cancelList.size() > 0) {
std::list<ticket_t>::iterator itL = cancelList.begin();
for( ; itL != cancelList.end(); itL++) {
fire_onRedisRequest_Error(REDIS_ERR_OTHER, "timeout", (void *)(*itL));
cancel(*itL);
}
}
break;
}
}
}
// redis callback
private:
#if defined(WIN32)
static void connectCallback(const redisAsyncContext *c) {
#else
static void connectCallback(const redisAsyncContext *c, int status) {
#endif
RedisRequestImpl *SELF = (RedisRequestImpl *)c->data;
#if ! defined(WIN32)
if (status != REDIS_OK) {
SELF->fire_onRedisRequest_ConnectFailed();
return;
}
#endif
SELF->fire_onRedisRequest_Connected();
}
static void disconnectCallback(const redisAsyncContext *c, int status) {
RedisRequestImpl *SELF = (RedisRequestImpl *)c->data;
SELF->fire_onRedisRequest_Closed(status);
}
static void getCallback(redisAsyncContext *c, void *r, void *privdata) {
RedisRequestImpl *SELF = (RedisRequestImpl *)c->data;
redisReply *reply = (redisReply *)r;
if (reply == NULL) {
SELF->fire_onRedisRequest_Error(c->err, c->errstr, privdata);
return;
}
SELF->fire_onRedisRequest_Response(reply, privdata);
}
private:
RedisRequest *owner_;
boost::shared_ptr<IOService> ioService_;
redisAsyncContext *redisContext_;
std::string host_;
int port_;
Mutex lockRedis_;
RedisRequestState state_;
typedef std::map<ticket_t, struct RedisRequest::requestContext> MapCallback_t;
MapCallback_t mapCallback_;
Timer *timerObj_;
// thread sync call method
DeferredCaller deferredCaller_;
struct reservedCommandContext {
ticket_t ticket;
DeferredCaller::deferredMethod_t callback;
};
typedef std::vector<struct reservedCommandContext> VectorReservedContext_t;
VectorReservedContext_t reservedCommands_;
};
//---------------------------------------------------------------------------------------------------------------
RedisRequest::RedisRequest(boost::shared_ptr<IOService> ioService, const char *host, int port/*, int timeout*/) {
impl_ = new RedisRequestImpl(this, ioService, host, port);
_LOG_TRACE("RedisRequest() : %p", this);
}
RedisRequest::~RedisRequest() {
_LOG_TRACE("~RedisRequest() : %p", this);
delete impl_;
}
boost::shared_ptr<IOService> RedisRequest::ioService() {
return impl_->ioService();
}
void RedisRequest::connect() {
impl_->connect();
}
void RedisRequest::close() {
impl_->close();
}
void RedisRequest::cancel(ticket_t ticket) {
impl_->cancel(ticket);
}
ticket_t RedisRequest::command(const std::string &cmd,
const std::string args,
RedisRequest::ResponseHandler handler,
int timeout)
{
return impl_->command(cmd, args, handler, timeout);
}
ticket_t RedisRequest::command(const std::vector<std::string> &args,
ResponseHandler handler,
int timeout)
{
return impl_->command(args, handler, timeout);
}
}
#endif
| gpl-2.0 |
Teness/BreakServer | test/functional/tasks_controller_test.rb | 1145 | require 'test_helper'
class TasksControllerTest < ActionController::TestCase
setup do
@task = tasks(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:tasks)
end
test "should get new" do
get :new
assert_response :success
end
test "should create task" do
assert_difference('Task.count') do
post :create, task: { level: @task.level, map_id: @task.map_id, name: @task.name, status: @task.status, type: @task.type }
end
assert_redirected_to task_path(assigns(:task))
end
test "should show task" do
get :show, id: @task
assert_response :success
end
test "should get edit" do
get :edit, id: @task
assert_response :success
end
test "should update task" do
put :update, id: @task, task: { level: @task.level, map_id: @task.map_id, name: @task.name, status: @task.status, type: @task.type }
assert_redirected_to task_path(assigns(:task))
end
test "should destroy task" do
assert_difference('Task.count', -1) do
delete :destroy, id: @task
end
assert_redirected_to tasks_path
end
end
| gpl-2.0 |
Dr-Shadow/android_kernel_acer_c10 | mediatek/platform/mt6577/hardware/camera/hal/CamAdapter/mHal/mHalCamAdapter.cpp | 99712 | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
/*
**
** Copyright 2008, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#define LOG_TAG "MtkCam/MCamHw"
//
#include <cutils/atomic.h>
#include <cutils/properties.h>
//
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/prctl.h>
#include <fcntl.h>
#include <pthread.h>
#include <linux/rtpm_prio.h>
#include <sched.h>
#include <unistd.h>
#include <sys/resource.h>
//
#include "Utils/inc/CamUtils.h"
using namespace android;
using namespace MtkCamUtils;
//
#include "inc/ICamAdapter.h"
#include "inc/BaseCamAdapter.h"
#include "inc/mHalBaseAdapter.h"
#include "inc/mHalCamAdapter.h"
#include "mHalCamCmdQueThread.h"
#include "./mHalCamImage.h"
#include "./mHalCamUtils.h"
//
#include "ClientCallback/inc/EventCallback.h"
//
#include <camera_feature.h>
using namespace NSFeature;
//
#include <mhal/inc/MediaHal.h>
#include <mhal/inc/camera.h>
#include <mhal/inc/camera/ioctl.h>
using namespace NSCamera;
#define mHalIoCtrl "[Warning] Please replace mHalIoCtrl with mHalIoctl"
#define MDP_NEW_PATH_FOR_ZSD
/******************************************************************************
*
*******************************************************************************/
#define MY_LOGV(fmt, arg...) CAM_LOGV("(%s)[mHalCamAdapter::%s] "fmt, getName(), __FUNCTION__, ##arg)
#define MY_LOGD(fmt, arg...) CAM_LOGD("(%s)[mHalCamAdapter::%s] "fmt, getName(), __FUNCTION__, ##arg)
#define MY_LOGI(fmt, arg...) CAM_LOGI("(%s)[mHalCamAdapter::%s] "fmt, getName(), __FUNCTION__, ##arg)
#define MY_LOGW(fmt, arg...) CAM_LOGW("(%s)[mHalCamAdapter::%s] "fmt, getName(), __FUNCTION__, ##arg)
#define MY_LOGE(fmt, arg...) CAM_LOGE("(%s)[mHalCamAdapter::%s] "fmt, getName(), __FUNCTION__, ##arg)
//
#define MY_LOGV_IF(cond, arg...) if (cond) { MY_LOGV(arg); }
#define MY_LOGD_IF(cond, arg...) if (cond) { MY_LOGD(arg); }
#define MY_LOGI_IF(cond, arg...) if (cond) { MY_LOGI(arg); }
#define MY_LOGW_IF(cond, arg...) if (cond) { MY_LOGW(arg); }
#define MY_LOGE_IF(cond, arg...) if (cond) { MY_LOGE(arg); }
/*******************************************************************************
*
********************************************************************************/
#define MTKCAM_CAP_PROFILE_OPT 1
#define MTKCAM_VDO_PROFILE_OPT 0
#define FILE_SAVE_WAIT (1)
namespace NSCamCustom
{
extern MUINT32 isSupportJpegOrientation();
}
/******************************************************************************
*
*******************************************************************************/
namespace android {
/******************************************************************************
*
*******************************************************************************/
MTKCameraHardware::MTKCameraHardware(String8 const& rName, int32_t const i4OpenId, CamDevInfo const& rDevInfo)
: mHalBaseAdapter(rName, i4OpenId, rDevInfo),
//
mu4ShotMode(MHAL_CAM_CAP_MODE_UNKNOWN),
//
meCamState(eCS_Init),
mStateLock(),
mStateCond(),
//
mmHalCamParam(),
mIsPreviewEnabled(false),
mIsVideoEnabled(false),
//
mZoomValue(0),
mZoomStopValue(0),
mIsSmoothZoom(false),
mIsSmoothZoomCBEnabled(false),
//
mIsDisplay(false),
//
mIsCancelPicture(false),
//
mIsATV(false),
mIsTakePrv(false),
mIsATVDelay(false),
mATVDispBufNo(0),
mATVStartTime(0),
mATVbuffers(),
mAtvDispDelay(0),
pushindex(0),
popindex(0),
//
mPanoW(0),
mPanoH(0),
mPanoNum(0),
mstrobeMode(-1),
mCurFramerate(30),
//
mIsZSD(0),
//
mDispBufNo(0),
//
mParameters(),
mFeatureParam(),
//
mPreviewMemPool(),
mQvMemPool(),
mJpegMemPool(),
mVideoMemPool(),
mPrvRgbMemPool(),
mPrvJpegMemPool(),
mPanoMemPool(),
//
mi4PreviewWidth(0),
mi4PreviewHeight(0),
mSemPrv(),
mbPreviewThreadAlive(false),
mPreviewThreadHandle(0),
//
maVdoCbBufNo(),
maVdoTimStampNs(),
miVdoInIndex(0),
miVdoOutIndex(0),
mSemVdo(),
mbVideoThreadAlive(0),
mVideoThreadHandle(0),
//
mpMainThread(NULL),
//
mEventCallback(NULL),
//
mSemTakePicBack(),
//
mIsAFMoveCallback(0),
//
mFocusStartTime(0),
mCaptureStartTime(0),
mFocusCallbackTime(0),
mShutterCallbackTime(0),
mRawCallbackTime(0),
mJpegCallbackTime(0)
{
::memset(&mmHalCamParam, 0, sizeof(mhalCamParam_t));
//
::sem_init(&mSemPrv, 0, 0);
::sem_init(&mSemVdo, 0, 0);
::sem_init(&mSemTakePicBack, 0, 0);
}
/******************************************************************************
*
*******************************************************************************/
MTKCameraHardware::~MTKCameraHardware()
{
}
/******************************************************************************
*
*******************************************************************************/
void
MTKCameraHardware::
mhalCallback(void* param)
{
mHalCamCBInfo*const pCBInfo = reinterpret_cast<mHalCamCBInfo*>(param);
if ( ! pCBInfo ) {
CAM_LOGW("[mHalCamAdapter::mhalCallback] NULL pCBInfo");
return;
}
//
mHalCamAdapter*const pmHalCamAdapter = reinterpret_cast<mHalCamAdapter*>(pCBInfo->mCookie);
if ( ! pmHalCamAdapter ) {
CAM_LOGW("[mHalCamAdapter::mhalCallback] NULL pmHalCamAdapter");
return;
}
//
pmHalCamAdapter->dispatchCallback(pCBInfo);
}
/******************************************************************************
*
*******************************************************************************/
void
MTKCameraHardware::
shotCallback(void* param)
{
mHalCamCBInfo*const pCBInfo = reinterpret_cast<mHalCamCBInfo*>(param);
if ( ! pCBInfo ) {
CAM_LOGW("[mHalCamAdapter::shotCallback] NULL pCBInfo");
return;
}
//
mHalCamAdapter*const pmHalCamAdapter = reinterpret_cast<mHalCamAdapter*>(pCBInfo->mCookie);
if ( ! pmHalCamAdapter ) {
CAM_LOGW("[mHalCamAdapter::shotCallback] NULL pmHalCamAdapter");
return;
}
//
pmHalCamAdapter->dispatchCallback(pCBInfo);
}
/******************************************************************************
*
*******************************************************************************/
void
MTKCameraHardware::
dispatchCallback(void*const param)
{
mHalCamCBInfo*const pinfo = reinterpret_cast<mHalCamCBInfo*>(param);
//
MUINT32 const u4Type = pinfo->mType;
void*const pvData = pinfo->mpData;
MUINT32 const u4Size = pinfo->mDataSize;
//
//
switch (u4Type) {
case MHAL_CAM_CB_ATV_DISP:
if (mIsATV && !mIsATVDelay) {
sem_post(&mSemPrv);
//trick log mATVbuffers[pushindex-1], add (pushindex-1+12)%12
CAM_LOGD(" mATVpreviewCallback : in %d , out %d\n", mATVbuffers[(pushindex+11)%12],mATVbuffers[popindex-1]);
if (popindex >= (int)mPreviewMemPool->getBufCount()) {
popindex -= (int)mPreviewMemPool->getBufCount();
}
}
break;
case MHAL_CAM_CB_PREVIEW:
// preview callback
previewCallback(pvData);
break;
case MHAL_CAM_CB_VIDEO_RECORD:
// video callback
videoRecordCallback(pvData);
break;
case MHAL_CAM_CB_AF:
if (mMsgEnabled & CAMERA_MSG_FOCUS) {
CAM_LOGD("[dispatchCallback] MHAL_CAM_CB_AF \n");
#if (MTKCAM_CAP_PROFILE_OPT)
mFocusCallbackTime = getTimeMs();
#endif
// focus callback
MINT32 *pbuf = (MINT32 *) pvData;
MBOOL isFocused = (MBOOL)pbuf[0];
uint32_t const u4AfDataSize = pbuf[1];
uint32_t const u4DataSize = u4AfDataSize + sizeof(uint32_t)*(1);
camera_memory_t mem;
if ( mpBufProvider->allocBuffer(mem, u4DataSize, 1) )
{
if ( mem.data && u4DataSize <= mem.size )
{
uint32_t*const pCBData = reinterpret_cast<uint32_t*>(mem.data);
pCBData[0] = MTK_CAMERA_MSG_EXT_DATA_AF;
for(uint_t i = 0; i < u4AfDataSize/4; ++i)
{
pCBData[i+1] = reinterpret_cast<uint32_t*>(pbuf)[i+2];
}
mDataCb(MTK_CAMERA_MSG_EXT_DATA, &mem, 0, NULL, mCallbackCookie);
}
mpBufProvider->freeBuffer(mem);
}
mNotifyCb(CAMERA_MSG_FOCUS, isFocused, 0, mCallbackCookie);
}
break;
case MHAL_CAM_CB_AF_MOVE:
{
// focus callback
MUINT32 isFocusMoving = *(MUINT32 *) pvData;
if (mIsAFMoveCallback)
{
mNotifyCb(CAMERA_MSG_FOCUS_MOVE, isFocusMoving, 0, mCallbackCookie);
}
}
break;
case MHAL_CAM_CB_ZOOM:
{
mhalZsdParam_t* pzsd = (mhalZsdParam_t*)pvData;
if ( (0 !=(mMsgEnabled & CAMERA_MSG_ZOOM)) && (mIsSmoothZoomCBEnabled) ) {
CAM_LOGD("[dispatchCallback] MHAL_CAM_CB_ZOOM \n");
mNotifyCb(CAMERA_MSG_ZOOM, mZoomValue, mZoomValue == mZoomStopValue, mCallbackCookie);
// The final zoom.
if ( mZoomValue == mZoomStopValue ){
mIsSmoothZoomCBEnabled = false;
mIsSmoothZoom = false;
}
}
if (pzsd->u4ZsdEnable == 0x1){
mmHalCamParam.camZsdParam.u4ZsdZoomWidth = pzsd->u4ZsdZoomWidth;
mmHalCamParam.camZsdParam.u4ZsdZoomHeigth = pzsd->u4ZsdZoomHeigth;
}
}
break;
//
case MHAL_CAM_CB_SHUTTER:
if (mMsgEnabled & CAMERA_MSG_SHUTTER) {
CAM_LOGD("[dispatchCallback] MHAL_CAM_CB_SHUTTER");
#if (MTKCAM_CAP_PROFILE_OPT)
mShutterCallbackTime = getTimeMs();
#endif
//
switch (mu4ShotMode) {
case MHAL_CAM_CAP_MODE_EV_BRACKET:
case MHAL_CAM_CAP_MODE_BURST_SHOT:
mNotifyCb(
MTK_CAMERA_MSG_EXT_NOTIFY, MTK_CAMERA_MSG_EXT_NOTIFY_BURST_SHUTTER,
( mmHalCamParam.u4BusrtCnt - 1 - mmHalCamParam.u4BusrtNo ),
mCallbackCookie
);
break;
//
case MHAL_CAM_CAP_MODE_CONTINUOUS_SHOT:
mNotifyCb(
MTK_CAMERA_MSG_EXT_NOTIFY, MTK_CAMERA_MSG_EXT_NOTIFY_CONTINUOUS_SHUTTER,
mmHalCamParam.u4BusrtNo+1,
mCallbackCookie
);
break;
default:
mNotifyCb(CAMERA_MSG_SHUTTER, 0, 0, mCallbackCookie);
break;
}
}
break;
//
case MHAL_CAM_CB_RAW:
CAM_LOGD("[dispatchCallback] MHAL_CAM_CB_RAW - (BusrtCnt,BusrtNo)=(%d,%d)", mmHalCamParam.u4BusrtCnt, mmHalCamParam.u4BusrtNo);
#if (MTKCAM_CAP_PROFILE_OPT)
mRawCallbackTime = getTimeMs();
#endif
//
if ( 1 + mmHalCamParam.u4BusrtNo == mmHalCamParam.u4BusrtCnt )
{
if ( msgTypeEnabled(CAMERA_MSG_RAW_IMAGE_NOTIFY) ) {
CAM_LOGD("CAMERA_MSG_RAW_IMAGE_NOTIFY");
mNotifyCb(CAMERA_MSG_RAW_IMAGE_NOTIFY, 0, 0, mCallbackCookie);
}
else if ( msgTypeEnabled(CAMERA_MSG_RAW_IMAGE) ) {
CAM_LOGD("CAMERA_MSG_RAW_IMAGE");
camera_memory_t dummyRaw;
if ( mpBufProvider->allocBuffer(dummyRaw, 1, 1) )
{
mDataCb(CAMERA_MSG_RAW_IMAGE, &dummyRaw, 0, NULL, mCallbackCookie);
mpBufProvider->freeBuffer(dummyRaw);
}
}
}
break;
//
case MHAL_CAM_CB_POSTVIEW:
CAM_LOGD("[dispatchCallback] MHAL_CAM_CB_POSTVIEW");
postBuffer(mQvMemPool, 0, 0, CAMERA_MSG_POSTVIEW_FRAME);
break;
//
case MHAL_CAM_CB_JPEG:
//
if (mmHalCamParam.u4IsDumpRaw) {
mhalCamRawImageInfo_t rawInfo;
memset(&rawInfo, 0, sizeof(mhalCamRawImageInfo_t));
MINT32 mode = 0;
if (mParameters.getInt(MtkCameraParameters::KEY_RAW_SAVE_MODE) == 1) {//preview
mode = 1;
}
LOGD("[EM] mode: %d", mode);
::mHalIoctl(mmHalFd, MHAL_IOCTL_GET_RAW_IMAGE_INFO, &mode, sizeof(int), &rawInfo, sizeof(mhalCamRawImageInfo_t), NULL);
saveUnpackRaw((char *)mmHalCamParam.u1FileName,
rawInfo.u4Width,
rawInfo.u4Height,
rawInfo.u4BitDepth,
rawInfo.u1Order,
rawInfo.u4Size,
rawInfo.u4IsPacked
);
}
//
if ( msgTypeEnabled(CAMERA_MSG_COMPRESSED_IMAGE) ) {
//
uint32_t const jpegSize = u4Size;
//
CAM_LOGD("[dispatchCallback] MHAL_CAM_CB_JPEG - size(%d)", jpegSize);
#if (MTKCAM_CAP_PROFILE_OPT)
mJpegCallbackTime = getTimeMs();
MY_LOGD("MCamHw-pn", "***Callback time, %8lld, %8lld, %8lld, %8lld, %8lld, %8lld",
mFocusStartTime, mFocusCallbackTime, mCaptureStartTime, mShutterCallbackTime,
mRawCallbackTime, mJpegCallbackTime );
CAM_LOGD("***Callback time, %8lld, %8lld, %8lld, %8lld, %8lld ",
mFocusCallbackTime - mFocusStartTime, mCaptureStartTime - mFocusCallbackTime,
mShutterCallbackTime - mCaptureStartTime, mRawCallbackTime - mShutterCallbackTime,
mJpegCallbackTime - mRawCallbackTime );
#endif
/*
* Notes:
* jpegSize and the size of mJpegMemPool are different, so we cannot
* directly invoke a data callback with mJpegMemPool.
*/
switch (mu4ShotMode)
{
case MHAL_CAM_CAP_MODE_EV_BRACKET:
case MHAL_CAM_CAP_MODE_BURST_SHOT:
// case MHAL_CAM_CAP_MODE_NORMAL:
{
uint32_t const u4DataSize = jpegSize + sizeof(uint32_t)*(1+2);
camera_memory_t mem;
if ( mpBufProvider->allocBuffer(mem, u4DataSize, 1) )
{
if ( mem.data && u4DataSize == mem.size )
{
uint32_t*const pCBData = reinterpret_cast<uint32_t*>(mem.data);
pCBData[0] = MTK_CAMERA_MSG_EXT_DATA_BURST_SHOT;
pCBData[1] = mmHalCamParam.u4BusrtCnt;
pCBData[2] = ( mmHalCamParam.u4BusrtCnt - 1 - mmHalCamParam.u4BusrtNo );
::memcpy((void*)(&pCBData[3]), (void*)mJpegMemPool->getVirAddr(), jpegSize);
//
mDataCb(MTK_CAMERA_MSG_EXT_DATA, &mem, 0, NULL, mCallbackCookie);
}
mpBufProvider->freeBuffer(mem);
}
}
break;
case MHAL_CAM_CAP_MODE_CONTINUOUS_SHOT:
{
uint32_t const u4DataSize = jpegSize + sizeof(uint32_t)*(1+1);
camera_memory_t mem;
if ( mpBufProvider->allocBuffer(mem, u4DataSize, 1) )
{
if ( mem.data && u4DataSize == mem.size )
{
uint32_t*const pCBData = reinterpret_cast<uint32_t*>(mem.data);
pCBData[0] = MTK_CAMERA_MSG_EXT_DATA_CONTINUOUS_SHOT;
pCBData[1] = mmHalCamParam.u4BusrtNo+1;
::memcpy((void*)(&pCBData[2]), (void*)mJpegMemPool->getVirAddr(), jpegSize);
//
mDataCb(MTK_CAMERA_MSG_EXT_DATA, &mem, 0, NULL, mCallbackCookie);
}
mpBufProvider->freeBuffer(mem);
}
}
break;
default:
{
sp<IMemoryBufferPool> jpegMemPool = allocMem(jpegSize, 1, "jpeg callback");
if ( jpegMemPool != NULL )
{
::memcpy((void*)jpegMemPool->getVirAddr(), (void*)mJpegMemPool->getVirAddr(), jpegSize);
mDataCb(CAMERA_MSG_COMPRESSED_IMAGE, jpegMemPool->get_camera_memory(), 0, NULL, mCallbackCookie);
jpegMemPool = NULL;
}
}
break;
}
}
break;
//
case MHAL_CAM_CB_CAPTURE_DONE:
CAM_LOGD("[dispatchCallback] MHAL_CAM_CB_CAPTURE_DONE");
::sem_post(&mSemTakePicBack);
CAM_LOGD(" - post mSemTakePicBack\n");
break;
//
case MHAL_CAM_CB_MAV:
CAM_LOGD("[dispatchCallback] MTK_CAMERA_MSG_EXT_NOTIFY_MAV");
mNotifyCb(MTK_CAMERA_MSG_EXT_NOTIFY, MTK_CAMERA_MSG_EXT_NOTIFY_MAV, 0, mCallbackCookie);
break;
case MHAL_CAM_CB_AUTORAMA:
{
CAM_LOGD("[dispatchCallback] MHAL_CAM_CB_AUTORAMA \n");
//
uint32_t const u4DataSize = sizeof(uint32_t)*(1+3);
//
camera_memory_t mem;
if ( mpBufProvider->allocBuffer(mem, u4DataSize, 1) )
{
if ( mem.data && u4DataSize <= mem.size )
{
uint32_t*const pCBData = reinterpret_cast<uint32_t*>(mem.data);
pCBData[0] = MTK_CAMERA_MSG_EXT_DATA_AUTORAMA;
pCBData[1] = 1;//(MHAL_CAM_CB_AUTORAMA == pcbParam->type);
pCBData[2] = reinterpret_cast<uint32_t*>(pvData)[0];
pCBData[3] = reinterpret_cast<uint32_t*>(pvData)[1];
//
if (pCBData[2])
mNotifyCb(CAMERA_MSG_SHUTTER, 0, 0, mCallbackCookie);
mDataCb(MTK_CAMERA_MSG_EXT_DATA, &mem, 0, NULL, mCallbackCookie);
}
mpBufProvider->freeBuffer(mem);
}
}
break;
case MHAL_CAM_CB_AUTORAMAMV:
{
CAM_LOGD("[dispatchCallback] MHAL_CAM_CB_AUTORAMAMV");
//
uint32_t const u4DataSize = sizeof(uint32_t)*(1+4);
//
camera_memory_t mem;
if ( mpBufProvider->allocBuffer(mem, u4DataSize, 1) )
{
if ( mem.data && u4DataSize <= mem.size )
{
uint32_t*const pData = reinterpret_cast<uint32_t*>(pvData);
uint32_t*const pCBData = reinterpret_cast<uint32_t*>(mem.data);
pCBData[0] = MTK_CAMERA_MSG_EXT_DATA_AUTORAMA;
pCBData[1] = 0;//(MHAL_CAM_CB_AUTORAMAMV == pcbParam->type);
pCBData[2] = pData[0];
pCBData[3] = pData[1];
pCBData[4] = pData[2];
//
mDataCb(MTK_CAMERA_MSG_EXT_DATA, &mem, 0, NULL, mCallbackCookie);
}
mpBufProvider->freeBuffer(mem);
}
}
break;
case MHAL_CAM_CB_SCALADO:{
uint8_t * addr;
int capW,capH;
CAM_LOGD("[dispatchCallback] MHAL_CAM_CB_SCALADO start\n");
mParameters.getPictureSize(&capW, &capH);
addr = (uint8_t *)pvData;
//saveBufToFile((char *) pcapFName, addr, capW*capH*2);
}
CAM_LOGD("[dispatchCallback] MHAL_CAM_CB_SCALADO done\n");
break;
case MHAL_CAM_CB_ASD:
{
MUINT32 const u4Scene = *reinterpret_cast<MUINT32*>(pvData);
CAM_LOGD("[dispatchCallback] MTK_CAMERA_MSG_EXT_NOTIFY_ASD:Scene = %d", u4Scene);
mNotifyCb(MTK_CAMERA_MSG_EXT_NOTIFY, MTK_CAMERA_MSG_EXT_NOTIFY_ASD, u4Scene, mCallbackCookie);
}
break;
case MHAL_CAM_CB_FD:
{
if (msgTypeEnabled(CAMERA_MSG_PREVIEW_METADATA)) {
CAM_LOGD("[dispatchCallback]MHAL_CAM_CB_FD +");
if (mEventCallback != 0) {
mEventCallback->setDataCallback(mDataCb);
mEventCallback->setBufferProvider(mpBufProvider);
mEventCallback->setDataBuf(
CAMERA_MSG_PREVIEW_METADATA,
NULL,
0,
pvData,
mCallbackCookie
);
}
}
}
break;
case MHAL_CAM_CB_SMILE:
if (msgTypeEnabled(CAMERA_MSG_PREVIEW_METADATA)) {
CAM_LOGD("[dispatchCallback] MTK_CAMERA_MSG_EXT_NOTIFY_SMILE_DETECT +");
if (mEventCallback != 0) {
mEventCallback->setNotifyCallback(mNotifyCb);
mEventCallback->setNotifyBuf(
MTK_CAMERA_MSG_EXT_NOTIFY,
MTK_CAMERA_MSG_EXT_NOTIFY_SMILE_DETECT,
0,
mCallbackCookie
);
}
}
break;
case MHAL_CAM_CB_ERR:
{
MUINT32 const msg = *reinterpret_cast<MUINT32*>(pvData);
mNotifyCb(CAMERA_MSG_ERROR, msg, 0, mCallbackCookie); // no memory callback to AP.
}
break;
case MHAL_CAM_CB_VSS_JPG_ENC:
{
CAM_LOGD("[dispatchCallback]VSS:MHAL_CAM_CB_VSS_JPG_ENC");
if(msgTypeEnabled(CAMERA_MSG_COMPRESSED_IMAGE))
{
mhalVSSJpgEncParam_t* pVSSJpgEncParam = (mhalVSSJpgEncParam_t*)pvData;
// use sw to compress rgb565 to jpeg
CAM_LOGD("[dispatchCallback]VSS:JPG:RgbAddr(0x%08X),YuvAddr(0x%08X),JpgAddr(0x%08X),W(%d),H(%d)",
pVSSJpgEncParam->u4ImgRgbVirAddr,
pVSSJpgEncParam->u4ImgYuvVirAddr,
pVSSJpgEncParam->u4ImgJpgVirAddr,
pVSSJpgEncParam->u4ImgWidth,
pVSSJpgEncParam->u4ImgHeight);
if(pVSSJpgEncParam->u4ImgYuvVirAddr != 0)
{
CAM_LOGD("[dispatchCallback]VSS:YUV2RGB");
::hwConvertImageFormat(
(uint8_t*)pVSSJpgEncParam->u4ImgYuvVirAddr,
MHAL_FORMAT_YUV_420,
pVSSJpgEncParam->u4ImgWidth,
pVSSJpgEncParam->u4ImgHeight,
(uint8_t*)pVSSJpgEncParam->u4ImgRgbVirAddr,
MHAL_FORMAT_RGB_565);
}
CAM_LOGD("[dispatchCallback]VSS:RGB2JPG");
::rgb565toJpeg(
(uint8_t*)(pVSSJpgEncParam->u4ImgRgbVirAddr),
(uint8_t*)(pVSSJpgEncParam->u4ImgJpgVirAddr),
pVSSJpgEncParam->u4ImgWidth,
pVSSJpgEncParam->u4ImgHeight,
&(pVSSJpgEncParam->u4ImgJpgSize));
CAM_LOGD("[dispatchCallback]VSS:JPG:Size(%d)",pVSSJpgEncParam->u4ImgJpgSize);
}
else
{
CAM_LOGE("[dispatchCallback]CAMERA_MSG_COMPRESSED_IMAGE is not enabled");
}
break;
}
case MHAL_CAM_CB_VSS_JPG:
{
CAM_LOGD("[dispatchCallback]VSS:MHAL_CAM_CB_VSS_JPG");
if(msgTypeEnabled(CAMERA_MSG_COMPRESSED_IMAGE))
{
sp<IMemoryBufferPool> jpegMemPool = allocMem(
u4Size,
1,
"VSS jpeg callback");
CAM_LOGD("[dispatchCallback]VSS:JPG:SrcAddr(0x%08X),DstAddr(0x%08X),Size(%d)",
(MUINT32)pvData,
jpegMemPool->getVirAddr(),
u4Size);
::memcpy(
(void*)jpegMemPool->getVirAddr(),
pvData,
u4Size);
//
CAM_LOGD("[dispatchCallback]VSS:Jpg callback E");
mDataCb(CAMERA_MSG_COMPRESSED_IMAGE, jpegMemPool->get_camera_memory(), 0, NULL, mCallbackCookie);
CAM_LOGD("[dispatchCallback]VSS:Jpg callback X");
}
else
{
CAM_LOGE("[dispatchCallback]CAMERA_MSG_COMPRESSED_IMAGE is not enabled");
}
}
break;
case MHAL_CAM_CB_FLASHON:
{
CAM_LOGD("[dispatchCallback]MHAL_CAM_CB_FLASHON\n");
mIsZSD = 0;
mmHalCamParam.u4strobeon = 1;
}
break;
case MHAL_CAM_CB_ZSD_PREVIEW_DONE:
{
CAM_LOGD("[dispatchCallback]ZSD:preview done");
mNotifyCb(MTK_CAMERA_MSG_EXT_NOTIFY, MTK_CAMERA_MSG_EXT_NOTIFY_ZSD_PREVIEW_DONE, 0, mCallbackCookie); // no memory callback to AP.
}
break;
default:
CAM_LOGD("[dispatchCallback] Unsupported \n");
break;
} // end of switch
}
/*******************************************************************************
*
********************************************************************************/
void* MTKCameraHardware::_previewThread(void* arg)
{
::prctl(PR_SET_NAME,"Camera@Preview",0,0,0);
//
// thread policy & priority
int policy = 0, priority = 0;
getPriority(policy, priority);
CAM_LOGD("[mHalCamAdapter::_previewThread] (tid, policy, priority)=(%d, %d, %d)", ::gettid(), policy, priority);
// detach thread
::pthread_detach(::pthread_self());
//
MTKCameraHardware*const pHardware = reinterpret_cast<MTKCameraHardware*>(arg);
if ( ! pHardware )
{
CAM_LOGE("[mHalCamAdapter::_previewThread] NULL arg");
return NULL;
}
return ( eDevId_AtvSensor == pHardware->getDevId() )
? pHardware->mAtvPreviewThread()
: pHardware->cameraPreviewThread()
;
}
/******************************************************************************
*
*******************************************************************************/
void*
MTKCameraHardware::
mAtvPreviewThread()
{
MY_LOGD("+ tid(%d), mbPreviewThreadAlive(%d)", ::gettid(), mbPreviewThreadAlive);
//
while (mbPreviewThreadAlive)
{
::sem_wait(&mSemPrv);
if ( ! mbPreviewThreadAlive )
{
break;
}
//
// After sleep, CamAdapter object (& memory) could be deleted and freed,
// so that de-reference bad object will cause exception.
// And hence, we firstly hold a strong pointer before sleep.
sp<ICamAdapter> pThis = this;
//
//to resolve matv desense issue
::usleep(mAtvDispDelay);
//
if ( pThis->getStrongCount() <= 1 ) {
MY_LOGW("tid(%d): Camera Adapter was set to free during sleep %d us - getStrongCount(%d)", ::gettid(), mAtvDispDelay, pThis->getStrongCount());
pThis.clear();
MY_LOGW("break loop !!");
break;
}
//
postPreviewFrame(mDispBufNo);
}
//
MY_LOGD("- tid(%d)", ::gettid());
return NULL;
}
/******************************************************************************
*
*******************************************************************************/
void*
MTKCameraHardware::
cameraPreviewThread()
{
// After wake-up from sem_wait, CamAdapter object (& memory) could be deleted and freed,
// so that de-reference bad object will cause exception.
// And hence, we firstly hold a strong pointer during this thread is running.
sp<ICamAdapter> pThis = this;
DispQueNode dispQueNode;
size_t dispQueSize = 0;
MY_LOGD("+ tid(%d), mbPreviewThreadAlive(%d)", ::gettid(), mbPreviewThreadAlive);
//
while (mbPreviewThreadAlive)
{
#if 0
mIsDisplay = false;
::sem_wait(&mSemPrv);
if ( ! mbPreviewThreadAlive )
{
break;
}
//
mIsDisplay = true;
//
postPreviewFrame();
#else
{
Mutex::Autolock _lock(mDispQueLock);
while ( mDispQue.empty() && mbPreviewThreadAlive )
{
status_t status = mDispQueCond.wait(mDispQueLock);
if ( OK != status )
{
MY_LOGW("wait status(%d), DispQue.size(%d), mbPreviewThreadAlive(%d)", status, mDispQue.size(), mbPreviewThreadAlive);
}
}
dispQueSize = mDispQue.size();
if ( dispQueSize > 0 )
{
dispQueNode = mDispQue[dispQueSize-1];
if ( mDispQue.size() > 1 )
{
MY_LOGW("Maybe Display too long, DispQue.size(%d)>1: use the lastest", mDispQue.size());
}
mDispQue.clear();
}
}
//
if ( ! mbPreviewThreadAlive )
{
break;
}
//
if ( dispQueSize > 0 )
{
postPreviewFrame(dispQueNode.mi4Index, dispQueNode.mi8Timestamp);
}
#endif
}
//
MY_LOGD("- tid(%d)", ::gettid());
return NULL;
}
/******************************************************************************
*
*******************************************************************************/
bool
MTKCameraHardware::
postPreviewFrame(int32_t i4Index, int64_t i8Timestamp)
{
// [1] Don't post preview frame if preview has been disabled.
if ( ! previewEnabled() )
{
MY_LOGW("Preview not enabled - skip i4Index(%d)", i4Index);
return false;
}
//
// [2] Load a strong pointer to preview memory pool.
int32_t const i4DispBufNo = i4Index;
sp<IImageBufferPool> pImagePool = mPreviewMemPool;
if (pImagePool == 0)
{
MY_LOGW("NULL pImagePool");
return false;
}
//
// [3] Post preview frame.
CamProfile profile(__FUNCTION__, "MTKCameraHardware");
//
postBuffer(pImagePool, i4DispBufNo, i8Timestamp, CAMERA_MSG_PREVIEW_FRAME);
//
if ( profile.print_overtime(12, "postBuffer for CAMERA_MSG_PREVIEW_FRAME") )
{
MY_LOGW(
"i4Index(%d), ImagePool(%p/%d), image WxH=%dx%d",
i4Index, pImagePool->getVirAddr(i4DispBufNo), pImagePool->getBufSize(),
pImagePool->getImgWidth(), pImagePool->getImgHeight()
);
}
//
return true;
}
/******************************************************************************
*
*******************************************************************************/
void MTKCameraHardware::mATVbufferFIFOin(int pcbInfo_dispBufNo)
{
mATVbuffers[pushindex++] = pcbInfo_dispBufNo;
//CAM_LOGD(" mATVbufferFIFOin : %d %d\n", pushindex-1, popindex);
if (pushindex >= (int)mPreviewMemPool->getBufCount()) {
pushindex -= (int)mPreviewMemPool->getBufCount();
}
}
/******************************************************************************
*
*******************************************************************************/
void MTKCameraHardware::mATVbufferFIFOout()
{
//if need delay not post buffer.
if (mIsATVDelay) {
if (mATVDispBufNo == -1) {
mATVStartTime = getTimeMs();
mATVDispBufNo = 0;
//pushindex = 0;
//popindex= 0;
}
int delta = getTimeMs() - mATVStartTime;
if (delta >= mParameters.getInt("tv-delay")) {
mIsATVDelay = false;
CAM_LOGD(" Elapsed time: %d \n", delta);
//get atv custom delay time
::mHalIoctl(mmHalFd, MHAL_IOCTL_GET_ATV_DISP_DELAY,NULL,0,&mAtvDispDelay, sizeof(unsigned int),NULL);
//start wait VD to callback display
::mHalIoctl(mmHalFd, MHAL_IOCTL_SET_ATV_DISP,NULL,0,NULL, 0,NULL);
}
else {
return;
}
}
mDispBufNo = mATVbuffers[popindex++];
//to resolve matv desense issue
//sem_post(&mSemPrv);
//move to dispatchCallback() to resolve matv desense issue
//trick log mATVbuffers[pushindex-1], add (pushindex-1+12)%12
//CAM_LOGD(" mATVpreviewCallback : in %d , out %d\n", mATVbuffers[(pushindex+11)%12],mATVbuffers[popindex-1]);
//if (popindex >= YUV_ATV_BUF_NUM) {
// popindex -= YUV_ATV_BUF_NUM;
//}
return;
}
/*******************************************************************************
*
********************************************************************************/
void* MTKCameraHardware::_videoThread(void* arg)
{
::prctl(PR_SET_NAME,"Camera@Video",0,0,0);
//
// thread policy & priority
int policy = 0, priority = 0;
getPriority(policy, priority);
CAM_LOGD("[mHalCamAdapter::_videoThread] (tid, policy, priority)=(%d, %d, %d)", ::gettid(), policy, priority);
// detach thread
::pthread_detach(::pthread_self());
//
MTKCameraHardware*const pHardware = reinterpret_cast<MTKCameraHardware*>(arg);
if ( ! pHardware )
{
CAM_LOGE("[mHalCamAdapter::_videoThread] NULL arg");
return NULL;
}
return pHardware->cameraVideoThread();
}
/******************************************************************************
*
*******************************************************************************/
void*
MTKCameraHardware::
cameraVideoThread()
{
MY_LOGD("+ tid(%d), mbVideoThreadAlive(%d)", ::gettid(), mbVideoThreadAlive);
//
while (mbVideoThreadAlive == 0x55555555)
{
::sem_wait(&mSemVdo);
if ( mbVideoThreadAlive != 0x55555555)
{
break;
}
CamProfile profile(__FUNCTION__, "MTKCameraHardware");
sp<IMemoryBufferPool> pMemPool;
if (mVideoMemPool.get() ) {
pMemPool = mVideoMemPool;
}
else {
pMemPool = mPreviewMemPool;
}
camera_memory_t*p_cam_mem = pMemPool->get_camera_memory();
int iOutIndex = miVdoOutIndex;
int iCbNo = maVdoCbBufNo[iOutIndex];
miVdoOutIndex = (miVdoOutIndex+1) % 8;
mDataCbTimestamp(maVdoTimStampNs[iOutIndex], CAMERA_MSG_VIDEO_FRAME, p_cam_mem, maVdoCbBufNo[iOutIndex], mCallbackCookie);
profile.print_overtime(5, "mDataCbTimestamp(CAMERA_MSG_VIDEO_FRAME, %d)", iCbNo);
}
//
MY_LOGD("- tid(%d)", ::gettid());
return NULL;
}
/******************************************************************************
*
*******************************************************************************/
static long long msRecordStart = 0;
static long long msRecordEnd = 0;
void MTKCameraHardware::videoRecordCallback(void *param)
{
if (!mIsVideoEnabled || param == NULL) {
return;
}
//
mhalCamTimeStampBufCBInfo *pcbInfo = (mhalCamTimeStampBufCBInfo *) param;
/*
sp<IMemoryBufferPool> pMemPool;
if (mVideoMemPool.get() ) {
pMemPool = mVideoMemPool;
}
else {
pMemPool = mPreviewMemPool;
}
*/
if (mMsgEnabled & CAMERA_MSG_VIDEO_FRAME) {
nsecs_t nsecCur;
nsecCur = (nsecs_t) pcbInfo->u4TimStampS * (nsecs_t) 1000000000LL,
nsecCur += (nsecs_t) pcbInfo->u4TimStampUs * (nsecs_t) 1000LL;
msRecordStart = getTimeMs();
/*
int32_t i4CbIndex = pcbInfo->u4BufIndex;
camera_memory_t*p_cam_mem = pMemPool->get_camera_memory();
//
CamProfile profile(__FUNCTION__, "MTKCameraHardware");
//
mDataCbTimestamp(nsecCur, CAMERA_MSG_VIDEO_FRAME, p_cam_mem, i4CbIndex, mCallbackCookie);
//
profile.print_overtime(5, "mDataCbTimestamp(CAMERA_MSG_VIDEO_FRAME, %d)", i4CbIndex);
*/
maVdoTimStampNs[miVdoInIndex] = nsecCur;
maVdoCbBufNo[miVdoInIndex] = pcbInfo->u4BufIndex;
if(miVdoInIndex != miVdoOutIndex)
CAM_LOGD("videoRecordCallback in %d, out %d \n", maVdoCbBufNo[miVdoInIndex], maVdoCbBufNo[miVdoOutIndex]);
miVdoInIndex = (miVdoInIndex+1) % 8;
sem_post(&mSemVdo);
}
}
/******************************************************************************
*
*******************************************************************************/
void MTKCameraHardware::previewCallback(void *param)
{
mhalCamBufCBInfo *pcbInfo = (mhalCamBufCBInfo *) param;
if (mIsTakePrv) {
mIsTakePrv = false;
uint8_t *pbufIn, *pbufOut;
pbufIn = (uint8_t *) mmHalCamParam.frmYuv.virtAddr + mmHalCamParam.frmYuv.frmSize * pcbInfo->u4BufIndex;
pbufOut = (uint8_t *) mPrvRgbMemPool->getVirAddr();
//CAM_LOGD(" pbufIn: 0x%x, pbufOut: 0x%x \n", (int) pbufIn, (int) pbufOut);
const char *prvFmt = mParameters.get(MtkCameraParameters::KEY_PREVIEW_INT_FORMAT);
uint32_t mPrvFmt = MHAL_FORMAT_YUV_420_SP;
if (prvFmt != NULL) {
if (strcmp(prvFmt, "mtkyuv") == 0) {
mPrvFmt = MHAL_FORMAT_MTK_YUV;
}
else if (strcmp(prvFmt, "yuv420p") == 0) {
mPrvFmt = MHAL_FORMAT_YUV_420;
}
else if (0 == strcmp(prvFmt, MtkCameraParameters::PIXEL_FORMAT_YUV420I)) {
// [FIXME:] not sure, mdp pipe may need modify.
mPrvFmt = MHAL_FORMAT_YUV_420;
}
else {
CAM_LOGD("No mPixelFmt, error \n");
}
}
//use hw to convert preview frame to rgb565
::hwConvertImageFormat(pbufIn, mPrvFmt, mmHalCamParam.frmYuv.w, mmHalCamParam.frmYuv.h, pbufOut, MHAL_FORMAT_RGB_565);
//saveBufToFile("/data/1.565", (uint8_t *) mPrvRgbPmemPool->mVirtAddr, mmHalCamParam.frmYuv.w * mmHalCamParam.frmYuv.h * 2);
mpMainThread->postCommand(CmdQueThread::Command(CmdQueThread::Command::eID_TAKE_PRV_PIC));
}
if (mIsATV) {
if (!mIsDisplay) {
//add by tengfei mtk80343 for AV sync
//mATV FIFO in
mATVbufferFIFOin(pcbInfo->u4BufIndex);
//maTV FIFO out and trigger sem_post()
mATVbufferFIFOout();
}
else {
CAM_LOGD(" Display too long (>33ms), skip one \n\n");
}
}
else {
#if 0
if (!mIsDisplay) {
mDispBufNo = pcbInfo->u4BufIndex;
sem_post(&mSemPrv);
}
else {
CAM_LOGD(" Display too long (>33ms), skip one \n\n");
}
#else
mhalCamTimeStampBufCBInfo *_pcbInfo = (mhalCamTimeStampBufCBInfo *) param;
nsecs_t timestamp = (nsecs_t)_pcbInfo->u4TimStampS * (nsecs_t)1000000000LL + (nsecs_t)_pcbInfo->u4TimStampUs * (nsecs_t)1000LL;
int32_t index = _pcbInfo->u4BufIndex;
Mutex::Autolock _lock(mDispQueLock);
/*
if ( mDispQue.size() >= 1 ) {
CAM_LOGD(" Maybe Display too long: que.size(%d), skip one", mDispQue.size());
return;
}
// if ( mDispQue.size() >= 1 ) {
// CAM_LOGD(" Maybe Display too long: que.size(%d)", mDispQue.size());
// }
*/
mDispQue.push_back(DispQueNode(index, timestamp));
mDispQueCond.broadcast();
#endif
}
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::doZoom(int currZoom, int nextZoom)
{
status_t status = NO_ERROR;
CAM_LOGD("[doZoom] zoom: %d, %d \n", currZoom, nextZoom);
if (currZoom == nextZoom) {
return NO_ERROR;
}
if ((nextZoom < 0) || (nextZoom > mZoom_max_value)) {
// Restore to its current valid value
mParameters.set(MtkCameraParameters::KEY_ZOOM, currZoom);
return BAD_VALUE;
}
if (getZoomValue(nextZoom) < 100 ) { // in case of wrong customization
mParameters.set(CameraParameters::KEY_ZOOM, currZoom);
return BAD_VALUE;
}
// Set zoom
mZoomValue = nextZoom;
// Immediate zoom is set in setParameters(); but don't forget to set smooth zoom.
mParameters.set(MtkCameraParameters::KEY_ZOOM, mZoomValue);
int realZoom = getZoomValue(nextZoom);
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_SET_ZOOM, &realZoom, sizeof(realZoom), NULL, 0, NULL);
if (status != NO_ERROR) {
// Should not happen
CAM_LOGD("[doZoom] MHAL_IOCTL_SET_ZOOM fail \n");
}
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::startSmoothZoom(int currZoom, int finalZoom)
{
// ICS. [Sean]
// 1. Only support for Mediatek proprietary APK
// 2. Only support in Video mode for increase the zoom performance in video record
CAM_LOGD("[startSmoothZoom] Zoom (Cur, Fianl) = (%d, %d)\n", currZoom, finalZoom);
status_t status = NO_ERROR;
if (mParameters.getInt(MtkCameraParameters::KEY_CAMERA_MODE) == 2) {
mZoomStopValue = finalZoom;
status = doZoom(mZoomValue, mZoomStopValue);
if (status != NO_ERROR) {
return status;
}
}
#if 0
status_t status = NO_ERROR;
int zoomStep, nextZoom;
int priority, policy;
int zoomTime;
mIsSmoothZoomCBEnabled = true;
// Get its default priority
getPriority(policy, priority);
// Set to RR
setPriority(SCHED_RR, 20);
//
if (finalZoom > currZoom) {
zoomStep = 1;
zoomTime = finalZoom - currZoom;
}
else {
zoomStep = -1;
zoomTime = currZoom - finalZoom;
}
// Here we make sure currZoom != finalZoom.
// Do zooming with the final one left.
while ( 1 < zoomTime && (mIsSmoothZoom) ) {
nextZoom = currZoom + zoomStep;
status = doZoom(currZoom, nextZoom);
if (status != NO_ERROR) {
break;
}
currZoom = nextZoom;
zoomTime--;
}
// The final zoom.
// Force to callback with a stoped signal.
if ( 1 <= zoomTime ) {
currZoom = mZoomValue;
nextZoom = currZoom + zoomStep;
mZoomStopValue = nextZoom; // Force to stop.
status = doZoom(currZoom, nextZoom);
}
if (status != NO_ERROR) {
mIsSmoothZoomCBEnabled = false;
mIsSmoothZoom = false;
}
// Restore to its default priority
setPriority(policy, priority);
#endif
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::stopSmoothZoom()
{
status_t status = NO_ERROR;
mIsSmoothZoom = false;
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::startPreviewInternal()
{
status_t status = NO_ERROR;
CAM_LOGD("[startPreviewInternal] Start\n");
//
mZoomValue = mParameters.getInt(MtkCameraParameters::KEY_ZOOM);
//
if ( mPreviewMemPool == NULL ) {
CAM_LOGD("[startPreviewInternal] Err Not enough MEMORY mPreviewPmemPool \n\n");
return NO_MEMORY;
}
//
memset(&mmHalCamParam, 0, sizeof(mhalCamParam_t));
mmHalCamParam.frmYuv.w = mi4PreviewWidth;
mmHalCamParam.frmYuv.h = mi4PreviewHeight;
mmHalCamParam.frmYuv.frmSize = mPreviewMemPool->getBufSize(); //yuvW * yuvH * 2;
mmHalCamParam.frmYuv.frmCount = mPreviewMemPool->getBufCount(); // yuvBufCnt;
mmHalCamParam.frmYuv.bufSize = mPreviewMemPool->getPoolSize(); //(yuvW * yuvH * 2) * yuvBufCnt;
mmHalCamParam.frmYuv.virtAddr = (uint32_t)mPreviewMemPool->getVirAddr();
mmHalCamParam.frmYuv.phyAddr = (uint32_t)mPreviewMemPool->getPhyAddr();
//
const char *prvFmt = mParameters.get(MtkCameraParameters::KEY_PREVIEW_INT_FORMAT);
const char *defaultFmt = MtkCameraParameters::PIXEL_FORMAT_YUV420SP;
int pixelFmt;
if (prvFmt == NULL) {
prvFmt = defaultFmt;
}
mmHalCamParam.frmYuv.frmFormat = mapPixelFormat_string_to_mHal(String8(prvFmt));
// video frame parameter
mVideoMemPool = NULL;
if (NULL != mParameters.get(CameraParameters::KEY_PREFERRED_PREVIEW_SIZE_FOR_VIDEO)) {
int i4VideoWidth = 0, i4VideoHeight =0;
mParameters.getVideoSize(&i4VideoWidth, &i4VideoHeight);
mVideoMemPool = allocCamMem(MHAL_CAM_BUF_VIDEO, "video", i4VideoWidth, i4VideoHeight);
if ( mVideoMemPool == NULL ) {
CAM_LOGE("[startPreviewInternal] Err Not enough MEMORY mVideoPmemPool \n\n");
return NO_MEMORY;
}
mmHalCamParam.frmVdo.w = i4VideoWidth;
mmHalCamParam.frmVdo.h = i4VideoHeight;
mmHalCamParam.frmVdo.frmSize = mVideoMemPool->getBufSize();
mmHalCamParam.frmVdo.frmCount = mVideoMemPool->getBufCount();
mmHalCamParam.frmVdo.bufSize = mVideoMemPool->getPoolSize();
mmHalCamParam.frmVdo.virtAddr = (uint32_t)mVideoMemPool->getVirAddr();
mmHalCamParam.frmVdo.phyAddr = (uint32_t)mVideoMemPool->getPhyAddr();
mmHalCamParam.frmVdo.frmFormat = mapPixelFormat_string_to_mHal(String8(prvFmt));
}
//
mmHalCamParam.u4CamMode = mParameters.getInt(MtkCameraParameters::KEY_CAMERA_MODE);
if (mmHalCamParam.u4CamMode == 1){
if (strcmp(mParameters.get(MtkCameraParameters::KEY_ZSD_MODE), MtkCameraParameters::ON) == 0) {
#ifdef MDP_NEW_PATH_FOR_ZSD
CAM_LOGD("[ZSD.N]ZSD enable \n");
mmHalCamParam.camZsdParam.u4ZsdEnable = 0x2;
#else
CAM_LOGD("[ZSD]ZSD enable \n");
mmHalCamParam.camZsdParam.u4ZsdEnable = 0x1;
#endif
if (mIsZSD == 1){
mmHalCamParam.camZsdParam.u4ZsdSkipPrev = 1;
}
mIsZSD = 1;
}
else{
mIsZSD = 0;
}
}
else{
mIsZSD = 0;
}
updateShotMode(String8(mParameters.get(MtkCameraParameters::KEY_CAPTURE_MODE)));
mapCam3AParameter(mmHalCamParam.cam3AParam, mParameters, mFeatureParam);
//
mmHalCamParam.cam3AParam.eisW = mi4PreviewWidth;
mmHalCamParam.cam3AParam.eisH = mi4PreviewHeight;
//
mmHalCamParam.u4ZoomVal = getZoomValue(mZoomValue);
mmHalCamParam.mhalObserver = mHalCamObserver(mhalCallback, this);
mmHalCamParam.shotObserver = mHalCamObserver(shotCallback, this);
//
mmHalCamParam.u4CamIspMode = mParameters.getInt(MtkCameraParameters::KEY_ISP_MODE);
//
strcpy((char *) mmHalCamParam.u1FileName, mParameters.get(MtkCameraParameters::KEY_RAW_PATH));
//
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_PREVIEW_START, &mmHalCamParam, sizeof(mhalCamParam_t), NULL, 0, NULL);
if (status != NO_ERROR) {
CAM_LOGD("[startPreviewInternal] MHAL_IOCTL_PREVIEW_START err \n");
return status;
}
//
::android_atomic_release_store(true, &mIsPreviewEnabled);
//
CAM_LOGD("[startPreviewInternal] End\n");
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::stopPreviewInternal()
{
status_t status = NO_ERROR;
//CAM_LOGD("[stopPreviewInternal] Start\n");
if (previewEnabled()) {
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_PREVIEW_STOP, NULL, 0, NULL, 0, NULL);
::android_atomic_acquire_store(false, &mIsPreviewEnabled);
mPreviewMemPool = NULL;
mVideoMemPool = NULL;
if (mIsATV) {
// Disable fb immediate update
int enable = 0;
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_FB_CONFIG_IMEDIATE_UPDATE, &enable, sizeof(enable), NULL, 0, NULL);
if (status != NO_ERROR) {
CAM_LOGD("[stopPreviewInternal] MHAL_IOCTL_FB_CONFIG_IMEDIATE_UPDATE err \n");
return status;
}
}
}
//CAM_LOGD("[stopPreviewInternal] End\n");
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::startPreview()
{
CAM_LOGD("[startPreview] + tid(%d)", gettid());
status_t status = NO_ERROR;
MUINT32 TimeoutCount;
// Check if it is ATV preview
mIsATV = false;
mIsATVDelay = false;
mAtvDispDelay = 0;
mParameters.getPreviewSize(&mi4PreviewWidth, &mi4PreviewHeight);
Vector<Size> sizes;
int32_t i4MaxPrvW = 0;
int32_t i4MaxPrvH = 0;
mParameters.getSupportedPreviewSizes(sizes);
for(Vector<Size>::iterator iter = sizes.begin(); iter!=sizes.end(); ++iter)
{
if(i4MaxPrvW<iter->width || i4MaxPrvH<iter->height);
{
i4MaxPrvW = iter->width;
i4MaxPrvH = iter->height;
}
}
if(mi4PreviewWidth>i4MaxPrvW || mi4PreviewHeight>i4MaxPrvH)
{
CAM_LOGE("The preview size is to large, not supported! Max supported preview size(%d/%d), required preview size(%d/%d)",
i4MaxPrvW, i4MaxPrvH, mi4PreviewWidth, mi4PreviewHeight);
return BAD_VALUE;
}
if ( getDevId() == eDevId_AtvSensor )
{
CAM_LOGD("[startPreview] ATV Preview \n");
mIsATV = true;
mIsATVDelay = true;
mATVDispBufNo = -1;
//add by tengfei mtk80343 for AV sync
pushindex = 0;
popindex = 0;
mPreviewMemPool = allocImagePool(MHAL_CAM_BUF_PREVIEW_ATV, mi4PreviewWidth, mi4PreviewHeight, "previewATV");
status = startPreviewInternal();
if (status != NO_ERROR)
{
CAM_LOGD("[startPreview] startPreviewInternal err \n");
return status;
}
// Enable fb immediate update
int enable = 1;
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_FB_CONFIG_IMEDIATE_UPDATE, &enable, sizeof(enable), NULL, 0, NULL);
if (status != NO_ERROR) {
CAM_LOGD("[startPreview] MHAL_IOCTL_FB_CONFIG_IMEDIATE_UPDATE err \n");
return status;
}
}
else
{
TimeoutCount = 0;
while(meCamState == eCS_TakingPicture)
{
CAM_LOGW("[startPreview]Wait capture end,count(%d)",TimeoutCount);
::usleep(20*1000);
TimeoutCount++;
if(TimeoutCount > 50)
{
CAM_LOGE("[startPreview]Wait capture end timeout,count(%d)",TimeoutCount);
return INVALID_OPERATION;
}
}
//
CAM_LOGD("[startPreview] Camera Preview \n");
mPreviewMemPool = allocImagePool(MHAL_CAM_BUF_PREVIEW, mi4PreviewWidth, mi4PreviewHeight, "preview");
status = startPreviewInternal();
if (status != NO_ERROR)
{
CAM_LOGD("[startPreview] startPreviewInternal err \n");
return status;
}
}
return status;
}
/******************************************************************************
*
*******************************************************************************/
void MTKCameraHardware::stopPreview()
{
CAM_LOGD("[stopPreview] + tid(%d)", gettid());
stopPreviewInternal();
//mIsZoomReset = true;
//CAM_LOGD("[stopPreview] End\n");
}
/******************************************************************************
*
*******************************************************************************/
bool MTKCameraHardware::previewEnabled() {
return (0 != ::android_atomic_acquire_load(&mIsPreviewEnabled));
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::startRecording()
{
status_t status = NO_ERROR;
int data[3];
//
CAM_LOGD("[startRecording] E \n");
//
miVdoInIndex= 0;
miVdoOutIndex = 0;
//
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_VIDEO_START_RECORD, data, sizeof(data), NULL, 0, NULL);
if (status != NO_ERROR) {
CAM_LOGD("[startRecording] MHAL_IOCTL_VIDEO_START_RECORD err \n");
return status;
}
//
mIsVideoEnabled = true;
return status;
}
/******************************************************************************
*
*******************************************************************************/
void MTKCameraHardware::stopRecording()
{
status_t status = NO_ERROR;
//
CAM_LOGD("[stopRecording] \n");
//
mIsVideoEnabled = false;
//
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_VIDEO_STOP_RECORD, NULL, 0, NULL, 0, NULL);
if (status != NO_ERROR) {
CAM_LOGD("[stopRecording] MHAL_IOCTL_VIDEO_STOP_RECORD err \n");
}
}
/******************************************************************************
*
*******************************************************************************/
bool MTKCameraHardware::recordingEnabled()
{
return mIsVideoEnabled;
}
/******************************************************************************
* Release a record frame previously returned by CAMERA_MSG_VIDEO_FRAME.
*
* It is camera hal client's responsibility to release video recording
* frames sent out by the camera hal before the camera hal receives
* a call to disableMsgType(CAMERA_MSG_VIDEO_FRAME). After it receives
* the call to disableMsgType(CAMERA_MSG_VIDEO_FRAME), it is camera hal's
* responsibility of managing the life-cycle of the video recording
* frames.
*******************************************************************************/
void
MTKCameraHardware::
releaseRecordingFrame(const void *opaque)
{
if ( ! msgTypeEnabled(CAMERA_MSG_VIDEO_FRAME) )
{
CAM_LOGI(
"[releaseRecordingFrame] + CAMERA_MSG_VIDEO_FRAME has been disabled: tid(%d), opaque(%p)"
, gettid(), opaque
);
}
//
sp<IMemoryBufferPool> pMemPool;
if (mVideoMemPool.get() ) {
pMemPool = mVideoMemPool;
}
else {
pMemPool = mPreviewMemPool;
}
if (pMemPool == NULL)
{
CAM_LOGI("[releaseRecordingFrame] video mem already release");
return;
}
void const*const pReleaseMem = opaque;
msRecordEnd = getTimeMs();
static uint32_t idx = 0;
if ( pReleaseMem != (void const*)pMemPool->getVirAddr(idx) ) {
CAM_LOGD("[releaseRecordingFrame] invalid frame - mVideoMemPool->getVirAddr(%d)=%08x", idx, pMemPool->getVirAddr(idx));
for (idx = 0; idx < pMemPool->getBufCount(); idx++) {
if ( pReleaseMem == (void const*)pMemPool->getVirAddr(idx) ) {
break;
}
}
}
if (idx < pMemPool->getBufCount()) {
CAM_LOGD("[releaseRecordingFrame] mpBuffer[%d]=%p - period: %lld ms", idx, pReleaseMem, msRecordEnd-msRecordStart);
status_t status = NO_ERROR;
status = ::mHalIoctl(mmHalFd, MAHL_IOCTL_RELEASE_VDO_FRAME, &idx, sizeof(int), NULL, 0, NULL);
idx = (idx+1) % pMemPool->getBufCount();
}
else {
CAM_LOGD("[releaseRecordingFrame] cannot find frame: %08x", pMemPool->getVirAddr(idx));
idx = 0;
}
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::autoFocus()
{
status_t status = NO_ERROR;
if (!mIsPreviewEnabled) {
CAM_LOGD("[autoFocus] not in preview state \n");
return NO_ERROR; //It is better to return INVALID_OPERATION;
}
CAM_LOGD("[autoFocus] \n");
#if (MTKCAM_CAP_PROFILE_OPT)
mFocusStartTime = getTimeMs();
#endif
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_DO_FOCUS, NULL, 0, NULL, 0, NULL);
if (status != NO_ERROR) {
// can't lock resource
CAM_LOGD(" autoFocus, set MHAL_IOCTL_DO_FOCUS fail \n");
freeCamCaptureMem();
}
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::cancelAutoFocus()
{
status_t status = NO_ERROR;
CAM_LOGD("[cancelAutoFocus] \n");
if (previewEnabled()) {
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_CANCEL_FOCUS, NULL, 0, NULL, 0, NULL);
if (status != NO_ERROR) {
// can't lock resource
CAM_LOGD(" cancelAutoFocus, set MHAL_IOCTL_CANCEL_FOCUS fail \n");
}
}
return status;
}
/******************************************************************************
*
*******************************************************************************/
sp<IMemoryBufferPool>
MTKCameraHardware::
allocMem(size_t const bufsize, uint_t const numbufs, char const*const szName) const
{
sp<IMemoryBufferPool> mem;
int i = 0, retry = 10;
int us = 200 * 1000;
//
do {
mpBufProvider->allocBuffer(mem, bufsize, numbufs, szName);
if ( mem != NULL && 0 != mem->getPoolSize() && 0 != mem->getVirAddr() ) {
break;
}
::usleep(us);
CAM_LOGD("[allocMem] retry: %d \n ", i++);
} while ((--retry) > 0);
//
if ( mem == NULL || 0 == mem->getPoolSize() || 0 == mem->getVirAddr() ) {
// Should not happen
CAM_LOGD("[allocMem] alloc mem fail, should not happen \n");
mem = NULL;
//while (1);
}
return mem;
}
/******************************************************************************
*
*******************************************************************************/
sp<IMemoryBufferPool>
MTKCameraHardware::
allocCamMem(int poolID, char const*const szName, int frmW, int frmH) const
{
status_t status = NO_ERROR;
CAM_LOGD("[allocCamMem] poolID = %d, poolName = %s, frmW = %d, frmH = %d \n",
poolID, szName, frmW, frmH);
//
mhalCamBufMemInfo_t camBufInfo;
memset(&camBufInfo, 0, sizeof(mhalCamBufMemInfo_t));
camBufInfo.bufID = poolID;
camBufInfo.frmW = frmW;
camBufInfo.frmH = frmH;
//
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_GET_CAM_BUF_MEM_INFO, NULL, 0, &camBufInfo, sizeof(mhalCamBufMemInfo_t), NULL);
if (status != NO_ERROR) {
CAM_LOGD("[allocCamMem] MHAL_IOCTL_GET_CAM_BUF_INFO fail \n");
return NULL;
}
/*
int32_t i4Type = MemPool::eTYPE_UKNOWN;
switch (camBufInfo.camMemType)
{
case MHAL_CAM_ASHMEM_TYPE:
i4Type = MemPool::eTYPE_ASHMEM;
break;
case MHAL_CAM_PMEM_TYPE:
i4Type = MemPool::eTYPE_PMEM;
break;
default:
i4Type = MemPool::eTYPE_UKNOWN;
break;
}
*/
return allocMem(camBufInfo.camBufSize, camBufInfo.camBufCount, szName);
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::freeCamCaptureMem()
{
mQvMemPool = NULL;
mJpegMemPool = NULL;
return NO_ERROR;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::allocCamCaptureMem()
{
status_t status = NO_ERROR;
//
if (mQvMemPool == NULL) {
int qvW = 0, qvH = 0;
//qv size is the same as preview size
mParameters.getPreviewSize(&qvW, &qvH);
if(1920 == qvW && 1088 == qvH)
{
CAM_LOGD("For 1080p preview size, QV size is set as 640*480 \n");
qvW = 640;
qvH = 480;
}
mQvMemPool = allocImagePool(MHAL_CAM_BUF_POSTVIEW, qvW, qvH, "qv");
//
if (mQvMemPool == NULL) {
CAM_LOGD("[allocCamCaptureMem] Err Not enough MEMORY for mQvPmemPool \n\n");
return NO_MEMORY;
}
}
//
if (mJpegMemPool == NULL) {
int capW = 0, capH = 0;
mParameters.getPictureSize(&capW, &capH);
mJpegMemPool = allocCamMem(MHAL_CAM_BUF_CAPTURE, "jpeg", capW, capH);
//
if (mJpegMemPool == NULL) {
CAM_LOGD("[allocCamCaptureMem] Err Not enough MEMORY for mJpegPmemPool \n\n");
return NO_MEMORY;
}
}
return status;
}
/*******************************************************************************
*
********************************************************************************/
status_t MTKCameraHardware::takePictureProc()
{
int rotation_angle;
int current_sensor;
int current_sensor_angle;
status_t status = NO_ERROR;
int burstCnt = mmHalCamParam.u4BusrtCnt;
CAM_LOGD("[takePictureProc]: tid(%d) getStrongCount(%d) burstCnt(%d)", gettid(), getStrongCount(), burstCnt);
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_CAPTURE_INIT, &mmHalCamParam, sizeof(mhalCamParam_t), NULL, 0, NULL);
if (status != NO_ERROR) {
CAM_LOGD(" takePictureProc, set MHAL_IOCTL_CAPTURE_INIT fail \n");
return status;
}
{
mStateLock.lock();
CAM_LOGD("[takePictureProc][state transition] %s --> %s", getCamStateStr(meCamState), getCamStateStr(eCS_TakingPicture));
//
// TODO: should check the current state.
//
//
meCamState = eCS_TakingPicture;
mStateLock.unlock();
}
// if (burstCnt > 1) {
// // disable jpeg callback, enable it until last picture
// disableMsgType(CAMERA_MSG_COMPRESSED_IMAGE);
// }
//
while ( ! mIsCancelPicture && burstCnt > 0 ) {
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_CAPTURE_START, &mmHalCamParam, sizeof(mhalCamParam_t), NULL, 0, NULL);
if (status != NO_ERROR) {
CAM_LOGD(" takePictureProc, set MHAL_IOCTL_CAPTURE_START fail \n");
break;
}
if ( 0 != mmHalCamParam.camZsdParam.u4ZsdAddr ){
mmHalCamParam.camZsdParam.u4ZsdAddr = 0;
mmHalCamParam.u4ZoomVal = getZoomValue(mZoomValue);
// mmHalCamParam.camZsdParam.u4ZsdEVShot = 0;
mmHalCamParam.camZsdParam.u4ZsdEnable = 0;
}
//
::sem_wait(&mSemTakePicBack);
CAM_LOGD(" got mSemTakePicBack \n");
//
mmHalCamParam.u4BusrtNo++;
burstCnt--;
//
if (mIsCancelPicture) {
CAM_LOGD("mIsCancelPicture=true");
break;
}
//
if (burstCnt > 0) {
mIsZSD = 0;
//freeCamCaptureMem();
//allocCamCaptureMem();
mmHalCamParam.frmQv.virtAddr = (uint32_t)mQvMemPool->getVirAddr();
mmHalCamParam.frmQv.phyAddr = (uint32_t)mQvMemPool->getPhyAddr();
mmHalCamParam.frmJpg.virtAddr = (uint32_t)mJpegMemPool->getVirAddr();
mmHalCamParam.frmJpg.phyAddr = (uint32_t)mJpegMemPool->getPhyAddr();
// if (burstCnt == 1) {
// // enable last jpeg callback
// enableMsgType(CAMERA_MSG_COMPRESSED_IMAGE);
// }
}
}
if(mu4ShotMode == MHAL_CAM_CAP_MODE_CONTINUOUS_SHOT)
{
LOGD("continuous shot end");
mNotifyCb(
MTK_CAMERA_MSG_EXT_NOTIFY, MTK_CAMERA_MSG_EXT_NOTIFY_CONTINUOUS_END,
mmHalCamParam.u4BusrtNo,
mCallbackCookie);
}
//
if(burstCnt > 0)
{
CAM_LOGD("[takePictureProc]Force save all file");
waitFileSaveDone();
CAM_LOGD("[takePictureProc]All file saved done");
}
//
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_CAPTURE_UNINIT, NULL, 0, NULL, 0, NULL);
if (status != NO_ERROR) {
CAM_LOGD(" takePictureProc, set MHAL_IOCTL_CAPTURE_UNINIT fail \n");
}
// Free memory
mQvMemPool = NULL;
mJpegMemPool = NULL;
changeState(eCS_Init, true);
CAM_LOGD("[takePictureProc] -");
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::takePictureInternal()
{
status_t status = NO_ERROR;
int capW, capH, thumbW, thumbH;
int jpqQVal, gpsAltitude;
char *gpsLatitude, *gpsLongitude, *gpsTimestamp, *gpsProcessingMethod;
char *pstr, *pstrVals;
int zsdAddr=0,zsdW=0,zsdH=0;
int strobeon;
#if 0 // For Debug
mParameters.set(MtkCameraParameters::KEY_JPEG_THUMBNAIL_WIDTH, 0);
mParameters.set(MtkCameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT, 0);
mParameters.set(MtkCameraParameters::KEY_GPS_ALTITUDE, "21");
mParameters.set(MtkCameraParameters::KEY_GPS_LATITUDE, "37.736071");
mParameters.set(MtkCameraParameters::KEY_GPS_LONGITUDE, "-122.441983");
mParameters.set(MtkCameraParameters::KEY_GPS_TIMESTAMP, "1199145600");
mParameters.set(MtkCameraParameters::KEY_GPS_PROCESSING_METHOD, "GPS NETWORK HYBRID ARE ALL FINE.");
#endif
// Get capture size
mParameters.getPictureSize(&capW, &capH);
// Get Zoom dimension
mZoomValue = mParameters.getInt(MtkCameraParameters::KEY_ZOOM);
thumbW = mParameters.getInt(MtkCameraParameters::KEY_JPEG_THUMBNAIL_WIDTH);
thumbH = mParameters.getInt(MtkCameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT);
jpqQVal = mParameters.getInt(MtkCameraParameters::KEY_JPEG_QUALITY);
gpsAltitude = mParameters.getInt(MtkCameraParameters::KEY_GPS_ALTITUDE);
gpsLatitude = (char *) mParameters.get(MtkCameraParameters::KEY_GPS_LATITUDE);
gpsLongitude = (char *) mParameters.get(MtkCameraParameters::KEY_GPS_LONGITUDE);
gpsTimestamp = (char *) mParameters.get(MtkCameraParameters::KEY_GPS_TIMESTAMP);
gpsProcessingMethod = (char *) mParameters.get(MtkCameraParameters::KEY_GPS_PROCESSING_METHOD);
if ((mIsZSD == 1)&&(0!=mmHalCamParam.camZsdParam.u4ZsdAddr)){
if((mmHalCamParam.camZsdParam.u4ZsdZoomWidth != 0) && (mmHalCamParam.camZsdParam.u4ZsdZoomHeigth !=0)){
zsdW = mmHalCamParam.camZsdParam.u4ZsdZoomWidth;
zsdH = mmHalCamParam.camZsdParam.u4ZsdZoomHeigth;
}
else{
zsdW = mmHalCamParam.camZsdParam.u4ZsdWidth;
zsdH = mmHalCamParam.camZsdParam.u4ZsdHeight;
}
zsdAddr = mmHalCamParam.camZsdParam.u4ZsdAddr;
if (mmHalCamParam.camZsdParam.u4ZsdDump){
CAM_LOGD("[dump to file][ZSD]: Addr:%x, W:%d,H:%d \n",zsdAddr,zsdW,zsdH);
saveBufToFile((char *) "/sdcard/zsd_cap.bin", (MUINT8 *) zsdAddr, zsdW*zsdH*2);
}
CAM_LOGD("[takePictureInternal][ZSD]: Addr:0x%x,W:%d,H:%d \n",zsdAddr,zsdW,zsdH);
}
else{
mIsZSD = 0;
mmHalCamParam.camZsdParam.u4ZsdAddr = 0;
mmHalCamParam.camZsdParam.u4ZsdEnable = 0;
mmHalCamParam.u4ZoomVal = getZoomValue(mZoomValue);
CAM_LOGD("[takePictureInternal][ZSD]: zsd off\n");
}
strobeon = mmHalCamParam.u4strobeon;
status = allocCamCaptureMem();
if (status != NO_ERROR) {
CAM_LOGE("[takePictureInternal] Err Not enough MEMORY for capture \n\n");
mNotifyCb(CAMERA_MSG_ERROR, CAMERA_ERROR_NO_MEMORY, 0, mCallbackCookie); // no memory callback to AP.
return NO_ERROR; // to avoid java exception triggered in JNI
}
//
::memset(&mmHalCamParam, 0, sizeof(mhalCamParam_t));
if (mIsZSD == 1){
mmHalCamParam.camZsdParam.u4ZsdEnable = 0x1;
mmHalCamParam.camZsdParam.u4ZsdAddr = zsdAddr;
mmHalCamParam.camZsdParam.u4ZsdWidth = zsdW;
mmHalCamParam.camZsdParam.u4ZsdHeight = zsdH;
}
mmHalCamParam.u4strobeon = strobeon;
//AWB2PASS
if (strcmp(mParameters.get(MtkCameraParameters::KEY_AWB2PASS), MtkCameraParameters::ON) == 0) {
mmHalCamParam.u4awb2pass = 0x1;
}
// Quickview
mmHalCamParam.frmQv.w = mQvMemPool->getImgWidth();
mmHalCamParam.frmQv.h = mQvMemPool->getImgHeight();
mmHalCamParam.frmQv.frmSize = mQvMemPool->getBufSize();
mmHalCamParam.frmQv.frmCount = mQvMemPool->getBufCount();
mmHalCamParam.frmQv.bufSize = mQvMemPool->getBufSize();
mmHalCamParam.frmQv.virtAddr = (uint32_t)mQvMemPool->getVirAddr();
mmHalCamParam.frmQv.phyAddr = (uint32_t)mQvMemPool->getPhyAddr();
mmHalCamParam.frmQv.frmFormat = mapPixelFormat_string_to_mHal(mQvMemPool->getImgFormat());
//
// Jpeg
mmHalCamParam.frmJpg.w = capW;
mmHalCamParam.frmJpg.h = capH;
mmHalCamParam.frmJpg.frmSize = mJpegMemPool->getBufSize();
mmHalCamParam.frmJpg.frmCount = mJpegMemPool->getBufCount();
mmHalCamParam.frmJpg.bufSize = mJpegMemPool->getBufSize();
mmHalCamParam.frmJpg.virtAddr = (uint32_t)mJpegMemPool->getVirAddr();
mmHalCamParam.frmJpg.phyAddr = (uint32_t)mJpegMemPool->getPhyAddr();
//
// Thumb
mmHalCamParam.u4ThumbW = thumbW;
mmHalCamParam.u4ThumbH = thumbH;
if (mIsZSD == 1){
#ifdef MDP_NEW_PATH_FOR_ZSD
mmHalCamParam.u4ZoomVal = getZoomValue(mZoomValue);
#else
mmHalCamParam.u4ZoomVal = 100;
#endif
}
else{
mmHalCamParam.u4ZoomVal = getZoomValue(mZoomValue);
}
mmHalCamParam.mhalObserver = mHalCamObserver(mhalCallback, this);
mmHalCamParam.shotObserver = mHalCamObserver(shotCallback, this);
// Other
mmHalCamParam.u4JpgQValue = jpqQVal;
mmHalCamParam.camExifParam.gpsIsOn = 0;
if ((gpsLatitude != NULL) && (gpsLongitude != NULL)
&& (gpsTimestamp != NULL) && (gpsProcessingMethod != NULL))
{
strcpy(mmHalCamParam.camExifParam.gpsLongitude, gpsLongitude);
strcpy(mmHalCamParam.camExifParam.gpsLatitude, gpsLatitude);
strcpy(mmHalCamParam.camExifParam.gpsTimeStamp, gpsTimestamp);
strcpy(mmHalCamParam.camExifParam.gpsProcessingMethod, gpsProcessingMethod);
mmHalCamParam.camExifParam.gpsAltitude = gpsAltitude;
mmHalCamParam.camExifParam.gpsIsOn = 1;
}
else
{
CAM_LOGW("[startAUTORAMA] GPS Information are not avaiable !");
}
// rawsave-mode
if (mParameters.getInt(MtkCameraParameters::KEY_RAW_SAVE_MODE) > 0) {
mmHalCamParam.u4IsDumpRaw = 1;
if (mParameters.getInt(MtkCameraParameters::KEY_RAW_SAVE_MODE) == 1) {
mmHalCamParam.u4CapPreFlag = 1;
}
}
strcpy((char *) mmHalCamParam.u1FileName, mParameters.get(MtkCameraParameters::KEY_RAW_PATH));
if ( char const* pFileName = mParameters.get(MtkCameraParameters::KEY_CAPTURE_PATH) )
{
::strncpy((char *)mmHalCamParam.uShotFileName, pFileName, sizeof(mmHalCamParam.uShotFileName));
MY_LOGD("uShotFileName=\"%s\"", mmHalCamParam.uShotFileName);
}
// Restore ui settings for 3A for EXIF
updateShotMode(String8(mParameters.get(MtkCameraParameters::KEY_CAPTURE_MODE)));
mapCam3AParameter(mmHalCamParam.cam3AParam, mParameters, mFeatureParam);
// capture mode
mmHalCamParam.u4BusrtNo = 0;
switch (mu4ShotMode) {
case MHAL_CAM_CAP_MODE_EV_BRACKET:
case MHAL_CAM_CAP_MODE_BEST_SHOT:
mmHalCamParam.u4BusrtCnt = 3;
break;
case MHAL_CAM_CAP_MODE_BURST_SHOT:
mmHalCamParam.u4BusrtCnt = mParameters.getInt(MtkCameraParameters::KEY_BURST_SHOT_NUM);
break;
case MHAL_CAM_CAP_MODE_CONTINUOUS_SHOT:
mmHalCamParam.u4BusrtCnt = mParameters.getInt(MtkCameraParameters::KEY_BURST_SHOT_NUM);
if (strcmp(mParameters.get(MtkCameraParameters::KEY_FAST_CONTINUOUS_SHOT), MtkCameraParameters::ON) == 0)
mmHalCamParam.u4ContinuousShotSpeed = 1;
else
mmHalCamParam.u4ContinuousShotSpeed = 0;
break;
default:
mmHalCamParam.u4BusrtCnt = 1;
break;
}
if (mu4ShotMode != MHAL_CAM_CAP_MODE_NORMAL){
if (mIsZSD == 1){
mmHalCamParam.camZsdParam.u4ZsdEnable = 0;
mmHalCamParam.camZsdParam.u4ZsdAddr = 0;
mmHalCamParam.u4ZoomVal = getZoomValue(mZoomValue);
mIsZSD = 0;
CAM_LOGD("[takePictureInternal][ZSD]Off ZSD, mu4ShotMode:%d \n",mu4ShotMode);
}
}
//
// for JPEG orienation,
// Due to contiuous shot performance, in this mode, do not do JPEG orientation
if (mu4ShotMode == MHAL_CAM_CAP_MODE_CONTINUOUS_SHOT ||
false == NSCamCustom::isSupportJpegOrientation()
)
{
mmHalCamParam.camExifParam.orientation = mParameters.getInt(MtkCameraParameters::KEY_ROTATION);
mmHalCamParam.u4JPEGOrientation = 0;
}
else
{
mmHalCamParam.camExifParam.orientation = 0;
mmHalCamParam.u4JPEGOrientation = mParameters.getInt(MtkCameraParameters::KEY_ROTATION) / 90;
if (mmHalCamParam.u4JPEGOrientation != 0)
{
mmHalCamParam.u4DumpYuvData = 1;
}
}
//
mmHalCamParam.u4CamIspMode = mParameters.getInt(MtkCameraParameters::KEY_ISP_MODE);
//
mpMainThread->postCommand(CmdQueThread::Command(CmdQueThread::Command::eID_TAKE_PICTURE));
//CAM_LOGD("[takePicture] End\n");
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::takePicture()
{
CAM_LOGD("[takePicture] + tid(%d)", gettid());
if ( ! previewEnabled() )
{
CAM_LOGE("[takePicture] not in preview state");
return INVALID_OPERATION;
}
status_t status = NO_ERROR;
#if (MTKCAM_CAP_PROFILE_OPT)
mCaptureStartTime = getTimeMs();
#endif
mIsCancelPicture = false;
if (mIsATV) {
takePreviewPictureInternal();
return status;
}
//
if(mIsVideoEnabled)
{
CAM_LOGD("[takePicture]MHAL_IOCTL_VIDEO_SNAPSHOT");
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_VIDEO_SNAPSHOT, (void*)(mParameters.getInt(MtkCameraParameters::KEY_ROTATION)), 0, NULL, 0, NULL);
if(status != NO_ERROR)
{
CAM_LOGD("[takePicture]MHAL_IOCTL_VIDEO_SNAPSHOT fail");
return status;
}
return status;
}
//
if (mParameters.getInt(MtkCameraParameters::KEY_FOCUS_ENG_MODE) == 0 || mParameters.getInt(MtkCameraParameters::KEY_FOCUS_ENG_MODE) == 5) {
// Do pre capture before stop preview, for 3A
CAM_LOGD("[takePicture] Do pre capture \n");
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_PRE_CAPTURE, NULL, 0, NULL, 0, NULL);
if (status != NO_ERROR) {
CAM_LOGD("[takePicture] MHAL_IOCTL_PRE_CAPTURE fail \n");
return status;
}
}
//
stopPreviewInternal();
//
status = takePictureInternal();
//
CAM_LOGD("[takePicture] - status(%d)", status);
return status;
}
/*******************************************************************************
*
********************************************************************************/
status_t MTKCameraHardware::takePreviewPictureProc()
{
status_t status = NO_ERROR;
int memSize;
CAM_LOGD("[takePreviewPictureProc] \n");
//
uint8_t *pbufIn, *pbufOut;
pbufIn = (uint8_t *) mPrvRgbMemPool->getVirAddr();
pbufOut = (uint8_t *) mPrvJpegMemPool->getVirAddr();
// use sw to compress rgb565 to jpeg
uint32_t jpegSize;
uint32_t w = mmHalCamParam.frmYuv.w;
uint32_t h = mmHalCamParam.frmYuv.h;
::rgb565toJpeg(pbufIn, pbufOut, w, h, &jpegSize);
//FIX_ME
//saveBufToFile((char *)"/data/1.jpg", pbufOut, jpegSize);
//
if (mMsgEnabled & CAMERA_MSG_COMPRESSED_IMAGE) {
CAM_LOGD("[takePreviewPictureProc] MHAL_CAM_CB_JPEG \n");
mDataCb(CAMERA_MSG_COMPRESSED_IMAGE, mPrvJpegMemPool->get_camera_memory(), 0, NULL, mCallbackCookie);
}
//
mPrvRgbMemPool = NULL;
mPrvJpegMemPool = NULL;
CAM_LOGD("[takePreviewPictureProc] End \n");
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::takePreviewPictureInternal()
{
status_t status = NO_ERROR;
int memSize = mmHalCamParam.frmYuv.w * mmHalCamParam.frmYuv.h * 2;
mPrvRgbMemPool = allocMem(memSize, 1, "prvRgb");
mPrvJpegMemPool = allocMem(memSize, 1, "prvJpeg");
mIsTakePrv = true;
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::cancelPicture()
{
CAM_LOGD("[cancelPicture] + (pid,tid)=(%d,%d) mIsCancelPicture(%d)", getpid(), gettid(), mIsCancelPicture);
mIsCancelPicture = true;
//
// Callers cannot be callback threads to CameraService, such as mainThread and shutterThread.
// TODO: check shutterThread
CAM_LOGD("[cancelPicture] tid:(current, main thread)=(%d, %d)", ::gettid(), mpMainThread->getTid());
if ( ::gettid() == mpMainThread->getTid() )
{
MY_LOGW("[cancelPicture] The caller is mainThread");
return PERMISSION_DENIED;
}
//
Mutex::Autolock stateLock(&mStateLock);
while ( eCS_TakingPicture == meCamState )
{
CAM_LOGD("[cancelPicture] waiting until taking picture done");
::mHalIoctl(mmHalFd, MHAL_IOCTL_CAPTURE_CANCEL, NULL, 0, NULL, 0, NULL);
mStateCond.wait(mStateLock);
}
CAM_LOGD("[cancelPicture] -");
return NO_ERROR;
}
/*******************************************************************************
*
*******************************************************************************/
bool
MTKCameraHardware::
handleMainThreadCommand(void const*const pCmd)
{
if ( ! pCmd )
{
CAM_LOGD("[handleMainThreadCommand] null cmd");
return NO_ERROR;
}
CmdQueThread::Command const& rCmd = *reinterpret_cast<CmdQueThread::Command const*>(pCmd);
status_t status = NO_ERROR;
switch (rCmd.eId)
{
case CmdQueThread::Command::eID_TAKE_PICTURE:
status = takePictureProc();
if ( NO_ERROR != status )
{
CAM_LOGD(" mainThread, takePictureProc err: %d", status);
// Error callback T.B.D
}
break;
//
case CmdQueThread::Command::eID_TAKE_PRV_PIC:
status = takePreviewPictureProc();
if ( NO_ERROR != status )
{
CAM_LOGD(" mainThread, takePreviewPictureProc err: %d", status);
// Error callback T.B.D
}
break;
//
case CmdQueThread::Command::eID_SMOOTH_ZOOM:
mZoomStopValue = rCmd.u4Ext1;
mIsSmoothZoom = true;
status = startSmoothZoom(mZoomValue, mZoomStopValue);
if ( NO_ERROR != status )
{
CAM_LOGD(" mainThread, takePreviewPictureProc err: %d", status);
// Error callback T.B.D
}
break;
//
default:
CAM_LOGA("mainThread cannot handle bad command::%s", rCmd.name());
break;
}
return (NO_ERROR==status);
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::decidePanoMaxDim()
{
status_t status = NO_ERROR;
if (mPanoW == 0) {
#if 0
// Try to allocate 16MB memory
int memSize;
sp<CamMemPool> memPool;
memSize = 16 * 1024 * 1024;
memPool = allocMem(memSize, "pano", 1, memSize);
if (memPool->mMemHeapBase != NULL) {
mPanoW = 1600;
mPanoH = 1200;
}
else {
mPanoW = 1280;
mPanoH = 960;
}
memPool = NULL;
#else
// Sysram is not enough, use 1280x960 instead
mPanoW = 1280;
mPanoH = 960;
#endif
CAM_LOGD("[decidePanoMaxDim] W/H: %d/%d \n", mPanoW, mPanoH);
}
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::startMAV(int num)
{
status_t status = NO_ERROR;
CAM_LOGD("[startMAV] %d", num);
strcpy((char *) mmHalCamParam.u1FileName, mParameters.get(MtkCameraParameters::KEY_CAPTURE_PATH));
mmHalCamParam.u4BusrtNo = num;
mmHalCamParam.camExifParam.orientation = mParameters.getInt(MtkCameraParameters::KEY_ROTATION);
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_START_MAV, &mmHalCamParam, sizeof(mhalCamParam_t), NULL, 0, NULL);
if (status != NO_ERROR)
{
CAM_LOGD("error occurs in startMAV");
mNotifyCb(CAMERA_MSG_ERROR, CAMERA_ERROR_RESET, 0, mCallbackCookie);
status = NO_ERROR; // To avoid Java exception in JNI
}
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::stopMAV(int isMerge)
{
status_t status = NO_ERROR;
CAM_LOGD("[stopMAV] %d", isMerge);
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_STOP_MAV, &isMerge, sizeof(int), NULL, 0, NULL);
if (status != NO_ERROR)
{
CAM_LOGD("error occurs in startMAV");
mNotifyCb(CAMERA_MSG_ERROR, CAMERA_ERROR_RESET, 0, mCallbackCookie);
status = NO_ERROR; // To avoid Java exception in JNI
}
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::startAUTORAMA(int num)
{
status_t status = NO_ERROR;
CAM_LOGD("[startAUTORAMA] %d", num);
strcpy((char *) mmHalCamParam.u1FileName, mParameters.get(MtkCameraParameters::KEY_CAPTURE_PATH));
mmHalCamParam.u4BusrtNo = num;
mmHalCamParam.camExifParam.orientation = mParameters.getInt(MtkCameraParameters::KEY_ROTATION);
char *gpsLatitude, *gpsLongitude, *gpsTimestamp, *gpsProcessingMethod;
int gpsAltitude;
gpsAltitude = mParameters.getInt(MtkCameraParameters::KEY_GPS_ALTITUDE);
gpsLatitude = (char *) mParameters.get(MtkCameraParameters::KEY_GPS_LATITUDE);
gpsLongitude = (char *) mParameters.get(MtkCameraParameters::KEY_GPS_LONGITUDE);
gpsTimestamp = (char *) mParameters.get(MtkCameraParameters::KEY_GPS_TIMESTAMP);
gpsProcessingMethod = (char *) mParameters.get(MtkCameraParameters::KEY_GPS_PROCESSING_METHOD);
mmHalCamParam.camExifParam.gpsIsOn = 0;
if ((gpsLatitude != NULL) && (gpsLongitude != NULL)
&& (gpsTimestamp != NULL) && (gpsProcessingMethod != NULL) )
{
CAM_LOGD("GPS is recorded");
strcpy(mmHalCamParam.camExifParam.gpsLongitude, gpsLongitude);
strcpy(mmHalCamParam.camExifParam.gpsLatitude, gpsLatitude);
strcpy(mmHalCamParam.camExifParam.gpsTimeStamp, gpsTimestamp);
strcpy(mmHalCamParam.camExifParam.gpsProcessingMethod, gpsProcessingMethod);
mmHalCamParam.camExifParam.gpsAltitude = gpsAltitude;
mmHalCamParam.camExifParam.gpsIsOn = 1;
}
else
{
CAM_LOGW("[startAUTORAMA] GPS Information are not avaiable !");
}
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_START_AUTORAMA, &mmHalCamParam, sizeof(mhalCamParam_t), NULL, 0, NULL);
if (status != NO_ERROR)
{
CAM_LOGD("error occurs in startAUTORAMA");
mNotifyCb(CAMERA_MSG_ERROR, CAMERA_ERROR_RESET, 0, mCallbackCookie);
status = NO_ERROR; // To avoid Java exception in JNI
}
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::stopAUTORAMA(int isMerge)
{
status_t status = NO_ERROR;
CAM_LOGD("[stopAUTORAMA] %d", isMerge);
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_STOP_AUTORAMA, &isMerge, sizeof(int), NULL, 0, NULL);
if (status != NO_ERROR)
{
CAM_LOGD("error occurs in stopAUTORAMA");
mNotifyCb(CAMERA_MSG_ERROR, CAMERA_ERROR_RESET, 0, mCallbackCookie);
status = NO_ERROR; // To avoid Java exception in JNI
}
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::start3Dshot(int num)
{
status_t status = NO_ERROR;
CAM_LOGD("[start3Dshot] %d", num);
strcpy((char *) mmHalCamParam.u1FileName, mParameters.get(MtkCameraParameters::KEY_CAPTURE_PATH));
mmHalCamParam.u4BusrtNo = num;
mmHalCamParam.camExifParam.orientation = mParameters.getInt(MtkCameraParameters::KEY_ROTATION);
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_START_3DSHOT, &mmHalCamParam, sizeof(mhalCamParam_t), NULL, 0, NULL);
if (status != NO_ERROR)
{
CAM_LOGD("error occurs in start3Dshot");
mNotifyCb(CAMERA_MSG_ERROR, CAMERA_ERROR_RESET, 0, mCallbackCookie);
status = NO_ERROR; // To avoid Java exception in JNI
}
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::stop3Dshot(int isMerge)
{
status_t status = NO_ERROR;
CAM_LOGD("[stop3Dshot] %d", isMerge);
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_STOP_3DSHOT, &isMerge, sizeof(int), NULL, 0, NULL);
if (status != NO_ERROR)
{
CAM_LOGD("error occurs in stop3Dshot");
mNotifyCb(CAMERA_MSG_ERROR, CAMERA_ERROR_RESET, 0, mCallbackCookie);
status = NO_ERROR; // To avoid Java exception in JNI
}
return status;
}
/******************************************************************************
*
*******************************************************************************/
void
MTKCameraHardware::
returnFrame(int32_t const frameType, void*const frameBuf)
{
#warning "[TODO] frame reference counting by means of map"
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::sendCommand(int32_t command, int32_t arg1,
int32_t arg2)
{
status_t status = NO_ERROR;
CAM_LOGD("[sendCommand] cmd: 0x%x, arg: 0x%x,0x%x \n", command, arg1, arg2);
switch (command) {
case CAMERA_CMD_START_SMOOTH_ZOOM:
if ( (0 > arg1) || (mZoom_max_value < arg1) ) {
CAM_LOGD("[sendCommand] ZOOM_MAX_VALUE(%d) <= arg1(%d) \n", mZoom_max_value, arg1);
status = BAD_VALUE;
break;
}
if (mZoomValue == arg1) {
CAM_LOGD("[sendCommand] mZoomValue == arg1(%d) \n", arg1);
status = NO_ERROR;
break;
}
//mpMainThread->postCommand(CmdQueThread::Command(CmdQueThread::Command::eID_SMOOTH_ZOOM, arg1, true));
// [Sean] for ICS zoom performance
// In video mode, the set zoom will use startSmoothZoom
// instead of setParameters()
status = startSmoothZoom(mZoomValue, arg1);
break;
case CAMERA_CMD_STOP_SMOOTH_ZOOM:
status = stopSmoothZoom();
break;
case CAMERA_CMD_ENABLE_FOCUS_MOVE_MSG:
CAM_LOGD("[sendCommand] CAMERA_CMD_ENABLE_FOCUS_MOVE_MSG (%d)\n", arg1);
mIsAFMoveCallback = (arg1 == 0) ? (0) : (1);
status = 0;
break;
case CAMERA_CMD_START_FACE_DETECTION:
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_START_FACE_DETECTION, NULL, 0, NULL, 0, NULL);
break;
case CAMERA_CMD_STOP_FACE_DETECTION:
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_STOP_FACE_DETECTION, NULL, 0, NULL, 0, NULL);
break;
case CAMERA_CMD_START_SD_PREVIEW:
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_START_SD_PREVIEW, NULL, 0, NULL, 0, NULL);
break;
case CAMERA_CMD_CANCEL_SD_PREVIEW:
status = ::mHalIoctl(mmHalFd, MHAL_IOCTL_CANCEL_SD_PREVIEW, NULL, 0, NULL, 0, NULL);
break;
case CAMERA_CMD_START_MAV:
status = startMAV(arg1);
break;
case CAMERA_CMD_STOP_MAV:
status = stopMAV(arg1);
break;
case CAMERA_CMD_START_AUTORAMA:
status = startAUTORAMA(arg1);
break;
case CAMERA_CMD_STOP_AUTORAMA:
status = stopAUTORAMA(arg1);
break;
case CAMERA_CMD_GET_MEM_INFO:
{
CameraMemInfo& rInfo = *reinterpret_cast<CameraMemInfo*>(arg1);
sp<IMemoryBufferPool> pMemPool;
if (mVideoMemPool.get()) {
pMemPool = mVideoMemPool;
}
else {
pMemPool = mPreviewMemPool;
}
if ( sizeof(CameraMemInfo) != arg2 )
{
MY_LOGE("<CAMERA_CMD_GET_MEM_INFO> argument size(%d) != struct size(%d)", arg2, sizeof(CameraMemInfo));
status = BAD_VALUE;
break;
}
if ( CameraMemInfo::eTYPE_PMEM != rInfo.u4Type )
{
MY_LOGE("<CAMERA_CMD_GET_MEM_INFO> type(%d) != PMEM", rInfo.u4Type);
status = BAD_TYPE;
break;
}
if ( ! pMemPool.get() )
{
MY_LOGE("<CAMERA_CMD_GET_MEM_INFO> NULL mVideoMemPool");
status = NO_MEMORY;
break;
}
rInfo.u4VABase = (uint32_t)pMemPool->getVirAddr();
rInfo.u4PABase = (uint32_t)pMemPool->getPhyAddr();
rInfo.u4MemSize = pMemPool->getBufSize();
rInfo.u4MemCount= pMemPool->getBufCount();
MY_LOGI("<CAMERA_CMD_GET_MEM_INFO> type:%d (VA, PA)=(0x%08X, 0x%08X) (u4MemSize, u4MemCount)=(%d, %d)", rInfo.u4Type, rInfo.u4VABase, rInfo.u4PABase, rInfo.u4MemSize, rInfo.u4MemCount);
}
break;
case CAMERA_CMD_CANCEL_CONTINUOUS_SHOT:
status = cancelPicture();
break;
case CAMERA_CMD_SLOW_CONTINUOUS_SHOT:
mmHalCamParam.u4ContinuousShotSpeed = 2;
break;
default:
status = BaseCamAdapter::sendCommand(command, arg1, arg2);
break;
}
return status;
}
/******************************************************************************
*
*******************************************************************************/
status_t MTKCameraHardware::queryQvFmt(int32_t &width, int32_t &height, String8 &s8FrmFormat)
{
if (mQvMemPool != NULL)
{
width = mQvMemPool->getImgWidth();
height = mQvMemPool->getImgHeight();
s8FrmFormat = mQvMemPool->getImgFormat();
return NO_ERROR;
}
else
{
return BAD_VALUE;
}
}
/******************************************************************************
*
*******************************************************************************/
bool
mHalCamAdapter::
onInitParameters()
{
setCamFeatureMode(SCENE_MODE_OFF, MEFFECT_OFF);
initDefaultParameters();
return true;
}
/******************************************************************************
*
*******************************************************************************/
bool
MTKCameraHardware::
init()
{
bool ret = false;
status_t status = NO_ERROR;
//
MY_LOGI("+ tid(%d), OpenId(%d), getStrongCount(%d)", ::gettid(), getOpenId(), getStrongCount());
//
//
if ( ! mHalBaseAdapter::init() || ! mmHalFd )
{
MY_LOGE("mHalBaseAdapter::init() fail");
goto lbExit;
}
//
// preview thread
{
mbPreviewThreadAlive = true;
pthread_attr_t const attr = {0, NULL, 1024 * 1024, 4096, SCHED_RR, RTPM_PRIO_CAMERA_PREVIEW};
::pthread_create(&mPreviewThreadHandle, &attr, _previewThread, this);
}
//
// video thread
{
mbVideoThreadAlive = 0x55555555;
pthread_attr_t const attr = {0, NULL, 1024 * 1024, 4096, SCHED_RR, RTPM_PRIO_CAMERA_RECORD};
::pthread_create(&mVideoThreadHandle, &attr, _videoThread, this);
}
//
// main thread
mpMainThread = new CmdQueThread(this, &MTKCameraHardware::handleMainThreadCommand);
if (
mpMainThread == 0
|| NO_ERROR!=(status = mpMainThread->run())
)
{
MY_LOGE("Fail to run CmdQueThread - (mpMainThread,status)=(%p,%d)", mpMainThread.get(), status);
goto lbExit;
}
//
// mEventCallback
mEventCallback = new EventCallback();
if (
mEventCallback == 0
|| NO_ERROR!=(status = mEventCallback->run())
)
{
MY_LOGE("Fail to run mEventCallback - (mEventCallback,status)=(%p,%d)", mEventCallback.get(), status);
goto lbExit;
}
ret = true;
lbExit:
MY_LOGI("- ret(%d), getStrongCount(%d)", ret, getStrongCount());
return ret;
}
/******************************************************************************
*
*******************************************************************************/
bool
MTKCameraHardware::
uninit()
{
MY_LOGI(
"+ caller tid(%d), OpenId(%d), getStrongCount(%d), mPreviewThreadHandle(%lx), mVideoThreadHandle(%lx),mmHalFd(%p)",
::gettid(), getOpenId(), getStrongCount(), mPreviewThreadHandle, mVideoThreadHandle, mmHalFd
);
if ( mmHalFd )
{
//
{
Mutex::Autolock _lock(mDispQueLock);
MY_LOGD("Clear DispQue");
mDispQue.clear();
mDispQueCond.broadcast();
mbPreviewThreadAlive = false;
}
::sem_post(&mSemPrv);
//
mbVideoThreadAlive = 0;
::sem_post(&mSemVdo);
//
if ( mpMainThread != 0 )
{
MY_LOGD(
"Main Thread: (tid, getStrongCount, mpMainThread)=(%d, %d, %p)",
mpMainThread->getTid(), mpMainThread->getStrongCount(), mpMainThread.get()
);
mpMainThread->requestExit();
mpMainThread = NULL;
}
//
//
if ( mEventCallback != 0 )
{
MY_LOGD(
"FD Thread: (tid, getStrongCount, mEventCallback)=(%d, %d, %p)",
mEventCallback->getTid(), mEventCallback->getStrongCount(), mEventCallback.get()
);
mEventCallback->requestExit();
mEventCallback = NULL;
}
}
//
mHalBaseAdapter::uninit();
//
//
MY_LOGI("- caller tid(%d), getStrongCount(%d)", ::gettid(), getStrongCount());
return true;
}
/******************************************************************************
*
*******************************************************************************/
char const*
MTKCameraHardware::
getCamStateStr(ECamState const eState)
{
static char const* states[] = {
#define STATE_STR(x) #x
STATE_STR(eCS_Init),
STATE_STR(eCS_TakingPicture),
#undef STATE_STR
};
return states[eState];
}
/******************************************************************************
*
*******************************************************************************/
MTKCameraHardware::ECamState
MTKCameraHardware::
changeState(ECamState const eNewState, bool isLock /*= true*/)
{
if (isLock)
{
mStateLock.lock();
}
//
if ( eNewState != meCamState )
{
CAM_LOGD("[state transition] %s --> %s", getCamStateStr(meCamState), getCamStateStr(eNewState));
meCamState = eNewState;
mStateCond.signal();
}
//
if (isLock)
{
mStateLock.unlock();
}
return eNewState;
}
/******************************************************************************
*
*******************************************************************************/
sp<ICamAdapter>
ICamAdapter::
createInstance(String8 const& rName, int32_t const i4OpenId, CamDevInfo const& rDevInfo)
{
switch ( rDevInfo.eDevID )
{
case eDevId_AtvSensor:
case eDevId_ImgSensor:
default:
return new mHalCamAdapter(rName, i4OpenId, rDevInfo);
}
return NULL;
}
}; // namespace android
| gpl-2.0 |
slackstone/tuxjunior | src/scripting/serialize.hpp | 1219 | // $Id: serialize.hpp 4063 2006-07-21 21:05:23Z anmaster $
//
// SuperTux
// Copyright (C) 2006 Matthias Braun <matze@braunis.de>
//
// 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 __SERIALIZE_HPP__
#define __SERIALIZE_HPP__
#include <squirrel.h>
#include <string>
#include "lisp/lisp.hpp"
#include "lisp/writer.hpp"
namespace Scripting
{
void save_squirrel_table(HSQUIRRELVM vm, SQInteger table_idx, lisp::Writer& writer);
void load_squirrel_table(HSQUIRRELVM vm, SQInteger table_idx, const lisp::Lisp* lisp);
}
#endif
| gpl-2.0 |
Saftemand/S_DW_Continuous_Deployment_Test | S_DW_Continuous_Deployment_test/CustomModules/CustomDealersearch/Objects/DealerCollection.cs | 1224 | using Dynamicweb;
using System.Data;
namespace CustomDealersearch
{
public class DealerCollection : System.Collections.Generic.List<Dealer>
{
public DealerCollection()
{
}
public DealerCollection(int categoryID)
{
string SQL = "SELECT * ";
SQL += "FROM DealerSearchDealer ";
if (categoryID > 0)
{
SQL += "WHERE DealerSearchDealerCategoryID = " + categoryID;
}
//SQL += " AND DatoFelt > " & Database.SqlDate(Dates.DWNow)
Init(SQL);
}
public DealerCollection(string sql)
{
Init(sql);
}
public void Init(string sql)
{
Dealer objDealer;
using (IDataReader objDataReader = Database.CreateDataReader(sql, "DealerSearch.mdb"))
{
int index = 0;
while (objDataReader.Read())
{
index += 1;
objDealer = new Dealer();
objDealer.Fill(objDataReader);
objDealer.Index = index;
Add(objDealer);
}
}
}
}
}
| gpl-2.0 |
georgejhunt/HaitiDictionary.activity | data/words/potko.js | 124 | showWord(["adv. "," Poko, pako, advèb ki endike yon bagay poko fini osnon fèt. Jak potko vini lè lapli a tap tonbe a."
]) | gpl-2.0 |
nurulimamnotes/sistem-informasi-sekolah | jibas/infoguru/jadwal/blank_jadwalkelas.php | 2386 | <?
/**[N]**
* JIBAS Education Community
* Jaringan Informasi Bersama Antar Sekolah
*
* @version: 3.2 (September 03, 2013)
* @notes: JIBAS Education Community will be managed by Yayasan Indonesia Membaca (http://www.indonesiamembaca.net)
*
* Copyright (C) 2009 Yayasan Indonesia Membaca (http://www.indonesiamembaca.net)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
**[N]**/ ?>
<?
require_once('../include/sessioninfo.php');
require_once('../include/common.php');
require_once('../include/config.php');
require_once('../include/db_functions.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="../style/style.css">
</head>
<body>
<table border="0" width="100%" height="100%"align="center">
<!-- TABLE CENTER -->
<tr height="250">
<td align="left" valign="middle" >
<table width="100%" border="0" cellspacing="0" cellpadding="0" >
<tr>
<td align="center" valign="middle">
<? OpenDb();
$sql = "SELECT * FROM departemen";
$result = QueryDb($sql);
if (@mysql_num_rows($result) > 0){
?>
<font size="2" color="#757575"><b>Klik pada icon <img src="../images/ico/view_x.png" border="0"> di atas <br />untuk melihat jadwal sesuai dengan Kelas dan Info Jadwal yang terpilih
</font>
<? } else { ?>
<font size = "2" color ="red"><b>Belum ada data Departemen.
<br />Silahkan isi terlebih dahulu di menu Departemen pada bagian Referensi.
</b></font>
<? } ?>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html> | gpl-2.0 |
x2nie/open10fingers | js/util.js | 236 | Array.prototype.contains = function(elm) {
for (var i = 0; i < this.length; i++) {
if (elm == this[i]) return true;
}
return false;
};
Array.prototype.random = function() {
return this[Math.floor(Math.random() * this.length)];
}; | gpl-2.0 |
jschwartzenberg/kicker | kicker/kicker/ui/addapplet.cpp | 9863 | /*****************************************************************
Copyright (c) 2007, 2006 Rafael Fernández López <ereslibre@kde.org>
Copyright (c) 2005 Marc Cramdal
Copyright (c) 2005 Aaron Seigo <aseigo@kde.org>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************/
#include <QApplication>
#include <QComboBox>
#include <QDir>
#include <QLabel>
#include <QLayout>
#include <QLineEdit>
#include <QPalette>
#include <QTimer>
#include <Qt3Support/q3tl.h>
#include <QMimeData>
#include <QMouseEvent>
#include <QPixmap>
#include <QVBoxLayout>
#include <QEvent>
#include <QCloseEvent>
#include <kicon.h>
#include <kdebug.h>
#include <kglobalsettings.h>
#include <kpushbutton.h>
#include <kstandarddirs.h>
#include <KStandardGuiItem>
#include "addapplet.h"
#include "addappletvisualfeedback.h"
#include "container_applet.h"
#include "container_extension.h"
#include "containerarea.h"
#include "kicker.h"
#include "kickerSettings.h"
#include "menuinfo.h"
#include "pluginmanager.h"
AddAppletDialog::AddAppletDialog(ContainerArea *cArea,
QWidget *parent,
const char *name)
: KDialog(parent)
, m_mainWidgetView(new Ui::AppletView())
, m_containerArea(cArea)
, m_insertionPoint(Kicker::self()->insertionPoint())
{
setCaption(i18n("Add Applet"));
Q_UNUSED(name);
setModal(false);
setButtons(KDialog::User1 | KDialog::Close);
setButtonGuiItem(User1, KGuiItem(i18n("Load Applet"), "ok"));
enableButton(KDialog::User1, false);
KConfigGroup cg = KGlobal::config()->group( "AddAppletDialog Settings");
restoreDialogSize(cg);
centerOnScreen(this);
m_mainWidget = new QWidget(this);
m_mainWidgetView->setupUi(m_mainWidget);
setMainWidget(m_mainWidget);
connect(m_mainWidgetView->appletSearch, SIGNAL(textChanged(const QString&)), this, SLOT(search(const QString&)));
connect(m_mainWidgetView->appletFilter, SIGNAL(activated(int)), this, SLOT(filter(int)));
connect(m_mainWidgetView->appletListView, SIGNAL(clicked(const QModelIndex&)), this, SLOT(selectApplet(const QModelIndex&)));
connect(m_mainWidgetView->appletListView, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(addCurrentApplet(const QModelIndex&)));
connect(this, SIGNAL(user1Clicked()), this, SLOT(slotUser1Clicked()));
connect(PluginManager::self(), SIGNAL(pluginDestroyed()), this, SLOT(updateAppletList()));
m_selectedType = AppletInfo::Undefined;
m_mainWidgetView->appletListView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
m_mainWidgetView->appletSearch->setClearButtonShown(true);
QTimer::singleShot(0, this, SLOT(populateApplets()));
}
void AddAppletDialog::updateInsertionPoint()
{
m_insertionPoint = Kicker::self()->insertionPoint();
}
void AddAppletDialog::closeEvent(QCloseEvent *e)
{
KConfigGroup cg( KGlobal::config(), "AddAppletDialog Settings");
KDialog::saveDialogSize( cg );
KDialog::closeEvent(e);
}
void AddAppletDialog::populateApplets()
{
// Loading applets
m_applets = PluginManager::applets(false, &m_applets);
// Loading built in buttons
m_applets = PluginManager::builtinButtons(false, &m_applets);
// Loading special buttons
m_applets = PluginManager::specialButtons(false, &m_applets);
qHeapSort(m_applets);
foreach(AppletInfo appletInfo, m_applets)
{
if (appletInfo.isHidden() || appletInfo.name().isEmpty())
m_applets.erase(&appletInfo);
}
m_listModel = new AppletListModel(m_applets, this);
m_mainWidgetView->appletListView->setModel(m_listModel);
int i = 0;
foreach(AppletInfo appletInfo, m_applets)
{
if (appletInfo.isUniqueApplet() && PluginManager::self()->hasInstance(appletInfo))
m_mainWidgetView->appletListView->setRowHidden(i, true);
i++;
}
AppletItemDelegate *appletItemDelegate = new AppletItemDelegate(this);
appletItemDelegate->setIconSize(48, 48);
appletItemDelegate->setMinimumItemWidth(200);
appletItemDelegate->setLeftMargin(20);
appletItemDelegate->setRightMargin(0);
appletItemDelegate->setSeparatorPixels(20);
m_mainWidgetView->appletListView->setItemDelegate(appletItemDelegate);
}
void AddAppletDialog::selectApplet(const QModelIndex &applet)
{
selectedApplet = applet;
if (!isButtonEnabled(KDialog::User1))
enableButton(KDialog::User1, true);
}
void AddAppletDialog::addCurrentApplet(const QModelIndex &selectedApplet)
{
this->selectedApplet = selectedApplet;
AppletInfo applet(m_applets[selectedApplet.row()]);
QPoint prevInsertionPoint = Kicker::self()->insertionPoint();
Kicker::self()->setInsertionPoint(m_insertionPoint);
const QWidget* appletContainer = 0;
if (applet.type() == AppletInfo::Applet)
{
appletContainer = m_containerArea->addApplet(applet);
}
else if (applet.type() & AppletInfo::Button)
{
appletContainer = m_containerArea->addButton(applet);
}
if (appletContainer)
{
ExtensionContainer* ec = dynamic_cast<ExtensionContainer*>(m_containerArea->topLevelWidget());
if (ec)
{
// unhide the panel and keep it unhidden for at least the time the
// helper tip will be there
ec->unhideIfHidden(KickerSettings::mouseOversSpeed() + 2500);
}
new AddAppletVisualFeedback(selectedApplet,
m_mainWidgetView->appletListView,
appletContainer,
m_containerArea->popupDirection());
}
if (applet.isUniqueApplet() && PluginManager::self()->hasInstance(applet))
{
m_mainWidgetView->appletListView->setRowHidden(selectedApplet.row(), true);
m_mainWidgetView->appletListView->clearSelection();
enableButton(KDialog::User1, false);
}
Kicker::self()->setInsertionPoint(prevInsertionPoint);
}
bool AddAppletDialog::appletMatchesSearch(const AppletInfo *i, const QString &s)
{
if (i->type() == AppletInfo::Applet &&
i->isUniqueApplet() && PluginManager::self()->hasInstance(*i))
{
return false;
}
return (m_selectedType == AppletInfo::Undefined ||
i->type() & m_selectedType) &&
(i->name().contains(s, Qt::CaseInsensitive) ||
i->comment().contains(s, Qt::CaseInsensitive));
}
void AddAppletDialog::search(const QString &s)
{
AppletInfo *appletInfo;
for (int i = 0; i < m_listModel->rowCount(); i++)
{
appletInfo = static_cast<AppletInfo*>(m_listModel->index(i).internalPointer());
m_mainWidgetView->appletListView->setRowHidden(i, !appletMatchesSearch(appletInfo, s) ||
(appletInfo->isUniqueApplet() &&
PluginManager::self()->hasInstance(*appletInfo)));
}
/**
* If our selection gets hidden because of searching, we deselect it and
* disable the "Add Applet" button.
*/
if ((selectedApplet.isValid() &&
(m_mainWidgetView->appletListView->isRowHidden(selectedApplet.row()))) ||
(!selectedApplet.isValid()))
{
m_mainWidgetView->appletListView->clearSelection();
enableButton(KDialog::User1, false);
}
}
void AddAppletDialog::filter(int i)
{
m_selectedType = AppletInfo::Undefined;
if (i == 1)
{
m_selectedType = AppletInfo::Applet;
}
else if (i == 2)
{
m_selectedType = AppletInfo::Button;
}
AppletInfo *appletInfo;
QString searchString = m_mainWidgetView->appletSearch->text();
for (int j = 0; j < m_listModel->rowCount(); j++)
{
appletInfo = static_cast<AppletInfo*>(m_listModel->index(j).internalPointer());
m_mainWidgetView->appletListView->setRowHidden(j, !appletMatchesSearch(appletInfo, searchString) ||
(appletInfo->isUniqueApplet() &&
PluginManager::self()->hasInstance(*appletInfo)));
}
/**
* If our selection gets hidden because of filtering, we deselect it and
* disable the "Add Applet" button.
*/
if ((selectedApplet.isValid() &&
(m_mainWidgetView->appletListView->isRowHidden(selectedApplet.row()))) ||
(!selectedApplet.isValid()))
{
m_mainWidgetView->appletListView->clearSelection();
enableButton(KDialog::User1, false);
}
}
void AddAppletDialog::slotUser1Clicked()
{
if (selectedApplet.isValid())
{
addCurrentApplet(selectedApplet);
}
}
void AddAppletDialog::updateAppletList()
{
search(m_mainWidgetView->appletSearch->text());
}
#include "addapplet.moc"
| gpl-2.0 |
iWantMoneyMore/ykj | ykj-api/src/main/java/com/gnet/app/customerHouseProperty/CustomerHouseProperty.java | 1165 | package com.gnet.app.customerHouseProperty;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.gnet.mybatis.BaseEntity;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
@Entity
@Table(name = "ykj_customer_house_property")
public class CustomerHouseProperty extends BaseEntity{
private static final long serialVersionUID = -4584865205360689505L;
/** 创建时间 **/
private @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date createDate;
/** 更新时间 **/
private @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date modifyDate;
/** 客户编号 **/
private String customerId;
/** 楼盘名称 **/
private String buildingName;
/** 楼幢房号 **/
private String buildingNo;
/** 风格 **/
private Integer roomStyle;
/** 装修进度 **/
private Integer decorateProcess;
/** 装修类型 **/
private Integer decorateType;
/** 户型 **/
private Integer roomModel;
/** 区域 **/
private String buildingPosition;
/** 面积 **/
private Integer area;
}
| gpl-2.0 |
Fluorohydride/ygopro-scripts | c48576971.lua | 3040 | --与奪の首飾り
function c48576971.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_CONTINUOUS_TARGET)
e1:SetTarget(c48576971.target)
e1:SetOperation(c48576971.operation)
c:RegisterEffect(e1)
--Equip limit
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_EQUIP_LIMIT)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetValue(1)
c:RegisterEffect(e2)
--effect
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(48576971,0))
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetCondition(c48576971.effcon)
e3:SetTarget(c48576971.efftg)
e3:SetOperation(c48576971.effop)
c:RegisterEffect(e3)
end
function c48576971.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsFaceup() end
if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c48576971.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Equip(tp,c,tc)
end
end
function c48576971.effcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local ec=c:GetPreviousEquipTarget()
return c:IsReason(REASON_LOST_TARGET) and ec:IsReason(REASON_BATTLE) and ec:IsPreviousControler(tp)
end
function c48576971.efftg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local opt=0
local b1=Duel.IsPlayerCanDraw(tp,1)
local b2=Duel.GetFieldGroupCount(tp,0,LOCATION_HAND)>0
if b1 and b2 then
opt=Duel.SelectOption(tp,aux.Stringid(48576971,1),aux.Stringid(48576971,2))
elseif b1 then
opt=Duel.SelectOption(tp,aux.Stringid(48576971,1))
elseif b2 then
opt=Duel.SelectOption(tp,aux.Stringid(48576971,2))+1
else opt=2 end
e:SetLabel(opt)
if opt==0 then
e:SetCategory(CATEGORY_DRAW)
e:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
elseif opt==1 then
e:SetCategory(CATEGORY_HANDES)
e:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
Duel.SetTargetPlayer(1-tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_HANDES,nil,0,1-tp,1)
else
e:SetCategory(0)
e:SetProperty(0)
end
end
function c48576971.effop(e,tp,eg,ep,ev,re,r,rp)
if e:GetLabel()==0 then
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Draw(p,d,REASON_EFFECT)
elseif e:GetLabel()==1 then
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
local g=Duel.GetFieldGroup(p,LOCATION_HAND,0):RandomSelect(p,d)
Duel.SendtoGrave(g,REASON_EFFECT+REASON_DISCARD)
end
end
| gpl-2.0 |
agencerebus/Site-ariew | wp-content/themes/FoundationPress-master/js/script.js | 8382 | (function ($, root, undefined) {
$(function () {
'use strict';
init();
});
function init(){
first_scroll();
fixed_header();
margin_top();
copyright();
absolute_center('#arrow');
absolute_center('.calltoaction_text');
absolute_center('.bloc_content5');
details_toggle();
slider_produit();
click_produit();
preco_resize();
bullet_nav_post('.bullet-text');
hover_home();
var home_page = $('#home_bloc_2');
if (home_page.length){
nav_intern();
}
}
$(window).resize(function() {
preco_resize();
fixed_header();
margin_top();
copyright();
absolute_center('#arrow');
absolute_center('.calltoaction_text');
absolute_center('.bloc_content5');
});
function margin_top(){
var height_1 = $('#home_bloc_intro').height();
height_1 -= $('.menu-home-wrapper').outerHeight();
$('#home_bloc_2').css({'margin-top': height_1})
}
function hover_home(){
$('#home_bloc_5 img').each(function(e){
var src = $(this).attr('src');
$(this).hover(function(){
$(this).attr('src', src.replace('.png', '_hover.png'));
}, function(){
$(this).attr('src', src);
});
});
}
function first_scroll(){
$("#arrow").click(function() {
$('html, body').animate({
scrollTop: $('#home_bloc_2').offset().top
}, 500);
});
}
function nav_intern(){
if ($(this).scrollTop() <= $('#home_bloc_2').offset().top) {
$('.bullet-nav').removeClass('bull-active');
$('.bullet-nav[data-position="1"]').addClass('bull-active');
}
$('.bullet-nav').click(function(){
var number = $(this).data("position");
switch(number) {
case 1:
$('html, body').animate({
scrollTop: $('body').offset().top
}, 500);
$('.bullet-nav').removeClass('bull-active');
$(this).addClass('bull-active');
break;
case 2:
$('html, body').animate({
scrollTop: $('#home_bloc_2').offset().top
}, 500);
$('.bullet-nav').removeClass('bull-active');
$(this).addClass('bull-active');
break;
case 3:
$('html, body').animate({
scrollTop: $('#home_bloc_3').offset().top
}, 500);
$('.bullet-nav').removeClass('bull-active');
$(this).addClass('bull-active');
break;
case 4:
$('html, body').animate({
scrollTop: $('#home_bloc_4').offset().top
}, 500);
$('.bullet-nav').removeClass('bull-active');
$(this).addClass('bull-active');
break;
case 5:
$('html, body').animate({
scrollTop: $('#home_bloc_5').offset().top
}, 500);
$('.bullet-nav').removeClass('bull-active');
$(this).addClass('bull-active');
break;
case 6:
$('html, body').animate({
scrollTop: $('#home_bloc_6').offset().top
}, 500);
$('.bullet-nav').removeClass('bull-active');
$(this).addClass('bull-active');
break;
default:
}
})
$(window).scroll(function() {
if ($(this).scrollTop() <= $('#home_bloc_2').offset().top) {
$('.bullet-nav').removeClass('bull-active');
$('.bullet-nav[data-position="1"]').addClass('bull-active');
}
if ($(this).scrollTop() >= ($('#home_bloc_2').offset().top)-250) {
$('.bullet-nav').removeClass('bull-active');
$('.bullet-nav[data-position="2"]').addClass('bull-active');
}
if ($(this).scrollTop() >= ($('#home_bloc_3').offset().top)-250) {
$('.bullet-nav').removeClass('bull-active');
$('.bullet-nav[data-position="3"]').addClass('bull-active');
}
if ($(this).scrollTop() >= ($('#home_bloc_4').offset().top)-250) {
$('.bullet-nav').removeClass('bull-active');
$('.bullet-nav[data-position="4"]').addClass('bull-active');
}
if ($(this).scrollTop() >= ($('#home_bloc_5').offset().top)-250) {
$('.bullet-nav').removeClass('bull-active');
$('.bullet-nav[data-position="5"]').addClass('bull-active');
}
if ($(this).scrollTop() >= ($('#home_bloc_6').offset().top)-250) {
$('.bullet-nav').removeClass('bull-active');
$('.bullet-nav[data-position="6"]').addClass('bull-active');
}
});
}
function absolute_center(el){
elW = $(el).width();
$(el).css({'margin-left': -elW/2})
}
function fixed_header(){
var height = $(window).height();
height -= $('.menu-home-wrapper').outerHeight();;
$(window).scroll(function() {
if ($(this).scrollTop() >= height){
$('.menu-home-wrapper').addClass("fixedmenu");
} else {
$('.menu-home-wrapper').removeClass("fixedmenu");
}
});
}
function copyright(){
var genWidth = $('body').width();
if ( genWidth <= 992){
$('#copyright').insertAfter('.socials');
}
}
function preco_resize(){
var genWidth = $('body').width();
if ( genWidth <= 768){
$('#form_preco').removeClass('medium-6').addClass('medium-12');
}
}
function details_toggle(){
$('#depassement').click(function(){
$('#details2, #details3').hide();
$('#details1').fadeIn('slow').show();
})
$('#plaisir').click(function(){
$('#details1, #details3').hide();
$('#details2').fadeIn('slow').show();
})
$('#communaute').click(function(){
$('#details1, #details2').hide();
$('#details3').fadeIn('slow').show();
})
}
function slider_produit(){
$('#li-elegance').click(function(){
$('.li-active').removeClass('li-active');
$(this).addClass('li-active');
$('#img_free').hide();
$('#img_defi').hide();
$('#img_poursuite').hide();
$('#img_montre').hide();
$('.defi_wrapper').hide();
$('.free_wrapper').hide();
$('.montre_wrapper').hide();
$('.poursuite_wrapper').hide();
$('#img_elegance').fadeIn('slow').show();
$('.elegance_wrapper').fadeIn('slow').show();
})
$('#li-free').click(function(){
$('.li-active').removeClass('li-active');
$(this).addClass('li-active');
$('#img_elegance').hide();
$('#img_defi').hide();
$('#img_poursuite').hide();
$('#img_montre').hide();
$('.elegance_wrapper').hide();
$('.poursuite_wrapper').hide();
$('.defi_wrapper').hide();
$('.montre_wrapper').hide();
$('#img_free').fadeIn('slow').show();
$('.free_wrapper').fadeIn('slow').show();
})
$('#li-poursuite').click(function(){
$('.li-active').removeClass('li-active');
$(this).addClass('li-active');
$('#img_free').hide();
$('#img_elegance').hide();
$('#img_defi').hide();
$('#img_montre').hide();
$('.free_wrapper').hide();
$('.elegance_wrapper').hide();
$('.defi_wrapper').hide();
$('.montre_wrapper').hide()
$('#img_poursuite').fadeIn('slow').show();
$('.poursuite_wrapper').fadeIn('slow').show();
})
$('#li-defi').click(function(){
$('.li-active').removeClass('li-active');
$(this).addClass('li-active');
$('#img_free').hide();
$('#img_elegance').hide();
$('#img_poursuite').hide();
$('#img_montre').hide();
$('.free_wrapper').hide();
$('.poursuite_wrapper').hide();
$('.elegance_wrapper').hide();
$('.montre_wrapper').hide();
$('#img_defi').fadeIn('slow').show();
$('.defi_wrapper').fadeIn('slow').show();
})
$('#li-montre').click(function(){
$('.li-active').removeClass('li-active');
$(this).addClass('li-active');
$('#img_free').hide();
$('#img_elegance').hide();
$('#img_poursuite').hide();
$('#img_defi').hide();
$('.free_wrapper').hide();
$('.poursuite_wrapper').hide();
$('.elegance_wrapper').hide();
$('.defi_wrapper').hide();
$('#img_montre').fadeIn('slow').show();
$('.montre_wrapper').fadeIn('slow').show();
})
}
function click_produit(){
$('.circle1').click(function (){
$('#haute_def_title').hide();
$('#haute_def_content').hide();
$('#capacite_title').hide();
$('#capacite_content').hide();
$('#immersion_title').fadeIn('slow').show();
$('#immersion_content').fadeIn('slow').show();
})
$('.circle2').click(function (){
$('#haute_def_title').hide();
$('#haute_def_content').hide();
$('#immersion_title').hide();
$('#immersion_content').hide();
$('#capacite_title').fadeIn('slow').show();
$('#capacite_content').fadeIn('slow').show();
})
$('.circle3').click(function (){
$('#immersion_title').hide();
$('#immersion_content').hide();
$('#capacite_title').hide();
$('#capacite_content').hide();
$('#haute_def_title').fadeIn('slow').show();
$('#haute_def_content').fadeIn('slow').show();
})
}
function bullet_nav_post(el){
$(el).each(function() {
elW = $(this).width();
$(this).css({'margin-left': - elW})
});
}
})(jQuery, this);
| gpl-2.0 |
belkincapital/wpmunotify | js/notification-js.php | 5857 | <?php
/**
* WPMU Push (wpmunotify.com)
* Prepare notification script
* @author: Jason Jersey
* @since: 1.0
*/
function wpmun_notify_js() {
global $wpdb;
$user_id = get_current_user_id();
$post_id = get_posts("numberposts=1");
$wpmun_ip_address = $_SERVER['REMOTE_ADDR']; /** receiver ip */
$wpmun_post_id = $post_id[0]->ID; /** post id */
$db_table = $wpdb->prefix . 'wpmunotify_posts_activity';
$sql_one = $wpdb->query("SELECT * FROM $db_table WHERE user_id = $user_id AND post_id = $wpmun_post_id");
$sql_two = $wpdb->query("SELECT * FROM $db_table WHERE ip_address = '$wpmun_ip_address' AND post_id = $wpmun_post_id");
/** Get plugin directory url */
$wpmunotify_url = plugin_dir_url( dirname(__FILE__) );
if ( is_user_logged_in() ) {/** START: if logged in */
/** the code within this function (below) is javascript */
?>
<?php if ( ! $sql_one == $user_id && $wpmun_post_id ) { ?>
<?php query_posts('showposts=1'); ?>
<?php while (have_posts()) : the_post(); ?>
jQuery(function() {
jQuery(document).ready(function() {
/*Set the timeout timer, 30000 milliseconds equals 30 seconds*/
var timer = 30000, timeoutId;
/*Set the selector for the notification alert box*/
var notiAlert = jQuery(".wpmunotify_noti");
/*Call the function to show the notification alert box*/
showAlert();
/*Call the function to start the timer to close the notification alert box*/
startTimer();
/**
* The function to show notification alert box
* <?php echo wp_get_attachment_url(get_post_thumbnail_id($post->ID)); ?>
* <?php echo get_avatar_url(get_the_author_meta('ID'), wp_parse_args( $args, array( 'size' => 30 ) )); ?>
*/
function showAlert() {
jQuery(".wpmunotify_notification").html('<a rel="permalink" href="<?php the_permalink(); ?>"><div class="wpmunotify_noti noti_clearfix"><div class="wpmunotify_noti_image noti_left" style="background-image: url(<?php echo get_avatar_url(get_the_author_meta('ID'), wp_parse_args( $args, array( 'size' => 30 ) )); ?>);"></div><div class="wpmunotify_noti_content noti_left"><p><b><?php echo get_the_author(); ?></b> published: "<?php echo ucwords( get_the_title() ); ?>"</p><span class="wpmunotify_noti_time"><i class="icon_comment"></i> <?php the_time('F j, Y'); ?></span></div><div class="icon_close noti_right" id="close"></div></div></a>');
var wpmupsnd = new Audio("<?php echo $wpmunotify_url; ?>audio/new_post.mp3");wpmupsnd.volume = 0.2;wpmupsnd.play();
}
/*The function to start the timeout timer*/
function startTimer() {
timeoutId = setTimeout(function() {
jQuery(".wpmunotify_noti").hide();
}, timer);
}
/*The function to stop the timeout timer*/
function stopTimer() {
clearTimeout(timeoutId);
}
/*Call the stopTimer function on mouse enter and call the startTimer function on mouse leave*/
jQuery(".wpmunotify_noti").mouseenter(stopTimer).mouseleave(startTimer);
/*Close the notification alert box when close button is clicked*/
jQuery("#close").click(function() {
jQuery(".wpmunotify_noti").hide();
});
});
});
<?php endwhile; ?>
<?php wpmunotify_insert_posts_activity_data(); } ?>
<?php
/** the code within this function (above) is javascript */
}/** END: if logged in */
else { /** START: if logged out */
/** the code within this function (below) is javascript */
?>
<?php if ( ! $sql_two == $wpmun_ip_address && $wpmun_post_id ) { ?>
<?php query_posts('showposts=1'); ?>
<?php while (have_posts()) : the_post(); ?>
jQuery(function() {
jQuery(document).ready(function() {
/*Set the timeout timer, 30000 milliseconds equals 30 seconds*/
var timer = 30000, timeoutId;
/*Set the selector for the notification alert box*/
var notiAlert = jQuery(".wpmunotify_noti");
/*Call the function to show the notification alert box*/
showAlert();
/*Call the function to start the timer to close the notification alert box*/
startTimer();
/**
* The function to show notification alert box
* <?php echo wp_get_attachment_url(get_post_thumbnail_id($post->ID)); ?>
* <?php echo get_avatar_url(get_the_author_meta('ID'), wp_parse_args( $args, array( 'size' => 30 ) )); ?>
*/
function showAlert() {
jQuery(".wpmunotify_notification").html('<a rel="permalink" href="<?php the_permalink(); ?>"><div class="wpmunotify_noti noti_clearfix"><div class="wpmunotify_noti_image noti_left" style="background-image: url(<?php echo get_avatar_url(get_the_author_meta('ID'), wp_parse_args( $args, array( 'size' => 30 ) )); ?>);"></div><div class="wpmunotify_noti_content noti_left"><p><b><?php echo get_the_author(); ?></b> published: "<?php echo ucwords( get_the_title() ); ?>"</p><span class="wpmunotify_noti_time"><i class="icon_comment"></i> <?php the_time('F j, Y'); ?></span></div><div class="icon_close noti_right" id="close"></div></div></a>');
var wpmupsnd = new Audio("<?php echo $wpmunotify_url; ?>audio/new_post.mp3");wpmupsnd.volume = 0.2;wpmupsnd.play();
}
/*The function to start the timeout timer*/
function startTimer() {
timeoutId = setTimeout(function() {
jQuery(".wpmunotify_noti").hide();
}, timer);
}
/*The function to stop the timeout timer*/
function stopTimer() {
clearTimeout(timeoutId);
}
/*Call the stopTimer function on mouse enter and call the startTimer function on mouse leave*/
jQuery(".wpmunotify_noti").mouseenter(stopTimer).mouseleave(startTimer);
/*Close the notification alert box when close button is clicked*/
jQuery("#close").click(function() {
jQuery(".wpmunotify_noti").hide();
});
});
});
<?php endwhile; ?>
<?php wpmunotify_insert_posts_activity_data(); } ?>
<?php
/** the code within this function (above) is javascript */
}/** END: if logged out */
}/** END: wpmun_notify_js() */
?> | gpl-2.0 |
ksjogo/TYPO3.CMS | typo3/sysext/workspaces/Classes/Domain/Record/WorkspaceRecord.php | 6359 | <?php
namespace TYPO3\CMS\Workspaces\Domain\Record;
/*
* 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\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Workspaces\Service\StagesService;
/**
* Combined record class
*/
class WorkspaceRecord extends AbstractRecord
{
/**
* @var array
*/
protected $internalStages = [
StagesService::STAGE_EDIT_ID => [
'name' => 'edit',
'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_mod_user_ws.xlf:stage_editing'
],
StagesService::STAGE_PUBLISH_ID => [
'name' => 'publish',
'label' => 'LLL:EXT:workspaces/Resources/Private/Language/locallang_mod.xlf:stage_ready_to_publish'
],
StagesService::STAGE_PUBLISH_EXECUTE_ID => [
'name' => 'execute',
'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_mod_user_ws.xlf:stage_publish'
],
];
/**
* @var array
*/
protected $internalStageFieldNames = [
'notification_defaults',
'notification_preselection',
'allow_notificaton_settings'
];
/**
* @var array
*/
protected $owners;
/**
* @var array
*/
protected $members;
/**
* @var StageRecord[]
*/
protected $stages;
/**
* @param int $uid
* @param array $record
* @return WorkspaceRecord
*/
public static function get($uid, array $record = null)
{
if (empty($uid)) {
$record = [];
} elseif (empty($record)) {
$record = static::fetch('sys_workspace', $uid);
}
return new static($record);
}
/**
* @return array
*/
public function getOwners()
{
if (!isset($this->owners)) {
$this->owners = $this->getStagesService()->resolveBackendUserIds($this->record['adminusers']);
}
return $this->owners;
}
/**
* @return array
*/
public function getMembers()
{
if (!isset($this->members)) {
$this->members = $this->getStagesService()->resolveBackendUserIds($this->record['members']);
}
return $this->members;
}
/**
* @return StageRecord[]
*/
public function getStages()
{
if (!isset($this->stages)) {
$this->stages = [];
$this->addStage($this->createInternalStage(StagesService::STAGE_EDIT_ID));
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('sys_workspace_stage');
$result = $queryBuilder
->select('*')
->from('sys_workspace_stage')
->where(
$queryBuilder->expr()->eq(
'parentid',
$queryBuilder->createNamedParameter($this->getUid(), \PDO::PARAM_INT)
),
$queryBuilder->expr()->eq(
'parenttable',
$queryBuilder->createNamedParameter('sys_workspace', \PDO::PARAM_STR)
)
)
->orderBy('sorting')
->execute();
while ($record = $result->fetch()) {
$this->addStage(StageRecord::build($this, $record['uid'], $record));
}
$this->addStage($this->createInternalStage(StagesService::STAGE_PUBLISH_ID));
$this->addStage($this->createInternalStage(StagesService::STAGE_PUBLISH_EXECUTE_ID));
}
return $this->stages;
}
/**
* @param int $stageId
* @return NULL|StageRecord
*/
public function getStage($stageId)
{
$stageId = (int)$stageId;
$this->getStages();
if (!isset($this->stages[$stageId])) {
return null;
}
return $this->stages[$stageId];
}
/**
* @param int $stageId
* @return NULL|StageRecord
*/
public function getPreviousStage($stageId)
{
$stageId = (int)$stageId;
$stageIds = array_keys($this->getStages());
$stageIndex = array_search($stageId, $stageIds);
// catches "0" (edit stage) as well
if (empty($stageIndex)) {
return null;
}
$previousStageId = $stageIds[$stageIndex - 1];
return $this->stages[$previousStageId];
}
/**
* @param int $stageId
* @return NULL|StageRecord
*/
public function getNextStage($stageId)
{
$stageId = (int)$stageId;
$stageIds = array_keys($this->getStages());
$stageIndex = array_search($stageId, $stageIds);
if ($stageIndex === false || !isset($stageIds[$stageIndex + 1])) {
return null;
}
$nextStageId = $stageIds[$stageIndex + 1];
return $this->stages[$nextStageId];
}
/**
* @param StageRecord $stage
*/
protected function addStage(StageRecord $stage)
{
$this->stages[$stage->getUid()] = $stage;
}
/**
* @param int $stageId
* @return StageRecord
* @throws \RuntimeException
*/
protected function createInternalStage($stageId)
{
$stageId = (int)$stageId;
if (!isset($this->internalStages[$stageId])) {
throw new \RuntimeException('Invalid internal stage "' . $stageId . '"', 1476048246);
}
$record = [
'uid' => $stageId,
'title' => static::getLanguageService()->sL($this->internalStages[$stageId]['label'])
];
$fieldNamePrefix = $this->internalStages[$stageId]['name'] . '_';
foreach ($this->internalStageFieldNames as $fieldName) {
$record[$fieldName] = $this->record[$fieldNamePrefix . $fieldName];
}
$stage = StageRecord::build($this, $stageId, $record);
$stage->setInternal(true);
return $stage;
}
}
| gpl-2.0 |
svn2github/autowikibrowser | tags/REL_4_3_2/UnitTests/ToolsTests.cs | 15590 | using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using WikiFunctions;
using System.Text.RegularExpressions;
using System.Diagnostics;
namespace UnitTests
{
[TestFixture]
public class ToolsTests
{
public ToolsTests()
{
Globals.UnitTestMode = true;
}
[Test]
public void TestInvalidChars()
{
Assert.IsTrue(Tools.IsValidTitle("test"));
Assert.IsTrue(Tools.IsValidTitle("This is a_test"));
Assert.IsTrue(Tools.IsValidTitle("123"));
Assert.IsTrue(Tools.IsValidTitle("А & Б сидели на трубе! ة日?"));
Assert.IsFalse(Tools.IsValidTitle(""), "Empty strings are not supposed to be valid titles");
Assert.IsFalse(Tools.IsValidTitle("[xxx"));
Assert.IsFalse(Tools.IsValidTitle("]abc"));
Assert.IsFalse(Tools.IsValidTitle("{duh!"));
Assert.IsFalse(Tools.IsValidTitle("}yoyo"));
Assert.IsFalse(Tools.IsValidTitle("|pwn3d"));
Assert.IsFalse(Tools.IsValidTitle("<1337"));
Assert.IsFalse(Tools.IsValidTitle(">nooooo"));
Assert.IsFalse(Tools.IsValidTitle("#yeee-hooo"));
//Complex titles
Assert.IsFalse(Tools.IsValidTitle("[test]#1"));
Assert.IsFalse(Tools.IsValidTitle("_ _"), "Titles should be normalised before checking");
Assert.IsTrue(Tools.IsValidTitle("http://www.wikipedia.org")); //unfortunately
Assert.IsTrue(Tools.IsValidTitle("index.php/Viagra")); //even more unfortunately
Assert.IsTrue(Tools.IsValidTitle("index.php?title=foobar"));
}
[Test]
public void RemoveInvalidChars()
{
Assert.AreEqual("tesT 123!", Tools.RemoveInvalidChars("tesT 123!"));
Assert.AreEqual("тест, ёпта", Tools.RemoveInvalidChars("тест, ёпта"));
Assert.AreEqual("", Tools.RemoveInvalidChars(""));
Assert.AreEqual("test", Tools.RemoveInvalidChars("{<[test]>}"));
Assert.AreEqual("", Tools.RemoveInvalidChars("#|#"));
Assert.AreEqual("http://www.wikipedia.org", Tools.RemoveInvalidChars("http://www.wikipedia.org"));
}
[Test]
public void TestRomanNumbers()
{
Assert.IsTrue(Tools.IsRomanNumber("XVII"));
Assert.IsTrue(Tools.IsRomanNumber("I"));
Assert.IsFalse(Tools.IsRomanNumber("xvii"));
Assert.IsFalse(Tools.IsRomanNumber("XXXXXX"));
Assert.IsFalse(Tools.IsRomanNumber("V II"));
Assert.IsFalse(Tools.IsRomanNumber("AAA"));
Assert.IsFalse(Tools.IsRomanNumber("123"));
Assert.IsFalse(Tools.IsRomanNumber(" "));
Assert.IsFalse(Tools.IsRomanNumber(""));
}
[Test]
public void TestCaseInsensitive()
{
Assert.AreEqual("", Tools.CaseInsensitive(""));
Assert.AreEqual("123", Tools.CaseInsensitive("123"));
Assert.AreEqual("-", Tools.CaseInsensitive("-"));
Regex r = new Regex(Tools.CaseInsensitive("test"));
Assert.IsTrue(r.IsMatch("test 123"));
Assert.AreEqual("Test", r.Match("Test").Value);
Assert.IsFalse(r.IsMatch("tEst"));
r = new Regex(Tools.CaseInsensitive("Test"));
Assert.IsTrue(r.IsMatch("test 123"));
Assert.AreEqual("Test", r.Match("Test").Value);
Assert.IsFalse(r.IsMatch("TEst"));
r = new Regex(Tools.CaseInsensitive("[test}"));
Assert.IsTrue(r.IsMatch("[test}"));
Assert.IsFalse(r.IsMatch("[Test}"));
Assert.IsFalse(r.IsMatch("test"));
}
[Test]
public void TestAllCaseInsensitive()
{
Assert.AreEqual("", Tools.AllCaseInsensitive(""));
Assert.AreEqual("123", Tools.AllCaseInsensitive("123"));
Assert.AreEqual("-", Tools.AllCaseInsensitive("-"));
Regex r = new Regex(Tools.AllCaseInsensitive("tEsT"));
Assert.IsTrue(r.IsMatch("Test 123"));
Assert.AreEqual("Test", r.Match("Test").Value);
Assert.IsFalse(r.IsMatch("teZt"));
r = new Regex(Tools.AllCaseInsensitive("[test}"));
Assert.IsTrue(r.IsMatch("[test}"));
Assert.IsTrue(r.IsMatch("[tEsT}"));
Assert.IsFalse(r.IsMatch("test"));
}
[Test, Ignore("Too slow")]
public void TestTurnFirstToUpper()
{
Assert.AreEqual("", Tools.TurnFirstToUpper(""));
Assert.AreEqual("ASDA", Tools.TurnFirstToUpper("ASDA"));
Assert.AreEqual("ASDA", Tools.TurnFirstToUpper("aSDA"));
Assert.AreEqual("%test", Tools.TurnFirstToUpper("%test"));
Assert.AreEqual("Ыыыы", Tools.TurnFirstToUpper("ыыыы"));
Variables.SetProject(LangCodeEnum.en, ProjectEnum.wiktionary);
Assert.AreEqual("test", Tools.TurnFirstToUpper("test"));
Assert.AreEqual("Test", Tools.TurnFirstToUpper("Test"));
}
[Test]
public void TestTurnFirstToLower()
{
Assert.AreEqual("", Tools.TurnFirstToLower(""));
Assert.AreEqual("test", Tools.TurnFirstToLower("test"));
Assert.AreEqual("%test", Tools.TurnFirstToLower("%test"));
Assert.AreEqual("ыыыы", Tools.TurnFirstToLower("Ыыыы"));
Assert.AreEqual("tEST", Tools.TurnFirstToLower("TEST"));
Assert.AreEqual("test", Tools.TurnFirstToLower("Test"));
}
[Test]
public void TestWordCount()
{
Assert.AreEqual(0, Tools.WordCount(""));
Assert.AreEqual(0, Tools.WordCount(" "));
Assert.AreEqual(0, Tools.WordCount("."));
Assert.AreEqual(1, Tools.WordCount("foo"));
Assert.AreEqual(2, Tools.WordCount("Превед медвед"));
Assert.AreEqual(1, Tools.WordCount("123"));
Assert.AreEqual(3, Tools.WordCount("foo\nbar\r\nboz"));
Assert.AreEqual(2, Tools.WordCount("foo.bar"));
Assert.AreEqual(1, Tools.WordCount("foo<!-- bar boz -->"));
Assert.AreEqual(1, Tools.WordCount("foo<!--bar-->quux"));
Assert.AreEqual(2, Tools.WordCount("foo <!--\r\nbar--> quux"));
Assert.AreEqual(2, Tools.WordCount("foo {{template| bar boz box}} quux"));
Assert.AreEqual(2, Tools.WordCount("foo{{template\r\n|boz = quux}}bar"));
Assert.AreEqual(2, Tools.WordCount(@"foo
{|
! test !! test
|-
| test
| test || test
|-
|}bar"));
Assert.AreEqual(2, Tools.WordCount(@"foo
{|
! test !! test
|-
| test
| test || test
|-
|}
bar"));
Assert.AreEqual(1, Tools.WordCount(@"foo
{| class=""wikitable""
! test !! test
|- style=""color:red""
| test
| test || test
|-
|}"));
}
[Test]
public void TestReplacePartOfString()
{
Assert.AreEqual("abc123ef", Tools.ReplacePartOfString("abcdef", 3, 1, "123"));
Assert.AreEqual("123abc", Tools.ReplacePartOfString("abc", 0, 0, "123"));
Assert.AreEqual("abc123", Tools.ReplacePartOfString("abc", 3, 0, "123"));
Assert.AreEqual("123", Tools.ReplacePartOfString("", 0, 0, "123"));
Assert.AreEqual("abc", Tools.ReplacePartOfString("abc", 1, 0, ""));
Assert.AreEqual("123", Tools.ReplacePartOfString("abc", 0, 3, "123"));
Assert.AreEqual("1bc", Tools.ReplacePartOfString("abc", 0, 1, "1"));
Assert.AreEqual("ab3", Tools.ReplacePartOfString("abc", 2, 1, "3"));
}
[Test]
public void TestWikiEncode()
{
Assert.AreEqual("foo", Tools.WikiEncode("foo"));
Assert.AreEqual("Foo", Tools.WikiEncode("Foo"));
Assert.AreEqual("foo_bar", Tools.WikiEncode("foo bar"));
Assert.AreEqual("foo_bar", Tools.WikiEncode("foo_bar"));
Assert.AreEqual("foo/bar", Tools.WikiEncode("foo/bar"));
Assert.AreEqual("foo:bar", Tools.WikiEncode("foo:bar"));
StringAssert.AreEqualIgnoringCase("Caf%C3%A9", Tools.WikiEncode("Café"));
StringAssert.AreEqualIgnoringCase("%D1%82%D0%B5%D1%81%D1%82:%D1%82%D0%B5%D1%81%D1%82", Tools.WikiEncode("тест:тест"));
}
[Test]
public void TestSplitToSections()
{
string[] sections = Tools.SplitToSections("foo\r\n==bar=\r\nboo\r\n\r\n= boz =\r\n==quux==");
CollectionAssert.AreEqual(new string[]
{
"foo\r\n",
"==bar=\r\nboo\r\n\r\n",
"= boz =\r\n",
"==quux==\r\n"
}, sections);
sections = Tools.SplitToSections("==bar=\r\nboo\r\n\r\n= boz =\r\n==quux==");
CollectionAssert.AreEqual(new string[]
{
"==bar=\r\nboo\r\n\r\n",
"= boz =\r\n",
"==quux==\r\n"
}, sections);
sections = Tools.SplitToSections("\r\n==bar=\r\nboo\r\n\r\n= boz =\r\n==quux==");
CollectionAssert.AreEqual(new string[]
{
"\r\n",
"==bar=\r\nboo\r\n\r\n",
"= boz =\r\n",
"==quux==\r\n"
}, sections);
sections = Tools.SplitToSections("");
CollectionAssert.AreEqual(new string[] { "\r\n" }, sections);
sections = Tools.SplitToSections("==foo==");
CollectionAssert.AreEqual(new string[] { "==foo==\r\n" }, sections);
}
[Test]
public void TestRemoveMatches()
{
MatchCollection matches = Regex.Matches("abc bce cde def", "[ce]");
Assert.AreEqual("ab b d df", Tools.RemoveMatches("abc bce cde def", matches));
matches = Regex.Matches("", "test");
Assert.AreEqual("test", Tools.RemoveMatches("test", matches));
Assert.AreEqual("abc", Tools.RemoveMatches("abc", matches));
Assert.AreEqual("", Tools.RemoveMatches("", matches));
matches = Regex.Matches("abc123", "(123|abc)");
Assert.AreEqual("", Tools.RemoveMatches("abc123", matches));
matches = Regex.Matches("test", "[Tt]est");
Assert.AreEqual("", Tools.RemoveMatches("test", matches));
}
[Test]
public void TestRemoveHashFromPageTitle()
{
Assert.AreEqual("ab c", Tools.RemoveHashFromPageTitle("ab c"));
Assert.AreEqual("foo", Tools.RemoveHashFromPageTitle("foo#bar"));
Assert.AreEqual("foo", Tools.RemoveHashFromPageTitle("foo##bar#"));
Assert.AreEqual("foo", Tools.RemoveHashFromPageTitle("foo#"));
Assert.AreEqual("", Tools.RemoveHashFromPageTitle("#"));
Assert.AreEqual("", Tools.RemoveHashFromPageTitle(""));
}
[Test]
public void TestSplitLines()
{
CollectionAssert.IsEmpty(Tools.SplitLines(""));
string[] test = new string[] { "foo" };
CollectionAssert.AreEqual(test, Tools.SplitLines("foo"));
CollectionAssert.AreEqual(test, Tools.SplitLines("foo\r"));
CollectionAssert.AreEqual(test, Tools.SplitLines("foo\n"));
CollectionAssert.AreEqual(test, Tools.SplitLines("foo\r\n"));
test = new string[] { "foo", "bar" };
CollectionAssert.AreEqual(test, Tools.SplitLines("foo\r\nbar"));
CollectionAssert.AreEqual(test, Tools.SplitLines("foo\rbar"));
CollectionAssert.AreEqual(test, Tools.SplitLines("foo\rbar"));
test = new string[] { "" };
CollectionAssert.AreEqual(test, Tools.SplitLines("\n"));
CollectionAssert.AreEqual(test, Tools.SplitLines("\r\n"));
CollectionAssert.AreEqual(test, Tools.SplitLines("\r"));
test = new string[] { "", "" };
CollectionAssert.AreEqual(test, Tools.SplitLines("\n\n"));
CollectionAssert.AreEqual(test, Tools.SplitLines("\r\n\r\n"));
CollectionAssert.AreEqual(test, Tools.SplitLines("\r\r"));
test = new string[] { "", "foo", "", "bar" };
CollectionAssert.AreEqual(test, Tools.SplitLines("\r\nfoo\r\n\r\nbar"));
CollectionAssert.AreEqual(test, Tools.SplitLines("\rfoo\r\rbar"));
CollectionAssert.AreEqual(test, Tools.SplitLines("\nfoo\n\nbar"));
}
}
[TestFixture]
public class HumanCatKeyTests
{
[SetUp]
public void SetUp()
{
Globals.UnitTestMode = true;
Variables.SetToEnglish();
}
[Test]
public void OneWordNames()
{
Assert.AreEqual("OneWordName", Tools.MakeHumanCatKey("OneWordName"));
}
[Test]
public void WithRomanNumbers()
{
Assert.AreEqual("Doe, John, III", Tools.MakeHumanCatKey("John Doe III"));
}
[Test]
public void WithJrSr()
{
Assert.AreEqual("Doe, John, Jr.", Tools.MakeHumanCatKey("John Doe, Jr."));
Assert.AreEqual("Doe, John, Sr.", Tools.MakeHumanCatKey("John Doe, Sr."));
}
[Test]
public void WithApostrophes()
{
Assert.AreEqual("Ddoe, John", Tools.MakeHumanCatKey("J'ohn D'Doe"));
Assert.AreEqual("Test", Tools.MakeHumanCatKey("'Test"));
}
[Test]
public void WithPrefixes()
{
Assert.AreEqual("Doe, John de", Tools.MakeHumanCatKey("John de Doe"));
}
[Test]
public void RemoveDiacritics()
{
Assert.AreEqual("Doe", Tools.MakeHumanCatKey("Ďöê"));
Assert.AreEqual("Doe, John", Tools.MakeHumanCatKey("Ĵǒħń Ďöê"));
// Ё should be changed, but not Й
Assert.AreEqual("Епрстий", Tools.MakeHumanCatKey("Ёпрстий"));
}
[Test]
public void RemoveNamespace()
{
Assert.AreEqual("Doe, John", Tools.MakeHumanCatKey("Wikipedia:John Doe"));
}
[Test]
public void FuzzTest()
{
string allowedChars = "abcdefghijklmnopqrstuvwxyzйцукенфывапролдж ,,,,,";
Random rnd = new Random();
for (int i = 0; i < 10000; i++)
{
string name = "";
for (int j = 0; j < rnd.Next(45); j++) name += allowedChars[rnd.Next(allowedChars.Length)];
name = Regex.Replace(name, @"\s{2,}", " ").Trim(new char[] { ' ', ',' });
//System.Diagnostics.Trace.WriteLine(name);
name = Tools.MakeHumanCatKey(name);
Assert.IsFalse(name.Contains(" "), "Sorting key shouldn't contain consecutive spaces - it breaks the sorting ({0})", name);
Assert.IsFalse(name.StartsWith(" "), "Sorting key shouldn't start with spaces");
Assert.IsFalse(name.EndsWith(" "), "Sorting key shouldn't cend with spaces");
}
}
}
}
| gpl-2.0 |
gaofengGit/TDQQ | TDQQ/obj/Debug/TDQQ_Content.g.i.cs | 608 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("image/countybroad.png")]
[assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("image/departmentbroad.png")]
| gpl-2.0 |
htuyen1994/nukeviet_hue | admin/themes/package_theme_module.php | 5017 | <?php
/**
* @Project NUKEVIET 4.x
* @Author VINADES.,JSC (contact@vinades.vn)
* @Copyright (C) 2014 VINADES.,JSC. All rights reserved
* @License GNU/GPL version 2 or any later version
* @Createdate 2-2-2010 12:55
*/
if( ! defined( 'NV_IS_FILE_THEMES' ) ) die( 'Stop!!!' );
$xtpl = new XTemplate( 'package_theme_module.tpl', NV_ROOTDIR . '/themes/' . $global_config['module_theme'] . '/modules/' . $module_file );
$xtpl->assign( 'LANG', $lang_module );
$xtpl->assign( 'GLANG', $lang_global );
if( $nv_Request->isset_request( 'op', 'post' ) )
{
$contents = $lang_module['package_noselect_module_theme'];
$themename = $nv_Request->get_string( 'themename', 'post' );
if( preg_match( $global_config['check_theme'], $themename ) or preg_match( $global_config['check_theme_mobile'], $themename ) )
{
$allowfolder = array();
$modulearray = array();
$all_module_file = $nv_Request->get_title( 'module_file', 'post' );
$module_file_array = explode( ',', $all_module_file );
array_unique( $module_file_array );
foreach ( $module_file_array as $_module_file )
{
$_module_file = nv_unhtmlspecialchars($_module_file);
if( preg_match( $global_config['check_module'], $_module_file ) )
{
$modulearray[] = $_module_file;
$allowfolder[] = NV_ROOTDIR . '/themes/' . $themename . '/modules/' . $_module_file . '/';
if( file_exists( NV_ROOTDIR . '/themes/' . $themename . '/css/' . $_module_file . '.css' ) )
{
$allowfolder[] = NV_ROOTDIR . '/themes/' . $themename . '/css/' . $_module_file . '.css';
}
if( file_exists( NV_ROOTDIR . '/themes/' . $themename . '/images/' . $_module_file . '/' ) )
{
$allowfolder[] = NV_ROOTDIR . '/themes/' . $themename . '/images/' . $_module_file . '/';
}
}
}
if( ! empty( $allowfolder ) )
{
$all_module_file = implode( '_', $modulearray );
$file_src = NV_ROOTDIR . '/' . NV_TEMP_DIR . '/' . NV_TEMPNAM_PREFIX . 'theme_' . $themename . '_' . $all_module_file . '_' . md5( nv_genpass( 10 ) . session_id() ) . '.zip';
require_once NV_ROOTDIR . '/includes/class/pclzip.class.php';
$zip = new PclZip( $file_src );
$zip->create( $allowfolder, PCLZIP_OPT_REMOVE_PATH, NV_ROOTDIR . '/themes' );
$filesize = filesize( $file_src );
$file_name = basename( $file_src );
nv_insert_logs( NV_LANG_DATA, $module_name, $lang_module['package_theme_module'], 'file name : ' . $themename . '_' . $all_module_file . '.zip', $admin_info['userid'] );
$linkgetfile = NV_BASE_ADMINURL . 'index.php?' . NV_LANG_VARIABLE . '=' . NV_LANG_DATA . '&' . NV_NAME_VARIABLE . '=' . $module_name . '&' . NV_OP_VARIABLE . '=getfile&mod=nv4_theme_' . $themename . '_' . $all_module_file . '.zip&checkss=' . md5( $file_name . $client_info['session_id'] . $global_config['sitekey'] ) . '&filename=' . $file_name;
$xtpl->assign( 'LINKGETFILE', $linkgetfile );
$xtpl->assign( 'THEMENAME', $themename );
$xtpl->assign( 'MODULENAME', $all_module_file );
$xtpl->assign( 'FILESIZE', nv_convertfromBytes( $filesize ) );
$xtpl->parse( 'complete' );
$contents = $xtpl->text( 'complete' );
}
}
include NV_ROOTDIR . '/includes/header.php';
echo $contents;
include NV_ROOTDIR . '/includes/footer.php';
}
else
{
$op = $nv_Request->get_string( NV_OP_VARIABLE, 'get', '' );
$theme_list = nv_scandir( NV_ROOTDIR . '/themes', array( $global_config['check_theme'], $global_config['check_theme_mobile'] ) );
foreach( $theme_list as $themes_i )
{
if( file_exists( NV_ROOTDIR . '/themes/' . $themes_i . '/config.ini' ) )
{
$xtpl->assign( 'THEME', $themes_i );
$xtpl->parse( 'main.theme' );
}
}
$result = $db->query( 'SELECT title, module_file, custom_title FROM ' . NV_MODULES_TABLE . ' ORDER BY weight ASC' );
$array_module_seup = array();
while( $row = $result->fetch() )
{
if ( $row['module_file'] == $row['module_file'] )
{
$xtpl->assign( 'MODULE', array( 'module_file' => $row['module_file'], 'custom_title' => $row['custom_title'] ) );
$xtpl->parse( 'main.module' );
$array_module_seup[] = $row['module_file'];
}
}
$modules_list = nv_scandir( NV_ROOTDIR . '/modules', $global_config['check_module'] );
foreach( $modules_list as $module_i )
{
if ( ! in_array( $module_i, $array_module_seup ) )
{
$xtpl->assign( 'MODULE', array( 'module_file' => $module_i, 'custom_title' => $module_i ) );
$xtpl->parse( 'main.module' );
}
}
$xtpl->assign( 'NV_BASE_ADMINURL', NV_BASE_ADMINURL );
$xtpl->assign( 'NV_NAME_VARIABLE', NV_NAME_VARIABLE );
$xtpl->assign( 'NV_OP_VARIABLE', NV_OP_VARIABLE );
$xtpl->assign( 'MODULE_NAME', $module_name );
$xtpl->assign( 'OP', $op );
$xtpl->parse( 'main' );
$contents = $xtpl->text( 'main' );
$page_title = $lang_module['package_theme_module'];
include NV_ROOTDIR . '/includes/header.php';
echo nv_admin_theme( $contents );
include NV_ROOTDIR . '/includes/footer.php';
} | gpl-2.0 |
CodeTreeCommunity/Shooter2D | Source/Shooter2D/Properties/AssemblyInfo.cs | 1362 | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Shooter2D")]
[assembly: AssemblyProduct("Shooter2D")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ec39d369-21a9-40d2-84c2-21a462a0b526")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.4.0.456")]
[assembly: AssemblyFileVersion("3.4.0.456")] | gpl-2.0 |
ATRGamers/ATRSeeder | PureSeeder.Core/Monitoring/ProcessMonitor.cs | 5073 | using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ATRGamers.ATRSeeder.Core.Annotations;
using ATRGamers.ATRSeeder.Core.Configuration;
namespace ATRGamers.ATRSeeder.Core.Monitoring
{
public delegate void ProcessStateChangeHandler(object sender, ProcessStateChangeEventArgs e);
public class ProcessMonitor
{
private readonly ICrashDetector[] _crashDetectors;
public ProcessMonitor([NotNull] ICrashDetector[] crashDetectors)
{
if (crashDetectors == null) throw new ArgumentNullException("crashDetectors");
_crashDetectors = crashDetectors;
}
// Need a couple of custom events to attach to
public event ProcessStateChangeHandler OnProcessStateChanged;
public /*async*/ Task CheckOnProcess(CancellationToken ct, Func<GameInfo> getGameInfo, SynchronizationContext context)
{
/*await*/ return Task.Factory.StartNew(() =>
{
// Check for the process every few seconds
// If it's running, trigger idle kick avoidance
// If state changes from running or to running, trigger an event
var previousState = false;
while (!ct.IsCancellationRequested)
{
var currentGame = getGameInfo.Invoke();
if (currentGame != null)
{
var process =
Process.GetProcessesByName(currentGame.ProcessName).FirstOrDefault();
var isRunning = process != null;
if (isRunning != previousState && OnProcessStateChanged != null)
context.Post(_ => OnProcessStateChanged(this, new ProcessStateChangeEventArgs() {IsRunning = isRunning}), null);
//OnProcessStateChanged.Invoke(this,new ProcessStateChangeEventArgs() {IsRunning = isRunning}); // Deprecated
previousState = isRunning;
foreach (var crashDetector in _crashDetectors)
{
crashDetector.DetectCrash(currentGame.ProcessName,
currentGame.FaultWindowTitle);
}
}
Thread.Sleep(5000);
}
});
}
}
public interface ICrashDetector
{
void DetectCrash(string processName, string faultWindowTitle);
}
/// <summary>
/// If the app is not responding, then it has crashed/locked up
/// </summary>
class CrashDetector : ICrashDetector
{
private readonly ICrashHandler _crashHandler;
public CrashDetector([NotNull] ICrashHandler crashHandler)
{
if (crashHandler == null) throw new ArgumentNullException("crashHandler");
_crashHandler = crashHandler;
}
public void DetectCrash(string processName, string faultWindowTitle)
{
var process = Process.GetProcessesByName(processName).FirstOrDefault();
if (process == null)
return;
if(!process.Responding)
_crashHandler.HandleCrash(process, processName, faultWindowTitle);
}
}
/// <summary>
/// If there is a fault window, then it has crashed/locked up
/// </summary>
class DetectCrashByFaultWindow : ICrashDetector
{
public void DetectCrash(string processName, string faultWindowTitle)
{
var faultProcess = Process.GetProcessesByName("WerFault")
.FirstOrDefault(x => x.MainWindowTitle == faultWindowTitle);
if (faultProcess == null)
return;
// Assume the game has crashed
faultProcess.Kill();
var gameProcess = Process.GetProcessesByName(processName).FirstOrDefault();
if (gameProcess != null)
gameProcess.Kill();
}
}
public interface ICrashHandler
{
void HandleCrash(Process process, string processName, string faultWindowTitle);
}
class CrashHandler : ICrashHandler
{
public void HandleCrash(Process process, string processName, string faultWindowTitle)
{
if(process != null)
process.Kill();
// Find the fault window and kill it
var faultProcess =
Process.GetProcessesByName("WerFault")
.FirstOrDefault(x => x.MainWindowTitle == faultWindowTitle);
if (faultProcess == null)
return;
faultProcess.Kill(); // Kill the fault window
}
}
public class ProcessStateChangeEventArgs : EventArgs
{
public bool IsRunning { get; set; }
}
} | gpl-2.0 |
birkelbach/python-canbus | canbus/simulate.py | 7040 | # CAN-FIX Utilities - An Open Source CAN FIX Utility Package
# Copyright (c) 2012 Phil Birkelbach
#
# 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.
from .exceptions import *
try:
import queue
except:
import Queue as queue
import random
import time
import struct
from . import cantypes
import inspect # For TESTING Only
class Node():
def __init__(self, name = None):
self.name = name
self.nodeID = 255
self.deviceType = 0
self.model = 0xAABBCC
self.FWRevision = 1
self.FWVCode = 0x0000
self.FWChannel = None
self.frameFunction = None
def setFunction(self, function):
if callable(function):
self.frameFunction = function
else:
raise TypeError("Argument passed is not a function")
def doFrame(self, frame):
"""Function that handles incoming frames for the node"""
if frame.id > 0x700 and frame.data[0] == self.nodeID:
# We start a response frame in case we need it
f = canbus.Frame(self.nodeID + 0x700, [frame.id - 0x700, frame.data[1]])
cmd = frame.data[1]
if cmd == 0: #Node identification
# TODO: Fix the model number part
f.data.extend([0x01, self.deviceType % 255, 1, 0 , 0, 0])
elif cmd == 1: # Bitrate Set Command
return None
elif cmd == 2: # Node Set Command
self.nodeID = frame.data[2]
f.data.append(0x00)
#TODO: Fix these so they work??
elif cmd == 3: # Disable Parameter
return None
elif cmd == 4: # Enable Parameter
return None
elif cmd == 5: # Node Report
return None
elif cmd == 7: # Firmware Update
FCode = frame.data[3]<<8 | frame.data[2]
if FCode == self.FWVCode:
FWChannel = frame.data[4]
f.data.append(0x00)
return f
return None
def getFrame(self):
"""Function that produces a frame for the node."""
if self.frameFunction:
return self.frameFunction(self.nodeID)
else:
pass
# These are just functions that generate messages for each of the
# nodes that we've created.
r_fuel_qty = 22.0
l_fuel_qty = 22.0
fuel_flow = 7.0
def __func_fuel(node):
pass
engine = {}
engine['lasttime'] = time.time() + 0.25
engine['cht'] = (357 - 32 ) * 5/9
engine['egt'] = (1340 - 32) * 5/9
engine['oil_press'] = 78
engine['oil_temp'] = (180-32) * 5/9
engine['rpm'] = 2400
engine['man_press'] = 24
engine['n'] = 0
engine['i'] = 0
def __func_engine(node):
global engine
t = time.time()
frame = cantypes.Frame()
if t > engine['lasttime'] + 1:
if engine['n'] == 0:
o = (int(time.time()*100) % 10) - 5
x = struct.pack('<H', (engine['cht']+o)*10)
frame.id = 0x500 #Cylinder Head Temperature
frame.data = [node, engine['i'], 0, ord(x[0]), ord(x[1])]
engine['i'] += 1
if engine['i'] == 4:
engine['i'] = 0
engine['n'] += 1
else:
engine['n'] = 0
engine['lasttime'] = t
return None
return frame
airdata = {}
airdata['lasttime'] = 0.0
airdata['airspeed'] = 165
airdata['altitude'] = 8500
airdata['oat'] = 10.5
airdata['n'] = 0
def __func_airdata(node):
global airdata
t = time.time()
frame = cantypes.Frame()
if t > airdata['lasttime'] + 1:
if airdata['n'] == 0:
o = (int(time.time()*1000.0) % 40) - 20
x = struct.pack('<H', (airdata['airspeed']*10 + o))
frame.id = 0x183 #Indicated Airspeed
#frame.data = [node, 0, 0, ord(x[0]), ord(x[1])]
frame.data = [node, 0, 0, x[0], x[1]]
airdata['n'] += 1
elif airdata['n'] == 1:
o = (int(time.time()*1000.0) % 20) - 10
x = struct.pack('<l', (airdata['altitude']+o))
frame.id = 0x184 #Indicated Altitude
#frame.data = [node, 0, 0, ord(x[0]), ord(x[1]), ord(x[2]), ord(x[3])]
frame.data = [node, 0, 0, x[0], x[1], x[2], x[3]]
airdata['n'] += 1
elif airdata['n'] == 2:
o = (int(time.time()*1000.0) % 100) - 50
x = struct.pack('<H', int(airdata['oat'] * 100 + o))
frame.id = 0x407 #OAT
#frame.data = [node, 0, 0, ord(x[0]), ord(x[1])]
frame.data = [node, 0, 0, x[0], x[1]]
airdata['n'] += 1
else:
airdata['n'] = 0
airdata['lasttime'] = t
return None
return frame
def configNodes():
nodelist = []
for each in range(3):
node = Node()
node.nodeID = each + 1
node.deviceType = 0x60
node.model = 0x001
nodelist.append(node)
nodelist[0].setFunction(__func_airdata)
nodelist[1].setFunction(__func_engine)
#nodelist[0].FMVCode =
return nodelist
class Adapter():
"""Class that represents a CAN Bus simulation adapter"""
def __init__(self):
self.name = "CAN Device Simulator"
self.shortname = "simulate"
self.type = "None"
self.__rQueue = queue.Queue()
random.seed()
self.nodes = configNodes()
def connect(self, config):
print("Connecting to simulation adapter")
self.open()
def disconnect(self):
print("Disconnecting from simulation adapter")
self.close()
def open(self):
print("Opening CAN Port")
def close(self):
print("Closing CAN Port")
def error(self):
print("Closing CAN Port")
def sendFrame(self, frame):
print("sendFrame() Called")
if frame.id < 0 or frame.id > 2047:
raise ValueError("Frame ID out of range")
else:
for each in self.nodes:
result = each.doFrame(frame)
if result:
self.__rQueue.put(result)
def recvFrame(self):
for each in self.nodes:
result = each.getFrame()
if result:
self.__rQueue.put(result)
try:
return self.__rQueue.get(timeout = 0.25)
except queue.Empty:
raise DeviceTimeout()
| gpl-2.0 |
MatrixPeckham/Ray-Tracer-Ground-Up-Java | RayTracer-BookBuild/src/com/matrixpeckham/raytracer/build/figures/ch31/BuildFigure29C.java | 3259 | /*
* Copyright (C) 2016 William Matrix Peckham
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.matrixpeckham.raytracer.build.figures.ch31;
import com.matrixpeckham.raytracer.cameras.Pinhole;
import com.matrixpeckham.raytracer.geometricobjects.primitives.Sphere;
import com.matrixpeckham.raytracer.lights.PointLight;
import com.matrixpeckham.raytracer.materials.SV_Matte;
import com.matrixpeckham.raytracer.textures.procedural.CubicNoise;
import com.matrixpeckham.raytracer.textures.procedural.WrappedFBmTexture;
import com.matrixpeckham.raytracer.tracers.RayCast;
import com.matrixpeckham.raytracer.util.Point3D;
import com.matrixpeckham.raytracer.util.RGBColor;
import com.matrixpeckham.raytracer.world.BuildWorldFunction;
import com.matrixpeckham.raytracer.world.World;
/**
*
* @author William Matrix Peckham
*/
public class BuildFigure29C implements BuildWorldFunction {
@Override
public void build(World w) {
// Copyright (C) Kevin Suffern 2000-2008.
// This C++ code is for non-commercial purposes only.
// This C++ code is licensed under the GNU General Public License Version 2.
// See the file COPYING.txt for the full license.
// This builds the scene for Figure 31.29(c)
int numSamples = 16;
w.vp.setHres(600);
w.vp.setVres(600);
w.vp.setSamples(numSamples);
w.backgroundColor = new RGBColor(0.5);
w.tracer = new RayCast(w);
Pinhole pinholePtr = new Pinhole();
pinholePtr.setEye(0, 0, 100);
pinholePtr.setLookat(new Point3D(0.0));
pinholePtr.setViewDistance(9500.0);
pinholePtr.computeUVW();
w.setCamera(pinholePtr);
PointLight lightPtr1 = new PointLight();
lightPtr1.setLocation(5, 5, 20);
lightPtr1.scaleRadiance(3.0);
w.addLight(lightPtr1);
// noise
CubicNoise noisePtr = new CubicNoise();
noisePtr.setNumOctaves(6);
noisePtr.setGain(0.5);
noisePtr.setLacunarity(6.0);
// texture: flowery fBm
WrappedFBmTexture texturePtr = new WrappedFBmTexture(noisePtr);
texturePtr.setColor(0.7, 1.0, 0.5); // light green
texturePtr.setExpansionNumber(3.0);
texturePtr.setMinValue(0.0);
texturePtr.setMaxValue(1.0);
// material:
SV_Matte svMattePtr = new SV_Matte();
svMattePtr.setKa(0.25);
svMattePtr.setKd(0.85);
svMattePtr.setCd(texturePtr);
Sphere spherePtr = new Sphere(new Point3D(0.0), 3.0);
spherePtr.setMaterial(svMattePtr);
w.addObject(spherePtr);
}
}
| gpl-2.0 |
seankelly/buildbot | master/buildbot/test/unit/test_data_buildrequests.py | 26077 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# 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 Buildbot Team Members
from __future__ import absolute_import
from __future__ import print_function
import datetime
import mock
from twisted.internet import defer
from twisted.internet import reactor
from twisted.trial import unittest
from buildbot.data import buildrequests
from buildbot.data import resultspec
from buildbot.test.fake import fakedb
from buildbot.test.fake import fakemaster
from buildbot.test.util import endpoint
from buildbot.test.util import interfaces
from buildbot.util import UTC
class TestBuildRequestEndpoint(endpoint.EndpointMixin, unittest.TestCase):
endpointClass = buildrequests.BuildRequestEndpoint
resourceTypeClass = buildrequests.BuildRequest
CLAIMED_AT = datetime.datetime(1978, 6, 15, 12, 31, 15, tzinfo=UTC)
CLAIMED_AT_EPOCH = 266761875
SUBMITTED_AT = datetime.datetime(1979, 6, 15, 12, 31, 15, tzinfo=UTC)
SUBMITTED_AT_EPOCH = 298297875
COMPLETE_AT = datetime.datetime(1980, 6, 15, 12, 31, 15, tzinfo=UTC)
COMPLETE_AT_EPOCH = 329920275
def setUp(self):
self.setUpEndpoint()
self.db.insertTestData([
fakedb.Builder(id=77, name='bbb'),
fakedb.Master(id=fakedb.FakeBuildRequestsComponent.MASTER_ID),
fakedb.Worker(id=13, name='wrk'),
fakedb.Buildset(id=8822),
fakedb.BuildRequest(id=44, buildsetid=8822, builderid=77,
priority=7, submitted_at=self.SUBMITTED_AT_EPOCH,
waited_for=1),
fakedb.BuildsetProperty(buildsetid=8822, property_name='prop1',
property_value='["one", "fake1"]'),
fakedb.BuildsetProperty(buildsetid=8822, property_name='prop2',
property_value='["two", "fake2"]'),
])
def tearDown(self):
self.tearDownEndpoint()
@defer.inlineCallbacks
def testGetExisting(self):
self.db.buildrequests.claimBuildRequests(
[44], claimed_at=self.CLAIMED_AT)
self.db.buildrequests.completeBuildRequests(
[44], 75, complete_at=self.COMPLETE_AT)
buildrequest = yield self.callGet(('buildrequests', 44))
self.validateData(buildrequest)
# check data formatting:
self.assertEqual(buildrequest['buildrequestid'], 44)
self.assertEqual(buildrequest['complete'], True)
self.assertEqual(buildrequest['builderid'], 77)
self.assertEqual(buildrequest['waited_for'], True)
self.assertEqual(buildrequest['claimed_at'], self.CLAIMED_AT)
self.assertEqual(buildrequest['results'], 75)
self.assertEqual(buildrequest['claimed_by_masterid'],
fakedb.FakeBuildRequestsComponent.MASTER_ID)
self.assertEqual(buildrequest['claimed'], True)
self.assertEqual(buildrequest['submitted_at'], self.SUBMITTED_AT)
self.assertEqual(buildrequest['complete_at'], self.COMPLETE_AT)
self.assertEqual(buildrequest['buildsetid'], 8822)
self.assertEqual(buildrequest['priority'], 7)
self.assertEqual(buildrequest['properties'], None)
@defer.inlineCallbacks
def testGetMissing(self):
buildrequest = yield self.callGet(('buildrequests', 9999))
self.assertEqual(buildrequest, None)
@defer.inlineCallbacks
def testGetProperty(self):
prop = resultspec.Property(b'property', 'eq', 'prop1')
buildrequest = yield self.callGet(('buildrequests', 44),
resultSpec=resultspec.ResultSpec(properties=[prop]))
self.assertEqual(buildrequest['buildrequestid'], 44)
self.assertEqual(buildrequest['properties'], {u'prop1': (u'one', u'fake1')})
@defer.inlineCallbacks
def testGetProperties(self):
prop = resultspec.Property(b'property', 'eq', '*')
buildrequest = yield self.callGet(('buildrequests', 44),
resultSpec=resultspec.ResultSpec(properties=[prop]))
self.assertEqual(buildrequest['buildrequestid'], 44)
self.assertEqual(buildrequest['properties'],
{u'prop1': (u'one', u'fake1'), u'prop2': (u'two', u'fake2')})
class TestBuildRequestsEndpoint(endpoint.EndpointMixin, unittest.TestCase):
endpointClass = buildrequests.BuildRequestsEndpoint
resourceTypeClass = buildrequests.BuildRequest
CLAIMED_AT = datetime.datetime(1978, 6, 15, 12, 31, 15, tzinfo=UTC)
CLAIMED_AT_EPOCH = 266761875
SUBMITTED_AT = datetime.datetime(1979, 6, 15, 12, 31, 15, tzinfo=UTC)
SUBMITTED_AT_EPOCH = 298297875
COMPLETE_AT = datetime.datetime(1980, 6, 15, 12, 31, 15, tzinfo=UTC)
COMPLETE_AT_EPOCH = 329920275
def setUp(self):
self.setUpEndpoint()
self.db.insertTestData([
fakedb.Builder(id=77, name='bbb'),
fakedb.Builder(id=78, name='ccc'),
fakedb.Builder(id=79, name='ddd'),
fakedb.Master(id=fakedb.FakeBuildRequestsComponent.MASTER_ID),
fakedb.Worker(id=13, name='wrk'),
fakedb.Buildset(id=8822),
fakedb.BuildRequest(id=44, buildsetid=8822, builderid=77,
priority=7, submitted_at=self.SUBMITTED_AT_EPOCH,
waited_for=1),
fakedb.BuildRequest(id=45, buildsetid=8822, builderid=77),
fakedb.BuildRequest(id=46, buildsetid=8822, builderid=78),
])
def tearDown(self):
self.tearDownEndpoint()
@defer.inlineCallbacks
def testGetAll(self):
buildrequests = yield self.callGet(('buildrequests',))
[self.validateData(br) for br in buildrequests]
self.assertEqual(sorted([br['buildrequestid'] for br in buildrequests]),
[44, 45, 46])
@defer.inlineCallbacks
def testGetNoBuildRequest(self):
buildrequests = yield self.callGet(('builders', 79, 'buildrequests'))
self.assertEqual(buildrequests, [])
@defer.inlineCallbacks
def testGetBuilderid(self):
buildrequests = yield self.callGet(('builders', 78, 'buildrequests'))
[self.validateData(br) for br in buildrequests]
self.assertEqual(
sorted([br['buildrequestid'] for br in buildrequests]), [46])
@defer.inlineCallbacks
def testGetUnknownBuilderid(self):
buildrequests = yield self.callGet(('builders', 79, 'buildrequests'))
self.assertEqual(buildrequests, [])
@defer.inlineCallbacks
def testGetProperties(self):
self.master.db.insertTestData([
fakedb.BuildsetProperty(buildsetid=8822, property_name='prop1',
property_value='["one", "fake1"]'),
fakedb.BuildsetProperty(buildsetid=8822, property_name='prop2',
property_value='["two", "fake2"]'),
])
prop = resultspec.Property(b'property', 'eq', '*')
buildrequests = yield self.callGet(('builders', 78, 'buildrequests'),
resultSpec=resultspec.ResultSpec(properties=[prop]))
self.assertEqual(len(buildrequests), 1)
self.assertEqual(buildrequests[0]['buildrequestid'], 46)
self.assertEqual(buildrequests[0]['properties'],
{u'prop1': (u'one', u'fake1'), u'prop2': (u'two', u'fake2')})
@defer.inlineCallbacks
def testGetNoFilters(self):
getBuildRequestsMock = mock.Mock(return_value={})
self.patch(
self.master.db.buildrequests, 'getBuildRequests', getBuildRequestsMock)
yield self.callGet(('buildrequests',))
getBuildRequestsMock.assert_called_with(
builderid=None,
bsid=None,
complete=None,
claimed=None,
resultSpec=resultspec.ResultSpec())
@defer.inlineCallbacks
def testGetFilters(self):
getBuildRequestsMock = mock.Mock(return_value={})
self.patch(
self.master.db.buildrequests, 'getBuildRequests', getBuildRequestsMock)
f1 = resultspec.Filter('complete', 'eq', [False])
f2 = resultspec.Filter('claimed', 'eq', [True])
f3 = resultspec.Filter('buildsetid', 'eq', [55])
f4 = resultspec.Filter('branch', 'eq', ['mybranch'])
f5 = resultspec.Filter('repository', 'eq', ['myrepo'])
yield self.callGet(
('buildrequests',),
resultSpec=resultspec.ResultSpec(filters=[f1, f2, f3, f4, f5]))
getBuildRequestsMock.assert_called_with(
builderid=None,
bsid=55,
complete=False,
claimed=True,
resultSpec=resultspec.ResultSpec(filters=[f4, f5]))
@defer.inlineCallbacks
def testGetClaimedByMasterIdFilters(self):
getBuildRequestsMock = mock.Mock(return_value={})
self.patch(
self.master.db.buildrequests, 'getBuildRequests', getBuildRequestsMock)
f1 = resultspec.Filter('claimed', 'eq', [True])
f2 = resultspec.Filter('claimed_by_masterid', 'eq',
[fakedb.FakeBuildRequestsComponent.MASTER_ID])
yield self.callGet(
('buildrequests',),
resultSpec=resultspec.ResultSpec(filters=[f1, f2]))
getBuildRequestsMock.assert_called_with(
builderid=None,
bsid=None,
complete=None,
claimed=fakedb.FakeBuildRequestsComponent.MASTER_ID,
resultSpec=resultspec.ResultSpec(filters=[f1]))
@defer.inlineCallbacks
def testGetSortedLimit(self):
yield self.master.db.buildrequests.completeBuildRequests([44], 1)
res = yield self.callGet(
('buildrequests',),
resultSpec=resultspec.ResultSpec(order=['results'], limit=2))
self.assertEqual(len(res), 2)
self.assertEqual(res[0]['results'], -1)
res = yield self.callGet(
('buildrequests',),
resultSpec=resultspec.ResultSpec(order=['-results'], limit=2))
self.assertEqual(len(res), 2)
self.assertEqual(res[0]['results'], 1)
class TestBuildRequest(interfaces.InterfaceTests, unittest.TestCase):
CLAIMED_AT = datetime.datetime(1978, 6, 15, 12, 31, 15, tzinfo=UTC)
COMPLETE_AT = datetime.datetime(1980, 6, 15, 12, 31, 15, tzinfo=UTC)
class dBLayerException(Exception):
pass
def setUp(self):
self.master = fakemaster.make_master(testcase=self,
wantMq=True, wantDb=True, wantData=True)
self.rtype = buildrequests.BuildRequest(self.master)
@defer.inlineCallbacks
def doTestCallthrough(self, dbMethodName, dbMockedMethod, method,
methodargs=None, methodkwargs=None,
expectedRes=None, expectedException=None,
expectedDbApiCalled=True):
self.patch(self.master.db.buildrequests, dbMethodName, dbMockedMethod)
if expectedException is not None:
try:
yield method(*methodargs, **methodkwargs)
except expectedException:
pass
except Exception as e:
self.fail('%s exception should be raised, but got %r' %
(expectedException, e))
else:
self.fail('%s exception should be raised' %
(expectedException,))
else:
res = yield method(*methodargs, **methodkwargs)
self.assertEqual(res, expectedRes)
if expectedDbApiCalled:
dbMockedMethod.assert_called_with(*methodargs, **methodkwargs)
def testSignatureClaimBuildRequests(self):
@self.assertArgSpecMatches(
self.master.data.updates.claimBuildRequests, # fake
self.rtype.claimBuildRequests) # real
def claimBuildRequests(self, brids, claimed_at=None, _reactor=reactor):
pass
@defer.inlineCallbacks
def testFakeDataClaimBuildRequests(self):
self.master.db.insertTestData([
fakedb.BuildRequest(id=44, buildsetid=8822),
fakedb.BuildRequest(id=55, buildsetid=8822),
])
res = yield self.master.data.updates.claimBuildRequests(
[44, 55],
claimed_at=self.CLAIMED_AT,
_reactor=reactor)
self.assertTrue(res)
@defer.inlineCallbacks
def testFakeDataClaimBuildRequestsNoneArgs(self):
res = yield self.master.data.updates.claimBuildRequests([])
self.assertTrue(res)
@defer.inlineCallbacks
def testClaimBuildRequests(self):
self.master.db.insertTestData([
fakedb.Builder(id=123),
fakedb.BuildRequest(id=44, buildsetid=8822, builderid=123),
fakedb.BuildRequest(id=55, buildsetid=8822, builderid=123),
])
claimBuildRequestsMock = mock.Mock(return_value=defer.succeed(None))
yield self.doTestCallthrough('claimBuildRequests', claimBuildRequestsMock,
self.rtype.claimBuildRequests,
methodargs=[[44]],
methodkwargs=dict(claimed_at=self.CLAIMED_AT,
_reactor=reactor),
expectedRes=True,
expectedException=None)
msg = {
'buildrequestid': 44,
'complete_at': None,
'complete': False,
'builderid': 123,
'waited_for': False,
'claimed_at': None,
'results': -1,
'priority': 0,
'submitted_at': datetime.datetime(1970, 5, 23, 21, 21, 18, tzinfo=UTC),
'claimed': False,
'claimed_by_masterid': None,
'buildsetid': 8822,
'properties': None,
}
self.assertEqual(sorted(self.master.mq.productions), sorted([
(('buildrequests', '44', 'claimed'), msg),
(('builders', '123', 'buildrequests', '44', 'claimed'), msg),
(('buildsets', '8822', 'builders', '123',
'buildrequests', '44', 'claimed'), msg),
]))
@defer.inlineCallbacks
def testClaimBuildRequestsNoBrids(self):
claimBuildRequestsMock = mock.Mock(return_value=defer.succeed(None))
yield self.doTestCallthrough('claimBuildRequests', claimBuildRequestsMock,
self.rtype.claimBuildRequests,
methodargs=[[]],
methodkwargs=dict(),
expectedRes=True,
expectedException=None,
expectedDbApiCalled=False)
self.assertEqual(self.master.mq.productions, [])
@defer.inlineCallbacks
def testClaimBuildRequestsAlreadyClaimed(self):
claimBuildRequestsMock = mock.Mock(
side_effect=buildrequests.AlreadyClaimedError('oups ! buildrequest already claimed'))
yield self.doTestCallthrough('claimBuildRequests', claimBuildRequestsMock,
self.rtype.claimBuildRequests,
methodargs=[[44]],
methodkwargs=dict(claimed_at=self.CLAIMED_AT,
_reactor=reactor),
expectedRes=False,
expectedException=None)
self.assertEqual(self.master.mq.productions, [])
@defer.inlineCallbacks
def testClaimBuildRequestsUnknownException(self):
claimBuildRequestsMock = mock.Mock(
side_effect=self.dBLayerException('oups ! unknown error'))
yield self.doTestCallthrough('claimBuildRequests', claimBuildRequestsMock,
self.rtype.claimBuildRequests,
methodargs=[[44]],
methodkwargs=dict(claimed_at=self.CLAIMED_AT,
_reactor=reactor),
expectedRes=None,
expectedException=self.dBLayerException)
self.assertEqual(self.master.mq.productions, [])
def testSignatureUnclaimBuildRequests(self):
@self.assertArgSpecMatches(
self.master.data.updates.unclaimBuildRequests, # fake
self.rtype.unclaimBuildRequests) # real
def unclaimBuildRequests(self, brids):
pass
@defer.inlineCallbacks
def testFakeDataUnclaimBuildRequests(self):
res = yield self.master.data.updates.unclaimBuildRequests([44, 55])
self.assertEqual(res, None)
@defer.inlineCallbacks
def testFakeDataUnclaimBuildRequestsNoneArgs(self):
res = yield self.master.data.updates.unclaimBuildRequests([])
self.assertEqual(res, None)
@defer.inlineCallbacks
def testUnclaimBuildRequests(self):
self.master.db.insertTestData([
fakedb.Builder(id=123),
fakedb.BuildRequest(id=44, buildsetid=8822, builderid=123),
])
unclaimBuildRequestsMock = mock.Mock(return_value=defer.succeed(None))
yield self.doTestCallthrough('unclaimBuildRequests',
unclaimBuildRequestsMock,
self.rtype.unclaimBuildRequests,
methodargs=[[44]],
methodkwargs=dict(),
expectedRes=None,
expectedException=None)
msg = {
'buildrequestid': 44,
'complete_at': None,
'complete': False,
'builderid': 123,
'waited_for': False,
'claimed_at': None,
'results': -1,
'priority': 0,
'submitted_at': datetime.datetime(1970, 5, 23, 21, 21, 18, tzinfo=UTC),
'claimed': False,
'claimed_by_masterid': None,
'buildsetid': 8822,
'properties': None,
}
self.assertEqual(sorted(self.master.mq.productions), sorted([
(('buildrequests', '44', 'unclaimed'), msg),
(('builders', '123', 'buildrequests', '44', 'unclaimed'), msg),
(('buildsets', '8822', 'builders', '123',
'buildrequests', '44', 'unclaimed'), msg),
]))
@defer.inlineCallbacks
def testUnclaimBuildRequestsNoBrids(self):
unclaimBuildRequestsMock = mock.Mock(return_value=defer.succeed(None))
yield self.doTestCallthrough('unclaimBuildRequests',
unclaimBuildRequestsMock,
self.rtype.unclaimBuildRequests,
methodargs=[[]],
methodkwargs=dict(),
expectedRes=None,
expectedException=None,
expectedDbApiCalled=False)
def testSignatureCompleteBuildRequests(self):
@self.assertArgSpecMatches(
self.master.data.updates.completeBuildRequests, # fake
self.rtype.completeBuildRequests) # real
def completeBuildRequests(self, brids, results, complete_at=None,
_reactor=reactor):
pass
@defer.inlineCallbacks
def testFakeDataCompleteBuildRequests(self):
res = yield self.master.data.updates.completeBuildRequests(
[44, 55],
12,
complete_at=self.COMPLETE_AT,
_reactor=reactor)
self.assertTrue(res)
@defer.inlineCallbacks
def testFakeDataCompleteBuildRequestsNoneArgs(self):
res = yield self.master.data.updates.completeBuildRequests([], 0)
self.assertTrue(res)
@defer.inlineCallbacks
def testCompleteBuildRequests(self):
completeBuildRequestsMock = mock.Mock(return_value=defer.succeed(None))
yield self.doTestCallthrough('completeBuildRequests',
completeBuildRequestsMock,
self.rtype.completeBuildRequests,
methodargs=[[46], 12],
methodkwargs=dict(complete_at=self.COMPLETE_AT,
_reactor=reactor),
expectedRes=True,
expectedException=None)
@defer.inlineCallbacks
def testCompleteBuildRequestsNoBrids(self):
completeBuildRequestsMock = mock.Mock(return_value=defer.succeed(None))
yield self.doTestCallthrough('completeBuildRequests',
completeBuildRequestsMock,
self.rtype.completeBuildRequests,
methodargs=[[], 0],
methodkwargs=dict(),
expectedRes=True,
expectedException=None,
expectedDbApiCalled=False)
@defer.inlineCallbacks
def testCompleteBuildRequestsNotClaimed(self):
completeBuildRequestsMock = mock.Mock(
side_effect=buildrequests.NotClaimedError('oups ! buildrequest not claimed'))
yield self.doTestCallthrough('completeBuildRequests',
completeBuildRequestsMock,
self.rtype.completeBuildRequests,
methodargs=[[46], 12],
methodkwargs=dict(complete_at=self.COMPLETE_AT,
_reactor=reactor),
expectedRes=False,
expectedException=None)
@defer.inlineCallbacks
def testCompleteBuildRequestsUnknownException(self):
completeBuildRequestsMock = mock.Mock(
side_effect=self.dBLayerException('oups ! unknown error'))
yield self.doTestCallthrough('completeBuildRequests',
completeBuildRequestsMock,
self.rtype.completeBuildRequests,
methodargs=[[46], 12],
methodkwargs=dict(complete_at=self.COMPLETE_AT,
_reactor=reactor),
expectedRes=None,
expectedException=self.dBLayerException)
@defer.inlineCallbacks
def testRebuildBuildrequest(self):
self.master.db.insertTestData([
fakedb.Builder(id=77, name='builder'),
fakedb.Master(id=88),
fakedb.Worker(id=13, name='wrk'),
fakedb.Buildset(id=8822),
fakedb.SourceStamp(id=234),
fakedb.BuildsetSourceStamp(buildsetid=8822, sourcestampid=234),
fakedb.BuildRequest(id=82, buildsetid=8822, builderid=77),
fakedb.BuildsetProperty(buildsetid=8822, property_name='prop1',
property_value='["one", "fake1"]'),
fakedb.BuildsetProperty(buildsetid=8822, property_name='prop2',
property_value='["two", "fake2"]'),
])
buildrequest = yield self.master.data.get(('buildrequests', 82))
new_bsid, brid_dict = yield self.rtype.rebuildBuildrequest(buildrequest)
self.assertEqual(list(brid_dict.keys()), [77])
buildrequest = yield self.master.data.get(('buildrequests', brid_dict[77]))
# submitted_at is the time of the test, so better not depend on it
self.assertTrue(buildrequest['submitted_at'] is not None)
buildrequest['submitted_at'] = None
self.assertEqual(buildrequest, {'buildrequestid': 1001, 'complete': False, 'waited_for': False,
'claimed_at': None, 'results': -1, 'claimed': False,
'buildsetid': 200, 'complete_at': None, 'submitted_at': None,
'builderid': 77, 'claimed_by_masterid': None, 'priority': 0,
'properties': None})
buildset = yield self.master.data.get(('buildsets', new_bsid))
oldbuildset = yield self.master.data.get(('buildsets', 8822))
# assert same sourcestamp
self.assertEqual(buildset['sourcestamps'], oldbuildset['sourcestamps'])
buildset['sourcestamps'] = None
self.assertTrue(buildset['submitted_at'] is not None)
buildset['submitted_at'] = None
self.assertEqual(buildset, {'bsid': 200, 'complete_at': None, 'submitted_at': None,
'sourcestamps': None, 'parent_buildid': None, 'results': -1, 'parent_relationship': None, 'reason': u'rebuild', 'external_idstring': u'extid', 'complete': False})
properties = yield self.master.data.get(('buildsets', new_bsid, 'properties'))
self.assertEqual(
properties, {u'prop1': (u'one', u'fake1'), u'prop2': (u'two', u'fake2')})
| gpl-2.0 |
bcmb/Classes | Task3.java | 538 | package practice.one;
public class Task3 {
public static void main(String[] args) {
short short1 = 10 + 11;
short short2 = (short) (10 + (10.08f));
short short3 = (short) (10 + (1.008));
byte byteVar = 5;
float floatVar = 102.745f;
double doubleVar = 102457.44745;
short short4 = (short) (byteVar + 1.008f);
short short5 = (short) (floatVar + doubleVar);
System.out.println(short1);
System.out.println(short2);
System.out.println(short3);
System.out.println(short4);
System.out.println(short5);
}
}
| gpl-2.0 |
vazmer/edgar | wp-content/plugins/simple-share-buttons-adder/inc/ssba_admin_panel.php | 46489 | <?php
function ssba_admin_panel($arrSettings, $htmlSettingsSaved) {
// variables
$htmlShareButtonsForm = '';
// header
$htmlShareButtonsForm .= '<div id="ssba-header">';
//logo
$htmlShareButtonsForm .= '<div id="ssba-logo">';
$htmlShareButtonsForm .= '<a href="http://www.simplesharebuttons.com" target="_blank"><img src="' . plugins_url() . '/simple-share-buttons-adder/images/simplesharebuttons.png' . '" /></a>';
$htmlShareButtonsForm .= '</div>';
// top nav
$htmlShareButtonsForm .= '<div id="ssba-top-nav">';
$htmlShareButtonsForm .= '<a href="http://www.simplesharebuttons.com/forums/forum/wordpress-forum/" target="_blank">Support</a>';
$htmlShareButtonsForm .= '<a href="http://www.simplesharebuttons.com/wordpress-faq/" target="_blank">FAQ</a>';
$htmlShareButtonsForm .= '<a href="http://www.simplesharebuttons.com/showcase/" target="_blank">Showcase</a>';
$htmlShareButtonsForm .= '<a href="http://www.simplesharebuttons.com/donate/" target="_blank">Donate</a>';
$htmlShareButtonsForm .= '<a href="https://github.com/davidsneal/simplesharebuttons" target="_blank">GitHub</a>';
$htmlShareButtonsForm .= '</div>';
// close header
$htmlShareButtonsForm .= '</div>';
// tabs
$htmlShareButtonsForm .= '<div id="ssba-tabs">';
$htmlShareButtonsForm .= '<a id="ssba_tab_basic" class="ssba-selected-tab" href="javascript:;">Basic</a>';
$htmlShareButtonsForm .= '<a id="ssba_tab_styling" href="javascript:;">Styling</a>';
$htmlShareButtonsForm .= '<a id="ssba_tab_counters" href="javascript:;">Counters</a>';
$htmlShareButtonsForm .= '<a id="ssba_tab_advanced" href="javascript:;">Advanced</a>';
$htmlShareButtonsForm .= '</div>';
// html form
$htmlShareButtonsForm .= '<div class="wrap">';
// create a table and cell to contain all minus the author cell
$htmlShareButtonsForm .= '<table><tr><td style="width: 610px; vertical-align: top;">';
// show settings saved message if set
(isset($htmlSettingsSaved) ? $htmlShareButtonsForm .= $htmlSettingsSaved : NULL);
// start form
$htmlShareButtonsForm .= '<form method="post">';
// hidden field to check for post IMPORTANT
$htmlShareButtonsForm .= '<input type="hidden" name="ssba_options" id="ssba_options" value="save" />';
//------ BASIC TAB -------//
$htmlShareButtonsForm .= '<div id="ssba_settings_basic">';
$htmlShareButtonsForm .= '<h2>Basic Settings</h2>';
$htmlShareButtonsForm .= '<table class="form-table">';
$htmlShareButtonsForm .= '<tr><td><h3>Where</h3></td></tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Location:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= 'Homepage <input type="checkbox" name="ssba_homepage" id="ssba_homepage" ' . ($arrSettings['ssba_homepage'] == 'Y' ? 'checked' : NULL) . ' value="Y" style="margin-right: 10px;" />';
$htmlShareButtonsForm .= 'Pages <input type="checkbox" name="ssba_pages" id="ssba_pages" ' . ($arrSettings['ssba_pages'] == 'Y' ? 'checked' : NULL) . ' value="Y" style="margin-right: 10px;" />';
$htmlShareButtonsForm .= 'Posts <input type="checkbox" name="ssba_posts" id="ssba_posts" ' . ($arrSettings['ssba_posts'] == 'Y' ? 'checked' : NULL) . ' value="Y" style="margin-right: 10px;" />';
$htmlShareButtonsForm .= 'Categories/Archives <input type="checkbox" name="ssba_cats_archs" id="ssba_cats_archs" ' . ($arrSettings['ssba_cats_archs'] == 'Y' ? 'checked' : NULL) . ' value="Y" style="margin-right: 10px;" />';
$htmlShareButtonsForm .= '<p class="description">Check all those that you wish to show your share buttons</br>Note you can also show/hide your buttons using [ssba] and [ssba_hide]</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_before_or_after">Placement: </label></th>';
$htmlShareButtonsForm .= '<td><select name="ssba_before_or_after" id="ssba_before_or_after">';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_before_or_after'] == 'after' ? 'selected="selected"' : NULL) . ' value="after">After</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_before_or_after'] == 'before' ? 'selected="selected"' : NULL) . ' value="before">Before</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_before_or_after'] == 'both' ? 'selected="selected"' : NULL) . ' value="both">Both</option>';
$htmlShareButtonsForm .= '</select>';
$htmlShareButtonsForm .= '<p class="description">Place share buttons before or after your content</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr><td><h3>What</h3></td></tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_share_text">Share Text: </label></th>';
$htmlShareButtonsForm .= '<td><input type="text" name="ssba_share_text" id="ssba_share_text" value="' . $arrSettings['ssba_share_text'] . '" />';
$htmlShareButtonsForm .= '<p class="description">Add some custom text by your share buttons</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_image_set">Image Set: </label></th>';
$htmlShareButtonsForm .= '<td><select name="ssba_image_set" id="ssba_image_set">';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_image_set'] == 'arbenta' ? 'selected="selected"' : NULL) . ' value="arbenta">Arbenta</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_image_set'] == 'custom' ? 'selected="selected"' : NULL) . ' value="custom">Custom</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_image_set'] == 'metal' ? 'selected="selected"' : NULL) . ' value="metal">Metal</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_image_set'] == 'pagepeel' ? 'selected="selected"' : NULL) . ' value="pagepeel">Page Peel</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_image_set'] == 'plain' ? 'selected="selected"' : NULL) . ' value="plain">Plain</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_image_set'] == 'retro' ? 'selected="selected"' : NULL) . ' value="retro">Retro</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_image_set'] == 'ribbons' ? 'selected="selected"' : NULL) . ' value="ribbons">Ribbons</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_image_set'] == 'simple' ? 'selected="selected"' : NULL) . ' value="simple">Simple</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_image_set'] == 'somacro' ? 'selected="selected"' : NULL) . ' value="somacro">Somacro</option>';
$htmlShareButtonsForm .= '</select>';
$htmlShareButtonsForm .= '<p class="description">You can make your own <a href="http://make.simplesharebuttons.com" target="blank"><strong>custom-coloured share buttons here</strong></a>! Choose your favourite set of buttons, or set to 'Custom' to choose your own. <a href="http://www.simplesharebuttons.com/button-sets/" target="_blank">Click here</a> to preview the button sets</br>';
$htmlShareButtonsForm .= "</p></td>";
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '</table>';
// --------- CUSTOM IMAGES ------------ //
$htmlShareButtonsForm .= '<div id="ssba-custom-images"' . ($arrSettings['ssba_image_set'] != 'custom' ? 'style="display: none;"' : NULL) . '>';
$htmlShareButtonsForm .= '<h4>Custom Images</h4>';
$htmlShareButtonsForm .= '<table class="form-table">';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Buffer:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '<input id="ssba_custom_buffer" type="text" size="50" name="ssba_custom_buffer" value="' . (isset($arrSettings['ssba_custom_buffer']) ? $arrSettings['ssba_custom_buffer'] : NULL) . '" />';
$htmlShareButtonsForm .= '<input id="upload_buffer_button" data-ssba-input="ssba_custom_buffer" class="button customUpload" type="button" value="Upload Image" />';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Diggit:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '<input id="ssba_custom_diggit" type="text" size="50" name="ssba_custom_diggit" value="' . (isset($arrSettings['ssba_custom_diggit']) ? $arrSettings['ssba_custom_diggit'] : NULL) . '" />';
$htmlShareButtonsForm .= '<input id="upload_diggit_button" data-ssba-input="ssba_custom_diggit" class="button customUpload" type="button" value="Upload Image" />';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Email:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '<input id="ssba_custom_email" type="text" size="50" name="ssba_custom_email" value="' . (isset($arrSettings['ssba_custom_email']) ? $arrSettings['ssba_custom_email'] : NULL) . '" />';
$htmlShareButtonsForm .= '<input id="upload_email_button" data-ssba-input="ssba_custom_email" class="button customUpload" type="button" value="Upload Image" />';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Facebook:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '<input id="ssba_custom_facebook" type="text" size="50" name="ssba_custom_facebook" value="' . (isset($arrSettings['ssba_custom_facebook']) ? $arrSettings['ssba_custom_facebook'] : NULL) . '" />';
$htmlShareButtonsForm .= '<input id="upload_facebook_button" data-ssba-input="ssba_custom_facebook" class="button customUpload" type="button" value="Upload Image" />';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Flattr:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '<input id="ssba_custom_flattr" type="text" size="50" name="ssba_custom_flattr" value="' . (isset($arrSettings['ssba_custom_flattr']) ? $arrSettings['ssba_custom_flattr'] : NULL) . '" />';
$htmlShareButtonsForm .= '<input id="upload_flattr_button" data-ssba-input="ssba_custom_flattr" class="button customUpload" type="button" value="Upload Image" />';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Google:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '<input id="ssba_custom_google" type="text" size="50" name="ssba_custom_google" value="' . (isset($arrSettings['ssba_custom_google']) ? $arrSettings['ssba_custom_google'] : NULL) . '" />';
$htmlShareButtonsForm .= '<input id="upload_google_button" data-ssba-input="ssba_custom_google" class="button customUpload" type="button" value="Upload Image" />';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>LinkedIn:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '<input id="ssba_custom_linkedin" type="text" size="50" name="ssba_custom_linkedin" value="' . (isset($arrSettings['ssba_custom_linkedin']) ? $arrSettings['ssba_custom_linkedin'] : NULL) . '" />';
$htmlShareButtonsForm .= '<input id="upload_linkedin_button" data-ssba-input="ssba_custom_linkedin" class="button customUpload" type="button" value="Upload Image" />';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Pinterest:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '<input id="ssba_custom_pinterest" type="text" size="50" name="ssba_custom_pinterest" value="' . (isset($arrSettings['ssba_custom_pinterest']) ? $arrSettings['ssba_custom_pinterest'] : NULL) . '" />';
$htmlShareButtonsForm .= '<input id="upload_pinterest_button" data-ssba-input="ssba_custom_pinterest" class="button customUpload" type="button" value="Upload Image" />';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Reddit:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '<input id="ssba_custom_reddit" type="text" size="50" name="ssba_custom_reddit" value="' . (isset($arrSettings['ssba_custom_reddit']) ? $arrSettings['ssba_custom_reddit'] : NULL) . '" />';
$htmlShareButtonsForm .= '<input id="upload_reddit_button" data-ssba-input="ssba_custom_reddit" class="button customUpload" type="button" value="Upload Image" />';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>StumbleUpon:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '<input id="ssba_custom_stumbleupon" type="text" size="50" name="ssba_custom_stumbleupon" value="' . (isset($arrSettings['ssba_custom_stumbleupon']) ? $arrSettings['ssba_custom_stumbleupon'] : NULL) . '" />';
$htmlShareButtonsForm .= '<input id="upload_stumbleupon_button" data-ssba-input="ssba_custom_stumbleupon" class="button customUpload" type="button" value="Upload Image" />';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Tumblr:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '<input id="ssba_custom_tumblr" type="text" size="50" name="ssba_custom_tumblr" value="' . (isset($arrSettings['ssba_custom_tumblr']) ? $arrSettings['ssba_custom_tumblr'] : NULL) . '" />';
$htmlShareButtonsForm .= '<input id="upload_tumblr_button" data-ssba-input="ssba_custom_tumblr" class="button customUpload" type="button" value="Upload Image" />';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Twitter:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '<input id="ssba_custom_twitter" type="text" size="50" name="ssba_custom_twitter" value="' . (isset($arrSettings['ssba_custom_twitter']) ? $arrSettings['ssba_custom_twitter'] : NULL) . '" />';
$htmlShareButtonsForm .= '<input id="upload_twitter_button" data-ssba-input="ssba_custom_twitter" class="button customUpload" type="button" value="Upload Image" />';
$htmlShareButtonsForm .= '<p class="description">Enter the URLs of your images or upload from here.<br/>Simply leave any blank you do not wish to include.</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '</table>';
$htmlShareButtonsForm .= '</div>';
// --------- NON-CUSTOM IMAGE SETTINGS ------------ //
$htmlShareButtonsForm .= '<div id="ssba-image-settings">';
$htmlShareButtonsForm .= '<table class="form-table">';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px !important;"><label for="ssba_choices">Include:</label></th>';
$htmlShareButtonsForm .= '<td class="ssba-include-list available">';
$htmlShareButtonsForm .= '<span class="include-heading">Available</span>';
$htmlShareButtonsForm .= '<center><ul id="ssbasort1" class="connectedSortable">';
$htmlShareButtonsForm .= getAvailableSSBA($arrSettings['ssba_selected_buttons']);
$htmlShareButtonsForm .= '</ul></center>';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '<td class="ssba-include-list chosen">';
$htmlShareButtonsForm .= '<span class="include-heading">Selected</span>';
$htmlShareButtonsForm .= '<center><ul id="ssbasort2" class="connectedSortable">';
$htmlShareButtonsForm .= getSelectedSSBA($arrSettings['ssba_selected_buttons']);
$htmlShareButtonsForm .= '</ul></center>';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px !important;"></th>';
$htmlShareButtonsForm .= '<td colspan=2>';
$htmlShareButtonsForm .= '<p class="description">Drag, drop and reorder those buttons that you wish to include.</p>';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '</table>';
$htmlShareButtonsForm .= '</div>';
$htmlShareButtonsForm .= '</div>';
$htmlShareButtonsForm .= '<input type="hidden" name="ssba_selected_buttons" id="ssba_selected_buttons" />';
//------ STYLING TAB ------//
//----- STYLING SETTINGS DIV ------//
$htmlShareButtonsForm .= '<div id="ssba_settings_styling" style="display: none;">';
$htmlShareButtonsForm .= '<h2>Style Settings</h2>';
// toggle setting options
$htmlShareButtonsForm .= '<div id="ssba_toggle_styling" style="margin: 10px 0 20px;">';
$htmlShareButtonsForm .= 'Toggle between <a href="javascript:;" id="ssba_button_normal_settings">assisted styling</a> and <a href="javascript:;" id="ssba_button_custom_styles">custom CSS</a>.';
$htmlShareButtonsForm .= '</div>';
// normal settings options
$htmlShareButtonsForm .= '<div id="ssba_normal_settings" ' . ($arrSettings['ssba_custom_styles'] != '' ? 'style="display: none;"' : NULL) . '>';
$htmlShareButtonsForm .= '<table class="form-table">';
$htmlShareButtonsForm .= '<tr><td><h3>Buttons</h3></td></tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_size">Button Size: </label></th>';
$htmlShareButtonsForm .= '<td><input type="number" name="ssba_size" id="ssba_size" step="1" min="10" max="50" value="' . $arrSettings['ssba_size'] . '"><span class="description">px</span>';
$htmlShareButtonsForm .= '<p class="description">Set the width of your buttons in pixels</p></td>';
$htmlShareButtonsForm .= '</input></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_align">Alignment: </label></th>';
$htmlShareButtonsForm .= '<td><select name="ssba_align" id="ssba_align">';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_align'] == 'left' ? 'selected="selected"' : NULL) . ' value="left">Left</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_align'] == 'center' ? 'selected="selected"' : NULL) . ' value="center">Center</option>';
$htmlShareButtonsForm .= '</select>';
$htmlShareButtonsForm .= '<p class="description">Center your buttons if desired</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_padding">Padding: </label></th>';
$htmlShareButtonsForm .= '<td><input type="number" name="ssba_padding" id="ssba_padding" step="1" min="0" value="' . $arrSettings['ssba_padding'] . '" /><span class="description">px</span>';
$htmlShareButtonsForm .= '<p class="description">Apply some space around your images</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr><td><h3>Share Text</h3></td></tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_font_color">Font Colour: </label></th>';
$htmlShareButtonsForm .= '<td><input type="text" name="ssba_font_color" id="ssba_font_color" value="' . $arrSettings['ssba_font_color'] . '">';
$htmlShareButtonsForm .= '</input>';
$htmlShareButtonsForm .= '<p class="description">Choose the colour of your share text</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_font_family">Font Family: </label></th>';
$htmlShareButtonsForm .= '<td><select name="ssba_font_family" id="ssba_font_family">';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_font_family'] == 'Reenie Beanie' ? 'selected="selected"' : NULL) . ' value="Reenie Beanie">Reenie Beanie</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_font_family'] == 'Indie Flower' ? 'selected="selected"' : NULL) . ' value="Indie Flower">Indie Flower</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_font_family'] == '' ? 'selected="selected"' : NULL) . ' value="">Inherit from my website</option>';
$htmlShareButtonsForm .= '</select>';
$htmlShareButtonsForm .= '<p class="description">Choose a font available or inherit the font from your website</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_font_size">Font Size: </label></th>';
$htmlShareButtonsForm .= '<td><input type="number" name="ssba_font_size" id="ssba_font_size" value="' . $arrSettings['ssba_font_size'] . '"><span class="description">px</span>';
$htmlShareButtonsForm .= '</input>';
$htmlShareButtonsForm .= '<p class="description">Set the size of the share text in pixels</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_font_weight">Font Weight: </label></th>';
$htmlShareButtonsForm .= '<td><select name="ssba_font_weight" id="ssba_font_weight">';
$htmlShareButtonsForm .= '<option value="">Please select...</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_font_weight'] == 'bold' ? 'selected="selected"' : NULL) . ' value="bold">Bold</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_font_weight'] == 'normal' ? 'selected="selected"' : NULL) . ' value="normal">Normal</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_font_weight'] == 'light' ? 'selected="selected"' : NULL) . ' value="light">Light</option>';
$htmlShareButtonsForm .= '</select>';
$htmlShareButtonsForm .= '<p class="description">Set the weight of the share text</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_text_placement">Text placement: </label></th>';
$htmlShareButtonsForm .= '<td><select name="ssba_text_placement" id="ssba_text_placement">';
$htmlShareButtonsForm .= '<option value="">Please select...</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_text_placement'] == 'above' ? 'selected="selected"' : NULL) . ' value="above">Above</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_text_placement'] == 'left' ? 'selected="selected"' : NULL) . ' value="left">Left</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_text_placement'] == 'right' ? 'selected="selected"' : NULL) . ' value="right">Right</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_text_placement'] == 'below' ? 'selected="selected"' : NULL) . ' value="below">Below</option>';
$htmlShareButtonsForm .= '</select>';
$htmlShareButtonsForm .= '<p class="description">Choose where you want your text to be displayed, in relation to the buttons</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr><td><h3>Container</h3></td></tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_div_padding">Padding: </label></th>';
$htmlShareButtonsForm .= '<td><input type="number" name="ssba_div_padding" id="ssba_div_padding" value="' . $arrSettings['ssba_div_padding'] . '">';
$htmlShareButtonsForm .= '</input>';
$htmlShareButtonsForm .= '<p class="description">Add some padding to your share container</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_div_background">Background Colour: </label></th>';
$htmlShareButtonsForm .= '<td><input type="text" name="ssba_div_background" id="ssba_div_background" value="' . $arrSettings['ssba_div_background'] . '">';
$htmlShareButtonsForm .= '</input>';
$htmlShareButtonsForm .= '<p class="description">Choose the colour of your share container</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_div_border">Border Colour: </label></th>';
$htmlShareButtonsForm .= '<td><input type="text" name="ssba_div_border" id="ssba_div_border" value="' . $arrSettings['ssba_div_border'] . '">';
$htmlShareButtonsForm .= '</input>';
$htmlShareButtonsForm .= '<p class="description">Choose the colour of your share container border</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_border_width">Border Width: </label></th>';
$htmlShareButtonsForm .= '<td><input type="number" name="ssba_border_width" id="ssba_border_width" value="' . $arrSettings['ssba_border_width'] . '"><span class="description">px</span>';
$htmlShareButtonsForm .= '</input>';
$htmlShareButtonsForm .= '<p class="description">Set the width of the share container border</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Container Corners: </label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= 'Round the corners <input type="checkbox" name="ssba_div_rounded_corners" id="ssba_div_rounded_corners" ' . ($arrSettings['ssba_div_rounded_corners'] == 'Y' ? 'checked' : NULL) . ' value="Y" style="margin-right: 10px;" />';
$htmlShareButtonsForm .= '<p class="description">Check this box to round the corners of the share container</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '</table>';
$htmlShareButtonsForm .= '</div>';
// custom style field
$htmlShareButtonsForm .= '<div id="ssba_option_custom_css" ' . ($arrSettings['ssba_custom_styles'] == '' ? 'style="display: none;"' : NULL) . '>';
$htmlShareButtonsForm .= '<table>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_custom_styles">Custom CSS: </label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '<textarea name="ssba_custom_styles" id="ssba_custom_styles" rows="20" cols="50">' . $arrSettings['ssba_custom_styles'] . '</textarea>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= <<<CODE
<h3>Default CSS</h3>
#ssba img</br>
{ </br>
width: 35px;</br>
padding: 6px;</br>
border: 0;</br>
box-shadow: none !important;</br>
display: inline;</br>
vertical-align: middle;</br>
}</br></br>
#ssba, #ssba a </br>
{</br>
font-family: Indie Flower;</br>
font-size: 20px;</br>
}
CODE;
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '<tr>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '<td colspan=2>';
$htmlShareButtonsForm .= '<p class="description">Note that entering any text into the 'Custom styles' box will automatically override any other style settings on this page.<br/>The div id is ssba.</p>';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '</table>';
$htmlShareButtonsForm .= '</div>';
// close styling tab
$htmlShareButtonsForm .= '</div>';
//------ COUNTERS TAB ------//
//----- COUNTERS SETTINGS DIV ------//
$htmlShareButtonsForm .= '<div id="ssba_settings_counters" style="display: none;">';
$htmlShareButtonsForm .= '<h2>Counter Settings</h2>';
// toggle setting options
$htmlShareButtonsForm .= '<div id="ssba_toggle_styling" style="margin: 10px 0 20px;">';
$htmlShareButtonsForm .= '<p>Toggle between <a href="javascript:;" id="ssba_counter_normal_settings">assisted styling</a> and <a href="javascript:;" id="ssba_counter_custom_styles">custom CSS</a>.</p>';
$htmlShareButtonsForm .= '</div>';
// activate option
$htmlShareButtonsForm .= '<table class="form-table">';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Share Count:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= 'Show <input type="checkbox" name="ssba_show_share_count" id="ssba_show_share_count" ' . ($arrSettings['ssba_show_share_count'] == 'Y' ? 'checked' : NULL) . ' value="Y" style="margin-right: 10px;" />';
$htmlShareButtonsForm .= '<p class="description">Check the box if you wish to display a share count for those sites that it is available.</br>Note that enabling this option will slow down the loading of any pages that use share buttons.</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Show Once:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= 'Show only on posts and pages <input type="checkbox" name="ssba_share_count_once" id="ssba_share_count_once" ' . ($arrSettings['ssba_share_count_once'] == 'Y' ? 'checked' : NULL) . ' value="Y" style="margin-right: 10px;" />';
$htmlShareButtonsForm .= '<p class="description">This option is recommended, it deactivates share counts for categories and archives allowing them to load more quickly</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '</table>';
// normal counter settings options
$htmlShareButtonsForm .= '<div id="ssba_counter_settings" ' . ($arrSettings['ssba_share_count_css'] != '' ? 'style="display: none;"' : NULL) . '>';
$htmlShareButtonsForm .= '<table class="form-table">';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_share_count_style">Counters Style: </label></th>';
$htmlShareButtonsForm .= '<td><select name="ssba_share_count_style" id="ssba_share_count_style">';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_share_count_style'] == 'default' ? 'selected="selected"' : NULL) . ' value="default">Default</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_share_count_style'] == 'white' ? 'selected="selected"' : NULL) . ' value="white">White</option>';
$htmlShareButtonsForm .= '<option ' . ($arrSettings['ssba_share_count_style'] == 'blue' ? 'selected="selected"' : NULL) . ' value="blue">Blue</option>';
$htmlShareButtonsForm .= '</select>';
$htmlShareButtonsForm .= '<p class="description">Pick a setting to style the share counters</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '</table>';
$htmlShareButtonsForm .= '</div>';
// custom counter style field
$htmlShareButtonsForm .= '<div id="ssba_counter_custom_css" ' . ($arrSettings['ssba_share_count_css'] == '' ? 'style="display: none;"' : NULL) . '>';
$htmlShareButtonsForm .= '<table>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_share_count_css">Custom CSS: </label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '<textarea name="ssba_share_count_css" id="ssba_share_count_css" rows="20" cols="50">' . $arrSettings['ssba_share_count_css'] . '</textarea>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= <<<CODE
<h3>Default CSS</h3>
.ssba_sharecount:after, .ssba_sharecount:before {</br>
right: 100%;</br>
border: solid transparent;</br>
content: " ";</br>
height: 0;</br>
width: 0;</br>
position: absolute;</br>
pointer-events: none;</br>
}</br>
.ssba_sharecount:after {</br>
border-color: rgba(224, 221, 221, 0);</br>
border-right-color: #f5f5f5;</br>
border-width: 5px;</br>
top: 50%;</br>
margin-top: -5px;</br>
}
.ssba_sharecount:before {</br>
border-color: rgba(85, 94, 88, 0);</br>
border-right-color: #e0dddd;</br>
border-width: 6px;</br>
top: 50%;</br>
margin-top: -6px;</br>
}</br>
.ssba_sharecount {</br>
font: 11px Arial, Helvetica, sans-serif;</br>
color: #555e58;</br>
padding: 5px;</br>
-khtml-border-radius: 6px;</br>
-o-border-radius: 6px;</br>
-webkit-border-radius: 6px;</br>
-moz-border-radius: 6px;</br>
border-radius: 6px;</br>
position: relative;</br>
background: #f5f5f5;</br>
border: 1px solid #e0dddd;</br>
}
CODE;
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '<tr>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '<td colspan=2>';
$htmlShareButtonsForm .= '<p class="description">Note that entering any text into the 'Custom styles' box will automatically override any other style settings on this page.<br/>The share count class is ssba_sharecount.</p>';
$htmlShareButtonsForm .= '</td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '</table>';
$htmlShareButtonsForm .= '</div>';
// close counters tab
$htmlShareButtonsForm .= '</div>';
//------ ADVANCED TAB ------//
$htmlShareButtonsForm .= '<div id="ssba_settings_advanced" style="display: none;">';
$htmlShareButtonsForm .= '<h2>Advanced Settings</h2>';
$htmlShareButtonsForm .= '<table class="form-table">';
$htmlShareButtonsForm .= '<tr><td><h3>General</h3></td></tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Links:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= 'Open links in a new window <input type="checkbox" name="ssba_share_new_window" id="ssba_share_new_window" ' . ($arrSettings['ssba_share_new_window'] == 'Y' ? 'checked' : NULL) . ' value="Y" />';
$htmlShareButtonsForm .= '<p class="description">Unchecking this box will make links open in the same window</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label>Share Text Link:</label></th>';
$htmlShareButtonsForm .= '<td>';
$htmlShareButtonsForm .= 'Share text links to simplesharebuttons.com <input type="checkbox" name="ssba_link_to_ssb" id="ssba_link_to_ssb" ' . ($arrSettings['ssba_link_to_ssb'] == 'Y' ? 'checked' : NULL) . ' value="Y" />';
$htmlShareButtonsForm .= '<p class="description">Leave this checked if you are feeling kind :)</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr><td><h3>Email</h3></td></tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_email_message">Email Text: </label></th>';
$htmlShareButtonsForm .= '<td><input type="text" name="ssba_email_message" style="width: 250px;" id="ssba_email_message" value="' . $arrSettings['ssba_email_message'] . '" />';
$htmlShareButtonsForm .= '<p class="description">Add some text included in the email when people share that way</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr><td><h3>Twitter</h3></td></tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_twitter_text">Twitter Text: </label></th>';
$htmlShareButtonsForm .= '<td><input type="text" name="ssba_twitter_text" style="width: 250px;" id="ssba_twitter_text" value="' . $arrSettings['ssba_twitter_text'] . '" />';
$htmlShareButtonsForm .= '<p class="description">Add some custom text for when people share via Twitter</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr><td><h3>Flattr</h3></td></tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_flattr_user_id">Flattr User ID: </label></th>';
$htmlShareButtonsForm .= '<td><input type="text" name="ssba_flattr_user_id" id="ssba_flattr_user_id" value="' . $arrSettings['ssba_flattr_user_id'] . '" />';
$htmlShareButtonsForm .= '<p class="description">Enter your Flattr ID, e.g. davidsneal</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_flattr_url">Flattr URL: </label></th>';
$htmlShareButtonsForm .= '<td><input type="text" name="ssba_flattr_url" style="width: 250px;" id="ssba_flattr_url" value="' . $arrSettings['ssba_flattr_url'] . '" />';
$htmlShareButtonsForm .= '<p class="description">This option is perfect for dedicated sites, e.g. http://www.simplesharebuttons.com</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '<tr><td><h3>Buffer</h3></td></tr>';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<th scope="row" style="width: 120px;"><label for="ssba_buffer_text">Custom Buffer Text: </label></th>';
$htmlShareButtonsForm .= '<td><input type="text" name="ssba_buffer_text" style="width: 250px;" id="ssba_buffer_text" value="' . $arrSettings['ssba_buffer_text'] . '" />';
$htmlShareButtonsForm .= '<p class="description">Add some custom text for when people share via Buffer</p></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '</table>';
$htmlShareButtonsForm .= '</div>';
// save button
$htmlShareButtonsForm .= '<table class="form-table">';
$htmlShareButtonsForm .= '<tr valign="top">';
$htmlShareButtonsForm .= '<td><input type="submit" value="Save changes" id="submit" class="button button-primary"/></td>';
$htmlShareButtonsForm .= '</tr>';
$htmlShareButtonsForm .= '</table>';
$htmlShareButtonsForm .= '</form>';
// close form cell and open author one
$htmlShareButtonsForm .= '</td><td style="vertical-align: top;">';
// author div
$htmlShareButtonsForm .= ' <div class="ssba-box ssba-shadow">
<div class="ssba-box-content">Quite a fair amount of time and effort has gone into Simple Share Buttons, any donations would be greatly appreciated, it will help me continue to be able to offer this for free!<p></p>
<div class="author-shortcodes">
<div class="author-inner">
<div class="author-image">
<img src="' . plugins_url() . '/simple-share-buttons-adder/images/david.png" style="float: left; margin-right: 10px;" alt="">
<div class="author-overlay"></div>
</div> <!-- .author-image -->
<div class="author-info">
<a href="http://www.davidsneal.co.uk" target="_blank">David Neal</a> – Married, father of one, with an (sometimes unhealthy) obsession with websites, coding and gaming. This plugin and its website has been funded by myself.
</div> <!-- .author-info -->
</div> <!-- .author-inner -->
</div> <!-- .author-shortcodes -->
</div></br>
<center><table>
<tr>
<td><form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="4TLXT69XCP3B8">
<input type="image" src="' . plugins_url() . '/simple-share-buttons-adder/images/paypal.png" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="' . plugins_url() . '/simple-share-buttons-adder/images/paypal.png" width="1" height="1">
</form>
<td><a href="http://flattr.com/thing/1328301/Simple-Share-Buttons" target="_blank"><img class="ssba-flattr-this" src="' . plugins_url() . '/simple-share-buttons-adder/images/flattr.png" alt="Flattr this" title="Flattr this" border="0" /></a>
<td><a href="https://www.freelancer.co.uk/u/davidsneal.html" target="_blank"><img src="' . plugins_url() . '/simple-share-buttons-adder/images/freelancer.png" title="Hire me on Freelancer!" /></a>
</tr>
</table>
<p>You can show your support for <strong>free</strong> too!</p>
<table class="centerme">
<tr>
<td><a href="http://wordpress.org/support/view/plugin-reviews/simple-share-buttons-adder" target="_blank" title="Rate 5 Star">Rate the plugin<br/><img src="' . plugins_url() . '/simple-share-buttons-adder/images/stars.png"></a></br></td>
<tr>
<td><a href="http://twitter.com/share?url=http://www.simplesharebuttons.com&text=Simple Share Buttons" target="_blank" title="Tweet">Tweet about Simple Share Buttons<br/><img src="' . plugins_url() . '/simple-share-buttons-adder/images/tweet.png"></a></td>
<tr>
<td><a href="http://www.facebook.com/sharer.php?u=http://www.simplesharebuttons.com" target="_blank" title="Share on Facebook">Share on Facebook<br/><img src="' . plugins_url() . '/simple-share-buttons-adder/images/share.png"></a></td>
</tr>
</table>
<div class="et-box et-bio">
<div class="et-box-content">
<h2>Make your own custom-coloured buttons for free!</h2>
<h3>Visit <a href="http://make.simplesharebuttons.com" target="blank">make.simplesharebuttons.com</a></h3>
</center></div></div>
</div>';
// close author cell and close table
$htmlShareButtonsForm .= '</td></tr></table>';
// close #wrap
$htmlShareButtonsForm .= '</div>';
echo $htmlShareButtonsForm;
}
// get an html formatted of currently selected and ordered buttons
function getSelectedSSBA($strSelectedSSBA) {
// variables
$htmlSelectedList = '';
$arrSelectedSSBA = '';
// if there are some selected buttons
if ($strSelectedSSBA != '') {
// explode saved include list and add to a new array
$arrSelectedSSBA = explode(',', $strSelectedSSBA);
// check if array is not empty
if ($arrSelectedSSBA != '') {
// for each included button
foreach ($arrSelectedSSBA as $strSelected) {
// add a list item for each selected option
$htmlSelectedList .= '<li id="' . $strSelected . '">' . $strSelected . '</li>';
}
}
}
// return html list options
return $htmlSelectedList;
}
// get an html formatted of currently selected and ordered buttons
function getAvailableSSBA($strSelectedSSBA) {
// variables
$htmlAvailableList = '';
$arrSelectedSSBA = '';
// explode saved include list and add to a new array
$arrSelectedSSBA = explode(',', $strSelectedSSBA);
// create array of all available buttons
$arrAllAvailableSSBA = array('buffer', 'diggit', 'email', 'facebook', 'flattr', 'google', 'linkedin', 'pinterest', 'print', 'reddit', 'stumbleupon', 'tumblr', 'twitter');
// explode saved include list and add to a new array
$arrAvailableSSBA = array_diff($arrAllAvailableSSBA, $arrSelectedSSBA);
// check if array is not empty
if ($arrSelectedSSBA != '') {
// for each included button
foreach ($arrAvailableSSBA as $strAvailable) {
// add a list item for each available option
$htmlAvailableList .= '<li id="' . $strAvailable . '">' . $strAvailable . '</li>';
}
}
// return html list options
return $htmlAvailableList;
}
?> | gpl-2.0 |
Click3X/abbot-water | wp-content/themes/ariva/templates/onepage-template.php | 3989 | <?php
/**
* Template Name: One Page Template
*
* @author FastWP
* @package Babel
* @since 1.0.0
*/
get_header();
global $ts_ariva;
?>
<!-- VIEW PORT TEST DIV - NOT VISIBLE -->
<div id="vw-test" class="vw-test"></div>
<!-- content -->
<div id="container_full">
<?php
while ( have_posts() ) : the_post();
the_content();
endwhile;
wp_reset_postdata();
?>
<?php
// BIO + CREDENTIALS
$args = array(
'page_id'=>8
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<article id="bio" class="clearfix article-page">';
echo '<div class="banner new-banner">
<div class="banner-content text-center">
<h1>'.get_the_title().'</h1>
<hr>
</div>
</div>';
echo '<div class="container">';
the_content();
echo '</div>';
echo '</article>';
}
}
/* Restore original Post Data */
wp_reset_postdata();
?>
<?php
// PHIL + APPROACH
$args = array(
'page_id'=>10
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<article id="philosophy" class="clearfix article-page">';
echo '<div class="banner new-banner">
<div class="banner-content text-center">
<h1>'.get_the_title().'</h1>
<hr>
</div>
</div>';
echo '<div class="container">';
the_content();
echo '</div>';
echo '</article>';
}
}
/* Restore original Post Data */
wp_reset_postdata();
?>
<?php
// SERVICES
$args = array(
'page_id'=>12
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<article id="services" class="clearfix article-page">';
echo '<div class="banner new-banner">
<div class="banner-content text-center">
<h1>'.get_the_title().'</h1>
<hr>
</div>
</div>';
echo '<div class="container">';
the_content();
echo '</div>';
echo '</article>';
}
}
/* Restore original Post Data */
wp_reset_postdata();
?>
<?php
// NYC-LA
$args = array(
'post_type' => 'portfolio',
'posts_per_page' => -1
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<article id="nyc-la" class="clearfix article-page">';
echo '<div class="banner new-banner">
<div class="banner-content text-center">
<h1>NYC <---> LA</h1>
<hr>
</div>
</div>';
echo '<div class="container_full">';
echo '<ul id="portfolio-grid" class="portfolio-grid clearfix">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$post_thumb = get_the_post_thumbnail( $post->ID, 'square-500');
echo '<li>'.$post_thumb.'</li>';
}
echo '</ul>';
echo '</div>';
echo '</article>';
}
/* Restore original Post Data */
wp_reset_postdata();
?>
</div>
<!-- End / content -->
<?php get_footer(); ?> | gpl-2.0 |
TYPO3-extensions/oelib | Classes/Domain/Repository/CountryRepository.php | 1675 | <?php
/***************************************************************
* Copyright notice
*
* (c) 2012-2013 Oliver Klee <typo3-coding@oliverklee.de>
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project 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.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script 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.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* Repository for country models.
*
* @deprecated Do not use this class. It will be copied to the static_info_tables extension and then removed.
*
* @package TYPO3
* @subpackage tx_oelib
*
* @author Oliver Klee <typo3-coding@oliverklee.de>
*/
class Tx_Oelib_Domain_Repository_CountryRepository extends Tx_Oelib_Domain_Repository_AbstractReadOnlyRepository {
/**
* Initializes the repository.
*
* @return void
*/
public function initializeObject() {
/** @var $querySettings Tx_Extbase_Persistence_Typo3QuerySettings */
$querySettings = $this->objectManager->create('Tx_Extbase_Persistence_Typo3QuerySettings');
$querySettings->setRespectStoragePage(FALSE);
$this->setDefaultQuerySettings($querySettings);
}
} | gpl-2.0 |
ya6adu6adu/schoolmule | dhtmlx/dhtmlxGrid/codebase/ext/dhtmlxgrid_mcol.js | 8155 | //v.3.5 build 120822
/*
Copyright DHTMLX LTD. http://www.dhtmlx.com
To use this component please contact sales@dhtmlx.com to obtain license
*/
dhtmlXGridObject.prototype.insertColumn=function(b,a,d,c,f,e,g,h,k){b=parseInt(b);if(b>this._cCount)b=this._cCount;if(!this._cMod)this._cMod=this._cCount;this._processAllArrays(this._cCount,b-1,[a||" ",c||100,d||"ed",e||"left",g||"",f||"na",k||"","",this._cMod,c||100]);this._processAllRows("_addColInRow",b);if(typeof a=="object")for(var i=1;i<this.hdr.rows.length;i++)if(a[i-1]=="#rspan"){for(var l=i-1,n=!1,m=null;!n;){for(var m=this.hdr.rows[l],j=0;j<m.cells.length;j++)if(m.cells[j]._cellIndex==
b){n=j;break}l--}this.hdr.rows[l+1].cells[j].rowSpan=(this.hdr.rows[l].cells[j].rowSpan||1)+1}else this.setHeaderCol(b,a[i-1]||" ",i);else this.setHeaderCol(b,a||" ");this._cCount++;this._cMod++;this._master_row=null;this.setSizes()};
dhtmlXGridObject.prototype.deleteColumn=function(b){b=parseInt(b);if(this._cCount!=0){if(!this._cMod)this._cMod=this._cCount;if(!(b>=this._cCount))this._processAllArrays(b,this._cCount-1,[null,null,null,null,null,null,null,null,null,null,null]),this._processAllRows("_deleteColInRow",b),this._cCount--,this._master_row=null,this.setSizes()}};
dhtmlXGridObject.prototype._processAllRows=function(b,a,d){this[b](this.obj.rows[0],a,d,0);for(var c=this.hdr.rows.length,f=0;f<c;f++)this[b](this.hdr.rows[f],a,d,f);if(this.ftr){c=this.ftr.firstChild.rows.length;for(f=0;f<c;f++)this[b](this.ftr.firstChild.rows[f],a,d,f)}this.forEachRow(function(c){if(this.rowsAr[c]&&this.rowsAr[c].tagName=="TR")this[b](this.rowsAr[c],a,d,-1)})};
dhtmlXGridObject.prototype._processAllArrays=function(b,a,d){var c="hdrLabels,initCellWidth,cellType,cellAlign,cellVAlign,fldSort,columnColor,_hrrar,_c_order".split(",");this.cellWidthPX.length&&c.push("cellWidthPX");this.cellWidthPC.length&&c.push("cellWidthPC");this._col_combos&&c.push("_col_combos");this._mCols&&(c[c.length]="_mCols");this.columnIds&&(c[c.length]="columnIds");this._maskArr&&c.push("_maskArr");this._drsclmW&&c.push("_drsclmW");this._RaSeCol&&c.push("_RaSeCol");this.clists&&c.push("clists");
this._validators&&this._validators.data&&c.push(this._validators.data);c.push("combos");this._customSorts&&c.push("_customSorts");this._aggregators&&c.push("_aggregators");var f=b<=a;if(!this._c_order){this._c_order=[];for(var e=this._cCount,g=0;g<e;g++)this._c_order[g]=g}for(g=0;g<c.length;g++){var h=this[c[g]]||c[g];if(h){if(f){for(var k=h[b],i=b;i<a;i++)h[i]=h[i+1];h[a]=k}else{k=h[b];for(i=b;i>a+1;i--)h[i]=h[i-1];h[a+1]=k}d&&(h[a+(f?0:1)]=d[g])}}};
dhtmlXGridObject.prototype.moveColumn=function(b,a){a--;var b=parseInt(b),a=parseInt(a),d=a<b?a+1:a;if(!this.callEvent("onBeforeCMove",[b,d]))return!1;b!=d&&(this.editStop(),this._processAllRows("_moveColInRow",b,a),this._processAllArrays(b,a),this.fldSorted&&this.setSortImgPos(this.fldSorted._cellIndex),this.callEvent("onAfterCMove",[b,d]))};dhtmlXGridObject.prototype._swapColumns=function(b){for(var a=[],d=0;d<this._cCount;d++){var c=b[this._c_order[d]];typeof c=="undefined"&&(c="");a[d]=c}return a};
dhtmlXGridObject.prototype._moveColInRow=function(b,a,d){var c=b.childNodes[a],f=b.childNodes[d+1];if(c){f?b.insertBefore(c,f):b.appendChild(c);for(var e=0;e<b.childNodes.length;e++)b.childNodes[e]._cellIndex=b.childNodes[e]._cellIndexS=e}};
dhtmlXGridObject.prototype._addColInRow=function(b,a,d,c){var f=a;if(b._childIndexes){if(b._childIndexes[a-1]==b._childIndexes[a]||!b.childNodes[b._childIndexes[a-1]]){for(var e=b._childIndexes.length;e>=a;e--)b._childIndexes[e]=e?b._childIndexes[e-1]+1:0;b._childIndexes[a]--}else for(e=b._childIndexes.length;e>=a;e--)b._childIndexes[e]=e?b._childIndexes[e-1]+1:0;f=b._childIndexes[a]}var g=b.childNodes[f],h=document.createElement(c?"TD":"TH");c?h._attrs={}:h.style.width=(parseInt(this.cellWidthPX[a])||
"100")+"px";g?b.insertBefore(h,g):b.appendChild(h);this.dragAndDropOff&&b.idd&&this.dragger.addDraggableItem(b.childNodes[f],this);for(e=f+1;e<b.childNodes.length;e++)b.childNodes[e]._cellIndex=b.childNodes[e]._cellIndexS=b.childNodes[e]._cellIndex+1;if(b.childNodes[f])b.childNodes[f]._cellIndex=b.childNodes[f]._cellIndexS=a;if(b.idd||typeof b.idd!="undefined")this.cells3(b,a).setValue(""),h.align=this.cellAlign[a],h.style.verticalAlign=this.cellVAlign[a],h.bgColor=this.columnColor[a];else if(h.tagName==
"TD")h.innerHTML=!b.idd&&this.forceDivInHeader?"<div class='hdrcell'> </div>":" "};
dhtmlXGridObject.prototype._deleteColInRow=function(b,a){b._childIndexes&&(a=b._childIndexes[a]);var d=b.childNodes[a];if(d){if(d.colSpan&&d.colSpan>1&&d.parentNode.idd){var c=d.colSpan-1,f=this.cells4(d).getValue();this.setColspan(d.parentNode.idd,d._cellIndex,1);if(c>1){var e=d._cellIndex*1;this.setColspan(d.parentNode.idd,e+1,c);this.cells(d.parentNode.idd,d._cellIndex*1+1).setValue(f);b._childIndexes.splice(e,1);for(var g=e;g<b._childIndexes.length;g++)b._childIndexes[g]-=1}}else if(b._childIndexes){b._childIndexes.splice(a,
1);for(g=a;g<b._childIndexes.length;g++)b._childIndexes[g]--}d&&b.removeChild(d);for(g=a;g<b.childNodes.length;g++)b.childNodes[g]._cellIndex=b.childNodes[g]._cellIndexS=b.childNodes[g]._cellIndex-1}};
dhtmlXGridObject.prototype.enableColumnMove=function(b,a){this._mCol=convertStringToBoolean(b);if(typeof a!="undefined")this._mCols=a.split(",");if(!this._mmevTrue)dhtmlxEvent(this.hdr,"mousedown",this._startColumnMove),dhtmlxEvent(document.body,"mousemove",this._onColumnMove),dhtmlxEvent(document.body,"mouseup",this._stopColumnMove),this._mmevTrue=!0};
dhtmlXGridObject.prototype._startColumnMove=function(b){for(var b=b||event,a=b.target||b.srcElement,d=a;d.tagName!="TABLE";)d=d.parentNode;var c=d.grid;if(c&&(c.setActive(),c._mCol&&b.button!=2)){a=c.getFirstParentOfType(a,"TD");if(a.style.cursor!="default")return!0;if(c&&!c._colInMove&&(c.resized=null,!c._mCols||c._mCols[a._cellIndex]=="true"))c._colInMove=a._cellIndex+1;return!0}};
dhtmlXGridObject.prototype._onColumnMove=function(b){var b=b||event,a=window.globalActiveDHTMLGridObject;if(a&&a._colInMove){a._showHContext&&a._showHContext(!1);if(typeof a._colInMove!="object"){var d=document.createElement("DIV");d._aIndex=a._colInMove-1;d._bIndex=null;d.innerHTML=a.getHeaderCol(d._aIndex);d.className="dhx_dragColDiv";d.style.position="absolute";document.body.appendChild(d);a._colInMove=d}var c=[];c[0]=document.body.scrollLeft||document.documentElement.scrollLeft;c[1]=document.body.scrollTop||
document.documentElement.scrollTop;a._colInMove.style.left=b.clientX+c[0]+8+"px";a._colInMove.style.top=b.clientY+c[1]+8+"px";for(var f=b.target||b.srcElement;f&&typeof f._cellIndexS=="undefined";)f=f.parentNode;if(a._colInMove._oldHe)a._colInMove._oldHe.className=a._colInMove._oldHe.className.replace(/columnTarget(L|R)/g,""),a._colInMove._oldHe=null,a._colInMove._bIndex=null;if(f){var e=a.hdr.rows[1]._childIndexes?a.hdr.rows[1].cells[a.hdr.rows[1]._childIndexes[f._cellIndexS]]:a.hdr.rows[1].cells[f._cellIndexS],
d=b.clientX-(getAbsoluteLeft(e)-a.hdrBox.scrollLeft);d/e.offsetWidth>0.5?(e.className+=" columnTargetR",a._colInMove._bIndex=f._cellIndexS):(e.className+=" columnTargetL",a._colInMove._bIndex=f._cellIndexS-1);if(e.offsetLeft<a.objBox.scrollLeft+20)a.objBox.scrollLeft=Math.max(0,e.offsetLeft-20);if(e.offsetLeft+e.offsetWidth-a.objBox.scrollLeft>a.objBox.offsetWidth-20)a.objBox.scrollLeft=Math.min(a.objBox.scrollLeft+e.offsetWidth+20,a.objBox.scrollWidth-a.objBox.offsetWidth);a._colInMove._oldHe=e}b.cancelBubble=
!0;return!1}return!0};
dhtmlXGridObject.prototype._stopColumnMove=function(b){var b=b||event,a=window.globalActiveDHTMLGridObject;if(a&&a._colInMove){if(typeof a._colInMove=="object"){a._colInMove.parentNode.removeChild(a._colInMove);a._colInMove._bIndex!=null&&a.moveColumn(a._colInMove._aIndex,a._colInMove._bIndex+1);if(a._colInMove._oldHe)a._colInMove._oldHe.className=a._colInMove._oldHe.className.replace(/columnTarget(L|R)/g,"");a._colInMove._oldHe=null;a._colInMove.grid=null;a.resized=!0}a._colInMove=0}return!0};
//v.3.5 build 120822
/*
Copyright DHTMLX LTD. http://www.dhtmlx.com
To use this component please contact sales@dhtmlx.com to obtain license
*/ | gpl-2.0 |
adamrduffy/pjx | src/main/java/com/etymon/pjx/stream/PdfDecodeStream.java | 4359 | /*
Copyright (C) Etymon Systems, Inc. <http://www.etymon.com/>
*/
package com.etymon.pjx.stream;
import java.io.*;
import java.util.*;
import com.etymon.pjx.*;
/**
Performs pipelined stream filtering to attempt to decode a stream.
This class is synchronized.
@author Nassib Nassar
*/
public class PdfDecodeStream {
protected static final PdfName PDFNAME_FILTER = new PdfName("Filter");
protected static final PdfName PDFNAME_FLATEDECODE = new PdfName("FlateDecode");
/**
The manager associated with the PDF document.
*/
protected PdfManager _m;
/**
A flate filter instance to use for decoding.
*/
protected PdfFlateFilter _flateFilter;
/**
Constructs an instance of this class with a specified
manager.
@param manager the manager instance.
*/
public PdfDecodeStream(PdfManager manager) {
_m = manager;
_flateFilter = new PdfFlateFilter(manager);
}
/**
Applies a sequence of stream filter decoders to the
specified stream, based on the stream dictionary's Filter
entry, in order to decode the stream. If the stream is
encoded with an unsupported filter, this method will throw
{@link PdfDecoderNotSupportedException
PdfDecoderNotSupportedException} to indicate that it is
unable to decode the stream. If the stream is not encoded
with any filters, this method returns the original stream
unmodified.
@param stream the stream to decode.
@return the decoded stream, or the original stream if it is
not encoded with any filters.
@throws IOException
@throws PdfFormatException
@throws PdfDecoderException
*/
public PdfStream decode(PdfStream stream) throws IOException, PdfFormatException, PdfDecoderException {
synchronized (this) {
synchronized (_m) {
PdfManager m = _m;
// get the filter list
List filters = getFilterList(m, stream.getDictionary().getMap());
if (filters == null) {
return stream;
}
// cycle through for each and decode via the
// appropriate filter
PdfStream filtered = stream;
for (Iterator t = filters.iterator(); t.hasNext(); ) {
// get the first filter
Object obj = t.next();
if ( !(obj instanceof PdfName) ) {
throw new PdfFormatException("Stream filter is not a name object.");
}
PdfName filter = (PdfName)obj;
if (filter.equals(_flateFilter.getName())) {
filtered = _flateFilter.decode(filtered);
} else {
throw new PdfDecoderNotSupportedException(
"Stream filter decoder \"" +
filter.getString() + "\" not supported.");
}
}
// return the resultant stream
return filtered;
}
}
}
/**
Removes the first element of a filter list, adds the filter
list to a stream dictionary map, and returns the resultant
stream dictionary.
@param filters the filter list.
@param streamDict the stream dictionary map.
@throws PdfFormatException
*/
protected static void modifyFilterList(List filters, Map streamDict) throws PdfFormatException {
// remove first element
filters.remove(0);
// add the filter list to the stream dictionary
if (filters.size() == 0) {
streamDict.remove(PDFNAME_FILTER);
} else {
streamDict.put(PDFNAME_FILTER, filters);
}
}
/**
Extracts the filter list from a stream dictionary map.
@param manager the manager to use for indirect reference
look-ups.
@param streamDict the stream dictionary map.
@return the filter list.
@throws PdfFormatException
*/
protected static List getFilterList(PdfManager manager, Map streamDict) throws IOException, PdfFormatException {
Object obj = streamDict.get(PDFNAME_FILTER);
if (PdfNull.isNull(obj)) {
return null;
}
if ( !(obj instanceof PdfObject) ) {
throw new PdfFormatException("Filter name is not a PDF object.");
}
obj = manager.getObjectIndirect((PdfObject)obj);
if (PdfNull.isNull(obj)) {
return null;
}
if ( ( !(obj instanceof PdfName) ) &&
( !(obj instanceof PdfArray) ) ) {
throw new PdfFormatException("Filter name is not a name or array.");
}
List filters;
if (obj instanceof PdfArray) {
filters = new ArrayList( ((PdfArray)obj).getList() );
} else {
filters = new ArrayList();
filters.add( (PdfName)obj );
}
return filters;
}
}
| gpl-2.0 |
zhang123shuo/javamop | src/javamop/output/combinedaspect/indexingtree/centralized/FullParamIndexingTree.java | 13428 | package javamop.output.combinedaspect.indexingtree.centralized;
import java.util.HashMap;
import javamop.MOPException;
import javamop.output.MOPVariable;
import javamop.output.combinedaspect.event.advice.LocalVariables;
import javamop.output.combinedaspect.indexingtree.IndexingCache;
import javamop.output.combinedaspect.indexingtree.IndexingTree;
import javamop.output.combinedaspect.indexingtree.reftree.RefTree;
import javamop.output.monitor.SuffixMonitor;
import javamop.output.monitorset.MonitorSet;
import javamop.parser.ast.mopspec.MOPParameter;
import javamop.parser.ast.mopspec.MOPParameters;
public class FullParamIndexingTree extends IndexingTree {
public FullParamIndexingTree(String aspectName, MOPParameters queryParam, MOPParameters contentParam, MOPParameters fullParam, MonitorSet monitorSet, SuffixMonitor monitor,
HashMap<String, RefTree> refTrees, boolean perthread, boolean isGeneral) throws MOPException {
super(aspectName, queryParam, contentParam, fullParam, monitorSet, monitor, refTrees, perthread, isGeneral);
if (!isFullParam)
throw new MOPException("FullParamIndexingTree can be created only when queryParam equals to fullParam.");
if (queryParam.size() == 0)
throw new MOPException("FullParamIndexingTree should contain at least one parameter.");
if (anycontent) {
this.name = new MOPVariable(aspectName + "_" + queryParam.parameterStringUnderscore() + "_Map");
} else {
if (!contentParam.contains(queryParam))
throw new MOPException("[Internal] contentParam should contain queryParam");
this.name = new MOPVariable(aspectName + "_" + queryParam.parameterStringUnderscore() + "__To__" + contentParam.parameterStringUnderscore() + "_Map");
}
if (anycontent){
this.cache = new IndexingCache(this.name, this.queryParam, this.fullParam, this.monitorClass, this.monitorSet, refTrees, perthread, isGeneral);
//this.cache = new LocalityIndexingCache(this.name, this.queryParam, this.fullParam, this.monitorClass, this.monitorSet, refTrees, perthread, isGeneral);
}
}
public MOPParameter getLastParam(){
return queryParam.get(queryParam.size() - 1);
}
protected String lookupIntermediateCreative(LocalVariables localVars, MOPVariable monitor, MOPVariable lastMap, MOPVariable lastSet, int i) {
String ret = "";
MOPVariable obj = localVars.get("obj");
MOPVariable tempMap = localVars.get("tempMap");
MOPParameter p = queryParam.get(i);
MOPVariable tempRef = localVars.getTempRef(p);
ret += obj + " = " + tempMap + ".getMap(" + tempRef + ");\n";
MOPParameter nextP = queryParam.get(i + 1);
ret += "if (" + obj + " == null) {\n";
if (i == queryParam.size() - 2){
ret += obj + " = new javamoprt.map.MOPMapOfMonitor(" + fullParam.getIdnum(nextP) + ");\n";
} else {
if(isGeneral){
ret += obj + " = new javamoprt.map.MOPMapOfAll(" + fullParam.getIdnum(nextP) + ");\n";
} else {
ret += obj + " = new javamoprt.map.MOPMapOfMapSet(" + fullParam.getIdnum(nextP) + ");\n";
}
}
ret += tempMap + ".putMap(" + tempRef + ", " + obj + ");\n";
ret += "}\n";
if (i == queryParam.size() - 2) {
ret += lastMap + " = (javamoprt.map.MOPAbstractMap)" + obj + ";\n";
ret += lookupNodeLast(localVars, monitor, lastMap, lastSet, i + 1, true);
} else {
ret += tempMap + " = (javamoprt.map.MOPAbstractMap)" + obj + ";\n";
ret += lookupIntermediateCreative(localVars, monitor, lastMap, lastSet, i + 1);
}
return ret;
}
protected String lookupIntermediateNonCreative(LocalVariables localVars, MOPVariable monitor, MOPVariable lastMap, MOPVariable lastSet, int i) {
String ret = "";
MOPVariable obj = localVars.get("obj");
MOPVariable tempMap = localVars.get("tempMap");
MOPParameter p = queryParam.get(i);
MOPVariable tempRef = localVars.getTempRef(p);
ret += obj + " = " + tempMap + ".getMap(" + tempRef + ");\n";
ret += "if (" + obj + " != null) {\n";
if (i == queryParam.size() - 2) {
ret += lastMap + " = (javamoprt.map.MOPAbstractMap)" + obj + ";\n";
ret += lookupNodeLast(localVars, monitor, lastMap, lastSet, i + 1, false);
} else {
ret += tempMap + " = (javamoprt.map.MOPAbstractMap)" + obj + ";\n";
ret += lookupIntermediateNonCreative(localVars, monitor, lastMap, lastSet, i + 1);
}
ret += "}\n";
return ret;
}
protected String lookupNodeLast(LocalVariables localVars, MOPVariable monitor, MOPVariable lastMap, MOPVariable lastSet, int i, boolean creative) {
String ret = "";
MOPParameter p = queryParam.get(i);
MOPVariable tempRef = localVars.getTempRef(p);
ret += monitor + " = " + "(" + monitorClass.getOutermostName() + ")" + lastMap + ".getNode(" + tempRef + ");\n";
return ret;
}
public String lookupNode(LocalVariables localVars, String monitorStr, String lastMapStr, String lastSetStr, boolean creative){
String ret = "";
MOPVariable monitor = localVars.get(monitorStr);
MOPVariable lastMap = localVars.get(lastMapStr);
if (queryParam.size() == 1) {
ret += lastMap + " = " + retrieveTree() + ";\n";
ret += lookupNodeLast(localVars, monitor, lastMap, null, 0, creative);
} else {
MOPVariable tempMap = localVars.get("tempMap");
ret += tempMap + " = " + retrieveTree() + ";\n";
if (creative) {
ret += lookupIntermediateCreative(localVars, monitor, lastMap, null, 0);
} else {
ret += lookupIntermediateNonCreative(localVars, monitor, lastMap, null, 0);
}
}
return ret;
}
public String lookupSet(LocalVariables localVars, String monitorStr, String lastMapStr, String lastSetStr, boolean creative){
return "";
}
public String lookupNodeAndSet(LocalVariables localVars, String monitorStr, String lastMapStr, String lastSetStr, boolean creative){
return lookupNode(localVars, monitorStr, lastMapStr, lastSetStr, creative);
}
public String attachNode(LocalVariables localVars, String monitorStr, String lastMapStr, String lastSetStr){
String ret = "";
MOPVariable monitor = localVars.get(monitorStr);
MOPVariable tempRef = localVars.getTempRef(getLastParam());
if (queryParam.size() == 1) {
ret += retrieveTree() + ".putNode(" + tempRef + ", " + monitor + ");\n";
} else {
MOPVariable lastMap = localVars.get(lastMapStr);
ret += lastMap + ".putNode(" + tempRef + ", " + monitor + ");\n";
}
return ret;
}
public String attachSet(LocalVariables localVars, String monitorStr, String lastMapStr, String lastSetStr){
return "";
}
public String addMonitor(LocalVariables localVars, String monitorStr, String tempMapStr, String tempSetStr){
String ret = "";
MOPVariable obj = localVars.get("obj");
MOPVariable tempMap = localVars.get(tempMapStr);
MOPVariable monitor = localVars.get(monitorStr);
ret += tempMap + " = " + retrieveTree() + ";\n";
for (int i = 0; i < queryParam.size() - 1; i++) {
MOPParameter p = queryParam.get(i);
MOPParameter nextp = queryParam.get(i + 1);
MOPVariable tempRef = localVars.getTempRef(p);
ret += obj + " = " + tempMap + ".getMap(" + tempRef + ");\n";
ret += "if (" + obj + " == null) {\n";
if (i == queryParam.size() - 2) {
ret += obj + " = new javamoprt.map.MOPMapOfMonitor(" + fullParam.getIdnum(nextp) + ");\n";
} else {
if(isGeneral)
ret += obj + " = new javamoprt.map.MOPMapOfAll(" + fullParam.getIdnum(nextp) + ");\n";
else
ret += obj + " = new javamoprt.map.MOPMapOfMapSet(" + fullParam.getIdnum(nextp) + ");\n";
}
ret += tempMap + ".putMap(" + tempRef + ", " + obj + ");\n";
ret += "}\n";
ret += tempMap + " = (javamoprt.map.MOPAbstractMap)" + obj + ";\n";
}
MOPParameter p = getLastParam();
MOPVariable tempRef = localVars.getTempRef(p);
ret += tempMap + ".putNode(" + tempRef + ", " + monitor + ");\n";
// if(cache != null){
// ret += cache.setCacheKeys(localVars);
//
// if (cache.hasNode){
// ret += cache.setCacheNode(monitor);
// }
// }
return ret;
}
public boolean containsSet() {
return false;
}
public String retrieveTree(){
if(parentTree != null)
return parentTree.retrieveTree();
if (perthread) {
String ret = "";
ret += "(";
ret += "(javamoprt.map.MOPAbstractMap)";
ret += name + ".get()";
ret += ")";
return ret;
} else {
return name.toString();
}
}
public String getRefTreeType(){
String ret = "";
if(parentTree != null)
return parentTree.getRefTreeType();
if(parasiticRefTree == null)
return ret;
if(isGeneral){
if (queryParam.size() == 1) {
if (parasiticRefTree.generalProperties.size() == 0) {
ret = "javamoprt.map.MOPBasicRefMapOfMonitor";
} else if (parasiticRefTree.generalProperties.size() == 1) {
ret = "javamoprt.map.MOPTagRefMapOfMonitor";
} else {
ret = "javamoprt.map.MOPMultiTagRefMapOfMonitor";
}
} else {
if (parasiticRefTree.generalProperties.size() == 0) {
ret = "javamoprt.map.MOPBasicRefMapOfAll";
} else if (parasiticRefTree.generalProperties.size() == 1) {
ret = "javamoprt.map.MOPTagRefMapOfAll";
} else {
ret = "javamoprt.map.MOPMultiTagRefMapOfAll";
}
}
} else {
if (queryParam.size() == 1) {
if (parasiticRefTree.generalProperties.size() == 0) {
ret = "javamoprt.map.MOPBasicRefMapOfMonitor";
} else if (parasiticRefTree.generalProperties.size() == 1) {
ret = "javamoprt.map.MOPTagRefMapOfMonitor";
} else {
ret = "javamoprt.map.MOPMultiTagRefMapOfMonitor";
}
} else {
if (parasiticRefTree.generalProperties.size() == 0) {
ret = "javamoprt.map.MOPBasicRefMapOfMapSet";
} else if (parasiticRefTree.generalProperties.size() == 1) {
ret = "javamoprt.map.MOPTagRefMapOfMapSet";
} else {
ret = "javamoprt.map.MOPMultiTagRefMapOfMapSet";
}
}
}
return ret;
}
public String toString() {
String ret = "";
if(parentTree == null){
if (perthread) {
ret += "static final ThreadLocal " + name + " = new ThreadLocal() {\n";
ret += "protected Object initialValue(){\n";
ret += "return ";
if (queryParam.size() == 1) {
ret += "new javamoprt.map.MOPMapOfMonitor(" + fullParam.getIdnum(queryParam.get(0)) + ");\n";
} else {
if(isGeneral)
ret += "new javamoprt.map.MOPMapOfAll(" + fullParam.getIdnum(queryParam.get(0)) + ");\n";
else
ret += "new javamoprt.map.MOPMapOfMapSet(" + fullParam.getIdnum(queryParam.get(0)) + ");\n";
}
ret += "}\n";
ret += "};\n";
} else {
if(parasiticRefTree == null){
if(isGeneral){
if (queryParam.size() == 1) {
ret += "static javamoprt.map.MOPAbstractMap " + name + " = new javamoprt.map.MOPMapOfMonitor(" + fullParam.getIdnum(queryParam.get(0)) + ");\n";
} else {
ret += "static javamoprt.map.MOPAbstractMap " + name + " = new javamoprt.map.MOPMapOfAll(" + fullParam.getIdnum(queryParam.get(0)) + ");\n";
}
} else {
if (queryParam.size() == 1) {
ret += "static javamoprt.map.MOPAbstractMap " + name + " = new javamoprt.map.MOPMapOfMonitor(" + fullParam.getIdnum(queryParam.get(0)) + ");\n";
} else {
ret += "static javamoprt.map.MOPAbstractMap " + name + " = new javamoprt.map.MOPMapOfMapSet(" + fullParam.getIdnum(queryParam.get(0)) + ");\n";
}
}
} else {
if(parasiticRefTree.generalProperties.size() <= 1){
ret += "static " + getRefTreeType() + " " + name + " = new " + getRefTreeType() + "(" + fullParam.getIdnum(queryParam.get(0)) + ");\n";
} else {
ret += "static " + getRefTreeType() + " " + name + " = new " + getRefTreeType() + "(" + fullParam.getIdnum(queryParam.get(0)) + ", " + parasiticRefTree.generalProperties.size() + ");\n";
}
}
}
}
if (cache != null)
ret += cache;
return ret;
}
public String reset() {
String ret = "";
if(parentTree == null){
if (perthread) {
} else {
//ret += "System.err.println(\""+ name + " size: \" + (" + name + ".addedMappings - " + name + ".deletedMappings" + "));\n";
if(parasiticRefTree == null){
if(isGeneral){
if (queryParam.size() == 1) {
ret += name + " = new javamoprt.map.MOPMapOfMonitor(" + fullParam.getIdnum(queryParam.get(0)) + ");\n";
} else {
ret += name + " = new javamoprt.map.MOPMapOfAll(" + fullParam.getIdnum(queryParam.get(0)) + ");\n";
}
} else {
if (queryParam.size() == 1) {
ret += name + " = new javamoprt.map.MOPMapOfMonitor(" + fullParam.getIdnum(queryParam.get(0)) + ");\n";
} else {
ret += name + " = new javamoprt.map.MOPMapOfMapSet(" + fullParam.getIdnum(queryParam.get(0)) + ");\n";
}
}
} else {
if(parasiticRefTree.generalProperties.size() <= 1){
ret += name + " = new " + getRefTreeType() + "(" + fullParam.getIdnum(queryParam.get(0)) + ");\n";
} else {
ret += name + " = new " + getRefTreeType() + "(" + fullParam.getIdnum(queryParam.get(0)) + ", " + parasiticRefTree.generalProperties.size() + ");\n";
}
}
}
}
if (cache != null)
ret += cache.reset();
return ret;
}
}
| gpl-2.0 |
accruemarketing/DanceEnergy | wp-content/plugins/post-forking/tests/post_forking_test.php | 2876 | <?php
/**
* Core functions used in tested. All tests extend this class
* Creates objects for testing purposes
*
*/
class Post_Forking_Test extends WP_UnitTestCase {
static $instance;
function __construct() {
self::$instance = &$this;
}
function get_instance() {
global $fork;
if (is_null($fork) ){
$fork = new Fork();
}
return $fork;
}
function create_post( $author = null, $post_type = 'post' ) {
if ( $author == null )
$author = $this->create_user();
$post = array(
'post_title' => 'foo',
'post_content' => "1\n2\n3\n4",
'post_author' => $author,
'post_type' => 'post',
'post_date' => date( 'Y-m-d H:i:s', strtotime( '-1 day' ) ),
);
return wp_insert_post( $post );
}
function create_user( $role = 'administrator', $user_login = '', $pass='', $email='' ) {
$user = array(
'role' => $role,
'user_login' => ( $user_login ) ? $user_login : rand_str(),
'user_pass' => ( $pass ) ? $pass: rand_str(),
'user_email' => ( $email ) ? $email : rand_str() . '@example.com',
);
$userID = wp_insert_user( $user );
return $userID;
}
function create_fork( $branch = false, $revision = true ) {
$fork = $this->get_instance();
$post = $this->create_post();
//make a revision to make finding parent revisions easier
if ( $revision )
wp_update_post( array( 'ID' => $post, 'post_name' => 'bar' ) );
$post = get_post( $post );
if ( $branch )
$author = $post->post_author;
else
$author = $this->create_user();
return $fork->fork( $post, $author );
}
function create_branch() {
return $this->create_fork( true );
}
function create_conflict( $fork ) {
//assumes a standard post of 1,2,3,4 and an unedited fork
if ( !is_object( $fork ) )
$fork = get_post( $fork );
//edit fork
$fork_arr = array( 'ID' => $fork->ID, 'post_content' => $this->fork );
wp_update_post( $fork_arr );
//edit parent to put in conflict
$parent_arr = array( 'ID' => $fork->post_parent, 'post_content' => $this->latest );
wp_update_post( $parent_arr );
//flush object cache to ensure we have the right versions of everything
wp_cache_flush();
}
function create_revision( $post = null ) {
if ( $post == null )
$post = $this->create_post();
if ( !is_object( $post ) )
$post = get_post( $post );
return wp_update_post( array( 'ID' => $post->ID, 'post_content' => $post->post_content . "\n5" ) );
}
function assertDied( $null, $msg = null ) {
if ( $msg == null )
$msg = 'Did not properly trip `wp_die()`';
$this->assertTrue( $this->die_handler->died(), $msg );
}
function test_test() {
$this->assertTrue( true );
}
}
| gpl-2.0 |
RodneyMcKay/x_hero_siege | game/dota_addons/barebones/scripts/vscripts/abilities/heroes/hero_marine.lua | 6729 | function FanOfRockets( keys )
local caster = keys.caster
local ability = keys.ability
local particleName = "particles/econ/items/clockwerk/clockwerk_paraflare/clockwerk_para_rocket_flare.vpcf"
local modifierDudName = "modifier_fan_of_rockets_dud"
local projectileSpeed = 850
local radius = ability:GetLevelSpecialValueFor("radius", ability:GetLevel() - 1)
local max_targets = ability:GetLevelSpecialValueFor("targets", ability:GetLevel() - 1)
local targetTeam = ability:GetAbilityTargetTeam()
local targetType = ability:GetAbilityTargetType()
local targetFlag = ability:GetAbilityTargetFlags() -- DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES + DOTA_UNIT_TARGET_FLAG_NO_INVIS + DOTA_UNIT_TARGET_FLAG_NOT_ILLUSIONS
local projectileDodgable = false
local projectileProvidesVision = false
-- pick up x nearest target heroes and create tracking projectile targeting the number of targets
local units = FindUnitsInRadius(caster:GetTeamNumber(), caster:GetAbsOrigin(), caster, radius, targetTeam, targetType, targetFlag, FIND_CLOSEST, false)
-- Seek out target
local count = 0
for k, v in pairs( units ) do
if count < max_targets then
local projTable = {
Target = v,
Source = caster,
Ability = ability,
EffectName = particleName,
bDodgeable = projectileDodgable,
bProvidesVision = projectileProvidesVision,
iMoveSpeed = projectileSpeed,
vSpawnOrigin = caster:GetAbsOrigin()
}
ProjectileManager:CreateTrackingProjectile( projTable )
count = count + 1
else
break
end
end
-- If no unit is found, fire dud
if count == 0 then
ability:ApplyDataDrivenModifier( caster, caster, modifierDudName, {} )
end
end
function FanOfRocketsExplode( keys )
local caster = keys.target
local ability = keys.ability
local radius = ability:GetLevelSpecialValueFor("radius", ability:GetLevel() - 1)
local point = caster:GetAbsOrigin() + RandomInt(1, radius - (math.floor(400 / 2.0))) * RandomVector(1)
local rocket = ParticleManager:CreateParticle("particles/econ/items/clockwerk/clockwerk_paraflare/clockwerk_para_rocket_flare_explosion.vpcf", PATTACH_CUSTOMORIGIN, caster)
ParticleManager:SetParticleControl(rocket, 3, point + Vector(0, 0, 128))
end
function Clone( keys )
local caster = keys.caster
local target = keys.target
local player = caster:GetPlayerOwnerID()
local ability = keys.ability
local ability_level = ability:GetLevel() - 1
local unit_name = target:GetUnitName()
local duration = ability:GetLevelSpecialValueFor( "illusion_duration", ability_level )
local outgoingDamage = ability:GetLevelSpecialValueFor( "outgoing_damage", ability_level )
local incomingDamage = ability:GetLevelSpecialValueFor( "incoming_damage", ability_level )
-- Initialize the illusion table to keep track of the units created by the spell
if not caster.clones then
caster.clones = {}
end
-- Kill the old images
for k,v in pairs(caster.clones) do
if v and IsValidEntity(v) then
v:ForceKill(false)
end
end
-- Start a clean illusion table
caster.clones = {}
-- handle_UnitOwner needs to be nil, else it will crash the game.
local illusion = CreateUnitByName(unit_name, caster:GetAbsOrigin()+150*caster:GetForwardVector()+RandomVector(RandomInt(0, 50)), true, caster, nil, caster:GetTeamNumber())
illusion:SetControllableByPlayer(player, true)
-- Level Up the unit to the casters level
local casterLevel = target:GetLevel()
for i=1,casterLevel-1 do
illusion:HeroLevelUp(false)
end
illusion:SetBaseStrength(target:GetBaseStrength())
illusion:SetBaseIntellect(target:GetBaseIntellect())
illusion:SetBaseAgility(target:GetBaseAgility())
-- Set the skill points to 0 and learn the skills of the caster
illusion:SetAbilityPoints(0)
for abilitySlot=0,15 do
local ability = target:GetAbilityByIndex(abilitySlot)
if ability ~= nil then
local abilityLevel = ability:GetLevel()
local abilityName = ability:GetAbilityName()
local illusionAbility = illusion:FindAbilityByName(abilityName)
if IsValidEntity(illusionAbility) then
illusionAbility:SetLevel(abilityLevel)
end
end
end
-- Recreate the items of the caster
for itemSlot=0,5 do
local item = target:GetItemInSlot(itemSlot)
if item ~= nil and item:GetName() ~= "item_cloak_of_immolation" then
local itemName = item:GetName()
local newItem = CreateItem(itemName, illusion, illusion)
illusion:AddItem(newItem)
end
end
illusion:AddNewModifier(caster, ability, "modifier_illusion", { duration = duration, outgoing_damage = outgoingDamage, incoming_damage = incomingDamage })
illusion:MakeIllusion()
illusion:SetHealth(target:GetHealth())
illusion:SetPlayerID(caster:GetPlayerOwnerID())
-- Add the illusion created to a table within the caster handle, to remove the illusions on the next cast if necessary
table.insert(caster.clones, illusion)
end
function ClusterRockets(keys)
local caster = keys.caster
local target = keys.target
local ability = keys.ability
local radius = ability:GetLevelSpecialValueFor("radius", ability:GetLevel() -1)
local radius_explosion = ability:GetLevelSpecialValueFor("radius_explosion", ability:GetLevel() -1)
local damage_per_unit = ability:GetLevelSpecialValueFor("damage_per_unit", ability:GetLevel() -1)
local stun_duration = ability:GetLevelSpecialValueFor("stun_duration", ability:GetLevel() -1)
local explosions_per_tick = ability:GetLevelSpecialValueFor("explosions_per_tick", ability:GetLevel() -1)
local delay = ability:GetLevelSpecialValueFor("delay", ability:GetLevel() -1)
local particleEffect = keys.particleEffect
for i = 1, explosions_per_tick do
local point = target:GetAbsOrigin() + RandomInt(1, radius - (math.floor(radius_explosion / 2.0))) * RandomVector(1)
Timers:CreateTimer(delay, function()
local units = FindUnitsInRadius(target:GetTeam(), point, nil, radius_explosion, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_HERO , DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_CLOSEST, false)
for _,unit in pairs(units) do
ApplyDamage({victim = unit, attacker = target, damage = damage_per_unit, damage_type = DAMAGE_TYPE_MAGICAL})
unit:AddNewModifier(target, nil, "modifier_stunned", {duration = stun_duration})
end
end)
local rockets = ParticleManager:CreateParticle(particleEffect, PATTACH_CUSTOMORIGIN, caster)
local distance = caster:GetAbsOrigin() - point
distance = distance:Length2D()
distance = math.min(distance, 800)
distance = math.max(distance, 100)
local factor = (distance -100) / 700.0
ParticleManager:SetParticleControl(rockets, 0, caster:GetAbsOrigin() + Vector(0,0,64))
ParticleManager:SetParticleControl(rockets, 1, point)
ParticleManager:SetParticleControl(rockets, 3, Vector(delay + factor * 0.7, 0, 0))
end
end
| gpl-2.0 |
ghtmtt/DataPlotly | DataPlotly/test/test_translations.py | 1837 | # coding=utf-8
"""Safe Translations Test.
.. note:: 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.
"""
__author__ = 'ismailsunni@yahoo.co.id'
__date__ = '12/10/2011'
__copyright__ = ('Copyright 2012, Australia Indonesia Facility for '
'Disaster Reduction')
import unittest
import os
from qgis.PyQt.QtCore import QCoreApplication, QTranslator
from DataPlotly.test.utilities import get_qgis_app
QGIS_APP = get_qgis_app()
class SafeTranslationsTest(unittest.TestCase):
"""Test translations work."""
def setUp(self):
"""Runs before each test."""
if 'LANG' in iter(os.environ.keys()):
os.environ.__delitem__('LANG')
def tearDown(self):
"""Runs after each test."""
if 'LANG' in iter(os.environ.keys()):
os.environ.__delitem__('LANG')
def test_qgis_translations(self):
"""Test that translations work."""
parent_path = os.path.join(__file__, os.path.pardir, os.path.pardir)
dir_path = os.path.abspath(parent_path)
file_path = os.path.join(
dir_path, 'i18n', 'DataPlotly_af.qm')
self.assertTrue(os.path.exists(file_path), file_path)
translator = QTranslator()
translator.load(file_path)
QCoreApplication.installTranslator(translator)
expected_message = 'Goeie more'
real_message = QCoreApplication.translate("@default", 'Good morning')
self.assertEqual(real_message, expected_message)
if __name__ == "__main__":
suite = unittest.makeSuite(SafeTranslationsTest)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)
| gpl-2.0 |
titokone/titotrainer | public/js/utils.js | 3083 |
/*
* Miscellaneous utility functions.
*/
/**
* Writes the object to Firebug's console if Firebug is installed.
*/
function debug(obj) {
if (typeof(window.loadFirebugConsole) == 'function')
window.loadFirebugConsole();
if (window.console && window.console.log) {
window.console.log(obj);
}
}
/**
* An abbreviation for not null and not undefined
*/
function hasValue(x) {
return x !== undefined && x !== null;
}
/**
* Returns x if it is not null and not undefined,
* otherwise returns def.
*/
function withDefault(x, def) {
return hasValue(x) ? x : def;
}
/**
* Returns obj.keys[0].keys[1].....keys[keys.length-1] unless
* one of the intermediate keys is unset. If one of the keys
* is unset or null, returns null.
*/
function getNestedObject(obj, keys) {
var current = obj;
for (var i = 0; i < keys.length; ++i) {
if (hasValue(current[keys[i]]))
current = current[keys[i]];
else
return null;
}
return current;
}
/**
* Takes an object, an array of keys and a value.
* Assigns value to obj.keys[0].keys[1].....keys[keys.length-1]
* making sure each subobject exists.
*/
function setNestedObject(obj, keys, value) {
var current = obj;
for (var i = 0; i < keys.length - 1; ++i) {
if (typeof(current[keys[i]]) == 'undefined') {
current[keys[i]] = {};
}
current = current[keys[i]];
}
var lastKey = keys[keys.length - 1];
current[lastKey] = value;
}
/**
* Opens a namespace.
*
* Takes any number of string arguments and returns
* window.arg1.arg2.arg3.....argN,
* creating the chain of nested objects if needed.
*
* Also works with a dot-delimited single string argument.
*
* If the final argument is a function, it is executed with the
* namespace as 'this' and its return value is returned.
* Otherwise the namespace is returned.
*/
function namespace() {
var args = []; // arguments as an Array
for (var i = 0; i < arguments.length; ++i)
args[i] = arguments[i];
var func = null;
if (args.length > 0 && typeof(args[args.length - 1]) == 'function') {
func = args.pop();
}
if (args.length == 1)
args = args[0].split('.');
var hash = window;
for (var i = 0; i < args.length; ++i) {
if (typeof(hash[args[i]]) == 'undefined') {
hash[args[i]] = {};
}
hash = hash[args[i]];
}
if (func)
return func.apply(hash);
else
return hash;
}
/**
* Returns a function that returns an incrementing
* number on each call.
*/
function makeIdGenerator(firstValue /* = 0*/) {
if (!firstValue)
firstValue = 0;
var counter = firstValue;
return function() {
return counter++;
}
}
/**
* Upper-cases the first character of a string.
*/
function ucfirst(str) {
return str.substr(0, 1).toUpperCase() + str.substr(1);
}
/**
* Lower-cases the first character of a string.
*/
function lcfirst(str) {
return str.substr(0, 1).toLowerCase() + str.substr(1);
}
| gpl-2.0 |
eugeneuskov/modna | components/com_mijoshop/opencart/admin/model/localisation/return_status.php | 3929 | <?php
/*
* @package MijoShop
* @copyright 2009-2013 Miwisoft LLC, miwisoft.com
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
* @license GNU/GPL based on AceShop www.joomace.net
*/
// No Permission
defined('_JEXEC') or die('Restricted access');
class ModelLocalisationReturnStatus extends Model {
public function addReturnStatus($data) {
foreach ($data['return_status'] as $language_id => $value) {
if (isset($return_status_id)) {
$this->db->query("INSERT INTO " . DB_PREFIX . "return_status SET return_status_id = '" . (int)$return_status_id . "', language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "'");
} else {
$this->db->query("INSERT INTO " . DB_PREFIX . "return_status SET language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "'");
$return_status_id = $this->db->getLastId();
}
}
$this->cache->delete('return_status');
}
public function editReturnStatus($return_status_id, $data) {
$this->db->query("DELETE FROM " . DB_PREFIX . "return_status WHERE return_status_id = '" . (int)$return_status_id . "'");
foreach ($data['return_status'] as $language_id => $value) {
$this->db->query("INSERT INTO " . DB_PREFIX . "return_status SET return_status_id = '" . (int)$return_status_id . "', language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "'");
}
$this->cache->delete('return_status');
}
public function deleteReturnStatus($return_status_id) {
$this->db->query("DELETE FROM " . DB_PREFIX . "return_status WHERE return_status_id = '" . (int)$return_status_id . "'");
$this->cache->delete('return_status');
}
public function getReturnStatus($return_status_id) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "return_status WHERE return_status_id = '" . (int)$return_status_id . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");
return $query->row;
}
public function getReturnStatuses($data = array()) {
if ($data) {
$sql = "SELECT * FROM " . DB_PREFIX . "return_status WHERE language_id = '" . (int)$this->config->get('config_language_id') . "'";
$sql .= " ORDER BY name";
if (isset($data['order']) && ($data['order'] == 'DESC')) {
$sql .= " DESC";
} else {
$sql .= " ASC";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->rows;
} else {
$return_status_data = $this->cache->get('return_status.' . (int)$this->config->get('config_language_id'));
if (!$return_status_data) {
$query = $this->db->query("SELECT return_status_id, name FROM " . DB_PREFIX . "return_status WHERE language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY name");
$return_status_data = $query->rows;
$this->cache->set('return_status.' . (int)$this->config->get('config_language_id'), $return_status_data);
}
return $return_status_data;
}
}
public function getReturnStatusDescriptions($return_status_id) {
$return_status_data = array();
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "return_status WHERE return_status_id = '" . (int)$return_status_id . "'");
foreach ($query->rows as $result) {
$return_status_data[$result['language_id']] = array('name' => $result['name']);
}
return $return_status_data;
}
public function getTotalReturnStatuses() {
$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "return_status WHERE language_id = '" . (int)$this->config->get('config_language_id') . "'");
return $query->row['total'];
}
}
?> | gpl-2.0 |
cleanrock/flobby | src/main.cpp | 3138 | // This file is part of flobby (GPL v2 or later), see the LICENSE file
#include "FlobbyDirs.h"
#include "FlobbyConfig.h"
#include "log/Log.h"
#include "controller/Controller.h"
#include "model/Model.h"
#include "gui/UserInterface.h"
#include <FL/Fl.H>
#include <csignal>
// TODO #include <pr-downloader.h>
static std::string dir_;
static bool zerok_ = false;
static
void printUsage(char const* argv0, std::string const& errorMsg = "")
{
char const* usage =
"%s" // errorMsg
"usage: %s [options]\n"
" -d | --dir <dir> : use <dir> for flobby config and cache instead of XDG\n"
" -z | --zerok : use zero-k lobby protocol\n"
" -v | --version : print flobby version\n"
" -h | --help : print help message\n"
" plus standard fltk options:\n"
"%s\n";
Fl::fatal(usage, errorMsg.c_str(), argv0, Fl::help);
}
static
int parseArgs(int argc, char** argv, int& i)
{
if (strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0)
{
printUsage(argv[0]);
}
else if (strcmp("-d", argv[i]) == 0 || strcmp("--dir", argv[i]) == 0)
{
if (i < argc-1 && argv[i+1] != 0)
{
dir_ = argv[i+1];
i += 2;
return 2;
}
}
else if (strcmp("-z", argv[i]) == 0 || strcmp("--zerok", argv[i]) == 0)
{
zerok_ = true;
i += 1;
return 1;
}
else if (strcmp("-v", argv[i]) == 0 || strcmp("--version", argv[i]) == 0)
{
Fl::fatal("flobby version %s\n", FLOBBY_VERSION);
}
return 0;
}
void my_handler(int s)
{
// printf("Caught signal %d\n",s);
UserInterface::postQuitEvent();
}
int main(int argc, char * argv[])
{
// setup handling of SIGINT (Ctrl-C)
{
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = my_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
}
std::string commandLine;
for (int i=0; i<argc; ++i)
{
commandLine += argv[i];
if (i < (argc-1))
{
commandLine += " ";
}
}
int i = 1;
if (Fl::args(argc, argv, i, parseArgs) < argc)
{
std::string errorMsg = "error: unknown option: ";
errorMsg += argv[i];
errorMsg += "\n";
printUsage(argv[0], errorMsg);
}
LOG(INFO)<< "starting flobby "<< FLOBBY_VERSION << ", command line '" << commandLine << "'";
initDirs(dir_);
/* TODO disable static pr-d for now (91.0 unitsync cause crash when trying engine download)
// init pr-downloader
DownloadInit();
DownloadDisableLogging(true);
*/
// extra scope to be able to check destruction
{
// setup
UserInterface::setupEarlySettings();
Controller controller;
Model model(controller, zerok_);
UserInterface ui(model);
controller.model(model);
controller.userInterface(ui);
// start
ui.run(argc, argv);
}
// shutdown pr-downloader
// TODO DownloadShutdown();
return 0;
}
| gpl-2.0 |
scoophealth/oscar | src/main/java/oscar/oscarLab/ca/all/upload/handlers/IHAPOIHandler.java | 7305 | /**
* Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved.
* This software is published under the GPL GNU General Public License.
* 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.
*
* This software was written for the
* Department of Family Medicine
* McMaster University
* Hamilton
* Ontario, Canada
*/
package oscar.oscarLab.ca.all.upload.handlers;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.log4j.Logger;
import org.oscarehr.util.LoggedInInfo;
import org.oscarehr.util.MiscUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import oscar.oscarLab.ca.all.upload.MessageUploader;
public class IHAPOIHandler implements MessageHandler {
public final String HL7_FORMAT = "IHAPOI";
Logger logger = MiscUtils.getLogger();
private final String XML_PATTERN = "<";
private final String MESSAGE_ID_NODE_NAME = "msgId";
private final String SUCCESS = "success:";
private final String FAILED = "fail:";
@Override
public String parse(LoggedInInfo loggedInInfo, String serviceName, String fileName, int fileId, String ipAddr) {
FileInputStream is = null;
Map<String, String> hl7BodyMap = null;
String messageId = "0";
StringBuilder result = new StringBuilder( FAILED + messageId + "," );
try {
is = new FileInputStream( fileName );
hl7BodyMap = parse( is );
Iterator<String> keySetIterator = null;
if( hl7BodyMap != null && hl7BodyMap.size() > 0 ) {
keySetIterator = hl7BodyMap.keySet().iterator();
}
if( keySetIterator != null ) {
result = new StringBuilder( "" );
while ( keySetIterator.hasNext() ) {
messageId = keySetIterator.next();
if( ! MessageUploader.routeReport( loggedInInfo, serviceName, HL7_FORMAT, hl7BodyMap.get(messageId), fileId ).isEmpty() ) {
result.append( SUCCESS + messageId + "," );
} else {
result.append( FAILED + messageId + "," );
}
}
}
} catch (ExceptionInInitializerError e) {
result = new StringBuilder( FAILED + messageId + "," );
logger.error("There was an unknown internal error with file " + fileName + " message id " + messageId, e);
} catch (Exception e) {
result = new StringBuilder( FAILED + messageId + "," );
logger.error("Could not upload IHAPOI message " + fileName + " due to an error with message id " + messageId, e);
} finally {
if( is != null ) {
try {
is.close();
is = null;
} catch (IOException e) {
logger.error("Failed to close IHAPOI InputStream ", e);
}
}
if( FAILED.equals( result.toString().split(":")[0] + ":" ) ) {
logger.error( "Cleaning up MessageUploader file." );
MessageUploader.clean(fileId);
}
}
if( result.length() > 1) {
result = result.deleteCharAt( result.length() - 1 );
}
return result.toString();
}
public Map<String, String> parse(InputStream is) throws ParserConfigurationException, SAXException, IOException {
return textOrXml(is);
}
private Map<String, String> textOrXml(InputStream is) throws ParserConfigurationException, SAXException, IOException {
ByteArrayInputStream bais = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
org.apache.commons.io.IOUtils.copy(is, baos);
byte[] bytes = baos.toByteArray();
String hl7Body = new String( bytes, StandardCharsets.UTF_8 ).trim();
Map<String, String> hl7BodyMap = null;
if( hl7Body != null && hl7Body.length() > 0 ) {
if( hl7Body.startsWith( XML_PATTERN ) ) {
bais = new ByteArrayInputStream( bytes );
bais.reset();
hl7BodyMap = parseXml( bais );
} else {
hl7BodyMap = parseText( hl7Body );
}
}
if( baos != null ) {
baos.close();
}
if( bais != null ) {
bais.close();
}
return hl7BodyMap;
}
protected Map<String, String> parseXml(InputStream is) throws ParserConfigurationException, SAXException, IOException {
Element messageSpec = null;
Element messagesElement = null;
NodeList messagesNode = null;
Map<String, String> hl7BodyMap = null;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(true);
docFactory.setValidating(false);
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(is);
if(doc != null) {
messageSpec = doc.getDocumentElement();
}
if( messageSpec != null && messageSpec.hasChildNodes() ) {
messageSpec.normalize();
messagesNode = messageSpec.getChildNodes();
for(int i = 0; i < messagesNode.getLength(); i++) {
if (messagesNode.item(i) instanceof Element) {
messagesElement = (Element) messagesNode.item(i);
break;
}
}
}
if(messagesElement != null && messagesElement.hasChildNodes() ) {
messagesNode = messagesElement.getChildNodes();
}
if( messagesNode.getLength() > 0 ) {
for( int i = 0; i < messagesNode.getLength(); i++ ) {
if( hl7BodyMap == null ) {
hl7BodyMap = new HashMap<String, String>();
}
if( messagesNode.item(i) instanceof Element ) {
Element messageNode = (Element) messagesNode.item(i);
hl7BodyMap.put( getMessageId( messageNode ), messageNode.getTextContent() );
}
}
}
return hl7BodyMap;
}
private Map<String, String> parseText( String hl7Body ) {
// anymore division and pre-parsing should be done here.
// so far, only one body per string is expected.
HashMap<String, String> hl7BodyMap = new HashMap<String, String>();
hl7BodyMap.put("0", hl7Body);
return hl7BodyMap;
}
private String getMessageId( Element element ) {
NamedNodeMap nodeAttributes = element.getAttributes();
String messageId = "";
if ( nodeAttributes != null ) {
for (int i = 0; i < nodeAttributes.getLength(); i++) {
Node attribute = nodeAttributes.item(i);
String attributeName = attribute.getNodeName();
if( MESSAGE_ID_NODE_NAME.equalsIgnoreCase( attributeName ) ) {
messageId = attribute.getNodeValue();
}
}
}
return messageId;
}
}
| gpl-2.0 |
appsol/gf-quickbooks-online | public/class-gf-quickbooks-online-public.php | 2673 | <?php
/**
* The public-facing functionality of the plugin.
*
* @link http://example.com
* @since 0.1.0
*
* @package GFQuickbooksOnline
* @subpackage GFQuickbooksOnline/public
*/
namespace AppSol\GFQuickbooksOnline\Pub;
/**
* The public-facing functionality of the plugin.
*
* Defines the plugin name, version, and two examples hooks for how to
* enqueue the admin-specific stylesheet and JavaScript.
*
* @package GFQuickbooksOnline
* @subpackage GFQuickbooksOnline/public
* @author Stuart Laverick <stuart@appropriatesolutions.co.uk>
*/
class Pub {
/**
* The ID of this plugin.
*
* @since 0.1.0
* @access private
* @var string $plugin_name The ID of this plugin.
*/
private $plugin_name;
/**
* The version of this plugin.
*
* @since 0.1.0
* @access private
* @var string $version The current version of this plugin.
*/
private $version;
/**
* Initialize the class and set its properties.
*
* @since 0.1.0
* @param string $plugin_name The name of the plugin.
* @param string $version The version of this plugin.
*/
public function __construct($plugin_name, $version) {
$this->plugin_name = $plugin_name;
$this->version = $version;
}
/**
* Register the stylesheets for the public-facing side of the site.
*
* @since 0.1.0
*/
public function enqueueStyles() {
/**
* This function is provided for demonstration purposes only.
*
* An instance of this class should be passed to the run() function
* defined in GFQuickbooksOnline_Loader as all of the hooks are defined
* in that particular class.
*
* The GFQuickbooksOnline_Loader will then create the relationship
* between the defined hooks and the functions defined in this
* class.
*/
wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/gf-quickbooks-online-public.css', array(), $this->version, 'all');
}
/**
* Register the JavaScript for the public-facing side of the site.
*
* @since 0.1.0
*/
public function enqueueScripts() {
/**
* This function is provided for demonstration purposes only.
*
* An instance of this class should be passed to the run() function
* defined in GFQuickbooksOnline_Loader as all of the hooks are defined
* in that particular class.
*
* The GFQuickbooksOnline_Loader will then create the relationship
* between the defined hooks and the functions defined in this
* class.
*/
wp_enqueue_script($this->plugin_name, plugin_dir_url(__FILE__) . 'js/gf-quickbooks-online-public.js', array('jquery'), $this->version, false);
}
}
| gpl-2.0 |
mekolat/ManaPlus | src/resources/db/emotedb.cpp | 9474 | /*
* The ManaPlus Client
* Copyright (C) 2009 Aethyra Development Team
* Copyright (C) 2011-2018 The ManaPlus Developers
*
* This file is part of The ManaPlus Client.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "resources/db/emotedb.h"
#include "client.h"
#include "configuration.h"
#include "utils/checkutils.h"
#include "resources/beingcommon.h"
#include "resources/emoteinfo.h"
#include "resources/emotesprite.h"
#include "resources/sprite/animatedsprite.h"
#include "debug.h"
namespace
{
EmoteInfos mEmoteInfos;
EmoteToEmote mEmotesAlt;
EmoteInfo mUnknown;
bool mLoaded = false;
int mLastEmote = 0;
} // namespace
void EmoteDB::load()
{
if (mLoaded)
unload();
logger->log1("Initializing emote database...");
EmoteSprite *const unknownSprite = new EmoteSprite;
unknownSprite->sprite = AnimatedSprite::load(pathJoin(paths.getStringValue(
"sprites"), paths.getStringValue(
"spriteErrorFile")),
0);
unknownSprite->name = "unknown";
unknownSprite->id = 0;
mUnknown.sprites.push_back(unknownSprite);
mLastEmote = 0;
loadXmlFile(paths.getStringValue("emotesFile"), SkipError_false);
loadXmlFile(paths.getStringValue("emotesPatchFile"), SkipError_true);
loadXmlDir("emotesPatchDir", loadXmlFile);
loadSpecialXmlFile("graphics/sprites/manaplus_emotes.xml",
SkipError_false);
mLoaded = true;
}
void EmoteDB::loadXmlFile(const std::string &fileName,
const SkipError skipError)
{
XML::Document doc(fileName, UseVirtFs_true, skipError);
XmlNodePtrConst rootNode = doc.rootNode();
if ((rootNode == nullptr) || !xmlNameEqual(rootNode, "emotes"))
{
logger->log("Emote Database: Error while loading %s!",
fileName.c_str());
return;
}
// iterate <emote>s
for_each_xml_child_node(emoteNode, rootNode)
{
if (xmlNameEqual(emoteNode, "include"))
{
const std::string name = XML::getProperty(emoteNode, "name", "");
if (!name.empty())
loadXmlFile(name, skipError);
continue;
}
else if (!xmlNameEqual(emoteNode, "emote"))
{
continue;
}
const int id = XML::getProperty(emoteNode, "id", -1);
// skip hight images
if (id > 19 || (Client::isTmw() && id > 13))
continue;
if (id == -1)
{
reportAlways("Emote Database: Emote with missing ID in %s!",
paths.getStringValue("emotesFile").c_str());
continue;
}
EmoteInfo *currentInfo = nullptr;
if (mEmoteInfos.find(id) != mEmoteInfos.end())
currentInfo = mEmoteInfos[id];
else
currentInfo = new EmoteInfo;
if (currentInfo == nullptr)
continue;
currentInfo->time = XML::getProperty(emoteNode, "time", 500);
currentInfo->effectId = XML::getProperty(emoteNode, "effect", -1);
for_each_xml_child_node(spriteNode, emoteNode)
{
if (!XmlHaveChildContent(spriteNode))
continue;
if (xmlNameEqual(spriteNode, "sprite"))
{
EmoteSprite *const currentSprite = new EmoteSprite;
currentSprite->sprite = AnimatedSprite::load(pathJoin(
paths.getStringValue("sprites"),
XmlChildContent(spriteNode)),
XML::getProperty(spriteNode, "variant", 0));
currentSprite->name = XML::langProperty(
spriteNode, "name", "");
currentSprite->id = id;
currentInfo->sprites.push_back(currentSprite);
}
else if (xmlNameEqual(spriteNode, "particlefx"))
{
currentInfo->particles.push_back(XmlChildContent(spriteNode));
}
}
mEmoteInfos[id] = currentInfo;
if (id > mLastEmote)
mLastEmote = id;
}
}
void EmoteDB::loadSpecialXmlFile(const std::string &fileName,
const SkipError skipError)
{
XML::Document doc(fileName, UseVirtFs_true, skipError);
XmlNodePtrConst rootNode = doc.rootNode();
if ((rootNode == nullptr) || !xmlNameEqual(rootNode, "emotes"))
{
logger->log1("Emote Database: Error while loading"
" manaplus_emotes.xml!");
return;
}
// iterate <emote>s
for_each_xml_child_node(emoteNode, rootNode)
{
if (xmlNameEqual(emoteNode, "include"))
{
const std::string name = XML::getProperty(emoteNode, "name", "");
if (!name.empty())
loadSpecialXmlFile(name, skipError);
continue;
}
else if (!xmlNameEqual(emoteNode, "emote"))
{
continue;
}
const int id = XML::getProperty(emoteNode, "id", -1);
if (id == -1)
{
reportAlways("Emote Database: Emote with missing ID in "
"manaplus_emotes.xml!");
continue;
}
const int altId = XML::getProperty(emoteNode, "altid", -1);
EmoteInfo *currentInfo = nullptr;
if (mEmoteInfos.find(id) != mEmoteInfos.end())
currentInfo = mEmoteInfos[id];
if (currentInfo == nullptr)
currentInfo = new EmoteInfo;
currentInfo->time = XML::getProperty(emoteNode, "time", 500);
currentInfo->effectId = XML::getProperty(emoteNode, "effect", -1);
for_each_xml_child_node(spriteNode, emoteNode)
{
if (!XmlHaveChildContent(spriteNode))
continue;
if (xmlNameEqual(spriteNode, "sprite"))
{
EmoteSprite *const currentSprite = new EmoteSprite;
currentSprite->sprite = AnimatedSprite::load(pathJoin(
paths.getStringValue("sprites"),
XmlChildContent(spriteNode)),
XML::getProperty(spriteNode, "variant", 0));
currentSprite->name = XML::langProperty(
spriteNode, "name", "");
currentSprite->id = id;
currentInfo->sprites.push_back(currentSprite);
}
else if (xmlNameEqual(spriteNode, "particlefx"))
{
currentInfo->particles.push_back(XmlChildContent(spriteNode));
}
}
mEmoteInfos[id] = currentInfo;
if (altId != -1)
mEmotesAlt[altId] = id;
if (id > mLastEmote)
mLastEmote = id;
}
}
void EmoteDB::unload()
{
logger->log1("Unloading emote database...");
FOR_EACH (EmoteInfos::const_iterator, i, mEmoteInfos)
{
if (i->second != nullptr)
{
std::list<EmoteSprite*> &sprites = i->second->sprites;
while (!sprites.empty())
{
delete sprites.front()->sprite;
delete sprites.front();
sprites.pop_front();
}
delete i->second;
}
}
mEmoteInfos.clear();
std::list<EmoteSprite*> &sprites = mUnknown.sprites;
while (!sprites.empty())
{
delete sprites.front()->sprite;
delete sprites.front();
sprites.pop_front();
}
mLoaded = false;
}
const EmoteInfo *EmoteDB::get(const int id, const bool allowNull)
{
const EmoteInfos::const_iterator i = mEmoteInfos.find(id);
if (i == mEmoteInfos.end())
{
if (allowNull)
return nullptr;
reportAlways("EmoteDB: Warning, unknown emote ID %d requested",
id);
return &mUnknown;
}
return i->second;
}
const EmoteInfo *EmoteDB::get2(int id, const bool allowNull)
{
const EmoteToEmote::const_iterator it = mEmotesAlt.find(id);
if (it != mEmotesAlt.end())
id = (*it).second;
const EmoteInfos::const_iterator i = mEmoteInfos.find(id);
if (i == mEmoteInfos.end())
{
if (allowNull)
return nullptr;
reportAlways("EmoteDB: Warning, unknown emote ID %d requested",
id);
return &mUnknown;
}
return i->second;
}
const EmoteSprite *EmoteDB::getSprite(const int id, const bool allowNull)
{
const EmoteInfo *const info = get(id, allowNull);
if (info == nullptr)
return nullptr;
return info->sprites.front();
}
const int &EmoteDB::getLast()
{
return mLastEmote;
}
int EmoteDB::size()
{
return static_cast<signed int>(mEmoteInfos.size());
}
int EmoteDB::getIdByIndex(const int index)
{
if (index < 0 || index >= static_cast<signed int>(mEmoteInfos.size()))
return 0;
EmoteInfos::const_iterator it = mEmoteInfos.begin();
for (int f = 0; f < index; f ++)
++ it;
return (*it).first;
}
| gpl-2.0 |
ahmedRguei/job | typo3conf/ext/flux/Classes/Utility/AnnotationUtility.php | 5452 | <?php
namespace FluidTYPO3\Flux\Utility;
/*
* This file is part of the FluidTYPO3/Flux project under GPLv2 or later.
*
* For the full copyright and license information, please read the
* LICENSE.md file that was distributed with this source code.
*/
use TYPO3\CMS\Extbase\Reflection\ClassReflection;
use TYPO3\CMS\Extbase\Reflection\ObjectAccess;
use TYPO3\CMS\Fluid\Core\Parser\TemplateParser;
use TYPO3Fluid\Fluid\Core\Parser\Patterns;
/**
* Annotation Utility
*/
class AnnotationUtility
{
/**
* @param string $className
* @param string $annotationName
* @param string|boolean $propertyName
* @return array|boolean
*/
public static function getAnnotationValueFromClass($className, $annotationName, $propertyName = null)
{
$reflection = new ClassReflection($className);
$sample = new $className();
$annotations = [];
if (null === $propertyName) {
if (false === $reflection->isTaggedWith($annotationName)) {
return false;
}
$annotations = $reflection->getTagValues($annotationName);
} elseif (false === $propertyName) {
$properties = ObjectAccess::getGettablePropertyNames($sample);
foreach ($properties as $reflectedPropertyName) {
if (false === property_exists($className, $reflectedPropertyName)) {
continue;
}
$propertyAnnotationValues = self::getPropertyAnnotations(
$reflection,
$reflectedPropertyName,
$annotationName
);
if (null !== $propertyAnnotationValues) {
$annotations[$reflectedPropertyName] = $propertyAnnotationValues;
}
}
} else {
$annotations = self::getPropertyAnnotations($reflection, $propertyName, $annotationName);
}
$annotations = self::parseAnnotation($annotations);
return ($propertyName && isset($annotations[$propertyName])) ? $annotations[$propertyName] : $annotations;
}
/**
* @param ClassReflection $reflection
* @param string $propertyName
* @param string $annotationName
* @return array
*/
protected static function getPropertyAnnotations(ClassReflection $reflection, $propertyName, $annotationName)
{
$reflectedProperty = $reflection->getProperty($propertyName);
if (true === $reflectedProperty->isTaggedWith($annotationName)) {
return $reflectedProperty->getTagValues($annotationName);
}
return null;
}
/**
* @param string $argumentsAsString
* @return string
*/
protected static function parseAnnotationArguments($argumentsAsString)
{
if (class_exists(TemplateParser::class)) {
$pattern = TemplateParser::$SPLIT_PATTERN_SHORTHANDSYNTAX_ARRAY_PARTS;
} else {
$pattern = Patterns::$SPLIT_PATTERN_SHORTHANDSYNTAX_ARRAY_PARTS;
}
$matches = [];
preg_match_all($pattern, $argumentsAsString, $matches, PREG_SET_ORDER);
$arguments = [];
foreach ($matches as $match) {
$name = $match['Key'];
if (true === isset($match['Subarray']) && 0 < strlen($match['Subarray'])) {
$arguments[$name] = self::parseAnnotationArguments($match['Subarray']);
} elseif (true === isset($match['Number'])) {
if (true === ctype_digit($match['Number'])) {
$arguments[$name] = intval($match['Number']);
} elseif (false !== strpos($match['Number'], '.')) {
$arguments[$name] = floatval($match['Number']);
}
} elseif (true === isset($match['QuotedString'])) {
$arguments[$name] = trim($match['QuotedString'], '\'');
}
}
return $arguments;
}
/**
* @param mixed $annotation
* @return string
*/
public static function parseAnnotation($annotation)
{
if (true === is_array($annotation)) {
if (true === empty($annotation)) {
return true;
} elseif (true === isset($annotation[0]) && 1 === count($annotation)) {
return self::parseAnnotation(array_pop($annotation));
}
return array_map([self, 'parseAnnotation'], $annotation);
}
if (class_exists(TemplateParser::class)) {
$pattern = TemplateParser::$SPLIT_PATTERN_SHORTHANDSYNTAX_VIEWHELPER;
} else {
$pattern = Patterns::$SPLIT_PATTERN_SHORTHANDSYNTAX_VIEWHELPER;
}
$annotation = trim($annotation);
if (true === empty($annotation)) {
// simple indication that annotation does exist but has no attributes.
return true;
}
if (false === strpos($annotation, '(') && false === strpos($annotation, ')')) {
$annotation .= '()';
}
if (0 !== strpos($annotation, '{')) {
$annotation = '{flux:' . $annotation . '}';
}
$matches = [];
preg_match_all($pattern, $annotation, $matches, PREG_SET_ORDER);
$structure = [
'type' => $matches[0]['MethodIdentifier'],
'config' => self::parseAnnotationArguments($matches['0']['ViewHelperArguments'])
];
return $structure;
}
}
| gpl-2.0 |
iut-ibk/DynaMind-ToolBox | DynaMind-BasicModules/src/DynaMind-BasicModules/simplecrypt.cpp | 7260 | /*
Copyright (c) 2011, Andre Somers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Rathenau Instituut, Andre Somers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL ANDRE SOMERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "simplecrypt.h"
#include <QByteArray>
#include <QtDebug>
#include <QtGlobal>
#include <QDateTime>
#include <QDataStream>
#include <QCryptographicHash>
SimpleCrypt::SimpleCrypt():
m_key(0),
m_compressionMode(CompressionAuto),
m_protectionMode(ProtectionChecksum),
m_lastError(ErrorNoError)
{
qsrand(uint(QDateTime::currentMSecsSinceEpoch() & 0xFFFF));
}
SimpleCrypt::SimpleCrypt(quint64 key):
m_key(key),
m_compressionMode(CompressionAuto),
m_protectionMode(ProtectionChecksum),
m_lastError(ErrorNoError)
{
qsrand(uint(QDateTime::currentMSecsSinceEpoch() & 0xFFFF));
splitKey();
}
void SimpleCrypt::setKey(quint64 key)
{
m_key = key;
splitKey();
}
void SimpleCrypt::splitKey()
{
m_keyParts.clear();
m_keyParts.resize(8);
for (int i=0;i<8;i++) {
quint64 part = m_key;
for (int j=i; j>0; j--)
part = part >> 8;
part = part & 0xff;
m_keyParts[i] = static_cast<char>(part);
}
}
QByteArray SimpleCrypt::encryptToByteArray(const QString& plaintext)
{
QByteArray plaintextArray = plaintext.toUtf8();
return encryptToByteArray(plaintextArray);
}
QByteArray SimpleCrypt::encryptToByteArray(QByteArray plaintext)
{
if (m_keyParts.isEmpty()) {
qWarning() << "No key set.";
m_lastError = ErrorNoKeySet;
return QByteArray();
}
QByteArray ba = plaintext;
CryptoFlags flags = CryptoFlagNone;
if (m_compressionMode == CompressionAlways) {
ba = qCompress(ba, 9); //maximum compression
flags |= CryptoFlagCompression;
} else if (m_compressionMode == CompressionAuto) {
QByteArray compressed = qCompress(ba, 9);
if (compressed.count() < ba.count()) {
ba = compressed;
flags |= CryptoFlagCompression;
}
}
QByteArray integrityProtection;
if (m_protectionMode == ProtectionChecksum) {
flags |= CryptoFlagChecksum;
QDataStream s(&integrityProtection, QIODevice::WriteOnly);
s << qChecksum(ba.constData(), ba.length());
} else if (m_protectionMode == ProtectionHash) {
flags |= CryptoFlagHash;
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData(ba);
integrityProtection += hash.result();
}
//prepend a random char to the string
char randomChar = char(qrand() & 0xFF);
ba = randomChar + integrityProtection + ba;
int pos(0);
char lastChar(0);
int cnt = ba.count();
while (pos < cnt) {
ba[pos] = ba.at(pos) ^ m_keyParts.at(pos % 8) ^ lastChar;
lastChar = ba.at(pos);
++pos;
}
QByteArray resultArray;
resultArray.append(char(0x03)); //version for future updates to algorithm
resultArray.append(char(flags)); //encryption flags
resultArray.append(ba);
m_lastError = ErrorNoError;
return resultArray;
}
QString SimpleCrypt::encryptToString(const QString& plaintext)
{
QByteArray plaintextArray = plaintext.toUtf8();
QByteArray cypher = encryptToByteArray(plaintextArray);
QString cypherString = QString::fromLatin1(cypher.toBase64());
return cypherString;
}
QString SimpleCrypt::encryptToString(QByteArray plaintext)
{
QByteArray cypher = encryptToByteArray(plaintext);
QString cypherString = QString::fromLatin1(cypher.toBase64());
return cypherString;
}
QString SimpleCrypt::decryptToString(const QString &cyphertext)
{
QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toLatin1());
QByteArray plaintextArray = decryptToByteArray(cyphertextArray);
QString plaintext = QString::fromUtf8(plaintextArray, plaintextArray.size());
return plaintext;
}
QString SimpleCrypt::decryptToString(QByteArray cypher)
{
QByteArray ba = decryptToByteArray(cypher);
QString plaintext = QString::fromUtf8(ba, ba.size());
return plaintext;
}
QByteArray SimpleCrypt::decryptToByteArray(const QString& cyphertext)
{
QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toLatin1());
QByteArray ba = decryptToByteArray(cyphertextArray);
return ba;
}
QByteArray SimpleCrypt::decryptToByteArray(QByteArray cypher)
{
if (m_keyParts.isEmpty()) {
qWarning() << "No key set.";
m_lastError = ErrorNoKeySet;
return QByteArray();
}
if (!cypher.length()) {
m_lastError = ErrorUnknownVersion;
return QByteArray();
}
QByteArray ba = cypher;
char version = ba.at(0);
if (version !=3) { //we only work with version 3
m_lastError = ErrorUnknownVersion;
qWarning() << "Invalid version or not a cyphertext.";
return QByteArray();
}
CryptoFlags flags = CryptoFlags(ba.at(1));
ba = ba.mid(2);
int pos(0);
int cnt(ba.count());
char lastChar = 0;
while (pos < cnt) {
char currentChar = ba[pos];
ba[pos] = ba.at(pos) ^ lastChar ^ m_keyParts.at(pos % 8);
lastChar = currentChar;
++pos;
}
ba = ba.mid(1); //chop off the random number at the start
bool integrityOk(true);
if (flags.testFlag(CryptoFlagChecksum)) {
if (ba.length() < 2) {
m_lastError = ErrorIntegrityFailed;
return QByteArray();
}
quint16 storedChecksum;
{
QDataStream s(&ba, QIODevice::ReadOnly);
s >> storedChecksum;
}
ba = ba.mid(2);
quint16 checksum = qChecksum(ba.constData(), ba.length());
integrityOk = (checksum == storedChecksum);
} else if (flags.testFlag(CryptoFlagHash)) {
if (ba.length() < 20) {
m_lastError = ErrorIntegrityFailed;
return QByteArray();
}
QByteArray storedHash = ba.left(20);
ba = ba.mid(20);
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData(ba);
integrityOk = (hash.result() == storedHash);
}
if (!integrityOk) {
m_lastError = ErrorIntegrityFailed;
return QByteArray();
}
if (flags.testFlag(CryptoFlagCompression))
ba = qUncompress(ba);
m_lastError = ErrorNoError;
return ba;
}
| gpl-2.0 |
Open-Transport/synthese | legacy/server/src/10_db/103_svn/SVNCommitAction.cpp | 4200 |
//////////////////////////////////////////////////////////////////////////
/// SVNCommitAction class implementation.
/// @file SVNCommitAction.cpp
/// @author Hugues Romain
/// @date 2012
///
/// This file belongs to the SYNTHESE project (public transportation specialized software)
/// Copyright (C) 2002 Hugues Romain - RCSmobility <contact@rcsmobility.com>
///
/// This program is free software; you can redistribute it and/or
/// modify it under the terms of the GNU General Public License
/// as published by the Free Software Foundation; either version 2
/// of the License, or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#include "SVNCommitAction.hpp"
#include "ActionException.h"
#include "DBModule.h"
#include "ObjectBase.hpp"
#include "ParametersMap.h"
#include "Request.h"
#include "SVNWorkingCopy.hpp"
using namespace boost;
using namespace std;
namespace synthese
{
using namespace server;
using namespace security;
using namespace util;
template<>
const string FactorableTemplate<Action, db::svn::SVNCommitAction>::FACTORY_KEY = "SVNCommit";
namespace db
{
namespace svn
{
const string SVNCommitAction::PARAMETER_OBJECT_ID = Action_PARAMETER_PREFIX + "_object_id";
const string SVNCommitAction::PARAMETER_USER = Action_PARAMETER_PREFIX + "_user";
const string SVNCommitAction::PARAMETER_PASSWORD = Action_PARAMETER_PREFIX + "_password";
const string SVNCommitAction::PARAMETER_MESSAGE = Action_PARAMETER_PREFIX + "_message";
const string SVNCommitAction::PARAMETER_NO_COMMIT = Action_PARAMETER_PREFIX + "_no_commit";
const string SVNCommitAction::PARAMETER_NO_UPDATE = Action_PARAMETER_PREFIX + "_no_update";
ParametersMap SVNCommitAction::getParametersMap() const
{
ParametersMap map;
// Object
if(_object.get())
{
map.insert(PARAMETER_OBJECT_ID, _object->getKey());
}
return map;
}
void SVNCommitAction::_setFromParametersMap(const ParametersMap& map)
{
// Object
try
{
_object = dynamic_pointer_cast<ObjectBase, Registrable>(
DBModule::GetEditableObject(
map.get<RegistryKeyType>(PARAMETER_OBJECT_ID),
Env::GetOfficialEnv()
) );
}
catch(ObjectNotFoundException<Registrable>&)
{
throw ActionException("No such object");
}
catch(Exception&)
{
throw ActionException("This object cannot be saved into a subversion repository");
}
if(!_object.get())
{
throw ActionException("This object cannot be saved into a subversion repository");
}
// Check if the object has SVN storage capabilities
if(!_object->hasField<SVNWorkingCopy>())
{
throw ActionException("This object cannot be saved into a subversion repository");
}
// User
_user = map.getDefault<string>(PARAMETER_USER);
// Password
_password = map.getDefault<string>(PARAMETER_PASSWORD);
// Message
_message = map.getDefault<string>(PARAMETER_MESSAGE);
// No commit
_noCommit = map.getDefault<bool>(PARAMETER_NO_COMMIT, false);
// No update
_noUpdate = map.getDefault<bool>(PARAMETER_NO_UPDATE, false);
}
void SVNCommitAction::run(
Request& request
){
SVNWorkingCopy& wc(const_cast<SVNWorkingCopy&>(_object->dynamic_get<SVNWorkingCopy>()));
wc.commit(_message, _user, _password, _noCommit, _noUpdate);
}
bool SVNCommitAction::isAuthorized(
const Session* session
) const {
// return session && session->hasProfile() && session->getUser()->getProfile()->isAuthorized<>();
return true;
}
} } }
| gpl-2.0 |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/_ssl.py | 59543 | # encoding: utf-8
# module _ssl
# from /usr/lib/python3.4/lib-dynload/_ssl.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
"""
Implementation module for SSL socket operations. See the socket module
for documentation.
"""
# imports
import ssl as __ssl
# Variables with simple values
ALERT_DESCRIPTION_ACCESS_DENIED = 49
ALERT_DESCRIPTION_BAD_CERTIFICATE = 42
ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE = 114
ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE = 113
ALERT_DESCRIPTION_BAD_RECORD_MAC = 20
ALERT_DESCRIPTION_CERTIFICATE_EXPIRED = 45
ALERT_DESCRIPTION_CERTIFICATE_REVOKED = 44
ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN = 46
ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE = 111
ALERT_DESCRIPTION_CLOSE_NOTIFY = 0
ALERT_DESCRIPTION_DECODE_ERROR = 50
ALERT_DESCRIPTION_DECOMPRESSION_FAILURE = 30
ALERT_DESCRIPTION_DECRYPT_ERROR = 51
ALERT_DESCRIPTION_HANDSHAKE_FAILURE = 40
ALERT_DESCRIPTION_ILLEGAL_PARAMETER = 47
ALERT_DESCRIPTION_INSUFFICIENT_SECURITY = 71
ALERT_DESCRIPTION_INTERNAL_ERROR = 80
ALERT_DESCRIPTION_NO_RENEGOTIATION = 100
ALERT_DESCRIPTION_PROTOCOL_VERSION = 70
ALERT_DESCRIPTION_RECORD_OVERFLOW = 22
ALERT_DESCRIPTION_UNEXPECTED_MESSAGE = 10
ALERT_DESCRIPTION_UNKNOWN_CA = 48
ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY = 115
ALERT_DESCRIPTION_UNRECOGNIZED_NAME = 112
ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE = 43
ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION = 110
ALERT_DESCRIPTION_USER_CANCELLED = 90
CERT_NONE = 0
CERT_OPTIONAL = 1
CERT_REQUIRED = 2
HAS_ECDH = True
HAS_NPN = True
HAS_SNI = True
HAS_TLS_UNIQUE = True
OPENSSL_VERSION = 'OpenSSL 1.0.1i 6 Aug 2014'
OPENSSL_VERSION_NUMBER = 268439711
OP_ALL = 2147484671
OP_CIPHER_SERVER_PREFERENCE = 4194304
OP_NO_COMPRESSION = 131072
OP_NO_SSLv2 = 16777216
OP_NO_SSLv3 = 33554432
OP_NO_TLSv1 = 67108864
OP_NO_TLSv1_1 = 268435456
OP_NO_TLSv1_2 = 134217728
OP_SINGLE_DH_USE = 1048576
OP_SINGLE_ECDH_USE = 524288
PROTOCOL_SSLv23 = 2
PROTOCOL_SSLv3 = 1
PROTOCOL_TLSv1 = 3
PROTOCOL_TLSv1_1 = 4
PROTOCOL_TLSv1_2 = 5
SSL_ERROR_EOF = 8
SSL_ERROR_INVALID_ERROR_CODE = 10
SSL_ERROR_SSL = 1
SSL_ERROR_SYSCALL = 5
SSL_ERROR_WANT_CONNECT = 7
SSL_ERROR_WANT_READ = 2
SSL_ERROR_WANT_WRITE = 3
SSL_ERROR_WANT_X509_LOOKUP = 4
SSL_ERROR_ZERO_RETURN = 6
VERIFY_CRL_CHECK_CHAIN = 12
VERIFY_CRL_CHECK_LEAF = 4
VERIFY_DEFAULT = 0
VERIFY_X509_STRICT = 32
# functions
def get_default_verify_paths(): # real signature unknown; restored from __doc__
"""
get_default_verify_paths() -> tuple
Return search paths and environment vars that are used by SSLContext's
set_default_verify_paths() to load default CAs. The values are
'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
"""
return ()
def nid2obj(nid): # real signature unknown; restored from __doc__
"""
nid2obj(nid) -> (nid, shortname, longname, oid)
Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
"""
pass
def RAND_add(string, entropy): # real signature unknown; restored from __doc__
"""
RAND_add(string, entropy)
Mix string into the OpenSSL PRNG state. entropy (a float) is a lower
bound on the entropy contained in string. See RFC 1750.
"""
pass
def RAND_bytes(n): # real signature unknown; restored from __doc__
"""
RAND_bytes(n) -> bytes
Generate n cryptographically strong pseudo-random bytes.
"""
return b""
def RAND_egd(path): # real signature unknown; restored from __doc__
"""
RAND_egd(path) -> bytes
Queries the entropy gather daemon (EGD) on the socket named by 'path'.
Returns number of bytes read. Raises SSLError if connection to EGD
fails or if it does not provide enough data to seed PRNG.
"""
return b""
def RAND_pseudo_bytes(n): # real signature unknown; restored from __doc__
"""
RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)
Generate n pseudo-random bytes. is_cryptographic is True if the bytesgenerated are cryptographically strong.
"""
pass
def RAND_status(): # real signature unknown; restored from __doc__
"""
RAND_status() -> 0 or 1
Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
It is necessary to seed the PRNG with RAND_add() on some platforms before
using the ssl() function.
"""
pass
def txt2obj(txt, name=False): # real signature unknown; restored from __doc__
"""
txt2obj(txt, name=False) -> (nid, shortname, longname, oid)
Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default
objects are looked up by OID. With name=True short and long name are also
matched.
"""
pass
def _test_decode_cert(*args, **kwargs): # real signature unknown
pass
# classes
from .OSError import OSError
class SSLError(OSError):
""" An error occurred in the SSL implementation. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
class SSLEOFError(__ssl.SSLError):
""" SSL/TLS connection terminated abruptly. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
class SSLSyscallError(__ssl.SSLError):
""" System error when attempting SSL operation. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
class SSLWantReadError(__ssl.SSLError):
"""
Non-blocking SSL socket needs to read more data
before the requested operation can be completed.
"""
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
class SSLWantWriteError(__ssl.SSLError):
"""
Non-blocking SSL socket needs to write more data
before the requested operation can be completed.
"""
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
class SSLZeroReturnError(__ssl.SSLError):
""" SSL/TLS session closed cleanly. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
from .object import object
class _SSLContext(object):
# no doc
def cert_store_stats(self): # real signature unknown; restored from __doc__
"""
cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}
Returns quantities of loaded X.509 certificates. X.509 certificates with a
CA extension and certificate revocation lists inside the context's cert
store.
NOTE: Certificates in a capath directory aren't loaded unless they have
been used at least once.
"""
pass
def get_ca_certs(self, binary_form=False): # real signature unknown; restored from __doc__
"""
get_ca_certs(binary_form=False) -> list of loaded certificate
Returns a list of dicts with information of loaded CA certs. If the
optional argument is True, returns a DER-encoded copy of the CA certificate.
NOTE: Certificates in a capath directory aren't loaded unless they have
been used at least once.
"""
return []
def load_cert_chain(self, *args, **kwargs): # real signature unknown
pass
def load_dh_params(self, *args, **kwargs): # real signature unknown
pass
def load_verify_locations(self, *args, **kwargs): # real signature unknown
pass
def session_stats(self, *args, **kwargs): # real signature unknown
pass
def set_ciphers(self, *args, **kwargs): # real signature unknown
pass
def set_default_verify_paths(self, *args, **kwargs): # real signature unknown
pass
def set_ecdh_curve(self, *args, **kwargs): # real signature unknown
pass
def set_servername_callback(self, method): # real signature unknown; restored from __doc__
"""
set_servername_callback(method)
This sets a callback that will be called when a server name is provided by
the SSL/TLS client in the SNI extension.
If the argument is None then the callback is disabled. The method is called
with the SSLSocket, the server name as a string, and the SSLContext object.
See RFC 6066 for details of the SNI extension.
"""
pass
def _set_npn_protocols(self, *args, **kwargs): # real signature unknown
pass
def _wrap_socket(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
check_hostname = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
options = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
verify_flags = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
verify_mode = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
from .object import object
class _SSLSocket(object):
# no doc
def cipher(self, *args, **kwargs): # real signature unknown
pass
def compression(self, *args, **kwargs): # real signature unknown
pass
def do_handshake(self, *args, **kwargs): # real signature unknown
pass
def peer_certificate(self, der=False): # real signature unknown; restored from __doc__
"""
peer_certificate([der=False]) -> certificate
Returns the certificate for the peer. If no certificate was provided,
returns None. If a certificate was provided, but not validated, returns
an empty dictionary. Otherwise returns a dict containing information
about the peer certificate.
If the optional argument is True, returns a DER-encoded copy of the
peer certificate, or None if no certificate was provided. This will
return the certificate even if it wasn't validated.
"""
pass
def pending(self): # real signature unknown; restored from __doc__
"""
pending() -> count
Returns the number of already decrypted bytes available for read,
pending on the connection.
"""
pass
def read(self, len=None): # real signature unknown; restored from __doc__
"""
read([len]) -> string
Read up to len bytes from the SSL socket.
"""
return ""
def selected_npn_protocol(self, *args, **kwargs): # real signature unknown
pass
def shutdown(self, s): # real signature unknown; restored from __doc__
"""
shutdown(s) -> socket
Does the SSL shutdown handshake with the remote end, and returns
the underlying socket object.
"""
pass
def tls_unique_cb(self): # real signature unknown; restored from __doc__
"""
tls_unique_cb() -> bytes
Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
If the TLS handshake is not yet complete, None is returned
"""
return b""
def write(self, s): # real signature unknown; restored from __doc__
"""
write(s) -> len
Writes the string s into the SSL object. Returns the number
of bytes written.
"""
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
context = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""_setter_context(ctx)
This changes the context associated with the SSLSocket. This is typically
used from within a callback function set by the set_servername_callback
on the SSLContext to change the certificate information associated with the
SSLSocket before the cryptographic exchange handshake messages
"""
# variables with complex values
err_codes_to_names = {
(
9,
100,
):
'BAD_BASE64_DECODE'
,
(
9,
101,
):
'BAD_DECRYPT'
,
(
9,
102,
):
'BAD_END_LINE'
,
(
9,
103,
):
'BAD_IV_CHARS'
,
(
9,
104,
):
'BAD_PASSWORD_READ'
,
(
9,
105,
):
'NOT_DEK_INFO'
,
(
9,
106,
):
'NOT_ENCRYPTED'
,
(
9,
107,
):
'NOT_PROC_TYPE'
,
(
9,
108,
):
'NO_START_LINE'
,
(
9,
109,
):
'PROBLEMS_GETTING_PASSWORD'
,
(
9,
110,
):
'PUBLIC_KEY_NO_RSA'
,
(
9,
111,
):
'READ_KEY'
,
(
9,
112,
):
'SHORT_HEADER'
,
(
9,
113,
):
'UNSUPPORTED_CIPHER'
,
(
9,
114,
):
'UNSUPPORTED_ENCRYPTION'
,
(
9,
115,
):
'ERROR_CONVERTING_PRIVATE_KEY'
,
(
9,
116,
):
'BAD_MAGIC_NUMBER'
,
(
9,
117,
):
'BAD_VERSION_NUMBER'
,
(
9,
118,
):
'BIO_WRITE_FAILURE'
,
(
9,
119,
):
'EXPECTING_PRIVATE_KEY_BLOB'
,
(
9,
120,
):
'EXPECTING_PUBLIC_KEY_BLOB'
,
(
9,
121,
):
'INCONSISTENT_HEADER'
,
(
9,
122,
):
'KEYBLOB_HEADER_PARSE_ERROR'
,
(
9,
123,
):
'KEYBLOB_TOO_SHORT'
,
(
9,
124,
):
'PVK_DATA_TOO_SHORT'
,
(
9,
125,
):
'PVK_TOO_SHORT'
,
(
9,
126,
):
'UNSUPPORTED_KEY_COMPONENTS'
,
(
9,
127,
):
'CIPHER_IS_NULL'
,
(
11,
100,
):
'BAD_X509_FILETYPE'
,
(
11,
101,
):
'CERT_ALREADY_IN_HASH_TABLE'
,
(
11,
102,
):
'ERR_ASN1_LIB'
,
(
11,
103,
):
'LOADING_CERT_DIR'
,
(
11,
104,
):
'LOADING_DEFAULTS'
,
(
11,
105,
):
'NO_CERT_SET_FOR_US_TO_VERIFY'
,
(
11,
106,
):
'SHOULD_RETRY'
,
(
11,
107,
):
'UNABLE_TO_FIND_PARAMETERS_IN_CHAIN'
,
(
11,
108,
):
'UNABLE_TO_GET_CERTS_PUBLIC_KEY'
,
(
11,
109,
):
'UNKNOWN_NID'
,
(
11,
111,
):
'UNSUPPORTED_ALGORITHM'
,
(
11,
112,
):
'WRONG_LOOKUP_TYPE'
,
(
11,
113,
):
'INVALID_DIRECTORY'
,
(
11,
114,
):
'CANT_CHECK_DH_KEY'
,
(
11,
115,
):
'KEY_TYPE_MISMATCH'
,
(
11,
116,
):
'KEY_VALUES_MISMATCH'
,
(
11,
117,
):
'UNKNOWN_KEY_TYPE'
,
(
11,
118,
):
'BASE64_DECODE_ERROR'
,
(
11,
119,
):
'INVALID_FIELD_NAME'
,
(
11,
120,
):
'UNKNOWN_TRUST_ID'
,
(
11,
121,
):
'UNKNOWN_PURPOSE_ID'
,
(
11,
122,
):
'WRONG_TYPE'
,
(
11,
123,
):
'INVALID_TRUST'
,
(
11,
124,
):
'METHOD_NOT_SUPPORTED'
,
(
11,
125,
):
'PUBLIC_KEY_DECODE_ERROR'
,
(
11,
126,
):
'PUBLIC_KEY_ENCODE_ERROR'
,
(
20,
100,
):
'APP_DATA_IN_HANDSHAKE'
,
(
20,
101,
):
'BAD_ALERT_RECORD'
,
(
20,
102,
):
'BAD_AUTHENTICATION_TYPE'
,
(
20,
103,
):
'BAD_CHANGE_CIPHER_SPEC'
,
(
20,
104,
):
'BAD_CHECKSUM'
,
(
20,
105,
):
'BAD_HELLO_REQUEST'
,
(
20,
106,
):
'BAD_DATA_RETURNED_BY_CALLBACK'
,
(
20,
107,
):
'BAD_DECOMPRESSION'
,
(
20,
108,
):
'BAD_DH_G_LENGTH'
,
(
20,
109,
):
'BAD_DH_PUB_KEY_LENGTH'
,
(
20,
110,
):
'BAD_DH_P_LENGTH'
,
(
20,
111,
):
'BAD_DIGEST_LENGTH'
,
(
20,
112,
):
'BAD_DSA_SIGNATURE'
,
(
20,
113,
):
'BAD_MAC_DECODE'
,
(
20,
114,
):
'BAD_MESSAGE_TYPE'
,
(
20,
115,
):
'BAD_PACKET_LENGTH'
,
(
20,
116,
):
'BAD_PROTOCOL_VERSION_NUMBER'
,
(
20,
117,
):
'BAD_RESPONSE_ARGUMENT'
,
(
20,
118,
):
'BAD_RSA_DECRYPT'
,
(
20,
119,
):
'BAD_RSA_ENCRYPT'
,
(
20,
120,
):
'BAD_RSA_E_LENGTH'
,
(
20,
121,
):
'BAD_RSA_MODULUS_LENGTH'
,
(
20,
122,
):
'BAD_RSA_SIGNATURE'
,
(
20,
123,
):
'BAD_SIGNATURE'
,
(
20,
124,
):
'BAD_SSL_FILETYPE'
,
(
20,
125,
):
'BAD_SSL_SESSION_ID_LENGTH'
,
(
20,
126,
):
'BAD_STATE'
,
(
20,
127,
):
'BAD_WRITE_RETRY'
,
(
20,
128,
):
'BIO_NOT_SET'
,
(
20,
129,
):
'BLOCK_CIPHER_PAD_IS_WRONG'
,
(
20,
130,
):
'BN_LIB'
,
(
20,
131,
):
'CA_DN_LENGTH_MISMATCH'
,
(
20,
132,
):
'CA_DN_TOO_LONG'
,
(
20,
133,
):
'CCS_RECEIVED_EARLY'
,
(
20,
134,
):
'CERTIFICATE_VERIFY_FAILED'
,
(
20,
135,
):
'CERT_LENGTH_MISMATCH'
,
(
20,
136,
):
'CHALLENGE_IS_DIFFERENT'
,
(
20,
137,
):
'CIPHER_CODE_WRONG_LENGTH'
,
(
20,
138,
):
'CIPHER_OR_HASH_UNAVAILABLE'
,
(
20,
139,
):
'CIPHER_TABLE_SRC_ERROR'
,
(
20,
140,
):
'COMPRESSED_LENGTH_TOO_LONG'
,
(
20,
141,
):
'COMPRESSION_FAILURE'
,
(
20,
142,
):
'COMPRESSION_LIBRARY_ERROR'
,
(
20,
143,
):
'CONNECTION_ID_IS_DIFFERENT'
,
(
20,
144,
):
'CONNECTION_TYPE_NOT_SET'
,
(
20,
145,
):
'DATA_BETWEEN_CCS_AND_FINISHED'
,
(
20,
146,
):
'DATA_LENGTH_TOO_LONG'
,
(
20,
147,
):
'DECRYPTION_FAILED'
,
(
20,
148,
):
'DH_PUBLIC_VALUE_LENGTH_IS_WRONG'
,
(
20,
149,
):
'DIGEST_CHECK_FAILED'
,
(
20,
150,
):
'ENCRYPTED_LENGTH_TOO_LONG'
,
(
20,
151,
):
'ERROR_IN_RECEIVED_CIPHER_LIST'
,
(
20,
152,
):
'EXCESSIVE_MESSAGE_SIZE'
,
(
20,
153,
):
'EXTRA_DATA_IN_MESSAGE'
,
(
20,
154,
):
'GOT_A_FIN_BEFORE_A_CCS'
,
(
20,
155,
):
'HTTPS_PROXY_REQUEST'
,
(
20,
156,
):
'HTTP_REQUEST'
,
(
20,
157,
):
'TLS_INVALID_ECPOINTFORMAT_LIST'
,
(
20,
158,
):
'INVALID_CHALLENGE_LENGTH'
,
(
20,
159,
):
'LENGTH_MISMATCH'
,
(
20,
160,
):
'LENGTH_TOO_SHORT'
,
(
20,
161,
):
'LIBRARY_HAS_NO_CIPHERS'
,
(
20,
162,
):
'MISSING_DH_DSA_CERT'
,
(
20,
163,
):
'MISSING_DH_KEY'
,
(
20,
164,
):
'MISSING_DH_RSA_CERT'
,
(
20,
165,
):
'MISSING_DSA_SIGNING_CERT'
,
(
20,
166,
):
'MISSING_EXPORT_TMP_DH_KEY'
,
(
20,
167,
):
'MISSING_EXPORT_TMP_RSA_KEY'
,
(
20,
168,
):
'MISSING_RSA_CERTIFICATE'
,
(
20,
169,
):
'MISSING_RSA_ENCRYPTING_CERT'
,
(
20,
170,
):
'MISSING_RSA_SIGNING_CERT'
,
(
20,
171,
):
'MISSING_TMP_DH_KEY'
,
(
20,
172,
):
'MISSING_TMP_RSA_KEY'
,
(
20,
173,
):
'MISSING_TMP_RSA_PKEY'
,
(
20,
174,
):
'MISSING_VERIFY_MESSAGE'
,
(
20,
175,
):
'NON_SSLV2_INITIAL_PACKET'
,
(
20,
176,
):
'NO_CERTIFICATES_RETURNED'
,
(
20,
177,
):
'NO_CERTIFICATE_ASSIGNED'
,
(
20,
178,
):
'NO_CERTIFICATE_RETURNED'
,
(
20,
179,
):
'NO_CERTIFICATE_SET'
,
(
20,
180,
):
'NO_CERTIFICATE_SPECIFIED'
,
(
20,
181,
):
'NO_CIPHERS_AVAILABLE'
,
(
20,
182,
):
'NO_CIPHERS_PASSED'
,
(
20,
183,
):
'NO_CIPHERS_SPECIFIED'
,
(
20,
184,
):
'NO_CIPHER_LIST'
,
(
20,
185,
):
'NO_CIPHER_MATCH'
,
(
20,
186,
):
'NO_CLIENT_CERT_RECEIVED'
,
(
20,
187,
):
'NO_COMPRESSION_SPECIFIED'
,
(
20,
188,
):
'NO_METHOD_SPECIFIED'
,
(
20,
189,
):
'NO_PRIVATEKEY'
,
(
20,
190,
):
'NO_PRIVATE_KEY_ASSIGNED'
,
(
20,
191,
):
'NO_PROTOCOLS_AVAILABLE'
,
(
20,
192,
):
'NO_PUBLICKEY'
,
(
20,
193,
):
'NO_SHARED_CIPHER'
,
(
20,
194,
):
'NO_VERIFY_CALLBACK'
,
(
20,
195,
):
'NULL_SSL_CTX'
,
(
20,
196,
):
'NULL_SSL_METHOD_PASSED'
,
(
20,
197,
):
'OLD_SESSION_CIPHER_NOT_RETURNED'
,
(
20,
198,
):
'PACKET_LENGTH_TOO_LONG'
,
(
20,
199,
):
'PEER_DID_NOT_RETURN_A_CERTIFICATE'
,
(
20,
200,
):
'PEER_ERROR'
,
(
20,
201,
):
'PEER_ERROR_CERTIFICATE'
,
(
20,
202,
):
'PEER_ERROR_NO_CERTIFICATE'
,
(
20,
203,
):
'PEER_ERROR_NO_CIPHER'
,
(
20,
204,
):
'PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE'
,
(
20,
205,
):
'PRE_MAC_LENGTH_TOO_LONG'
,
(
20,
206,
):
'PROBLEMS_MAPPING_CIPHER_FUNCTIONS'
,
(
20,
207,
):
'PROTOCOL_IS_SHUTDOWN'
,
(
20,
208,
):
'PUBLIC_KEY_ENCRYPT_ERROR'
,
(
20,
209,
):
'PUBLIC_KEY_IS_NOT_RSA'
,
(
20,
210,
):
'PUBLIC_KEY_NOT_RSA'
,
(
20,
211,
):
'READ_BIO_NOT_SET'
,
(
20,
212,
):
'READ_WRONG_PACKET_TYPE'
,
(
20,
213,
):
'RECORD_LENGTH_MISMATCH'
,
(
20,
214,
):
'RECORD_TOO_LARGE'
,
(
20,
215,
):
'REQUIRED_CIPHER_MISSING'
,
(
20,
216,
):
'REUSE_CERT_LENGTH_NOT_ZERO'
,
(
20,
217,
):
'REUSE_CERT_TYPE_NOT_ZERO'
,
(
20,
218,
):
'REUSE_CIPHER_LIST_NOT_ZERO'
,
(
20,
219,
):
'SHORT_READ'
,
(
20,
220,
):
'SIGNATURE_FOR_NON_SIGNING_CERTIFICATE'
,
(
20,
221,
):
'SSL23_DOING_SESSION_ID_REUSE'
,
(
20,
222,
):
'SSL3_SESSION_ID_TOO_SHORT'
,
(
20,
223,
):
'PSK_IDENTITY_NOT_FOUND'
,
(
20,
224,
):
'PSK_NO_CLIENT_CB'
,
(
20,
225,
):
'PSK_NO_SERVER_CB'
,
(
20,
226,
):
'CLIENTHELLO_TLSEXT'
,
(
20,
227,
):
'PARSE_TLSEXT'
,
(
20,
228,
):
'SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION'
,
(
20,
229,
):
'SSL_HANDSHAKE_FAILURE'
,
(
20,
230,
):
'SSL_LIBRARY_HAS_NO_CIPHERS'
,
(
20,
231,
):
'SSL_SESSION_ID_IS_DIFFERENT'
,
(
20,
232,
):
'TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER'
,
(
20,
233,
):
'TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST'
,
(
20,
234,
):
'TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG'
,
(
20,
235,
):
'TRIED_TO_USE_UNSUPPORTED_CIPHER'
,
(
20,
236,
):
'UNABLE_TO_DECODE_DH_CERTS'
,
(
20,
237,
):
'UNABLE_TO_EXTRACT_PUBLIC_KEY'
,
(
20,
238,
):
'UNABLE_TO_FIND_DH_PARAMETERS'
,
(
20,
239,
):
'UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS'
,
(
20,
240,
):
'UNABLE_TO_FIND_SSL_METHOD'
,
(
20,
241,
):
'UNABLE_TO_LOAD_SSL2_MD5_ROUTINES'
,
(
20,
242,
):
'UNABLE_TO_LOAD_SSL3_MD5_ROUTINES'
,
(
20,
243,
):
'UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES'
,
(
20,
244,
):
'UNEXPECTED_MESSAGE'
,
(
20,
245,
):
'UNEXPECTED_RECORD'
,
(
20,
246,
):
'UNKNOWN_ALERT_TYPE'
,
(
20,
247,
):
'UNKNOWN_CERTIFICATE_TYPE'
,
(
20,
248,
):
'UNKNOWN_CIPHER_RETURNED'
,
(
20,
249,
):
'UNKNOWN_CIPHER_TYPE'
,
(
20,
250,
):
'UNKNOWN_KEY_EXCHANGE_TYPE'
,
(
20,
251,
):
'UNKNOWN_PKEY_TYPE'
,
(
20,
252,
):
'UNKNOWN_PROTOCOL'
,
(
20,
253,
):
'UNKNOWN_REMOTE_ERROR_TYPE'
,
(
20,
254,
):
'UNKNOWN_SSL_VERSION'
,
(
20,
255,
):
'UNKNOWN_STATE'
,
(
20,
256,
):
'UNSUPPORTED_CIPHER'
,
(
20,
257,
):
'UNSUPPORTED_COMPRESSION_ALGORITHM'
,
(
20,
258,
):
'UNSUPPORTED_PROTOCOL'
,
(
20,
259,
):
'UNSUPPORTED_SSL_VERSION'
,
(
20,
260,
):
'WRITE_BIO_NOT_SET'
,
(
20,
261,
):
'WRONG_CIPHER_RETURNED'
,
(
20,
262,
):
'WRONG_MESSAGE_TYPE'
,
(
20,
263,
):
'WRONG_NUMBER_OF_KEY_BITS'
,
(
20,
264,
):
'WRONG_SIGNATURE_LENGTH'
,
(
20,
265,
):
'WRONG_SIGNATURE_SIZE'
,
(
20,
266,
):
'WRONG_SSL_VERSION'
,
(
20,
267,
):
'WRONG_VERSION_NUMBER'
,
(
20,
268,
):
'X509_LIB'
,
(
20,
269,
):
'X509_VERIFICATION_SETUP_PROBLEMS'
,
(
20,
270,
):
'PATH_TOO_LONG'
,
(
20,
271,
):
'BAD_LENGTH'
,
(
20,
272,
):
'ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT'
,
(
20,
273,
):
'SSL_SESSION_ID_CONTEXT_TOO_LONG'
,
(
20,
274,
):
'LIBRARY_BUG'
,
(
20,
275,
):
'SERVERHELLO_TLSEXT'
,
(
20,
276,
):
'UNINITIALIZED'
,
(
20,
277,
):
'SESSION_ID_CONTEXT_UNINITIALIZED'
,
(
20,
278,
):
'INVALID_PURPOSE'
,
(
20,
279,
):
'INVALID_TRUST'
,
(
20,
280,
):
'INVALID_COMMAND'
,
(
20,
281,
):
'DECRYPTION_FAILED_OR_BAD_RECORD_MAC'
,
(
20,
282,
):
'ERROR_GENERATING_TMP_RSA_KEY'
,
(
20,
283,
):
'ILLEGAL_PADDING'
,
(
20,
284,
):
'KEY_ARG_TOO_LONG'
,
(
20,
285,
):
'KRB5'
,
(
20,
286,
):
'KRB5_C_CC_PRINC'
,
(
20,
287,
):
'KRB5_C_GET_CRED'
,
(
20,
288,
):
'KRB5_C_INIT'
,
(
20,
289,
):
'KRB5_C_MK_REQ'
,
(
20,
290,
):
'KRB5_S_BAD_TICKET'
,
(
20,
291,
):
'KRB5_S_INIT'
,
(
20,
292,
):
'KRB5_S_RD_REQ'
,
(
20,
293,
):
'KRB5_S_TKT_EXPIRED'
,
(
20,
294,
):
'KRB5_S_TKT_NYV'
,
(
20,
295,
):
'KRB5_S_TKT_SKEW'
,
(
20,
296,
):
'MESSAGE_TOO_LONG'
,
(
20,
297,
):
'ONLY_TLS_ALLOWED_IN_FIPS_MODE'
,
(
20,
298,
):
'RECORD_TOO_SMALL'
,
(
20,
299,
):
'SSL2_CONNECTION_ID_TOO_LONG'
,
(
20,
300,
):
'SSL3_SESSION_ID_TOO_LONG'
,
(
20,
301,
):
'SSL_SESSION_ID_CALLBACK_FAILED'
,
(
20,
302,
):
'SSL_SESSION_ID_CONFLICT'
,
(
20,
303,
):
'SSL_SESSION_ID_HAS_BAD_LENGTH'
,
(
20,
304,
):
'BAD_ECC_CERT'
,
(
20,
305,
):
'BAD_ECDSA_SIGNATURE'
,
(
20,
306,
):
'BAD_ECPOINT'
,
(
20,
307,
):
'COMPRESSION_ID_NOT_WITHIN_PRIVATE_RANGE'
,
(
20,
308,
):
'COOKIE_MISMATCH'
,
(
20,
309,
):
'DUPLICATE_COMPRESSION_ID'
,
(
20,
310,
):
'ECGROUP_TOO_LARGE_FOR_CIPHER'
,
(
20,
311,
):
'MISSING_TMP_ECDH_KEY'
,
(
20,
312,
):
'READ_TIMEOUT_EXPIRED'
,
(
20,
313,
):
'UNABLE_TO_DECODE_ECDH_CERTS'
,
(
20,
314,
):
'UNABLE_TO_FIND_ECDH_PARAMETERS'
,
(
20,
315,
):
'UNSUPPORTED_ELLIPTIC_CURVE'
,
(
20,
316,
):
'BAD_PSK_IDENTITY_HINT_LENGTH'
,
(
20,
317,
):
'ECC_CERT_NOT_FOR_KEY_AGREEMENT'
,
(
20,
318,
):
'ECC_CERT_NOT_FOR_SIGNING'
,
(
20,
319,
):
'SSL3_EXT_INVALID_SERVERNAME'
,
(
20,
320,
):
'SSL3_EXT_INVALID_SERVERNAME_TYPE'
,
(
20,
321,
):
'SSL3_EXT_INVALID_ECPOINTFORMAT'
,
(
20,
322,
):
'ECC_CERT_SHOULD_HAVE_RSA_SIGNATURE'
,
(
20,
323,
):
'ECC_CERT_SHOULD_HAVE_SHA1_SIGNATURE'
,
(
20,
324,
):
'NO_REQUIRED_DIGEST'
,
(
20,
325,
):
'INVALID_TICKET_KEYS_LENGTH'
,
(
20,
326,
):
'UNSUPPORTED_DIGEST_TYPE'
,
(
20,
327,
):
'OPAQUE_PRF_INPUT_TOO_LONG'
,
(
20,
328,
):
'INVALID_STATUS_RESPONSE'
,
(
20,
329,
):
'UNSUPPORTED_STATUS_TYPE'
,
(
20,
330,
):
'NO_GOST_CERTIFICATE_SENT_BY_PEER'
,
(
20,
331,
):
'NO_CLIENT_CERT_METHOD'
,
(
20,
332,
):
'BAD_HANDSHAKE_LENGTH'
,
(
20,
333,
):
'BAD_MAC_LENGTH'
,
(
20,
334,
):
'DTLS_MESSAGE_TOO_BIG'
,
(
20,
335,
):
'RENEGOTIATE_EXT_TOO_LONG'
,
(
20,
336,
):
'RENEGOTIATION_ENCODING_ERR'
,
(
20,
337,
):
'RENEGOTIATION_MISMATCH'
,
(
20,
338,
):
'UNSAFE_LEGACY_RENEGOTIATION_DISABLED'
,
(
20,
339,
):
'NO_RENEGOTIATION'
,
(
20,
340,
):
'INCONSISTENT_COMPRESSION'
,
(
20,
341,
):
'INVALID_COMPRESSION_ALGORITHM'
,
(
20,
342,
):
'REQUIRED_COMPRESSSION_ALGORITHM_MISSING'
,
(
20,
343,
):
'COMPRESSION_DISABLED'
,
(
20,
344,
):
'OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED'
,
(
20,
345,
):
'SCSV_RECEIVED_WHEN_RENEGOTIATING'
,
(
20,
1010,
):
'SSLV3_ALERT_UNEXPECTED_MESSAGE'
,
(
20,
1020,
):
'SSLV3_ALERT_BAD_RECORD_MAC'
,
(
20,
1021,
):
'TLSV1_ALERT_DECRYPTION_FAILED'
,
(
20,
1022,
):
'TLSV1_ALERT_RECORD_OVERFLOW'
,
(
20,
1030,
):
'SSLV3_ALERT_DECOMPRESSION_FAILURE'
,
(
20,
1040,
):
'SSLV3_ALERT_HANDSHAKE_FAILURE'
,
(
20,
1041,
):
'SSLV3_ALERT_NO_CERTIFICATE'
,
(
20,
1042,
):
'SSLV3_ALERT_BAD_CERTIFICATE'
,
(
20,
1043,
):
'SSLV3_ALERT_UNSUPPORTED_CERTIFICATE'
,
(
20,
1044,
):
'SSLV3_ALERT_CERTIFICATE_REVOKED'
,
(
20,
1045,
):
'SSLV3_ALERT_CERTIFICATE_EXPIRED'
,
(
20,
1046,
):
'SSLV3_ALERT_CERTIFICATE_UNKNOWN'
,
(
20,
1047,
):
'SSLV3_ALERT_ILLEGAL_PARAMETER'
,
(
20,
1048,
):
'TLSV1_ALERT_UNKNOWN_CA'
,
(
20,
1049,
):
'TLSV1_ALERT_ACCESS_DENIED'
,
(
20,
1050,
):
'TLSV1_ALERT_DECODE_ERROR'
,
(
20,
1051,
):
'TLSV1_ALERT_DECRYPT_ERROR'
,
(
20,
1060,
):
'TLSV1_ALERT_EXPORT_RESTRICTION'
,
(
20,
1070,
):
'TLSV1_ALERT_PROTOCOL_VERSION'
,
(
20,
1071,
):
'TLSV1_ALERT_INSUFFICIENT_SECURITY'
,
(
20,
1080,
):
'TLSV1_ALERT_INTERNAL_ERROR'
,
(
20,
1090,
):
'TLSV1_ALERT_USER_CANCELLED'
,
(
20,
1100,
):
'TLSV1_ALERT_NO_RENEGOTIATION'
,
(
20,
1110,
):
'TLSV1_UNSUPPORTED_EXTENSION'
,
(
20,
1111,
):
'TLSV1_CERTIFICATE_UNOBTAINABLE'
,
(
20,
1112,
):
'TLSV1_UNRECOGNIZED_NAME'
,
(
20,
1113,
):
'TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE'
,
(
20,
1114,
):
'TLSV1_BAD_CERTIFICATE_HASH_VALUE'
,
}
err_names_to_codes = {
'APP_DATA_IN_HANDSHAKE': (
20,
100,
),
'ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT': (
20,
272,
),
'BAD_ALERT_RECORD': (
20,
101,
),
'BAD_AUTHENTICATION_TYPE': (
20,
102,
),
'BAD_BASE64_DECODE': (
9,
100,
),
'BAD_CHANGE_CIPHER_SPEC': (
20,
103,
),
'BAD_CHECKSUM': (
20,
104,
),
'BAD_DATA_RETURNED_BY_CALLBACK': (
20,
106,
),
'BAD_DECOMPRESSION': (
20,
107,
),
'BAD_DECRYPT': (
9,
101,
),
'BAD_DH_G_LENGTH': (
20,
108,
),
'BAD_DH_PUB_KEY_LENGTH': (
20,
109,
),
'BAD_DH_P_LENGTH': (
20,
110,
),
'BAD_DIGEST_LENGTH': (
20,
111,
),
'BAD_DSA_SIGNATURE': (
20,
112,
),
'BAD_ECC_CERT': (
20,
304,
),
'BAD_ECDSA_SIGNATURE': (
20,
305,
),
'BAD_ECPOINT': (
20,
306,
),
'BAD_END_LINE': (
9,
102,
),
'BAD_HANDSHAKE_LENGTH': (
20,
332,
),
'BAD_HELLO_REQUEST': (
20,
105,
),
'BAD_IV_CHARS': (
9,
103,
),
'BAD_LENGTH': (
20,
271,
),
'BAD_MAC_DECODE': (
20,
113,
),
'BAD_MAC_LENGTH': (
20,
333,
),
'BAD_MAGIC_NUMBER': (
9,
116,
),
'BAD_MESSAGE_TYPE': (
20,
114,
),
'BAD_PACKET_LENGTH': (
20,
115,
),
'BAD_PASSWORD_READ': (
9,
104,
),
'BAD_PROTOCOL_VERSION_NUMBER': (
20,
116,
),
'BAD_PSK_IDENTITY_HINT_LENGTH': (
20,
316,
),
'BAD_RESPONSE_ARGUMENT': (
20,
117,
),
'BAD_RSA_DECRYPT': (
20,
118,
),
'BAD_RSA_ENCRYPT': (
20,
119,
),
'BAD_RSA_E_LENGTH': (
20,
120,
),
'BAD_RSA_MODULUS_LENGTH': (
20,
121,
),
'BAD_RSA_SIGNATURE': (
20,
122,
),
'BAD_SIGNATURE': (
20,
123,
),
'BAD_SSL_FILETYPE': (
20,
124,
),
'BAD_SSL_SESSION_ID_LENGTH': (
20,
125,
),
'BAD_STATE': (
20,
126,
),
'BAD_VERSION_NUMBER': (
9,
117,
),
'BAD_WRITE_RETRY': (
20,
127,
),
'BAD_X509_FILETYPE': (
11,
100,
),
'BASE64_DECODE_ERROR': (
11,
118,
),
'BIO_NOT_SET': (
20,
128,
),
'BIO_WRITE_FAILURE': (
9,
118,
),
'BLOCK_CIPHER_PAD_IS_WRONG': (
20,
129,
),
'BN_LIB': (
20,
130,
),
'CANT_CHECK_DH_KEY': (
11,
114,
),
'CA_DN_LENGTH_MISMATCH': (
20,
131,
),
'CA_DN_TOO_LONG': (
20,
132,
),
'CCS_RECEIVED_EARLY': (
20,
133,
),
'CERTIFICATE_VERIFY_FAILED': (
20,
134,
),
'CERT_ALREADY_IN_HASH_TABLE': (
11,
101,
),
'CERT_LENGTH_MISMATCH': (
20,
135,
),
'CHALLENGE_IS_DIFFERENT': (
20,
136,
),
'CIPHER_CODE_WRONG_LENGTH': (
20,
137,
),
'CIPHER_IS_NULL': (
9,
127,
),
'CIPHER_OR_HASH_UNAVAILABLE': (
20,
138,
),
'CIPHER_TABLE_SRC_ERROR': (
20,
139,
),
'CLIENTHELLO_TLSEXT': (
20,
226,
),
'COMPRESSED_LENGTH_TOO_LONG': (
20,
140,
),
'COMPRESSION_DISABLED': (
20,
343,
),
'COMPRESSION_FAILURE': (
20,
141,
),
'COMPRESSION_ID_NOT_WITHIN_PRIVATE_RANGE': (
20,
307,
),
'COMPRESSION_LIBRARY_ERROR': (
20,
142,
),
'CONNECTION_ID_IS_DIFFERENT': (
20,
143,
),
'CONNECTION_TYPE_NOT_SET': (
20,
144,
),
'COOKIE_MISMATCH': (
20,
308,
),
'DATA_BETWEEN_CCS_AND_FINISHED': (
20,
145,
),
'DATA_LENGTH_TOO_LONG': (
20,
146,
),
'DECRYPTION_FAILED': (
20,
147,
),
'DECRYPTION_FAILED_OR_BAD_RECORD_MAC': (
20,
281,
),
'DH_PUBLIC_VALUE_LENGTH_IS_WRONG': (
20,
148,
),
'DIGEST_CHECK_FAILED': (
20,
149,
),
'DTLS_MESSAGE_TOO_BIG': (
20,
334,
),
'DUPLICATE_COMPRESSION_ID': (
20,
309,
),
'ECC_CERT_NOT_FOR_KEY_AGREEMENT': (
20,
317,
),
'ECC_CERT_NOT_FOR_SIGNING': (
20,
318,
),
'ECC_CERT_SHOULD_HAVE_RSA_SIGNATURE': (
20,
322,
),
'ECC_CERT_SHOULD_HAVE_SHA1_SIGNATURE': (
20,
323,
),
'ECGROUP_TOO_LARGE_FOR_CIPHER': (
20,
310,
),
'ENCRYPTED_LENGTH_TOO_LONG': (
20,
150,
),
'ERROR_CONVERTING_PRIVATE_KEY': (
9,
115,
),
'ERROR_GENERATING_TMP_RSA_KEY': (
20,
282,
),
'ERROR_IN_RECEIVED_CIPHER_LIST': (
20,
151,
),
'ERR_ASN1_LIB': (
11,
102,
),
'EXCESSIVE_MESSAGE_SIZE': (
20,
152,
),
'EXPECTING_PRIVATE_KEY_BLOB': (
9,
119,
),
'EXPECTING_PUBLIC_KEY_BLOB': (
9,
120,
),
'EXTRA_DATA_IN_MESSAGE': (
20,
153,
),
'GOT_A_FIN_BEFORE_A_CCS': (
20,
154,
),
'HTTPS_PROXY_REQUEST': (
20,
155,
),
'HTTP_REQUEST': (
20,
156,
),
'ILLEGAL_PADDING': (
20,
283,
),
'INCONSISTENT_COMPRESSION': (
20,
340,
),
'INCONSISTENT_HEADER': (
9,
121,
),
'INVALID_CHALLENGE_LENGTH': (
20,
158,
),
'INVALID_COMMAND': (
20,
280,
),
'INVALID_COMPRESSION_ALGORITHM': (
20,
341,
),
'INVALID_DIRECTORY': (
11,
113,
),
'INVALID_FIELD_NAME': (
11,
119,
),
'INVALID_PURPOSE': (
20,
278,
),
'INVALID_STATUS_RESPONSE': (
20,
328,
),
'INVALID_TICKET_KEYS_LENGTH': (
20,
325,
),
'INVALID_TRUST': (
11,
123,
),
'KEYBLOB_HEADER_PARSE_ERROR': (
9,
122,
),
'KEYBLOB_TOO_SHORT': (
9,
123,
),
'KEY_ARG_TOO_LONG': (
20,
284,
),
'KEY_TYPE_MISMATCH': (
11,
115,
),
'KEY_VALUES_MISMATCH': (
11,
116,
),
'KRB5': (
20,
285,
),
'KRB5_C_CC_PRINC': (
20,
286,
),
'KRB5_C_GET_CRED': (
20,
287,
),
'KRB5_C_INIT': (
20,
288,
),
'KRB5_C_MK_REQ': (
20,
289,
),
'KRB5_S_BAD_TICKET': (
20,
290,
),
'KRB5_S_INIT': (
20,
291,
),
'KRB5_S_RD_REQ': (
20,
292,
),
'KRB5_S_TKT_EXPIRED': (
20,
293,
),
'KRB5_S_TKT_NYV': (
20,
294,
),
'KRB5_S_TKT_SKEW': (
20,
295,
),
'LENGTH_MISMATCH': (
20,
159,
),
'LENGTH_TOO_SHORT': (
20,
160,
),
'LIBRARY_BUG': (
20,
274,
),
'LIBRARY_HAS_NO_CIPHERS': (
20,
161,
),
'LOADING_CERT_DIR': (
11,
103,
),
'LOADING_DEFAULTS': (
11,
104,
),
'MESSAGE_TOO_LONG': (
20,
296,
),
'METHOD_NOT_SUPPORTED': (
11,
124,
),
'MISSING_DH_DSA_CERT': (
20,
162,
),
'MISSING_DH_KEY': (
20,
163,
),
'MISSING_DH_RSA_CERT': (
20,
164,
),
'MISSING_DSA_SIGNING_CERT': (
20,
165,
),
'MISSING_EXPORT_TMP_DH_KEY': (
20,
166,
),
'MISSING_EXPORT_TMP_RSA_KEY': (
20,
167,
),
'MISSING_RSA_CERTIFICATE': (
20,
168,
),
'MISSING_RSA_ENCRYPTING_CERT': (
20,
169,
),
'MISSING_RSA_SIGNING_CERT': (
20,
170,
),
'MISSING_TMP_DH_KEY': (
20,
171,
),
'MISSING_TMP_ECDH_KEY': (
20,
311,
),
'MISSING_TMP_RSA_KEY': (
20,
172,
),
'MISSING_TMP_RSA_PKEY': (
20,
173,
),
'MISSING_VERIFY_MESSAGE': (
20,
174,
),
'NON_SSLV2_INITIAL_PACKET': (
20,
175,
),
'NOT_DEK_INFO': (
9,
105,
),
'NOT_ENCRYPTED': (
9,
106,
),
'NOT_PROC_TYPE': (
9,
107,
),
'NO_CERTIFICATES_RETURNED': (
20,
176,
),
'NO_CERTIFICATE_ASSIGNED': (
20,
177,
),
'NO_CERTIFICATE_RETURNED': (
20,
178,
),
'NO_CERTIFICATE_SET': (
20,
179,
),
'NO_CERTIFICATE_SPECIFIED': (
20,
180,
),
'NO_CERT_SET_FOR_US_TO_VERIFY': (
11,
105,
),
'NO_CIPHERS_AVAILABLE': (
20,
181,
),
'NO_CIPHERS_PASSED': (
20,
182,
),
'NO_CIPHERS_SPECIFIED': (
20,
183,
),
'NO_CIPHER_LIST': (
20,
184,
),
'NO_CIPHER_MATCH': (
20,
185,
),
'NO_CLIENT_CERT_METHOD': (
20,
331,
),
'NO_CLIENT_CERT_RECEIVED': (
20,
186,
),
'NO_COMPRESSION_SPECIFIED': (
20,
187,
),
'NO_GOST_CERTIFICATE_SENT_BY_PEER': (
20,
330,
),
'NO_METHOD_SPECIFIED': (
20,
188,
),
'NO_PRIVATEKEY': (
20,
189,
),
'NO_PRIVATE_KEY_ASSIGNED': (
20,
190,
),
'NO_PROTOCOLS_AVAILABLE': (
20,
191,
),
'NO_PUBLICKEY': (
20,
192,
),
'NO_RENEGOTIATION': (
20,
339,
),
'NO_REQUIRED_DIGEST': (
20,
324,
),
'NO_SHARED_CIPHER': (
20,
193,
),
'NO_START_LINE': (
9,
108,
),
'NO_VERIFY_CALLBACK': (
20,
194,
),
'NULL_SSL_CTX': (
20,
195,
),
'NULL_SSL_METHOD_PASSED': (
20,
196,
),
'OLD_SESSION_CIPHER_NOT_RETURNED': (
20,
197,
),
'OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED': (
20,
344,
),
'ONLY_TLS_ALLOWED_IN_FIPS_MODE': (
20,
297,
),
'OPAQUE_PRF_INPUT_TOO_LONG': (
20,
327,
),
'PACKET_LENGTH_TOO_LONG': (
20,
198,
),
'PARSE_TLSEXT': (
20,
227,
),
'PATH_TOO_LONG': (
20,
270,
),
'PEER_DID_NOT_RETURN_A_CERTIFICATE': (
20,
199,
),
'PEER_ERROR': (
20,
200,
),
'PEER_ERROR_CERTIFICATE': (
20,
201,
),
'PEER_ERROR_NO_CERTIFICATE': (
20,
202,
),
'PEER_ERROR_NO_CIPHER': (
20,
203,
),
'PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE': (
20,
204,
),
'PRE_MAC_LENGTH_TOO_LONG': (
20,
205,
),
'PROBLEMS_GETTING_PASSWORD': (
9,
109,
),
'PROBLEMS_MAPPING_CIPHER_FUNCTIONS': (
20,
206,
),
'PROTOCOL_IS_SHUTDOWN': (
20,
207,
),
'PSK_IDENTITY_NOT_FOUND': (
20,
223,
),
'PSK_NO_CLIENT_CB': (
20,
224,
),
'PSK_NO_SERVER_CB': (
20,
225,
),
'PUBLIC_KEY_DECODE_ERROR': (
11,
125,
),
'PUBLIC_KEY_ENCODE_ERROR': (
11,
126,
),
'PUBLIC_KEY_ENCRYPT_ERROR': (
20,
208,
),
'PUBLIC_KEY_IS_NOT_RSA': (
20,
209,
),
'PUBLIC_KEY_NOT_RSA': (
20,
210,
),
'PUBLIC_KEY_NO_RSA': (
9,
110,
),
'PVK_DATA_TOO_SHORT': (
9,
124,
),
'PVK_TOO_SHORT': (
9,
125,
),
'READ_BIO_NOT_SET': (
20,
211,
),
'READ_KEY': (
9,
111,
),
'READ_TIMEOUT_EXPIRED': (
20,
312,
),
'READ_WRONG_PACKET_TYPE': (
20,
212,
),
'RECORD_LENGTH_MISMATCH': (
20,
213,
),
'RECORD_TOO_LARGE': (
20,
214,
),
'RECORD_TOO_SMALL': (
20,
298,
),
'RENEGOTIATE_EXT_TOO_LONG': (
20,
335,
),
'RENEGOTIATION_ENCODING_ERR': (
20,
336,
),
'RENEGOTIATION_MISMATCH': (
20,
337,
),
'REQUIRED_CIPHER_MISSING': (
20,
215,
),
'REQUIRED_COMPRESSSION_ALGORITHM_MISSING': (
20,
342,
),
'REUSE_CERT_LENGTH_NOT_ZERO': (
20,
216,
),
'REUSE_CERT_TYPE_NOT_ZERO': (
20,
217,
),
'REUSE_CIPHER_LIST_NOT_ZERO': (
20,
218,
),
'SCSV_RECEIVED_WHEN_RENEGOTIATING': (
20,
345,
),
'SERVERHELLO_TLSEXT': (
20,
275,
),
'SESSION_ID_CONTEXT_UNINITIALIZED': (
20,
277,
),
'SHORT_HEADER': (
9,
112,
),
'SHORT_READ': (
20,
219,
),
'SHOULD_RETRY': (
11,
106,
),
'SIGNATURE_FOR_NON_SIGNING_CERTIFICATE': (
20,
220,
),
'SSL23_DOING_SESSION_ID_REUSE': (
20,
221,
),
'SSL2_CONNECTION_ID_TOO_LONG': (
20,
299,
),
'SSL3_EXT_INVALID_ECPOINTFORMAT': (
20,
321,
),
'SSL3_EXT_INVALID_SERVERNAME': (
20,
319,
),
'SSL3_EXT_INVALID_SERVERNAME_TYPE': (
20,
320,
),
'SSL3_SESSION_ID_TOO_LONG': (
20,
300,
),
'SSL3_SESSION_ID_TOO_SHORT': (
20,
222,
),
'SSLV3_ALERT_BAD_CERTIFICATE': (
20,
1042,
),
'SSLV3_ALERT_BAD_RECORD_MAC': (
20,
1020,
),
'SSLV3_ALERT_CERTIFICATE_EXPIRED': (
20,
1045,
),
'SSLV3_ALERT_CERTIFICATE_REVOKED': (
20,
1044,
),
'SSLV3_ALERT_CERTIFICATE_UNKNOWN': (
20,
1046,
),
'SSLV3_ALERT_DECOMPRESSION_FAILURE': (
20,
1030,
),
'SSLV3_ALERT_HANDSHAKE_FAILURE': (
20,
1040,
),
'SSLV3_ALERT_ILLEGAL_PARAMETER': (
20,
1047,
),
'SSLV3_ALERT_NO_CERTIFICATE': (
20,
1041,
),
'SSLV3_ALERT_UNEXPECTED_MESSAGE': (
20,
1010,
),
'SSLV3_ALERT_UNSUPPORTED_CERTIFICATE': (
20,
1043,
),
'SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION': (
20,
228,
),
'SSL_HANDSHAKE_FAILURE': (
20,
229,
),
'SSL_LIBRARY_HAS_NO_CIPHERS': (
20,
230,
),
'SSL_SESSION_ID_CALLBACK_FAILED': (
20,
301,
),
'SSL_SESSION_ID_CONFLICT': (
20,
302,
),
'SSL_SESSION_ID_CONTEXT_TOO_LONG': (
20,
273,
),
'SSL_SESSION_ID_HAS_BAD_LENGTH': (
20,
303,
),
'SSL_SESSION_ID_IS_DIFFERENT': (
20,
231,
),
'TLSV1_ALERT_ACCESS_DENIED': (
20,
1049,
),
'TLSV1_ALERT_DECODE_ERROR': (
20,
1050,
),
'TLSV1_ALERT_DECRYPTION_FAILED': (
20,
1021,
),
'TLSV1_ALERT_DECRYPT_ERROR': (
20,
1051,
),
'TLSV1_ALERT_EXPORT_RESTRICTION': (
20,
1060,
),
'TLSV1_ALERT_INSUFFICIENT_SECURITY': (
20,
1071,
),
'TLSV1_ALERT_INTERNAL_ERROR': (
20,
1080,
),
'TLSV1_ALERT_NO_RENEGOTIATION': (
20,
1100,
),
'TLSV1_ALERT_PROTOCOL_VERSION': (
20,
1070,
),
'TLSV1_ALERT_RECORD_OVERFLOW': (
20,
1022,
),
'TLSV1_ALERT_UNKNOWN_CA': (
20,
1048,
),
'TLSV1_ALERT_USER_CANCELLED': (
20,
1090,
),
'TLSV1_BAD_CERTIFICATE_HASH_VALUE': (
20,
1114,
),
'TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE': (
20,
1113,
),
'TLSV1_CERTIFICATE_UNOBTAINABLE': (
20,
1111,
),
'TLSV1_UNRECOGNIZED_NAME': (
20,
1112,
),
'TLSV1_UNSUPPORTED_EXTENSION': (
20,
1110,
),
'TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER': (
20,
232,
),
'TLS_INVALID_ECPOINTFORMAT_LIST': (
20,
157,
),
'TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST': (
20,
233,
),
'TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG': (
20,
234,
),
'TRIED_TO_USE_UNSUPPORTED_CIPHER': (
20,
235,
),
'UNABLE_TO_DECODE_DH_CERTS': (
20,
236,
),
'UNABLE_TO_DECODE_ECDH_CERTS': (
20,
313,
),
'UNABLE_TO_EXTRACT_PUBLIC_KEY': (
20,
237,
),
'UNABLE_TO_FIND_DH_PARAMETERS': (
20,
238,
),
'UNABLE_TO_FIND_ECDH_PARAMETERS': (
20,
314,
),
'UNABLE_TO_FIND_PARAMETERS_IN_CHAIN': (
11,
107,
),
'UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS': (
20,
239,
),
'UNABLE_TO_FIND_SSL_METHOD': (
20,
240,
),
'UNABLE_TO_GET_CERTS_PUBLIC_KEY': (
11,
108,
),
'UNABLE_TO_LOAD_SSL2_MD5_ROUTINES': (
20,
241,
),
'UNABLE_TO_LOAD_SSL3_MD5_ROUTINES': (
20,
242,
),
'UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES': (
20,
243,
),
'UNEXPECTED_MESSAGE': (
20,
244,
),
'UNEXPECTED_RECORD': (
20,
245,
),
'UNINITIALIZED': (
20,
276,
),
'UNKNOWN_ALERT_TYPE': (
20,
246,
),
'UNKNOWN_CERTIFICATE_TYPE': (
20,
247,
),
'UNKNOWN_CIPHER_RETURNED': (
20,
248,
),
'UNKNOWN_CIPHER_TYPE': (
20,
249,
),
'UNKNOWN_KEY_EXCHANGE_TYPE': (
20,
250,
),
'UNKNOWN_KEY_TYPE': (
11,
117,
),
'UNKNOWN_NID': (
11,
109,
),
'UNKNOWN_PKEY_TYPE': (
20,
251,
),
'UNKNOWN_PROTOCOL': (
20,
252,
),
'UNKNOWN_PURPOSE_ID': (
11,
121,
),
'UNKNOWN_REMOTE_ERROR_TYPE': (
20,
253,
),
'UNKNOWN_SSL_VERSION': (
20,
254,
),
'UNKNOWN_STATE': (
20,
255,
),
'UNKNOWN_TRUST_ID': (
11,
120,
),
'UNSAFE_LEGACY_RENEGOTIATION_DISABLED': (
20,
338,
),
'UNSUPPORTED_ALGORITHM': (
11,
111,
),
'UNSUPPORTED_CIPHER': (
20,
256,
),
'UNSUPPORTED_COMPRESSION_ALGORITHM': (
20,
257,
),
'UNSUPPORTED_DIGEST_TYPE': (
20,
326,
),
'UNSUPPORTED_ELLIPTIC_CURVE': (
20,
315,
),
'UNSUPPORTED_ENCRYPTION': (
9,
114,
),
'UNSUPPORTED_KEY_COMPONENTS': (
9,
126,
),
'UNSUPPORTED_PROTOCOL': (
20,
258,
),
'UNSUPPORTED_SSL_VERSION': (
20,
259,
),
'UNSUPPORTED_STATUS_TYPE': (
20,
329,
),
'WRITE_BIO_NOT_SET': (
20,
260,
),
'WRONG_CIPHER_RETURNED': (
20,
261,
),
'WRONG_LOOKUP_TYPE': (
11,
112,
),
'WRONG_MESSAGE_TYPE': (
20,
262,
),
'WRONG_NUMBER_OF_KEY_BITS': (
20,
263,
),
'WRONG_SIGNATURE_LENGTH': (
20,
264,
),
'WRONG_SIGNATURE_SIZE': (
20,
265,
),
'WRONG_SSL_VERSION': (
20,
266,
),
'WRONG_TYPE': (
11,
122,
),
'WRONG_VERSION_NUMBER': (
20,
267,
),
'X509_LIB': (
20,
268,
),
'X509_VERIFICATION_SETUP_PROBLEMS': (
20,
269,
),
}
lib_codes_to_names = {
9: 'PEM',
11: 'X509',
20: 'SSL',
}
OPENSSL_VERSION_INFO = (
1,
0,
1,
9,
15,
)
_OPENSSL_API_VERSION = (
1,
0,
1,
9,
15,
)
__loader__ = None # (!) real value is ''
__spec__ = None # (!) real value is ''
| gpl-2.0 |
Epix37/Hearthstone-Deck-Tracker | Hearthstone Deck Tracker/Enums/DeckLayout.cs | 243 | namespace Hearthstone_Deck_Tracker.Enums
{
public enum DeckLayout
{
[LocDescription("Enum_DeckLayout_Layout1")]
Layout1,
[LocDescription("Enum_DeckLayout_Layout2")]
Layout2,
[LocDescription("Enum_DeckLayout_Legacy")]
Legacy
}
}
| gpl-2.0 |
nologic/nabs | client/trunk/shared/libraries/je-3.2.74/test/com/sleepycat/je/RunRecoveryFailureTest.java | 4948 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002,2008 Oracle. All rights reserved.
*
* $Id: RunRecoveryFailureTest.java,v 1.34.2.4 2008/01/07 15:14:25 cwl Exp $
*/
package com.sleepycat.je;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import junit.framework.TestCase;
import com.sleepycat.je.DbInternal;
import com.sleepycat.je.config.EnvironmentParams;
import com.sleepycat.je.log.FileManager;
import com.sleepycat.je.util.TestUtils;
public class RunRecoveryFailureTest extends TestCase {
private Environment env;
private File envHome;
public RunRecoveryFailureTest() {
envHome = new File(System.getProperty(TestUtils.DEST_DIR));
}
public void setUp()
throws Exception {
TestUtils.removeLogFiles("Setup", envHome, false);
openEnv();
}
public void tearDown()
throws Exception {
/*
* Close down environments in case the unit test failed so that the log
* files can be removed.
*/
try {
if (env != null) {
env.close();
env = null;
}
} catch (RunRecoveryException e) {
/* ok, the test hosed it. */
return;
} catch (DatabaseException e) {
/* ok, the test closed it */
}
TestUtils.removeLogFiles("TearDown", envHome, false);
}
private void openEnv()
throws DatabaseException {
EnvironmentConfig envConfig = TestUtils.initEnvConfig();
envConfig.setTransactional(true);
/*
* Run with tiny log buffers, so we can go to disk more (and see the
* checksum errors)
*/
DbInternal.disableParameterValidation(envConfig);
envConfig.setConfigParam
(EnvironmentParams.NUM_LOG_BUFFERS.getName(), "2");
envConfig.setConfigParam
(EnvironmentParams.LOG_MEM_SIZE.getName(),
EnvironmentParams.LOG_MEM_SIZE_MIN_STRING);
envConfig.setConfigParam
(EnvironmentParams.LOG_FILE_MAX.getName(), "1024");
envConfig.setConfigParam
(EnvironmentParams.JE_LOGGING_LEVEL.getName(), "CONFIG");
envConfig.setAllowCreate(true);
env = new Environment(envHome, envConfig);
}
/*
* Corrupt an environment while open, make sure we get a
* RunRecoveryException.
*/
public void testInvalidateEnvMidStream()
throws Throwable {
try {
/* Make a new db in this env and flush the file. */
Transaction txn =
env.beginTransaction(null, TransactionConfig.DEFAULT);
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setTransactional(true);
dbConfig.setAllowCreate(true);
Database db = env.openDatabase(txn, "foo", dbConfig);
DatabaseEntry key = new DatabaseEntry(new byte[1000]);
DatabaseEntry data = new DatabaseEntry(new byte[1000]);
for (int i = 0; i < 100; i += 1) {
db.put(txn, key, data);
}
env.getEnvironmentImpl().getLogManager().flush();
env.getEnvironmentImpl().getFileManager().clear();
/*
* Corrupt the file, then abort the txn in order to force it to
* re-read. Should get a checksum error, which should invalidate
* the environment.
*/
long currentFile = DbInternal.envGetEnvironmentImpl(env)
.getFileManager()
.getCurrentFileNum();
for (int fileNum = 0; fileNum <= currentFile; fileNum += 1) {
File file = new File
(envHome, "0000000" + fileNum + FileManager.JE_SUFFIX);
RandomAccessFile starterFile =
new RandomAccessFile(file, "rw");
FileChannel channel = starterFile.getChannel();
long fileSize = channel.size();
if (fileSize > FileManager.firstLogEntryOffset()) {
ByteBuffer junkBuffer = ByteBuffer.allocate
((int) fileSize - FileManager.firstLogEntryOffset());
int written = channel.write
(junkBuffer, FileManager.firstLogEntryOffset());
assertTrue(written > 0);
starterFile.close();
}
}
try {
txn.abort();
fail("Should see a run recovery exception");
} catch (RunRecoveryException e) {
}
try {
env.getDatabaseNames();
fail("Should see a run recovery exception again");
} catch (RunRecoveryException e) {
}
} catch (Throwable t) {
t.printStackTrace();
throw t;
}
}
}
| gpl-2.0 |
czurnieden/Little | libs/frexp.js | 1896 | /*
Port of the Posix frexp(3) from the SunPro C-code
Needs current ECMAScript 5.1 to work
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
function frexp(dnum)
{
"use asm";
var high = 0>>>0, tmp = 0>>>0, low = 0>>>0;
var exp = 0|0;
var num, cdnum;
if (dnum === 0) {
return dnum;
}
cdnum = dnum;
/* unsigned char * byte_string = (unsigned char *) & double_value; */
num = new DataView(new ArrayBuffer(8));
num.setFloat64(0, cdnum);
/*
typedef union
{
double cdnum;
struct
{
u_int32_t high;
u_int32_t low;
} halves;
} num;
*/
high = num.getUint32(0);
low = num.getUint32(4);
/* exponent = (high & 0x7ff00000) >> 20 */
tmp = 0x7fffffff & high;
/* errors (0, inf, nan) see IEEE-754 */
if (tmp >= 0x7ff00000 || ((tmp | low) === 0)) {
return cdnum;
}
/* See IEEE-754 for explanation of subnormal but
the problem is easily resolved by up-sizing */
if (tmp < 0x00100000) { /* subnormal */
/* One of the disadvantages of the Arraybuffer */
var temp = num.getFloat64(0);
temp *= 18014398509481984.0; // 2^54
num.setFloat64(0, temp);
high = num.getUint32(0);
tmp = high & 0x7fffffff;
/* down-size to normal */
exp = -54;
}
/* extract exponent and de-bias it */
exp += (tmp >>> 20) - 1022;
/* normalize mantissa 0.5 <= |dnum| < 1.0 */
high = (high & 0x800fffff) | 0x3fe00000;
num.setUint32(0, high);
return [num.getFloat64(0), exp];
}
| gpl-2.0 |
nizaranand/tide-and-pool | wp-content/plugins/woocommerce-gravityforms-product-addons/gravityforms-product-addons.php | 37988 | <?php
/*
Plugin Name: WooCommerce - Gravity Forms Product Add-Ons
Plugin URI: http://woothemes.com/woocommerce
Description: Allows you to use Gravity Forms on individual WooCommerce products. Requires the Gravity Forms plugin to work.
Version: 2.1
Author: Lucas Stark
Author URI: http://lucasstark.com
Requires at least: 3.1
Tested up to: 3.3
Copyright: © 2009-2011 Lucas Stark.
License: GNU General Public License v3.0
License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/
/**
* Required functions
*/
if (!function_exists('woothemes_queue_update'))
require_once( 'woo-includes/woo-functions.php' );
/**
* Plugin updates
*/
woothemes_queue_update(plugin_basename(__FILE__), 'a6ac0ab1a1536e3a357ccf24c0650ed0', '18633');
if (is_woocommerce_active() && in_array('gravityforms/gravityforms.php', apply_filters('active_plugins', get_option('active_plugins')))) {
load_plugin_textdomain('wc_gf_addons', null, dirname(plugin_basename(__FILE__)) . '/languages');
if (defined('DOING_AJAX'))
include 'gravityforms-product-addons-ajax.php';
class woocommerce_gravityforms {
var $settings;
var $edits = array();
public function __construct() {
wp_get_referer();
// Add script to the footer to override the default add to cart buttons throuhgout woocommerce
add_action('wp_footer', array(&$this, 'on_wp_footer'));
// Enqueue Gravity Forms Scripts
add_action('wp_enqueue_scripts', array(&$this, 'woocommerce_gravityform_enqueue_scripts'), 10);
// Addon display
add_action('woocommerce_before_add_to_cart_button', array(&$this, 'woocommerce_gravityform'), 10);
// Filters for price display
add_filter('woocommerce_grouped_price_html', array(&$this, 'get_price_html'), 10, 2);
add_filter('woocommerce_variation_price_html', array(&$this, 'get_price_html'), 10, 2);
add_filter('woocommerce_variation_sale_price_html', array(&$this, 'get_free_price_html'), 10, 2);
add_filter('woocommerce_variable_price_html', array(&$this, 'get_price_html'), 10, 2);
add_filter('woocommerce_variable_sale_price_html', array(&$this, 'get_price_html'), 10, 2);
add_filter('woocommerce_variable_empty_price_html', array(&$this, 'get_price_html'), 10, 2);
add_filter('woocommerce_variable_free_sale_price_html', array(&$this, 'get_free_price_html'), 10, 2);
add_filter('woocommerce_variable_free_price_html', array(&$this, 'get_free_price_html'), 10, 2);
add_filter('woocommerce_sale_price_html', array(&$this, 'get_price_html'), 10, 2);
add_filter('woocommerce_price_html', array(&$this, 'get_price_html'), 10, 2);
add_filter('woocommerce_empty_price_html', array(&$this, 'get_price_html'), 10, 2);
add_filter('woocommerce_free_sale_price_html', array(&$this, 'get_free_price_html'), 10, 2);
add_filter('woocommerce_free_price_html', array(&$this, 'get_free_price_html'), 10, 2);
// Filters for cart actions
add_filter('woocommerce_add_cart_item_data', array(&$this, 'add_cart_item_data'), 10, 2);
add_filter('woocommerce_get_cart_item_from_session', array(&$this, 'get_cart_item_from_session'), 10, 2);
add_filter('woocommerce_get_item_data', array(&$this, 'get_item_data'), 10, 2);
add_filter('woocommerce_add_cart_item', array(&$this, 'add_cart_item'), 10, 1);
add_action('woocommerce_order_item_meta', array(&$this, 'order_item_meta'), 10, 2);
add_filter('woocommerce_add_to_cart_validation', array(&$this, 'add_to_cart_validation'), 99, 3);
// Write Panel
add_action('add_meta_boxes', array(&$this, 'add_meta_box'));
add_action('woocommerce_process_product_meta', array(&$this, 'process_meta_box'), 1, 2);
}
//Fix up any add to cart button that has a gravity form assoicated with the product.
function on_wp_footer() {
global $wpdb;
$metakey = '_gravity_form_data';
$product_ids = $wpdb->get_col($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key=%s", $metakey));
if (is_array($product_ids)) {
$product_ids = array_flip($product_ids);
foreach ($product_ids as $k => $v) {
$product_ids[$k] = get_permalink($k);
}
}
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var gravityform_products = <?php echo json_encode($product_ids); ?>;
var label = "<?php echo apply_filters('gravityforms_add_to_cart_text', apply_filters('variable_add_to_cart_text', __('Select options', 'wc_gf_addons'))); ?>";
$('.add_to_cart_button').each(function(){
if ($(this).data('product_id') in gravityform_products){
$(this).text(label);
$(this).click(function(event) {
event.preventDefault();
var product_id = $(this).data('product_id');
window.location = gravityform_products[product_id];
return false;
});
}
});
});
</script>
<?php
}
/* ----------------------------------------------------------------------------------- */
/* Write Panel */
/* ----------------------------------------------------------------------------------- */
function add_meta_box() {
global $post;
add_meta_box('woocommerce-gravityforms-meta', __('Gravity Forms Product Add-Ons', 'wc_gf_addons'), array(&$this, 'meta_box'), 'product', 'normal', 'default');
}
function meta_box($post) {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#gravityform-id').change(function() {
if ($(this).val() != '') {
$('.gforms-panel').show();
}else {
$('.gforms-panel').hide();
}
})
});
</script>
<div id="gravityforms_data" class="panel woocommerce_options_panel">
<h4><?php _e('General', 'wc_gravityforms'); ?></h4>
<?php
$gravity_form_data = get_post_meta($post->ID, '_gravity_form_data', true);
$gravityform = NULL;
if (is_array($gravity_form_data) && isset($gravity_form_data['id']) && is_numeric($gravity_form_data['id'])) {
$form_meta = RGFormsModel::get_form_meta($gravity_form_data['id']);
if (!empty($form_meta)) {
$gravityform = RGFormsModel::get_form($gravity_form_data['id']);
}
}
?>
<div class="options_group">
<p class="form-field">
<label for="gravityform-id"><?php _e('Choose Form', 'wc_gravityforms'); ?></label>
<?php
echo '<select id="gravityform-id" name="gravityform-id"><option value="">' . __('None', 'wc_gf_addons') . '</option>';
foreach (RGFormsModel::get_forms() as $form) {
echo '<option ' . selected($form->id, $gravity_form_data['id']) . ' value="' . sanitize_title($form->id) . '">' . wptexturize($form->title) . '</option>';
}
echo '</select>';
?>
</p>
<?php
woocommerce_wp_checkbox(array(
'id' => 'gravityform-display_title',
'label' => __('Display Title', 'wc_gravityforms'),
'value' => isset($gravity_form_data['display_title']) && $gravity_form_data['display_title'] ? 'yes' : ''));
woocommerce_wp_checkbox(array(
'id' => 'gravityform-display_description',
'label' => __('Display Description', 'wc_gravityforms'),
'value' => isset($gravity_form_data['display_description']) && $gravity_form_data['display_description'] ? 'yes' : ''));
?>
</div>
<div class="options_group" style="padding: 0 9px;">
<?php if (!empty($gravityform) && is_object($gravityform)) : ?>
<h4><a href="<?php printf('%s/admin.php?page=gf_edit_forms&id=%d', get_admin_url(), $gravityform->id) ?>" class="edit_gravityform">Edit <?php echo $gravityform->title; ?> Gravity Form</a></h4>
<?php endif; ?>
</div>
</div>
<div id="price_labels_data" class="gforms-panel panel woocommerce_options_panel" <?php echo empty($gravity_form_data['id']) ? "style='display:none;'" : ''; ?>>
<h4><?php _e('Price Labels', 'wc_gravityforms'); ?></h4>
<div class="options_group">
<?php
woocommerce_wp_checkbox(array(
'id' => 'gravityform-disable_woocommerce_price',
'label' => __('Remove WooCommerce Price?', 'wc_gravityforms'),
'value' => isset($gravity_form_data['disable_woocommerce_price']) ? $gravity_form_data['disable_woocommerce_price'] : ''));
woocommerce_wp_text_input(array('id' => 'gravityform-price-before', 'label' => __('Price Before', 'wc_gravityforms'),
'value' => isset($gravity_form_data['price_before']) ? $gravity_form_data['price_before'] : '',
'placeholder' => __('Base Price:', 'wc_gravityforms'), 'description' => __('Enter text you would like printed before the price of the product.', 'wc_gravityforms')));
woocommerce_wp_text_input(array('id' => 'gravityform-price-after', 'label' => __('Price After', 'wc_gravityforms'),
'value' => isset($gravity_form_data['price_after']) ? $gravity_form_data['price_after'] : '',
'placeholder' => __('', 'wc_gravityforms'), 'description' => __('Enter text you would like printed after the price of the product.', 'wc_gravityforms')));
?>
</div>
</div>
<div id="total_labels_data" class="gforms-panel panel woocommerce_options_panel" <?php echo empty($gravity_form_data['id']) ? "style='display:none;'" : ''; ?>>
<h4><?php _e('Total Calculations', 'wc_gravityforms'); ?></h4>
<?php
echo '<div class="options_group">';
woocommerce_wp_checkbox(array(
'id' => 'gravityform-disable_calculations',
'label' => __('Disable Calculations?', 'wc_gravityforms'),
'value' => isset($gravity_form_data['disable_calculations']) ? $gravity_form_data['disable_calculations'] : ''));
echo '</div><div class="options_group">';
woocommerce_wp_checkbox(array(
'id' => 'gravityform-disable_label_subtotal',
'label' => __('Disable Subtotal?', 'wc_gravityforms'),
'value' => isset($gravity_form_data['disable_label_subtotal']) ? $gravity_form_data['disable_label_subtotal'] : ''));
woocommerce_wp_text_input(array('id' => 'gravityform-label_subtotal', 'label' => __('Subtotal Label', 'wc_gravityforms'),
'value' => isset($gravity_form_data['label_subtotal']) && !empty($gravity_form_data['label_subtotal']) ? $gravity_form_data['label_subtotal'] : 'Subtotal',
'placeholder' => __('Subtotal', 'wc_gravityforms'), 'description' => __('Enter "Subtotal" label to display on for single products.', 'wc_gravityforms')));
echo '</div><div class="options_group">';
woocommerce_wp_checkbox(array(
'id' => 'gravityform-disable_label_options',
'label' => __('Disable Options Label?', 'wc_gravityforms'),
'value' => isset($gravity_form_data['disable_label_options']) ? $gravity_form_data['disable_label_options'] : ''));
woocommerce_wp_text_input(array('id' => 'gravityform-label_options', 'label' => __('Options Label', 'wc_gravityforms'),
'value' => isset($gravity_form_data['label_options']) && !empty($gravity_form_data['label_options']) ? $gravity_form_data['label_options'] : 'Options',
'placeholder' => __('Options', 'wc_gravityforms'), 'description' => __('Enter the "Options" label to display for single products.', 'wc_gravityforms')));
echo '</div><div class="options_group">';
woocommerce_wp_checkbox(array(
'id' => 'gravityform-disable_label_total',
'label' => __('Disable Total Label?', 'wc_gravityforms'),
'value' => isset($gravity_form_data['disable_label_total']) ? $gravity_form_data['disable_label_total'] : ''));
woocommerce_wp_text_input(array('id' => 'gravityform-label_total', 'label' => __('Total Label', 'wc_gravityforms'),
'value' => isset($gravity_form_data['label_total']) && !empty($gravity_form_data['label_total']) ? $gravity_form_data['label_total'] : 'Total',
'placeholder' => __('Total', 'wc_gravityforms'), 'description' => __('Enter the "Total" label to display for single products.', 'wc_gravityforms')));
echo '</div>';
?>
</div>
<?php
}
function process_meta_box($post_id, $post) {
global $woocommerce_errors;
// Save gravity form as serialised array
if (isset($_POST['gravityform-id']) && !empty($_POST['gravityform-id'])) {
$product = null;
if (function_exists('get_product')) {
$product = get_product($post_id);
} else {
$product = new WC_Product($post_id);
}
if ($product->product_type != 'variable' && empty($product->price) && ($product->price != '0' || $product->price != '0.00')) {
$woocommerce_errors[] = __('You must set a price for the product before the gravity form will be visible. Set the price to 0 if you are performing all price calculations with the attached Gravity Form.', 'woocommerce');
}
$gravity_form_data = array(
'id' => $_POST['gravityform-id'],
'display_title' => isset($_POST['gravityform-display_title']) ? true : false,
'display_description' => isset($_POST['gravityform-display_description']) ? true : false,
'disable_woocommerce_price' => isset($_POST['gravityform-disable_woocommerce_price']) ? 'yes' : 'no',
'price_before' => $_POST['gravityform-price-before'],
'price_after' => $_POST['gravityform-price-after'],
'disable_calculations' => isset($_POST['gravityform-disable_calculations']) ? 'yes' : 'no',
'disable_label_subtotal' => isset($_POST['gravityform-disable_label_subtotal']) ? 'yes' : 'no',
'disable_label_options' => isset($_POST['gravityform-disable_label_options']) ? 'yes' : 'no',
'disable_label_total' => isset($_POST['gravityform-disable_label_total']) ? 'yes' : 'no',
'label_subtotal' => $_POST['gravityform-label_subtotal'],
'label_options' => $_POST['gravityform-label_options'],
'label_total' => $_POST['gravityform-label_total']
);
update_post_meta($post_id, '_gravity_form_data', $gravity_form_data);
} else {
delete_post_meta($post_id, '_gravity_form_data');
}
}
/* ----------------------------------------------------------------------------------- */
/* Product Form Functions */
/* ----------------------------------------------------------------------------------- */
function woocommerce_gravityform() {
global $post, $woocommerce;
include_once( 'gravityforms-product-addons-form.php' );
$gravity_form_data = get_post_meta($post->ID, '_gravity_form_data', true);
if (is_array($gravity_form_data) && $gravity_form_data['id']) {
$product = null;
if (function_exists('get_product')) {
$product = get_product($post->ID);
} else {
$product = new WC_Product($post->ID);
}
$product_form = new woocommerce_gravityforms_product_form($gravity_form_data['id'], $post->ID);
$product_form->get_form($gravity_form_data);
$add_to_cart_value = '';
if ($product->is_type('variable')) :
$add_to_cart_value = 'variation';
elseif ($product->has_child()) :
$add_to_cart_value = 'group';
else :
$add_to_cart_value = $product->id;
endif;
$woocommerce->nonce_field('add_to_cart');
echo '<input type="hidden" name="add-to-cart" value="' . $add_to_cart_value . '" />';
}
echo '<div class="clear"></div>';
}
function woocommerce_gravityform_enqueue_scripts() {
global $post;
if (is_product()) {
$gravity_form_data = get_post_meta($post->ID, '_gravity_form_data', true);
if ($gravity_form_data && is_array($gravity_form_data)) {
gravity_form_enqueue_scripts($gravity_form_data['id'], false);
}
}
}
function get_price_html($html, $_product) {
$gravity_form_data = get_post_meta($_product->id, '_gravity_form_data', true);
if ($gravity_form_data && is_array($gravity_form_data)) {
if (isset($gravity_form_data['disable_woocommerce_price']) && $gravity_form_data['disable_woocommerce_price'] == 'yes') {
$html = '';
}
if (isset($gravity_form_data['price_before'])) {
$html = '<span class="woocommerce-price-before">' . $gravity_form_data['price_before'] . ' </span>' . $html;
}
if (isset($gravity_form_data['price_after'])) {
$html .= '<span class="woocommerce-price-after"> ' . $gravity_form_data['price_after'] . '</span>';
}
}
return $html;
}
function get_free_price_html($html, $_product) {
$gravity_form_data = get_post_meta($_product->id, '_gravity_form_data', true);
if ($gravity_form_data && is_array($gravity_form_data)) {
if (isset($gravity_form_data['price_before'])) {
$html = '<span class="woocommerce-price-before">' . $gravity_form_data['price_before'] . ' </span>';
}
if (isset($gravity_form_data['price_after'])) {
$html .= '<span class="woocommerce-price-after"> ' . $gravity_form_data['price_after'] . '</span>';
}
}
return $html;
}
function get_formatted_price($price) {
return woocommerce_price($price);
}
function disable_notifications($disabled, $form, $lead) {
return true;
}
function add_to_cart_validation($valid, $product_id, $quantity) {
global $woocommerce;
// Check if we need a gravity form!
$gravity_form_data = get_post_meta($product_id, '_gravity_form_data', true);
if (is_array($gravity_form_data) && $gravity_form_data['id'] && empty($_POST['gform_form_id']))
return false;
if (isset($_POST['gform_form_id']) && is_numeric($_POST['gform_form_id'])) {
$form_id = $_POST['gform_form_id'];
//Gravity forms generates errors and warnings. To prevent these from conflicting with other things, we are going to disable warnings and errors.
error_reporting(0);
//MUST disable notifications manually.
add_filter('gform_disable_user_notification_' . $form_id, array(&$this, 'disable_notifications'), 10, 3);
add_filter('gform_disable_admin_notification_' . $form_id, array(&$this, 'disable_notifications'), 10, 3);
require_once(GFCommon::get_base_path() . "/form_display.php");
$_POST['gform_submit'] = $_POST['gform_old_submit'];
GFFormDisplay::process_form($form_id);
$_POST['gform_old_submit'] = $_POST['gform_submit'];
unset($_POST['gform_submit']);
if (!GFFormDisplay::$submission[$form_id]['is_valid']) {
return false;
}
if (GFFormDisplay::$submission[$form_id]['page_number'] != 0) {
return false;
}
}
return $valid;
}
//When the item is being added to the cart.
function add_cart_item_data($cart_item_meta, $product_id) {
global $woocommerce;
$gravity_form_data = get_post_meta($product_id, '_gravity_form_data', true);
$cart_item_meta['_gravity_form_data'] = $gravity_form_data;
if ($gravity_form_data && is_array($gravity_form_data) &&
isset($gravity_form_data['id']) && intval($gravity_form_data['id']) > 0) {
$form_id = $gravity_form_data['id'];
$form_meta = RGFormsModel::get_form_meta($form_id);
//Gravity forms generates errors and warnings. To prevent these from conflicting with other things, we are going to disable warnings and errors.
error_reporting(0);
//MUST disable notifications manually.
add_filter('gform_disable_user_notification_' . $form_id, array(&$this, 'disable_notifications'), 10, 3);
add_filter('gform_disable_admin_notification_' . $form_id, array(&$this, 'disable_notifications'), 10, 3);
if (empty($form_meta)) {
return $cart_item_meta;
}
require_once(GFCommon::get_base_path() . "/form_display.php");
$_POST['gform_submit'] = $_POST['gform_old_submit'];
GFFormDisplay::process_form($form_id);
$_POST['gform_old_submit'] = $_POST['gform_submit'];
unset($_POST['gform_submit']);
$lead = GFFormDisplay::$submission[$form_id]['lead'];
$cart_item_meta['_gravity_form_lead'] = array();
foreach ($form_meta['fields'] as $field) {
if (isset($field['displayOnly']) && $field['displayOnly']) {
continue;
}
$value = RGFormsModel::get_lead_field_value($lead, $field);
if (isset($field['inputs']) && is_array($field['inputs'])) {
foreach ($field['inputs'] as $input) {
$cart_item_meta['_gravity_form_lead'][strval($input['id'])] = $value[strval($input['id'])];
}
} else {
$cart_item_meta['_gravity_form_lead'][strval($field['id'])] = $value;
}
}
//RGFormsModel::delete_lead($lead['id']);
if (GFFormDisplay::$submission[$form_id]['is_valid']) {
add_filter('add_to_cart_redirect', array(&$this, 'get_redirect_url'), 99);
if (get_option('woocommerce_cart_redirect_after_add') == 'yes') {
$_SERVER['REQUEST_URI'] = get_site_url();
}
}
}
return $cart_item_meta;
}
function get_cart_item_from_session($cart_item, $values) {
if (isset($values['_gravity_form_data'])) {
$cart_item['_gravity_form_data'] = $values['_gravity_form_data'];
}
if (isset($values['_gravity_form_lead'])) {
$cart_item['_gravity_form_lead'] = $values['_gravity_form_lead'];
}
if (isset($cart_item['_gravity_form_lead']) && isset($cart_item['_gravity_form_data'])) {
$this->add_cart_item($cart_item);
}
return $cart_item;
}
function get_item_data($other_data, $cart_item) {
if (isset($cart_item['_gravity_form_lead']) && isset($cart_item['_gravity_form_data'])) {
//Gravity forms generates errors and warnings. To prevent these from conflicting with other things, we are going to disable warnings and errors.
error_reporting(0);
$gravity_form_data = $cart_item['_gravity_form_data'];
$form_meta = RGFormsModel::get_form_meta($gravity_form_data['id']);
if (!empty($form_meta)) {
$lead = $cart_item['_gravity_form_lead'];
$lead['id'] = -1;
foreach ($form_meta['fields'] as $field) {
if ($field['inputType'] == 'hiddenproduct' || $field['type'] == 'total' || (isset($field['displayOnly']) && $field['displayOnly'])) {
continue;
}
$value = RGFormsModel::get_lead_field_value($lead, $field);
$arr_var = (is_array($value)) ? implode('', $value) : '-';
if (!empty($value) && !empty($arr_var)) {
$display_value = GFCommon::get_lead_field_display($field, $value, isset($lead["currency"]) ? $lead["currency"] : false );
$price_adjustement = false;
$display_value = apply_filters("gform_entry_field_value", $display_value, $field, $lead, $form_meta);
$display_title = GFCommon::get_label($field);
$other_data[] = array('name' => $display_title, 'value' => $display_value);
}
}
}
}
return $other_data;
}
//Helper function, used when an item is added to the cart as well as when an item is restored from session.
function add_cart_item($cart_item) {
global $woocommerce;
// Adjust price if required based on the gravity form data
if (isset($cart_item['_gravity_form_lead']) && isset($cart_item['_gravity_form_data'])) {
//Gravity forms generates errors and warnings. To prevent these from conflicting with other things, we are going to disable warnings and errors.
error_reporting(0);
$gravity_form_data = $cart_item['_gravity_form_data'];
$form_meta = RGFormsModel::get_form_meta($gravity_form_data['id']);
if (empty($form_meta)) {
$_product = $cart_item['data'];
$woocommerce->add_error($_product->get_title() . __(' is invalid. Please remove and try readding to the cart', 'wc_gf_addons'));
return $cart_item;
}
$lead = $cart_item['_gravity_form_lead'];
$products = array();
$total = 0;
$lead['id'] = -1;
$products = $this->get_product_fields($form_meta, $lead);
if (!empty($products["products"])) {
foreach ($products["products"] as $product) {
$price = GFCommon::to_number($product["price"]);
if (is_array(rgar($product, "options"))) {
$count = sizeof($product["options"]);
$index = 1;
foreach ($product["options"] as $option) {
$price += GFCommon::to_number($option["price"]);
$class = $index == $count ? " class='lastitem'" : "";
$index++;
}
}
$subtotal = floatval($product["quantity"]) * $price;
$total += $subtotal;
}
$total += floatval($products["shipping"]["price"]);
}
$cart_item['data']->adjust_price($total);
}
return $cart_item;
}
function order_item_meta($item_meta, $cart_item) {
if (isset($cart_item['_gravity_form_lead']) && isset($cart_item['_gravity_form_data'])) {
//Gravity forms generates errors and warnings. To prevent these from conflicting with other things, we are going to disable warnings and errors.
error_reporting(0);
$gravity_form_data = $cart_item['_gravity_form_data'];
$form_meta = RGFormsModel::get_form_meta($gravity_form_data['id']);
if (!empty($form_meta)) {
$lead = $cart_item['_gravity_form_lead'];
foreach ($form_meta['fields'] as $field) {
if ((isset($field['inputType']) && $field['inputType'] == 'hiddenproduct') || (isset($field['displayOnly']) && $field['displayOnly'])) {
continue;
}
$value = RGFormsModel::get_lead_field_value($lead, $field);
$arr_var = (is_array($value)) ? implode('', $value) : '-';
if (!empty($value) && !empty($arr_var)) {
try {
$display_value = GFCommon::get_lead_field_display($field, $value, isset($lead["currency"]) ? $lead["currency"] : false );
$price_adjustement = false;
$display_value = apply_filters("gform_entry_field_value", $display_value, $field, $lead, $form_meta);
$display_title = GFCommon::get_label($field);
$item_meta->add($display_title, $display_value);
} catch (Exception $e) {
}
}
}
}
}
}
public function get_product_fields($form, $lead, $use_choice_text = false, $use_admin_label = false) {
$products = array();
foreach ($form["fields"] as $field) {
$id = $field["id"];
$lead_value = RGFormsModel::get_lead_field_value($lead, $field);
$quantity_field = GFCommon::get_product_fields_by_type($form, array("quantity"), $id);
$quantity = sizeof($quantity_field) > 0 ? RGFormsModel::get_lead_field_value($lead, $quantity_field[0]) : 1;
switch ($field["type"]) {
case "product" :
//if single product, get values from the multiple inputs
if (is_array($lead_value)) {
$product_quantity = sizeof($quantity_field) == 0 && !rgar($field, "disableQuantity") ? rgget($id . ".3", $lead_value) : $quantity;
if (empty($product_quantity))
continue;
if (!rgget($id, $products))
$products[$id] = array();
$products[$id]["name"] = $use_admin_label && !rgempty("adminLabel", $field) ? $field["adminLabel"] : $lead_value[$id . ".1"];
$products[$id]["price"] = $lead_value[$id . ".2"];
$products[$id]["quantity"] = $product_quantity;
}
else if (!empty($lead_value)) {
if (empty($quantity))
continue;
if (!rgar($products, $id))
$products[$id] = array();
if ($field["inputType"] == "price") {
$name = $field["label"];
$price = $lead_value;
} else {
list($name, $price) = explode("|", $lead_value);
}
$products[$id]["name"] = !$use_choice_text ? $name : RGFormsModel::get_choice_text($field, $name);
$products[$id]["price"] = $price;
$products[$id]["quantity"] = $quantity;
$products[$id]["options"] = array();
}
if (isset($products[$id])) {
$options = GFCommon::get_product_fields_by_type($form, array("option"), $id);
foreach ($options as $option) {
$option_value = RGFormsModel::get_lead_field_value($lead, $option);
$option_label = empty($option["adminLabel"]) ? $option["label"] : $option["adminLabel"];
if (is_array($option_value)) {
foreach ($option_value as $value) {
$option_info = GFCommon::get_option_info($value, $option, $use_choice_text);
if (!empty($option_info))
$products[$id]["options"][] = array("field_label" => rgar($option, "label"), "option_name" => rgar($option_info, "name"), "option_label" => $option_label . ": " . rgar($option_info, "name"), "price" => rgar($option_info, "price"));
}
}
else if (!empty($option_value)) {
$option_info = GFCommon::get_option_info($option_value, $option, $use_choice_text);
$products[$id]["options"][] = array("field_label" => rgar($option, "label"), "option_name" => rgar($option_info, "name"), "option_label" => $option_label . ": " . rgar($option_info, "name"), "price" => rgar($option_info, "price"));
}
}
}
break;
}
}
$shipping_field = GFCommon::get_fields_by_type($form, array("shipping"));
$shipping_price = $shipping_name = "";
if (!empty($shipping_field)) {
$shipping_price = RGFormsModel::get_lead_field_value($lead, $shipping_field[0]);
$shipping_name = $shipping_field[0]["label"];
if ($shipping_field[0]["inputType"] != "singleshipping") {
list($shipping_method, $shipping_price) = explode("|", $shipping_price);
$shipping_name = $shipping_field[0]["label"] . " ($shipping_method)";
}
}
$shipping_price = GFCommon::to_number($shipping_price);
$product_info = array("products" => $products, "shipping" => array("name" => $shipping_name, "price" => $shipping_price));
$product_info = apply_filters("gform_product_info_{$form["id"]}", apply_filters("gform_product_info", $product_info, $form, $lead), $form, $lead);
return $product_info;
}
function get_redirect_url($url) {
global $woocommerce;
if (!empty($url)) {
return $url;
} elseif (get_option('woocommerce_cart_redirect_after_add') == 'yes' && $woocommerce->error_count() == 0) {
$url = $woocommerce->cart->get_cart_url();
} else {
$ref = false;
if (!empty($_REQUEST['_wp_http_referer']))
$ref = $_REQUEST['_wp_http_referer'];
else if (!empty($_SERVER['HTTP_REFERER']))
$ref = $_SERVER['HTTP_REFERER'];
$url = $ref ? $ref : $url;
}
return $url;
}
}
$woocommerce_gravityforms = new woocommerce_gravityforms();
}
| gpl-2.0 |
pngames/pavillon-noir | pavillonnoir/__src/pncommon/PNRendererInterface.cpp | 1905 | /*
* PNRendererInterface.cpp
*
* Description :
* PNRendererInterface definition
*
* Copyright (C) 2005 PAVILLON-NOIR TEAM, http://pavillon-noir.org
* This software has been written in EPITECH <http://www.epitech.net>
* EPITECH is computer science school in Paris - FRANCE -
* under the direction of flav <http://www.epita.fr/~flav>.
* and Jerome Landrieu.
*
* This file is part of Pavillon Noir.
*
* Pavillon Noir 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.
*
* Pavillon Noir 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
* Pavillon Noir; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "pndefs.h"
#include "pnplugins.h"
#include "pnrender.h"
#include "PNRendererInterface.hpp"
namespace fs = boost::filesystem;
using namespace PN;
namespace PN {
//////////////////////////////////////////////////////////////////////////
PNRendererInterface* PNRendererInterface::_instance = NULL;
//////////////////////////////////////////////////////////////////////////
PNRendererInterface::PNRendererInterface()
{
_instance = this;
_name = _label = "Renderer";
}
PNRendererInterface::~PNRendererInterface()
{
}
//////////////////////////////////////////////////////////////////////////
plugintypes
PNRendererInterface::getType()
{
return PN_PLUGIN_RENDERER;
}
//////////////////////////////////////////////////////////////////////////
};
| gpl-2.0 |
tectronics/volunteer-passport | units/rpc/rpc_init.php | 1842 | <?php
/*
* XML-RPC init stuff
*/
// The class libraries
include_once $CFG->dirroot . "units/rpc/lib/class_elggobject.php";
include_once $CFG->dirroot . "units/rpc/lib/class_user.php";
include_once $CFG->dirroot . "units/rpc/lib/class_weblog.php";
include_once $CFG->dirroot . "units/rpc/lib/class_comment.php";
include_once $CFG->dirroot . "units/rpc/lib/class_post.php";
include_once $CFG->dirroot . "units/rpc/lib/class_tag.php";
include_once $CFG->dirroot . "units/rpc/lib/class_folder.php";
include_once $CFG->dirroot . "units/rpc/lib/class_file.php";
// Autodiscovery editlink
// Add to profile and weblog section
global $metatags;
$add_meta = false;
if (isset($_GET['weblog_name'])) {
$user_id = user_info_username('ident', $_GET['weblog_name']);
$add_meta = true;
} else if (isset($_GET['profile_name'])) {
$user_id = user_info_username('ident', $_GET['profile_name']);
$add_meta = true;
}
if ($add_meta) {
$metatags .= "\n<link rel=\"EditURI\" type=\"application/rsd+xml\" title=\"RSD\" href=\"" . url . "_rpc/rsd.php?user_id=".$user_id."\" />\n";
}
// A basic handler registry, for other plugins to register their xml-rpc calls
global $RPC;
include ($CFG->dirroot . "units/rpc/lib/class_rpc_config.php");
$RPC = new RpcConfig();
// Blogger API
include $CFG->dirroot . "units/rpc/xmlrpc/handlers_blogger_xmlrpc.php";
// MoveableType API
include $CFG->dirroot . "units/rpc/xmlrpc/handlers_mt_xmlrpc.php";
// LiveJournal API
include $CFG->dirroot . "units/rpc/xmlrpc/handlers_livejournal_xmlrpc.php";
// Misc Elgg functions
include $CFG->dirroot . "units/rpc/xmlrpc/handlers_elgg_user.php";
?>
| gpl-2.0 |