code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
<?php
/**
*
* This file is part of the phpBB Forum Software package.
*
* @copyright (c) phpBB Limited <https://www.phpbb.com>
* @copyright (c) 2010-2013 Moxiecode Systems AB
* @license GNU General Public License, version 2 (GPL-2.0)
*
* For full copyright and license information, please see
* the docs/CREDITS.txt file.
*
* Deutsche Übersetzung durch die Übersetzer-Gruppe von phpBB.de:
* siehe language/de/AUTHORS.md und https://www.phpbb.de/go/ubersetzerteam
*
*/
/**
* DO NOT CHANGE
*/
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
// DEVELOPERS PLEASE NOTE
//
// All language files should use UTF-8 as their encoding and the files must not contain a BOM.
//
// Placeholders can now contain order information, e.g. instead of
// 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows
// translators to re-order the output of data while ensuring it remains correct
//
// You do not need this where single placeholders are used, e.g. 'Message %d' is fine
// equally where a string contains only two placeholders which are used to wrap text
// in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine
$lang = array_merge($lang, array(
'PLUPLOAD_ADD_FILES' => 'Dateien hinzufügen',
'PLUPLOAD_ADD_FILES_TO_QUEUE' => 'Füge die anzuhängenden Dateien der Warteschlange hinzu und klicke auf die Schaltfläche „Warteschlange hochladen“.',
'PLUPLOAD_ALREADY_QUEUED' => '%s ist bereits in der Warteschlange vorhanden.',
'PLUPLOAD_CLOSE' => 'Schließen',
'PLUPLOAD_DRAG' => 'Ziehe neue Dateien in diesen Bereich.',
'PLUPLOAD_DUPLICATE_ERROR' => 'Doppelte-Datei-Fehler.',
'PLUPLOAD_DRAG_TEXTAREA' => 'Du kannst Dateien auch anhängen, indem du sie mit der Maus in den Beitragseditor ziehst.',
'PLUPLOAD_ERR_INPUT' => 'Eingabestrom konnte nicht geöffnet werden.',
'PLUPLOAD_ERR_MOVE_UPLOADED' => 'Hochgeladene Datei konnte nicht verschoben werden.',
'PLUPLOAD_ERR_OUTPUT' => 'Ausgabestrom konnte nicht geöffnet werden.',
'PLUPLOAD_ERR_FILE_TOO_LARGE' => 'Datei zu groß:',
'PLUPLOAD_ERR_FILE_COUNT' => 'Dateianzahl-Fehler.',
'PLUPLOAD_ERR_FILE_INVALID_EXT' => 'Ungültige Dateierweiterung:',
'PLUPLOAD_ERR_RUNTIME_MEMORY' => 'Der Laufzeitumgebung steht nicht ausreichend Arbeitsspeicher zur Verfügung.',
'PLUPLOAD_ERR_UPLOAD_URL' => 'Die hochzuladende URL ist entweder fehlerhaft oder existiert nicht.',
'PLUPLOAD_EXTENSION_ERROR' => 'Dateierweiterungs-Fehler.',
'PLUPLOAD_FILE' => 'Datei: %s',
'PLUPLOAD_FILE_DETAILS' => 'Datei: %s, Größe: %d, maximale Dateigröße: %d',
'PLUPLOAD_FILENAME' => 'Dateiname',
'PLUPLOAD_FILES_QUEUED' => '%d Dateien in der Warteschlange',
'PLUPLOAD_GENERIC_ERROR' => 'Allgemeiner Fehler.',
'PLUPLOAD_HTTP_ERROR' => 'HTTP-Fehler.',
'PLUPLOAD_IMAGE_FORMAT' => 'Das Bild-Format ist entweder fehlerhaft oder wird nicht unterstützt.',
'PLUPLOAD_INIT_ERROR' => 'Initialisierungs-Fehler',
'PLUPLOAD_IO_ERROR' => 'Eingabe-/Ausgabe-Fehler',
'PLUPLOAD_NOT_APPLICABLE' => 'n/a',
'PLUPLOAD_SECURITY_ERROR' => 'Sicherheits-Fehler.',
'PLUPLOAD_SELECT_FILES' => 'Dateien auswählen',
'PLUPLOAD_SIZE' => 'Größe',
'PLUPLOAD_SIZE_ERROR' => 'Dateigrößen-Fehler.',
'PLUPLOAD_STATUS' => 'Status',
'PLUPLOAD_START_UPLOAD' => 'Hochladen beginnen',
'PLUPLOAD_START_CURRENT_UPLOAD' => 'Warteschlange hochladen',
'PLUPLOAD_STOP_UPLOAD' => 'Hochladen stoppen',
'PLUPLOAD_STOP_CURRENT_UPLOAD' => 'Aktuellen Vorgang stoppen',
// Note: This string is formatted independently by plupload and so does not
// use the same formatting rules as normal phpBB translation strings
'PLUPLOAD_UPLOADED' => '%d/%d Dateien hochgeladen',
));
| phpbb-de/phpbb-translation | language/de/plupload.php | PHP | gpl-2.0 | 3,708 |
/*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.vm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class faddp_ST6_ST1 extends Executable
{
public faddp_ST6_ST1(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
}
public Branch execute(Processor cpu)
{
double freg0 = cpu.fpu.ST(6);
double freg1 = cpu.fpu.ST(1);
if ((freg0 == Double.NEGATIVE_INFINITY && freg1 == Double.POSITIVE_INFINITY) || (freg0 == Double.POSITIVE_INFINITY && freg1 == Double.NEGATIVE_INFINITY))
cpu.fpu.setInvalidOperation();
cpu.fpu.setST(6, freg0+freg1);
cpu.fpu.pop();
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | ysangkok/JPC | src/org/jpc/emulator/execution/opcodes/vm/faddp_ST6_ST1.java | Java | gpl-2.0 | 2,015 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>jQuery Dropdown CheckList</title>
<!-- Use a JQuery ThemeRoller theme, in this case 'smoothness' -->
<link rel="stylesheet" type="text/css" href="smoothness-1.8.13/jquery-ui-1.8.13.custom.css">
<link rel="stylesheet" type="text/css" href="ui.dropdownchecklist.themeroller.css">
<style>
table td { vertical-align: top }
dd { padding-bottom: 15px }
</style>
<!-- Include the basic JQuery support (core and ui) -->
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.13.custom.min.js"></script>
<script type="text/javascript" src="../src/ui.dropdownchecklist.js"></script>
<!-- Apply dropdown check list to the selected items -->
<script type="text/javascript">
$(document).ready(function() {
$returnS5 = $('#returnS5');
$("#s5").dropdownchecklist({
onItemClick: function(checkbox, selector){
var justChecked = checkbox.prop("checked");
var checkCount = (justChecked) ? 1 : -1;
for( i = 0; i < selector.options.length; i++ ){
if ( selector.options[i].selected ) checkCount += 1;
}
if ( checkCount > 3 ) {
alert( "Limit is 3" );
throw "too many";
}
}
});
$returnS6 = $('#returnS6');
$("#s6").dropdownchecklist({
onItemClick: function(checkbox, selector){
var thisIndex = checkbox.attr("id").split('-')[2].replace('i', '');
selector.options[thisIndex].selected = checkbox.attr("checked");
var values = "";
var newText = 'Checkbox ID = '+checkbox.attr('id')+'<br/><br/>';
for( i=0; i < selector.options.length; i++ ){
newText += 'Option i = ' +i+ ' || value = ' +selector.options[i].value+ ' || checked = ' +selector.options[i].selected+ '<br/><br/>';
if (selector.options[i].selected && (selector.options[i].value != "")){
if ( values != "" )
values += ";";
values += selector.options[i].value;
}
}
newText += 'Selector Value = '+values;
$returnS6.html( newText );
}
});
$('select option').removeProp('selected');
//for jquery < 1.6
//$('select option').removeAttr('selected');
});
</script>
</head>
<body>
<div id="content">
<h2>This example shows that the original select isn't automatically updated on the event onItemClick</h2>
<table>
<tr>
<td>
<select multiple="multiple" style="height: 100px;">
<option>Coffee Chip</option>
<option>Cookie Dough</option>
<option>Cookies 'n Cream</option>
<option>Dutch Chocolate</option>
<option>Fudgee Peanut Butter Cup</option>
</select>
</td>
<td>
<select id="s5" multiple="multiple">
<option>Coffee Chip</option>
<option>Cookie Dough</option>
<option>Cookies 'n Cream</option>
<option>Dutch Chocolate</option>
<option>Fudgee Peanut Butter Cup</option>
</select>
</td>
<td id="returnS5">
</td>
</tr>
<tr>
<td colspan='3'>
<h3>Code for this dropdown</h3>
<pre>
$returnS5 = $('#returnS5');
$("#s5").dropdownchecklist({
onItemClick: function(checkbox, selector){
var values = "";
var newText = 'Checkbox ID = '+checkbox.attr('id')+'<br/><br/>';
for( i = 0; i < selector.options.length; i++ ){
newText += 'Option i = ' +i+ ' || value = ' +selector.options[i].value+ ' || checked = ' +selector.options[i].selected+ '<br/><br/>';
if (selector.options[i].selected && (selector.options[i].value != "")){
if ( values != "" )
values += ";";
values += selector.options[i].value;
}
}
newText += 'Selector Value = '+values;
$returnS5.html( newText );
}
});
</pre>
</td>
</tr>
</table>
<h2>This modified code updates the original select on the event onItemClick</h2>
<table>
<tr>
<td>
<select multiple="multiple" style="height: 100px;">
<option>Coffee Chip</option>
<option>Cookie Dough</option>
<option>Cookies 'n Cream</option>
<option>Dutch Chocolate</option>
<option>Fudgee Peanut Butter Cup</option>
</select>
</td>
<td>
<select id="s6" multiple="multiple">
<option>Coffee Chip</option>
<option>Cookie Dough</option>
<option>Cookies 'n Cream</option>
<option>Dutch Chocolate</option>
<option>Fudgee Peanut Butter Cup</option>
</select>
</td>
<td id="returnS6">
</td>
</tr>
<tr>
<td colspan='3'>
<h3>Code for this dropdown</h3>
<pre>
$returnS6 = $('#returnS6');
$("#s6").dropdownchecklist({
onItemClick: function(checkbox, selector){
var thisIndex = checkbox.attr("id").split('-')[2].replace('i', '');
selector.options[thisIndex].selected = checkbox.attr("checked");
var values = "";
var newText = 'Checkbox ID = '+checkbox.attr('id')+'<br/><br/>';
for( i=0; i < selector.options.length; i++ ){
newText += 'Option i = ' +i+ ' || value = ' +selector.options[i].value+ ' || checked = ' +selector.options[i].selected+ '<br/><br/>';
if (selector.options[i].selected && (selector.options[i].value != "")){
if ( values != "" )
values += ";";
values += selector.options[i].value;
}
}
newText += 'Selector Value = '+values;
$returnS6.html( newText );
}
});
</pre>
</td>
</tr>
</table>
</div>
</body>
</html>
| Itshalffull/Docademy | sites/all/libraries/doc/dropdownchecklist-modified.html | HTML | gpl-2.0 | 5,650 |
class Citation < ActiveRecord::Base
belongs_to :citeable, :polymorphic => true
end
| dazzaji/opengovernment | app/models/citation.rb | Ruby | gpl-2.0 | 85 |
<?php
/**
* Aliases for special pages
*
* @file
* @ingroup Extensions
*/
$specialPageAliases = array();
/** English (English) */
$specialPageAliases['en'] = array(
'AdminLinks' => array( 'AdminLinks' ),
);
/** Afrikaans (Afrikaans) */
$specialPageAliases['af'] = array(
'AdminLinks' => array( 'AdminSkakels' ),
);
/** Arabic (العربية) */
$specialPageAliases['ar'] = array(
'AdminLinks' => array( 'وصلات_الإدارة' ),
);
/** Egyptian Spoken Arabic (مصرى) */
$specialPageAliases['arz'] = array(
'AdminLinks' => array( 'لينكات_الاداره' ),
);
/** Breton (Brezhoneg) */
$specialPageAliases['br'] = array(
'AdminLinks' => array( 'LiammoùMerañ' ),
);
/** German (Deutsch) */
$specialPageAliases['de'] = array(
'AdminLinks' => array( 'Admin-Links' ),
);
/** Esperanto (Esperanto) */
$specialPageAliases['eo'] = array(
'AdminLinks' => array( 'Ligiloj_por_administrantoj' ),
);
/** Spanish (Español) */
$specialPageAliases['es'] = array(
'AdminLinks' => array( 'EnlacesAdministrador' ),
);
/** Persian (فارسی) */
$specialPageAliases['fa'] = array(
'AdminLinks' => array( 'پیوندهای_مدیر' ),
);
/** Finnish (Suomi) */
$specialPageAliases['fi'] = array(
'AdminLinks' => array( 'Ylläpitolinkit' ),
);
/** Galician (Galego) */
$specialPageAliases['gl'] = array(
'AdminLinks' => array( 'Ligazóns_de_administración' ),
);
/** 湘语 (湘语) */
$specialPageAliases['hsn'] = array(
'AdminLinks' => array( '管理链接' ),
);
/** Haitian (Kreyòl ayisyen) */
$specialPageAliases['ht'] = array(
'AdminLinks' => array( 'LyenAdmin' ),
);
/** Interlingua (Interlingua) */
$specialPageAliases['ia'] = array(
'AdminLinks' => array( 'Ligamines_pro_administratores' ),
);
/** Indonesian (Bahasa Indonesia) */
$specialPageAliases['id'] = array(
'AdminLinks' => array( 'Pranala_admin', 'PranalaAdmin' ),
);
/** Japanese (日本語) */
$specialPageAliases['ja'] = array(
'AdminLinks' => array( '管理者用リンク集' ),
);
/** Colognian (Ripoarisch) */
$specialPageAliases['ksh'] = array(
'AdminLinks' => array( 'Lengks_för_Wiki_Köbesse' ),
);
/** Ladino (Ladino) */
$specialPageAliases['lad'] = array(
'AdminLinks' => array( 'Linkes_de_administradores' ),
);
/** Luxembourgish (Lëtzebuergesch) */
$specialPageAliases['lb'] = array(
'AdminLinks' => array( 'Linke_fir_Administrateuren' ),
);
/** Malagasy (Malagasy) */
$specialPageAliases['mg'] = array(
'AdminLinks' => array( 'Rohim-pandrindra' ),
);
/** Macedonian (Македонски) */
$specialPageAliases['mk'] = array(
'AdminLinks' => array( 'АдминистраторскиВрски' ),
);
/** Malayalam (മലയാളം) */
$specialPageAliases['ml'] = array(
'AdminLinks' => array( 'കാര്യനിർവാഹകകണ്ണികൾ' ),
);
/** Marathi (मराठी) */
$specialPageAliases['mr'] = array(
'AdminLinks' => array( 'प्रचालकदुवे' ),
);
/** Maltese (Malti) */
$specialPageAliases['mt'] = array(
'AdminLinks' => array( 'ĦoloqAmmin' ),
);
/** Norwegian Bokmål (Norsk (bokmål)) */
$specialPageAliases['nb'] = array(
'AdminLinks' => array( 'Administratorlenker' ),
);
/** Nedersaksisch (Nedersaksisch) */
$specialPageAliases['nds-nl'] = array(
'AdminLinks' => array( 'Beheerdersverwiezingen' ),
);
/** Dutch (Nederlands) */
$specialPageAliases['nl'] = array(
'AdminLinks' => array( 'Beheerdersverwijzingen' ),
);
/** Portuguese (Português) */
$specialPageAliases['pt'] = array(
'AdminLinks' => array( 'Ligações_de_administração' ),
);
/** Romanian (Română) */
$specialPageAliases['ro'] = array(
'AdminLinks' => array( 'Legături_admini' ),
);
/** Sanskrit (संस्कृतम्) */
$specialPageAliases['sa'] = array(
'AdminLinks' => array( 'कार्यकर्ता_सम्भन्दिन्' ),
);
/** Sinhala (සිංහල) */
$specialPageAliases['si'] = array(
'AdminLinks' => array( 'පරිපාලක_සබැඳි' ),
);
/** Slovak (Slovenčina) */
$specialPageAliases['sk'] = array(
'AdminLinks' => array( 'OdkazySprávcu' ),
);
/** Swedish (Svenska) */
$specialPageAliases['sv'] = array(
'AdminLinks' => array( 'Administratörslänkar' ),
);
/** Turkish (Türkçe) */
$specialPageAliases['tr'] = array(
'AdminLinks' => array( 'HizmetliBağları', 'HizmetliBağlantıları' ),
);
/** Simplified Chinese (中文(简体)) */
$specialPageAliases['zh-hans'] = array(
'AdminLinks' => array( '管理员链接' ),
);
/** Traditional Chinese (中文(繁體)) */
$specialPageAliases['zh-hant'] = array(
'AdminLinks' => array( '管理員鏈接' ),
); | SuriyaaKudoIsc/wikia-app-test | extensions/AdminLinks/AdminLinks.alias.php | PHP | gpl-2.0 | 4,620 |
/*
* This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Common.h"
#include "Database/DatabaseEnv.h"
#include "DBCStores.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "World.h"
#include "ObjectMgr.h"
#include "Player.h"
#include "Opcodes.h"
#include "Chat.h"
#include "Log.h"
#include "MapManager.h"
#include "ObjectAccessor.h"
#include "Language.h"
#include "CellImpl.h"
#include "MapPersistentStateMgr.h"
#include "Mail.h"
#include "Util.h"
#include "SpellMgr.h"
#ifdef _DEBUG_VMAPS
#include "VMapFactory.h"
#endif
//-----------------------Npc Commands-----------------------
bool ChatHandler::HandleNpcSayCommand(char* args)
{
if (!*args)
return false;
Creature* pCreature = getSelectedCreature();
if (!pCreature)
{
SendSysMessage(LANG_SELECT_CREATURE);
SetSentErrorMessage(true);
return false;
}
pCreature->MonsterSay(args, LANG_UNIVERSAL, m_session->GetPlayer());
return true;
}
bool ChatHandler::HandleNpcYellCommand(char* args)
{
if (!*args)
return false;
Creature* pCreature = getSelectedCreature();
if (!pCreature)
{
SendSysMessage(LANG_SELECT_CREATURE);
SetSentErrorMessage(true);
return false;
}
pCreature->MonsterYell(args, LANG_UNIVERSAL, m_session->GetPlayer());
return true;
}
// show text emote by creature in chat
bool ChatHandler::HandleNpcTextEmoteCommand(char* args)
{
if (!*args)
return false;
Creature* pCreature = getSelectedCreature();
if (!pCreature)
{
SendSysMessage(LANG_SELECT_CREATURE);
SetSentErrorMessage(true);
return false;
}
pCreature->MonsterTextEmote(args, m_session->GetPlayer());
return true;
}
// make npc whisper to player
bool ChatHandler::HandleNpcWhisperCommand(char* args)
{
Player* target;
if (!ExtractPlayerTarget(&args, &target))
return false;
ObjectGuid guid = m_session->GetPlayer()->GetSelectionGuid();
if (!guid)
return false;
Creature* pCreature = m_session->GetPlayer()->GetMap()->GetCreature(guid);
if (!pCreature || !target || !*args)
return false;
// check online security
if (HasLowerSecurity(target))
return false;
pCreature->MonsterWhisper(args, target);
return true;
}
//----------------------------------------------------------
// global announce
bool ChatHandler::HandleAnnounceCommand(char* args)
{
if (!*args)
return false;
sWorld.SendWorldText(LANG_SYSTEMMESSAGE, args);
return true;
}
// notification player at the screen
bool ChatHandler::HandleNotifyCommand(char* args)
{
if (!*args)
return false;
std::string str = GetMangosString(LANG_GLOBAL_NOTIFY);
str += args;
WorldPacket data(SMSG_NOTIFICATION, (str.size() + 1));
data << str;
sWorld.SendGlobalMessage(&data);
return true;
}
// Enable\Dissable GM Mode
bool ChatHandler::HandleGMCommand(char* args)
{
if (!*args)
{
if (m_session->GetPlayer()->isGameMaster())
m_session->SendNotification(LANG_GM_ON);
else
m_session->SendNotification(LANG_GM_OFF);
return true;
}
bool value;
if (!ExtractOnOff(&args, value))
{
SendSysMessage(LANG_USE_BOL);
SetSentErrorMessage(true);
return false;
}
if (value)
{
m_session->GetPlayer()->SetGameMaster(true);
m_session->SendNotification(LANG_GM_ON);
}
else
{
m_session->GetPlayer()->SetGameMaster(false);
m_session->SendNotification(LANG_GM_OFF);
}
return true;
}
// Enables or disables hiding of the staff badge
bool ChatHandler::HandleGMChatCommand(char* args)
{
if (!*args)
{
if (m_session->GetPlayer()->isGMChat())
m_session->SendNotification(LANG_GM_CHAT_ON);
else
m_session->SendNotification(LANG_GM_CHAT_OFF);
return true;
}
bool value;
if (!ExtractOnOff(&args, value))
{
SendSysMessage(LANG_USE_BOL);
SetSentErrorMessage(true);
return false;
}
if (value)
{
m_session->GetPlayer()->SetGMChat(true);
m_session->SendNotification(LANG_GM_CHAT_ON);
}
else
{
m_session->GetPlayer()->SetGMChat(false);
m_session->SendNotification(LANG_GM_CHAT_OFF);
}
return true;
}
// Enable\Dissable Invisible mode
bool ChatHandler::HandleGMVisibleCommand(char* args)
{
if (!*args)
{
PSendSysMessage(LANG_YOU_ARE, m_session->GetPlayer()->isGMVisible() ? GetMangosString(LANG_VISIBLE) : GetMangosString(LANG_INVISIBLE));
return true;
}
bool value;
if (!ExtractOnOff(&args, value))
{
SendSysMessage(LANG_USE_BOL);
SetSentErrorMessage(true);
return false;
}
Player* player = m_session->GetPlayer();
SpellEntry const* invisibleAuraInfo = sSpellStore.LookupEntry(sWorld.getConfig(CONFIG_UINT32_GM_INVISIBLE_AURA));
if (!invisibleAuraInfo || !IsSpellAppliesAura(invisibleAuraInfo))
invisibleAuraInfo = nullptr;
if (value)
{
player->SetGMVisible(true);
m_session->SendNotification(LANG_INVISIBLE_VISIBLE);
if (invisibleAuraInfo)
player->RemoveAurasDueToSpell(invisibleAuraInfo->Id);
}
else
{
m_session->SendNotification(LANG_INVISIBLE_INVISIBLE);
player->SetGMVisible(false);
if (invisibleAuraInfo)
player->CastSpell(player, invisibleAuraInfo, true);
}
return true;
}
bool ChatHandler::HandleGPSCommand(char* args)
{
WorldObject* obj = nullptr;
if (*args)
{
if (ObjectGuid guid = ExtractGuidFromLink(&args))
obj = (WorldObject*)m_session->GetPlayer()->GetObjectByTypeMask(guid, TYPEMASK_CREATURE_OR_GAMEOBJECT);
if (!obj)
{
SendSysMessage(LANG_PLAYER_NOT_FOUND);
SetSentErrorMessage(true);
return false;
}
}
else
{
obj = getSelectedUnit();
if (!obj)
{
SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
SetSentErrorMessage(true);
return false;
}
}
CellPair cell_val = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY());
Cell cell(cell_val);
uint32 zone_id, area_id;
obj->GetZoneAndAreaId(zone_id, area_id);
MapEntry const* mapEntry = sMapStore.LookupEntry(obj->GetMapId());
AreaTableEntry const* zoneEntry = GetAreaEntryByAreaID(zone_id);
AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(area_id);
float zone_x = obj->GetPositionX();
float zone_y = obj->GetPositionY();
if (!Map2ZoneCoordinates(zone_x, zone_y, zone_id))
{
zone_x = 0;
zone_y = 0;
}
Map const* map = obj->GetMap();
float ground_z = map->GetHeight(obj->GetPositionX(), obj->GetPositionY(), MAX_HEIGHT);
float floor_z = map->GetHeight(obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ());
GridPair p = MaNGOS::ComputeGridPair(obj->GetPositionX(), obj->GetPositionY());
int gx = 63 - p.x_coord;
int gy = 63 - p.y_coord;
uint32 have_map = GridMap::ExistMap(obj->GetMapId(), gx, gy) ? 1 : 0;
uint32 have_vmap = GridMap::ExistVMap(obj->GetMapId(), gx, gy) ? 1 : 0;
TerrainInfo const* terrain = obj->GetTerrain();
if (have_vmap)
{
if (terrain->IsOutdoors(obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ()))
PSendSysMessage("You are OUTdoor");
else
PSendSysMessage("You are INdoor");
}
else PSendSysMessage("no VMAP available for area info");
PSendSysMessage(LANG_MAP_POSITION,
obj->GetMapId(), (mapEntry ? mapEntry->name[GetSessionDbcLocale()] : "<unknown>"),
zone_id, (zoneEntry ? zoneEntry->area_name[GetSessionDbcLocale()] : "<unknown>"),
area_id, (areaEntry ? areaEntry->area_name[GetSessionDbcLocale()] : "<unknown>"),
obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ(), obj->GetOrientation(),
cell.GridX(), cell.GridY(), cell.CellX(), cell.CellY(), obj->GetInstanceId(),
zone_x, zone_y, ground_z, floor_z, have_map, have_vmap);
DEBUG_LOG("Player %s GPS call for %s '%s' (%s: %u):",
m_session ? GetNameLink().c_str() : GetMangosString(LANG_CONSOLE_COMMAND),
(obj->GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), obj->GetName(),
(obj->GetTypeId() == TYPEID_PLAYER ? "GUID" : "Entry"), (obj->GetTypeId() == TYPEID_PLAYER ? obj->GetGUIDLow() : obj->GetEntry()));
DEBUG_LOG(GetMangosString(LANG_MAP_POSITION),
obj->GetMapId(), (mapEntry ? mapEntry->name[sWorld.GetDefaultDbcLocale()] : "<unknown>"),
zone_id, (zoneEntry ? zoneEntry->area_name[sWorld.GetDefaultDbcLocale()] : "<unknown>"),
area_id, (areaEntry ? areaEntry->area_name[sWorld.GetDefaultDbcLocale()] : "<unknown>"),
obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ(), obj->GetOrientation(),
cell.GridX(), cell.GridY(), cell.CellX(), cell.CellY(), obj->GetInstanceId(),
zone_x, zone_y, ground_z, floor_z, have_map, have_vmap);
GridMapLiquidData liquid_status;
GridMapLiquidStatus res = terrain->getLiquidStatus(obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ(), MAP_ALL_LIQUIDS, &liquid_status);
if (res)
{
PSendSysMessage(LANG_LIQUID_STATUS, liquid_status.level, liquid_status.depth_level, liquid_status.type_flags, res);
}
// Additional vmap debugging help
#ifdef _DEBUG_VMAPS
PSendSysMessage("Static terrain height (maps only): %f", obj->GetTerrain()->GetHeightStatic(obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ(), false));
if (VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
PSendSysMessage("Vmap Terrain Height %f", vmgr->getHeight(obj->GetMapId(), obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ() + 2.0f, 10000.0f));
PSendSysMessage("Static map height (maps and vmaps): %f", obj->GetTerrain()->GetHeightStatic(obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ()));
#endif
return true;
}
// Summon Player
bool ChatHandler::HandleNamegoCommand(char* args)
{
Player* target;
ObjectGuid target_guid;
std::string target_name;
if (!ExtractPlayerTarget(&args, &target, &target_guid, &target_name))
return false;
Player* player = m_session->GetPlayer();
if (target == player || target_guid == player->GetObjectGuid())
{
PSendSysMessage(LANG_CANT_TELEPORT_SELF);
SetSentErrorMessage(true);
return false;
}
if (target)
{
std::string nameLink = playerLink(target_name);
// check online security
if (HasLowerSecurity(target))
return false;
if (target->IsBeingTeleported())
{
PSendSysMessage(LANG_IS_TELEPORTED, nameLink.c_str());
SetSentErrorMessage(true);
return false;
}
Map* pMap = player->GetMap();
if (pMap->IsBattleGroundOrArena())
{
// only allow if gm mode is on
if (!target->isGameMaster())
{
PSendSysMessage(LANG_CANNOT_GO_TO_BG_GM, nameLink.c_str());
SetSentErrorMessage(true);
return false;
}
// if both players are in different bgs
else if (target->GetBattleGroundId() && player->GetBattleGroundId() != target->GetBattleGroundId())
{
PSendSysMessage(LANG_CANNOT_GO_TO_BG_FROM_BG, nameLink.c_str());
SetSentErrorMessage(true);
return false;
}
// all's well, set bg id
// when porting out from the bg, it will be reset to 0
target->SetBattleGroundId(player->GetBattleGroundId(), player->GetBattleGroundTypeId());
// remember current position as entry point for return at bg end teleportation
if (!target->GetMap()->IsBattleGroundOrArena())
target->SetBattleGroundEntryPoint();
}
else if (pMap->IsDungeon())
{
Map* cMap = target->GetMap();
if (cMap->Instanceable() && cMap->GetInstanceId() != pMap->GetInstanceId())
{
// cannot summon from instance to instance
PSendSysMessage(LANG_CANNOT_SUMMON_TO_INST, nameLink.c_str());
SetSentErrorMessage(true);
return false;
}
// we are in instance, and can summon only player in our group with us as lead
if (!player->GetGroup() || !target->GetGroup() ||
(target->GetGroup()->GetLeaderGuid() != player->GetObjectGuid()) ||
(player->GetGroup()->GetLeaderGuid() != player->GetObjectGuid()))
// the last check is a bit excessive, but let it be, just in case
{
PSendSysMessage(LANG_CANNOT_SUMMON_TO_INST, nameLink.c_str());
SetSentErrorMessage(true);
return false;
}
}
PSendSysMessage(LANG_SUMMONING, nameLink.c_str(), "");
if (needReportToTarget(target))
ChatHandler(target).PSendSysMessage(LANG_SUMMONED_BY, playerLink(player->GetName()).c_str());
// stop flight if need
if (target->IsTaxiFlying())
{
target->GetMotionMaster()->MovementExpired();
target->m_taxi.ClearTaxiDestinations();
}
// save only in non-flight case
else
target->SaveRecallPosition();
// before GM
float x, y, z;
player->GetClosePoint(x, y, z, target->GetObjectBoundingRadius());
target->TeleportTo(player->GetMapId(), x, y, z, target->GetOrientation());
}
else
{
// check offline security
if (HasLowerSecurity(nullptr, target_guid))
return false;
std::string nameLink = playerLink(target_name);
PSendSysMessage(LANG_SUMMONING, nameLink.c_str(), GetMangosString(LANG_OFFLINE));
// in point where GM stay
Player::SavePositionInDB(target_guid, player->GetMapId(),
player->GetPositionX(),
player->GetPositionY(),
player->GetPositionZ(),
player->GetOrientation(),
player->GetZoneId());
}
return true;
}
// Teleport to Player
bool ChatHandler::HandleGonameCommand(char* args)
{
Player* target;
ObjectGuid target_guid;
std::string target_name;
if (!ExtractPlayerTarget(&args, &target, &target_guid, &target_name))
return false;
Player* _player = m_session->GetPlayer();
if (target == _player || target_guid == _player->GetObjectGuid())
{
SendSysMessage(LANG_CANT_TELEPORT_SELF);
SetSentErrorMessage(true);
return false;
}
if (target)
{
// check online security
if (HasLowerSecurity(target))
return false;
std::string chrNameLink = playerLink(target_name);
Map* cMap = target->GetMap();
if (cMap->IsBattleGroundOrArena())
{
// only allow if gm mode is on
if (!_player->isGameMaster())
{
PSendSysMessage(LANG_CANNOT_GO_TO_BG_GM, chrNameLink.c_str());
SetSentErrorMessage(true);
return false;
}
// if both players are in different bgs
else if (_player->GetBattleGroundId() && _player->GetBattleGroundId() != target->GetBattleGroundId())
{
PSendSysMessage(LANG_CANNOT_GO_TO_BG_FROM_BG, chrNameLink.c_str());
SetSentErrorMessage(true);
return false;
}
// all's well, set bg id
// when porting out from the bg, it will be reset to 0
_player->SetBattleGroundId(target->GetBattleGroundId(), target->GetBattleGroundTypeId());
// remember current position as entry point for return at bg end teleportation
if (!_player->GetMap()->IsBattleGroundOrArena())
_player->SetBattleGroundEntryPoint();
}
else if (cMap->IsDungeon())
{
// we have to go to instance, and can go to player only if:
// 1) we are in his group (either as leader or as member)
// 2) we are not bound to any group and have GM mode on
if (_player->GetGroup())
{
// we are in group, we can go only if we are in the player group
if (_player->GetGroup() != target->GetGroup())
{
PSendSysMessage(LANG_CANNOT_GO_TO_INST_PARTY, chrNameLink.c_str());
SetSentErrorMessage(true);
return false;
}
}
else
{
// we are not in group, let's verify our GM mode
if (!_player->isGameMaster())
{
PSendSysMessage(LANG_CANNOT_GO_TO_INST_GM, chrNameLink.c_str());
SetSentErrorMessage(true);
return false;
}
}
// if the player or the player's group is bound to another instance
// the player will not be bound to another one
InstancePlayerBind* pBind = _player->GetBoundInstance(target->GetMapId(), target->GetDifficulty());
if (!pBind)
{
Group* group = _player->GetGroup();
// if no bind exists, create a solo bind
InstanceGroupBind* gBind = group ? group->GetBoundInstance(target->GetMapId(), target) : nullptr;
// if no bind exists, create a solo bind
if (!gBind)
{
DungeonPersistentState* save = ((DungeonMap*)target->GetMap())->GetPersistanceState();
// if player is group leader then we need add group bind
if (group && group->IsLeader(_player->GetObjectGuid()))
group->BindToInstance(save, !save->CanReset());
else
_player->BindToInstance(save, !save->CanReset());
}
}
_player->SetDifficulty(target->GetDifficulty());
}
PSendSysMessage(LANG_APPEARING_AT, chrNameLink.c_str());
if (needReportToTarget(target))
ChatHandler(target).PSendSysMessage(LANG_APPEARING_TO, GetNameLink().c_str());
// stop flight if need
if (_player->IsTaxiFlying())
{
_player->GetMotionMaster()->MovementExpired();
_player->m_taxi.ClearTaxiDestinations();
}
// save only in non-flight case
else
_player->SaveRecallPosition();
// to point to see at target with same orientation
float x, y, z;
target->GetContactPoint(_player, x, y, z);
_player->TeleportTo(target->GetMapId(), x, y, z, _player->GetAngle(target), TELE_TO_GM_MODE);
}
else
{
// check offline security
if (HasLowerSecurity(nullptr, target_guid))
return false;
std::string nameLink = playerLink(target_name);
PSendSysMessage(LANG_APPEARING_AT, nameLink.c_str());
// to point where player stay (if loaded)
float x, y, z, o;
uint32 map;
bool in_flight;
if (!Player::LoadPositionFromDB(target_guid, map, x, y, z, o, in_flight))
return false;
return HandleGoHelper(_player, map, x, y, &z);
}
return true;
}
// Teleport player to last position
bool ChatHandler::HandleRecallCommand(char* args)
{
Player* target;
if (!ExtractPlayerTarget(&args, &target))
return false;
// check online security
if (HasLowerSecurity(target))
return false;
if (target->IsBeingTeleported())
{
PSendSysMessage(LANG_IS_TELEPORTED, GetNameLink(target).c_str());
SetSentErrorMessage(true);
return false;
}
return HandleGoHelper(target, target->m_recallMap, target->m_recallX, target->m_recallY, &target->m_recallZ, &target->m_recallO);
}
// Edit Player HP
bool ChatHandler::HandleModifyHPCommand(char* args)
{
if (!*args)
return false;
int32 hp = atoi(args);
int32 hpm = atoi(args);
if (hp <= 0 || hpm <= 0 || hpm < hp)
{
SendSysMessage(LANG_BAD_VALUE);
SetSentErrorMessage(true);
return false;
}
Player* chr = getSelectedPlayer();
if (chr == nullptr)
{
SendSysMessage(LANG_NO_CHAR_SELECTED);
SetSentErrorMessage(true);
return false;
}
// check online security
if (HasLowerSecurity(chr))
return false;
PSendSysMessage(LANG_YOU_CHANGE_HP, GetNameLink(chr).c_str(), hp, hpm);
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_YOURS_HP_CHANGED, GetNameLink().c_str(), hp, hpm);
chr->SetMaxHealth(hpm);
chr->SetHealth(hp);
return true;
}
// Edit Player Mana
bool ChatHandler::HandleModifyManaCommand(char* args)
{
if (!*args)
return false;
int32 mana = atoi(args);
int32 manam = atoi(args);
if (mana <= 0 || manam <= 0 || manam < mana)
{
SendSysMessage(LANG_BAD_VALUE);
SetSentErrorMessage(true);
return false;
}
Player* chr = getSelectedPlayer();
if (chr == nullptr)
{
SendSysMessage(LANG_NO_CHAR_SELECTED);
SetSentErrorMessage(true);
return false;
}
// check online security
if (HasLowerSecurity(chr))
return false;
PSendSysMessage(LANG_YOU_CHANGE_MANA, GetNameLink(chr).c_str(), mana, manam);
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_YOURS_MANA_CHANGED, GetNameLink().c_str(), mana, manam);
chr->SetMaxPower(POWER_MANA, manam);
chr->SetPower(POWER_MANA, mana);
return true;
}
// Edit Player Energy
bool ChatHandler::HandleModifyEnergyCommand(char* args)
{
if (!*args)
return false;
int32 energy = atoi(args) * 10;
int32 energym = atoi(args) * 10;
if (energy <= 0 || energym <= 0 || energym < energy)
{
SendSysMessage(LANG_BAD_VALUE);
SetSentErrorMessage(true);
return false;
}
Player* chr = getSelectedPlayer();
if (!chr)
{
SendSysMessage(LANG_NO_CHAR_SELECTED);
SetSentErrorMessage(true);
return false;
}
// check online security
if (HasLowerSecurity(chr))
return false;
PSendSysMessage(LANG_YOU_CHANGE_ENERGY, GetNameLink(chr).c_str(), energy / 10, energym / 10);
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_YOURS_ENERGY_CHANGED, GetNameLink().c_str(), energy / 10, energym / 10);
chr->SetMaxPower(POWER_ENERGY, energym);
chr->SetPower(POWER_ENERGY, energy);
DETAIL_LOG(GetMangosString(LANG_CURRENT_ENERGY), chr->GetMaxPower(POWER_ENERGY));
return true;
}
// Edit Player Rage
bool ChatHandler::HandleModifyRageCommand(char* args)
{
if (!*args)
return false;
int32 rage = atoi(args) * 10;
int32 ragem = atoi(args) * 10;
if (rage <= 0 || ragem <= 0 || ragem < rage)
{
SendSysMessage(LANG_BAD_VALUE);
SetSentErrorMessage(true);
return false;
}
Player* chr = getSelectedPlayer();
if (chr == nullptr)
{
SendSysMessage(LANG_NO_CHAR_SELECTED);
SetSentErrorMessage(true);
return false;
}
// check online security
if (HasLowerSecurity(chr))
return false;
PSendSysMessage(LANG_YOU_CHANGE_RAGE, GetNameLink(chr).c_str(), rage / 10, ragem / 10);
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_YOURS_RAGE_CHANGED, GetNameLink().c_str(), rage / 10, ragem / 10);
chr->SetMaxPower(POWER_RAGE, ragem);
chr->SetPower(POWER_RAGE, rage);
return true;
}
// Edit Player Faction
bool ChatHandler::HandleModifyFactionCommand(char* args)
{
Creature* chr = getSelectedCreature();
if (!chr)
{
SendSysMessage(LANG_SELECT_CREATURE);
SetSentErrorMessage(true);
return false;
}
if (!*args)
{
if (chr)
{
uint32 factionid = chr->getFaction();
uint32 flag = chr->GetUInt32Value(UNIT_FIELD_FLAGS);
uint32 npcflag = chr->GetUInt32Value(UNIT_NPC_FLAGS);
uint32 dyflag = chr->GetUInt32Value(UNIT_DYNAMIC_FLAGS);
PSendSysMessage(LANG_CURRENT_FACTION, chr->GetGUIDLow(), factionid, flag, npcflag, dyflag);
}
return true;
}
if (!chr)
{
SendSysMessage(LANG_NO_CHAR_SELECTED);
SetSentErrorMessage(true);
return false;
}
uint32 factionid;
if (!ExtractUint32KeyFromLink(&args, "Hfaction", factionid))
return false;
if (!sFactionTemplateStore.LookupEntry(factionid))
{
PSendSysMessage(LANG_WRONG_FACTION, factionid);
SetSentErrorMessage(true);
return false;
}
uint32 flag;
if (!ExtractOptUInt32(&args, flag, chr->GetUInt32Value(UNIT_FIELD_FLAGS)))
return false;
uint32 npcflag;
if (!ExtractOptUInt32(&args, npcflag, chr->GetUInt32Value(UNIT_NPC_FLAGS)))
return false;
uint32 dyflag;
if (!ExtractOptUInt32(&args, dyflag, chr->GetUInt32Value(UNIT_DYNAMIC_FLAGS)))
return false;
PSendSysMessage(LANG_YOU_CHANGE_FACTION, chr->GetGUIDLow(), factionid, flag, npcflag, dyflag);
chr->setFaction(factionid);
chr->SetUInt32Value(UNIT_FIELD_FLAGS, flag);
chr->SetUInt32Value(UNIT_NPC_FLAGS, npcflag);
chr->SetUInt32Value(UNIT_DYNAMIC_FLAGS, dyflag);
return true;
}
// Edit Player TP
bool ChatHandler::HandleModifyTalentCommand(char* args)
{
if (!*args)
return false;
int tp = atoi(args);
if (tp < 0)
return false;
Player* target = getSelectedPlayer();
if (!target)
{
SendSysMessage(LANG_NO_CHAR_SELECTED);
SetSentErrorMessage(true);
return false;
}
// check online security
if (HasLowerSecurity(target))
return false;
target->SetFreeTalentPoints(tp);
return true;
}
// Enable On\OFF all taxi paths
bool ChatHandler::HandleTaxiCheatCommand(char* args)
{
bool value;
if (!ExtractOnOff(&args, value))
{
SendSysMessage(LANG_USE_BOL);
SetSentErrorMessage(true);
return false;
}
Player* chr = getSelectedPlayer();
if (!chr)
chr = m_session->GetPlayer();
// check online security
else if (HasLowerSecurity(chr))
return false;
if (value)
{
chr->SetTaxiCheater(true);
PSendSysMessage(LANG_YOU_GIVE_TAXIS, GetNameLink(chr).c_str());
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_YOURS_TAXIS_ADDED, GetNameLink().c_str());
}
else
{
chr->SetTaxiCheater(false);
PSendSysMessage(LANG_YOU_REMOVE_TAXIS, GetNameLink(chr).c_str());
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_YOURS_TAXIS_REMOVED, GetNameLink().c_str());
}
return true;
}
// Edit Player Aspeed
bool ChatHandler::HandleModifyASpeedCommand(char* args)
{
if (!*args)
return false;
float modSpeed = (float)atof(args);
if (modSpeed > 10 || modSpeed < 0.1)
{
SendSysMessage(LANG_BAD_VALUE);
SetSentErrorMessage(true);
return false;
}
Player* chr = getSelectedPlayer();
if (chr == nullptr)
{
SendSysMessage(LANG_NO_CHAR_SELECTED);
SetSentErrorMessage(true);
return false;
}
// check online security
if (HasLowerSecurity(chr))
return false;
std::string chrNameLink = GetNameLink(chr);
if (chr->IsTaxiFlying())
{
PSendSysMessage(LANG_CHAR_IN_FLIGHT, chrNameLink.c_str());
SetSentErrorMessage(true);
return false;
}
PSendSysMessage(LANG_YOU_CHANGE_ASPEED, modSpeed, chrNameLink.c_str());
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_YOURS_ASPEED_CHANGED, GetNameLink().c_str(), modSpeed);
chr->UpdateSpeed(MOVE_WALK, true, modSpeed);
chr->UpdateSpeed(MOVE_RUN, true, modSpeed);
chr->UpdateSpeed(MOVE_SWIM, true, modSpeed);
// chr->UpdateSpeed(MOVE_TURN, true, modSpeed);
chr->UpdateSpeed(MOVE_FLIGHT, true, modSpeed);
return true;
}
// Edit Player Speed
bool ChatHandler::HandleModifySpeedCommand(char* args)
{
if (!*args)
return false;
float modSpeed = (float)atof(args);
if (modSpeed > 10 || modSpeed < 0.1)
{
SendSysMessage(LANG_BAD_VALUE);
SetSentErrorMessage(true);
return false;
}
Player* chr = getSelectedPlayer();
if (chr == nullptr)
{
SendSysMessage(LANG_NO_CHAR_SELECTED);
SetSentErrorMessage(true);
return false;
}
// check online security
if (HasLowerSecurity(chr))
return false;
std::string chrNameLink = GetNameLink(chr);
if (chr->IsTaxiFlying())
{
PSendSysMessage(LANG_CHAR_IN_FLIGHT, chrNameLink.c_str());
SetSentErrorMessage(true);
return false;
}
PSendSysMessage(LANG_YOU_CHANGE_SPEED, modSpeed, chrNameLink.c_str());
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_YOURS_SPEED_CHANGED, GetNameLink().c_str(), modSpeed);
chr->UpdateSpeed(MOVE_RUN, true, modSpeed);
return true;
}
// Edit Player Swim Speed
bool ChatHandler::HandleModifySwimCommand(char* args)
{
if (!*args)
return false;
float modSpeed = (float)atof(args);
if (modSpeed > 10.0f || modSpeed < 0.01f)
{
SendSysMessage(LANG_BAD_VALUE);
SetSentErrorMessage(true);
return false;
}
Player* chr = getSelectedPlayer();
if (chr == nullptr)
{
SendSysMessage(LANG_NO_CHAR_SELECTED);
SetSentErrorMessage(true);
return false;
}
// check online security
if (HasLowerSecurity(chr))
return false;
std::string chrNameLink = GetNameLink(chr);
if (chr->IsTaxiFlying())
{
PSendSysMessage(LANG_CHAR_IN_FLIGHT, chrNameLink.c_str());
SetSentErrorMessage(true);
return false;
}
PSendSysMessage(LANG_YOU_CHANGE_SWIM_SPEED, modSpeed, chrNameLink.c_str());
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_YOURS_SWIM_SPEED_CHANGED, GetNameLink().c_str(), modSpeed);
chr->UpdateSpeed(MOVE_SWIM, true, modSpeed);
return true;
}
// Edit Player Walk Speed
bool ChatHandler::HandleModifyBWalkCommand(char* args)
{
if (!*args)
return false;
float modSpeed = (float)atof(args);
if (modSpeed > 10.0f || modSpeed < 0.1f)
{
SendSysMessage(LANG_BAD_VALUE);
SetSentErrorMessage(true);
return false;
}
Player* chr = getSelectedPlayer();
if (chr == nullptr)
{
SendSysMessage(LANG_NO_CHAR_SELECTED);
SetSentErrorMessage(true);
return false;
}
// check online security
if (HasLowerSecurity(chr))
return false;
std::string chrNameLink = GetNameLink(chr);
if (chr->IsTaxiFlying())
{
PSendSysMessage(LANG_CHAR_IN_FLIGHT, chrNameLink.c_str());
SetSentErrorMessage(true);
return false;
}
PSendSysMessage(LANG_YOU_CHANGE_BACK_SPEED, modSpeed, chrNameLink.c_str());
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_YOURS_BACK_SPEED_CHANGED, GetNameLink().c_str(), modSpeed);
chr->UpdateSpeed(MOVE_RUN_BACK, true, modSpeed);
return true;
}
// Edit Player Fly
bool ChatHandler::HandleModifyFlyCommand(char* args)
{
if (!*args)
return false;
float modSpeed = (float)atof(args);
if (modSpeed > 10.0f || modSpeed < 0.1f)
{
SendSysMessage(LANG_BAD_VALUE);
SetSentErrorMessage(true);
return false;
}
Player* chr = getSelectedPlayer();
if (chr == nullptr)
{
SendSysMessage(LANG_NO_CHAR_SELECTED);
SetSentErrorMessage(true);
return false;
}
// check online security
if (HasLowerSecurity(chr))
return false;
PSendSysMessage(LANG_YOU_CHANGE_FLY_SPEED, modSpeed, GetNameLink(chr).c_str());
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_YOURS_FLY_SPEED_CHANGED, GetNameLink().c_str(), modSpeed);
chr->UpdateSpeed(MOVE_FLIGHT, true, modSpeed);
return true;
}
// Edit Player Scale
bool ChatHandler::HandleModifyScaleCommand(char* args)
{
if (!*args)
return false;
float Scale = (float)atof(args);
if (Scale > 10.0f || Scale <= 0.0f)
{
SendSysMessage(LANG_BAD_VALUE);
SetSentErrorMessage(true);
return false;
}
Unit* target = getSelectedUnit();
if (target == nullptr)
{
SendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
SetSentErrorMessage(true);
return false;
}
if (target->GetTypeId() == TYPEID_PLAYER)
{
// check online security
if (HasLowerSecurity((Player*)target))
return false;
PSendSysMessage(LANG_YOU_CHANGE_SIZE, Scale, GetNameLink((Player*)target).c_str());
if (needReportToTarget((Player*)target))
ChatHandler((Player*)target).PSendSysMessage(LANG_YOURS_SIZE_CHANGED, GetNameLink().c_str(), Scale);
}
target->SetObjectScale(Scale);
target->UpdateModelData();
return true;
}
// Enable Player mount
bool ChatHandler::HandleModifyMountCommand(char* args)
{
if (!*args)
return false;
uint16 mId = 1147;
float speed = (float)15;
uint32 num = atoi(args);
switch (num)
{
case 1:
mId = 14340;
break;
case 2:
mId = 4806;
break;
case 3:
mId = 6471;
break;
case 4:
mId = 12345;
break;
case 5:
mId = 6472;
break;
case 6:
mId = 6473;
break;
case 7:
mId = 10670;
break;
case 8:
mId = 10719;
break;
case 9:
mId = 10671;
break;
case 10:
mId = 10672;
break;
case 11:
mId = 10720;
break;
case 12:
mId = 14349;
break;
case 13:
mId = 11641;
break;
case 14:
mId = 12244;
break;
case 15:
mId = 12242;
break;
case 16:
mId = 14578;
break;
case 17:
mId = 14579;
break;
case 18:
mId = 14349;
break;
case 19:
mId = 12245;
break;
case 20:
mId = 14335;
break;
case 21:
mId = 207;
break;
case 22:
mId = 2328;
break;
case 23:
mId = 2327;
break;
case 24:
mId = 2326;
break;
case 25:
mId = 14573;
break;
case 26:
mId = 14574;
break;
case 27:
mId = 14575;
break;
case 28:
mId = 604;
break;
case 29:
mId = 1166;
break;
case 30:
mId = 2402;
break;
case 31:
mId = 2410;
break;
case 32:
mId = 2409;
break;
case 33:
mId = 2408;
break;
case 34:
mId = 2405;
break;
case 35:
mId = 14337;
break;
case 36:
mId = 6569;
break;
case 37:
mId = 10661;
break;
case 38:
mId = 10666;
break;
case 39:
mId = 9473;
break;
case 40:
mId = 9476;
break;
case 41:
mId = 9474;
break;
case 42:
mId = 14374;
break;
case 43:
mId = 14376;
break;
case 44:
mId = 14377;
break;
case 45:
mId = 2404;
break;
case 46:
mId = 2784;
break;
case 47:
mId = 2787;
break;
case 48:
mId = 2785;
break;
case 49:
mId = 2736;
break;
case 50:
mId = 2786;
break;
case 51:
mId = 14347;
break;
case 52:
mId = 14346;
break;
case 53:
mId = 14576;
break;
case 54:
mId = 9695;
break;
case 55:
mId = 9991;
break;
case 56:
mId = 6448;
break;
case 57:
mId = 6444;
break;
case 58:
mId = 6080;
break;
case 59:
mId = 6447;
break;
case 60:
mId = 4805;
break;
case 61:
mId = 9714;
break;
case 62:
mId = 6448;
break;
case 63:
mId = 6442;
break;
case 64:
mId = 14632;
break;
case 65:
mId = 14332;
break;
case 66:
mId = 14331;
break;
case 67:
mId = 8469;
break;
case 68:
mId = 2830;
break;
case 69:
mId = 2346;
break;
default:
SendSysMessage(LANG_NO_MOUNT);
SetSentErrorMessage(true);
return false;
}
Player* chr = getSelectedPlayer();
if (!chr)
{
SendSysMessage(LANG_NO_CHAR_SELECTED);
SetSentErrorMessage(true);
return false;
}
// check online security
if (HasLowerSecurity(chr))
return false;
PSendSysMessage(LANG_YOU_GIVE_MOUNT, GetNameLink(chr).c_str());
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_MOUNT_GIVED, GetNameLink().c_str());
chr->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP);
chr->Mount(mId);
WorldPacket data(SMSG_FORCE_RUN_SPEED_CHANGE, (8 + 4 + 1 + 4));
data << chr->GetPackGUID();
data << (uint32)0;
data << (uint8)0; // new 2.1.0
data << float(speed);
chr->SendMessageToSet(&data, true);
data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, (8 + 4 + 4));
data << chr->GetPackGUID();
data << (uint32)0;
data << float(speed);
chr->SendMessageToSet(&data, true);
return true;
}
// Edit Player money
bool ChatHandler::HandleModifyMoneyCommand(char* args)
{
if (!*args)
return false;
Player* chr = getSelectedPlayer();
if (chr == nullptr)
{
SendSysMessage(LANG_NO_CHAR_SELECTED);
SetSentErrorMessage(true);
return false;
}
// check online security
if (HasLowerSecurity(chr))
return false;
int32 addmoney = atoi(args);
uint32 moneyuser = chr->GetMoney();
if (addmoney < 0)
{
int32 newmoney = int32(moneyuser) + addmoney;
DETAIL_LOG(GetMangosString(LANG_CURRENT_MONEY), moneyuser, addmoney, newmoney);
if (newmoney <= 0)
{
PSendSysMessage(LANG_YOU_TAKE_ALL_MONEY, GetNameLink(chr).c_str());
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_YOURS_ALL_MONEY_GONE, GetNameLink().c_str());
chr->SetMoney(0);
}
else
{
if (newmoney > MAX_MONEY_AMOUNT)
newmoney = MAX_MONEY_AMOUNT;
PSendSysMessage(LANG_YOU_TAKE_MONEY, abs(addmoney), GetNameLink(chr).c_str());
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_YOURS_MONEY_TAKEN, GetNameLink().c_str(), abs(addmoney));
chr->SetMoney(newmoney);
}
}
else
{
PSendSysMessage(LANG_YOU_GIVE_MONEY, addmoney, GetNameLink(chr).c_str());
if (needReportToTarget(chr))
ChatHandler(chr).PSendSysMessage(LANG_YOURS_MONEY_GIVEN, GetNameLink().c_str(), addmoney);
if (addmoney >= MAX_MONEY_AMOUNT)
chr->SetMoney(MAX_MONEY_AMOUNT);
else
chr->ModifyMoney(addmoney);
}
DETAIL_LOG(GetMangosString(LANG_NEW_MONEY), moneyuser, addmoney, chr->GetMoney());
return true;
}
bool ChatHandler::HandleModifyHonorCommand(char* args)
{
if (!*args)
return false;
Player* target = getSelectedPlayer();
if (!target)
{
SendSysMessage(LANG_PLAYER_NOT_FOUND);
SetSentErrorMessage(true);
return false;
}
// check online security
if (HasLowerSecurity(target))
return false;
int32 amount = (int32)atoi(args);
target->ModifyHonorPoints(amount);
PSendSysMessage(LANG_COMMAND_MODIFY_HONOR, GetNameLink(target).c_str(), target->GetHonorPoints());
return true;
}
bool ChatHandler::HandleTeleCommand(char* args)
{
if (!*args)
return false;
Player* _player = m_session->GetPlayer();
// id, or string, or [name] Shift-click form |color|Htele:id|h[name]|h|r
GameTele const* tele = ExtractGameTeleFromLink(&args);
if (!tele)
{
SendSysMessage(LANG_COMMAND_TELE_NOTFOUND);
SetSentErrorMessage(true);
return false;
}
return HandleGoHelper(_player, tele->mapId, tele->position_x, tele->position_y, &tele->position_z, &tele->orientation);
}
bool ChatHandler::HandleLookupAreaCommand(char* args)
{
if (!*args)
return false;
std::string namepart = args;
std::wstring wnamepart;
if (!Utf8toWStr(namepart, wnamepart))
return false;
uint32 counter = 0; // Counter for figure out that we found smth.
// converting string that we try to find to lower case
wstrToLower(wnamepart);
// Search in AreaTable.dbc
for (uint32 areaflag = 0; areaflag < sAreaStore.GetNumRows(); ++areaflag)
{
AreaTableEntry const* areaEntry = sAreaStore.LookupEntry(areaflag);
if (areaEntry)
{
int loc = GetSessionDbcLocale();
std::string name = areaEntry->area_name[loc];
if (name.empty())
continue;
if (!Utf8FitTo(name, wnamepart))
{
loc = 0;
for (; loc < MAX_LOCALE; ++loc)
{
if (loc == GetSessionDbcLocale())
continue;
name = areaEntry->area_name[loc];
if (name.empty())
continue;
if (Utf8FitTo(name, wnamepart))
break;
}
}
if (loc < MAX_LOCALE)
{
// send area in "id - [name]" format
std::ostringstream ss;
if (m_session)
ss << areaEntry->ID << " - |cffffffff|Harea:" << areaEntry->ID << "|h[" << name << " " << localeNames[loc] << "]|h|r";
else
ss << areaEntry->ID << " - " << name << " " << localeNames[loc];
SendSysMessage(ss.str().c_str());
++counter;
}
}
}
if (counter == 0) // if counter == 0 then we found nth
SendSysMessage(LANG_COMMAND_NOAREAFOUND);
return true;
}
// Find tele in game_tele order by name
bool ChatHandler::HandleLookupTeleCommand(char* args)
{
if (!*args)
{
SendSysMessage(LANG_COMMAND_TELE_PARAMETER);
SetSentErrorMessage(true);
return false;
}
std::string namepart = args;
std::wstring wnamepart;
if (!Utf8toWStr(namepart, wnamepart))
return false;
// converting string that we try to find to lower case
wstrToLower(wnamepart);
std::ostringstream reply;
GameTeleMap const& teleMap = sObjectMgr.GetGameTeleMap();
for (GameTeleMap::const_iterator itr = teleMap.begin(); itr != teleMap.end(); ++itr)
{
GameTele const* tele = &itr->second;
if (tele->wnameLow.find(wnamepart) == std::wstring::npos)
continue;
if (m_session)
reply << " |cffffffff|Htele:" << itr->first << "|h[" << tele->name << "]|h|r\n";
else
reply << " " << itr->first << " " << tele->name << "\n";
}
if (reply.str().empty())
SendSysMessage(LANG_COMMAND_TELE_NOLOCATION);
else
PSendSysMessage(LANG_COMMAND_TELE_LOCATION, reply.str().c_str());
return true;
}
// Enable\Dissable accept whispers (for GM)
bool ChatHandler::HandleWhispersCommand(char* args)
{
if (!*args)
{
PSendSysMessage(LANG_COMMAND_WHISPERACCEPTING, GetOnOffStr(m_session->GetPlayer()->isAcceptWhispers()));
return true;
}
bool value;
if (!ExtractOnOff(&args, value))
{
SendSysMessage(LANG_USE_BOL);
SetSentErrorMessage(true);
return false;
}
// whisper on
if (value)
{
m_session->GetPlayer()->SetAcceptWhispers(true);
SendSysMessage(LANG_COMMAND_WHISPERON);
}
// whisper off
else
{
m_session->GetPlayer()->SetAcceptWhispers(false);
SendSysMessage(LANG_COMMAND_WHISPEROFF);
}
return true;
}
// Save all players in the world
bool ChatHandler::HandleSaveAllCommand(char* /*args*/)
{
sObjectAccessor.SaveAllPlayers();
SendSysMessage(LANG_PLAYERS_SAVED);
return true;
}
// Send mail by command
bool ChatHandler::HandleSendMailCommand(char* args)
{
// format: name "subject text" "mail text"
Player* target;
ObjectGuid target_guid;
std::string target_name;
if (!ExtractPlayerTarget(&args, &target, &target_guid, &target_name))
return false;
MailDraft draft;
// fill draft
if (!HandleSendMailHelper(draft, args))
return false;
// from console show nonexistent sender
MailSender sender(MAIL_NORMAL, m_session ? m_session->GetPlayer()->GetObjectGuid().GetCounter() : 0, MAIL_STATIONERY_GM);
draft.SendMailTo(MailReceiver(target, target_guid), sender);
std::string nameLink = playerLink(target_name);
PSendSysMessage(LANG_MAIL_SENT, nameLink.c_str());
return true;
}
// teleport player to given game_tele.entry
bool ChatHandler::HandleTeleNameCommand(char* args)
{
char* nameStr = ExtractOptNotLastArg(&args);
Player* target;
ObjectGuid target_guid;
std::string target_name;
if (!ExtractPlayerTarget(&nameStr, &target, &target_guid, &target_name))
return false;
// id, or string, or [name] Shift-click form |color|Htele:id|h[name]|h|r
GameTele const* tele = ExtractGameTeleFromLink(&args);
if (!tele)
{
SendSysMessage(LANG_COMMAND_TELE_NOTFOUND);
SetSentErrorMessage(true);
return false;
}
if (target)
{
// check online security
if (HasLowerSecurity(target))
return false;
std::string chrNameLink = playerLink(target_name);
if (target->IsBeingTeleported() == true)
{
PSendSysMessage(LANG_IS_TELEPORTED, chrNameLink.c_str());
SetSentErrorMessage(true);
return false;
}
PSendSysMessage(LANG_TELEPORTING_TO, chrNameLink.c_str(), "", tele->name.c_str());
if (needReportToTarget(target))
ChatHandler(target).PSendSysMessage(LANG_TELEPORTED_TO_BY, GetNameLink().c_str());
return HandleGoHelper(target, tele->mapId, tele->position_x, tele->position_y, &tele->position_z, &tele->orientation);
}
else
{
// check offline security
if (HasLowerSecurity(nullptr, target_guid))
return false;
std::string nameLink = playerLink(target_name);
PSendSysMessage(LANG_TELEPORTING_TO, nameLink.c_str(), GetMangosString(LANG_OFFLINE), tele->name.c_str());
Player::SavePositionInDB(target_guid, tele->mapId,
tele->position_x, tele->position_y, tele->position_z, tele->orientation,
sTerrainMgr.GetZoneId(tele->mapId, tele->position_x, tele->position_y, tele->position_z));
}
return true;
}
// Teleport group to given game_tele.entry
bool ChatHandler::HandleTeleGroupCommand(char* args)
{
if (!*args)
return false;
Player* player = getSelectedPlayer();
if (!player)
{
SendSysMessage(LANG_NO_CHAR_SELECTED);
SetSentErrorMessage(true);
return false;
}
// check online security
if (HasLowerSecurity(player))
return false;
// id, or string, or [name] Shift-click form |color|Htele:id|h[name]|h|r
GameTele const* tele = ExtractGameTeleFromLink(&args);
if (!tele)
{
SendSysMessage(LANG_COMMAND_TELE_NOTFOUND);
SetSentErrorMessage(true);
return false;
}
std::string nameLink = GetNameLink(player);
Group* grp = player->GetGroup();
if (!grp)
{
PSendSysMessage(LANG_NOT_IN_GROUP, nameLink.c_str());
SetSentErrorMessage(true);
return false;
}
for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next())
{
Player* pl = itr->getSource();
if (!pl || !pl->GetSession())
continue;
// check online security
if (HasLowerSecurity(pl))
return false;
std::string plNameLink = GetNameLink(pl);
if (pl->IsBeingTeleported())
{
PSendSysMessage(LANG_IS_TELEPORTED, plNameLink.c_str());
continue;
}
PSendSysMessage(LANG_TELEPORTING_TO, plNameLink.c_str(), "", tele->name.c_str());
if (needReportToTarget(pl))
ChatHandler(pl).PSendSysMessage(LANG_TELEPORTED_TO_BY, nameLink.c_str());
// stop flight if need
if (pl->IsTaxiFlying())
{
pl->GetMotionMaster()->MovementExpired();
pl->m_taxi.ClearTaxiDestinations();
}
// save only in non-flight case
else
pl->SaveRecallPosition();
pl->TeleportTo(tele->mapId, tele->position_x, tele->position_y, tele->position_z, tele->orientation);
}
return true;
}
// Summon group of player
bool ChatHandler::HandleGroupgoCommand(char* args)
{
Player* target;
if (!ExtractPlayerTarget(&args, &target))
return false;
// check online security
if (HasLowerSecurity(target))
return false;
Group* grp = target->GetGroup();
std::string nameLink = GetNameLink(target);
if (!grp)
{
PSendSysMessage(LANG_NOT_IN_GROUP, nameLink.c_str());
SetSentErrorMessage(true);
return false;
}
Player* player = m_session->GetPlayer();
Map* gmMap = player->GetMap();
bool to_instance = gmMap->Instanceable();
// we are in instance, and can summon only player in our group with us as lead
if (to_instance && (
!player->GetGroup() || (grp->GetLeaderGuid() != player->GetObjectGuid()) ||
(player->GetGroup()->GetLeaderGuid() != player->GetObjectGuid())))
// the last check is a bit excessive, but let it be, just in case
{
SendSysMessage(LANG_CANNOT_SUMMON_TO_INST);
SetSentErrorMessage(true);
return false;
}
for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next())
{
Player* pl = itr->getSource();
if (!pl || pl == m_session->GetPlayer() || !pl->GetSession())
continue;
// check online security
if (HasLowerSecurity(pl))
return false;
std::string plNameLink = GetNameLink(pl);
if (pl->IsBeingTeleported() == true)
{
PSendSysMessage(LANG_IS_TELEPORTED, plNameLink.c_str());
SetSentErrorMessage(true);
return false;
}
if (to_instance)
{
Map* plMap = pl->GetMap();
if (plMap->Instanceable() && plMap->GetInstanceId() != gmMap->GetInstanceId())
{
// cannot summon from instance to instance
PSendSysMessage(LANG_CANNOT_SUMMON_TO_INST, plNameLink.c_str());
SetSentErrorMessage(true);
return false;
}
}
PSendSysMessage(LANG_SUMMONING, plNameLink.c_str(), "");
if (needReportToTarget(pl))
ChatHandler(pl).PSendSysMessage(LANG_SUMMONED_BY, nameLink.c_str());
// stop flight if need
if (pl->IsTaxiFlying())
{
pl->GetMotionMaster()->MovementExpired();
pl->m_taxi.ClearTaxiDestinations();
}
// save only in non-flight case
else
pl->SaveRecallPosition();
// before GM
float x, y, z;
m_session->GetPlayer()->GetClosePoint(x, y, z, pl->GetObjectBoundingRadius());
pl->TeleportTo(m_session->GetPlayer()->GetMapId(), x, y, z, pl->GetOrientation());
}
return true;
}
bool ChatHandler::HandleGoHelper(Player* player, uint32 mapid, float x, float y, float const* zPtr, float const* ortPtr)
{
float z;
float ort = player->GetOrientation();
if (zPtr)
{
z = *zPtr;
if (ortPtr)
ort = *ortPtr;
// check full provided coordinates
if (!MapManager::IsValidMapCoord(mapid, x, y, z, ort))
{
PSendSysMessage(LANG_INVALID_TARGET_COORD, x, y, mapid);
SetSentErrorMessage(true);
return false;
}
}
else
{
// we need check x,y before ask Z or can crash at invalide coordinates
if (!MapManager::IsValidMapCoord(mapid, x, y))
{
PSendSysMessage(LANG_INVALID_TARGET_COORD, x, y, mapid);
SetSentErrorMessage(true);
return false;
}
TerrainInfo const* map = sTerrainMgr.LoadTerrain(mapid);
z = map->GetWaterOrGroundLevel(x, y, MAX_HEIGHT);
}
// stop flight if need
if (player->IsTaxiFlying())
{
player->GetMotionMaster()->MovementExpired();
player->m_taxi.ClearTaxiDestinations();
}
// save only in non-flight case
else
player->SaveRecallPosition();
player->TeleportTo(mapid, x, y, z, ort);
return true;
}
bool ChatHandler::HandleGoTaxinodeCommand(char* args)
{
Player* _player = m_session->GetPlayer();
uint32 nodeId;
if (!ExtractUint32KeyFromLink(&args, "Htaxinode", nodeId))
return false;
TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(nodeId);
if (!node)
{
PSendSysMessage(LANG_COMMAND_GOTAXINODENOTFOUND, nodeId);
SetSentErrorMessage(true);
return false;
}
if (node->x == 0.0f && node->y == 0.0f && node->z == 0.0f)
{
PSendSysMessage(LANG_INVALID_TARGET_COORD, node->x, node->y, node->map_id);
SetSentErrorMessage(true);
return false;
}
return HandleGoHelper(_player, node->map_id, node->x, node->y, &node->z);
}
bool ChatHandler::HandleGoCommand(char* args)
{
if (!*args)
return false;
Player* _player = m_session->GetPlayer();
uint32 mapid;
float x, y, z;
// raw coordinates case
if (ExtractFloat(&args, x))
{
if (!ExtractFloat(&args, y))
return false;
if (!ExtractFloat(&args, z))
return false;
if (!ExtractOptUInt32(&args, mapid, _player->GetMapId()))
return false;
}
// link case
else if (!ExtractLocationFromLink(&args, mapid, x, y, z))
return false;
return HandleGoHelper(_player, mapid, x, y, &z);
}
// teleport at coordinates
bool ChatHandler::HandleGoXYCommand(char* args)
{
Player* _player = m_session->GetPlayer();
float x;
if (!ExtractFloat(&args, x))
return false;
float y;
if (!ExtractFloat(&args, y))
return false;
uint32 mapid;
if (!ExtractOptUInt32(&args, mapid, _player->GetMapId()))
return false;
return HandleGoHelper(_player, mapid, x, y);
}
// teleport at coordinates, including Z
bool ChatHandler::HandleGoXYZCommand(char* args)
{
Player* _player = m_session->GetPlayer();
float x;
if (!ExtractFloat(&args, x))
return false;
float y;
if (!ExtractFloat(&args, y))
return false;
float z;
if (!ExtractFloat(&args, z))
return false;
uint32 mapid;
if (!ExtractOptUInt32(&args, mapid, _player->GetMapId()))
return false;
return HandleGoHelper(_player, mapid, x, y, &z);
}
// teleport at coordinates
bool ChatHandler::HandleGoZoneXYCommand(char* args)
{
Player* _player = m_session->GetPlayer();
float x;
if (!ExtractFloat(&args, x))
return false;
float y;
if (!ExtractFloat(&args, y))
return false;
uint32 areaid;
if (*args)
{
if (!ExtractUint32KeyFromLink(&args, "Harea", areaid))
return false;
}
else
areaid = _player->GetZoneId();
AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(areaid);
if (x < 0 || x > 100 || y < 0 || y > 100 || !areaEntry)
{
PSendSysMessage(LANG_INVALID_ZONE_COORD, x, y, areaid);
SetSentErrorMessage(true);
return false;
}
// update to parent zone if exist (client map show only zones without parents)
AreaTableEntry const* zoneEntry = areaEntry->zone ? GetAreaEntryByAreaID(areaEntry->zone) : areaEntry;
MapEntry const* mapEntry = sMapStore.LookupEntry(zoneEntry->mapid);
if (mapEntry->Instanceable())
{
PSendSysMessage(LANG_INVALID_ZONE_MAP, areaEntry->ID, areaEntry->area_name[GetSessionDbcLocale()],
mapEntry->MapID, mapEntry->name[GetSessionDbcLocale()]);
SetSentErrorMessage(true);
return false;
}
if (!Zone2MapCoordinates(x, y, zoneEntry->ID))
{
PSendSysMessage(LANG_INVALID_ZONE_MAP, areaEntry->ID, areaEntry->area_name[GetSessionDbcLocale()],
mapEntry->MapID, mapEntry->name[GetSessionDbcLocale()]);
SetSentErrorMessage(true);
return false;
}
return HandleGoHelper(_player, mapEntry->MapID, x, y);
}
// teleport to grid
bool ChatHandler::HandleGoGridCommand(char* args)
{
Player* _player = m_session->GetPlayer();
float grid_x;
if (!ExtractFloat(&args, grid_x))
return false;
float grid_y;
if (!ExtractFloat(&args, grid_y))
return false;
uint32 mapid;
if (!ExtractOptUInt32(&args, mapid, _player->GetMapId()))
return false;
// center of grid
float x = (grid_x - CENTER_GRID_ID + 0.5f) * SIZE_OF_GRIDS;
float y = (grid_y - CENTER_GRID_ID + 0.5f) * SIZE_OF_GRIDS;
return HandleGoHelper(_player, mapid, x, y);
}
bool ChatHandler::HandleModifyDrunkCommand(char* args)
{
if (!*args) return false;
uint32 drunklevel = (uint32)atoi(args);
if (drunklevel > 100)
drunklevel = 100;
uint16 drunkMod = drunklevel * 0xFFFF / 100;
m_session->GetPlayer()->SetDrunkValue(drunkMod);
return true;
}
bool ChatHandler::HandleSetViewCommand(char* /*args*/)
{
if (Unit* unit = getSelectedUnit())
m_session->GetPlayer()->GetCamera().SetView(unit);
else
{
PSendSysMessage(LANG_SELECT_CHAR_OR_CREATURE);
SetSentErrorMessage(true);
return false;
}
return true;
}
| Poxleit/s-core | src/game/Level1.cpp | C++ | gpl-2.0 | 61,221 |
<?php
#**************************************************************************
# openSIS is a free student information system for public and non-public
# schools from Open Solutions for Education, Inc. web: www.os4ed.com
#
# openSIS is web-based, open source, and comes packed with features that
# include student demographic info, scheduling, grade book, attendance,
# report cards, eligibility, transcripts, parent portal,
# student portal and more.
#
# Visit the openSIS web site at http://www.opensis.com to learn more.
# If you have question regarding this system or the license, please send
# an email to info@os4ed.com.
#
# This program is released under the terms of the GNU General Public License as
# published by the Free Software Foundation, version 2 of the License.
# See license.txt.
#
# 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('../../Redirect_modules.php');
if($_REQUEST['month_date'] && $_REQUEST['day_date'] && $_REQUEST['year_date'])
while(!VerifyDate($date = $_REQUEST['day_date'].'-'.$_REQUEST['month_date'].'-'.$_REQUEST['year_date']))
$_REQUEST['day_date']--;
else
{
$_REQUEST['day_date'] = date('d');
$_REQUEST['month_date'] = strtoupper(date('M'));
$_REQUEST['year_date'] = date('y');
$date = $_REQUEST['day_date'].'-'.$_REQUEST['month_date'].'-'.$_REQUEST['year_date'];
}
DrawBC(""._('Attendance')." > ".ProgramTitle());
//$QI = DBQuery("SELECT PERIOD_ID,TITLE FROM school_periods WHERE SCHOOL_ID='".UserSchool()."' AND SYEAR='".UserSyear()."' ORDER BY SORT_ORDER ");
$QI = DBQuery('SELECT sp.PERIOD_ID,sp.TITLE FROM school_periods sp WHERE sp.SCHOOL_ID=\''.UserSchool().'\' AND sp.SYEAR=\''.UserSyear().'\' AND EXISTS (SELECT \'\' FROM course_periods WHERE SYEAR=sp.SYEAR AND PERIOD_ID=sp.PERIOD_ID AND DOES_ATTENDANCE=\'Y\') ORDER BY sp.SORT_ORDER');
$periods_RET = DBGet($QI,array(),array('PERIOD_ID'));
$period_select = "<SELECT name=period><OPTION value=''>All</OPTION>";
foreach($periods_RET as $id=>$period)
$period_select .= "<OPTION value=$id".(($_REQUEST['period']==$id)?' SELECTED':'').">".$period[1]['TITLE']."</OPTION>";
$period_select .= "</SELECT>";
echo "<FORM action=Modules.php?modname=$_REQUEST[modname] method=POST>";
DrawHeaderHome('<table><tr><td>'.PrepareDateSchedule($date,'_date',false,array('submit'=>true)).'</td><td> - </td><td>'.$period_select.'</td><td> : <INPUT type=submit class=btn_medium value='._('Go').'></td></tr></table>');
echo '</FORM>';
$day = date('D',strtotime($date));
switch($day)
{
case 'Sun':
$day = 'U';
break;
case 'Thu':
$day = 'H';
break;
default:
$day = substr($day,0,1);
break;
}
/*$sql = "SELECT concat(s.LAST_NAME,',',s.FIRST_NAME, ' ') AS FULL_NAME,sp.TITLE,cp.PERIOD_ID,s.STAFF_ID
FROM staff s,course_periods cp,school_periods sp
WHERE
sp.PERIOD_ID = cp.PERIOD_ID
AND cp.TEACHER_ID=s.STAFF_ID AND cp.MARKING_PERIOD_ID IN (".GetAllMP('QTR',GetCurrentMP('QTR',$date)).")
AND cp.SYEAR='".UserSyear()."' AND cp.SCHOOL_ID='".UserSchool()."' AND s.PROFILE='teacher'
AND cp.DOES_ATTENDANCE='Y' AND instr(cp.DAYS,'$day')>0".(($_REQUEST['period'])?" AND cp.PERIOD_ID='$_REQUEST[period]'":'')."
AND NOT EXISTS (SELECT '' FROM attendance_completed ac WHERE ac.STAFF_ID=cp.TEACHER_ID AND ac.SCHOOL_DATE='".date('Y-m-d',strtotime($date))."' AND ac.PERIOD_ID=sp.PERIOD_ID)
";*/
$p=optional_param('period','',PARAM_SPCL);
$current_mp = GetCurrentMP('QTR',$date);
$MP_TYPE='QTR';
if(!$current_mp){
$current_mp = GetCurrentMP('SEM',$date);
$MP_TYPE='SEM';
}
if(!$current_mp){
$current_mp = GetCurrentMP('FY',$date);
$MP_TYPE='FY';
}
$sql = 'SELECT concat(s.LAST_NAME,\',\',s.FIRST_NAME, \' \') AS FULL_NAME,sp.TITLE,cp.PERIOD_ID,s.STAFF_ID
FROM staff s,course_periods cp,school_periods sp,attendance_calendar acc
WHERE
sp.PERIOD_ID = cp.PERIOD_ID
AND acc.CALENDAR_id=cp.CALENDAR_ID
AND acc.SCHOOL_DATE=\''.date('Y-m-d',strtotime($date)).'\'
AND cp.TEACHER_ID=s.STAFF_ID AND cp.MARKING_PERIOD_ID IN ('.GetAllMP($MP_TYPE,$current_mp).')
AND cp.SYEAR=\''.UserSyear().'\' AND cp.SCHOOL_ID=\''.UserSchool().'\' AND s.PROFILE=\'teacher\'
AND cp.DOES_ATTENDANCE=\'Y\' AND instr(cp.DAYS,\''.$day.'\')>0'.(($p)?' AND cp.PERIOD_ID=\''.$p.'\'':'').'
AND NOT EXISTS (SELECT \'\' FROM attendance_completed ac WHERE ac.STAFF_ID=cp.TEACHER_ID AND ac.SCHOOL_DATE=\''.date('Y-m-d',strtotime($date)).'\' AND ac.PERIOD_ID=sp.PERIOD_ID)
';
$RET = DBGet(DBQuery($sql),array(),array('STAFF_ID','PERIOD_ID'));
$i= 0;
if(count($RET))
{
foreach($RET as $staff_id=>$periods)
{
$i++;
$staff_RET[$i]['FULL_NAME'] = $periods[key($periods)][1]['FULL_NAME'];
foreach($periods as $period_id=>$period)
{
$staff_RET[$i][$period_id] = '<IMG SRC=assets/false.png>';
}
}
}
$columns = array('FULL_NAME'=>_('Teacher'));
if(!$_REQUEST['period'])
{
foreach($periods_RET as $id=>$period)
$columns[$id] = $period[1]['TITLE'];
}
else
$period_title = $periods_RET[$_REQUEST['period']][1]['TITLE'].' ';
echo '<div style="overflow:auto; overflow-x:auto; overflow-y:auto; height:400px; width:830px;">';
ListOutput($staff_RET,$columns,_('Teacher who hasn\'t taken ').$period_title._('attendance'),_('Teachers who haven\'t taken ').$period_title._('attendance'));
echo '</div>';
?>
| MjAbuz/opensis-ml | modules/Attendance/TeacherCompletion.php | PHP | gpl-2.0 | 5,789 |
subroutine cumxtp_DZ(A,devPtrX,C,M)
!========================================================================!
!!!!!!!! Hace C=A*X para matrices cuadradas
!========================================================================!
implicit none
integer*8 devPtrA
integer*8 devPtrScratch
integer,intent(in) :: M
integer*8,intent(in) :: devPtrX
REAL*8, dimension (:,:), ALLOCATABLE :: scratch1,scratch2
integer i,j,stat
external CUBLAS_INIT, CUBLAS_SET_MATRIX, CUBLAS_GET_MATRIX
external CUBLAS_SHUTDOWN, CUBLAS_ALLOC, CUBLAS_CGEMM,CUBLAS_ZGEMM
integer CUBLAS_ALLOC, CUBLAS_SET_MATRIX, CUBLAS_GET_MATRIX
integer CUBLAS_INIT,CUBLAS_CGEMM,CUBLAS_ZGEMM
integer sizeof_complex
COMPLEX*16 , intent(in) :: A(M,M)
COMPLEX*16, intent(out) :: C(M,M)
COMPLEX*16 :: alpha,beta
parameter(sizeof_complex=16)
!---------------------------------------------------------------------!
alpha=cmplx(1.0D0,0.0D0)
beta=cmplx(0.0D0,0.0D0)
!-------------------------ALLOCATION---------------------------------!
stat= CUBLAS_ALLOC(M*M, sizeof_complex, devPtrA)
if (stat.NE.0) then
write(*,*) "Matrix allocation failed -cumpx-1"
call CUBLAS_SHUTDOWN
stop
endif
stat= CUBLAS_ALLOC(M*M, sizeof_complex, devPtrScratch)
if (stat.NE.0) then
write(*,*) "Matrix allocation failed -cumpx-2"
call CUBLAS_SHUTDOWN
stop
endif
!--------------------------------------------------------------------!
stat = CUBLAS_SET_MATRIX(M,M,sizeof_complex,A,M,
> devPtrA,M)
if (stat.NE.0) then
write(*,*) "Matrix setting on device -cumpx-1"
call CUBLAS_SHUTDOWN
stop
endif
!-----------------------GEMM-----------------------------------------!
stat=CUBLAS_ZGEMM ('T','N',M,M,M,alpha,devPtrX
> ,M ,devPtrA,M, beta, devPtrScratch,M)
if (stat.NE.0) then
write(*,*) "ZGEMM failed -cumpx"
call CUBLAS_SHUTDOWN
stop
endif
!-----------------GETTING MATRIX FROM DEVICE-------------------------!
stat = CUBLAS_GET_MATRIX(M,M,sizeof_complex,devPtrScratch,M,
> C,M)
if (stat.NE.0) then
write(*,*) "Getting matrix from device failed -cumpx"
call CUBLAS_SHUTDOWN
stop
endif
!--------------------------------------------------------------------!
call CUBLAS_FREE ( devPtrA )
call CUBLAS_FREE ( devPtrScratch )
return
end subroutine
!====================================================================!
subroutine cumxtp_DC(A,devPtrX,C,M)
!========================================================================!
!!!!!!!! Hace C=A*X para matrices cuadradas
!========================================================================!
implicit none
integer*8 devPtrA
integer*8 devPtrScratch
integer,intent(in) :: M
integer*8,intent(in) :: devPtrX
REAL*8, dimension (:,:), ALLOCATABLE :: scratch1,scratch2
integer i,j,stat
external CUBLAS_INIT, CUBLAS_SET_MATRIX, CUBLAS_GET_MATRIX
external CUBLAS_SHUTDOWN, CUBLAS_ALLOC, CUBLAS_CGEMM,CUBLAS_ZGEMM
integer CUBLAS_ALLOC, CUBLAS_SET_MATRIX, CUBLAS_GET_MATRIX
integer CUBLAS_INIT,CUBLAS_CGEMM,CUBLAS_ZGEMM
integer sizeof_complex
COMPLEX*8 , intent(in) :: A(M,M)
COMPLEX*8, intent(out) :: C(M,M)
COMPLEX*8 :: alpha,beta
parameter(sizeof_complex=8)
!---------------------------------------------------------------------!
alpha=cmplx(1.0D0,0.0D0)
beta=cmplx(0.0D0,0.0D0)
!-------------------------ALLOCATION---------------------------------!
stat= CUBLAS_ALLOC(M*M, sizeof_complex, devPtrA)
if (stat.NE.0) then
write(*,*) "Matrix allocation failed -cumpx-1"
call CUBLAS_SHUTDOWN
stop
endif
stat= CUBLAS_ALLOC(M*M, sizeof_complex, devPtrScratch)
if (stat.NE.0) then
write(*,*) "Matrix allocation failed -cumpx-2"
call CUBLAS_SHUTDOWN
stop
endif
!--------------------------------------------------------------------!
stat = CUBLAS_SET_MATRIX(M,M,sizeof_complex,A,M,
> devPtrA,M)
if (stat.NE.0) then
write(*,*) "Matrix setting on device -cumpx-1"
call CUBLAS_SHUTDOWN
stop
endif
!-----------------------GEMM-----------------------------------------!
stat=CUBLAS_CGEMM ('T','N',M,M,M,alpha,devPtrX
> ,M ,devPtrA,M, beta, devPtrScratch,M)
if (stat.NE.0) then
write(*,*) "CGEMM failed -cumpx"
call CUBLAS_SHUTDOWN
stop
endif
!-----------------GETTING MATRIX FROM DEVICE-------------------------!
stat = CUBLAS_GET_MATRIX(M,M,sizeof_complex,devPtrScratch,M,
> C,M)
if (stat.NE.0) then
write(*,*) "Getting matrix from device failed -cumpx"
call CUBLAS_SHUTDOWN
stop
endif
!--------------------------------------------------------------------!
call CUBLAS_FREE ( devPtrA )
call CUBLAS_FREE ( devPtrScratch )
return
end subroutine
| ramirezfranciscof/lio | lioamber/cublasmath/cumxtp.f | FORTRAN | gpl-2.0 | 5,134 |
/*
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
*/
#pragma once
#include <JavaScriptCore/JavaScript.h>
#include <wtf/Optional.h>
#include <wtf/RefCounted.h>
namespace WTR {
class JSWrappable : public RefCounted<JSWrappable> {
public:
virtual ~JSWrappable() { }
virtual JSClassRef wrapperClass() = 0;
};
inline JSValueRef JSValueMakeBooleanOrNull(JSContextRef context, std::optional<bool> value)
{
return value ? JSValueMakeBoolean(context, value.value()) : JSValueMakeNull(context);
}
inline std::optional<bool> JSValueToNullableBoolean(JSContextRef context, JSValueRef value)
{
return JSValueIsUndefined(context, value) || JSValueIsNull(context, value) ? std::nullopt : std::optional<bool>(JSValueToBoolean(context, value));
}
inline JSValueRef JSValueMakeStringOrNull(JSContextRef context, JSStringRef stringOrNull)
{
return stringOrNull ? JSValueMakeString(context, stringOrNull) : JSValueMakeNull(context);
}
} // namespace WTR
| teamfx/openjfx-8u-dev-rt | modules/web/src/main/native/Tools/TestRunnerShared/Bindings/JSWrappable.h | C | gpl-2.0 | 2,264 |
/*++
linux/drivers/media/video/wmt_v4l2/sensors/flash/flash_eup2471.c
Copyright (c) 2013 WonderMedia Technologies, Inc.
This program is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software Foundation,
either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
WonderMedia Technologies, Inc.
10F, 529, Chung-Cheng Road, Hsin-Tien, Taipei 231, R.O.C.
--*/
/* wmt.camera.flash <flash>:<en>:<flen>
* wmt.camera.flash eup2471:3:2
*/
#include <linux/gpio.h>
#include <mach/wmt_env.h>
#include "../cmos-subdev.h"
#include "../../wmt-vid.h"
#include "flash.h"
struct eup2471_struct {
int gpio_en;
int gpio_flen;
};
static struct eup2471_struct *eup;
#define EUP2471_I2CADDR 0x37
/*
* TODO register flash as a subdev
*/
static int flash_dev_set_mode(int mode)
{
if (!eup)
return -EINVAL;
switch (mode) {
case FLASH_MODE_OFF:
gpio_direction_output(eup->gpio_en, 0);
gpio_direction_output(eup->gpio_flen, 0);
break;
case FLASH_MODE_ON:
gpio_direction_output(eup->gpio_en, 1);
gpio_direction_output(eup->gpio_flen, 0);
msleep(1);
wmt_vid_i2c_write(EUP2471_I2CADDR, 0x00, 0x00);
wmt_vid_i2c_write(EUP2471_I2CADDR, 0x01, 0x33);
break;
case FLASH_MODE_STROBE:
gpio_direction_output(eup->gpio_en, 1);
gpio_direction_output(eup->gpio_flen, 1);
msleep(1);
gpio_direction_output(eup->gpio_flen, 0);
break;
case FLASH_MODE_TORCH:
gpio_direction_output(2, 0);
gpio_direction_output(3, 1);
msleep(1);
break;
default:
return -EINVAL;
}
return 0;
}
static int parse_charger_param(void)
{
char *dev_name = "eup2471";
char *env = "wmt.camera.flash";
char s[64];
size_t l = sizeof(s);
int gpio_en, gpio_flen;
int rc;
if (wmt_getsyspara(env, s, &l)) {
pr_err("read %s fail!\n", env);
return -EINVAL;
}
if (strncmp(s, dev_name, strlen(dev_name))) {
return -EINVAL;
}
rc = sscanf(s, "eup2471:%d:%d", &gpio_en, &gpio_flen);
if (rc < 2) {
pr_err("bad uboot env: %s\n", env);
return -EINVAL;
}
rc = gpio_request(gpio_en, "flash eup2471 en");
if (rc) {
pr_err("flash en gpio(%d) request failed\n", gpio_en);
return rc;
}
rc = gpio_request(gpio_flen, "flash eup2471 flen");
if (rc) {
pr_err("flash flen gpio(%d) request failed\n", gpio_flen);
gpio_free(gpio_en);
return rc;
}
eup = kzalloc(sizeof(*eup), GFP_KERNEL);
if (!eup)
return -ENOMEM;
eup->gpio_en = gpio_en;
eup->gpio_flen = gpio_flen;
printk("flash eup2471 register ok: en %d, flen %d\n",
eup->gpio_en, eup->gpio_flen);
return 0;
}
static int flash_dev_init(void)
{
if (eup)
return -EINVAL;
return parse_charger_param();
}
static void flash_dev_exit(void)
{
if (eup) {
gpio_free(eup->gpio_en);
gpio_free(eup->gpio_flen);
kfree(eup);
eup = NULL;
}
}
struct flash_dev flash_dev_eup2471 = {
.name = "eup2471",
.init = flash_dev_init,
.set_mode = flash_dev_set_mode,
.exit = flash_dev_exit,
};
| manishj-patel/netbook_kernel_3.4.5_plus | drivers/media/video/wmt_v4l2/sensors/flash/flash_eup2471.c | C | gpl-2.0 | 3,355 |
/*
* Copyright (c) 2013, NVIDIA CORPORATION. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __OV5693_H__
#define __OV5693_H__
#include <media/nvc.h>
#include <media/nvc_image.h>
#define OV5693_IOCTL_SET_MODE _IOW('o', 1, struct ov5693_mode)
#define OV5693_IOCTL_SET_FRAME_LENGTH _IOW('o', 2, __u32)
#define OV5693_IOCTL_SET_COARSE_TIME _IOW('o', 3, __u32)
#define OV5693_IOCTL_SET_GAIN _IOW('o', 4, __u16)
#define OV5693_IOCTL_GET_STATUS _IOR('o', 5, __u8)
#define OV5693_IOCTL_SET_BINNING _IOW('o', 6, __u8)
#define OV5693_IOCTL_TEST_PATTERN _IOW('o', 7, \
enum ov5693_test_pattern)
#define OV5693_IOCTL_SET_GROUP_HOLD _IOW('o', 8, struct ov5693_ae)
/* IOCTL to set the operating mode of camera.
* This can be either stereo , leftOnly or rightOnly */
#define OV5693_IOCTL_SET_CAMERA_MODE _IOW('o', 10, __u32)
#define OV5693_IOCTL_SYNC_SENSORS _IOW('o', 11, __u32)
#define OV5693_IOCTL_GET_FUSEID _IOR('o', 12, struct ov5693_fuseid)
struct ov5693_mode {
int res_x;
int res_y;
int fps;
__u32 frame_length;
__u32 coarse_time;
__u16 gain;
};
struct ov5693_ae {
__u32 frame_length;
__u8 frame_length_enable;
__u32 coarse_time;
__u8 coarse_time_enable;
__s32 gain;
__u8 gain_enable;
};
struct ov5693_fuseid {
__u32 size;
__u8 id[16];
};
/* See notes in the nvc.h file on the GPIO usage */
enum ov5693_gpio_type {
OV5693_GPIO_TYPE_PWRDN = 0,
};
struct ov5693_power_rail {
struct regulator *dvdd;
struct regulator *avdd;
struct regulator *dovdd;
};
struct ov5693_platform_data {
unsigned cfg;
unsigned num;
const char *dev_name;
unsigned gpio_count; /* see nvc.h GPIO notes */
struct nvc_gpio_pdata *gpio; /* see nvc.h GPIO notes */
unsigned lens_focal_length; /* / _INT2FLOAT_DIVISOR */
unsigned lens_max_aperture; /* / _INT2FLOAT_DIVISOR */
unsigned lens_fnumber; /* / _INT2FLOAT_DIVISOR */
unsigned lens_view_angle_h; /* / _INT2FLOAT_DIVISOR */
unsigned lens_view_angle_v; /* / _INT2FLOAT_DIVISOR */
int (*probe_clock)(unsigned long);
int (*power_on)(struct ov5693_power_rail *);
int (*power_off)(struct ov5693_power_rail *);
};
#endif /* __OV5693_H__ */
| Tegra4/android_kernel_hp_phobos-old | include/media/ov5693.h | C | gpl-2.0 | 2,801 |
/*
*
* Copyright (c) 1994
* Hewlett-Packard Company
*
* Copyright (c) 1996,1997
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1997
* Moscow Center for SPARC Technology
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
/* NOTE: This is an internal header file, included by other STL headers.
* You should not attempt to use it directly.
*/
#ifndef _STLP_INTERNAL_ALGO_H
#define _STLP_INTERNAL_ALGO_H
# ifndef _STLP_INTERNAL_ALGOBASE_H
# include <stl/_algobase.h>
# endif
# ifndef _STLP_INTERNAL_HEAP_H
# include <stl/_heap.h>
# endif
# ifndef _STLP_INTERNAL_ITERATOR_H
# include <stl/_iterator.h>
# endif
# ifndef _STLP_INTERNAL_FUNCTION_BASE_H
# include <stl/_function_base.h>
# endif
# ifdef __SUNPRO_CC
// remove() conflict
# include <cstdio>
# endif
_STLP_BEGIN_NAMESPACE
// for_each. Apply a function to every element of a range.
template <class _InputIter, class _Function>
_STLP_INLINE_LOOP _Function
for_each(_InputIter __first, _InputIter __last, _Function __f) {
for ( ; __first != __last; ++__first)
__f(*__first);
return __f;
}
// count_if
template <class _InputIter, class _Predicate>
_STLP_INLINE_LOOP _STLP_DIFFERENCE_TYPE(_InputIter)
count_if(_InputIter __first, _InputIter __last, _Predicate __pred) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
_STLP_DIFFERENCE_TYPE(_InputIter) __n = 0;
for ( ; __first != __last; ++__first)
if (__pred(*__first))
++__n;
return __n;
}
// adjacent_find.
template <class _ForwardIter, class _BinaryPredicate>
_STLP_INLINE_LOOP _ForwardIter
adjacent_find(_ForwardIter __first, _ForwardIter __last,
_BinaryPredicate __binary_pred) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
if (__first == __last)
return __last;
_ForwardIter __next = __first;
while(++__next != __last) {
if (__binary_pred(*__first, *__next))
return __first;
__first = __next;
}
return __last;
}
template <class _ForwardIter>
_STLP_INLINE_LOOP _ForwardIter
adjacent_find(_ForwardIter __first, _ForwardIter __last) {
return adjacent_find(__first, __last,
__equal_to(_STLP_VALUE_TYPE(__first, _ForwardIter)));
}
# ifndef _STLP_NO_ANACHRONISMS
template <class _InputIter, class _Tp, class _Size>
_STLP_INLINE_LOOP void
count(_InputIter __first, _InputIter __last, const _Tp& __val, _Size& __n) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
for ( ; __first != __last; ++__first)
if (*__first == __val)
++__n;
}
template <class _InputIter, class _Predicate, class _Size>
_STLP_INLINE_LOOP void
count_if(_InputIter __first, _InputIter __last, _Predicate __pred, _Size& __n) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
for ( ; __first != __last; ++__first)
if (__pred(*__first))
++__n;
}
# endif
template <class _ForwardIter1, class _ForwardIter2>
_ForwardIter1 search(_ForwardIter1 __first1, _ForwardIter1 __last1,
_ForwardIter2 __first2, _ForwardIter2 __last2);
// search_n. Search for __count consecutive copies of __val.
template <class _ForwardIter, class _Integer, class _Tp>
_ForwardIter search_n(_ForwardIter __first, _ForwardIter __last,
_Integer __count, const _Tp& __val);
template <class _ForwardIter, class _Integer, class _Tp, class _BinaryPred>
_ForwardIter search_n(_ForwardIter __first, _ForwardIter __last,
_Integer __count, const _Tp& __val, _BinaryPred __binary_pred);
template <class _InputIter, class _ForwardIter>
inline _InputIter find_first_of(_InputIter __first1, _InputIter __last1,
_ForwardIter __first2, _ForwardIter __last2) {
_STLP_DEBUG_CHECK(__check_range(__first1, __last1))
_STLP_DEBUG_CHECK(__check_range(__first2, __last2))
return __find_first_of(__first1, __last1, __first2, __last2,__equal_to(_STLP_VALUE_TYPE(__first1, _InputIter)));
}
template <class _InputIter, class _ForwardIter, class _BinaryPredicate>
inline _InputIter
find_first_of(_InputIter __first1, _InputIter __last1,
_ForwardIter __first2, _ForwardIter __last2,_BinaryPredicate __comp) {
_STLP_DEBUG_CHECK(__check_range(__first1, __last1))
_STLP_DEBUG_CHECK(__check_range(__first2, __last2))
return __find_first_of(__first1, __last1, __first2, __last2,__comp);
}
template <class _ForwardIter1, class _ForwardIter2>
_ForwardIter1
find_end(_ForwardIter1 __first1, _ForwardIter1 __last1,
_ForwardIter2 __first2, _ForwardIter2 __last2);
// swap_ranges
template <class _ForwardIter1, class _ForwardIter2>
_STLP_INLINE_LOOP _ForwardIter2
swap_ranges(_ForwardIter1 __first1, _ForwardIter1 __last1, _ForwardIter2 __first2) {
_STLP_DEBUG_CHECK(__check_range(__first1, __last1))
for ( ; __first1 != __last1; ++__first1, ++__first2)
iter_swap(__first1, __first2);
return __first2;
}
// transform
template <class _InputIter, class _OutputIter, class _UnaryOperation>
_STLP_INLINE_LOOP _OutputIter
transform(_InputIter __first, _InputIter __last, _OutputIter __result, _UnaryOperation __opr) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
for ( ; __first != __last; ++__first, ++__result)
*__result = __opr(*__first);
return __result;
}
template <class _InputIter1, class _InputIter2, class _OutputIter, class _BinaryOperation>
_STLP_INLINE_LOOP _OutputIter
transform(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _OutputIter __result,_BinaryOperation __binary_op) {
_STLP_DEBUG_CHECK(__check_range(__first1, __last1))
for ( ; __first1 != __last1; ++__first1, ++__first2, ++__result)
*__result = __binary_op(*__first1, *__first2);
return __result;
}
// replace_if, replace_copy, replace_copy_if
template <class _ForwardIter, class _Predicate, class _Tp>
_STLP_INLINE_LOOP void
replace_if(_ForwardIter __first, _ForwardIter __last, _Predicate __pred, const _Tp& __new_value) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
for ( ; __first != __last; ++__first)
if (__pred(*__first))
*__first = __new_value;
}
template <class _InputIter, class _OutputIter, class _Tp>
_STLP_INLINE_LOOP _OutputIter
replace_copy(_InputIter __first, _InputIter __last,_OutputIter __result,
const _Tp& __old_value, const _Tp& __new_value) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
for ( ; __first != __last; ++__first, ++__result)
*__result = *__first == __old_value ? __new_value : *__first;
return __result;
}
template <class _Iterator, class _OutputIter, class _Predicate, class _Tp>
_STLP_INLINE_LOOP _OutputIter
replace_copy_if(_Iterator __first, _Iterator __last,
_OutputIter __result,
_Predicate __pred, const _Tp& __new_value) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
for ( ; __first != __last; ++__first, ++__result)
*__result = __pred(*__first) ? __new_value : *__first;
return __result;
}
// generate and generate_n
template <class _ForwardIter, class _Generator>
_STLP_INLINE_LOOP void
generate(_ForwardIter __first, _ForwardIter __last, _Generator __gen) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
for ( ; __first != __last; ++__first)
*__first = __gen();
}
template <class _OutputIter, class _Size, class _Generator>
_STLP_INLINE_LOOP void
generate_n(_OutputIter __first, _Size __n, _Generator __gen) {
for ( ; __n > 0; --__n, ++__first)
*__first = __gen();
}
// remove, remove_if, remove_copy, remove_copy_if
template <class _InputIter, class _OutputIter, class _Tp>
_STLP_INLINE_LOOP _OutputIter
remove_copy(_InputIter __first, _InputIter __last,_OutputIter __result, const _Tp& __val) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
for ( ; __first != __last; ++__first)
if (!(*__first == __val)) {
*__result = *__first;
++__result;
}
return __result;
}
template <class _InputIter, class _OutputIter, class _Predicate>
_STLP_INLINE_LOOP _OutputIter
remove_copy_if(_InputIter __first, _InputIter __last, _OutputIter __result, _Predicate __pred) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
for ( ; __first != __last; ++__first)
if (!__pred(*__first)) {
*__result = *__first;
++__result;
}
return __result;
}
template <class _ForwardIter, class _Tp>
_STLP_INLINE_LOOP _ForwardIter
remove(_ForwardIter __first, _ForwardIter __last, const _Tp& __val) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
__first = find(__first, __last, __val);
if (__first == __last)
return __first;
else {
_ForwardIter __next = __first;
return remove_copy(++__next, __last, __first, __val);
}
}
template <class _ForwardIter, class _Predicate>
_STLP_INLINE_LOOP _ForwardIter
remove_if(_ForwardIter __first, _ForwardIter __last, _Predicate __pred) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
__first = find_if(__first, __last, __pred);
if ( __first == __last )
return __first;
else {
_ForwardIter __next = __first;
return remove_copy_if(++__next, __last, __first, __pred);
}
}
// unique and unique_copy
template <class _InputIter, class _OutputIter>
_OutputIter unique_copy(_InputIter __first, _InputIter __last, _OutputIter __result);
template <class _InputIter, class _OutputIter, class _BinaryPredicate>
_OutputIter unique_copy(_InputIter __first, _InputIter __last,_OutputIter __result,
_BinaryPredicate __binary_pred);
template <class _ForwardIter>
inline _ForwardIter unique(_ForwardIter __first, _ForwardIter __last) {
__first = adjacent_find(__first, __last);
return unique_copy(__first, __last, __first);
}
template <class _ForwardIter, class _BinaryPredicate>
inline _ForwardIter unique(_ForwardIter __first, _ForwardIter __last,
_BinaryPredicate __binary_pred) {
__first = adjacent_find(__first, __last, __binary_pred);
return unique_copy(__first, __last, __first, __binary_pred);
}
// reverse and reverse_copy, and their auxiliary functions
template <class _BidirectionalIter>
_STLP_INLINE_LOOP void
__reverse(_BidirectionalIter __first, _BidirectionalIter __last, const bidirectional_iterator_tag &) {
for(; __first != __last && __first != --__last; ++__first)
iter_swap(__first,__last);
}
template <class _RandomAccessIter>
_STLP_INLINE_LOOP void
__reverse(_RandomAccessIter __first, _RandomAccessIter __last, const random_access_iterator_tag &) {
for (; __first < __last; ++__first) iter_swap(__first, --__last);
}
template <class _BidirectionalIter>
inline void
reverse(_BidirectionalIter __first, _BidirectionalIter __last) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
__reverse(__first, __last, _STLP_ITERATOR_CATEGORY(__first, _BidirectionalIter));
}
template <class _BidirectionalIter, class _OutputIter>
_STLP_INLINE_LOOP
_OutputIter reverse_copy(_BidirectionalIter __first,
_BidirectionalIter __last,
_OutputIter __result) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
while (__first != __last) {
--__last;
*__result = *__last;
++__result;
}
return __result;
}
// rotate and rotate_copy, and their auxiliary functions
template <class _EuclideanRingElement>
_STLP_INLINE_LOOP
_EuclideanRingElement __gcd(_EuclideanRingElement __m,
_EuclideanRingElement __n)
{
while (__n != 0) {
_EuclideanRingElement __t = __m % __n;
__m = __n;
__n = __t;
}
return __m;
}
template <class _ForwardIter>
void rotate(_ForwardIter __first, _ForwardIter __middle, _ForwardIter __last);
template <class _ForwardIter, class _OutputIter>
inline _OutputIter rotate_copy(_ForwardIter __first, _ForwardIter __middle,
_ForwardIter __last, _OutputIter __result) {
return copy(__first, __middle, copy(__middle, __last, __result));
}
// random_shuffle
template <class _RandomAccessIter>
void random_shuffle(_RandomAccessIter __first, _RandomAccessIter __last);
template <class _RandomAccessIter, class _RandomNumberGenerator>
void random_shuffle(_RandomAccessIter __first, _RandomAccessIter __last,
_RandomNumberGenerator& __rand);
# ifndef _STLP_NO_EXTENSIONS
// random_sample and random_sample_n (extensions, not part of the standard).
template <class _ForwardIter, class _OutputIter, class _Distance>
_OutputIter random_sample_n(_ForwardIter __first, _ForwardIter __last,
_OutputIter __out_ite, const _Distance __n);
template <class _ForwardIter, class _OutputIter, class _Distance,
class _RandomNumberGenerator>
_OutputIter random_sample_n(_ForwardIter __first, _ForwardIter __last,
_OutputIter __out_ite, const _Distance __n,
_RandomNumberGenerator& __rand);
template <class _InputIter, class _RandomAccessIter>
_RandomAccessIter
random_sample(_InputIter __first, _InputIter __last,
_RandomAccessIter __out_first, _RandomAccessIter __out_last);
template <class _InputIter, class _RandomAccessIter,
class _RandomNumberGenerator>
_RandomAccessIter
random_sample(_InputIter __first, _InputIter __last,
_RandomAccessIter __out_first, _RandomAccessIter __out_last,
_RandomNumberGenerator& __rand);
# endif /* _STLP_NO_EXTENSIONS */
// partition, stable_partition, and their auxiliary functions
template <class _ForwardIter, class _Predicate>
_ForwardIter partition(_ForwardIter __first, _ForwardIter __last, _Predicate __pred);
template <class _ForwardIter, class _Predicate>
_ForwardIter
stable_partition(_ForwardIter __first, _ForwardIter __last, _Predicate __pred);
// sort() and its auxiliary functions.
template <class _Size>
inline _Size __lg(_Size __n) {
_Size __k;
for (__k = 0; __n != 1; __n >>= 1) ++__k;
return __k;
}
template <class _RandomAccessIter>
void sort(_RandomAccessIter __first, _RandomAccessIter __last);
template <class _RandomAccessIter, class _Compare>
void sort(_RandomAccessIter __first, _RandomAccessIter __last, _Compare __comp);
// stable_sort() and its auxiliary functions.
template <class _RandomAccessIter>
void stable_sort(_RandomAccessIter __first,
_RandomAccessIter __last);
template <class _RandomAccessIter, class _Compare>
void stable_sort(_RandomAccessIter __first,
_RandomAccessIter __last, _Compare __comp);
// partial_sort, partial_sort_copy, and auxiliary functions.
template <class _RandomAccessIter>
void
partial_sort(_RandomAccessIter __first,_RandomAccessIter __middle, _RandomAccessIter __last);
template <class _RandomAccessIter, class _Compare>
void
partial_sort(_RandomAccessIter __first,_RandomAccessIter __middle,
_RandomAccessIter __last, _Compare __comp);
template <class _InputIter, class _RandomAccessIter>
_RandomAccessIter
partial_sort_copy(_InputIter __first, _InputIter __last,
_RandomAccessIter __result_first, _RandomAccessIter __result_last);
template <class _InputIter, class _RandomAccessIter, class _Compare>
_RandomAccessIter
partial_sort_copy(_InputIter __first, _InputIter __last,
_RandomAccessIter __result_first,
_RandomAccessIter __result_last, _Compare __comp);
// nth_element() and its auxiliary functions.
template <class _RandomAccessIter>
void nth_element(_RandomAccessIter __first, _RandomAccessIter __nth,
_RandomAccessIter __last);
template <class _RandomAccessIter, class _Compare>
void nth_element(_RandomAccessIter __first, _RandomAccessIter __nth,
_RandomAccessIter __last, _Compare __comp);
// auxiliary class for lower_bound, etc.
template <class _T1, class _T2>
struct __less_2 {
bool operator() (const _T1& __x, const _T2& __y) const { return __x < __y ; }
};
template <class _T1, class _T2>
__less_2<_T1,_T2> __less2(_T1*, _T2* ) { return __less_2<_T1, _T2>(); }
#ifdef _STLP_FUNCTION_PARTIAL_ORDER
template <class _Tp>
less<_Tp> __less2(_Tp*, _Tp* ) { return less<_Tp>(); }
#endif
// Binary search (lower_bound, upper_bound, equal_range, binary_search).
template <class _ForwardIter, class _Tp>
inline _ForwardIter lower_bound(_ForwardIter __first, _ForwardIter __last,
const _Tp& __val) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
return __lower_bound(__first, __last, __val,
__less2(_STLP_VALUE_TYPE(__first, _ForwardIter), (_Tp*)0),
_STLP_DISTANCE_TYPE(__first, _ForwardIter));
}
template <class _ForwardIter, class _Tp, class _Compare>
inline _ForwardIter lower_bound(_ForwardIter __first, _ForwardIter __last,
const _Tp& __val, _Compare __comp) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
return __lower_bound(__first, __last, __val, __comp, _STLP_DISTANCE_TYPE(__first, _ForwardIter));
}
template <class _ForwardIter, class _Tp, class _Compare, class _Distance>
_ForwardIter __upper_bound(_ForwardIter __first, _ForwardIter __last,
const _Tp& __val, _Compare __comp, _Distance*);
template <class _ForwardIter, class _Tp>
inline _ForwardIter upper_bound(_ForwardIter __first, _ForwardIter __last,
const _Tp& __val) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
return __upper_bound(__first, __last, __val,
__less2(_STLP_VALUE_TYPE(__first, _ForwardIter), (_Tp*)0),
_STLP_DISTANCE_TYPE(__first, _ForwardIter));
}
template <class _ForwardIter, class _Tp, class _Compare>
inline _ForwardIter upper_bound(_ForwardIter __first, _ForwardIter __last,
const _Tp& __val, _Compare __comp) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
return __upper_bound(__first, __last, __val, __comp,
_STLP_DISTANCE_TYPE(__first, _ForwardIter));
}
template <class _ForwardIter, class _Tp, class _Compare, class _Distance>
pair<_ForwardIter, _ForwardIter>
__equal_range(_ForwardIter __first, _ForwardIter __last, const _Tp& __val,
_Compare __comp, _Distance*);
template <class _ForwardIter, class _Tp>
inline pair<_ForwardIter, _ForwardIter>
equal_range(_ForwardIter __first, _ForwardIter __last, const _Tp& __val) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
return __equal_range(__first, __last, __val,
__less2(_STLP_VALUE_TYPE(__first, _ForwardIter), (_Tp*)0),
_STLP_DISTANCE_TYPE(__first, _ForwardIter));
}
template <class _ForwardIter, class _Tp, class _Compare>
inline pair<_ForwardIter, _ForwardIter>
equal_range(_ForwardIter __first, _ForwardIter __last, const _Tp& __val,
_Compare __comp) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
return __equal_range(__first, __last, __val, __comp,
_STLP_DISTANCE_TYPE(__first, _ForwardIter));
}
template <class _ForwardIter, class _Tp>
inline bool binary_search(_ForwardIter __first, _ForwardIter __last,
const _Tp& __val) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
_ForwardIter __i = __lower_bound(__first, __last, __val,
__less2(_STLP_VALUE_TYPE(__first, _ForwardIter), (_Tp*)0),
_STLP_DISTANCE_TYPE(__first, _ForwardIter));
return __i != __last && !(__val < *__i);
}
template <class _ForwardIter, class _Tp, class _Compare>
inline bool binary_search(_ForwardIter __first, _ForwardIter __last,
const _Tp& __val,
_Compare __comp) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
_ForwardIter __i = __lower_bound(__first, __last, __val, __comp, _STLP_DISTANCE_TYPE(__first, _ForwardIter));
return __i != __last && !__comp(__val, *__i);
}
// merge, with and without an explicitly supplied comparison function.
template <class _InputIter1, class _InputIter2, class _OutputIter>
_OutputIter merge(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2,
_OutputIter __result);
template <class _InputIter1, class _InputIter2, class _OutputIter,
class _Compare>
_OutputIter merge(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2,
_OutputIter __result, _Compare __comp);
// inplace_merge and its auxiliary functions.
template <class _BidirectionalIter>
void inplace_merge(_BidirectionalIter __first,
_BidirectionalIter __middle,
_BidirectionalIter __last) ;
template <class _BidirectionalIter, class _Compare>
void inplace_merge(_BidirectionalIter __first,
_BidirectionalIter __middle,
_BidirectionalIter __last, _Compare __comp);
// Set algorithms: includes, set_union, set_intersection, set_difference,
// set_symmetric_difference. All of these algorithms have the precondition
// that their input ranges are sorted and the postcondition that their output
// ranges are sorted.
template <class _InputIter1, class _InputIter2>
bool includes(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2);
template <class _InputIter1, class _InputIter2, class _Compare>
bool includes(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2, _Compare __comp);
template <class _InputIter1, class _InputIter2, class _OutputIter>
_OutputIter set_union(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2,
_OutputIter __result);
template <class _InputIter1, class _InputIter2, class _OutputIter,
class _Compare>
_OutputIter set_union(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2,
_OutputIter __result, _Compare __comp);
template <class _InputIter1, class _InputIter2, class _OutputIter>
_OutputIter set_intersection(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2,
_OutputIter __result);
template <class _InputIter1, class _InputIter2, class _OutputIter,
class _Compare>
_OutputIter set_intersection(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2,
_OutputIter __result, _Compare __comp);
template <class _InputIter1, class _InputIter2, class _OutputIter>
_OutputIter set_difference(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2,
_OutputIter __result);
template <class _InputIter1, class _InputIter2, class _OutputIter,
class _Compare>
_OutputIter set_difference(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2,
_OutputIter __result, _Compare __comp);
template <class _InputIter1, class _InputIter2, class _OutputIter>
_OutputIter
set_symmetric_difference(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2,
_OutputIter __result);
template <class _InputIter1, class _InputIter2, class _OutputIter,
class _Compare>
_OutputIter
set_symmetric_difference(_InputIter1 __first1, _InputIter1 __last1,
_InputIter2 __first2, _InputIter2 __last2,
_OutputIter __result,
_Compare __comp);
// min_element and max_element, with and without an explicitly supplied
// comparison function.
template <class _ForwardIter>
_ForwardIter max_element(_ForwardIter __first, _ForwardIter __last);
template <class _ForwardIter, class _Compare>
_ForwardIter max_element(_ForwardIter __first, _ForwardIter __last,
_Compare __comp);
template <class _ForwardIter>
_ForwardIter min_element(_ForwardIter __first, _ForwardIter __last);
template <class _ForwardIter, class _Compare>
_ForwardIter min_element(_ForwardIter __first, _ForwardIter __last,
_Compare __comp);
// next_permutation and prev_permutation, with and without an explicitly
// supplied comparison function.
template <class _BidirectionalIter>
bool next_permutation(_BidirectionalIter __first, _BidirectionalIter __last);
template <class _BidirectionalIter, class _Compare>
bool next_permutation(_BidirectionalIter __first, _BidirectionalIter __last,
_Compare __comp);
template <class _BidirectionalIter>
bool prev_permutation(_BidirectionalIter __first, _BidirectionalIter __last);
template <class _BidirectionalIter, class _Compare>
bool prev_permutation(_BidirectionalIter __first, _BidirectionalIter __last,
_Compare __comp);
# ifndef _STLP_NO_EXTENSIONS
// is_heap, a predicate testing whether or not a range is
// a heap. This function is an extension, not part of the C++
// standard.
template <class _RandomAccessIter>
bool is_heap(_RandomAccessIter __first, _RandomAccessIter __last);
template <class _RandomAccessIter, class _StrictWeakOrdering>
bool is_heap(_RandomAccessIter __first, _RandomAccessIter __last,
_StrictWeakOrdering __comp);
// is_sorted, a predicated testing whether a range is sorted in
// nondescending order. This is an extension, not part of the C++
// standard.
template <class _ForwardIter, class _StrictWeakOrdering>
bool __is_sorted(_ForwardIter __first, _ForwardIter __last,
_StrictWeakOrdering __comp);
template <class _ForwardIter>
inline bool is_sorted(_ForwardIter __first, _ForwardIter __last) {
return __is_sorted(__first, __last, __less(_STLP_VALUE_TYPE(__first, _ForwardIter)));
}
template <class _ForwardIter, class _StrictWeakOrdering>
inline bool is_sorted(_ForwardIter __first, _ForwardIter __last,
_StrictWeakOrdering __comp) {
return __is_sorted(__first, __last, __comp);
}
# endif
_STLP_END_NAMESPACE
# if !defined (_STLP_LINK_TIME_INSTANTIATION)
# include <stl/_algo.c>
# endif
#endif /* _STLP_INTERNAL_ALGO_H */
// Local Variables:
// mode:C++
// End:
| ZHAW-INES/rioxo-uClinux-dist | lib/STLport/stlport/stl/_algo.h | C | gpl-2.0 | 26,838 |
/*
* Standard Hot Plug Controller Driver
*
* Copyright (C) 1995,2001 Compaq Computer Corporation
* Copyright (C) 2001 Greg Kroah-Hartman (greg@kroah.com)
* Copyright (C) 2001 IBM Corp.
* Copyright (C) 2003-2004 Intel Corporation
*
* 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, GOOD TITLE or
* 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 this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Send feedback to <greg@kroah.com>, <dely.l.sy@intel.com>
*
*/
#include <linux/config.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/proc_fs.h>
#include <linux/miscdevice.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <asm/uaccess.h>
#include "shpchp.h"
#include "shpchprm.h"
/* Global variables */
int shpchp_debug;
int shpchp_poll_mode;
int shpchp_poll_time;
struct controller *shpchp_ctrl_list; /* = NULL */
struct pci_func *shpchp_slot_list[256];
#define DRIVER_VERSION "0.4"
#define DRIVER_AUTHOR "Dan Zink <dan.zink@compaq.com>, Greg Kroah-Hartman <greg@kroah.com>, Dely Sy <dely.l.sy@intel.com>"
#define DRIVER_DESC "Standard Hot Plug PCI Controller Driver"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
module_param(shpchp_debug, bool, 0644);
module_param(shpchp_poll_mode, bool, 0644);
module_param(shpchp_poll_time, int, 0644);
MODULE_PARM_DESC(shpchp_debug, "Debugging mode enabled or not");
MODULE_PARM_DESC(shpchp_poll_mode, "Using polling mechanism for hot-plug events or not");
MODULE_PARM_DESC(shpchp_poll_time, "Polling mechanism frequency, in seconds");
#define SHPC_MODULE_NAME "shpchp"
static int shpc_start_thread (void);
static int set_attention_status (struct hotplug_slot *slot, u8 value);
static int enable_slot (struct hotplug_slot *slot);
static int disable_slot (struct hotplug_slot *slot);
static int get_power_status (struct hotplug_slot *slot, u8 *value);
static int get_attention_status (struct hotplug_slot *slot, u8 *value);
static int get_latch_status (struct hotplug_slot *slot, u8 *value);
static int get_adapter_status (struct hotplug_slot *slot, u8 *value);
static int get_max_bus_speed (struct hotplug_slot *slot, enum pci_bus_speed *value);
static int get_cur_bus_speed (struct hotplug_slot *slot, enum pci_bus_speed *value);
static struct hotplug_slot_ops shpchp_hotplug_slot_ops = {
.owner = THIS_MODULE,
.set_attention_status = set_attention_status,
.enable_slot = enable_slot,
.disable_slot = disable_slot,
.get_power_status = get_power_status,
.get_attention_status = get_attention_status,
.get_latch_status = get_latch_status,
.get_adapter_status = get_adapter_status,
.get_max_bus_speed = get_max_bus_speed,
.get_cur_bus_speed = get_cur_bus_speed,
};
/**
* release_slot - free up the memory used by a slot
* @hotplug_slot: slot to free
*/
static void release_slot(struct hotplug_slot *hotplug_slot)
{
struct slot *slot = (struct slot *)hotplug_slot->private;
dbg("%s - physical_slot = %s\n", __FUNCTION__, hotplug_slot->name);
kfree(slot->hotplug_slot->info);
kfree(slot->hotplug_slot->name);
kfree(slot->hotplug_slot);
kfree(slot);
}
static int init_slots(struct controller *ctrl)
{
struct slot *new_slot;
u8 number_of_slots;
u8 slot_device;
u32 slot_number, sun;
int result = -ENOMEM;
dbg("%s\n",__FUNCTION__);
number_of_slots = ctrl->num_slots;
slot_device = ctrl->slot_device_offset;
slot_number = ctrl->first_slot;
while (number_of_slots) {
new_slot = (struct slot *) kmalloc(sizeof(struct slot), GFP_KERNEL);
if (!new_slot)
goto error;
memset(new_slot, 0, sizeof(struct slot));
new_slot->hotplug_slot = kmalloc (sizeof (struct hotplug_slot), GFP_KERNEL);
if (!new_slot->hotplug_slot)
goto error_slot;
memset(new_slot->hotplug_slot, 0, sizeof (struct hotplug_slot));
new_slot->hotplug_slot->info = kmalloc (sizeof (struct hotplug_slot_info), GFP_KERNEL);
if (!new_slot->hotplug_slot->info)
goto error_hpslot;
memset(new_slot->hotplug_slot->info, 0, sizeof (struct hotplug_slot_info));
new_slot->hotplug_slot->name = kmalloc (SLOT_NAME_SIZE, GFP_KERNEL);
if (!new_slot->hotplug_slot->name)
goto error_info;
new_slot->magic = SLOT_MAGIC;
new_slot->ctrl = ctrl;
new_slot->bus = ctrl->slot_bus;
new_slot->device = slot_device;
new_slot->hpc_ops = ctrl->hpc_ops;
if (shpchprm_get_physical_slot_number(ctrl, &sun,
new_slot->bus, new_slot->device))
goto error_name;
new_slot->number = sun;
new_slot->hp_slot = slot_device - ctrl->slot_device_offset;
/* register this slot with the hotplug pci core */
new_slot->hotplug_slot->private = new_slot;
new_slot->hotplug_slot->release = &release_slot;
make_slot_name(new_slot->hotplug_slot->name, SLOT_NAME_SIZE, new_slot);
new_slot->hotplug_slot->ops = &shpchp_hotplug_slot_ops;
new_slot->hpc_ops->get_power_status(new_slot, &(new_slot->hotplug_slot->info->power_status));
new_slot->hpc_ops->get_attention_status(new_slot, &(new_slot->hotplug_slot->info->attention_status));
new_slot->hpc_ops->get_latch_status(new_slot, &(new_slot->hotplug_slot->info->latch_status));
new_slot->hpc_ops->get_adapter_status(new_slot, &(new_slot->hotplug_slot->info->adapter_status));
dbg("Registering bus=%x dev=%x hp_slot=%x sun=%x slot_device_offset=%x\n", new_slot->bus,
new_slot->device, new_slot->hp_slot, new_slot->number, ctrl->slot_device_offset);
result = pci_hp_register (new_slot->hotplug_slot);
if (result) {
err ("pci_hp_register failed with error %d\n", result);
goto error_name;
}
new_slot->next = ctrl->slot;
ctrl->slot = new_slot;
number_of_slots--;
slot_device++;
slot_number += ctrl->slot_num_inc;
}
return 0;
error_name:
kfree(new_slot->hotplug_slot->name);
error_info:
kfree(new_slot->hotplug_slot->info);
error_hpslot:
kfree(new_slot->hotplug_slot);
error_slot:
kfree(new_slot);
error:
return result;
}
static void cleanup_slots(struct controller *ctrl)
{
struct slot *old_slot, *next_slot;
old_slot = ctrl->slot;
ctrl->slot = NULL;
while (old_slot) {
next_slot = old_slot->next;
pci_hp_deregister(old_slot->hotplug_slot);
old_slot = next_slot;
}
}
static int get_ctlr_slot_config(struct controller *ctrl)
{
int num_ctlr_slots;
int first_device_num;
int physical_slot_num;
int updown;
int rc;
int flags;
rc = shpc_get_ctlr_slot_config(ctrl, &num_ctlr_slots, &first_device_num, &physical_slot_num, &updown, &flags);
if (rc) {
err("%s: get_ctlr_slot_config fail for b:d (%x:%x)\n", __FUNCTION__, ctrl->bus, ctrl->device);
return -1;
}
ctrl->num_slots = num_ctlr_slots;
ctrl->slot_device_offset = first_device_num;
ctrl->first_slot = physical_slot_num;
ctrl->slot_num_inc = updown; /* either -1 or 1 */
dbg("%s: num_slot(0x%x) 1st_dev(0x%x) psn(0x%x) updown(%d) for b:d (%x:%x)\n",
__FUNCTION__, num_ctlr_slots, first_device_num, physical_slot_num, updown, ctrl->bus, ctrl->device);
return 0;
}
/*
* set_attention_status - Turns the Amber LED for a slot on, off or blink
*/
static int set_attention_status (struct hotplug_slot *hotplug_slot, u8 status)
{
struct slot *slot = get_slot (hotplug_slot, __FUNCTION__);
dbg("%s - physical_slot = %s\n", __FUNCTION__, hotplug_slot->name);
hotplug_slot->info->attention_status = status;
slot->hpc_ops->set_attention_status(slot, status);
return 0;
}
static int enable_slot (struct hotplug_slot *hotplug_slot)
{
struct slot *slot = get_slot (hotplug_slot, __FUNCTION__);
dbg("%s - physical_slot = %s\n", __FUNCTION__, hotplug_slot->name);
return shpchp_enable_slot(slot);
}
static int disable_slot (struct hotplug_slot *hotplug_slot)
{
struct slot *slot = get_slot (hotplug_slot, __FUNCTION__);
dbg("%s - physical_slot = %s\n", __FUNCTION__, hotplug_slot->name);
return shpchp_disable_slot(slot);
}
static int get_power_status (struct hotplug_slot *hotplug_slot, u8 *value)
{
struct slot *slot = get_slot (hotplug_slot, __FUNCTION__);
int retval;
dbg("%s - physical_slot = %s\n", __FUNCTION__, hotplug_slot->name);
retval = slot->hpc_ops->get_power_status(slot, value);
if (retval < 0)
*value = hotplug_slot->info->power_status;
return 0;
}
static int get_attention_status (struct hotplug_slot *hotplug_slot, u8 *value)
{
struct slot *slot = get_slot (hotplug_slot, __FUNCTION__);
int retval;
dbg("%s - physical_slot = %s\n", __FUNCTION__, hotplug_slot->name);
retval = slot->hpc_ops->get_attention_status(slot, value);
if (retval < 0)
*value = hotplug_slot->info->attention_status;
return 0;
}
static int get_latch_status (struct hotplug_slot *hotplug_slot, u8 *value)
{
struct slot *slot = get_slot (hotplug_slot, __FUNCTION__);
int retval;
dbg("%s - physical_slot = %s\n", __FUNCTION__, hotplug_slot->name);
retval = slot->hpc_ops->get_latch_status(slot, value);
if (retval < 0)
*value = hotplug_slot->info->latch_status;
return 0;
}
static int get_adapter_status (struct hotplug_slot *hotplug_slot, u8 *value)
{
struct slot *slot = get_slot (hotplug_slot, __FUNCTION__);
int retval;
dbg("%s - physical_slot = %s\n", __FUNCTION__, hotplug_slot->name);
retval = slot->hpc_ops->get_adapter_status(slot, value);
if (retval < 0)
*value = hotplug_slot->info->adapter_status;
return 0;
}
static int get_max_bus_speed (struct hotplug_slot *hotplug_slot, enum pci_bus_speed *value)
{
struct slot *slot = get_slot (hotplug_slot, __FUNCTION__);
int retval;
dbg("%s - physical_slot = %s\n", __FUNCTION__, hotplug_slot->name);
retval = slot->hpc_ops->get_max_bus_speed(slot, value);
if (retval < 0)
*value = PCI_SPEED_UNKNOWN;
return 0;
}
static int get_cur_bus_speed (struct hotplug_slot *hotplug_slot, enum pci_bus_speed *value)
{
struct slot *slot = get_slot (hotplug_slot, __FUNCTION__);
int retval;
dbg("%s - physical_slot = %s\n", __FUNCTION__, hotplug_slot->name);
retval = slot->hpc_ops->get_cur_bus_speed(slot, value);
if (retval < 0)
*value = PCI_SPEED_UNKNOWN;
return 0;
}
static int shpc_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
int rc;
struct controller *ctrl;
struct slot *t_slot;
int first_device_num; /* first PCI device number supported by this SHPC */
int num_ctlr_slots; /* number of slots supported by this SHPC */
ctrl = (struct controller *) kmalloc(sizeof(struct controller), GFP_KERNEL);
if (!ctrl) {
err("%s : out of memory\n", __FUNCTION__);
goto err_out_none;
}
memset(ctrl, 0, sizeof(struct controller));
dbg("DRV_thread pid = %d\n", current->pid);
rc = shpc_init(ctrl, pdev,
(php_intr_callback_t) shpchp_handle_attention_button,
(php_intr_callback_t) shpchp_handle_switch_change,
(php_intr_callback_t) shpchp_handle_presence_change,
(php_intr_callback_t) shpchp_handle_power_fault);
if (rc) {
dbg("%s: controller initialization failed\n", SHPC_MODULE_NAME);
goto err_out_free_ctrl;
}
dbg("%s: controller initialization success\n", __FUNCTION__);
ctrl->pci_dev = pdev; /* pci_dev of the P2P bridge */
pci_set_drvdata(pdev, ctrl);
ctrl->pci_bus = kmalloc (sizeof (*ctrl->pci_bus), GFP_KERNEL);
if (!ctrl->pci_bus) {
err("out of memory\n");
rc = -ENOMEM;
goto err_out_unmap_mmio_region;
}
memcpy (ctrl->pci_bus, pdev->bus, sizeof (*ctrl->pci_bus));
ctrl->bus = pdev->bus->number;
ctrl->slot_bus = pdev->subordinate->number;
ctrl->device = PCI_SLOT(pdev->devfn);
ctrl->function = PCI_FUNC(pdev->devfn);
dbg("ctrl bus=0x%x, device=%x, function=%x, irq=%x\n", ctrl->bus, ctrl->device, ctrl->function, pdev->irq);
/*
* Save configuration headers for this and subordinate PCI buses
*/
rc = get_ctlr_slot_config(ctrl);
if (rc) {
err(msg_initialization_err, rc);
goto err_out_free_ctrl_bus;
}
first_device_num = ctrl->slot_device_offset;
num_ctlr_slots = ctrl->num_slots;
/* Store PCI Config Space for all devices on this bus */
rc = shpchp_save_config(ctrl, ctrl->slot_bus, num_ctlr_slots, first_device_num);
if (rc) {
err("%s: unable to save PCI configuration data, error %d\n", __FUNCTION__, rc);
goto err_out_free_ctrl_bus;
}
/* Get IO, memory, and IRQ resources for new devices */
rc = shpchprm_find_available_resources(ctrl);
ctrl->add_support = !rc;
if (rc) {
dbg("shpchprm_find_available_resources = %#x\n", rc);
err("unable to locate PCI configuration resources for hot plug add.\n");
goto err_out_free_ctrl_bus;
}
/* Setup the slot information structures */
rc = init_slots(ctrl);
if (rc) {
err(msg_initialization_err, 6);
goto err_out_free_ctrl_slot;
}
/* Now hpc_functions (slot->hpc_ops->functions) are ready */
t_slot = shpchp_find_slot(ctrl, first_device_num);
/* Check for operation bus speed */
rc = t_slot->hpc_ops->get_cur_bus_speed(t_slot, &ctrl->speed);
dbg("%s: t_slot->hp_slot %x\n", __FUNCTION__,t_slot->hp_slot);
if (rc || ctrl->speed == PCI_SPEED_UNKNOWN) {
err(SHPC_MODULE_NAME ": Can't get current bus speed. Set to 33MHz PCI.\n");
ctrl->speed = PCI_SPEED_33MHz;
}
/* Finish setting up the hot plug ctrl device */
ctrl->next_event = 0;
if (!shpchp_ctrl_list) {
shpchp_ctrl_list = ctrl;
ctrl->next = NULL;
} else {
ctrl->next = shpchp_ctrl_list;
shpchp_ctrl_list = ctrl;
}
shpchp_create_ctrl_files(ctrl);
return 0;
err_out_free_ctrl_slot:
cleanup_slots(ctrl);
err_out_free_ctrl_bus:
kfree(ctrl->pci_bus);
err_out_unmap_mmio_region:
ctrl->hpc_ops->release_ctlr(ctrl);
err_out_free_ctrl:
kfree(ctrl);
err_out_none:
return -ENODEV;
}
static int shpc_start_thread(void)
{
int loop;
int retval = 0;
dbg("Initialize + Start the notification/polling mechanism \n");
retval = shpchp_event_start_thread();
if (retval) {
dbg("shpchp_event_start_thread() failed\n");
return retval;
}
dbg("Initialize slot lists\n");
/* One slot list for each bus in the system */
for (loop = 0; loop < 256; loop++) {
shpchp_slot_list[loop] = NULL;
}
return retval;
}
static inline void __exit
free_shpchp_res(struct pci_resource *res)
{
struct pci_resource *tres;
while (res) {
tres = res;
res = res->next;
kfree(tres);
}
}
static void __exit unload_shpchpd(void)
{
struct pci_func *next;
struct pci_func *TempSlot;
int loop;
struct controller *ctrl;
struct controller *tctrl;
ctrl = shpchp_ctrl_list;
while (ctrl) {
cleanup_slots(ctrl);
free_shpchp_res(ctrl->io_head);
free_shpchp_res(ctrl->mem_head);
free_shpchp_res(ctrl->p_mem_head);
free_shpchp_res(ctrl->bus_head);
kfree (ctrl->pci_bus);
dbg("%s: calling release_ctlr\n", __FUNCTION__);
ctrl->hpc_ops->release_ctlr(ctrl);
tctrl = ctrl;
ctrl = ctrl->next;
kfree(tctrl);
}
for (loop = 0; loop < 256; loop++) {
next = shpchp_slot_list[loop];
while (next != NULL) {
free_shpchp_res(next->io_head);
free_shpchp_res(next->mem_head);
free_shpchp_res(next->p_mem_head);
free_shpchp_res(next->bus_head);
TempSlot = next;
next = next->next;
kfree(TempSlot);
}
}
/* Stop the notification mechanism */
shpchp_event_stop_thread();
}
static struct pci_device_id shpcd_pci_tbl[] = {
{
.class = ((PCI_CLASS_BRIDGE_PCI << 8) | 0x00),
.class_mask = ~0,
.vendor = PCI_ANY_ID,
.device = PCI_ANY_ID,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{ /* end: all zeroes */ }
};
MODULE_DEVICE_TABLE(pci, shpcd_pci_tbl);
static struct pci_driver shpc_driver = {
.name = SHPC_MODULE_NAME,
.id_table = shpcd_pci_tbl,
.probe = shpc_probe,
/* remove: shpc_remove_one, */
};
static int __init shpcd_init(void)
{
int retval = 0;
#ifdef CONFIG_HOTPLUG_PCI_SHPC_POLL_EVENT_MODE
shpchp_poll_mode = 1;
#endif
retval = shpc_start_thread();
if (retval)
goto error_hpc_init;
retval = shpchprm_init(PCI);
if (!retval) {
retval = pci_module_init(&shpc_driver);
dbg("%s: pci_module_init = %d\n", __FUNCTION__, retval);
info(DRIVER_DESC " version: " DRIVER_VERSION "\n");
}
error_hpc_init:
if (retval) {
shpchprm_cleanup();
shpchp_event_stop_thread();
} else
shpchprm_print_pirt();
return retval;
}
static void __exit shpcd_cleanup(void)
{
dbg("unload_shpchpd()\n");
unload_shpchpd();
shpchprm_cleanup();
dbg("pci_unregister_driver\n");
pci_unregister_driver(&shpc_driver);
info(DRIVER_DESC " version: " DRIVER_VERSION " unloaded\n");
}
module_init(shpcd_init);
module_exit(shpcd_cleanup);
| souravzzz/cse5433 | drivers/pci/hotplug/shpchp_core.c | C | gpl-2.0 | 16,923 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Fancytree - Testing doctype html5</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.js" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.js" type="text/javascript"></script>
<link href="../../src/skin-win7/ui.fancytree.css" rel="stylesheet" type="text/css">
<script src="../../src/jquery.fancytree.js" type="text/javascript"></script>
<script src="../../src/jquery.fancytree.dnd.js" type="text/javascript"></script>
<!-- Start_Exclude: This block is not part of the sample code -->
<link href="../../lib/prettify.css" rel="stylesheet">
<script src="../../lib/prettify.js" type="text/javascript"></script>
<link href="../../demo/sample.css" rel="stylesheet" type="text/css">
<script src="../../demo/sample.js" type="text/javascript"></script>
<!-- End_Exclude -->
<style type="text/css">
#draggableSample, #droppableSample {
height:100px;
padding:0.5em;
width:150px;
border:1px solid #AAAAAA;
}
#draggableSample {
background-color: silver;
color:#222222;
}
#droppableSample {
background-color: maroon;
color: white;
}
#droppableSample.drophover {
border: 1px solid green;
}
</style>
<!-- Add code to initialize the tree when the document is loaded: -->
<script type="text/javascript">
$(function(){
// Tell skinswitcher about theme location
$("select#skinswitcher").skinswitcher("option", "base", "../../src/");
// Attach the fancytree widget to an existing <div id="tree"> element
// and pass the tree options as an argument to the fancytree() function:
$("#tree").fancytree({
extensions: ["dnd"],
source: {
url: "../unit/ajax-tree-plain.json"
},
dnd: {
preventVoidMoves: true,
preventRecursiveMoves: true,
autoExpandMS: 400,
dragStart: function(node, data) {
return true;
},
dragEnter: function(node, data) {
return true;
},
dragDrop: function(node, data) {
data.otherNode.moveTo(node, data.hitMode);
}
},
activate: function(event, data) {
// alert("activate " + data.node);
},
lazyLoad: function(event, data) {
data.result = {url: "../unit/ajax-sub2.json"}
}
});
});
</script>
</head>
<body class="example">
<h1>Example: testing DOCTYPE</h1>
<div>
<label for="skinswitcher">Skin:</label> <select id="skinswitcher"></select>
</div>
<!-- Add a <table> element where the tree should appear: -->
<div id="tree">
</div>
<!-- Start_Exclude: This block is not part of the sample code -->
<hr>
<p class="sample-links no_code">
<a class="hideInsideFS" href="https://github.com/mar10/fancytree">jquery.fancytree.js project home</a>
<a class="hideOutsideFS" href="#">Link to this page</a>
<a class="hideInsideFS" href="index.html">Example Browser</a>
<a href="#" id="codeExample">View source code</a>
</p>
<pre id="sourceCode" class="prettyprint" style="display:none"></pre>
<!-- End_Exclude -->
</body>
</html>
| dolfinitylearning/km | sites/all/libraries/fancytree/test/doctypes/doctype-html5.html | HTML | gpl-2.0 | 3,064 |
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#ifndef OS_WINDOWS_GC_Z_ZMAPPER_WINDOWS_HPP
#define OS_WINDOWS_GC_Z_ZMAPPER_WINDOWS_HPP
#include "memory/allocation.hpp"
#include "utilities/globalDefinitions.hpp"
#include <Windows.h>
class ZMapper : public AllStatic {
private:
// Create paging file mapping
static HANDLE create_paging_file_mapping(size_t size);
// Commit paging file mapping
static bool commit_paging_file_mapping(HANDLE file_handle, uintptr_t file_offset, size_t size);
// Map a view anywhere without a placeholder
static uintptr_t map_view_no_placeholder(HANDLE file_handle, uintptr_t file_offset, size_t size);
// Unmap a view without preserving a placeholder
static void unmap_view_no_placeholder(uintptr_t addr, size_t size);
// Commit memory covering the given virtual address range
static uintptr_t commit(uintptr_t addr, size_t size);
public:
// Reserve memory with a placeholder
static uintptr_t reserve(uintptr_t addr, size_t size);
// Unreserve memory
static void unreserve(uintptr_t addr, size_t size);
// Create and commit paging file mapping
static HANDLE create_and_commit_paging_file_mapping(size_t size);
// Close paging file mapping
static void close_paging_file_mapping(HANDLE file_handle);
// Split a placeholder
//
// A view can only replace an entire placeholder, so placeholders need to be
// split and coalesced to be the exact size of the new views.
// [addr, addr + size) needs to be a proper sub-placeholder of an existing
// placeholder.
static void split_placeholder(uintptr_t addr, size_t size);
// Coalesce a placeholder
//
// [addr, addr + size) is the new placeholder. A sub-placeholder needs to
// exist within that range.
static void coalesce_placeholders(uintptr_t addr, size_t size);
// Map a view of the file handle and replace the placeholder covering the
// given virtual address range
static void map_view_replace_placeholder(HANDLE file_handle, uintptr_t file_offset, uintptr_t addr, size_t size);
// Unmap the view and reinstate a placeholder covering the given virtual
// address range
static void unmap_view_preserve_placeholder(uintptr_t addr, size_t size);
};
#endif // OS_WINDOWS_GC_Z_ZMAPPER_WINDOWS_HPP
| md-5/jdk10 | src/hotspot/os/windows/gc/z/zMapper_windows.hpp | C++ | gpl-2.0 | 3,262 |
<?php
require_once ( CML_PLUGIN_ADMIN_PATH . 'admin-menu.php' );
$args = array(
'walker' => new CML_Walker_Nav_Menu_Edit(),
);
wp_nav_menu( $args );
?> | bourroush/kaycom | wp-content/plugins/ceceppa-multilingua/admin/layouts/translate-menu.php | PHP | gpl-2.0 | 181 |
/* Generated By:JJTree: Do not edit this line. ASTBuiltinValue.java */
package org.jzkit.a2j.codec.comp;
public class ASTBuiltinValue extends SimpleNode {
public int which = 0;
public ASTBuiltinValue(int id) {
super(id);
}
public ASTBuiltinValue(AsnParser p, int id) {
super(p, id);
}
}
| backslash47/a2j | src/main/java/org/jzkit/a2j/codec/comp/ASTBuiltinValue.java | Java | gpl-2.0 | 311 |
/* Basic block reordering routines for the GNU compiler.
Copyright (C) 2000, 2001 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2, or (at your option) any later
version.
GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING. If not, write to the Free
Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA. */
#include "config.h"
#include "system.h"
#include "tree.h"
#include "rtl.h"
#include "hard-reg-set.h"
#include "basic-block.h"
#include "insn-config.h"
#include "output.h"
#include "function.h"
#include "obstack.h"
#include "cfglayout.h"
/* The contents of the current function definition are allocated
in this obstack, and all are freed at the end of the function. */
extern struct obstack flow_obstack;
/* Holds the interesting trailing notes for the function. */
static rtx function_footer;
static rtx skip_insns_after_block PARAMS ((basic_block));
static void record_effective_endpoints PARAMS ((void));
static rtx label_for_bb PARAMS ((basic_block));
static void fixup_reorder_chain PARAMS ((void));
static void set_block_levels PARAMS ((tree, int));
static void change_scope PARAMS ((rtx, tree, tree));
void verify_insn_chain PARAMS ((void));
static void cleanup_unconditional_jumps PARAMS ((void));
static void fixup_fallthru_exit_predecessor PARAMS ((void));
static rtx unlink_insn_chain PARAMS ((rtx, rtx));
static rtx duplicate_insn_chain PARAMS ((rtx, rtx));
static rtx
unlink_insn_chain (first, last)
rtx first;
rtx last;
{
rtx prevfirst = PREV_INSN (first);
rtx nextlast = NEXT_INSN (last);
PREV_INSN (first) = NULL;
NEXT_INSN (last) = NULL;
if (prevfirst)
NEXT_INSN (prevfirst) = nextlast;
if (nextlast)
PREV_INSN (nextlast) = prevfirst;
else
set_last_insn (prevfirst);
if (!prevfirst)
set_first_insn (nextlast);
return first;
}
/* Skip over inter-block insns occurring after BB which are typically
associated with BB (e.g., barriers). If there are any such insns,
we return the last one. Otherwise, we return the end of BB. */
static rtx
skip_insns_after_block (bb)
basic_block bb;
{
rtx insn, last_insn, next_head, prev;
next_head = NULL_RTX;
if (bb->next_bb != EXIT_BLOCK_PTR)
next_head = bb->next_bb->head;
for (last_insn = insn = bb->end; (insn = NEXT_INSN (insn)) != 0; )
{
if (insn == next_head)
break;
switch (GET_CODE (insn))
{
case BARRIER:
last_insn = insn;
continue;
case NOTE:
switch (NOTE_LINE_NUMBER (insn))
{
case NOTE_INSN_LOOP_END:
case NOTE_INSN_BLOCK_END:
last_insn = insn;
continue;
case NOTE_INSN_DELETED:
case NOTE_INSN_DELETED_LABEL:
continue;
default:
continue;
break;
}
break;
case CODE_LABEL:
if (NEXT_INSN (insn)
&& GET_CODE (NEXT_INSN (insn)) == JUMP_INSN
&& (GET_CODE (PATTERN (NEXT_INSN (insn))) == ADDR_VEC
|| GET_CODE (PATTERN (NEXT_INSN (insn))) == ADDR_DIFF_VEC))
{
insn = NEXT_INSN (insn);
last_insn = insn;
continue;
}
break;
default:
break;
}
break;
}
/* It is possible to hit contradictory sequence. For instance:
jump_insn
NOTE_INSN_LOOP_BEG
barrier
Where barrier belongs to jump_insn, but the note does not. This can be
created by removing the basic block originally following
NOTE_INSN_LOOP_BEG. In such case reorder the notes. */
for (insn = last_insn; insn != bb->end; insn = prev)
{
prev = PREV_INSN (insn);
if (GET_CODE (insn) == NOTE)
switch (NOTE_LINE_NUMBER (insn))
{
case NOTE_INSN_LOOP_END:
case NOTE_INSN_BLOCK_END:
case NOTE_INSN_DELETED:
case NOTE_INSN_DELETED_LABEL:
continue;
default:
reorder_insns (insn, insn, last_insn);
}
}
return last_insn;
}
/* Locate or create a label for a given basic block. */
static rtx
label_for_bb (bb)
basic_block bb;
{
rtx label = bb->head;
if (GET_CODE (label) != CODE_LABEL)
{
if (rtl_dump_file)
fprintf (rtl_dump_file, "Emitting label for block %d\n", bb->index);
label = block_label (bb);
}
return label;
}
/* Locate the effective beginning and end of the insn chain for each
block, as defined by skip_insns_after_block above. */
static void
record_effective_endpoints ()
{
rtx next_insn = get_insns ();
basic_block bb;
FOR_EACH_BB (bb)
{
rtx end;
if (PREV_INSN (bb->head) && next_insn != bb->head)
RBI (bb)->header = unlink_insn_chain (next_insn,
PREV_INSN (bb->head));
end = skip_insns_after_block (bb);
if (NEXT_INSN (bb->end) && bb->end != end)
RBI (bb)->footer = unlink_insn_chain (NEXT_INSN (bb->end), end);
next_insn = NEXT_INSN (bb->end);
}
function_footer = next_insn;
if (function_footer)
function_footer = unlink_insn_chain (function_footer, get_last_insn ());
}
/* Build a varray mapping INSN_UID to lexical block. Return it. */
void
scope_to_insns_initialize ()
{
tree block = NULL;
rtx insn, next;
for (insn = get_insns (); insn; insn = next)
{
next = NEXT_INSN (insn);
if (active_insn_p (insn)
&& GET_CODE (PATTERN (insn)) != ADDR_VEC
&& GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC)
INSN_SCOPE (insn) = block;
else if (GET_CODE (insn) == NOTE)
{
switch (NOTE_LINE_NUMBER (insn))
{
case NOTE_INSN_BLOCK_BEG:
block = NOTE_BLOCK (insn);
delete_insn (insn);
break;
case NOTE_INSN_BLOCK_END:
block = BLOCK_SUPERCONTEXT (block);
delete_insn (insn);
break;
default:
break;
}
}
}
/* Tag the blocks with a depth number so that change_scope can find
the common parent easily. */
set_block_levels (DECL_INITIAL (cfun->decl), 0);
}
/* For each lexical block, set BLOCK_NUMBER to the depth at which it is
found in the block tree. */
static void
set_block_levels (block, level)
tree block;
int level;
{
while (block)
{
BLOCK_NUMBER (block) = level;
set_block_levels (BLOCK_SUBBLOCKS (block), level + 1);
block = BLOCK_CHAIN (block);
}
}
/* Return sope resulting from combination of S1 and S2. */
tree
choose_inner_scope (s1, s2)
tree s1, s2;
{
if (!s1)
return s2;
if (!s2)
return s1;
if (BLOCK_NUMBER (s1) > BLOCK_NUMBER (s2))
return s1;
return s2;
}
/* Emit lexical block notes needed to change scope from S1 to S2. */
static void
change_scope (orig_insn, s1, s2)
rtx orig_insn;
tree s1, s2;
{
rtx insn = orig_insn;
tree com = NULL_TREE;
tree ts1 = s1, ts2 = s2;
tree s;
while (ts1 != ts2)
{
if (ts1 == NULL || ts2 == NULL)
abort ();
if (BLOCK_NUMBER (ts1) > BLOCK_NUMBER (ts2))
ts1 = BLOCK_SUPERCONTEXT (ts1);
else if (BLOCK_NUMBER (ts1) < BLOCK_NUMBER (ts2))
ts2 = BLOCK_SUPERCONTEXT (ts2);
else
{
ts1 = BLOCK_SUPERCONTEXT (ts1);
ts2 = BLOCK_SUPERCONTEXT (ts2);
}
}
com = ts1;
/* Close scopes. */
s = s1;
while (s != com)
{
rtx note = emit_note_before (NOTE_INSN_BLOCK_END, insn);
NOTE_BLOCK (note) = s;
s = BLOCK_SUPERCONTEXT (s);
}
/* Open scopes. */
s = s2;
while (s != com)
{
insn = emit_note_before (NOTE_INSN_BLOCK_BEG, insn);
NOTE_BLOCK (insn) = s;
s = BLOCK_SUPERCONTEXT (s);
}
}
/* Rebuild all the NOTE_INSN_BLOCK_BEG and NOTE_INSN_BLOCK_END notes based
on the scope tree and the newly reordered instructions. */
void
scope_to_insns_finalize ()
{
tree cur_block = DECL_INITIAL (cfun->decl);
rtx insn, note;
insn = get_insns ();
if (!active_insn_p (insn))
insn = next_active_insn (insn);
for (; insn; insn = next_active_insn (insn))
{
tree this_block;
this_block = INSN_SCOPE (insn);
/* For sequences compute scope resulting from merging all scopes
of instructions nested inside. */
if (GET_CODE (PATTERN (insn)) == SEQUENCE)
{
int i;
rtx body = PATTERN (insn);
this_block = NULL;
for (i = 0; i < XVECLEN (body, 0); i++)
this_block = choose_inner_scope (this_block,
INSN_SCOPE (XVECEXP (body, 0, i)));
}
if (! this_block)
continue;
if (this_block != cur_block)
{
change_scope (insn, cur_block, this_block);
cur_block = this_block;
}
}
/* change_scope emits before the insn, not after. */
note = emit_note (NULL, NOTE_INSN_DELETED);
change_scope (note, cur_block, DECL_INITIAL (cfun->decl));
delete_insn (note);
reorder_blocks ();
}
/* Given a reorder chain, rearrange the code to match. */
static void
fixup_reorder_chain ()
{
basic_block bb, prev_bb;
int index;
rtx insn = NULL;
/* First do the bulk reordering -- rechain the blocks without regard to
the needed changes to jumps and labels. */
for (bb = ENTRY_BLOCK_PTR->next_bb, index = 0;
bb != 0;
bb = RBI (bb)->next, index++)
{
if (RBI (bb)->header)
{
if (insn)
NEXT_INSN (insn) = RBI (bb)->header;
else
set_first_insn (RBI (bb)->header);
PREV_INSN (RBI (bb)->header) = insn;
insn = RBI (bb)->header;
while (NEXT_INSN (insn))
insn = NEXT_INSN (insn);
}
if (insn)
NEXT_INSN (insn) = bb->head;
else
set_first_insn (bb->head);
PREV_INSN (bb->head) = insn;
insn = bb->end;
if (RBI (bb)->footer)
{
NEXT_INSN (insn) = RBI (bb)->footer;
PREV_INSN (RBI (bb)->footer) = insn;
while (NEXT_INSN (insn))
insn = NEXT_INSN (insn);
}
}
if (index != n_basic_blocks)
abort ();
NEXT_INSN (insn) = function_footer;
if (function_footer)
PREV_INSN (function_footer) = insn;
while (NEXT_INSN (insn))
insn = NEXT_INSN (insn);
set_last_insn (insn);
#ifdef ENABLE_CHECKING
verify_insn_chain ();
#endif
/* Now add jumps and labels as needed to match the blocks new
outgoing edges. */
for (bb = ENTRY_BLOCK_PTR->next_bb; bb ; bb = RBI (bb)->next)
{
edge e_fall, e_taken, e;
rtx bb_end_insn;
basic_block nb;
if (bb->succ == NULL)
continue;
/* Find the old fallthru edge, and another non-EH edge for
a taken jump. */
e_taken = e_fall = NULL;
for (e = bb->succ; e ; e = e->succ_next)
if (e->flags & EDGE_FALLTHRU)
e_fall = e;
else if (! (e->flags & EDGE_EH))
e_taken = e;
bb_end_insn = bb->end;
if (GET_CODE (bb_end_insn) == JUMP_INSN)
{
if (any_condjump_p (bb_end_insn))
{
/* If the old fallthru is still next, nothing to do. */
if (RBI (bb)->next == e_fall->dest
|| (!RBI (bb)->next
&& e_fall->dest == EXIT_BLOCK_PTR))
continue;
if (!e_taken)
e_taken = e_fall;
/* The degenerated case of conditional jump jumping to the next
instruction can happen on target having jumps with side
effects.
Create temporarily the duplicated edge representing branch.
It will get unidentified by force_nonfallthru_and_redirect
that would otherwise get confused by fallthru edge not pointing
to the next basic block. */
if (!e_taken)
{
rtx note;
edge e_fake;
e_fake = unchecked_make_edge (bb, e_fall->dest, 0);
note = find_reg_note (bb->end, REG_BR_PROB, NULL_RTX);
if (note)
{
int prob = INTVAL (XEXP (note, 0));
e_fake->probability = prob;
e_fake->count = e_fall->count * prob / REG_BR_PROB_BASE;
e_fall->probability -= e_fall->probability;
e_fall->count -= e_fake->count;
if (e_fall->probability < 0)
e_fall->probability = 0;
if (e_fall->count < 0)
e_fall->count = 0;
}
}
/* There is one special case: if *neither* block is next,
such as happens at the very end of a function, then we'll
need to add a new unconditional jump. Choose the taken
edge based on known or assumed probability. */
else if (RBI (bb)->next != e_taken->dest)
{
rtx note = find_reg_note (bb_end_insn, REG_BR_PROB, 0);
if (note
&& INTVAL (XEXP (note, 0)) < REG_BR_PROB_BASE / 2
&& invert_jump (bb_end_insn,
label_for_bb (e_fall->dest), 0))
{
e_fall->flags &= ~EDGE_FALLTHRU;
e_taken->flags |= EDGE_FALLTHRU;
update_br_prob_note (bb);
e = e_fall, e_fall = e_taken, e_taken = e;
}
}
/* Otherwise we can try to invert the jump. This will
basically never fail, however, keep up the pretense. */
else if (invert_jump (bb_end_insn,
label_for_bb (e_fall->dest), 0))
{
e_fall->flags &= ~EDGE_FALLTHRU;
e_taken->flags |= EDGE_FALLTHRU;
update_br_prob_note (bb);
continue;
}
}
else if (returnjump_p (bb_end_insn))
continue;
else
{
/* Otherwise we have some switch or computed jump. In the
99% case, there should not have been a fallthru edge. */
if (! e_fall)
continue;
#ifdef CASE_DROPS_THROUGH
/* Except for VAX. Since we didn't have predication for the
tablejump, the fallthru block should not have moved. */
if (RBI (bb)->next == e_fall->dest)
continue;
bb_end_insn = skip_insns_after_block (bb);
#else
abort ();
#endif
}
}
else
{
/* No fallthru implies a noreturn function with EH edges, or
something similarly bizarre. In any case, we don't need to
do anything. */
if (! e_fall)
continue;
/* If the fallthru block is still next, nothing to do. */
if (RBI (bb)->next == e_fall->dest)
continue;
/* A fallthru to exit block. */
if (!RBI (bb)->next && e_fall->dest == EXIT_BLOCK_PTR)
continue;
}
/* We got here if we need to add a new jump insn. */
nb = force_nonfallthru (e_fall);
if (nb)
{
alloc_aux_for_block (nb, sizeof (struct reorder_block_def));
RBI (nb)->visited = 1;
RBI (nb)->next = RBI (bb)->next;
RBI (bb)->next = nb;
/* Don't process this new block. */
bb = nb;
}
}
/* Put basic_block_info in the new order. */
if (rtl_dump_file)
{
fprintf (rtl_dump_file, "Reordered sequence:\n");
for (bb = ENTRY_BLOCK_PTR->next_bb, index = 0; bb; bb = RBI (bb)->next, index ++)
{
fprintf (rtl_dump_file, " %i ", index);
if (RBI (bb)->original)
fprintf (rtl_dump_file, "duplicate of %i ",
RBI (bb)->original->index);
else if (forwarder_block_p (bb) && GET_CODE (bb->head) != CODE_LABEL)
fprintf (rtl_dump_file, "compensation ");
else
fprintf (rtl_dump_file, "bb %i ", bb->index);
fprintf (rtl_dump_file, " [%i]\n", bb->frequency);
}
}
prev_bb = ENTRY_BLOCK_PTR;
bb = ENTRY_BLOCK_PTR->next_bb;
index = 0;
for (; bb; prev_bb = bb, bb = RBI (bb)->next, index ++)
{
bb->index = index;
BASIC_BLOCK (index) = bb;
bb->prev_bb = prev_bb;
prev_bb->next_bb = bb;
}
prev_bb->next_bb = EXIT_BLOCK_PTR;
EXIT_BLOCK_PTR->prev_bb = prev_bb;
}
/* Perform sanity checks on the insn chain.
1. Check that next/prev pointers are consistent in both the forward and
reverse direction.
2. Count insns in chain, going both directions, and check if equal.
3. Check that get_last_insn () returns the actual end of chain. */
void
verify_insn_chain ()
{
rtx x, prevx, nextx;
int insn_cnt1, insn_cnt2;
for (prevx = NULL, insn_cnt1 = 1, x = get_insns ();
x != 0;
prevx = x, insn_cnt1++, x = NEXT_INSN (x))
if (PREV_INSN (x) != prevx)
abort ();
if (prevx != get_last_insn ())
abort ();
for (nextx = NULL, insn_cnt2 = 1, x = get_last_insn ();
x != 0;
nextx = x, insn_cnt2++, x = PREV_INSN (x))
if (NEXT_INSN (x) != nextx)
abort ();
if (insn_cnt1 != insn_cnt2)
abort ();
}
/* Remove any unconditional jumps and forwarder block creating fallthru
edges instead. During BB reordering, fallthru edges are not required
to target next basic block in the linear CFG layout, so the unconditional
jumps are not needed. */
static void
cleanup_unconditional_jumps ()
{
basic_block bb;
FOR_EACH_BB (bb)
{
if (!bb->succ)
continue;
if (bb->succ->flags & EDGE_FALLTHRU)
continue;
if (!bb->succ->succ_next)
{
rtx insn;
if (GET_CODE (bb->head) != CODE_LABEL && forwarder_block_p (bb)
&& bb->prev_bb != ENTRY_BLOCK_PTR)
{
basic_block prev = bb->prev_bb;
if (rtl_dump_file)
fprintf (rtl_dump_file, "Removing forwarder BB %i\n",
bb->index);
redirect_edge_succ_nodup (bb->pred, bb->succ->dest);
flow_delete_block (bb);
bb = prev;
}
else if (simplejump_p (bb->end))
{
rtx jump = bb->end;
if (rtl_dump_file)
fprintf (rtl_dump_file, "Removing jump %i in BB %i\n",
INSN_UID (jump), bb->index);
delete_insn (jump);
bb->succ->flags |= EDGE_FALLTHRU;
}
else
continue;
insn = NEXT_INSN (bb->end);
while (insn
&& (GET_CODE (insn) != NOTE
|| NOTE_LINE_NUMBER (insn) != NOTE_INSN_BASIC_BLOCK))
{
rtx next = NEXT_INSN (insn);
if (GET_CODE (insn) == BARRIER)
delete_barrier (insn);
insn = next;
}
}
}
}
/* The block falling through to exit must be the last one in the
reordered chain. Ensure that this condition is met. */
static void
fixup_fallthru_exit_predecessor ()
{
edge e;
basic_block bb = NULL;
for (e = EXIT_BLOCK_PTR->pred; e; e = e->pred_next)
if (e->flags & EDGE_FALLTHRU)
bb = e->src;
if (bb && RBI (bb)->next)
{
basic_block c = ENTRY_BLOCK_PTR->next_bb;
while (RBI (c)->next != bb)
c = RBI (c)->next;
RBI (c)->next = RBI (bb)->next;
while (RBI (c)->next)
c = RBI (c)->next;
RBI (c)->next = bb;
RBI (bb)->next = NULL;
}
}
/* Return true in case it is possible to duplicate the basic block BB. */
bool
cfg_layout_can_duplicate_bb_p (bb)
basic_block bb;
{
rtx next;
edge s;
if (bb == EXIT_BLOCK_PTR || bb == ENTRY_BLOCK_PTR)
return false;
/* Duplicating fallthru block to exit would require adding a jump
and splitting the real last BB. */
for (s = bb->succ; s; s = s->succ_next)
if (s->dest == EXIT_BLOCK_PTR && s->flags & EDGE_FALLTHRU)
return false;
/* Do not attempt to duplicate tablejumps, as we need to unshare
the dispatch table. This is dificult to do, as the instructions
computing jump destination may be hoisted outside the basic block. */
if (GET_CODE (bb->end) == JUMP_INSN && JUMP_LABEL (bb->end)
&& (next = next_nonnote_insn (JUMP_LABEL (bb->end)))
&& GET_CODE (next) == JUMP_INSN
&& (GET_CODE (PATTERN (next)) == ADDR_VEC
|| GET_CODE (PATTERN (next)) == ADDR_DIFF_VEC))
return false;
return true;
}
static rtx
duplicate_insn_chain (from, to)
rtx from, to;
{
rtx insn, last;
/* Avoid updating of boundaries of previous basic block. The
note will get removed from insn stream in fixup. */
last = emit_note (NULL, NOTE_INSN_DELETED);
/* Create copy at the end of INSN chain. The chain will
be reordered later. */
for (insn = from; insn != NEXT_INSN (to); insn = NEXT_INSN (insn))
{
rtx new;
switch (GET_CODE (insn))
{
case INSN:
case CALL_INSN:
case JUMP_INSN:
/* Avoid copying of dispatch tables. We never duplicate
tablejumps, so this can hit only in case the table got
moved far from original jump. */
if (GET_CODE (PATTERN (insn)) == ADDR_VEC
|| GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC)
break;
new = emit_copy_of_insn_after (insn, get_last_insn ());
break;
case CODE_LABEL:
break;
case BARRIER:
emit_barrier ();
break;
case NOTE:
switch (NOTE_LINE_NUMBER (insn))
{
/* In case prologue is empty and function contain label
in first BB, we may want to copy the block. */
case NOTE_INSN_PROLOGUE_END:
case NOTE_INSN_LOOP_VTOP:
case NOTE_INSN_LOOP_CONT:
case NOTE_INSN_LOOP_BEG:
case NOTE_INSN_LOOP_END:
/* Strip down the loop notes - we don't really want to keep
them consistent in loop copies. */
case NOTE_INSN_DELETED:
case NOTE_INSN_DELETED_LABEL:
/* No problem to strip these. */
case NOTE_INSN_EPILOGUE_BEG:
case NOTE_INSN_FUNCTION_END:
/* Debug code expect these notes to exist just once.
Keep them in the master copy.
??? It probably makes more sense to duplicate them for each
epilogue copy. */
case NOTE_INSN_FUNCTION_BEG:
/* There is always just single entry to function. */
case NOTE_INSN_BASIC_BLOCK:
break;
/* There is no purpose to duplicate prologue. */
case NOTE_INSN_BLOCK_BEG:
case NOTE_INSN_BLOCK_END:
/* The BLOCK_BEG/BLOCK_END notes should be eliminated when BB
reordering is in the progress. */
case NOTE_INSN_EH_REGION_BEG:
case NOTE_INSN_EH_REGION_END:
/* Should never exist at BB duplication time. */
abort ();
break;
case NOTE_INSN_REPEATED_LINE_NUMBER:
emit_note (NOTE_SOURCE_FILE (insn), NOTE_LINE_NUMBER (insn));
break;
default:
if (NOTE_LINE_NUMBER (insn) < 0)
abort ();
/* It is possible that no_line_number is set and the note
won't be emitted. */
emit_note (NOTE_SOURCE_FILE (insn), NOTE_LINE_NUMBER (insn));
}
break;
default:
abort ();
}
}
insn = NEXT_INSN (last);
delete_insn (last);
return insn;
}
/* Redirect Edge to DEST. */
void
cfg_layout_redirect_edge (e, dest)
edge e;
basic_block dest;
{
basic_block src = e->src;
basic_block old_next_bb = src->next_bb;
/* Redirect_edge_and_branch may decide to turn branch into fallthru edge
in the case the basic block appears to be in sequence. Avoid this
transformation. */
src->next_bb = NULL;
if (e->flags & EDGE_FALLTHRU)
{
/* Redirect any branch edges unified with the fallthru one. */
if (GET_CODE (src->end) == JUMP_INSN
&& JUMP_LABEL (src->end) == e->dest->head)
{
if (!redirect_jump (src->end, block_label (dest), 0))
abort ();
}
/* In case we are redirecting fallthru edge to the branch edge
of conditional jump, remove it. */
if (src->succ->succ_next
&& !src->succ->succ_next->succ_next)
{
edge s = e->succ_next ? e->succ_next : src->succ;
if (s->dest == dest
&& any_condjump_p (src->end)
&& onlyjump_p (src->end))
delete_insn (src->end);
}
redirect_edge_succ_nodup (e, dest);
}
else
redirect_edge_and_branch (e, dest);
/* We don't want simplejumps in the insn stream during cfglayout. */
if (simplejump_p (src->end))
{
delete_insn (src->end);
delete_barrier (NEXT_INSN (src->end));
src->succ->flags |= EDGE_FALLTHRU;
}
src->next_bb = old_next_bb;
}
/* Create a duplicate of the basic block BB and redirect edge E into it. */
basic_block
cfg_layout_duplicate_bb (bb, e)
basic_block bb;
edge e;
{
rtx insn;
edge s, n;
basic_block new_bb;
gcov_type new_count = e ? e->count : 0;
if (bb->count < new_count)
new_count = bb->count;
if (!bb->pred)
abort ();
#ifdef ENABLE_CHECKING
if (!cfg_layout_can_duplicate_bb_p (bb))
abort ();
#endif
insn = duplicate_insn_chain (bb->head, bb->end);
new_bb = create_basic_block (insn,
insn ? get_last_insn () : NULL,
EXIT_BLOCK_PTR->prev_bb);
alloc_aux_for_block (new_bb, sizeof (struct reorder_block_def));
if (RBI (bb)->header)
{
insn = RBI (bb)->header;
while (NEXT_INSN (insn))
insn = NEXT_INSN (insn);
insn = duplicate_insn_chain (RBI (bb)->header, insn);
if (insn)
RBI (new_bb)->header = unlink_insn_chain (insn, get_last_insn ());
}
if (RBI (bb)->footer)
{
insn = RBI (bb)->footer;
while (NEXT_INSN (insn))
insn = NEXT_INSN (insn);
insn = duplicate_insn_chain (RBI (bb)->footer, insn);
if (insn)
RBI (new_bb)->footer = unlink_insn_chain (insn, get_last_insn ());
}
if (bb->global_live_at_start)
{
new_bb->global_live_at_start = OBSTACK_ALLOC_REG_SET (&flow_obstack);
new_bb->global_live_at_end = OBSTACK_ALLOC_REG_SET (&flow_obstack);
COPY_REG_SET (new_bb->global_live_at_start, bb->global_live_at_start);
COPY_REG_SET (new_bb->global_live_at_end, bb->global_live_at_end);
}
new_bb->loop_depth = bb->loop_depth;
new_bb->flags = bb->flags;
for (s = bb->succ; s; s = s->succ_next)
{
n = make_edge (new_bb, s->dest, s->flags);
n->probability = s->probability;
if (new_count)
/* Take care for overflows! */
n->count = s->count * (new_count * 10000 / bb->count) / 10000;
else
n->count = 0;
s->count -= n->count;
}
new_bb->count = new_count;
bb->count -= new_count;
if (e)
{
new_bb->frequency = EDGE_FREQUENCY (e);
bb->frequency -= EDGE_FREQUENCY (e);
cfg_layout_redirect_edge (e, new_bb);
}
if (bb->count < 0)
bb->count = 0;
if (bb->frequency < 0)
bb->frequency = 0;
RBI (new_bb)->original = bb;
return new_bb;
}
/* Main entry point to this module - initialize the datastructures for
CFG layout changes. It keeps LOOPS up-to-date if not null. */
void
cfg_layout_initialize ()
{
/* Our algorithm depends on fact that there are now dead jumptables
around the code. */
alloc_aux_for_blocks (sizeof (struct reorder_block_def));
cleanup_unconditional_jumps ();
record_effective_endpoints ();
}
/* Finalize the changes: reorder insn list according to the sequence, enter
compensation code, rebuild scope forest. */
void
cfg_layout_finalize ()
{
fixup_fallthru_exit_predecessor ();
fixup_reorder_chain ();
#ifdef ENABLE_CHECKING
verify_insn_chain ();
#endif
free_aux_for_blocks ();
#ifdef ENABLE_CHECKING
verify_flow_info ();
#endif
}
| acassis/xap-gcc | gcc/cfglayout.c | C | gpl-2.0 | 26,362 |
<h2>Listas de Usuários</h2>
<p>A lista de usuários <strong>Disponíveis</strong> contém os usuários que passaram pelos Filtros Ativos. Por exemplo, se a seção dos Filtros ativos contém somente um filtro para usuários cujo país é a Rômenia, então a lista dos usuários Disponíveis conterá apenas usuários que definiram a Romênia como seu país na página de perfil.</p>
<p>A lista de usuários<strong>Selecionados</strong> contém os usuários que foram adicionados a esta lista por você, usando os botões da seção <em>Lista de usuários selecionados...</em>. Quando o botão <em>Vá</em> da seção <em>Com os usuários selecionados...</em> é pressionado, a operação escolhida será executada com relação aos usuários da lista.</p> | eduardolfalcao/dialoga19 | moodledata/lang/pt_br_utf8/help/bulkusers/lists.html | HTML | gpl-2.0 | 759 |
/**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
*
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*
*
* Credits goes to all Open Source Core Developer Groups listed below
* Please do not change here something, ragarding the developer credits, except the "developed by XXXX".
* Even if you edit a lot of files in this source, you still have no rights to call it as "your Core".
* Everybody knows that this Emulator Core was developed by Aion Lightning
* @-Aion-Unique-
* @-Aion-Lightning
* @Aion-Engine
* @Aion-Extreme
* @Aion-NextGen
* @Aion-Core Dev.
*/
package ai.instance.IdgelDome;
import com.aionemu.commons.utils.Rnd;
import com.aionemu.gameserver.ai2.AIName;
import com.aionemu.gameserver.ai2.NpcAI2;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.skillengine.SkillEngine;
import com.aionemu.gameserver.utils.MathUtil;
import com.aionemu.gameserver.utils.ThreadPoolManager;
import com.aionemu.gameserver.world.WorldPosition;
import com.aionemu.gameserver.world.knownlist.Visitor;
/**
* @author GiGatR00n v4.7.5.x
*/
@AIName("unstable_ide_energy") //855008, 855012
public class UnstableIdeEnergyAI2 extends NpcAI2 {
private Player LuckyPlayer;
private boolean gotIt = false;
@Override
protected void handleSpawned() {
super.handleSpawned();
switch (getNpcId()) {
case 855008:
AttackPlayers();
case 855012:
useSkill(21559);//SkillId:21559 (Ide Explosion)
}
DeleteNpc();//After 3-Seconds the Unstable Ide Energy will be deleted.
}
@Override
public void handleDespawned() {
super.handleDespawned();
}
@Override
protected void handleDied() {
super.handleDied();
}
private void useSkill(int skillId) {
SkillEngine.getInstance().getSkill(getOwner(), skillId, 1, getOwner()).useSkill();
}
private Player getLuckyPlayer() {
LuckyPlayer = null; gotIt = false;
getPosition().getWorldMapInstance().doOnAllPlayers(new Visitor<Player>() {
@Override
public void visit(Player player) {
if (!gotIt) {
/* if it couldn't find any lucky player, then it returns the last player */
LuckyPlayer = player;
int rand = Rnd.get(1, 3);
if (rand == 3) {
gotIt = true;
}
}
}
});
return LuckyPlayer;
}
private void AttackPlayers() {
/*
* The Players got lucky. No one is intended to be attacked.
*/
Player player = getLuckyPlayer();
if (player == null) {
return;
}
WorldPosition Pos = player.getPosition();
if (!MathUtil.isInSphere(player, 284.359385f, 334.957915f, 80f, 25f) && !MathUtil.isInSphere(player, 245.880305f, 183.984715f, 80f, 25f)) {
float r1 = Rnd.get(-15, 15);
float r2 = Rnd.get(-15, 15);
getOwner().setXYZH(Pos.getX() + r1, Pos.getY() + r2, Pos.getZ(), Pos.getHeading());
useSkill(21559);//SkillId:21559 (Ide Explosion)
}
}
private void DeleteNpc() {
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
getOwner().getController().onDelete();
}
}, 3000);//After 3-Seconds the Unstable Ide Energy will be deleted.
}
} | GiGatR00n/Aion-Core-v4.7.5 | AC-Game/data/scripts/system/handlers/ai/instance/IdgelDome/UnstableIdeEnergyAI2.java | Java | gpl-2.0 | 4,039 |
using System;
using System.Collections.Generic;
using MrCMS.Entities.Documents;
using MrCMS.Entities.Documents.Metadata;
using MrCMS.Web.Apps.Ecommerce.Pages;
namespace MrCMS.Web.Apps.Ecommerce.Metadata
{
public class ProductSearchMetadata : DocumentMetadataMap<ProductSearch>
{
public override ChildrenListType ChildrenListType
{
get { return ChildrenListType.WhiteList; }
}
public override IEnumerable<Type> ChildrenList
{
get { yield return typeof(Category); }
}
public override bool ShowChildrenInAdminNav { get { return false; } }
public override string WebGetController
{
get { return "ProductSearch"; }
}
public override string WebGetAction
{
get { return "Show"; }
}
public override bool ChildrenMaintainHierarchy
{
get { return false; }
}
public override string DefaultLayoutName
{
get
{
return "Search Layout";
}
}
}
} | MaiLT/Ecommerce | MrCMS.Web/Apps/Ecommerce/Metadata/ProductSearchMetadata.cs | C# | gpl-2.0 | 1,111 |
/*
* This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef MANGOSSERVER_MOVESPLINEINIT_H
#define MANGOSSERVER_MOVESPLINEINIT_H
#include "Movement/MoveSplineInitArgs.h"
#include "MotionGenerators/PathFinder.h"
class Unit;
namespace Movement
{
/* Initializes and launches spline movement
*/
class MoveSplineInit
{
public:
explicit MoveSplineInit(Unit& m);
/* Final pass of initialization that launches spline movement.
* @return duration - estimated travel time
*/
int32 Launch();
/* Stop any creature movement */
void Stop(bool forceSend = false);
/* Adds final facing animation
* sets unit's facing to specified point/angle after all path done
* you can have only one final facing: previous will be overriden
*/
void SetFacing(float angle);
void SetFacing(Vector3 const& spot);
void SetFacing(const Unit* target);
/* Initializes movement by path
* @param path - array of points, shouldn't be empty
* @param pointId - Id of fisrt point of the path. Example: when third path point will be done it will notify that pointId + 3 done
*/
void MovebyPath(const PointsArray& controls, int32 path_offset = 0);
/* Initializes simple A to B mition, A is current unit's position, B is destination
*/
void MoveTo(const Vector3& dest, bool generatePath = false, bool forceDestination = false);
void MoveTo(float x, float y, float z, bool generatePath = false, bool forceDestination = false);
/* Sets Id of fisrt point of the path. When N-th path point will be done ILisener will notify that pointId + N done
* Needed for waypoint movement where path splitten into parts
*/
void SetFirstPointId(int32 pointId) { args.path_Idx_offset = pointId; }
/* Enables CatmullRom spline interpolation mode, enables flying animation. Disabled by default
*/
void SetFly();
/* Enables walk mode. Disabled by default
*/
void SetWalk(bool enable);
/* Makes movement cyclic. Disabled by default
*/
void SetCyclic();
/* Enables falling mode. Disabled by default
*/
void SetFall();
/* Sets the velocity (in case you want to have custom movement velocity)
* if no set, speed will be selected based on unit's speeds and current movement mode
* Has no effect if falling mode enabled
* velocity shouldn't be negative
*/
void SetVelocity(float vel);
PointsArray& Path() { return args.path; }
protected:
MoveSplineInitArgs args;
Unit& unit;
};
inline void MoveSplineInit::SetFly() { args.flags.flying = true;}
inline void MoveSplineInit::SetWalk(bool enable) { args.flags.runmode = !enable;}
inline void MoveSplineInit::SetCyclic() { args.flags.cyclic = true;}
inline void MoveSplineInit::SetFall() { args.flags.falling = true;}
inline void MoveSplineInit::SetVelocity(float vel) { args.velocity = vel;}
inline void MoveSplineInit::MovebyPath(const PointsArray& controls, int32 path_offset)
{
args.path_Idx_offset = path_offset;
args.path.assign(controls.begin(), controls.end());
}
inline void MoveSplineInit::MoveTo(float x, float y, float z, bool generatePath, bool forceDestination)
{
Vector3 v(x, y, z);
MoveTo(v, generatePath, forceDestination);
}
inline void MoveSplineInit::MoveTo(const Vector3& dest, bool generatePath, bool forceDestination)
{
if (generatePath)
{
PathFinder path(&unit);
path.calculate(dest.x, dest.y, dest.z, forceDestination);
MovebyPath(path.getPath());
}
else
{
args.path_Idx_offset = 0;
args.path.resize(2);
args.path[1] = dest;
}
}
inline void MoveSplineInit::SetFacing(Vector3 const& spot)
{
args.facing.f.x = spot.x;
args.facing.f.y = spot.y;
args.facing.f.z = spot.z;
args.flags.EnableFacingPoint();
}
}
#endif // MANGOSSERVER_MOVESPLINEINIT_H
| krullgor/mangos-tbc | src/game/Movement/MoveSplineInit.h | C | gpl-2.0 | 5,205 |
/*
* linux/arch/arm/mach-sa1100/system3.c
*
* Copyright (C) 2001 Stefan Eletzhofer <stefan.eletzhofer@eletztrick.de>
*
* $Id: system3.c,v 1.1.6.1 2001/12/04 17:28:06 seletz Exp $
*
* This file contains all PT Sytsem 3 tweaks. Based on original work from
* Nicolas Pitre's assabet fixes
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* $Log: system3.c,v $
* Revision 1.1.6.1 2001/12/04 17:28:06 seletz
* - merged from previous branch
*
* Revision 1.1.4.3 2001/12/04 15:16:31 seletz
* - merged from linux_2_4_13_ac5_rmk2
*
* Revision 1.1.4.2 2001/11/19 17:18:57 seletz
* - more code cleanups
*
* Revision 1.1.4.1 2001/11/16 13:52:05 seletz
* - PT Digital Board Support Code
*
* Revision 1.1.2.2 2001/11/05 16:46:18 seletz
* - cleanups
*
* Revision 1.1.2.1 2001/10/15 16:00:43 seletz
* - first revision working with new board
*
*
*/
#include <linux/config.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/tty.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/cpufreq.h>
#include <asm/hardware.h>
#include <asm/setup.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <asm/mach/serial_sa1100.h>
#include <asm/arch/irq.h>
#include <linux/serial_core.h>
#include "generic.h"
#include "sa1111.h"
#define DEBUG 1
#ifdef DEBUG
# define DPRINTK( x, args... ) printk( "%s: line %d: "x, __FUNCTION__, __LINE__, ## args );
#else
# define DPRINTK( x, args... ) /* nix */
#endif
/**********************************************************************
* prototypes
*/
/* init funcs */
static void __init fixup_system3(struct machine_desc *desc,
struct param_struct *params, char **cmdline, struct meminfo *mi);
static void __init get_system3_scr(void);
static int __init system3_init(void);
static void __init system3_init_irq(void);
static void __init system3_map_io(void);
static void system3_IRQ_demux( int irq, void *dev_id, struct pt_regs *regs );
static int system3_get_mctrl(struct uart_port *port);
static void system3_set_mctrl(struct uart_port *port, u_int mctrl);
static void system3_uart_pm(struct uart_port *port, u_int state, u_int oldstate);
static int sdram_notifier(struct notifier_block *nb, unsigned long event, void *data);
extern void convert_to_tag_list(struct param_struct *params, int mem_init);
/**********************************************************************
* global data
*/
/**********************************************************************
* static data
*/
static struct map_desc system3_io_desc[] __initdata = {
/* virtual physical length domain r w c b */
{ 0xe8000000, 0x00000000, 0x01000000, DOMAIN_IO, 0, 1, 0, 0 }, /* Flash bank 0 */
{ 0xf3000000, 0x10000000, 0x00100000, DOMAIN_IO, 0, 1, 0, 0 }, /* System Registers */
{ 0xf4000000, 0x40000000, 0x00100000, DOMAIN_IO, 0, 1, 0, 0 }, /* SA-1111 */
LAST_DESC
};
static struct sa1100_port_fns system3_port_fns __initdata = {
set_mctrl: system3_set_mctrl,
get_mctrl: system3_get_mctrl,
pm: system3_uart_pm,
};
static struct irqaction system3_irq = {
name: "PT Digital Board SA1111 IRQ",
handler: system3_IRQ_demux,
flags: SA_INTERRUPT
};
static struct notifier_block system3_clkchg_block = {
notifier_call: sdram_notifier,
};
/**********************************************************************
* Static functions
*/
static void __init system3_map_io(void)
{
DPRINTK( "%s\n", "START" );
sa1100_map_io();
iotable_init(system3_io_desc);
sa1100_register_uart_fns(&system3_port_fns);
sa1100_register_uart(0, 1); /* com port */
sa1100_register_uart(1, 2);
sa1100_register_uart(2, 3); /* radio module */
Ser1SDCR0 |= SDCR0_SUS;
}
/*********************************************************************
* Install IRQ handler
*/
static void system3_IRQ_demux( int irq, void *dev_id, struct pt_regs *regs )
{
u_char irr;
for(;;){
//irr = PTCPLD_REG_IRQSR & (PT_IRQ_LAN | PT_IRQ_USAR | PT_IRQ_SA1111);
irr = PT_IRQSR & (PT_IRQ_LAN | PT_IRQ_SA1111);
irr ^= (PT_IRQ_LAN);
if (!irr) break;
if( irr & PT_IRQ_LAN )
do_IRQ(IRQ_SYSTEM3_SMC9196, regs);
#if 0
/* Highspeed Serial Bus not yet used */
if( irr & PT_IRQ_USAR )
do_IRQ(PT_USAR_IRQ, regs);
#endif
if( irr & PT_IRQ_SA1111 )
sa1111_IRQ_demux(irq, dev_id, regs);
}
}
static void __init system3_init_irq(void)
{
int irq;
DPRINTK( "%s\n", "START" );
/* SA1111 IRQ not routed to a GPIO. */
sa1111_init_irq(-1);
/* setup extra IRQs */
irq = IRQ_SYSTEM3_SMC9196;
irq_desc[irq].valid = 1;
irq_desc[irq].probe_ok = 1;
#if 0
/* Highspeed Serial Bus not yet used */
irq = PT_USAR_IRQ;
irq_desc[irq].valid = 1;
irq_desc[irq].probe_ok = 1;
#endif
/* IRQ by CPLD */
set_GPIO_IRQ_edge( GPIO_GPIO(25), GPIO_RISING_EDGE );
setup_arm_irq( IRQ_GPIO25, &system3_irq );
}
/**********************************************************************
* On system 3 limit cpu frequency to 206 Mhz
*/
static int sdram_notifier(struct notifier_block *nb, unsigned long event,
void *data)
{
switch (event) {
case CPUFREQ_MINMAX:
cpufreq_updateminmax(data, 147500, 206000);
break;
}
return 0;
}
/**
* fixup_system3 - fixup function for system 3 board
* @desc: machine description
* @param: kernel params
* @cmdline: kernel cmdline
* @mi: memory info struct
*
*/
static void __init fixup_system3(struct machine_desc *desc,
struct param_struct *params, char **cmdline, struct meminfo *mi)
{
DPRINTK( "%s\n", "START" );
ROOT_DEV = MKDEV(RAMDISK_MAJOR,0);
setup_ramdisk( 1, 0, 0, 8192 );
setup_initrd( 0xc0800000, 8*1024*1024 );
}
/**
* system3_uart_pm - powermgmt callback function for system 3 UART
* @port: uart port structure
* @state: pm state
* @oldstate: old pm state
*
*/
static void system3_uart_pm(struct uart_port *port, u_int state, u_int oldstate)
{
/* TODO: switch on/off uart in powersave mode */
}
/*
* Note! this can be called from IRQ context.
* FIXME: Handle PT Digital Board CTRL regs irq-safe.
*
* NB: system3 uses COM_RTS and COM_DTR for both UART1 (com port)
* and UART3 (radio module). We only handle them for UART1 here.
*/
static void system3_set_mctrl(struct uart_port *port, u_int mctrl)
{
if (port->mapbase == _Ser1UTCR0) {
u_int set = 0, clear = 0;
if (mctrl & TIOCM_RTS)
set |= PT_CTRL2_RS1_RTS;
else
clear |= PT_CTRL2_RS1_RTS;
if (mctrl & TIOCM_DTR)
set |= PT_CTRL2_RS1_DTR;
else
clear |= PT_CTRL2_RS1_DTR;
PTCTRL2_clear(clear);
PTCTRL2_set(set);
}
}
static int system3_get_mctrl(struct uart_port *port)
{
u_int ret = 0;
u_int irqsr = PT_IRQSR;
/* need 2 reads to read current value */
irqsr = PT_IRQSR;
/* TODO: check IRQ source register for modem/com
status lines and set them correctly. */
ret = TIOCM_CD | TIOCM_CTS | TIOCM_DSR;
return ret;
}
static int __init system3_init(void)
{
int ret = 0;
DPRINTK( "%s\n", "START" );
if ( !machine_is_pt_system3() ) {
ret = -EINVAL;
goto DONE;
}
/* init control register */
PT_CTRL0 = PT_CTRL0_INIT;
PT_CTRL1 = 0x02;
PT_CTRL2 = 0x00;
DPRINTK( "CTRL[0]=0x%02x\n", PT_CTRL0 );
DPRINTK( "CTRL[1]=0x%02x\n", PT_CTRL1 );
DPRINTK( "CTRL[2]=0x%02x\n", PT_CTRL2 );
/*
* Ensure that the memory bus request/grant signals are setup,
* and the grant is held in its inactive state.
*/
sa1110_mb_disable();
/*
* Probe for a SA1111.
*/
ret = sa1111_probe(PT_SA1111_BASE);
if (ret < 0) {
printk( KERN_WARNING"PT Digital Board: no SA1111 found!\n" );
goto DONE;
}
/*
* We found it. Wake the chip up.
*/
sa1111_wake();
/*
* The SDRAM configuration of the SA1110 and the SA1111 must
* match. This is very important to ensure that SA1111 accesses
* don't corrupt the SDRAM. Note that this ungates the SA1111's
* MBGNT signal, so we must have called sa1110_mb_disable()
* beforehand.
*/
sa1111_configure_smc(1,
FExtr(MDCNFG, MDCNFG_SA1110_DRAC0),
FExtr(MDCNFG, MDCNFG_SA1110_TDL0));
/*
* We only need to turn on DCLK whenever we want to use the
* DMA. It can otherwise be held firmly in the off position.
*/
SKPCR |= SKPCR_DCLKEN;
/*
* Enable the SA1110 memory bus request and grant signals.
*/
sa1110_mb_enable();
system3_init_irq();
#if defined( CONFIG_CPU_FREQ )
ret = cpufreq_register_notifier(&system3_clkchg_block);
if ( ret != 0 ) {
printk( KERN_WARNING"PT Digital Board: could not register clock scale callback\n" );
goto DONE;
}
#endif
ret = 0;
DONE:
DPRINTK( "ret=%d\n", ret );
return ret;
}
/**********************************************************************
* Exported Functions
*/
/**********************************************************************
* kernel magic macros
*/
__initcall(system3_init);
MACHINE_START(PT_SYSTEM3, "PT System 3")
BOOT_MEM(0xc0000000, 0x80000000, 0xf8000000)
BOOT_PARAMS(0xc0000100)
FIXUP(fixup_system3)
MAPIO(system3_map_io)
INITIRQ(sa1100_init_irq)
MACHINE_END
| robacklin/celinux | arch/arm/mach-sa1100/system3.c | C | gpl-2.0 | 9,174 |
<?php
/**
* Implements hook_form_system_theme_settings_alter().
*
* @param $form
* Nested array of form elements that comprise the form.
* @param $form_state
* A keyed array containing the current state of the form.
*/
function interactive_media_form_system_theme_settings_alter(&$form, &$form_state) {
$form['themedev']['zen_layout'] = array(
'#type' => 'radios',
'#title' => t('Layout method'),
'#options' => array(
'zen-columns-liquid' => t('Liquid layout') . ' <small>(layout-liquid.css)</small>',
'zen-columns-fixed' => t('Fixed layout') . ' <small>(layout-fixed.css)</small>',
),
'#default_value' => theme_get_setting('zen_layout'),
);
}
| iamdan/iamdanan | themes/interactive_media/theme-settings.php | PHP | gpl-2.0 | 775 |
/*
** Copyright (C) 1999-2005 Erik de Castro Lopo <erikd@mega-nerd.com>
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "sfconfig.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <math.h>
#if (defined (WIN32) || defined (_WIN32))
#include <fcntl.h>
static int truncate (const char *filename, int ignored) ;
#endif
#include <sndfile.h>
#include "utils.h"
#define SAMPLE_RATE 11025
#define DATA_LENGTH (1<<12)
#define SILLY_WRITE_COUNT (234)
static void pcm_test_char (const char *str, int format, int long_file_okz) ;
static void pcm_test_short (const char *str, int format, int long_file_okz) ;
static void pcm_test_24bit (const char *str, int format, int long_file_okz) ;
static void pcm_test_int (const char *str, int format, int long_file_okz) ;
static void pcm_test_float (const char *str, int format, int long_file_okz) ;
static void pcm_test_double (const char *str, int format, int long_file_okz) ;
static void empty_file_test (const char *filename, int format) ;
typedef union
{ double d [DATA_LENGTH] ;
float f [DATA_LENGTH] ;
int i [DATA_LENGTH] ;
short s [DATA_LENGTH] ;
char c [DATA_LENGTH] ;
} BUFFER ;
static BUFFER orig_data ;
static BUFFER test_data ;
int
main (int argc, char **argv)
{ int do_all = 0 ;
int test_count = 0 ;
count_open_files () ;
if (argc != 2)
{ printf ("Usage : %s <test>\n", argv [0]) ;
printf (" Where <test> is one of the following:\n") ;
printf (" wav - test WAV file functions (little endian)\n") ;
printf (" aiff - test AIFF file functions (big endian)\n") ;
printf (" au - test AU file functions\n") ;
printf (" avr - test AVR file functions\n") ;
printf (" caf - test CAF file functions\n") ;
printf (" raw - test RAW header-less PCM file functions\n") ;
printf (" paf - test PAF file functions\n") ;
printf (" svx - test 8SVX/16SV file functions\n") ;
printf (" nist - test NIST Sphere file functions\n") ;
printf (" ircam - test IRCAM file functions\n") ;
printf (" voc - Create Voice file functions\n") ;
printf (" w64 - Sonic Foundry's W64 file functions\n") ;
printf (" flac - test FLAC file functions\n") ;
printf (" all - perform all tests\n") ;
exit (1) ;
} ;
do_all = !strcmp (argv [1], "all") ;
if (do_all || ! strcmp (argv [1], "wav"))
{ pcm_test_char ("char.wav" , SF_FORMAT_WAV | SF_FORMAT_PCM_U8, SF_FALSE) ;
pcm_test_short ("short.wav" , SF_FORMAT_WAV | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_24bit ("24bit.wav" , SF_FORMAT_WAV | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_int ("int.wav" , SF_FORMAT_WAV | SF_FORMAT_PCM_32, SF_FALSE) ;
pcm_test_char ("char.rifx" , SF_ENDIAN_BIG | SF_FORMAT_WAV | SF_FORMAT_PCM_U8, SF_FALSE) ;
pcm_test_short ("short.rifx" , SF_ENDIAN_BIG | SF_FORMAT_WAV | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_24bit ("24bit.rifx" , SF_ENDIAN_BIG | SF_FORMAT_WAV | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_int ("int.rifx" , SF_ENDIAN_BIG | SF_FORMAT_WAV | SF_FORMAT_PCM_32, SF_FALSE) ;
pcm_test_24bit ("24bit.wavex" , SF_FORMAT_WAVEX | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_int ("int.wavex" , SF_FORMAT_WAVEX | SF_FORMAT_PCM_32, SF_FALSE) ;
/* Lite remove start */
pcm_test_float ("float.wav" , SF_FORMAT_WAV | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_double ("double.wav" , SF_FORMAT_WAV | SF_FORMAT_DOUBLE, SF_FALSE) ;
pcm_test_float ("float.rifx" , SF_ENDIAN_BIG | SF_FORMAT_WAV | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_double ("double.rifx" , SF_ENDIAN_BIG | SF_FORMAT_WAV | SF_FORMAT_DOUBLE, SF_FALSE) ;
pcm_test_float ("float.wavex" , SF_FORMAT_WAVEX | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_double ("double.wavex" , SF_FORMAT_WAVEX | SF_FORMAT_DOUBLE, SF_FALSE) ;
/* Lite remove end */
empty_file_test ("empty_char.wav", SF_FORMAT_WAV | SF_FORMAT_PCM_U8) ;
empty_file_test ("empty_short.wav", SF_FORMAT_WAV | SF_FORMAT_PCM_16) ;
empty_file_test ("empty_float.wav", SF_FORMAT_WAV | SF_FORMAT_FLOAT) ;
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "aiff"))
{ pcm_test_char ("char_u8.aiff" , SF_FORMAT_AIFF | SF_FORMAT_PCM_U8, SF_FALSE) ;
pcm_test_char ("char_s8.aiff" , SF_FORMAT_AIFF | SF_FORMAT_PCM_S8, SF_FALSE) ;
pcm_test_short ("short.aiff" , SF_FORMAT_AIFF | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_24bit ("24bit.aiff" , SF_FORMAT_AIFF | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_int ("int.aiff" , SF_FORMAT_AIFF | SF_FORMAT_PCM_32, SF_FALSE) ;
pcm_test_short ("short_sowt.aifc" , SF_ENDIAN_LITTLE | SF_FORMAT_AIFF | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_24bit ("24bit_sowt.aifc" , SF_ENDIAN_LITTLE | SF_FORMAT_AIFF | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_int ("int_sowt.aifc" , SF_ENDIAN_LITTLE | SF_FORMAT_AIFF | SF_FORMAT_PCM_32, SF_FALSE) ;
pcm_test_short ("short_twos.aifc" , SF_ENDIAN_BIG | SF_FORMAT_AIFF | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_24bit ("24bit_twos.aifc" , SF_ENDIAN_BIG | SF_FORMAT_AIFF | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_int ("int_twos.aifc" , SF_ENDIAN_BIG | SF_FORMAT_AIFF | SF_FORMAT_PCM_32, SF_FALSE) ;
/* Lite remove start */
pcm_test_short ("dwvw16.aifc", SF_FORMAT_AIFF | SF_FORMAT_DWVW_16, SF_TRUE) ;
pcm_test_24bit ("dwvw24.aifc", SF_FORMAT_AIFF | SF_FORMAT_DWVW_24, SF_TRUE) ;
pcm_test_float ("float.aifc" , SF_FORMAT_AIFF | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_double ("double.aifc" , SF_FORMAT_AIFF | SF_FORMAT_DOUBLE, SF_FALSE) ;
/* Lite remove end */
empty_file_test ("empty_char.aiff", SF_FORMAT_AIFF | SF_FORMAT_PCM_U8) ;
empty_file_test ("empty_short.aiff", SF_FORMAT_AIFF | SF_FORMAT_PCM_16) ;
empty_file_test ("empty_float.aiff", SF_FORMAT_AIFF | SF_FORMAT_FLOAT) ;
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "au"))
{ pcm_test_char ("char.au" , SF_FORMAT_AU | SF_FORMAT_PCM_S8, SF_FALSE) ;
pcm_test_short ("short.au" , SF_FORMAT_AU | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_24bit ("24bit.au" , SF_FORMAT_AU | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_int ("int.au" , SF_FORMAT_AU | SF_FORMAT_PCM_32, SF_FALSE) ;
/* Lite remove start */
pcm_test_float ("float.au" , SF_FORMAT_AU | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_double ("double.au", SF_FORMAT_AU | SF_FORMAT_DOUBLE, SF_FALSE) ;
/* Lite remove end */
pcm_test_char ("char_le.au" , SF_ENDIAN_LITTLE | SF_FORMAT_AU | SF_FORMAT_PCM_S8, SF_FALSE) ;
pcm_test_short ("short_le.au" , SF_ENDIAN_LITTLE | SF_FORMAT_AU | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_24bit ("24bit_le.au" , SF_ENDIAN_LITTLE | SF_FORMAT_AU | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_int ("int_le.au" , SF_ENDIAN_LITTLE | SF_FORMAT_AU | SF_FORMAT_PCM_32, SF_FALSE) ;
/* Lite remove start */
pcm_test_float ("float_le.au" , SF_ENDIAN_LITTLE | SF_FORMAT_AU | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_double ("double_le.au" , SF_ENDIAN_LITTLE | SF_FORMAT_AU | SF_FORMAT_DOUBLE, SF_FALSE) ;
/* Lite remove end */
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "caf"))
{ pcm_test_char ("char.caf" , SF_FORMAT_CAF | SF_FORMAT_PCM_S8, SF_FALSE) ;
pcm_test_short ("short.caf" , SF_FORMAT_CAF | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_24bit ("24bit.caf" , SF_FORMAT_CAF | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_int ("int.caf" , SF_FORMAT_CAF | SF_FORMAT_PCM_32, SF_FALSE) ;
/* Lite remove start */
pcm_test_float ("float.caf" , SF_FORMAT_CAF | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_double ("double.caf" , SF_FORMAT_CAF | SF_FORMAT_DOUBLE, SF_FALSE) ;
/* Lite remove end */
pcm_test_short ("short_le.caf" , SF_ENDIAN_LITTLE | SF_FORMAT_CAF | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_24bit ("24bit_le.caf" , SF_ENDIAN_LITTLE | SF_FORMAT_CAF | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_int ("int_le.caf" , SF_ENDIAN_LITTLE | SF_FORMAT_CAF | SF_FORMAT_PCM_32, SF_FALSE) ;
/* Lite remove start */
pcm_test_float ("float_le.caf" , SF_ENDIAN_LITTLE | SF_FORMAT_CAF | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_double ("double_le.caf", SF_ENDIAN_LITTLE | SF_FORMAT_CAF | SF_FORMAT_DOUBLE, SF_FALSE) ;
/* Lite remove end */
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "raw"))
{ pcm_test_char ("char_s8.raw" , SF_FORMAT_RAW | SF_FORMAT_PCM_S8, SF_FALSE) ;
pcm_test_char ("char_u8.raw" , SF_FORMAT_RAW | SF_FORMAT_PCM_U8, SF_FALSE) ;
pcm_test_short ("short_le.raw" , SF_ENDIAN_LITTLE | SF_FORMAT_RAW | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_short ("short_be.raw" , SF_ENDIAN_BIG | SF_FORMAT_RAW | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_24bit ("24bit_le.raw" , SF_ENDIAN_LITTLE | SF_FORMAT_RAW | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_24bit ("24bit_be.raw" , SF_ENDIAN_BIG | SF_FORMAT_RAW | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_int ("int_le.raw" , SF_ENDIAN_LITTLE | SF_FORMAT_RAW | SF_FORMAT_PCM_32, SF_FALSE) ;
pcm_test_int ("int_be.raw" , SF_ENDIAN_BIG | SF_FORMAT_RAW | SF_FORMAT_PCM_32, SF_FALSE) ;
/* Lite remove start */
pcm_test_float ("float_le.raw" , SF_ENDIAN_LITTLE | SF_FORMAT_RAW | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_float ("float_be.raw" , SF_ENDIAN_BIG | SF_FORMAT_RAW | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_double ("double_le.raw", SF_ENDIAN_LITTLE | SF_FORMAT_RAW | SF_FORMAT_DOUBLE, SF_FALSE) ;
pcm_test_double ("double_be.raw", SF_ENDIAN_BIG | SF_FORMAT_RAW | SF_FORMAT_DOUBLE, SF_FALSE) ;
/* Lite remove end */
test_count++ ;
} ;
/* Lite remove start */
if (do_all || ! strcmp (argv [1], "paf"))
{ pcm_test_char ("char_le.paf", SF_ENDIAN_LITTLE | SF_FORMAT_PAF | SF_FORMAT_PCM_S8, SF_FALSE) ;
pcm_test_char ("char_be.paf", SF_ENDIAN_BIG | SF_FORMAT_PAF | SF_FORMAT_PCM_S8, SF_FALSE) ;
pcm_test_short ("short_le.paf", SF_ENDIAN_LITTLE | SF_FORMAT_PAF | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_short ("short_be.paf", SF_ENDIAN_BIG | SF_FORMAT_PAF | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_24bit ("24bit_le.paf", SF_ENDIAN_LITTLE | SF_FORMAT_PAF | SF_FORMAT_PCM_24, SF_TRUE) ;
pcm_test_24bit ("24bit_be.paf", SF_ENDIAN_BIG | SF_FORMAT_PAF | SF_FORMAT_PCM_24, SF_TRUE) ;
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "svx"))
{ pcm_test_char ("char.svx" , SF_FORMAT_SVX | SF_FORMAT_PCM_S8, SF_FALSE) ;
pcm_test_short ("short.svx", SF_FORMAT_SVX | SF_FORMAT_PCM_16, SF_FALSE) ;
empty_file_test ("empty_char.svx", SF_FORMAT_SVX | SF_FORMAT_PCM_S8) ;
empty_file_test ("empty_short.svx", SF_FORMAT_SVX | SF_FORMAT_PCM_16) ;
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "nist"))
{ pcm_test_short ("short_le.nist", SF_ENDIAN_LITTLE | SF_FORMAT_NIST | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_short ("short_be.nist", SF_ENDIAN_BIG | SF_FORMAT_NIST | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_24bit ("24bit_le.nist", SF_ENDIAN_LITTLE | SF_FORMAT_NIST | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_24bit ("24bit_be.nist", SF_ENDIAN_BIG | SF_FORMAT_NIST | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_int ("int_le.nist" , SF_ENDIAN_LITTLE | SF_FORMAT_NIST | SF_FORMAT_PCM_32, SF_FALSE) ;
pcm_test_int ("int_be.nist" , SF_ENDIAN_BIG | SF_FORMAT_NIST | SF_FORMAT_PCM_32, SF_FALSE) ;
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "ircam"))
{ pcm_test_short ("short_be.ircam" , SF_ENDIAN_BIG | SF_FORMAT_IRCAM | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_short ("short_le.ircam" , SF_ENDIAN_LITTLE | SF_FORMAT_IRCAM | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_int ("int_be.ircam" , SF_ENDIAN_BIG | SF_FORMAT_IRCAM | SF_FORMAT_PCM_32, SF_FALSE) ;
pcm_test_int ("int_le.ircam" , SF_ENDIAN_LITTLE | SF_FORMAT_IRCAM | SF_FORMAT_PCM_32, SF_FALSE) ;
pcm_test_float ("float_be.ircam" , SF_ENDIAN_BIG | SF_FORMAT_IRCAM | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_float ("float_le.ircam" , SF_ENDIAN_LITTLE | SF_FORMAT_IRCAM | SF_FORMAT_FLOAT , SF_FALSE) ;
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "voc"))
{ pcm_test_char ("char.voc" , SF_FORMAT_VOC | SF_FORMAT_PCM_U8, SF_FALSE) ;
pcm_test_short ("short.voc", SF_FORMAT_VOC | SF_FORMAT_PCM_16, SF_FALSE) ;
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "mat4"))
{ pcm_test_short ("short_be.mat4" , SF_ENDIAN_BIG | SF_FORMAT_MAT4 | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_short ("short_le.mat4" , SF_ENDIAN_LITTLE | SF_FORMAT_MAT4 | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_int ("int_be.mat4" , SF_ENDIAN_BIG | SF_FORMAT_MAT4 | SF_FORMAT_PCM_32, SF_FALSE) ;
pcm_test_int ("int_le.mat4" , SF_ENDIAN_LITTLE | SF_FORMAT_MAT4 | SF_FORMAT_PCM_32, SF_FALSE) ;
pcm_test_float ("float_be.mat4" , SF_ENDIAN_BIG | SF_FORMAT_MAT4 | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_float ("float_le.mat4" , SF_ENDIAN_LITTLE | SF_FORMAT_MAT4 | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_double ("double_be.mat4" , SF_ENDIAN_BIG | SF_FORMAT_MAT4 | SF_FORMAT_DOUBLE, SF_FALSE) ;
pcm_test_double ("double_le.mat4" , SF_ENDIAN_LITTLE | SF_FORMAT_MAT4 | SF_FORMAT_DOUBLE, SF_FALSE) ;
empty_file_test ("empty_short.mat4", SF_FORMAT_MAT4 | SF_FORMAT_PCM_16) ;
empty_file_test ("empty_float.mat4", SF_FORMAT_MAT4 | SF_FORMAT_FLOAT) ;
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "mat5"))
{ pcm_test_char ("char_be.mat5" , SF_ENDIAN_BIG | SF_FORMAT_MAT5 | SF_FORMAT_PCM_U8, SF_FALSE) ;
pcm_test_char ("char_le.mat5" , SF_ENDIAN_LITTLE | SF_FORMAT_MAT5 | SF_FORMAT_PCM_U8, SF_FALSE) ;
pcm_test_short ("short_be.mat5" , SF_ENDIAN_BIG | SF_FORMAT_MAT5 | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_short ("short_le.mat5" , SF_ENDIAN_LITTLE | SF_FORMAT_MAT5 | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_int ("int_be.mat5" , SF_ENDIAN_BIG | SF_FORMAT_MAT5 | SF_FORMAT_PCM_32, SF_FALSE) ;
pcm_test_int ("int_le.mat5" , SF_ENDIAN_LITTLE | SF_FORMAT_MAT5 | SF_FORMAT_PCM_32, SF_FALSE) ;
pcm_test_float ("float_be.mat5" , SF_ENDIAN_BIG | SF_FORMAT_MAT5 | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_float ("float_le.mat5" , SF_ENDIAN_LITTLE | SF_FORMAT_MAT5 | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_double ("double_be.mat5" , SF_ENDIAN_BIG | SF_FORMAT_MAT5 | SF_FORMAT_DOUBLE, SF_FALSE) ;
pcm_test_double ("double_le.mat5" , SF_ENDIAN_LITTLE | SF_FORMAT_MAT5 | SF_FORMAT_DOUBLE, SF_FALSE) ;
increment_open_file_count () ;
empty_file_test ("empty_char.mat5", SF_FORMAT_MAT5 | SF_FORMAT_PCM_U8) ;
empty_file_test ("empty_short.mat5", SF_FORMAT_MAT5 | SF_FORMAT_PCM_16) ;
empty_file_test ("empty_float.mat5", SF_FORMAT_MAT5 | SF_FORMAT_FLOAT) ;
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "pvf"))
{ pcm_test_char ("char.pvf" , SF_FORMAT_PVF | SF_FORMAT_PCM_S8, SF_FALSE) ;
pcm_test_short ("short.pvf", SF_FORMAT_PVF | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_int ("int.pvf" , SF_FORMAT_PVF | SF_FORMAT_PCM_32, SF_FALSE) ;
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "htk"))
{ pcm_test_short ("short.htk", SF_FORMAT_HTK | SF_FORMAT_PCM_16, SF_FALSE) ;
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "avr"))
{ pcm_test_char ("char_u8.avr" , SF_FORMAT_AVR | SF_FORMAT_PCM_U8, SF_FALSE) ;
pcm_test_char ("char_s8.avr" , SF_FORMAT_AVR | SF_FORMAT_PCM_S8, SF_FALSE) ;
pcm_test_short ("short.avr" , SF_FORMAT_AVR | SF_FORMAT_PCM_16, SF_FALSE) ;
test_count++ ;
} ;
/* Lite remove end */
if (do_all || ! strcmp (argv [1], "w64"))
{ pcm_test_char ("char.w64" , SF_FORMAT_W64 | SF_FORMAT_PCM_U8, SF_FALSE) ;
pcm_test_short ("short.w64" , SF_FORMAT_W64 | SF_FORMAT_PCM_16, SF_FALSE) ;
pcm_test_24bit ("24bit.w64" , SF_FORMAT_W64 | SF_FORMAT_PCM_24, SF_FALSE) ;
pcm_test_int ("int.w64" , SF_FORMAT_W64 | SF_FORMAT_PCM_32, SF_FALSE) ;
/* Lite remove start */
pcm_test_float ("float.w64" , SF_FORMAT_W64 | SF_FORMAT_FLOAT , SF_FALSE) ;
pcm_test_double ("double.w64" , SF_FORMAT_W64 | SF_FORMAT_DOUBLE, SF_FALSE) ;
/* Lite remove end */
empty_file_test ("empty_char.w64", SF_FORMAT_W64 | SF_FORMAT_PCM_U8) ;
empty_file_test ("empty_short.w64", SF_FORMAT_W64 | SF_FORMAT_PCM_16) ;
empty_file_test ("empty_float.w64", SF_FORMAT_W64 | SF_FORMAT_FLOAT) ;
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "sds"))
{ pcm_test_char ("char.sds" , SF_FORMAT_SDS | SF_FORMAT_PCM_S8, SF_TRUE) ;
pcm_test_short ("short.sds" , SF_FORMAT_SDS | SF_FORMAT_PCM_16, SF_TRUE) ;
pcm_test_24bit ("24bit.sds" , SF_FORMAT_SDS | SF_FORMAT_PCM_24, SF_TRUE) ;
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "sd2"))
{ pcm_test_char ("char.sd2" , SF_FORMAT_SD2 | SF_FORMAT_PCM_S8, SF_TRUE) ;
pcm_test_short ("short.sd2" , SF_FORMAT_SD2 | SF_FORMAT_PCM_16, SF_TRUE) ;
pcm_test_24bit ("24bit.sd2" , SF_FORMAT_SD2 | SF_FORMAT_PCM_24, SF_TRUE) ;
test_count++ ;
} ;
if (do_all || ! strcmp (argv [1], "flac"))
{
#ifdef HAVE_FLAC_ALL_H
pcm_test_char ("char.flac" , SF_FORMAT_FLAC | SF_FORMAT_PCM_S8, SF_TRUE) ;
pcm_test_short ("short.flac" , SF_FORMAT_FLAC | SF_FORMAT_PCM_16, SF_TRUE) ;
pcm_test_24bit ("24bit.flac" , SF_FORMAT_FLAC | SF_FORMAT_PCM_24, SF_TRUE) ;
#else
printf (" **** flac not supported in this binary. ****\n") ;
#endif
test_count++ ;
} ;
if (test_count == 0)
{ printf ("Mono : ************************************\n") ;
printf ("Mono : * No '%s' test defined.\n", argv [1]) ;
printf ("Mono : ************************************\n") ;
return 1 ;
} ;
/* Only open file descriptors should be stdin, stdout and stderr. */
check_open_file_count_or_die (__LINE__) ;
return 0 ;
} /* main */
/*============================================================================================
** Helper functions and macros.
*/
static void create_short_file (const char *filename) ;
#define CHAR_ERROR(x,y) (abs ((x) - (y)) > 255)
#define INT_ERROR(x,y) (((x) - (y)) != 0)
#define TRIBYTE_ERROR(x,y) (abs ((x) - (y)) > 255)
#define FLOAT_ERROR(x,y) (fabs ((x) - (y)) > 1e-5)
#define CONVERT_DATA(k,len,new,orig) \
{ for ((k) = 0 ; (k) < (len) ; (k) ++) \
(new) [k] = (orig) [k] ; \
}
/*======================================================================================
*/
static void mono_char_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void stereo_char_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void mono_rdwr_char_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void new_rdwr_char_test (const char *filename, int format, int allow_fd) ;
static void
pcm_test_char (const char *filename, int format, int long_file_ok)
{ SF_INFO sfinfo ;
short *orig, *test ;
int k, items, allow_fd ;
/* Sd2 files cannot be opened from an existing file descriptor. */
allow_fd = ((format & SF_FORMAT_TYPEMASK) == SF_FORMAT_SD2) ? SF_FALSE : SF_TRUE ;
print_test_name ("pcm_test_char", filename) ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 1 ;
sfinfo.format = format ;
gen_windowed_sine_double (orig_data.d, DATA_LENGTH, 32000.0) ;
orig = orig_data.s ;
test = test_data.s ;
/* Make this a macro so gdb steps over it in one go. */
CONVERT_DATA (k, DATA_LENGTH, orig, orig_data.d) ;
items = DATA_LENGTH ;
/* Some test broken out here. */
mono_char_test (filename, format, long_file_ok, allow_fd) ;
/* Sub format DWVW does not allow seeking. */
if ((format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_16 ||
(format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_24)
{ unlink (filename) ;
printf ("no seek : ok\n") ;
return ;
} ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_FLAC)
mono_rdwr_char_test (filename, format, long_file_ok, allow_fd) ;
/* If the format doesn't support stereo we're done. */
sfinfo.channels = 2 ;
if (sf_format_check (&sfinfo) == 0)
{ unlink (filename) ;
puts ("no stereo : ok") ;
return ;
} ;
stereo_char_test (filename, format, long_file_ok, allow_fd) ;
/* New read/write test. Not sure if this is needed yet. */
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_PAF &&
(format & SF_FORMAT_TYPEMASK) != SF_FORMAT_VOC &&
(format & SF_FORMAT_TYPEMASK) != SF_FORMAT_FLAC)
new_rdwr_char_test (filename, format, allow_fd) ;
delete_file (format, filename) ;
puts ("ok") ;
return ;
} /* pcm_test_char */
static void
mono_char_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
short *orig, *test ;
sf_count_t count ;
int k, items ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 1 ;
sfinfo.format = format ;
orig = orig_data.s ;
test = test_data.s ;
items = DATA_LENGTH ;
file = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_set_string (file, SF_STR_ARTIST, "Your name here") ;
test_write_short_or_die (file, 0, orig, items, __LINE__) ;
sf_write_sync (file) ;
test_write_short_or_die (file, 0, orig, items, __LINE__) ;
sf_write_sync (file) ;
/* Add non-audio data after the audio. */
sf_set_string (file, SF_STR_COPYRIGHT, "Copyright (c) 2003") ;
sf_close (file) ;
memset (test, 0, items * sizeof (short)) ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_RAW)
memset (&sfinfo, 0, sizeof (sfinfo)) ;
file = test_open_file_or_die (filename, SFM_READ, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Mono : Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < 2 * items)
{ printf ("\n\nLine %d : Mono : Incorrect number of frames in file (too short). (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), items) ;
exit (1) ;
} ;
if (! long_file_ok && sfinfo.frames > 2 * items)
{ printf ("\n\nLine %d : Mono : Incorrect number of frames in file (too long). (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), items) ;
exit (1) ;
} ;
if (sfinfo.channels != 1)
{ printf ("\n\nLine %d : Mono : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
check_log_buffer_or_die (file, __LINE__) ;
test_read_short_or_die (file, 0, test, items, __LINE__) ;
for (k = 0 ; k < items ; k++)
if (CHAR_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d: Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to start of file. */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
test_read_short_or_die (file, 0, test, 4, __LINE__) ;
for (k = 0 ; k < 4 ; k++)
if (CHAR_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
if ((format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_16 ||
(format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_24)
{ sf_close (file) ;
unlink (filename) ;
printf ("no seek : ") ;
return ;
} ;
/* Seek to offset from start of file. */
test_seek_or_die (file, items + 10, SEEK_SET, items + 10, sfinfo.channels, __LINE__) ;
test_read_short_or_die (file, 0, test + 10, 4, __LINE__) ;
for (k = 10 ; k < 14 ; k++)
if (CHAR_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Seek to offset from current position. */
test_seek_or_die (file, 6, SEEK_CUR, items + 20, sfinfo.channels, __LINE__) ;
test_read_short_or_die (file, 0, test + 20, 4, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (CHAR_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Seek to offset from end of file. */
test_seek_or_die (file, -1 * (sfinfo.frames - 10), SEEK_END, 10, sfinfo.channels, __LINE__) ;
test_read_short_or_die (file, 0, test + 10, 4, __LINE__) ;
for (k = 10 ; k < 14 ; k++)
if (CHAR_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample D (#%d : 0x%X => 0x%X).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Check read past end of file followed by sf_seek (sndfile, 0, SEEK_CUR). */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
count = 0 ;
while (count < sfinfo.frames)
count += sf_read_short (file, test, 311) ;
/* Check that no error has occurred. */
if (sf_error (file))
{ printf ("\n\nLine %d : Mono : error where there shouldn't have been one.\n", __LINE__) ;
puts (sf_strerror (file)) ;
exit (1) ;
} ;
/* Check that we haven't read beyond EOF. */
if (count > sfinfo.frames)
{ printf ("\n\nLines %d : read past end of file (%ld should be %ld)\n", __LINE__, (long) count, (long) sfinfo.frames) ;
exit (1) ;
} ;
test_seek_or_die (file, 0, SEEK_CUR, sfinfo.frames, sfinfo.channels, __LINE__) ;
sf_close (file) ;
} /* mono_char_test */
static void
stereo_char_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
short *orig, *test ;
int k, items, frames ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 2 ;
sfinfo.format = format ;
gen_windowed_sine_double (orig_data.d, DATA_LENGTH, 32000.0) ;
orig = orig_data.s ;
test = test_data.s ;
/* Make this a macro so gdb steps over it in one go. */
CONVERT_DATA (k, DATA_LENGTH, orig, orig_data.d) ;
items = DATA_LENGTH ;
frames = items / sfinfo.channels ;
file = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_set_string (file, SF_STR_ARTIST, "Your name here") ;
test_writef_short_or_die (file, 0, orig, frames, __LINE__) ;
sf_set_string (file, SF_STR_COPYRIGHT, "Copyright (c) 2003") ;
sf_close (file) ;
memset (test, 0, items * sizeof (short)) ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_RAW)
memset (&sfinfo, 0, sizeof (sfinfo)) ;
file = test_open_file_or_die (filename, SFM_READ, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Stereo : Returned format incorrect (0x%08X => 0x%08X).\n",
__LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < frames)
{ printf ("\n\nLine %d : Stereo : Incorrect number of frames in file (too short). (%ld should be %d)\n",
__LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
if (! long_file_ok && sfinfo.frames > frames)
{ printf ("\n\nLine %d : Stereo : Incorrect number of frames in file (too long). (%ld should be %d)\n",
__LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
if (sfinfo.channels != 2)
{ printf ("\n\nLine %d : Stereo : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
check_log_buffer_or_die (file, __LINE__) ;
test_readf_short_or_die (file, 0, test, frames, __LINE__) ;
for (k = 0 ; k < items ; k++)
if (CHAR_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to start of file. */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
test_readf_short_or_die (file, 0, test, 2, __LINE__) ;
for (k = 0 ; k < 4 ; k++)
if (CHAR_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from start of file. */
test_seek_or_die (file, 10, SEEK_SET, 10, sfinfo.channels, __LINE__) ;
/* Check for errors here. */
if (sf_error (file))
{ printf ("Line %d: Should NOT return an error.\n", __LINE__) ;
puts (sf_strerror (file)) ;
exit (1) ;
} ;
if (sf_read_short (file, test, 1) > 0)
{ printf ("Line %d: Should return 0.\n", __LINE__) ;
exit (1) ;
} ;
if (! sf_error (file))
{ printf ("Line %d: Should return an error.\n", __LINE__) ;
exit (1) ;
} ;
/*-----------------------*/
test_readf_short_or_die (file, 0, test + 10, 2, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (CHAR_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from current position. */
test_seek_or_die (file, 8, SEEK_CUR, 20, sfinfo.channels, __LINE__) ;
test_readf_short_or_die (file, 0, test + 20, 2, __LINE__) ;
for (k = 40 ; k < 44 ; k++)
if (CHAR_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from end of file. */
test_seek_or_die (file, -1 * (sfinfo.frames - 10), SEEK_END, 10, sfinfo.channels, __LINE__) ;
test_readf_short_or_die (file, 0, test + 20, 2, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (CHAR_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
sf_close (file) ;
} /* stereo_char_test */
static void
mono_rdwr_char_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
short *orig, *test ;
int k, pass ;
orig = orig_data.s ;
test = test_data.s ;
sfinfo.samplerate = SAMPLE_RATE ;
sfinfo.frames = DATA_LENGTH ;
sfinfo.channels = 1 ;
sfinfo.format = format ;
if ((format & SF_FORMAT_TYPEMASK) == SF_FORMAT_RAW
|| (format & SF_FORMAT_TYPEMASK) == SF_FORMAT_AU
|| (format & SF_FORMAT_TYPEMASK) == SF_FORMAT_SD2)
unlink (filename) ;
else
{ /* Create a short file. */
create_short_file (filename) ;
/* Opening a already existing short file (ie invalid header) RDWR is disallowed.
** If this returns a valif pointer sf_open() screwed up.
*/
if ((file = sf_open (filename, SFM_RDWR, &sfinfo)))
{ printf ("\n\nLine %d: sf_open should (SFM_RDWR) have failed but didn't.\n", __LINE__) ;
exit (1) ;
} ;
/* Truncate the file to zero bytes. */
if (truncate (filename, 0) < 0)
{ printf ("\n\nLine %d: truncate (%s) failed", __LINE__, filename) ;
perror (NULL) ;
exit (1) ;
} ;
} ;
/* Opening a zero length file RDWR is allowed, but the SF_INFO struct must contain
** all the usual data required when opening the file in WRITE mode.
*/
sfinfo.samplerate = SAMPLE_RATE ;
sfinfo.frames = DATA_LENGTH ;
sfinfo.channels = 1 ;
sfinfo.format = format ;
file = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
/* Do 3 writes followed by reads. After each, check the data and the current
** read and write offsets.
*/
for (pass = 1 ; pass <= 3 ; pass ++)
{ orig [20] = pass * 2 ;
/* Write some data. */
test_write_short_or_die (file, pass, orig, DATA_LENGTH, __LINE__) ;
test_read_write_position_or_die (file, __LINE__, pass, (pass - 1) * DATA_LENGTH, pass * DATA_LENGTH) ;
/* Read what we just wrote. */
test_read_short_or_die (file, 0, test, DATA_LENGTH, __LINE__) ;
/* Check the data. */
for (k = 0 ; k < DATA_LENGTH ; k++)
if (CHAR_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d (pass %d): Error at sample %d (0x%X => 0x%X).\n", __LINE__, pass, k, orig [k], test [k]) ;
oct_save_short (orig, test, DATA_LENGTH) ;
exit (1) ;
} ;
test_read_write_position_or_die (file, __LINE__, pass, pass * DATA_LENGTH, pass * DATA_LENGTH) ;
} ; /* for (pass ...) */
sf_close (file) ;
/* Open the file again to check the data. */
file = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < 3 * DATA_LENGTH)
{ printf ("\n\nLine %d : Not enough frames in file. (%ld < %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), 3 * DATA_LENGTH ) ;
exit (1) ;
}
if (! long_file_ok && sfinfo.frames != 3 * DATA_LENGTH)
{ printf ("\n\nLine %d : Incorrect number of frames in file. (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), 3 * DATA_LENGTH ) ;
exit (1) ;
} ;
if (sfinfo.channels != 1)
{ printf ("\n\nLine %d : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
if (! long_file_ok)
test_read_write_position_or_die (file, __LINE__, 0, 0, 3 * DATA_LENGTH) ;
else
test_seek_or_die (file, 3 * DATA_LENGTH, SFM_WRITE | SEEK_SET, 3 * DATA_LENGTH, sfinfo.channels, __LINE__) ;
for (pass = 1 ; pass <= 3 ; pass ++)
{ orig [20] = pass * 2 ;
test_read_write_position_or_die (file, __LINE__, pass, (pass - 1) * DATA_LENGTH, 3 * DATA_LENGTH) ;
/* Read what we just wrote. */
test_read_short_or_die (file, pass, test, DATA_LENGTH, __LINE__) ;
/* Check the data. */
for (k = 0 ; k < DATA_LENGTH ; k++)
if (CHAR_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d (pass %d): Error at sample %d (0x%X => 0x%X).\n", __LINE__, pass, k, orig [k], test [k]) ;
oct_save_short (orig, test, DATA_LENGTH) ;
exit (1) ;
} ;
} ; /* for (pass ...) */
sf_close (file) ;
} /* mono_rdwr_short_test */
static void
new_rdwr_char_test (const char *filename, int format, int allow_fd)
{ SNDFILE *wfile, *rwfile ;
SF_INFO sfinfo ;
short *orig, *test ;
int items, frames ;
orig = orig_data.s ;
test = test_data.s ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 2 ;
sfinfo.format = format ;
items = DATA_LENGTH ;
frames = items / sfinfo.channels ;
wfile = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_command (wfile, SFC_SET_UPDATE_HEADER_AUTO, NULL, SF_TRUE) ;
test_writef_short_or_die (wfile, 1, orig, frames, __LINE__) ;
sf_write_sync (wfile) ;
test_writef_short_or_die (wfile, 2, orig, frames, __LINE__) ;
sf_write_sync (wfile) ;
rwfile = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.frames != 2 * frames)
{ printf ("\n\nLine %d : incorrect number of frames in file (%ld shold be %d)\n\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
test_writef_short_or_die (wfile, 3, orig, frames, __LINE__) ;
test_readf_short_or_die (rwfile, 1, test, frames, __LINE__) ;
test_readf_short_or_die (rwfile, 2, test, frames, __LINE__) ;
sf_close (wfile) ;
sf_close (rwfile) ;
} /* new_rdwr_char_test */
/*======================================================================================
*/
static void mono_short_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void stereo_short_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void mono_rdwr_short_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void new_rdwr_short_test (const char *filename, int format, int allow_fd) ;
static void
pcm_test_short (const char *filename, int format, int long_file_ok)
{ SF_INFO sfinfo ;
short *orig, *test ;
int k, items, allow_fd ;
/* Sd2 files cannot be opened from an existing file descriptor. */
allow_fd = ((format & SF_FORMAT_TYPEMASK) == SF_FORMAT_SD2) ? SF_FALSE : SF_TRUE ;
print_test_name ("pcm_test_short", filename) ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 1 ;
sfinfo.format = format ;
gen_windowed_sine_double (orig_data.d, DATA_LENGTH, 32000.0) ;
orig = orig_data.s ;
test = test_data.s ;
/* Make this a macro so gdb steps over it in one go. */
CONVERT_DATA (k, DATA_LENGTH, orig, orig_data.d) ;
items = DATA_LENGTH ;
/* Some test broken out here. */
mono_short_test (filename, format, long_file_ok, allow_fd) ;
/* Sub format DWVW does not allow seeking. */
if ((format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_16 ||
(format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_24)
{ unlink (filename) ;
printf ("no seek : ok\n") ;
return ;
} ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_FLAC)
mono_rdwr_short_test (filename, format, long_file_ok, allow_fd) ;
/* If the format doesn't support stereo we're done. */
sfinfo.channels = 2 ;
if (sf_format_check (&sfinfo) == 0)
{ unlink (filename) ;
puts ("no stereo : ok") ;
return ;
} ;
stereo_short_test (filename, format, long_file_ok, allow_fd) ;
/* New read/write test. Not sure if this is needed yet. */
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_PAF &&
(format & SF_FORMAT_TYPEMASK) != SF_FORMAT_VOC &&
(format & SF_FORMAT_TYPEMASK) != SF_FORMAT_FLAC)
new_rdwr_short_test (filename, format, allow_fd) ;
delete_file (format, filename) ;
puts ("ok") ;
return ;
} /* pcm_test_short */
static void
mono_short_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
short *orig, *test ;
sf_count_t count ;
int k, items ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 1 ;
sfinfo.format = format ;
orig = orig_data.s ;
test = test_data.s ;
items = DATA_LENGTH ;
file = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_set_string (file, SF_STR_ARTIST, "Your name here") ;
test_write_short_or_die (file, 0, orig, items, __LINE__) ;
sf_write_sync (file) ;
test_write_short_or_die (file, 0, orig, items, __LINE__) ;
sf_write_sync (file) ;
/* Add non-audio data after the audio. */
sf_set_string (file, SF_STR_COPYRIGHT, "Copyright (c) 2003") ;
sf_close (file) ;
memset (test, 0, items * sizeof (short)) ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_RAW)
memset (&sfinfo, 0, sizeof (sfinfo)) ;
file = test_open_file_or_die (filename, SFM_READ, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Mono : Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < 2 * items)
{ printf ("\n\nLine %d : Mono : Incorrect number of frames in file (too short). (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), items) ;
exit (1) ;
} ;
if (! long_file_ok && sfinfo.frames > 2 * items)
{ printf ("\n\nLine %d : Mono : Incorrect number of frames in file (too long). (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), items) ;
exit (1) ;
} ;
if (sfinfo.channels != 1)
{ printf ("\n\nLine %d : Mono : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
check_log_buffer_or_die (file, __LINE__) ;
test_read_short_or_die (file, 0, test, items, __LINE__) ;
for (k = 0 ; k < items ; k++)
if (INT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d: Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to start of file. */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
test_read_short_or_die (file, 0, test, 4, __LINE__) ;
for (k = 0 ; k < 4 ; k++)
if (INT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
if ((format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_16 ||
(format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_24)
{ sf_close (file) ;
unlink (filename) ;
printf ("no seek : ") ;
return ;
} ;
/* Seek to offset from start of file. */
test_seek_or_die (file, items + 10, SEEK_SET, items + 10, sfinfo.channels, __LINE__) ;
test_read_short_or_die (file, 0, test + 10, 4, __LINE__) ;
for (k = 10 ; k < 14 ; k++)
if (INT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Seek to offset from current position. */
test_seek_or_die (file, 6, SEEK_CUR, items + 20, sfinfo.channels, __LINE__) ;
test_read_short_or_die (file, 0, test + 20, 4, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (INT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Seek to offset from end of file. */
test_seek_or_die (file, -1 * (sfinfo.frames - 10), SEEK_END, 10, sfinfo.channels, __LINE__) ;
test_read_short_or_die (file, 0, test + 10, 4, __LINE__) ;
for (k = 10 ; k < 14 ; k++)
if (INT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample D (#%d : 0x%X => 0x%X).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Check read past end of file followed by sf_seek (sndfile, 0, SEEK_CUR). */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
count = 0 ;
while (count < sfinfo.frames)
count += sf_read_short (file, test, 311) ;
/* Check that no error has occurred. */
if (sf_error (file))
{ printf ("\n\nLine %d : Mono : error where there shouldn't have been one.\n", __LINE__) ;
puts (sf_strerror (file)) ;
exit (1) ;
} ;
/* Check that we haven't read beyond EOF. */
if (count > sfinfo.frames)
{ printf ("\n\nLines %d : read past end of file (%ld should be %ld)\n", __LINE__, (long) count, (long) sfinfo.frames) ;
exit (1) ;
} ;
test_seek_or_die (file, 0, SEEK_CUR, sfinfo.frames, sfinfo.channels, __LINE__) ;
sf_close (file) ;
} /* mono_short_test */
static void
stereo_short_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
short *orig, *test ;
int k, items, frames ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 2 ;
sfinfo.format = format ;
gen_windowed_sine_double (orig_data.d, DATA_LENGTH, 32000.0) ;
orig = orig_data.s ;
test = test_data.s ;
/* Make this a macro so gdb steps over it in one go. */
CONVERT_DATA (k, DATA_LENGTH, orig, orig_data.d) ;
items = DATA_LENGTH ;
frames = items / sfinfo.channels ;
file = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_set_string (file, SF_STR_ARTIST, "Your name here") ;
test_writef_short_or_die (file, 0, orig, frames, __LINE__) ;
sf_set_string (file, SF_STR_COPYRIGHT, "Copyright (c) 2003") ;
sf_close (file) ;
memset (test, 0, items * sizeof (short)) ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_RAW)
memset (&sfinfo, 0, sizeof (sfinfo)) ;
file = test_open_file_or_die (filename, SFM_READ, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Stereo : Returned format incorrect (0x%08X => 0x%08X).\n",
__LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < frames)
{ printf ("\n\nLine %d : Stereo : Incorrect number of frames in file (too short). (%ld should be %d)\n",
__LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
if (! long_file_ok && sfinfo.frames > frames)
{ printf ("\n\nLine %d : Stereo : Incorrect number of frames in file (too long). (%ld should be %d)\n",
__LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
if (sfinfo.channels != 2)
{ printf ("\n\nLine %d : Stereo : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
check_log_buffer_or_die (file, __LINE__) ;
test_readf_short_or_die (file, 0, test, frames, __LINE__) ;
for (k = 0 ; k < items ; k++)
if (INT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to start of file. */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
test_readf_short_or_die (file, 0, test, 2, __LINE__) ;
for (k = 0 ; k < 4 ; k++)
if (INT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from start of file. */
test_seek_or_die (file, 10, SEEK_SET, 10, sfinfo.channels, __LINE__) ;
/* Check for errors here. */
if (sf_error (file))
{ printf ("Line %d: Should NOT return an error.\n", __LINE__) ;
puts (sf_strerror (file)) ;
exit (1) ;
} ;
if (sf_read_short (file, test, 1) > 0)
{ printf ("Line %d: Should return 0.\n", __LINE__) ;
exit (1) ;
} ;
if (! sf_error (file))
{ printf ("Line %d: Should return an error.\n", __LINE__) ;
exit (1) ;
} ;
/*-----------------------*/
test_readf_short_or_die (file, 0, test + 10, 2, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (INT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from current position. */
test_seek_or_die (file, 8, SEEK_CUR, 20, sfinfo.channels, __LINE__) ;
test_readf_short_or_die (file, 0, test + 20, 2, __LINE__) ;
for (k = 40 ; k < 44 ; k++)
if (INT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from end of file. */
test_seek_or_die (file, -1 * (sfinfo.frames - 10), SEEK_END, 10, sfinfo.channels, __LINE__) ;
test_readf_short_or_die (file, 0, test + 20, 2, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (INT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
sf_close (file) ;
} /* stereo_short_test */
static void
mono_rdwr_short_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
short *orig, *test ;
int k, pass ;
orig = orig_data.s ;
test = test_data.s ;
sfinfo.samplerate = SAMPLE_RATE ;
sfinfo.frames = DATA_LENGTH ;
sfinfo.channels = 1 ;
sfinfo.format = format ;
if ((format & SF_FORMAT_TYPEMASK) == SF_FORMAT_RAW
|| (format & SF_FORMAT_TYPEMASK) == SF_FORMAT_AU
|| (format & SF_FORMAT_TYPEMASK) == SF_FORMAT_SD2)
unlink (filename) ;
else
{ /* Create a short file. */
create_short_file (filename) ;
/* Opening a already existing short file (ie invalid header) RDWR is disallowed.
** If this returns a valif pointer sf_open() screwed up.
*/
if ((file = sf_open (filename, SFM_RDWR, &sfinfo)))
{ printf ("\n\nLine %d: sf_open should (SFM_RDWR) have failed but didn't.\n", __LINE__) ;
exit (1) ;
} ;
/* Truncate the file to zero bytes. */
if (truncate (filename, 0) < 0)
{ printf ("\n\nLine %d: truncate (%s) failed", __LINE__, filename) ;
perror (NULL) ;
exit (1) ;
} ;
} ;
/* Opening a zero length file RDWR is allowed, but the SF_INFO struct must contain
** all the usual data required when opening the file in WRITE mode.
*/
sfinfo.samplerate = SAMPLE_RATE ;
sfinfo.frames = DATA_LENGTH ;
sfinfo.channels = 1 ;
sfinfo.format = format ;
file = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
/* Do 3 writes followed by reads. After each, check the data and the current
** read and write offsets.
*/
for (pass = 1 ; pass <= 3 ; pass ++)
{ orig [20] = pass * 2 ;
/* Write some data. */
test_write_short_or_die (file, pass, orig, DATA_LENGTH, __LINE__) ;
test_read_write_position_or_die (file, __LINE__, pass, (pass - 1) * DATA_LENGTH, pass * DATA_LENGTH) ;
/* Read what we just wrote. */
test_read_short_or_die (file, 0, test, DATA_LENGTH, __LINE__) ;
/* Check the data. */
for (k = 0 ; k < DATA_LENGTH ; k++)
if (INT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d (pass %d): Error at sample %d (0x%X => 0x%X).\n", __LINE__, pass, k, orig [k], test [k]) ;
oct_save_short (orig, test, DATA_LENGTH) ;
exit (1) ;
} ;
test_read_write_position_or_die (file, __LINE__, pass, pass * DATA_LENGTH, pass * DATA_LENGTH) ;
} ; /* for (pass ...) */
sf_close (file) ;
/* Open the file again to check the data. */
file = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < 3 * DATA_LENGTH)
{ printf ("\n\nLine %d : Not enough frames in file. (%ld < %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), 3 * DATA_LENGTH ) ;
exit (1) ;
}
if (! long_file_ok && sfinfo.frames != 3 * DATA_LENGTH)
{ printf ("\n\nLine %d : Incorrect number of frames in file. (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), 3 * DATA_LENGTH ) ;
exit (1) ;
} ;
if (sfinfo.channels != 1)
{ printf ("\n\nLine %d : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
if (! long_file_ok)
test_read_write_position_or_die (file, __LINE__, 0, 0, 3 * DATA_LENGTH) ;
else
test_seek_or_die (file, 3 * DATA_LENGTH, SFM_WRITE | SEEK_SET, 3 * DATA_LENGTH, sfinfo.channels, __LINE__) ;
for (pass = 1 ; pass <= 3 ; pass ++)
{ orig [20] = pass * 2 ;
test_read_write_position_or_die (file, __LINE__, pass, (pass - 1) * DATA_LENGTH, 3 * DATA_LENGTH) ;
/* Read what we just wrote. */
test_read_short_or_die (file, pass, test, DATA_LENGTH, __LINE__) ;
/* Check the data. */
for (k = 0 ; k < DATA_LENGTH ; k++)
if (INT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d (pass %d): Error at sample %d (0x%X => 0x%X).\n", __LINE__, pass, k, orig [k], test [k]) ;
oct_save_short (orig, test, DATA_LENGTH) ;
exit (1) ;
} ;
} ; /* for (pass ...) */
sf_close (file) ;
} /* mono_rdwr_short_test */
static void
new_rdwr_short_test (const char *filename, int format, int allow_fd)
{ SNDFILE *wfile, *rwfile ;
SF_INFO sfinfo ;
short *orig, *test ;
int items, frames ;
orig = orig_data.s ;
test = test_data.s ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 2 ;
sfinfo.format = format ;
items = DATA_LENGTH ;
frames = items / sfinfo.channels ;
wfile = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_command (wfile, SFC_SET_UPDATE_HEADER_AUTO, NULL, SF_TRUE) ;
test_writef_short_or_die (wfile, 1, orig, frames, __LINE__) ;
sf_write_sync (wfile) ;
test_writef_short_or_die (wfile, 2, orig, frames, __LINE__) ;
sf_write_sync (wfile) ;
rwfile = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.frames != 2 * frames)
{ printf ("\n\nLine %d : incorrect number of frames in file (%ld shold be %d)\n\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
test_writef_short_or_die (wfile, 3, orig, frames, __LINE__) ;
test_readf_short_or_die (rwfile, 1, test, frames, __LINE__) ;
test_readf_short_or_die (rwfile, 2, test, frames, __LINE__) ;
sf_close (wfile) ;
sf_close (rwfile) ;
} /* new_rdwr_short_test */
/*======================================================================================
*/
static void mono_24bit_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void stereo_24bit_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void mono_rdwr_24bit_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void new_rdwr_24bit_test (const char *filename, int format, int allow_fd) ;
static void
pcm_test_24bit (const char *filename, int format, int long_file_ok)
{ SF_INFO sfinfo ;
int *orig, *test ;
int k, items, allow_fd ;
/* Sd2 files cannot be opened from an existing file descriptor. */
allow_fd = ((format & SF_FORMAT_TYPEMASK) == SF_FORMAT_SD2) ? SF_FALSE : SF_TRUE ;
print_test_name ("pcm_test_24bit", filename) ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 1 ;
sfinfo.format = format ;
gen_windowed_sine_double (orig_data.d, DATA_LENGTH, (1.0 * 0x7F000000)) ;
orig = orig_data.i ;
test = test_data.i ;
/* Make this a macro so gdb steps over it in one go. */
CONVERT_DATA (k, DATA_LENGTH, orig, orig_data.d) ;
items = DATA_LENGTH ;
/* Some test broken out here. */
mono_24bit_test (filename, format, long_file_ok, allow_fd) ;
/* Sub format DWVW does not allow seeking. */
if ((format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_16 ||
(format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_24)
{ unlink (filename) ;
printf ("no seek : ok\n") ;
return ;
} ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_FLAC)
mono_rdwr_24bit_test (filename, format, long_file_ok, allow_fd) ;
/* If the format doesn't support stereo we're done. */
sfinfo.channels = 2 ;
if (sf_format_check (&sfinfo) == 0)
{ unlink (filename) ;
puts ("no stereo : ok") ;
return ;
} ;
stereo_24bit_test (filename, format, long_file_ok, allow_fd) ;
/* New read/write test. Not sure if this is needed yet. */
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_PAF &&
(format & SF_FORMAT_TYPEMASK) != SF_FORMAT_VOC &&
(format & SF_FORMAT_TYPEMASK) != SF_FORMAT_FLAC)
new_rdwr_24bit_test (filename, format, allow_fd) ;
delete_file (format, filename) ;
puts ("ok") ;
return ;
} /* pcm_test_24bit */
static void
mono_24bit_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
int *orig, *test ;
sf_count_t count ;
int k, items ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 1 ;
sfinfo.format = format ;
orig = orig_data.i ;
test = test_data.i ;
items = DATA_LENGTH ;
file = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_set_string (file, SF_STR_ARTIST, "Your name here") ;
test_write_int_or_die (file, 0, orig, items, __LINE__) ;
sf_write_sync (file) ;
test_write_int_or_die (file, 0, orig, items, __LINE__) ;
sf_write_sync (file) ;
/* Add non-audio data after the audio. */
sf_set_string (file, SF_STR_COPYRIGHT, "Copyright (c) 2003") ;
sf_close (file) ;
memset (test, 0, items * sizeof (int)) ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_RAW)
memset (&sfinfo, 0, sizeof (sfinfo)) ;
file = test_open_file_or_die (filename, SFM_READ, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Mono : Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < 2 * items)
{ printf ("\n\nLine %d : Mono : Incorrect number of frames in file (too short). (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), items) ;
exit (1) ;
} ;
if (! long_file_ok && sfinfo.frames > 2 * items)
{ printf ("\n\nLine %d : Mono : Incorrect number of frames in file (too long). (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), items) ;
exit (1) ;
} ;
if (sfinfo.channels != 1)
{ printf ("\n\nLine %d : Mono : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
check_log_buffer_or_die (file, __LINE__) ;
test_read_int_or_die (file, 0, test, items, __LINE__) ;
for (k = 0 ; k < items ; k++)
if (TRIBYTE_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d: Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to start of file. */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
test_read_int_or_die (file, 0, test, 4, __LINE__) ;
for (k = 0 ; k < 4 ; k++)
if (TRIBYTE_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
if ((format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_16 ||
(format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_24)
{ sf_close (file) ;
unlink (filename) ;
printf ("no seek : ") ;
return ;
} ;
/* Seek to offset from start of file. */
test_seek_or_die (file, items + 10, SEEK_SET, items + 10, sfinfo.channels, __LINE__) ;
test_read_int_or_die (file, 0, test + 10, 4, __LINE__) ;
for (k = 10 ; k < 14 ; k++)
if (TRIBYTE_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Seek to offset from current position. */
test_seek_or_die (file, 6, SEEK_CUR, items + 20, sfinfo.channels, __LINE__) ;
test_read_int_or_die (file, 0, test + 20, 4, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (TRIBYTE_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Seek to offset from end of file. */
test_seek_or_die (file, -1 * (sfinfo.frames - 10), SEEK_END, 10, sfinfo.channels, __LINE__) ;
test_read_int_or_die (file, 0, test + 10, 4, __LINE__) ;
for (k = 10 ; k < 14 ; k++)
if (TRIBYTE_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample D (#%d : 0x%X => 0x%X).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Check read past end of file followed by sf_seek (sndfile, 0, SEEK_CUR). */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
count = 0 ;
while (count < sfinfo.frames)
count += sf_read_int (file, test, 311) ;
/* Check that no error has occurred. */
if (sf_error (file))
{ printf ("\n\nLine %d : Mono : error where there shouldn't have been one.\n", __LINE__) ;
puts (sf_strerror (file)) ;
exit (1) ;
} ;
/* Check that we haven't read beyond EOF. */
if (count > sfinfo.frames)
{ printf ("\n\nLines %d : read past end of file (%ld should be %ld)\n", __LINE__, (long) count, (long) sfinfo.frames) ;
exit (1) ;
} ;
test_seek_or_die (file, 0, SEEK_CUR, sfinfo.frames, sfinfo.channels, __LINE__) ;
sf_close (file) ;
} /* mono_24bit_test */
static void
stereo_24bit_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
int *orig, *test ;
int k, items, frames ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 2 ;
sfinfo.format = format ;
gen_windowed_sine_double (orig_data.d, DATA_LENGTH, (1.0 * 0x7F000000)) ;
orig = orig_data.i ;
test = test_data.i ;
/* Make this a macro so gdb steps over it in one go. */
CONVERT_DATA (k, DATA_LENGTH, orig, orig_data.d) ;
items = DATA_LENGTH ;
frames = items / sfinfo.channels ;
file = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_set_string (file, SF_STR_ARTIST, "Your name here") ;
test_writef_int_or_die (file, 0, orig, frames, __LINE__) ;
sf_set_string (file, SF_STR_COPYRIGHT, "Copyright (c) 2003") ;
sf_close (file) ;
memset (test, 0, items * sizeof (int)) ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_RAW)
memset (&sfinfo, 0, sizeof (sfinfo)) ;
file = test_open_file_or_die (filename, SFM_READ, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Stereo : Returned format incorrect (0x%08X => 0x%08X).\n",
__LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < frames)
{ printf ("\n\nLine %d : Stereo : Incorrect number of frames in file (too short). (%ld should be %d)\n",
__LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
if (! long_file_ok && sfinfo.frames > frames)
{ printf ("\n\nLine %d : Stereo : Incorrect number of frames in file (too long). (%ld should be %d)\n",
__LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
if (sfinfo.channels != 2)
{ printf ("\n\nLine %d : Stereo : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
check_log_buffer_or_die (file, __LINE__) ;
test_readf_int_or_die (file, 0, test, frames, __LINE__) ;
for (k = 0 ; k < items ; k++)
if (TRIBYTE_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to start of file. */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
test_readf_int_or_die (file, 0, test, 2, __LINE__) ;
for (k = 0 ; k < 4 ; k++)
if (TRIBYTE_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from start of file. */
test_seek_or_die (file, 10, SEEK_SET, 10, sfinfo.channels, __LINE__) ;
/* Check for errors here. */
if (sf_error (file))
{ printf ("Line %d: Should NOT return an error.\n", __LINE__) ;
puts (sf_strerror (file)) ;
exit (1) ;
} ;
if (sf_read_int (file, test, 1) > 0)
{ printf ("Line %d: Should return 0.\n", __LINE__) ;
exit (1) ;
} ;
if (! sf_error (file))
{ printf ("Line %d: Should return an error.\n", __LINE__) ;
exit (1) ;
} ;
/*-----------------------*/
test_readf_int_or_die (file, 0, test + 10, 2, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (TRIBYTE_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from current position. */
test_seek_or_die (file, 8, SEEK_CUR, 20, sfinfo.channels, __LINE__) ;
test_readf_int_or_die (file, 0, test + 20, 2, __LINE__) ;
for (k = 40 ; k < 44 ; k++)
if (TRIBYTE_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from end of file. */
test_seek_or_die (file, -1 * (sfinfo.frames - 10), SEEK_END, 10, sfinfo.channels, __LINE__) ;
test_readf_int_or_die (file, 0, test + 20, 2, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (TRIBYTE_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
sf_close (file) ;
} /* stereo_24bit_test */
static void
mono_rdwr_24bit_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
int *orig, *test ;
int k, pass ;
orig = orig_data.i ;
test = test_data.i ;
sfinfo.samplerate = SAMPLE_RATE ;
sfinfo.frames = DATA_LENGTH ;
sfinfo.channels = 1 ;
sfinfo.format = format ;
if ((format & SF_FORMAT_TYPEMASK) == SF_FORMAT_RAW
|| (format & SF_FORMAT_TYPEMASK) == SF_FORMAT_AU
|| (format & SF_FORMAT_TYPEMASK) == SF_FORMAT_SD2)
unlink (filename) ;
else
{ /* Create a short file. */
create_short_file (filename) ;
/* Opening a already existing short file (ie invalid header) RDWR is disallowed.
** If this returns a valif pointer sf_open() screwed up.
*/
if ((file = sf_open (filename, SFM_RDWR, &sfinfo)))
{ printf ("\n\nLine %d: sf_open should (SFM_RDWR) have failed but didn't.\n", __LINE__) ;
exit (1) ;
} ;
/* Truncate the file to zero bytes. */
if (truncate (filename, 0) < 0)
{ printf ("\n\nLine %d: truncate (%s) failed", __LINE__, filename) ;
perror (NULL) ;
exit (1) ;
} ;
} ;
/* Opening a zero length file RDWR is allowed, but the SF_INFO struct must contain
** all the usual data required when opening the file in WRITE mode.
*/
sfinfo.samplerate = SAMPLE_RATE ;
sfinfo.frames = DATA_LENGTH ;
sfinfo.channels = 1 ;
sfinfo.format = format ;
file = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
/* Do 3 writes followed by reads. After each, check the data and the current
** read and write offsets.
*/
for (pass = 1 ; pass <= 3 ; pass ++)
{ orig [20] = pass * 2 ;
/* Write some data. */
test_write_int_or_die (file, pass, orig, DATA_LENGTH, __LINE__) ;
test_read_write_position_or_die (file, __LINE__, pass, (pass - 1) * DATA_LENGTH, pass * DATA_LENGTH) ;
/* Read what we just wrote. */
test_read_int_or_die (file, 0, test, DATA_LENGTH, __LINE__) ;
/* Check the data. */
for (k = 0 ; k < DATA_LENGTH ; k++)
if (TRIBYTE_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d (pass %d): Error at sample %d (0x%X => 0x%X).\n", __LINE__, pass, k, orig [k], test [k]) ;
oct_save_int (orig, test, DATA_LENGTH) ;
exit (1) ;
} ;
test_read_write_position_or_die (file, __LINE__, pass, pass * DATA_LENGTH, pass * DATA_LENGTH) ;
} ; /* for (pass ...) */
sf_close (file) ;
/* Open the file again to check the data. */
file = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < 3 * DATA_LENGTH)
{ printf ("\n\nLine %d : Not enough frames in file. (%ld < %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), 3 * DATA_LENGTH ) ;
exit (1) ;
}
if (! long_file_ok && sfinfo.frames != 3 * DATA_LENGTH)
{ printf ("\n\nLine %d : Incorrect number of frames in file. (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), 3 * DATA_LENGTH ) ;
exit (1) ;
} ;
if (sfinfo.channels != 1)
{ printf ("\n\nLine %d : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
if (! long_file_ok)
test_read_write_position_or_die (file, __LINE__, 0, 0, 3 * DATA_LENGTH) ;
else
test_seek_or_die (file, 3 * DATA_LENGTH, SFM_WRITE | SEEK_SET, 3 * DATA_LENGTH, sfinfo.channels, __LINE__) ;
for (pass = 1 ; pass <= 3 ; pass ++)
{ orig [20] = pass * 2 ;
test_read_write_position_or_die (file, __LINE__, pass, (pass - 1) * DATA_LENGTH, 3 * DATA_LENGTH) ;
/* Read what we just wrote. */
test_read_int_or_die (file, pass, test, DATA_LENGTH, __LINE__) ;
/* Check the data. */
for (k = 0 ; k < DATA_LENGTH ; k++)
if (TRIBYTE_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d (pass %d): Error at sample %d (0x%X => 0x%X).\n", __LINE__, pass, k, orig [k], test [k]) ;
oct_save_int (orig, test, DATA_LENGTH) ;
exit (1) ;
} ;
} ; /* for (pass ...) */
sf_close (file) ;
} /* mono_rdwr_int_test */
static void
new_rdwr_24bit_test (const char *filename, int format, int allow_fd)
{ SNDFILE *wfile, *rwfile ;
SF_INFO sfinfo ;
int *orig, *test ;
int items, frames ;
orig = orig_data.i ;
test = test_data.i ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 2 ;
sfinfo.format = format ;
items = DATA_LENGTH ;
frames = items / sfinfo.channels ;
wfile = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_command (wfile, SFC_SET_UPDATE_HEADER_AUTO, NULL, SF_TRUE) ;
test_writef_int_or_die (wfile, 1, orig, frames, __LINE__) ;
sf_write_sync (wfile) ;
test_writef_int_or_die (wfile, 2, orig, frames, __LINE__) ;
sf_write_sync (wfile) ;
rwfile = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.frames != 2 * frames)
{ printf ("\n\nLine %d : incorrect number of frames in file (%ld shold be %d)\n\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
test_writef_int_or_die (wfile, 3, orig, frames, __LINE__) ;
test_readf_int_or_die (rwfile, 1, test, frames, __LINE__) ;
test_readf_int_or_die (rwfile, 2, test, frames, __LINE__) ;
sf_close (wfile) ;
sf_close (rwfile) ;
} /* new_rdwr_24bit_test */
/*======================================================================================
*/
static void mono_int_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void stereo_int_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void mono_rdwr_int_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void new_rdwr_int_test (const char *filename, int format, int allow_fd) ;
static void
pcm_test_int (const char *filename, int format, int long_file_ok)
{ SF_INFO sfinfo ;
int *orig, *test ;
int k, items, allow_fd ;
/* Sd2 files cannot be opened from an existing file descriptor. */
allow_fd = ((format & SF_FORMAT_TYPEMASK) == SF_FORMAT_SD2) ? SF_FALSE : SF_TRUE ;
print_test_name ("pcm_test_int", filename) ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 1 ;
sfinfo.format = format ;
gen_windowed_sine_double (orig_data.d, DATA_LENGTH, (1.0 * 0x7F000000)) ;
orig = orig_data.i ;
test = test_data.i ;
/* Make this a macro so gdb steps over it in one go. */
CONVERT_DATA (k, DATA_LENGTH, orig, orig_data.d) ;
items = DATA_LENGTH ;
/* Some test broken out here. */
mono_int_test (filename, format, long_file_ok, allow_fd) ;
/* Sub format DWVW does not allow seeking. */
if ((format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_16 ||
(format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_24)
{ unlink (filename) ;
printf ("no seek : ok\n") ;
return ;
} ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_FLAC)
mono_rdwr_int_test (filename, format, long_file_ok, allow_fd) ;
/* If the format doesn't support stereo we're done. */
sfinfo.channels = 2 ;
if (sf_format_check (&sfinfo) == 0)
{ unlink (filename) ;
puts ("no stereo : ok") ;
return ;
} ;
stereo_int_test (filename, format, long_file_ok, allow_fd) ;
/* New read/write test. Not sure if this is needed yet. */
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_PAF &&
(format & SF_FORMAT_TYPEMASK) != SF_FORMAT_VOC &&
(format & SF_FORMAT_TYPEMASK) != SF_FORMAT_FLAC)
new_rdwr_int_test (filename, format, allow_fd) ;
delete_file (format, filename) ;
puts ("ok") ;
return ;
} /* pcm_test_int */
static void
mono_int_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
int *orig, *test ;
sf_count_t count ;
int k, items ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 1 ;
sfinfo.format = format ;
orig = orig_data.i ;
test = test_data.i ;
items = DATA_LENGTH ;
file = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_set_string (file, SF_STR_ARTIST, "Your name here") ;
test_write_int_or_die (file, 0, orig, items, __LINE__) ;
sf_write_sync (file) ;
test_write_int_or_die (file, 0, orig, items, __LINE__) ;
sf_write_sync (file) ;
/* Add non-audio data after the audio. */
sf_set_string (file, SF_STR_COPYRIGHT, "Copyright (c) 2003") ;
sf_close (file) ;
memset (test, 0, items * sizeof (int)) ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_RAW)
memset (&sfinfo, 0, sizeof (sfinfo)) ;
file = test_open_file_or_die (filename, SFM_READ, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Mono : Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < 2 * items)
{ printf ("\n\nLine %d : Mono : Incorrect number of frames in file (too short). (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), items) ;
exit (1) ;
} ;
if (! long_file_ok && sfinfo.frames > 2 * items)
{ printf ("\n\nLine %d : Mono : Incorrect number of frames in file (too long). (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), items) ;
exit (1) ;
} ;
if (sfinfo.channels != 1)
{ printf ("\n\nLine %d : Mono : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
check_log_buffer_or_die (file, __LINE__) ;
test_read_int_or_die (file, 0, test, items, __LINE__) ;
for (k = 0 ; k < items ; k++)
if (INT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d: Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to start of file. */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
test_read_int_or_die (file, 0, test, 4, __LINE__) ;
for (k = 0 ; k < 4 ; k++)
if (INT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
if ((format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_16 ||
(format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_24)
{ sf_close (file) ;
unlink (filename) ;
printf ("no seek : ") ;
return ;
} ;
/* Seek to offset from start of file. */
test_seek_or_die (file, items + 10, SEEK_SET, items + 10, sfinfo.channels, __LINE__) ;
test_read_int_or_die (file, 0, test + 10, 4, __LINE__) ;
for (k = 10 ; k < 14 ; k++)
if (INT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Seek to offset from current position. */
test_seek_or_die (file, 6, SEEK_CUR, items + 20, sfinfo.channels, __LINE__) ;
test_read_int_or_die (file, 0, test + 20, 4, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (INT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : 0x%X => 0x%X).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Seek to offset from end of file. */
test_seek_or_die (file, -1 * (sfinfo.frames - 10), SEEK_END, 10, sfinfo.channels, __LINE__) ;
test_read_int_or_die (file, 0, test + 10, 4, __LINE__) ;
for (k = 10 ; k < 14 ; k++)
if (INT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample D (#%d : 0x%X => 0x%X).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Check read past end of file followed by sf_seek (sndfile, 0, SEEK_CUR). */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
count = 0 ;
while (count < sfinfo.frames)
count += sf_read_int (file, test, 311) ;
/* Check that no error has occurred. */
if (sf_error (file))
{ printf ("\n\nLine %d : Mono : error where there shouldn't have been one.\n", __LINE__) ;
puts (sf_strerror (file)) ;
exit (1) ;
} ;
/* Check that we haven't read beyond EOF. */
if (count > sfinfo.frames)
{ printf ("\n\nLines %d : read past end of file (%ld should be %ld)\n", __LINE__, (long) count, (long) sfinfo.frames) ;
exit (1) ;
} ;
test_seek_or_die (file, 0, SEEK_CUR, sfinfo.frames, sfinfo.channels, __LINE__) ;
sf_close (file) ;
} /* mono_int_test */
static void
stereo_int_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
int *orig, *test ;
int k, items, frames ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 2 ;
sfinfo.format = format ;
gen_windowed_sine_double (orig_data.d, DATA_LENGTH, (1.0 * 0x7F000000)) ;
orig = orig_data.i ;
test = test_data.i ;
/* Make this a macro so gdb steps over it in one go. */
CONVERT_DATA (k, DATA_LENGTH, orig, orig_data.d) ;
items = DATA_LENGTH ;
frames = items / sfinfo.channels ;
file = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_set_string (file, SF_STR_ARTIST, "Your name here") ;
test_writef_int_or_die (file, 0, orig, frames, __LINE__) ;
sf_set_string (file, SF_STR_COPYRIGHT, "Copyright (c) 2003") ;
sf_close (file) ;
memset (test, 0, items * sizeof (int)) ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_RAW)
memset (&sfinfo, 0, sizeof (sfinfo)) ;
file = test_open_file_or_die (filename, SFM_READ, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Stereo : Returned format incorrect (0x%08X => 0x%08X).\n",
__LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < frames)
{ printf ("\n\nLine %d : Stereo : Incorrect number of frames in file (too short). (%ld should be %d)\n",
__LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
if (! long_file_ok && sfinfo.frames > frames)
{ printf ("\n\nLine %d : Stereo : Incorrect number of frames in file (too long). (%ld should be %d)\n",
__LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
if (sfinfo.channels != 2)
{ printf ("\n\nLine %d : Stereo : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
check_log_buffer_or_die (file, __LINE__) ;
test_readf_int_or_die (file, 0, test, frames, __LINE__) ;
for (k = 0 ; k < items ; k++)
if (INT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to start of file. */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
test_readf_int_or_die (file, 0, test, 2, __LINE__) ;
for (k = 0 ; k < 4 ; k++)
if (INT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from start of file. */
test_seek_or_die (file, 10, SEEK_SET, 10, sfinfo.channels, __LINE__) ;
/* Check for errors here. */
if (sf_error (file))
{ printf ("Line %d: Should NOT return an error.\n", __LINE__) ;
puts (sf_strerror (file)) ;
exit (1) ;
} ;
if (sf_read_int (file, test, 1) > 0)
{ printf ("Line %d: Should return 0.\n", __LINE__) ;
exit (1) ;
} ;
if (! sf_error (file))
{ printf ("Line %d: Should return an error.\n", __LINE__) ;
exit (1) ;
} ;
/*-----------------------*/
test_readf_int_or_die (file, 0, test + 10, 2, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (INT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from current position. */
test_seek_or_die (file, 8, SEEK_CUR, 20, sfinfo.channels, __LINE__) ;
test_readf_int_or_die (file, 0, test + 20, 2, __LINE__) ;
for (k = 40 ; k < 44 ; k++)
if (INT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from end of file. */
test_seek_or_die (file, -1 * (sfinfo.frames - 10), SEEK_END, 10, sfinfo.channels, __LINE__) ;
test_readf_int_or_die (file, 0, test + 20, 2, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (INT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : 0x%X => 0x%X).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
sf_close (file) ;
} /* stereo_int_test */
static void
mono_rdwr_int_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
int *orig, *test ;
int k, pass ;
orig = orig_data.i ;
test = test_data.i ;
sfinfo.samplerate = SAMPLE_RATE ;
sfinfo.frames = DATA_LENGTH ;
sfinfo.channels = 1 ;
sfinfo.format = format ;
if ((format & SF_FORMAT_TYPEMASK) == SF_FORMAT_RAW
|| (format & SF_FORMAT_TYPEMASK) == SF_FORMAT_AU
|| (format & SF_FORMAT_TYPEMASK) == SF_FORMAT_SD2)
unlink (filename) ;
else
{ /* Create a short file. */
create_short_file (filename) ;
/* Opening a already existing short file (ie invalid header) RDWR is disallowed.
** If this returns a valif pointer sf_open() screwed up.
*/
if ((file = sf_open (filename, SFM_RDWR, &sfinfo)))
{ printf ("\n\nLine %d: sf_open should (SFM_RDWR) have failed but didn't.\n", __LINE__) ;
exit (1) ;
} ;
/* Truncate the file to zero bytes. */
if (truncate (filename, 0) < 0)
{ printf ("\n\nLine %d: truncate (%s) failed", __LINE__, filename) ;
perror (NULL) ;
exit (1) ;
} ;
} ;
/* Opening a zero length file RDWR is allowed, but the SF_INFO struct must contain
** all the usual data required when opening the file in WRITE mode.
*/
sfinfo.samplerate = SAMPLE_RATE ;
sfinfo.frames = DATA_LENGTH ;
sfinfo.channels = 1 ;
sfinfo.format = format ;
file = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
/* Do 3 writes followed by reads. After each, check the data and the current
** read and write offsets.
*/
for (pass = 1 ; pass <= 3 ; pass ++)
{ orig [20] = pass * 2 ;
/* Write some data. */
test_write_int_or_die (file, pass, orig, DATA_LENGTH, __LINE__) ;
test_read_write_position_or_die (file, __LINE__, pass, (pass - 1) * DATA_LENGTH, pass * DATA_LENGTH) ;
/* Read what we just wrote. */
test_read_int_or_die (file, 0, test, DATA_LENGTH, __LINE__) ;
/* Check the data. */
for (k = 0 ; k < DATA_LENGTH ; k++)
if (INT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d (pass %d): Error at sample %d (0x%X => 0x%X).\n", __LINE__, pass, k, orig [k], test [k]) ;
oct_save_int (orig, test, DATA_LENGTH) ;
exit (1) ;
} ;
test_read_write_position_or_die (file, __LINE__, pass, pass * DATA_LENGTH, pass * DATA_LENGTH) ;
} ; /* for (pass ...) */
sf_close (file) ;
/* Open the file again to check the data. */
file = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < 3 * DATA_LENGTH)
{ printf ("\n\nLine %d : Not enough frames in file. (%ld < %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), 3 * DATA_LENGTH ) ;
exit (1) ;
}
if (! long_file_ok && sfinfo.frames != 3 * DATA_LENGTH)
{ printf ("\n\nLine %d : Incorrect number of frames in file. (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), 3 * DATA_LENGTH ) ;
exit (1) ;
} ;
if (sfinfo.channels != 1)
{ printf ("\n\nLine %d : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
if (! long_file_ok)
test_read_write_position_or_die (file, __LINE__, 0, 0, 3 * DATA_LENGTH) ;
else
test_seek_or_die (file, 3 * DATA_LENGTH, SFM_WRITE | SEEK_SET, 3 * DATA_LENGTH, sfinfo.channels, __LINE__) ;
for (pass = 1 ; pass <= 3 ; pass ++)
{ orig [20] = pass * 2 ;
test_read_write_position_or_die (file, __LINE__, pass, (pass - 1) * DATA_LENGTH, 3 * DATA_LENGTH) ;
/* Read what we just wrote. */
test_read_int_or_die (file, pass, test, DATA_LENGTH, __LINE__) ;
/* Check the data. */
for (k = 0 ; k < DATA_LENGTH ; k++)
if (INT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d (pass %d): Error at sample %d (0x%X => 0x%X).\n", __LINE__, pass, k, orig [k], test [k]) ;
oct_save_int (orig, test, DATA_LENGTH) ;
exit (1) ;
} ;
} ; /* for (pass ...) */
sf_close (file) ;
} /* mono_rdwr_int_test */
static void
new_rdwr_int_test (const char *filename, int format, int allow_fd)
{ SNDFILE *wfile, *rwfile ;
SF_INFO sfinfo ;
int *orig, *test ;
int items, frames ;
orig = orig_data.i ;
test = test_data.i ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 2 ;
sfinfo.format = format ;
items = DATA_LENGTH ;
frames = items / sfinfo.channels ;
wfile = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_command (wfile, SFC_SET_UPDATE_HEADER_AUTO, NULL, SF_TRUE) ;
test_writef_int_or_die (wfile, 1, orig, frames, __LINE__) ;
sf_write_sync (wfile) ;
test_writef_int_or_die (wfile, 2, orig, frames, __LINE__) ;
sf_write_sync (wfile) ;
rwfile = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.frames != 2 * frames)
{ printf ("\n\nLine %d : incorrect number of frames in file (%ld shold be %d)\n\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
test_writef_int_or_die (wfile, 3, orig, frames, __LINE__) ;
test_readf_int_or_die (rwfile, 1, test, frames, __LINE__) ;
test_readf_int_or_die (rwfile, 2, test, frames, __LINE__) ;
sf_close (wfile) ;
sf_close (rwfile) ;
} /* new_rdwr_int_test */
/*======================================================================================
*/
static void mono_float_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void stereo_float_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void mono_rdwr_float_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void new_rdwr_float_test (const char *filename, int format, int allow_fd) ;
static void
pcm_test_float (const char *filename, int format, int long_file_ok)
{ SF_INFO sfinfo ;
float *orig, *test ;
int k, items, allow_fd ;
/* Sd2 files cannot be opened from an existing file descriptor. */
allow_fd = ((format & SF_FORMAT_TYPEMASK) == SF_FORMAT_SD2) ? SF_FALSE : SF_TRUE ;
print_test_name ("pcm_test_float", filename) ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 1 ;
sfinfo.format = format ;
gen_windowed_sine_double (orig_data.d, DATA_LENGTH, 1.0) ;
orig = orig_data.f ;
test = test_data.f ;
/* Make this a macro so gdb steps over it in one go. */
CONVERT_DATA (k, DATA_LENGTH, orig, orig_data.d) ;
items = DATA_LENGTH ;
/* Some test broken out here. */
mono_float_test (filename, format, long_file_ok, allow_fd) ;
/* Sub format DWVW does not allow seeking. */
if ((format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_16 ||
(format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_24)
{ unlink (filename) ;
printf ("no seek : ok\n") ;
return ;
} ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_FLAC)
mono_rdwr_float_test (filename, format, long_file_ok, allow_fd) ;
/* If the format doesn't support stereo we're done. */
sfinfo.channels = 2 ;
if (sf_format_check (&sfinfo) == 0)
{ unlink (filename) ;
puts ("no stereo : ok") ;
return ;
} ;
stereo_float_test (filename, format, long_file_ok, allow_fd) ;
/* New read/write test. Not sure if this is needed yet. */
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_PAF &&
(format & SF_FORMAT_TYPEMASK) != SF_FORMAT_VOC &&
(format & SF_FORMAT_TYPEMASK) != SF_FORMAT_FLAC)
new_rdwr_float_test (filename, format, allow_fd) ;
delete_file (format, filename) ;
puts ("ok") ;
return ;
} /* pcm_test_float */
static void
mono_float_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
float *orig, *test ;
sf_count_t count ;
int k, items ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 1 ;
sfinfo.format = format ;
orig = orig_data.f ;
test = test_data.f ;
items = DATA_LENGTH ;
file = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_set_string (file, SF_STR_ARTIST, "Your name here") ;
test_write_float_or_die (file, 0, orig, items, __LINE__) ;
sf_write_sync (file) ;
test_write_float_or_die (file, 0, orig, items, __LINE__) ;
sf_write_sync (file) ;
/* Add non-audio data after the audio. */
sf_set_string (file, SF_STR_COPYRIGHT, "Copyright (c) 2003") ;
sf_close (file) ;
memset (test, 0, items * sizeof (float)) ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_RAW)
memset (&sfinfo, 0, sizeof (sfinfo)) ;
file = test_open_file_or_die (filename, SFM_READ, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Mono : Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < 2 * items)
{ printf ("\n\nLine %d : Mono : Incorrect number of frames in file (too short). (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), items) ;
exit (1) ;
} ;
if (! long_file_ok && sfinfo.frames > 2 * items)
{ printf ("\n\nLine %d : Mono : Incorrect number of frames in file (too long). (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), items) ;
exit (1) ;
} ;
if (sfinfo.channels != 1)
{ printf ("\n\nLine %d : Mono : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
check_log_buffer_or_die (file, __LINE__) ;
test_read_float_or_die (file, 0, test, items, __LINE__) ;
for (k = 0 ; k < items ; k++)
if (FLOAT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d: Mono : Incorrect sample A (#%d : %g => %g).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to start of file. */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
test_read_float_or_die (file, 0, test, 4, __LINE__) ;
for (k = 0 ; k < 4 ; k++)
if (FLOAT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : %g => %g).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
if ((format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_16 ||
(format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_24)
{ sf_close (file) ;
unlink (filename) ;
printf ("no seek : ") ;
return ;
} ;
/* Seek to offset from start of file. */
test_seek_or_die (file, items + 10, SEEK_SET, items + 10, sfinfo.channels, __LINE__) ;
test_read_float_or_die (file, 0, test + 10, 4, __LINE__) ;
for (k = 10 ; k < 14 ; k++)
if (FLOAT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : %g => %g).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Seek to offset from current position. */
test_seek_or_die (file, 6, SEEK_CUR, items + 20, sfinfo.channels, __LINE__) ;
test_read_float_or_die (file, 0, test + 20, 4, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (FLOAT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : %g => %g).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Seek to offset from end of file. */
test_seek_or_die (file, -1 * (sfinfo.frames - 10), SEEK_END, 10, sfinfo.channels, __LINE__) ;
test_read_float_or_die (file, 0, test + 10, 4, __LINE__) ;
for (k = 10 ; k < 14 ; k++)
if (FLOAT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample D (#%d : %g => %g).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Check read past end of file followed by sf_seek (sndfile, 0, SEEK_CUR). */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
count = 0 ;
while (count < sfinfo.frames)
count += sf_read_float (file, test, 311) ;
/* Check that no error has occurred. */
if (sf_error (file))
{ printf ("\n\nLine %d : Mono : error where there shouldn't have been one.\n", __LINE__) ;
puts (sf_strerror (file)) ;
exit (1) ;
} ;
/* Check that we haven't read beyond EOF. */
if (count > sfinfo.frames)
{ printf ("\n\nLines %d : read past end of file (%ld should be %ld)\n", __LINE__, (long) count, (long) sfinfo.frames) ;
exit (1) ;
} ;
test_seek_or_die (file, 0, SEEK_CUR, sfinfo.frames, sfinfo.channels, __LINE__) ;
sf_close (file) ;
} /* mono_float_test */
static void
stereo_float_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
float *orig, *test ;
int k, items, frames ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 2 ;
sfinfo.format = format ;
gen_windowed_sine_double (orig_data.d, DATA_LENGTH, 1.0) ;
orig = orig_data.f ;
test = test_data.f ;
/* Make this a macro so gdb steps over it in one go. */
CONVERT_DATA (k, DATA_LENGTH, orig, orig_data.d) ;
items = DATA_LENGTH ;
frames = items / sfinfo.channels ;
file = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_set_string (file, SF_STR_ARTIST, "Your name here") ;
test_writef_float_or_die (file, 0, orig, frames, __LINE__) ;
sf_set_string (file, SF_STR_COPYRIGHT, "Copyright (c) 2003") ;
sf_close (file) ;
memset (test, 0, items * sizeof (float)) ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_RAW)
memset (&sfinfo, 0, sizeof (sfinfo)) ;
file = test_open_file_or_die (filename, SFM_READ, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Stereo : Returned format incorrect (0x%08X => 0x%08X).\n",
__LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < frames)
{ printf ("\n\nLine %d : Stereo : Incorrect number of frames in file (too short). (%ld should be %d)\n",
__LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
if (! long_file_ok && sfinfo.frames > frames)
{ printf ("\n\nLine %d : Stereo : Incorrect number of frames in file (too long). (%ld should be %d)\n",
__LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
if (sfinfo.channels != 2)
{ printf ("\n\nLine %d : Stereo : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
check_log_buffer_or_die (file, __LINE__) ;
test_readf_float_or_die (file, 0, test, frames, __LINE__) ;
for (k = 0 ; k < items ; k++)
if (FLOAT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : %g => %g).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to start of file. */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
test_readf_float_or_die (file, 0, test, 2, __LINE__) ;
for (k = 0 ; k < 4 ; k++)
if (FLOAT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : %g => %g).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from start of file. */
test_seek_or_die (file, 10, SEEK_SET, 10, sfinfo.channels, __LINE__) ;
/* Check for errors here. */
if (sf_error (file))
{ printf ("Line %d: Should NOT return an error.\n", __LINE__) ;
puts (sf_strerror (file)) ;
exit (1) ;
} ;
if (sf_read_float (file, test, 1) > 0)
{ printf ("Line %d: Should return 0.\n", __LINE__) ;
exit (1) ;
} ;
if (! sf_error (file))
{ printf ("Line %d: Should return an error.\n", __LINE__) ;
exit (1) ;
} ;
/*-----------------------*/
test_readf_float_or_die (file, 0, test + 10, 2, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (FLOAT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : %g => %g).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from current position. */
test_seek_or_die (file, 8, SEEK_CUR, 20, sfinfo.channels, __LINE__) ;
test_readf_float_or_die (file, 0, test + 20, 2, __LINE__) ;
for (k = 40 ; k < 44 ; k++)
if (FLOAT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : %g => %g).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from end of file. */
test_seek_or_die (file, -1 * (sfinfo.frames - 10), SEEK_END, 10, sfinfo.channels, __LINE__) ;
test_readf_float_or_die (file, 0, test + 20, 2, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (FLOAT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : %g => %g).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
sf_close (file) ;
} /* stereo_float_test */
static void
mono_rdwr_float_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
float *orig, *test ;
int k, pass ;
orig = orig_data.f ;
test = test_data.f ;
sfinfo.samplerate = SAMPLE_RATE ;
sfinfo.frames = DATA_LENGTH ;
sfinfo.channels = 1 ;
sfinfo.format = format ;
if ((format & SF_FORMAT_TYPEMASK) == SF_FORMAT_RAW
|| (format & SF_FORMAT_TYPEMASK) == SF_FORMAT_AU
|| (format & SF_FORMAT_TYPEMASK) == SF_FORMAT_SD2)
unlink (filename) ;
else
{ /* Create a short file. */
create_short_file (filename) ;
/* Opening a already existing short file (ie invalid header) RDWR is disallowed.
** If this returns a valif pointer sf_open() screwed up.
*/
if ((file = sf_open (filename, SFM_RDWR, &sfinfo)))
{ printf ("\n\nLine %d: sf_open should (SFM_RDWR) have failed but didn't.\n", __LINE__) ;
exit (1) ;
} ;
/* Truncate the file to zero bytes. */
if (truncate (filename, 0) < 0)
{ printf ("\n\nLine %d: truncate (%s) failed", __LINE__, filename) ;
perror (NULL) ;
exit (1) ;
} ;
} ;
/* Opening a zero length file RDWR is allowed, but the SF_INFO struct must contain
** all the usual data required when opening the file in WRITE mode.
*/
sfinfo.samplerate = SAMPLE_RATE ;
sfinfo.frames = DATA_LENGTH ;
sfinfo.channels = 1 ;
sfinfo.format = format ;
file = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
/* Do 3 writes followed by reads. After each, check the data and the current
** read and write offsets.
*/
for (pass = 1 ; pass <= 3 ; pass ++)
{ orig [20] = pass * 2 ;
/* Write some data. */
test_write_float_or_die (file, pass, orig, DATA_LENGTH, __LINE__) ;
test_read_write_position_or_die (file, __LINE__, pass, (pass - 1) * DATA_LENGTH, pass * DATA_LENGTH) ;
/* Read what we just wrote. */
test_read_float_or_die (file, 0, test, DATA_LENGTH, __LINE__) ;
/* Check the data. */
for (k = 0 ; k < DATA_LENGTH ; k++)
if (FLOAT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d (pass %d): Error at sample %d (%g => %g).\n", __LINE__, pass, k, orig [k], test [k]) ;
oct_save_float (orig, test, DATA_LENGTH) ;
exit (1) ;
} ;
test_read_write_position_or_die (file, __LINE__, pass, pass * DATA_LENGTH, pass * DATA_LENGTH) ;
} ; /* for (pass ...) */
sf_close (file) ;
/* Open the file again to check the data. */
file = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < 3 * DATA_LENGTH)
{ printf ("\n\nLine %d : Not enough frames in file. (%ld < %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), 3 * DATA_LENGTH ) ;
exit (1) ;
}
if (! long_file_ok && sfinfo.frames != 3 * DATA_LENGTH)
{ printf ("\n\nLine %d : Incorrect number of frames in file. (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), 3 * DATA_LENGTH ) ;
exit (1) ;
} ;
if (sfinfo.channels != 1)
{ printf ("\n\nLine %d : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
if (! long_file_ok)
test_read_write_position_or_die (file, __LINE__, 0, 0, 3 * DATA_LENGTH) ;
else
test_seek_or_die (file, 3 * DATA_LENGTH, SFM_WRITE | SEEK_SET, 3 * DATA_LENGTH, sfinfo.channels, __LINE__) ;
for (pass = 1 ; pass <= 3 ; pass ++)
{ orig [20] = pass * 2 ;
test_read_write_position_or_die (file, __LINE__, pass, (pass - 1) * DATA_LENGTH, 3 * DATA_LENGTH) ;
/* Read what we just wrote. */
test_read_float_or_die (file, pass, test, DATA_LENGTH, __LINE__) ;
/* Check the data. */
for (k = 0 ; k < DATA_LENGTH ; k++)
if (FLOAT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d (pass %d): Error at sample %d (%g => %g).\n", __LINE__, pass, k, orig [k], test [k]) ;
oct_save_float (orig, test, DATA_LENGTH) ;
exit (1) ;
} ;
} ; /* for (pass ...) */
sf_close (file) ;
} /* mono_rdwr_float_test */
static void
new_rdwr_float_test (const char *filename, int format, int allow_fd)
{ SNDFILE *wfile, *rwfile ;
SF_INFO sfinfo ;
float *orig, *test ;
int items, frames ;
orig = orig_data.f ;
test = test_data.f ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 2 ;
sfinfo.format = format ;
items = DATA_LENGTH ;
frames = items / sfinfo.channels ;
wfile = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_command (wfile, SFC_SET_UPDATE_HEADER_AUTO, NULL, SF_TRUE) ;
test_writef_float_or_die (wfile, 1, orig, frames, __LINE__) ;
sf_write_sync (wfile) ;
test_writef_float_or_die (wfile, 2, orig, frames, __LINE__) ;
sf_write_sync (wfile) ;
rwfile = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.frames != 2 * frames)
{ printf ("\n\nLine %d : incorrect number of frames in file (%ld shold be %d)\n\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
test_writef_float_or_die (wfile, 3, orig, frames, __LINE__) ;
test_readf_float_or_die (rwfile, 1, test, frames, __LINE__) ;
test_readf_float_or_die (rwfile, 2, test, frames, __LINE__) ;
sf_close (wfile) ;
sf_close (rwfile) ;
} /* new_rdwr_float_test */
/*======================================================================================
*/
static void mono_double_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void stereo_double_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void mono_rdwr_double_test (const char *filename, int format, int long_file_ok, int allow_fd) ;
static void new_rdwr_double_test (const char *filename, int format, int allow_fd) ;
static void
pcm_test_double (const char *filename, int format, int long_file_ok)
{ SF_INFO sfinfo ;
double *orig, *test ;
int k, items, allow_fd ;
/* Sd2 files cannot be opened from an existing file descriptor. */
allow_fd = ((format & SF_FORMAT_TYPEMASK) == SF_FORMAT_SD2) ? SF_FALSE : SF_TRUE ;
print_test_name ("pcm_test_double", filename) ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 1 ;
sfinfo.format = format ;
gen_windowed_sine_double (orig_data.d, DATA_LENGTH, 1.0) ;
orig = orig_data.d ;
test = test_data.d ;
/* Make this a macro so gdb steps over it in one go. */
CONVERT_DATA (k, DATA_LENGTH, orig, orig_data.d) ;
items = DATA_LENGTH ;
/* Some test broken out here. */
mono_double_test (filename, format, long_file_ok, allow_fd) ;
/* Sub format DWVW does not allow seeking. */
if ((format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_16 ||
(format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_24)
{ unlink (filename) ;
printf ("no seek : ok\n") ;
return ;
} ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_FLAC)
mono_rdwr_double_test (filename, format, long_file_ok, allow_fd) ;
/* If the format doesn't support stereo we're done. */
sfinfo.channels = 2 ;
if (sf_format_check (&sfinfo) == 0)
{ unlink (filename) ;
puts ("no stereo : ok") ;
return ;
} ;
stereo_double_test (filename, format, long_file_ok, allow_fd) ;
/* New read/write test. Not sure if this is needed yet. */
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_PAF &&
(format & SF_FORMAT_TYPEMASK) != SF_FORMAT_VOC &&
(format & SF_FORMAT_TYPEMASK) != SF_FORMAT_FLAC)
new_rdwr_double_test (filename, format, allow_fd) ;
delete_file (format, filename) ;
puts ("ok") ;
return ;
} /* pcm_test_double */
static void
mono_double_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
double *orig, *test ;
sf_count_t count ;
int k, items ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 1 ;
sfinfo.format = format ;
orig = orig_data.d ;
test = test_data.d ;
items = DATA_LENGTH ;
file = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_set_string (file, SF_STR_ARTIST, "Your name here") ;
test_write_double_or_die (file, 0, orig, items, __LINE__) ;
sf_write_sync (file) ;
test_write_double_or_die (file, 0, orig, items, __LINE__) ;
sf_write_sync (file) ;
/* Add non-audio data after the audio. */
sf_set_string (file, SF_STR_COPYRIGHT, "Copyright (c) 2003") ;
sf_close (file) ;
memset (test, 0, items * sizeof (double)) ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_RAW)
memset (&sfinfo, 0, sizeof (sfinfo)) ;
file = test_open_file_or_die (filename, SFM_READ, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Mono : Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < 2 * items)
{ printf ("\n\nLine %d : Mono : Incorrect number of frames in file (too short). (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), items) ;
exit (1) ;
} ;
if (! long_file_ok && sfinfo.frames > 2 * items)
{ printf ("\n\nLine %d : Mono : Incorrect number of frames in file (too long). (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), items) ;
exit (1) ;
} ;
if (sfinfo.channels != 1)
{ printf ("\n\nLine %d : Mono : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
check_log_buffer_or_die (file, __LINE__) ;
test_read_double_or_die (file, 0, test, items, __LINE__) ;
for (k = 0 ; k < items ; k++)
if (FLOAT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d: Mono : Incorrect sample A (#%d : %g => %g).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to start of file. */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
test_read_double_or_die (file, 0, test, 4, __LINE__) ;
for (k = 0 ; k < 4 ; k++)
if (FLOAT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : %g => %g).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
if ((format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_16 ||
(format & SF_FORMAT_SUBMASK) == SF_FORMAT_DWVW_24)
{ sf_close (file) ;
unlink (filename) ;
printf ("no seek : ") ;
return ;
} ;
/* Seek to offset from start of file. */
test_seek_or_die (file, items + 10, SEEK_SET, items + 10, sfinfo.channels, __LINE__) ;
test_read_double_or_die (file, 0, test + 10, 4, __LINE__) ;
for (k = 10 ; k < 14 ; k++)
if (FLOAT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : %g => %g).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Seek to offset from current position. */
test_seek_or_die (file, 6, SEEK_CUR, items + 20, sfinfo.channels, __LINE__) ;
test_read_double_or_die (file, 0, test + 20, 4, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (FLOAT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample A (#%d : %g => %g).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Seek to offset from end of file. */
test_seek_or_die (file, -1 * (sfinfo.frames - 10), SEEK_END, 10, sfinfo.channels, __LINE__) ;
test_read_double_or_die (file, 0, test + 10, 4, __LINE__) ;
for (k = 10 ; k < 14 ; k++)
if (FLOAT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d : Mono : Incorrect sample D (#%d : %g => %g).\n", __LINE__, k, test [k], orig [k]) ;
exit (1) ;
} ;
/* Check read past end of file followed by sf_seek (sndfile, 0, SEEK_CUR). */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
count = 0 ;
while (count < sfinfo.frames)
count += sf_read_double (file, test, 311) ;
/* Check that no error has occurred. */
if (sf_error (file))
{ printf ("\n\nLine %d : Mono : error where there shouldn't have been one.\n", __LINE__) ;
puts (sf_strerror (file)) ;
exit (1) ;
} ;
/* Check that we haven't read beyond EOF. */
if (count > sfinfo.frames)
{ printf ("\n\nLines %d : read past end of file (%ld should be %ld)\n", __LINE__, (long) count, (long) sfinfo.frames) ;
exit (1) ;
} ;
test_seek_or_die (file, 0, SEEK_CUR, sfinfo.frames, sfinfo.channels, __LINE__) ;
sf_close (file) ;
} /* mono_double_test */
static void
stereo_double_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
double *orig, *test ;
int k, items, frames ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 2 ;
sfinfo.format = format ;
gen_windowed_sine_double (orig_data.d, DATA_LENGTH, 1.0) ;
orig = orig_data.d ;
test = test_data.d ;
/* Make this a macro so gdb steps over it in one go. */
CONVERT_DATA (k, DATA_LENGTH, orig, orig_data.d) ;
items = DATA_LENGTH ;
frames = items / sfinfo.channels ;
file = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_set_string (file, SF_STR_ARTIST, "Your name here") ;
test_writef_double_or_die (file, 0, orig, frames, __LINE__) ;
sf_set_string (file, SF_STR_COPYRIGHT, "Copyright (c) 2003") ;
sf_close (file) ;
memset (test, 0, items * sizeof (double)) ;
if ((format & SF_FORMAT_TYPEMASK) != SF_FORMAT_RAW)
memset (&sfinfo, 0, sizeof (sfinfo)) ;
file = test_open_file_or_die (filename, SFM_READ, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Stereo : Returned format incorrect (0x%08X => 0x%08X).\n",
__LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < frames)
{ printf ("\n\nLine %d : Stereo : Incorrect number of frames in file (too short). (%ld should be %d)\n",
__LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
if (! long_file_ok && sfinfo.frames > frames)
{ printf ("\n\nLine %d : Stereo : Incorrect number of frames in file (too long). (%ld should be %d)\n",
__LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
if (sfinfo.channels != 2)
{ printf ("\n\nLine %d : Stereo : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
check_log_buffer_or_die (file, __LINE__) ;
test_readf_double_or_die (file, 0, test, frames, __LINE__) ;
for (k = 0 ; k < items ; k++)
if (FLOAT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : %g => %g).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to start of file. */
test_seek_or_die (file, 0, SEEK_SET, 0, sfinfo.channels, __LINE__) ;
test_readf_double_or_die (file, 0, test, 2, __LINE__) ;
for (k = 0 ; k < 4 ; k++)
if (FLOAT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : %g => %g).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from start of file. */
test_seek_or_die (file, 10, SEEK_SET, 10, sfinfo.channels, __LINE__) ;
/* Check for errors here. */
if (sf_error (file))
{ printf ("Line %d: Should NOT return an error.\n", __LINE__) ;
puts (sf_strerror (file)) ;
exit (1) ;
} ;
if (sf_read_double (file, test, 1) > 0)
{ printf ("Line %d: Should return 0.\n", __LINE__) ;
exit (1) ;
} ;
if (! sf_error (file))
{ printf ("Line %d: Should return an error.\n", __LINE__) ;
exit (1) ;
} ;
/*-----------------------*/
test_readf_double_or_die (file, 0, test + 10, 2, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (FLOAT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : %g => %g).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from current position. */
test_seek_or_die (file, 8, SEEK_CUR, 20, sfinfo.channels, __LINE__) ;
test_readf_double_or_die (file, 0, test + 20, 2, __LINE__) ;
for (k = 40 ; k < 44 ; k++)
if (FLOAT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : %g => %g).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
/* Seek to offset from end of file. */
test_seek_or_die (file, -1 * (sfinfo.frames - 10), SEEK_END, 10, sfinfo.channels, __LINE__) ;
test_readf_double_or_die (file, 0, test + 20, 2, __LINE__) ;
for (k = 20 ; k < 24 ; k++)
if (FLOAT_ERROR (test [k], orig [k]))
{ printf ("\n\nLine %d : Stereo : Incorrect sample (#%d : %g => %g).\n", __LINE__, k, orig [k], test [k]) ;
exit (1) ;
} ;
sf_close (file) ;
} /* stereo_double_test */
static void
mono_rdwr_double_test (const char *filename, int format, int long_file_ok, int allow_fd)
{ SNDFILE *file ;
SF_INFO sfinfo ;
double *orig, *test ;
int k, pass ;
orig = orig_data.d ;
test = test_data.d ;
sfinfo.samplerate = SAMPLE_RATE ;
sfinfo.frames = DATA_LENGTH ;
sfinfo.channels = 1 ;
sfinfo.format = format ;
if ((format & SF_FORMAT_TYPEMASK) == SF_FORMAT_RAW
|| (format & SF_FORMAT_TYPEMASK) == SF_FORMAT_AU
|| (format & SF_FORMAT_TYPEMASK) == SF_FORMAT_SD2)
unlink (filename) ;
else
{ /* Create a short file. */
create_short_file (filename) ;
/* Opening a already existing short file (ie invalid header) RDWR is disallowed.
** If this returns a valif pointer sf_open() screwed up.
*/
if ((file = sf_open (filename, SFM_RDWR, &sfinfo)))
{ printf ("\n\nLine %d: sf_open should (SFM_RDWR) have failed but didn't.\n", __LINE__) ;
exit (1) ;
} ;
/* Truncate the file to zero bytes. */
if (truncate (filename, 0) < 0)
{ printf ("\n\nLine %d: truncate (%s) failed", __LINE__, filename) ;
perror (NULL) ;
exit (1) ;
} ;
} ;
/* Opening a zero length file RDWR is allowed, but the SF_INFO struct must contain
** all the usual data required when opening the file in WRITE mode.
*/
sfinfo.samplerate = SAMPLE_RATE ;
sfinfo.frames = DATA_LENGTH ;
sfinfo.channels = 1 ;
sfinfo.format = format ;
file = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
/* Do 3 writes followed by reads. After each, check the data and the current
** read and write offsets.
*/
for (pass = 1 ; pass <= 3 ; pass ++)
{ orig [20] = pass * 2 ;
/* Write some data. */
test_write_double_or_die (file, pass, orig, DATA_LENGTH, __LINE__) ;
test_read_write_position_or_die (file, __LINE__, pass, (pass - 1) * DATA_LENGTH, pass * DATA_LENGTH) ;
/* Read what we just wrote. */
test_read_double_or_die (file, 0, test, DATA_LENGTH, __LINE__) ;
/* Check the data. */
for (k = 0 ; k < DATA_LENGTH ; k++)
if (FLOAT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d (pass %d): Error at sample %d (%g => %g).\n", __LINE__, pass, k, orig [k], test [k]) ;
oct_save_double (orig, test, DATA_LENGTH) ;
exit (1) ;
} ;
test_read_write_position_or_die (file, __LINE__, pass, pass * DATA_LENGTH, pass * DATA_LENGTH) ;
} ; /* for (pass ...) */
sf_close (file) ;
/* Open the file again to check the data. */
file = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.format != format)
{ printf ("\n\nLine %d : Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, format, sfinfo.format) ;
exit (1) ;
} ;
if (sfinfo.frames < 3 * DATA_LENGTH)
{ printf ("\n\nLine %d : Not enough frames in file. (%ld < %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), 3 * DATA_LENGTH ) ;
exit (1) ;
}
if (! long_file_ok && sfinfo.frames != 3 * DATA_LENGTH)
{ printf ("\n\nLine %d : Incorrect number of frames in file. (%ld should be %d)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), 3 * DATA_LENGTH ) ;
exit (1) ;
} ;
if (sfinfo.channels != 1)
{ printf ("\n\nLine %d : Incorrect number of channels in file.\n", __LINE__) ;
exit (1) ;
} ;
if (! long_file_ok)
test_read_write_position_or_die (file, __LINE__, 0, 0, 3 * DATA_LENGTH) ;
else
test_seek_or_die (file, 3 * DATA_LENGTH, SFM_WRITE | SEEK_SET, 3 * DATA_LENGTH, sfinfo.channels, __LINE__) ;
for (pass = 1 ; pass <= 3 ; pass ++)
{ orig [20] = pass * 2 ;
test_read_write_position_or_die (file, __LINE__, pass, (pass - 1) * DATA_LENGTH, 3 * DATA_LENGTH) ;
/* Read what we just wrote. */
test_read_double_or_die (file, pass, test, DATA_LENGTH, __LINE__) ;
/* Check the data. */
for (k = 0 ; k < DATA_LENGTH ; k++)
if (FLOAT_ERROR (orig [k], test [k]))
{ printf ("\n\nLine %d (pass %d): Error at sample %d (%g => %g).\n", __LINE__, pass, k, orig [k], test [k]) ;
oct_save_double (orig, test, DATA_LENGTH) ;
exit (1) ;
} ;
} ; /* for (pass ...) */
sf_close (file) ;
} /* mono_rdwr_double_test */
static void
new_rdwr_double_test (const char *filename, int format, int allow_fd)
{ SNDFILE *wfile, *rwfile ;
SF_INFO sfinfo ;
double *orig, *test ;
int items, frames ;
orig = orig_data.d ;
test = test_data.d ;
sfinfo.samplerate = 44100 ;
sfinfo.frames = SILLY_WRITE_COUNT ; /* Wrong length. Library should correct this on sf_close. */
sfinfo.channels = 2 ;
sfinfo.format = format ;
items = DATA_LENGTH ;
frames = items / sfinfo.channels ;
wfile = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, allow_fd, __LINE__) ;
sf_command (wfile, SFC_SET_UPDATE_HEADER_AUTO, NULL, SF_TRUE) ;
test_writef_double_or_die (wfile, 1, orig, frames, __LINE__) ;
sf_write_sync (wfile) ;
test_writef_double_or_die (wfile, 2, orig, frames, __LINE__) ;
sf_write_sync (wfile) ;
rwfile = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, allow_fd, __LINE__) ;
if (sfinfo.frames != 2 * frames)
{ printf ("\n\nLine %d : incorrect number of frames in file (%ld shold be %d)\n\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), frames) ;
exit (1) ;
} ;
test_writef_double_or_die (wfile, 3, orig, frames, __LINE__) ;
test_readf_double_or_die (rwfile, 1, test, frames, __LINE__) ;
test_readf_double_or_die (rwfile, 2, test, frames, __LINE__) ;
sf_close (wfile) ;
sf_close (rwfile) ;
} /* new_rdwr_double_test */
/*----------------------------------------------------------------------------------------
*/
static void
empty_file_test (const char *filename, int format)
{ SNDFILE *file ;
SF_INFO info ;
int allow_fd ;
/* Sd2 files cannot be opened from an existing file descriptor. */
allow_fd = ((format & SF_FORMAT_TYPEMASK) == SF_FORMAT_SD2) ? SF_FALSE : SF_TRUE ;
print_test_name ("empty_file_test", filename) ;
unlink (filename) ;
info.samplerate = 48000 ;
info.channels = 2 ;
info.format = format ;
if (sf_format_check (&info) == SF_FALSE)
{ info.channels = 1 ;
if (sf_format_check (&info) == SF_FALSE)
{ puts ("invalid file format") ;
return ;
} ;
} ;
/* Create an empty file. */
file = test_open_file_or_die (filename, SFM_WRITE, &info, allow_fd, __LINE__) ;
sf_close (file) ;
/* Open for read and check the length. */
file = test_open_file_or_die (filename, SFM_READ, &info, allow_fd, __LINE__) ;
if (SF_COUNT_TO_LONG (info.frames) != 0)
{ printf ("\n\nError : frame count (%ld) should be zero.\n", SF_COUNT_TO_LONG (info.frames)) ;
exit (1) ;
} ;
sf_close (file) ;
/* Open for read/write and check the length. */
file = test_open_file_or_die (filename, SFM_RDWR, &info, allow_fd, __LINE__) ;
if (SF_COUNT_TO_LONG (info.frames) != 0)
{ printf ("\n\nError : frame count (%ld) should be zero.\n", SF_COUNT_TO_LONG (info.frames)) ;
exit (1) ;
} ;
sf_close (file) ;
/* Open for read and check the length. */
file = test_open_file_or_die (filename, SFM_READ, &info, allow_fd, __LINE__) ;
if (SF_COUNT_TO_LONG (info.frames) != 0)
{ printf ("\n\nError : frame count (%ld) should be zero.\n", SF_COUNT_TO_LONG (info.frames)) ;
exit (1) ;
} ;
sf_close (file) ;
check_open_file_count_or_die (__LINE__) ;
unlink (filename) ;
puts ("ok") ;
return ;
} /* empty_file_test */
/*----------------------------------------------------------------------------------------
*/
static void
create_short_file (const char *filename)
{ FILE *file ;
if (! (file = fopen (filename, "w")))
{ printf ("create_short_file : fopen (%s, \"w\") failed.", filename) ;
fflush (stdout) ;
perror (NULL) ;
exit (1) ;
} ;
fprintf (file, "This is the file data.\n") ;
fclose (file) ;
} /* create_short_file */
#if (defined (WIN32) || defined (__WIN32))
/* Win32 does not have truncate (nor does it have the POSIX function ftruncate).
** Hack somethng up here to over come this. This function can only truncate to a
** length of zero.
*/
static int
truncate (const char *filename, int ignored)
{ int fd ;
ignored = 0 ;
if ((fd = open (filename, O_RDWR | O_TRUNC | O_BINARY)) < 0)
return 0 ;
close (fd) ;
return 0 ;
} /* truncate */
#endif
| ipwndev/DSLinux-Mirror | lib/libsndfile/src/tests/write_read_test.c | C | gpl-2.0 | 120,552 |
/*
*
* BlueZ - Bluetooth protocol stack for Linux
*
* Copyright (C) 2004-2010 Marcel Holtmann <marcel@holtmann.org>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/bnep.h>
#include <bluetooth/sdp.h>
#include <bluetooth/sdp_lib.h>
#include <netinet/in.h>
#include <glib.h>
#include <gdbus/gdbus.h>
#include <btio/btio.h>
#include "lib/uuid.h"
#include "../src/dbus-common.h"
#include "../src/adapter.h"
#include "log.h"
#include "error.h"
#include "sdpd.h"
#include "bnep.h"
#include "server.h"
#define NETWORK_SERVER_INTERFACE "org.bluez.NetworkServer1"
#define SETUP_TIMEOUT 1
/* Pending Authorization */
struct network_session {
bdaddr_t dst; /* Remote Bluetooth Address */
char dev[16]; /* Interface name */
GIOChannel *io; /* Pending connect channel */
guint watch; /* BNEP socket watch */
};
struct network_adapter {
struct btd_adapter *adapter; /* Adapter pointer */
GIOChannel *io; /* Bnep socket */
struct network_session *setup; /* Setup in progress */
GSList *servers; /* Server register to adapter */
};
/* Main server structure */
struct network_server {
bdaddr_t src; /* Bluetooth Local Address */
char *name; /* Server service name */
char *bridge; /* Bridge name */
uint32_t record_id; /* Service record id */
uint16_t id; /* Service class identifier */
GSList *sessions; /* Active connections */
struct network_adapter *na; /* Adapter reference */
guint watch_id; /* Client service watch */
};
static GSList *adapters = NULL;
static gboolean security = TRUE;
static struct network_adapter *find_adapter(GSList *list,
struct btd_adapter *adapter)
{
for (; list; list = list->next) {
struct network_adapter *na = list->data;
if (na->adapter == adapter)
return na;
}
return NULL;
}
static struct network_server *find_server(GSList *list, uint16_t id)
{
for (; list; list = list->next) {
struct network_server *ns = list->data;
if (ns->id == id)
return ns;
}
return NULL;
}
static struct network_server *find_server_by_uuid(GSList *list,
const char *uuid)
{
for (; list; list = list->next) {
struct network_server *ns = list->data;
if (strcasecmp(uuid, bnep_uuid(ns->id)) == 0)
return ns;
if (strcasecmp(uuid, bnep_name(ns->id)) == 0)
return ns;
}
return NULL;
}
static sdp_record_t *server_record_new(const char *name, uint16_t id)
{
sdp_list_t *svclass, *pfseq, *apseq, *root, *aproto;
uuid_t root_uuid, pan, l2cap, bnep;
sdp_profile_desc_t profile[1];
sdp_list_t *proto[2];
sdp_data_t *v, *p;
uint16_t psm = BNEP_PSM, version = 0x0100;
uint16_t security_desc = (security ? 0x0001 : 0x0000);
uint16_t net_access_type = 0xfffe;
uint32_t max_net_access_rate = 0;
const char *desc = "Network service";
sdp_record_t *record;
record = sdp_record_alloc();
if (!record)
return NULL;
record->attrlist = NULL;
record->pattern = NULL;
switch (id) {
case BNEP_SVC_NAP:
sdp_uuid16_create(&pan, NAP_SVCLASS_ID);
svclass = sdp_list_append(NULL, &pan);
sdp_set_service_classes(record, svclass);
sdp_uuid16_create(&profile[0].uuid, NAP_PROFILE_ID);
profile[0].version = 0x0100;
pfseq = sdp_list_append(NULL, &profile[0]);
sdp_set_profile_descs(record, pfseq);
sdp_set_info_attr(record, name, NULL, desc);
sdp_attr_add_new(record, SDP_ATTR_NET_ACCESS_TYPE,
SDP_UINT16, &net_access_type);
sdp_attr_add_new(record, SDP_ATTR_MAX_NET_ACCESSRATE,
SDP_UINT32, &max_net_access_rate);
break;
case BNEP_SVC_GN:
sdp_uuid16_create(&pan, GN_SVCLASS_ID);
svclass = sdp_list_append(NULL, &pan);
sdp_set_service_classes(record, svclass);
sdp_uuid16_create(&profile[0].uuid, GN_PROFILE_ID);
profile[0].version = 0x0100;
pfseq = sdp_list_append(NULL, &profile[0]);
sdp_set_profile_descs(record, pfseq);
sdp_set_info_attr(record, name, NULL, desc);
break;
case BNEP_SVC_PANU:
sdp_uuid16_create(&pan, PANU_SVCLASS_ID);
svclass = sdp_list_append(NULL, &pan);
sdp_set_service_classes(record, svclass);
sdp_uuid16_create(&profile[0].uuid, PANU_PROFILE_ID);
profile[0].version = 0x0100;
pfseq = sdp_list_append(NULL, &profile[0]);
sdp_set_profile_descs(record, pfseq);
sdp_set_info_attr(record, name, NULL, desc);
break;
default:
sdp_record_free(record);
return NULL;
}
sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
root = sdp_list_append(NULL, &root_uuid);
sdp_set_browse_groups(record, root);
sdp_uuid16_create(&l2cap, L2CAP_UUID);
proto[0] = sdp_list_append(NULL, &l2cap);
p = sdp_data_alloc(SDP_UINT16, &psm);
proto[0] = sdp_list_append(proto[0], p);
apseq = sdp_list_append(NULL, proto[0]);
sdp_uuid16_create(&bnep, BNEP_UUID);
proto[1] = sdp_list_append(NULL, &bnep);
v = sdp_data_alloc(SDP_UINT16, &version);
proto[1] = sdp_list_append(proto[1], v);
/* Supported protocols */
{
uint16_t ptype[] = {
0x0800, /* IPv4 */
0x0806, /* ARP */
};
sdp_data_t *head, *pseq;
int p;
for (p = 0, head = NULL; p < 2; p++) {
sdp_data_t *data = sdp_data_alloc(SDP_UINT16, &ptype[p]);
if (head)
sdp_seq_append(head, data);
else
head = data;
}
pseq = sdp_data_alloc(SDP_SEQ16, head);
proto[1] = sdp_list_append(proto[1], pseq);
}
apseq = sdp_list_append(apseq, proto[1]);
aproto = sdp_list_append(NULL, apseq);
sdp_set_access_protos(record, aproto);
sdp_add_lang_attr(record);
sdp_attr_add_new(record, SDP_ATTR_SECURITY_DESC,
SDP_UINT16, &security_desc);
sdp_data_free(p);
sdp_data_free(v);
sdp_list_free(apseq, NULL);
sdp_list_free(root, NULL);
sdp_list_free(aproto, NULL);
sdp_list_free(proto[0], NULL);
sdp_list_free(proto[1], NULL);
sdp_list_free(svclass, NULL);
sdp_list_free(pfseq, NULL);
return record;
}
static void session_free(void *data)
{
struct network_session *session = data;
if (session->watch)
g_source_remove(session->watch);
if (session->io)
g_io_channel_unref(session->io);
g_free(session);
}
static void setup_destroy(void *user_data)
{
struct network_adapter *na = user_data;
struct network_session *setup = na->setup;
if (!setup)
return;
na->setup = NULL;
session_free(setup);
}
static gboolean bnep_setup(GIOChannel *chan,
GIOCondition cond, gpointer user_data)
{
struct network_adapter *na = user_data;
struct network_server *ns;
uint8_t packet[BNEP_MTU];
struct bnep_setup_conn_req *req = (void *) packet;
uint16_t src_role, dst_role, rsp = BNEP_CONN_NOT_ALLOWED;
int n, sk;
if (cond & G_IO_NVAL)
return FALSE;
if (cond & (G_IO_ERR | G_IO_HUP)) {
error("Hangup or error on BNEP socket");
return FALSE;
}
sk = g_io_channel_unix_get_fd(chan);
/* Reading BNEP_SETUP_CONNECTION_REQUEST_MSG */
n = read(sk, packet, sizeof(packet));
if (n < 0) {
error("read(): %s(%d)", strerror(errno), errno);
return FALSE;
}
/* Highest known Control command ID
* is BNEP_FILTER_MULT_ADDR_RSP = 0x06 */
if (req->type == BNEP_CONTROL &&
req->ctrl > BNEP_FILTER_MULT_ADDR_RSP) {
uint8_t pkt[3];
pkt[0] = BNEP_CONTROL;
pkt[1] = BNEP_CMD_NOT_UNDERSTOOD;
pkt[2] = req->ctrl;
send(sk, pkt, sizeof(pkt), 0);
return FALSE;
}
if (req->type != BNEP_CONTROL || req->ctrl != BNEP_SETUP_CONN_REQ)
return FALSE;
rsp = bnep_setup_decode(req, &dst_role, &src_role);
if (rsp)
goto reply;
rsp = bnep_setup_chk(dst_role, src_role);
if (rsp)
goto reply;
rsp = BNEP_CONN_NOT_ALLOWED;
ns = find_server(na->servers, dst_role);
if (!ns) {
error("Server unavailable: (0x%x)", dst_role);
goto reply;
}
if (!ns->record_id) {
error("Service record not available");
goto reply;
}
if (!ns->bridge) {
error("Bridge interface not configured");
goto reply;
}
if (bnep_server_add(sk, dst_role, ns->bridge, na->setup->dev,
&na->setup->dst) < 0)
goto reply;
na->setup = NULL;
rsp = BNEP_SUCCESS;
reply:
bnep_send_ctrl_rsp(sk, BNEP_CONTROL, BNEP_SETUP_CONN_RSP, rsp);
return FALSE;
}
static void connect_event(GIOChannel *chan, GError *err, gpointer user_data)
{
struct network_adapter *na = user_data;
if (err) {
error("%s", err->message);
setup_destroy(na);
return;
}
g_io_channel_set_close_on_unref(chan, TRUE);
na->setup->watch = g_io_add_watch_full(chan, G_PRIORITY_DEFAULT,
G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
bnep_setup, na, setup_destroy);
}
static void auth_cb(DBusError *derr, void *user_data)
{
struct network_adapter *na = user_data;
GError *err = NULL;
if (derr) {
error("Access denied: %s", derr->message);
goto reject;
}
if (!bt_io_accept(na->setup->io, connect_event, na, NULL,
&err)) {
error("bt_io_accept: %s", err->message);
g_error_free(err);
goto reject;
}
return;
reject:
g_io_channel_shutdown(na->setup->io, TRUE, NULL);
setup_destroy(na);
}
static void confirm_event(GIOChannel *chan, gpointer user_data)
{
struct network_adapter *na = user_data;
struct network_server *ns;
bdaddr_t src, dst;
char address[18];
GError *err = NULL;
guint ret;
bt_io_get(chan, &err,
BT_IO_OPT_SOURCE_BDADDR, &src,
BT_IO_OPT_DEST_BDADDR, &dst,
BT_IO_OPT_DEST, address,
BT_IO_OPT_INVALID);
if (err) {
error("%s", err->message);
g_error_free(err);
goto drop;
}
DBG("BNEP: incoming connect from %s", address);
if (na->setup) {
error("Refusing connect from %s: setup in progress", address);
goto drop;
}
ns = find_server(na->servers, BNEP_SVC_NAP);
if (!ns)
goto drop;
if (!ns->record_id)
goto drop;
if (!ns->bridge)
goto drop;
na->setup = g_new0(struct network_session, 1);
bacpy(&na->setup->dst, &dst);
na->setup->io = g_io_channel_ref(chan);
ret = btd_request_authorization(&src, &dst, BNEP_SVC_UUID,
auth_cb, na);
if (ret == 0) {
error("Refusing connect from %s", address);
setup_destroy(na);
goto drop;
}
return;
drop:
g_io_channel_shutdown(chan, TRUE, NULL);
}
int server_init(gboolean secure)
{
security = secure;
return 0;
}
static uint32_t register_server_record(struct network_server *ns)
{
sdp_record_t *record;
record = server_record_new(ns->name, ns->id);
if (!record) {
error("Unable to allocate new service record");
return 0;
}
if (adapter_service_add(ns->na->adapter, record) < 0) {
error("Failed to register service record");
sdp_record_free(record);
return 0;
}
DBG("got record id 0x%x", record->handle);
return record->handle;
}
static void server_remove_sessions(struct network_server *ns)
{
GSList *list;
for (list = ns->sessions; list; list = list->next) {
struct network_session *session = list->data;
if (*session->dev == '\0')
continue;
bnep_server_delete(ns->bridge, session->dev, &session->dst);
}
g_slist_free_full(ns->sessions, session_free);
ns->sessions = NULL;
}
static void server_disconnect(DBusConnection *conn, void *user_data)
{
struct network_server *ns = user_data;
server_remove_sessions(ns);
ns->watch_id = 0;
if (ns->record_id) {
adapter_service_remove(ns->na->adapter, ns->record_id);
ns->record_id = 0;
}
g_free(ns->bridge);
ns->bridge = NULL;
}
static DBusMessage *register_server(DBusConnection *conn,
DBusMessage *msg, void *data)
{
struct network_adapter *na = data;
struct network_server *ns;
DBusMessage *reply;
const char *uuid, *bridge;
if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &uuid,
DBUS_TYPE_STRING, &bridge, DBUS_TYPE_INVALID))
return btd_error_invalid_args(msg);
ns = find_server_by_uuid(na->servers, uuid);
if (ns == NULL)
return btd_error_failed(msg, "Invalid UUID");
if (ns->record_id)
return btd_error_already_exists(msg);
reply = dbus_message_new_method_return(msg);
if (!reply)
return NULL;
ns->record_id = register_server_record(ns);
if (!ns->record_id)
return btd_error_failed(msg, "SDP record registration failed");
g_free(ns->bridge);
ns->bridge = g_strdup(bridge);
ns->watch_id = g_dbus_add_disconnect_watch(conn,
dbus_message_get_sender(msg),
server_disconnect, ns, NULL);
return reply;
}
static DBusMessage *unregister_server(DBusConnection *conn,
DBusMessage *msg, void *data)
{
struct network_adapter *na = data;
struct network_server *ns;
DBusMessage *reply;
const char *uuid;
if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &uuid,
DBUS_TYPE_INVALID))
return btd_error_invalid_args(msg);
ns = find_server_by_uuid(na->servers, uuid);
if (!ns)
return btd_error_failed(msg, "Invalid UUID");
reply = dbus_message_new_method_return(msg);
if (!reply)
return NULL;
g_dbus_remove_watch(conn, ns->watch_id);
server_disconnect(conn, ns);
return reply;
}
static void adapter_free(struct network_adapter *na)
{
if (na->io != NULL) {
g_io_channel_shutdown(na->io, TRUE, NULL);
g_io_channel_unref(na->io);
}
setup_destroy(na);
btd_adapter_unref(na->adapter);
g_free(na);
}
static void server_free(void *data)
{
struct network_server *ns = data;
if (!ns)
return;
server_remove_sessions(ns);
if (ns->record_id)
adapter_service_remove(ns->na->adapter, ns->record_id);
g_dbus_remove_watch(btd_get_dbus_connection(), ns->watch_id);
g_free(ns->name);
g_free(ns->bridge);
g_free(ns);
}
static void path_unregister(void *data)
{
struct network_adapter *na = data;
DBG("Unregistered interface %s on path %s",
NETWORK_SERVER_INTERFACE, adapter_get_path(na->adapter));
g_slist_free_full(na->servers, server_free);
adapters = g_slist_remove(adapters, na);
adapter_free(na);
}
static const GDBusMethodTable server_methods[] = {
{ GDBUS_METHOD("Register",
GDBUS_ARGS({ "uuid", "s" }, { "bridge", "s" }), NULL,
register_server) },
{ GDBUS_METHOD("Unregister",
GDBUS_ARGS({ "uuid", "s" }), NULL,
unregister_server) },
{ }
};
static struct network_adapter *create_adapter(struct btd_adapter *adapter)
{
struct network_adapter *na;
GError *err = NULL;
na = g_new0(struct network_adapter, 1);
na->adapter = btd_adapter_ref(adapter);
na->io = bt_io_listen(NULL, confirm_event, na,
NULL, &err,
BT_IO_OPT_SOURCE_BDADDR,
btd_adapter_get_address(adapter),
BT_IO_OPT_PSM, BNEP_PSM,
BT_IO_OPT_OMTU, BNEP_MTU,
BT_IO_OPT_IMTU, BNEP_MTU,
BT_IO_OPT_SEC_LEVEL,
security ? BT_IO_SEC_MEDIUM : BT_IO_SEC_LOW,
BT_IO_OPT_INVALID);
if (!na->io) {
error("%s", err->message);
g_error_free(err);
adapter_free(na);
return NULL;
}
return na;
}
int server_register(struct btd_adapter *adapter, uint16_t id)
{
struct network_adapter *na;
struct network_server *ns;
const char *path;
na = find_adapter(adapters, adapter);
if (!na) {
na = create_adapter(adapter);
if (!na)
return -EINVAL;
adapters = g_slist_append(adapters, na);
}
ns = find_server(na->servers, id);
if (ns)
return 0;
ns = g_new0(struct network_server, 1);
ns->name = g_strdup("Network service");
path = adapter_get_path(adapter);
if (g_slist_length(na->servers) > 0)
goto done;
if (!g_dbus_register_interface(btd_get_dbus_connection(),
path, NETWORK_SERVER_INTERFACE,
server_methods, NULL, NULL,
na, path_unregister)) {
error("D-Bus failed to register %s interface",
NETWORK_SERVER_INTERFACE);
server_free(ns);
return -1;
}
DBG("Registered interface %s on path %s", NETWORK_SERVER_INTERFACE,
path);
done:
bacpy(&ns->src, btd_adapter_get_address(adapter));
ns->id = id;
ns->na = na;
ns->record_id = 0;
na->servers = g_slist_append(na->servers, ns);
return 0;
}
int server_unregister(struct btd_adapter *adapter, uint16_t id)
{
struct network_adapter *na;
struct network_server *ns;
na = find_adapter(adapters, adapter);
if (!na)
return -EINVAL;
ns = find_server(na->servers, id);
if (!ns)
return -EINVAL;
na->servers = g_slist_remove(na->servers, ns);
server_free(ns);
if (g_slist_length(na->servers) > 0)
return 0;
g_dbus_unregister_interface(btd_get_dbus_connection(),
adapter_get_path(adapter),
NETWORK_SERVER_INTERFACE);
return 0;
}
| modpow/bluez | profiles/network/server.c | C | gpl-2.0 | 16,703 |
<?php
/* v_news.php */
class __TwigTemplate_9e08b33d57d4999af4b97a7de7be260d99651c0c32a52969c4f3cc24a76180c7 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "
<h1 class=\"title\">Блог <a href=\"javascript:window.print();\" class=\"print\" title=\"Print this page\">Print</a></h1>
";
// line 3
if (isset($context["news"])) { $_news_ = $context["news"]; } else { $_news_ = null; }
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($_news_);
foreach ($context['_seq'] as $context["_key"] => $context["new"]) {
// line 4
echo "<article class=\"news__item\">
<div class=\"news__item-image\">
<a href=\"news/post/";
// line 6
if (isset($context["new"])) { $_new_ = $context["new"]; } else { $_new_ = null; }
echo $this->getAttribute($_new_, "id_article");
echo "\"><img src=\"";
if (isset($context["C"])) { $_C_ = $context["C"]; } else { $_C_ = null; }
echo $this->getAttribute($_C_, "IMG_DIR");
if (isset($context["new"])) { $_new_ = $context["new"]; } else { $_new_ = null; }
echo $this->getAttribute($_new_, "path");
echo "\" width=\"116\" height=\"77\" alt=\"\" /></a>
</div>
<div class=\"news__item-right\">
<div class=\"news__item-date\">";
// line 9
if (isset($context["new"])) { $_new_ = $context["new"]; } else { $_new_ = null; }
echo $this->getAttribute($_new_, "dt");
echo "</div>
<div class=\"news__item-title\"><a href=\"news/post/";
// line 10
if (isset($context["new"])) { $_new_ = $context["new"]; } else { $_new_ = null; }
echo $this->getAttribute($_new_, "id_article");
echo "\">";
if (isset($context["new"])) { $_new_ = $context["new"]; } else { $_new_ = null; }
echo $this->getAttribute($_new_, "title");
echo "</a></div>
<div class=\"news__item-summary\"><p>";
// line 11
if (isset($context["new"])) { $_new_ = $context["new"]; } else { $_new_ = null; }
echo $this->getAttribute($_new_, "intro");
echo "</p></div>
<div class=\"news__item-more\"><a href=\"news/post/";
// line 12
if (isset($context["new"])) { $_new_ = $context["new"]; } else { $_new_ = null; }
echo $this->getAttribute($_new_, "id_article");
echo "\">Читать далее</a></div>
</div>
</article>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['new'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 16
if (isset($context["navbar"])) { $_navbar_ = $context["navbar"]; } else { $_navbar_ = null; }
echo $_navbar_;
}
public function getTemplateName()
{
return "v_news.php";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 73 => 16, 62 => 12, 57 => 11, 49 => 10, 44 => 9, 32 => 6, 28 => 4, 23 => 3, 19 => 1,);
}
}
| akudryav/cms | v/themes/ura/twig_cache/9e/08/b33d57d4999af4b97a7de7be260d99651c0c32a52969c4f3cc24a76180c7.php | PHP | gpl-2.0 | 3,539 |
<?php
/**
* @version $Id: gantryformhelper.class.php 59361 2013-03-13 23:10:27Z btowles $
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2014 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*
* derived from Joomla with original copyright and license
* @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('GANTRY_VERSION') or die;
/**
* JForm's helper class.
* Provides a storage for filesystem's paths where JForm's entities resides and methods for creating this entities.
* Also stores objects with entities' prototypes for further reusing.
*
* @package Joomla.Framework
* @subpackage Form
* @since 1.6
*/
class GantryFormHelper
{
/**
* Array with paths where entities(field, rule, form) can be found.
*
* Array's structure:
* <code>
* paths:
* {ENTITY_NAME}:
* - /path/1
* - /path/2
* </code>
*
* @var array
* @since 1.6
*
*/
protected static $paths;
/**
* Static array of JForm's entity objects for re-use.
* All field's and rule's prototypes are here.
*
* Array's structure:
* <code>
* entities:
* {ENTITY_NAME}:
* {KEY}: {OBJECT}
* </code>
*
* @var array
* @since 1.6
*/
protected static $entities = array();
/**
* Method to load a form field object given a type.
*
* @param string $type The field type.
* @param boolean $new Flag to toggle whether we should get a new instance of the object.
*
* @return mixed JFormField object on success, false otherwise.
* @since 1.6
*/
public static function loadFieldType($type, $new = true)
{
return self::loadType('field', $type, $new);
}
/**
* Method to load a form entity object given a type.
* Each type is loaded only once and then used as a prototype for other objects of same type.
* Please, use this method only with those entities which support types (forms aren't support them).
*
* @param string $type The entity type.
* @param boolean $new Flag to toggle whether we should get a new instance of the object.
*
* @return mixed Entity object on success, false otherwise.
* @since 1.6
*/
protected static function loadType($entity, $type, $new = true)
{
// Reference to an array with current entity's type instances
$types = & self::$entities[$entity];
// Initialize variables.
$key = md5($type);
$class = '';
// Return an entity object if it already exists and we don't need a new one.
if (isset($types[$key]) && $new === false) {
return $types[$key];
}
if (($class = self::loadClass($entity, $type)) !== false) {
// Instantiate a new type object.
$types[$key] = new $class();
return $types[$key];
} else {
return false;
}
}
/**
* Attempt to import the JFormField class file if it isn't already imported.
* You can use this method outside of JForm for loading a field for inheritance or composition.
*
* @param string Type of a field whose class should be loaded.
*
* @return mixed Class name on success or false otherwise.
* @since 1.6
*/
public static function loadFieldClass($type)
{
return self::loadClass('field', $type);
}
/**
* Load a class for one of the form's entities of a particular type.
* Currently, it makes sence to use this method for the "field" and "rule" entities
* (but you can support more entities in your subclass).
*
* @param string One of the form entities (field or rule).
* @param string Type of an entity.
*
* @return mixed Class name on success or false otherwise.
*/
protected static function loadClass($entity, $type)
{
$class = 'GantryForm' . ucfirst($entity) . ucfirst($type);
if (class_exists($class)) return $class;
// Get the field search path array.
$paths = self::addPath($entity);
// If the type is complex, add the base type to the paths.
if ($pos = strpos($type, '_')) {
// Add the complex type prefix to the paths.
for ($i = 0, $n = count($paths); $i < $n; $i++) {
// Derive the new path.
$path = $paths[$i] . '/' . strtolower(substr($type, 0, $pos));
// If the path does not exist, add it.
if (!in_array($path, $paths)) {
array_unshift($paths, $path);
}
}
// Break off the end of the complex type.
$type = substr($type, $pos + 1);
}
// Try to find the class file.
if ($file = self::find($paths, strtolower($type) . '.php')) {
require_once $file;
}
// Check for all if the class exists.
return class_exists($class) ? $class : false;
}
/**
* Method to add a path to the list of field include paths.
*
* @param mixed $new A path or array of paths to add.
*
* @return array The list of paths that have been added.
* @since 1.6
*/
public static function addFieldPath($new = null)
{
return self::addPath('field', $new);
}
/**
* Method to add a path to the list of form include paths.
*
* @param mixed $new A path or array of paths to add.
*
* @return array The list of paths that have been added.
* @since 1.6
*/
public static function addFormPath($new = null)
{
return self::addPath('form', $new);
}
/**
* Method to add a path to the list of include paths for one of the form's entities.
* Currently supported entities: field, rule and form. You are free to support your own in a subclass.
*
* @param string Form's entity name for which paths will be added.
* @param mixed A path or array of paths to add.
*
* @return array The list of paths that have been added.
* @since 1.6
*/
protected static function addPath($entity, $new = null)
{
// Reference to an array with paths for current entity
$paths = & self::$paths[$entity];
// Add the default entity's search path if not set.
if (empty($paths)) {
// Until we support limited number of entities (form, field and rule)
// we can do this dumb pluralisation:
$entity_plural = $entity . 's';
// But when someday we would want to support more entities, then we should consider adding
// an inflector class to "libraries/joomla/utilities" and use it here (or somebody can use a real inflector in his subclass).
// see also: pluralization snippet by Paul Osman in JControllerForm's constructor.
$paths[] = gantry_dirname(__FILE__) . '/' . $entity_plural;
}
// Force the new path(s) to an array.
settype($new, 'array');
// Add the new paths to the stack if not already there.
foreach ($new as $path) {
if (!in_array($path, $paths)) {
array_unshift($paths, trim($path));
}
}
return $paths;
}
/**
* Searches the directory paths for a given file.
*
* @param array|string An path or array of path to search in
* @param string The file name to look for.
*
* @return mixed The full path and file name for the target file, or boolean false if the file is not found in any of the paths.
* @since 1.5
*/
public static function find($paths, $file)
{
settype($paths, 'array'); //force to array
// start looping through the path set
foreach ($paths as $path) {
// get the path to the file
$fullname = $path . '/' . $file;
// is the path based on a stream?
if (strpos($path, '://') === false) {
// not a stream, so do a realpath() to avoid directory
// traversal attempts on the local file system.
$path = gantry_clean_path(realpath($path)); // needed for substr() later
$fullname = gantry_clean_path(realpath($fullname));
}
// the substr() check added to make sure that the realpath()
// results in a directory registered so that
// non-registered directores are not accessible via directory
// traversal attempts.
if (file_exists($fullname) && substr($fullname, 0, strlen($path)) == $path) {
return $fullname;
}
}
// could not find the file in the set of paths
return false;
}
/**
* Method to load a form field object given a type.
*
* @param string $type The field type.
* @param boolean $new Flag to toggle whether we should get a new instance of the object.
*
* @return mixed JFormField object on success, false otherwise.
* @since 1.6
*/
public static function loadGroupType($type, $new = true)
{
return self::loadType('group', $type, $new);
}
/**
* Attempt to import the JFormRule class file if it isn't already imported.
* You can use this method outside of JForm for loading a rule for inheritance or composition.
*
* @param string Type of a rule whose class should be loaded.
*
* @return mixed Class name on success or false otherwise.
* @since 1.6
*/
public static function loadGroupClass($type)
{
return self::loadClass('group', $type);
}
/**
* Method to add a path to the list of field include paths.
*
* @param mixed $new A path or array of paths to add.
*
* @return array The list of paths that have been added.
* @since 1.6
*/
public static function addGroupPath($new = null)
{
return self::addPath('group', $new);
}
} | Dwightgnjohnson/corcoranpruett.com | wp-content/themes/gantry/core/config/gantryformhelper.class.php | PHP | gpl-2.0 | 9,408 |
/* ==========================================================================
* $File: //dwh/usb_iip/dev/software/otg_ipmate/linux/drivers/dwc_otg_cil_intr.c $
* $Revision: #7 $
* $Date: 2005/11/02 $
* $Change: 553126 $
*
* Synopsys HS OTG Linux Software Driver and documentation (hereinafter,
* "Software") is an Unsupported proprietary work of Synopsys, Inc. unless
* otherwise expressly agreed to in writing between Synopsys and you.
*
* The Software IS NOT an item of Licensed Software or Licensed Product under
* any End User Software License Agreement or Agreement for Licensed Product
* with Synopsys or any supplement thereto. You are permitted to use and
* redistribute this Software in source and binary forms, with or without
* modification, provided that redistributions of source code must retain this
* notice. You may not view, use, disclose, copy or distribute this file or
* any information contained herein except pursuant to this license grant from
* Synopsys. If you do not agree with this notice, including the disclaimer
* below, then you are not authorized to use the Software.
*
* THIS SOFTWARE IS BEING DISTRIBUTED BY SYNOPSYS SOLELY ON AN "AS IS" BASIS
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE HEREBY DISCLAIMED. IN NO EVENT SHALL SYNOPSYS 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.
* ========================================================================== */
/** @file
*
* The Core Interface Layer provides basic services for accessing and
* managing the DWC_otg hardware. These services are used by both the
* Host Controller Driver and the Peripheral Controller Driver.
*
* This file contains the Common Interrupt handlers.
*/
#include <linux/device.h>
#include "linux/dwc_otg_plat.h"
#include "dwc_otg_regs.h"
#include "dwc_otg_cil.h"
#include "dwc_otg_driver.h"
#include "dwc_otg_pcd.h"
#include "dwc_otg_hcd.h"
#if 1//#ifdef DEBUG
inline const char *op_state_str( dwc_otg_core_if_t *_core_if )
{
return (_core_if->op_state==A_HOST?"a_host":
(_core_if->op_state==A_SUSPEND?"a_suspend":
(_core_if->op_state==A_PERIPHERAL?"a_peripheral":
(_core_if->op_state==B_PERIPHERAL?"b_peripheral":
(_core_if->op_state==B_HOST?"b_host":
"unknown")))));
}
#endif
/** This function will log a debug message
*
* @param _core_if Programming view of DWC_otg controller.
*/
int32_t dwc_otg_handle_mode_mismatch_intr (dwc_otg_core_if_t *_core_if)
{
gintsts_data_t gintsts;
DWC_WARN("Mode Mismatch Interrupt: currently in %s mode\n",
dwc_otg_mode(_core_if) ? "Host" : "Device");
/* Clear interrupt */
gintsts.d32 = 0;
gintsts.b.modemismatch = 1;
dwc_write_reg32 (&_core_if->core_global_regs->gintsts, gintsts.d32);
return 1;
}
/** Start the HCD. Helper function for using the HCD callbacks.
*
* @param _core_if Programming view of DWC_otg controller.
*/
/*static*/ inline void hcd_start( dwc_otg_core_if_t *_core_if )
{
if (_core_if->hcd_cb && _core_if->hcd_cb->start) {
_core_if->hcd_cb->start( _core_if->hcd_cb->p );
}
}
/** Stop the HCD. Helper function for using the HCD callbacks.
*
* @param _core_if Programming view of DWC_otg controller.
*/
static inline void hcd_stop( dwc_otg_core_if_t *_core_if )
{
if (_core_if->hcd_cb && _core_if->hcd_cb->stop) {
_core_if->hcd_cb->stop( _core_if->hcd_cb->p );
}
}
/** Disconnect the HCD. Helper function for using the HCD callbacks.
*
* @param _core_if Programming view of DWC_otg controller.
*/
/*static*/ inline void hcd_disconnect( dwc_otg_core_if_t *_core_if )
{
if (_core_if->hcd_cb && _core_if->hcd_cb->disconnect) {
_core_if->hcd_cb->disconnect( _core_if->hcd_cb->p );
}
}
/** Inform the HCD the a New Session has begun. Helper function for
* using the HCD callbacks.
*
* @param _core_if Programming view of DWC_otg controller.
*/
static inline void hcd_session_start( dwc_otg_core_if_t *_core_if )
{
if (_core_if->hcd_cb && _core_if->hcd_cb->session_start) {
_core_if->hcd_cb->session_start( _core_if->hcd_cb->p );
}
}
/** Start the PCD. Helper function for using the PCD callbacks.
*
* @param _core_if Programming view of DWC_otg controller.
*/
static inline void pcd_start( dwc_otg_core_if_t *_core_if )
{
if (_core_if->pcd_cb && _core_if->pcd_cb->start ) {
_core_if->pcd_cb->start( _core_if->pcd_cb->p );
}
}
/** Stop the PCD. Helper function for using the PCD callbacks.
*
* @param _core_if Programming view of DWC_otg controller.
*/
static inline void pcd_stop( dwc_otg_core_if_t *_core_if )
{
if (_core_if->pcd_cb && _core_if->pcd_cb->stop ) {
_core_if->pcd_cb->stop( _core_if->pcd_cb->p );
}
}
/** Suspend the PCD. Helper function for using the PCD callbacks.
*
* @param _core_if Programming view of DWC_otg controller.
*/
static inline void pcd_suspend( dwc_otg_core_if_t *_core_if )
{
if (_core_if->pcd_cb && _core_if->pcd_cb->suspend ) {
_core_if->pcd_cb->suspend( _core_if->pcd_cb->p, 0);
}
}
/** Resume the PCD. Helper function for using the PCD callbacks.
*
* @param _core_if Programming view of DWC_otg controller.
*/
static inline void pcd_resume( dwc_otg_core_if_t *_core_if )
{
if (_core_if->pcd_cb && _core_if->pcd_cb->resume_wakeup ) {
_core_if->pcd_cb->resume_wakeup( _core_if->pcd_cb->p );
}
}
/**
* This function handles the OTG Interrupts. It reads the OTG
* Interrupt Register (GOTGINT) to determine what interrupt has
* occurred.
*
* @param _core_if Programming view of DWC_otg controller.
*/
int32_t dwc_otg_handle_otg_intr(dwc_otg_core_if_t *_core_if)
{
dwc_otg_core_global_regs_t *global_regs =
_core_if->core_global_regs;
gotgint_data_t gotgint;
gotgctl_data_t gotgctl;
dctl_data_t dctl = {.d32=0};
gintmsk_data_t gintmsk;
gotgint.d32 = dwc_read_reg32( &global_regs->gotgint);
gotgctl.d32 = dwc_read_reg32( &global_regs->gotgctl);
DWC_DEBUGPL(DBG_CIL, "++OTG Interrupt gotgint=%0x [%s]\n", gotgint.d32,
op_state_str(_core_if));
//DWC_DEBUGPL(DBG_CIL, "gotgctl=%08x\n", gotgctl.d32 );
if (gotgint.b.sesenddet) {
DWC_DEBUGPL(DBG_ANY, " ++OTG Interrupt: "
"Session End Detected++ (%s)\n",
op_state_str(_core_if));
#ifndef DWC_HOST_ONLY
//add by everest/////////////////
if(1 ) {//!__system_crashed()
/* soft disconnect */
dctl.d32 = dwc_read_reg32( &_core_if->dev_if->dev_global_regs->dctl );
dctl.b.sftdiscon = 1;
dwc_write_reg32( &_core_if->dev_if->dev_global_regs->dctl, dctl.d32 );
DWC_PRINT("********session end intr,soft disconnect************************\n");
}
_core_if->otg_dev->pcd->vbus_status = 0;
///////////////////////////////
#endif
gotgctl.d32 = dwc_read_reg32( &global_regs->gotgctl);
if (_core_if->op_state == B_HOST) {
pcd_start( _core_if );
_core_if->op_state = B_PERIPHERAL;
} else {
/* If not B_HOST and Device HNP still set. HNP
* Did not succeed!*/
if (gotgctl.b.devhnpen) {
DWC_DEBUGPL(DBG_ANY, "Session End Detected\n");
DWC_ERROR( "Device Not Connected/Responding!\n" );
}
/* If Session End Detected the B-Cable has
* been disconnected. */
/* Reset PCD and Gadget driver to a
* clean state. */
pcd_stop(_core_if);
}
gotgctl.d32 = 0;
gotgctl.b.devhnpen = 1;
dwc_modify_reg32( &global_regs->gotgctl,
gotgctl.d32, 0);
}
if (gotgint.b.sesreqsucstschng) {
DWC_DEBUGPL(DBG_ANY, " ++OTG Interrupt: "
"Session Reqeust Success Status Change++\n");
gotgctl.d32 = dwc_read_reg32( &global_regs->gotgctl);
if (gotgctl.b.sesreqscs) {
if ((_core_if->core_params->phy_type == DWC_PHY_TYPE_PARAM_FS) &&
(_core_if->core_params->i2c_enable)) {
_core_if->srp_success = 1;
}
else {
pcd_resume( _core_if );
/* Clear Session Request */
gotgctl.d32 = 0;
gotgctl.b.sesreq = 1;
dwc_modify_reg32( &global_regs->gotgctl,
gotgctl.d32, 0);
}
}
}
if (gotgint.b.hstnegsucstschng) {
/* Print statements during the HNP interrupt handling
* can cause it to fail.*/
gotgctl.d32 = dwc_read_reg32(&global_regs->gotgctl);
if (gotgctl.b.hstnegscs) {
if (dwc_otg_is_host_mode(_core_if) ) {
_core_if->op_state = B_HOST;
/*
* Need to disable SOF interrupt immediately.
* When switching from device to host, the PCD
* interrupt handler won't handle the
* interrupt if host mode is already set. The
* HCD interrupt handler won't get called if
* the HCD state is HALT. This means that the
* interrupt does not get handled and Linux
* complains loudly.
*/
gintmsk.d32 = 0;
gintmsk.b.sofintr = 1;
dwc_modify_reg32(&global_regs->gintmsk,
gintmsk.d32, 0);
pcd_stop(_core_if);
/*
* Initialize the Core for Host mode.
*/
hcd_start( _core_if );
_core_if->op_state = B_HOST;
}
} else {
gotgctl.d32 = 0;
gotgctl.b.hnpreq = 1;
gotgctl.b.devhnpen = 1;
dwc_modify_reg32( &global_regs->gotgctl,
gotgctl.d32, 0);
DWC_DEBUGPL( DBG_ANY, "HNP Failed\n");
DWC_ERROR( "Device Not Connected/Responding\n" );
}
}
if (gotgint.b.hstnegdet) {
/* The disconnect interrupt is set at the same time as
* Host Negotiation Detected. During the mode
* switch all interrupts are cleared so the disconnect
* interrupt handler will not get executed.
*/
DWC_DEBUGPL(DBG_ANY, " ++OTG Interrupt: "
"Host Negotiation Detected++ (%s)\n",
(dwc_otg_is_host_mode(_core_if)?"Host":"Device"));
if (dwc_otg_is_device_mode(_core_if)){
DWC_DEBUGPL(DBG_ANY, "a_suspend->a_peripheral (%d)\n",_core_if->op_state);
hcd_disconnect( _core_if );
pcd_start( _core_if );
_core_if->op_state = A_PERIPHERAL;
} else {
/*
* Need to disable SOF interrupt immediately. When
* switching from device to host, the PCD interrupt
* handler won't handle the interrupt if host mode is
* already set. The HCD interrupt handler won't get
* called if the HCD state is HALT. This means that
* the interrupt does not get handled and Linux
* complains loudly.
*/
gintmsk.d32 = 0;
gintmsk.b.sofintr = 1;
dwc_modify_reg32(&global_regs->gintmsk,
gintmsk.d32, 0);
pcd_stop( _core_if );
hcd_start( _core_if );
_core_if->op_state = A_HOST;
}
}
if (gotgint.b.adevtoutchng) {
DWC_DEBUGPL(DBG_ANY, " ++OTG Interrupt: "
"A-Device Timeout Change++\n");
}
if (gotgint.b.debdone) {
DWC_DEBUGPL(DBG_ANY, " ++OTG Interrupt: "
"Debounce Done++\n");
}
/* Clear GOTGINT */
dwc_write_reg32 (&_core_if->core_global_regs->gotgint, gotgint.d32);
return 1;
}
/**
* This function handles the Connector ID Status Change Interrupt. It
* reads the OTG Interrupt Register (GOTCTL) to determine whether this
* is a Device to Host Mode transition or a Host Mode to Device
* Transition.
*
* This only occurs when the cable is connected/removed from the PHY
* connector.
*
* @param _core_if Programming view of DWC_otg controller.
*/
int32_t dwc_otg_handle_conn_id_status_change_intr(dwc_otg_core_if_t *_core_if)
{
gintsts_data_t gintsts = { .d32 = 0 };
/* Set flag and clear interrupt */
gintsts.b.conidstschng = 1;
dwc_write_reg32 (&_core_if->core_global_regs->gintsts, gintsts.d32);
return 1;
}
/**
* This interrupt indicates that a device is initiating the Session
* Request Protocol to request the host to turn on bus power so a new
* session can begin. The handler responds by turning on bus power. If
* the DWC_otg controller is in low power mode, the handler brings the
* controller out of low power mode before turning on bus power.
*
* @param _core_if Programming view of DWC_otg controller.
*/
int32_t dwc_otg_handle_session_req_intr( dwc_otg_core_if_t *_core_if )
{
hprt0_data_t hprt0;
gintsts_data_t gintsts;
#ifndef DWC_HOST_ONLY
DWC_DEBUGPL(DBG_ANY, "++Session Request Interrupt++\n");
if (dwc_otg_is_device_mode(_core_if) ) {
DWC_PRINT("SRP: Device mode\n");
} else {
DWC_PRINT("SRP: Host mode\n");
// dump_coreif(_core_if);
// dump_hostif(_core_if);
dwc_otg_dump_global_registers(_core_if);
/* Turn on the port power bit. */
hprt0.d32 = dwc_otg_read_hprt0( _core_if );
hprt0.b.prtpwr = 1;
dwc_write_reg32(_core_if->host_if->hprt0, hprt0.d32);
/* Start the Connection timer. So a message can be displayed
* if connect does not occur within 10 seconds. */
hcd_session_start( _core_if );
}
#endif
/* Clear interrupt */
gintsts.d32 = 0;
gintsts.b.sessreqintr = 1;
dwc_write_reg32 (&_core_if->core_global_regs->gintsts, gintsts.d32);
return 1;
}
/**
* This interrupt indicates that the DWC_otg controller has detected a
* resume or remote wakeup sequence. If the DWC_otg controller is in
* low power mode, the handler must brings the controller out of low
* power mode. The controller automatically begins resume
* signaling. The handler schedules a time to stop resume signaling.
*/
int32_t dwc_otg_handle_wakeup_detected_intr( dwc_otg_core_if_t *_core_if )
{
gintsts_data_t gintsts;
DWC_DEBUGPL(DBG_ANY, "++Resume and Remote Wakeup Detected Interrupt++\n");
if (dwc_otg_is_device_mode(_core_if) ) {
dctl_data_t dctl = {.d32=0};
DWC_DEBUGPL(DBG_PCD, "DSTS=0x%0x\n",
dwc_read_reg32( &_core_if->dev_if->dev_global_regs->dsts));
#ifdef PARTIAL_POWER_DOWN
if (_core_if->hwcfg4.b.power_optimiz) {
pcgcctl_data_t power = {.d32=0};
power.d32 = dwc_read_reg32( _core_if->pcgcctl );
DWC_DEBUGPL(DBG_CIL, "PCGCCTL=%0x\n", power.d32);
power.b.stoppclk = 0;
dwc_write_reg32( _core_if->pcgcctl, power.d32);
power.b.pwrclmp = 0;
dwc_write_reg32( _core_if->pcgcctl, power.d32);
power.b.rstpdwnmodule = 0;
dwc_write_reg32( _core_if->pcgcctl, power.d32);
}
#endif
/* Clear the Remote Wakeup Signalling */
dctl.b.rmtwkupsig = 1;
dwc_modify_reg32( &_core_if->dev_if->dev_global_regs->dctl,
dctl.d32, 0 );
if (_core_if->pcd_cb && _core_if->pcd_cb->resume_wakeup) {
_core_if->pcd_cb->resume_wakeup( _core_if->pcd_cb->p );
}
} else {
/*
* Clear the Resume after 70ms. (Need 20 ms minimum. Use 70 ms
* so that OPT tests pass with all PHYs).
*/
hprt0_data_t hprt0 = {.d32=0};
pcgcctl_data_t pcgcctl = {.d32=0};
/* Restart the Phy Clock */
pcgcctl.b.stoppclk = 1;
dwc_modify_reg32(_core_if->pcgcctl, pcgcctl.d32, 0);
UDELAY(10);
/* Now wait for 70 ms. */
hprt0.d32 = dwc_otg_read_hprt0( _core_if );
DWC_DEBUGPL(DBG_ANY,"Resume: HPRT0=%0x\n", hprt0.d32);
MDELAY(70);
hprt0.b.prtres = 0; /* Resume */
dwc_write_reg32(_core_if->host_if->hprt0, hprt0.d32);
DWC_DEBUGPL(DBG_ANY,"Clear Resume: HPRT0=%0x\n", dwc_read_reg32(_core_if->host_if->hprt0));
}
/* Clear interrupt */
gintsts.d32 = 0;
gintsts.b.wkupintr = 1;
dwc_write_reg32 (&_core_if->core_global_regs->gintsts, gintsts.d32);
return 1;
}
/**
* This interrupt indicates that a device has been disconnected from
* the root port.
*/
int32_t dwc_otg_handle_disconnect_intr( dwc_otg_core_if_t *_core_if)
{
gintsts_data_t gintsts;
DWC_DEBUGPL(DBG_ANY, "++Disconnect Detected Interrupt++ (%s) %s\n",
(dwc_otg_is_host_mode(_core_if)?"Host":"Device"),
op_state_str(_core_if));
/** @todo Consolidate this if statement. */
#if 0//ndef DWC_HOST_ONLY
if (_core_if->op_state == B_HOST) {
/* If in device mode Disconnect and stop the HCD, then
* start the PCD. */
hcd_disconnect( _core_if );
pcd_start( _core_if );
_core_if->op_state = B_PERIPHERAL;
} else if (dwc_otg_is_device_mode(_core_if)) {
gotgctl_data_t gotgctl = { .d32 = 0 };
gotgctl.d32 = dwc_read_reg32(&_core_if->core_global_regs->gotgctl);
if (gotgctl.b.hstsethnpen==1) {
/* Do nothing, if HNP in process the OTG
* interrupt "Host Negotiation Detected"
* interrupt will do the mode switch.
*/
} else if (gotgctl.b.devhnpen == 0) {
/* If in device mode Disconnect and stop the HCD, then
* start the PCD. */
hcd_disconnect( _core_if );
pcd_start( _core_if );
_core_if->op_state = B_PERIPHERAL;
} else {
DWC_DEBUGPL(DBG_ANY,"!a_peripheral && !devhnpen\n");
}
} else {
if (_core_if->op_state == A_HOST) {
/* A-Cable still connected but device disconnected. */
hcd_disconnect( _core_if );
}
}
#endif
hcd_disconnect( _core_if );
gintsts.d32 = 0;
gintsts.b.disconnect = 1;
dwc_write_reg32 (&_core_if->core_global_regs->gintsts, gintsts.d32);
return 1;
}
/**
* This interrupt indicates that SUSPEND state has been detected on
* the USB.
*
* For HNP the USB Suspend interrupt signals the change from
* "a_peripheral" to "a_host".
*
* When power management is enabled the core will be put in low power
* mode.
*/
int32_t dwc_otg_handle_usb_suspend_intr(dwc_otg_core_if_t *_core_if )
{
dsts_data_t dsts;
gintsts_data_t gintsts;
DWC_DEBUGPL(DBG_ANY,"USB SUSPEND\n");
DWC_PRINT("USB SUSPEND\n");
if (dwc_otg_is_device_mode( _core_if ) ) {
/* Check the Device status register to determine if the Suspend
* state is active. */
dsts.d32 = dwc_read_reg32( &_core_if->dev_if->dev_global_regs->dsts);
DWC_DEBUGPL(DBG_PCD, "DSTS=0x%0x\n", dsts.d32);
DWC_DEBUGPL(DBG_PCD, "DSTS.Suspend Status=%d "
"HWCFG4.power Optimize=%d\n",
dsts.b.suspsts, _core_if->hwcfg4.b.power_optimiz);
#ifdef PARTIAL_POWER_DOWN
/** @todo Add a module parameter for power management. */
if (dsts.b.suspsts && _core_if->hwcfg4.b.power_optimiz) {
DWC_PRINT("suspend power_optimiz\n");
#if 0
pcgcctl_data_t power = {.d32=0};
DWC_DEBUGPL(DBG_CIL, "suspend\n");
power.b.pwrclmp = 1;
dwc_write_reg32( _core_if->pcgcctl, power.d32);
power.b.rstpdwnmodule = 1;
dwc_modify_reg32( _core_if->pcgcctl, 0, power.d32);
power.b.stoppclk = 1;
dwc_modify_reg32( _core_if->pcgcctl, 0, power.d32);
#endif
} else {
DWC_DEBUGPL(DBG_ANY,"disconnect?\n");
}
#endif
/* PCD callback for suspend. */
pcd_suspend(_core_if);
} else {
if (_core_if->op_state == A_PERIPHERAL) {
DWC_DEBUGPL(DBG_ANY,"a_peripheral->a_host\n");
/* Clear the a_peripheral flag, back to a_host. */
pcd_stop( _core_if );
hcd_start( _core_if );
_core_if->op_state = A_HOST;
}
}
/* Clear interrupt */
gintsts.d32 = 0;
gintsts.b.usbsuspend = 1;
dwc_write_reg32( &_core_if->core_global_regs->gintsts, gintsts.d32);
return 1;
}
/**
* This function returns the Core Interrupt register.
*/
static inline uint32_t dwc_otg_read_common_intr(dwc_otg_core_if_t *_core_if)
{
gintsts_data_t gintsts;
gintmsk_data_t gintmsk;
gintmsk_data_t gintmsk_common = {.d32=0};
gintmsk_common.b.wkupintr = 1;
gintmsk_common.b.sessreqintr = 1;
gintmsk_common.b.conidstschng = 1;
gintmsk_common.b.otgintr = 1;
gintmsk_common.b.modemismatch = 1;
gintmsk_common.b.disconnect = 1;
gintmsk_common.b.usbsuspend = 1;
/** @todo: The port interrupt occurs while in device
* mode. Added code to CIL to clear the interrupt for now!
*/
gintmsk_common.b.portintr = 1;
gintsts.d32 = dwc_read_reg32(&_core_if->core_global_regs->gintsts);
gintmsk.d32 = dwc_read_reg32(&_core_if->core_global_regs->gintmsk);
#ifdef DEBUG
/* if any common interrupts set */
if (gintsts.d32 & gintmsk_common.d32) {
DWC_DEBUGPL(DBG_ANY, "gintsts=%08x gintmsk=%08x\n",
gintsts.d32, gintmsk.d32);
}
#endif
return ((gintsts.d32 & gintmsk.d32 ) & gintmsk_common.d32);
}
/**
* Common interrupt handler.
*
* The common interrupts are those that occur in both Host and Device mode.
* This handler handles the following interrupts:
* - Mode Mismatch Interrupt
* - Disconnect Interrupt
* - OTG Interrupt
* - Connector ID Status Change Interrupt
* - Session Request Interrupt.
* - Resume / Remote Wakeup Detected Interrupt.
*
*/
int32_t dwc_otg_handle_common_intr( dwc_otg_core_if_t *_core_if )
{
int retval = 0;
gintsts_data_t gintsts;
gintsts.d32 = dwc_otg_read_common_intr(_core_if);
if (gintsts.b.modemismatch) {
retval |= dwc_otg_handle_mode_mismatch_intr( _core_if );
}
if (gintsts.b.otgintr) {
retval |= dwc_otg_handle_otg_intr( _core_if );
}
if (gintsts.b.conidstschng) {
retval |= dwc_otg_handle_conn_id_status_change_intr( _core_if );
}
if (gintsts.b.disconnect) {
retval |= dwc_otg_handle_disconnect_intr( _core_if );
}
if (gintsts.b.sessreqintr) {
retval |= dwc_otg_handle_session_req_intr( _core_if );
}
if (gintsts.b.wkupintr) {
retval |= dwc_otg_handle_wakeup_detected_intr( _core_if );
}
if (gintsts.b.usbsuspend) {
retval |= dwc_otg_handle_usb_suspend_intr( _core_if );
}
if (gintsts.b.portintr && dwc_otg_is_device_mode(_core_if)) {
/* The port interrupt occurs while in device mode with HPRT0
* Port Enable/Disable.
*/
gintsts.d32 = 0;
gintsts.b.portintr = 1;
dwc_write_reg32(&_core_if->core_global_regs->gintsts,
gintsts.d32);
retval |= 1;
}
return retval;
}
| smartassfox/rk-29 | drivers/usb/dwc_otg/dwc_otg_cil_intr.c | C | gpl-2.0 | 25,260 |
/*
* Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.tools.jaotc;
import jdk.tools.jaotc.amd64.AMD64InstructionDecoder;
import jdk.tools.jaotc.aarch64.AArch64InstructionDecoder;
import jdk.vm.ci.amd64.AMD64;
import jdk.vm.ci.aarch64.AArch64;
import jdk.vm.ci.code.Architecture;
import jdk.vm.ci.code.TargetDescription;
public abstract class InstructionDecoder {
public static InstructionDecoder getInstructionDecoder(TargetDescription target) {
Architecture architecture = target.arch;
if (architecture instanceof AMD64) {
return new AMD64InstructionDecoder(target);
} else if (architecture instanceof AArch64) {
return new AArch64InstructionDecoder();
} else {
throw new InternalError("Unsupported architecture " + architecture);
}
}
public abstract void decodePosition(byte[] code, int pcOffset);
public abstract int currentEndOfInstruction();
}
| md-5/jdk10 | src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/InstructionDecoder.java | Java | gpl-2.0 | 1,966 |
<h2 class='title'>Edit Bike</h2>
<div><img src="/images/metallt.png" class="bb-back"></div>
<div>{{bike.year}}</div>
<form class="newForm">
<div class="newColumn">
<!-- <fieldset>
<legend>Ready?</legend>
<ul>
<li>Yes:<input type="radio" ng-model='bk.ready' value='yes'></li>
<li>No:<input type="radio" ng-model='bk.ready' value='no'></li>
</ul>
</fieldset>
<label>Year:</label>
<input name='year' type="text" ng-model='bk.year' value='{{bike.year}}'>
<label>Make:</label>
<select class='dropdown' ng-model='bk.make'>
<option value="Honda"> Honda </option>
<option value="Kawasaki"> Kawasaki </option>
<option value="Suzuki"> Suzuki </option>
<option value="Yamaha"> Yamaha </option>
<option value="Other"> Other </option>
</select> -->
<label >Model:</label>
<input name='model' type="text" ng-model='model' >
</div>
<!-- <div class="newColumn">
<label>ID:</label>
<input name='id' type="text" ng-model='bk.ident'>
<label>SN:</label>
<input name='sn' type="text" ng-model='bk.sn'>
<label class='newLabel'>Color:</label>
<input name='color' type="text" ng-model='bk.maincolor'>
<fieldset>
<legend>Type:</legend>
<ul>
<li>Standard:<input type="radio" ng-model='bk.maintype' value='Standard'></li>
<li>Sport:<input type="radio" ng-model='bk.maintype' value='Sport'></li>
<li>Cruiser:<input type="radio" ng-model='bk.maintype' value='Cruiser'></li>
<li>Dual:<input type="radio" ng-model='bk.maintype' value='Dual'></li>
</ul>
</fieldset>
</div> -->
<div>
<label >Notes:</label>
<textarea ng-model='notes'></textarea>
</div>
<div class="button">
<button ng-click="savebike()">Save Bike</button>
</div>
</form>
| melindae/bike-barn | dist/templates/edit-bike.html | HTML | gpl-2.0 | 1,885 |
package com.nutiteq.maps;
import com.nutiteq.maps.projections.EPSG3785;
import com.nutiteq.ui.Copyright;
import com.nutiteq.ui.StringCopyright;
/**
* Default implementation using Open Street Map tiles server.
*/
public class OpenStreetMap extends EPSG3785 implements GeoMap, UnstreamedMap {
private static final String OSM_MAPNIK_URL = "http://tile.openstreetmap.org/";
public static final int MIN_ZOOM = 0;
public static final int MAX_ZOOM = 17;
public static final int TILE_SIZE = 256;
/**
* Instance if Open Street Map
*/
public static final OpenStreetMap MAPNIK = new OpenStreetMap(OSM_MAPNIK_URL, TILE_SIZE, MIN_ZOOM,
MAX_ZOOM);
private final String baseUrl;
public OpenStreetMap(final String baseUrl, final int tileSize, final int minZoom,
final int maxZoom) {
this(new StringCopyright("OpenStreetMap"), baseUrl, tileSize, minZoom, maxZoom);
}
public OpenStreetMap(final Copyright copyright, final String baseUrl, final int tileSize,
final int minZoom, final int maxZoom) {
super(copyright, tileSize, minZoom, maxZoom);
this.baseUrl = baseUrl;
}
public String buildPath(final int mapX, final int mapY, final int zoom) {
final StringBuffer result = new StringBuffer();
result.append(baseUrl);
result.append(zoom);
result.append('/');
result.append((mapX / getTileSize()) & ((1 << zoom) - 1));
result.append('/');
result.append(mapY / getTileSize());
result.append(".png");
return result.toString();
}
}
| camptocamp/maps-lib-nutiteq | src/com/nutiteq/maps/OpenStreetMap.java | Java | gpl-2.0 | 1,518 |
<?php
/**
* Fired when the plugin is uninstalled.
*
* @package ReduxFramework\Uninstall
* @author Dovy Paukstys <info@simplerain.com>
* @since 3.0.0
*/
// If uninstall, not called from WordPress, then exit
if( !defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit;
}
// TODO: Define uninstall functionality here
| sadpiglet20/ninesouthestates | wp-content/themes/real-spaces/includes/uninstall.php | PHP | gpl-2.0 | 323 |
/***************************************************************************
*
* LanScsiProtocol.h
*
* LanScsiProtocol definitions
*
* Copyright (c) 2003 XiMeta, Inc. All rights reserved.
*
**************************************************************************/
#ifndef _LANSCSIPROTOCOL_H_
#define _LANSCSIPROTOCOL_H_
#include "cdb.h"
#ifdef KERNEL
#include "LanScsiSocket.h"
#endif
#define MAX_NR_OF_TARGETS_PER_DEVICE 16
#define PACKET_COMMAND_SIZE 12
typedef struct _PNP_MESSAGE {
unsigned char ucType;
unsigned char ucVersion;
} PNP_MESSAGE, *PPNP_MESSAGE;
typedef struct _TARGET_DATA {
bool bPresent;
uint8_t NRRWHost;
uint8_t NRROHost;
uint64_t TargetData;
uint32_t DiskArrayType;
// IDE Info.
bool bLBA;
bool bLBA48;
bool bPacket;
bool bDMA;
uint8_t SelectedTransferMode;
bool bCable80;
uint64_t SectorCount;
uint32_t SectorSize;
uint32_t configuration;
uint32_t status;
char model[42];
char firmware[10];
char serialNumber[22];
uint32_t MaxRequestBytes;
} TARGET_DATA, *PTARGET_DATA;
struct LanScsiSession {
#ifdef KERNEL
xi_socket_t DevSo;
#else
int DevSo;
#endif
char Password[8];
uint8_t ui8HWType;
uint8_t ui8HWVersion;
uint16_t ui16Revision;
int32_t HPID;
int16_t RPID;
uint32_t Tag;
uint32_t SessionPhase;
uint32_t CHAP_C;
uint32_t MaxRequestBlocks;
uint16_t HeaderEncryptAlgo;
uint16_t DataEncryptAlgo;
uint32_t NumberOfTargets;
};
#define HW_VERSION_1_0 0
#define HW_VERSION_1_1 1
#define HW_VERSION_2_0 2
//
// NDAS hardware version 2.0 revisions
//
#define LANSCSIIDE_VER20_REV_1G_ORIGINAL 0x0000
#define LANSCSIIDE_VER20_REV_100M 0x0018
#define LANSCSIIDE_VER20_REV_1G 0x0010
#define LOGIN_TYPE_NORMAL 0x00
#define LOGIN_TYPE_DISCOVERY 0xFF
#define DISCOVERY_USER 0x00000000
#define FIRST_TARGET_RO_USER 0x00000001
#define FIRST_TARGET_RW_USER 0x00010001
#define ALL_TARGET_RO_USER 0x00007fff
#define ALL_TARGET_RW_USER 0x7fff7fff
#define SUPER_USER 0xffffffff
#define MAX_REQUEST_SIZE 1500
#define DISK_BLOCK_SIZE 512
#define DISK_CACHE_SIZE_BY_BLOCK_SIZE (64 * 1024 * 1024 / DISK_BLOCK_SIZE) // 64MB
#define MAX_REQUEST_BLOCKS_GIGA_CHIP_BUG 108 // 54KB
/***************************************************************************
*
* Function prototypes
*
**************************************************************************/
#ifdef __cplusplus
extern "C"
{
#endif // __cplusplus
extern int Login(struct LanScsiSession *Session, uint8_t LoginType, uint32_t UserID, char *Key);
extern int Logout(struct LanScsiSession *Session);
extern int TextTargetList(struct LanScsiSession *Session, int *NRTarget, TARGET_DATA *PerTarget);
extern int GetDiskInfo(struct LanScsiSession *Session, uint32_t TargetID, TARGET_DATA *TargetData);
extern int IdeCommand(struct LanScsiSession *Session,
int32_t TargetId,
TARGET_DATA *TargetData,
int64_t LUN,
uint8_t Command,
int64_t Location,
int16_t SectorCount,
int8_t Feature,
char * pData,
uint32_t BufferLength,
uint8_t *pResult,
PCDBd pCdb,
uint8_t DataTransferDirection
);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif /* _LANSCSIPROTOCOL_H_ */
| iocellnetworks/ndas4mac | tags/1.8.3_alpha7/Sources/Inc/LanScsiProtocol.h | C | gpl-2.0 | 3,525 |
#
# Makefile for the kernel pcmcia subsystem (c/o David Hinds)
#
ifeq ($(CONFIG_PCMCIA_DEBUG),y)
EXTRA_CFLAGS += -DDEBUG
endif
pcmcia_core-y += cs.o cistpl.o rsrc_mgr.o socket_sysfs.o
pcmcia_core-$(CONFIG_CARDBUS) += cardbus.o
obj-$(CONFIG_PCCARD) += pcmcia_core.o
pcmcia-y += ds.o pcmcia_compat.o pcmcia_resource.o
pcmcia-$(CONFIG_PCMCIA_IOCTL) += pcmcia_ioctl.o
obj-$(CONFIG_PCMCIA) += pcmcia.o
obj-$(CONFIG_PCCARD_NONSTATIC) += rsrc_nonstatic.o
# socket drivers
obj-$(CONFIG_YENTA) += yenta_socket.o
obj-$(CONFIG_PD6729) += pd6729.o
obj-$(CONFIG_I82365) += i82365.o
obj-$(CONFIG_I82092) += i82092.o
obj-$(CONFIG_TCIC) += tcic.o
obj-$(CONFIG_HD64465_PCMCIA) += hd64465_ss.o
obj-$(CONFIG_PCMCIA_SA1100) += sa11xx_core.o sa1100_cs.o
obj-$(CONFIG_PCMCIA_SA1111) += sa11xx_core.o sa1111_cs.o
obj-$(CONFIG_PCMCIA_PXA2XX) += pxa2xx_core.o pxa2xx_cs.o
obj-$(CONFIG_M32R_PCC) += m32r_pcc.o
obj-$(CONFIG_M32R_CFC) += m32r_cfc.o
obj-$(CONFIG_PCMCIA_AU1X00) += au1x00_ss.o
obj-$(CONFIG_PCMCIA_VRC4171) += vrc4171_card.o
obj-$(CONFIG_PCMCIA_VRC4173) += vrc4173_cardu.o
obj-$(CONFIG_OMAP_CF) += omap_cf.o
sa11xx_core-y += soc_common.o sa11xx_base.o
pxa2xx_core-y += soc_common.o pxa2xx_base.o
au1x00_ss-y += au1000_generic.o
au1x00_ss-$(CONFIG_MIPS_PB1000) += au1000_pb1x00.o
au1x00_ss-$(CONFIG_MIPS_PB1100) += au1000_pb1x00.o
au1x00_ss-$(CONFIG_MIPS_PB1500) += au1000_pb1x00.o
au1x00_ss-$(CONFIG_MIPS_DB1000) += au1000_db1x00.o
au1x00_ss-$(CONFIG_MIPS_DB1100) += au1000_db1x00.o
au1x00_ss-$(CONFIG_MIPS_DB1500) += au1000_db1x00.o
au1x00_ss-$(CONFIG_MIPS_DB1550) += au1000_db1x00.o
au1x00_ss-$(CONFIG_MIPS_XXS1500) += au1000_xxs1500.o
sa1111_cs-y += sa1111_generic.o
sa1111_cs-$(CONFIG_ASSABET_NEPONSET) += sa1100_neponset.o
sa1111_cs-$(CONFIG_SA1100_BADGE4) += sa1100_badge4.o
sa1111_cs-$(CONFIG_SA1100_JORNADA720) += sa1100_jornada720.o
sa1100_cs-y += sa1100_generic.o
sa1100_cs-$(CONFIG_SA1100_ASSABET) += sa1100_assabet.o
sa1100_cs-$(CONFIG_SA1100_CERF) += sa1100_cerf.o
sa1100_cs-$(CONFIG_SA1100_H3600) += sa1100_h3600.o
sa1100_cs-$(CONFIG_SA1100_SHANNON) += sa1100_shannon.o
sa1100_cs-$(CONFIG_SA1100_SIMPAD) += sa1100_simpad.o
pxa2xx_cs-$(CONFIG_ARCH_LUBBOCK) += pxa2xx_lubbock.o sa1111_generic.o
pxa2xx_cs-$(CONFIG_MACH_MAINSTONE) += pxa2xx_mainstone.o
pxa2xx_cs-$(CONFIG_PXA_SHARPSL) += pxa2xx_sharpsl.o
| ipwndev/DSLinux-Mirror | linux-2.6.x/drivers/pcmcia/Makefile | Makefile | gpl-2.0 | 2,454 |
/* New version of run front end support for simulators.
Copyright (C) 1997, 2004 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
#include <signal.h>
#include "sim-main.h"
#include "bfd.h"
#ifdef HAVE_ENVIRON
extern char **environ;
#endif
#ifdef HAVE_UNISTD_H
/* For chdir. */
#include <unistd.h>
#endif
static void usage (void);
extern host_callback default_callback;
static char *myname;
static SIM_DESC sd;
static RETSIGTYPE
cntrl_c (int sig)
{
if (! sim_stop (sd))
{
fprintf (stderr, "Quit!\n");
exit (1);
}
}
int
main (int argc, char **argv)
{
char *name;
char **prog_argv = NULL;
struct bfd *prog_bfd;
enum sim_stop reason;
int sigrc = 0;
int single_step = 0;
RETSIGTYPE (*prev_sigint) ();
myname = argv[0] + strlen (argv[0]);
while (myname > argv[0] && myname[-1] != '/')
--myname;
/* INTERNAL: When MYNAME is `step', single step the simulator
instead of allowing it to run free. The sole purpose of this
HACK is to allow the sim_resume interface's step argument to be
tested without having to build/run gdb. */
if (strlen (myname) > 4 && strcmp (myname - 4, "step") == 0)
{
single_step = 1;
}
/* Create an instance of the simulator. */
default_callback.init (&default_callback);
sd = sim_open (SIM_OPEN_STANDALONE, &default_callback, NULL, argv);
if (sd == 0)
exit (1);
if (STATE_MAGIC (sd) != SIM_MAGIC_NUMBER)
{
fprintf (stderr, "Internal error - bad magic number in simulator struct\n");
abort ();
}
/* We can't set the endianness in the callback structure until
sim_config is called, which happens in sim_open. */
default_callback.target_endian
= (CURRENT_TARGET_BYTE_ORDER == BIG_ENDIAN
? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
/* Was there a program to run? */
prog_argv = STATE_PROG_ARGV (sd);
prog_bfd = STATE_PROG_BFD (sd);
if (prog_argv == NULL || *prog_argv == NULL)
usage ();
name = *prog_argv;
/* For simulators that don't open prog during sim_open() */
if (prog_bfd == NULL)
{
prog_bfd = bfd_openr (name, 0);
if (prog_bfd == NULL)
{
fprintf (stderr, "%s: can't open \"%s\": %s\n",
myname, name, bfd_errmsg (bfd_get_error ()));
exit (1);
}
if (!bfd_check_format (prog_bfd, bfd_object))
{
fprintf (stderr, "%s: \"%s\" is not an object file: %s\n",
myname, name, bfd_errmsg (bfd_get_error ()));
exit (1);
}
}
if (STATE_VERBOSE_P (sd))
printf ("%s %s\n", myname, name);
/* Load the program into the simulator. */
if (sim_load (sd, name, prog_bfd, 0) == SIM_RC_FAIL)
exit (1);
/* Prepare the program for execution. */
#ifdef HAVE_ENVIRON
sim_create_inferior (sd, prog_bfd, prog_argv, environ);
#else
sim_create_inferior (sd, prog_bfd, prog_argv, NULL);
#endif
/* To accommodate relative file paths, chdir to sysroot now. We
mustn't do this until BFD has opened the program, else we wouldn't
find the executable if it has a relative file path. */
if (simulator_sysroot[0] != '\0' && chdir (simulator_sysroot) < 0)
{
fprintf (stderr, "%s: can't change directory to \"%s\"\n",
myname, simulator_sysroot);
exit (1);
}
/* Run/Step the program. */
if (single_step)
{
do
{
prev_sigint = signal (SIGINT, cntrl_c);
sim_resume (sd, 1/*step*/, 0);
signal (SIGINT, prev_sigint);
sim_stop_reason (sd, &reason, &sigrc);
if ((reason == sim_stopped) &&
(sigrc == sim_signal_to_host (sd, SIM_SIGINT)))
break; /* exit on control-C */
}
/* remain on breakpoint or signals in oe mode*/
while (((reason == sim_signalled) &&
(sigrc == sim_signal_to_host (sd, SIM_SIGTRAP))) ||
((reason == sim_stopped) &&
(STATE_ENVIRONMENT (sd) == OPERATING_ENVIRONMENT)));
}
else
{
do
{
#if defined (HAVE_SIGACTION) && defined (SA_RESTART)
struct sigaction sa, osa;
sa.sa_handler = cntrl_c;
sigemptyset (&sa.sa_mask);
sa.sa_flags = 0;
sigaction (SIGINT, &sa, &osa);
prev_sigint = osa.sa_handler;
#else
prev_sigint = signal (SIGINT, cntrl_c);
#endif
sim_resume (sd, 0, sigrc);
signal (SIGINT, prev_sigint);
sim_stop_reason (sd, &reason, &sigrc);
if ((reason == sim_stopped) &&
(sigrc == sim_signal_to_host (sd, SIM_SIGINT)))
break; /* exit on control-C */
/* remain on signals in oe mode */
} while ((reason == sim_stopped) &&
(STATE_ENVIRONMENT (sd) == OPERATING_ENVIRONMENT));
}
/* Print any stats the simulator collected. */
if (STATE_VERBOSE_P (sd))
sim_info (sd, 0);
/* Shutdown the simulator. */
sim_close (sd, 0);
/* If reason is sim_exited, then sigrc holds the exit code which we want
to return. If reason is sim_stopped or sim_signalled, then sigrc holds
the signal that the simulator received; we want to return that to
indicate failure. */
/* Why did we stop? */
switch (reason)
{
case sim_signalled:
case sim_stopped:
if (sigrc != 0)
fprintf (stderr, "program stopped with signal %d.\n", sigrc);
break;
case sim_exited:
break;
default:
fprintf (stderr, "program in undefined state (%d:%d)\n", reason, sigrc);
break;
}
return sigrc;
}
static void
usage ()
{
fprintf (stderr, "Usage: %s [options] program [program args]\n", myname);
fprintf (stderr, "Run `%s --help' for full list of options.\n", myname);
exit (1);
}
| ipwndev/DSLinux-Mirror | user/gdb/sim/common/nrun.c | C | gpl-2.0 | 6,142 |
<?php
/**
* Bottom Padding Control
*
* Outputs a jquery ui slider to allow the
* user to control the bottom padding of an
* element.
*
* @package Easy_Google_Fonts
* @author Sunny Johal - Titanium Themes <support@titaniumthemes.com>
* @license GPL-2.0+
* @link http://wordpress.org/plugins/easy-google-fonts/
* @copyright Copyright (c) 2015, Titanium Themes
* @version 1.3.6
*
*/
?>
<#
// Get settings and defaults.
var egfPaddingBottom = typeof egfSettings.padding_bottom !== "undefined" ? egfSettings.padding_bottom : data.egf_defaults.padding_bottom;
#>
<div class="egf-font-slider-control egf-padding-bottom-slider">
<span class="egf-slider-title"><?php _e( 'Bottom', 'easy-google-fonts' ); ?></span>
<div class="egf-font-slider-display">
<span>{{ egfPaddingBottom.amount }}{{ egfPaddingBottom.unit }}</span> | <a class="egf-font-slider-reset" href="#"><?php _e( 'Reset', 'easy-google-fonts' ); ?></a>
</div>
<div class="egf-clear" ></div>
<!-- Slider -->
<div class="egf-slider" value="{{ egfPaddingBottom.amount }}"></div>
<div class="egf-clear"></div>
</div>
| StabbyMcDuck/skillcrush_wordpress_starter_theme | wp-content/plugins/easy-google-fonts/views/customizer/control/positioning/padding/bottom.php | PHP | gpl-2.0 | 1,111 |
/**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
*
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*
*
* Credits goes to all Open Source Core Developer Groups listed below
* Please do not change here something, ragarding the developer credits, except the "developed by XXXX".
* Even if you edit a lot of files in this source, you still have no rights to call it as "your Core".
* Everybody knows that this Emulator Core was developed by Aion Lightning
* @-Aion-Unique-
* @-Aion-Lightning
* @Aion-Engine
* @Aion-Extreme
* @Aion-NextGen
* @Aion-Core Dev.
*/
package com.aionemu.gameserver.model.items;
import com.aionemu.commons.utils.Rnd;
import com.aionemu.gameserver.controllers.observer.ActionObserver;
import com.aionemu.gameserver.controllers.observer.ObserverType;
import com.aionemu.gameserver.dataholders.DataManager;
import com.aionemu.gameserver.model.gameobjects.Creature;
import com.aionemu.gameserver.model.gameobjects.Item;
import com.aionemu.gameserver.model.gameobjects.PersistentState;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.model.templates.item.GodstoneInfo;
import com.aionemu.gameserver.model.templates.item.ItemTemplate;
import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE;
import com.aionemu.gameserver.skillengine.SkillEngine;
import com.aionemu.gameserver.skillengine.model.Effect;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.skillengine.model.Skill;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author ATracer
* @Reworked Kill3r
*/
public class GodStone extends ItemStone {
private static final Logger log = LoggerFactory.getLogger(GodStone.class);
private final GodstoneInfo godstoneInfo;
private ActionObserver actionListener;
private final int probability;
private final int probabilityLeft;
private final ItemTemplate godItem;
public GodStone(int itemObjId, int itemId, PersistentState persistentState) {
super(itemObjId, itemId, 0, persistentState);
ItemTemplate itemTemplate = DataManager.ITEM_DATA.getItemTemplate(itemId);
godItem = itemTemplate;
godstoneInfo = itemTemplate.getGodstoneInfo();
if (godstoneInfo != null) {
probability = godstoneInfo.getProbability();
probabilityLeft = godstoneInfo.getProbabilityleft();
} else {
probability = 0;
probabilityLeft = 0;
log.warn("CHECKPOINT: Godstone info missing for item : " + itemId);
}
}
/**
* @param player
*/
public void onEquip(final Player player) {
if (godstoneInfo == null || godItem == null) {
return;
}
Item equippedItem = player.getEquipment().getEquippedItemByObjId(getItemObjId());
long equipmentSlot = equippedItem.getEquipmentSlot();
final int handProbability = equipmentSlot == ItemSlot.MAIN_HAND.getSlotIdMask() ? probability : probabilityLeft;
actionListener = new ActionObserver(ObserverType.ATTACK) {
@Override
public void attack(Creature creature) {
if (handProbability > Rnd.get(0, 1000)) {
Skill skill = SkillEngine.getInstance().getSkill(player, godstoneInfo.getSkillid(), godstoneInfo.getSkilllvl(), player.getTarget(), godItem);
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_SKILL_PROC_EFFECT_OCCURRED(skill.getSkillTemplate().getNameId()));
skill.setFirstTargetRangeCheck(false);
if (skill.canUseSkill()) {
Effect effect = new Effect(player, creature, skill.getSkillTemplate(), 1, 0, godItem);
effect.initialize();
effect.applyEffect();
effect = null;
}
}
}
};
player.getObserveController().addObserver(actionListener);
}
/**
* @param player
*/
public void onUnEquip(Player player) {
if (actionListener != null) {
player.getObserveController().removeObserver(actionListener);
}
}
}
| GiGatR00n/Aion-Core-v4.7.5 | AC-Game/src/com/aionemu/gameserver/model/items/GodStone.java | Java | gpl-2.0 | 4,983 |
##
# Copyright 2012-2021 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (FWO) (http://www.fwo.be/en)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# https://github.com/easybuilders/easybuild
#
# EasyBuild 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 v2.
#
# EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>.
##
"""
EasyBuild support for iompi compiler toolchain (includes Intel compilers (icc, ifort) and OpenMPI.
:author: Stijn De Weirdt (Ghent University)
:author: Kenneth Hoste (Ghent University)
"""
from distutils.version import LooseVersion
import re
from easybuild.toolchains.iccifort import IccIfort
from easybuild.toolchains.intel_compilers import IntelCompilersToolchain
from easybuild.toolchains.mpi.openmpi import OpenMPI
class Iompi(IccIfort, IntelCompilersToolchain, OpenMPI):
"""
Compiler toolchain with Intel compilers (icc/ifort) and OpenMPI.
"""
NAME = 'iompi'
# compiler-only subtoolchain can't be determine statically
# since depends on toolchain version (see below),
# so register both here as possible alternatives (which is taken into account elsewhere)
SUBTOOLCHAIN = [(IntelCompilersToolchain.NAME, IccIfort.NAME)]
def __init__(self, *args, **kwargs):
"""Constructor for Iompi toolchain class."""
super(Iompi, self).__init__(*args, **kwargs)
# make sure a non-symbolic version (e.g., 'system') is used before making comparisons using LooseVersion
if re.match('^[0-9]', self.version):
# need to transform a version like '2016a' with something that is safe to compare with '8.0', '2016.01'
# comparing subversions that include letters causes TypeErrors in Python 3
# 'a' is assumed to be equivalent with '.01' (January), and 'b' with '.07' (June)
# (good enough for this purpose)
self.iompi_ver = self.version.replace('a', '.01').replace('b', '.07')
if LooseVersion(self.iompi_ver) >= LooseVersion('2020.12'):
self.oneapi_gen = True
self.SUBTOOLCHAIN = IntelCompilersToolchain.NAME
self.COMPILER_MODULE_NAME = IntelCompilersToolchain.COMPILER_MODULE_NAME
else:
self.oneapi_gen = False
self.SUBTOOLCHAIN = IccIfort.NAME
self.COMPILER_MODULE_NAME = IccIfort.COMPILER_MODULE_NAME
else:
self.iompi_ver = self.version
self.oneapi_gen = False
def is_dep_in_toolchain_module(self, *args, **kwargs):
"""Check whether a specific software name is listed as a dependency in the module for this toolchain."""
if self.oneapi_gen:
res = IntelCompilersToolchain.is_dep_in_toolchain_module(self, *args, **kwargs)
else:
res = IccIfort.is_dep_in_toolchain_module(self, *args, **kwargs)
return res
def _set_compiler_vars(self):
"""Intel compilers-specific adjustments after setting compiler variables."""
if self.oneapi_gen:
IntelCompilersToolchain._set_compiler_vars(self)
else:
IccIfort._set_compiler_vars(self)
def set_variables(self):
"""Intel compilers-specific adjustments after setting compiler variables."""
if self.oneapi_gen:
IntelCompilersToolchain.set_variables(self)
else:
IccIfort.set_variables(self)
def is_deprecated(self):
"""Return whether or not this toolchain is deprecated."""
# need to transform a version like '2018b' with something that is safe to compare with '2019'
# comparing subversions that include letters causes TypeErrors in Python 3
# 'a' is assumed to be equivalent with '.01' (January), and 'b' with '.07' (June) (good enough for this purpose)
version = self.version.replace('a', '.01').replace('b', '.07')
# iompi toolchains older than iompi/2019a are deprecated since EasyBuild v4.5.0
# make sure a non-symbolic version (e.g., 'system') is used before making comparisons using LooseVersion
if re.match('^[0-9]', version) and LooseVersion(version) < LooseVersion('2019'):
deprecated = True
else:
deprecated = False
return deprecated
| hpcugent/easybuild-framework | easybuild/toolchains/iompi.py | Python | gpl-2.0 | 4,978 |
<?php
/**
* @copyright Copyright (c) 2009-2017 Ryan Demmer. All rights reserved
* @license GNU/GPL 2 or later - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* JCE is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses
*/
defined('_JEXEC') or die('RESTRICTED');
?>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onafterprint">onafterprint</label>
<div class="uk-form-controls uk-width-8-10"><input id="onafterprint" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onbeforeprint">onbeforeprint</label>
<div class="uk-form-controls uk-width-8-10"><input id="onbeforeprint" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onbeforeonload">onbeforeonload</label>
<div class="uk-form-controls uk-width-8-10"><input id="onbeforeonload" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onblur">onblur</label>
<div class="uk-form-controls uk-width-8-10"><input id="onblur" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onerror">onerror</label>
<div class="uk-form-controls uk-width-8-10"><input id="onerror" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onfocus">onfocus</label>
<div class="uk-form-controls uk-width-8-10"><input id="onfocus" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onhaschange">onhaschange</label>
<div class="uk-form-controls uk-width-8-10"><input id="onhaschange" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onload">onload</label>
<div class="uk-form-controls uk-width-8-10"><input id="onload" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onmessage">onmessage</label>
<div class="uk-form-controls uk-width-8-10"><input id="onmessage" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onoffline">onoffline</label>
<div class="uk-form-controls uk-width-8-10"><input id="onoffline" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="ononline">ononline</label>
<div class="uk-form-controls uk-width-8-10"><input id="ononline" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onpagehide">onpagehide</label>
<div class="uk-form-controls uk-width-8-10"><input id="onpagehide" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onpageshow">onpageshow</label>
<div class="uk-form-controls uk-width-8-10"><input id="onpageshow" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onpopstate">onpopstate</label>
<div class="uk-form-controls uk-width-8-10"><input id="onpopstate" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onredo">onredo</label>
<div class="uk-form-controls uk-width-8-10"><input id="onredo" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onresize">onresize</label>
<div class="uk-form-controls uk-width-8-10"><input id="onresize" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onstorage">onstorage</label>
<div class="uk-form-controls uk-width-8-10"><input id="onstorage" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onundo">onundo</label>
<div class="uk-form-controls uk-width-8-10"><input id="onundo" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onunloa">onunloa</label>
<div class="uk-form-controls uk-width-8-10"><input id="onunload" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onkeydown">onkeydown</label>
<div class="uk-form-controls uk-width-8-10"><input id="onkeydown" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onkeypress">onkeypress</label>
<div class="uk-form-controls uk-width-8-10"><input id="onkeypress" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onkeyu">onkeyu</label>
<div class="uk-form-controls uk-width-8-10"><input id="onkeyu" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onclick">onclick</label>
<div class="uk-form-controls uk-width-8-10"><input id="onclick" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="ondblclick">ondblclick</label>
<div class="uk-form-controls uk-width-8-10"><input id="ondblclick" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="ondrag">ondrag</label>
<div class="uk-form-controls uk-width-8-10"><input id="ondrag" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="ondragend">ondragend</label>
<div class="uk-form-controls uk-width-8-10"><input id="ondragend" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="ondragenter">ondragenter</label>
<div class="uk-form-controls uk-width-8-10"><input id="ondragenter" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="ondragleave">ondragleave</label>
<div class="uk-form-controls uk-width-8-10"><input id="ondragleave" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="ondragover">ondragover</label>
<div class="uk-form-controls uk-width-8-10"><input id="ondragover" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="ondragstart">ondragstart</label>
<div class="uk-form-controls uk-width-8-10"><input id="ondragstart" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="ondrop">ondrop</label>
<div class="uk-form-controls uk-width-8-10"><input id="ondrop" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onmousedown">onmousedown</label>
<div class="uk-form-controls uk-width-8-10"><input id="onmousedown" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onmousemove">onmousemove</label>
<div class="uk-form-controls uk-width-8-10"><input id="onmousemove" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onmouseout">onmouseout</label>
<div class="uk-form-controls uk-width-8-10"><input id="onmouseout" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onmouseover">onmouseover</label>
<div class="uk-form-controls uk-width-8-10"><input id="onmouseover" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onmouseup">onmouseup</label>
<div class="uk-form-controls uk-width-8-10"><input id="onmouseup" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onmousewheel">onmousewheel</label>
<div class="uk-form-controls uk-width-8-10"><input id="onmousewheel" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onscroll">onscroll</label>
<div class="uk-form-controls uk-width-8-10"><input id="onscroll" class="html5" type="text" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="oncontextmenu">oncontextmenu</label>
<div class="uk-form-controls uk-width-8-10"><input id="oncontextmenu" type="text" class="html5" value="" /></div>
</div>
<!-- Form -->
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onblur">onblur</label>
<div class="uk-form-controls uk-width-8-10"><input id="onblur" type="text" class="form" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onchange">onchange</label>
<div class="uk-form-controls uk-width-8-10"><input id="onchange" type="text" class="form" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onfocus">onfocus</label>
<div class="uk-form-controls uk-width-8-10"><input id="onfocus" type="text" class="form" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onformchange">onformchange</label>
<div class="uk-form-controls uk-width-8-10"><input id="onformchange" type="text" class="html5 form" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onforminput">onforminput</label>
<div class="uk-form-controls uk-width-8-10"><input id="onforminput" type="text" class="html5 form" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="oninput">oninput</label>
<div class="uk-form-controls uk-width-8-10"><input id="oninput" type="text" class="html5 form" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="oninvalid">oninvalid</label>
<div class="uk-form-controls uk-width-8-10"><input id="oninvalid" type="text" class="html5 form" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onselect">onselect</label>
<div class="uk-form-controls uk-width-8-10"><input id="onselect" type="text" class="form" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onsubmit">onsubmit</label>
<div class="uk-form-controls uk-width-8-10"><input id="onsubmit" type="text" class="form" value="" /></div>
</div>
<!-- Media -->
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onabort">onabort</label>
<div class="uk-form-controls uk-width-8-10"><input id="onabort" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="oncanplay">oncanplay</label>
<div class="uk-form-controls uk-width-8-10"><input id="oncanplay" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="oncanplaythrough">oncanplaythrough</label>
<div class="uk-form-controls uk-width-8-10"><input id="oncanplaythrough" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="ondurationchange">ondurationchange</label>
<div class="uk-form-controls uk-width-8-10"><input id="ondurationchange" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onemptied">onemptied</label>
<div class="uk-form-controls uk-width-8-10"><input id="onemptied" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onended">onended</label>
<div class="uk-form-controls uk-width-8-10"><input id="onended" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onerror">onerror</label>
<div class="uk-form-controls uk-width-8-10"><input id="onerror" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onloadeddata">onloadeddata</label>
<div class="uk-form-controls uk-width-8-10"><input id="onloadeddata" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onloadedmetadata">onloadedmetadata</label>
<div class="uk-form-controls uk-width-8-10"><input id="onloadedmetadata" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onloadstart">onloadstart</label>
<div class="uk-form-controls uk-width-8-10"><input id="onloadstart" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onpause">onpause</label>
<div class="uk-form-controls uk-width-8-10"><input id="onpause" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onplay">onplay</label>
<div class="uk-form-controls uk-width-8-10"><input id="onplay" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onplaying">onplaying</label>
<div class="uk-form-controls uk-width-8-10"><input id="onplaying" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onprogress">onprogress</label>
<div class="uk-form-controls uk-width-8-10"><input id="onprogress" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onratechange">onratechange</label>
<div class="uk-form-controls uk-width-8-10"><input id="onratechange" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onreadystatechange">onreadystatechange</label>
<div class="uk-form-controls uk-width-8-10"><input id="onreadystatechange" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onseeked">onseeked</label>
<div class="uk-form-controls uk-width-8-10"><input id="onseeked" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onseeking">onseeking</label>
<div class="uk-form-controls uk-width-8-10"><input id="onseeking" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onstalled">onstalled</label>
<div class="uk-form-controls uk-width-8-10"><input id="onstalled" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onsuspend">onsuspend</label>
<div class="uk-form-controls uk-width-8-10"><input id="onsuspend" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="ontimeupdate">ontimeupdate</label>
<div class="uk-form-controls uk-width-8-10"><input id="ontimeupdate" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onvolumechange">onvolumechange</label>
<div class="uk-form-controls uk-width-8-10"><input id="onvolumechange" type="text" class="html5 media" value="" /></div>
</div>
<div class="uk-form-row">
<label class="uk-form-label uk-width-2-10" for="onwaiting">onwaiting</label>
<div class="uk-form-controls uk-width-8-10"><input id="onwaiting" type="text" class="html5 media" value="" /></div>
</div> | tkaniowski/bj25 | components/com_jce/editor/tiny_mce/plugins/xhtmlxtras/tmpl/events.php | PHP | gpl-2.0 | 17,919 |
/* Copyright (C) 1991, 1995, 1996 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C 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 the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
/* Close a stream. */
int
__fcloseall ()
{
/* Close all streams. */
register FILE *f;
for (f = __stdio_head; f != NULL; f = f->__next)
if (__validfp(f))
(void) fclose(f);
return 0;
}
weak_alias (__fcloseall, fcloseall)
| nslu2/glibc | stdio/fcloseall.c | C | gpl-2.0 | 1,202 |
require 'katello_test_helper'
module Actions
describe Katello::Repository::CloneYumMetadata do
include Dynflow::Testing
include Support::Actions::Fixtures
include FactoryBot::Syntax::Methods
let(:action_class) { ::Actions::Katello::Repository::CloneYumMetadata }
let(:metadata_gen) { ::Actions::Katello::Repository::MetadataGenerate }
let(:bulk_action) { ::Actions::BulkAction }
let(:environment_repo) { katello_repositories(:rhel_6_x86_64_dev) }
let(:archive_repo) { katello_repositories(:rhel_6_x86_64_dev_archive) }
it 'plans to clone the metadata' do
action = create_action(action_class)
action.execution_plan.stub_planned_action(Katello::Repository::CheckMatchingContent) do |matching|
matching.stubs(output: { :matching_content => false})
end
plan_action(action, archive_repo, environment_repo)
matching_action = assert_action_planed_with(action, Katello::Repository::CheckMatchingContent,
:source_repo_id => archive_repo.id,
:target_repo_id => environment_repo.id)
assert_action_planed_with(action, Katello::Repository::IndexContent, :id => environment_repo.id)
assert_action_planed_with(action, Katello::Repository::MetadataGenerate, environment_repo,
:source_repository => archive_repo,
:matching_content => matching_action[0].output[:matching_content])
end
it 'plans to clone the metadata with force_yum_metadata_regeneration' do
action = create_action(action_class)
plan_action(action, archive_repo, environment_repo, :force_yum_metadata_regeneration => true)
refute_action_planed(action, Katello::Repository::CheckMatchingContent)
assert_action_planed_with(action, Katello::Repository::IndexContent, :id => environment_repo.id)
assert_action_planed_with(action, Katello::Repository::MetadataGenerate, environment_repo,
:source_repository => archive_repo,
:matching_content => nil)
end
it 'plans to clone the metadata if unprotected changed' do
action = create_action(action_class)
environment_repo.update_attributes!(:unprotected => !environment_repo.unprotected)
plan_action(action, archive_repo, environment_repo)
refute_action_planed(action, Katello::Repository::CheckMatchingContent)
assert_action_planed_with(action, Katello::Repository::IndexContent, :id => environment_repo.id)
assert_action_planed_with(action, Katello::Repository::MetadataGenerate, environment_repo,
:source_repository => archive_repo,
:matching_content => nil)
end
end
end
| stbenjam/katello | test/actions/katello/repository/clone_yum_metadata_test.rb | Ruby | gpl-2.0 | 2,811 |
/*
* Copyright (c) 2011, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_JFR_RECORDER_STACKTRACE_JFRSTACKTRACEREPOSITORY_HPP
#define SHARE_JFR_RECORDER_STACKTRACE_JFRSTACKTRACEREPOSITORY_HPP
#include "jfr/recorder/stacktrace/jfrStackTrace.hpp"
#include "jfr/utilities/jfrAllocation.hpp"
#include "jfr/utilities/jfrTypes.hpp"
class JavaThread;
class JfrCheckpointWriter;
class JfrChunkWriter;
class JfrStackTraceRepository : public JfrCHeapObj {
friend class JfrRecorder;
friend class JfrRecorderService;
friend class JfrThreadSampleClosure;
friend class ObjectSampleCheckpoint;
friend class ObjectSampler;
friend class StackTraceBlobInstaller;
friend class StackTraceRepository;
private:
static const u4 TABLE_SIZE = 2053;
JfrStackTrace* _table[TABLE_SIZE];
traceid _next_id;
u4 _entries;
JfrStackTraceRepository();
static JfrStackTraceRepository& instance();
static JfrStackTraceRepository* create();
static void destroy();
bool initialize();
bool is_modified() const;
size_t write(JfrChunkWriter& cw, bool clear);
size_t clear();
const JfrStackTrace* lookup(unsigned int hash, traceid id) const;
traceid add_trace(const JfrStackTrace& stacktrace);
static traceid add(const JfrStackTrace& stacktrace);
traceid record_for(JavaThread* thread, int skip, JfrStackFrame* frames, u4 max_frames);
public:
static traceid record(Thread* thread, int skip = 0);
static void record_and_cache(JavaThread* thread, int skip = 0);
};
#endif // SHARE_JFR_RECORDER_STACKTRACE_JFRSTACKTRACEREPOSITORY_HPP
| md-5/jdk10 | src/hotspot/share/jfr/recorder/stacktrace/jfrStackTraceRepository.hpp | C++ | gpl-2.0 | 2,551 |
/*
* arch/arm/mach-msm/msm_flashlight.c - The flashlight driver
* Copyright (C) 2009 HTC Corporation
*
* 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 <asm/gpio.h>
#include <linux/delay.h>
#include <linux/earlysuspend.h>
#include <linux/platform_device.h>
#include <mach/msm_flashlight.h>
#include <mach/msm_iomap.h>
#include <asm/io.h>
#include <linux/leds.h>
#include <linux/hrtimer.h>
#include <linux/wakelock.h>
#include <linux/slab.h>
#include <mach/htc_battery.h>
struct flashlight_struct {
struct led_classdev fl_lcdev;
struct early_suspend early_suspend_flashlight;
struct hrtimer timer;
struct wake_lock wake_lock;
spinlock_t spin_lock;
uint32_t gpio_torch;
uint32_t gpio_flash;
uint32_t gpio_flash_adj;
uint32_t flash_sw_timeout_ms;
enum flashlight_mode_flags mode_status;
unsigned long spinlock_flags;
unsigned flash_adj_gpio_status;
/* inactive: 0x0
* active: 0x1
* force disable flashlight function: 0x2 */
uint8_t flash_adj_value;
uint8_t led_count;
};
/* disable it, we didn't need to adjust GPIO */
/* #define FLASHLIGHT_ADJ_FUNC */
static struct flashlight_struct *this_fl_str;
static void flashlight_hw_command(uint8_t addr, uint8_t data)
{
uint8_t loop_i, loop_j;
const uint8_t fl_addr_to_rising_count[4] = { 17, 18, 19, 20 };
uint8_t loop_tmp;
if (!this_fl_str->gpio_torch && !this_fl_str->gpio_flash) {
printk(KERN_ERR "%s: not setup GPIO??? torch: %d, flash: %d\n",
__func__, this_fl_str->gpio_torch,
this_fl_str->gpio_flash);
return;
}
for (loop_j = 0; loop_j < 2; loop_j++) {
if (!loop_j)
loop_tmp = fl_addr_to_rising_count[addr];
else
loop_tmp = data;
for (loop_i = 0; loop_i < loop_tmp; loop_i++) {
gpio_direction_output(this_fl_str->gpio_torch, 0);
udelay(2);
gpio_direction_output(this_fl_str->gpio_torch, 1);
udelay(2);
}
udelay(500);
}
}
static void flashlight_turn_off(void)
{
gpio_direction_output(this_fl_str->gpio_flash, 0);
gpio_direction_output(this_fl_str->gpio_torch, 0);
this_fl_str->mode_status = FL_MODE_OFF;
this_fl_str->fl_lcdev.brightness = LED_OFF;
}
static enum hrtimer_restart flashlight_hrtimer_func(struct hrtimer *timer)
{
struct flashlight_struct *fl_str = container_of(timer,
struct flashlight_struct, timer);
wake_unlock(&fl_str->wake_lock);
spin_lock_irqsave(&fl_str->spin_lock, fl_str->spinlock_flags);
flashlight_turn_off();
spin_unlock_irqrestore(&fl_str->spin_lock, fl_str->spinlock_flags);
printk(KERN_INFO "%s: turn off flash mode\n", __func__);
return HRTIMER_NORESTART;
}
int aat1271_flashlight_control(int mode)
{
int ret = 0;
uint32_t flash_ns = ktime_to_ns(ktime_get());
#if 0 /* disable flash_adj_value check now */
if (this_fl_str->flash_adj_value == 2) {
printk(KERN_WARNING "%s: force disable function!\n", __func__);
return -EIO;
}
#endif
#if 0 /* disable this for DEATH_RAY */
if (this_fl_str->mode_status == mode) {
printk(KERN_INFO "%s: mode is same: %d\n",
FLASHLIGHT_NAME, mode);
if (!hrtimer_active(&this_fl_str->timer) &&
this_fl_str->mode_status == FL_MODE_OFF) {
pr_info("flashlight hasn't been enable or" \
"has already reset to 0 due to timeout\n");
return ret;
}
else
return -EINVAL;
}
#endif
spin_lock_irqsave(&this_fl_str->spin_lock,
this_fl_str->spinlock_flags);
if (this_fl_str->mode_status == FL_MODE_FLASH) {
hrtimer_cancel(&this_fl_str->timer);
wake_unlock(&this_fl_str->wake_lock);
flashlight_turn_off();
}
switch (mode) {
case FL_MODE_OFF:
flashlight_turn_off();
break;
case FL_MODE_TORCH:
flashlight_hw_command(3, 3);
flashlight_hw_command(0, 6);
flashlight_hw_command(2, 4);
this_fl_str->mode_status = FL_MODE_TORCH;
this_fl_str->fl_lcdev.brightness = LED_HALF;
break;
case FL_MODE_TORCH_LED_A:
flashlight_hw_command(3, 1);
flashlight_hw_command(0, 15);
flashlight_hw_command(2, 3);
this_fl_str->mode_status = FL_MODE_TORCH_LED_A;
this_fl_str->fl_lcdev.brightness = 1;
break;
case FL_MODE_TORCH_LED_B:
flashlight_hw_command(3, 1);
flashlight_hw_command(0, 15);
flashlight_hw_command(2, 2);
this_fl_str->mode_status = FL_MODE_TORCH_LED_B;
this_fl_str->fl_lcdev.brightness = 2;
break;
case FL_MODE_FLASH:
flashlight_hw_command(2, 4);
gpio_direction_output(this_fl_str->gpio_flash, 1);
this_fl_str->mode_status = FL_MODE_FLASH;
this_fl_str->fl_lcdev.brightness = LED_FULL;
hrtimer_start(&this_fl_str->timer,
ktime_set(this_fl_str->flash_sw_timeout_ms / 1000,
(this_fl_str->flash_sw_timeout_ms % 1000) *
NSEC_PER_MSEC), HRTIMER_MODE_REL);
wake_lock(&this_fl_str->wake_lock);
break;
case FL_MODE_PRE_FLASH:
flashlight_hw_command(3, 1);
flashlight_hw_command(0, 9);
flashlight_hw_command(2, 4);
this_fl_str->mode_status = FL_MODE_PRE_FLASH;
this_fl_str->fl_lcdev.brightness = LED_HALF + 1;
break;
case FL_MODE_TORCH_LEVEL_1:
flashlight_hw_command(3, 3);
flashlight_hw_command(0, 15);
flashlight_hw_command(2, 4);
this_fl_str->mode_status = FL_MODE_TORCH_LEVEL_1;
this_fl_str->fl_lcdev.brightness = LED_HALF - 2;
break;
case FL_MODE_TORCH_LEVEL_2:
flashlight_hw_command(3, 3);
flashlight_hw_command(0, 10);
flashlight_hw_command(2, 4);
this_fl_str->mode_status = FL_MODE_TORCH_LEVEL_2;
this_fl_str->fl_lcdev.brightness = LED_HALF - 1;
break;
case FL_MODE_DEATH_RAY:
pr_info("%s: death ray\n", __func__);
hrtimer_cancel(&this_fl_str->timer);
gpio_direction_output(this_fl_str->gpio_flash, 0);
udelay(40);
gpio_direction_output(this_fl_str->gpio_flash, 1);
this_fl_str->mode_status = 0;
this_fl_str->fl_lcdev.brightness = 3;
break;
default:
printk(KERN_ERR "%s: unknown flash_light flags: %d\n",
__func__, mode);
ret = -EINVAL;
break;
}
printk(KERN_DEBUG "%s: mode: %d, %u\n", FLASHLIGHT_NAME, mode,
flash_ns/(1000*1000));
spin_unlock_irqrestore(&this_fl_str->spin_lock,
this_fl_str->spinlock_flags);
return ret;
}
static void fl_lcdev_brightness_set(struct led_classdev *led_cdev,
enum led_brightness brightness)
{
struct flashlight_struct *fl_str;
enum flashlight_mode_flags mode;
fl_str = container_of(led_cdev, struct flashlight_struct, fl_lcdev);
if (brightness > 0 && brightness <= LED_HALF) {
/* Torch mode */
if (brightness == (LED_HALF - 2))
mode = FL_MODE_TORCH_LEVEL_1;
else if (brightness == (LED_HALF - 1))
mode = FL_MODE_TORCH_LEVEL_2;
else if (brightness == 1 && fl_str->led_count)
mode = FL_MODE_TORCH_LED_A;
else if (brightness == 2 && fl_str->led_count)
mode = FL_MODE_TORCH_LED_B;
else if (brightness == 3)
mode = FL_MODE_DEATH_RAY;
else
mode = FL_MODE_TORCH;
} else if (brightness > LED_HALF && brightness <= LED_FULL) {
/* Flashlight mode */
if (brightness == (LED_HALF + 1))
mode = FL_MODE_PRE_FLASH; /* pre-flash mode */
else
mode = FL_MODE_FLASH;
} else
/* off and else */
mode = FL_MODE_OFF;
aat1271_flashlight_control(mode);
return;
}
static void flashlight_early_suspend(struct early_suspend *handler)
{
struct flashlight_struct *fl_str = container_of(handler,
struct flashlight_struct, early_suspend_flashlight);
if (fl_str != NULL && fl_str->mode_status) {
spin_lock_irqsave(&fl_str->spin_lock, fl_str->spinlock_flags);
flashlight_turn_off();
spin_unlock_irqrestore(&fl_str->spin_lock,
fl_str->spinlock_flags);
}
}
static void flashlight_late_resume(struct early_suspend *handler)
{
/*
struct flashlight_struct *fl_str = container_of(handler,
struct flashlight_struct, early_suspend_flashlight);
*/
}
static int flashlight_setup_gpio(struct flashlight_platform_data *flashlight,
struct flashlight_struct *fl_str)
{
int ret = 0;
if (flashlight->gpio_init)
flashlight->gpio_init();
if (flashlight->torch) {
ret = gpio_request(flashlight->torch, "fl_torch");
if (ret < 0) {
printk(KERN_ERR "%s: gpio_request(torch) failed\n",
__func__);
return ret;
}
fl_str->gpio_torch = flashlight->torch;
}
if (flashlight->flash) {
ret = gpio_request(flashlight->flash, "fl_flash");
if (ret < 0) {
printk(KERN_ERR "%s: gpio_request(flash) failed\n",
__func__);
return ret;
}
fl_str->gpio_flash = flashlight->flash;
}
if (flashlight->flash_adj) {
ret = gpio_request(flashlight->flash_adj, "fl_flash_adj");
if (ret < 0) {
printk(KERN_ERR "%s: gpio_request(flash_adj) failed\n",
__func__);
return ret;
}
fl_str->gpio_flash_adj = flashlight->flash_adj;
gpio_set_value(fl_str->gpio_flash_adj, 0);
fl_str->flash_adj_gpio_status = 0;
printk(KERN_DEBUG "%s: enable flash_adj function\n",
FLASHLIGHT_NAME);
}
if (flashlight->flash_duration_ms)
fl_str->flash_sw_timeout_ms = flashlight->flash_duration_ms;
else /* load default value */
fl_str->flash_sw_timeout_ms = 600;
return ret;
}
static int flashlight_free_gpio(struct flashlight_platform_data *flashlight,
struct flashlight_struct *fl_str)
{
int ret = 0;
if (fl_str->gpio_torch) {
gpio_free(flashlight->torch);
fl_str->gpio_torch = 0;
}
if (fl_str->gpio_flash) {
gpio_free(flashlight->flash);
fl_str->gpio_flash = 0;
}
if (fl_str->gpio_flash_adj) {
gpio_free(flashlight->flash_adj);
fl_str->gpio_flash_adj = 0;
}
return ret;
}
#ifdef FLASHLIGHT_ADJ_FUNC
static ssize_t show_flash_adj(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t length;
length = sprintf(buf, "%d\n", this_fl_str->flash_adj_value);
return length;
}
static ssize_t store_flash_adj(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
static int tmp, adj_tmp;
if ((buf[0] == '0' || buf[0] == '1' || buf[0] == '2')
&& buf[1] == '\n') {
spin_lock_irqsave(&this_fl_str->spin_lock,
this_fl_str->spinlock_flags);
tmp = buf[0] - 0x30;
if (tmp == this_fl_str->flash_adj_value) {
spin_unlock_irqrestore(&this_fl_str->spin_lock,
this_fl_str->spinlock_flags);
printk(KERN_NOTICE "%s: status is same(%d)\n",
__func__, this_fl_str->flash_adj_value);
return count;
}
adj_tmp = this_fl_str->gpio_flash_adj;
switch (tmp) {
case 2:
flashlight_turn_off();
break;
case 1:
/*
if (this_fl_str->flash_adj_gpio_status) {
gpio_set_value(adj_tmp, 0);
this_fl_str->flash_adj_gpio_status = 0;
}
*/
break;
case 0:
/*
if (!this_fl_str->flash_adj_gpio_status) {
gpio_set_value(adj_tmp, 1);
this_fl_str->flash_adj_gpio_status = 1;
}
*/
break;
}
this_fl_str->flash_adj_value = tmp;
spin_unlock_irqrestore(&this_fl_str->spin_lock,
this_fl_str->spinlock_flags);
}
return count;
}
static DEVICE_ATTR(flash_adj, 0666, show_flash_adj, store_flash_adj);
#endif
static int flashlight_probe(struct platform_device *pdev)
{
struct flashlight_platform_data *flashlight = pdev->dev.platform_data;
struct flashlight_struct *fl_str;
int err = 0;
fl_str = kzalloc(sizeof(struct flashlight_struct), GFP_KERNEL);
if (!fl_str) {
printk(KERN_ERR "%s: kzalloc fail !!!\n", __func__);
return -ENOMEM;
}
err = flashlight_setup_gpio(flashlight, fl_str);
if (err < 0) {
printk(KERN_ERR "%s: setup GPIO fail !!!\n", __func__);
goto fail_free_mem;
}
spin_lock_init(&fl_str->spin_lock);
wake_lock_init(&fl_str->wake_lock, WAKE_LOCK_SUSPEND, pdev->name);
fl_str->fl_lcdev.name = pdev->name;
fl_str->fl_lcdev.brightness_set = fl_lcdev_brightness_set;
fl_str->fl_lcdev.brightness = 0;
err = led_classdev_register(&pdev->dev, &fl_str->fl_lcdev);
if (err < 0) {
printk(KERN_ERR "failed on led_classdev_register\n");
goto fail_free_gpio;
}
#ifdef FLASHLIGHT_ADJ_FUNC
if (fl_str->gpio_flash_adj) {
printk(KERN_DEBUG "%s: flash_adj exist, create attr file\n",
__func__);
err = device_create_file(fl_str->fl_lcdev.dev,
&dev_attr_flash_adj);
if (err != 0)
printk(KERN_WARNING "dev_attr_flash_adj failed\n");
}
#endif
#ifdef CONFIG_HAS_EARLYSUSPEND
fl_str->early_suspend_flashlight.suspend = flashlight_early_suspend;
fl_str->early_suspend_flashlight.resume = flashlight_late_resume;
register_early_suspend(&fl_str->early_suspend_flashlight);
#endif
hrtimer_init(&fl_str->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
fl_str->timer.function = flashlight_hrtimer_func;
fl_str->led_count = flashlight->led_count;
this_fl_str = fl_str;
printk(KERN_INFO "%s: The Flashlight Driver is ready\n", __func__);
return 0;
fail_free_gpio:
wake_lock_destroy(&fl_str->wake_lock);
flashlight_free_gpio(flashlight, fl_str);
fail_free_mem:
kfree(fl_str);
printk(KERN_ERR "%s: The Flashlight driver is Failure\n", __func__);
return err;
}
static int flashlight_remove(struct platform_device *pdev)
{
struct flashlight_platform_data *flashlight = pdev->dev.platform_data;
flashlight_turn_off();
hrtimer_cancel(&this_fl_str->timer);
unregister_early_suspend(&this_fl_str->early_suspend_flashlight);
#ifdef FLASHLIGHT_ADJ_FUNC
if (this_fl_str->gpio_flash_adj) {
device_remove_file(this_fl_str->fl_lcdev.dev,
&dev_attr_flash_adj);
}
#endif
led_classdev_unregister(&this_fl_str->fl_lcdev);
wake_lock_destroy(&this_fl_str->wake_lock);
flashlight_free_gpio(flashlight, this_fl_str);
kfree(this_fl_str);
return 0;
}
static struct platform_driver flashlight_driver = {
.probe = flashlight_probe,
.remove = flashlight_remove,
.driver = {
.name = FLASHLIGHT_NAME,
.owner = THIS_MODULE,
},
};
static int __init flashlight_init(void)
{
return platform_driver_register(&flashlight_driver);
}
static void __exit flashlight_exit(void)
{
platform_driver_unregister(&flashlight_driver);
}
module_init(flashlight_init);
module_exit(flashlight_exit);
MODULE_DESCRIPTION("flash light driver");
MODULE_LICENSE("GPL");
| jznomoney/htc_spade_2.6.35 | arch/arm/mach-msm/msm_flashlight.c | C | gpl-2.0 | 14,328 |
/*
* Copyright(c) 2012, Analogix Semiconductor. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/slimport.h>
#include "slimport7816_tx_drv.h"
#include "slimport7816_tx_reg.h"
#ifdef CONFIG_MACH_LGE
#include <soc/qcom/lge/board_lge.h>
#endif
#define SLIMPORT_DRV_DEBUG
#ifndef XTAL_CLK_DEF
#define XTAL_CLK_DEF XTAL_27M
#endif
#define XTAL_CLK_M10 pXTAL_data[XTAL_CLK_DEF].xtal_clk_m10
#define XTAL_CLK pXTAL_data[XTAL_CLK_DEF].xtal_clk
static unchar sp_tx_test_bw;
static bool sp_tx_test_lt;
static bool sp_tx_test_edid;
/* static unsigned char ext_int_index; */
static unsigned char g_changed_bandwidth;
static unsigned char sp_rx_bandwidth;
static unsigned char g_hdmi_dvi_status;
static unsigned char g_need_clean_status;
/* HDCP switch for external block*/
/* external_block_en = 1: enable, 0: disable*/
extern int external_block_en;
extern int hdcp_disable;
#ifdef ENABLE_READ_EDID
unsigned char g_edid_break;
unsigned char g_edid_checksum;
unchar edid_blocks[256];
static unsigned char g_read_edid_flag;
#endif
static struct Packet_AVI sp_tx_packet_avi;
static struct Packet_SPD sp_tx_packet_spd;
static struct Packet_MPEG sp_tx_packet_mpeg;
static struct AudiInfoframe sp_tx_audioinfoframe;
enum SP_TX_System_State sp_tx_system_state;
enum RX_CBL_TYPE sp_tx_rx_type;
enum CHARGING_STATUS downstream_charging_status; /* xjh add for charging */
enum AUDIO_OUTPUT_STATUS sp_tx_ao_state;
enum VIDEO_OUTPUT_STATUS sp_tx_vo_state;
enum SINK_CONNECTION_STATUS sp_tx_sc_state;
enum SP_TX_LT_STATUS sp_tx_LT_state;
enum SP_TX_System_State sp_tx_system_state_bak;
#ifndef HDCP_AUTO_EN
enum HDCP_STATUS HDCP_state;
#endif
uint chipid_list[CO3_NUMS] = {
0x7818,
0x7816,
0x7812,
0x7810,
0x7806,
0x7802
};
#ifdef SP_REGISTER_SET_TEST
unchar val_SP_TX_LT_CTRL_REG0;
unchar val_SP_TX_LT_CTRL_REG1;
unchar val_SP_TX_LT_CTRL_REG2;
unchar val_SP_TX_LT_CTRL_REG3;
unchar val_SP_TX_LT_CTRL_REG4;
unchar val_SP_TX_LT_CTRL_REG5;
unchar val_SP_TX_LT_CTRL_REG6;
unchar val_SP_TX_LT_CTRL_REG7;
unchar val_SP_TX_LT_CTRL_REG8;
unchar val_SP_TX_LT_CTRL_REG9;
unchar val_SP_TX_LT_CTRL_REG10;
unchar val_SP_TX_LT_CTRL_REG11;
unchar val_SP_TX_LT_CTRL_REG12;
unchar val_SP_TX_LT_CTRL_REG13;
unchar val_SP_TX_LT_CTRL_REG14;
unchar val_SP_TX_LT_CTRL_REG15;
unchar val_SP_TX_LT_CTRL_REG16;
unchar val_SP_TX_LT_CTRL_REG17;
unchar val_SP_TX_LT_CTRL_REG18;
unchar val_SP_TX_LT_CTRL_REG19;
#endif
struct COMMON_INT common_int_status;
struct HDMI_RX_INT hdmi_rx_int_status;
#define COMMON_INT1 common_int_status.common_int[0]
#define COMMON_INT2 common_int_status.common_int[1]
#define COMMON_INT3 common_int_status.common_int[2]
#define COMMON_INT4 common_int_status.common_int[3]
#define COMMON_INT5 common_int_status.common_int[4]
#define COMMON_INT_CHANGED common_int_status.change_flag
#define HDMI_RX_INT1 hdmi_rx_int_status.hdmi_rx_int[0]
#define HDMI_RX_INT2 hdmi_rx_int_status.hdmi_rx_int[1]
#define HDMI_RX_INT3 hdmi_rx_int_status.hdmi_rx_int[2]
#define HDMI_RX_INT4 hdmi_rx_int_status.hdmi_rx_int[3]
#define HDMI_RX_INT5 hdmi_rx_int_status.hdmi_rx_int[4]
#define HDMI_RX_INT6 hdmi_rx_int_status.hdmi_rx_int[5]
#define HDMI_RX_INT7 hdmi_rx_int_status.hdmi_rx_int[6]
#define HDMI_RX_INT_CHANGED hdmi_rx_int_status.change_flag
static unchar down_sample_en = 0;
static unsigned char __i2c_read_byte(unsigned char dev,unsigned char offset);
static void hardware_power_ctl(unchar enable);
static void hdmi_rx_new_vsi_int(void);
#define sp_tx_aux_polling_enable() sp_write_reg_or(TX_P0, TX_DEBUG1, POLLING_EN)
#define sp_tx_aux_polling_disable() sp_write_reg_and(TX_P0, TX_DEBUG1, ~POLLING_EN)
#define reg_bit_ctl(addr, offset, data, enable) \
do { \
unchar c; \
sp_read_reg(addr, offset, &c); \
if (enable) { \
if ((c & data) != data) { \
c |= data; \
sp_write_reg(addr, offset, c); \
} \
} else { \
if ((c & data) == data) { \
c &= ~data; \
sp_write_reg(addr, offset, c); \
} \
} \
} while (0)
#define sp_tx_video_mute(enable) \
reg_bit_ctl(TX_P2, VID_CTRL1, VIDEO_MUTE, enable)
#define hdmi_rx_mute_audio(enable) \
reg_bit_ctl(RX_P0, RX_MUTE_CTRL, AUD_MUTE, enable)
#define hdmi_rx_mute_video(enable) \
reg_bit_ctl(RX_P0, RX_MUTE_CTRL, VID_MUTE, enable)
#define sp_tx_addronly_set(enable) \
reg_bit_ctl(TX_P0, AUX_CTRL2, ADDR_ONLY_BIT, enable)
#define sp_tx_set_link_bw(bw) \
sp_write_reg(TX_P0, SP_TX_LINK_BW_SET_REG, bw);
#define sp_tx_get_link_bw() \
__i2c_read_byte(TX_P0, SP_TX_LINK_BW_SET_REG)
#define sp_tx_get_pll_lock_status() \
((__i2c_read_byte(TX_P0, TX_DEBUG1) & DEBUG_PLL_LOCK) != 0 ? 1 : 0)
#define gen_M_clk_with_downspeading() \
sp_write_reg_or(TX_P0, SP_TX_M_CALCU_CTRL, M_GEN_CLK_SEL)
#define gen_M_clk_without_downspeading \
sp_write_reg_and(TX_P0, SP_TX_M_CALCU_CTRL, (~M_GEN_CLK_SEL))
#define hdmi_rx_set_hpd(enable) \
if((bool)enable) sp_write_reg_or(TX_P2, SP_TX_VID_CTRL3_REG, HPD_OUT); \
else sp_write_reg_and(TX_P2, SP_TX_VID_CTRL3_REG, ~HPD_OUT)
#define hdmi_rx_set_termination(enable) \
if ((bool)enable) sp_write_reg_and(RX_P0, HDMI_RX_TMDS_CTRL_REG7, ~TERM_PD); \
else sp_write_reg_or(RX_P0, HDMI_RX_TMDS_CTRL_REG7, TERM_PD)
#define sp_tx_get_rx_bw(pdata) \
sp_tx_aux_dpcdread_bytes(0x00, 0x00, DPCD_MAX_LINK_RATE, 1, pdata)
#define sp_tx_clean_hdcp_status() do { \
sp_write_reg(TX_P0, TX_HDCP_CTRL0, 0x03); \
sp_write_reg_or(TX_P0, TX_HDCP_CTRL0, RE_AUTH); \
mdelay(2); \
pr_info("%s %s : sp_tx_clean_hdcp_status \n", LOG_TAG, __func__); \
} while (0)
#define reg_hardware_reset() do { \
sp_write_reg_or(TX_P2, SP_TX_RST_CTRL_REG, HW_RST); \
sp_tx_clean_state_machine(); \
sp_tx_set_sys_state(STATE_SP_INITIALIZED); \
mdelay(500); \
}while(0)
#ifdef NEW_HDCP_CONTROL_LOGIC
unsigned char g_hdcp_cap_bak;
#endif
//===================================================================== =======
#define write_dpcd_addr(addrh, addrm, addrl) \
do { \
unchar temp; \
if (__i2c_read_byte(TX_P0, AUX_ADDR_7_0) != (unchar)addrl) \
sp_write_reg(TX_P0, AUX_ADDR_7_0, (unchar)addrl); \
if (__i2c_read_byte(TX_P0, AUX_ADDR_15_8) != (unchar)addrm) \
sp_write_reg(TX_P0, AUX_ADDR_15_8, (unchar)addrm); \
sp_read_reg(TX_P0, AUX_ADDR_19_16, &temp); \
if ((unchar)(temp & 0x0F) != ((unchar)addrh & 0x0F)) \
sp_write_reg(TX_P0, AUX_ADDR_19_16, (temp & 0xF0) | ((unchar)addrh)); \
} while (0)
#define sp_tx_set_sys_state(ss) \
do { \
pr_info("%s %s : set: clean_status: %x,\n ", LOG_TAG, __func__, (uint)g_need_clean_status); \
if((sp_tx_system_state >= STATE_LINK_TRAINING)&&(ss <STATE_LINK_TRAINING)) \
sp_write_reg_or(TX_P0, SP_TX_ANALOG_PD_REG, CH0_PD); \
sp_tx_system_state_bak = sp_tx_system_state; \
sp_tx_system_state = (unchar)ss; \
g_need_clean_status = 1; \
print_sys_state(sp_tx_system_state); \
} while (0)
#define goto_next_system_state() \
do { \
pr_info("%s %s : next: clean_status: %x,\n ", LOG_TAG, __func__, (uint)g_need_clean_status); \
sp_tx_system_state_bak = sp_tx_system_state; \
sp_tx_system_state++;\
print_sys_state(sp_tx_system_state); \
} while (0)
#define redo_cur_system_state() \
do { \
pr_info("%s %s : redo: clean_status: %x,\n ", LOG_TAG, __func__, (uint)g_need_clean_status); \
g_need_clean_status = 1; \
sp_tx_system_state_bak = sp_tx_system_state; \
print_sys_state(sp_tx_system_state); \
} while(0)
#define system_state_change_with_case(status) \
do{ \
if(sp_tx_system_state >= status) { \
pr_info("%s %s : change_case: clean_status: %xm,\n ", LOG_TAG, __func__, (uint)g_need_clean_status); \
if((sp_tx_system_state >= STATE_LINK_TRAINING)&&(status <STATE_LINK_TRAINING)) \
sp_write_reg_or(TX_P0, SP_TX_ANALOG_PD_REG, CH0_PD); \
g_need_clean_status = 1; \
sp_tx_system_state_bak = sp_tx_system_state; \
sp_tx_system_state = (unchar)status; \
print_sys_state(sp_tx_system_state); \
} \
} while (0)
#define sp_write_reg_or(address, offset, mask) \
sp_write_reg(address, offset, ((unsigned char)__i2c_read_byte(address, offset) | (mask)))
#define sp_write_reg_and(address, offset, mask) \
sp_write_reg(address, offset, ((unsigned char)__i2c_read_byte(address, offset) & (mask)))
#define sp_write_reg_and_or(address, offset, and_mask, or_mask) \
sp_write_reg(address, offset, (((unsigned char)__i2c_read_byte(address, offset)) & and_mask) | (or_mask))
#define sp_write_reg_or_and(address, offset, or_mask, and_mask) \
sp_write_reg(address, offset, (((unsigned char)__i2c_read_byte(address, offset)) | or_mask) & (and_mask))
unsigned char ANX_OUI[3] = { 0x00, 0x22, 0xB9 };
unsigned char is_anx_dongle(void)
{
unsigned char buf[3];
sp_tx_aux_dpcdread_bytes(0x00, 0x04, 0x00, 3, buf);
if (buf[0] == ANX_OUI[0] && buf[1] == ANX_OUI[1]
&& buf[2] == ANX_OUI[2]) {
return 1;
/* debug_puts("DPCD 400 show ANX-dongle"); */
}
/* just for ANX7730 */
sp_tx_aux_dpcdread_bytes(0x00, 0x05, 0x00, 3, buf);
if (buf[0] == ANX_OUI[0] && buf[1] == ANX_OUI[1]
&& buf[2] == ANX_OUI[2]) {
return 1;
/* debug_puts("DPCD 500 show ANX-dongle"); */
}
return 0;
}
static unsigned char __i2c_read_byte(unsigned char dev, unsigned char offset)
{
unsigned char temp;
sp_read_reg(dev, offset, &temp);
return temp;
}
void hardware_power_ctl(unchar enable)
{
//static unsigned char supply_power = 0;
//if(supply_power != enable)
// supply_power = enable;
//else
// return;
if(enable == 0) sp_tx_hardware_powerdown();
else sp_tx_hardware_poweron();
}
void wait_aux_op_finish(unchar * err_flag)
{
unchar cnt;
unchar c;
*err_flag = 0;
cnt = 150;
while (__i2c_read_byte(TX_P0, AUX_CTRL2) & AUX_OP_EN) {
mdelay(2);
if ((cnt--) == 0) {
pr_info("%s %s :aux operate failed!\n", LOG_TAG, __func__);
*err_flag = 1;
break;
}
}
sp_read_reg(TX_P0, SP_TX_AUX_STATUS, &c);
if (c & 0x0F) {
pr_info("%s %s : wait aux operation status %.2x\n", LOG_TAG, __func__, (uint)c);
*err_flag = 1;
}
}
//===================================================================== =======
void print_sys_state(unchar ss)
{
switch (ss) {
case STATE_INIT:
pr_info("%s %s : -STATE_INIT- \n", LOG_TAG, __func__);
break;
case STATE_WAITTING_CABLE_PLUG:
pr_info("%s %s : -STATE_WAITTING_CABLE_PLUG- \n", LOG_TAG, __func__);
break;
case STATE_SP_INITIALIZED:
pr_info("%s %s : -STATE_SP_INITIALIZED- \n", LOG_TAG, __func__);
break;
case STATE_SINK_CONNECTION:
pr_info("%s %s : -STATE_SINK_CONNECTION- \n", LOG_TAG, __func__);
break;
#ifdef ENABLE_READ_EDID
case STATE_PARSE_EDID:
pr_info("%s %s : -STATE_PARSE_EDID- \n", LOG_TAG, __func__);
break;
#endif
case STATE_LINK_TRAINING:
pr_info("%s %s : -STATE_LINK_TRAINING- \n", LOG_TAG, __func__);
break;
case STATE_VIDEO_OUTPUT:
pr_info("%s %s : -STATE_VIDEO_OUTPUT- \n", LOG_TAG, __func__);
break;
#ifndef HDCP_AUTO_EN
case STATE_HDCP_AUTH:
pr_info("%s %s : -STATE_HDCP_AUTH- \n", LOG_TAG, __func__);
break;
#endif
case STATE_AUDIO_OUTPUT:
pr_info("%s %s : -STATE_AUDIO_OUTPUT- \n", LOG_TAG, __func__);
break;
case STATE_PLAY_BACK:
pr_info("%s %s : -STATE_PLAY_BACK- \n", LOG_TAG, __func__);
break;
default:
pr_err("%s %s : system state is error1 \n", LOG_TAG, __func__);
break;
}
}
/* DPCD */
void sp_tx_rst_aux(void)
{
sp_tx_aux_polling_disable();
sp_write_reg_or(TX_P2, RST_CTRL2, AUX_RST);
sp_write_reg_and(TX_P2, RST_CTRL2, ~AUX_RST);
sp_tx_aux_polling_enable();
}
unchar sp_tx_aux_dpcdread_bytes(unchar addrh, unchar addrm,
unchar addrl, unchar cCount, unchar *pBuf)
{
unchar c, c1, i;
unchar bOK;
sp_write_reg(TX_P0, BUF_DATA_COUNT, 0x80); /*clear buffer */
/* command and length */
c = ((cCount - 1) << 4) | 0x09;
sp_write_reg(TX_P0, AUX_CTRL, c);
write_dpcd_addr(addrh, addrm, addrl);
sp_write_reg_or(TX_P0, AUX_CTRL2, AUX_OP_EN);
mdelay(2);
wait_aux_op_finish(&bOK);
if (bOK == AUX_ERR) {
pr_err("%s %s : aux read failed\n", LOG_TAG, __func__);
/* add by span 20130217. */
sp_read_reg(TX_P2, SP_TX_INT_STATUS1, &c);
sp_read_reg(TX_P0, TX_DEBUG1, &c1);
/* if polling is enabled, wait polling error interrupt */
if (c1&POLLING_EN) {
if (c & POLLING_ERR)
sp_tx_rst_aux();
} else
sp_tx_rst_aux();
return AUX_ERR;
}
for (i = 0; i < cCount; i++) {
sp_read_reg(TX_P0, BUF_DATA_0 + i, &c);
*(pBuf + i) = c;
if (i >= MAX_BUF_CNT)
break;
}
return AUX_OK;
}
EXPORT_SYMBOL(sp_tx_aux_dpcdread_bytes);
unchar sp_tx_aux_dpcdwrite_bytes(unchar addrh, unchar addrm, unchar addrl, unchar cCount, unchar *pBuf)
{
unchar c, i,ret;
c = ((cCount - 1) << 4) | 0x08;
sp_write_reg(TX_P0, AUX_CTRL, c);
write_dpcd_addr(addrh, addrm, addrl);
for (i = 0; i < cCount; i++) {
c = *pBuf;
pBuf++;
sp_write_reg(TX_P0, BUF_DATA_0 + i, c);
if (i >= 15)
break;
}
sp_write_reg_or(TX_P0, AUX_CTRL2, AUX_OP_EN);
wait_aux_op_finish(&ret);
return ret;
}
unchar sp_tx_aux_dpcdwrite_byte(unchar addrh, unchar addrm, unchar addrl, unchar data1)
{
unchar ret;
sp_write_reg(TX_P0, AUX_CTRL, 0x08);//one byte write.
write_dpcd_addr(addrh, addrm, addrl);
sp_write_reg(TX_P0, BUF_DATA_0, data1);
sp_write_reg_or(TX_P0, AUX_CTRL2, AUX_OP_EN);
wait_aux_op_finish(&ret);
return ret;
}
/* ========initialized system */
void slimport_block_power_ctrl(enum SP_TX_POWER_BLOCK sp_tx_pd_block, unchar power)
{
if (power == SP_POWER_ON)
sp_write_reg_and(TX_P2, SP_POWERD_CTRL_REG, (~sp_tx_pd_block));
else
sp_write_reg_or(TX_P2, SP_POWERD_CTRL_REG, (sp_tx_pd_block));
pr_info("%s %s : sp_tx_power_on: %.2x\n", LOG_TAG, __func__, (uint)sp_tx_pd_block);
}
void vbus_power_ctrl(unsigned char ON)
{
unchar i;
if (ON == 0) {
/* sp_tx_aux_polling_disable(); */
sp_write_reg_and(TX_P2, TX_PLL_FILTER, ~V33_SWITCH_ON);
sp_write_reg_or(TX_P2, TX_PLL_FILTER5, P5V_PROTECT_PD | SHORT_PROTECT_PD);
pr_info("%s %s : 3.3V output disabled\n", LOG_TAG, __func__);
} else {
for (i = 0; i < 5; i++) {
sp_write_reg_and(TX_P2, TX_PLL_FILTER5, (~P5V_PROTECT_PD & ~SHORT_PROTECT_PD));
sp_write_reg_or(TX_P2, TX_PLL_FILTER, V33_SWITCH_ON);
if (!((unchar)__i2c_read_byte(TX_P2, TX_PLL_FILTER5) & 0xc0)) {
pr_info("%s %s : 3.3V output enabled\n", LOG_TAG, __func__);
break;
} else {
pr_info("%s %s : VBUS power can not be supplied\n", LOG_TAG, __func__);
}
}
}
}
void system_power_ctrl(unchar enable)
{
vbus_power_ctrl(enable);
slimport_block_power_ctrl(SP_TX_PWR_REG, enable);
slimport_block_power_ctrl(SP_TX_PWR_TOTAL, enable);
hardware_power_ctl(enable);
sp_tx_clean_state_machine();
sp_tx_set_sys_state(STATE_WAITTING_CABLE_PLUG);
}
void sp_tx_clean_state_machine(void)
{
sp_tx_system_state = STATE_INIT;
sp_tx_system_state_bak = STATE_INIT;
sp_tx_sc_state = SC_INIT;
sp_tx_LT_state = LT_INIT;
#ifndef HDCP_AUTO_EN
HDCP_state = HDCP_CAPABLE_CHECK;
#endif
sp_tx_vo_state = VO_WAIT_VIDEO_STABLE;
sp_tx_ao_state = AO_INIT;
}
enum CHARGING_STATUS downstream_charging_status_get(void) /* xjh add for charging */
{
return downstream_charging_status;
}
void downstream_charging_status_set(void)
{
unchar c1;
if (AUX_OK == sp_tx_aux_dpcdread_bytes
(0x00, 0x05, 0x22, 1, &c1)) {
if ((c1&0x01) == 0x00) {
downstream_charging_status = FAST_CHARGING;
sp_write_reg_or(TX_P2, TX_ANALOG_CTRL, SHORT_DPDM);
pr_info("%s %s : fast charging!\n", LOG_TAG, __func__);
} else {
downstream_charging_status = NO_FAST_CHARGING;
sp_write_reg_and(TX_P2, TX_ANALOG_CTRL, ~SHORT_DPDM);
pr_info("%s %s : no charging!\n", LOG_TAG, __func__);
}
}
}
unchar sp_tx_cur_states(void)
{
return sp_tx_system_state;
}
unchar sp_tx_cur_cable_type(void)
{
return sp_tx_rx_type;
}
unchar sp_tx_cur_bw(void)
{
return g_changed_bandwidth;
}
void sp_tx_set_bw(unchar bw)
{
g_changed_bandwidth = bw;
}
unchar sp_rx_cur_bw(void)
{
return sp_rx_bandwidth;
}
void sp_tx_variable_init(void)
{
uint i;
sp_tx_system_state = STATE_INIT;
sp_tx_system_state_bak = STATE_INIT;
sp_tx_rx_type = DWN_STRM_IS_NULL;
#ifdef ENABLE_READ_EDID
g_edid_break = 0;
g_read_edid_flag = 0;
g_edid_checksum = 0;
for (i = 0; i < 256; i++)
edid_blocks[i] = 0;
#endif
sp_tx_LT_state = LT_INIT;
#ifndef HDCP_AUTO_EN
HDCP_state = HDCP_CAPABLE_CHECK;
#endif
g_need_clean_status = 0;
sp_tx_sc_state = SC_INIT;
sp_tx_vo_state = VO_WAIT_VIDEO_STABLE;
sp_tx_ao_state = AO_INIT;
g_changed_bandwidth = LINK_5P4G;
sp_rx_bandwidth = LINK_5P4G;
g_hdmi_dvi_status = HDMI_MODE;
sp_tx_test_lt = 0;
sp_tx_test_bw = 0;
sp_tx_test_edid = 0;
downstream_charging_status = NO_CHARGING_CAPABLE;
#ifdef NEW_HDCP_CONTROL_LOGIC
g_hdcp_cap_bak = 0;
#endif
}
static void hdmi_rx_tmds_phy_initialization(void)
{
sp_write_reg(RX_P0,HDMI_RX_TMDS_CTRL_REG2, 0xa9);
//sp_write_reg(RX_P0,HDMI_RX_TMDS_CTRL_REG4, 0x28);
//sp_write_reg(RX_P0,HDMI_RX_TMDS_CTRL_REG5, 0xe3);
sp_write_reg(RX_P0,HDMI_RX_TMDS_CTRL_REG7, 0x80);
//sp_write_reg(RX_P0,HDMI_RX_TMDS_CTRL_REG19, 0x00);
//sp_write_reg(RX_P0,HDMI_RX_TMDS_CTRL_REG21, 0x04);
//sp_write_reg(RX_P0,HDMI_RX_TMDS_CTRL_REG22, 0x38);
//HDMI RX PHY
sp_write_reg(RX_P0, HDMI_RX_TMDS_CTRL_REG1, 0x90);
sp_write_reg(RX_P0, HDMI_RX_TMDS_CTRL_REG6, 0x92);
sp_write_reg(RX_P0, HDMI_RX_TMDS_CTRL_REG20, 0xf2);
}
void hdmi_rx_initialization(void)
{
sp_write_reg(TX_P2, SP_TX_DP_ADDR_REG1, 0xbc);
sp_write_reg(RX_P0, RX_MUTE_CTRL, AUD_MUTE | VID_MUTE);
sp_write_reg_or(RX_P0, RX_CHIP_CTRL,
MAN_HDMI5V_DET | PLLLOCK_CKDT_EN | DIGITAL_CKDT_EN);
/* sp_write_reg_or(RX_P0, RX_AEC_CTRL, AVC_OE); */
sp_write_reg_or(RX_P0, RX_SRST, HDCP_MAN_RST | SW_MAN_RST |
TMDS_RST | VIDEO_RST);
sp_write_reg_and(RX_P0, RX_SRST, (~HDCP_MAN_RST) & (~SW_MAN_RST) &
(~TMDS_RST) & (~VIDEO_RST));
sp_write_reg_or(RX_P0, RX_AEC_EN0, AEC_EN06 | AEC_EN05); /* Sync detect change , GP set mute */
sp_write_reg_or(RX_P0, RX_AEC_EN2, AEC_EN21);
sp_write_reg_or(RX_P0, RX_AEC_CTRL, AVC_EN | AAC_OE | AAC_EN);
sp_write_reg_and(RX_P0, RX_SYS_PWDN1, ~PWDN_CTRL);
/*
//default value is 0x00
sp_write_reg(RX_P0, HDMI_RX_INT_MASK1_REG, 0x00);
sp_write_reg(RX_P0, HDMI_RX_INT_MASK2_REG, 0x00);
sp_write_reg(RX_P0, HDMI_RX_INT_MASK3_REG, 0x00);
sp_write_reg(RX_P0, HDMI_RX_INT_MASK4_REG, 0x00);
sp_write_reg(RX_P0, HDMI_RX_INT_MASK5_REG, 0x00);
sp_write_reg(RX_P0, HDMI_RX_INT_MASK6_REG, 0x00);
sp_write_reg(RX_P0, HDMI_RX_INT_MASK7_REG, 0x00);
*/
sp_write_reg_or(RX_P0, RX_VID_DATA_RNG, R2Y_INPUT_LIMIT);
#ifdef CEC_ENABLE
sp_write_reg(RX_P0, RX_CEC_CTRL, 0x09);
sp_write_reg(RX_P0, RX_CEC_SPEED, CEC_SPEED_27M);
sp_write_reg(TX_P0, SP_TX_DP_POLLING_PERIOD, 0x32); //50ms polling period
#endif
//add10, dvdd10 and avdd18 setting
sp_write_reg(RX_P0, 0x65, 0xc4);
sp_write_reg(RX_P0, 0x66, 0x18);
/* sp_write_reg(RX_P0, RX_CEC_CTRL, CEC_RX_EN); */
hdmi_rx_tmds_phy_initialization();
hdmi_rx_set_hpd(0);
hdmi_rx_set_termination(0);
pr_info("%s %s : HDMI Rx is initialized...\n", LOG_TAG, __func__);
}
static void sp_tx_link_phy_initialization(void)
{
sp_write_reg(TX_P2, 0xe1, 0x02);
#ifdef SP_REGISTER_SET_TEST
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG0, val_SP_TX_LT_CTRL_REG0);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG1, val_SP_TX_LT_CTRL_REG1);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG2, val_SP_TX_LT_CTRL_REG2);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG3, val_SP_TX_LT_CTRL_REG3);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG4, val_SP_TX_LT_CTRL_REG4);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG5, val_SP_TX_LT_CTRL_REG5);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG6, val_SP_TX_LT_CTRL_REG6);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG7, val_SP_TX_LT_CTRL_REG7);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG8, val_SP_TX_LT_CTRL_REG8);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG9, val_SP_TX_LT_CTRL_REG9);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG10, val_SP_TX_LT_CTRL_REG10);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG11, val_SP_TX_LT_CTRL_REG11);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG12, val_SP_TX_LT_CTRL_REG12);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG13, val_SP_TX_LT_CTRL_REG13);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG14, val_SP_TX_LT_CTRL_REG14);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG15, val_SP_TX_LT_CTRL_REG15);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG16, val_SP_TX_LT_CTRL_REG16);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG17, val_SP_TX_LT_CTRL_REG17);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG18, val_SP_TX_LT_CTRL_REG18);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG19, val_SP_TX_LT_CTRL_REG19);
#else
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG0, 0x01);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG1, 0x03);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG2, 0x57);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG3, 0x7f);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG4, 0x71);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG5, 0x6b);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG6, 0x7f);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG7, 0x73);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG8, 0x7f);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG9, 0x7F);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG10, 0x00);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG11, 0x00);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG12, 0x02);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG13, 0x00);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG14, 0x0c);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG15, 0x42);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG16, 0x1e);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG17, 0x3e);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG18, 0x72);
sp_write_reg(TX_P1, SP_TX_LT_CTRL_REG19, 0x7e);
#endif
}
struct clock_Data const pXTAL_data[XTAL_CLK_NUM] = {
{19, 192},
{24, 240},
{25, 250},
{26, 260},
{27, 270},
{38, 384},
{52, 520},
{27, 270},
};
void xtal_clk_sel(void)
{
pr_info("%s %s : define XTAL_CLK: %x\n ", LOG_TAG, __func__, (uint)XTAL_CLK_DEF);
sp_write_reg_and_or(TX_P2, TX_ANALOG_DEBUG2, (~0x3c), 0x3c & (XTAL_CLK_DEF << 2));
sp_write_reg(TX_P0, 0xEC, (unchar)(((uint)XTAL_CLK_M10)));
sp_write_reg(TX_P0, 0xED, (unchar)(((uint)XTAL_CLK_M10 & 0xFF00) >> 2) | XTAL_CLK);
sp_write_reg(TX_P0, I2C_GEN_10US_TIMER0, (unchar)(((uint)XTAL_CLK_M10)));
sp_write_reg(TX_P0, I2C_GEN_10US_TIMER1, (unchar)(((uint)XTAL_CLK_M10 & 0xFF00) >> 8));
sp_write_reg(TX_P0, 0xBF, (unchar)(((uint)XTAL_CLK - 1)));
/* CEC function need to change the value. */
sp_write_reg_and_or(RX_P0, 0x49, 0x07, (unchar)(((((uint)XTAL_CLK) >> 1) - 2) << 3));
/* sp_write_reg(RX_P0, 0x49, 0x5b);//cec test */
}
void sp_tx_initialization(void)
{
sp_write_reg(TX_P0, AUX_CTRL2, 0x30); /* xjh add set terminal reistor to 50ohm */
#ifndef HDCP_AUTO_EN
sp_write_reg_and(TX_P0, TX_HDCP_CTRL, (~AUTO_EN) & (~AUTO_START));
sp_write_reg(TX_P0, OTP_KEY_PROTECT1, OTP_PSW1);
sp_write_reg(TX_P0, OTP_KEY_PROTECT2, OTP_PSW2);
sp_write_reg(TX_P0, OTP_KEY_PROTECT3, OTP_PSW3);
sp_write_reg_or(TX_P0, HDCP_KEY_CMD, DISABLE_SYNC_HDCP);
#endif
sp_write_reg(TX_P2, SP_TX_VID_CTRL8_REG, VID_VRES_TH);
sp_write_reg(TX_P0, HDCP_AUTO_TIMER, HDCP_AUTO_TIMER_VAL);
sp_write_reg_or(TX_P0, TX_HDCP_CTRL, LINK_POLLING);
/* sp_write_reg_or(TX_P0, 0x65 , 0x30); */
sp_write_reg_or(TX_P0, TX_LINK_DEBUG , M_VID_DEBUG);
sp_write_reg_or(TX_P0, TX_DEBUG1, FORCE_HPD);
/* sp_tx_aux_polling_disable(); */
/*
sp_write_reg_or(TX_P2, TX_PLL_FILTER, AUX_TERM_50OHM);
sp_write_reg_and(TX_P2, TX_PLL_FILTER5,
(~P5V_PROTECT_PD) & (~SHORT_PROTECT_PD));
*/
sp_write_reg_or(TX_P2, TX_ANALOG_DEBUG2, POWERON_TIME_1P5MS);/* ..................... */
/*
sp_write_reg_or(TX_P0, TX_HDCP_CTRL0,
BKSV_SRM_PASS |KSVLIST_VLD);
*/
/* sp_write_reg(TX_P2, TX_ANALOG_CTRL, 0xC5); */
xtal_clk_sel();
sp_write_reg(TX_P0, AUX_DEFER_CTRL, 0x8C);
sp_write_reg_or(TX_P0, TX_DP_POLLING, AUTO_POLLING_DISABLE);
/*Short the link intergrity check timer to speed up bstatus
polling for HDCP CTS item 1A-07 */
sp_write_reg(TX_P0, SP_TX_LINK_CHK_TIMER, 0x1d);
sp_write_reg_or(TX_P0, TX_MISC, EQ_TRAINING_LOOP);
if (lge_get_boot_mode() != LGE_BOOT_MODE_QEM_56K) {
//power down main link by default
pr_err("%s: !LGE_BOOT_MODE_QEM_56K \n", __func__);
sp_write_reg_or(TX_P0, SP_TX_ANALOG_PD_REG, CH0_PD);
}
/*
sp_write_reg(TX_P2, SP_COMMON_INT_MASK1, 0X00);
sp_write_reg(TX_P2, SP_COMMON_INT_MASK2, 0X00);
sp_write_reg(TX_P2, SP_COMMON_INT_MASK3, 0X00);
sp_write_reg(TX_P2, SP_COMMON_INT_MASK4, 0X00);
*/
//sp_write_reg(TX_P2, SP_INT_MASK, 0X90);
sp_write_reg(TX_P2, SP_TX_INT_CTRL_REG, 0X01);
/*disable HDCP mismatch function for VGA dongle*/
#ifdef CONFIG_MACH_MSM8992_PPLUS
sp_write_reg(TX_P0, SP_TX_LT_SET_REG, 0x08); /* Swing : 1(400mv AMP), Pre-Emphasis : 2(6dB) */
#else
sp_write_reg(TX_P0, SP_TX_LT_SET_REG, 0);
#endif
sp_tx_link_phy_initialization();
gen_M_clk_with_downspeading();
down_sample_en = 0;
}
void slimport_chip_initial(void)
{
sp_tx_variable_init();
/* vbus_power_ctrl(0); */
hardware_power_ctl(0);
/* sp_tx_set_sys_state(STATE_CABLE_PLUG); */
}
bool slimport_chip_detect(void)
{
uint c;
unchar i;
bool big_endian;
unchar *ptemp;
/*check whether CPU is big endian*/
c = 0x1122;
ptemp = (unchar*)&c;
if(*ptemp == 0x11 && *(ptemp + 1) == 0x22)
big_endian = 1;
else
big_endian = 0;
hardware_power_ctl(1);
c = 0;
/*check chip id*/
if(big_endian) {
sp_read_reg(TX_P2, SP_TX_DEV_IDL_REG, (unchar *)(&c) + 1);
sp_read_reg(TX_P2, SP_TX_DEV_IDH_REG, (unchar *)(&c));
}else{
sp_read_reg(TX_P2, SP_TX_DEV_IDL_REG, (unchar *)(&c));
sp_read_reg(TX_P2, SP_TX_DEV_IDH_REG, (unchar *)(&c) + 1);
}
pr_info("%s %s : CHIPID: ANX%x\n", LOG_TAG, __func__, c & 0x0000FFFF);
for(i = 0; i < CO3_NUMS; i++){
if (c == chipid_list[i])
return 1;
}
return 0;
}
/* ========cable plug */
unchar is_cable_detected(void)
{
return slimport_is_connected();
/*
if(cable_detected()) {
mdelay(50);
return cable_detected();
}
return 0;
*/
}
void slimport_waitting_cable_plug_process(void)
{
if (is_cable_detected()) {
#ifdef CONFIG_SLIMPORT_DYNAMIC_HPD
slimport_set_hdmi_hpd(1);
#endif
hardware_power_ctl(1);
goto_next_system_state();
} else {
hardware_power_ctl(0);
}
}
static unchar sp_tx_get_cable_type(enum CABLE_TYPE_STATUS det_cable_type_state, bool bdelay)
{
unchar ds_port_preset;
unchar aux_status;
unchar data_buf[16];
unchar cur_cable_type;
ds_port_preset = 0;
cur_cable_type = DWN_STRM_IS_NULL;
downstream_charging_status = NO_CHARGING_CAPABLE; /* xjh add for charging */
aux_status = sp_tx_aux_dpcdread_bytes(0x00, 0x00, 0x05, 1, &ds_port_preset);
pr_info("%s %s : DPCD 0x005: %x \n", LOG_TAG, __func__, (int)ds_port_preset);
switch(det_cable_type_state)
{
case CHECK_AUXCH:
if(AUX_OK == aux_status) {
sp_tx_aux_dpcdread_bytes(0x00, 0x00, 0, 0x0c, data_buf);
det_cable_type_state = GETTED_CABLE_TYPE;
} else {
mdelay(50);
pr_err("%s %s : AUX access error\n", LOG_TAG, __func__);
break;
}
case GETTED_CABLE_TYPE:
switch ((ds_port_preset & (_BIT1 | _BIT2) ) >>1) {
case 0x00:
cur_cable_type = DWN_STRM_IS_DIGITAL;
pr_info("%s %s : Downstream is DP dongle.\n", LOG_TAG, __func__);
break;
case 0x01:
case 0x03:
cur_cable_type = DWN_STRM_IS_ANALOG;
downstream_charging_status = NO_FAST_CHARGING;
if(bdelay){
//eeprom_reload();
mdelay(150);
}
pr_info("%s %s : Downstream is general DP2VGA converter.\n", LOG_TAG, __func__);
break;
case 0x02:
sp_tx_aux_dpcdread_bytes(0x00, 0x05, 0x23, 1, data_buf); // add for charging
if((data_buf[0]&0x7f)>=0x15){ //version >= 2.1
downstream_charging_status = NO_FAST_CHARGING;
}
//sp_tx_send_message(MSG_OCM_EN);
cur_cable_type = DWN_STRM_IS_HDMI;
pr_info("%s %s : Downstream is HDMI dongle.\n", LOG_TAG, __func__);
break;
default:
cur_cable_type = DWN_STRM_IS_NULL;
pr_err("%s %s : Downstream can not recognized.\n", LOG_TAG, __func__);
break;
}
default:
break;
}
return cur_cable_type;
}
unchar sp_tx_get_hdmi_connection(void)
{
unchar c;
/* msleep(200); */ /* why delay here? 20130217? */
if(is_anx_dongle()){
if (AUX_OK != sp_tx_aux_dpcdread_bytes(0x00, 0x05, 0x18, 1, &c))
return 0;
if ((c & 0x41) == 0x41)
return 1;
else
return 0;
}else
return sp_tx_get_dp_connection();
}
unchar sp_tx_get_vga_connection(void)
{
unchar c;
if (AUX_OK != sp_tx_aux_dpcdread_bytes(0x00, 0x02, DPCD_SINK_COUNT, 1, &c)) {
pr_err("%s %s : aux error.\n", LOG_TAG, __func__);
return 0;
}
if (c & 0x01)
return 1;
else
return 0;
}
unchar sp_tx_get_dp_connection(void)
{
unchar c;
if (AUX_OK != sp_tx_aux_dpcdread_bytes(0x00, 0x02, DPCD_SINK_COUNT, 1, &c)){
return 0;
}
if (c & 0x1f) {
sp_tx_aux_dpcdread_bytes(0x00, 0x00, 0x04, 1, &c);
if (c & 0x20){
sp_tx_aux_dpcdread_bytes(0x00, 0x06, 0x00, 1, &c);
/*Bit 5 = SET_DN_DEVICE_DP_PWR_5V
Bit 6 = SET_DN_DEVICE_DP_PWR_12V
Bit 7 = SET_DN_DEVICE_DP_PWR_18V*/
c = c & 0x1F;
sp_tx_aux_dpcdwrite_byte(0x00, 0x06, 0x00, c | 0x20);
}
return 1;
} else
return 0;
}
unchar sp_tx_get_downstream_connection(void)
{
switch(sp_tx_rx_type) {
case DWN_STRM_IS_HDMI:
return sp_tx_get_hdmi_connection();
case DWN_STRM_IS_DIGITAL:
return sp_tx_get_dp_connection();
case DWN_STRM_IS_ANALOG:
case DWN_STRM_IS_VGA_9832:
return sp_tx_get_vga_connection();
case DWN_STRM_IS_NULL:
default:
return 0;
}
return 0;
}
void slimport_sink_connection(void)
{
if(check_cable_det_pin() ==0){
sp_tx_set_sys_state(STATE_WAITTING_CABLE_PLUG);
return;
}
switch(sp_tx_sc_state) {
case SC_INIT:
sp_tx_sc_state++;
case SC_CHECK_CABLE_TYPE:
case SC_WAITTING_CABLE_TYPE:
default:
sp_tx_rx_type = sp_tx_get_cable_type(CHECK_AUXCH, 1);
if(sp_tx_rx_type == DWN_STRM_IS_NULL) {
sp_tx_sc_state++;
if(sp_tx_sc_state >= SC_WAITTING_CABLE_TYPE){
sp_tx_sc_state = SC_NOT_CABLE;
pr_info("%s %s : Can not get cable type!\n", LOG_TAG, __func__);
}
break;
}
//dongle has fast charging detection capability
if(downstream_charging_status != NO_CHARGING_CAPABLE){
downstream_charging_status_set();
}
sp_tx_sc_state = SC_SINK_CONNECTED;
case SC_SINK_CONNECTED:
if(sp_tx_get_downstream_connection()){
#ifdef CEC_ENABLE
if(sp_tx_rx_type == DWN_STRM_IS_HDMI)
cec_init(); //for CEC
#endif
goto_next_system_state();
}
break;
case SC_NOT_CABLE:
vbus_power_ctrl(0);
reg_hardware_reset();
break;
}
}
/******************start EDID process********************/
void sp_tx_enable_video_input(unchar enable)
{
unchar c;
sp_read_reg(TX_P2, VID_CTRL1, &c);
if (enable) {
if ((c & VIDEO_EN) != VIDEO_EN) {
c = (c & 0xf7) | VIDEO_EN;
sp_write_reg(TX_P2, VID_CTRL1, c);
pr_info("%s %s : Slimport Video is enabled!\n", LOG_TAG, __func__);
}
} else {
if ((c & VIDEO_EN) == VIDEO_EN) {
c &= ~VIDEO_EN;
sp_write_reg(TX_P2, VID_CTRL1, c);
pr_info("%s %s : Slimport Video is disabled!\n", LOG_TAG, __func__);
}
}
}
void sp_tx_send_message(enum SP_TX_SEND_MSG message)
{
unchar c;
switch (message) {
default:
break;
case MSG_INPUT_HDMI:
if (sp_tx_rx_type == DWN_STRM_IS_HDMI)
sp_tx_aux_dpcdwrite_byte(0x00, 0x05, 0x26, 0x01);
break;
case MSG_INPUT_DVI:
if (sp_tx_rx_type == DWN_STRM_IS_HDMI)
sp_tx_aux_dpcdwrite_byte(0x00, 0x05, 0x26, 0x00);
break;
case MSG_CLEAR_IRQ:
/* pr_info("%s %s : clear irq start!\n", LOG_TAG, __func__); */
sp_tx_aux_dpcdread_bytes(0x00, 0x04, 0x10, 1, &c);
/* pr_info("%s %s : clear irq middle!\n", LOG_TAG, __func__); */
c |= 0x01;
sp_tx_aux_dpcdwrite_byte(0x00, 0x04, 0x10, c);
/* pr_info("%s %s : clear irq end!\n", LOG_TAG, __func__); */
break;
}
}
static unchar read_dvi_hdmi_mode(void)
{
unchar temp;
if (sp_tx_rx_type == DWN_STRM_IS_HDMI)
sp_tx_aux_dpcdread_bytes(0x00, 0x05, 0x26, 1, &temp);
else
temp = g_hdmi_dvi_status;
return temp;
}
#ifdef ENABLE_READ_EDID
static unchar get_edid_detail(unchar *data_buf)
{
uint pixclock_edid;
pixclock_edid = ((((uint)data_buf[1] << 8)) | ((uint)data_buf[0] & 0xFF));
pr_err("%s %s : =============pixclock via EDID : %d\n", LOG_TAG, __func__, (uint)pixclock_edid);
if (pixclock_edid <= 5300)
return LINK_1P62G;
else if ((5300 < pixclock_edid) && (pixclock_edid <= 8900))
return LINK_2P7G;
else if ((8900 < pixclock_edid) && (pixclock_edid <= 18000))
return LINK_5P4G;
else
return LINK_6P75G;
}
static unchar parse_edid_to_get_bandwidth(void)
{
unchar desc_offset = 0;
unchar i, bandwidth, temp;
bandwidth = LINK_1P62G;
temp = LINK_1P62G;
i = 0;
while (4 > i && 0 != edid_blocks[0x36+desc_offset]) {
temp = get_edid_detail(edid_blocks+0x36+desc_offset);
pr_err("%s %s : bandwidth via EDID : %x\n", LOG_TAG, __func__, (uint)temp);
if (bandwidth < temp)
bandwidth = temp;
if (bandwidth > LINK_5P4G) /* xjh mod2 >= */
break;
desc_offset += 0x12;
++i;
}
return bandwidth;
}
static void sp_tx_aux_wr(unchar offset)
{
sp_write_reg(TX_P0, BUF_DATA_0, offset);
sp_write_reg(TX_P0, AUX_CTRL, 0x04);
sp_write_reg_or(TX_P0, AUX_CTRL2, AUX_OP_EN);
wait_aux_op_finish(&g_edid_break);
}
static void sp_tx_aux_rd(unchar len_cmd)
{
sp_write_reg(TX_P0, AUX_CTRL, len_cmd);
sp_write_reg_or(TX_P0, AUX_CTRL2, AUX_OP_EN);
wait_aux_op_finish(&g_edid_break);
}
unchar sp_tx_get_edid_block(void)
{
unchar c;
sp_tx_aux_wr(0x7e);
sp_tx_aux_rd(0x01);
sp_read_reg(TX_P0, BUF_DATA_0, &c);
pr_info("%s %s : EDID Block = %d\n", LOG_TAG, __func__, (int)(c + 1));
if (c > 3)
c = 1;
/* g_edid_break = 1; */
return c;
}
void edid_read(unchar offset, unchar *pblock_buf)
{
unchar data_cnt, cnt;
unchar c;
sp_tx_aux_wr(offset);
sp_tx_aux_rd(0xf5); /* set I2C read com 0x05 mot = 1 and read 16 bytes */
data_cnt = 0;
cnt = 0;
while((data_cnt) < 16)
{
sp_read_reg(TX_P0, BUF_DATA_COUNT, &c);
/* if(c != 0x10)
pr_info("%s %s : edid read: len : %x \n", LOG_TAG, __func__, (uint)c); */
if ((c & 0x1f) != 0) {
data_cnt = data_cnt + c;
do {
sp_read_reg(TX_P0, BUF_DATA_0 + c - 1, &(pblock_buf[c - 1]));
/* pr_info("%s %s : index: %x, data: %x ", LOG_TAG, __func__, (uint)c, (uint)pblock_buf[c]); */
if (c == 1)
break;
} while (c--);
} else {
/* pr_info("%s %s : edid read : length: 0 \n", LOG_TAG, __func__); */
if (cnt++ <= 2) {
sp_tx_rst_aux();
c = 0x05 | ((0x0f - data_cnt) << 4);
sp_tx_aux_rd(c);
} else {
g_edid_break = 1;
break;
}
}
}
/* issue a stop every 16 bytes read */
sp_write_reg(TX_P0, AUX_CTRL, 0x01);
sp_write_reg_or(TX_P0, AUX_CTRL2, ADDR_ONLY_BIT | AUX_OP_EN);
wait_aux_op_finish(&g_edid_break);
sp_tx_addronly_set(0);
}
void sp_tx_edid_read_initial(void)
{
sp_write_reg(TX_P0, AUX_ADDR_7_0, 0x50);
sp_write_reg(TX_P0, AUX_ADDR_15_8, 0);
sp_write_reg_and(TX_P0, AUX_ADDR_19_16, 0xf0);
}
static void segments_edid_read(unchar segment, unchar offset)
{
unchar c, cnt;
int i;
sp_write_reg(TX_P0, AUX_CTRL, 0x04);
sp_write_reg(TX_P0, AUX_ADDR_7_0, 0x30);
sp_write_reg_or(TX_P0, AUX_CTRL2, ADDR_ONLY_BIT | AUX_OP_EN);
//sp_tx_addronly_set(0);
sp_read_reg(TX_P0, AUX_CTRL2, &c);
wait_aux_op_finish(&g_edid_break);
sp_read_reg(TX_P0, AUX_CTRL, &c);
sp_write_reg(TX_P0, BUF_DATA_0, segment);
/* set I2C write com 0x04 mot = 1 */
sp_write_reg(TX_P0, AUX_CTRL, 0x04);
sp_write_reg_and_or(TX_P0, AUX_CTRL2, ~ADDR_ONLY_BIT, AUX_OP_EN);
cnt = 0;
sp_read_reg(TX_P0, AUX_CTRL2, &c);
while(c&AUX_OP_EN)
{
mdelay(1);
cnt ++;
if(cnt == 10)
{
pr_info("%s %s : write break", LOG_TAG, __func__);
sp_tx_rst_aux();
cnt = 0;
g_edid_break = 1;
return; /* bReturn; */
}
sp_read_reg(TX_P0, AUX_CTRL2, &c);
}
sp_write_reg(TX_P0, AUX_ADDR_7_0, 0x50);
sp_tx_aux_wr(offset);
sp_tx_aux_rd(0xf5);
cnt = 0;
for(i=0; i<16; i++)
{
sp_read_reg(TX_P0, BUF_DATA_COUNT, &c);
while((c & 0x1f) == 0)
{
mdelay(2);
cnt ++;
sp_read_reg(TX_P0, BUF_DATA_COUNT, &c);
if(cnt == 10)
{
pr_info("%s %s : read break", LOG_TAG, __func__);
sp_tx_rst_aux();
g_edid_break = 1;
return;
}
}
sp_read_reg(TX_P0, BUF_DATA_0+i, &c);
}
sp_write_reg(TX_P0, AUX_CTRL, 0x01);
sp_write_reg_or(TX_P0, AUX_CTRL2, ADDR_ONLY_BIT | AUX_OP_EN);
sp_write_reg_and(TX_P0, AUX_CTRL2, ~ADDR_ONLY_BIT);
sp_read_reg(TX_P0, AUX_CTRL2, &c);
while(c & AUX_OP_EN)
sp_read_reg(TX_P0, AUX_CTRL2, &c);
/* sp_tx_addronly_set(0); */
}
static bool edid_checksum_result(unchar *pBuf)
{
unchar cnt, checksum;
checksum = 0;
/* xjh mod5 20130929 << */
for (cnt = 0; cnt < 0x80; cnt++)
checksum = checksum + pBuf[cnt];
g_edid_checksum = checksum - pBuf[0x7f];
g_edid_checksum = ~g_edid_checksum + 1;
// pr_info("%s %s : ====g_edid_checksum ==%x \n", LOG_TAG, __func__, (uint)g_edid_checksum);
return checksum == 0 ? 1 : 0;
}
static void edid_header_result(unchar *pBuf)
{
if ((pBuf[0] == 0) && (pBuf[7] == 0) && (pBuf[1] == 0xff) && (pBuf[2] == 0xff) && (pBuf[3] == 0xff)
&& (pBuf[4] == 0xff) && (pBuf[5] == 0xff) && (pBuf[6] == 0xff))
pr_info("%s %s : Good EDID header!\n", LOG_TAG, __func__);
else
pr_err("%s %s : Bad EDID header!\n", LOG_TAG, __func__);
}
void check_edid_data(unchar *pblock_buf)
{
unchar i;
edid_header_result(pblock_buf);
for (i = 0; i <= ((pblock_buf[0x7e] > 1) ? 1 : pblock_buf[0x7e]); i++) {
if (!edid_checksum_result(pblock_buf + i*128))
pr_err("%s %s : Block %x edid checksum error\n", LOG_TAG, __func__, (uint)i);
else
pr_info("%s %s : Block %x edid checksum OK\n", LOG_TAG, __func__, (uint)i);
}
}
bool sp_tx_edid_read(unchar *pedid_blocks_buf)
{
unchar offset = 0;
unchar count, blocks_num;
unchar pblock_buf[16];
unchar i, j, c;
g_edid_break = 0;
sp_tx_edid_read_initial();
sp_write_reg(TX_P0, AUX_CTRL, 0x04);
sp_write_reg_or(TX_P0, AUX_CTRL2, 0x03);
wait_aux_op_finish(&g_edid_break);
sp_tx_addronly_set(0);
blocks_num = sp_tx_get_edid_block();
count = 0;
do {
switch(count) {
case 0:
case 1:
for (i = 0; i < 8; i++) {
offset = (i+count*8) * 16;
edid_read(offset, pblock_buf);
if (g_edid_break == 1)
break;
for(j = 0; j<16; j++){
pedid_blocks_buf[offset + j] = pblock_buf[j];
}
}
break;
case 2:
offset = 0x00;
for (j = 0; j < 8; j++) {
if (g_edid_break == 1)
break;
segments_edid_read(count /2, offset);
offset = offset + 0x10;
}
break;
case 3:
offset = 0x80;
for (j = 0; j < 8; j++) {
if (g_edid_break == 1)
break;
segments_edid_read(count /2, offset);
offset = offset + 0x10;
}
break;
default:
break;
}
count++;
if (g_edid_break == 1)
break;
} while (blocks_num >= count);
sp_tx_rst_aux();
/* check edid data */
if (g_read_edid_flag == 0) {
check_edid_data(pedid_blocks_buf);
g_read_edid_flag = 1;
}
/* test edid << */
sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x18, 1, &c);
if(c & 0x04)
{
pr_info("%s %s : check sum = %.2x\n", LOG_TAG, __func__, (uint)g_edid_checksum);
c = g_edid_checksum;
sp_tx_aux_dpcdwrite_bytes(0x00, 0x02, 0x61, 1, &c);
c = 0x04;
sp_tx_aux_dpcdwrite_bytes(0x00, 0x02, 0x60, 1, &c);
pr_info("%s %s : Test EDID done\n", LOG_TAG, __func__);
}
/* test edid >> */
return 0;
}
static bool check_with_pre_edid(unchar *org_buf)
{
unchar i;
unchar temp_buf[16];
bool return_flag;
return_flag = 0;
/* check checksum and blocks number */
g_edid_break = 0;
sp_tx_edid_read_initial();
sp_write_reg(TX_P0, AUX_CTRL, 0x04);
sp_write_reg_or(TX_P0, AUX_CTRL2, 0x03);
wait_aux_op_finish(&g_edid_break);
sp_tx_addronly_set(0);
edid_read(0x70, temp_buf);
if (g_edid_break == 0) {
for (i = 0; i < 16; i++) {
if (org_buf[0x70 + i] != temp_buf[i]) {
pr_info("%s %s : different checksum and blocks num\n", LOG_TAG, __func__);
return_flag = 1; /* need re-read edid */
break;
}
}
} else
return_flag = 1;
if (return_flag)
goto return_point;
/* check edid information */
edid_read(0x08, temp_buf);
if (g_edid_break == 0) {
for (i = 0; i < 16; i++) {
if (org_buf[i + 8] != temp_buf[i]) {
pr_info("%s %s : different edid information\n", LOG_TAG, __func__);
return_flag = 1;
break;
}
}
} else
return_flag = 1;
return_point:
sp_tx_rst_aux();
return return_flag;
}
#ifdef NEW_HDCP_CONTROL_LOGIC
void hdmi_rx_hdcp_cap(unsigned char hdcp_cap)
{
if(hdcp_cap == 1){
pr_info("*****HDCP CAP changed to active*******!\n");
sp_write_reg_and(RX_P1, HDMI_RX_HDCP_STATUS_REG, ~BKSV_DISABLE);
}else {
pr_info("*****HDCP CAP changed to inactive*******!\n");
sp_write_reg_or(RX_P1, HDMI_RX_HDCP_STATUS_REG, ~BKSV_DISABLE);
}
sp_write_reg_or(RX_P0, RX_SRST, HDCP_MAN_RST);
msleep(10) ;
sp_write_reg_and(RX_P0, RX_SRST, ~HDCP_MAN_RST);
sp_tx_clean_hdcp_status();
}
#endif
void slimport_edid_process(void)
{
unchar temp_value, temp_value1;
unchar i;
pr_info("%s %s : edid_process\n", LOG_TAG, __func__);
/* mdelay(200); */
if (g_read_edid_flag == 1) {
if (check_with_pre_edid(edid_blocks))
g_read_edid_flag = 0;
else
pr_info("%s %s : Don`t need to read edid!\n", LOG_TAG, __func__);
}
if (g_read_edid_flag == 0) {
sp_tx_edid_read(edid_blocks);
if (g_edid_break)
pr_err("%s %s : ERR:EDID corruption!\n", LOG_TAG, __func__);
}
/*Release the HPD after the EEPROM loaddown*/
i = 10;
do {
if ((__i2c_read_byte(TX_P0, HDCP_KEY_STATUS) & 0x01))
break;
else{
pr_info("%s %s : waiting HDCP KEY loaddown \n", LOG_TAG, __func__);
mdelay(1);
}
} while (--i);
sp_write_reg(RX_P0, HDMI_RX_INT_MASK1_REG, 0xe2);
#ifdef NEW_HDCP_CONTROL_LOGIC
if(sp_tx_rx_type == DWN_STRM_IS_HDMI)
g_hdcp_cap_bak = 1;
else
g_hdcp_cap_bak = slimport_hdcp_cap_check();
hdmi_rx_hdcp_cap(g_hdcp_cap_bak);
#endif
hdmi_rx_set_hpd(1);
pr_info("%s %s : hdmi_rx_set_hpd 1 !\n", LOG_TAG, __func__);
hdmi_rx_set_termination(1);
sp_tx_get_rx_bw(&temp_value);
pr_info("%s %s : get rx bandwidth info = [%x] \n", LOG_TAG, __func__, (uint)temp_value);
sp_rx_bandwidth = temp_value;
temp_value1 = parse_edid_to_get_bandwidth();
if (temp_value <= temp_value1)
temp_value1 = temp_value;
pr_info("%s %s : set link bw in edid %x \n", LOG_TAG, __func__, (uint)temp_value1);
//sp_tx_set_link_bw(temp_value1);
g_changed_bandwidth = temp_value1;
/*
sp_tx_send_message(
(g_hdmi_dvi_status == HDMI_MODE) ? MSG_INPUT_HDMI : MSG_INPUT_DVI);
*/
goto_next_system_state();
}
#endif
/******************End EDID process********************/
/******************start Link training process********************/
static void sp_tx_lvttl_bit_mapping(void)
{
unchar c, colorspace;
unchar vid_bit;
vid_bit = 0;
sp_read_reg(RX_P1,HDMI_RX_AVI_DATA00_REG, &colorspace);
colorspace &= 0x60;
switch (((__i2c_read_byte(RX_P0, HDMI_RX_VIDEO_STATUS_REG1) & COLOR_DEPTH) >> 4)) {
default:
case Hdmi_legacy:
c = IN_BPC_8BIT;
vid_bit = 0;
break;
case Hdmi_24bit:
c = IN_BPC_8BIT;
if(colorspace == 0x20)
vid_bit = 5;
else
vid_bit = 1;
break;
case Hdmi_30bit:
c = IN_BPC_10BIT;
if (colorspace == 0x20)
vid_bit = 6;
else
vid_bit = 2;
break;
case Hdmi_36bit:
c = IN_BPC_12BIT;
if (colorspace == 0x20)
vid_bit = 6;
else
vid_bit = 3;
break;
}
/* For down sample video (12bit, 10bit ---> 8bit), this register don`t change*/
if(down_sample_en == 0)
sp_write_reg_and_or(TX_P2, SP_TX_VID_CTRL2_REG, 0x8c, colorspace >> 5 | c);
//mdelay(500);
/*Patch: for 10bit video must be set this value to 12bit by someone*/
if(down_sample_en ==1 && c == IN_BPC_10BIT)
vid_bit = 3;
sp_write_reg_and_or(TX_P2, BIT_CTRL_SPECIFIC, 0x00, ENABLE_BIT_CTRL | vid_bit << 1);
if (sp_tx_test_edid ){
//set color depth to 18-bit for link cts
sp_write_reg_and(TX_P2, SP_TX_VID_CTRL2_REG, 0x8f);
sp_tx_test_edid = 0;
pr_info("%s %s : ***color space is set to 18bit***\n", LOG_TAG, __func__);
}
if (!down_sample_en) {
sp_write_reg(TX_P0, SP_TX_VID_BLANK_SET1, 0x0);
sp_write_reg(TX_P0, SP_TX_VID_BLANK_SET2, 0x0);
sp_write_reg(TX_P0, SP_TX_VID_BLANK_SET3, 0x0);
}
else {
sp_write_reg(TX_P0, SP_TX_VID_BLANK_SET1, 0x80);
sp_write_reg(TX_P0, SP_TX_VID_BLANK_SET2, 0x00);
sp_write_reg(TX_P0, SP_TX_VID_BLANK_SET3, 0x80);
}
}
ulong sp_tx_pclk_calc(void)
{
ulong str_plck;
uint vid_counter;
unchar c;
sp_read_reg(RX_P0, 0x8d, &c);
vid_counter = c;
vid_counter = vid_counter << 8;
sp_read_reg(RX_P0, 0x8c, &c);
vid_counter |= c;
str_plck = ((ulong)vid_counter * XTAL_CLK_M10) >> 12;
pr_info("%s %s : PCLK = %d.%d \n", LOG_TAG, __func__, (((uint)(str_plck))/10), ((uint)str_plck - (((uint)str_plck/10)*10)));
return str_plck ;
}
static unchar sp_tx_bw_lc_sel(ulong pclk)
{
ulong pixel_clk;
unchar c1;
switch (((__i2c_read_byte(RX_P0, HDMI_RX_VIDEO_STATUS_REG1) & COLOR_DEPTH) >> 4)) {
case Hdmi_legacy:
case Hdmi_24bit:
default:
pixel_clk = pclk;
break;
case Hdmi_30bit:
pixel_clk = (pclk * 5) >> 2;
break;
case Hdmi_36bit:
pixel_clk = (pclk * 3) >> 1;
break;
}
pr_info("%s %s : pixel_clk = %d.%d \n", LOG_TAG, __func__, (((uint)(pixel_clk))/10), ((uint)pixel_clk - (((uint)pixel_clk/10)*10)));
down_sample_en = 0;
if(pixel_clk <= 530)
c1 = LINK_1P62G;
else if ((530 < pixel_clk) && (pixel_clk <= 890))
c1 = LINK_2P7G;
else if ((890 < pixel_clk) && (pixel_clk <= 1800))
c1 = LINK_5P4G;
else {
c1 = LINK_6P75G;
if(pixel_clk > 2240)
down_sample_en = 1;
}
if(sp_tx_get_link_bw() != c1){
g_changed_bandwidth = c1;
pr_info("%s %s : It is different bandwidth between sink support and cur video!%.2x\n", LOG_TAG, __func__, (uint)c1);
return 1;
}
return 0;
}
void sp_tx_spread_enable(unchar benable)
{
unchar c;
sp_read_reg(TX_P0, SP_TX_DOWN_SPREADING_CTRL1, &c);
if (benable) {
c |= SP_TX_SSC_DWSPREAD;
sp_write_reg(TX_P0, SP_TX_DOWN_SPREADING_CTRL1, c);
sp_tx_aux_dpcdread_bytes(0x00, 0x01,
DPCD_DOWNSPREAD_CTRL, 1, &c);
c |= SPREAD_AMPLITUDE;
sp_tx_aux_dpcdwrite_byte(0x00, 0x01, DPCD_DOWNSPREAD_CTRL, c);
} else {
c &= ~SP_TX_SSC_DISABLE;
sp_write_reg(TX_P0, SP_TX_DOWN_SPREADING_CTRL1, c);
sp_tx_aux_dpcdread_bytes(0x00, 0x01,
DPCD_DOWNSPREAD_CTRL, 1, &c);
c &= ~SPREAD_AMPLITUDE;
sp_tx_aux_dpcdwrite_byte(0x00, 0x01, DPCD_DOWNSPREAD_CTRL, c);
}
}
void sp_tx_config_ssc(enum SP_SSC_DEP sscdep)
{
sp_write_reg(TX_P0, SP_TX_DOWN_SPREADING_CTRL1, 0x0); /* clear register */
sp_write_reg(TX_P0, SP_TX_DOWN_SPREADING_CTRL1, sscdep);
sp_tx_spread_enable(1);
}
void sp_tx_enhancemode_set(void)
{
unchar c;
sp_tx_aux_dpcdread_bytes(0x00, 0x00, DPCD_MAX_LANE_COUNT, 1, &c);
if (c & ENHANCED_FRAME_CAP) {
sp_write_reg_or(TX_P0, SP_TX_SYS_CTRL4_REG, ENHANCED_MODE);
sp_tx_aux_dpcdread_bytes(0x00, 0x01,
DPCD_LANE_COUNT_SET, 1, &c);
c |= ENHANCED_FRAME_EN;
sp_tx_aux_dpcdwrite_byte(0x00, 0x01,
DPCD_LANE_COUNT_SET, c);
pr_info("%s %s : Enhance mode enabled\n", LOG_TAG, __func__);
} else {
sp_write_reg_and(TX_P0, SP_TX_SYS_CTRL4_REG, ~ENHANCED_MODE);
sp_tx_aux_dpcdread_bytes(0x00, 0x01,
DPCD_LANE_COUNT_SET, 1, &c);
c &= ~ENHANCED_FRAME_EN;
sp_tx_aux_dpcdwrite_byte(0x00, 0x01,
DPCD_LANE_COUNT_SET, c);
pr_info("%s %s : Enhance mode disabled\n", LOG_TAG, __func__);
}
}
uint sp_tx_link_err_check(void)
{
uint errl = 0, errh = 0;
unchar bytebuf[2];
sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x10, 2, bytebuf);
mdelay(5);
sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x10, 2, bytebuf);
errh = bytebuf[1];
if (errh & 0x80) {
errl = bytebuf[0];
errh = (errh & 0x7f) << 8;
errl = errh + errl;
}
pr_err("%s %s : Err of Lane = %d\n", LOG_TAG, __func__, errl);
return errl;
}
static void serdes_fifo_reset(void)
{
sp_write_reg_or(TX_P2, RST_CTRL2, SERDES_FIFO_RST);
mdelay(20);
sp_write_reg_and(TX_P2, RST_CTRL2, (~SERDES_FIFO_RST));
}
void slimport_link_training(void)
{
unchar temp_value, return_value, c;
return_value = 1;
pr_info("%s %s : sp_tx_LT_state : %x\n", LOG_TAG, __func__, (int)sp_tx_LT_state);
switch(sp_tx_LT_state) {
case LT_INIT:
slimport_block_power_ctrl(SP_TX_PWR_VIDEO, SP_POWER_ON);
sp_tx_video_mute(1);
sp_tx_enable_video_input(0);
sp_tx_LT_state++;
sp_tx_send_message(
(g_hdmi_dvi_status == HDMI_MODE) ? MSG_INPUT_HDMI : MSG_INPUT_DVI);
case LT_WAIT_PLL_LOCK:
if (!sp_tx_get_pll_lock_status()) {
//pll reset when plll not lock.
sp_read_reg(TX_P0, SP_TX_PLL_CTRL_REG, &temp_value);
temp_value |= PLL_RST;
sp_write_reg(TX_P0, SP_TX_PLL_CTRL_REG, temp_value);
temp_value &=~PLL_RST;
sp_write_reg(TX_P0, SP_TX_PLL_CTRL_REG, temp_value);
pr_info("%s %s : PLL not lock!\n", LOG_TAG, __func__);
}else
sp_tx_LT_state = LT_CHECK_LINK_BW;
SP_BREAK(LT_WAIT_PLL_LOCK, sp_tx_LT_state);
case LT_CHECK_LINK_BW:
sp_tx_get_rx_bw(&temp_value);
if(temp_value < g_changed_bandwidth){
pr_info("%s %s : ****Over bandwidth****\n", LOG_TAG, __func__);
g_changed_bandwidth = temp_value;
}
else
sp_tx_LT_state++;
case LT_START:
if(sp_tx_test_lt) {
//sp_tx_test_lt = 0;
g_changed_bandwidth = sp_tx_test_bw;
sp_write_reg_and(TX_P2, SP_TX_VID_CTRL2_REG, 0x8f);
}else{
#ifdef DEMO_4K_2K
if(down_sample_en)
sp_write_reg(TX_P0, SP_TX_LT_SET_REG, 0x09);
else
#endif
if (lge_get_boot_mode() != LGE_BOOT_MODE_QEM_56K) {
pr_err("%s: LGE_BOOT_MODE_QEM_56K - LT_SET_REG = 0x0\n", __func__);
sp_write_reg(TX_P0, SP_TX_LT_SET_REG, 0x0);
} else {
pr_err("%s: LGE_BOOT_MODE_QEM_56K - LT_SET_REG = xxx\n", __func__);
}
}
sp_write_reg(TX_P0, SP_TX_LT_SET_REG, 0x0); //add by leo 20150728
if (lge_get_boot_mode() != LGE_BOOT_MODE_QEM_56K) {
//power on main link before link training
pr_err("%s: LGE_BOOT_MODE_QEM_56K - 4000PPM\n", __func__);
sp_write_reg_and(TX_P0, SP_TX_ANALOG_PD_REG, ~CH0_PD);
sp_tx_config_ssc(SSC_DEP_4000PPM);
} else {
pr_err("%s: LGE_BOOT_MODE_QEM_56K - 5000PPM\n", __func__);
sp_tx_config_ssc(SSC_DEP_5000PPM);
}
sp_tx_set_link_bw(g_changed_bandwidth);
sp_tx_enhancemode_set();
// judge downstream DP version and set downstream sink to D0 (normal operation mode)
sp_tx_aux_dpcdread_bytes(0x00, 0x00, 0x00, 0x01, &c);
sp_tx_aux_dpcdread_bytes(0x00, 0x06, 0x00, 0x01, &temp_value);
if(c >= 0x12){ //DP 1.2 and above
temp_value &= 0xf8;
}
else {//DP 1.1 or 1.0
temp_value &= 0xfc;
}
temp_value |= 0x01;
sp_tx_aux_dpcdwrite_byte(0x00, 0x06, 0x00, temp_value);
//sp_write_reg_or(TX_P2, SP_INT_MASK, 0X20); //hardware interrupt mask enable
sp_write_reg(TX_P0, LT_CTRL, SP_TX_LT_EN);
sp_tx_LT_state = LT_WAITTING_FINISH;
//There is no break;
case LT_WAITTING_FINISH:
/*here : waitting interrupt to change training state.*/
break;
case LT_ERROR:
serdes_fifo_reset();
pr_info("LT ERROR Status: SERDES FIFO reset.");
redo_cur_system_state();
sp_tx_LT_state = LT_INIT;
break;
case LT_FINISH:
sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x02, 1, &temp_value);
if ((temp_value&0x07) == 0x07) {// for one lane case.
/* if there is link error, adjust pre-emphsis to check error again.
If there is no error,keep the setting, otherwise use 400mv0db */
if(!sp_tx_test_lt) {
if (sp_tx_link_err_check()) {
sp_read_reg(TX_P0, SP_TX_LT_SET_REG, &temp_value);
if(!(temp_value & MAX_PRE_REACH)){
sp_write_reg(TX_P0, SP_TX_LT_SET_REG, (temp_value + 0x08));//increase one pre-level
pr_err("%s %s : increase one pre-level\n", LOG_TAG, __func__);
//if error still exist, return to the link traing value
if (sp_tx_link_err_check())
sp_write_reg(TX_P0, SP_TX_LT_SET_REG, temp_value);
}
}
sp_read_reg(TX_P0, SP_TX_LINK_BW_SET_REG, &temp_value);
if (temp_value == g_changed_bandwidth){
pr_info("%s %s : LT succeed, bw: %.2x ", LOG_TAG, __func__, (uint) temp_value);
pr_info("Lane0 Set: %.2x\n", (uint) __i2c_read_byte(TX_P0, SP_TX_LT_SET_REG));
sp_tx_LT_state = LT_INIT;
if(sp_tx_link_err_check() > 200){
pr_info("%s %s :Need to reset Serdes FIFO.\n", LOG_TAG, __func__);
sp_tx_LT_state = LT_ERROR;
}else {
goto_next_system_state();
}
}else {
pr_info("%s %s : bw cur:%.2x, per:%.2x \n", LOG_TAG, __func__, (uint)temp_value, (uint)g_changed_bandwidth);
sp_tx_LT_state = LT_ERROR;
}
} else {
sp_tx_test_lt = 0;
sp_tx_LT_state = LT_INIT;
goto_next_system_state();
}
}else {
pr_info("%s %s : LANE0 Status error: %.2x\n", LOG_TAG, __func__, (uint)(temp_value&0x07));
sp_tx_LT_state = LT_ERROR;
}
break;
default:
break;
}
}
/******************End Link training process********************/
/******************Start Output video process********************/
void sp_tx_set_colorspace(void)
{
unchar color_space;
unchar c;
if(down_sample_en){
sp_read_reg(RX_P1, HDMI_RX_AVI_DATA00_REG, &color_space);
color_space &= 0x60;
if(color_space == 0x20){
pr_info("%s %s : YCbCr4:2:2 ---> PASS THROUGH.\n", LOG_TAG, __func__);
sp_write_reg(TX_P2, SP_TX_VID_CTRL6_REG, 0x00);
sp_write_reg(TX_P2, SP_TX_VID_CTRL5_REG, 0x00);
sp_write_reg(TX_P2, SP_TX_VID_CTRL2_REG, 0x11);
//sp_write_reg_and_or(TX_P2, SP_TX_VID_CTRL2_REG, 0xfc,0x01);
}else if(color_space == 0x40){
pr_info("%s %s : YCbCr4:4:4 ---> YCbCr4:2:2\n", LOG_TAG, __func__);
sp_write_reg(TX_P2, SP_TX_VID_CTRL6_REG, 0x41);
sp_write_reg(TX_P2, SP_TX_VID_CTRL5_REG, 0x00);
sp_write_reg(TX_P2, SP_TX_VID_CTRL2_REG, 0x12);
//sp_write_reg_and_or(TX_P2, SP_TX_VID_CTRL2_REG, 0xfc,0x02);
}else if(color_space == 0x00){
pr_info("%s %s : RGB4:4:4 ---> YCbCr4:2:2\n", LOG_TAG, __func__);
sp_write_reg(TX_P2, SP_TX_VID_CTRL6_REG, 0x41);
sp_write_reg(TX_P2, SP_TX_VID_CTRL5_REG, 0x83);
sp_write_reg(TX_P2, SP_TX_VID_CTRL2_REG, 0x10);
//sp_write_reg_and(TX_P2, SP_TX_VID_CTRL2_REG, 0xfc);
}
} else{
switch(sp_tx_rx_type){
case DWN_STRM_IS_VGA_9832:
case DWN_STRM_IS_ANALOG:
case DWN_STRM_IS_DIGITAL: /* add DP case by span 20130217 */
sp_read_reg(TX_P2, SP_TX_VID_CTRL2_REG, &color_space);
if((color_space & 0x03)== 0x01) { //YCBCR422
sp_write_reg_or(TX_P2, SP_TX_VID_CTRL5_REG, RANGE_Y2R|CSPACE_Y2R); //YUV->RGB
sp_read_reg(RX_P1, (HDMI_RX_AVI_DATA00_REG + 3), &c);
//vic for BT709.
if((c ==0x04)||(c ==0x05)||(c ==0x10)||
(c ==0x13)||(c ==0x14)||(c ==0x1F)||
(c ==0x20)||(c ==0x21)||(c ==0x22)||
(c ==0x27)||(c ==0x28)||(c ==0x29)||
(c ==0x2E)||(c ==0x2F)||(c ==0x3C)||
(c ==0x3D)||(c ==0x3E)||(c ==0x3F)||
(c ==0x40))
sp_write_reg_or(TX_P2, SP_TX_VID_CTRL5_REG, CSC_STD_SEL);
else
sp_write_reg_and(TX_P2, SP_TX_VID_CTRL5_REG, ~CSC_STD_SEL);
sp_write_reg_or(TX_P2, SP_TX_VID_CTRL6_REG, VIDEO_PROCESS_EN|UP_SAMPLE); //up sample
} else if((color_space & 0x03) == 0x02){//YCBCR444
sp_write_reg_or(TX_P2, SP_TX_VID_CTRL5_REG, RANGE_Y2R|CSPACE_Y2R); //YUV->RGB
sp_read_reg(RX_P1, (HDMI_RX_AVI_DATA00_REG + 3), &c);
//vic for BT709.
if((c ==0x04)||(c ==0x05)||(c ==0x10)||
(c ==0x13)||(c ==0x14)||(c ==0x1F)||
(c ==0x20)||(c ==0x21)||(c ==0x22)||
(c ==0x27)||(c ==0x28)||(c ==0x29)||
(c ==0x2E)||(c ==0x2F)||(c ==0x3C)||
(c ==0x3D)||(c ==0x3E)||(c ==0x3F)||
(c ==0x40))
sp_write_reg_or(TX_P2, SP_TX_VID_CTRL5_REG, CSC_STD_SEL);
else
sp_write_reg_and(TX_P2, SP_TX_VID_CTRL5_REG, ~CSC_STD_SEL);
sp_write_reg_or_and(TX_P2, SP_TX_VID_CTRL6_REG, VIDEO_PROCESS_EN, ~UP_SAMPLE);
} else if((color_space & 0x03) == 0x00) {//RGB
sp_write_reg_and(TX_P2, SP_TX_VID_CTRL5_REG, (~RANGE_Y2R) & (~CSPACE_Y2R) & (~CSC_STD_SEL));
sp_write_reg_and(TX_P2, SP_TX_VID_CTRL6_REG, (~ VIDEO_PROCESS_EN) & (~UP_SAMPLE));
}
break;
case DWN_STRM_IS_HDMI:
sp_write_reg(TX_P2, SP_TX_VID_CTRL6_REG, 0x00);
sp_write_reg(TX_P2, SP_TX_VID_CTRL5_REG, 0x00);
break;
default:
break;
}
}
}
void sp_tx_avi_setup(void)
{
unchar c;
int i;
for (i = 0; i < 13; i++) {
sp_read_reg(RX_P1, (HDMI_RX_AVI_DATA00_REG + i), &c);
sp_tx_packet_avi.AVI_data[i] = c;
}
/* not change AVI for down sample video
if(down_sample_en)
sp_tx_packet_avi.AVI_data[0] =(sp_tx_packet_avi.AVI_data[0] & 0x9f) |0x20;
else
*/
{
switch(sp_tx_rx_type){
case DWN_STRM_IS_VGA_9832:
case DWN_STRM_IS_ANALOG:
case DWN_STRM_IS_DIGITAL:/* by span 20130217 */
sp_tx_packet_avi.AVI_data[0] &= ~0x60;
break;
case DWN_STRM_IS_HDMI:
/* case DWN_STRM_IS_DIGITAL: */
break;
default:
break;
}
}
}
static void sp_tx_load_packet(enum PACKETS_TYPE type)
{
int i;
unchar c;
switch (type) {
case AVI_PACKETS:
sp_write_reg(TX_P2, SP_TX_AVI_TYPE, 0x82);
sp_write_reg(TX_P2, SP_TX_AVI_VER, 0x02);
sp_write_reg(TX_P2, SP_TX_AVI_LEN, 0x0d);
for (i = 0; i < 13; i++) {
sp_write_reg(TX_P2, SP_TX_AVI_DB0 + i,
sp_tx_packet_avi.AVI_data[i]);
}
break;
case SPD_PACKETS:
sp_write_reg(TX_P2, SP_TX_SPD_TYPE, 0x83);
sp_write_reg(TX_P2, SP_TX_SPD_VER, 0x01);
sp_write_reg(TX_P2, SP_TX_SPD_LEN, 0x19);
for (i = 0; i < 25; i++) {
sp_write_reg(TX_P2, SP_TX_SPD_DB0 + i,
sp_tx_packet_spd.SPD_data[i]);
}
break;
case VSI_PACKETS:
sp_write_reg(TX_P2, SP_TX_MPEG_TYPE, 0x81);
sp_write_reg(TX_P2, SP_TX_MPEG_VER, 0x01);
sp_read_reg(RX_P1, HDMI_RX_MPEG_LEN_REG, &c);
sp_write_reg(TX_P2, SP_TX_MPEG_LEN, c);
for (i = 0; i < 10; i++) {
sp_write_reg(TX_P2, SP_TX_MPEG_DB0 + i,
sp_tx_packet_mpeg.MPEG_data[i]);
}
break;
case MPEG_PACKETS:
sp_write_reg(TX_P2, SP_TX_MPEG_TYPE, 0x85);
sp_write_reg(TX_P2, SP_TX_MPEG_VER, 0x01);
sp_write_reg(TX_P2, SP_TX_MPEG_LEN, 0x0d);
for (i = 0; i < 10; i++) {
sp_write_reg(TX_P2, SP_TX_MPEG_DB0 + i,
sp_tx_packet_mpeg.MPEG_data[i]);
}
break;
case AUDIF_PACKETS:
sp_write_reg(TX_P2, SP_TX_AUD_TYPE, 0x84);
sp_write_reg(TX_P2, SP_TX_AUD_VER, 0x01);
sp_write_reg(TX_P2, SP_TX_AUD_LEN, 0x0a);
for (i = 0; i < 10; i++) {
sp_write_reg(TX_P2, SP_TX_AUD_DB0 + i,
sp_tx_audioinfoframe.pb_byte[i]);
}
break;
default:
break;
}
}
void sp_tx_config_packets(enum PACKETS_TYPE bType)
{
unchar c;
switch (bType) {
case AVI_PACKETS:
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c &= ~AVI_IF_EN;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
sp_tx_load_packet(AVI_PACKETS);
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c |= AVI_IF_UD;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c |= AVI_IF_EN;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
break;
case SPD_PACKETS:
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c &= ~SPD_IF_EN;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
sp_tx_load_packet(SPD_PACKETS);
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c |= SPD_IF_UD;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c |= SPD_IF_EN;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
break;
case VSI_PACKETS:
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c &= ~MPEG_IF_EN;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
sp_tx_load_packet(VSI_PACKETS);
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c |= MPEG_IF_UD;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c |= MPEG_IF_EN;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
break;
case MPEG_PACKETS:
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c &= ~MPEG_IF_EN;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
sp_tx_load_packet(MPEG_PACKETS);
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c |= MPEG_IF_UD;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c |= MPEG_IF_EN;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
break;
case AUDIF_PACKETS:
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c &= ~AUD_IF_EN;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
sp_tx_load_packet(AUDIF_PACKETS);
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c |= AUD_IF_UP;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
sp_read_reg(TX_P0, SP_TX_PKT_EN_REG, &c);
c |= AUD_IF_EN;
sp_write_reg(TX_P0, SP_TX_PKT_EN_REG, c);
break;
default:
break;
}
}
void slimport_config_video_output(void)
{
unchar temp_value;
static int rx_count = 0;
static int tx_count = 0;
switch (sp_tx_vo_state) {
default:
case VO_WAIT_VIDEO_STABLE:
//HDMI RX video judge
sp_read_reg(RX_P0,HDMI_RX_SYS_STATUS_REG, &temp_value);
if ((temp_value & (TMDS_DE_DET | TMDS_CLOCK_DET)) == 0x03) { //input video stable
sp_tx_bw_lc_sel(sp_tx_pclk_calc());
sp_tx_enable_video_input(0);
sp_tx_avi_setup();
sp_tx_config_packets(AVI_PACKETS);
sp_tx_set_colorspace();
sp_tx_lvttl_bit_mapping();
if(__i2c_read_byte(RX_P0, RX_PACKET_REV_STA) & VSI_RCVD) //VSI packet received
hdmi_rx_new_vsi_int();
sp_tx_enable_video_input(1);
sp_tx_vo_state = VO_WAIT_TX_VIDEO_STABLE;
rx_count = 0;
}
else {
pr_info("%s %s :HDMI input video not stable! conunt=%d\n", LOG_TAG, __func__, rx_count);
if (rx_count++ > 30) {
rx_count = 0;
vbus_power_ctrl(0);
#ifdef CONFIG_SLIMPORT_DYNAMIC_HPD
slimport_set_hdmi_hpd(0);
#endif
break;
}
}
SP_BREAK(VO_WAIT_VIDEO_STABLE, sp_tx_vo_state);
case VO_WAIT_TX_VIDEO_STABLE:
sp_read_reg(TX_P0, SP_TX_SYS_CTRL2_REG, &temp_value);
sp_write_reg(TX_P0, SP_TX_SYS_CTRL2_REG, temp_value);
sp_read_reg(TX_P0, SP_TX_SYS_CTRL2_REG, &temp_value);
if (temp_value & CHA_STA) {
pr_info("%s %s : Stream clock not stable!\n", LOG_TAG, __func__);
} else {
sp_read_reg(TX_P0, SP_TX_SYS_CTRL3_REG, &temp_value);
sp_write_reg(TX_P0, SP_TX_SYS_CTRL3_REG, temp_value);
sp_read_reg(TX_P0, SP_TX_SYS_CTRL3_REG, &temp_value);
if (!(temp_value & STRM_VALID)) {
pr_err("%s %s : video stream not valid! count=%d\n", LOG_TAG, __func__, tx_count);
if (tx_count++ > 30) {
tx_count = 0;
vbus_power_ctrl(0);
#ifdef CONFIG_SLIMPORT_DYNAMIC_HPD
slimport_set_hdmi_hpd(0);
#endif
break;
}
} else{
tx_count = 0;
#ifdef DEMO_4K_2K
if(down_sample_en)
sp_tx_vo_state = VO_FINISH;
else
#endif
sp_tx_vo_state = VO_CHECK_VIDEO_INFO;
}
}
SP_BREAK(VO_WAIT_TX_VIDEO_STABLE, sp_tx_vo_state);
/*
case VO_WAIT_PLL_LOCK:
if (!sp_tx_get_pll_lock_status()) {
//pll reset when plll not lock. by span 20130217
sp_read_reg(TX_P0, SP_TX_PLL_CTRL_REG, &temp_value);
temp_value |= PLL_RST;
sp_write_reg(TX_P0, SP_TX_PLL_CTRL_REG, temp_value);
temp_value &=~PLL_RST;
sp_write_reg(TX_P0, SP_TX_PLL_CTRL_REG, temp_value);
pr_info("%s %s : PLL not lock!\n", LOG_TAG, __func__);
}else
sp_tx_vo_state = VO_CHECK_BW;
SP_BREAK(VO_WAIT_PLL_LOCK, sp_tx_vo_state);
*/
case VO_CHECK_VIDEO_INFO:
temp_value = __i2c_read_byte(RX_P0, HDMI_STATUS) & HDMI_MODE;
g_hdmi_dvi_status = read_dvi_hdmi_mode();
if (!sp_tx_bw_lc_sel(sp_tx_pclk_calc())
&& (g_hdmi_dvi_status & _BIT0) == temp_value)
sp_tx_vo_state++;
else{
if((g_hdmi_dvi_status & _BIT0) != temp_value){
pr_info("%s %s : Different mode of DVI or HDMI mode \n", LOG_TAG, __func__);
g_hdmi_dvi_status = temp_value;
if((g_hdmi_dvi_status & _BIT0) != HDMI_MODE)
hdmi_rx_mute_audio(0);
}
sp_tx_set_sys_state(STATE_LINK_TRAINING);
}
SP_BREAK(VO_CHECK_VIDEO_INFO, sp_tx_vo_state);
case VO_FINISH:
slimport_block_power_ctrl(SP_TX_PWR_AUDIO, SP_POWER_DOWN);
hdmi_rx_mute_video(0);
//sp_tx_lvttl_bit_mapping();
sp_tx_video_mute(0);
//sp_tx_set_colorspace();
//sp_tx_avi_setup();
//sp_tx_config_packets(AVI_PACKETS);
//sp_tx_enable_video_input(1);
sp_tx_show_infomation();
goto_next_system_state();
break;
}
}
/******************End Output video process********************/
/******************Start HDCP process********************/
#ifndef HDCP_AUTO_EN
static void sp_tx_hdcp_encryption_disable(void)
{
sp_write_reg_and(TX_P0, TX_HDCP_CTRL0, ~ENC_EN);
}
static void sp_tx_hdcp_encryption_enable(void)
{
sp_write_reg_or(TX_P0, TX_HDCP_CTRL0, ENC_EN);
}
static void sp_tx_hw_hdcp_enable(void)
{
unchar c;
sp_write_reg_and(TX_P0, TX_HDCP_CTRL0, (~ENC_EN) & (~HARD_AUTH_EN));
sp_write_reg_or(TX_P0, TX_HDCP_CTRL0, HARD_AUTH_EN | BKSV_SRM_PASS | KSVLIST_VLD | ENC_EN);
sp_read_reg(TX_P0, TX_HDCP_CTRL0, &c);
pr_info("%s %s : TX_HDCP_CTRL0 = %.2x\n", LOG_TAG, __func__, (uint)c);
sp_write_reg(TX_P0, SP_TX_WAIT_R0_TIME, 0xb0);
sp_write_reg(TX_P0, SP_TX_WAIT_KSVR_TIME, 0xc8);
/* sp_write_reg(TX_P2, SP_COMMON_INT_MASK2, 0xfc); */
pr_info("%s %s : Hardware HDCP is enabled.\n", LOG_TAG, __func__);
}
static bool sp_tx_get_ds_video_status(void)
{
unchar c;
sp_tx_aux_dpcdread_bytes(0x00, 0x05, 0x27, 1, &c);
pr_info("%s %s : 0x00527 = %.2x.\n", LOG_TAG, __func__, (uint)c);
if (c & 0x01)
return 1;
else
return 0;
}
#ifdef NEW_HDCP_CONTROL_LOGIC
unsigned char check_rx_hdcp_status(void)
{
unsigned char counter;
counter = 30;
do{
if(__i2c_read_reg(RX_P1,HDMI_RX_HDCP_STATUS_REG) & AUTH_EN)
break;
else
msleep(10);
}while(--counter);
return (counter == 0) ? 0 : 1;
}
#endif
void slimport_hdcp_process(void)
{
//unchar c;
static unchar ds_vid_stb_cntr = 0, HDCP_fail_count = 0;
switch (HDCP_state) {
case HDCP_CAPABLE_CHECK:
ds_vid_stb_cntr = 0;
HDCP_fail_count = 0;
HDCP_state = HDCP_WAITTING_VID_STB;
if (external_block_en == 0) {
#ifdef NEW_HDCP_CONTROL_LOGIC
unsigned char temp_var;
temp_var= 0;
if(check_rx_hdcp_status()){
/*AP enable HDCP*/
if(sp_tx_rx_type == DWN_STRM_IS_HDMI){
temp_var = slimport_hdcp_cap_check();
if(g_hdcp_cap_bak != temp_var){
hdmi_rx_hdcp_cap(g_hdcp_cap_bak);
g_hdcp_cap_bak = temp_var;
sp_tx_set_sys_state(STATE_LINK_TRAINING);
}
}else {
/*AP does not do HDCP*/
if(g_hdcp_cap_bak == 0)
HDCP_state = HDCP_NOT_SUPPORT;
}
}else {/*AP disable HDCP*/
HDCP_state = HDCP_NOT_SUPPORT;
pr_info("%s %s : Source disable HDCP.\n", LOG_TAG, __func__); //for debug
}
#else
if((sp_tx_rx_type == DWN_STRM_IS_ANALOG)
|| (sp_tx_rx_type == DWN_STRM_IS_VGA_9832)
||(slimport_hdcp_cap_check() == 0))
HDCP_state = HDCP_NOT_SUPPORT;
#endif
}
SP_BREAK(HDCP_CAPABLE_CHECK, HDCP_state);
case HDCP_WAITTING_VID_STB:
/*In case ANX7730 can not get ready video*/
if(sp_tx_rx_type == DWN_STRM_IS_HDMI) {
/* pr_info("%s %s : video stb : count%.2x \n", LOG_TAG, __func__,(WORD)ds_vid_stb_cntr); */
if (!sp_tx_get_ds_video_status()) {
if (ds_vid_stb_cntr >= 50) {
vbus_power_ctrl(0);
reg_hardware_reset();
ds_vid_stb_cntr = 0;
} else {
ds_vid_stb_cntr++;
mdelay(10);
}
#ifdef SLIMPORT_DRV_DEBUG
pr_info("%s %s : downstream video not stable\n", LOG_TAG, __func__); /* for debug */
#endif
} else {
ds_vid_stb_cntr = 0;
HDCP_state = HDCP_HW_ENABLE;
}
} else {
HDCP_state = HDCP_HW_ENABLE;
}
SP_BREAK(HDCP_WAITTING_VID_STB, HDCP_state);
case HDCP_HW_ENABLE:
sp_tx_video_mute(1);
/* sp_tx_clean_hdcp_status(); */
slimport_block_power_ctrl(SP_TX_PWR_HDCP, SP_POWER_ON);
sp_write_reg(TX_P2, SP_COMMON_INT_MASK2, 0x01);
//sp_tx_video_mute(0);
//sp_tx_aux_polling_disable();
//sp_tx_clean_hdcp_status();
mdelay(50);
//disable auto polling during hdcp.
sp_tx_hw_hdcp_enable();
HDCP_state = HDCP_WAITTING_FINISH;
case HDCP_WAITTING_FINISH:
break;
case HDCP_FINISH:
sp_tx_hdcp_encryption_enable();
hdmi_rx_mute_video(0);
sp_tx_video_mute(0);
/* enable auto polling after hdcp. */
/* sp_tx_aux_polling_enable(); */
goto_next_system_state();
HDCP_state = HDCP_CAPABLE_CHECK;
pr_info("%s %s : @@@@@@@hdcp_auth_pass@@@@@@\n", LOG_TAG, __func__);
break;
case HDCP_FAILE:
if (HDCP_fail_count > 5) {
vbus_power_ctrl(0);
reg_hardware_reset();
HDCP_state = HDCP_CAPABLE_CHECK;
HDCP_fail_count = 0;
pr_info("%s %s : *********hdcp_auth_failed*********\n", LOG_TAG, __func__);
} else {
HDCP_fail_count++;
HDCP_state = HDCP_WAITTING_VID_STB;
}
break;
default:
case HDCP_NOT_SUPPORT:
pr_info("%s %s : Sink is not capable HDCP\n", LOG_TAG, __func__);
slimport_block_power_ctrl(SP_TX_PWR_HDCP, SP_POWER_DOWN);
sp_tx_video_mute(0);
/* sp_tx_aux_polling_enable(); */
goto_next_system_state();
HDCP_state = HDCP_CAPABLE_CHECK;
break;
}
}
#endif
/******************End HDCP process********************/
/******************Start Audio process********************/
static void sp_tx_audioinfoframe_setup(void)
{
int i;
unchar c;
sp_read_reg(RX_P1, HDMI_RX_AUDIO_TYPE_REG, &c);
sp_tx_audioinfoframe.type = c;
sp_read_reg(RX_P1, HDMI_RX_AUDIO_VER_REG, &c);
sp_tx_audioinfoframe.version = c;
sp_read_reg(RX_P1, HDMI_RX_AUDIO_LEN_REG, &c);
sp_tx_audioinfoframe.length = c;
for (i = 0; i < 11; i++) {
sp_read_reg(RX_P1, (HDMI_RX_AUDIO_DATA00_REG + i), &c);
sp_tx_audioinfoframe.pb_byte[i] = c;
}
}
static void info_ANX7730_AUIF_changed(void)
{
unchar temp, count;
unchar pBuf[3] = {0x01, 0xd1, 0x02};
msleep(20);
if (sp_tx_rx_type == DWN_STRM_IS_HDMI) {/* assuming it is anx7730 */
sp_tx_aux_dpcdread_bytes(0x00, 0x05, 0x23, 1, &temp);
if (temp < 0x94) {
count = 3;
do {
mdelay(20);
if (sp_tx_aux_dpcdwrite_bytes(0x00, 0x05, 0xf0, 3, pBuf) == AUX_OK)
break;
if (!count)
pr_err("%s %s : dpcd write error\n", LOG_TAG, __func__);
} while (--count);
}
}
}
static void sp_tx_enable_audio_output(unchar benable)
{
unchar c;
sp_read_reg(TX_P0, SP_TX_AUD_CTRL, &c);
if (benable) {
if (c & AUD_EN) {/* if it has been enabled, disable first. */
c &= ~AUD_EN;
sp_write_reg(TX_P0, SP_TX_AUD_CTRL, c);
}
sp_tx_audioinfoframe_setup();
sp_tx_config_packets(AUDIF_PACKETS);
/* for audio multi-ch */
info_ANX7730_AUIF_changed();
/* end audio multi-ch */
c |= AUD_EN;
sp_write_reg(TX_P0, SP_TX_AUD_CTRL, c);
} else {
c &= ~AUD_EN;
sp_write_reg(TX_P0, SP_TX_AUD_CTRL, c);
sp_write_reg_and(TX_P0, SP_TX_PKT_EN_REG, ~AUD_IF_EN);
}
}
static void sp_tx_config_audio(void)
{
unchar c;
int i;
ulong M_AUD, LS_Clk = 0;
ulong AUD_Freq = 0;
pr_info("%s %s : **Config audio **\n", LOG_TAG, __func__);
slimport_block_power_ctrl(SP_TX_PWR_AUDIO, SP_POWER_ON);
sp_read_reg(RX_P0, 0xCA, &c);
switch (c & 0x0f) {
case 0x00:
AUD_Freq = 44.1;
break;
case 0x02:
AUD_Freq = 48;
break;
case 0x03:
AUD_Freq = 32;
break;
case 0x08:
AUD_Freq = 88.2;
break;
case 0x0a:
AUD_Freq = 96;
break;
case 0x0c:
AUD_Freq = 176.4;
break;
case 0x0e:
AUD_Freq = 192;
break;
default:
break;
}
switch (sp_tx_get_link_bw()) {
case LINK_1P62G:
LS_Clk = 162000;
break;
case LINK_2P7G:
LS_Clk = 270000;
break;
case LINK_5P4G:
LS_Clk = 540000;
break;
case LINK_6P75G:
LS_Clk = 675000;
break;
default:
break;
}
pr_info("%s %s : AUD_Freq = %ld , LS_CLK = %ld\n", LOG_TAG, __func__, AUD_Freq, LS_Clk);
M_AUD = ((512 * AUD_Freq) / LS_Clk) * 32768;
M_AUD = M_AUD + 0x05;
sp_write_reg(TX_P1, SP_TX_AUD_INTERFACE_CTRL4, (M_AUD & 0xff));
M_AUD = M_AUD >> 8;
sp_write_reg(TX_P1, SP_TX_AUD_INTERFACE_CTRL5, (M_AUD & 0xff));
sp_write_reg(TX_P1, SP_TX_AUD_INTERFACE_CTRL6, 0x00);
sp_write_reg_and(TX_P1, SP_TX_AUD_INTERFACE_CTRL0, ~AUD_INTERFACE_DISABLE);
sp_write_reg_or(TX_P1, SP_TX_AUD_INTERFACE_CTRL2, M_AUD_ADJUST_ST);
sp_read_reg(RX_P0, HDMI_STATUS, &c);
if (c & HDMI_AUD_LAYOUT)
sp_write_reg_or(TX_P2, SP_TX_AUD_CH_NUM_REG5, CH_NUM_8 |AUD_LAYOUT);
else
sp_write_reg_and(TX_P2, SP_TX_AUD_CH_NUM_REG5, (~CH_NUM_8) & (~AUD_LAYOUT));
/* transfer audio chaneel status from HDMI Rx to Slinmport Tx */
for (i = 0; i < 5; i++) {
sp_read_reg(RX_P0, (HDMI_RX_AUD_IN_CH_STATUS1_REG + i), &c);
sp_write_reg(TX_P2, (SP_TX_AUD_CH_STATUS_REG1 + i), c);
}
/* enable audio */
sp_tx_enable_audio_output(1);
/*
sp_read_reg(TX_P2, SP_COMMON_INT_MASK1, &c);
c |= 0x04;
sp_write_reg(TX_P2, SP_COMMON_INT_MASK1, c);
*/
}
void slimport_config_audio_output(void)
{
static unchar count = 0;
switch(sp_tx_ao_state){
default:
case AO_INIT:
case AO_CTS_RCV_INT:
case AO_AUDIO_RCV_INT:
if (!(__i2c_read_byte(RX_P0, HDMI_STATUS) & HDMI_MODE)) {
sp_tx_ao_state = AO_INIT;
goto_next_system_state();
}
break;
case AO_RCV_INT_FINISH:
if(count++ > 2)
sp_tx_ao_state = AO_OUTPUT;
else
sp_tx_ao_state = AO_INIT;
SP_BREAK(AO_INIT, sp_tx_ao_state);
case AO_OUTPUT:
count = 0;
sp_tx_ao_state = AO_INIT;
sp_tx_video_mute(0);
hdmi_rx_mute_audio(0);
sp_tx_config_audio();
goto_next_system_state();
break;
}
}
/******************End Audio process********************/
void slimport_initialization(void)
{
#ifdef ENABLE_READ_EDID
g_read_edid_flag = 0;
#endif
slimport_block_power_ctrl(SP_TX_PWR_REG, SP_POWER_ON);
slimport_block_power_ctrl(SP_TX_PWR_TOTAL, SP_POWER_ON);
/*Driver Version*/
sp_write_reg(TX_P1, FW_VER_REG, FW_VERSION);
/*disable OCM*/
sp_write_reg_or(TX_P1, OCM_REG3, OCM_RST);
vbus_power_ctrl(1);
hdmi_rx_initialization();
sp_tx_initialization();
/*waiting for downstream to be stable,at least 200ms*/
msleep(200);
sp_tx_aux_polling_enable();
goto_next_system_state();
}
void slimport_cable_monitor(void)
{
unchar cur_cable_type;
if(sp_tx_system_state_bak != sp_tx_system_state
&& HDCP_state != HDCP_WAITTING_FINISH
&& sp_tx_LT_state != LT_WAITTING_FINISH){
if (sp_tx_cur_states() > STATE_SINK_CONNECTION){
cur_cable_type = sp_tx_get_cable_type(GETTED_CABLE_TYPE, 0);
if(cur_cable_type!= sp_tx_rx_type) {//cable changed
//reg_hardware_reset();
sp_tx_clean_state_machine();
sp_tx_set_sys_state(STATE_SP_INITIALIZED);
mdelay(500);
}
}
}
}
void hdcp_external_ctrl_flag_monitor(void)
{
static unchar cur_flag = 0;
static unchar hdcp_flag = 0;
if ((sp_tx_rx_type == DWN_STRM_IS_ANALOG)
|| (sp_tx_rx_type == DWN_STRM_IS_VGA_9832)) {
if (external_block_en != cur_flag) {
cur_flag = external_block_en;
system_state_change_with_case(STATE_HDCP_AUTH);
}
}
if (hdcp_disable != hdcp_flag) {
hdcp_flag = hdcp_disable;
system_state_change_with_case(STATE_HDCP_AUTH);
}
}
void slimport_state_process (void)
{
switch (sp_tx_system_state) {
case STATE_INIT:
goto_next_system_state();
case STATE_WAITTING_CABLE_PLUG:
slimport_waitting_cable_plug_process();
SP_BREAK(STATE_WAITTING_CABLE_PLUG, sp_tx_system_state);
case STATE_SP_INITIALIZED:
slimport_initialization();
SP_BREAK(STATE_SP_INITIALIZED, sp_tx_system_state);
case STATE_SINK_CONNECTION:
slimport_sink_connection();
SP_BREAK(STATE_SINK_CONNECTION, sp_tx_system_state);
#ifdef ENABLE_READ_EDID
case STATE_PARSE_EDID:
slimport_edid_process();
SP_BREAK(STATE_PARSE_EDID, sp_tx_system_state);
#endif
case STATE_LINK_TRAINING:
slimport_link_training();
SP_BREAK(STATE_LINK_TRAINING, sp_tx_system_state);
case STATE_VIDEO_OUTPUT:
slimport_config_video_output();
SP_BREAK(STATE_VIDEO_OUTPUT, sp_tx_system_state);
#ifndef HDCP_AUTO_EN
case STATE_HDCP_AUTH:
slimport_hdcp_process();
SP_BREAK(STATE_HDCP_AUTH, sp_tx_system_state);
#endif
case STATE_AUDIO_OUTPUT:
slimport_config_audio_output();
SP_BREAK(STATE_AUDIO_OUTPUT, sp_tx_system_state);
case STATE_PLAY_BACK:
/* slimport_playback_process(); */
SP_BREAK(STATE_PLAY_BACK, sp_tx_system_state);
default:
break;
}
}
/******************Start INT process********************/
void sp_tx_int_rec(void)
{
sp_read_reg(TX_P2, SP_COMMON_INT_STATUS1, &COMMON_INT1);
sp_write_reg(TX_P2, SP_COMMON_INT_STATUS1, COMMON_INT1);
sp_read_reg(TX_P2, SP_COMMON_INT_STATUS1 + 1, &COMMON_INT2);
sp_write_reg(TX_P2, SP_COMMON_INT_STATUS1 + 1, COMMON_INT2);
sp_read_reg(TX_P2, SP_COMMON_INT_STATUS1 + 2, &COMMON_INT3);
sp_write_reg(TX_P2, SP_COMMON_INT_STATUS1 + 2, COMMON_INT3);
sp_read_reg(TX_P2, SP_COMMON_INT_STATUS1 + 3, &COMMON_INT4);
sp_write_reg(TX_P2, SP_COMMON_INT_STATUS1 + 3, COMMON_INT4);
sp_read_reg(TX_P2, SP_COMMON_INT_STATUS1 + 6, &COMMON_INT5);
sp_write_reg(TX_P2, SP_COMMON_INT_STATUS1 + 6, COMMON_INT5);
}
void hdmi_rx_int_rec(void)
{
/* if((hdmi_system_state < HDMI_CLOCK_DET)||(sp_tx_system_state <STATE_CONFIG_HDMI))
* return;*/
sp_read_reg(RX_P0, HDMI_RX_INT_STATUS1_REG , &HDMI_RX_INT1);
sp_write_reg(RX_P0, HDMI_RX_INT_STATUS1_REG , HDMI_RX_INT1);
sp_read_reg(RX_P0, HDMI_RX_INT_STATUS2_REG , &HDMI_RX_INT2);
sp_write_reg(RX_P0, HDMI_RX_INT_STATUS2_REG , HDMI_RX_INT2);
sp_read_reg(RX_P0, HDMI_RX_INT_STATUS3_REG , &HDMI_RX_INT3);
sp_write_reg(RX_P0, HDMI_RX_INT_STATUS3_REG , HDMI_RX_INT3);
sp_read_reg(RX_P0, HDMI_RX_INT_STATUS4_REG , &HDMI_RX_INT4);
sp_write_reg(RX_P0, HDMI_RX_INT_STATUS4_REG , HDMI_RX_INT4);
sp_read_reg(RX_P0, HDMI_RX_INT_STATUS5_REG , &HDMI_RX_INT5);
sp_write_reg(RX_P0, HDMI_RX_INT_STATUS5_REG , HDMI_RX_INT5);
sp_read_reg(RX_P0, HDMI_RX_INT_STATUS6_REG , &HDMI_RX_INT6);
sp_write_reg(RX_P0, HDMI_RX_INT_STATUS6_REG , HDMI_RX_INT6);
sp_read_reg(RX_P0, HDMI_RX_INT_STATUS7_REG , &HDMI_RX_INT7);
sp_write_reg(RX_P0, HDMI_RX_INT_STATUS7_REG , HDMI_RX_INT7);
}
void slimport_int_rec(void)
{
sp_tx_int_rec();
hdmi_rx_int_rec();
/*
if(!sp_tx_pd_mode ){
sp_tx_int_irq_handler();
hdmi_rx_int_irq_handler();
}
*/
}
/******************End INT process********************/
/******************Start task process********************/
static void sp_tx_pll_changed_int_handler(void)
{
if (sp_tx_system_state >= STATE_LINK_TRAINING) {
if (!sp_tx_get_pll_lock_status()) {
pr_info("%s %s : PLL:PLL not lock!\n", LOG_TAG, __func__);
sp_tx_set_sys_state(STATE_LINK_TRAINING);
}
}
}
static void sp_tx_hdcp_link_chk_fail_handler(void)
{
#ifndef HDCP_AUTO_EN
system_state_change_with_case(STATE_HDCP_AUTH);
#endif
pr_info("%s %s : hdcp_link_chk_fail:HDCP Sync lost!\n", LOG_TAG, __func__);
}
static unchar link_down_check(void)
{
unchar return_value;
return_value = 0;
pr_info("%s %s : link_down_check\n", LOG_TAG, __func__);
if ((sp_tx_system_state > STATE_LINK_TRAINING)) {
if (!(__i2c_read_byte(TX_P0, DPCD_204) & 0x01)
|| ((__i2c_read_byte(TX_P0, DPCD_202) & (0x01 | 0x04))) != 0x05) { /* xjh modify for link CTS 22 */
if (sp_tx_get_downstream_connection()) {
sp_tx_set_sys_state(STATE_LINK_TRAINING);
pr_info("%s %s : INT:re-LT request!\n", LOG_TAG, __func__);
} else {
vbus_power_ctrl(0);
reg_hardware_reset();
return_value = 1;
}
} else {
pr_info("%s %s : Lane align %x\n", LOG_TAG, __func__, (uint)__i2c_read_byte(TX_P0, DPCD_204));
pr_info("%s %s : Lane clock recovery %x\n", LOG_TAG, __func__, (uint)__i2c_read_byte(TX_P0, DPCD_202));
}
}
return return_value;
}
static void sp_tx_phy_auto_test(void)
{
unchar b_sw;
unchar c1;
unchar bytebuf[16];
unchar link_bw;
/*DPCD 0x219 TEST_LINK_RATE*/
sp_tx_aux_dpcdread_bytes(0x0, 0x02, 0x19, 1, bytebuf);
pr_info("%s %s : DPCD:0x00219 = %.2x\n", LOG_TAG, __func__, (uint)bytebuf[0]);
switch(bytebuf[0]){
case 0x06:
case 0x0A:
case 0x14:
case 0x19:
sp_tx_set_link_bw(bytebuf[0]);
sp_tx_test_bw = bytebuf[0];
break;
default:
sp_tx_set_link_bw(0x19);
sp_tx_test_bw = 0x19;
break;
}
/*DPCD 0x248 PHY_TEST_PATTERN*/
sp_tx_aux_dpcdread_bytes(0x0, 0x02, 0x48, 1, bytebuf);
pr_info("%s %s : DPCD:0x00248 = %.2x\n", LOG_TAG, __func__, (uint)bytebuf[0]);
switch (bytebuf[0]) {
case 0:
pr_info("%s %s : No test pattern selected\n", LOG_TAG, __func__);
break;
case 1:
sp_write_reg(TX_P0, SP_TX_TRAINING_PTN_SET_REG, 0x04);
pr_info("%s %s : D10.2 Pattern\n", LOG_TAG, __func__);
break;
case 2:
sp_write_reg(TX_P0, SP_TX_TRAINING_PTN_SET_REG, 0x08);
pr_info("%s %s : Symbol Error Measurement Count\n", LOG_TAG, __func__);
break;
case 3:
sp_write_reg(TX_P0, SP_TX_TRAINING_PTN_SET_REG, 0x0c);
pr_info("%s %s : PRBS7 Pattern\n", LOG_TAG, __func__);
break;
case 4:
sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x50, 0xa, bytebuf);
sp_write_reg(TX_P1, 0x80, bytebuf[0]);
sp_write_reg(TX_P1, 0x81, bytebuf[1]);
sp_write_reg(TX_P1, 0x82, bytebuf[2]);
sp_write_reg(TX_P1, 0x83, bytebuf[3]);
sp_write_reg(TX_P1, 0x84, bytebuf[4]);
sp_write_reg(TX_P1, 0x85, bytebuf[5]);
sp_write_reg(TX_P1, 0x86, bytebuf[6]);
sp_write_reg(TX_P1, 0x87, bytebuf[7]);
sp_write_reg(TX_P1, 0x88, bytebuf[8]);
sp_write_reg(TX_P1, 0x89, bytebuf[9]);
sp_write_reg(TX_P0, SP_TX_TRAINING_PTN_SET_REG, 0x30);
pr_info("%s %s : 80bit custom pattern transmitted\n", LOG_TAG, __func__);
break;
case 5:
sp_write_reg(TX_P0, 0xA9, 0x00);
sp_write_reg(TX_P0, 0xAA, 0x01);
sp_write_reg(TX_P0, SP_TX_TRAINING_PTN_SET_REG, 0x14);
pr_info("%s %s : HBR2 Compliance Eye Pattern\n", LOG_TAG, __func__);
break;
}
sp_tx_aux_dpcdread_bytes(0x00, 0x00, 0x03, 1, bytebuf);
pr_info("%s %s : DPCD:0x00003 = %.2x\n", LOG_TAG, __func__, (uint)bytebuf[0]);
switch (bytebuf[0] & 0x01) {
case 0:
sp_tx_spread_enable(0);
pr_info("%s %s : SSC OFF\n", LOG_TAG, __func__);
break;
case 1:
sp_read_reg(TX_P0, SP_TX_LINK_BW_SET_REG, &c1);
switch (c1) {
case 0x06:
link_bw = 0x06;
break;
case 0x0a:
link_bw = 0x0a;
break;
case 0x14:
link_bw = 0x14;
break;
case 0x19:
link_bw = 0x19;
break;
default:
link_bw = 0x00;
break;
}
sp_tx_config_ssc(SSC_DEP_4000PPM);
pr_info("%s %s : SSC ON\n", LOG_TAG, __func__);
break;
}
/*get swing and emphasis adjust request*/
sp_read_reg(TX_P0, 0xA3, &b_sw);
sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x06, 1, bytebuf);
pr_info("%s %s : DPCD:0x00206 = %.2x\n", LOG_TAG, __func__, (uint)bytebuf[0]);
c1 = bytebuf[0] & 0x0f;
switch (c1) {
case 0x00:
sp_write_reg(TX_P0, 0xA3, (b_sw & ~0x1b) | 0x00);
pr_info("%s %s : lane0,Swing200mv, emp 0db.\n", LOG_TAG, __func__);
break;
case 0x01:
sp_write_reg(TX_P0, 0xA3, (b_sw & ~0x1b) | 0x01);
pr_info("%s %s : lane0,Swing400mv, emp 0db.\n", LOG_TAG, __func__);
break;
case 0x02:
sp_write_reg(TX_P0, 0xA3, (b_sw & ~0x1b) | 0x02);
pr_info("%s %s : lane0,Swing600mv, emp 0db.\n", LOG_TAG, __func__);
break;
case 0x03:
sp_write_reg(TX_P0, 0xA3, (b_sw & ~0x1b) | 0x03);
pr_info("%s %s : lane0,Swing800mv, emp 0db.\n", LOG_TAG, __func__);
break;
case 0x04:
sp_write_reg(TX_P0, 0xA3, (b_sw & ~0x1b) | 0x08);
pr_info("%s %s : lane0,Swing200mv, emp 3.5db.\n", LOG_TAG, __func__);
break;
case 0x05:
sp_write_reg(TX_P0, 0xA3, (b_sw & ~0x1b) | 0x09);
pr_info("%s %s : lane0,Swing400mv, emp 3.5db.\n", LOG_TAG, __func__);
break;
case 0x06:
sp_write_reg(TX_P0, 0xA3, (b_sw & ~0x1b) | 0x0a);
pr_info("%s %s : lane0,Swing600mv, emp 3.5db.\n", LOG_TAG, __func__);
break;
case 0x08:
sp_write_reg(TX_P0, 0xA3, (b_sw & ~0x1b) | 0x10);
pr_info("%s %s : lane0,Swing200mv, emp 6db.\n", LOG_TAG, __func__);
break;
case 0x09:
sp_write_reg(TX_P0, 0xA3, (b_sw & ~0x1b) | 0x11);
pr_info("%s %s : lane0,Swing400mv, emp 6db.\n", LOG_TAG, __func__);
break;
case 0x0c:
sp_write_reg(TX_P0, 0xA3, (b_sw & ~0x1b) | 0x18);
pr_info("%s %s : lane0,Swing200mv, emp 9.5db.\n", LOG_TAG, __func__);
break;
default:
break;
}
}
static void sp_tx_sink_irq_int_handler(void)
{
unchar c, c1;
unchar IRQ_Vector; /* Int_vector1, Int_vector2; */
unchar Int_vector[2]; /* by span 20130217 */
unchar test_vector;
unchar temp, need_return;
need_return = 0;
pr_info("%s %s : sp_tx_sink_irq_int_handler \n" , LOG_TAG, __func__);
IRQ_Vector = __i2c_read_byte(TX_P0, DPCD_201);
if (IRQ_Vector != 0)
sp_tx_aux_dpcdwrite_bytes(0x00, 0x02, DPCD_SERVICE_IRQ_VECTOR, 1, &IRQ_Vector);
else
return;
/* HDCP IRQ */
if (IRQ_Vector & CP_IRQ) {
#ifndef HDCP_AUTO_EN
if (HDCP_state > HDCP_WAITTING_FINISH
|| sp_tx_system_state > STATE_HDCP_AUTH)
#endif
{
sp_tx_aux_dpcdread_bytes(0x06, 0x80, 0x29, 1, &c1);
if (c1 & 0x04) {
#ifndef HDCP_AUTO_EN
system_state_change_with_case(STATE_HDCP_AUTH);
sp_tx_clean_hdcp_status();
#endif
pr_info("%s %s : IRQ:____________HDCP Sync lost!\n", LOG_TAG, __func__);
}
}
}
if((IRQ_Vector & SINK_SPECIFIC_IRQ)
&& (sp_tx_system_state > STATE_SP_INITIALIZED)
&& (downstream_charging_status != NO_CHARGING_CAPABLE)){
downstream_charging_status_set();
}
if(sp_tx_system_state <= STATE_SINK_CONNECTION) return;
/* specific int */
if (IRQ_Vector & SINK_SPECIFIC_IRQ) {
if (sp_tx_rx_type == DWN_STRM_IS_HDMI) {
sp_tx_aux_dpcdread_bytes(0x00, 0x05, DPCD_SPECIFIC_INTERRUPT1,
2, Int_vector);
sp_tx_aux_dpcdwrite_bytes(0x00, 0x05, DPCD_SPECIFIC_INTERRUPT1,
2, Int_vector);
temp = 0x01;
do {
switch( Int_vector[0] & temp) {
default:
break;
case 0x01:
if ((Int_vector[0] & 0x01) == 0x01) {//downstream HPD changed from 0 to 1
sp_tx_aux_dpcdread_bytes(0x00, 0x05, 0x18, 1, &c);
if (c & 0x01)
pr_info("%s %s : Downstream HDMI is pluged!\n", LOG_TAG, __func__);
}
break;
case 0x02:
sp_tx_aux_dpcdread_bytes(0x00, 0x05, 0x18, 1, &c);
if ((c & (DOWN_STRM_HPD | DOWN_R_TERM_DET)) != 0x00){
pr_info("%s %s : fake unplug event!\n", LOG_TAG, __func__);
sp_tx_clean_state_machine();
sp_tx_set_sys_state(STATE_LINK_TRAINING);
}else{
pr_info("%s %s : Downstream HDMI is unpluged!\n", LOG_TAG, __func__);
vbus_power_ctrl(0);
reg_hardware_reset();
sp_tx_set_sys_state(STATE_SP_INITIALIZED);
need_return = 1;
}
break;
case 0x04:
pr_info("%s %s : Here is check: Link is down!\n", LOG_TAG, __func__);
if((sp_tx_system_state > STATE_VIDEO_OUTPUT)) {
pr_info("%s %s : Rx specific IRQ: Link is down!\n", LOG_TAG, __func__);
need_return = link_down_check();
}
break;
case 0x08:
if ((Int_vector[0] & 0x10) != 0x10)
pr_info("%s %s : Downstream HDCP is passed!\n", LOG_TAG, __func__);
else {
#ifndef HDCP_AUTO_EN
if (sp_tx_system_state >= STATE_HDCP_AUTH) {
sp_tx_video_mute(1);
sp_tx_set_sys_state(STATE_HDCP_AUTH);
pr_info("%s %s : Re-authentication due to downstream HDCP failure!\n", LOG_TAG, __func__);
sp_tx_clean_hdcp_status();
}
#else
//sp_tx_clean_hdcp_status();
pr_info("%s %s : Re-authentication due to downstream HDCP failure!\n", LOG_TAG, __func__);
#endif
}
break;
case 0x10:
break;
case 0x20:
pr_info("%s %s : Downstream HDCP link integrity check fail!\n", LOG_TAG, __func__);
#ifndef HDCP_AUTO_EN
system_state_change_with_case(STATE_HDCP_AUTH);
//msleep(2000);//20130217 by span for samsung monitor
sp_tx_clean_hdcp_status();
#endif
pr_info("%s %s : IRQ:____________HDCP Sync lost!\n", LOG_TAG, __func__);
break;
#ifdef CEC_ENABLE
case 0x40:
if(TASK_OK == dp_cec_recv_process())
cec.dp_cec_receive_done = 1;
pr_info("%s %s : Receive CEC command from downstream done!\n", LOG_TAG, __func__);
break;
case 0x80:
cec.dp_cec_transmit_done = 1;
pr_info("%s %s : CEC command transfer to downstream done!\n", LOG_TAG, __func__);
break;
#endif
}
if(need_return == 1)
return;
temp = (temp << 1);
}while(temp != 0);
#ifdef CEC_ENABLE
if (Int_vector[1] & 0x03) //tx error or no ack
cec.dp_frametx_error = 1;
#endif
if ((Int_vector[1] & 0x04) == 0x04) {
sp_tx_aux_dpcdread_bytes(0x00, 0x05, 0x18, 1, &c);
if ((c & 0x40) == 0x40)
pr_info("%s %s : Downstream HDMI termination is detected!\n", LOG_TAG, __func__);
}
} else if (sp_tx_rx_type != DWN_STRM_IS_HDMI) {
/* sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x00, 1, &c); */
c = __i2c_read_byte(TX_P0, DPCD_200);
if (!(c & 0x01)) {
if (sp_tx_system_state > STATE_SINK_CONNECTION) {
vbus_power_ctrl(0);
reg_hardware_reset();
} else {
if (sp_tx_rx_type == DWN_STRM_IS_VGA_9832)
sp_tx_send_message(MSG_CLEAR_IRQ);
}
if (sp_tx_system_state >= STATE_LINK_TRAINING) {
link_down_check();
}
}
}
}
/* AUTOMATED TEST IRQ */
if (IRQ_Vector & TEST_IRQ) {
sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x18, 1, &test_vector);
if (test_vector & 0x01) {/* test link training */
sp_tx_test_lt = 1;
sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x19,1,&c);
switch(c){
case 0x06:
case 0x0A:
case 0x14:
case 0x19:
sp_tx_set_link_bw(c);
sp_tx_test_bw = c;
break;
default:
sp_tx_set_link_bw(0x19);
sp_tx_test_bw = 0x19;
break;
}
pr_info("%s %s : test_bw = %.2x\n", LOG_TAG, __func__, (uint)sp_tx_test_bw);
sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x60, 1, &c);
c = c | TEST_ACK;
sp_tx_aux_dpcdwrite_bytes(0x00, 0x02, 0x60,1, &c);
pr_info("%s %s : Set TEST_ACK!\n", LOG_TAG, __func__);
if (sp_tx_system_state >= STATE_LINK_TRAINING){
sp_tx_LT_state = LT_INIT;
sp_tx_set_sys_state(STATE_LINK_TRAINING);
}
pr_info("%s %s : IRQ:test-LT request!\n", LOG_TAG, __func__);
}
if(test_vector & 0x02){
//pr_info("-------------------test pattern\n");
sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x60,1,&c);
c = c | TEST_ACK;
sp_tx_aux_dpcdwrite_bytes(0x00, 0x02, 0x60,1, &c);
}
if (test_vector & 0x04) {//test edid
if (sp_tx_system_state > STATE_PARSE_EDID)
sp_tx_set_sys_state(STATE_PARSE_EDID);
sp_tx_test_edid = 1;
pr_info("%s %s : Test EDID Requested!\n", LOG_TAG, __func__);
}
if (test_vector & 0x08) {//phy test pattern
sp_tx_test_lt = 1;
sp_tx_phy_auto_test();
sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x60, 1, &c);
c = c | 0x01;
sp_tx_aux_dpcdwrite_bytes(0x00, 0x02, 0x60, 1, &c);
/*
sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x60, 1, &c);
while((c & 0x03) == 0){
c = c | 0x01;
sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x60, 1, &c);
sp_tx_aux_dpcdread_bytes(0x00, 0x02, 0x60, 1, &c);
}*/
}
}
}
static void sp_tx_vsi_setup(void)
{
unchar c;
int i;
for (i = 0; i < 10; i++) {
sp_read_reg(RX_P1, (HDMI_RX_MPEG_DATA00_REG + i), &c);
sp_tx_packet_mpeg.MPEG_data[i] = c;
}
}
static void sp_tx_mpeg_setup(void)
{
unchar c;
int i;
for (i = 0; i < 10; i++) {
sp_read_reg(RX_P1, (HDMI_RX_MPEG_DATA00_REG + i), &c);
sp_tx_packet_mpeg.MPEG_data[i] = c;
}
}
static void sp_tx_auth_done_int_handler(void)
{
#ifndef HDCP_AUTO_EN
unchar bytebuf[2];
if (HDCP_state > HDCP_HW_ENABLE
&& sp_tx_system_state == STATE_HDCP_AUTH) {
sp_read_reg(TX_P0, SP_TX_HDCP_STATUS, bytebuf);
if (bytebuf[0] & SP_TX_HDCP_AUTH_PASS) {
sp_tx_aux_dpcdread_bytes(0x06, 0x80, 0x2A, 2, bytebuf);
/* max cascade exceeded or max devs exceed, disable encryption */
if ((bytebuf[1] & 0x08) || (bytebuf[0]&0x80)) {
pr_info("%s %s : max cascade/devs exceeded!\n", LOG_TAG, __func__);
sp_tx_hdcp_encryption_disable();
} else
pr_info("%s %s : Authentication pass in Auth_Done\n", LOG_TAG, __func__);
HDCP_state = HDCP_FINISH;
} else {
pr_err("%s %s : Authentication failed in AUTH_done\n", LOG_TAG, __func__);
sp_tx_video_mute(1);
sp_tx_clean_hdcp_status();
HDCP_state = HDCP_FAILE;
}
}
#endif
pr_info("%s %s : sp_tx_auth_done_int_handler \n", LOG_TAG, __func__);
}
static void sp_tx_polling_err_int_handler(void)
{
/* unchar temp; */
pr_info("%s %s : sp_tx_polling_err_int_handler \n", LOG_TAG, __func__);
#ifdef CONFIG_SLIMPORT_DYNAMIC_HPD
slimport_set_hdmi_hpd(0);
#endif
/* if (AUX_ERR == sp_tx_aux_dpcdread_bytes(0x00, 0x00, 0x00, 1, &temp)) */
system_power_ctrl(0);
}
static void sp_tx_lt_done_int_handler(void)
{
unchar c;
if (sp_tx_LT_state == LT_WAITTING_FINISH
&& sp_tx_system_state == STATE_LINK_TRAINING) {
sp_read_reg(TX_P0, LT_CTRL, &c);
if (c & 0x70) {
c = (c & 0x70) >> 4;
pr_info("%s %s : LT failed in interrupt, ERR code = %.2x\n", LOG_TAG, __func__, (uint) c);
sp_tx_LT_state = LT_ERROR;
} else {
pr_info("%s %s : lt_done: LT Finish \n", LOG_TAG, __func__);
sp_tx_LT_state = LT_FINISH;
}
}
}
static void sp_tx_link_change_int_handler(void)
{
pr_info("%s %s : sp_tx_link_change_int_handler \n", LOG_TAG, __func__);
if (sp_tx_system_state < STATE_LINK_TRAINING)
return;
sp_tx_link_err_check();
link_down_check();
}
static void hdmi_rx_clk_det_int(void)
{
pr_info("%s %s : *HDMI_RX Interrupt: Pixel Clock Change.\n", LOG_TAG, __func__);
if (sp_tx_system_state > STATE_VIDEO_OUTPUT) {
sp_tx_video_mute(1);
sp_tx_enable_audio_output(0);
sp_tx_set_sys_state(STATE_VIDEO_OUTPUT);
}
}
static void hdmi_rx_sync_det_int(void)
{
pr_info("%s %s : *HDMI_RX Interrupt: Sync Detect.\n", LOG_TAG, __func__);
}
static void hdmi_rx_hdmi_dvi_int(void)
{
unchar c;
pr_info("%s %s : hdmi_rx_hdmi_dvi_int. \n", LOG_TAG, __func__);
sp_read_reg(RX_P0, HDMI_STATUS, &c);
g_hdmi_dvi_status = read_dvi_hdmi_mode();
if ((c & _BIT0) != (g_hdmi_dvi_status & _BIT0)) {
pr_info("%s %s : hdmi_dvi_int: Is HDMI MODE: %x.\n", LOG_TAG, __func__, (uint)(c & HDMI_MODE));
g_hdmi_dvi_status = (c & _BIT0);
hdmi_rx_mute_audio(1);
system_state_change_with_case(STATE_LINK_TRAINING);
}
}
/*
static void hdmi_rx_avmute_int(void)
{
unchar avmute_status, c;
sp_read_reg(RX_P0, HDMI_STATUS,
&avmute_status);
if (avmute_status & MUTE_STAT) {
pr_info("%s %s : HDMI_RX AV mute packet received.\n", LOG_TAG, __func__);
hdmi_rx_mute_video(1);
hdmi_rx_mute_audio(1);
c = avmute_status & (~MUTE_STAT);
sp_write_reg(RX_P0, HDMI_STATUS, c);
}
}
*/
static void hdmi_rx_new_avi_int(void)
{
pr_info("%s %s : *HDMI_RX Interrupt: New AVI Packet.\n", LOG_TAG, __func__);
sp_tx_lvttl_bit_mapping();
sp_tx_set_colorspace();
sp_tx_avi_setup();
sp_tx_config_packets(AVI_PACKETS);
}
static void hdmi_rx_new_vsi_int(void)
{
//unchar c;
unchar hdmi_video_format,v3d_structure;
pr_info("%s %s : *HDMI_RX Interrupt: NEW VSI packet.\n", LOG_TAG, __func__);
sp_write_reg_and(TX_P0, SP_TX_3D_VSC_CTRL, ~INFO_FRAME_VSC_EN);
/*VSI package header*/
if((__i2c_read_byte(RX_P1, HDMI_RX_MPEG_TYPE_REG) != 0x81)
|| (__i2c_read_byte(RX_P1, HDMI_RX_MPEG_VER_REG) != 0x01))
return ;
pr_info("%s %s : Setup VSI package!\n", LOG_TAG, __func__);
sp_tx_vsi_setup(); //use mpeg packet as mail box to send vsi packet
sp_tx_config_packets(VSI_PACKETS);
sp_read_reg(RX_P1, HDMI_RX_MPEG_DATA03_REG, &hdmi_video_format);
if((hdmi_video_format & 0xe0)== 0x40)
{
pr_info("%s %s : 3D VSI packet is detected. Config VSC packet\n", LOG_TAG, __func__);
sp_read_reg(RX_P1, HDMI_RX_MPEG_DATA05_REG, &v3d_structure);
switch(v3d_structure&0xf0){
case 0x00://frame packing
v3d_structure = 0x02;
break;
case 0x20://Line alternative
v3d_structure = 0x03;
break;
case 0x30://Side-by-side(full)
v3d_structure = 0x04;
break;
default:
v3d_structure = 0x00;
pr_info("%s %s : 3D structure is not supported\n", LOG_TAG, __func__);
break;
}
sp_write_reg(TX_P0, SP_TX_VSC_DB1, v3d_structure);
}
sp_write_reg_or(TX_P0, SP_TX_3D_VSC_CTRL, INFO_FRAME_VSC_EN);
sp_write_reg_and(TX_P0, SP_TX_PKT_EN_REG, ~SPD_IF_EN);
sp_write_reg_or(TX_P0, SP_TX_PKT_EN_REG, SPD_IF_UD);
sp_write_reg_or(TX_P0, SP_TX_PKT_EN_REG, SPD_IF_EN);
}
static void hdmi_rx_no_vsi_int(void)
{
unchar c;
sp_read_reg(TX_P0, SP_TX_3D_VSC_CTRL, &c);
if(c&INFO_FRAME_VSC_EN)
{
pr_info("%s %s : No new VSI is received, disable VSC packet\n", LOG_TAG, __func__);
c &= ~INFO_FRAME_VSC_EN;
sp_write_reg(TX_P0, SP_TX_3D_VSC_CTRL, c);
sp_tx_mpeg_setup();
sp_tx_config_packets(MPEG_PACKETS);
}
}
static void hdmi_rx_restart_audio_chk(void)
{
pr_info("%s %s : WAIT_AUDIO: hdmi_rx_restart_audio_chk.\n", LOG_TAG, __func__);
system_state_change_with_case(STATE_AUDIO_OUTPUT);
}
static void hdmi_rx_cts_rcv_int(void)
{
if (sp_tx_ao_state == AO_INIT)
sp_tx_ao_state = AO_CTS_RCV_INT;
else if (sp_tx_ao_state == AO_AUDIO_RCV_INT)
sp_tx_ao_state = AO_RCV_INT_FINISH;
/* pr_info("%s %s : *hdmi_rx_cts_rcv_int. \n", LOG_TAG, __func__); */
return;
}
static void hdmi_rx_audio_rcv_int(void)
{
if (sp_tx_ao_state == AO_INIT)
sp_tx_ao_state = AO_AUDIO_RCV_INT;
else if (sp_tx_ao_state == AO_CTS_RCV_INT)
sp_tx_ao_state = AO_RCV_INT_FINISH;
/* pr_info("%s %s : *hdmi_rx_audio_rcv_int\n", LOG_TAG, __func__); */
return;
}
static void hdmi_rx_audio_samplechg_int(void)
{
uint i;
unchar c;
/* transfer audio chaneel status from HDMI Rx to Slinmport Tx */
for (i = 0; i < 5; i++) {
sp_read_reg(RX_P0, (HDMI_RX_AUD_IN_CH_STATUS1_REG + i), &c);
sp_write_reg(TX_P2, (SP_TX_AUD_CH_STATUS_REG1 + i), c);
}
// pr_info("%s %s : *hdmi_rx_audio_samplechg_int\n", LOG_TAG, __func__);
return;
}
static void hdmi_rx_hdcp_error_int(void)
{
static unchar count = 0;
pr_info("%s %s : *HDMI_RX Interrupt: hdcp error.\n", LOG_TAG, __func__);
if(count >= 40) {
count = 0;
pr_info("%s %s : Lots of hdcp error occured ...\n", LOG_TAG, __func__);
hdmi_rx_mute_audio(1);
hdmi_rx_mute_video(1);
hdmi_rx_set_hpd(0);
mdelay(10);
hdmi_rx_set_hpd(1);
} else
count++;
}
static void hdmi_rx_new_gcp_int(void)
{
unchar c;
/* pr_info("%s %s : *HDMI_RX Interrupt: New GCP Packet.\n", LOG_TAG, __func__); */
sp_read_reg(RX_P1, HDMI_RX_GENERAL_CTRL, &c);
if (c&SET_AVMUTE) {
hdmi_rx_mute_video(1);
hdmi_rx_mute_audio(1);
} else if (c&CLEAR_AVMUTE) {
/* by span 20130217 */
/* if ((g_video_muted) && */
/* (hdmi_system_state >HDMI_VIDEO_CONFIG)) */
hdmi_rx_mute_video(0);
/* if ((g_audio_muted) && */
/* (hdmi_system_state >HDMI_AUDIO_CONFIG)) */
hdmi_rx_mute_audio(0);
}
}
void system_isr_handler(void)
{
/* if (sp_tx_system_state < STATE_PLAY_BACK) */
/* pr_info("%s %s : ========= system_isr ========== \n", LOG_TAG, __func__); */
if (COMMON_INT1 & PLL_LOCK_CHG)
sp_tx_pll_changed_int_handler();
if (COMMON_INT2 & HDCP_AUTH_DONE)
sp_tx_auth_done_int_handler();
if (COMMON_INT3 & HDCP_LINK_CHECK_FAIL)
sp_tx_hdcp_link_chk_fail_handler();
if (COMMON_INT5 & DPCD_IRQ_REQUEST)
sp_tx_sink_irq_int_handler();
if(sp_tx_system_state > STATE_SP_INITIALIZED){
if (COMMON_INT5 & POLLING_ERR)
sp_tx_polling_err_int_handler();
}
if (COMMON_INT5 & TRAINING_Finish)
sp_tx_lt_done_int_handler();
if (COMMON_INT5 & LINK_CHANGE)
sp_tx_link_change_int_handler();
if (sp_tx_system_state > STATE_SINK_CONNECTION) {
if (HDMI_RX_INT6 & NEW_AVI)
hdmi_rx_new_avi_int();
#ifdef CEC_ENABLE
if ( HDMI_RX_INT7 & CEC_RX_READY)
{
if(TASK_OK == hdmi_cec_recv_process())
cec.hdmi_cec_receive_done = 1;
pr_info("%s %s : HDMI -> DP receive CEC data done!\n", LOG_TAG, __func__);
}
if ( HDMI_RX_INT7 & CEC_TX_DONE)
{
cec.hdmi_cec_transmit_done = 1;
pr_info("%s %s : DP -> HDMI CEC data transmit done!\n", LOG_TAG, __func__);
}
#endif
}
if(sp_tx_system_state >STATE_VIDEO_OUTPUT) {
if (HDMI_RX_INT7 & NEW_VS){
HDMI_RX_INT7 &= ~NO_VSI; //clear no_vsi interrupt flag
hdmi_rx_new_vsi_int();
}
if (HDMI_RX_INT7 & NO_VSI)
hdmi_rx_no_vsi_int();
}
if(sp_tx_system_state >= STATE_VIDEO_OUTPUT) {
if (HDMI_RX_INT1 & CKDT_CHANGE)
hdmi_rx_clk_det_int();
if (HDMI_RX_INT1 & SCDT_CHANGE)
hdmi_rx_sync_det_int();
if (HDMI_RX_INT1 & HDMI_DVI)
hdmi_rx_hdmi_dvi_int();
/*
if (HDMI_RX_INT1 & SET_MUTE)
hdmi_rx_avmute_int();
*/
if((HDMI_RX_INT6 & NEW_AUD) || (HDMI_RX_INT3 & AUD_MODE_CHANGE))
hdmi_rx_restart_audio_chk();
if (HDMI_RX_INT6 & CTS_RCV)
hdmi_rx_cts_rcv_int();
if (HDMI_RX_INT5 & AUDIO_RCV)
hdmi_rx_audio_rcv_int();
if (HDMI_RX_INT2 & HDCP_ERR)
hdmi_rx_hdcp_error_int();
if (HDMI_RX_INT6 & NEW_CP)
hdmi_rx_new_gcp_int();
if (HDMI_RX_INT2 & AUDIO_SAMPLE_CHANGE)
hdmi_rx_audio_samplechg_int();
}
}
void sp_tx_show_infomation(void)
{
unchar c, c1;
uint h_res, h_act, v_res, v_act;
uint h_fp, h_sw, h_bp, v_fp, v_sw, v_bp;
ulong fresh_rate;
ulong pclk;
pr_info(" \n******************SP Video Information*******************\n");
sp_read_reg(TX_P0, SP_TX_LINK_BW_SET_REG, &c);
switch (c) {
case 0x06:
pr_info("%s %s : BW = 1.62G\n", LOG_TAG, __func__);
break;
case 0x0a:
pr_info("%s %s : BW = 2.7G\n", LOG_TAG, __func__);
break;
case 0x14:
pr_info("%s %s : BW = 5.4G\n", LOG_TAG, __func__);
break;
case 0x19:
pr_info("%s %s : BW = 6.75G\n", LOG_TAG, __func__);
break;
default:
break;
}
pclk = sp_tx_pclk_calc();
pclk = pclk / 10;
//pr_info("%s %s : SSC On\n", LOG_TAG, __func__);
sp_read_reg(TX_P2, SP_TX_TOTAL_LINE_STA_L, &c);
sp_read_reg(TX_P2, SP_TX_TOTAL_LINE_STA_H, &c1);
v_res = c1;
v_res = v_res << 8;
v_res = v_res + c;
sp_read_reg(TX_P2, SP_TX_ACT_LINE_STA_L, &c);
sp_read_reg(TX_P2, SP_TX_ACT_LINE_STA_H, &c1);
v_act = c1;
v_act = v_act << 8;
v_act = v_act + c;
sp_read_reg(TX_P2, SP_TX_TOTAL_PIXEL_STA_L, &c);
sp_read_reg(TX_P2, SP_TX_TOTAL_PIXEL_STA_H, &c1);
h_res = c1;
h_res = h_res << 8;
h_res = h_res + c;
sp_read_reg(TX_P2, SP_TX_ACT_PIXEL_STA_L, &c);
sp_read_reg(TX_P2, SP_TX_ACT_PIXEL_STA_H, &c1);
h_act = c1;
h_act = h_act << 8;
h_act = h_act + c;
sp_read_reg(TX_P2, SP_TX_H_F_PORCH_STA_L, &c);
sp_read_reg(TX_P2, SP_TX_H_F_PORCH_STA_H, &c1);
h_fp = c1;
h_fp = h_fp << 8;
h_fp = h_fp + c;
sp_read_reg(TX_P2, SP_TX_H_SYNC_STA_L, &c);
sp_read_reg(TX_P2, SP_TX_H_SYNC_STA_H, &c1);
h_sw = c1;
h_sw = h_sw << 8;
h_sw = h_sw + c;
sp_read_reg(TX_P2, SP_TX_H_B_PORCH_STA_L, &c);
sp_read_reg(TX_P2, SP_TX_H_B_PORCH_STA_H, &c1);
h_bp = c1;
h_bp = h_bp << 8;
h_bp = h_bp + c;
sp_read_reg(TX_P2, SP_TX_V_F_PORCH_STA, &c);
v_fp = c;
sp_read_reg(TX_P2, SP_TX_V_SYNC_STA, &c);
v_sw = c;
sp_read_reg(TX_P2, SP_TX_V_B_PORCH_STA, &c);
v_bp = c;
pr_info("%s %s : Total resolution is %d * %d \n", LOG_TAG, __func__, h_res, v_res);
pr_info("%s %s : HF=%d, HSW=%d, HBP=%d\n", LOG_TAG, __func__, h_fp, h_sw, h_bp);
pr_info("%s %s : VF=%d, VSW=%d, VBP=%d\n", LOG_TAG, __func__, v_fp, v_sw, v_bp);
pr_info("%s %s : Active resolution is %d * %d", LOG_TAG, __func__, h_act, v_act);
if(h_res == 0 || v_res == 0)
fresh_rate = 0;
else{
fresh_rate = pclk * 1000;
fresh_rate = fresh_rate / h_res;
fresh_rate = fresh_rate * 1000;
fresh_rate = fresh_rate / v_res;
}
pr_info(" @ %ldHz\n", fresh_rate);
sp_read_reg(TX_P0, SP_TX_VID_CTRL, &c);
if ((c & 0x06) == 0x00)
pr_info("%s %s : ColorSpace: RGB,", LOG_TAG, __func__);
else if ((c & 0x06) == 0x02)
pr_info("%s %s : ColorSpace: YCbCr422,", LOG_TAG, __func__);
else if ((c & 0x06) == 0x04)
pr_info("%s %s : ColorSpace: YCbCr444,", LOG_TAG, __func__);
sp_read_reg(TX_P0, SP_TX_VID_CTRL, &c);
if ((c & 0xe0) == 0x00)
pr_info("6 BPC\n");
else if ((c & 0xe0) == 0x20)
pr_info("8 BPC\n");
else if ((c & 0xe0) == 0x40)
pr_info("10 BPC\n");
else if ((c & 0xe0) == 0x60)
pr_info("12 BPC\n");
if(sp_tx_rx_type == DWN_STRM_IS_HDMI) {//assuming it is anx7730
sp_tx_aux_dpcdread_bytes(0x00, 0x05, 0x23, 1, &c);
pr_info("%s %s : HDMI Dongle FW Ver %.2x \n", LOG_TAG, __func__, (uint)(c & 0x7f));
}
pr_info("\n**************************************************\n");
}
void hdmi_rx_show_video_info(void)
{
unchar c, c1;
unchar cl, ch;
uint n;
uint h_res, v_res;
sp_read_reg(RX_P0, HDMI_RX_HACT_LOW, &cl);
sp_read_reg(RX_P0, HDMI_RX_HACT_HIGH, &ch);
n = ch;
n = (n << 8) + cl;
h_res = n;
sp_read_reg(RX_P0, HDMI_RX_VACT_LOW, &cl);
sp_read_reg(RX_P0, HDMI_RX_VACT_HIGH, &ch);
n = ch;
n = (n << 8) + cl;
v_res = n;
pr_info("%s %s : >HDMI_RX Info<\n", LOG_TAG, __func__);
sp_read_reg(RX_P0, HDMI_STATUS, &c);
if (c & HDMI_MODE)
pr_info("%s %s : HDMI_RX Mode = HDMI Mode.\n", LOG_TAG, __func__);
else
pr_info("%s %s : HDMI_RX Mode = DVI Mode.\n", LOG_TAG, __func__);
sp_read_reg(RX_P0,HDMI_RX_VIDEO_STATUS_REG1, &c);
if(c & VIDEO_TYPE)
{
v_res += v_res;
}
pr_info("%s %s : HDMI_RX Video Resolution = %d * %d ", LOG_TAG, __func__,h_res,v_res);
sp_read_reg(RX_P0,HDMI_RX_VIDEO_STATUS_REG1, &c);
if(c & VIDEO_TYPE)
pr_info("Interlace Video.\n");
else
pr_info("Progressive Video.\n");
sp_read_reg(RX_P0, HDMI_RX_SYS_CTRL1_REG, &c);
if ((c & 0x30) == 0x00)
pr_info("%s %s : Input Pixel Clock = Not Repeated.\n", LOG_TAG, __func__);
else if ((c & 0x30) == 0x10)
pr_info("%s %s : Input Pixel Clock = 2x Video Clock. Repeated.\n", LOG_TAG, __func__);
else if ((c & 0x30) == 0x30)
pr_info("%s %s : Input Pixel Clock = 4x Vvideo Clock. Repeated.\n", LOG_TAG, __func__);
if ((c & 0xc0) == 0x00)
pr_info("%s %s : Output Video Clock = Not Divided.\n", LOG_TAG, __func__);
else if ((c & 0xc0) == 0x40)
pr_info("%s %s : Output Video Clock = Divided By 2.\n", LOG_TAG, __func__);
else if ((c & 0xc0) == 0xc0)
pr_info("%s %s : Output Video Clock = Divided By 4.\n", LOG_TAG, __func__);
if (c & 0x02)
pr_info("%s %s : Output Video Using Rising Edge To Latch Data.\n", LOG_TAG, __func__);
else
pr_info("%s %s : Output Video Using Falling Edge To Latch Data.\n", LOG_TAG, __func__);
pr_info("Input Video Color Depth = ");
sp_read_reg(RX_P0, 0x70, &c1);
c1 &= 0xf0;
if (c1 == 0x00)
pr_info("%s %s : Legacy Mode.\n", LOG_TAG, __func__);
else if (c1 == 0x40)
pr_info("%s %s : 24 Bit Mode.\n", LOG_TAG, __func__);
else if (c1 == 0x50)
pr_info("%s %s : 30 Bit Mode.\n", LOG_TAG, __func__);
else if (c1 == 0x60)
pr_info("%s %s : 36 Bit Mode.\n", LOG_TAG, __func__);
else if (c1 == 0x70)
pr_info("%s %s : 48 Bit Mode.\n", LOG_TAG, __func__);
pr_info("%s %s : Input Video Color Space = ", LOG_TAG, __func__);
sp_read_reg(RX_P1, HDMI_RX_AVI_DATA00_REG, &c);
c &= 0x60;
if (c == 0x20)
pr_info("YCbCr4:2:2 .\n");
else if (c == 0x40)
pr_info("YCbCr4:4:4 .\n");
else if (c == 0x00)
pr_info("RGB.\n");
else
pr_err("Unknow 0x44 = 0x%.2x\n", (int)c);
sp_read_reg(RX_P1, HDMI_RX_HDCP_STATUS_REG, &c);
if (c & AUTH_EN)
pr_info("%s %s : Authentication is attempted.\n", LOG_TAG, __func__);
else
pr_info("%s %s : Authentication is not attempted.\n", LOG_TAG, __func__);
for(cl=0;cl<20;cl++)
{
sp_read_reg(RX_P1,HDMI_RX_HDCP_STATUS_REG, &c);
if(c & DECRYPT_EN)
break;
else
mdelay(10);
}
if (cl < 20)
pr_info("%s %s : Decryption is active.\n", LOG_TAG, __func__);
else
pr_info("%s %s : Decryption is not active.\n", LOG_TAG, __func__);
}
void clean_system_status(void)
{
if (g_need_clean_status) {
pr_info("%s %s : clean_system_status. A -> B; \n", LOG_TAG, __func__);
pr_info("A:");
print_sys_state(sp_tx_system_state_bak);
pr_info("B:");
print_sys_state(sp_tx_system_state);
g_need_clean_status = 0;
if(sp_tx_system_state_bak >= STATE_LINK_TRAINING){
if(sp_tx_system_state >= STATE_AUDIO_OUTPUT)
hdmi_rx_mute_audio(1);
else {
hdmi_rx_mute_video(1);
sp_tx_video_mute(1);
}
//sp_tx_enable_video_input(0);
//sp_tx_enable_audio_output(0);
//slimport_block_power_ctrl(SP_TX_PWR_VIDEO, SP_POWER_DOWN);
//slimport_block_power_ctrl(SP_TX_PWR_AUDIO, SP_POWER_DOWN);
}
if(sp_tx_system_state_bak >= STATE_HDCP_AUTH
&& sp_tx_system_state<= STATE_HDCP_AUTH){
if(__i2c_read_byte(TX_P0, TX_HDCP_CTRL0) & 0xFC)
sp_tx_clean_hdcp_status();
}
#ifndef HDCP_AUTO_EN
if (HDCP_state != HDCP_CAPABLE_CHECK)
HDCP_state = HDCP_CAPABLE_CHECK;
#endif
if (sp_tx_sc_state != SC_INIT)
sp_tx_sc_state = SC_INIT;
if (sp_tx_LT_state != LT_INIT)
sp_tx_LT_state = LT_INIT;
if (sp_tx_vo_state != VO_WAIT_VIDEO_STABLE)
sp_tx_vo_state = VO_WAIT_VIDEO_STABLE;
}
}
/******************add for HDCP cap check********************/
void sp_tx_get_ddc_hdcp_BCAP(unchar *bcap)
{
unchar c;
sp_write_reg(TX_P0, AUX_ADDR_7_0, 0X3A);//0X74 FOR HDCP DDC
sp_write_reg(TX_P0, AUX_ADDR_15_8, 0);
sp_read_reg(TX_P0, AUX_ADDR_19_16, &c);
c &= 0xf0;
sp_write_reg(TX_P0, AUX_ADDR_19_16, c);
sp_tx_aux_wr(0x00);
sp_tx_aux_rd(0x01);
sp_read_reg(TX_P0, BUF_DATA_0, &c);
sp_tx_aux_wr(0x40);//0X40: bcap
sp_tx_aux_rd(0x01);
sp_read_reg(TX_P0, BUF_DATA_0, bcap);
//pr_info("%s %s :HDCP BCAP = %.2x\n", LOG_TAG, __func__, (uint)*bcap);
}
void sp_tx_get_ddc_hdcp_BKSV(unchar *bksv)
{
unchar c;
sp_write_reg(TX_P0, AUX_ADDR_7_0, 0X3A);//0X74 FOR HDCP DDC
sp_write_reg(TX_P0, AUX_ADDR_15_8, 0);
sp_read_reg(TX_P0, AUX_ADDR_19_16, &c);
c &= 0xf0;
sp_write_reg(TX_P0, AUX_ADDR_19_16, c);
sp_tx_aux_wr(0x00);
sp_tx_aux_rd(0x01);
sp_read_reg(TX_P0, BUF_DATA_0, &c);
sp_tx_aux_wr(0x00);//0X00: bksv
sp_tx_aux_rd(0x01);
sp_read_reg(TX_P0, BUF_DATA_0, bksv);
//pr_info("%s %s :HDCP BKSV0 = %.2x\n", LOG_TAG, __func__, (uint)*bksv);
}
unchar slimport_hdcp_cap_check(void)
{
unchar g_hdcp_cap = 0;
unchar c,DDC_HDCP_BCAP,DDC_HDCP_BKSV;
if((sp_tx_rx_type == DWN_STRM_IS_VGA_9832)
|| (sp_tx_rx_type == DWN_STRM_IS_ANALOG)) {
g_hdcp_cap=0; // not capable HDCP
} else if (sp_tx_rx_type == DWN_STRM_IS_DIGITAL) {
if(AUX_OK == sp_tx_aux_dpcdread_bytes(0x06, 0x80, 0x28, 1, &c)) {
if (!(c & 0x01)) {
pr_info("%s %s : Sink is not capable HDCP\n", LOG_TAG, __func__);
g_hdcp_cap=0; // not capable HDCP
}
else
g_hdcp_cap=1; // capable HDCP
}
else
pr_info("%s %s : HDCP CAPABLE: read AUX err! \n", LOG_TAG, __func__);
} else if (sp_tx_rx_type == DWN_STRM_IS_HDMI) {
sp_tx_get_ddc_hdcp_BCAP(&DDC_HDCP_BCAP);
sp_tx_get_ddc_hdcp_BKSV(&DDC_HDCP_BKSV);
if((DDC_HDCP_BCAP==0x80)||(DDC_HDCP_BCAP==0x82)||(DDC_HDCP_BCAP==0x83)
||(DDC_HDCP_BCAP==0xc0)||(DDC_HDCP_BCAP==0xe0)||(DDC_HDCP_BKSV!=0x00))
g_hdcp_cap=1;
else
g_hdcp_cap=0;
}else
g_hdcp_cap = 1;
return g_hdcp_cap;
}
/******************End HDCP cap check********************/
#ifdef SIMULATE_WATCHDOG
void simulate_watchdog_func(void)
{
static unchar bak_states = 0;
if((sp_tx_cur_states() < STATE_AUDIO_OUTPUT)
&& (sp_tx_cur_states() == sp_tx_system_state_bak)){
bak_states++;
/*100ms about one main loop, then 100*200 = 20s for watchdog*/
if(bak_states > 200){
bak_states = 0;
system_power_ctrl(0);
pr_err("%s %s :SlimPort Watchdog start!\n", LOG_TAG, __func__);
}
}else{
if(bak_states != 0)
bak_states = 0;
}
}
#endif
void slimport_tasks_handler(void)
{
//isr
if(sp_tx_system_state > STATE_WAITTING_CABLE_PLUG)
system_isr_handler();
#ifdef CEC_ENABLE
if(sp_tx_system_state > STATE_SINK_CONNECTION)
CEC_handler();
#endif
hdcp_external_ctrl_flag_monitor();
clean_system_status();
#ifdef SIMULATE_WATCHDOG
simulate_watchdog_func();
#endif
slimport_cable_monitor();
/*clear up backup system state*/
if(sp_tx_system_state_bak != sp_tx_system_state)
sp_tx_system_state_bak = sp_tx_system_state;
}
/******************End task process********************/
void slimport_main_process(void)
{
slimport_state_process();
slimport_int_rec();
slimport_tasks_handler();
}
/* ***************************************************************** */
/* Functions for slimport_rx anx7730 */
/* ***************************************************************** */
#define SOURCE_AUX_OK 1
#define SOURCE_AUX_ERR 0
#define SOURCE_REG_OK 1
#define SOURCE_REG_ERR 0
#define SINK_DEV_SEL 0x005f0
#define SINK_ACC_OFS 0x005f1
#define SINK_ACC_REG 0x005f2
bool source_aux_read_7730dpcd(long addr, unchar cCount, unchar *pBuf)
{
unchar c;
unchar addr_l;
unchar addr_m;
unchar addr_h;
addr_l = (unchar)addr;
addr_m = (unchar)(addr>>8);
addr_h = (unchar)(addr>>16);
c = 0;
while (1) {
if (sp_tx_aux_dpcdread_bytes(addr_h, addr_m, addr_l, cCount, pBuf) == AUX_OK)
return SOURCE_AUX_OK;
c++;
if (c > 3) {
return SOURCE_AUX_ERR;
}
}
}
bool source_aux_write_7730dpcd(long addr, unchar cCount, unchar *pBuf)
{
unchar c;
unchar addr_l;
unchar addr_m;
unchar addr_h;
addr_l = (unchar)addr;
addr_m = (unchar)(addr>>8);
addr_h = (unchar)(addr>>16);
c = 0;
while (1) {
if (sp_tx_aux_dpcdwrite_bytes(addr_h, addr_m, addr_l, cCount, pBuf) == AUX_OK)
return SOURCE_AUX_OK;
c++;
if (c > 3) {
return SOURCE_AUX_ERR;
}
}
}
bool i2c_master_read_reg(unchar Sink_device_sel, unchar offset, unchar *Buf)
{
unchar sbytebuf[2] = {0};
long a0, a1;
a0 = SINK_DEV_SEL;
a1 = SINK_ACC_REG;
sbytebuf[0] = Sink_device_sel;
sbytebuf[1] = offset;
if (source_aux_write_7730dpcd(a0, 2, sbytebuf) == SOURCE_AUX_OK) {
if (source_aux_read_7730dpcd(a1, 1, Buf) == SOURCE_AUX_OK)
return SOURCE_REG_OK;
}
return SOURCE_REG_ERR;
}
bool i2c_master_write_reg(unchar Sink_device_sel, unchar offset, unchar value)
{
unchar sbytebuf[3] = {0};
long a0;
a0 = SINK_DEV_SEL;
sbytebuf[0] = Sink_device_sel;
sbytebuf[1] = offset;
sbytebuf[2] = value;
if (source_aux_write_7730dpcd(a0, 3, sbytebuf) == SOURCE_AUX_OK)
return SOURCE_REG_OK;
else
return SOURCE_REG_ERR;
}
MODULE_DESCRIPTION("Slimport transmitter ANX7816 driver");
MODULE_AUTHOR("<choonmin.lee@lge.com>");
MODULE_LICENSE("GPL");
| LG-V10/LGV10__pplus_msm8992_kernel | drivers/video/slimport/anx7816/slimport7816_tx_drv.c | C | gpl-2.0 | 112,936 |
<?php
/**
* NoNumber Framework Helper File: Assignments: AkeebaSubs
*
* @package NoNumber Framework
* @version 15.11.2151
*
* @author Peter van Westen <peter@nonumber.nl>
* @link http://www.nonumber.nl
* @copyright Copyright © 2015 NoNumber All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
defined('_JEXEC') or die;
require_once JPATH_PLUGINS . '/system/nnframework/helpers/assignment.php';
class NNFrameworkAssignmentsAkeebaSubs extends NNFrameworkAssignment
{
function init()
{
if (!$this->request->id && $this->request->view == 'level')
{
$slug = JFactory::getApplication()->input->getString('slug', '');
if ($slug)
{
$query = $this->db->getQuery(true)
->select('l.akeebasubs_level_id')
->from('#__akeebasubs_levels AS l')
->where('l.slug = ' . $this->db->quote($slug));
$this->db->setQuery($query);
$this->request->id = $this->db->loadResult();
}
}
}
function passPageTypes()
{
return $this->passByPageTypes('com_akeebasubs', $this->selection, $this->assignment);
}
function passLevels()
{
if (!$this->request->id || $this->request->option != 'com_akeebasubs' || $this->request->view != 'level')
{
return $this->pass(false);
}
return $this->passSimple($this->request->id);
}
}
| christopherstock/WinklerUndSchorn | joomla/plugins/system/nnframework/helpers/assignments/akeebasubs.php | PHP | gpl-2.0 | 1,349 |
/*
* f_fs.c -- user mode file system API for USB composite function controllers
*
* Copyright (C) 2010 Samsung Electronics
* Author: Michal Nazarewicz <mina86@mina86.com>
*
* Based on inode.c (GadgetFS) which was:
* Copyright (C) 2003-2004 David Brownell
* Copyright (C) 2003 Agilent Technologies
*
* 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.
*/
/* #define DEBUG */
/* #define VERBOSE_DEBUG */
#include <linux/blkdev.h>
#include <linux/pagemap.h>
#include <linux/export.h>
#include <linux/hid.h>
#include <asm/unaligned.h>
#include <linux/usb/composite.h>
#include <linux/usb/functionfs.h>
#define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
/* Debugging ****************************************************************/
#ifdef VERBOSE_DEBUG
#ifndef pr_vdebug
# define pr_vdebug pr_debug
#endif /* pr_vdebug */
# define ffs_dump_mem(prefix, ptr, len) \
print_hex_dump_bytes(pr_fmt(prefix ": "), DUMP_PREFIX_NONE, ptr, len)
#else
#ifndef pr_vdebug
# define pr_vdebug(...) do { } while (0)
#endif /* pr_vdebug */
# define ffs_dump_mem(prefix, ptr, len) do { } while (0)
#endif /* VERBOSE_DEBUG */
#define ENTER() pr_vdebug("%s()\n", __func__)
/* The data structure and setup file ****************************************/
enum ffs_state {
/*
* Waiting for descriptors and strings.
*
* In this state no open(2), read(2) or write(2) on epfiles
* may succeed (which should not be the problem as there
* should be no such files opened in the first place).
*/
FFS_READ_DESCRIPTORS,
FFS_READ_STRINGS,
/*
* We've got descriptors and strings. We are or have called
* functionfs_ready_callback(). functionfs_bind() may have
* been called but we don't know.
*
* This is the only state in which operations on epfiles may
* succeed.
*/
FFS_ACTIVE,
/*
* All endpoints have been closed. This state is also set if
* we encounter an unrecoverable error. The only
* unrecoverable error is situation when after reading strings
* from user space we fail to initialise epfiles or
* functionfs_ready_callback() returns with error (<0).
*
* In this state no open(2), read(2) or write(2) (both on ep0
* as well as epfile) may succeed (at this point epfiles are
* unlinked and all closed so this is not a problem; ep0 is
* also closed but ep0 file exists and so open(2) on ep0 must
* fail).
*/
FFS_CLOSING
};
enum ffs_setup_state {
/* There is no setup request pending. */
FFS_NO_SETUP,
/*
* User has read events and there was a setup request event
* there. The next read/write on ep0 will handle the
* request.
*/
FFS_SETUP_PENDING,
/*
* There was event pending but before user space handled it
* some other event was introduced which canceled existing
* setup. If this state is set read/write on ep0 return
* -EIDRM. This state is only set when adding event.
*/
FFS_SETUP_CANCELED
};
struct ffs_epfile;
struct ffs_function;
struct ffs_data {
struct usb_gadget *gadget;
/*
* Protect access read/write operations, only one read/write
* at a time. As a consequence protects ep0req and company.
* While setup request is being processed (queued) this is
* held.
*/
struct mutex mutex;
/*
* Protect access to endpoint related structures (basically
* usb_ep_queue(), usb_ep_dequeue(), etc. calls) except for
* endpoint zero.
*/
spinlock_t eps_lock;
/*
* XXX REVISIT do we need our own request? Since we are not
* handling setup requests immediately user space may be so
* slow that another setup will be sent to the gadget but this
* time not to us but another function and then there could be
* a race. Is that the case? Or maybe we can use cdev->req
* after all, maybe we just need some spinlock for that?
*/
struct usb_request *ep0req; /* P: mutex */
struct completion ep0req_completion; /* P: mutex */
int ep0req_status; /* P: mutex */
struct completion epin_completion;
struct completion epout_completion;
/* reference counter */
atomic_t ref;
/* how many files are opened (EP0 and others) */
atomic_t opened;
/* EP0 state */
enum ffs_state state;
/*
* Possible transitions:
* + FFS_NO_SETUP -> FFS_SETUP_PENDING -- P: ev.waitq.lock
* happens only in ep0 read which is P: mutex
* + FFS_SETUP_PENDING -> FFS_NO_SETUP -- P: ev.waitq.lock
* happens only in ep0 i/o which is P: mutex
* + FFS_SETUP_PENDING -> FFS_SETUP_CANCELED -- P: ev.waitq.lock
* + FFS_SETUP_CANCELED -> FFS_NO_SETUP -- cmpxchg
*/
enum ffs_setup_state setup_state;
#define FFS_SETUP_STATE(ffs) \
((enum ffs_setup_state)cmpxchg(&(ffs)->setup_state, \
FFS_SETUP_CANCELED, FFS_NO_SETUP))
/* Events & such. */
struct {
u8 types[4];
unsigned short count;
/* XXX REVISIT need to update it in some places, or do we? */
unsigned short can_stall;
struct usb_ctrlrequest setup;
wait_queue_head_t waitq;
} ev; /* the whole structure, P: ev.waitq.lock */
/* Flags */
unsigned long flags;
#define FFS_FL_CALL_CLOSED_CALLBACK 0
#define FFS_FL_BOUND 1
/* Active function */
struct ffs_function *func;
/*
* Device name, write once when file system is mounted.
* Intended for user to read if she wants.
*/
const char *dev_name;
/* Private data for our user (ie. gadget). Managed by user. */
void *private_data;
/* filled by __ffs_data_got_descs() */
/*
* Real descriptors are 16 bytes after raw_descs (so you need
* to skip 16 bytes (ie. ffs->raw_descs + 16) to get to the
* first full speed descriptor). raw_descs_length and
* raw_fs_hs_descs_length do not have those 16 bytes added.
* ss_desc are 8 bytes (ss_magic + count) pass the hs_descs
*/
const void *raw_descs;
unsigned raw_descs_length;
unsigned raw_fs_hs_descs_length;
unsigned raw_ss_descs_offset;
unsigned raw_ss_descs_length;
unsigned fs_descs_count;
unsigned hs_descs_count;
unsigned ss_descs_count;
unsigned short strings_count;
unsigned short interfaces_count;
unsigned short eps_count;
unsigned short _pad1;
int first_id;
int old_strings_count;
/* filled by __ffs_data_got_strings() */
/* ids in stringtabs are set in functionfs_bind() */
const void *raw_strings;
struct usb_gadget_strings **stringtabs;
/*
* File system's super block, write once when file system is
* mounted.
*/
struct super_block *sb;
/* File permissions, written once when fs is mounted */
struct ffs_file_perms {
umode_t mode;
kuid_t uid;
kgid_t gid;
} file_perms;
/*
* The endpoint files, filled by ffs_epfiles_create(),
* destroyed by ffs_epfiles_destroy().
*/
struct ffs_epfile *epfiles;
};
/* Reference counter handling */
static void ffs_data_get(struct ffs_data *ffs);
static void ffs_data_put(struct ffs_data *ffs);
/* Creates new ffs_data object. */
static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
/* Opened counter handling. */
static void ffs_data_opened(struct ffs_data *ffs);
static void ffs_data_closed(struct ffs_data *ffs);
/* Called with ffs->mutex held; take over ownership of data. */
static int __must_check
__ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
static int __must_check
__ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
/* The function structure ***************************************************/
struct ffs_ep;
struct ffs_function {
struct usb_configuration *conf;
struct usb_gadget *gadget;
struct ffs_data *ffs;
struct ffs_ep *eps;
u8 eps_revmap[16];
short *interfaces_nums;
struct usb_function function;
};
static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
{
return container_of(f, struct ffs_function, function);
}
static void ffs_func_free(struct ffs_function *func);
static void ffs_func_eps_disable(struct ffs_function *func);
static int __must_check ffs_func_eps_enable(struct ffs_function *func);
static int ffs_func_bind(struct usb_configuration *,
struct usb_function *);
static void ffs_func_unbind(struct usb_configuration *,
struct usb_function *);
static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
static void ffs_func_disable(struct usb_function *);
static int ffs_func_setup(struct usb_function *,
const struct usb_ctrlrequest *);
static void ffs_func_suspend(struct usb_function *);
static void ffs_func_resume(struct usb_function *);
static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
/* The endpoints structures *************************************************/
struct ffs_ep {
struct usb_ep *ep; /* P: ffs->eps_lock */
struct usb_request *req; /* P: epfile->mutex */
/* [0]: full speed, [1]: high speed, [2]: super speed */
struct usb_endpoint_descriptor *descs[3];
u8 num;
int status; /* P: epfile->mutex */
};
struct ffs_epfile {
/* Protects ep->ep and ep->req. */
struct mutex mutex;
wait_queue_head_t wait;
atomic_t error;
struct ffs_data *ffs;
struct ffs_ep *ep; /* P: ffs->eps_lock */
struct dentry *dentry;
char name[5];
unsigned char in; /* P: ffs->eps_lock */
unsigned char isoc; /* P: ffs->eps_lock */
unsigned char _pad;
};
static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
static struct inode *__must_check
ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
const struct file_operations *fops,
struct dentry **dentry_p);
/* Misc helper functions ****************************************************/
static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
__attribute__((warn_unused_result, nonnull));
static char *ffs_prepare_buffer(const char __user *buf, size_t len)
__attribute__((warn_unused_result, nonnull));
/* Control file aka ep0 *****************************************************/
static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
{
struct ffs_data *ffs = req->context;
complete_all(&ffs->ep0req_completion);
}
static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
{
struct usb_request *req = ffs->ep0req;
int ret;
req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
spin_unlock_irq(&ffs->ev.waitq.lock);
req->buf = data;
req->length = len;
/*
* UDC layer requires to provide a buffer even for ZLP, but should
* not use it at all. Let's provide some poisoned pointer to catch
* possible bug in the driver.
*/
if (req->buf == NULL)
req->buf = (void *)0xDEADBABE;
INIT_COMPLETION(ffs->ep0req_completion);
ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
if (unlikely(ret < 0))
return ret;
ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
if (unlikely(ret)) {
usb_ep_dequeue(ffs->gadget->ep0, req);
return -EINTR;
}
ffs->setup_state = FFS_NO_SETUP;
return ffs->ep0req_status;
}
static int __ffs_ep0_stall(struct ffs_data *ffs)
{
if (ffs->ev.can_stall) {
pr_vdebug("ep0 stall\n");
usb_ep_set_halt(ffs->gadget->ep0);
ffs->setup_state = FFS_NO_SETUP;
return -EL2HLT;
} else {
pr_debug("bogus ep0 stall!\n");
return -ESRCH;
}
}
static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
size_t len, loff_t *ptr)
{
struct ffs_data *ffs = file->private_data;
ssize_t ret;
char *data;
ENTER();
/* Fast check if setup was canceled */
if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
return -EIDRM;
/* Acquire mutex */
ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
if (unlikely(ret < 0))
return ret;
/* Check state */
switch (ffs->state) {
case FFS_READ_DESCRIPTORS:
case FFS_READ_STRINGS:
/* Copy data */
if (unlikely(len < 16)) {
ret = -EINVAL;
break;
}
data = ffs_prepare_buffer(buf, len);
if (IS_ERR(data)) {
ret = PTR_ERR(data);
break;
}
/* Handle data */
if (ffs->state == FFS_READ_DESCRIPTORS) {
pr_info("read descriptors\n");
ret = __ffs_data_got_descs(ffs, data, len);
if (unlikely(ret < 0))
break;
ffs->state = FFS_READ_STRINGS;
ret = len;
} else {
pr_info("read strings\n");
ret = __ffs_data_got_strings(ffs, data, len);
if (unlikely(ret < 0))
break;
ret = ffs_epfiles_create(ffs);
if (unlikely(ret)) {
ffs->state = FFS_CLOSING;
break;
}
ffs->state = FFS_ACTIVE;
mutex_unlock(&ffs->mutex);
ret = functionfs_ready_callback(ffs);
if (unlikely(ret < 0)) {
ffs->state = FFS_CLOSING;
return ret;
}
set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
return len;
}
break;
case FFS_ACTIVE:
data = NULL;
/*
* We're called from user space, we can use _irq
* rather then _irqsave
*/
spin_lock_irq(&ffs->ev.waitq.lock);
switch (FFS_SETUP_STATE(ffs)) {
case FFS_SETUP_CANCELED:
ret = -EIDRM;
goto done_spin;
case FFS_NO_SETUP:
ret = -ESRCH;
goto done_spin;
case FFS_SETUP_PENDING:
break;
}
/* FFS_SETUP_PENDING */
if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
spin_unlock_irq(&ffs->ev.waitq.lock);
ret = __ffs_ep0_stall(ffs);
break;
}
/* FFS_SETUP_PENDING and not stall */
len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
spin_unlock_irq(&ffs->ev.waitq.lock);
data = ffs_prepare_buffer(buf, len);
if (IS_ERR(data)) {
ret = PTR_ERR(data);
break;
}
spin_lock_irq(&ffs->ev.waitq.lock);
/*
* We are guaranteed to be still in FFS_ACTIVE state
* but the state of setup could have changed from
* FFS_SETUP_PENDING to FFS_SETUP_CANCELED so we need
* to check for that. If that happened we copied data
* from user space in vain but it's unlikely.
*
* For sure we are not in FFS_NO_SETUP since this is
* the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
* transition can be performed and it's protected by
* mutex.
*/
if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
ret = -EIDRM;
done_spin:
spin_unlock_irq(&ffs->ev.waitq.lock);
} else {
/* unlocks spinlock */
ret = __ffs_ep0_queue_wait(ffs, data, len);
}
kfree(data);
break;
default:
ret = -EBADFD;
break;
}
mutex_unlock(&ffs->mutex);
return ret;
}
static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
size_t n)
{
/*
* We are holding ffs->ev.waitq.lock and ffs->mutex and we need
* to release them.
*/
struct usb_functionfs_event events[n];
unsigned i = 0;
memset(events, 0, sizeof events);
do {
events[i].type = ffs->ev.types[i];
if (events[i].type == FUNCTIONFS_SETUP) {
events[i].u.setup = ffs->ev.setup;
ffs->setup_state = FFS_SETUP_PENDING;
}
} while (++i < n);
if (n < ffs->ev.count) {
ffs->ev.count -= n;
memmove(ffs->ev.types, ffs->ev.types + n,
ffs->ev.count * sizeof *ffs->ev.types);
} else {
ffs->ev.count = 0;
}
spin_unlock_irq(&ffs->ev.waitq.lock);
mutex_unlock(&ffs->mutex);
return unlikely(__copy_to_user(buf, events, sizeof events))
? -EFAULT : sizeof events;
}
static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
size_t len, loff_t *ptr)
{
struct ffs_data *ffs = file->private_data;
char *data = NULL;
size_t n;
int ret;
ENTER();
/* Fast check if setup was canceled */
if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
return -EIDRM;
/* Acquire mutex */
ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
if (unlikely(ret < 0))
return ret;
/* Check state */
if (ffs->state != FFS_ACTIVE) {
ret = -EBADFD;
goto done_mutex;
}
/*
* We're called from user space, we can use _irq rather then
* _irqsave
*/
spin_lock_irq(&ffs->ev.waitq.lock);
switch (FFS_SETUP_STATE(ffs)) {
case FFS_SETUP_CANCELED:
ret = -EIDRM;
break;
case FFS_NO_SETUP:
n = len / sizeof(struct usb_functionfs_event);
if (unlikely(!n)) {
ret = -EINVAL;
break;
}
if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
ret = -EAGAIN;
break;
}
if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
ffs->ev.count)) {
ret = -EINTR;
break;
}
return __ffs_ep0_read_events(ffs, buf,
min(n, (size_t)ffs->ev.count));
case FFS_SETUP_PENDING:
if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
spin_unlock_irq(&ffs->ev.waitq.lock);
ret = __ffs_ep0_stall(ffs);
goto done_mutex;
}
len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
spin_unlock_irq(&ffs->ev.waitq.lock);
if (likely(len)) {
data = kmalloc(len, GFP_KERNEL);
if (unlikely(!data)) {
ret = -ENOMEM;
goto done_mutex;
}
}
spin_lock_irq(&ffs->ev.waitq.lock);
/* See ffs_ep0_write() */
if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
ret = -EIDRM;
break;
}
/* unlocks spinlock */
ret = __ffs_ep0_queue_wait(ffs, data, len);
if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
ret = -EFAULT;
goto done_mutex;
default:
ret = -EBADFD;
break;
}
spin_unlock_irq(&ffs->ev.waitq.lock);
done_mutex:
mutex_unlock(&ffs->mutex);
kfree(data);
return ret;
}
static int ffs_ep0_open(struct inode *inode, struct file *file)
{
struct ffs_data *ffs = inode->i_private;
ENTER();
if (unlikely(ffs->state == FFS_CLOSING))
return -EBUSY;
/*bug290503,shenyong.wt,201410.13,start,add atomic from qcom advice*/
if(atomic_read(&ffs->opened))
return -EBUSY;
/*bug290503,shenyong.wt,201410.13,end,add atomid from qcom advice*/
file->private_data = ffs;
ffs_data_opened(ffs);
return 0;
}
static int ffs_ep0_release(struct inode *inode, struct file *file)
{
struct ffs_data *ffs = file->private_data;
ENTER();
ffs_data_closed(ffs);
return 0;
}
static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
{
struct ffs_data *ffs = file->private_data;
struct usb_gadget *gadget = ffs->gadget;
long ret;
ENTER();
if (code == FUNCTIONFS_INTERFACE_REVMAP) {
struct ffs_function *func = ffs->func;
ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
} else if (gadget && gadget->ops->ioctl) {
ret = gadget->ops->ioctl(gadget, code, value);
} else {
ret = -ENOTTY;
}
return ret;
}
static const struct file_operations ffs_ep0_operations = {
.llseek = no_llseek,
.open = ffs_ep0_open,
.write = ffs_ep0_write,
.read = ffs_ep0_read,
.release = ffs_ep0_release,
.unlocked_ioctl = ffs_ep0_ioctl,
};
/* "Normal" endpoints operations ********************************************/
static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
{
struct ffs_ep *ep = _ep->driver_data;
ENTER();
/* req may be freed during unbind */
if (ep && ep->req && likely(req->context)) {
struct ffs_ep *ep = _ep->driver_data;
ep->status = req->status ? req->status : req->actual;
complete(req->context);
}
}
static ssize_t ffs_epfile_io(struct file *file,
char __user *buf, size_t len, int read)
{
struct ffs_epfile *epfile = file->private_data;
struct ffs_ep *ep;
struct ffs_data *ffs = epfile->ffs;
char *data = NULL;
ssize_t ret;
int halt;
int buffer_len = 0;
pr_debug("%s: len %zu, read %d\n", __func__, len, read);
if (atomic_read(&epfile->error))
return -ENODEV;
goto first_try;
do {
spin_unlock_irq(&epfile->ffs->eps_lock);
mutex_unlock(&epfile->mutex);
first_try:
/* Are we still active? */
if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
ret = -ENODEV;
goto error;
}
/* Wait for endpoint to be enabled */
ep = epfile->ep;
if (!ep) {
if (file->f_flags & O_NONBLOCK) {
ret = -EAGAIN;
goto error;
}
/* Don't wait on write if device is offline */
if (!read) {
ret = -ENODEV;
goto error;
}
/*
* if ep is disabled, this fails all current IOs
* and wait for next epfile open to happen
*/
if (!atomic_read(&epfile->error)) {
ret = wait_event_interruptible(epfile->wait,
(ep = epfile->ep));
if (ret < 0)
goto error;
}
if (!ep) {
ret = -ENODEV;
goto error;
}
}
buffer_len = !read ? len : round_up(len,
ep->ep->desc->wMaxPacketSize);
/* Do we halt? */
halt = !read == !epfile->in;
if (halt && epfile->isoc) {
ret = -EINVAL;
goto error;
}
/* Allocate & copy */
if (!halt && !data) {
data = kzalloc(buffer_len, GFP_KERNEL);
if (unlikely(!data))
return -ENOMEM;
if (!read &&
unlikely(__copy_from_user(data, buf, len))) {
ret = -EFAULT;
goto error;
}
}
/* We will be using request */
ret = ffs_mutex_lock(&epfile->mutex,
file->f_flags & O_NONBLOCK);
if (unlikely(ret))
goto error;
/*
* We're called from user space, we can use _irq rather then
* _irqsave
*/
spin_lock_irq(&epfile->ffs->eps_lock);
/*
* While we were acquiring mutex endpoint got disabled
* or changed?
*/
} while (unlikely(epfile->ep != ep));
/* Halt */
if (unlikely(halt)) {
if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
usb_ep_set_halt(ep->ep);
spin_unlock_irq(&epfile->ffs->eps_lock);
ret = -EBADMSG;
} else {
/* Fire the request */
struct completion *done;
struct usb_request *req = ep->req;
req->complete = ffs_epfile_io_complete;
req->buf = data;
req->length = buffer_len;
if (read) {
INIT_COMPLETION(ffs->epout_completion);
req->context = done = &ffs->epout_completion;
} else {
INIT_COMPLETION(ffs->epin_completion);
req->context = done = &ffs->epin_completion;
}
ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
spin_unlock_irq(&epfile->ffs->eps_lock);
if (unlikely(ret < 0)) {
ret = -EIO;
} else if (unlikely(wait_for_completion_interruptible(done))) {
spin_lock_irq(&epfile->ffs->eps_lock);
/*
* While we were acquiring lock endpoint got disabled
* (disconnect) or changed (composition switch) ?
*/
if (epfile->ep == ep)
usb_ep_dequeue(ep->ep, req);
spin_unlock_irq(&epfile->ffs->eps_lock);
ret = -EINTR;
} else {
spin_lock_irq(&epfile->ffs->eps_lock);
/*
* While we were acquiring lock endpoint got disabled
* (disconnect) or changed (composition switch) ?
*/
if (epfile->ep == ep)
ret = ep->status;
else
ret = -ENODEV;
spin_unlock_irq(&epfile->ffs->eps_lock);
if (read && ret > 0) {
if (ret > len)
ret = -EOVERFLOW;
else if (unlikely(copy_to_user(buf, data, ret)))
ret = -EFAULT;
}
}
}
mutex_unlock(&epfile->mutex);
error:
kfree(data);
return ret;
}
static ssize_t
ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
loff_t *ptr)
{
ENTER();
return ffs_epfile_io(file, (char __user *)buf, len, 0);
}
static ssize_t
ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
{
ENTER();
return ffs_epfile_io(file, buf, len, 1);
}
static int
ffs_epfile_open(struct inode *inode, struct file *file)
{
struct ffs_epfile *epfile = inode->i_private;
ENTER();
if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
return -ENODEV;
file->private_data = epfile;
ffs_data_opened(epfile->ffs);
atomic_set(&epfile->error, 0);
return 0;
}
static int
ffs_epfile_release(struct inode *inode, struct file *file)
{
struct ffs_epfile *epfile = inode->i_private;
ENTER();
atomic_set(&epfile->error, 1);
ffs_data_closed(epfile->ffs);
file->private_data = NULL;
return 0;
}
static long ffs_epfile_ioctl(struct file *file, unsigned code,
unsigned long value)
{
struct ffs_epfile *epfile = file->private_data;
int ret;
ENTER();
if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
return -ENODEV;
spin_lock_irq(&epfile->ffs->eps_lock);
if (likely(epfile->ep)) {
switch (code) {
case FUNCTIONFS_FIFO_STATUS:
ret = usb_ep_fifo_status(epfile->ep->ep);
break;
case FUNCTIONFS_FIFO_FLUSH:
usb_ep_fifo_flush(epfile->ep->ep);
ret = 0;
break;
case FUNCTIONFS_CLEAR_HALT:
ret = usb_ep_clear_halt(epfile->ep->ep);
break;
case FUNCTIONFS_ENDPOINT_REVMAP:
ret = epfile->ep->num;
break;
default:
ret = -ENOTTY;
}
} else {
ret = -ENODEV;
}
spin_unlock_irq(&epfile->ffs->eps_lock);
return ret;
}
static const struct file_operations ffs_epfile_operations = {
.llseek = no_llseek,
.open = ffs_epfile_open,
.write = ffs_epfile_write,
.read = ffs_epfile_read,
.release = ffs_epfile_release,
.unlocked_ioctl = ffs_epfile_ioctl,
};
/* File system and super block operations ***********************************/
/*
* Mounting the file system creates a controller file, used first for
* function configuration then later for event monitoring.
*/
static struct inode *__must_check
ffs_sb_make_inode(struct super_block *sb, void *data,
const struct file_operations *fops,
const struct inode_operations *iops,
struct ffs_file_perms *perms)
{
struct inode *inode;
ENTER();
inode = new_inode(sb);
if (likely(inode)) {
struct timespec current_time = CURRENT_TIME;
inode->i_ino = get_next_ino();
inode->i_mode = perms->mode;
inode->i_uid = perms->uid;
inode->i_gid = perms->gid;
inode->i_atime = current_time;
inode->i_mtime = current_time;
inode->i_ctime = current_time;
inode->i_private = data;
if (fops)
inode->i_fop = fops;
if (iops)
inode->i_op = iops;
}
return inode;
}
/* Create "regular" file */
static struct inode *ffs_sb_create_file(struct super_block *sb,
const char *name, void *data,
const struct file_operations *fops,
struct dentry **dentry_p)
{
struct ffs_data *ffs = sb->s_fs_info;
struct dentry *dentry;
struct inode *inode;
ENTER();
dentry = d_alloc_name(sb->s_root, name);
if (unlikely(!dentry))
return NULL;
inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
if (unlikely(!inode)) {
dput(dentry);
return NULL;
}
d_add(dentry, inode);
if (dentry_p)
*dentry_p = dentry;
return inode;
}
/* Super block */
static const struct super_operations ffs_sb_operations = {
.statfs = simple_statfs,
.drop_inode = generic_delete_inode,
};
struct ffs_sb_fill_data {
struct ffs_file_perms perms;
umode_t root_mode;
const char *dev_name;
struct ffs_data *ffs_data;
};
static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
{
struct ffs_sb_fill_data *data = _data;
struct inode *inode;
struct ffs_data *ffs = data->ffs_data;
ENTER();
ffs->sb = sb;
data->ffs_data = NULL;
sb->s_fs_info = ffs;
sb->s_blocksize = PAGE_CACHE_SIZE;
sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
sb->s_magic = FUNCTIONFS_MAGIC;
sb->s_op = &ffs_sb_operations;
sb->s_time_gran = 1;
/* Root inode */
data->perms.mode = data->root_mode;
inode = ffs_sb_make_inode(sb, NULL,
&simple_dir_operations,
&simple_dir_inode_operations,
&data->perms);
sb->s_root = d_make_root(inode);
if (unlikely(!sb->s_root))
return -ENOMEM;
/* EP0 file */
if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
&ffs_ep0_operations, NULL)))
return -ENOMEM;
return 0;
}
static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
{
ENTER();
if (!opts || !*opts)
return 0;
for (;;) {
unsigned long value;
char *eq, *comma;
/* Option limit */
comma = strchr(opts, ',');
if (comma)
*comma = 0;
/* Value limit */
eq = strchr(opts, '=');
if (unlikely(!eq)) {
pr_err("'=' missing in %s\n", opts);
return -EINVAL;
}
*eq = 0;
/* Parse value */
if (kstrtoul(eq + 1, 0, &value)) {
pr_err("%s: invalid value: %s\n", opts, eq + 1);
return -EINVAL;
}
/* Interpret option */
switch (eq - opts) {
case 5:
if (!memcmp(opts, "rmode", 5))
data->root_mode = (value & 0555) | S_IFDIR;
else if (!memcmp(opts, "fmode", 5))
data->perms.mode = (value & 0666) | S_IFREG;
else
goto invalid;
break;
case 4:
if (!memcmp(opts, "mode", 4)) {
data->root_mode = (value & 0555) | S_IFDIR;
data->perms.mode = (value & 0666) | S_IFREG;
} else {
goto invalid;
}
break;
case 3:
if (!memcmp(opts, "uid", 3)) {
data->perms.uid = make_kuid(current_user_ns(), value);
if (!uid_valid(data->perms.uid)) {
pr_err("%s: unmapped value: %lu\n", opts, value);
return -EINVAL;
}
} else if (!memcmp(opts, "gid", 3)) {
data->perms.gid = make_kgid(current_user_ns(), value);
if (!gid_valid(data->perms.gid)) {
pr_err("%s: unmapped value: %lu\n", opts, value);
return -EINVAL;
}
} else {
goto invalid;
}
break;
default:
invalid:
pr_err("%s: invalid option\n", opts);
return -EINVAL;
}
/* Next iteration */
if (!comma)
break;
opts = comma + 1;
}
return 0;
}
/* "mount -t functionfs dev_name /dev/function" ends up here */
static struct dentry *
ffs_fs_mount(struct file_system_type *t, int flags,
const char *dev_name, void *opts)
{
struct ffs_sb_fill_data data = {
.perms = {
.mode = S_IFREG | 0600,
.uid = GLOBAL_ROOT_UID,
.gid = GLOBAL_ROOT_GID,
},
.root_mode = S_IFDIR | 0500,
};
struct dentry *rv;
int ret;
void *ffs_dev;
struct ffs_data *ffs;
ENTER();
ret = ffs_fs_parse_opts(&data, opts);
if (unlikely(ret < 0))
return ERR_PTR(ret);
ffs = ffs_data_new();
if (unlikely(!ffs))
return ERR_PTR(-ENOMEM);
ffs->file_perms = data.perms;
ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
if (unlikely(!ffs->dev_name)) {
ffs_data_put(ffs);
return ERR_PTR(-ENOMEM);
}
ffs_dev = functionfs_acquire_dev_callback(dev_name);
if (IS_ERR(ffs_dev)) {
ffs_data_put(ffs);
return ERR_CAST(ffs_dev);
}
ffs->private_data = ffs_dev;
data.ffs_data = ffs;
rv = mount_nodev(t, flags, &data, ffs_sb_fill);
if (IS_ERR(rv) && data.ffs_data) {
functionfs_release_dev_callback(data.ffs_data);
ffs_data_put(data.ffs_data);
}
return rv;
}
static void
ffs_fs_kill_sb(struct super_block *sb)
{
ENTER();
kill_litter_super(sb);
if (sb->s_fs_info) {
functionfs_release_dev_callback(sb->s_fs_info);
ffs_data_put(sb->s_fs_info);
}
}
static struct file_system_type ffs_fs_type = {
.owner = THIS_MODULE,
.name = "functionfs",
.mount = ffs_fs_mount,
.kill_sb = ffs_fs_kill_sb,
};
MODULE_ALIAS_FS("functionfs");
/* Driver's main init/cleanup functions *************************************/
static int functionfs_init(void)
{
int ret;
ENTER();
ret = register_filesystem(&ffs_fs_type);
if (likely(!ret))
pr_info("file system registered\n");
else
pr_err("failed registering file system (%d)\n", ret);
return ret;
}
static void functionfs_cleanup(void)
{
ENTER();
pr_info("unloading\n");
unregister_filesystem(&ffs_fs_type);
}
/* ffs_data and ffs_function construction and destruction code **************/
static void ffs_data_clear(struct ffs_data *ffs);
static void ffs_data_reset(struct ffs_data *ffs);
static void ffs_data_get(struct ffs_data *ffs)
{
ENTER();
atomic_inc(&ffs->ref);
}
static void ffs_data_opened(struct ffs_data *ffs)
{
ENTER();
atomic_inc(&ffs->ref);
atomic_inc(&ffs->opened);
}
static void ffs_data_put(struct ffs_data *ffs)
{
ENTER();
if (unlikely(atomic_dec_and_test(&ffs->ref))) {
pr_info("%s(): freeing\n", __func__);
ffs_data_clear(ffs);
BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
waitqueue_active(&ffs->ep0req_completion.wait));
kfree(ffs->dev_name);
kfree(ffs);
}
}
static void ffs_data_closed(struct ffs_data *ffs)
{
ENTER();
if (atomic_dec_and_test(&ffs->opened)) {
ffs->state = FFS_CLOSING;
ffs_data_reset(ffs);
}
ffs_data_put(ffs);
}
static struct ffs_data *ffs_data_new(void)
{
struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
if (unlikely(!ffs))
return 0;
ENTER();
atomic_set(&ffs->ref, 1);
atomic_set(&ffs->opened, 0);
ffs->state = FFS_READ_DESCRIPTORS;
mutex_init(&ffs->mutex);
spin_lock_init(&ffs->eps_lock);
init_waitqueue_head(&ffs->ev.waitq);
init_completion(&ffs->ep0req_completion);
init_completion(&ffs->epout_completion);
init_completion(&ffs->epin_completion);
/* XXX REVISIT need to update it in some places, or do we? */
ffs->ev.can_stall = 1;
return ffs;
}
static void ffs_data_clear(struct ffs_data *ffs)
{
ENTER();
if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
functionfs_closed_callback(ffs);
BUG_ON(ffs->gadget);
if (ffs->epfiles)
ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
kfree(ffs->raw_descs);
kfree(ffs->raw_strings);
kfree(ffs->stringtabs);
}
static void ffs_data_reset(struct ffs_data *ffs)
{
ENTER();
ffs_data_clear(ffs);
ffs->epfiles = NULL;
ffs->raw_descs = NULL;
ffs->raw_strings = NULL;
ffs->stringtabs = NULL;
ffs->raw_descs_length = 0;
ffs->raw_fs_hs_descs_length = 0;
ffs->raw_ss_descs_offset = 0;
ffs->raw_ss_descs_length = 0;
ffs->fs_descs_count = 0;
ffs->hs_descs_count = 0;
ffs->ss_descs_count = 0;
ffs->strings_count = 0;
ffs->interfaces_count = 0;
ffs->eps_count = 0;
ffs->ev.count = 0;
ffs->state = FFS_READ_DESCRIPTORS;
ffs->setup_state = FFS_NO_SETUP;
ffs->flags = 0;
}
static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
{
struct usb_gadget_strings **lang;
ENTER();
if (WARN_ON(ffs->state != FFS_ACTIVE
|| test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
return -EBADFD;
if (!ffs->first_id || ffs->old_strings_count < ffs->strings_count) {
int first_id = usb_string_ids_n(cdev, ffs->strings_count);
if (unlikely(first_id < 0))
return first_id;
ffs->first_id = first_id;
ffs->old_strings_count = ffs->strings_count;
}
ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
if (unlikely(!ffs->ep0req))
return -ENOMEM;
ffs->ep0req->complete = ffs_ep0_complete;
ffs->ep0req->context = ffs;
lang = ffs->stringtabs;
//bug290503,shenyong.wt,2014.10.13,start,pointer protect from qcom advice
if(lang)
{
for (/*lang = ffs->stringtabs*/; *lang; ++lang) {
struct usb_string *str = (*lang)->strings;
int id = ffs->first_id;
for (; str->s; ++id, ++str)
str->id = id;
}
}
//bug290503,shenyong.wt,2014.10.13,end,pointer protect frome qcom advice
ffs->gadget = cdev->gadget;
ffs_data_get(ffs);
return 0;
}
static void functionfs_unbind(struct ffs_data *ffs)
{
ENTER();
if (!WARN_ON(!ffs->gadget)) {
usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
ffs->ep0req = NULL;
ffs->gadget = NULL;
ffs_data_put(ffs);
clear_bit(FFS_FL_BOUND, &ffs->flags);
}
}
static int ffs_epfiles_create(struct ffs_data *ffs)
{
struct ffs_epfile *epfile, *epfiles;
unsigned i, count;
ENTER();
count = ffs->eps_count;
epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
if (!epfiles)
return -ENOMEM;
epfile = epfiles;
for (i = 1; i <= count; ++i, ++epfile) {
epfile->ffs = ffs;
mutex_init(&epfile->mutex);
init_waitqueue_head(&epfile->wait);
sprintf(epfiles->name, "ep%u", i);
if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
&ffs_epfile_operations,
&epfile->dentry))) {
ffs_epfiles_destroy(epfiles, i - 1);
return -ENOMEM;
}
}
ffs->epfiles = epfiles;
return 0;
}
static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
{
struct ffs_epfile *epfile = epfiles;
ENTER();
for (; count; --count, ++epfile) {
BUG_ON(mutex_is_locked(&epfile->mutex) ||
waitqueue_active(&epfile->wait));
if (epfile->dentry) {
d_delete(epfile->dentry);
dput(epfile->dentry);
epfile->dentry = NULL;
}
}
kfree(epfiles);
}
/*bug290503,shenyong.wt,20141003,start,add usb strings define for adb*/
#if 1
static struct usb_string adb_string_defs[] = {
[0].s = "ADB Interface",
{ } /* end of list */
};
static struct usb_gadget_strings adb_string_table = {
.language = 0x0409, /* en-us */
.strings = adb_string_defs,
};
static struct usb_gadget_strings *adb_strings[] = {
&adb_string_table,
NULL,
};
#endif
static int functionfs_bind_config(struct usb_composite_dev *cdev,
struct usb_configuration *c,
struct ffs_data *ffs)
{
struct ffs_function *func;
int ret;
struct usb_gadget_strings *s;//hoper
struct usb_gadget_strings *s1;//hoper
ENTER();
func = kzalloc(sizeof *func, GFP_KERNEL);
if (unlikely(!func))
return -ENOMEM;
func->function.name = "Function FS Gadget";
/*bug290503,shenyong.wt,201410.13,start,add lock getsting*/
func->function.strings = adb_strings/*ffs->stringtabs*/;
#if 1
s1 =*( func->function.strings);
if(ffs)
{
if(ffs->stringtabs)
{
s = *( ffs->stringtabs);
if(s)
{
printk("XXX::functionfs_bind_config::language=%d\r\n",s->language);//hoper
if(s->strings)
{
s1->strings->id = s->strings->id;
printk("XXX::functionfs_bind_config::sid=%d,s1id=%d\r\n",s->strings->id,s1->strings->id);//hoper
if(s->strings->s)
printk("XXX::functionfs_bind_config::s=%s\r\n",s->strings->s);//hoper
}
}
}
}
#endif
/*bug290503,shenyong.wt,201410.13,end,add lock getsting*/
func->function.bind = ffs_func_bind;
func->function.unbind = ffs_func_unbind;
func->function.set_alt = ffs_func_set_alt;
func->function.disable = ffs_func_disable;
func->function.setup = ffs_func_setup;
func->function.suspend = ffs_func_suspend;
func->function.resume = ffs_func_resume;
func->conf = c;
func->gadget = cdev->gadget;
func->ffs = ffs;
ffs_data_get(ffs);
ret = usb_add_function(c, &func->function);
if (unlikely(ret))
ffs_func_free(func);
return ret;
}
static void ffs_func_free(struct ffs_function *func)
{
struct ffs_ep *ep = func->eps;
unsigned count = func->ffs->eps_count;
unsigned long flags;
ENTER();
/* cleanup after autoconfig */
spin_lock_irqsave(&func->ffs->eps_lock, flags);
do {
if (ep->ep && ep->req)
usb_ep_free_request(ep->ep, ep->req);
ep->req = NULL;
ep->ep = NULL;
++ep;
} while (--count);
spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
ffs_data_put(func->ffs);
kfree(func->eps);
/*
* eps and interfaces_nums are allocated in the same chunk so
* only one free is required. Descriptors are also allocated
* in the same chunk.
*/
kfree(func);
}
static void ffs_func_eps_disable(struct ffs_function *func)
{
struct ffs_ep *ep = func->eps;
struct ffs_epfile *epfile = func->ffs->epfiles;
unsigned count = func->ffs->eps_count;
unsigned long flags;
spin_lock_irqsave(&func->ffs->eps_lock, flags);
do {
atomic_set(&epfile->error, 1);
/* pending requests get nuked */
if (likely(ep->ep)) {
usb_ep_disable(ep->ep);
ep->ep->driver_data = NULL;
}
epfile->ep = NULL;
++ep;
++epfile;
} while (--count);
spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
}
static int ffs_func_eps_enable(struct ffs_function *func)
{
struct ffs_data *ffs = func->ffs;
struct ffs_ep *ep = func->eps;
struct ffs_epfile *epfile = ffs->epfiles;
unsigned count = ffs->eps_count;
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&func->ffs->eps_lock, flags);
do {
struct usb_endpoint_descriptor *ds;
int desc_idx;
if (ffs->gadget->speed == USB_SPEED_SUPER)
desc_idx = 2;
else if (ffs->gadget->speed == USB_SPEED_HIGH)
desc_idx = 1;
else
desc_idx = 0;
ds = ep->descs[desc_idx];
if (!ds) {
ret = -EINVAL;
break;
}
ep->ep->driver_data = ep;
ep->ep->desc = ds;
ret = usb_ep_enable(ep->ep);
if (likely(!ret)) {
epfile->ep = ep;
epfile->in = usb_endpoint_dir_in(ds);
epfile->isoc = usb_endpoint_xfer_isoc(ds);
} else {
break;
}
wake_up(&epfile->wait);
++ep;
++epfile;
} while (--count);
spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
return ret;
}
/* Parsing and building descriptors and strings *****************************/
/*
* This validates if data pointed by data is a valid USB descriptor as
* well as record how many interfaces, endpoints and strings are
* required by given configuration. Returns address after the
* descriptor or NULL if data is invalid.
*/
enum ffs_entity_type {
FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
};
typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
u8 *valuep,
struct usb_descriptor_header *desc,
void *priv);
static int __must_check ffs_do_desc(char *data, unsigned len,
ffs_entity_callback entity, void *priv)
{
struct usb_descriptor_header *_ds = (void *)data;
u8 length;
int ret;
ENTER();
/* At least two bytes are required: length and type */
if (len < 2) {
pr_vdebug("descriptor too short\n");
return -EINVAL;
}
/* If we have at least as many bytes as the descriptor takes? */
length = _ds->bLength;
if (len < length) {
pr_vdebug("descriptor longer then available data\n");
return -EINVAL;
}
#define __entity_check_INTERFACE(val) 1
#define __entity_check_STRING(val) (val)
#define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
#define __entity(type, val) do { \
pr_vdebug("entity " #type "(%02x)\n", (val)); \
if (unlikely(!__entity_check_ ##type(val))) { \
pr_vdebug("invalid entity's value\n"); \
return -EINVAL; \
} \
ret = entity(FFS_ ##type, &val, _ds, priv); \
if (unlikely(ret < 0)) { \
pr_debug("entity " #type "(%02x); ret = %d\n", \
(val), ret); \
return ret; \
} \
} while (0)
/* Parse descriptor depending on type. */
switch (_ds->bDescriptorType) {
case USB_DT_DEVICE:
case USB_DT_CONFIG:
case USB_DT_STRING:
case USB_DT_DEVICE_QUALIFIER:
/* function can't have any of those */
pr_vdebug("descriptor reserved for gadget: %d\n",
_ds->bDescriptorType);
return -EINVAL;
case USB_DT_INTERFACE: {
struct usb_interface_descriptor *ds = (void *)_ds;
pr_vdebug("interface descriptor\n");
if (length != sizeof *ds)
goto inv_length;
__entity(INTERFACE, ds->bInterfaceNumber);
if (ds->iInterface)
__entity(STRING, ds->iInterface);
}
break;
case USB_DT_ENDPOINT: {
struct usb_endpoint_descriptor *ds = (void *)_ds;
pr_vdebug("endpoint descriptor\n");
if (length != USB_DT_ENDPOINT_SIZE &&
length != USB_DT_ENDPOINT_AUDIO_SIZE)
goto inv_length;
__entity(ENDPOINT, ds->bEndpointAddress);
}
break;
case HID_DT_HID:
pr_vdebug("hid descriptor\n");
if (length != sizeof(struct hid_descriptor))
goto inv_length;
break;
case USB_DT_OTG:
if (length != sizeof(struct usb_otg_descriptor))
goto inv_length;
break;
case USB_DT_INTERFACE_ASSOCIATION: {
struct usb_interface_assoc_descriptor *ds = (void *)_ds;
pr_vdebug("interface association descriptor\n");
if (length != sizeof *ds)
goto inv_length;
if (ds->iFunction)
__entity(STRING, ds->iFunction);
}
break;
case USB_DT_SS_ENDPOINT_COMP:
pr_vdebug("EP SS companion descriptor\n");
if (length != sizeof(struct usb_ss_ep_comp_descriptor))
goto inv_length;
break;
case USB_DT_OTHER_SPEED_CONFIG:
case USB_DT_INTERFACE_POWER:
case USB_DT_DEBUG:
case USB_DT_SECURITY:
case USB_DT_CS_RADIO_CONTROL:
/* TODO */
pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
return -EINVAL;
default:
/* We should never be here */
pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
return -EINVAL;
inv_length:
pr_vdebug("invalid length: %d (descriptor %d)\n",
_ds->bLength, _ds->bDescriptorType);
return -EINVAL;
}
#undef __entity
#undef __entity_check_DESCRIPTOR
#undef __entity_check_INTERFACE
#undef __entity_check_STRING
#undef __entity_check_ENDPOINT
return length;
}
static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
ffs_entity_callback entity, void *priv)
{
const unsigned _len = len;
unsigned long num = 0;
ENTER();
for (;;) {
int ret;
if (num == count)
data = NULL;
/* Record "descriptor" entity */
ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
if (unlikely(ret < 0)) {
pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
num, ret);
return ret;
}
if (!data)
return _len - len;
ret = ffs_do_desc(data, len, entity, priv);
if (unlikely(ret < 0)) {
pr_debug("%s returns %d\n", __func__, ret);
return ret;
}
len -= ret;
data += ret;
++num;
}
}
static int __ffs_data_do_entity(enum ffs_entity_type type,
u8 *valuep, struct usb_descriptor_header *desc,
void *priv)
{
struct ffs_data *ffs = priv;
ENTER();
switch (type) {
case FFS_DESCRIPTOR:
break;
case FFS_INTERFACE:
/*
* Interfaces are indexed from zero so if we
* encountered interface "n" then there are at least
* "n+1" interfaces.
*/
if (*valuep >= ffs->interfaces_count)
ffs->interfaces_count = *valuep + 1;
break;
case FFS_STRING:
/*
* Strings are indexed from 1 (0 is magic ;) reserved
* for languages list or some such)
*/
if (*valuep > ffs->strings_count)
ffs->strings_count = *valuep;
break;
case FFS_ENDPOINT:
/* Endpoints are indexed from 1 as well. */
if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
break;
}
return 0;
}
static int __ffs_data_got_descs(struct ffs_data *ffs,
char *const _data, size_t len)
{
unsigned fs_count, hs_count, ss_count = 0;
int fs_len, hs_len, ss_len, ss_magic, ret = -EINVAL;
char *data = _data;
ENTER();
if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_DESCRIPTORS_MAGIC ||
get_unaligned_le32(data + 4) != len))
goto error;
fs_count = get_unaligned_le32(data + 8);
hs_count = get_unaligned_le32(data + 12);
data += 16;
len -= 16;
if (likely(fs_count)) {
fs_len = ffs_do_descs(fs_count, data, len,
__ffs_data_do_entity, ffs);
if (unlikely(fs_len < 0)) {
ret = fs_len;
goto error;
}
data += fs_len;
len -= fs_len;
} else {
fs_len = 0;
}
if (likely(hs_count)) {
hs_len = ffs_do_descs(hs_count, data, len,
__ffs_data_do_entity, ffs);
if (unlikely(hs_len < 0)) {
ret = hs_len;
goto error;
}
} else {
hs_len = 0;
}
if ((len >= hs_len + 8)) {
/* Check SS_MAGIC for presence of ss_descs and get SS_COUNT */
ss_magic = get_unaligned_le32(data + hs_len);
if (ss_magic != FUNCTIONFS_SS_DESC_MAGIC)
goto einval;
ss_count = get_unaligned_le32(data + hs_len + 4);
data += hs_len + 8;
len -= hs_len + 8;
} else {
data += hs_len;
len -= hs_len;
}
if (!fs_count && !hs_count && !ss_count)
goto einval;
if (ss_count) {
ss_len = ffs_do_descs(ss_count, data, len,
__ffs_data_do_entity, ffs);
if (unlikely(ss_len < 0)) {
ret = ss_len;
goto error;
}
ret = ss_len;
} else {
ss_len = 0;
ret = 0;
}
if (unlikely(len != ret))
goto einval;
ffs->raw_fs_hs_descs_length = fs_len + hs_len;
ffs->raw_ss_descs_length = ss_len;
ffs->raw_descs_length = ffs->raw_fs_hs_descs_length + ss_len;
ffs->raw_descs = _data;
ffs->fs_descs_count = fs_count;
ffs->hs_descs_count = hs_count;
ffs->ss_descs_count = ss_count;
if (ffs->ss_descs_count)
ffs->raw_ss_descs_offset = 16 + ffs->raw_fs_hs_descs_length + 8;
return 0;
einval:
ret = -EINVAL;
error:
kfree(_data);
return ret;
}
static int __ffs_data_got_strings(struct ffs_data *ffs,
char *const _data, size_t len)
{
u32 str_count, needed_count, lang_count;
struct usb_gadget_strings **stringtabs, *t;
struct usb_string *strings, *s;
const char *data = _data;
ENTER();
if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
get_unaligned_le32(data + 4) != len))
goto error;
str_count = get_unaligned_le32(data + 8);
lang_count = get_unaligned_le32(data + 12);
/* if one is zero the other must be zero */
if (unlikely(!str_count != !lang_count))
goto error;
/* Do we have at least as many strings as descriptors need? */
needed_count = ffs->strings_count;
if (unlikely(str_count < needed_count))
goto error;
/*
* If we don't need any strings just return and free all
* memory.
*/
if (!needed_count) {
kfree(_data);
return 0;
}
/* Allocate everything in one chunk so there's less maintenance. */
{
struct {
struct usb_gadget_strings *stringtabs[lang_count + 1];
struct usb_gadget_strings stringtab[lang_count];
struct usb_string strings[lang_count*(needed_count+1)];
} *d;
unsigned i = 0;
d = kmalloc(sizeof *d, GFP_KERNEL);
if (unlikely(!d)) {
kfree(_data);
return -ENOMEM;
}
stringtabs = d->stringtabs;
t = d->stringtab;
i = lang_count;
do {
*stringtabs++ = t++;
} while (--i);
*stringtabs = NULL;
stringtabs = d->stringtabs;
t = d->stringtab;
s = d->strings;
strings = s;
}
/* For each language */
data += 16;
len -= 16;
do { /* lang_count > 0 so we can use do-while */
unsigned needed = needed_count;
if (unlikely(len < 3))
goto error_free;
t->language = get_unaligned_le16(data);
t->strings = s;
++t;
data += 2;
len -= 2;
/* For each string */
do { /* str_count > 0 so we can use do-while */
size_t length = strnlen(data, len);
if (unlikely(length == len))
goto error_free;
/*
* User may provide more strings then we need,
* if that's the case we simply ignore the
* rest
*/
if (likely(needed)) {
/*
* s->id will be set while adding
* function to configuration so for
* now just leave garbage here.
*/
s->s = data;
--needed;
++s;
}
data += length + 1;
len -= length + 1;
} while (--str_count);
s->id = 0; /* terminator */
s->s = NULL;
++s;
} while (--lang_count);
/* Some garbage left? */
if (unlikely(len))
goto error_free;
/* Done! */
ffs->stringtabs = stringtabs;
ffs->raw_strings = _data;
return 0;
error_free:
kfree(stringtabs);
error:
kfree(_data);
return -EINVAL;
}
/* Events handling and management *******************************************/
static void __ffs_event_add(struct ffs_data *ffs,
enum usb_functionfs_event_type type)
{
enum usb_functionfs_event_type rem_type1, rem_type2 = type;
int neg = 0;
/*
* Abort any unhandled setup
*
* We do not need to worry about some cmpxchg() changing value
* of ffs->setup_state without holding the lock because when
* state is FFS_SETUP_PENDING cmpxchg() in several places in
* the source does nothing.
*/
if (ffs->setup_state == FFS_SETUP_PENDING)
ffs->setup_state = FFS_SETUP_CANCELED;
switch (type) {
case FUNCTIONFS_RESUME:
rem_type2 = FUNCTIONFS_SUSPEND;
/* FALL THROUGH */
case FUNCTIONFS_SUSPEND:
case FUNCTIONFS_SETUP:
rem_type1 = type;
/* Discard all similar events */
break;
case FUNCTIONFS_BIND:
case FUNCTIONFS_UNBIND:
case FUNCTIONFS_DISABLE:
case FUNCTIONFS_ENABLE:
/* Discard everything other then power management. */
rem_type1 = FUNCTIONFS_SUSPEND;
rem_type2 = FUNCTIONFS_RESUME;
neg = 1;
break;
default:
BUG();
}
{
u8 *ev = ffs->ev.types, *out = ev;
unsigned n = ffs->ev.count;
for (; n; --n, ++ev)
if ((*ev == rem_type1 || *ev == rem_type2) == neg)
*out++ = *ev;
else
pr_vdebug("purging event %d\n", *ev);
ffs->ev.count = out - ffs->ev.types;
}
pr_vdebug("adding event %d\n", type);
ffs->ev.types[ffs->ev.count++] = type;
wake_up_locked(&ffs->ev.waitq);
}
static void ffs_event_add(struct ffs_data *ffs,
enum usb_functionfs_event_type type)
{
unsigned long flags;
spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
__ffs_event_add(ffs, type);
spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
}
/* Bind/unbind USB function hooks *******************************************/
static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
struct usb_descriptor_header *desc,
void *priv)
{
struct usb_endpoint_descriptor *ds = (void *)desc;
struct ffs_function *func = priv;
struct ffs_ep *ffs_ep;
/*
* If hs_descriptors is not NULL then we are reading hs
* descriptors now
*/
const int is_hs = func->function.hs_descriptors != NULL;
const int is_ss = func->function.ss_descriptors != NULL;
unsigned ep_desc_id, idx;
if (type != FFS_DESCRIPTOR)
return 0;
if (is_ss) {
func->function.ss_descriptors[(long)valuep] = desc;
ep_desc_id = 2;
} else if (is_hs) {
func->function.hs_descriptors[(long)valuep] = desc;
ep_desc_id = 1;
} else {
func->function.fs_descriptors[(long)valuep] = desc;
ep_desc_id = 0;
}
if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
return 0;
idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
ffs_ep = func->eps + idx;
if (unlikely(ffs_ep->descs[ep_desc_id])) {
pr_vdebug("two %sspeed descriptors for EP %d\n",
is_ss ? "super" : "high/full",
ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
return -EINVAL;
}
ffs_ep->descs[ep_desc_id] = ds;
ffs_dump_mem(": Original ep desc", ds, ds->bLength);
if (ffs_ep->ep) {
ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
if (!ds->wMaxPacketSize)
ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
} else {
struct usb_request *req;
struct usb_ep *ep;
pr_vdebug("autoconfig\n");
ep = usb_ep_autoconfig(func->gadget, ds);
if (unlikely(!ep))
return -ENOTSUPP;
ep->driver_data = func->eps + idx;
req = usb_ep_alloc_request(ep, GFP_KERNEL);
if (unlikely(!req))
return -ENOMEM;
ffs_ep->ep = ep;
ffs_ep->req = req;
func->eps_revmap[ds->bEndpointAddress &
USB_ENDPOINT_NUMBER_MASK] = idx + 1;
}
ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
return 0;
}
static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
struct usb_descriptor_header *desc,
void *priv)
{
struct ffs_function *func = priv;
unsigned idx;
u8 newValue;
switch (type) {
default:
case FFS_DESCRIPTOR:
/* Handled in previous pass by __ffs_func_bind_do_descs() */
return 0;
case FFS_INTERFACE:
idx = *valuep;
if (func->interfaces_nums[idx] < 0) {
int id = usb_interface_id(func->conf, &func->function);
if (unlikely(id < 0))
return id;
func->interfaces_nums[idx] = id;
}
newValue = func->interfaces_nums[idx];
break;
case FFS_STRING:
/* String' IDs are allocated when fsf_data is bound to cdev */
newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
break;
case FFS_ENDPOINT:
/*
* USB_DT_ENDPOINT are handled in
* __ffs_func_bind_do_descs().
*/
if (desc->bDescriptorType == USB_DT_ENDPOINT)
return 0;
idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
if (unlikely(!func->eps[idx].ep))
return -EINVAL;
{
struct usb_endpoint_descriptor **descs;
descs = func->eps[idx].descs;
newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
}
break;
}
pr_vdebug("%02x -> %02x\n", *valuep, newValue);
*valuep = newValue;
return 0;
}
static int ffs_func_bind(struct usb_configuration *c,
struct usb_function *f)
{
struct ffs_function *func = ffs_func_from_usb(f);
struct ffs_data *ffs = func->ffs;
const int full = !!func->ffs->fs_descs_count;
const int high = gadget_is_dualspeed(func->gadget) &&
func->ffs->hs_descs_count;
const int super = gadget_is_superspeed(func->gadget) &&
func->ffs->ss_descs_count;
int fs_len, hs_len, ret;
/* Make it a single chunk, less management later on */
struct {
struct ffs_ep eps[ffs->eps_count];
struct usb_descriptor_header
*fs_descs[full ? ffs->fs_descs_count + 1 : 0];
struct usb_descriptor_header
*hs_descs[high ? ffs->hs_descs_count + 1 : 0];
struct usb_descriptor_header
*ss_descs[super ? ffs->ss_descs_count + 1 : 0];
short inums[ffs->interfaces_count];
char raw_descs[ffs->raw_descs_length];
} *data;
ENTER();
/* Only high/super speed but not supported by gadget? */
if (unlikely(!(full | high | super)))
return -ENOTSUPP;
/* Allocate */
data = kmalloc(sizeof *data, GFP_KERNEL);
if (unlikely(!data))
return -ENOMEM;
/* Zero */
memset(data->eps, 0, sizeof data->eps);
/* Copy only raw (hs,fs) descriptors (until ss_magic and ss_count) */
memcpy(data->raw_descs, ffs->raw_descs + 16,
ffs->raw_fs_hs_descs_length);
/* Copy SS descriptors */
if (func->ffs->ss_descs_count)
memcpy(data->raw_descs + ffs->raw_fs_hs_descs_length,
ffs->raw_descs + ffs->raw_ss_descs_offset,
ffs->raw_ss_descs_length);
memset(data->inums, 0xff, sizeof data->inums);
for (ret = ffs->eps_count; ret; --ret)
data->eps[ret].num = -1;
/* Save pointers */
func->eps = data->eps;
func->interfaces_nums = data->inums;
/*
* Go through all the endpoint descriptors and allocate
* endpoints first, so that later we can rewrite the endpoint
* numbers without worrying that it may be described later on.
*/
if (likely(full)) {
func->function.fs_descriptors = data->fs_descs;
fs_len = ffs_do_descs(ffs->fs_descs_count,
data->raw_descs,
sizeof(data->raw_descs),
__ffs_func_bind_do_descs, func);
if (unlikely(fs_len < 0)) {
ret = fs_len;
goto error;
}
} else {
fs_len = 0;
}
if (likely(high)) {
func->function.hs_descriptors = data->hs_descs;
hs_len = ffs_do_descs(ffs->hs_descs_count,
data->raw_descs + fs_len,
(sizeof(data->raw_descs)) - fs_len,
__ffs_func_bind_do_descs, func);
if (unlikely(hs_len < 0)) {
ret = hs_len;
goto error;
}
} else {
hs_len = 0;
}
if (likely(super)) {
func->function.ss_descriptors = data->ss_descs;
ret = ffs_do_descs(ffs->ss_descs_count,
data->raw_descs + fs_len + hs_len,
(sizeof(data->raw_descs)) - fs_len - hs_len,
__ffs_func_bind_do_descs, func);
if (unlikely(ret < 0))
goto error;
}
/*
* Now handle interface numbers allocation and interface and
* endpoint numbers rewriting. We can do that in one go
* now.
*/
ret = ffs_do_descs(ffs->fs_descs_count +
(high ? ffs->hs_descs_count : 0) +
(super ? ffs->ss_descs_count : 0),
data->raw_descs, sizeof(data->raw_descs),
__ffs_func_bind_do_nums, func);
if (unlikely(ret < 0))
goto error;
/* And we're done */
ffs_event_add(ffs, FUNCTIONFS_BIND);
return 0;
error:
/* XXX Do we need to release all claimed endpoints here? */
return ret;
}
/* Other USB function hooks *************************************************/
static void ffs_func_unbind(struct usb_configuration *c,
struct usb_function *f)
{
struct ffs_function *func = ffs_func_from_usb(f);
struct ffs_data *ffs = func->ffs;
ENTER();
if (ffs->func == func) {
ffs_func_eps_disable(func);
ffs->func = NULL;
}
ffs_event_add(ffs, FUNCTIONFS_UNBIND);
ffs_func_free(func);
}
static int ffs_func_set_alt(struct usb_function *f,
unsigned interface, unsigned alt)
{
struct ffs_function *func = ffs_func_from_usb(f);
struct ffs_data *ffs = func->ffs;
int ret = 0, intf;
if (alt != (unsigned)-1) {
intf = ffs_func_revmap_intf(func, interface);
if (unlikely(intf < 0))
return intf;
}
if (ffs->func) {
ffs_func_eps_disable(ffs->func);
ffs->func = NULL;
}
if (ffs->state != FFS_ACTIVE)
return -ENODEV;
if (alt == (unsigned)-1) {
ffs->func = NULL;
ffs_event_add(ffs, FUNCTIONFS_DISABLE);
return 0;
}
ffs->func = func;
ret = ffs_func_eps_enable(func);
if (likely(ret >= 0))
ffs_event_add(ffs, FUNCTIONFS_ENABLE);
return ret;
}
static void ffs_func_disable(struct usb_function *f)
{
ffs_func_set_alt(f, 0, (unsigned)-1);
}
static int ffs_func_setup(struct usb_function *f,
const struct usb_ctrlrequest *creq)
{
struct ffs_function *func = ffs_func_from_usb(f);
struct ffs_data *ffs = func->ffs;
unsigned long flags;
int ret;
ENTER();
pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
/*
* Most requests directed to interface go through here
* (notable exceptions are set/get interface) so we need to
* handle them. All other either handled by composite or
* passed to usb_configuration->setup() (if one is set). No
* matter, we will handle requests directed to endpoint here
* as well (as it's straightforward) but what to do with any
* other request?
*/
if (ffs->state != FFS_ACTIVE)
return -ENODEV;
switch (creq->bRequestType & USB_RECIP_MASK) {
case USB_RECIP_INTERFACE:
ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
if (unlikely(ret < 0))
return ret;
break;
case USB_RECIP_ENDPOINT:
ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
if (unlikely(ret < 0))
return ret;
break;
default:
return -EOPNOTSUPP;
}
spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
ffs->ev.setup = *creq;
ffs->ev.setup.wIndex = cpu_to_le16(ret);
__ffs_event_add(ffs, FUNCTIONFS_SETUP);
spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
return 0;
}
static void ffs_func_suspend(struct usb_function *f)
{
ENTER();
ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
}
static void ffs_func_resume(struct usb_function *f)
{
ENTER();
ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
}
/* Endpoint and interface numbers reverse mapping ***************************/
static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
{
num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
return num ? num : -EDOM;
}
static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
{
short *nums = func->interfaces_nums;
unsigned count = func->ffs->interfaces_count;
for (; count; --count, ++nums) {
if (*nums >= 0 && *nums == intf)
return nums - func->interfaces_nums;
}
return -EDOM;
}
/* Misc helper functions ****************************************************/
static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
{
return nonblock
? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
: mutex_lock_interruptible(mutex);
}
static char *ffs_prepare_buffer(const char __user *buf, size_t len)
{
char *data;
if (unlikely(!len))
return NULL;
data = kmalloc(len, GFP_KERNEL);
if (unlikely(!data))
return ERR_PTR(-ENOMEM);
if (unlikely(__copy_from_user(data, buf, len))) {
kfree(data);
return ERR_PTR(-EFAULT);
}
pr_vdebug("Buffer from user space:\n");
ffs_dump_mem("", data, len);
return data;
}
| bju2000/android_kernel_lenovo_k30t | drivers/usb/gadget/f_fs.c | C | gpl-2.0 | 62,389 |
<!DOCTYPE html>
<html>
<head>
<title>Human-computer interaction</title>
<meta name="author" content="Samuele Decarli">
<link rel="stylesheet" type="text/css" href="../../../css/style.css">
<meta charset="UTF-8">
<link rel="shortcut icon" href="../../../favicon.png">
</head>
<body>
<div id="wrapper">
<div id="navigation">
<ul>
<li><a href="../../../index.html">Home</a></li>
<li><a href="../../hardware/index.html">Hardware</a></li>
<li class="selected"><a href="../../software/index.html">Software</a></li>
<li><a href="../../internet/index.html">Internet</a></li>
<li><a href="../../games/index.html">Games</a></li>
</ul>
</div>
<div id="contentContainer" class="clearfix">
<div id="content">
<h1>Human-computer interaction</h1>
<p>Practically all of todays' ways of interacting with computers and
software were developed before or during the period from the 70s and the
90s, even the touchscreen, the staple of the smartphone era.</p>
<h2>Command-line interface</h2>
<div class="imgRightWithCaption" style="width: 33%">
<img class="captionedImg" src="images/bash.jpg" alt="CLI">
<div class="caption">Bash, an example of CLI</div>
</div>
<p>Evolved from earlier forms of controlling computers, the command-line
interface (CLI) was the prevalent form of interaction with software in
the 70s, and early 80s, until the widespread introduction of the GUI.<br>
The command line interface allowed people to interact in a real time
way with software, by giving written commands to the computer and, with
interpreters, allowed people to use a programming language, notably BASIC,
to communicate with their machines. It had become possible thanks to better
monitor technology, (going from teleprinters that literally printed
characters on paper to actual monitors).<br>
This kind of interface required users to memorise a list of commands and
have some programming knowledge.<br>
Though completely replaced by GUIs in the mainstream CLIs would continue
to be used in certain contexts, like programming.</p>
<h2>Text-based UI</h2>
<a href="#1"><div class="imgLeftWithCaption" style="width: 33%">
<img class="captionedImg" src="images/text_ui.jpg" alt="Text-based UI">
<div class="caption">Text-based UI</div>
</div></a>
<p>Text-based interfaces would be a sort of <q>missing link</q> between
the command-line and the GUI. Still mostly text based they offered a more
friendly approach to interacting with software. Some of these interfaces
allowed for the use of a mouse, others would be navigated via keyboard or
both. Though certainly easier to utilise than CLIs these interfaces did
not yet allow for the usability level and intuitive metaphors of GUIs.<br>
Many of the earlier <a href="../os/visicalc_lotus123.html">killer apps</a>
had text-based interfaces.<br>
They would be almost completely replaced by GUIs, surviving only in
<a href="../os/bios.html">BIOS</a>
and niche applications, like servers.</p>
<h2>The mouse</h2>
<p>Though invented earlier than the 70s (it was shown by
<a href="../companies_people/Douglas_Engelbart.html">Douglas Engelbert</a>
in his famous demo, in 1968) the
<a href="../../hardware/mouse.html">mouse</a>
would become widespread only later
on, in the 80s, with PC compatible mouses and mouses being included with
the <a href="../../hardware/apple_lisa.html">Apple Lisa</a> and
<a href="../../hardware/macintosh128k_hw.html">Macintosh 128K</a>.<br>
The mouse will allow for a revolution in software, opening up new ways of
interacting with it, and leading to modern GUIs.</p>
<a href="#2"><div class="imgRightWithCaption" style="width: 33%">
<img class="captionedImg" src="images/mac_gui.jpg" alt="GUI">
<div class="caption">Macintosh GUI</div>
</div></a>
<h2>The GUI</h2>
<p>Enabled by the mouse, better monitors and ever more powerful computers,
<a href="../os/gui.html">GUIs</a> would revolutionise the way people
interact with software leading to the development of modern metaphors and
paradigms, like the desktop and windows. Though it was first developed by
<a href="../../internet/xerox_parc.html">Xerox PARC</a>, it would be
Apple with the Apple Lisa, Macintosh and
<a href="../companies_people/microsoft.html">Microsoft's</a> imitations
that would bring the GUI into the mainstream.<br>
Its characteristics would allow GUIs to make computers and software much
more usable and approachable by users, even less tech savvy ones.</p>
<h2>Touchscreens</h2>
<a href="#3"><div class="imgLeftWithCaption" style="width:29%">
<img class="captionedImg" src="images/hp_touchscreen.jpg" alt="Touch">
<div class="caption">HP-150</div>
</div></a>
<p>Though imagined already in the late 60s the first touch was realised
by CERN scientists Frank Beck and Bent Stumpe in 1973. They would remain
out of the mainstream computers for another decade, and only in 1983
a computer with a touchscreen would be commercialised, the HP-150.<br>
Those early touchscreens were based on infrared transmitters and sensors
and did not have the multi-touch capacity of later touchscreens.
Multi-touch capabilities would be developed in 1982, and in 1985, the
first tablet was developed.<br>
Though touchscreens did not greatly influence the computers of the time
they would later become ubiquitous.</p>
<div class="externalLinks">
<h3>External Links</h3>
<ol>
<li>[Visited on 06/11/2014]
<a id="1" href="https://en.wikipedia.org/wiki/File:Synchronet.png">
Image from Wikipedia</a></li>
<li>[Visited on 06/11/2014]
<a id="2" href="https://en.wikipedia.org/wiki/File:Apple_Macintosh_Desktop.png">
Image from Wikipedia</a>, fair use intended</li>
<li>[Visited on 06/11/2014]
<a id="3" href="https://commons.wikimedia.org/wiki/File:Hp150_touchscreen_20081129.jpg">
Image from Wikimedia Commons</a></li>
</ol>
</div>
</div>
</div>
<footer>
<address>Copyright © Samuele Decarli</address>
</footer>
</div>
</body>
</html>
| Lexmark0381/informatics_history_HCI_atelier_2015 | html/software/eco_society/interaction.html | HTML | gpl-2.0 | 6,286 |
#ifndef BOOST_SMART_PTR_DETAIL_SP_COUNTED_BASE_SPIN_HPP_INCLUDED
#define BOOST_SMART_PTR_DETAIL_SP_COUNTED_BASE_SPIN_HPP_INCLUDED
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
//
// detail/sp_counted_base_spin.hpp - spinlock pool atomic emulation
//
// Copyright (c) 2001, 2002, 2003 Peter Dimov and Multi Media Ltd.
// Copyright 2004-2008 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#include "boost/detail/sp_typeinfo.hpp"
#include "boost/smart_ptr/detail/spinlock_pool.hpp"
namespace boost
{
namespace detail
{
inline int atomic_exchange_and_add( int * pw, int dv )
{
spinlock_pool<1>::scoped_lock lock( pw );
int r = *pw;
*pw += dv;
return r;
}
inline void atomic_increment( int * pw )
{
spinlock_pool<1>::scoped_lock lock( pw );
++*pw;
}
inline int atomic_conditional_increment( int * pw )
{
spinlock_pool<1>::scoped_lock lock( pw );
int rv = *pw;
if( rv != 0 ) ++*pw;
return rv;
}
class sp_counted_base
{
private:
sp_counted_base( sp_counted_base const & );
sp_counted_base & operator= ( sp_counted_base const & );
int use_count_; // #shared
int weak_count_; // #weak + (#shared != 0)
public:
sp_counted_base(): use_count_( 1 ), weak_count_( 1 )
{
}
virtual ~sp_counted_base() // nothrow
{
}
// dispose() is called when use_count_ drops to zero, to release
// the resources managed by *this.
virtual void dispose() = 0; // nothrow
// destroy() is called when weak_count_ drops to zero.
virtual void destroy() // nothrow
{
delete this;
}
virtual void * get_deleter( sp_typeinfo const & ti ) = 0;
void add_ref_copy()
{
atomic_increment( &use_count_ );
}
bool add_ref_lock() // true on success
{
return atomic_conditional_increment( &use_count_ ) != 0;
}
void release() // nothrow
{
if( atomic_exchange_and_add( &use_count_, -1 ) == 1 )
{
dispose();
weak_release();
}
}
void weak_add_ref() // nothrow
{
atomic_increment( &weak_count_ );
}
void weak_release() // nothrow
{
if( atomic_exchange_and_add( &weak_count_, -1 ) == 1 )
{
destroy();
}
}
long use_count() const // nothrow
{
spinlock_pool<1>::scoped_lock lock( &use_count_ );
return use_count_;
}
};
} // namespace detail
} // namespace boost
#endif // #ifndef BOOST_SMART_PTR_DETAIL_SP_COUNTED_BASE_SPIN_HPP_INCLUDED
| pallamidessi/GridVis | easeaMultiIslandsOneMachine/boost/boost/smart_ptr/detail/sp_counted_base_spin.hpp | C++ | gpl-2.0 | 2,870 |
<div>
<h2><a href="#book_{{ entity.entityId }}" name="book_{{ entity.entityId }}">{{ entity.title }}</a></h2>
<h3>{{ i18n_TABLE_OF_CONTENTS }}</h3>
<div class="toc">
{% include "book_toc_list.html" %}
</div>
<div>
{% for entity in entity.entities %}
<hr />
{% if entity.isBook %}
{% include "booktemplate.html" %}
{% else %}
{% if entity.isPage %}
{% include "pagetemplate.html" %}
{% endif %}
{% endif %}
{% endfor %}
</div>
</div>
| chusopr/kdepim-ktimetracker-akonadi | kjots/themes/default/booktemplate.html | HTML | gpl-2.0 | 462 |
<?php
/**
* Template File: tutorial 12 - using the pagination helper with custom html.
*
* This is not a complete view file. It is only used to style one row of data and the table heading
* (based on a variable passed to this view file).
*
* @package Tina-MVC
* @subpackage Samples
*/
/**
* Security check - make sure we were included by the main plugin file
*/
if( ! defined('TINA_MVC_LOAD_VIEW') ) exit();
?>
<?php if( $view_file_part == 'headings' ): ?>
<h2>My Custom Table Heading</h2>
<?php else: ?>
<?php
if( $i % 2 ) {
$bg = '#222';
$fg = '#aaa';
}
else {
$bg = '#aaa';
$fg = '#222';
}
?>
<div style="color: <?= $fg ?>; background: <?= $bg ?>">
<small><em>This is row number <?= $i ?></em></small><br />
<strong><big>Display Name: <?= $r->{'Display Name'} ?></big></strong><br />
User Login: <?= $r->{'User Login'} ?> (Database ID: <?= $r->{'Database ID'} ?>)
</div>
<?php endif; ?> | RA2WP/wordpress | wp-content/plugins/tina-mvc/samples/12_table_and_pagination_helpers/page_test_2_view.php | PHP | gpl-2.0 | 1,004 |
/**
* Copyright (c) SpaceToad, 2011
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.blueprints;
import java.util.LinkedList;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
@Deprecated
public class BptBlockUtils {
public static void requestInventoryContents(BptSlotInfo slot, IBptContext context, LinkedList<ItemStack> requirements) {
ItemStack[] stacks = getItemStacks(slot, context);
for (ItemStack stack : stacks) {
if (stack != null) {
requirements.add(stack);
}
}
}
public static void initializeInventoryContents(BptSlotInfo slot, IBptContext context, IInventory inventory) {
ItemStack[] stacks = new ItemStack[inventory.getSizeInventory()];
for (int i = 0; i < inventory.getSizeInventory(); ++i) {
stacks[i] = inventory.getStackInSlot(i);
}
setItemStacks(slot, context, stacks);
}
public static void buildInventoryContents(BptSlotInfo slot, IBptContext context, IInventory inventory) {
ItemStack[] stacks = getItemStacks(slot, context);
for (int i = 0; i < stacks.length; ++i) {
inventory.setInventorySlotContents(i, stacks[i]);
}
}
public static ItemStack[] getItemStacks(BptSlotInfo slot, IBptContext context) {
NBTTagList list = (NBTTagList) slot.cpt.getTag("inv");
if (list == null)
return new ItemStack[0];
ItemStack stacks[] = new ItemStack[list.tagCount()];
for (int i = 0; i < list.tagCount(); ++i) {
ItemStack stack = ItemStack.loadItemStackFromNBT((NBTTagCompound) list.tagAt(i));
if (stack != null && stack.itemID != 0 && stack.stackSize > 0) {
stacks[i] = context.mapItemStack(stack);
}
}
return stacks;
}
public static void setItemStacks(BptSlotInfo slot, IBptContext context, ItemStack[] stacks) {
NBTTagList nbttaglist = new NBTTagList();
for (int i = 0; i < stacks.length; ++i) {
NBTTagCompound cpt = new NBTTagCompound();
nbttaglist.appendTag(cpt);
ItemStack stack = stacks[i];
if (stack != null && stack.stackSize != 0) {
stack.writeToNBT(cpt);
context.storeId(stack.itemID);
}
}
slot.cpt.setTag("inv", nbttaglist);
}
}
| Vexatos/PeripheralsPlusPlus | src/api/resources/reference/buildcraft/api/blueprints/BptBlockUtils.java | Java | gpl-2.0 | 2,396 |
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Copyright (C) 2009 - 2011 Red Hat, Inc.
* Copyright (C) 2009 Novell, Inc.
*/
#ifndef __NETWORKMANAGER_MODEM_H__
#define __NETWORKMANAGER_MODEM_H__
#include <glib-object.h>
#include "ppp-manager/nm-ppp-manager.h"
#include "nm-device.h"
G_BEGIN_DECLS
#define NM_TYPE_MODEM (nm_modem_get_type ())
#define NM_MODEM(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), NM_TYPE_MODEM, NMModem))
#define NM_MODEM_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), NM_TYPE_MODEM, NMModemClass))
#define NM_IS_MODEM(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), NM_TYPE_MODEM))
#define NM_IS_MODEM_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), NM_TYPE_MODEM))
#define NM_MODEM_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), NM_TYPE_MODEM, NMModemClass))
/* Properties */
#define NM_MODEM_UID "uid"
#define NM_MODEM_PATH "path"
#define NM_MODEM_DRIVER "driver"
#define NM_MODEM_CONTROL_PORT "control-port"
#define NM_MODEM_DATA_PORT "data-port"
#define NM_MODEM_IP4_METHOD "ip4-method"
#define NM_MODEM_IP6_METHOD "ip6-method"
#define NM_MODEM_IP_TIMEOUT "ip-timeout"
#define NM_MODEM_STATE "state"
#define NM_MODEM_DEVICE_ID "device-id"
#define NM_MODEM_SIM_ID "sim-id"
#define NM_MODEM_IP_TYPES "ip-types" /* Supported IP types */
/* Signals */
#define NM_MODEM_PPP_STATS "ppp-stats"
#define NM_MODEM_PPP_FAILED "ppp-failed"
#define NM_MODEM_PREPARE_RESULT "prepare-result"
#define NM_MODEM_IP4_CONFIG_RESULT "ip4-config-result"
#define NM_MODEM_IP6_CONFIG_RESULT "ip6-config-result"
#define NM_MODEM_AUTH_REQUESTED "auth-requested"
#define NM_MODEM_AUTH_RESULT "auth-result"
#define NM_MODEM_REMOVED "removed"
#define NM_MODEM_STATE_CHANGED "state-changed"
typedef enum {
NM_MODEM_IP_METHOD_UNKNOWN = 0,
NM_MODEM_IP_METHOD_PPP,
NM_MODEM_IP_METHOD_STATIC,
NM_MODEM_IP_METHOD_AUTO, /* DHCP and/or SLAAC */
} NMModemIPMethod;
/**
* NMModemIPType:
* @NM_MODEM_IP_TYPE_UNKNOWN: unknown or no IP support
* @NM_MODEM_IP_TYPE_IPV4: IPv4-only bearers are supported
* @NM_MODEM_IP_TYPE_IPV6: IPv6-only bearers are supported
* @NM_MODEM_IP_TYPE_IPV4V6: dual-stack IPv4 + IPv6 bearers are supported
*
* Indicates what IP protocols the modem supports for an IP bearer. Any
* combination of flags is possible. For example, (%NM_MODEM_IP_TYPE_IPV4 |
* %NM_MODEM_IP_TYPE_IPV6) indicates that the modem supports IPv4 and IPv6
* but not simultaneously on the same bearer.
*/
typedef enum {
NM_MODEM_IP_TYPE_UNKNOWN = 0x0,
NM_MODEM_IP_TYPE_IPV4 = 0x1,
NM_MODEM_IP_TYPE_IPV6 = 0x2,
NM_MODEM_IP_TYPE_IPV4V6 = 0x4
} NMModemIPType;
typedef enum { /*< underscore_name=nm_modem_state >*/
NM_MODEM_STATE_UNKNOWN = 0,
NM_MODEM_STATE_FAILED = 1,
NM_MODEM_STATE_INITIALIZING = 2,
NM_MODEM_STATE_LOCKED = 3,
NM_MODEM_STATE_DISABLED = 4,
NM_MODEM_STATE_DISABLING = 5,
NM_MODEM_STATE_ENABLING = 6,
NM_MODEM_STATE_ENABLED = 7,
NM_MODEM_STATE_SEARCHING = 8,
NM_MODEM_STATE_REGISTERED = 9,
NM_MODEM_STATE_DISCONNECTING = 10,
NM_MODEM_STATE_CONNECTING = 11,
NM_MODEM_STATE_CONNECTED = 12,
} NMModemState;
typedef struct {
GObject parent;
} NMModem;
typedef struct {
GObjectClass parent;
void (*get_capabilities) (NMModem *self,
NMDeviceModemCapabilities *modem_caps,
NMDeviceModemCapabilities *current_caps);
gboolean (*get_user_pass) (NMModem *modem,
NMConnection *connection,
const char **user,
const char **pass);
gboolean (*check_connection_compatible) (NMModem *modem,
NMConnection *connection);
gboolean (*complete_connection) (NMModem *modem,
NMConnection *connection,
const GSList *existing_connections,
GError **error);
NMActStageReturn (*act_stage1_prepare) (NMModem *modem,
NMConnection *connection,
NMDeviceStateReason *reason);
NMActStageReturn (*static_stage3_ip4_config_start) (NMModem *self,
NMActRequest *req,
NMDeviceStateReason *reason);
/* Request the IP6 config; when the config returns the modem
* subclass should emit the ip6_config_result signal.
*/
NMActStageReturn (*stage3_ip6_config_request) (NMModem *self,
NMDeviceStateReason *reason);
void (*set_mm_enabled) (NMModem *self, gboolean enabled);
void (*disconnect) (NMModem *self, gboolean warn);
void (*deactivate) (NMModem *self, NMDevice *device);
gboolean (*owns_port) (NMModem *self, const char *iface);
/* Signals */
void (*ppp_stats) (NMModem *self, guint32 in_bytes, guint32 out_bytes);
void (*ppp_failed) (NMModem *self, NMDeviceStateReason reason);
void (*prepare_result) (NMModem *self, gboolean success, NMDeviceStateReason reason);
void (*ip4_config_result) (NMModem *self, NMIP4Config *config, GError *error);
void (*ip6_config_result) (NMModem *self,
NMIP6Config *config,
gboolean do_slaac,
GError *error);
void (*auth_requested) (NMModem *self);
void (*auth_result) (NMModem *self, GError *error);
void (*state_changed) (NMModem *self,
NMModemState new_state,
NMModemState old_state);
void (*removed) (NMModem *self);
} NMModemClass;
GType nm_modem_get_type (void);
const char *nm_modem_get_path (NMModem *modem);
const char *nm_modem_get_uid (NMModem *modem);
const char *nm_modem_get_control_port (NMModem *modem);
const char *nm_modem_get_data_port (NMModem *modem);
const char *nm_modem_get_driver (NMModem *modem);
gboolean nm_modem_get_iid (NMModem *modem, NMUtilsIPv6IfaceId *out_iid);
gboolean nm_modem_owns_port (NMModem *modem, const char *iface);
void nm_modem_get_capabilities (NMModem *self,
NMDeviceModemCapabilities *modem_caps,
NMDeviceModemCapabilities *current_caps);
gboolean nm_modem_check_connection_compatible (NMModem *self, NMConnection *connection);
gboolean nm_modem_complete_connection (NMModem *self,
NMConnection *connection,
const GSList *existing_connections,
GError **error);
NMActStageReturn nm_modem_act_stage1_prepare (NMModem *modem,
NMActRequest *req,
NMDeviceStateReason *reason);
NMActStageReturn nm_modem_act_stage2_config (NMModem *modem,
NMActRequest *req,
NMDeviceStateReason *reason);
NMActStageReturn nm_modem_stage3_ip4_config_start (NMModem *modem,
NMDevice *device,
NMDeviceClass *device_class,
NMDeviceStateReason *reason);
NMActStageReturn nm_modem_stage3_ip6_config_start (NMModem *modem,
NMActRequest *req,
NMDeviceStateReason *reason);
void nm_modem_ip4_pre_commit (NMModem *modem, NMDevice *device, NMIP4Config *config);
gboolean nm_modem_get_secrets (NMModem *modem,
const char *setting_name,
gboolean request_new,
const char *hint);
void nm_modem_deactivate (NMModem *modem, NMDevice *device);
void nm_modem_device_state_changed (NMModem *modem,
NMDeviceState new_state,
NMDeviceState old_state,
NMDeviceStateReason reason);
void nm_modem_set_mm_enabled (NMModem *self, gboolean enabled);
NMModemState nm_modem_get_state (NMModem *self);
void nm_modem_set_state (NMModem *self,
NMModemState new_state,
const char *reason);
void nm_modem_set_prev_state (NMModem *self, const char *reason);
const char * nm_modem_state_to_string (NMModemState state);
NMModemIPType nm_modem_get_supported_ip_types (NMModem *self);
/* For the modem-manager only */
void nm_modem_emit_removed (NMModem *self);
NMModemIPType nm_modem_get_connection_ip_type (NMModem *self,
NMConnection *connection,
GError **error);
/* For subclasses */
void nm_modem_emit_ip6_config_result (NMModem *self,
NMIP6Config *config,
GError *error);
G_END_DECLS
#endif /* __NETWORKMANAGER_MODEM_H__ */
| sujithshankar/NetworkManager | src/devices/wwan/nm-modem.h | C | gpl-2.0 | 10,419 |
require 'rails_helper'
require_dependency 'user_option'
describe UserOption do
describe "should_be_redirected_to_top" do
let!(:user) { Fabricate(:user) }
it "should be redirected to top when there is a reason to" do
user.user_option.expects(:redirected_to_top).returns({ reason: "42" })
expect(user.user_option.should_be_redirected_to_top).to eq(true)
end
it "should not be redirected to top when there is no reason to" do
user.user_option.expects(:redirected_to_top).returns(nil)
expect(user.user_option.should_be_redirected_to_top).to eq(false)
end
end
describe ".redirected_to_top" do
let!(:user) { Fabricate(:user) }
it "should have no reason when `SiteSetting.redirect_users_to_top_page` is disabled" do
SiteSetting.expects(:redirect_users_to_top_page).returns(false)
expect(user.user_option.redirected_to_top).to eq(nil)
end
context "when `SiteSetting.redirect_users_to_top_page` is enabled" do
before { SiteSetting.expects(:redirect_users_to_top_page).returns(true) }
it "should have no reason when top is not in the `SiteSetting.top_menu`" do
SiteSetting.expects(:top_menu).returns("latest")
expect(user.user_option.redirected_to_top).to eq(nil)
end
context "and when top is in the `SiteSetting.top_menu`" do
before { SiteSetting.expects(:top_menu).returns("latest|top") }
it "should have no reason when there are not enough topics" do
SiteSetting.expects(:min_redirected_to_top_period).returns(nil)
expect(user.user_option.redirected_to_top).to eq(nil)
end
context "and there are enough topics" do
before { SiteSetting.expects(:min_redirected_to_top_period).returns(:monthly) }
describe "a new user" do
before do
user.stubs(:trust_level).returns(0)
user.stubs(:last_seen_at).returns(5.minutes.ago)
end
it "should have a reason for the first visit" do
expect(user.user_option.redirected_to_top).to eq({
reason: I18n.t('redirected_to_top_reasons.new_user'),
period: :monthly
})
end
it "should not have a reason for next visits" do
user.user_option.expects(:last_redirected_to_top_at).returns(10.minutes.ago)
user.user_option.expects(:update_last_redirected_to_top!).never
expect(user.user_option.redirected_to_top).to eq(nil)
end
end
describe "an older user" do
before { user.stubs(:trust_level).returns(1) }
it "should have a reason when the user hasn't been seen in a month" do
user.last_seen_at = 2.months.ago
user.user_option.expects(:update_last_redirected_to_top!).once
expect(user.user_option.redirected_to_top).to eq({
reason: I18n.t('redirected_to_top_reasons.not_seen_in_a_month'),
period: :monthly
})
end
end
end
end
end
end
end
| scossar/discourse-dev | spec/models/user_option_spec.rb | Ruby | gpl-2.0 | 3,138 |
/*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.vm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class cwde extends Executable
{
public cwde(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
}
public Branch execute(Processor cpu)
{
cpu.r_eax.set32((short)cpu.r_ax.get16());
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | ysangkok/JPC | src/org/jpc/emulator/execution/opcodes/vm/cwde.java | Java | gpl-2.0 | 1,672 |
// Copyright 2016, VIXL authors
// 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 ARM Limited 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 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.
// -----------------------------------------------------------------------------
// This file is auto generated from the
// test/aarch32/config/template-assembler-aarch32.cc.in template file using
// tools/generate_tests.py.
//
// PLEASE DO NOT EDIT.
// -----------------------------------------------------------------------------
#include "test-runner.h"
#include "test-utils.h"
#include "test-utils-aarch32.h"
#include "aarch32/assembler-aarch32.h"
#include "aarch32/macro-assembler-aarch32.h"
#define BUF_SIZE (4096)
namespace vixl {
namespace aarch32 {
// List of instruction mnemonics.
#define FOREACH_INSTRUCTION(M) \
M(adc) \
M(adcs) \
M(add) \
M(adds) \
M(and_) \
M(ands) \
M(bic) \
M(bics) \
M(eor) \
M(eors) \
M(orn) \
M(orns) \
M(orr) \
M(orrs) \
M(rsb) \
M(rsbs) \
M(sbc) \
M(sbcs) \
M(sub) \
M(subs)
// The following definitions are defined again in each generated test, therefore
// we need to place them in an anomymous namespace. It expresses that they are
// local to this file only, and the compiler is not allowed to share these types
// across test files during template instantiation. Specifically, `Operands` has
// various layouts across generated tests so it absolutely cannot be shared.
#ifdef VIXL_INCLUDE_TARGET_T32
namespace {
// Values to be passed to the assembler to produce the instruction under test.
struct Operands {
Condition cond;
Register rd;
Register rn;
Register rm;
ShiftType shift;
uint32_t amount;
};
// This structure contains all data needed to test one specific
// instruction.
struct TestData {
// The `operands` field represents what to pass to the assembler to
// produce the instruction.
Operands operands;
// True if we need to generate an IT instruction for this test to be valid.
bool in_it_block;
// The condition to give the IT instruction, this will be set to "al" by
// default.
Condition it_condition;
// Description of the operands, used for error reporting.
const char* operands_description;
// Unique identifier, used for generating traces.
const char* identifier;
};
struct TestResult {
size_t size;
const byte* encoding;
};
// Each element of this array produce one instruction encoding.
const TestData kTests[] = {{{al, r12, r4, r7, LSL, 7},
false,
al,
"al r12 r4 r7 LSL 7",
"al_r12_r4_r7_LSL_7"},
{{al, r7, r8, r10, ROR, 21},
false,
al,
"al r7 r8 r10 ROR 21",
"al_r7_r8_r10_ROR_21"},
{{al, r5, r5, r3, ROR, 12},
false,
al,
"al r5 r5 r3 ROR 12",
"al_r5_r5_r3_ROR_12"},
{{al, r14, r13, r10, LSL, 22},
false,
al,
"al r14 r13 r10 LSL 22",
"al_r14_r13_r10_LSL_22"},
{{al, r9, r10, r11, ROR, 2},
false,
al,
"al r9 r10 r11 ROR 2",
"al_r9_r10_r11_ROR_2"},
{{al, r14, r11, r5, LSL, 15},
false,
al,
"al r14 r11 r5 LSL 15",
"al_r14_r11_r5_LSL_15"},
{{al, r2, r2, r7, LSL, 28},
false,
al,
"al r2 r2 r7 LSL 28",
"al_r2_r2_r7_LSL_28"},
{{al, r2, r11, r1, ROR, 9},
false,
al,
"al r2 r11 r1 ROR 9",
"al_r2_r11_r1_ROR_9"},
{{al, r11, r2, r8, LSL, 4},
false,
al,
"al r11 r2 r8 LSL 4",
"al_r11_r2_r8_LSL_4"},
{{al, r6, r13, r3, ROR, 1},
false,
al,
"al r6 r13 r3 ROR 1",
"al_r6_r13_r3_ROR_1"},
{{al, r13, r2, r7, LSL, 11},
false,
al,
"al r13 r2 r7 LSL 11",
"al_r13_r2_r7_LSL_11"},
{{al, r9, r9, r1, LSL, 29},
false,
al,
"al r9 r9 r1 LSL 29",
"al_r9_r9_r1_LSL_29"},
{{al, r2, r12, r1, LSL, 15},
false,
al,
"al r2 r12 r1 LSL 15",
"al_r2_r12_r1_LSL_15"},
{{al, r0, r2, r11, LSL, 10},
false,
al,
"al r0 r2 r11 LSL 10",
"al_r0_r2_r11_LSL_10"},
{{al, r11, r12, r8, LSL, 13},
false,
al,
"al r11 r12 r8 LSL 13",
"al_r11_r12_r8_LSL_13"},
{{al, r3, r1, r6, ROR, 3},
false,
al,
"al r3 r1 r6 ROR 3",
"al_r3_r1_r6_ROR_3"},
{{al, r5, r9, r11, LSL, 16},
false,
al,
"al r5 r9 r11 LSL 16",
"al_r5_r9_r11_LSL_16"},
{{al, r2, r0, r6, ROR, 3},
false,
al,
"al r2 r0 r6 ROR 3",
"al_r2_r0_r6_ROR_3"},
{{al, r7, r10, r10, ROR, 19},
false,
al,
"al r7 r10 r10 ROR 19",
"al_r7_r10_r10_ROR_19"},
{{al, r14, r12, r11, LSL, 27},
false,
al,
"al r14 r12 r11 LSL 27",
"al_r14_r12_r11_LSL_27"},
{{al, r2, r13, r1, LSL, 3},
false,
al,
"al r2 r13 r1 LSL 3",
"al_r2_r13_r1_LSL_3"},
{{al, r5, r3, r2, LSL, 11},
false,
al,
"al r5 r3 r2 LSL 11",
"al_r5_r3_r2_LSL_11"},
{{al, r10, r3, r6, ROR, 1},
false,
al,
"al r10 r3 r6 ROR 1",
"al_r10_r3_r6_ROR_1"},
{{al, r6, r14, r2, ROR, 13},
false,
al,
"al r6 r14 r2 ROR 13",
"al_r6_r14_r2_ROR_13"},
{{al, r9, r8, r6, ROR, 13},
false,
al,
"al r9 r8 r6 ROR 13",
"al_r9_r8_r6_ROR_13"},
{{al, r12, r5, r8, LSL, 22},
false,
al,
"al r12 r5 r8 LSL 22",
"al_r12_r5_r8_LSL_22"},
{{al, r11, r8, r11, LSL, 3},
false,
al,
"al r11 r8 r11 LSL 3",
"al_r11_r8_r11_LSL_3"},
{{al, r0, r9, r4, LSL, 24},
false,
al,
"al r0 r9 r4 LSL 24",
"al_r0_r9_r4_LSL_24"},
{{al, r2, r2, r7, ROR, 30},
false,
al,
"al r2 r2 r7 ROR 30",
"al_r2_r2_r7_ROR_30"},
{{al, r9, r3, r10, LSL, 27},
false,
al,
"al r9 r3 r10 LSL 27",
"al_r9_r3_r10_LSL_27"},
{{al, r10, r4, r11, LSL, 23},
false,
al,
"al r10 r4 r11 LSL 23",
"al_r10_r4_r11_LSL_23"},
{{al, r12, r5, r11, ROR, 8},
false,
al,
"al r12 r5 r11 ROR 8",
"al_r12_r5_r11_ROR_8"},
{{al, r6, r6, r6, ROR, 4},
false,
al,
"al r6 r6 r6 ROR 4",
"al_r6_r6_r6_ROR_4"},
{{al, r5, r5, r10, ROR, 29},
false,
al,
"al r5 r5 r10 ROR 29",
"al_r5_r5_r10_ROR_29"},
{{al, r12, r12, r1, LSL, 8},
false,
al,
"al r12 r12 r1 LSL 8",
"al_r12_r12_r1_LSL_8"},
{{al, r5, r3, r1, LSL, 4},
false,
al,
"al r5 r3 r1 LSL 4",
"al_r5_r3_r1_LSL_4"},
{{al, r4, r11, r7, LSL, 17},
false,
al,
"al r4 r11 r7 LSL 17",
"al_r4_r11_r7_LSL_17"},
{{al, r12, r8, r3, LSL, 2},
false,
al,
"al r12 r8 r3 LSL 2",
"al_r12_r8_r3_LSL_2"},
{{al, r2, r11, r3, LSL, 13},
false,
al,
"al r2 r11 r3 LSL 13",
"al_r2_r11_r3_LSL_13"},
{{al, r11, r11, r4, ROR, 19},
false,
al,
"al r11 r11 r4 ROR 19",
"al_r11_r11_r4_ROR_19"},
{{al, r5, r1, r3, LSL, 4},
false,
al,
"al r5 r1 r3 LSL 4",
"al_r5_r1_r3_LSL_4"},
{{al, r2, r5, r7, ROR, 20},
false,
al,
"al r2 r5 r7 ROR 20",
"al_r2_r5_r7_ROR_20"},
{{al, r8, r8, r1, LSL, 24},
false,
al,
"al r8 r8 r1 LSL 24",
"al_r8_r8_r1_LSL_24"},
{{al, r7, r1, r0, LSL, 11},
false,
al,
"al r7 r1 r0 LSL 11",
"al_r7_r1_r0_LSL_11"},
{{al, r10, r5, r0, LSL, 17},
false,
al,
"al r10 r5 r0 LSL 17",
"al_r10_r5_r0_LSL_17"},
{{al, r14, r13, r13, ROR, 18},
false,
al,
"al r14 r13 r13 ROR 18",
"al_r14_r13_r13_ROR_18"},
{{al, r8, r3, r11, LSL, 4},
false,
al,
"al r8 r3 r11 LSL 4",
"al_r8_r3_r11_LSL_4"},
{{al, r1, r11, r10, LSL, 2},
false,
al,
"al r1 r11 r10 LSL 2",
"al_r1_r11_r10_LSL_2"},
{{al, r0, r2, r11, LSL, 25},
false,
al,
"al r0 r2 r11 LSL 25",
"al_r0_r2_r11_LSL_25"},
{{al, r0, r1, r12, LSL, 7},
false,
al,
"al r0 r1 r12 LSL 7",
"al_r0_r1_r12_LSL_7"},
{{al, r5, r0, r8, LSL, 19},
false,
al,
"al r5 r0 r8 LSL 19",
"al_r5_r0_r8_LSL_19"},
{{al, r1, r5, r8, ROR, 16},
false,
al,
"al r1 r5 r8 ROR 16",
"al_r1_r5_r8_ROR_16"},
{{al, r5, r11, r0, LSL, 7},
false,
al,
"al r5 r11 r0 LSL 7",
"al_r5_r11_r0_LSL_7"},
{{al, r4, r5, r9, LSL, 28},
false,
al,
"al r4 r5 r9 LSL 28",
"al_r4_r5_r9_LSL_28"},
{{al, r2, r6, r0, ROR, 5},
false,
al,
"al r2 r6 r0 ROR 5",
"al_r2_r6_r0_ROR_5"},
{{al, r8, r13, r4, ROR, 19},
false,
al,
"al r8 r13 r4 ROR 19",
"al_r8_r13_r4_ROR_19"},
{{al, r10, r11, r4, LSL, 27},
false,
al,
"al r10 r11 r4 LSL 27",
"al_r10_r11_r4_LSL_27"},
{{al, r2, r8, r10, ROR, 12},
false,
al,
"al r2 r8 r10 ROR 12",
"al_r2_r8_r10_ROR_12"},
{{al, r8, r11, r8, ROR, 30},
false,
al,
"al r8 r11 r8 ROR 30",
"al_r8_r11_r8_ROR_30"},
{{al, r7, r12, r14, LSL, 21},
false,
al,
"al r7 r12 r14 LSL 21",
"al_r7_r12_r14_LSL_21"},
{{al, r1, r7, r14, LSL, 18},
false,
al,
"al r1 r7 r14 LSL 18",
"al_r1_r7_r14_LSL_18"},
{{al, r1, r2, r11, ROR, 26},
false,
al,
"al r1 r2 r11 ROR 26",
"al_r1_r2_r11_ROR_26"},
{{al, r12, r10, r0, ROR, 10},
false,
al,
"al r12 r10 r0 ROR 10",
"al_r12_r10_r0_ROR_10"},
{{al, r4, r4, r10, ROR, 22},
false,
al,
"al r4 r4 r10 ROR 22",
"al_r4_r4_r10_ROR_22"},
{{al, r10, r10, r11, LSL, 25},
false,
al,
"al r10 r10 r11 LSL 25",
"al_r10_r10_r11_LSL_25"},
{{al, r5, r11, r12, LSL, 20},
false,
al,
"al r5 r11 r12 LSL 20",
"al_r5_r11_r12_LSL_20"},
{{al, r6, r14, r7, LSL, 26},
false,
al,
"al r6 r14 r7 LSL 26",
"al_r6_r14_r7_LSL_26"},
{{al, r10, r3, r3, LSL, 10},
false,
al,
"al r10 r3 r3 LSL 10",
"al_r10_r3_r3_LSL_10"},
{{al, r11, r3, r5, LSL, 24},
false,
al,
"al r11 r3 r5 LSL 24",
"al_r11_r3_r5_LSL_24"},
{{al, r9, r5, r10, ROR, 23},
false,
al,
"al r9 r5 r10 ROR 23",
"al_r9_r5_r10_ROR_23"},
{{al, r4, r6, r5, ROR, 28},
false,
al,
"al r4 r6 r5 ROR 28",
"al_r4_r6_r5_ROR_28"},
{{al, r9, r10, r4, ROR, 26},
false,
al,
"al r9 r10 r4 ROR 26",
"al_r9_r10_r4_ROR_26"},
{{al, r9, r0, r9, LSL, 2},
false,
al,
"al r9 r0 r9 LSL 2",
"al_r9_r0_r9_LSL_2"},
{{al, r4, r12, r8, LSL, 23},
false,
al,
"al r4 r12 r8 LSL 23",
"al_r4_r12_r8_LSL_23"},
{{al, r7, r9, r11, LSL, 18},
false,
al,
"al r7 r9 r11 LSL 18",
"al_r7_r9_r11_LSL_18"},
{{al, r5, r2, r3, LSL, 19},
false,
al,
"al r5 r2 r3 LSL 19",
"al_r5_r2_r3_LSL_19"},
{{al, r5, r5, r1, ROR, 10},
false,
al,
"al r5 r5 r1 ROR 10",
"al_r5_r5_r1_ROR_10"},
{{al, r3, r0, r7, ROR, 27},
false,
al,
"al r3 r0 r7 ROR 27",
"al_r3_r0_r7_ROR_27"},
{{al, r8, r12, r8, ROR, 14},
false,
al,
"al r8 r12 r8 ROR 14",
"al_r8_r12_r8_ROR_14"},
{{al, r3, r8, r2, LSL, 25},
false,
al,
"al r3 r8 r2 LSL 25",
"al_r3_r8_r2_LSL_25"},
{{al, r8, r5, r8, LSL, 24},
false,
al,
"al r8 r5 r8 LSL 24",
"al_r8_r5_r8_LSL_24"},
{{al, r10, r2, r9, LSL, 23},
false,
al,
"al r10 r2 r9 LSL 23",
"al_r10_r2_r9_LSL_23"},
{{al, r13, r11, r3, ROR, 25},
false,
al,
"al r13 r11 r3 ROR 25",
"al_r13_r11_r3_ROR_25"},
{{al, r2, r13, r2, ROR, 1},
false,
al,
"al r2 r13 r2 ROR 1",
"al_r2_r13_r2_ROR_1"},
{{al, r9, r7, r7, ROR, 18},
false,
al,
"al r9 r7 r7 ROR 18",
"al_r9_r7_r7_ROR_18"},
{{al, r13, r13, r4, ROR, 15},
false,
al,
"al r13 r13 r4 ROR 15",
"al_r13_r13_r4_ROR_15"},
{{al, r1, r2, r0, LSL, 1},
false,
al,
"al r1 r2 r0 LSL 1",
"al_r1_r2_r0_LSL_1"},
{{al, r0, r14, r1, LSL, 7},
false,
al,
"al r0 r14 r1 LSL 7",
"al_r0_r14_r1_LSL_7"},
{{al, r2, r2, r3, LSL, 18},
false,
al,
"al r2 r2 r3 LSL 18",
"al_r2_r2_r3_LSL_18"},
{{al, r12, r12, r10, ROR, 22},
false,
al,
"al r12 r12 r10 ROR 22",
"al_r12_r12_r10_ROR_22"},
{{al, r12, r10, r2, ROR, 13},
false,
al,
"al r12 r10 r2 ROR 13",
"al_r12_r10_r2_ROR_13"},
{{al, r7, r3, r11, LSL, 23},
false,
al,
"al r7 r3 r11 LSL 23",
"al_r7_r3_r11_LSL_23"},
{{al, r4, r7, r14, LSL, 10},
false,
al,
"al r4 r7 r14 LSL 10",
"al_r4_r7_r14_LSL_10"},
{{al, r3, r7, r5, ROR, 27},
false,
al,
"al r3 r7 r5 ROR 27",
"al_r3_r7_r5_ROR_27"},
{{al, r5, r11, r5, ROR, 24},
false,
al,
"al r5 r11 r5 ROR 24",
"al_r5_r11_r5_ROR_24"},
{{al, r12, r0, r6, ROR, 29},
false,
al,
"al r12 r0 r6 ROR 29",
"al_r12_r0_r6_ROR_29"},
{{al, r14, r3, r8, LSL, 26},
false,
al,
"al r14 r3 r8 LSL 26",
"al_r14_r3_r8_LSL_26"},
{{al, r12, r10, r3, LSL, 10},
false,
al,
"al r12 r10 r3 LSL 10",
"al_r12_r10_r3_LSL_10"},
{{al, r3, r8, r6, ROR, 16},
false,
al,
"al r3 r8 r6 ROR 16",
"al_r3_r8_r6_ROR_16"},
{{al, r14, r1, r1, LSL, 23},
false,
al,
"al r14 r1 r1 LSL 23",
"al_r14_r1_r1_LSL_23"},
{{al, r14, r1, r0, LSL, 18},
false,
al,
"al r14 r1 r0 LSL 18",
"al_r14_r1_r0_LSL_18"},
{{al, r7, r1, r8, LSL, 29},
false,
al,
"al r7 r1 r8 LSL 29",
"al_r7_r1_r8_LSL_29"},
{{al, r8, r12, r1, ROR, 22},
false,
al,
"al r8 r12 r1 ROR 22",
"al_r8_r12_r1_ROR_22"},
{{al, r8, r12, r10, ROR, 10},
false,
al,
"al r8 r12 r10 ROR 10",
"al_r8_r12_r10_ROR_10"},
{{al, r1, r14, r3, ROR, 7},
false,
al,
"al r1 r14 r3 ROR 7",
"al_r1_r14_r3_ROR_7"},
{{al, r3, r4, r3, LSL, 20},
false,
al,
"al r3 r4 r3 LSL 20",
"al_r3_r4_r3_LSL_20"},
{{al, r2, r13, r0, LSL, 7},
false,
al,
"al r2 r13 r0 LSL 7",
"al_r2_r13_r0_LSL_7"},
{{al, r13, r0, r9, ROR, 20},
false,
al,
"al r13 r0 r9 ROR 20",
"al_r13_r0_r9_ROR_20"},
{{al, r6, r4, r14, ROR, 5},
false,
al,
"al r6 r4 r14 ROR 5",
"al_r6_r4_r14_ROR_5"},
{{al, r12, r8, r9, ROR, 3},
false,
al,
"al r12 r8 r9 ROR 3",
"al_r12_r8_r9_ROR_3"},
{{al, r0, r11, r2, LSL, 19},
false,
al,
"al r0 r11 r2 LSL 19",
"al_r0_r11_r2_LSL_19"},
{{al, r2, r3, r3, LSL, 8},
false,
al,
"al r2 r3 r3 LSL 8",
"al_r2_r3_r3_LSL_8"},
{{al, r5, r1, r1, ROR, 26},
false,
al,
"al r5 r1 r1 ROR 26",
"al_r5_r1_r1_ROR_26"},
{{al, r4, r4, r13, ROR, 31},
false,
al,
"al r4 r4 r13 ROR 31",
"al_r4_r4_r13_ROR_31"},
{{al, r4, r6, r8, ROR, 11},
false,
al,
"al r4 r6 r8 ROR 11",
"al_r4_r6_r8_ROR_11"},
{{al, r4, r10, r13, LSL, 28},
false,
al,
"al r4 r10 r13 LSL 28",
"al_r4_r10_r13_LSL_28"},
{{al, r0, r8, r5, LSL, 19},
false,
al,
"al r0 r8 r5 LSL 19",
"al_r0_r8_r5_LSL_19"},
{{al, r14, r0, r7, ROR, 10},
false,
al,
"al r14 r0 r7 ROR 10",
"al_r14_r0_r7_ROR_10"},
{{al, r9, r10, r9, ROR, 13},
false,
al,
"al r9 r10 r9 ROR 13",
"al_r9_r10_r9_ROR_13"},
{{al, r5, r1, r7, LSL, 31},
false,
al,
"al r5 r1 r7 LSL 31",
"al_r5_r1_r7_LSL_31"},
{{al, r8, r4, r12, ROR, 8},
false,
al,
"al r8 r4 r12 ROR 8",
"al_r8_r4_r12_ROR_8"},
{{al, r8, r13, r0, LSL, 4},
false,
al,
"al r8 r13 r0 LSL 4",
"al_r8_r13_r0_LSL_4"},
{{al, r10, r4, r10, LSL, 19},
false,
al,
"al r10 r4 r10 LSL 19",
"al_r10_r4_r10_LSL_19"},
{{al, r5, r2, r3, LSL, 5},
false,
al,
"al r5 r2 r3 LSL 5",
"al_r5_r2_r3_LSL_5"},
{{al, r1, r1, r2, LSL, 17},
false,
al,
"al r1 r1 r2 LSL 17",
"al_r1_r1_r2_LSL_17"},
{{al, r9, r2, r13, ROR, 13},
false,
al,
"al r9 r2 r13 ROR 13",
"al_r9_r2_r13_ROR_13"},
{{al, r2, r5, r5, ROR, 8},
false,
al,
"al r2 r5 r5 ROR 8",
"al_r2_r5_r5_ROR_8"},
{{al, r11, r11, r10, ROR, 31},
false,
al,
"al r11 r11 r10 ROR 31",
"al_r11_r11_r10_ROR_31"},
{{al, r13, r14, r13, LSL, 23},
false,
al,
"al r13 r14 r13 LSL 23",
"al_r13_r14_r13_LSL_23"},
{{al, r9, r0, r3, ROR, 6},
false,
al,
"al r9 r0 r3 ROR 6",
"al_r9_r0_r3_ROR_6"},
{{al, r10, r10, r11, LSL, 9},
false,
al,
"al r10 r10 r11 LSL 9",
"al_r10_r10_r11_LSL_9"},
{{al, r13, r10, r11, ROR, 31},
false,
al,
"al r13 r10 r11 ROR 31",
"al_r13_r10_r11_ROR_31"},
{{al, r8, r8, r10, LSL, 23},
false,
al,
"al r8 r8 r10 LSL 23",
"al_r8_r8_r10_LSL_23"},
{{al, r13, r13, r10, ROR, 27},
false,
al,
"al r13 r13 r10 ROR 27",
"al_r13_r13_r10_ROR_27"},
{{al, r6, r4, r7, LSL, 19},
false,
al,
"al r6 r4 r7 LSL 19",
"al_r6_r4_r7_LSL_19"},
{{al, r6, r1, r7, LSL, 23},
false,
al,
"al r6 r1 r7 LSL 23",
"al_r6_r1_r7_LSL_23"},
{{al, r11, r13, r9, ROR, 2},
false,
al,
"al r11 r13 r9 ROR 2",
"al_r11_r13_r9_ROR_2"},
{{al, r14, r13, r8, LSL, 11},
false,
al,
"al r14 r13 r8 LSL 11",
"al_r14_r13_r8_LSL_11"},
{{al, r10, r11, r8, ROR, 11},
false,
al,
"al r10 r11 r8 ROR 11",
"al_r10_r11_r8_ROR_11"},
{{al, r5, r5, r1, ROR, 15},
false,
al,
"al r5 r5 r1 ROR 15",
"al_r5_r5_r1_ROR_15"},
{{al, r1, r3, r0, LSL, 14},
false,
al,
"al r1 r3 r0 LSL 14",
"al_r1_r3_r0_LSL_14"},
{{al, r11, r4, r0, ROR, 29},
false,
al,
"al r11 r4 r0 ROR 29",
"al_r11_r4_r0_ROR_29"},
{{al, r6, r11, r10, ROR, 25},
false,
al,
"al r6 r11 r10 ROR 25",
"al_r6_r11_r10_ROR_25"},
{{al, r8, r3, r9, ROR, 15},
false,
al,
"al r8 r3 r9 ROR 15",
"al_r8_r3_r9_ROR_15"},
{{al, r3, r12, r14, LSL, 23},
false,
al,
"al r3 r12 r14 LSL 23",
"al_r3_r12_r14_LSL_23"},
{{al, r14, r14, r6, ROR, 23},
false,
al,
"al r14 r14 r6 ROR 23",
"al_r14_r14_r6_ROR_23"},
{{al, r6, r8, r8, ROR, 25},
false,
al,
"al r6 r8 r8 ROR 25",
"al_r6_r8_r8_ROR_25"},
{{al, r5, r5, r2, LSL, 17},
false,
al,
"al r5 r5 r2 LSL 17",
"al_r5_r5_r2_LSL_17"},
{{al, r13, r4, r6, ROR, 13},
false,
al,
"al r13 r4 r6 ROR 13",
"al_r13_r4_r6_ROR_13"},
{{al, r10, r9, r0, LSL, 25},
false,
al,
"al r10 r9 r0 LSL 25",
"al_r10_r9_r0_LSL_25"},
{{al, r11, r2, r5, ROR, 15},
false,
al,
"al r11 r2 r5 ROR 15",
"al_r11_r2_r5_ROR_15"},
{{al, r4, r13, r4, LSL, 8},
false,
al,
"al r4 r13 r4 LSL 8",
"al_r4_r13_r4_LSL_8"},
{{al, r13, r6, r5, LSL, 31},
false,
al,
"al r13 r6 r5 LSL 31",
"al_r13_r6_r5_LSL_31"},
{{al, r3, r5, r6, ROR, 25},
false,
al,
"al r3 r5 r6 ROR 25",
"al_r3_r5_r6_ROR_25"},
{{al, r7, r7, r12, ROR, 12},
false,
al,
"al r7 r7 r12 ROR 12",
"al_r7_r7_r12_ROR_12"},
{{al, r6, r10, r6, ROR, 18},
false,
al,
"al r6 r10 r6 ROR 18",
"al_r6_r10_r6_ROR_18"},
{{al, r8, r14, r14, LSL, 30},
false,
al,
"al r8 r14 r14 LSL 30",
"al_r8_r14_r14_LSL_30"},
{{al, r0, r0, r2, LSL, 4},
false,
al,
"al r0 r0 r2 LSL 4",
"al_r0_r0_r2_LSL_4"},
{{al, r11, r2, r3, ROR, 10},
false,
al,
"al r11 r2 r3 ROR 10",
"al_r11_r2_r3_ROR_10"},
{{al, r2, r6, r14, ROR, 29},
false,
al,
"al r2 r6 r14 ROR 29",
"al_r2_r6_r14_ROR_29"},
{{al, r4, r5, r11, ROR, 22},
false,
al,
"al r4 r5 r11 ROR 22",
"al_r4_r5_r11_ROR_22"},
{{al, r13, r5, r1, LSL, 8},
false,
al,
"al r13 r5 r1 LSL 8",
"al_r13_r5_r1_LSL_8"},
{{al, r9, r3, r0, ROR, 25},
false,
al,
"al r9 r3 r0 ROR 25",
"al_r9_r3_r0_ROR_25"},
{{al, r10, r0, r14, LSL, 11},
false,
al,
"al r10 r0 r14 LSL 11",
"al_r10_r0_r14_LSL_11"},
{{al, r8, r13, r13, ROR, 6},
false,
al,
"al r8 r13 r13 ROR 6",
"al_r8_r13_r13_ROR_6"},
{{al, r10, r7, r14, LSL, 10},
false,
al,
"al r10 r7 r14 LSL 10",
"al_r10_r7_r14_LSL_10"},
{{al, r9, r6, r12, ROR, 31},
false,
al,
"al r9 r6 r12 ROR 31",
"al_r9_r6_r12_ROR_31"},
{{al, r9, r5, r0, ROR, 1},
false,
al,
"al r9 r5 r0 ROR 1",
"al_r9_r5_r0_ROR_1"},
{{al, r0, r10, r12, LSL, 11},
false,
al,
"al r0 r10 r12 LSL 11",
"al_r0_r10_r12_LSL_11"},
{{al, r8, r0, r8, ROR, 15},
false,
al,
"al r8 r0 r8 ROR 15",
"al_r8_r0_r8_ROR_15"},
{{al, r13, r2, r1, LSL, 21},
false,
al,
"al r13 r2 r1 LSL 21",
"al_r13_r2_r1_LSL_21"},
{{al, r3, r0, r9, LSL, 29},
false,
al,
"al r3 r0 r9 LSL 29",
"al_r3_r0_r9_LSL_29"},
{{al, r14, r10, r11, LSL, 17},
false,
al,
"al r14 r10 r11 LSL 17",
"al_r14_r10_r11_LSL_17"},
{{al, r13, r4, r0, LSL, 17},
false,
al,
"al r13 r4 r0 LSL 17",
"al_r13_r4_r0_LSL_17"},
{{al, r0, r3, r4, LSL, 6},
false,
al,
"al r0 r3 r4 LSL 6",
"al_r0_r3_r4_LSL_6"},
{{al, r13, r9, r2, LSL, 21},
false,
al,
"al r13 r9 r2 LSL 21",
"al_r13_r9_r2_LSL_21"},
{{al, r13, r5, r13, LSL, 23},
false,
al,
"al r13 r5 r13 LSL 23",
"al_r13_r5_r13_LSL_23"},
{{al, r14, r10, r2, LSL, 8},
false,
al,
"al r14 r10 r2 LSL 8",
"al_r14_r10_r2_LSL_8"},
{{al, r12, r11, r12, LSL, 13},
false,
al,
"al r12 r11 r12 LSL 13",
"al_r12_r11_r12_LSL_13"},
{{al, r10, r2, r12, ROR, 23},
false,
al,
"al r10 r2 r12 ROR 23",
"al_r10_r2_r12_ROR_23"},
{{al, r5, r5, r8, ROR, 28},
false,
al,
"al r5 r5 r8 ROR 28",
"al_r5_r5_r8_ROR_28"},
{{al, r0, r14, r12, ROR, 19},
false,
al,
"al r0 r14 r12 ROR 19",
"al_r0_r14_r12_ROR_19"},
{{al, r8, r13, r11, LSL, 24},
false,
al,
"al r8 r13 r11 LSL 24",
"al_r8_r13_r11_LSL_24"},
{{al, r9, r5, r3, ROR, 30},
false,
al,
"al r9 r5 r3 ROR 30",
"al_r9_r5_r3_ROR_30"},
{{al, r9, r10, r7, ROR, 22},
false,
al,
"al r9 r10 r7 ROR 22",
"al_r9_r10_r7_ROR_22"},
{{al, r10, r3, r10, LSL, 18},
false,
al,
"al r10 r3 r10 LSL 18",
"al_r10_r3_r10_LSL_18"},
{{al, r7, r3, r14, ROR, 22},
false,
al,
"al r7 r3 r14 ROR 22",
"al_r7_r3_r14_ROR_22"},
{{al, r11, r4, r4, LSL, 20},
false,
al,
"al r11 r4 r4 LSL 20",
"al_r11_r4_r4_LSL_20"},
{{al, r7, r13, r14, ROR, 25},
false,
al,
"al r7 r13 r14 ROR 25",
"al_r7_r13_r14_ROR_25"},
{{al, r10, r10, r1, ROR, 5},
false,
al,
"al r10 r10 r1 ROR 5",
"al_r10_r10_r1_ROR_5"},
{{al, r4, r12, r6, LSL, 6},
false,
al,
"al r4 r12 r6 LSL 6",
"al_r4_r12_r6_LSL_6"},
{{al, r3, r6, r9, ROR, 3},
false,
al,
"al r3 r6 r9 ROR 3",
"al_r3_r6_r9_ROR_3"},
{{al, r14, r3, r7, LSL, 26},
false,
al,
"al r14 r3 r7 LSL 26",
"al_r14_r3_r7_LSL_26"},
{{al, r0, r8, r10, LSL, 10},
false,
al,
"al r0 r8 r10 LSL 10",
"al_r0_r8_r10_LSL_10"},
{{al, r13, r10, r7, ROR, 19},
false,
al,
"al r13 r10 r7 ROR 19",
"al_r13_r10_r7_ROR_19"},
{{al, r14, r1, r6, ROR, 27},
false,
al,
"al r14 r1 r6 ROR 27",
"al_r14_r1_r6_ROR_27"},
{{al, r0, r5, r13, LSL, 18},
false,
al,
"al r0 r5 r13 LSL 18",
"al_r0_r5_r13_LSL_18"},
{{al, r10, r9, r0, LSL, 15},
false,
al,
"al r10 r9 r0 LSL 15",
"al_r10_r9_r0_LSL_15"},
{{al, r12, r8, r13, ROR, 19},
false,
al,
"al r12 r8 r13 ROR 19",
"al_r12_r8_r13_ROR_19"},
{{al, r8, r0, r11, LSL, 31},
false,
al,
"al r8 r0 r11 LSL 31",
"al_r8_r0_r11_LSL_31"},
{{al, r8, r14, r0, ROR, 20},
false,
al,
"al r8 r14 r0 ROR 20",
"al_r8_r14_r0_ROR_20"},
{{al, r8, r7, r6, ROR, 14},
false,
al,
"al r8 r7 r6 ROR 14",
"al_r8_r7_r6_ROR_14"},
{{al, r10, r9, r5, LSL, 21},
false,
al,
"al r10 r9 r5 LSL 21",
"al_r10_r9_r5_LSL_21"},
{{al, r9, r8, r13, ROR, 28},
false,
al,
"al r9 r8 r13 ROR 28",
"al_r9_r8_r13_ROR_28"},
{{al, r12, r12, r12, ROR, 25},
false,
al,
"al r12 r12 r12 ROR 25",
"al_r12_r12_r12_ROR_25"},
{{al, r5, r11, r4, ROR, 12},
false,
al,
"al r5 r11 r4 ROR 12",
"al_r5_r11_r4_ROR_12"},
{{al, r1, r7, r10, ROR, 13},
false,
al,
"al r1 r7 r10 ROR 13",
"al_r1_r7_r10_ROR_13"},
{{al, r14, r12, r2, LSL, 19},
false,
al,
"al r14 r12 r2 LSL 19",
"al_r14_r12_r2_LSL_19"},
{{al, r0, r5, r14, LSL, 20},
false,
al,
"al r0 r5 r14 LSL 20",
"al_r0_r5_r14_LSL_20"},
{{al, r12, r4, r3, ROR, 27},
false,
al,
"al r12 r4 r3 ROR 27",
"al_r12_r4_r3_ROR_27"},
{{al, r9, r3, r1, ROR, 22},
false,
al,
"al r9 r3 r1 ROR 22",
"al_r9_r3_r1_ROR_22"},
{{al, r2, r12, r7, ROR, 23},
false,
al,
"al r2 r12 r7 ROR 23",
"al_r2_r12_r7_ROR_23"},
{{al, r10, r4, r8, ROR, 11},
false,
al,
"al r10 r4 r8 ROR 11",
"al_r10_r4_r8_ROR_11"},
{{al, r6, r0, r2, LSL, 8},
false,
al,
"al r6 r0 r2 LSL 8",
"al_r6_r0_r2_LSL_8"},
{{al, r10, r3, r0, LSL, 1},
false,
al,
"al r10 r3 r0 LSL 1",
"al_r10_r3_r0_LSL_1"},
{{al, r6, r6, r4, LSL, 1},
false,
al,
"al r6 r6 r4 LSL 1",
"al_r6_r6_r4_LSL_1"},
{{al, r13, r12, r13, ROR, 13},
false,
al,
"al r13 r12 r13 ROR 13",
"al_r13_r12_r13_ROR_13"},
{{al, r0, r9, r10, ROR, 1},
false,
al,
"al r0 r9 r10 ROR 1",
"al_r0_r9_r10_ROR_1"},
{{al, r9, r13, r9, ROR, 16},
false,
al,
"al r9 r13 r9 ROR 16",
"al_r9_r13_r9_ROR_16"},
{{al, r0, r6, r2, LSL, 4},
false,
al,
"al r0 r6 r2 LSL 4",
"al_r0_r6_r2_LSL_4"},
{{al, r9, r2, r11, LSL, 31},
false,
al,
"al r9 r2 r11 LSL 31",
"al_r9_r2_r11_LSL_31"},
{{al, r12, r12, r13, ROR, 19},
false,
al,
"al r12 r12 r13 ROR 19",
"al_r12_r12_r13_ROR_19"},
{{al, r7, r14, r2, ROR, 23},
false,
al,
"al r7 r14 r2 ROR 23",
"al_r7_r14_r2_ROR_23"},
{{al, r7, r1, r3, LSL, 26},
false,
al,
"al r7 r1 r3 LSL 26",
"al_r7_r1_r3_LSL_26"},
{{al, r13, r6, r12, ROR, 26},
false,
al,
"al r13 r6 r12 ROR 26",
"al_r13_r6_r12_ROR_26"},
{{al, r10, r14, r12, ROR, 5},
false,
al,
"al r10 r14 r12 ROR 5",
"al_r10_r14_r12_ROR_5"},
{{al, r5, r9, r12, LSL, 9},
false,
al,
"al r5 r9 r12 LSL 9",
"al_r5_r9_r12_LSL_9"},
{{al, r2, r7, r2, ROR, 10},
false,
al,
"al r2 r7 r2 ROR 10",
"al_r2_r7_r2_ROR_10"},
{{al, r12, r12, r8, ROR, 6},
false,
al,
"al r12 r12 r8 ROR 6",
"al_r12_r12_r8_ROR_6"},
{{al, r1, r13, r13, ROR, 24},
false,
al,
"al r1 r13 r13 ROR 24",
"al_r1_r13_r13_ROR_24"},
{{al, r6, r10, r10, ROR, 26},
false,
al,
"al r6 r10 r10 ROR 26",
"al_r6_r10_r10_ROR_26"},
{{al, r13, r9, r1, LSL, 18},
false,
al,
"al r13 r9 r1 LSL 18",
"al_r13_r9_r1_LSL_18"},
{{al, r6, r1, r4, ROR, 21},
false,
al,
"al r6 r1 r4 ROR 21",
"al_r6_r1_r4_ROR_21"},
{{al, r0, r3, r3, ROR, 18},
false,
al,
"al r0 r3 r3 ROR 18",
"al_r0_r3_r3_ROR_18"},
{{al, r1, r9, r5, LSL, 29},
false,
al,
"al r1 r9 r5 LSL 29",
"al_r1_r9_r5_LSL_29"},
{{al, r11, r8, r7, ROR, 18},
false,
al,
"al r11 r8 r7 ROR 18",
"al_r11_r8_r7_ROR_18"},
{{al, r2, r3, r12, LSL, 7},
false,
al,
"al r2 r3 r12 LSL 7",
"al_r2_r3_r12_LSL_7"},
{{al, r8, r3, r9, LSL, 18},
false,
al,
"al r8 r3 r9 LSL 18",
"al_r8_r3_r9_LSL_18"},
{{al, r8, r12, r1, LSL, 11},
false,
al,
"al r8 r12 r1 LSL 11",
"al_r8_r12_r1_LSL_11"},
{{al, r14, r9, r5, ROR, 21},
false,
al,
"al r14 r9 r5 ROR 21",
"al_r14_r9_r5_ROR_21"},
{{al, r0, r6, r12, ROR, 26},
false,
al,
"al r0 r6 r12 ROR 26",
"al_r0_r6_r12_ROR_26"},
{{al, r3, r6, r14, LSL, 14},
false,
al,
"al r3 r6 r14 LSL 14",
"al_r3_r6_r14_LSL_14"},
{{al, r11, r0, r9, LSL, 9},
false,
al,
"al r11 r0 r9 LSL 9",
"al_r11_r0_r9_LSL_9"},
{{al, r8, r13, r7, LSL, 9},
false,
al,
"al r8 r13 r7 LSL 9",
"al_r8_r13_r7_LSL_9"},
{{al, r3, r1, r13, LSL, 23},
false,
al,
"al r3 r1 r13 LSL 23",
"al_r3_r1_r13_LSL_23"},
{{al, r12, r13, r13, ROR, 4},
false,
al,
"al r12 r13 r13 ROR 4",
"al_r12_r13_r13_ROR_4"},
{{al, r10, r14, r9, ROR, 13},
false,
al,
"al r10 r14 r9 ROR 13",
"al_r10_r14_r9_ROR_13"},
{{al, r14, r5, r1, LSL, 22},
false,
al,
"al r14 r5 r1 LSL 22",
"al_r14_r5_r1_LSL_22"},
{{al, r11, r8, r8, ROR, 28},
false,
al,
"al r11 r8 r8 ROR 28",
"al_r11_r8_r8_ROR_28"},
{{al, r0, r8, r12, ROR, 19},
false,
al,
"al r0 r8 r12 ROR 19",
"al_r0_r8_r12_ROR_19"},
{{al, r11, r3, r1, ROR, 6},
false,
al,
"al r11 r3 r1 ROR 6",
"al_r11_r3_r1_ROR_6"},
{{al, r2, r7, r2, ROR, 5},
false,
al,
"al r2 r7 r2 ROR 5",
"al_r2_r7_r2_ROR_5"},
{{al, r11, r14, r2, ROR, 14},
false,
al,
"al r11 r14 r2 ROR 14",
"al_r11_r14_r2_ROR_14"},
{{al, r9, r13, r7, LSL, 27},
false,
al,
"al r9 r13 r7 LSL 27",
"al_r9_r13_r7_LSL_27"},
{{al, r0, r0, r3, ROR, 29},
false,
al,
"al r0 r0 r3 ROR 29",
"al_r0_r0_r3_ROR_29"},
{{al, r9, r12, r7, LSL, 24},
false,
al,
"al r9 r12 r7 LSL 24",
"al_r9_r12_r7_LSL_24"},
{{al, r8, r5, r4, LSL, 10},
false,
al,
"al r8 r5 r4 LSL 10",
"al_r8_r5_r4_LSL_10"},
{{al, r0, r2, r12, ROR, 10},
false,
al,
"al r0 r2 r12 ROR 10",
"al_r0_r2_r12_ROR_10"},
{{al, r6, r0, r5, ROR, 16},
false,
al,
"al r6 r0 r5 ROR 16",
"al_r6_r0_r5_ROR_16"},
{{al, r9, r9, r14, ROR, 2},
false,
al,
"al r9 r9 r14 ROR 2",
"al_r9_r9_r14_ROR_2"},
{{al, r0, r0, r7, ROR, 28},
false,
al,
"al r0 r0 r7 ROR 28",
"al_r0_r0_r7_ROR_28"},
{{al, r2, r11, r12, LSL, 16},
false,
al,
"al r2 r11 r12 LSL 16",
"al_r2_r11_r12_LSL_16"},
{{al, r14, r0, r8, ROR, 13},
false,
al,
"al r14 r0 r8 ROR 13",
"al_r14_r0_r8_ROR_13"},
{{al, r3, r4, r3, LSL, 2},
false,
al,
"al r3 r4 r3 LSL 2",
"al_r3_r4_r3_LSL_2"},
{{al, r11, r6, r4, ROR, 25},
false,
al,
"al r11 r6 r4 ROR 25",
"al_r11_r6_r4_ROR_25"},
{{al, r14, r1, r12, LSL, 4},
false,
al,
"al r14 r1 r12 LSL 4",
"al_r14_r1_r12_LSL_4"},
{{al, r9, r2, r6, LSL, 12},
false,
al,
"al r9 r2 r6 LSL 12",
"al_r9_r2_r6_LSL_12"},
{{al, r10, r9, r2, ROR, 26},
false,
al,
"al r10 r9 r2 ROR 26",
"al_r10_r9_r2_ROR_26"},
{{al, r2, r3, r10, ROR, 2},
false,
al,
"al r2 r3 r10 ROR 2",
"al_r2_r3_r10_ROR_2"},
{{al, r6, r7, r9, LSL, 12},
false,
al,
"al r6 r7 r9 LSL 12",
"al_r6_r7_r9_LSL_12"},
{{al, r4, r1, r7, LSL, 6},
false,
al,
"al r4 r1 r7 LSL 6",
"al_r4_r1_r7_LSL_6"},
{{al, r4, r3, r13, ROR, 31},
false,
al,
"al r4 r3 r13 ROR 31",
"al_r4_r3_r13_ROR_31"},
{{al, r14, r1, r0, ROR, 11},
false,
al,
"al r14 r1 r0 ROR 11",
"al_r14_r1_r0_ROR_11"},
{{al, r4, r3, r9, ROR, 18},
false,
al,
"al r4 r3 r9 ROR 18",
"al_r4_r3_r9_ROR_18"},
{{al, r4, r5, r2, ROR, 26},
false,
al,
"al r4 r5 r2 ROR 26",
"al_r4_r5_r2_ROR_26"},
{{al, r11, r13, r9, LSL, 1},
false,
al,
"al r11 r13 r9 LSL 1",
"al_r11_r13_r9_LSL_1"},
{{al, r6, r13, r8, LSL, 31},
false,
al,
"al r6 r13 r8 LSL 31",
"al_r6_r13_r8_LSL_31"},
{{al, r8, r6, r5, LSL, 7},
false,
al,
"al r8 r6 r5 LSL 7",
"al_r8_r6_r5_LSL_7"},
{{al, r3, r12, r11, LSL, 29},
false,
al,
"al r3 r12 r11 LSL 29",
"al_r3_r12_r11_LSL_29"},
{{al, r4, r11, r3, ROR, 25},
false,
al,
"al r4 r11 r3 ROR 25",
"al_r4_r11_r3_ROR_25"},
{{al, r11, r0, r3, ROR, 1},
false,
al,
"al r11 r0 r3 ROR 1",
"al_r11_r0_r3_ROR_1"},
{{al, r10, r7, r8, ROR, 14},
false,
al,
"al r10 r7 r8 ROR 14",
"al_r10_r7_r8_ROR_14"},
{{al, r12, r8, r5, ROR, 17},
false,
al,
"al r12 r8 r5 ROR 17",
"al_r12_r8_r5_ROR_17"},
{{al, r13, r11, r1, LSL, 26},
false,
al,
"al r13 r11 r1 LSL 26",
"al_r13_r11_r1_LSL_26"},
{{al, r13, r4, r5, ROR, 26},
false,
al,
"al r13 r4 r5 ROR 26",
"al_r13_r4_r5_ROR_26"},
{{al, r12, r5, r8, ROR, 17},
false,
al,
"al r12 r5 r8 ROR 17",
"al_r12_r5_r8_ROR_17"},
{{al, r12, r0, r10, ROR, 16},
false,
al,
"al r12 r0 r10 ROR 16",
"al_r12_r0_r10_ROR_16"},
{{al, r6, r4, r14, ROR, 28},
false,
al,
"al r6 r4 r14 ROR 28",
"al_r6_r4_r14_ROR_28"},
{{al, r13, r13, r5, LSL, 16},
false,
al,
"al r13 r13 r5 LSL 16",
"al_r13_r13_r5_LSL_16"},
{{al, r9, r6, r10, LSL, 15},
false,
al,
"al r9 r6 r10 LSL 15",
"al_r9_r6_r10_LSL_15"},
{{al, r2, r10, r8, LSL, 16},
false,
al,
"al r2 r10 r8 LSL 16",
"al_r2_r10_r8_LSL_16"},
{{al, r11, r4, r0, LSL, 5},
false,
al,
"al r11 r4 r0 LSL 5",
"al_r11_r4_r0_LSL_5"},
{{al, r9, r2, r14, ROR, 31},
false,
al,
"al r9 r2 r14 ROR 31",
"al_r9_r2_r14_ROR_31"},
{{al, r0, r7, r11, LSL, 25},
false,
al,
"al r0 r7 r11 LSL 25",
"al_r0_r7_r11_LSL_25"},
{{al, r2, r6, r12, LSL, 8},
false,
al,
"al r2 r6 r12 LSL 8",
"al_r2_r6_r12_LSL_8"},
{{al, r1, r10, r4, ROR, 7},
false,
al,
"al r1 r10 r4 ROR 7",
"al_r1_r10_r4_ROR_7"},
{{al, r4, r3, r7, LSL, 10},
false,
al,
"al r4 r3 r7 LSL 10",
"al_r4_r3_r7_LSL_10"},
{{al, r6, r7, r11, LSL, 14},
false,
al,
"al r6 r7 r11 LSL 14",
"al_r6_r7_r11_LSL_14"},
{{al, r9, r10, r0, LSL, 31},
false,
al,
"al r9 r10 r0 LSL 31",
"al_r9_r10_r0_LSL_31"},
{{al, r5, r5, r13, LSL, 2},
false,
al,
"al r5 r5 r13 LSL 2",
"al_r5_r5_r13_LSL_2"},
{{al, r7, r10, r2, LSL, 26},
false,
al,
"al r7 r10 r2 LSL 26",
"al_r7_r10_r2_LSL_26"},
{{al, r3, r7, r7, LSL, 29},
false,
al,
"al r3 r7 r7 LSL 29",
"al_r3_r7_r7_LSL_29"},
{{al, r4, r1, r8, LSL, 18},
false,
al,
"al r4 r1 r8 LSL 18",
"al_r4_r1_r8_LSL_18"},
{{al, r14, r12, r2, LSL, 29},
false,
al,
"al r14 r12 r2 LSL 29",
"al_r14_r12_r2_LSL_29"},
{{al, r11, r6, r3, ROR, 8},
false,
al,
"al r11 r6 r3 ROR 8",
"al_r11_r6_r3_ROR_8"},
{{al, r14, r5, r3, LSL, 7},
false,
al,
"al r14 r5 r3 LSL 7",
"al_r14_r5_r3_LSL_7"},
{{al, r6, r13, r12, LSL, 2},
false,
al,
"al r6 r13 r12 LSL 2",
"al_r6_r13_r12_LSL_2"},
{{al, r9, r1, r0, ROR, 13},
false,
al,
"al r9 r1 r0 ROR 13",
"al_r9_r1_r0_ROR_13"},
{{al, r9, r5, r7, LSL, 16},
false,
al,
"al r9 r5 r7 LSL 16",
"al_r9_r5_r7_LSL_16"},
{{al, r2, r6, r0, ROR, 27},
false,
al,
"al r2 r6 r0 ROR 27",
"al_r2_r6_r0_ROR_27"},
{{al, r4, r9, r5, LSL, 19},
false,
al,
"al r4 r9 r5 LSL 19",
"al_r4_r9_r5_LSL_19"},
{{al, r9, r5, r13, ROR, 26},
false,
al,
"al r9 r5 r13 ROR 26",
"al_r9_r5_r13_ROR_26"},
{{al, r4, r9, r14, LSL, 25},
false,
al,
"al r4 r9 r14 LSL 25",
"al_r4_r9_r14_LSL_25"},
{{al, r7, r13, r1, LSL, 22},
false,
al,
"al r7 r13 r1 LSL 22",
"al_r7_r13_r1_LSL_22"},
{{al, r14, r13, r6, LSL, 25},
false,
al,
"al r14 r13 r6 LSL 25",
"al_r14_r13_r6_LSL_25"},
{{al, r14, r12, r14, ROR, 1},
false,
al,
"al r14 r12 r14 ROR 1",
"al_r14_r12_r14_ROR_1"},
{{al, r9, r7, r4, ROR, 28},
false,
al,
"al r9 r7 r4 ROR 28",
"al_r9_r7_r4_ROR_28"},
{{al, r13, r14, r11, ROR, 4},
false,
al,
"al r13 r14 r11 ROR 4",
"al_r13_r14_r11_ROR_4"},
{{al, r14, r6, r14, LSL, 22},
false,
al,
"al r14 r6 r14 LSL 22",
"al_r14_r6_r14_LSL_22"},
{{al, r9, r10, r13, LSL, 27},
false,
al,
"al r9 r10 r13 LSL 27",
"al_r9_r10_r13_LSL_27"},
{{al, r12, r1, r7, LSL, 17},
false,
al,
"al r12 r1 r7 LSL 17",
"al_r12_r1_r7_LSL_17"},
{{al, r8, r0, r5, ROR, 6},
false,
al,
"al r8 r0 r5 ROR 6",
"al_r8_r0_r5_ROR_6"},
{{al, r3, r11, r6, LSL, 6},
false,
al,
"al r3 r11 r6 LSL 6",
"al_r3_r11_r6_LSL_6"},
{{al, r13, r5, r7, LSL, 23},
false,
al,
"al r13 r5 r7 LSL 23",
"al_r13_r5_r7_LSL_23"},
{{al, r13, r8, r1, ROR, 20},
false,
al,
"al r13 r8 r1 ROR 20",
"al_r13_r8_r1_ROR_20"},
{{al, r13, r0, r7, LSL, 10},
false,
al,
"al r13 r0 r7 LSL 10",
"al_r13_r0_r7_LSL_10"},
{{al, r7, r1, r12, ROR, 17},
false,
al,
"al r7 r1 r12 ROR 17",
"al_r7_r1_r12_ROR_17"},
{{al, r5, r3, r12, LSL, 12},
false,
al,
"al r5 r3 r12 LSL 12",
"al_r5_r3_r12_LSL_12"},
{{al, r0, r12, r4, LSL, 6},
false,
al,
"al r0 r12 r4 LSL 6",
"al_r0_r12_r4_LSL_6"},
{{al, r7, r11, r11, ROR, 8},
false,
al,
"al r7 r11 r11 ROR 8",
"al_r7_r11_r11_ROR_8"},
{{al, r3, r0, r0, LSL, 17},
false,
al,
"al r3 r0 r0 LSL 17",
"al_r3_r0_r0_LSL_17"},
{{al, r4, r12, r0, ROR, 2},
false,
al,
"al r4 r12 r0 ROR 2",
"al_r4_r12_r0_ROR_2"},
{{al, r6, r3, r3, LSL, 25},
false,
al,
"al r6 r3 r3 LSL 25",
"al_r6_r3_r3_LSL_25"},
{{al, r9, r5, r5, LSL, 9},
false,
al,
"al r9 r5 r5 LSL 9",
"al_r9_r5_r5_LSL_9"},
{{al, r7, r3, r4, LSL, 20},
false,
al,
"al r7 r3 r4 LSL 20",
"al_r7_r3_r4_LSL_20"},
{{al, r12, r1, r7, ROR, 6},
false,
al,
"al r12 r1 r7 ROR 6",
"al_r12_r1_r7_ROR_6"},
{{al, r2, r14, r7, LSL, 23},
false,
al,
"al r2 r14 r7 LSL 23",
"al_r2_r14_r7_LSL_23"},
{{al, r9, r6, r9, ROR, 22},
false,
al,
"al r9 r6 r9 ROR 22",
"al_r9_r6_r9_ROR_22"},
{{al, r1, r8, r2, ROR, 11},
false,
al,
"al r1 r8 r2 ROR 11",
"al_r1_r8_r2_ROR_11"},
{{al, r10, r2, r14, ROR, 15},
false,
al,
"al r10 r2 r14 ROR 15",
"al_r10_r2_r14_ROR_15"},
{{al, r9, r1, r9, ROR, 27},
false,
al,
"al r9 r1 r9 ROR 27",
"al_r9_r1_r9_ROR_27"},
{{al, r12, r11, r13, ROR, 30},
false,
al,
"al r12 r11 r13 ROR 30",
"al_r12_r11_r13_ROR_30"},
{{al, r13, r11, r1, ROR, 5},
false,
al,
"al r13 r11 r1 ROR 5",
"al_r13_r11_r1_ROR_5"},
{{al, r12, r8, r10, LSL, 24},
false,
al,
"al r12 r8 r10 LSL 24",
"al_r12_r8_r10_LSL_24"},
{{al, r8, r6, r10, ROR, 19},
false,
al,
"al r8 r6 r10 ROR 19",
"al_r8_r6_r10_ROR_19"},
{{al, r0, r0, r2, ROR, 26},
false,
al,
"al r0 r0 r2 ROR 26",
"al_r0_r0_r2_ROR_26"},
{{al, r7, r14, r10, LSL, 28},
false,
al,
"al r7 r14 r10 LSL 28",
"al_r7_r14_r10_LSL_28"},
{{al, r3, r2, r12, LSL, 12},
false,
al,
"al r3 r2 r12 LSL 12",
"al_r3_r2_r12_LSL_12"},
{{al, r9, r3, r8, ROR, 29},
false,
al,
"al r9 r3 r8 ROR 29",
"al_r9_r3_r8_ROR_29"},
{{al, r4, r11, r12, LSL, 14},
false,
al,
"al r4 r11 r12 LSL 14",
"al_r4_r11_r12_LSL_14"},
{{al, r7, r5, r11, ROR, 9},
false,
al,
"al r7 r5 r11 ROR 9",
"al_r7_r5_r11_ROR_9"},
{{al, r12, r7, r7, ROR, 2},
false,
al,
"al r12 r7 r7 ROR 2",
"al_r12_r7_r7_ROR_2"},
{{al, r3, r6, r9, ROR, 24},
false,
al,
"al r3 r6 r9 ROR 24",
"al_r3_r6_r9_ROR_24"},
{{al, r13, r14, r9, ROR, 12},
false,
al,
"al r13 r14 r9 ROR 12",
"al_r13_r14_r9_ROR_12"},
{{al, r7, r3, r13, ROR, 2},
false,
al,
"al r7 r3 r13 ROR 2",
"al_r7_r3_r13_ROR_2"},
{{al, r5, r11, r3, LSL, 21},
false,
al,
"al r5 r11 r3 LSL 21",
"al_r5_r11_r3_LSL_21"},
{{al, r12, r9, r9, ROR, 17},
false,
al,
"al r12 r9 r9 ROR 17",
"al_r12_r9_r9_ROR_17"},
{{al, r0, r12, r13, ROR, 3},
false,
al,
"al r0 r12 r13 ROR 3",
"al_r0_r12_r13_ROR_3"},
{{al, r2, r4, r7, ROR, 28},
false,
al,
"al r2 r4 r7 ROR 28",
"al_r2_r4_r7_ROR_28"},
{{al, r11, r14, r8, LSL, 5},
false,
al,
"al r11 r14 r8 LSL 5",
"al_r11_r14_r8_LSL_5"},
{{al, r14, r3, r14, ROR, 11},
false,
al,
"al r14 r3 r14 ROR 11",
"al_r14_r3_r14_ROR_11"},
{{al, r3, r4, r9, LSL, 10},
false,
al,
"al r3 r4 r9 LSL 10",
"al_r3_r4_r9_LSL_10"},
{{al, r10, r5, r3, ROR, 11},
false,
al,
"al r10 r5 r3 ROR 11",
"al_r10_r5_r3_ROR_11"},
{{al, r5, r12, r2, ROR, 29},
false,
al,
"al r5 r12 r2 ROR 29",
"al_r5_r12_r2_ROR_29"},
{{al, r12, r10, r8, ROR, 29},
false,
al,
"al r12 r10 r8 ROR 29",
"al_r12_r10_r8_ROR_29"},
{{al, r4, r2, r12, ROR, 13},
false,
al,
"al r4 r2 r12 ROR 13",
"al_r4_r2_r12_ROR_13"},
{{al, r11, r7, r7, ROR, 29},
false,
al,
"al r11 r7 r7 ROR 29",
"al_r11_r7_r7_ROR_29"},
{{al, r12, r10, r2, ROR, 20},
false,
al,
"al r12 r10 r2 ROR 20",
"al_r12_r10_r2_ROR_20"},
{{al, r0, r11, r3, LSL, 6},
false,
al,
"al r0 r11 r3 LSL 6",
"al_r0_r11_r3_LSL_6"},
{{al, r12, r8, r10, ROR, 13},
false,
al,
"al r12 r8 r10 ROR 13",
"al_r12_r8_r10_ROR_13"},
{{al, r2, r3, r9, LSL, 30},
false,
al,
"al r2 r3 r9 LSL 30",
"al_r2_r3_r9_LSL_30"},
{{al, r9, r5, r8, ROR, 27},
false,
al,
"al r9 r5 r8 ROR 27",
"al_r9_r5_r8_ROR_27"},
{{al, r7, r3, r12, ROR, 16},
false,
al,
"al r7 r3 r12 ROR 16",
"al_r7_r3_r12_ROR_16"},
{{al, r11, r8, r3, LSL, 29},
false,
al,
"al r11 r8 r3 LSL 29",
"al_r11_r8_r3_LSL_29"},
{{al, r3, r9, r3, LSL, 13},
false,
al,
"al r3 r9 r3 LSL 13",
"al_r3_r9_r3_LSL_13"},
{{al, r10, r2, r13, LSL, 7},
false,
al,
"al r10 r2 r13 LSL 7",
"al_r10_r2_r13_LSL_7"},
{{al, r1, r0, r9, LSL, 22},
false,
al,
"al r1 r0 r9 LSL 22",
"al_r1_r0_r9_LSL_22"},
{{al, r8, r3, r9, ROR, 24},
false,
al,
"al r8 r3 r9 ROR 24",
"al_r8_r3_r9_ROR_24"},
{{al, r9, r13, r8, LSL, 25},
false,
al,
"al r9 r13 r8 LSL 25",
"al_r9_r13_r8_LSL_25"},
{{al, r7, r2, r13, ROR, 16},
false,
al,
"al r7 r2 r13 ROR 16",
"al_r7_r2_r13_ROR_16"},
{{al, r5, r6, r3, LSL, 3},
false,
al,
"al r5 r6 r3 LSL 3",
"al_r5_r6_r3_LSL_3"},
{{al, r5, r6, r10, LSL, 15},
false,
al,
"al r5 r6 r10 LSL 15",
"al_r5_r6_r10_LSL_15"},
{{al, r6, r8, r12, LSL, 13},
false,
al,
"al r6 r8 r12 LSL 13",
"al_r6_r8_r12_LSL_13"},
{{al, r1, r9, r11, ROR, 7},
false,
al,
"al r1 r9 r11 ROR 7",
"al_r1_r9_r11_ROR_7"},
{{al, r0, r3, r7, LSL, 12},
false,
al,
"al r0 r3 r7 LSL 12",
"al_r0_r3_r7_LSL_12"},
{{al, r8, r10, r2, ROR, 6},
false,
al,
"al r8 r10 r2 ROR 6",
"al_r8_r10_r2_ROR_6"},
{{al, r2, r11, r5, LSL, 10},
false,
al,
"al r2 r11 r5 LSL 10",
"al_r2_r11_r5_LSL_10"},
{{al, r13, r5, r4, LSL, 15},
false,
al,
"al r13 r5 r4 LSL 15",
"al_r13_r5_r4_LSL_15"},
{{al, r6, r1, r12, LSL, 27},
false,
al,
"al r6 r1 r12 LSL 27",
"al_r6_r1_r12_LSL_27"},
{{al, r14, r3, r5, ROR, 19},
false,
al,
"al r14 r3 r5 ROR 19",
"al_r14_r3_r5_ROR_19"},
{{al, r14, r0, r13, LSL, 12},
false,
al,
"al r14 r0 r13 LSL 12",
"al_r14_r0_r13_LSL_12"},
{{al, r11, r2, r8, ROR, 15},
false,
al,
"al r11 r2 r8 ROR 15",
"al_r11_r2_r8_ROR_15"},
{{al, r0, r1, r3, ROR, 1},
false,
al,
"al r0 r1 r3 ROR 1",
"al_r0_r1_r3_ROR_1"},
{{al, r13, r11, r11, ROR, 31},
false,
al,
"al r13 r11 r11 ROR 31",
"al_r13_r11_r11_ROR_31"},
{{al, r1, r4, r4, LSL, 20},
false,
al,
"al r1 r4 r4 LSL 20",
"al_r1_r4_r4_LSL_20"},
{{al, r2, r7, r6, ROR, 7},
false,
al,
"al r2 r7 r6 ROR 7",
"al_r2_r7_r6_ROR_7"},
{{al, r0, r3, r11, ROR, 21},
false,
al,
"al r0 r3 r11 ROR 21",
"al_r0_r3_r11_ROR_21"},
{{al, r14, r9, r6, LSL, 20},
false,
al,
"al r14 r9 r6 LSL 20",
"al_r14_r9_r6_LSL_20"},
{{al, r11, r2, r14, ROR, 1},
false,
al,
"al r11 r2 r14 ROR 1",
"al_r11_r2_r14_ROR_1"},
{{al, r13, r10, r8, ROR, 22},
false,
al,
"al r13 r10 r8 ROR 22",
"al_r13_r10_r8_ROR_22"},
{{al, r11, r2, r2, LSL, 27},
false,
al,
"al r11 r2 r2 LSL 27",
"al_r11_r2_r2_LSL_27"},
{{al, r3, r2, r14, LSL, 6},
false,
al,
"al r3 r2 r14 LSL 6",
"al_r3_r2_r14_LSL_6"},
{{al, r8, r3, r0, LSL, 20},
false,
al,
"al r8 r3 r0 LSL 20",
"al_r8_r3_r0_LSL_20"},
{{al, r8, r14, r11, ROR, 19},
false,
al,
"al r8 r14 r11 ROR 19",
"al_r8_r14_r11_ROR_19"},
{{al, r7, r14, r0, ROR, 8},
false,
al,
"al r7 r14 r0 ROR 8",
"al_r7_r14_r0_ROR_8"},
{{al, r6, r6, r3, ROR, 13},
false,
al,
"al r6 r6 r3 ROR 13",
"al_r6_r6_r3_ROR_13"},
{{al, r1, r9, r3, LSL, 10},
false,
al,
"al r1 r9 r3 LSL 10",
"al_r1_r9_r3_LSL_10"},
{{al, r14, r12, r14, ROR, 13},
false,
al,
"al r14 r12 r14 ROR 13",
"al_r14_r12_r14_ROR_13"},
{{al, r8, r5, r13, LSL, 19},
false,
al,
"al r8 r5 r13 LSL 19",
"al_r8_r5_r13_LSL_19"},
{{al, r6, r10, r10, ROR, 3},
false,
al,
"al r6 r10 r10 ROR 3",
"al_r6_r10_r10_ROR_3"},
{{al, r9, r5, r1, ROR, 19},
false,
al,
"al r9 r5 r1 ROR 19",
"al_r9_r5_r1_ROR_19"},
{{al, r10, r8, r1, LSL, 12},
false,
al,
"al r10 r8 r1 LSL 12",
"al_r10_r8_r1_LSL_12"},
{{al, r3, r0, r6, ROR, 31},
false,
al,
"al r3 r0 r6 ROR 31",
"al_r3_r0_r6_ROR_31"},
{{al, r6, r6, r5, ROR, 1},
false,
al,
"al r6 r6 r5 ROR 1",
"al_r6_r6_r5_ROR_1"},
{{al, r3, r0, r0, LSL, 18},
false,
al,
"al r3 r0 r0 LSL 18",
"al_r3_r0_r0_LSL_18"},
{{al, r14, r12, r1, LSL, 11},
false,
al,
"al r14 r12 r1 LSL 11",
"al_r14_r12_r1_LSL_11"},
{{al, r4, r13, r1, ROR, 17},
false,
al,
"al r4 r13 r1 ROR 17",
"al_r4_r13_r1_ROR_17"},
{{al, r1, r13, r0, ROR, 10},
false,
al,
"al r1 r13 r0 ROR 10",
"al_r1_r13_r0_ROR_10"},
{{al, r8, r0, r0, LSL, 11},
false,
al,
"al r8 r0 r0 LSL 11",
"al_r8_r0_r0_LSL_11"},
{{al, r3, r3, r10, ROR, 18},
false,
al,
"al r3 r3 r10 ROR 18",
"al_r3_r3_r10_ROR_18"},
{{al, r12, r8, r9, LSL, 7},
false,
al,
"al r12 r8 r9 LSL 7",
"al_r12_r8_r9_LSL_7"},
{{al, r3, r3, r11, ROR, 10},
false,
al,
"al r3 r3 r11 ROR 10",
"al_r3_r3_r11_ROR_10"},
{{al, r3, r14, r6, ROR, 5},
false,
al,
"al r3 r14 r6 ROR 5",
"al_r3_r14_r6_ROR_5"},
{{al, r7, r0, r12, ROR, 7},
false,
al,
"al r7 r0 r12 ROR 7",
"al_r7_r0_r12_ROR_7"},
{{al, r12, r2, r8, LSL, 13},
false,
al,
"al r12 r2 r8 LSL 13",
"al_r12_r2_r8_LSL_13"},
{{al, r10, r1, r0, ROR, 8},
false,
al,
"al r10 r1 r0 ROR 8",
"al_r10_r1_r0_ROR_8"},
{{al, r6, r12, r6, LSL, 30},
false,
al,
"al r6 r12 r6 LSL 30",
"al_r6_r12_r6_LSL_30"},
{{al, r6, r3, r7, ROR, 11},
false,
al,
"al r6 r3 r7 ROR 11",
"al_r6_r3_r7_ROR_11"},
{{al, r5, r12, r7, ROR, 28},
false,
al,
"al r5 r12 r7 ROR 28",
"al_r5_r12_r7_ROR_28"},
{{al, r4, r12, r10, LSL, 6},
false,
al,
"al r4 r12 r10 LSL 6",
"al_r4_r12_r10_LSL_6"},
{{al, r11, r5, r1, ROR, 3},
false,
al,
"al r11 r5 r1 ROR 3",
"al_r11_r5_r1_ROR_3"},
{{al, r9, r3, r0, ROR, 26},
false,
al,
"al r9 r3 r0 ROR 26",
"al_r9_r3_r0_ROR_26"},
{{al, r8, r1, r10, LSL, 13},
false,
al,
"al r8 r1 r10 LSL 13",
"al_r8_r1_r10_LSL_13"},
{{al, r14, r13, r14, ROR, 20},
false,
al,
"al r14 r13 r14 ROR 20",
"al_r14_r13_r14_ROR_20"},
{{al, r2, r3, r8, LSL, 7},
false,
al,
"al r2 r3 r8 LSL 7",
"al_r2_r3_r8_LSL_7"},
{{al, r0, r11, r10, ROR, 4},
false,
al,
"al r0 r11 r10 ROR 4",
"al_r0_r11_r10_ROR_4"},
{{al, r1, r6, r9, LSL, 27},
false,
al,
"al r1 r6 r9 LSL 27",
"al_r1_r6_r9_LSL_27"},
{{al, r5, r2, r4, ROR, 10},
false,
al,
"al r5 r2 r4 ROR 10",
"al_r5_r2_r4_ROR_10"},
{{al, r13, r8, r9, LSL, 20},
false,
al,
"al r13 r8 r9 LSL 20",
"al_r13_r8_r9_LSL_20"},
{{al, r11, r7, r0, LSL, 20},
false,
al,
"al r11 r7 r0 LSL 20",
"al_r11_r7_r0_LSL_20"},
{{al, r2, r9, r1, LSL, 30},
false,
al,
"al r2 r9 r1 LSL 30",
"al_r2_r9_r1_LSL_30"},
{{al, r5, r0, r5, ROR, 24},
false,
al,
"al r5 r0 r5 ROR 24",
"al_r5_r0_r5_ROR_24"},
{{al, r7, r4, r10, LSL, 17},
false,
al,
"al r7 r4 r10 LSL 17",
"al_r7_r4_r10_LSL_17"},
{{al, r11, r3, r7, ROR, 19},
false,
al,
"al r11 r3 r7 ROR 19",
"al_r11_r3_r7_ROR_19"},
{{al, r8, r2, r6, ROR, 1},
false,
al,
"al r8 r2 r6 ROR 1",
"al_r8_r2_r6_ROR_1"},
{{al, r5, r1, r8, ROR, 25},
false,
al,
"al r5 r1 r8 ROR 25",
"al_r5_r1_r8_ROR_25"},
{{al, r1, r4, r12, LSL, 28},
false,
al,
"al r1 r4 r12 LSL 28",
"al_r1_r4_r12_LSL_28"},
{{al, r12, r1, r4, LSL, 14},
false,
al,
"al r12 r1 r4 LSL 14",
"al_r12_r1_r4_LSL_14"},
{{al, r9, r12, r13, LSL, 25},
false,
al,
"al r9 r12 r13 LSL 25",
"al_r9_r12_r13_LSL_25"},
{{al, r11, r14, r5, ROR, 12},
false,
al,
"al r11 r14 r5 ROR 12",
"al_r11_r14_r5_ROR_12"},
{{al, r3, r8, r13, LSL, 4},
false,
al,
"al r3 r8 r13 LSL 4",
"al_r3_r8_r13_LSL_4"},
{{al, r9, r14, r10, ROR, 12},
false,
al,
"al r9 r14 r10 ROR 12",
"al_r9_r14_r10_ROR_12"},
{{al, r0, r13, r1, ROR, 30},
false,
al,
"al r0 r13 r1 ROR 30",
"al_r0_r13_r1_ROR_30"},
{{al, r11, r9, r9, ROR, 23},
false,
al,
"al r11 r9 r9 ROR 23",
"al_r11_r9_r9_ROR_23"},
{{al, r5, r2, r8, ROR, 6},
false,
al,
"al r5 r2 r8 ROR 6",
"al_r5_r2_r8_ROR_6"},
{{al, r8, r14, r10, ROR, 23},
false,
al,
"al r8 r14 r10 ROR 23",
"al_r8_r14_r10_ROR_23"},
{{al, r14, r12, r2, LSL, 26},
false,
al,
"al r14 r12 r2 LSL 26",
"al_r14_r12_r2_LSL_26"},
{{al, r2, r9, r10, LSL, 12},
false,
al,
"al r2 r9 r10 LSL 12",
"al_r2_r9_r10_LSL_12"},
{{al, r3, r1, r11, LSL, 17},
false,
al,
"al r3 r1 r11 LSL 17",
"al_r3_r1_r11_LSL_17"},
{{al, r3, r8, r10, LSL, 23},
false,
al,
"al r3 r8 r10 LSL 23",
"al_r3_r8_r10_LSL_23"},
{{al, r3, r6, r4, ROR, 31},
false,
al,
"al r3 r6 r4 ROR 31",
"al_r3_r6_r4_ROR_31"},
{{al, r3, r5, r10, LSL, 22},
false,
al,
"al r3 r5 r10 LSL 22",
"al_r3_r5_r10_LSL_22"},
{{al, r0, r3, r10, ROR, 1},
false,
al,
"al r0 r3 r10 ROR 1",
"al_r0_r3_r10_ROR_1"},
{{al, r5, r9, r7, ROR, 9},
false,
al,
"al r5 r9 r7 ROR 9",
"al_r5_r9_r7_ROR_9"},
{{al, r11, r2, r2, LSL, 24},
false,
al,
"al r11 r2 r2 LSL 24",
"al_r11_r2_r2_LSL_24"},
{{al, r10, r11, r7, LSL, 29},
false,
al,
"al r10 r11 r7 LSL 29",
"al_r10_r11_r7_LSL_29"},
{{al, r5, r4, r10, ROR, 26},
false,
al,
"al r5 r4 r10 ROR 26",
"al_r5_r4_r10_ROR_26"},
{{al, r8, r8, r7, LSL, 20},
false,
al,
"al r8 r8 r7 LSL 20",
"al_r8_r8_r7_LSL_20"},
{{al, r12, r6, r5, ROR, 20},
false,
al,
"al r12 r6 r5 ROR 20",
"al_r12_r6_r5_ROR_20"},
{{al, r9, r4, r7, LSL, 21},
false,
al,
"al r9 r4 r7 LSL 21",
"al_r9_r4_r7_LSL_21"},
{{al, r8, r2, r7, LSL, 4},
false,
al,
"al r8 r2 r7 LSL 4",
"al_r8_r2_r7_LSL_4"},
{{al, r9, r14, r12, LSL, 8},
false,
al,
"al r9 r14 r12 LSL 8",
"al_r9_r14_r12_LSL_8"},
{{al, r1, r12, r8, ROR, 25},
false,
al,
"al r1 r12 r8 ROR 25",
"al_r1_r12_r8_ROR_25"},
{{al, r4, r1, r4, ROR, 26},
false,
al,
"al r4 r1 r4 ROR 26",
"al_r4_r1_r4_ROR_26"},
{{al, r12, r6, r14, ROR, 22},
false,
al,
"al r12 r6 r14 ROR 22",
"al_r12_r6_r14_ROR_22"},
{{al, r2, r6, r9, LSL, 17},
false,
al,
"al r2 r6 r9 LSL 17",
"al_r2_r6_r9_LSL_17"},
{{al, r8, r8, r1, ROR, 15},
false,
al,
"al r8 r8 r1 ROR 15",
"al_r8_r8_r1_ROR_15"},
{{al, r13, r10, r8, ROR, 27},
false,
al,
"al r13 r10 r8 ROR 27",
"al_r13_r10_r8_ROR_27"},
{{al, r1, r10, r10, LSL, 27},
false,
al,
"al r1 r10 r10 LSL 27",
"al_r1_r10_r10_LSL_27"},
{{al, r7, r1, r11, ROR, 26},
false,
al,
"al r7 r1 r11 ROR 26",
"al_r7_r1_r11_ROR_26"},
{{al, r13, r14, r11, ROR, 29},
false,
al,
"al r13 r14 r11 ROR 29",
"al_r13_r14_r11_ROR_29"},
{{al, r5, r3, r14, ROR, 7},
false,
al,
"al r5 r3 r14 ROR 7",
"al_r5_r3_r14_ROR_7"},
{{al, r2, r12, r9, LSL, 22},
false,
al,
"al r2 r12 r9 LSL 22",
"al_r2_r12_r9_LSL_22"},
{{al, r4, r2, r9, LSL, 12},
false,
al,
"al r4 r2 r9 LSL 12",
"al_r4_r2_r9_LSL_12"},
{{al, r6, r7, r5, LSL, 8},
false,
al,
"al r6 r7 r5 LSL 8",
"al_r6_r7_r5_LSL_8"},
{{al, r14, r11, r6, LSL, 10},
false,
al,
"al r14 r11 r6 LSL 10",
"al_r14_r11_r6_LSL_10"},
{{al, r11, r10, r7, ROR, 10},
false,
al,
"al r11 r10 r7 ROR 10",
"al_r11_r10_r7_ROR_10"},
{{al, r9, r11, r5, ROR, 8},
false,
al,
"al r9 r11 r5 ROR 8",
"al_r9_r11_r5_ROR_8"},
{{al, r13, r12, r0, ROR, 1},
false,
al,
"al r13 r12 r0 ROR 1",
"al_r13_r12_r0_ROR_1"},
{{al, r7, r9, r3, ROR, 1},
false,
al,
"al r7 r9 r3 ROR 1",
"al_r7_r9_r3_ROR_1"},
{{al, r10, r2, r13, LSL, 17},
false,
al,
"al r10 r2 r13 LSL 17",
"al_r10_r2_r13_LSL_17"},
{{al, r10, r6, r6, LSL, 16},
false,
al,
"al r10 r6 r6 LSL 16",
"al_r10_r6_r6_LSL_16"},
{{al, r5, r8, r9, ROR, 25},
false,
al,
"al r5 r8 r9 ROR 25",
"al_r5_r8_r9_ROR_25"},
{{al, r14, r13, r2, LSL, 23},
false,
al,
"al r14 r13 r2 LSL 23",
"al_r14_r13_r2_LSL_23"},
{{al, r5, r13, r6, ROR, 13},
false,
al,
"al r5 r13 r6 ROR 13",
"al_r5_r13_r6_ROR_13"},
{{al, r6, r14, r5, LSL, 3},
false,
al,
"al r6 r14 r5 LSL 3",
"al_r6_r14_r5_LSL_3"},
{{al, r11, r8, r14, ROR, 2},
false,
al,
"al r11 r8 r14 ROR 2",
"al_r11_r8_r14_ROR_2"},
{{al, r3, r11, r13, ROR, 25},
false,
al,
"al r3 r11 r13 ROR 25",
"al_r3_r11_r13_ROR_25"},
{{al, r2, r1, r6, LSL, 3},
false,
al,
"al r2 r1 r6 LSL 3",
"al_r2_r1_r6_LSL_3"},
{{al, r1, r7, r3, ROR, 30},
false,
al,
"al r1 r7 r3 ROR 30",
"al_r1_r7_r3_ROR_30"}};
// These headers each contain an array of `TestResult` with the reference output
// values. The reference arrays are names `kReference{mnemonic}`.
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-adc-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-adcs-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-add-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-adds-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-and-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-ands-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-bic-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-bics-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-eor-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-eors-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-orn-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-orns-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-orr-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-orrs-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-rsb-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-rsbs-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-sbc-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-sbcs-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-sub-t32.h"
#include "aarch32/traces/assembler-cond-rd-rn-operand-rm-shift-amount-1to31-subs-t32.h"
// The maximum number of errors to report in detail for each test.
const unsigned kErrorReportLimit = 8;
typedef void (MacroAssembler::*Fn)(Condition cond,
Register rd,
Register rn,
const Operand& op);
void TestHelper(Fn instruction,
const char* mnemonic,
const TestResult reference[]) {
unsigned total_error_count = 0;
MacroAssembler masm(BUF_SIZE);
masm.UseT32();
for (unsigned i = 0; i < ARRAY_SIZE(kTests); i++) {
// Values to pass to the macro-assembler.
Condition cond = kTests[i].operands.cond;
Register rd = kTests[i].operands.rd;
Register rn = kTests[i].operands.rn;
Register rm = kTests[i].operands.rm;
ShiftType shift = kTests[i].operands.shift;
uint32_t amount = kTests[i].operands.amount;
Operand op(rm, shift, amount);
int32_t start = masm.GetCursorOffset();
{
// We never generate more that 4 bytes, as IT instructions are only
// allowed for narrow encodings.
ExactAssemblyScope scope(&masm, 4, ExactAssemblyScope::kMaximumSize);
if (kTests[i].in_it_block) {
masm.it(kTests[i].it_condition);
}
(masm.*instruction)(cond, rd, rn, op);
}
int32_t end = masm.GetCursorOffset();
const byte* result_ptr =
masm.GetBuffer()->GetOffsetAddress<const byte*>(start);
VIXL_ASSERT(start < end);
uint32_t result_size = end - start;
if (Test::generate_test_trace()) {
// Print the result bytes.
printf("const byte kInstruction_%s_%s[] = {\n",
mnemonic,
kTests[i].identifier);
for (uint32_t j = 0; j < result_size; j++) {
if (j == 0) {
printf(" 0x%02" PRIx8, result_ptr[j]);
} else {
printf(", 0x%02" PRIx8, result_ptr[j]);
}
}
// This comment is meant to be used by external tools to validate
// the encoding. We can parse the comment to figure out what
// instruction this corresponds to.
if (kTests[i].in_it_block) {
printf(" // It %s; %s %s\n};\n",
kTests[i].it_condition.GetName(),
mnemonic,
kTests[i].operands_description);
} else {
printf(" // %s %s\n};\n", mnemonic, kTests[i].operands_description);
}
} else {
// Check we've emitted the exact same encoding as present in the
// trace file. Only print up to `kErrorReportLimit` errors.
if (((result_size != reference[i].size) ||
(memcmp(result_ptr, reference[i].encoding, reference[i].size) !=
0)) &&
(++total_error_count <= kErrorReportLimit)) {
printf("Error when testing \"%s\" with operands \"%s\":\n",
mnemonic,
kTests[i].operands_description);
printf(" Expected: ");
for (uint32_t j = 0; j < reference[i].size; j++) {
if (j == 0) {
printf("0x%02" PRIx8, reference[i].encoding[j]);
} else {
printf(", 0x%02" PRIx8, reference[i].encoding[j]);
}
}
printf("\n");
printf(" Found: ");
for (uint32_t j = 0; j < result_size; j++) {
if (j == 0) {
printf("0x%02" PRIx8, result_ptr[j]);
} else {
printf(", 0x%02" PRIx8, result_ptr[j]);
}
}
printf("\n");
}
}
}
masm.FinalizeCode();
if (Test::generate_test_trace()) {
// Finalize the trace file by writing the final `TestResult` array
// which links all generated instruction encodings.
printf("const TestResult kReference%s[] = {\n", mnemonic);
for (unsigned i = 0; i < ARRAY_SIZE(kTests); i++) {
printf(" {\n");
printf(" ARRAY_SIZE(kInstruction_%s_%s),\n",
mnemonic,
kTests[i].identifier);
printf(" kInstruction_%s_%s,\n", mnemonic, kTests[i].identifier);
printf(" },\n");
}
printf("};\n");
} else {
if (total_error_count > kErrorReportLimit) {
printf("%u other errors follow.\n",
total_error_count - kErrorReportLimit);
}
// Crash if the test failed.
VIXL_CHECK(total_error_count == 0);
}
}
// Instantiate tests for each instruction in the list.
#define TEST(mnemonic) \
void Test_##mnemonic() { \
TestHelper(&MacroAssembler::mnemonic, #mnemonic, kReference##mnemonic); \
} \
Test test_##mnemonic( \
"AARCH32_ASSEMBLER_COND_RD_RN_OPERAND_RM_SHIFT_AMOUNT_1TO31_" #mnemonic \
"_T32", \
&Test_##mnemonic);
FOREACH_INSTRUCTION(TEST)
#undef TEST
} // namespace
#endif
} // namespace aarch32
} // namespace vixl
| MerryMage/dynarmic | externals/vixl/vixl/test/aarch32/test-assembler-cond-rd-rn-operand-rm-shift-amount-1to31-t32.cc | C++ | gpl-2.0 | 123,757 |
/* * Copyright (c) 2012 The Linux Foundation. All rights reserved.* */
#ifndef _NSS_REG_H_
#define _NSS_REG_H_
#define IPQ806X_NSS_TCM_PHYS (0x39000000)
#define MSM_NSS_TCM_BASE (0xFB700000) /* 128K */
#define MSM_NSS_FPB_BASE (0xFB720000) /* 4K */
#define MSM_UBI32_0_CSM_BASE (0xFB721000) /* 4K */
#define MSM_UBI32_1_CSM_BASE (0xFB722000) /* 4K */
#define NSS_RESET_ADDR (0x40000000)
#define NSS_REGS_CORE_ID_OFFSET 0x0000
#define NSS_REGS_RESET_CTRL_OFFSET 0x0004
#define NSS_REGS_CORE_BAR_OFFSET 0x0008
#define NSS_REGS_CORE_AMC_OFFSET 0x000c
#define NSS_REGS_CORE_BOOT_ADDR_OFFSET 0x0010
#define NSS_REGS_C2C_INTR_STATUS_OFFSET 0x0014
#define NSS_REGS_C2C_INTR_SET_OFFSET 0x0018
#define NSS_REGS_C2C_INTR_CLR_OFFSET 0x001c
#define NSS_REGS_N2H_INTR_STATUS_OFFSET 0x0020
#define NSS_REGS_N2H_INTR_SET_OFFSET 0x0024
#define NSS_REGS_N2H_INTR_CLR_OFFSET 0x0028
#define NSS_REGS_N2H_INTR_MASK_OFFSET 0x002c
#define NSS_REGS_N2H_INTR_MASK_SET_OFFSET 0x0030
#define NSS_REGS_N2H_INTR_MASK_CLR_OFFSET 0x0034
#define NSS_REGS_CORE_INT_STAT0_TYPE_OFFSET 0x0038
#define NSS_REGS_CORE_INT_STAT1_TYPE_OFFSET 0x003c
#define NSS_REGS_CORE_INT_STAT2_TYPE_OFFSET 0x0040
#define NSS_REGS_CORE_INT_STAT3_TYPE_OFFSET 0x0044
#define NSS_REGS_CORE_IFETCH_RANGE_OFFSET 0x0048
/*
* Defines for N2H interrupts
*/
#define NSS_REGS_N2H_INTR_STATUS_EMPTY_BUFFER_QUEUE 0x0001
#define NSS_REGS_N2H_INTR_STATUS_DATA_COMMAND_QUEUE 0x0002
#define NSS_REGS_N2H_INTR_STATUS_EMPTY_BUFFERS_SOS 0x0400
#define NSS_REGS_N2H_INTR_STATUS_TX_UNBLOCKED 0x0800
/*
* Defines for H2N interrupts
*/
#define NSS_REGS_H2N_INTR_STATUS_EMPTY_BUFFER_QUEUE 0x0001
#define NSS_REGS_H2N_INTR_STATUS_DATA_COMMAND_QUEUE 0x0002
#define NSS_REGS_H2N_INTR_STATUS_RESET 0x0400 /** Unused */
#define NSS_REGS_H2N_INTR_STATUS_TX_UNBLOCKED 0x0800
#endif /* _NSS_REG_H_ */
| itgb/opCloudRouter | qca/src/u-boot/arch/arm/include/asm/arch-ipq806x/nss/nss_reg.h | C | gpl-2.0 | 1,887 |
<?php
/**
* @package Joomla.Site
* @subpackage com_weblinks
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
// Code to support edit links for weblinks
// Create a shortcut for params.
$params = &$this->item->params;
JHtml::addIncludePath(JPATH_COMPONENT.'/helpers/html');
JHtml::_('behavior.tooltip');
JHtml::_('behavior.framework');
// Get the user object.
$user = JFactory::getUser();
// Check if user is allowed to add/edit based on weblinks permissinos.
$canEdit = $user->authorise('core.edit', 'com_weblinks');
$canCreate = $user->authorise('core.create', 'com_weblinks');
$canEditState = $user->authorise('core.edit.state', 'com_weblinks');
$n = count($this->items);
$listOrder = $this->escape($this->state->get('list.ordering'));
$listDirn = $this->escape($this->state->get('list.direction'));
?>
<?php if (empty($this->items)) : ?>
<p> <?php echo JText::_('COM_WEBLINKS_NO_WEBLINKS'); ?></p>
<?php else : ?>
<form action="<?php echo htmlspecialchars(JUri::getInstance()->toString()); ?>" method="post" name="adminForm" id="adminForm">
<?php if ($this->params->get('filter_field') != 'hide' || $this->params->get('show_pagination_limit')) :?>
<fieldset class="filters btn-toolbar">
<?php if ($this->params->get('filter_field') != 'hide') :?>
<div class="btn-group">
<label class="filter-search-lbl element-invisible" for="filter-search"><span class="label label-warning"><?php echo JText::_('JUNPUBLISHED'); ?></span><?php echo JText::_('JGLOBAL_FILTER_LABEL').' '; ?></label>
<input type="text" name="filter-search" id="filter-search" value="<?php echo $this->escape($this->state->get('list.filter')); ?>" class="input" onchange="document.adminForm.submit();"<?php if(version_compare(JVERSION, '3.0', 'ge')) : ?> title="<?php echo JText::_('COM_WEBLINKS_FILTER_SEARCH_DESC'); ?>" placeholder="<?php echo JText::_('COM_WEBLINKS_FILTER_SEARCH_DESC'); ?>"<?php endif; ?> />
</div>
<?php endif; ?>
<?php if ($this->params->get('show_pagination_limit')) : ?>
<div class="btn-group pull-right">
<label for="limit" class="element-invisible">
<?php echo JText::_('JGLOBAL_DISPLAY_NUM'); ?>
</label>
<?php echo $this->pagination->getLimitBox(); ?>
</div>
<?php endif; ?>
</fieldset>
<?php endif; ?>
<ul class="category list-striped list-condensed">
<?php foreach ($this->items as $i => $item) : ?>
<?php if (in_array($item->access, $user->getAuthorisedViewLevels())) : ?>
<?php if ($this->items[$i]->state == 0) : ?>
<li class="system-unpublished cat-list-row<?php echo $i % 2; ?>">
<?php else: ?>
<li class="cat-list-row<?php echo $i % 2; ?>" >
<?php endif; ?>
<?php if ($this->params->get('show_link_hits', 1)) : ?>
<span class="list-hits badge badge-info pull-right">
<?php echo JText::_('JGLOBAL_HITS'), ': ', $item->hits; ?>
</span>
<?php endif; ?>
<?php if ($canEdit) : ?>
<span class="list-edit pull-left width-50">
<?php echo JHtml::_('icon.edit', $item, $params); ?>
</span>
<?php endif; ?>
<strong class="list-title">
<?php if ($this->params->get('icons') == 0) : ?>
<?php echo JText::_('COM_WEBLINKS_LINK'); ?>
<?php elseif ($this->params->get('icons') == 1) : ?>
<?php if (!$this->params->get('link_icons')) : ?>
<?php echo JHtml::_('image', 'system/'.$this->params->get('link_icons', 'weblink.png'), JText::_('COM_WEBLINKS_LINK'), null, true); ?>
<?php else: ?>
<?php echo '<img src="'.$this->params->get('link_icons').'" alt="'.JText::_('COM_WEBLINKS_LINK').'" />'; ?>
<?php endif; ?>
<?php endif; ?>
<?php
// Compute the correct link
$menuclass = 'category'.$this->pageclass_sfx;
$link = $item->link;
$width = $item->params->get('width');
$height = $item->params->get('height');
if ($width == null || $height == null)
{
$width = 600;
$height = 500;
}
if ($this->items[$i]->state == 0) : ?>
<span class="label label-warning">Unpublished</span>
<?php endif; ?>
<?php switch ($item->params->get('target', $this->params->get('target')))
{
case 1:
// open in a new window
echo '<a href="'. $link .'" target="_blank" class="'. $menuclass .'" rel="nofollow">'.
$this->escape($item->title) .'</a>';
break;
case 2:
// open in a popup window
$attribs = 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width='.$this->escape($width).',height='.$this->escape($height).'';
echo "<a href=\"$link\" onclick=\"window.open(this.href, 'targetWindow', '".$attribs."'); return false;\">".
$this->escape($item->title).'</a>';
break;
case 3:
// open in a modal window
JHtml::_('behavior.modal', 'a.modal'); ?>
<a class="modal" href="<?php echo $link;?>" rel="{handler: 'iframe', size: {x:<?php echo $this->escape($width);?>, y:<?php echo $this->escape($height);?>}}">
<?php echo $this->escape($item->title). ' </a>';
break;
default:
// open in parent window
echo '<a href="'. $link . '" class="'. $menuclass .'" rel="nofollow">'.
$this->escape($item->title) . ' </a>';
break;
}
?>
</strong>
<?php if ($this->params->get('show_tags', 1) && !empty($item->tags)) : ?>
<?php $tagsData = $item->tags->getItemTags('com_weblinks.weblink', $item->id); ?>
<?php $this->item->tagLayout = new JLayoutFile('joomla.content.tags'); ?>
<?php echo $this->item->tagLayout->render($tagsData); ?>
<?php endif; ?>
<?php if (($this->params->get('show_link_description')) and ($item->description != '')) : ?>
<?php echo $item->description; ?>
<?php endif; ?>
</li>
<?php endif;?>
<?php endforeach; ?>
</ul>
<?php // Code to add a link to submit a weblink. ?>
<?php /* if ($canCreate) : // TODO This is not working due to some problem in the router, I think. Ref issue #23685 ?>
<?php echo JHtml::_('icon.create', $item, $item->params); ?>
<?php endif; */ ?>
<?php if ($this->params->get('show_pagination')) : ?>
<div class="pagination">
<?php if ($this->params->def('show_pagination_results', 1)) : ?>
<p class="counter">
<?php echo $this->pagination->getPagesCounter(); ?>
</p>
<?php endif; ?>
<?php echo $this->pagination->getPagesLinks(); ?>
</div>
<?php endif; ?>
</form>
<?php endif; ?>
| majordome/t3 | source/plg_system_t3/base/html/com_weblinks/category/default_items.php | PHP | gpl-2.0 | 6,725 |
<?php
/**
* Java Form
*
* @package Upload
* @subpackage UploadPhotoGallery
* @copyright 2014 Haudenschilt LLC
* @author Ryan Haudenschilt <r.haudenschilt@gmail.com>
* @license http://www.gnu.org/licenses/gpl-2.0.html
*/
class JavaUploadPhotoGalleryForm extends UploadPhotoGalleryForm
{
/**
* __construct
*
* @param FCMS_Error $fcmsError
* @param Database $fcmsDatabase
* @param User $fcmsUser
*
* @return void
*/
public function __construct (FCMS_Error $fcmsError, Database $fcmsDatabase, User $fcmsUser)
{
$this->fcmsError = $fcmsError;
$this->fcmsDatabase = $fcmsDatabase;
$this->fcmsUser = $fcmsUser;
}
/**
* display
*
* @return boolean
*/
public function display ()
{
$_SESSION['fcms_uploader_type'] = 'java';
// Setup some applet params
$scaledInstanceNames = '<param name="uc_scaledInstanceNames" value="thumb,main"/>';
$scaledInstanceDimensions = '<param name="uc_scaledInstanceDimensions" value="150x150xcrop,600x600xfit"/>';
$fullSizedPhotos = '';
if (usingFullSizePhotos())
{
$scaledInstanceNames = '<param name="uc_scaledInstanceNames" value="thumb,main,full"/>';
$scaledInstanceDimensions = '<param name="uc_scaledInstanceDimensions" value="150x150xcrop,600x600xfit,1400x1400xfit"/>';
$fullSizedPhotos = '
function sendFullSizedPhotos() {
var uploader = document.jumpLoaderApplet.getUploader();
var attrSet = uploader.getAttributeSet();
var attr = attrSet.createStringAttribute("full-sized-photos", "1");
attr.setSendToServer(true);
}
sendFullSizedPhotos();';
}
echo '
<noscript>
<style type="text/css">
applet, .photo-uploader {display: none;}
#noscript {padding:1em;}
#noscript p {background-color:#ff9; padding:3em; font-size:130%; line-height:200%;}
#noscript p span {font-size:60%;}
</style>
<div id="noscript">
<p>
'.T_('JavaScript must be enabled in order for you to use the Advanced Uploader. However, it seems JavaScript is either disabled or not supported by your browser.').'<br/>
<span>
'.T_('Either enable JavaScript by changing your browser options.').'<br/>
'.T_('or').'<br/>
'.T_('Enable the Basic Upload option by changing Your Settings.').'
</span>
</p>
</div>
</noscript>
<div id="loading">'.T_('Loading Advanced Uploader...').'</div>
<form method="post" id="uploadForm" name="uploadForm" class="photo-uploader" style="visibility:hidden">
<div class="header">
<label>'.T_('Category').'</label>
'.$this->getCategoryInputs().'
</div>
<ul class="upload-types">
'.$this->getUploadTypesNavigation('upload').'
</ul>
<div class="upload-area">
<applet id="jumpLoaderApplet" name="jumpLoaderApplet"
code="jmaster.jumploader.app.JumpLoaderApplet.class"
archive="../inc/thirdparty/jumploader_z.jar"
width="758"
height="300"
mayscript>
<param name="uc_sendImageMetadata" value="true"/>
<param name="uc_uploadUrl" value="index.php"/>
<param name="vc_useThumbs" value="true"/>
<param name="uc_uploadScaledImagesNoZip" value="true"/>
<param name="uc_uploadScaledImages" value="true"/>
'.$scaledInstanceNames.'
'.$scaledInstanceDimensions.'
<param name="uc_scaledInstanceQualityFactors" value="900"/>
<param name="uc_uploadFormName" value="uploadForm"/>
<param name="vc_lookAndFeel" value="system"/>
<param name="vc_uploadViewStartActionVisible" value="false"/>
<param name="vc_uploadViewStopActionVisible" value="false"/>
<param name="vc_uploadViewPasteActionVisible" value="false"/>
<param name="vc_uploadViewRetryActionVisible" value="false"/>
<param name="vc_uploadViewFilesSummaryBarVisible" value="false"/>
<param name="vc_uiDefaults" value="Panel.background=#eff0f4; List.background=#eff0f4;"/>
<param name="ac_fireAppletInitialized" value="true"/>
<param name="ac_fireUploaderStatusChanged" value="true"/>
<param name="ac_fireUploaderFileStatusChanged" value="true"/>
</applet>
</div>
<div class="footer">
<input class="sub1" type="button" value="'.T_('Upload').'" id="start-upload" name="start-upload"/>
</div>
</form>
<script type="text/javascript">
document.onkeydown = keyHandler;
function keyHandler(e)
{
if (!e) { e = window.event; }
if (e.keyCode == 27) {
$("#uploadForm").css("visibility", "visible");
$("#loading").hide();
}
}
$("#start-upload").click(function(e) {
'.$this->getJsUploadValidation().'
var uploader = document.jumpLoaderApplet.getUploader();
var attrSet = uploader.getAttributeSet();
var newValue = $("#new-category").val();
var newAttr = attrSet.createStringAttribute("new-category", newValue);
newAttr.setSendToServer(true);
var attribute = attrSet.createStringAttribute("javaUpload", 1);
attribute.setSendToServer(true);
if ($("#existing-categories")) {
var value = $("#existing-categories").val();
var attr = attrSet.createStringAttribute("category", value);
attr.setSendToServer(true);
}
uploader.startUpload();
});'.$fullSizedPhotos.'
function uploaderStatusChanged(uploader) {
if (uploader.getStatus() == 0) {
window.location.href = "index.php?action=advanced";
}
}
function appletInitialized(applet) {
$("#uploadForm").css("visibility", "visible");
$("#loading").hide();
}
</script>';
}
}
| ryanhowdy/fcms | familyconnections/inc/Upload/PhotoGallery/Form/Java.php | PHP | gpl-2.0 | 7,101 |
function act() {
rm.killMonster(6090001);
} | icelemon1314/mapleLemon | scripts/reactors/2119006.js | JavaScript | gpl-2.0 | 49 |
--龍骨鬼
function c57281778.initial_effect(c)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(57281778,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_DAMAGE_STEP_END)
e1:SetCondition(c57281778.descon)
e1:SetTarget(c57281778.destg)
e1:SetOperation(c57281778.desop)
c:RegisterEffect(e1)
end
function c57281778.descon(e,tp,eg,ep,ev,re,r,rp)
local t=Duel.GetAttackTarget()
if ev==1 then t=Duel.GetAttacker() end
e:SetLabelObject(t)
return t and t:IsRace(RACE_SPELLCASTER+RACE_WARRIOR) and t:IsRelateToBattle()
end
function c57281778.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetLabelObject():IsDestructable() end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,e:GetLabelObject(),1,0,0)
end
function c57281778.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
if tc:IsRelateToBattle() then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| Lsty/ygopro-scripts | c57281778.lua | Lua | gpl-2.0 | 949 |
<?php
$strings = "tinyMCE.addI18n({
en:{
theme_shortcode: {
desc : 'Add a theme specific shortcode'
},
theme_contact:{
desc : 'Add a contact form'
}
}
});
";
?> | andremalan/edgen | wp-content/themes/parallelus-salutation/framework/theme-functions/editor-button/langs.php | PHP | gpl-2.0 | 176 |
/* Copyright (c) 2009-2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/leds-pmic8058.h>
#include <linux/pwm.h>
#include <linux/pmic8058-pwm.h>
#include <linux/hrtimer.h>
#include <linux/i2c.h>
#include <mach/pmic.h>
#include <mach/camera.h>
#include <mach/gpio.h>
struct i2c_client *sx150x_client;
struct timer_list timer_flash;
static struct msm_camera_sensor_info *sensor_data;
#if (defined(CONFIG_HW_ANDORRA) || defined(CONFIG_HW_ARMANI)|| defined(CONFIG_HW_AUDI))
static uint32_t FLASH_HW_EN = 49;
static uint32_t FLAHS_TORCH_EN = 23;
static uint32_t FLAHS_FLASH_EN = 32;
//static bool GPIO_CONFIG=0;
#endif
enum msm_cam_flash_stat{
MSM_CAM_FLASH_OFF,
MSM_CAM_FLASH_ON,
};
static struct i2c_client *sc628a_client;
static int32_t flash_i2c_txdata(struct i2c_client *client,
unsigned char *txdata, int length)
{
struct i2c_msg msg[] = {
{
.addr = client->addr,
.flags = 0,
.len = length,
.buf = txdata,
},
};
if (i2c_transfer(client->adapter, msg, 1) < 0) {
CDBG("flash_i2c_txdata faild 0x%x\n", client->addr >> 1);
return -EIO;
}
return 0;
}
static int32_t flash_i2c_write_b(struct i2c_client *client,
uint8_t baddr, uint8_t bdata)
{
int32_t rc = -EFAULT;
unsigned char buf[2];
if (!client)
return -ENOTSUPP;
memset(buf, 0, sizeof(buf));
buf[0] = baddr;
buf[1] = bdata;
rc = flash_i2c_txdata(client, buf, 2);
if (rc < 0) {
CDBG("i2c_write_b failed, addr = 0x%x, val = 0x%x!\n",
baddr, bdata);
}
usleep_range(4000, 5000);
return rc;
}
static const struct i2c_device_id sc628a_i2c_id[] = {
{"sc628a", 0},
{ }
};
static int sc628a_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int rc = 0;
CDBG("sc628a_probe called!\n");
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
pr_err("i2c_check_functionality failed\n");
goto probe_failure;
}
sc628a_client = client;
CDBG("sc628a_probe success rc = %d\n", rc);
return 0;
probe_failure:
pr_err("sc628a_probe failed! rc = %d\n", rc);
return rc;
}
static struct i2c_driver sc628a_i2c_driver = {
.id_table = sc628a_i2c_id,
.probe = sc628a_i2c_probe,
.remove = __exit_p(sc628a_i2c_remove),
.driver = {
.name = "sc628a",
},
};
static struct i2c_client *tps61310_client;
static const struct i2c_device_id tps61310_i2c_id[] = {
{"tps61310", 0},
{ }
};
static int tps61310_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int rc = 0;
CDBG("%s enter\n", __func__);
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
pr_err("i2c_check_functionality failed\n");
goto probe_failure;
}
tps61310_client = client;
rc = flash_i2c_write_b(tps61310_client, 0x01, 0x00);
if (rc < 0) {
tps61310_client = NULL;
goto probe_failure;
}
CDBG("%s success! rc = %d\n", __func__, rc);
return 0;
probe_failure:
pr_err("%s failed! rc = %d\n", __func__, rc);
return rc;
}
static struct i2c_driver tps61310_i2c_driver = {
.id_table = tps61310_i2c_id,
.probe = tps61310_i2c_probe,
.remove = __exit_p(tps61310_i2c_remove),
.driver = {
.name = "tps61310",
},
};
static struct i2c_client *lm3554_client;
static const struct i2c_device_id lm3554_i2c_id[] = {
{"lm3554", 0},
{ }
};
static int lm3554_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int rc = 0;
printk("%s enter\n", __func__);
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
printk("i2c_check_functionality failed\n");
goto probe_failure;
}
lm3554_client = client;
return 0;
probe_failure:
printk("%s failed! rc = %d\n", __func__, rc);
return rc;
}
static struct i2c_driver lm3554_i2c_driver = {
.id_table = lm3554_i2c_id,
.probe = lm3554_i2c_probe,
.remove = __exit_p(lm3554_i2c_remove),
.driver = {
.name = "lm3554",
},
};
static int config_flash_gpio_table(enum msm_cam_flash_stat stat,
struct msm_camera_sensor_strobe_flash_data *sfdata)
{
int rc = 0, i = 0;
int msm_cam_flash_gpio_tbl[][2] = {
{sfdata->flash_trigger, 1},
{sfdata->flash_charge, 1},
{sfdata->flash_charge_done, 0}
};
if (stat == MSM_CAM_FLASH_ON) {
for (i = 0; i < ARRAY_SIZE(msm_cam_flash_gpio_tbl); i++) {
rc = gpio_request(msm_cam_flash_gpio_tbl[i][0],
"CAM_FLASH_GPIO");
if (unlikely(rc < 0)) {
pr_err("%s not able to get gpio\n", __func__);
for (i--; i >= 0; i--)
gpio_free(msm_cam_flash_gpio_tbl[i][0]);
break;
}
if (msm_cam_flash_gpio_tbl[i][1])
gpio_direction_output(
msm_cam_flash_gpio_tbl[i][0], 0);
else
gpio_direction_input(
msm_cam_flash_gpio_tbl[i][0]);
}
} else {
for (i = 0; i < ARRAY_SIZE(msm_cam_flash_gpio_tbl); i++) {
gpio_direction_input(msm_cam_flash_gpio_tbl[i][0]);
gpio_free(msm_cam_flash_gpio_tbl[i][0]);
}
}
return rc;
}
int msm_camera_flash_current_driver(
struct msm_camera_sensor_flash_current_driver *current_driver,
unsigned led_state)
{
int rc = 0;
#if defined CONFIG_LEDS_PMIC8058
int idx;
const struct pmic8058_leds_platform_data *driver_channel =
current_driver->driver_channel;
int num_leds = driver_channel->num_leds;
CDBG("%s: led_state = %d\n", __func__, led_state);
/* Evenly distribute current across all channels */
switch (led_state) {
case MSM_CAMERA_LED_OFF:
for (idx = 0; idx < num_leds; ++idx) {
rc = pm8058_set_led_current(
driver_channel->leds[idx].id, 0);
if (rc < 0)
pr_err(
"%s: FAIL name = %s, rc = %d\n",
__func__,
driver_channel->leds[idx].name,
rc);
}
break;
case MSM_CAMERA_LED_LOW:
for (idx = 0; idx < num_leds; ++idx) {
rc = pm8058_set_led_current(
driver_channel->leds[idx].id,
current_driver->low_current/num_leds);
if (rc < 0)
pr_err(
"%s: FAIL name = %s, rc = %d\n",
__func__,
driver_channel->leds[idx].name,
rc);
}
break;
case MSM_CAMERA_LED_HIGH:
for (idx = 0; idx < num_leds; ++idx) {
rc = pm8058_set_led_current(
driver_channel->leds[idx].id,
current_driver->high_current/num_leds);
if (rc < 0)
pr_err(
"%s: FAIL name = %s, rc = %d\n",
__func__,
driver_channel->leds[idx].name,
rc);
}
break;
case MSM_CAMERA_LED_INIT:
case MSM_CAMERA_LED_RELEASE:
break;
default:
rc = -EFAULT;
break;
}
CDBG("msm_camera_flash_led_pmic8058: return %d \n", rc);
#endif /* CONFIG_LEDS_PMIC8058 */
return rc;
}
#if (defined(CONFIG_HW_ANDORRA) || defined(CONFIG_HW_ARMANI) || defined(CONFIG_HW_AUDI))
static void config_flash_gpio_func(struct msm_camera_sensor_flash_external *external)
{
int rc = 0;
uint32_t led_hw_en = 0;
uint32_t led_torch_en = 0;
uint32_t led_flash_en = 0;
if(external)
{
led_hw_en = external->led_en;
led_torch_en = external->led_torch_en;
led_flash_en = external->led_flash_en;
}
else
{
led_hw_en = FLASH_HW_EN;
led_torch_en = FLAHS_TORCH_EN;
led_flash_en = FLAHS_FLASH_EN;
}
//config the led_hw_en
rc = gpio_request(led_hw_en, "sgm3141");
pr_err("MSM_CAMERA_LED_INIT: gpio_req: %d %d\n",led_hw_en, rc);
if (!rc)
{
//gpio_direction_output(external->led_en, 0);
pr_err("MSM_CAMERA_LED_INIT: gpio_req: %d success! \n",led_hw_en);
}
else
{
pr_err("MSM_CAMERA_LED_INIT: gpio_req: %d failed! \n",led_hw_en);
//return -EFAULT;
}
rc = gpio_tlmm_config(GPIO_CFG(led_hw_en,
0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP,
GPIO_CFG_2MA), GPIO_CFG_ENABLE);
if (!rc)
{
pr_err("%s: gpio_config led_en=%d success!\n",__func__,led_hw_en);
}
else
{
pr_err("%s:unable to config led_en=%d failed!\n",__func__,led_hw_en);
//return -EFAULT;
}
//config the led_torch_en
rc = gpio_request(led_torch_en, "sgm3141");
pr_err("MSM_CAMERA_LED_INIT: gpio_req: %d %d\n",led_torch_en, rc);
if (!rc)
{
//gpio_direction_output(external->led_en, 0);
pr_err("MSM_CAMERA_LED_INIT: gpio_req: %d success! \n",led_torch_en);
}
else
{
pr_err("MSM_CAMERA_LED_INIT: gpio_req: %d failed! \n",led_torch_en);
//return -EFAULT;
}
rc = gpio_tlmm_config(GPIO_CFG(led_torch_en,
0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP,
GPIO_CFG_2MA), GPIO_CFG_ENABLE);
if (!rc)
{
pr_err("%s: gpio_config led_en=%d success!\n",__func__,led_torch_en);
}
else
{
pr_err("%s:unable to config led_en=%d failed!\n",__func__,led_torch_en);
//return -EFAULT;
}
//config led_flash_en
rc = gpio_request(led_flash_en, "sgm3141");
pr_err("MSM_CAMERA_LED_INIT: gpio_req: %d %d\n",led_flash_en, rc);
if (!rc)
{
//gpio_direction_output(external->led_en, 0);
pr_err("MSM_CAMERA_LED_INIT: gpio_req: %d success! \n",led_flash_en);
}
else
{
pr_err("MSM_CAMERA_LED_INIT: gpio_req: %d failed! \n",led_flash_en);
//return -EFAULT;
}
rc = gpio_tlmm_config(GPIO_CFG(led_flash_en,
0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP,
GPIO_CFG_2MA), GPIO_CFG_ENABLE);
if (!rc)
{
pr_err("%s: gpio_config led_en=%d success!\n",__func__,led_flash_en);
}
else
{
pr_err("%s:unable to config led_en=%d failed!\n",__func__,led_flash_en);
//return -EFAULT;
}
}
#endif
int msm_camera_flash_led(
struct msm_camera_sensor_flash_external *external,
unsigned led_state)
{
int rc = 0;
pr_err("msm_camera_flash_led: %d\n", led_state);
switch (led_state) {
case MSM_CAMERA_LED_INIT:
//config HWEN
#if (defined(CONFIG_HW_ANDORRA) || defined(CONFIG_HW_ARMANI) || defined(CONFIG_HW_AUDI))
config_flash_gpio_func(external);
#endif
if (external->flash_id == MAM_CAMERA_EXT_LED_FLASH_LM3554)
{
if (!lm3554_client)
{
rc = i2c_add_driver(&lm3554_i2c_driver);
if (rc < 0 || lm3554_client == NULL)
{
pr_err("lm3554_i2c_driver add failed rc= 0x%x lm3554_client = 0x%x\n",rc,(unsigned int)lm3554_client);
rc = -ENOTSUPP;
return rc;
}
}
}
else
{
pr_err("Flash id not supported\n");
rc = -ENOTSUPP;
}
break;
case MSM_CAMERA_LED_RELEASE:
pr_err("MSM_CAMERA_LED_RELEASE\n");
#if (defined(CONFIG_HW_ANDORRA) || defined(CONFIG_HW_ARMANI) || defined(CONFIG_HW_AUDI))
gpio_direction_output(external->led_en, 0);
gpio_free(external->led_en);
gpio_direction_output(external->led_torch_en, 0);
gpio_free(external->led_torch_en);
gpio_direction_output(external->led_flash_en, 0);
gpio_free(external->led_flash_en);
#endif
if (lm3554_client)
{
i2c_del_driver(&lm3554_i2c_driver);
lm3554_client = NULL;
}
break;
case MSM_CAMERA_LED_OFF:
pr_err("MSM_CAMERA_LED_OFF \n");
#if (defined(CONFIG_HW_ANDORRA) || defined(CONFIG_HW_ARMANI) || defined(CONFIG_HW_AUDI))
gpio_direction_output(external->led_en, 0);
gpio_direction_output(external->led_torch_en, 0);
gpio_direction_output(external->led_flash_en, 0);
#endif
break;
case MSM_CAMERA_LED_LOW:
pr_err("MSM_CAMERA_LED_LOW\n");
#if (defined(CONFIG_HW_ARMANI) || defined(CONFIG_HW_AUDI))
gpio_direction_output(external->led_en, 1);
if(lm3554_client)
{
rc = flash_i2c_write_b(lm3554_client, 0xA0, 0x7A);
}
gpio_direction_output(external->led_torch_en, 1);
#endif
#if defined(CONFIG_HW_ANDORRA)
gpio_direction_output(external->led_en, 1);
if(lm3554_client)
{
// rc = flash_i2c_write_b(lm3554_client, 0xA0, 0x7A);
rc = flash_i2c_write_b(lm3554_client, 0xA0, 0x4E);
}
gpio_direction_output(external->led_torch_en, 1);
#endif
break;
case MSM_CAMERA_LED_HIGH:
pr_err("MSM_CAMERA_LED_HIGH\n");
#if (defined(CONFIG_HW_ANDORRA) || defined(CONFIG_HW_ARMANI) || defined(CONFIG_HW_AUDI))
gpio_direction_output(external->led_en, 1);
if(lm3554_client)
{
//rc = flash_i2c_write_b(lm3554_client, 0xB0, 0x4B);
rc = flash_i2c_write_b(lm3554_client, 0xB0, 0x7B);//max value
}
//gpio_direction_output(external->led_torch_en, 1);
gpio_direction_output(external->led_flash_en, 1);
#endif
break;
default:
rc = -EFAULT;
break;
}
return rc;
}
/*
{
case MSM_CAMERA_LED_INIT:
rc = gpio_request(external->led_en, "sgm3141");
pr_err("MSM_CAMERA_LED_INIT: gpio_req: %d %d\n",
external->led_en, rc);
rc = gpio_tlmm_config(GPIO_CFG(external->led_en, 0,
O_CFG(QRD_SKUA_GPIO_CAM_5MP_RESET, 0,
GPIO_CFG_2MA), GPIO_CFG_ENABLE);
if (!rc)
{
pr_err("%s: unable to enable reset gpio for main camera!\n",
__func__);
gpio_direction_output(external->led_en, 0);
gpio_free(external->led_en);
}
rc = gpio_request(external->led_flash_en, "sgm3141");
pr_err("MSM_CAMERA_LED_INIT: gpio_req: %d %d\n",
external->led_flash_en, rc);
rc = gpio_tlmm_config(GPIO_CFG(external->led_flash_en, 0,
O_CFG(QRD_SKUA_GPIO_CAM_5MP_RESET, 0,
GPIO_CFG_2MA), GPIO_CFG_ENABLE);
if (!rc)
{
pr_err("%s: unable to enable reset gpio for main camera!\n",
nable reset gpi
gpio_direction_output(external->led_flash_en, 0);
gpio_free(external->led_en);
}
pr_err("MSM_CAMERA_LED_INIT:ljk flash on\n");
gpio_direction_output(external->led_flash_en, 1);
break;
case MSM_CAMERA_LED_RELEASE:
pr_err("MSM_CAMERA_LED_RELEASE\n");
gpio_direction_output(external->led_en, 0);
gpio_free(external->led_en);
gpio_direction_output(external->led_flash_en, 0);
gpio_free(external->led_flash_en);
break;
case MSM_CAMERA_LED_OFF:
pr_err("MSM_CAMERA_LED_OFF\n");
gpio_direction_output(external->led_en, 0);
gpio_direction_output(external->led_flash_en, 0);
break;
case MSM_CAMERA_LED_LOW:
pr_err("MSM_CAMERA_LED_LOW\n");
gpio_direction_output(external->led_flash_en, 0);
gpio_direction_output(external->led_en, 1);
break;
case MSM_CAMERA_LED_HIGH:
pr_err("MSM_CAMERA_LED_HIGH\n");
gpio_direction_output(external->led_flash_en, 1);
gpio_direction_output(external->led_en, 1);
break;
default:
rc = -EFAULT;
break;
}
*/
int msm_camera_flash_external(
struct msm_camera_sensor_flash_external *external,
unsigned led_state)
{
int rc = 0;
pr_err("msm_camera_flash_external led_state=%d flash_id=%d\n",led_state,external->flash_id);
switch (led_state) {
case MSM_CAMERA_LED_INIT:
if (external->flash_id == MAM_CAMERA_EXT_LED_FLASH_SC628A) {
if (!sc628a_client) {
rc = i2c_add_driver(&sc628a_i2c_driver);
if (rc < 0 || sc628a_client == NULL) {
pr_err("sc628a_i2c_driver add failed\n");
rc = -ENOTSUPP;
return rc;
}
}
} else if (external->flash_id ==
MAM_CAMERA_EXT_LED_FLASH_TPS61310) {
if (!tps61310_client) {
rc = i2c_add_driver(&tps61310_i2c_driver);
if (rc < 0 || tps61310_client == NULL) {
pr_err("tps61310_i2c_driver add failed\n");
rc = -ENOTSUPP;
return rc;
}
}
} else {
pr_err("Flash id not supported\n");
rc = -ENOTSUPP;
return rc;
}
#if defined(CONFIG_GPIO_SX150X) || defined(CONFIG_GPIO_SX150X_MODULE)
if (external->expander_info && !sx150x_client) {
struct i2c_adapter *adapter =
i2c_get_adapter(external->expander_info->bus_id);
if (adapter)
sx150x_client = i2c_new_device(adapter,
external->expander_info->board_info);
if (!sx150x_client || !adapter) {
pr_err("sx150x_client is not available\n");
rc = -ENOTSUPP;
if (sc628a_client) {
i2c_del_driver(&sc628a_i2c_driver);
sc628a_client = NULL;
}
if (tps61310_client) {
i2c_del_driver(&tps61310_i2c_driver);
tps61310_client = NULL;
}
return rc;
}
i2c_put_adapter(adapter);
}
#endif
if (sc628a_client)
rc = gpio_request(external->led_en, "sc628a");
if (tps61310_client)
rc = gpio_request(external->led_en, "tps61310");
if (!rc) {
gpio_direction_output(external->led_en, 0);
} else {
goto error;
}
if (sc628a_client)
rc = gpio_request(external->led_flash_en, "sc628a");
if (tps61310_client)
rc = gpio_request(external->led_flash_en, "tps61310");
if (!rc) {
gpio_direction_output(external->led_flash_en, 0);
break;
}
gpio_set_value_cansleep(external->led_en, 0);
gpio_free(external->led_en);
error:
pr_err("%s gpio request failed\n", __func__);
if (sc628a_client) {
i2c_del_driver(&sc628a_i2c_driver);
sc628a_client = NULL;
}
if (tps61310_client) {
i2c_del_driver(&tps61310_i2c_driver);
tps61310_client = NULL;
}
break;
case MSM_CAMERA_LED_RELEASE:
if (sc628a_client || tps61310_client) {
gpio_set_value_cansleep(external->led_en, 0);
gpio_free(external->led_en);
gpio_set_value_cansleep(external->led_flash_en, 0);
gpio_free(external->led_flash_en);
if (sc628a_client) {
i2c_del_driver(&sc628a_i2c_driver);
sc628a_client = NULL;
}
if (tps61310_client) {
i2c_del_driver(&tps61310_i2c_driver);
tps61310_client = NULL;
}
}
#if defined(CONFIG_GPIO_SX150X) || defined(CONFIG_GPIO_SX150X_MODULE)
if (external->expander_info && sx150x_client) {
i2c_unregister_device(sx150x_client);
sx150x_client = NULL;
}
#endif
break;
case MSM_CAMERA_LED_OFF:
if (sc628a_client)
rc = flash_i2c_write_b(sc628a_client, 0x02, 0x00);
if (tps61310_client)
rc = flash_i2c_write_b(tps61310_client, 0x01, 0x00);
gpio_set_value_cansleep(external->led_en, 0);
gpio_set_value_cansleep(external->led_flash_en, 0);
break;
case MSM_CAMERA_LED_LOW:
gpio_set_value_cansleep(external->led_en, 1);
gpio_set_value_cansleep(external->led_flash_en, 1);
usleep_range(2000, 3000);
if (sc628a_client)
rc = flash_i2c_write_b(sc628a_client, 0x02, 0x06);
if (tps61310_client)
rc = flash_i2c_write_b(tps61310_client, 0x01, 0x86);
break;
case MSM_CAMERA_LED_HIGH:
gpio_set_value_cansleep(external->led_en, 1);
gpio_set_value_cansleep(external->led_flash_en, 1);
usleep_range(2000, 3000);
if (sc628a_client)
rc = flash_i2c_write_b(sc628a_client, 0x02, 0x49);
if (tps61310_client)
rc = flash_i2c_write_b(tps61310_client, 0x01, 0x8B);
break;
default:
rc = -EFAULT;
break;
}
return rc;
}
static int msm_camera_flash_pwm(
struct msm_camera_sensor_flash_pwm *pwm,
unsigned led_state)
{
int rc = 0;
int PWM_PERIOD = USEC_PER_SEC / pwm->freq;
static struct pwm_device *flash_pwm;
if (!flash_pwm) {
flash_pwm = pwm_request(pwm->channel, "camera-flash");
if (flash_pwm == NULL || IS_ERR(flash_pwm)) {
pr_err("%s: FAIL pwm_request(): flash_pwm=%p\n",
__func__, flash_pwm);
flash_pwm = NULL;
return -ENXIO;
}
}
switch (led_state) {
case MSM_CAMERA_LED_LOW:
rc = pwm_config(flash_pwm,
(PWM_PERIOD/pwm->max_load)*pwm->low_load,
PWM_PERIOD);
if (rc >= 0)
rc = pwm_enable(flash_pwm);
break;
case MSM_CAMERA_LED_HIGH:
rc = pwm_config(flash_pwm,
(PWM_PERIOD/pwm->max_load)*pwm->high_load,
PWM_PERIOD);
if (rc >= 0)
rc = pwm_enable(flash_pwm);
break;
case MSM_CAMERA_LED_OFF:
pwm_disable(flash_pwm);
break;
case MSM_CAMERA_LED_INIT:
case MSM_CAMERA_LED_RELEASE:
break;
default:
rc = -EFAULT;
break;
}
return rc;
}
int msm_camera_flash_pmic(
struct msm_camera_sensor_flash_pmic *pmic,
unsigned led_state)
{
int rc = 0;
switch (led_state) {
case MSM_CAMERA_LED_OFF:
rc = pmic->pmic_set_current(pmic->led_src_1, 0);
if (pmic->num_of_src > 1)
rc = pmic->pmic_set_current(pmic->led_src_2, 0);
break;
case MSM_CAMERA_LED_LOW:
rc = pmic->pmic_set_current(pmic->led_src_1,
pmic->low_current);
if (pmic->num_of_src > 1)
rc = pmic->pmic_set_current(pmic->led_src_2, 0);
break;
case MSM_CAMERA_LED_HIGH:
rc = pmic->pmic_set_current(pmic->led_src_1,
pmic->high_current);
if (pmic->num_of_src > 1)
rc = pmic->pmic_set_current(pmic->led_src_2,
pmic->high_current);
break;
case MSM_CAMERA_LED_INIT:
case MSM_CAMERA_LED_RELEASE:
break;
default:
rc = -EFAULT;
break;
}
pr_err("flash_set_led_state: return %d\n", rc);
return rc;
}
int32_t msm_camera_flash_set_led_state(
struct msm_camera_sensor_flash_data *fdata, unsigned led_state)
{
int32_t rc;
pr_err("msm_camera_flash_set_led_state flash_sr_type=%d\n",fdata->flash_src->flash_sr_type);
if (fdata->flash_type != MSM_CAMERA_FLASH_LED ||
fdata->flash_src == NULL)
return -ENODEV;
switch (fdata->flash_src->flash_sr_type) {
case MSM_CAMERA_FLASH_SRC_PMIC:
rc = msm_camera_flash_pmic(&fdata->flash_src->_fsrc.pmic_src,
led_state);
break;
case MSM_CAMERA_FLASH_SRC_PWM:
rc = msm_camera_flash_pwm(&fdata->flash_src->_fsrc.pwm_src,
led_state);
break;
case MSM_CAMERA_FLASH_SRC_CURRENT_DRIVER:
rc = msm_camera_flash_current_driver(
&fdata->flash_src->_fsrc.current_driver_src,
led_state);
break;
case MSM_CAMERA_FLASH_SRC_EXT:
rc = msm_camera_flash_external(
&fdata->flash_src->_fsrc.ext_driver_src,
led_state);
break;
case MSM_CAMERA_FLASH_SRC_LED1:
rc = msm_camera_flash_led(
&fdata->flash_src->_fsrc.ext_driver_src,
led_state);
break;
default:
rc = -ENODEV;
break;
}
return rc;
}
static int msm_strobe_flash_xenon_charge(int32_t flash_charge,
int32_t charge_enable, uint32_t flash_recharge_duration)
{
pr_err("ljk msm_strobe_flash_xenon_charge flash_charge=%d charge_enable=%d flash_recharge_duration=%d",flash_charge,charge_enable,flash_recharge_duration);
gpio_set_value_cansleep(flash_charge, charge_enable);
if (charge_enable) {
timer_flash.expires = jiffies +
msecs_to_jiffies(flash_recharge_duration);
/* add timer for the recharge */
if (!timer_pending(&timer_flash))
add_timer(&timer_flash);
} else
del_timer_sync(&timer_flash);
return 0;
}
static void strobe_flash_xenon_recharge_handler(unsigned long data)
{
unsigned long flags;
struct msm_camera_sensor_strobe_flash_data *sfdata =
(struct msm_camera_sensor_strobe_flash_data *)data;
spin_lock_irqsave(&sfdata->timer_lock, flags);
msm_strobe_flash_xenon_charge(sfdata->flash_charge, 1,
sfdata->flash_recharge_duration);
spin_unlock_irqrestore(&sfdata->timer_lock, flags);
return;
}
static irqreturn_t strobe_flash_charge_ready_irq(int irq_num, void *data)
{
struct msm_camera_sensor_strobe_flash_data *sfdata =
(struct msm_camera_sensor_strobe_flash_data *)data;
/* put the charge signal to low */
gpio_set_value_cansleep(sfdata->flash_charge, 0);
return IRQ_HANDLED;
}
static int msm_strobe_flash_xenon_init(
struct msm_camera_sensor_strobe_flash_data *sfdata)
{
unsigned long flags;
int rc = 0;
pr_err("ljk msm_strobe_flash_xenon_init ");
spin_lock_irqsave(&sfdata->spin_lock, flags);
if (!sfdata->state) {
rc = config_flash_gpio_table(MSM_CAM_FLASH_ON, sfdata);
if (rc < 0) {
pr_err("%s: gpio_request failed\n", __func__);
goto go_out;
}
rc = request_irq(sfdata->irq, strobe_flash_charge_ready_irq,
IRQF_TRIGGER_RISING, "charge_ready", sfdata);
if (rc < 0) {
pr_err("%s: request_irq failed %d\n", __func__, rc);
goto go_out;
}
spin_lock_init(&sfdata->timer_lock);
/* setup timer */
init_timer(&timer_flash);
timer_flash.function = strobe_flash_xenon_recharge_handler;
timer_flash.data = (unsigned long)sfdata;
}
sfdata->state++;
go_out:
spin_unlock_irqrestore(&sfdata->spin_lock, flags);
return rc;
}
static int msm_strobe_flash_xenon_release
(struct msm_camera_sensor_strobe_flash_data *sfdata, int32_t final_release)
{
unsigned long flags;
pr_err("ljk msm_strobe_flash_xenon_release");
spin_lock_irqsave(&sfdata->spin_lock, flags);
if (sfdata->state > 0) {
if (final_release)
sfdata->state = 0;
else
sfdata->state--;
if (!sfdata->state) {
free_irq(sfdata->irq, sfdata);
config_flash_gpio_table(MSM_CAM_FLASH_OFF, sfdata);
if (timer_pending(&timer_flash))
del_timer_sync(&timer_flash);
}
}
spin_unlock_irqrestore(&sfdata->spin_lock, flags);
return 0;
}
static void msm_strobe_flash_xenon_fn_init
(struct msm_strobe_flash_ctrl *strobe_flash_ptr)
{
pr_err("ljk msm_strobe_flash_xenon_fn_init");
strobe_flash_ptr->strobe_flash_init =
msm_strobe_flash_xenon_init;
strobe_flash_ptr->strobe_flash_charge =
msm_strobe_flash_xenon_charge;
strobe_flash_ptr->strobe_flash_release =
msm_strobe_flash_xenon_release;
}
int msm_strobe_flash_init(struct msm_sync *sync, uint32_t sftype)
{
int rc = 0;
pr_err("ljk msm_strobe_flash_init sftype=%d",sftype);
switch (sftype) {
case MSM_CAMERA_STROBE_FLASH_XENON:
if (sync->sdata->strobe_flash_data) {
msm_strobe_flash_xenon_fn_init(&sync->sfctrl);
rc = sync->sfctrl.strobe_flash_init(
sync->sdata->strobe_flash_data);
} else
return -ENODEV;
break;
default:
rc = -ENODEV;
}
return rc;
}
int msm_strobe_flash_ctrl(struct msm_camera_sensor_strobe_flash_data *sfdata,
struct strobe_flash_ctrl_data *strobe_ctrl)
{
int rc = 0;
pr_err("ljk msm_strobe_flash_ctrl strobe_ctrl->type=%d",strobe_ctrl->type);
switch (strobe_ctrl->type) {
case STROBE_FLASH_CTRL_INIT:
if (!sfdata)
return -ENODEV;
rc = msm_strobe_flash_xenon_init(sfdata);
break;
case STROBE_FLASH_CTRL_CHARGE:
rc = msm_strobe_flash_xenon_charge(sfdata->flash_charge,
strobe_ctrl->charge_en,
sfdata->flash_recharge_duration);
break;
case STROBE_FLASH_CTRL_RELEASE:
if (sfdata)
rc = msm_strobe_flash_xenon_release(sfdata, 0);
break;
default:
pr_err("Invalid Strobe Flash State\n");
rc = -EINVAL;
}
return rc;
}
#if (defined(CONFIG_HW_ANDORRA) || defined(CONFIG_HW_ARMANI) || defined(CONFIG_HW_AUDI))
ssize_t proc_flash_led_write (struct file *file, const char __user *buf, size_t nbytes, loff_t *ppos)
{
char string[nbytes];
int rc = 0;
sscanf(buf, "%s", string);
config_flash_gpio_func(NULL);
if (!strcmp((const char *)string, (const char *)"on"))
{
gpio_direction_output(FLASH_HW_EN, 0);
gpio_direction_output(FLAHS_TORCH_EN, 0);
gpio_direction_output(FLAHS_FLASH_EN, 0);
msleep(1);
{
if (!lm3554_client)
{
rc = i2c_add_driver(&lm3554_i2c_driver);
if (rc < 0 || lm3554_client == NULL)
{
pr_err("flash lm3554_i2c_driver add failed rc= 0x%x lm3554_client = 0x%x\n",rc,(unsigned int)lm3554_client);
rc = -ENOTSUPP;
return rc;
}
else
{
pr_err(" flash i2c_add_driver(&lm3554_i2c_driver) OK\n");
}
}
}
gpio_direction_output(FLASH_HW_EN, 1);
msleep(1);
// rc = flash_i2c_write_b(lm3554_client, 0xB0, 0x78); //flash
rc = flash_i2c_write_b(lm3554_client, 0xA0, 0x4E); //torch
if (rc < 0 )
{
pr_err(" flash lm3554_i2c_driver current setting error\n");
rc = -ENOTSUPP;
}
else
{
pr_err(" flash lm3554_i2c_driver current setting OK\n");
}
gpio_direction_output(FLAHS_TORCH_EN, 1);
//gpio_direction_output(FLAHS_FLASH_EN, 1); //delete for torch mode
}
else if (!strcmp((const char *)string, (const char *)"off"))
{
gpio_direction_output(FLASH_HW_EN, 0);
gpio_direction_output(FLAHS_TORCH_EN, 0);
gpio_direction_output(FLAHS_FLASH_EN, 0);
}
return nbytes;
}
EXPORT_SYMBOL(proc_flash_led_write);
#endif
int msm_flash_ctrl(struct msm_camera_sensor_info *sdata,
struct flash_ctrl_data *flash_info)
{
int rc = 0;
sensor_data = sdata;
pr_err("msm_flash_ctrls flashtype=%d flash_type=%d led_state=%d\n",flash_info->flashtype,sdata->flash_type,flash_info->ctrl_data.led_state);
if(sdata->flash_data->flash_type!=MSM_CAMERA_FLASH_NONE)
{
switch (flash_info->flashtype) {
case LED_FLASH:
rc = msm_camera_flash_set_led_state(sdata->flash_data,
flash_info->ctrl_data.led_state);
break;
case STROBE_FLASH:
rc = msm_strobe_flash_ctrl(sdata->strobe_flash_data,
&(flash_info->ctrl_data.strobe_ctrl));
break;
default:
pr_err("Invalid Flash MODE\n");
rc = -EINVAL;
}
}
return rc;
}
| estiko/android_kernel_lenovo_armani_row | drivers/media/video/msm/flash.c | C | gpl-2.0 | 29,397 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ScrollMagic Classes</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link rel="shortcut icon" href="../img/favicon.ico" type="image/x-icon">
<link type="text/css" rel="stylesheet" href="styles/site.cosmo.css">
</head>
<body>
<div class="container-fluid">
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<a class="brand" href="index.html">ScrollMagic</a>
<ul class="nav">
<li class="dropdown">
<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="ScrollMagic.Controller.html">Controller</a>
</li>
<li>
<a href="ScrollMagic.Scene.html">Scene</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="events.list.html" class="dropdown-toggle" data-toggle="dropdown">Events<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="ScrollMagic.Scene.html#event:add">add</a>
</li>
<li>
<a href="ScrollMagic.Scene.html#event:change">change</a>
</li>
<li>
<a href="ScrollMagic.Scene.html#event:destroy">destroy</a>
</li>
<li>
<a href="ScrollMagic.Scene.html#event:end">end</a>
</li>
<li>
<a href="ScrollMagic.Scene.html#event:enter">enter</a>
</li>
<li>
<a href="ScrollMagic.Scene.html#event:leave">leave</a>
</li>
<li>
<a href="ScrollMagic.Scene.html#event:progress">progress</a>
</li>
<li>
<a href="ScrollMagic.Scene.html#event:remove">remove</a>
</li>
<li>
<a href="ScrollMagic.Scene.html#event:shift">shift</a>
</li>
<li>
<a href="ScrollMagic.Scene.html#event:start">start</a>
</li>
<li>
<a href="ScrollMagic.Scene.html#event:update">update</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="mixins.list.html" class="dropdown-toggle" data-toggle="dropdown">Plugins<b
class="caret"></b></a>
<ul class="dropdown-menu ">
<li>
<a href="animation.GSAP.html">GSAP</a>
</li>
<li>
<a href="animation.Velocity.html">Velocity</a>
</li>
<li>
<a href="debug.addIndicators.html">addIndicators</a>
</li>
<li>
<a href="framework.jQuery.html">jQuery</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="row-fluid">
<div class="span8">
<div id="main">
<h1 class="page-title">
Classes</h1>
<section>
<article>
<div class="container-overview">
<dl class="details">
</dl>
</div>
<h3 class="subsection-title">Classes</h3>
<dl>
<dt><a href="ScrollMagic.Controller.html">Controller</a></dt>
<dd></dd>
<dt><a href="ScrollMagic.Scene.html">Scene</a></dt>
<dd></dd>
</dl>
<h3 class="subsection-title">Namespaces</h3>
<dl>
<dt><a href="namespaces.html#ScrollMagic"><a href="ScrollMagic.html">ScrollMagic</a></a></dt>
<dd></dd>
</dl>
<h3 class="subsection-title">Events</h3>
<dl>
<dt>
<h4 class="name" id="event:add">add</h4>
</dt>
<dd>
<div class="description">
<p>Scene add event.<br>Fires when the scene is added to a controller.
This is mostly used by plugins to know that change might be due.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>event</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="description last"><p>The event Object passed to each callback</p>
<h6>Properties</h6>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>type</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The name of the event</p></td>
</tr>
<tr>
<td class="name"><code>target</code></td>
<td class="type">
<span class="param-type">Scene</span>
</td>
<td class="description last"><p>The Scene object that triggered this event</p></td>
</tr>
<tr>
<td class="name"><code>controller</code></td>
<td class="type">
<span class="param-type">boolean</span>
</td>
<td class="description last"><p>The controller object the scene was added to.</p></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-since">Since:</dt>
<dd class="tag-since"><ul class="dummy"><li>2.0.0</dd><br>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="ScrollMagic_Scene_event-management.js.html">ScrollMagic/Scene/event-management.js</a>, <a href="ScrollMagic_Scene_event-management.js.html#sunlight-1-line-192">line 192</a>
</li></ul></dd>
</dl>
<h5>Example</h5>
<pre class="sunlight-highlight-javascript">scene.on("add", function (event) {
console.log('Scene was added to a new controller.');
});</pre>
</dd>
<dt>
<h4 class="name" id="event:change">change</h4>
</dt>
<dd>
<div class="description">
<p>Scene change event.<br>Fires whenvever a property of the scene is changed.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>event</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="description last"><p>The event Object passed to each callback</p>
<h6>Properties</h6>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>type</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The name of the event</p></td>
</tr>
<tr>
<td class="name"><code>target</code></td>
<td class="type">
<span class="param-type">Scene</span>
</td>
<td class="description last"><p>The Scene object that triggered this event</p></td>
</tr>
<tr>
<td class="name"><code>what</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>Indicates what value has been changed</p></td>
</tr>
<tr>
<td class="name"><code>newval</code></td>
<td class="type">
<span class="param-type">mixed</span>
</td>
<td class="description last"><p>The new value of the changed property</p></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="ScrollMagic_Scene_event-management.js.html">ScrollMagic/Scene/event-management.js</a>, <a href="ScrollMagic_Scene_event-management.js.html#sunlight-1-line-130">line 130</a>
</li></ul></dd>
</dl>
<h5>Example</h5>
<pre class="sunlight-highlight-javascript">scene.on("change", function (event) {
console.log("Scene Property \"" + event.what + "\" changed to " + event.newval);
});</pre>
</dd>
<dt>
<h4 class="name" id="event:destroy">destroy</h4>
</dt>
<dd>
<div class="description">
<p>Scene destroy event.<br>Fires whenvever the scene is destroyed.
This can be used to tidy up custom behaviour used in events.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>event</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="description last"><p>The event Object passed to each callback</p>
<h6>Properties</h6>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>type</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The name of the event</p></td>
</tr>
<tr>
<td class="name"><code>target</code></td>
<td class="type">
<span class="param-type">Scene</span>
</td>
<td class="description last"><p>The Scene object that triggered this event</p></td>
</tr>
<tr>
<td class="name"><code>reset</code></td>
<td class="type">
<span class="param-type">boolean</span>
</td>
<td class="description last"><p>Indicates if the destroy method was called with reset <code>true</code> or <code>false</code>.</p></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-since">Since:</dt>
<dd class="tag-since"><ul class="dummy"><li>1.1.0</dd><br>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="ScrollMagic_Scene_event-management.js.html">ScrollMagic/Scene/event-management.js</a>, <a href="ScrollMagic_Scene_event-management.js.html#sunlight-1-line-167">line 167</a>
</li></ul></dd>
</dl>
<h5>Example</h5>
<pre class="sunlight-highlight-javascript">scene.on("enter", function (event) {
// add custom action
$("#my-elem").left("200");
})
.on("destroy", function (event) {
// reset my element to start position
if (event.reset) {
$("#my-elem").left("0");
}
});</pre>
</dd>
<dt>
<h4 class="name" id="event:end">end</h4>
</dt>
<dd>
<div class="description">
<p>Scene end event.<br>Fires whenever the scroll position its the ending point of the scene.<br>It will also fire when scrolling back up from after the scene and going over its end position. If you want something to happen only when scrolling down/right, use the scrollDirection parameter passed to the callback.</p>
<p>For details on this event and the order in which it is fired, please review the <code>Scene.progress</code> method.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>event</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="description last"><p>The event Object passed to each callback</p>
<h6>Properties</h6>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>type</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The name of the event</p></td>
</tr>
<tr>
<td class="name"><code>target</code></td>
<td class="type">
<span class="param-type">Scene</span>
</td>
<td class="description last"><p>The Scene object that triggered this event</p></td>
</tr>
<tr>
<td class="name"><code>progress</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>Reflects the current progress of the scene</p></td>
</tr>
<tr>
<td class="name"><code>state</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The current state of the scene <code>"DURING"</code> or <code>"AFTER"</code></p></td>
</tr>
<tr>
<td class="name"><code>scrollDirection</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>Indicates which way we are scrolling <code>"PAUSED"</code>, <code>"FORWARD"</code> or <code>"REVERSE"</code></p></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="ScrollMagic_Scene_event-management.js.html">ScrollMagic/Scene/event-management.js</a>, <a href="ScrollMagic_Scene_event-management.js.html#sunlight-1-line-29">line 29</a>
</li></ul></dd>
</dl>
<h5>Example</h5>
<pre class="sunlight-highlight-javascript">scene.on("end", function (event) {
console.log("Hit end point of scene.");
});</pre>
</dd>
<dt>
<h4 class="name" id="event:enter">enter</h4>
</dt>
<dd>
<div class="description">
<p>Scene enter event.<br>Fires whenever the scene enters the "DURING" state.<br>Keep in mind that it doesn't matter if the scene plays forward or backward: This event always fires when the scene enters its active scroll timeframe, regardless of the scroll-direction.</p>
<p>For details on this event and the order in which it is fired, please review the <code>Scene.progress</code> method.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>event</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="description last"><p>The event Object passed to each callback</p>
<h6>Properties</h6>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>type</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The name of the event</p></td>
</tr>
<tr>
<td class="name"><code>target</code></td>
<td class="type">
<span class="param-type">Scene</span>
</td>
<td class="description last"><p>The Scene object that triggered this event</p></td>
</tr>
<tr>
<td class="name"><code>progress</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>Reflects the current progress of the scene</p></td>
</tr>
<tr>
<td class="name"><code>state</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The current state of the scene - always <code>"DURING"</code></p></td>
</tr>
<tr>
<td class="name"><code>scrollDirection</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>Indicates which way we are scrolling <code>"PAUSED"</code>, <code>"FORWARD"</code> or <code>"REVERSE"</code></p></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="ScrollMagic_Scene_event-management.js.html">ScrollMagic/Scene/event-management.js</a>, <a href="ScrollMagic_Scene_event-management.js.html#sunlight-1-line-50">line 50</a>
</li></ul></dd>
</dl>
<h5>Example</h5>
<pre class="sunlight-highlight-javascript">scene.on("enter", function (event) {
console.log("Scene entered.");
});</pre>
</dd>
<dt>
<h4 class="name" id="event:leave">leave</h4>
</dt>
<dd>
<div class="description">
<p>Scene leave event.<br>Fires whenever the scene's state goes from "DURING" to either "BEFORE" or "AFTER".<br>Keep in mind that it doesn't matter if the scene plays forward or backward: This event always fires when the scene leaves its active scroll timeframe, regardless of the scroll-direction.</p>
<p>For details on this event and the order in which it is fired, please review the <code>Scene.progress</code> method.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>event</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="description last"><p>The event Object passed to each callback</p>
<h6>Properties</h6>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>type</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The name of the event</p></td>
</tr>
<tr>
<td class="name"><code>target</code></td>
<td class="type">
<span class="param-type">Scene</span>
</td>
<td class="description last"><p>The Scene object that triggered this event</p></td>
</tr>
<tr>
<td class="name"><code>progress</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>Reflects the current progress of the scene</p></td>
</tr>
<tr>
<td class="name"><code>state</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The current state of the scene <code>"BEFORE"</code> or <code>"AFTER"</code></p></td>
</tr>
<tr>
<td class="name"><code>scrollDirection</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>Indicates which way we are scrolling <code>"PAUSED"</code>, <code>"FORWARD"</code> or <code>"REVERSE"</code></p></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="ScrollMagic_Scene_event-management.js.html">ScrollMagic/Scene/event-management.js</a>, <a href="ScrollMagic_Scene_event-management.js.html#sunlight-1-line-71">line 71</a>
</li></ul></dd>
</dl>
<h5>Example</h5>
<pre class="sunlight-highlight-javascript">scene.on("leave", function (event) {
console.log("Scene left.");
});</pre>
</dd>
<dt>
<h4 class="name" id="event:progress">progress</h4>
</dt>
<dd>
<div class="description">
<p>Scene progress event.<br>Fires whenever the progress of the scene changes.</p>
<p>For details on this event and the order in which it is fired, please review the <code>Scene.progress</code> method.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>event</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="description last"><p>The event Object passed to each callback</p>
<h6>Properties</h6>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>type</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The name of the event</p></td>
</tr>
<tr>
<td class="name"><code>target</code></td>
<td class="type">
<span class="param-type">Scene</span>
</td>
<td class="description last"><p>The Scene object that triggered this event</p></td>
</tr>
<tr>
<td class="name"><code>progress</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>Reflects the current progress of the scene</p></td>
</tr>
<tr>
<td class="name"><code>state</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The current state of the scene <code>"BEFORE"</code>, <code>"DURING"</code> or <code>"AFTER"</code></p></td>
</tr>
<tr>
<td class="name"><code>scrollDirection</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>Indicates which way we are scrolling <code>"PAUSED"</code>, <code>"FORWARD"</code> or <code>"REVERSE"</code></p></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="ScrollMagic_Scene_event-management.js.html">ScrollMagic/Scene/event-management.js</a>, <a href="ScrollMagic_Scene_event-management.js.html#sunlight-1-line-110">line 110</a>
</li></ul></dd>
</dl>
<h5>Example</h5>
<pre class="sunlight-highlight-javascript">scene.on("progress", function (event) {
console.log("Scene progress changed to " + event.progress);
});</pre>
</dd>
<dt>
<h4 class="name" id="event:remove">remove</h4>
</dt>
<dd>
<div class="description">
<p>Scene remove event.<br>Fires when the scene is removed from a controller.
This is mostly used by plugins to know that change might be due.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>event</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="description last"><p>The event Object passed to each callback</p>
<h6>Properties</h6>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>type</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The name of the event</p></td>
</tr>
<tr>
<td class="name"><code>target</code></td>
<td class="type">
<span class="param-type">Scene</span>
</td>
<td class="description last"><p>The Scene object that triggered this event</p></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-since">Since:</dt>
<dd class="tag-since"><ul class="dummy"><li>2.0.0</dd><br>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="ScrollMagic_Scene_event-management.js.html">ScrollMagic/Scene/event-management.js</a>, <a href="ScrollMagic_Scene_event-management.js.html#sunlight-1-line-210">line 210</a>
</li></ul></dd>
</dl>
<h5>Example</h5>
<pre class="sunlight-highlight-javascript">scene.on("remove", function (event) {
console.log('Scene was removed from its controller.');
});</pre>
</dd>
<dt>
<h4 class="name" id="event:shift">shift</h4>
</dt>
<dd>
<div class="description">
<p>Scene shift event.<br>Fires whenvever the start or end <strong>scroll offset</strong> of the scene change.
This happens explicitely, when one of these values change: <code>offset</code>, <code>duration</code> or <code>triggerHook</code>.
It will fire implicitly when the <code>triggerElement</code> changes, if the new element has a different position (most cases).
It will also fire implicitly when the size of the container changes and the triggerHook is anything other than <code>onLeave</code>.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>event</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="description last"><p>The event Object passed to each callback</p>
<h6>Properties</h6>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>type</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The name of the event</p></td>
</tr>
<tr>
<td class="name"><code>target</code></td>
<td class="type">
<span class="param-type">Scene</span>
</td>
<td class="description last"><p>The Scene object that triggered this event</p></td>
</tr>
<tr>
<td class="name"><code>reason</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>Indicates why the scene has shifted</p></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-since">Since:</dt>
<dd class="tag-since"><ul class="dummy"><li>1.1.0</dd><br>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="ScrollMagic_Scene_event-management.js.html">ScrollMagic/Scene/event-management.js</a>, <a href="ScrollMagic_Scene_event-management.js.html#sunlight-1-line-147">line 147</a>
</li></ul></dd>
</dl>
<h5>Example</h5>
<pre class="sunlight-highlight-javascript">scene.on("shift", function (event) {
console.log("Scene moved, because the " + event.reason + " has changed.)");
});</pre>
</dd>
<dt>
<h4 class="name" id="event:start">start</h4>
</dt>
<dd>
<div class="description">
<p>Scene start event.<br>Fires whenever the scroll position its the starting point of the scene.<br>It will also fire when scrolling back up going over the start position of the scene. If you want something to happen only when scrolling down/right, use the scrollDirection parameter passed to the callback.</p>
<p>For details on this event and the order in which it is fired, please review the <code>Scene.progress</code> method.</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>event</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="description last"><p>The event Object passed to each callback</p>
<h6>Properties</h6>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>type</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The name of the event</p></td>
</tr>
<tr>
<td class="name"><code>target</code></td>
<td class="type">
<span class="param-type">Scene</span>
</td>
<td class="description last"><p>The Scene object that triggered this event</p></td>
</tr>
<tr>
<td class="name"><code>progress</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>Reflects the current progress of the scene</p></td>
</tr>
<tr>
<td class="name"><code>state</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The current state of the scene <code>"BEFORE"</code> or <code>"DURING"</code></p></td>
</tr>
<tr>
<td class="name"><code>scrollDirection</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>Indicates which way we are scrolling <code>"PAUSED"</code>, <code>"FORWARD"</code> or <code>"REVERSE"</code></p></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="ScrollMagic_Scene_event-management.js.html">ScrollMagic/Scene/event-management.js</a>, <a href="ScrollMagic_Scene_event-management.js.html#sunlight-1-line-8">line 8</a>
</li></ul></dd>
</dl>
<h5>Example</h5>
<pre class="sunlight-highlight-javascript">scene.on("start", function (event) {
console.log("Hit start point of scene.");
});</pre>
</dd>
<dt>
<h4 class="name" id="event:update">update</h4>
</dt>
<dd>
<div class="description">
<p>Scene update event.<br>Fires whenever the scene is updated (but not necessarily changes the progress).</p>
</div>
<dl class="details">
<h5 class="subsection-title">Properties:</h5>
<dl>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>event</code></td>
<td class="type">
<span class="param-type">object</span>
</td>
<td class="description last"><p>The event Object passed to each callback</p>
<h6>Properties</h6>
<table class="props table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th class="last">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"><code>type</code></td>
<td class="type">
<span class="param-type">string</span>
</td>
<td class="description last"><p>The name of the event</p></td>
</tr>
<tr>
<td class="name"><code>target</code></td>
<td class="type">
<span class="param-type">Scene</span>
</td>
<td class="description last"><p>The Scene object that triggered this event</p></td>
</tr>
<tr>
<td class="name"><code>startPos</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The starting position of the scene (in relation to the conainer)</p></td>
</tr>
<tr>
<td class="name"><code>endPos</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The ending position of the scene (in relation to the conainer)</p></td>
</tr>
<tr>
<td class="name"><code>scrollPos</code></td>
<td class="type">
<span class="param-type">number</span>
</td>
<td class="description last"><p>The current scroll position of the container</p></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</dl>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="ScrollMagic_Scene_event-management.js.html">ScrollMagic/Scene/event-management.js</a>, <a href="ScrollMagic_Scene_event-management.js.html#sunlight-1-line-92">line 92</a>
</li></ul></dd>
</dl>
<h5>Example</h5>
<pre class="sunlight-highlight-javascript">scene.on("update", function (event) {
console.log("Scene updated.");
});</pre>
</dd>
</dl>
</article>
</section>
</div>
<div class="clearfix"></div>
<footer>
<span class="copyright">
© Jan Paepke 2015
</span>
<br />
<span class="jsdoc-message">
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc" target="_blank">JSDoc 3.3.0-beta1</a>
using a customized version of the <a href="https://github.com/terryweiss/docstrap" target="_blank">DocStrap template</a>.
</span>
</footer>
</div>
<div class="span3">
<div id="toc"></div>
</div>
<br clear="both">
</div>
</div>
<script src="scripts/sunlight.js"></script>
<script src="scripts/sunlight.javascript.js"></script>
<script src="scripts/sunlight-plugin.doclinks.js"></script>
<script src="scripts/sunlight-plugin.linenumbers.js"></script>
<script src="scripts/sunlight-plugin.menu.js"></script>
<script src="scripts/jquery.min.js"></script>
<script src="scripts/jquery.scrollTo.js"></script>
<script src="scripts/jquery.localScroll.js"></script>
<script src="scripts/bootstrap-dropdown.js"></script>
<script src="scripts/toc.js"></script>
<script> prettyPrint(); </script>
<script> Sunlight.highlightAll({lineNumbers:true, showMenu: true, enableDoclinks :true}); </script>
<script>
function openDeeplinkedElement (skipAni) {
$("dt h4.member-collapsed[id='" + window.location.hash.substring(1).replace(":", "\\:") +"']").trigger("click", skipAni);
}
$( function () {
$( "#toc" ).toc( {
anchorName : function(i, heading, prefix) {
return $(heading).attr("id") || ( prefix + i );
},
selectors : "h1:visible,h2:visible,h3:visible,h4:visible",
onScrollFinish : openDeeplinkedElement,
highlightOffset : 10,
scrollOffset: 60
} );
$( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" );
$( "#main span[id^='toc']" ).addClass( "toc-shim" );
} );
</script>
<script>
$( function () {
// $('#main').localScroll({
// offset: { top: 56 } //offset by the height of your header (give or take a few px, see what works for you)
// });
// workaround for anchors below header...
window.setTimeout(function () {
$(document).scrollTop($(document).scrollTop()-60);
}, 1)
var hash = window.location.hash.substring(1).replace(":", "\\:");
$( "dt h4.name" ).each( function () {
var $this = $( this );
var icon = $( "<i/>" ).addClass( "icon-plus-sign" ).addClass( "pull-right" ).addClass( "icon-white" );
var dt = $this.parents( "dt" );
var children = dt.next( "dd" );
$this.append( icon ).css( {cursor : "pointer"} );
$this.addClass( "member-collapsed" ).addClass( "member" );
if (hash != $this.attr("id")) {
children.hide();
}
$this.toggle( function (e, skipAni) {
var scrollPos = $(document).scrollTop();
window.location.hash = $(this).attr("id");
$(document).scrollTop(scrollPos);
icon.addClass( "icon-minus-sign" ).removeClass( "icon-plus-sign" ).removeClass( "icon-white" );
$this.addClass( "member-open" ).removeClass( "member-collapsed" );
children.slideDown(skipAni ? 0 : undefined);
}, function () {
icon.addClass( "icon-plus-sign" ).removeClass( "icon-minus-sign" ).addClass( "icon-white" );
$this.addClass( "member-collapsed" ).removeClass( "member-open" );
children.slideUp();
} );
} );
// open if deeplinked
if (hash.length > 0)
openDeeplinkedElement(true);
} );
</script>
<script type="text/javascript" src="../js/tracking.js"></script>
</body>
</html> | Garth619/Femi9 | wp-content/themes/femi9/scrollmagic/docs/classes.list.html | HTML | gpl-2.0 | 47,708 |
// pkg_acqfile.cc
//
// Copyright 2002, 2005 Daniel Burrows
//
// 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; see the file COPYING. If not, write to
// the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
// (based on pkg_changelog)
#include "pkg_acqfile.h"
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <aptitude.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/stat.h>
#include <apt-pkg/error.h>
#include <apt-pkg/acquire-item.h>
#include <apt-pkg/sourcelist.h>
#include <apt-pkg/strutl.h>
// Mostly copied from pkgAcqArchive.
bool get_archive(pkgAcquire *Owner, pkgSourceList *Sources,
pkgRecords *Recs, pkgCache::VerIterator const &Version,
string directory, string &StoreFilename)
{
pkgCache::VerFileIterator Vf=Version.FileList();
if(Version.Arch()==0)
return _error->Error(_("I wasn't able to locate a file for the %s package. "
"This might mean you need to manually fix this package. (due to missing arch)"),
Version.ParentPkg().Name());
/* We need to find a filename to determine the extension. We make the
assumption here that all the available sources for this version share
the same extension.. */
// Skip not source sources, they do not have file fields.
for (; Vf.end() == false; Vf++)
{
if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
continue;
break;
}
// Does not really matter here.. we are going to fail out below
if (Vf.end() != true)
{
// If this fails to get a file name we will bomb out below.
pkgRecords::Parser &Parse = Recs->Lookup(Vf);
if (_error->PendingError() == true)
return false;
// Generate the final file name as: package_version_arch.foo
StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
QuoteString(Version.VerStr(),"_:") + '_' +
QuoteString(Version.Arch(),"_:.") +
"." + flExtension(Parse.FileName());
}
for (; Vf.end() == false; Vf++)
{
// Ignore not source sources
if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
continue;
// Try to cross match against the source list
pkgIndexFile *Index;
if (Sources->FindIndex(Vf.File(),Index) == false)
continue;
// Grab the text package record
pkgRecords::Parser &Parse = Recs->Lookup(Vf);
if (_error->PendingError() == true)
return false;
const string PkgFile = Parse.FileName();
const string MD5 = Parse.MD5Hash();
if (PkgFile.empty() == true)
return _error->Error(_("The package index files are corrupted. No Filename: "
"field for package %s."),
Version.ParentPkg().Name());
string DestFile = directory + "/" + flNotDir(StoreFilename);
// Create the item
new pkgAcqFile(Owner,
Index->ArchiveURI(PkgFile),
MD5,
Version->Size,
Index->ArchiveInfo(Version),
Version.ParentPkg().Name(),
"", DestFile);
Vf++;
return true;
}
return false;
}
| SamB/aptitude | src/generic/apt/pkg_acqfile.cc | C++ | gpl-2.0 | 3,742 |
/*
Copyright (C) 2008 Paul Davis
Author: Hans Baier
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <sstream>
#include "midi_channel_selector.h"
#include "gtkmm/separator.h"
#include "i18n.h"
#include "rgb_macros.h"
using namespace std;
using namespace Gtk;
using namespace ARDOUR;
MidiChannelSelector::MidiChannelSelector(int n_rows, int n_columns, int start_row, int start_column)
: Table(n_rows, n_columns, true)
, _recursion_counter(0)
{
assert(n_rows >= 4);
assert(n_rows >= start_row + 4);
assert(n_columns >=4);
assert(n_columns >= start_column + 4);
property_column_spacing() = 0;
property_row_spacing() = 0;
uint8_t channel_nr = 0;
for (int row = 0; row < 4; ++row) {
for (int column = 0; column < 4; ++column) {
ostringstream channel;
channel << int(++channel_nr);
_button_labels[row][column].set_text(channel.str());
_button_labels[row][column].set_justify(JUSTIFY_RIGHT);
_buttons[row][column].add(_button_labels[row][column]);
_buttons[row][column].signal_toggled().connect(
sigc::bind(
sigc::mem_fun(this, &MidiChannelSelector::button_toggled),
&_buttons[row][column],
channel_nr - 1));
_buttons[row][column].set_widget_name (X_("MidiChannelSelectorButton"));
_buttons[row][column].signal_button_release_event().connect(
sigc::mem_fun(this, &MidiChannelSelector::was_clicked), false);
int table_row = start_row + row;
int table_column = start_column + column;
attach(_buttons[row][column], table_column, table_column + 1, table_row, table_row + 1);
}
}
}
MidiChannelSelector::~MidiChannelSelector()
{
}
bool
MidiChannelSelector::was_clicked (GdkEventButton*)
{
clicked ();
return false;
}
void
MidiChannelSelector::set_channel_colors(const uint32_t new_channel_colors[16])
{
for (int row = 0; row < 4; ++row) {
for (int column = 0; column < 4; ++column) {
char color_normal[8];
char color_active[8];
snprintf(color_normal, 8, "#%x", UINT_INTERPOLATE(new_channel_colors[row * 4 + column], 0x000000ff, 0.6));
snprintf(color_active, 8, "#%x", new_channel_colors[row * 4 + column]);
_buttons[row][column].modify_bg(STATE_NORMAL, Gdk::Color(color_normal));
_buttons[row][column].modify_bg(STATE_ACTIVE, Gdk::Color(color_active));
}
}
}
void
MidiChannelSelector::set_default_channel_color()
{
for (int row = 0; row < 4; ++row) {
for (int column = 0; column < 4; ++column) {
_buttons[row][column].unset_fg (STATE_NORMAL);
_buttons[row][column].unset_fg (STATE_ACTIVE);
_buttons[row][column].unset_bg (STATE_NORMAL);
_buttons[row][column].unset_bg (STATE_ACTIVE);
}
}
}
SingleMidiChannelSelector::SingleMidiChannelSelector(uint8_t active_channel)
: MidiChannelSelector()
{
_last_active_button = 0;
ToggleButton* button = &_buttons[active_channel / 4][active_channel % 4];
_active_channel = active_channel;
button->set_active(true);
_last_active_button = button;
}
void
SingleMidiChannelSelector::button_toggled(ToggleButton* button, uint8_t channel)
{
++_recursion_counter;
if (_recursion_counter == 1) {
// if the current button is active it must
// be different from the first one
if (button->get_active()) {
if (_last_active_button) {
_last_active_button->set_active(false);
_active_channel = channel;
_last_active_button = button;
channel_selected.emit(channel);
}
} else {
// if not, the user pressed the already active button
button->set_active(true);
_active_channel = channel;
}
}
--_recursion_counter;
}
MidiMultipleChannelSelector::MidiMultipleChannelSelector(ChannelMode mode, uint16_t mask)
: MidiChannelSelector(4, 6, 0, 0)
, _channel_mode(mode)
{
_select_all.add(*manage(new Label(_("All"))));
_select_all.signal_clicked().connect(
sigc::bind(sigc::mem_fun(this, &MidiMultipleChannelSelector::select_all), true));
_select_none.add(*manage(new Label(_("None"))));
_select_none.signal_clicked().connect(
sigc::bind(sigc::mem_fun(this, &MidiMultipleChannelSelector::select_all), false));
_invert_selection.add(*manage(new Label(_("Invert"))));
_invert_selection.signal_clicked().connect(
sigc::mem_fun(this, &MidiMultipleChannelSelector::invert_selection));
_force_channel.add(*manage(new Label(_("Force"))));
_force_channel.signal_toggled().connect(
sigc::mem_fun(this, &MidiMultipleChannelSelector::force_channels_button_toggled));
set_homogeneous(false);
attach(*manage(new VSeparator()), 4, 5, 0, 4, SHRINK, FILL, 0, 0);
//set_row_spacing(4, -5);
attach(_select_all, 5, 6, 0, 1);
attach(_select_none, 5, 6, 1, 2);
attach(_invert_selection, 5, 6, 2, 3);
attach(_force_channel, 5, 6, 3, 4);
set_selected_channels(mask);
}
MidiMultipleChannelSelector::~MidiMultipleChannelSelector()
{
mode_changed.clear();
}
void
MidiMultipleChannelSelector::set_channel_mode(ChannelMode mode, uint16_t mask)
{
switch (mode) {
case AllChannels:
_force_channel.set_active(false);
set_selected_channels(0xFFFF);
break;
case FilterChannels:
_force_channel.set_active(false);
set_selected_channels(mask);
break;
case ForceChannel:
_force_channel.set_active(true);
for (uint16_t i = 0; i < 16; i++) {
ToggleButton* button = &_buttons[i / 4][i % 4];
button->set_active(i == mask);
}
}
}
uint16_t
MidiMultipleChannelSelector::get_selected_channels() const
{
uint16_t selected_channels = 0;
for (uint16_t i = 0; i < 16; i++) {
const ToggleButton* button = &_buttons[i / 4][i % 4];
if (button->get_active()) {
selected_channels |= (1L << i);
}
}
return selected_channels;
}
void
MidiMultipleChannelSelector::set_selected_channels(uint16_t selected_channels)
{
for (uint16_t i = 0; i < 16; i++) {
ToggleButton* button = &_buttons[i / 4][i % 4];
if (selected_channels & (1L << i)) {
button->set_active(true);
} else {
button->set_active(false);
}
}
}
void
MidiMultipleChannelSelector::button_toggled(ToggleButton */*button*/, uint8_t channel)
{
++_recursion_counter;
if (_recursion_counter == 1) {
if (_channel_mode == ForceChannel) {
mode_changed.emit(_channel_mode, channel);
set_selected_channels(1 << channel);
} else {
mode_changed.emit(_channel_mode, get_selected_channels());
}
}
--_recursion_counter;
}
void
MidiMultipleChannelSelector::force_channels_button_toggled()
{
if (_force_channel.get_active()) {
_channel_mode = ForceChannel;
bool found_first_active = false;
// leave only the first button enabled
uint16_t active_channel = 0;
for (int i = 0; i <= 15; i++) {
ToggleButton* button = &_buttons[i / 4][i % 4];
if (button->get_active()) {
if (found_first_active) {
++_recursion_counter;
button->set_active(false);
--_recursion_counter;
} else {
found_first_active = true;
active_channel = i;
}
}
}
if (!found_first_active) {
_buttons[0][0].set_active(true);
}
_select_all.set_sensitive(false);
_select_none.set_sensitive(false);
_invert_selection.set_sensitive(false);
mode_changed.emit(_channel_mode, active_channel);
} else {
_channel_mode = FilterChannels;
_select_all.set_sensitive(true);
_select_none.set_sensitive(true);
_invert_selection.set_sensitive(true);
mode_changed.emit(FilterChannels, get_selected_channels());
}
}
void
MidiMultipleChannelSelector::select_all(bool on)
{
if (_channel_mode == ForceChannel)
return;
++_recursion_counter;
for (uint16_t i = 0; i < 16; i++) {
ToggleButton* button = &_buttons[i / 4][i % 4];
button->set_active(on);
}
--_recursion_counter;
mode_changed.emit(_channel_mode, get_selected_channels());
}
void
MidiMultipleChannelSelector::invert_selection(void)
{
if (_channel_mode == ForceChannel)
return;
++_recursion_counter;
for (uint16_t i = 0; i < 16; i++) {
ToggleButton* button = &_buttons[i / 4][i % 4];
if (button->get_active()) {
button->set_active(false);
} else {
button->set_active(true);
}
}
--_recursion_counter;
mode_changed.emit(_channel_mode, get_selected_channels());
}
| davidhalter-archive/ardour | gtk2_ardour/midi_channel_selector.cc | C++ | gpl-2.0 | 8,697 |
<?
session_name('cidesa');
session_start();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title><? echo $_GET["titulo"]; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<LINK media=all href="../../lib/css/base.css" type=text/css rel=stylesheet>
<link href="../../lib/css/siga.css" rel="stylesheet" type="text/css">
</head>
<style type="text/css">
.distabla tr:hover { background-color: #DFE7F2; color: #000000;}
.distabla tr.resaltar { background-color: #DFE7F2; color: #000000;}
.distabla td { border: 1px solid #CCCCCC;}
.distabla th { border: 1px solid #CCCCCC;
background-color: #CCCCCC;}
</style>
<body>
<form name="form1" onsubmit="return false;" method="post" action="catalogo2.php">
<p>
<?
// require_once("../../../lib/genegociocatalogo.php");
require_once($_SESSION["x"].'lib/bd/basedatosAdo.php');
require_once($_SESSION["x"].'lib/general/funciones.php');
require_once($_SESSION["x"].'lib/general/funciones2.php');
$obj=new negociocatalogo2();
$aux1=obtenerget("campo");
$aux2=obtenerget("campo2");
$aux3=obtenerget("foco");
$aux4=obtenerget("tipo");
if (!empty($aux1))
{
$_SESSION["c"]=$aux1;
$campo=$_SESSION["c"];
}
else
{
$campo=$_SESSION["c"];
}
if (!empty($aux2))
{
$_SESSION["d"]=$aux2;
$campo2=$_SESSION["d"];
}
else
{
$campo2=$_SESSION["d"];
}
if (!empty($aux3))
{
$_SESSION["f"]=$aux3;
$foco=$_SESSION["f"];
}
else
{
$foco=$_SESSION["f"];
}
if (!empty($aux4))
{
$_SESSION["t"]=$aux4;
$tipo=$_SESSION["t"];
}
else
{
$tipo=$_SESSION["t"];
}
$campo=obtenerget("campo");
$campo2=obtenerget("campo2");
$sql=obtenerget("sql");
$foco=obtenerget("foco");
$tipo=obtenerget("tipo");
$filtro=obtenerget("filtro");
$campoint=obtenerpost("campoint");
$sqlint=obtenerpost("sqlint");
$filtroint=obtenerpost("filtroint");
$condicion=obtenerpost("condicion");
$condicionnew="";
if ($sqlint=="")
{
$sqlint=$sql;
}
if ($campoint=="")
{
$campoint=$campo;
$campoint2=$campo2;
$focoint=$foco;
$tipoint=$tipo;
}
if ($filtroint!="")
{
if ($condicion=="")
{
$condicion="like upper(�%�)";
}
$condicionnew="like upper(�%".$filtroint."%�)";
$sqlint=str_replace($condicion,$condicionnew,$sqlint);
$condicion=$condicionnew;
}
$i=1;
?>
<input name="sqlint" type="hidden" id="sqlint" value="<?print $sqlint;?>">
<input name="campoint" type="hidden" id="campoint" value="<?print $campoint;?>">
<input name="condicion" type="hidden" id="condicion" value="<?print $condicion;?>">
<BR>
<table width="402" align="center">
<tr>
<td align="center" class="tpButtons">Opciones de Búsqueda </td>
</tr>
<tr valign="middle">
<td height="32" class="recuadro"><font face="verdana"> Filtar por: </font>
<input name="filtroint" type="text" id="filtro2" value="<?print $filtroint;?>" size="30" maxlength="200" class="imagenInicio" onMouseOver="this.className='imagenFoco'" onMouseOut="this.className='imagenInicio'">
<input type="submit" name="Submit" value="Filtrar"> </td>
</tr>
<tr valign="middle">
<td height="32" class="recuadro"><font face="verdana"> Buscar por: </font>
<input name="buscarref" type="text" class="imagenInicio" id="buscarref2" onMouseOver="this.className='imagenFoco'" onMouseOut="this.className='imagenInicio'" onKeyDown="tecla(event)" size="30" maxlength="200">
<input type="button" name="Button" value="Buscar" onClick="mostrarreferencia();"></td>
</tr>
</table>
</p>
<div style="overflow:auto; width:450px; height:301px; border:0px solid #CCCCCC">
<table width="100%" border="0" bordercolor="#000000" id="TablaCatalogo" class="recuadro">
<?
if ($sql!="")
{
$obj->mostrar($sql,$filtro);
}
else
{
$obj->mostrar($sqlint,$filtroint);
}
$cuantasfilas=$obj->numerofilas();
$arreglo=$obj->devuelve_arreglo();
$numcampos=$obj->numerocampos();
?>
</table>
</div>
<p> </p>
<p> </p>
<input type="hidden" name="aux">
<input type="hidden" name="valor" value="<?print $i;?>">
</form>
</body>
<script language="JavaScript">
function aceptar(c,d)
{
f=opener.document.form1;
var campo2='<? echo $campo2; ?>'
var campoint2='<? echo $campoint2; ?>'
var foco='<?print $foco; ?>';
var focoint='<?print $focoint; ?>';
<?
if ($campo=="")
{
?>
f.<?print $campoint; ?>.value=c;
if (campoint2=='x'){ } else{ f.<?print $campoint2; ?>.value=d; }
if (focoint!='submit'){
f.<?print $focoint; ?>.focus();
f.<?print $focoint; ?>.select();
}else{ opener.document.form1.submit(); }
tipoint='<? echo $tipoint; ?>';
if (tipoint=='G')
{
id='<?print $campoint; ?>';
id2='<?print $campoint2; ?>';
opener.repetido2(id,id2);
}
<?
}
else
{
?>
f.<?print $campo; ?>.value=c;
if (campo2=='x'){ } else{ f.<?print $campo2; ?>.value=d; }
if (foco!='submit'){
f.<?print $foco; ?>.focus();
f.<?print $foco; ?>.select();
}else{ opener.document.form1.submit(); }
tipo='<? echo $tipo; ?>';
if (tipo=='G')
{
id='<?print $campo; ?>';
id2='<?print $campo2; ?>';
opener.repetido2(id,id2);
}
<?
}
?>
close();
}
function enviar()
{
f=document.form1;
f.action="catalogo2.php";
f.submit();
}
function mostrarreferencia(letra)
{
var rows = document.getElementsByTagName("tr");
for(i in rows)
{
rows[i].className = null;
}
f=document.form1;
cuantos=f.buscarref.value.length+1; //validar error de longitud
maximo=<?print $cuantasfilas;?>;
referencia="";
f.aux.value=f.buscarref.value+letra;
for (i=0;i<maximo;i++)
{
valor=f.elements["r"+(i+1)].value.substr(0,cuantos);
if (valor==f.aux.value.toUpperCase())
{
rows[i+1].className = "resaltar";
referencia=f.elements["r"+(i+1)].value;
f.elements["p"+(i+1)].focus();
f.buscarref.focus();
break;
}
}
}
function enterbuscar()
{
f=document.form1;
cuantos=f.buscarref.value.length;
maximo=<?print $cuantasfilas;?>;
referencia="";
for (i=0;i<maximo;i++)
{
if (f.elements["r"+(i+1)].value.substr(0,cuantos)==f.buscarref.value.toUpperCase())
{
referencia=f.elements["r"+(i+1)].value;
f.elements["p"+(i+1)].focus();
f.buscarref.focus();
break;
}
}
aceptar(f.elements["c"+(i+1)].value);
}
function tecla(e)
{
f=document.form1;
letra = String.fromCharCode(e.keyCode);
if (e.keyCode!=13)
{
//f.buscarref.value=letra;
mostrarreferencia(letra);
}
else
{
enterbuscar();
}
}
function ColorFila()
{
var rows = document.getElementsByTagName("tr");
for(var i in rows)
{
rows[i].onmouseover = function() { rows.className = "resaltar"; }
rows[i].onmouseout = function() { rows.className = null; }
}
}
</script>
</html>
| cidesa/roraima | web/cp/aplicaciones/presupuesto/catalogo2_ant.php | PHP | gpl-2.0 | 7,672 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Port of ns-2/tcl/ex/simple.tcl to ns-3
//
// Network topology
//
// n0 n1 n2 n3
// | | | |
// =====================
//
// - CBR/UDP flows from n0 to n1, and from n3 to n0
// - UDP packet size of 210 bytes, with per-packet interval 0.00375 sec.
// (i.e., DataRate of 448,000 bps)
// - DropTail queues
// - Tracing of queues and packet receptions to file "csma-one-subnet.tr"
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/core-module.h"
#include "ns3/simulator-module.h"
#include "ns3/node-module.h"
#include "ns3/helper-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("CsmaPacketSocketExample");
static void SinkRx (Ptr<const Packet> p, const Address &ad)
{
//std::cout << *p << std::endl;
}
int
main (int argc, char *argv[])
{
#if 0
LogComponentEnable ("CsmaPacketSocketExample", LOG_LEVEL_INFO);
#endif
CommandLine cmd;
cmd.Parse (argc, argv);
// Here, we will explicitly create four nodes.
NS_LOG_INFO ("Create nodes.");
NodeContainer c;
c.Create (4);
// connect all our nodes to a shared channel.
NS_LOG_INFO ("Build Topology.");
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", DataRateValue (DataRate (5000000)));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
csma.SetDeviceAttribute ("EncapsulationMode", StringValue ("Llc"));
NetDeviceContainer devs = csma.Install (c);
// add an ip stack to all nodes.
NS_LOG_INFO ("Add ip stack.");
InternetStackHelper ipStack;
ipStack.Install (c);
// assign ip addresses
NS_LOG_INFO ("Assign ip addresses.");
Ipv4AddressHelper ip;
ip.SetBase ("192.168.1.0", "255.255.255.0");
Ipv4InterfaceContainer addresses = ip.Assign (devs);
NS_LOG_INFO ("Create Source");
Config::SetDefault ("ns3::Ipv4RawSocketImpl::Protocol", StringValue ("2"));
InetSocketAddress dst = InetSocketAddress (addresses.GetAddress (3));
OnOffHelper onoff = OnOffHelper ("ns3::Ipv4RawSocketFactory", dst);
onoff.SetAttribute ("OnTime", RandomVariableValue (ConstantVariable (1.0)));
onoff.SetAttribute ("OffTime", RandomVariableValue (ConstantVariable (0.0)));
onoff.SetAttribute ("DataRate", DataRateValue (DataRate (6000)));
onoff.SetAttribute ("PacketSize", UintegerValue (1200));
ApplicationContainer apps = onoff.Install (c.Get (0));
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));
NS_LOG_INFO ("Create Sink.");
PacketSinkHelper sink = PacketSinkHelper ("ns3::Ipv4RawSocketFactory", dst);
apps = sink.Install (c.Get (3));
apps.Start (Seconds (0.0));
apps.Stop (Seconds (11.0));
NS_LOG_INFO ("Configure Tracing.");
// first, pcap tracing in non-promiscuous mode
csma.EnablePcapAll ("csma-raw-ip-socket", false);
// then, print what the packet sink receives.
Config::ConnectWithoutContext ("/NodeList/3/ApplicationList/0/$ns3::PacketSink/Rx",
MakeCallback (&SinkRx));
Packet::EnablePrinting ();
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
| tectronics/ns-3-dev-def-routing | examples/csma/csma-raw-ip-socket.cc | C++ | gpl-2.0 | 3,811 |
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.sql.ResultSet;
import java.util.Properties;
/** Generated Model for AD_ReplicationDocument
* @author Adempiere (generated)
* @version Release 3.7.0LTS - $Id$ */
public class X_AD_ReplicationDocument extends PO implements I_AD_ReplicationDocument, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20110831L;
/** Standard Constructor */
public X_AD_ReplicationDocument (Properties ctx, int AD_ReplicationDocument_ID, String trxName)
{
super (ctx, AD_ReplicationDocument_ID, trxName);
/** if (AD_ReplicationDocument_ID == 0)
{
setAD_ReplicationDocument_ID (0);
setAD_ReplicationStrategy_ID (0);
setAD_Table_ID (0);
setC_DocType_ID (0);
setReplicationType (null);
} */
}
/** Load Constructor */
public X_AD_ReplicationDocument (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 3 - Client - Org
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_ReplicationDocument[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Replication Document.
@param AD_ReplicationDocument_ID Replication Document */
public void setAD_ReplicationDocument_ID (int AD_ReplicationDocument_ID)
{
if (AD_ReplicationDocument_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_ReplicationDocument_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_ReplicationDocument_ID, Integer.valueOf(AD_ReplicationDocument_ID));
}
/** Get Replication Document.
@return Replication Document */
public int getAD_ReplicationDocument_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_ReplicationDocument_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Replication Strategy.
@param AD_ReplicationStrategy_ID
Data Replication Strategy
*/
public void setAD_ReplicationStrategy_ID (int AD_ReplicationStrategy_ID)
{
if (AD_ReplicationStrategy_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_ReplicationStrategy_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_ReplicationStrategy_ID, Integer.valueOf(AD_ReplicationStrategy_ID));
}
/** Get Replication Strategy.
@return Data Replication Strategy
*/
public int getAD_ReplicationStrategy_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_ReplicationStrategy_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Table getAD_Table() throws RuntimeException
{
return (org.compiere.model.I_AD_Table)MTable.get(getCtx(), org.compiere.model.I_AD_Table.Table_Name)
.getPO(getAD_Table_ID(), get_TrxName()); }
/** Set Table.
@param AD_Table_ID
Database Table information
*/
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get Table.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_C_DocType getC_DocType() throws RuntimeException
{
return (org.compiere.model.I_C_DocType)MTable.get(getCtx(), org.compiere.model.I_C_DocType.Table_Name)
.getPO(getC_DocType_ID(), get_TrxName()); }
/** Set Document Type.
@param C_DocType_ID
Document type or rules
*/
public void setC_DocType_ID (int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_Value (COLUMNNAME_C_DocType_ID, null);
else
set_Value (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID));
}
/** Get Document Type.
@return Document type or rules
*/
public int getC_DocType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** ReplicationType AD_Reference_ID=126 */
public static final int REPLICATIONTYPE_AD_Reference_ID=126;
/** Local = L */
public static final String REPLICATIONTYPE_Local = "L";
/** Merge = M */
public static final String REPLICATIONTYPE_Merge = "M";
/** Reference = R */
public static final String REPLICATIONTYPE_Reference = "R";
/** Broadcast = B */
public static final String REPLICATIONTYPE_Broadcast = "B";
/** Set Replication Type.
@param ReplicationType
Type of Data Replication
*/
public void setReplicationType (String ReplicationType)
{
set_Value (COLUMNNAME_ReplicationType, ReplicationType);
}
/** Get Replication Type.
@return Type of Data Replication
*/
public String getReplicationType ()
{
return (String)get_Value(COLUMNNAME_ReplicationType);
}
} | geneos/adempiere | base/src/org/compiere/model/X_AD_ReplicationDocument.java | Java | gpl-2.0 | 6,693 |
/* SPDX-License-Identifier: GPL-2.0-only */
#include <baseboard/variants.h>
#include <bootblock_common.h>
#include <ec/ec.h>
#include <soc/gpio.h>
void bootblock_mainboard_early_init(void)
{
const struct pad_config *pads;
size_t num;
pads = mainboard_early_bootblock_gpio_table(&num);
gpio_configure_pads(pads, num);
};
void bootblock_mainboard_init(void)
{
const struct pad_config *pads, *override_pads;
size_t num, override_num;
/*
* Perform EC init before configuring GPIOs. This is because variant
* might talk to the EC to get board id and hence it will require EC
* init to have already performed.
*/
mainboard_ec_init();
pads = variant_early_gpio_table(&num);
override_pads = variant_early_override_gpio_table(&override_num);
gpio_configure_pads_with_override(pads, num,
override_pads, override_num);
}
| pcengines/coreboot | src/mainboard/google/octopus/bootblock.c | C | gpl-2.0 | 838 |
<?php
/**
* @package Joomla.Libraries
* @subpackage Table
*
* @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('JPATH_PLATFORM') or die;
/**
* Content History table.
*
* @package Joomla.Libraries
* @subpackage Table
* @since 3.2
*/
class JTableContenthistory extends JTable
{
/**
* Array of object fields to unset from the data object before calculating SHA1 hash. This allows us to detect a meaningful change
* in the database row using the hash. This can be read from the #__content_types content_history_options column.
*
* @var array
* @since 3.2
*/
public $ignoreChanges = array();
/**
* Array of object fields to convert to integers before calculating SHA1 hash. Some values are stored differently
* when an item is created than when the item is changed and saved. This works around that issue.
* This can be read from the #__content_types content_history_options column.
*
* @var array
* @since 3.2
*/
public $convertToInt = array();
/**
* Constructor
*
* @param JDatabaseDriver $db A database connector object
*
* @since 3.1
*/
public function __construct($db)
{
parent::__construct('#__ucm_history', 'version_id', $db);
$this->ignoreChanges = array(
'modified_by',
'modified_user_id',
'modified',
'modified_time',
'checked_out',
'checked_out_time',
'version',
'hits',
'path');
$this->convertToInt = array('publish_up', 'publish_down', 'ordering', 'featured');
}
/**
* Overrides JTable::store to set modified hash, user id, and save date.
*
* @param boolean $updateNulls True to update fields even if they are null.
*
* @return boolean True on success.
*
* @since 3.2
*/
public function store($updateNulls = false)
{
$this->set('character_count', strlen($this->get('version_data')));
$typeTable = JTable::getInstance('Contenttype');
$typeTable->load($this->ucm_type_id);
if (!isset($this->sha1_hash))
{
$this->set('sha1_hash', $this->getSha1($this->get('version_data'), $typeTable));
}
$this->set('editor_user_id', JFactory::getUser()->id);
$this->set('save_date', JFactory::getDate()->toSql());
return parent::store($updateNulls);
}
/**
* Utility method to get the hash after removing selected values. This lets us detect changes other than
* modified date (which will change on every save).
*
* @param mixed $jsonData Either an object or a string with json-encoded data
* @param JTableContenttype $typeTable Table object with data for this content type
*
* @return string SHA1 hash on sucess. Empty string on failure.
*
* @since 3.2
*/
public function getSha1($jsonData, JTableContenttype $typeTable)
{
$object = (is_object($jsonData)) ? $jsonData : json_decode($jsonData);
if (isset($typeTable->content_history_options) && (is_object(json_decode($typeTable->content_history_options))))
{
$options = json_decode($typeTable->content_history_options);
$this->ignoreChanges = isset($options->ignoreChanges) ? $options->ignoreChanges : $this->ignoreChanges;
$this->convertToInt = isset($options->convertToInt) ? $options->convertToInt : $this->convertToInt;
}
foreach ($this->ignoreChanges as $remove)
{
if (property_exists($object, $remove))
{
unset($object->$remove);
}
}
// Convert integers, booleans, and nulls to strings to get a consistent hash value
foreach ($object as $name => $value)
{
if (is_object($value))
{
// Go one level down for JSON column values
foreach ($value as $subName => $subValue)
{
$object->$subName = (is_int($subValue) || is_bool($subValue) || is_null($subValue)) ? (string) $subValue : $subValue;
}
}
else
{
$object->$name = (is_int($value) || is_bool($value) || is_null($value)) ? (string) $value : $value;
}
}
// Work around empty values
foreach ($this->convertToInt as $convert)
{
if (isset($object->$convert))
{
$object->$convert = (int) $object->$convert;
}
}
if (isset($object->review_time))
{
$object->review_time = (int) $object->review_time;
}
return sha1(json_encode($object));
}
/**
* Utility method to get a matching row based on the hash value and id columns.
* This lets us check to make sure we don't save duplicate versions.
*
* @return string SHA1 hash on sucess. Empty string on failure.
*
* @since 3.2
*/
public function getHashMatch()
{
$db = $this->_db;
$query = $db->getQuery(true);
$query->select('*')
->from($db->quoteName('#__ucm_history'))
->where($db->quoteName('ucm_item_id') . ' = ' . $this->get('ucm_item_id'))
->where($db->quoteName('ucm_type_id') . ' = ' . $this->get('ucm_type_id'))
->where($db->quoteName('sha1_hash') . ' = ' . $db->quote($this->get('sha1_hash')));
$db->setQuery($query, 0, 1);
return $db->loadObject();
}
/**
* Utility method to remove the oldest versions of an item, saving only the most recent versions.
*
* @param integer $maxVersions The maximum number of versions to save. All others will be deleted.
*
* @return boolean true on sucess, false on failure.
*
* @since 3.2
*/
public function deleteOldVersions($maxVersions)
{
$result = true;
// Get the list of version_id values we want to save
$db = $this->_db;
$query = $db->getQuery(true);
$query->select($db->quoteName('version_id'))
->from($db->quoteName('#__ucm_history'))
->where($db->quoteName('ucm_item_id') . ' = ' . (int) $this->ucm_item_id)
->where($db->quoteName('ucm_type_id') . ' = ' . (int) $this->ucm_type_id)
->where($db->quoteName('keep_forever') . ' != 1')
->order($db->quoteName('save_date') . ' DESC ');
$db->setQuery($query, 0, (int) $maxVersions);
$idsToSave = $db->loadColumn(0);
// Don't process delete query unless we have at least the maximum allowed versions
if (count($idsToSave) == (int) $maxVersions)
{
// Delete any rows not in our list and and not flagged to keep forever.
$query = $db->getQuery(true);
$query->delete($db->quoteName('#__ucm_history'))
->where($db->quoteName('ucm_item_id') . ' = ' . (int) $this->ucm_item_id)
->where($db->quoteName('ucm_type_id') . ' = ' . (int) $this->ucm_type_id)
->where($db->quoteName('version_id') . ' NOT IN (' . implode(',', $idsToSave) . ')')
->where($db->quoteName('keep_forever') . ' != 1');
$db->setQuery($query);
$result = (boolean) $db->execute();
}
return $result;
}
}
| prokyhb/joomla | libraries/cms/table/contenthistory.php | PHP | gpl-2.0 | 6,619 |
// StickyJS Plugin for jQuery
// =============
// Author: Sebastian Dawidziak <sebastian@dawidziak.eu>
// Created: 6/20/2014
// Version: 0.0.6
(function($) {
"use strict";
var defaults = {
zIndex: null,
stopper: null,
topSpacing: 0,
bottomSpacing: 0,
className: 'is-sticky',
wrapperClassName: 'sticky-wrapper',
center: false,
getWidthFrom: null
},
$window = $(window),
$document = $(document),
sticked = [],
windowHeight = $window.height(),
scroller = function() {
var scrollTop = $window.scrollTop(),
documentHeight = $document.height(),
dwh = documentHeight - windowHeight,
extra = (scrollTop > dwh) ? dwh - scrollTop : 0;
for (var i = 0; i < sticked.length; i++) {
var s = sticked[i],
elementTop = s.stickyWrapper.offset().top,
etse = elementTop - s.topSpacing - extra,
inside = s.stopper != null ? $(s.stopper).find(s.stickyElement).length > 0 : false,
newStop = s.stopper != null ? (inside ? $(s.stopper).offset().top + $(s.stopper).outerHeight(true) : $(s.stopper).offset().top) : null,
newBottom = s.stickyElement.offset().top - s.stickyElement.outerHeight(true),
isStop = s.stopper != null ? ((scrollTop - newStop) + (scrollTop - newBottom) + s.topSpacing > 0) : false;
if (scrollTop <= etse) {
if (s.currentTop !== null) {
s.stickyElement
.css('position', '')
.css('top', '');
s.stickyElement.parent().removeClass(s.className);
s.currentTop = null;
}
} else {
var newTop = documentHeight - s.stickyElement.outerHeight(true) - s.topSpacing - s.bottomSpacing - scrollTop - extra;
if (newTop == 0) {
newTop = newTop + s.topSpacing;
} else if (isStop) {
newTop = (newStop - scrollTop) - s.stickyElement.outerHeight(true);
} else {
newTop = s.topSpacing;
}
if (s.currentTop != newTop) {
s.stickyElement
.css('position', 'fixed')
.css('top', newTop);
if (typeof s.getWidthFrom !== 'undefined') {
s.stickyElement.css('width', $(s.getWidthFrom).width());
}
s.stickyElement.parent().addClass(s.className);
s.currentTop = newTop;
}
}
}
},
resizer = function() {
windowHeight = $window.height();
},
methods = {
init: function(options) {
var o = $.extend(defaults, options);
return this.each(function() {
var stickyElement = $(this);
var stickyId = stickyElement.attr('id');
var wrapper = $('<div></div>')
.attr('id', stickyId + '-sticky-wrapper')
.addClass(o.wrapperClassName);
stickyElement.wrapAll(wrapper);
if (o.center) {
stickyElement.parent().css({
width: wrapper.outerWidth(true),
marginLeft: "auto",
marginRight: "auto"
});
}
stickyElement.parent().css({
width: stickyElement.outerWidth(true)
});
if (stickyElement.css("float") == "right") {
stickyElement.css({
"float": "none"
}).parent().css({
"float": "right"
});
}
var stickyWrapper = stickyElement.parent();
stickyWrapper.css('height', stickyElement.outerHeight(true));
sticked.push({
zIndex: o.zIndex,
stopper: o.stopper,
topSpacing: o.topSpacing,
bottomSpacing: o.bottomSpacing,
stickyElement: stickyElement,
currentTop: null,
stickyWrapper: stickyWrapper,
className: o.className,
getWidthFrom: o.getWidthFrom
});
if (typeof o.getWidthFrom !== 'undefined') {
stickyElement.css('width', $(o.getWidthFrom).width());
}
});
},
update: scroller,
unstick: function(options) {
return this.each(function() {
var unstickyElement = $(this);
removeIdx = -1;
for (var i = 0; i < sticked.length; i++) {
if (sticked[i].stickyElement.get(0) == unstickyElement.get(0)) {
removeIdx = i;
}
}
if (removeIdx != -1) {
sticked.splice(removeIdx, 1);
unstickyElement.unwrap();
unstickyElement.removeAttr('style');
}
});
}
};
if (window.addEventListener) {
window.addEventListener('scroll', scroller, false);
window.addEventListener('resize', resizer, false);
} else if (window.attachEvent) {
window.attachEvent('onscroll', scroller);
window.attachEvent('onresize', resizer);
}
$.fn.sticky = function(method) {
if (methods[method]) return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
else if (typeof method === 'object' || !method) return methods.init.apply(this, arguments);
else $.error('Method ' + method + ' does not exist on StickyJS');
};
$.fn.unstick = function(method) {
if (methods[method]) return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
else if (typeof method === 'object' || !method) return methods.unstick.apply(this, arguments);
else $.error('Method ' + method + ' does not exist on StickyJS');
};
$(function() {
setTimeout(scroller, 0);
});
})(jQuery); | tweetgeek/stickyjs | stickyjs.js | JavaScript | gpl-2.0 | 4,998 |
<?php
/**
* The Custom Header for our theme.
*
* Displays all of the <head> section and everything up till <div id="main">
*
*/
?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<?php
get_template_part('hdr','title');
?>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<?php
get_template_part('hdr','css');
?>
</head>
<body <?php body_class(); ?>>
<?php
if (!weaver_getopt_checked('ttw_header_first')) // put the header before the wrapper?
echo "<div id=\"wrapper\" class=\"hfeed\">\n";
$per_page_code = weaver_get_per_page_value('page-pre-header-code'); /* or on a per page basis! */
if (!empty($per_page_code)) {
echo(do_shortcode($per_page_code));
} else {
weaver_put_area('preheader'); /* here to allow total header replacement */
}
if (!weaver_is_checked_page_opt('ttw-hide-header')) { ?>
<div id="header">
<?php
if (is_active_sidebar('header-widget-area')) { /* weaver header widget area */
ob_start(); /* use output buffering */
$success = dynamic_sidebar('header-widget-area');
$content = ob_get_clean();
if ($success) {
?>
<div id="ttw-head-widget" class="ttw-head-widget-area" role="complementary" ><ul>
<?php echo($content) ; ?>
</ul></div> <!-- #ttw-header-widget -->
<?php
} /* end if non-empty widgets */
}
?>
<div id="masthead">
<?php
/* ======== SITE TITLE ======== */
get_template_part('hdr','sitetitle');
/* ======== TOP MENU ======== */
get_template_part('nav','top');
/* ======== HEADER INSERT CODE ======== */
echo("\n\t ".'<div id="branding" role="banner">' . "\n");
$per_page_code = weaver_get_per_page_value('page-header-insert-code'); /* or on a per page basis! */
if (!empty($per_page_code)) {
echo(do_shortcode($per_page_code));
} elseif (weaver_getopt('ttw_custom_header_insert')) { /* header insert defined? */
echo (do_shortcode(weaver_getopt('ttw_custom_header_insert')));
}
/* The Dynamic Headers shows headers on a per page basis - will also optionally add site link */
if (function_exists('show_media_header')) show_media_header(); /* **Dynamic Headers** built-in support for plugin */
?>
</div><!-- #branding -->
<?php
/* ======== BOTTOM MENU ======== */
get_template_part('nav','bottom');
?>
</div><!-- #masthead -->
</div><!-- #header -->
<?php
} /* end of hide whole header */
weaver_put_area('postheader');
?>
<?php if (weaver_getopt_checked('ttw_header_first')) echo "<div id=\"wrapper\" class=\"hfeed\">\n"; ?>
<div id="main">
| ulearn/spanishblogwp | wp-content/themes/weaver/header-custom.php | PHP | gpl-2.0 | 2,808 |
#ifndef ___TXWIDESCREENWRAPPER_H__
#define ___TXWIDESCREENWRAPPER_H__
#include <string>
#ifdef ANDROID
int tx_swprintf(wchar_t* ws, size_t len, const wchar_t* format, ...);
bool wccmp(const wchar_t* w1, const wchar_t* w2);
#define BUF_SIZE 2048
class tx_wstring {
public:
tx_wstring() {}
tx_wstring(const wchar_t * wstr);
tx_wstring(const tx_wstring & other);
void assign(const wchar_t * wstr);
void assign(const tx_wstring & wstr);
void append(const tx_wstring & wstr);
tx_wstring & operator=(const tx_wstring & other);
tx_wstring & operator+=(const tx_wstring & other);
tx_wstring & operator+=(const wchar_t * wstr);
tx_wstring operator+(const tx_wstring & wstr);
tx_wstring operator+(const wchar_t * wstr);
const wchar_t * c_str() const;
bool empty() const;
int compare(const wchar_t * wstr);
private:
std::wstring _wstring;
std::string _astring;
char cbuf[BUF_SIZE];
wchar_t wbuf[BUF_SIZE];
};
class dummyWString
{
public:
dummyWString(const char * _str);
const wchar_t * c_str() const {
return _wstr.c_str();
}
private:
std::wstring _wstr;
};
#define wst(A) dummyWString(A).c_str()
#else
#define tx_wstring std::wstring
#define tx_swprintf swprintf
#define wst(A) L##A
#define wccmp(A, B) A[0] == B[0]
#endif // ANDROID
#endif // ___TXWIDESCREENWRAPPER_H__
| MoochMcGee/GLideN64-X | src/GLideNHQ/osal/txWidestringWrapper.h | C | gpl-2.0 | 1,300 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--Converted with LaTeX2HTML 2008 (1.71)
original version by: Nikos Drakos, CBLU, University of Leeds
* revised and updated by: Marcus Hennecke, Ross Moore, Herb Swan
* with significant contributions from:
Jens Lippmann, Marek Rouchal, Martin Wilck and others -->
<HTML>
<HEAD>
<TITLE>Running unit tests</TITLE>
<META NAME="description" CONTENT="Running unit tests">
<META NAME="keywords" CONTENT="clamdoc">
<META NAME="resource-type" CONTENT="document">
<META NAME="distribution" CONTENT="global">
<META NAME="Generator" CONTENT="LaTeX2HTML v2008">
<META HTTP-EQUIV="Content-Style-Type" CONTENT="text/css">
<LINK REL="STYLESHEET" HREF="clamdoc.css">
<LINK REL="next" HREF="node18.html">
<LINK REL="previous" HREF="node16.html">
<LINK REL="up" HREF="node11.html">
<LINK REL="next" HREF="node18.html">
</HEAD>
<BODY >
<DIV CLASS="navigation"><!--Navigation Panel-->
<A NAME="tex2html439"
HREF="node18.html">
<IMG WIDTH="37" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="next" SRC="next.png"></A>
<A NAME="tex2html435"
HREF="node11.html">
<IMG WIDTH="26" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="up" SRC="up.png"></A>
<A NAME="tex2html429"
HREF="node16.html">
<IMG WIDTH="63" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="previous" SRC="prev.png"></A>
<A NAME="tex2html437"
HREF="node1.html">
<IMG WIDTH="65" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="contents" SRC="contents.png"></A>
<BR>
<B> Next:</B> <A NAME="tex2html440"
HREF="node18.html">Reporting a unit test</A>
<B> Up:</B> <A NAME="tex2html436"
HREF="node11.html">Installation</A>
<B> Previous:</B> <A NAME="tex2html430"
HREF="node16.html">Compilation with clamav-milter enabled</A>
<B> <A NAME="tex2html438"
HREF="node1.html">Contents</A></B>
<BR>
<BR></DIV>
<!--End of Navigation Panel-->
<H2><A NAME="SECTION00046000000000000000"></A><A NAME="unit-testing"></A>
<BR>
Running unit tests
</H2>
ClamAV includes unit tests that allow you to test that the compiled binaries work correctly on your platform.
<BR>
<BR>
The first step is to use your OS's package manager to install the <code>check</code> package.
If your OS doesn't have that package, you can download it from <TT><A NAME="tex2html11"
HREF="http://check.sourceforge.net/">http://check.sourceforge.net/</A></TT>,
build it and install it.
<BR>
<BR>
To help clamav's configure script locate <code>check</code>, it is recommended that you install <code>pkg-config</code>, preferably
using your OS's package manager, or from <TT><A NAME="tex2html12"
HREF="http://pkg-config.freedesktop.org">http://pkg-config.freedesktop.org</A></TT>.
<BR>
<BR>
The recommended way to run unit-tests is the following, which ensures you will get an error if unit tests cannot be built:
<A NAME="tex2html13"
HREF="footnode.html#foot167"><SUP><SPAN CLASS="arabic">7</SPAN></SUP></A> <PRE>
$ ./configure --enable-check
$ make
$ make check
</PRE>
When <code>make check</code> is finished, you should get a message similar to this:
<PRE>
==================
All 8 tests passed
==================
</PRE>
If a unit test fails, you get a message similar to the following.
Note that in older versions of make check may report failures due to
the absence of optional packages. Please make sure you have the
latest versions of the components noted in section /refsec:components.
See the next section on how to report a bug when a unit test fails.
<PRE>
========================================
1 of 8 tests failed
Please report to http://bugs.clamav.net/
========================================
</PRE>
If unit tests are disabled (and you didn't use -enable-check), you will get this message:
<PRE>
*** Unit tests disabled in this build
*** Use ./configure --enable-check to enable them
SKIP: check_clamav
PASS: check_clamd.sh
PASS: check_freshclam.sh
PASS: check_sigtool.sh
PASS: check_clamscan.sh
======================
All 4 tests passed
(1 tests were not run)
======================
</PRE>
Running <code>./configure --enable-check</code> should tell you why.
<P>
<DIV CLASS="navigation"><HR>
<!--Navigation Panel-->
<A NAME="tex2html439"
HREF="node18.html">
<IMG WIDTH="37" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="next" SRC="next.png"></A>
<A NAME="tex2html435"
HREF="node11.html">
<IMG WIDTH="26" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="up" SRC="up.png"></A>
<A NAME="tex2html429"
HREF="node16.html">
<IMG WIDTH="63" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="previous" SRC="prev.png"></A>
<A NAME="tex2html437"
HREF="node1.html">
<IMG WIDTH="65" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="contents" SRC="contents.png"></A>
<BR>
<B> Next:</B> <A NAME="tex2html440"
HREF="node18.html">Reporting a unit test</A>
<B> Up:</B> <A NAME="tex2html436"
HREF="node11.html">Installation</A>
<B> Previous:</B> <A NAME="tex2html430"
HREF="node16.html">Compilation with clamav-milter enabled</A>
<B> <A NAME="tex2html438"
HREF="node1.html">Contents</A></B> </DIV>
<!--End of Navigation Panel-->
<ADDRESS>
Cisco 2015-03-02
</ADDRESS>
</BODY>
</HTML>
| Distrotech/clamav | docs/html/node17.html | HTML | gpl-2.0 | 5,145 |
/**
* @file
* @brief This file contains exported structure for NAND
*
* OMAP's General Purpose Memory Controller (GPMC) has a NAND controller
* embedded. this file provides the platform data structure required to
* hook on to it.
*
* (C) Copyright 2008
* Texas Instruments, <www.ti.com>
* Nishanth Menon <x0nishan@ti.com>
*
* Originally from Linux kernel:
* http://linux.omap.com/pub/kernel/3430zoom/linux-ldp-v1.3.tar.gz
* include/asm-arm/arch-omap/nand.h
*
* Copyright (C) 2006 Micron Technology Inc.
* Author: Shahrom Sharif-Kashani
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#ifndef __ASM_OMAP_NAND_GPMC_H
#define __ASM_OMAP_NAND_GPMC_H
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_ecc.h>
enum gpmc_ecc_mode {
OMAP_ECC_SOFT,
OMAP_ECC_HAMMING_CODE_HW_ROMCODE,
OMAP_ECC_BCH4_CODE_HW,
OMAP_ECC_BCH8_CODE_HW,
OMAP_ECC_BCH8_CODE_HW_ROMCODE,
};
/** omap nand platform data structure */
struct gpmc_nand_platform_data {
/** Chip select you want to use */
int cs;
struct mtd_partition *parts;
int nr_parts;
/** If there are any special setups you'd want to do */
int (*nand_setup) (struct gpmc_nand_platform_data *);
/** ecc mode to use */
enum gpmc_ecc_mode ecc_mode;
/** setup any special options */
unsigned int options;
/** set up device access as 8,16 as per GPMC config */
char device_width;
/** Set this to WAITx+1, so GPMC WAIT0 will be 1 and so on. */
char wait_mon_pin;
/* if you like a custom oob use this. */
struct nand_ecclayout *oob;
/** gpmc config for nand */
struct gpmc_config *nand_cfg;
};
int omap_add_gpmc_nand_device(struct gpmc_nand_platform_data *pdata);
extern struct gpmc_config omap3_nand_cfg;
extern struct gpmc_config omap4_nand_cfg;
#endif /* __ASM_OMAP_NAND_GPMC_H */
| jkent/mini210s-barebox | arch/arm/mach-omap/include/mach/gpmc_nand.h | C | gpl-2.0 | 1,935 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration |
\\ / A nd | For copyright notice see file Copyright
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "fixedEnthalpyFvPatchScalarField.H"
#include "addToRunTimeSelectionTable.H"
#include "fvPatchFieldMapper.H"
#include "volFields.H"
#include "basicThermo.H"
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::fixedEnthalpyFvPatchScalarField::fixedEnthalpyFvPatchScalarField
(
const fvPatch& p,
const DimensionedField<scalar, volMesh>& iF
)
:
fixedValueFvPatchScalarField(p, iF)
{}
Foam::fixedEnthalpyFvPatchScalarField::fixedEnthalpyFvPatchScalarField
(
const fixedEnthalpyFvPatchScalarField& ptf,
const fvPatch& p,
const DimensionedField<scalar, volMesh>& iF,
const fvPatchFieldMapper& mapper
)
:
fixedValueFvPatchScalarField(ptf, p, iF, mapper)
{}
Foam::fixedEnthalpyFvPatchScalarField::fixedEnthalpyFvPatchScalarField
(
const fvPatch& p,
const DimensionedField<scalar, volMesh>& iF,
const dictionary& dict
)
:
fixedValueFvPatchScalarField(p, iF, dict)
{}
Foam::fixedEnthalpyFvPatchScalarField::fixedEnthalpyFvPatchScalarField
(
const fixedEnthalpyFvPatchScalarField& tppsf
)
:
fixedValueFvPatchScalarField(tppsf)
{}
Foam::fixedEnthalpyFvPatchScalarField::fixedEnthalpyFvPatchScalarField
(
const fixedEnthalpyFvPatchScalarField& tppsf,
const DimensionedField<scalar, volMesh>& iF
)
:
fixedValueFvPatchScalarField(tppsf, iF)
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
void Foam::fixedEnthalpyFvPatchScalarField::updateCoeffs()
{
if (updated())
{
return;
}
const basicThermo& thermo = db().lookupObject<basicThermo>
(
"thermophysicalProperties"
);
const label patchi = patch().index();
fvPatchScalarField& Tw =
const_cast<fvPatchScalarField&>(thermo.T().boundaryField()[patchi]);
Tw.evaluate();
if (dimensionedInternalField().name() == db().mangleFileName("h"))
{
operator==(thermo.h(Tw, patchi));
}
else
{
operator==(thermo.hs(Tw, patchi));
}
fixedValueFvPatchScalarField::updateCoeffs();
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
makePatchTypeField
(
fvPatchScalarField,
fixedEnthalpyFvPatchScalarField
);
}
// ************************************************************************* //
| martinep/foam-extend-3.0 | src/thermophysicalModels/basic/derivedFvPatchFields/fixedEnthalpy/fixedEnthalpyFvPatchScalarField.C | C++ | gpl-2.0 | 3,509 |
<?php
include_once('../config/symbini.php');
include_once($serverRoot.'/classes/ChecklistAdmin.php');
$clid = array_key_exists("clid",$_REQUEST)?$_REQUEST["clid"]:0;
$pid = array_key_exists("pid",$_REQUEST)?$_REQUEST["pid"]:"";
$clManager = new ChecklistAdmin();
$clManager->setClid($clid);
?>
<!-- inner text -->
<div id="innertext" style="background-color:white;">
<div style="float:right;">
<a href="#" onclick="toggle('addchilddiv')"><img src="../images/add.png" /></a>
</div>
<div style="margin:15px;font-weight:bold;font-size:120%;">
<u>Children Checklists</u>
</div>
<div style="margin:25px;clear:both;">
Checklists will inherit scientific names, vouchers, notes, etc from all children checklists.
Adding a new taxon or voucher to a child checklist will automatically add it to all parent checklists.
The parent child relationship can transcend multiple levels (e.g. country <- state <- county).
Note that only direct child can be removed.
</div>
<div id="addchilddiv" style="margin:15px;display:none;">
<fieldset style="padding:15px;">
<legend><b>Link New Checklist</b></legend>
<form name="addchildform" target="checklistadmin.php" method="post" onsubmit="validateAddChildForm(this)">
<div style="margin:10px;">
<select name="clidadd">
<option value="">Select Child Checklist</option>
<option value="">-------------------------------</option>
<?php
$clArr = $clManager->getChildSelectArr();
foreach($clArr as $k => $name){
echo '<option value="'.$k.'">'.$name.'</option>';
}
?>
</select>
</div>
<div style="margin:10px;">
<input name="submitaction" type="submit" value="Add Child Checklist" />
<input name="clid" type="hidden" value="<?php echo $clid; ?>" />
<input name="pid" type="hidden" value="<?php echo $pid; ?>" />
<input name="tabindex" type="hidden" value="2" />
</div>
</form>
</fieldset>
</div>
<div style="margin:15px;">
<ul>
<?php
if($childArr = $clManager->getChildrenChecklist()){
foreach($childArr as $k => $cArr){
?>
<li>
<a href="checklist.php?cl=<?php echo $k; ?>"><?php echo $cArr['name']; ?></a>
<?php
if($cArr['pclid'] == $clid){
echo '<a href="checklistadmin.php?submitaction=delchild&tabindex=2&cliddel='.$k.'&clid='.$clid.'&pid='.$pid.'" onclick="return confirm(\'Are you sure you want to remove'.$cArr['name'].' as a child checklist?\')"><img src="../images/del.png" style="width:14px;" /></a>';
}
?>
</li>
<?php
}
}
else{
echo '<div style="font-size:110%;">There are no Children Checklists</div>';
}
?>
</ul>
</div>
<div style="margin:30px 15px;font-weight:bold;font-size:120%;">
<u>Parent Checklists</u>
</div>
<div style="margin:15px;">
<ul>
<?php
if($parentArr = $clManager->getParentChecklists()){
foreach($parentArr as $k => $name){
?>
<li>
<a href="checklist.php?cl=<?php echo $k; ?>"><?php echo $name; ?></a>
</li>
<?php
}
}
else{
echo '<div style="font-size:110%;">There are no Parent Checklists</div>';
}
?>
</ul>
</div>
</div> | seltmann/Symbiota | checklists/checklistadminchildren.php | PHP | gpl-2.0 | 3,267 |
<?php if (!defined('APPLICATION')) exit();
$User = val('User', Gdn::controller());
if (!$User && Gdn::session()->isValid()) {
$User = Gdn::session()->User;
}
if (!$User) {
return;
}
$Photo = $User->Photo;
if ($Photo) {
$Photo = (isUrl($Photo)) ? $Photo : Gdn_Upload::url(changeBasename($Photo, 'p%s'));
$PhotoAlt = t('Avatar');
} else {
$Photo = UserModel::getDefaultAvatarUrl($User, 'profile');
$PhotoAlt = t('Default Avatar');
}
if ($User->Banned) {
$BannedPhoto = c('Garden.BannedPhoto', 'https://images.v-cdn.net/banned_large.png');
if ($BannedPhoto) {
$Photo = Gdn_Upload::url($BannedPhoto);
}
}
if ($Photo) : ?>
<div class="Photo PhotoWrap PhotoWrapLarge <?php echo val('_CssClass', $User); ?>">
<?php
$canEditPhotos = Gdn::session()->checkRankedPermission(c('Garden.Profile.EditPhotos', true)) || checkPermission('Garden.Users.Edit');
if (!$User->Banned && $canEditPhotos && (Gdn::session()->UserID == $User->UserID || checkPermission('Garden.Users.Edit'))) {
echo anchor(wrap(t('Change Picture')), '/profile/picture?userid='.$User->UserID, 'ChangePicture Popup');
}
echo img($Photo, ['class' => 'ProfilePhotoLarge', 'alt' => $PhotoAlt]);
?>
</div>
<?php elseif ($User->UserID == Gdn::session()->UserID || Gdn::session()->checkPermission('Garden.Users.Edit')) : ?>
<div class="Photo">
<?php echo anchor(t('Add a Profile Picture'), '/profile/picture?userid='.$User->UserID, 'AddPicture BigButton'); ?>
</div>
<?php
endif;
| rwmcoder/Vanilla | applications/dashboard/views/modules/userphoto.php | PHP | gpl-2.0 | 1,563 |
package miscperipherals.util;
import java.util.LinkedList;
import java.util.List;
public class BFMachine implements Runnable {
private String code;
private String input;
private List<BFEventHandler> handlers = new LinkedList<BFEventHandler>();
public String output;
private int pc = 0;
private int head = 0;
private int[] tape = new int[256];
private int inputHead = -1;
private int depth = 0;
private int[] depthpos = new int[256];
public BFMachine(String code) throws BFException {
setCode(code);
}
public void setCode(String code) throws BFException {
int open = 0;
int close = 0;
for (int i = 0; i < code.length(); i++) {
char c = code.charAt(i);
if (c == '[') open++;
else if (c == ']') close++;
}
if (open != close) throw new BFException("parse error: unmatched brackets: " + open + " != " + close);
this.code = code;
}
public void setInput(String input) {
this.input = input;
}
public void addEventHandler(BFEventHandler handler) {
handlers.add(handler);
}
public boolean tick() throws BFException {
if (pc >= code.length()) {
for (BFEventHandler handler : handlers) handler.onEnd(output);
return false;
}
char c = code.charAt(pc);
switch (c) {
case '>': {
if (++head > tape.length) head = 0;
pc++;
break;
}
case '<': {
if (--head < 0) head = tape.length - 1;
pc++;
break;
}
case '+': {
tape[head]++;
pc++;
break;
}
case '-': {
tape[head]--;
pc++;
break;
}
case '.': {
for (BFEventHandler handler : handlers) handler.onOutput(output, "" + (char)tape[head]);
output += (char)tape[head];
pc++;
break;
}
case ',': {
if (input == null || ++inputHead >= input.length()) {
throw new BFException("at " + pc + ": reading beyond input size");
}
tape[head] = input.charAt(inputHead);
pc++;
break;
}
case '[': {
depth++;
if (depth >= depthpos.length) {
throw new BFException("at " + pc + ": code is too deep");
}
depthpos[depth] = pc;
if (tape[head] != 0) pc++;
else {
int j = 0;
while (j < depth) {
pc++;
if (code.charAt(pc) == ']') j++;
}
pc++;
}
break;
}
case ']': {
if (tape[head] != 0) pc = depthpos[depth];
else pc++;
depth--;
break;
}
case '$': {
for (BFEventHandler handler : handlers) handler.onInsta(tape[head]);
pc++;
break;
}
default: {
pc++;
break;
}
}
return true;
}
/**
* Autonomous run
*/
@Override
public void run() {
try {
while (tick()) {}
} catch (BFException e) {
for (BFEventHandler handler : handlers) handler.onError(e);
}
}
public static class BFException extends IllegalStateException {
public BFException(String s) {
super(s);
}
}
public static interface BFEventHandler {
public void onError(BFException e);
public void onInsta(int value);
public void onOutput(String output, String add);
public void onEnd(String output);
}
/** Ye olde BF machine
private static class BFExecutor implements Runnable {
private final IComputerAccess computer;
private final double id;
private final String code;
private final String input;
public BFExecutor(IComputerAccess computer, double id, String code, String input) {
this.computer = computer;
this.id = id;
this.code = code;
this.input = input;
}
@Override
public void run() {
try {
execute();
} catch (Throwable e) {
computer.queueEvent("bf_fail", new Object[] {id, e.getClass() == Exception.class ? e.getMessage() : e.toString()});
}
}
private void execute() throws Exception {
int head = 0;
int[] tape = new int[256];
int inputHead = -1;
int depth = 0;
int[] depthpos = new int[256];
int open = 0;
int close = 0;
for (int i = 0; i < code.length(); i++) {
char c = code.charAt(i);
if (c == '[') open++;
else if (c == ']') close++;
}
if (open != close) throw new Exception("parse error: unmatched brackets: "+open+" != "+close);
String output = "";
long start = System.currentTimeMillis();
int i = 0;
while (i < code.length()) {
char c = code.charAt(i);
switch (c) {
case '>': {
if (++head > tape.length) throw new Exception("at "+i+": seeking after tape length of "+tape.length);
i++;
break;
}
case '<': {
if (--head < 0) throw new Exception("at "+i+": seeking before tape start");
i++;
break;
}
case '+': {
tape[head]++;
i++;
break;
}
case '-': {
tape[head]--;
i++;
break;
}
case '.': {
output += (char)tape[head];
i++;
break;
}
case ',': {
if (input == null || ++inputHead >= input.length()) {
throw new Exception("at "+i+": reading beyond input size");
}
tape[head] = input.charAt(inputHead);
i++;
break;
}
case '[': {
depth++;
depthpos[depth] = i;
if (tape[head] != 0) i++;
else {
int j = 0;
while (j < depth) {
i++;
if (code.charAt(i) == ']') j++;
}
i++;
}
break;
}
case ']': {
if (tape[head] != 0) i = depthpos[depth];
else i++;
depth--;
break;
}
case '$': {
computer.queueEvent("bf_insta", new Object[] {id, tape[head]});
i++;
break;
}
default: {
i++;
break;
}
}
if (System.currentTimeMillis() - start > 10000L) throw new Exception("executing for too long");
}
computer.queueEvent("bf_done", new Object[] {id, output});
}
}
*/
}
| TheCodingMonster/PeripheralsPlusPlus | src/api/resources/reference/miscperipherals/util/BFMachine.java | Java | gpl-2.0 | 5,731 |
//** Smooth Navigational Menu- By Dynamic Drive DHTML code library: http://www.dynamicdrive.com
//** Script Download/ instructions page: http://www.dynamicdrive.com/dynamicindex1/ddlevelsmenu/
//** Menu created: Nov 12, 2008
//** Dec 12th, 08" (v1.01): Fixed Shadow issue when multiple LIs within the same UL (level) contain sub menus: http://www.dynamicdrive.com/forums/showthread.php?t=39177&highlight=smooth
//** Feb 11th, 09" (v1.02): The currently active main menu item (LI A) now gets a CSS class of ".selected", including sub menu items.
//** May 1st, 09" (v1.3):
//** 1) Now supports vertical (side bar) menu mode- set "orientation" to 'v'
//** 2) In IE6, shadows are now always disabled
//** July 27th, 09" (v1.31): Fixed bug so shadows can be disabled if desired.
//** Feb 2nd, 10" (v1.4): Adds ability to specify delay before sub menus appear and disappear, respectively. See showhidedelay variable below
//** Dec 17th, 10" (v1.5): Updated menu shadow to use CSS3 box shadows when the browser is FF3.5+, IE9+, Opera9.5+, or Safari3+/Chrome. Only .js file changed.
var ddsmoothmenu={
//Specify full URL to down and right arrow images (23 is padding-right added to top level LIs with drop downs):
arrowimages: {down:['downarrowclass', './img/down.gif', 23], right:['rightarrowclass', './img/right.gif']},
transition: {overtime:300, outtime:300}, //duration of slide in/ out animation, in milliseconds
shadow: {enable:false, offsetx:5, offsety:5}, //enable shadow?
showhidedelay: {showdelay: 100, hidedelay: 200}, //set delay in milliseconds before sub menus appear and disappear, respectively
///////Stop configuring beyond here///////////////////////////
detectwebkit: navigator.userAgent.toLowerCase().indexOf("applewebkit")!=-1, //detect WebKit browsers (Safari, Chrome etc)
detectie6: document.all && !window.XMLHttpRequest,
css3support: window.msPerformance || (!document.all && document.querySelector), //detect browsers that support CSS3 box shadows (ie9+ or FF3.5+, Safari3+, Chrome etc)
getajaxmenu:function($, setting){ //function to fetch external page containing the panel DIVs
var $menucontainer=$('#'+setting.contentsource[0]) //reference empty div on page that will hold menu
$menucontainer.html("Loading Menu...")
$.ajax({
url: setting.contentsource[1], //path to external menu file
async: true,
error:function(ajaxrequest){
$menucontainer.html('Error fetching content. Server Response: '+ajaxrequest.responseText)
},
success:function(content){
$menucontainer.html(content)
ddsmoothmenu.buildmenu($, setting)
}
})
},
buildmenu:function($, setting){
var smoothmenu=ddsmoothmenu
var $mainmenu=$("#"+setting.mainmenuid+">ul") //reference main menu UL
$mainmenu.parent().get(0).className=setting.classname || "ddsmoothmenu"
var $headers=$mainmenu.find("ul").parent()
$headers.hover(
function(e){
$(this).children('a:eq(0)').addClass('selected')
},
function(e){
$(this).children('a:eq(0)').removeClass('selected')
}
)
$headers.each(function(i){ //loop through each LI header
var $curobj=$(this).css({zIndex: 100-i}) //reference current LI header
var $subul=$(this).find('ul:eq(0)').css({display:'block'})
$subul.data('timers', {})
this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
this.istopheader=$curobj.parents("ul").length==1? true : false //is top level header?
$subul.css({top:this.istopheader && setting.orientation!='v'? this._dimensions.h+"px" : 0})
$curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: smoothmenu.arrowimages.down[2]} : {}).append( //add arrow images
'<img src="'+ (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[1] : smoothmenu.arrowimages.right[1])
+'" class="' + (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[0] : smoothmenu.arrowimages.right[0])
+ '" style="border:0;" />'
)
if (smoothmenu.shadow.enable && !smoothmenu.css3support){ //if shadows enabled and browser doesn't support CSS3 box shadows
this._shadowoffset={x:(this.istopheader?$subul.offset().left+smoothmenu.shadow.offsetx : this._dimensions.w), y:(this.istopheader? $subul.offset().top+smoothmenu.shadow.offsety : $curobj.position().top)} //store this shadow's offsets
if (this.istopheader)
$parentshadow=$(document.body)
else{
var $parentLi=$curobj.parents("li:eq(0)")
$parentshadow=$parentLi.get(0).$shadow
}
this.$shadow=$('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'}) //insert shadow DIV and set it to parent node for the next shadow div
}
$curobj.hover(
function(e){
var $targetul=$subul //reference UL to reveal
var header=$curobj.get(0) //reference header LI as DOM object
clearTimeout($targetul.data('timers').hidetimer)
$targetul.data('timers').showtimer=setTimeout(function(){
header._offsets={left:$curobj.offset().left, top:$curobj.offset().top}
var menuleft=header.istopheader && setting.orientation!='v'? 0 : header._dimensions.w
menuleft=(header._offsets.left+menuleft+header._dimensions.subulw>$(window).width())? (header.istopheader && setting.orientation!='v'? -header._dimensions.subulw+header._dimensions.w : -header._dimensions.w) : menuleft //calculate this sub menu's offsets from its parent
if ($targetul.queue().length<=1){ //if 1 or less queued animations
$targetul.css({left:menuleft+"px", width:header._dimensions.subulw+'px'}).animate({height:'show',opacity:'show'}, ddsmoothmenu.transition.overtime)
if (smoothmenu.shadow.enable && !smoothmenu.css3support){
var shadowleft=header.istopheader? $targetul.offset().left+ddsmoothmenu.shadow.offsetx : menuleft
var shadowtop=header.istopheader?$targetul.offset().top+smoothmenu.shadow.offsety : header._shadowoffset.y
if (!header.istopheader && ddsmoothmenu.detectwebkit){ //in WebKit browsers, restore shadow's opacity to full
header.$shadow.css({opacity:1})
}
header.$shadow.css({overflow:'', width:header._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'}).animate({height:header._dimensions.subulh+'px'}, ddsmoothmenu.transition.overtime)
}
}
}, ddsmoothmenu.showhidedelay.showdelay)
},
function(e){
var $targetul=$subul
var header=$curobj.get(0)
clearTimeout($targetul.data('timers').showtimer)
$targetul.data('timers').hidetimer=setTimeout(function(){
$targetul.animate({height:'hide', opacity:'hide'}, ddsmoothmenu.transition.outtime)
if (smoothmenu.shadow.enable && !smoothmenu.css3support){
if (ddsmoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them
header.$shadow.children('div:eq(0)').css({opacity:0})
}
header.$shadow.css({overflow:'hidden'}).animate({height:0}, ddsmoothmenu.transition.outtime)
}
}, ddsmoothmenu.showhidedelay.hidedelay)
}
) //end hover
}) //end $headers.each()
if (smoothmenu.shadow.enable && smoothmenu.css3support){ //if shadows enabled and browser supports CSS3 shadows
var $toplevelul=$('#'+setting.mainmenuid+' ul li ul')
var css3shadow=parseInt(smoothmenu.shadow.offsetx)+"px "+parseInt(smoothmenu.shadow.offsety)+"px 5px #aaa" //construct CSS3 box-shadow value
var shadowprop=["boxShadow", "MozBoxShadow", "WebkitBoxShadow", "MsBoxShadow"] //possible vendor specific CSS3 shadow properties
for (var i=0; i<shadowprop.length; i++){
$toplevelul.css(shadowprop[i], css3shadow)
}
}
$mainmenu.find("ul").css({display:'none', visibility:'visible'})
},
init:function(setting){
if (typeof setting.customtheme=="object" && setting.customtheme.length==2){ //override default menu colors (default/hover) with custom set?
var mainmenuid='#'+setting.mainmenuid
var mainselector=(setting.orientation=="v")? mainmenuid : mainmenuid+', '+mainmenuid
document.write('<style type="text/css">\n'
+mainselector+' ul li a {background:'+setting.customtheme[0]+';}\n'
+mainmenuid+' ul li a:hover {background:'+setting.customtheme[1]+';}\n'
+'</style>')
}
this.shadow.enable=(document.all && !window.XMLHttpRequest)? false : this.shadow.enable //in IE6, always disable shadow
jQuery(document).ready(function($){ //ajax menu?
if (typeof setting.contentsource=="object"){ //if external ajax menu
ddsmoothmenu.getajaxmenu($, setting)
}
else{ //else if markup menu
ddsmoothmenu.buildmenu($, setting)
}
})
}
} //end ddsmoothmenu variable | eddylecca/smeagol | themes/igp/js/ddsmoothmenu.js | JavaScript | gpl-2.0 | 8,635 |
/*
* util.h
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License Version 2 as
* published by the Free Software Foundation. You may not use, modify or
* distribute this program under any other version of the GNU General
* Public License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Copyright (C) 2014 Cisco and/or its affiliates. All rights reserved.
* Copyright (C) 2005-2013 Sourcefire, Inc.
*
*/
#ifndef __HI_UTIL_XMALLOC_H__
#define __HI_UTIL_XMALLOC_H__
#ifdef WIN32
#define snprintf _snprintf
#else
#include <sys/types.h>
#endif
void *xmalloc(size_t byteSize);
char *xstrdup(const char *str);
void xshowmem(void);
void xfree( void * );
#endif
| adwisatya/snort_ids | src/dynamic-preprocessors/ftptelnet/hi_util_xmalloc.h | C | gpl-2.0 | 1,174 |
/*
* Copyright (C) 2002 David Howells (dhowells@redhat.com)
* Copyright 2010 Tilera Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, version 2.
*
* 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, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*/
#ifndef _ASM_TILE_THREAD_INFO_H
#define _ASM_TILE_THREAD_INFO_H
#include <asm/processor.h>
#include <asm/page.h>
#ifndef __ASSEMBLY__
/*
* Low level task data that assembly code needs immediate access to.
* The structure is placed at the bottom of the supervisor stack.
*/
struct thread_info {
struct task_struct *task; /* main task structure */
struct exec_domain *exec_domain; /* execution domain */
unsigned long flags; /* low level flags */
unsigned long status; /* thread-synchronous flags */
__u32 homecache_cpu; /* CPU we are homecached on */
__u32 cpu; /* current CPU */
int preempt_count; /* 0 => preemptable,
<0 => BUG */
mm_segment_t addr_limit; /* thread address space
(KERNEL_DS or USER_DS) */
struct restart_block restart_block;
struct single_step_state *step_state; /* single step state
(if non-zero) */
};
/*
* macros/functions for gaining access to the thread information structure.
*/
#define INIT_THREAD_INFO(tsk) \
{ \
.task = &tsk, \
.exec_domain = &default_exec_domain, \
.flags = 0, \
.cpu = 0, \
.preempt_count = INIT_PREEMPT_COUNT, \
.addr_limit = KERNEL_DS, \
.restart_block = { \
.fn = do_no_restart_syscall, \
}, \
.step_state = NULL, \
}
#define init_thread_info (init_thread_union.thread_info)
#define init_stack (init_thread_union.stack)
#endif /* !__ASSEMBLY__ */
#if PAGE_SIZE < 8192
#define THREAD_SIZE_ORDER (13 - PAGE_SHIFT)
#else
#define THREAD_SIZE_ORDER (0)
#endif
#define THREAD_SIZE_PAGES (1 << THREAD_SIZE_ORDER)
#define THREAD_SIZE (PAGE_SIZE << THREAD_SIZE_ORDER)
#define LOG2_THREAD_SIZE (PAGE_SHIFT + THREAD_SIZE_ORDER)
#define STACK_WARN (THREAD_SIZE/8)
#ifndef __ASSEMBLY__
void arch_release_thread_info(struct thread_info *info);
/* How to get the thread information struct from C. */
register unsigned long stack_pointer __asm__("sp");
#define current_thread_info() \
((struct thread_info *)(stack_pointer & -THREAD_SIZE))
/* Sit on a nap instruction until interrupted. */
extern void smp_nap(void);
/* Enable interrupts racelessly and nap forever: helper for cpu_idle(). */
extern void _cpu_idle(void);
#else /* __ASSEMBLY__ */
/*
* How to get the thread information struct from assembly.
* Note that we use different macros since different architectures
* have different semantics in their "mm" instruction and we would
* like to guarantee that the macro expands to exactly one instruction.
*/
#ifdef __tilegx__
#define EXTRACT_THREAD_INFO(reg) mm reg, zero, LOG2_THREAD_SIZE, 63
#else
#define GET_THREAD_INFO(reg) mm reg, sp, zero, LOG2_THREAD_SIZE, 31
#endif
#endif /* !__ASSEMBLY__ */
#define PREEMPT_ACTIVE 0x10000000
/*
* Thread information flags that various assembly files may need to access.
* Keep flags accessed frequently in low bits, particular since it makes
* it easier to build constants in assembly.
*/
#define TIF_SIGPENDING 0 /* signal pending */
#define TIF_NEED_RESCHED 1 /* rescheduling necessary */
#define TIF_SINGLESTEP 2 /* restore singlestep on return to
user mode */
#define TIF_ASYNC_TLB 3 /* got an async TLB fault in kernel */
#define TIF_SYSCALL_TRACE 4 /* syscall trace active */
#define TIF_SYSCALL_AUDIT 5 /* syscall auditing active */
#define TIF_SECCOMP 6 /* secure computing */
#define TIF_MEMDIE 7 /* OOM killer at work */
#define TIF_NOTIFY_RESUME 8 /* callback before returning to user */
#define TIF_SYSCALL_TRACEPOINT 9 /* syscall tracepoint instrumentation */
#define _TIF_SIGPENDING (1<<TIF_SIGPENDING)
#define _TIF_NEED_RESCHED (1<<TIF_NEED_RESCHED)
#define _TIF_SINGLESTEP (1<<TIF_SINGLESTEP)
#define _TIF_ASYNC_TLB (1<<TIF_ASYNC_TLB)
#define _TIF_SYSCALL_TRACE (1<<TIF_SYSCALL_TRACE)
#define _TIF_SYSCALL_AUDIT (1<<TIF_SYSCALL_AUDIT)
#define _TIF_SECCOMP (1<<TIF_SECCOMP)
#define _TIF_MEMDIE (1<<TIF_MEMDIE)
#define _TIF_NOTIFY_RESUME (1<<TIF_NOTIFY_RESUME)
#define _TIF_SYSCALL_TRACEPOINT (1<<TIF_SYSCALL_TRACEPOINT)
/* Work to do on any return to user space. */
#define _TIF_ALLWORK_MASK \
(_TIF_SIGPENDING|_TIF_NEED_RESCHED|_TIF_SINGLESTEP|\
_TIF_ASYNC_TLB|_TIF_NOTIFY_RESUME)
/* Work to do at syscall entry. */
#define _TIF_SYSCALL_ENTRY_WORK (_TIF_SYSCALL_TRACE | _TIF_SYSCALL_TRACEPOINT)
/* Work to do at syscall exit. */
#define _TIF_SYSCALL_EXIT_WORK (_TIF_SYSCALL_TRACE | _TIF_SYSCALL_TRACEPOINT)
/*
* Thread-synchronous status.
*
* This is different from the flags in that nobody else
* ever touches our thread-synchronous status, so we don't
* have to worry about atomic accesses.
*/
#ifdef __tilegx__
#define TS_COMPAT 0x0001 /* 32-bit compatibility mode */
#endif
#define TS_POLLING 0x0004 /* in idle loop but not sleeping */
#define TS_RESTORE_SIGMASK 0x0008 /* restore signal mask in do_signal */
#define tsk_is_polling(t) (task_thread_info(t)->status & TS_POLLING)
#ifndef __ASSEMBLY__
#define HAVE_SET_RESTORE_SIGMASK 1
static inline void set_restore_sigmask(void)
{
struct thread_info *ti = current_thread_info();
ti->status |= TS_RESTORE_SIGMASK;
WARN_ON(!test_bit(TIF_SIGPENDING, &ti->flags));
}
static inline void clear_restore_sigmask(void)
{
current_thread_info()->status &= ~TS_RESTORE_SIGMASK;
}
static inline bool test_restore_sigmask(void)
{
return current_thread_info()->status & TS_RESTORE_SIGMASK;
}
static inline bool test_and_clear_restore_sigmask(void)
{
struct thread_info *ti = current_thread_info();
if (!(ti->status & TS_RESTORE_SIGMASK))
return false;
ti->status &= ~TS_RESTORE_SIGMASK;
return true;
}
#endif /* !__ASSEMBLY__ */
#endif /* _ASM_TILE_THREAD_INFO_H */
| Oleh-Kravchenko/asusp535 | arch/tile/include/asm/thread_info.h | C | gpl-2.0 | 6,206 |
<?php
abstract class BaseCscodtaller extends BaseObject implements Persistent {
protected static $peer;
protected $codart;
protected $id;
protected $alreadyInSave = false;
protected $alreadyInValidation = false;
public function getCodart()
{
return trim($this->codart);
}
public function getId()
{
return $this->id;
}
public function setCodart($v)
{
if ($this->codart !== $v) {
$this->codart = $v;
$this->modifiedColumns[] = CscodtallerPeer::CODART;
}
}
public function setId($v)
{
if ($this->id !== $v) {
$this->id = $v;
$this->modifiedColumns[] = CscodtallerPeer::ID;
}
}
public function hydrate(ResultSet $rs, $startcol = 1)
{
try {
$this->codart = $rs->getString($startcol + 0);
$this->id = $rs->getInt($startcol + 1);
$this->resetModified();
$this->setNew(false);
$this->afterHydrate();
return $startcol + 2;
} catch (Exception $e) {
throw new PropelException("Error populating Cscodtaller object", $e);
}
}
protected function afterHydrate()
{
}
public function __call($m, $a)
{
$prefijo = substr($m,0,3);
$metodo = strtolower(substr($m,3));
if($prefijo=='get'){
if(isset($this->$metodo)) return $this->$metodo;
else return '';
}elseif($prefijo=='set'){
if(isset($this->$metodo)) $this->$metodo = $a[0];
}else call_user_func_array($m, $a);
}
public function delete($con = null)
{
if ($this->isDeleted()) {
throw new PropelException("This object has already been deleted.");
}
if ($con === null) {
$con = Propel::getConnection(CscodtallerPeer::DATABASE_NAME);
}
try {
$con->begin();
CscodtallerPeer::doDelete($this, $con);
$this->setDeleted(true);
$con->commit();
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
public function save($con = null)
{
if ($this->isDeleted()) {
throw new PropelException("You cannot save an object that has been deleted.");
}
if ($con === null) {
$con = Propel::getConnection(CscodtallerPeer::DATABASE_NAME);
}
try {
$con->begin();
$affectedRows = $this->doSave($con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
protected function doSave($con)
{
$affectedRows = 0; if (!$this->alreadyInSave) {
$this->alreadyInSave = true;
if ($this->isModified()) {
if ($this->isNew()) {
$pk = CscodtallerPeer::doInsert($this, $con);
$affectedRows += 1;
$this->setNew(false);
} else {
$affectedRows += CscodtallerPeer::doUpdate($this, $con);
}
$this->resetModified(); }
$this->alreadyInSave = false;
}
return $affectedRows;
}
protected $validationFailures = array();
public function getValidationFailures()
{
return $this->validationFailures;
}
public function validate($columns = null)
{
$res = $this->doValidate($columns);
if ($res === true) {
$this->validationFailures = array();
return true;
} else {
$this->validationFailures = $res;
return false;
}
}
protected function doValidate($columns = null)
{
if (!$this->alreadyInValidation) {
$this->alreadyInValidation = true;
$retval = null;
$failureMap = array();
if (($retval = CscodtallerPeer::doValidate($this, $columns)) !== true) {
$failureMap = array_merge($failureMap, $retval);
}
$this->alreadyInValidation = false;
}
return (!empty($failureMap) ? $failureMap : true);
}
public function getByName($name, $type = BasePeer::TYPE_PHPNAME)
{
$pos = CscodtallerPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
return $this->getByPosition($pos);
}
public function getByPosition($pos)
{
switch($pos) {
case 0:
return $this->getCodart();
break;
case 1:
return $this->getId();
break;
default:
return null;
break;
} }
public function toArray($keyType = BasePeer::TYPE_PHPNAME)
{
$keys = CscodtallerPeer::getFieldNames($keyType);
$result = array(
$keys[0] => $this->getCodart(),
$keys[1] => $this->getId(),
);
return $result;
}
public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME)
{
$pos = CscodtallerPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
return $this->setByPosition($pos, $value);
}
public function setByPosition($pos, $value)
{
switch($pos) {
case 0:
$this->setCodart($value);
break;
case 1:
$this->setId($value);
break;
} }
public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME)
{
$keys = CscodtallerPeer::getFieldNames($keyType);
if (array_key_exists($keys[0], $arr)) $this->setCodart($arr[$keys[0]]);
if (array_key_exists($keys[1], $arr)) $this->setId($arr[$keys[1]]);
}
public function buildCriteria()
{
$criteria = new Criteria(CscodtallerPeer::DATABASE_NAME);
if ($this->isColumnModified(CscodtallerPeer::CODART)) $criteria->add(CscodtallerPeer::CODART, $this->codart);
if ($this->isColumnModified(CscodtallerPeer::ID)) $criteria->add(CscodtallerPeer::ID, $this->id);
return $criteria;
}
public function buildPkeyCriteria()
{
$criteria = new Criteria(CscodtallerPeer::DATABASE_NAME);
$criteria->add(CscodtallerPeer::ID, $this->id);
return $criteria;
}
public function getPrimaryKey()
{
return $this->getId();
}
public function setPrimaryKey($key)
{
$this->setId($key);
}
public function copyInto($copyObj, $deepCopy = false)
{
$copyObj->setCodart($this->codart);
$copyObj->setNew(true);
$copyObj->setId(NULL);
}
public function copy($deepCopy = false)
{
$clazz = get_class($this);
$copyObj = new $clazz();
$this->copyInto($copyObj, $deepCopy);
return $copyObj;
}
public function getPeer()
{
if (self::$peer === null) {
self::$peer = new CscodtallerPeer();
}
return self::$peer;
}
} | cidesa/roraima | lib/model/om/BaseCscodtaller.php | PHP | gpl-2.0 | 6,055 |
/* Copyright 2004,2007,2010 ENSEIRB, INRIA & CNRS
**
** This file is part of the Scotch software package for static mapping,
** graph partitioning and sparse matrix ordering.
**
** This software is governed by the CeCILL-C license under French law
** and abiding by the rules of distribution of free software. You can
** use, modify and/or redistribute the software under the terms of the
** CeCILL-C license as circulated by CEA, CNRS and INRIA at the following
** URL: "http://www.cecill.info".
**
** As a counterpart to the access to the source code and rights to copy,
** modify and redistribute granted by the license, users are provided
** only with a limited warranty and the software's author, the holder of
** the economic rights, and the successive licensors have only limited
** liability.
**
** In this respect, the user's attention is drawn to the risks associated
** with loading, using, modifying and/or developing or reproducing the
** software by the user in light of its specific status of free software,
** that may mean that it is complicated to manipulate, and that also
** therefore means that it is reserved for developers and experienced
** professionals having in-depth computer knowledge. Users are therefore
** encouraged to load and test the software's suitability as regards
** their requirements in conditions enabling the security of their
** systems and/or data to be ensured and, more generally, to use and
** operate it in the same conditions as regards security.
**
** The fact that you are presently reading this means that you have had
** knowledge of the CeCILL-C license and that you accept its terms.
*/
/************************************************************/
/** **/
/** NAME : library_graph_io_chac_f.c **/
/** **/
/** AUTHOR : Francois PELLEGRINI **/
/** **/
/** FUNCTION : This module is the Fortran API for the **/
/** graph i/o routines of the libSCOTCH **/
/** library. **/
/** **/
/** DATES : # Version 4.0 : from : 23 nov 2005 **/
/** to 23 nov 2005 **/
/** # Version 5.1 : from : 27 mar 2010 **/
/** to 27 mar 2010 **/
/** **/
/************************************************************/
/*
** The defines and includes.
*/
#define LIBRARY
#include "module.h"
#include "common.h"
#include "scotch.h"
/**************************************/
/* */
/* These routines are the Fortran API */
/* for the mapping routines. */
/* */
/**************************************/
/* String lengths are passed at the very
** end of the argument list.
*/
FORTRAN ( \
SCOTCHFGRAPHGEOMLOADCHAC, scotchfgraphgeomloadchac, ( \
SCOTCH_Graph * const grafptr, \
SCOTCH_Geom * const geomptr, \
const int * const filegrfptr, \
const int * const filegeoptr, \
const char * const dataptr, /* No use */ \
int * const revaptr, \
const int datanbr), \
(grafptr, geomptr, filegrfptr, filegeoptr, dataptr, revaptr, datanbr))
{
FILE * filegrfstream; /* Streams to build from handles */
FILE * filegeostream;
int filegrfnum; /* Duplicated handle */
int filegeonum;
int o;
if ((filegrfnum = dup (*filegrfptr)) < 0) { /* If cannot duplicate file descriptor */
errorPrint ("SCOTCHFGRAPHGEOMLOADCHAC: cannot duplicate handle (1)");
*revaptr = 1; /* Indicate error */
return;
}
if ((filegeonum = dup (*filegeoptr)) < 0) { /* If cannot duplicate file descriptor */
errorPrint ("SCOTCHFGRAPHGEOMLOADCHAC: cannot duplicate handle (2)");
close (filegrfnum);
*revaptr = 1; /* Indicate error */
return;
}
if ((filegrfstream = fdopen (filegrfnum, "r")) == NULL) { /* Build stream from handle */
errorPrint ("SCOTCHFGRAPHGEOMLOADCHAC: cannot open input stream (1)");
close (filegrfnum);
close (filegeonum);
*revaptr = 1;
return;
}
if ((filegeostream = fdopen (filegeonum, "r")) == NULL) { /* Build stream from handle */
errorPrint ("SCOTCHFGRAPHGEOMLOADCHAC: cannot open input stream (2)");
fclose (filegrfstream);
close (filegeonum);
*revaptr = 1;
return;
}
o = SCOTCH_graphGeomLoadChac (grafptr, geomptr, filegrfstream, filegeostream, NULL);
fclose (filegrfstream); /* This closes file descriptors too */
fclose (filegeostream);
*revaptr = o;
}
/* String lengths are passed at the very
** end of the argument list.
*/
FORTRAN ( \
SCOTCHFGRAPHGEOMSAVECHAC, scotchfgraphgeomsavechac, ( \
const SCOTCH_Graph * const grafptr, \
const SCOTCH_Geom * const geomptr, \
const int * const filegrfptr, \
const int * const filegeoptr, \
const char * const dataptr, /* No use */ \
int * const revaptr, \
const int datanbr), \
(grafptr, geomptr, filegrfptr, filegeoptr, dataptr, revaptr, datanbr))
{
FILE * filegrfstream; /* Streams to build from handles */
FILE * filegeostream;
int filegrfnum; /* Duplicated handle */
int filegeonum;
int o;
if ((filegrfnum = dup (*filegrfptr)) < 0) { /* If cannot duplicate file descriptor */
errorPrint ("SCOTCHFGRAPHGEOMSAVECHAC: cannot duplicate handle (1)");
*revaptr = 1; /* Indicate error */
return;
}
if ((filegeonum = dup (*filegeoptr)) < 0) { /* If cannot duplicate file descriptor */
errorPrint ("SCOTCHFGRAPHGEOMSAVECHAC: cannot duplicate handle (2)");
close (filegrfnum);
*revaptr = 1; /* Indicate error */
return;
}
if ((filegrfstream = fdopen (filegrfnum, "w")) == NULL) { /* Build stream from handle */
errorPrint ("SCOTCHFGRAPHGEOMSAVECHAC: cannot open output stream (1)");
close (filegrfnum);
close (filegeonum);
*revaptr = 1;
return;
}
if ((filegeostream = fdopen (filegeonum, "w")) == NULL) { /* Build stream from handle */
errorPrint ("SCOTCHFGRAPHGEOMSAVECHAC: cannot open output stream (2)");
fclose (filegrfstream);
close (filegeonum);
*revaptr = 1;
return;
}
o = SCOTCH_graphGeomSaveChac (grafptr, geomptr, filegrfstream, filegeostream, NULL);
fclose (filegrfstream); /* This closes file descriptors too */
fclose (filegeostream);
*revaptr = o;
}
| carenelarmat/Conejo | src/decompose_mesh/scotch_5.1.12b/src/libscotch/library_graph_io_chac_f.c | C | gpl-2.0 | 7,391 |
/* mpfr_div_{ui,si} -- divide a floating-point number by a machine integer
Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
Contributed by the Arenaire and Caramel projects, INRIA.
This file is part of the GNU MPFR Library.
The GNU MPFR 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 3 of the License, or (at your
option) any later version.
The GNU MPFR 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 the GNU MPFR Library; see the file COPYING.LESSER. If not, see
http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
#define MPFR_NEED_LONGLONG_H
#include "mpfr-impl.h"
/* returns 0 if result exact, non-zero otherwise */
int
mpfr_div_ui (mpfr_ptr y, mpfr_srcptr x, unsigned long int u, mpfr_rnd_t rnd_mode)
{
long i;
int sh;
mp_size_t xn, yn, dif;
mp_limb_t *xp, *yp, *tmp, c, d;
mpfr_exp_t exp;
int inexact, middle = 1, nexttoinf;
MPFR_TMP_DECL(marker);
MPFR_LOG_FUNC
(("x[%Pu]=%.*Rg u=%lu rnd=%d",
mpfr_get_prec(x), mpfr_log_prec, x, u, rnd_mode),
("y[%Pu]=%.*Rg inexact=%d",
mpfr_get_prec(y), mpfr_log_prec, y, inexact));
if (MPFR_UNLIKELY (MPFR_IS_SINGULAR (x)))
{
if (MPFR_IS_NAN (x))
{
MPFR_SET_NAN (y);
MPFR_RET_NAN;
}
else if (MPFR_IS_INF (x))
{
MPFR_SET_INF (y);
MPFR_SET_SAME_SIGN (y, x);
MPFR_RET (0);
}
else
{
MPFR_ASSERTD (MPFR_IS_ZERO(x));
if (u == 0) /* 0/0 is NaN */
{
MPFR_SET_NAN(y);
MPFR_RET_NAN;
}
else
{
MPFR_SET_ZERO(y);
MPFR_SET_SAME_SIGN (y, x);
MPFR_RET(0);
}
}
}
else if (MPFR_UNLIKELY (u <= 1))
{
if (u < 1)
{
/* x/0 is Inf since x != 0*/
MPFR_SET_INF (y);
MPFR_SET_SAME_SIGN (y, x);
mpfr_set_divby0 ();
MPFR_RET (0);
}
else /* y = x/1 = x */
return mpfr_set (y, x, rnd_mode);
}
else if (MPFR_UNLIKELY (IS_POW2 (u)))
return mpfr_div_2si (y, x, MPFR_INT_CEIL_LOG2 (u), rnd_mode);
MPFR_SET_SAME_SIGN (y, x);
MPFR_TMP_MARK (marker);
xn = MPFR_LIMB_SIZE (x);
yn = MPFR_LIMB_SIZE (y);
xp = MPFR_MANT (x);
yp = MPFR_MANT (y);
exp = MPFR_GET_EXP (x);
dif = yn + 1 - xn;
/* we need to store yn+1 = xn + dif limbs of the quotient */
/* don't use tmp=yp since the mpn_lshift call below requires yp >= tmp+1 */
tmp = MPFR_TMP_LIMBS_ALLOC (yn + 1);
c = (mp_limb_t) u;
MPFR_ASSERTN (u == c);
if (dif >= 0)
c = mpn_divrem_1 (tmp, dif, xp, xn, c); /* used all the dividend */
else /* dif < 0 i.e. xn > yn, don't use the (-dif) low limbs from x */
c = mpn_divrem_1 (tmp, 0, xp - dif, yn + 1, c);
inexact = (c != 0);
/* First pass in estimating next bit of the quotient, in case of RNDN *
* In case we just have the right number of bits (postpone this ?), *
* we need to check whether the remainder is more or less than half *
* the divisor. The test must be performed with a subtraction, so as *
* to prevent carries. */
if (MPFR_LIKELY (rnd_mode == MPFR_RNDN))
{
if (c < (mp_limb_t) u - c) /* We have u > c */
middle = -1;
else if (c > (mp_limb_t) u - c)
middle = 1;
else
middle = 0; /* exactly in the middle */
}
/* If we believe that we are right in the middle or exact, we should check
that we did not neglect any word of x (division large / 1 -> small). */
for (i=0; ((inexact == 0) || (middle == 0)) && (i < -dif); i++)
if (xp[i])
inexact = middle = 1; /* larger than middle */
/*
If the high limb of the result is 0 (xp[xn-1] < u), remove it.
Otherwise, compute the left shift to be performed to normalize.
In the latter case, we discard some low bits computed. They
contain information useful for the rounding, hence the updating
of middle and inexact.
*/
if (tmp[yn] == 0)
{
MPN_COPY(yp, tmp, yn);
exp -= GMP_NUMB_BITS;
}
else
{
int shlz;
count_leading_zeros (shlz, tmp[yn]);
/* shift left to normalize */
if (MPFR_LIKELY (shlz != 0))
{
mp_limb_t w = tmp[0] << shlz;
mpn_lshift (yp, tmp + 1, yn, shlz);
yp[0] += tmp[0] >> (GMP_NUMB_BITS - shlz);
if (w > (MPFR_LIMB_ONE << (GMP_NUMB_BITS - 1)))
{ middle = 1; }
else if (w < (MPFR_LIMB_ONE << (GMP_NUMB_BITS - 1)))
{ middle = -1; }
else
{ middle = (c != 0); }
inexact = inexact || (w != 0);
exp -= shlz;
}
else
{ /* this happens only if u == 1 and xp[xn-1] >=
1<<(GMP_NUMB_BITS-1). It might be better to handle the
u == 1 case seperately ?
*/
MPN_COPY (yp, tmp + 1, yn);
}
}
MPFR_UNSIGNED_MINUS_MODULO (sh, MPFR_PREC (y));
/* it remains sh bits in less significant limb of y */
d = *yp & MPFR_LIMB_MASK (sh);
*yp ^= d; /* set to zero lowest sh bits */
MPFR_TMP_FREE (marker);
if (exp < __gmpfr_emin - 1)
return mpfr_underflow (y, rnd_mode == MPFR_RNDN ? MPFR_RNDZ : rnd_mode,
MPFR_SIGN (y));
if (MPFR_UNLIKELY (d == 0 && inexact == 0))
nexttoinf = 0; /* result is exact */
else
{
MPFR_UPDATE2_RND_MODE(rnd_mode, MPFR_SIGN (y));
switch (rnd_mode)
{
case MPFR_RNDZ:
inexact = - MPFR_INT_SIGN (y); /* result is inexact */
nexttoinf = 0;
break;
case MPFR_RNDA:
inexact = MPFR_INT_SIGN (y);
nexttoinf = 1;
break;
default: /* should be MPFR_RNDN */
MPFR_ASSERTD (rnd_mode == MPFR_RNDN);
/* We have one more significant bit in yn. */
if (sh && d < (MPFR_LIMB_ONE << (sh - 1)))
{
inexact = - MPFR_INT_SIGN (y);
nexttoinf = 0;
}
else if (sh && d > (MPFR_LIMB_ONE << (sh - 1)))
{
inexact = MPFR_INT_SIGN (y);
nexttoinf = 1;
}
else /* sh = 0 or d = 1 << (sh-1) */
{
/* The first case is "false" even rounding (significant bits
indicate even rounding, but the result is inexact, so up) ;
The second case is the case where middle should be used to
decide the direction of rounding (no further bit computed) ;
The third is the true even rounding.
*/
if ((sh && inexact) || (!sh && middle > 0) ||
(!inexact && *yp & (MPFR_LIMB_ONE << sh)))
{
inexact = MPFR_INT_SIGN (y);
nexttoinf = 1;
}
else
{
inexact = - MPFR_INT_SIGN (y);
nexttoinf = 0;
}
}
}
}
if (nexttoinf &&
MPFR_UNLIKELY (mpn_add_1 (yp, yp, yn, MPFR_LIMB_ONE << sh)))
{
exp++;
yp[yn-1] = MPFR_LIMB_HIGHBIT;
}
/* Set the exponent. Warning! One may still have an underflow. */
MPFR_EXP (y) = exp;
return mpfr_check_range (y, inexact, rnd_mode);
}
int
mpfr_div_si (mpfr_ptr y, mpfr_srcptr x, long int u, mpfr_rnd_t rnd_mode)
{
int res;
MPFR_LOG_FUNC
(("x[%Pu]=%.*Rg u=%ld rnd=%d",
mpfr_get_prec(x), mpfr_log_prec, x, u, rnd_mode),
("y[%Pu]=%.*Rg inexact=%d",
mpfr_get_prec(y), mpfr_log_prec, y, res));
if (u >= 0)
res = mpfr_div_ui (y, x, u, rnd_mode);
else
{
res = -mpfr_div_ui (y, x, -u, MPFR_INVERT_RND (rnd_mode));
MPFR_CHANGE_SIGN (y);
}
return res;
}
| freedesktop-unofficial-mirror/gstreamer-sdk__mpfr | src/div_ui.c | C | gpl-3.0 | 8,383 |
/*****************************************************************************
* Copyright (c) 2014-2018 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#pragma once
#include <memory>
#include <string>
#include <openrct2/common.h>
struct SDL_Window;
namespace OpenRCT2
{
interface IContext;
interface IPlatformEnvironment;
namespace Ui
{
struct FileDialogDesc;
class InGameConsole;
interface IUiContext;
interface IPlatformUiContext
{
virtual ~IPlatformUiContext() = default;
virtual void SetWindowIcon(SDL_Window * window) abstract;
virtual bool IsSteamOverlayAttached() abstract;
virtual void ShowMessageBox(SDL_Window * window, const std::string &message) abstract;
virtual std::string ShowFileDialog(SDL_Window * window, const FileDialogDesc &desc) abstract;
virtual std::string ShowDirectoryDialog(SDL_Window * window, const std::string &title) abstract;
};
std::unique_ptr<IUiContext> CreateUiContext(const std::shared_ptr<IPlatformEnvironment>& env);
IPlatformUiContext * CreatePlatformUiContext();
InGameConsole& GetInGameConsole();
} // namespace Ui
} // namespace OpenRCT2
| blackhand1001/OpenRCT2 | src/openrct2-ui/UiContext.h | C | gpl-3.0 | 1,552 |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.widget;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.Widget;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.accessibility.AccessibilityEvent;
import com.android.internal.R;
import java.util.Locale;
/**
* A widget for selecting the time of day, in either 24-hour or AM/PM mode.
* <p>
* For a dialog using this view, see {@link android.app.TimePickerDialog}. See
* the <a href="{@docRoot}guide/topics/ui/controls/pickers.html">Pickers</a>
* guide for more information.
*
* @attr ref android.R.styleable#TimePicker_timePickerMode
*/
@Widget
public class TimePicker extends FrameLayout {
private static final int MODE_SPINNER = 1;
private static final int MODE_CLOCK = 2;
private final TimePickerDelegate mDelegate;
/**
* The callback interface used to indicate the time has been adjusted.
*/
public interface OnTimeChangedListener {
/**
* @param view The view associated with this listener.
* @param hourOfDay The current hour.
* @param minute The current minute.
*/
void onTimeChanged(TimePicker view, int hourOfDay, int minute);
}
public TimePicker(Context context) {
this(context, null);
}
public TimePicker(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.timePickerStyle);
}
public TimePicker(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public TimePicker(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.TimePicker, defStyleAttr, defStyleRes);
final int mode = a.getInt(R.styleable.TimePicker_timePickerMode, MODE_SPINNER);
a.recycle();
switch (mode) {
case MODE_CLOCK:
mDelegate = new TimePickerClockDelegate(
this, context, attrs, defStyleAttr, defStyleRes);
break;
case MODE_SPINNER:
default:
mDelegate = new TimePickerSpinnerDelegate(
this, context, attrs, defStyleAttr, defStyleRes);
break;
}
}
/**
* Sets the currently selected hour using 24-hour time.
*
* @param hour the hour to set, in the range (0-23)
* @see #getHour()
*/
public void setHour(int hour) {
mDelegate.setCurrentHour(hour);
}
/**
* Returns the currently selected hour using 24-hour time.
*
* @return the currently selected hour, in the range (0-23)
* @see #setHour(int)
*/
public int getHour() {
return mDelegate.getCurrentHour();
}
/**
* Sets the currently selected minute..
*
* @param minute the minute to set, in the range (0-59)
* @see #getMinute()
*/
public void setMinute(int minute) {
mDelegate.setCurrentMinute(minute);
}
/**
* Returns the currently selected minute.
*
* @return the currently selected minute, in the range (0-59)
* @see #setMinute(int)
*/
public int getMinute() {
return mDelegate.getCurrentMinute();
}
/**
* Sets the current hour.
*
* @deprecated Use {@link #setHour(int)}
*/
@Deprecated
public void setCurrentHour(@NonNull Integer currentHour) {
setHour(currentHour);
}
/**
* @return the current hour in the range (0-23)
* @deprecated Use {@link #getHour()}
*/
@NonNull
@Deprecated
public Integer getCurrentHour() {
return mDelegate.getCurrentHour();
}
/**
* Set the current minute (0-59).
*
* @deprecated Use {@link #setMinute(int)}
*/
@Deprecated
public void setCurrentMinute(@NonNull Integer currentMinute) {
mDelegate.setCurrentMinute(currentMinute);
}
/**
* @return the current minute
* @deprecated Use {@link #getMinute()}
*/
@NonNull
@Deprecated
public Integer getCurrentMinute() {
return mDelegate.getCurrentMinute();
}
/**
* Sets whether this widget displays time in 24-hour mode or 12-hour mode
* with an AM/PM picker.
*
* @param is24HourView {@code true} to display in 24-hour mode,
* {@code false} for 12-hour mode with AM/PM
* @see #is24HourView()
*/
public void setIs24HourView(@NonNull Boolean is24HourView) {
if (is24HourView == null) {
return;
}
mDelegate.setIs24HourView(is24HourView);
}
/**
* @return {@code true} if this widget displays time in 24-hour mode,
* {@code false} otherwise}
* @see #setIs24HourView(Boolean)
*/
public boolean is24HourView() {
return mDelegate.is24HourView();
}
/**
* Set the callback that indicates the time has been adjusted by the user.
*
* @param onTimeChangedListener the callback, should not be null.
*/
public void setOnTimeChangedListener(OnTimeChangedListener onTimeChangedListener) {
mDelegate.setOnTimeChangedListener(onTimeChangedListener);
}
/**
* Sets the callback that indicates the current time is valid.
*
* @param callback the callback, may be null
* @hide
*/
public void setValidationCallback(@Nullable ValidationCallback callback) {
mDelegate.setValidationCallback(callback);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
mDelegate.setEnabled(enabled);
}
@Override
public boolean isEnabled() {
return mDelegate.isEnabled();
}
@Override
public int getBaseline() {
return mDelegate.getBaseline();
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDelegate.onConfigurationChanged(newConfig);
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
return mDelegate.onSaveInstanceState(superState);
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
BaseSavedState ss = (BaseSavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
mDelegate.onRestoreInstanceState(ss);
}
@Override
public CharSequence getAccessibilityClassName() {
return TimePicker.class.getName();
}
/** @hide */
@Override
public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
return mDelegate.dispatchPopulateAccessibilityEvent(event);
}
/**
* A delegate interface that defined the public API of the TimePicker. Allows different
* TimePicker implementations. This would need to be implemented by the TimePicker delegates
* for the real behavior.
*/
interface TimePickerDelegate {
void setCurrentHour(int currentHour);
int getCurrentHour();
void setCurrentMinute(int currentMinute);
int getCurrentMinute();
void setIs24HourView(boolean is24HourView);
boolean is24HourView();
void setOnTimeChangedListener(OnTimeChangedListener onTimeChangedListener);
void setValidationCallback(ValidationCallback callback);
void setEnabled(boolean enabled);
boolean isEnabled();
int getBaseline();
void onConfigurationChanged(Configuration newConfig);
Parcelable onSaveInstanceState(Parcelable superState);
void onRestoreInstanceState(Parcelable state);
boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event);
void onPopulateAccessibilityEvent(AccessibilityEvent event);
}
/**
* A callback interface for updating input validity when the TimePicker
* when included into a Dialog.
*
* @hide
*/
public static interface ValidationCallback {
void onValidationChanged(boolean valid);
}
/**
* An abstract class which can be used as a start for TimePicker implementations
*/
abstract static class AbstractTimePickerDelegate implements TimePickerDelegate {
// The delegator
protected TimePicker mDelegator;
// The context
protected Context mContext;
// The current locale
protected Locale mCurrentLocale;
// Callbacks
protected OnTimeChangedListener mOnTimeChangedListener;
protected ValidationCallback mValidationCallback;
public AbstractTimePickerDelegate(TimePicker delegator, Context context) {
mDelegator = delegator;
mContext = context;
// initialization based on locale
setCurrentLocale(Locale.getDefault());
}
public void setCurrentLocale(Locale locale) {
if (locale.equals(mCurrentLocale)) {
return;
}
mCurrentLocale = locale;
}
@Override
public void setValidationCallback(ValidationCallback callback) {
mValidationCallback = callback;
}
protected void onValidationChanged(boolean valid) {
if (mValidationCallback != null) {
mValidationCallback.onValidationChanged(valid);
}
}
}
}
| syslover33/ctank | java/android-sdk-linux_r24.4.1_src/sources/android-23/android/widget/TimePicker.java | Java | gpl-3.0 | 10,323 |
/* vim: set ts=8 et sw=4 sta ai cin: */
/*
* @author Paulo Pizarro <paulo.pizarro@gmail.com>
* @author Tiago Katcipis <tiagokatcipis@gmail.com>
*
* This file is part of Luasofia.
*
* Luasofia 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 3 of the License, or
* (at your option) any later version.
*
* Luasofia 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 Luasofia. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __LUASOFIA_SU_TIMER_H__
#define __LUASOFIA_SU_TIMER_H__
#include <sofia-sip/su_wait.h>
int luasofia_su_timer_register_meta(lua_State *L);
int luasofia_su_timer_create(lua_State *L);
#endif //__LUASOFIA_SU_TIMER_H_
| LuaDist2/luasofia | src/su/luasofia_su_timer.h | C | gpl-3.0 | 1,074 |
-----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: Shiva's Gate
-- !pos 270 -34 100 195
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (npc:getAnimation() == 9) then
if (player:hasKeyItem(MAGICKED_ASTROLABE)) then
npc:openDoor(8);
else
player:messageSpecial(SOLID_STONE);
end
end
return 0;
end;
--
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | Arcscion/Shadowlyre | scripts/zones/The_Eldieme_Necropolis/npcs/_5f5.lua | Lua | gpl-3.0 | 1,246 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>dqsegdb.urifunctions — dqsegdb 1.6.1 documentation</title>
<link rel="stylesheet" href="../../_static/classic.css" type="text/css" />
<link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
<script id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
<script src="../../_static/jquery.js"></script>
<script src="../../_static/underscore.js"></script>
<script src="../../_static/doctools.js"></script>
<script src="../../_static/language_data.js"></script>
<link rel="index" title="Index" href="../../genindex.html" />
<link rel="search" title="Search" href="../../search.html" />
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="nav-item nav-item-0"><a href="../../index.html">dqsegdb 1.6.1 documentation</a> »</li>
<li class="nav-item nav-item-1"><a href="../index.html" accesskey="U">Module code</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<h1>Source code for dqsegdb.urifunctions</h1><div class="highlight"><pre>
<span></span><span class="c1"># Copyright (C) 2015 Ryan Fisher, Gary Hemming</span>
<span class="c1">#</span>
<span class="c1"># This program is free software: you can redistribute it and/or modify</span>
<span class="c1"># it under the terms of the GNU Affero General Public License as</span>
<span class="c1"># published by the Free Software Foundation, either version 3 of the</span>
<span class="c1"># License, or (at your option) any later version.</span>
<span class="c1">#</span>
<span class="c1"># This program is distributed in the hope that it will be useful,</span>
<span class="c1"># but WITHOUT ANY WARRANTY; without even the implied warranty of</span>
<span class="c1"># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the</span>
<span class="c1"># GNU Affero General Public License for more details.</span>
<span class="c1">#</span>
<span class="c1"># You should have received a copy of the GNU Affero General Public License</span>
<span class="c1"># along with this program. If not, see <http://www.gnu.org/licenses/>.</span>
<span class="kn">from</span> <span class="nn">warnings</span> <span class="kn">import</span> <span class="n">warn</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">import</span> <span class="nn">socket</span>
<span class="kn">import</span> <span class="nn">calendar</span>
<span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">from</span> <span class="nn">OpenSSL</span> <span class="kn">import</span> <span class="n">crypto</span>
<span class="kn">from</span> <span class="nn">six.moves.urllib.parse</span> <span class="kn">import</span> <span class="n">urlparse</span>
<span class="kn">from</span> <span class="nn">six.moves</span> <span class="kn">import</span> <span class="n">http_client</span>
<span class="kn">from</span> <span class="nn">six.moves.urllib</span> <span class="kn">import</span> <span class="p">(</span><span class="n">request</span> <span class="k">as</span> <span class="n">urllib_request</span><span class="p">,</span>
<span class="n">error</span> <span class="k">as</span> <span class="n">urllib_error</span><span class="p">)</span>
<span class="c1">#</span>
<span class="c1"># =============================================================================</span>
<span class="c1">#</span>
<span class="c1"># Library for DQSEGDB API Providing URL Functions</span>
<span class="c1">#</span>
<span class="c1"># =============================================================================</span>
<span class="c1">#</span>
<div class="viewcode-block" id="getDataUrllib2"><a class="viewcode-back" href="../../dqsegdb.html#dqsegdb.urifunctions.getDataUrllib2">[docs]</a><span class="k">def</span> <span class="nf">getDataUrllib2</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">900</span><span class="p">,</span> <span class="n">logger</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">warnings</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
<span class="o">**</span><span class="n">urlopen_kw</span><span class="p">):</span>
<span class="sd">"""Return response from server</span>
<span class="sd"> Parameters</span>
<span class="sd"> ----------</span>
<span class="sd"> url : `str`</span>
<span class="sd"> remote URL to request (HTTP or HTTPS)</span>
<span class="sd"> timeout : `float`</span>
<span class="sd"> time (seconds) to wait for reponse</span>
<span class="sd"> logger : `logging.Logger`</span>
<span class="sd"> logger to print to</span>
<span class="sd"> **urlopen_kw</span>
<span class="sd"> other keywords are passed to :func:`urllib.request.urlopen`</span>
<span class="sd"> Returns</span>
<span class="sd"> -------</span>
<span class="sd"> response : `str`</span>
<span class="sd"> the text reponse from the server</span>
<span class="sd"> """</span>
<span class="k">if</span> <span class="n">logger</span><span class="p">:</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"Beginning url call: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">url</span><span class="p">)</span>
<span class="k">if</span> <span class="n">urlparse</span><span class="p">(</span><span class="n">url</span><span class="p">)</span><span class="o">.</span><span class="n">scheme</span> <span class="o">==</span> <span class="s1">'https'</span> <span class="ow">and</span> <span class="s1">'context'</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">urlopen_kw</span><span class="p">:</span>
<span class="kn">from</span> <span class="nn">ssl</span> <span class="kn">import</span> <span class="n">create_default_context</span>
<span class="kn">from</span> <span class="nn">gwdatafind.utils</span> <span class="kn">import</span> <span class="n">find_credential</span>
<span class="n">urlopen_kw</span><span class="p">[</span><span class="s1">'context'</span><span class="p">]</span> <span class="o">=</span> <span class="n">context</span> <span class="o">=</span> <span class="n">create_default_context</span><span class="p">()</span>
<span class="n">context</span><span class="o">.</span><span class="n">load_cert_chain</span><span class="p">(</span><span class="o">*</span><span class="n">find_credential</span><span class="p">())</span>
<span class="n">output</span> <span class="o">=</span> <span class="n">urllib_request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="n">timeout</span><span class="p">,</span> <span class="o">**</span><span class="n">urlopen_kw</span><span class="p">)</span>
<span class="k">if</span> <span class="n">logger</span><span class="p">:</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"Completed url call: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">url</span><span class="p">)</span>
<span class="k">return</span> <span class="n">output</span><span class="o">.</span><span class="n">read</span><span class="p">()</span></div>
<div class="viewcode-block" id="constructSegmentQueryURLTimeWindow"><a class="viewcode-back" href="../../dqsegdb.html#dqsegdb.urifunctions.constructSegmentQueryURLTimeWindow">[docs]</a><span class="k">def</span> <span class="nf">constructSegmentQueryURLTimeWindow</span><span class="p">(</span><span class="n">protocol</span><span class="p">,</span><span class="n">server</span><span class="p">,</span><span class="n">ifo</span><span class="p">,</span><span class="n">name</span><span class="p">,</span><span class="n">version</span><span class="p">,</span><span class="n">include_list_string</span><span class="p">,</span><span class="n">startTime</span><span class="p">,</span><span class="n">endTime</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> Simple url construction method for dqsegdb server flag:version queries</span>
<span class="sd"> including restrictions on time ranges.</span>
<span class="sd"> Parameters</span>
<span class="sd"> ----------</span>
<span class="sd"> protocol : `string`</span>
<span class="sd"> Ex: 'https'</span>
<span class="sd"> server : `string`</span>
<span class="sd"> Ex: 'dqsegdb5.phy.syr.edu'</span>
<span class="sd"> ifo : `string`</span>
<span class="sd"> Ex: 'L1'</span>
<span class="sd"> name: `string`</span>
<span class="sd"> Ex: 'DMT-SCIENCE'</span>
<span class="sd"> version : `string` or `int`</span>
<span class="sd"> Ex: '1'</span>
<span class="sd"> include_list_string : `string`</span>
<span class="sd"> Ex: "metadata,known,active"</span>
<span class="sd"> startTime : `int`</span>
<span class="sd"> Ex: 999999999</span>
<span class="sd"> endTime : `int`</span>
<span class="sd"> Ex: 999999999</span>
<span class="sd"> """</span>
<span class="n">url1</span><span class="o">=</span><span class="n">protocol</span><span class="o">+</span><span class="s2">"://"</span><span class="o">+</span><span class="n">server</span><span class="o">+</span><span class="s2">"/dq"</span>
<span class="n">url2</span><span class="o">=</span><span class="s1">'/'</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">url1</span><span class="p">,</span><span class="n">ifo</span><span class="p">,</span><span class="n">name</span><span class="p">,</span><span class="nb">str</span><span class="p">(</span><span class="n">version</span><span class="p">)])</span>
<span class="c1"># include_list_string should be a comma seperated list expressed as a string for the URL</span>
<span class="c1"># Let's pass it as a python string for now? Fix!!!</span>
<span class="n">start</span><span class="o">=</span><span class="s1">'s=</span><span class="si">%i</span><span class="s1">'</span> <span class="o">%</span> <span class="n">startTime</span>
<span class="n">end</span><span class="o">=</span><span class="s1">'e=</span><span class="si">%i</span><span class="s1">'</span> <span class="o">%</span> <span class="n">endTime</span>
<span class="n">url3</span><span class="o">=</span><span class="n">url2</span><span class="o">+</span><span class="s1">'?'</span><span class="o">+</span><span class="n">start</span><span class="o">+</span><span class="s1">'&'</span><span class="o">+</span><span class="n">end</span><span class="o">+</span><span class="s1">'&include='</span><span class="o">+</span><span class="n">include_list_string</span>
<span class="k">return</span> <span class="n">url3</span></div>
<div class="viewcode-block" id="constructSegmentQueryURL"><a class="viewcode-back" href="../../dqsegdb.html#dqsegdb.urifunctions.constructSegmentQueryURL">[docs]</a><span class="k">def</span> <span class="nf">constructSegmentQueryURL</span><span class="p">(</span><span class="n">protocol</span><span class="p">,</span><span class="n">server</span><span class="p">,</span><span class="n">ifo</span><span class="p">,</span><span class="n">name</span><span class="p">,</span><span class="n">version</span><span class="p">,</span><span class="n">include_list_string</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> Simple url construction method for dqsegdb server flag:version queries</span>
<span class="sd"> not including restrictions on time ranges.</span>
<span class="sd"> Parameters</span>
<span class="sd"> ----------</span>
<span class="sd"> protocol : `string`</span>
<span class="sd"> Ex: 'https'</span>
<span class="sd"> server : `string`</span>
<span class="sd"> Ex: 'dqsegdb5.phy.syr.edu'</span>
<span class="sd"> ifo : `string`</span>
<span class="sd"> Ex: 'L1'</span>
<span class="sd"> name: `string`</span>
<span class="sd"> Ex: 'DMT-SCIENCE'</span>
<span class="sd"> version : `string` or `int`</span>
<span class="sd"> Ex: '1'</span>
<span class="sd"> include_list_string : `string`</span>
<span class="sd"> Ex: "metadata,known,active"</span>
<span class="sd"> """</span>
<span class="n">url1</span><span class="o">=</span><span class="n">protocol</span><span class="o">+</span><span class="s2">"://"</span><span class="o">+</span><span class="n">server</span><span class="o">+</span><span class="s2">"/dq"</span>
<span class="n">url2</span><span class="o">=</span><span class="s1">'/'</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">url1</span><span class="p">,</span><span class="n">ifo</span><span class="p">,</span><span class="n">name</span><span class="p">,</span><span class="n">version</span><span class="p">])</span>
<span class="n">url3</span><span class="o">=</span><span class="n">url2</span><span class="o">+</span><span class="s1">'?'</span><span class="o">+</span><span class="s1">'include='</span><span class="o">+</span><span class="n">include_list_string</span>
<span class="k">return</span> <span class="n">url3</span></div>
<div class="viewcode-block" id="constructVersionQueryURL"><a class="viewcode-back" href="../../dqsegdb.html#dqsegdb.urifunctions.constructVersionQueryURL">[docs]</a><span class="k">def</span> <span class="nf">constructVersionQueryURL</span><span class="p">(</span><span class="n">protocol</span><span class="p">,</span><span class="n">server</span><span class="p">,</span><span class="n">ifo</span><span class="p">,</span><span class="n">name</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> Simple url construction method for dqsegdb server version queries.</span>
<span class="sd"> Parameters</span>
<span class="sd"> ----------</span>
<span class="sd"> protocol : `string`</span>
<span class="sd"> Ex: 'https'</span>
<span class="sd"> server : `string`</span>
<span class="sd"> Ex: 'dqsegdb5.phy.syr.edu'</span>
<span class="sd"> ifo : `string`</span>
<span class="sd"> Ex: 'L1'</span>
<span class="sd"> name: `string`</span>
<span class="sd"> Ex: 'DMT-SCIENCE'</span>
<span class="sd"> """</span>
<span class="c1">## Simple url construction method:</span>
<span class="n">url1</span><span class="o">=</span><span class="n">protocol</span><span class="o">+</span><span class="s2">"://"</span><span class="o">+</span><span class="n">server</span><span class="o">+</span><span class="s2">"/dq"</span>
<span class="n">url2</span><span class="o">=</span><span class="s1">'/'</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">url1</span><span class="p">,</span><span class="n">ifo</span><span class="p">,</span><span class="n">name</span><span class="p">])</span>
<span class="k">return</span> <span class="n">url2</span></div>
<div class="viewcode-block" id="constructFlagQueryURL"><a class="viewcode-back" href="../../dqsegdb.html#dqsegdb.urifunctions.constructFlagQueryURL">[docs]</a><span class="k">def</span> <span class="nf">constructFlagQueryURL</span><span class="p">(</span><span class="n">protocol</span><span class="p">,</span><span class="n">server</span><span class="p">,</span><span class="n">ifo</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> Simple url construction method for dqsegdb server flag queries.</span>
<span class="sd"> Parameters</span>
<span class="sd"> ----------</span>
<span class="sd"> protocol : `string`</span>
<span class="sd"> Ex: 'https'</span>
<span class="sd"> server : `string`</span>
<span class="sd"> Ex: 'dqsegdb5.phy.syr.edu'</span>
<span class="sd"> ifo : `string`</span>
<span class="sd"> Ex: 'L1'</span>
<span class="sd"> """</span>
<span class="c1">## Simple url construction method:</span>
<span class="n">url1</span><span class="o">=</span><span class="n">protocol</span><span class="o">+</span><span class="s2">"://"</span><span class="o">+</span><span class="n">server</span><span class="o">+</span><span class="s2">"/dq"</span>
<span class="n">url2</span><span class="o">=</span><span class="s1">'/'</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">url1</span><span class="p">,</span><span class="n">ifo</span><span class="p">])</span>
<span class="k">return</span> <span class="n">url2</span></div>
<div class="viewcode-block" id="putDataUrllib2"><a class="viewcode-back" href="../../dqsegdb.html#dqsegdb.urifunctions.putDataUrllib2">[docs]</a><span class="k">def</span> <span class="nf">putDataUrllib2</span><span class="p">(</span><span class="n">url</span><span class="p">,</span><span class="n">payload</span><span class="p">,</span><span class="n">timeout</span><span class="o">=</span><span class="mi">900</span><span class="p">,</span><span class="n">logger</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="o">**</span><span class="n">urlopen_kw</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> Wrapper method for urllib2 that supports PUTs to a url.</span>
<span class="sd"> Parameters</span>
<span class="sd"> ----------</span>
<span class="sd"> url : `string`</span>
<span class="sd"> Ex: 'https://dqsegdb5.phy.syr.edu/L1/DMT-SCIENCE/1'</span>
<span class="sd"> payload : `string`</span>
<span class="sd"> JSON formatted string</span>
<span class="sd"> """</span>
<span class="n">socket</span><span class="o">.</span><span class="n">setdefaulttimeout</span><span class="p">(</span><span class="n">timeout</span><span class="p">)</span>
<span class="k">if</span> <span class="n">urlparse</span><span class="p">(</span><span class="n">url</span><span class="p">)</span><span class="o">.</span><span class="n">scheme</span> <span class="o">==</span> <span class="s1">'https'</span> <span class="ow">and</span> <span class="s1">'context'</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">urlopen_kw</span><span class="p">:</span>
<span class="kn">from</span> <span class="nn">ssl</span> <span class="kn">import</span> <span class="n">create_default_context</span>
<span class="kn">from</span> <span class="nn">gwdatafind.utils</span> <span class="kn">import</span> <span class="n">find_credential</span>
<span class="n">urlopen_kw</span><span class="p">[</span><span class="s1">'context'</span><span class="p">]</span> <span class="o">=</span> <span class="n">context</span> <span class="o">=</span> <span class="n">create_default_context</span><span class="p">()</span>
<span class="n">context</span><span class="o">.</span><span class="n">load_cert_chain</span><span class="p">(</span><span class="o">*</span><span class="n">find_credential</span><span class="p">())</span>
<span class="c1">#BEFORE HTTPS: opener = urllib2.build_opener(urllib2.HTTPHandler)</span>
<span class="c1">#if urlparse(url).scheme == 'https':</span>
<span class="c1"># opener=urllib_request.build_opener(HTTPSClientAuthHandler)</span>
<span class="c1">#else:</span>
<span class="c1"># opener = urllib_request.build_opener(urllib_request.HTTPHandler)</span>
<span class="n">request</span> <span class="o">=</span> <span class="n">urllib_request</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">payload</span><span class="p">)</span>
<span class="n">request</span><span class="o">.</span><span class="n">add_header</span><span class="p">(</span><span class="s1">'Content-Type'</span><span class="p">,</span> <span class="s1">'JSON'</span><span class="p">)</span>
<span class="n">request</span><span class="o">.</span><span class="n">get_method</span> <span class="o">=</span> <span class="k">lambda</span><span class="p">:</span> <span class="s1">'PUT'</span>
<span class="k">if</span> <span class="n">logger</span><span class="p">:</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"Beginning url call: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">url</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">urlreturned</span> <span class="o">=</span> <span class="n">urllib_request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="n">timeout</span><span class="p">,</span> <span class="o">**</span><span class="n">urlopen_kw</span><span class="p">)</span>
<span class="k">except</span> <span class="n">urllib_error</span><span class="o">.</span><span class="n">HTTPError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
<span class="n">handleHTTPError</span><span class="p">(</span><span class="s2">"PUT"</span><span class="p">,</span><span class="n">url</span><span class="p">,</span><span class="n">e</span><span class="p">)</span>
<span class="c1">##print(e.read())</span>
<span class="c1">#if int(e.code)==404:</span>
<span class="c1"># print("Flag does not exist in database yet for url: %s" % url)</span>
<span class="c1">#else:</span>
<span class="c1"># print("Warning: Issue accessing url: %s" % url)</span>
<span class="c1"># print("Code: ")</span>
<span class="c1"># print(e.code)</span>
<span class="c1"># print("Message: ")</span>
<span class="c1"># print(e.msg)</span>
<span class="c1"># #print(e.reason)</span>
<span class="c1"># #print(url)</span>
<span class="c1"># print("May be handled cleanly by calling instance: otherwise will result in an error.")</span>
<span class="c1">##print(e.reason)</span>
<span class="c1">##print(urlreturned)</span>
<span class="k">raise</span>
<span class="k">except</span> <span class="n">urllib_error</span><span class="o">.</span><span class="n">URLError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
<span class="c1">#print(e.read())</span>
<span class="n">warnmsg</span><span class="o">=</span><span class="s2">"Warning: Issue accessing url: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">url</span>
<span class="n">warnmsg</span><span class="o">+=</span><span class="s2">"; "</span>
<span class="n">warnmsg</span><span class="o">+=</span><span class="nb">str</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">reason</span><span class="p">)</span>
<span class="n">warnmsg</span><span class="o">+=</span><span class="s2">"; "</span>
<span class="n">warnmsg</span><span class="o">+=</span><span class="s2">"May be handled cleanly by calling instance: otherwise will result in an error."</span>
<span class="n">warn</span><span class="p">(</span><span class="n">warnmsg</span><span class="p">)</span>
<span class="k">raise</span>
<span class="k">if</span> <span class="n">logger</span><span class="p">:</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"Completed url call: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">url</span><span class="p">)</span>
<span class="k">return</span> <span class="n">url</span></div>
<div class="viewcode-block" id="patchDataUrllib2"><a class="viewcode-back" href="../../dqsegdb.html#dqsegdb.urifunctions.patchDataUrllib2">[docs]</a><span class="k">def</span> <span class="nf">patchDataUrllib2</span><span class="p">(</span><span class="n">url</span><span class="p">,</span><span class="n">payload</span><span class="p">,</span><span class="n">timeout</span><span class="o">=</span><span class="mi">900</span><span class="p">,</span><span class="n">logger</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
<span class="o">**</span><span class="n">urlopen_kw</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> Wrapper method for urllib2 that supports PATCHs to a url.</span>
<span class="sd"> Parameters</span>
<span class="sd"> ----------</span>
<span class="sd"> url : `string`</span>
<span class="sd"> Ex: 'https://dqsegdb5.phy.syr.edu/L1/DMT-SCIENCE/1'</span>
<span class="sd"> payload : `string`</span>
<span class="sd"> JSON formatted string</span>
<span class="sd"> """</span>
<span class="n">socket</span><span class="o">.</span><span class="n">setdefaulttimeout</span><span class="p">(</span><span class="n">timeout</span><span class="p">)</span>
<span class="c1">#BEFORE HTTPS: opener = urllib2.build_opener(urllib2.HTTPHandler)</span>
<span class="k">if</span> <span class="n">urlparse</span><span class="p">(</span><span class="n">url</span><span class="p">)</span><span class="o">.</span><span class="n">scheme</span> <span class="o">==</span> <span class="s1">'https'</span> <span class="ow">and</span> <span class="s1">'context'</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">urlopen_kw</span><span class="p">:</span>
<span class="kn">from</span> <span class="nn">ssl</span> <span class="kn">import</span> <span class="n">create_default_context</span>
<span class="kn">from</span> <span class="nn">gwdatafind.utils</span> <span class="kn">import</span> <span class="n">find_credential</span>
<span class="n">urlopen_kw</span><span class="p">[</span><span class="s1">'context'</span><span class="p">]</span> <span class="o">=</span> <span class="n">context</span> <span class="o">=</span> <span class="n">create_default_context</span><span class="p">()</span>
<span class="n">context</span><span class="o">.</span><span class="n">load_cert_chain</span><span class="p">(</span><span class="o">*</span><span class="n">find_credential</span><span class="p">())</span>
<span class="c1">#if urlparse(url).scheme == 'https':</span>
<span class="c1"># opener=urllib_request.build_opener(HTTPSClientAuthHandler)</span>
<span class="c1">#else:</span>
<span class="c1"># opener = urllib_request.build_opener(urllib_request.HTTPHandler)</span>
<span class="c1">#print(opener.handle_open.items())</span>
<span class="n">request</span> <span class="o">=</span> <span class="n">urllib_request</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">payload</span><span class="p">)</span>
<span class="n">request</span><span class="o">.</span><span class="n">add_header</span><span class="p">(</span><span class="s1">'Content-Type'</span><span class="p">,</span> <span class="s1">'JSON'</span><span class="p">)</span>
<span class="n">request</span><span class="o">.</span><span class="n">get_method</span> <span class="o">=</span> <span class="k">lambda</span><span class="p">:</span> <span class="s1">'PATCH'</span>
<span class="k">if</span> <span class="n">logger</span><span class="p">:</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"Beginning url call: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">url</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="c1">#urlreturned = opener.open(request)</span>
<span class="n">urlreturned</span> <span class="o">=</span> <span class="n">urllib_request</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="n">timeout</span><span class="p">,</span> <span class="o">**</span><span class="n">urlopen_kw</span><span class="p">)</span>
<span class="k">except</span> <span class="n">urllib_error</span><span class="o">.</span><span class="n">HTTPError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
<span class="n">handleHTTPError</span><span class="p">(</span><span class="s2">"PATCH"</span><span class="p">,</span><span class="n">url</span><span class="p">,</span><span class="n">e</span><span class="p">)</span>
<span class="c1">##print(e.read())</span>
<span class="c1">#print("Warning: Issue accessing url: %s" % url)</span>
<span class="c1">#print("Code: ")</span>
<span class="c1">#print(e.code)</span>
<span class="c1">##print(e.reason)</span>
<span class="c1">##print(url)</span>
<span class="c1">#print("May be handled cleanly by calling instance: otherwise will result in an error.")</span>
<span class="k">raise</span>
<span class="k">except</span> <span class="n">urllib_error</span><span class="o">.</span><span class="n">URLError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
<span class="c1">#print(e.read()</span>
<span class="n">warnmsg</span><span class="o">=</span><span class="s2">"Warning: Issue accessing url: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">url</span>
<span class="n">warnmsg</span><span class="o">+=</span><span class="s2">"; "</span>
<span class="n">warnmsg</span><span class="o">+=</span><span class="nb">str</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">reason</span><span class="p">)</span>
<span class="n">warnmsg</span><span class="o">+=</span><span class="s2">"; "</span>
<span class="n">warnmsg</span><span class="o">+=</span><span class="s2">"May be handled cleanly by calling instance: otherwise will result in an error."</span>
<span class="n">warn</span><span class="p">(</span><span class="n">warnmsg</span><span class="p">)</span>
<span class="c1">#warn("Warning: Issue accessing url: %s" % url</span>
<span class="c1">#warn(e.reason</span>
<span class="c1">#warn("May be handled cleanly by calling instance: otherwise will result in an error."</span>
<span class="k">raise</span>
<span class="k">if</span> <span class="n">logger</span><span class="p">:</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"Completed url call: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">url</span><span class="p">)</span>
<span class="k">return</span> <span class="n">url</span></div>
<div class="viewcode-block" id="handleHTTPError"><a class="viewcode-back" href="../../dqsegdb.html#dqsegdb.urifunctions.handleHTTPError">[docs]</a><span class="k">def</span> <span class="nf">handleHTTPError</span><span class="p">(</span><span class="n">method</span><span class="p">,</span><span class="n">url</span><span class="p">,</span><span class="n">e</span><span class="p">):</span>
<span class="k">if</span> <span class="nb">int</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">code</span><span class="p">)</span><span class="o">!=</span><span class="mi">404</span><span class="p">:</span>
<span class="n">warn</span><span class="p">(</span><span class="s2">"Warning: Issue accessing url: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">url</span><span class="p">)</span>
<span class="n">warn</span><span class="p">(</span><span class="s2">"Code: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="nb">str</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">code</span><span class="p">))</span>
<span class="n">warn</span><span class="p">(</span><span class="s2">"Message: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="nb">str</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">msg</span><span class="p">))</span>
<span class="c1">#print(e.reason)</span>
<span class="c1">#print(url)</span>
<span class="n">warn</span><span class="p">(</span><span class="s2">"May be handled cleanly by calling instance: otherwise will result in an error."</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">if</span> <span class="n">method</span> <span class="o">==</span> <span class="s2">"PUT"</span> <span class="ow">or</span> <span class="n">method</span> <span class="o">==</span> <span class="s2">"PATCH"</span><span class="p">:</span>
<span class="n">warn</span><span class="p">(</span><span class="s2">"Info: Flag does not exist in database yet for url: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">url</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">method</span> <span class="o">==</span> <span class="s2">"GET"</span><span class="p">:</span>
<span class="n">warn</span><span class="p">(</span><span class="s2">"Warning: Issue accessing url: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="n">url</span><span class="p">)</span>
<span class="c1">#print("yo! FIX!!!")</span>
<span class="n">warn</span><span class="p">(</span><span class="s2">"Code: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="nb">str</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">code</span><span class="p">))</span>
<span class="n">warn</span><span class="p">(</span><span class="s2">"Message: </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span> <span class="nb">str</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">msg</span><span class="p">))</span>
<span class="n">warn</span><span class="p">(</span><span class="s2">"May be handled cleanly by calling instance: otherwise will result in an error."</span><span class="p">)</span></div>
<span class="c1"># If method == "QUIET" print nothing: used for GET checks that don't need to toss info on a 404</span>
</pre></div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
<h3 id="searchlabel">Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../../search.html" method="get">
<input type="text" name="q" aria-labelledby="searchlabel" />
<input type="submit" value="Go" />
</form>
</div>
</div>
<script>$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="../../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="nav-item nav-item-0"><a href="../../index.html">dqsegdb 1.6.1 documentation</a> »</li>
<li class="nav-item nav-item-1"><a href="../index.html" >Module code</a> »</li>
</ul>
</div>
<div class="footer" role="contentinfo">
© Copyright 2014,2020 Ryan Fisher.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.4.3.
</div>
</body>
</html> | duncanmmacleod/dqsegdb | docs/_modules/dqsegdb/urifunctions.html | HTML | gpl-3.0 | 38,947 |
/* GIMP - The GNU Image Manipulation Program
* Copyright (C) 1995 Spencer Kimball and Peter Mattis
*
* gimpoperationlighten_onlymode.h
* Copyright (C) 2008 Michael Natterer <mitch@gimp.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/>.
*/
#ifndef __GIMP_OPERATION_LIGHTEN_ONLY_MODE_H__
#define __GIMP_OPERATION_LIGHTEN_ONLY_MODE_H__
#include "gimpoperationpointlayermode.h"
#define GIMP_TYPE_OPERATION_LIGHTEN_ONLY_MODE (gimp_operation_lighten_only_mode_get_type ())
#define GIMP_OPERATION_LIGHTEN_ONLY_MODE(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GIMP_TYPE_OPERATION_LIGHTEN_ONLY_MODE, GimpOperationLightenOnlyMode))
#define GIMP_OPERATION_LIGHTEN_ONLY_MODE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), GIMP_TYPE_OPERATION_LIGHTEN_ONLY_MODE, GimpOperationLightenOnlyModeClass))
#define GIMP_IS_OPERATION_LIGHTEN_ONLY_MODE(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GIMP_TYPE_OPERATION_LIGHTEN_ONLY_MODE))
#define GIMP_IS_OPERATION_LIGHTEN_ONLY_MODE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GIMP_TYPE_OPERATION_LIGHTEN_ONLY_MODE))
#define GIMP_OPERATION_LIGHTEN_ONLY_MODE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), GIMP_TYPE_OPERATION_LIGHTEN_ONLY_MODE, GimpOperationLightenOnlyModeClass))
typedef struct _GimpOperationLightenOnlyMode GimpOperationLightenOnlyMode;
typedef struct _GimpOperationLightenOnlyModeClass GimpOperationLightenOnlyModeClass;
struct _GimpOperationLightenOnlyMode
{
GimpOperationPointLayerMode parent_instance;
};
struct _GimpOperationLightenOnlyModeClass
{
GimpOperationPointLayerModeClass parent_class;
};
GType gimp_operation_lighten_only_mode_get_type (void) G_GNUC_CONST;
gboolean gimp_operation_lighten_only_mode_process_pixels (gfloat *in,
gfloat *layer,
gfloat *mask,
gfloat *out,
gfloat opacity,
glong samples,
const GeglRectangle *roi,
gint level);
#endif /* __GIMP_OPERATION_LIGHTEN_ONLY_MODE_H__ */
| brion/gimp | app/operations/gimpoperationlightenonlymode.h | C | gpl-3.0 | 3,024 |
# -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <http://weblate.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/>.
#
from django.shortcuts import render, redirect
from django.utils.translation import ugettext as _
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Sum, Count, Q
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
import django.views.defaults
from weblate.trans.models import (
Project, SubProject, Translation, Check,
Dictionary, Change, Unit, WhiteboardMessage
)
from weblate.requirements import get_versions, get_optional_versions
from weblate.lang.models import Language
from weblate.trans.forms import (
get_upload_form, SearchForm,
AutoForm, ReviewForm, NewLanguageForm,
UserManageForm,
)
from weblate.accounts.models import Profile, notify_new_language
from weblate.trans.views.helper import (
get_project, get_subproject, get_translation,
try_set_language,
)
import weblate
import datetime
from urllib import urlencode
def home(request):
"""
Home page of Weblate showing list of projects, stats
and user links if logged in.
"""
if 'show_set_password' in request.session:
messages.warning(
request,
_(
'You have activated your account, now you should set '
'the password to be able to login next time.'
)
)
return redirect('password')
wb_messages = WhiteboardMessage.objects.all()
projects = Project.objects.all_acl(request.user)
if projects.count() == 1:
projects = SubProject.objects.filter(
project=projects[0]
).select_related()
# Warn about not filled in username (usually caused by migration of
# users from older system
if not request.user.is_anonymous() and request.user.first_name == '':
messages.warning(
request,
_('Please set your full name in your profile.')
)
# Some stats
top_translations = Profile.objects.order_by('-translated')[:10]
top_suggestions = Profile.objects.order_by('-suggested')[:10]
last_changes = Change.objects.last_changes(request.user)[:10]
return render(
request,
'index.html',
{
'projects': projects,
'top_translations': top_translations.select_related('user'),
'top_suggestions': top_suggestions.select_related('user'),
'last_changes': last_changes,
'last_changes_rss': reverse('rss'),
'last_changes_url': '',
'search_form': SearchForm(),
'whiteboard_messages': wb_messages,
}
)
def search(request):
"""
Performs site-wide search on units.
"""
search_form = SearchForm(request.GET)
context = {
'search_form': search_form,
}
if search_form.is_valid():
units = Unit.objects.search(
None,
search_form.cleaned_data,
).select_related(
'translation',
)
# Filter results by ACL
acl_projects, filtered = Project.objects.get_acl_status(request.user)
if filtered:
units = units.filter(
translation__subproject__project__in=acl_projects
)
limit = request.GET.get('limit', 50)
page = request.GET.get('page', 1)
paginator = Paginator(units, limit)
try:
units = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
units = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of
# results.
units = paginator.page(paginator.num_pages)
context['page_obj'] = units
context['title'] = _('Search for %s') % (
search_form.cleaned_data['q']
)
context['query_string'] = search_form.urlencode()
context['search_query'] = search_form.cleaned_data['q']
else:
messages.error(request, _('Invalid search query!'))
return render(
request,
'search.html',
context
)
def show_engage(request, project, lang=None):
# Get project object, skipping ACL
obj = get_project(request, project, skip_acl=True)
# Handle language parameter
language = None
if lang is not None:
language = try_set_language(lang)
context = {
'object': obj,
'project': obj,
'languages': obj.get_language_count(),
'total': obj.get_total(),
'percent': obj.get_translated_percent(language),
'url': obj.get_absolute_url(),
'language': language,
}
# Render text
if language is None:
status_text = _(
'<a href="%(url)s">Translation project for %(project)s</a> '
'currently contains %(total)s strings for translation and is '
'<a href="%(url)s">being translated into %(languages)s languages'
'</a>. Overall, these translations are %(percent)s%% complete.'
)
else:
# Translators: line of text in engagement widget, please use your
# language name instead of English
status_text = _(
'<a href="%(url)s">Translation project for %(project)s</a> into '
'English currently contains %(total)s strings for translation and '
'is %(percent)s%% complete.'
)
if 'English' in status_text:
status_text = status_text.replace('English', language.name)
context['status_text'] = mark_safe(status_text % context)
return render(
request,
'engage.html',
context
)
def show_project(request, project):
obj = get_project(request, project)
dict_langs = Dictionary.objects.filter(
project=obj
).values_list(
'language', flat=True
).distinct()
dicts = []
for language in Language.objects.filter(id__in=dict_langs):
dicts.append(
{
'language': language,
'count': Dictionary.objects.filter(
language=language,
project=obj
).count(),
}
)
last_changes = Change.objects.prefetch().filter(
Q(translation__subproject__project=obj) |
Q(dictionary__project=obj)
)[:10]
return render(
request,
'project.html',
{
'object': obj,
'project': obj,
'dicts': dicts,
'last_changes': last_changes,
'last_changes_rss': reverse(
'rss-project',
kwargs={'project': obj.slug}
),
'last_changes_url': urlencode(
{'project': obj.slug}
),
'add_user_form': UserManageForm(),
}
)
def show_subproject(request, project, subproject):
obj = get_subproject(request, project, subproject)
last_changes = Change.objects.prefetch().filter(
translation__subproject=obj
)[:10]
new_lang_form = NewLanguageForm()
return render(
request,
'subproject.html',
{
'object': obj,
'project': obj.project,
'translations': obj.translation_set.enabled(),
'show_language': 1,
'last_changes': last_changes,
'last_changes_rss': reverse(
'rss-subproject',
kwargs={'subproject': obj.slug, 'project': obj.project.slug}
),
'last_changes_url': urlencode(
{'subproject': obj.slug, 'project': obj.project.slug}
),
'new_lang_form': new_lang_form,
}
)
def show_translation(request, project, subproject, lang):
obj = get_translation(request, project, subproject, lang)
last_changes = Change.objects.prefetch().filter(
translation=obj
)[:10]
# Check locks
obj.is_locked(request.user)
# Get form
form = get_upload_form(request)()
# Is user allowed to do automatic translation?
if request.user.has_perm('trans.automatic_translation'):
autoform = AutoForm(obj)
else:
autoform = None
# Search form for everybody
search_form = SearchForm()
# Review form for logged in users
if request.user.is_anonymous():
review_form = None
else:
review_form = ReviewForm(
initial={
'date': datetime.date.today() - datetime.timedelta(days=31)
}
)
return render(
request,
'translation.html',
{
'object': obj,
'project': obj.subproject.project,
'form': form,
'autoform': autoform,
'search_form': search_form,
'review_form': review_form,
'last_changes': last_changes,
'last_changes_url': urlencode(obj.get_kwargs()),
'last_changes_rss': reverse(
'rss-translation',
kwargs=obj.get_kwargs(),
),
'show_only_component': True,
'other_translations': Translation.objects.filter(
subproject__project=obj.subproject.project,
language=obj.language,
).exclude(
pk=obj.pk
),
}
)
def not_found(request):
"""
Error handler showing list of available projects.
"""
return render(
request,
'404.html',
{
'request_path': request.path,
'title': _('Page Not Found'),
},
status=404
)
def denied(request):
"""
Error handler showing list of available projects.
"""
return render(
request,
'403.html',
{
'request_path': request.path,
'title': _('Permission Denied'),
},
status=403
)
def server_error(request):
"""
Error handler for server errors.
"""
try:
return render(
request,
'500.html',
{
'request_path': request.path,
'title': _('Internal Server Error'),
},
status=500,
)
except Exception:
return django.views.defaults.server_error(request)
def about(request):
"""
Shows about page with version information.
"""
context = {}
totals = Profile.objects.aggregate(
Sum('translated'), Sum('suggested'), Count('id')
)
total_strings = 0
total_words = 0
for project in SubProject.objects.iterator():
try:
translation = project.translation_set.all()[0]
total_strings += translation.total
total_words += translation.total_words
except (IndexError, Translation.DoesNotExist):
pass
context['title'] = _('About Weblate')
context['total_translations'] = totals['translated__sum']
context['total_suggestions'] = totals['suggested__sum']
context['total_users'] = totals['id__count']
context['total_strings'] = total_strings
context['total_words'] = total_words
context['total_languages'] = Language.objects.filter(
translation__total__gt=0
).distinct().count()
context['total_checks'] = Check.objects.count()
context['ignored_checks'] = Check.objects.filter(ignore=True).count()
context['versions'] = get_versions() + get_optional_versions()
return render(
request,
'about.html',
context
)
def data_root(request):
return render(
request,
'data-root.html',
{
'hooks_docs': weblate.get_doc_url('api', 'hooks'),
'api_docs': weblate.get_doc_url('api', 'exports'),
'rss_docs': weblate.get_doc_url('api', 'rss'),
}
)
def data_project(request, project):
obj = get_project(request, project)
return render(
request,
'data.html',
{
'object': obj,
'project': obj,
'hooks_docs': weblate.get_doc_url('api', 'hooks'),
'api_docs': weblate.get_doc_url('api', 'exports'),
'rss_docs': weblate.get_doc_url('api', 'rss'),
}
)
@login_required
def new_language(request, project, subproject):
obj = get_subproject(request, project, subproject)
form = NewLanguageForm(request.POST)
if form.is_valid():
language = Language.objects.get(code=form.cleaned_data['lang'])
same_lang = obj.translation_set.filter(language=language)
if same_lang.exists():
messages.error(
request,
_('Chosen translation already exists in this project!')
)
elif obj.new_lang == 'contact':
notify_new_language(obj, language, request.user)
messages.success(
request,
_(
"A request for a new translation has been "
"sent to the project's maintainers."
)
)
elif obj.new_lang == 'add':
obj.add_new_language(language, request)
else:
messages.error(
request,
_(
'Please choose the language into which '
'you would like to translate.'
)
)
return redirect(
'subproject',
subproject=obj.slug,
project=obj.project.slug
)
| leohmoraes/weblate | weblate/trans/views/basic.py | Python | gpl-3.0 | 14,336 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Automatically generated strings for Moodle 2.1 installer
*
* Do not edit this file manually! It contains just a subset of strings
* needed during the very first steps of installation. This file was
* generated automatically by export-installer.php (which is part of AMOS
* {@link http://docs.moodle.org/en/Development:Languages/AMOS}) using the
* list of strings defined in /install/stringnames.txt.
*
* @package installer
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['admindirname'] = 'Administratora direktorijs';
$string['availablelangs'] = 'Pieejamās valodu pakotnes';
$string['chooselanguagehead'] = 'Valodas izvēle';
$string['chooselanguagesub'] = 'Lūdzu izvēlieties šīs instalācijas valodu. Izvēlētā valoda tiks izmantota arī kā noklusētā šīs vietnes valoda, lai gan tā var tikt nomainīta vēlāk.';
$string['databasetypehead'] = 'Izvēlēties datubāzes draiveru';
$string['dataroot'] = 'Datu direktorijs';
$string['dbprefix'] = 'Tabulu prefikss';
$string['dirroot'] = 'Moodle direktorijs';
$string['environmenthead'] = 'Vides pārbaude...';
$string['installation'] = 'Instalēšana';
$string['langdownloaderror'] = '“{$a}” valodas pakotne diemžēl netika instalēta. Instalēšana tiks turpināta angļu valodā.';
$string['memorylimithelp'] = '<p>Pašlaik iestatītais PHP atmiņas apjoma ierobežojums jūsu serverī ir {$a}.</p>
<p>Sistēmā Moodle tas vēlāk var izraisīt atmiņas izmantošanas problēmas, it īpaši tad,
ja būsit iespējojis lielu skaitu moduļu un/vai lietotāju.</p>
<p>Ja iespējams, ieteicams konfigurēt PHP ar lielāku maksimālās atmiņas apjomu, piemēram, 40 MB. Ir vairāki veidi, kā to var izdarīt, piemēram:</p>
<ol>
<li>Ja iespējams, atkārtoti kompilējiet PHP, izmantojot <i>--enable-memory-limit</i>.
Šādā gadījumā sistēma Moodle atmiņas apjoma ierobežojumu varēs iestatīt automātiski.</li>
<li>Ja jums ir piekļuve php.ini failam, varat mainīt tajā esošo parametra <b>memory_limit</b> iestatījumu, piemēram, uz 40 MB. Ja jums nav piekļuves šim failam, palūdziet to izdarīt administratoram.</li>
<li>Dažos PHP serveros Moodle direktorijā var izveidot failu .htaccess, kurā ir šāda rinda: <p><blockquote>php_value memory_limit 40M</blockquote></p>
<p>Tomēr dažos serveros tas neļaus darboties <b>nevienai</b> PHP lapai
(atverot šīs lapas, tiks parādīti kļūdas ziņojumi), un fails .htaccess būs jānoņem.</p></li>
</ol>';
$string['phpversion'] = 'PHP versija';
$string['phpversionhelp'] = '<p>Sistēmā Moodle jāizmanto PHP, kuras versija ir vismaz 4.3.0 vai 5.1.0 (versijai 5.0.x piemīt vairākas zināmas problēmas).</p>
<p>Jūs pašlaik lietojat versiju {$a}</p>
<p>Ir jājaunina PHP vai jāpāriet uz resursdatoru, kurā tiek izmantota jaunāka PHP versija.</p>
(Ja PHP versija ir 5.0.x, var arī atkāpties uz versiju 4.4.x)</p>';
$string['welcomep10'] = '{$a->installername} ({$a->installerversion})';
$string['welcomep20'] = 'Jūs redzat šo lapu, jo esat veiksmīgi instalējis un
palaidis savā datorā pakotni <strong>{$a->packname} {$a->packversion}</strong>. Apsveicam!';
$string['welcomep30'] = 'Šajā <strong>{$a->installername}</strong> laidienā ir iekļautas lietojumprogrammas,
kas paredzētas, lai izveidotu vidi, kurā darbosies sistēma <strong>Moodle</strong>, proti:';
$string['welcomep40'] = 'Pakotnē ir iekļauta arī sistēma <strong>Moodle {$a->moodlerelease} ({$a->moodleversion})</strong>.';
$string['welcomep50'] = 'Visu šīs pakotnes lietojumprogrammu izmantošanu regulē attiecīgo
licenču nosacījumi. Visā <strong>{$a->installername}</strong> pakotnē ir iekļauts
<a href="http://www.opensource.org/docs/definition_plain.html">atklātais pirmkods</a>, un tā tiek izplatīta
saskaņā ar <a href="http://www.gnu.org/copyleft/gpl.html">GPL</a> licences nosacījumiem.';
$string['welcomep60'] = 'Nākamajās lapās tiks sniegti vienkārši norādījumi par to, kā
datorā konfigurēt un iestatīt sistēmu <strong>Moodle</strong>. Varat akceptēt noklusējuma
iestatījumus vai varat tos mainīt, lai pielāgotu savām vajadzībām.';
$string['welcomep70'] = 'Noklikšķiniet uz pogas Tālāk, lai turpinātu sistēmas <strong>Moodle</strong> instalēšanu.';
$string['wwwroot'] = 'Tīmekļa adrese';
| CLAMP-IT/LAE | install/lang/lv/install.php | PHP | gpl-3.0 | 5,062 |
.select{
position:relative;
top:10px;
left:84%;
padding: 0.5em;
}
.Bitcoin {
background-image: url('https://image.ibb.co/c2qhZw/bitcoin.png');
}
.Ethereum{
background-image: url('https://image.ibb.co/bzF5nG/ethereum.png');
}
.Ripple{
background-image: url('https://image.ibb.co/gn8Egb/ripple.png');
}
.imageContainer {
position: relative;
top:25px;
left:0;
width: 100%;
height: 364px;
background-repeat: no-repeat;
background-size: contain;
}
@media only screen and (max-width: 412px) {
.select{
position:relative;
top:10px;
left:69%;
padding: 0.5em;
}
} | chaitanya1375/Myprojects | src/src/assets/styles/currency-chart.css | CSS | gpl-3.0 | 652 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* moodlelib.php - Moodle main library
*
* Main library file of miscellaneous general-purpose Moodle functions.
* Other main libraries:
* - weblib.php - functions that produce web output
* - datalib.php - functions that access the database
*
* @package core
* @subpackage lib
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
// CONSTANTS (Encased in phpdoc proper comments).
// Date and time constants.
/**
* Time constant - the number of seconds in a year
*/
define('YEARSECS', 31536000);
/**
* Time constant - the number of seconds in a week
*/
define('WEEKSECS', 604800);
/**
* Time constant - the number of seconds in a day
*/
define('DAYSECS', 86400);
/**
* Time constant - the number of seconds in an hour
*/
define('HOURSECS', 3600);
/**
* Time constant - the number of seconds in a minute
*/
define('MINSECS', 60);
/**
* Time constant - the number of minutes in a day
*/
define('DAYMINS', 1440);
/**
* Time constant - the number of minutes in an hour
*/
define('HOURMINS', 60);
// Parameter constants - every call to optional_param(), required_param()
// or clean_param() should have a specified type of parameter.
/**
* PARAM_ALPHA - contains only english ascii letters a-zA-Z.
*/
define('PARAM_ALPHA', 'alpha');
/**
* PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
* NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
*/
define('PARAM_ALPHAEXT', 'alphaext');
/**
* PARAM_ALPHANUM - expected numbers and letters only.
*/
define('PARAM_ALPHANUM', 'alphanum');
/**
* PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
*/
define('PARAM_ALPHANUMEXT', 'alphanumext');
/**
* PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
*/
define('PARAM_AUTH', 'auth');
/**
* PARAM_BASE64 - Base 64 encoded format
*/
define('PARAM_BASE64', 'base64');
/**
* PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
*/
define('PARAM_BOOL', 'bool');
/**
* PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
* checked against the list of capabilities in the database.
*/
define('PARAM_CAPABILITY', 'capability');
/**
* PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
* to use this. The normal mode of operation is to use PARAM_RAW when recieving
* the input (required/optional_param or formslib) and then sanitse the HTML
* using format_text on output. This is for the rare cases when you want to
* sanitise the HTML on input. This cleaning may also fix xhtml strictness.
*/
define('PARAM_CLEANHTML', 'cleanhtml');
/**
* PARAM_EMAIL - an email address following the RFC
*/
define('PARAM_EMAIL', 'email');
/**
* PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
*/
define('PARAM_FILE', 'file');
/**
* PARAM_FLOAT - a real/floating point number.
*
* Note that you should not use PARAM_FLOAT for numbers typed in by the user.
* It does not work for languages that use , as a decimal separator.
* Instead, do something like
* $rawvalue = required_param('name', PARAM_RAW);
* // ... other code including require_login, which sets current lang ...
* $realvalue = unformat_float($rawvalue);
* // ... then use $realvalue
*/
define('PARAM_FLOAT', 'float');
/**
* PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
*/
define('PARAM_HOST', 'host');
/**
* PARAM_INT - integers only, use when expecting only numbers.
*/
define('PARAM_INT', 'int');
/**
* PARAM_LANG - checks to see if the string is a valid installed language in the current site.
*/
define('PARAM_LANG', 'lang');
/**
* PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
* others! Implies PARAM_URL!)
*/
define('PARAM_LOCALURL', 'localurl');
/**
* PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
*/
define('PARAM_NOTAGS', 'notags');
/**
* PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
* traversals note: the leading slash is not removed, window drive letter is not allowed
*/
define('PARAM_PATH', 'path');
/**
* PARAM_PEM - Privacy Enhanced Mail format
*/
define('PARAM_PEM', 'pem');
/**
* PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
*/
define('PARAM_PERMISSION', 'permission');
/**
* PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
*/
define('PARAM_RAW', 'raw');
/**
* PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
*/
define('PARAM_RAW_TRIMMED', 'raw_trimmed');
/**
* PARAM_SAFEDIR - safe directory name, suitable for include() and require()
*/
define('PARAM_SAFEDIR', 'safedir');
/**
* PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
*/
define('PARAM_SAFEPATH', 'safepath');
/**
* PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
*/
define('PARAM_SEQUENCE', 'sequence');
/**
* PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
*/
define('PARAM_TAG', 'tag');
/**
* PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
*/
define('PARAM_TAGLIST', 'taglist');
/**
* PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
*/
define('PARAM_TEXT', 'text');
/**
* PARAM_THEME - Checks to see if the string is a valid theme name in the current site
*/
define('PARAM_THEME', 'theme');
/**
* PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
* http://localhost.localdomain/ is ok.
*/
define('PARAM_URL', 'url');
/**
* PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
* accounts, do NOT use when syncing with external systems!!
*/
define('PARAM_USERNAME', 'username');
/**
* PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
*/
define('PARAM_STRINGID', 'stringid');
// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
/**
* PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
* It was one of the first types, that is why it is abused so much ;-)
* @deprecated since 2.0
*/
define('PARAM_CLEAN', 'clean');
/**
* PARAM_INTEGER - deprecated alias for PARAM_INT
* @deprecated since 2.0
*/
define('PARAM_INTEGER', 'int');
/**
* PARAM_NUMBER - deprecated alias of PARAM_FLOAT
* @deprecated since 2.0
*/
define('PARAM_NUMBER', 'float');
/**
* PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
* NOTE: originally alias for PARAM_APLHA
* @deprecated since 2.0
*/
define('PARAM_ACTION', 'alphanumext');
/**
* PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
* NOTE: originally alias for PARAM_APLHA
* @deprecated since 2.0
*/
define('PARAM_FORMAT', 'alphanumext');
/**
* PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
* @deprecated since 2.0
*/
define('PARAM_MULTILANG', 'text');
/**
* PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
* string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
* America/Port-au-Prince)
*/
define('PARAM_TIMEZONE', 'timezone');
/**
* PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
*/
define('PARAM_CLEANFILE', 'file');
/**
* PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
* Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
* Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
* NOTE: numbers and underscores are strongly discouraged in plugin names!
*/
define('PARAM_COMPONENT', 'component');
/**
* PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
* It is usually used together with context id and component.
* Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
*/
define('PARAM_AREA', 'area');
/**
* PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
* Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
* NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
*/
define('PARAM_PLUGIN', 'plugin');
// Web Services.
/**
* VALUE_REQUIRED - if the parameter is not supplied, there is an error
*/
define('VALUE_REQUIRED', 1);
/**
* VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
*/
define('VALUE_OPTIONAL', 2);
/**
* VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
*/
define('VALUE_DEFAULT', 0);
/**
* NULL_NOT_ALLOWED - the parameter can not be set to null in the database
*/
define('NULL_NOT_ALLOWED', false);
/**
* NULL_ALLOWED - the parameter can be set to null in the database
*/
define('NULL_ALLOWED', true);
// Page types.
/**
* PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
*/
define('PAGE_COURSE_VIEW', 'course-view');
/** Get remote addr constant */
define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
/** Get remote addr constant */
define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
// Blog access level constant declaration.
define ('BLOG_USER_LEVEL', 1);
define ('BLOG_GROUP_LEVEL', 2);
define ('BLOG_COURSE_LEVEL', 3);
define ('BLOG_SITE_LEVEL', 4);
define ('BLOG_GLOBAL_LEVEL', 5);
// Tag constants.
/**
* To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
* length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
* TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
*
* @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
*/
define('TAG_MAX_LENGTH', 50);
// Password policy constants.
define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
define ('PASSWORD_DIGITS', '0123456789');
define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
// Feature constants.
// Used for plugin_supports() to report features that are, or are not, supported by a module.
/** True if module can provide a grade */
define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
/** True if module supports outcomes */
define('FEATURE_GRADE_OUTCOMES', 'outcomes');
/** True if module supports advanced grading methods */
define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
/** True if module controls the grade visibility over the gradebook */
define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
/** True if module supports plagiarism plugins */
define('FEATURE_PLAGIARISM', 'plagiarism');
/** True if module has code to track whether somebody viewed it */
define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
/** True if module has custom completion rules */
define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
/** True if module has no 'view' page (like label) */
define('FEATURE_NO_VIEW_LINK', 'viewlink');
/** True if module supports outcomes */
define('FEATURE_IDNUMBER', 'idnumber');
/** True if module supports groups */
define('FEATURE_GROUPS', 'groups');
/** True if module supports groupings */
define('FEATURE_GROUPINGS', 'groupings');
/** True if module supports groupmembersonly */
define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
/** Type of module */
define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
/** True if module supports intro editor */
define('FEATURE_MOD_INTRO', 'mod_intro');
/** True if module has default completion */
define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
define('FEATURE_COMMENT', 'comment');
define('FEATURE_RATE', 'rate');
/** True if module supports backup/restore of moodle2 format */
define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
/** True if module can show description on course main page */
define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
/** True if module uses the question bank */
define('FEATURE_USES_QUESTIONS', 'usesquestions');
/** Unspecified module archetype */
define('MOD_ARCHETYPE_OTHER', 0);
/** Resource-like type module */
define('MOD_ARCHETYPE_RESOURCE', 1);
/** Assignment module archetype */
define('MOD_ARCHETYPE_ASSIGNMENT', 2);
/** System (not user-addable) module archetype */
define('MOD_ARCHETYPE_SYSTEM', 3);
/** Return this from modname_get_types callback to use default display in activity chooser */
define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
/**
* Security token used for allowing access
* from external application such as web services.
* Scripts do not use any session, performance is relatively
* low because we need to load access info in each request.
* Scripts are executed in parallel.
*/
define('EXTERNAL_TOKEN_PERMANENT', 0);
/**
* Security token used for allowing access
* of embedded applications, the code is executed in the
* active user session. Token is invalidated after user logs out.
* Scripts are executed serially - normal session locking is used.
*/
define('EXTERNAL_TOKEN_EMBEDDED', 1);
/**
* The home page should be the site home
*/
define('HOMEPAGE_SITE', 0);
/**
* The home page should be the users my page
*/
define('HOMEPAGE_MY', 1);
/**
* The home page can be chosen by the user
*/
define('HOMEPAGE_USER', 2);
/**
* Hub directory url (should be moodle.org)
*/
define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
/**
* Moodle.org url (should be moodle.org)
*/
define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
/**
* Moodle mobile app service name
*/
define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
/**
* Indicates the user has the capabilities required to ignore activity and course file size restrictions
*/
define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
/**
* Course display settings: display all sections on one page.
*/
define('COURSE_DISPLAY_SINGLEPAGE', 0);
/**
* Course display settings: split pages into a page per section.
*/
define('COURSE_DISPLAY_MULTIPAGE', 1);
/**
* Authentication constant: String used in password field when password is not stored.
*/
define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
// PARAMETER HANDLING.
/**
* Returns a particular value for the named variable, taken from
* POST or GET. If the parameter doesn't exist then an error is
* thrown because we require this variable.
*
* This function should be used to initialise all required values
* in a script that are based on parameters. Usually it will be
* used like this:
* $id = required_param('id', PARAM_INT);
*
* Please note the $type parameter is now required and the value can not be array.
*
* @param string $parname the name of the page parameter we want
* @param string $type expected type of parameter
* @return mixed
* @throws coding_exception
*/
function required_param($parname, $type) {
if (func_num_args() != 2 or empty($parname) or empty($type)) {
throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
}
// POST has precedence.
if (isset($_POST[$parname])) {
$param = $_POST[$parname];
} else if (isset($_GET[$parname])) {
$param = $_GET[$parname];
} else {
print_error('missingparam', '', '', $parname);
}
if (is_array($param)) {
debugging('Invalid array parameter detected in required_param(): '.$parname);
// TODO: switch to fatal error in Moodle 2.3.
return required_param_array($parname, $type);
}
return clean_param($param, $type);
}
/**
* Returns a particular array value for the named variable, taken from
* POST or GET. If the parameter doesn't exist then an error is
* thrown because we require this variable.
*
* This function should be used to initialise all required values
* in a script that are based on parameters. Usually it will be
* used like this:
* $ids = required_param_array('ids', PARAM_INT);
*
* Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
*
* @param string $parname the name of the page parameter we want
* @param string $type expected type of parameter
* @return array
* @throws coding_exception
*/
function required_param_array($parname, $type) {
if (func_num_args() != 2 or empty($parname) or empty($type)) {
throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
}
// POST has precedence.
if (isset($_POST[$parname])) {
$param = $_POST[$parname];
} else if (isset($_GET[$parname])) {
$param = $_GET[$parname];
} else {
print_error('missingparam', '', '', $parname);
}
if (!is_array($param)) {
print_error('missingparam', '', '', $parname);
}
$result = array();
foreach ($param as $key => $value) {
if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
continue;
}
$result[$key] = clean_param($value, $type);
}
return $result;
}
/**
* Returns a particular value for the named variable, taken from
* POST or GET, otherwise returning a given default.
*
* This function should be used to initialise all optional values
* in a script that are based on parameters. Usually it will be
* used like this:
* $name = optional_param('name', 'Fred', PARAM_TEXT);
*
* Please note the $type parameter is now required and the value can not be array.
*
* @param string $parname the name of the page parameter we want
* @param mixed $default the default value to return if nothing is found
* @param string $type expected type of parameter
* @return mixed
* @throws coding_exception
*/
function optional_param($parname, $default, $type) {
if (func_num_args() != 3 or empty($parname) or empty($type)) {
throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
}
if (!isset($default)) {
$default = null;
}
// POST has precedence.
if (isset($_POST[$parname])) {
$param = $_POST[$parname];
} else if (isset($_GET[$parname])) {
$param = $_GET[$parname];
} else {
return $default;
}
if (is_array($param)) {
debugging('Invalid array parameter detected in required_param(): '.$parname);
// TODO: switch to $default in Moodle 2.3.
return optional_param_array($parname, $default, $type);
}
return clean_param($param, $type);
}
/**
* Returns a particular array value for the named variable, taken from
* POST or GET, otherwise returning a given default.
*
* This function should be used to initialise all optional values
* in a script that are based on parameters. Usually it will be
* used like this:
* $ids = optional_param('id', array(), PARAM_INT);
*
* Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
*
* @param string $parname the name of the page parameter we want
* @param mixed $default the default value to return if nothing is found
* @param string $type expected type of parameter
* @return array
* @throws coding_exception
*/
function optional_param_array($parname, $default, $type) {
if (func_num_args() != 3 or empty($parname) or empty($type)) {
throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
}
// POST has precedence.
if (isset($_POST[$parname])) {
$param = $_POST[$parname];
} else if (isset($_GET[$parname])) {
$param = $_GET[$parname];
} else {
return $default;
}
if (!is_array($param)) {
debugging('optional_param_array() expects array parameters only: '.$parname);
return $default;
}
$result = array();
foreach ($param as $key => $value) {
if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
continue;
}
$result[$key] = clean_param($value, $type);
}
return $result;
}
/**
* Strict validation of parameter values, the values are only converted
* to requested PHP type. Internally it is using clean_param, the values
* before and after cleaning must be equal - otherwise
* an invalid_parameter_exception is thrown.
* Objects and classes are not accepted.
*
* @param mixed $param
* @param string $type PARAM_ constant
* @param bool $allownull are nulls valid value?
* @param string $debuginfo optional debug information
* @return mixed the $param value converted to PHP type
* @throws invalid_parameter_exception if $param is not of given type
*/
function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
if (is_null($param)) {
if ($allownull == NULL_ALLOWED) {
return null;
} else {
throw new invalid_parameter_exception($debuginfo);
}
}
if (is_array($param) or is_object($param)) {
throw new invalid_parameter_exception($debuginfo);
}
$cleaned = clean_param($param, $type);
if ($type == PARAM_FLOAT) {
// Do not detect precision loss here.
if (is_float($param) or is_int($param)) {
// These always fit.
} else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
throw new invalid_parameter_exception($debuginfo);
}
} else if ((string)$param !== (string)$cleaned) {
// Conversion to string is usually lossless.
throw new invalid_parameter_exception($debuginfo);
}
return $cleaned;
}
/**
* Makes sure array contains only the allowed types, this function does not validate array key names!
*
* <code>
* $options = clean_param($options, PARAM_INT);
* </code>
*
* @param array $param the variable array we are cleaning
* @param string $type expected format of param after cleaning.
* @param bool $recursive clean recursive arrays
* @return array
* @throws coding_exception
*/
function clean_param_array(array $param = null, $type, $recursive = false) {
// Convert null to empty array.
$param = (array)$param;
foreach ($param as $key => $value) {
if (is_array($value)) {
if ($recursive) {
$param[$key] = clean_param_array($value, $type, true);
} else {
throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
}
} else {
$param[$key] = clean_param($value, $type);
}
}
return $param;
}
/**
* Used by {@link optional_param()} and {@link required_param()} to
* clean the variables and/or cast to specific types, based on
* an options field.
* <code>
* $course->format = clean_param($course->format, PARAM_ALPHA);
* $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
* </code>
*
* @param mixed $param the variable we are cleaning
* @param string $type expected format of param after cleaning.
* @return mixed
* @throws coding_exception
*/
function clean_param($param, $type) {
global $CFG;
if (is_array($param)) {
throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
} else if (is_object($param)) {
if (method_exists($param, '__toString')) {
$param = $param->__toString();
} else {
throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
}
}
switch ($type) {
case PARAM_RAW:
// No cleaning at all.
$param = fix_utf8($param);
return $param;
case PARAM_RAW_TRIMMED:
// No cleaning, but strip leading and trailing whitespace.
$param = fix_utf8($param);
return trim($param);
case PARAM_CLEAN:
// General HTML cleaning, try to use more specific type if possible this is deprecated!
// Please use more specific type instead.
if (is_numeric($param)) {
return $param;
}
$param = fix_utf8($param);
// Sweep for scripts, etc.
return clean_text($param);
case PARAM_CLEANHTML:
// Clean html fragment.
$param = fix_utf8($param);
// Sweep for scripts, etc.
$param = clean_text($param, FORMAT_HTML);
return trim($param);
case PARAM_INT:
// Convert to integer.
return (int)$param;
case PARAM_FLOAT:
// Convert to float.
return (float)$param;
case PARAM_ALPHA:
// Remove everything not `a-z`.
return preg_replace('/[^a-zA-Z]/i', '', $param);
case PARAM_ALPHAEXT:
// Remove everything not `a-zA-Z_-` (originally allowed "/" too).
return preg_replace('/[^a-zA-Z_-]/i', '', $param);
case PARAM_ALPHANUM:
// Remove everything not `a-zA-Z0-9`.
return preg_replace('/[^A-Za-z0-9]/i', '', $param);
case PARAM_ALPHANUMEXT:
// Remove everything not `a-zA-Z0-9_-`.
return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
case PARAM_SEQUENCE:
// Remove everything not `0-9,`.
return preg_replace('/[^0-9,]/i', '', $param);
case PARAM_BOOL:
// Convert to 1 or 0.
$tempstr = strtolower($param);
if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
$param = 1;
} else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
$param = 0;
} else {
$param = empty($param) ? 0 : 1;
}
return $param;
case PARAM_NOTAGS:
// Strip all tags.
$param = fix_utf8($param);
return strip_tags($param);
case PARAM_TEXT:
// Leave only tags needed for multilang.
$param = fix_utf8($param);
// If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
// for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
do {
if (strpos($param, '</lang>') !== false) {
// Old and future mutilang syntax.
$param = strip_tags($param, '<lang>');
if (!preg_match_all('/<.*>/suU', $param, $matches)) {
break;
}
$open = false;
foreach ($matches[0] as $match) {
if ($match === '</lang>') {
if ($open) {
$open = false;
continue;
} else {
break 2;
}
}
if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
break 2;
} else {
$open = true;
}
}
if ($open) {
break;
}
return $param;
} else if (strpos($param, '</span>') !== false) {
// Current problematic multilang syntax.
$param = strip_tags($param, '<span>');
if (!preg_match_all('/<.*>/suU', $param, $matches)) {
break;
}
$open = false;
foreach ($matches[0] as $match) {
if ($match === '</span>') {
if ($open) {
$open = false;
continue;
} else {
break 2;
}
}
if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
break 2;
} else {
$open = true;
}
}
if ($open) {
break;
}
return $param;
}
} while (false);
// Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
return strip_tags($param);
case PARAM_COMPONENT:
// We do not want any guessing here, either the name is correct or not
// please note only normalised component names are accepted.
if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
return '';
}
if (strpos($param, '__') !== false) {
return '';
}
if (strpos($param, 'mod_') === 0) {
// Module names must not contain underscores because we need to differentiate them from invalid plugin types.
if (substr_count($param, '_') != 1) {
return '';
}
}
return $param;
case PARAM_PLUGIN:
case PARAM_AREA:
// We do not want any guessing here, either the name is correct or not.
if (!is_valid_plugin_name($param)) {
return '';
}
return $param;
case PARAM_SAFEDIR:
// Remove everything not a-zA-Z0-9_- .
return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
case PARAM_SAFEPATH:
// Remove everything not a-zA-Z0-9/_- .
return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
case PARAM_FILE:
// Strip all suspicious characters from filename.
$param = fix_utf8($param);
$param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
if ($param === '.' || $param === '..') {
$param = '';
}
return $param;
case PARAM_PATH:
// Strip all suspicious characters from file path.
$param = fix_utf8($param);
$param = str_replace('\\', '/', $param);
// Explode the path and clean each element using the PARAM_FILE rules.
$breadcrumb = explode('/', $param);
foreach ($breadcrumb as $key => $crumb) {
if ($crumb === '.' && $key === 0) {
// Special condition to allow for relative current path such as ./currentdirfile.txt.
} else {
$crumb = clean_param($crumb, PARAM_FILE);
}
$breadcrumb[$key] = $crumb;
}
$param = implode('/', $breadcrumb);
// Remove multiple current path (./././) and multiple slashes (///).
$param = preg_replace('~//+~', '/', $param);
$param = preg_replace('~/(\./)+~', '/', $param);
return $param;
case PARAM_HOST:
// Allow FQDN or IPv4 dotted quad.
$param = preg_replace('/[^\.\d\w-]/', '', $param );
// Match ipv4 dotted quad.
if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
// Confirm values are ok.
if ( $match[0] > 255
|| $match[1] > 255
|| $match[3] > 255
|| $match[4] > 255 ) {
// Hmmm, what kind of dotted quad is this?
$param = '';
}
} else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
&& !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
&& !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
) {
// All is ok - $param is respected.
} else {
// All is not ok...
$param='';
}
return $param;
case PARAM_URL: // Allow safe ftp, http, mailto urls.
$param = fix_utf8($param);
include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
// All is ok, param is respected.
} else {
// Not really ok.
$param ='';
}
return $param;
case PARAM_LOCALURL:
// Allow http absolute, root relative and relative URLs within wwwroot.
$param = clean_param($param, PARAM_URL);
if (!empty($param)) {
// Simulate the HTTPS version of the site.
$httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
if (preg_match(':^/:', $param)) {
// Root-relative, ok!
} else if (preg_match('/^' . preg_quote($CFG->wwwroot, '/') . '/i', $param)) {
// Absolute, and matches our wwwroot.
} else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot, '/') . '/i', $param)) {
// Absolute, and matches our httpswwwroot.
} else {
// Relative - let's make sure there are no tricks.
if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
// Looks ok.
} else {
$param = '';
}
}
}
return $param;
case PARAM_PEM:
$param = trim($param);
// PEM formatted strings may contain letters/numbers and the symbols:
// forward slash: /
// plus sign: +
// equal sign: =
// , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
list($wholething, $body) = $matches;
unset($wholething, $matches);
$b64 = clean_param($body, PARAM_BASE64);
if (!empty($b64)) {
return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
} else {
return '';
}
}
return '';
case PARAM_BASE64:
if (!empty($param)) {
// PEM formatted strings may contain letters/numbers and the symbols
// forward slash: /
// plus sign: +
// equal sign: =.
if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
return '';
}
$lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
// Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
// than (or equal to) 64 characters long.
for ($i=0, $j=count($lines); $i < $j; $i++) {
if ($i + 1 == $j) {
if (64 < strlen($lines[$i])) {
return '';
}
continue;
}
if (64 != strlen($lines[$i])) {
return '';
}
}
return implode("\n", $lines);
} else {
return '';
}
case PARAM_TAG:
$param = fix_utf8($param);
// Please note it is not safe to use the tag name directly anywhere,
// it must be processed with s(), urlencode() before embedding anywhere.
// Remove some nasties.
$param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
// Convert many whitespace chars into one.
$param = preg_replace('/\s+/', ' ', $param);
$param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
return $param;
case PARAM_TAGLIST:
$param = fix_utf8($param);
$tags = explode(',', $param);
$result = array();
foreach ($tags as $tag) {
$res = clean_param($tag, PARAM_TAG);
if ($res !== '') {
$result[] = $res;
}
}
if ($result) {
return implode(',', $result);
} else {
return '';
}
case PARAM_CAPABILITY:
if (get_capability_info($param)) {
return $param;
} else {
return '';
}
case PARAM_PERMISSION:
$param = (int)$param;
if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
return $param;
} else {
return CAP_INHERIT;
}
case PARAM_AUTH:
$param = clean_param($param, PARAM_PLUGIN);
if (empty($param)) {
return '';
} else if (exists_auth_plugin($param)) {
return $param;
} else {
return '';
}
case PARAM_LANG:
$param = clean_param($param, PARAM_SAFEDIR);
if (get_string_manager()->translation_exists($param)) {
return $param;
} else {
// Specified language is not installed or param malformed.
return '';
}
case PARAM_THEME:
$param = clean_param($param, PARAM_PLUGIN);
if (empty($param)) {
return '';
} else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
return $param;
} else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
return $param;
} else {
// Specified theme is not installed.
return '';
}
case PARAM_USERNAME:
$param = fix_utf8($param);
$param = trim($param);
// Convert uppercase to lowercase MDL-16919.
$param = core_text::strtolower($param);
if (empty($CFG->extendedusernamechars)) {
$param = str_replace(" " , "", $param);
// Regular expression, eliminate all chars EXCEPT:
// alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
$param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
}
return $param;
case PARAM_EMAIL:
$param = fix_utf8($param);
if (validate_email($param)) {
return $param;
} else {
return '';
}
case PARAM_STRINGID:
if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
return $param;
} else {
return '';
}
case PARAM_TIMEZONE:
// Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
$param = fix_utf8($param);
$timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
if (preg_match($timezonepattern, $param)) {
return $param;
} else {
return '';
}
default:
// Doh! throw error, switched parameters in optional_param or another serious problem.
print_error("unknownparamtype", '', '', $type);
}
}
/**
* Makes sure the data is using valid utf8, invalid characters are discarded.
*
* Note: this function is not intended for full objects with methods and private properties.
*
* @param mixed $value
* @return mixed with proper utf-8 encoding
*/
function fix_utf8($value) {
if (is_null($value) or $value === '') {
return $value;
} else if (is_string($value)) {
if ((string)(int)$value === $value) {
// Shortcut.
return $value;
}
// No null bytes expected in our data, so let's remove it.
$value = str_replace("\0", '', $value);
// Note: this duplicates min_fix_utf8() intentionally.
static $buggyiconv = null;
if ($buggyiconv === null) {
$buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
}
if ($buggyiconv) {
if (function_exists('mb_convert_encoding')) {
$subst = mb_substitute_character();
mb_substitute_character('');
$result = mb_convert_encoding($value, 'utf-8', 'utf-8');
mb_substitute_character($subst);
} else {
// Warn admins on admin/index.php page.
$result = $value;
}
} else {
$result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
}
return $result;
} else if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = fix_utf8($v);
}
return $value;
} else if (is_object($value)) {
// Do not modify original.
$value = clone($value);
foreach ($value as $k => $v) {
$value->$k = fix_utf8($v);
}
return $value;
} else {
// This is some other type, no utf-8 here.
return $value;
}
}
/**
* Return true if given value is integer or string with integer value
*
* @param mixed $value String or Int
* @return bool true if number, false if not
*/
function is_number($value) {
if (is_int($value)) {
return true;
} else if (is_string($value)) {
return ((string)(int)$value) === $value;
} else {
return false;
}
}
/**
* Returns host part from url.
*
* @param string $url full url
* @return string host, null if not found
*/
function get_host_from_url($url) {
preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
if ($matches) {
return $matches[1];
}
return null;
}
/**
* Tests whether anything was returned by text editor
*
* This function is useful for testing whether something you got back from
* the HTML editor actually contains anything. Sometimes the HTML editor
* appear to be empty, but actually you get back a <br> tag or something.
*
* @param string $string a string containing HTML.
* @return boolean does the string contain any actual content - that is text,
* images, objects, etc.
*/
function html_is_blank($string) {
return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
}
/**
* Set a key in global configuration
*
* Set a key/value pair in both this session's {@link $CFG} global variable
* and in the 'config' database table for future sessions.
*
* Can also be used to update keys for plugin-scoped configs in config_plugin table.
* In that case it doesn't affect $CFG.
*
* A NULL value will delete the entry.
*
* NOTE: this function is called from lib/db/upgrade.php
*
* @param string $name the key to set
* @param string $value the value to set (without magic quotes)
* @param string $plugin (optional) the plugin scope, default null
* @return bool true or exception
*/
function set_config($name, $value, $plugin=null) {
global $CFG, $DB;
if (empty($plugin)) {
if (!array_key_exists($name, $CFG->config_php_settings)) {
// So it's defined for this invocation at least.
if (is_null($value)) {
unset($CFG->$name);
} else {
// Settings from db are always strings.
$CFG->$name = (string)$value;
}
}
if ($DB->get_field('config', 'name', array('name' => $name))) {
if ($value === null) {
$DB->delete_records('config', array('name' => $name));
} else {
$DB->set_field('config', 'value', $value, array('name' => $name));
}
} else {
if ($value !== null) {
$config = new stdClass();
$config->name = $name;
$config->value = $value;
$DB->insert_record('config', $config, false);
}
}
if ($name === 'siteidentifier') {
cache_helper::update_site_identifier($value);
}
cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
} else {
// Plugin scope.
if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
if ($value===null) {
$DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
} else {
$DB->set_field('config_plugins', 'value', $value, array('id' => $id));
}
} else {
if ($value !== null) {
$config = new stdClass();
$config->plugin = $plugin;
$config->name = $name;
$config->value = $value;
$DB->insert_record('config_plugins', $config, false);
}
}
cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
}
return true;
}
/**
* Get configuration values from the global config table
* or the config_plugins table.
*
* If called with one parameter, it will load all the config
* variables for one plugin, and return them as an object.
*
* If called with 2 parameters it will return a string single
* value or false if the value is not found.
*
* NOTE: this function is called from lib/db/upgrade.php
*
* @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
* that we need only fetch it once per request.
* @param string $plugin full component name
* @param string $name default null
* @return mixed hash-like object or single value, return false no config found
* @throws dml_exception
*/
function get_config($plugin, $name = null) {
global $CFG, $DB;
static $siteidentifier = null;
if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
$forced =& $CFG->config_php_settings;
$iscore = true;
$plugin = 'core';
} else {
if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
$forced =& $CFG->forced_plugin_settings[$plugin];
} else {
$forced = array();
}
$iscore = false;
}
if ($siteidentifier === null) {
try {
// This may fail during installation.
// If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
// install the database.
$siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
} catch (dml_exception $ex) {
// Set siteidentifier to false. We don't want to trip this continually.
$siteidentifier = false;
throw $ex;
}
}
if (!empty($name)) {
if (array_key_exists($name, $forced)) {
return (string)$forced[$name];
} else if ($name === 'siteidentifier' && $plugin == 'core') {
return $siteidentifier;
}
}
$cache = cache::make('core', 'config');
$result = $cache->get($plugin);
if ($result === false) {
// The user is after a recordset.
if (!$iscore) {
$result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
} else {
// This part is not really used any more, but anyway...
$result = $DB->get_records_menu('config', array(), '', 'name,value');;
}
$cache->set($plugin, $result);
}
if (!empty($name)) {
if (array_key_exists($name, $result)) {
return $result[$name];
}
return false;
}
if ($plugin === 'core') {
$result['siteidentifier'] = $siteidentifier;
}
foreach ($forced as $key => $value) {
if (is_null($value) or is_array($value) or is_object($value)) {
// We do not want any extra mess here, just real settings that could be saved in db.
unset($result[$key]);
} else {
// Convert to string as if it went through the DB.
$result[$key] = (string)$value;
}
}
return (object)$result;
}
/**
* Removes a key from global configuration.
*
* NOTE: this function is called from lib/db/upgrade.php
*
* @param string $name the key to set
* @param string $plugin (optional) the plugin scope
* @return boolean whether the operation succeeded.
*/
function unset_config($name, $plugin=null) {
global $CFG, $DB;
if (empty($plugin)) {
unset($CFG->$name);
$DB->delete_records('config', array('name' => $name));
cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
} else {
$DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
}
return true;
}
/**
* Remove all the config variables for a given plugin.
*
* NOTE: this function is called from lib/db/upgrade.php
*
* @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
* @return boolean whether the operation succeeded.
*/
function unset_all_config_for_plugin($plugin) {
global $DB;
// Delete from the obvious config_plugins first.
$DB->delete_records('config_plugins', array('plugin' => $plugin));
// Next delete any suspect settings from config.
$like = $DB->sql_like('name', '?', true, true, false, '|');
$params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
$DB->delete_records_select('config', $like, $params);
// Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
return true;
}
/**
* Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
*
* All users are verified if they still have the necessary capability.
*
* @param string $value the value of the config setting.
* @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
* @param bool $includeadmins include administrators.
* @return array of user objects.
*/
function get_users_from_config($value, $capability, $includeadmins = true) {
if (empty($value) or $value === '$@NONE@$') {
return array();
}
// We have to make sure that users still have the necessary capability,
// it should be faster to fetch them all first and then test if they are present
// instead of validating them one-by-one.
$users = get_users_by_capability(context_system::instance(), $capability);
if ($includeadmins) {
$admins = get_admins();
foreach ($admins as $admin) {
$users[$admin->id] = $admin;
}
}
if ($value === '$@ALL@$') {
return $users;
}
$result = array(); // Result in correct order.
$allowed = explode(',', $value);
foreach ($allowed as $uid) {
if (isset($users[$uid])) {
$user = $users[$uid];
$result[$user->id] = $user;
}
}
return $result;
}
/**
* Invalidates browser caches and cached data in temp.
*
* IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
* {@link phpunit_util::reset_dataroot()}
*
* @return void
*/
function purge_all_caches() {
global $CFG, $DB;
reset_text_filters_cache();
js_reset_all_caches();
theme_reset_all_caches();
get_string_manager()->reset_caches();
core_text::reset_caches();
if (class_exists('core_plugin_manager')) {
core_plugin_manager::reset_caches();
}
// Bump up cacherev field for all courses.
try {
increment_revision_number('course', 'cacherev', '');
} catch (moodle_exception $e) {
// Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
}
$DB->reset_caches();
cache_helper::purge_all();
// Purge all other caches: rss, simplepie, etc.
remove_dir($CFG->cachedir.'', true);
// Make sure cache dir is writable, throws exception if not.
make_cache_directory('');
// This is the only place where we purge local caches, we are only adding files there.
// The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
remove_dir($CFG->localcachedir, true);
set_config('localcachedirpurged', time());
make_localcache_directory('', true);
}
/**
* Get volatile flags
*
* @param string $type
* @param int $changedsince default null
* @return array records array
*/
function get_cache_flags($type, $changedsince = null) {
global $DB;
$params = array('type' => $type, 'expiry' => time());
$sqlwhere = "flagtype = :type AND expiry >= :expiry";
if ($changedsince !== null) {
$params['changedsince'] = $changedsince;
$sqlwhere .= " AND timemodified > :changedsince";
}
$cf = array();
if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
foreach ($flags as $flag) {
$cf[$flag->name] = $flag->value;
}
}
return $cf;
}
/**
* Get volatile flags
*
* @param string $type
* @param string $name
* @param int $changedsince default null
* @return string|false The cache flag value or false
*/
function get_cache_flag($type, $name, $changedsince=null) {
global $DB;
$params = array('type' => $type, 'name' => $name, 'expiry' => time());
$sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
if ($changedsince !== null) {
$params['changedsince'] = $changedsince;
$sqlwhere .= " AND timemodified > :changedsince";
}
return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
}
/**
* Set a volatile flag
*
* @param string $type the "type" namespace for the key
* @param string $name the key to set
* @param string $value the value to set (without magic quotes) - null will remove the flag
* @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
* @return bool Always returns true
*/
function set_cache_flag($type, $name, $value, $expiry = null) {
global $DB;
$timemodified = time();
if ($expiry === null || $expiry < $timemodified) {
$expiry = $timemodified + 24 * 60 * 60;
} else {
$expiry = (int)$expiry;
}
if ($value === null) {
unset_cache_flag($type, $name);
return true;
}
if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
// This is a potential problem in DEBUG_DEVELOPER.
if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
return true; // No need to update.
}
$f->value = $value;
$f->expiry = $expiry;
$f->timemodified = $timemodified;
$DB->update_record('cache_flags', $f);
} else {
$f = new stdClass();
$f->flagtype = $type;
$f->name = $name;
$f->value = $value;
$f->expiry = $expiry;
$f->timemodified = $timemodified;
$DB->insert_record('cache_flags', $f);
}
return true;
}
/**
* Removes a single volatile flag
*
* @param string $type the "type" namespace for the key
* @param string $name the key to set
* @return bool
*/
function unset_cache_flag($type, $name) {
global $DB;
$DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
return true;
}
/**
* Garbage-collect volatile flags
*
* @return bool Always returns true
*/
function gc_cache_flags() {
global $DB;
$DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
return true;
}
// USER PREFERENCE API.
/**
* Refresh user preference cache. This is used most often for $USER
* object that is stored in session, but it also helps with performance in cron script.
*
* Preferences for each user are loaded on first use on every page, then again after the timeout expires.
*
* @package core
* @category preference
* @access public
* @param stdClass $user User object. Preferences are preloaded into 'preference' property
* @param int $cachelifetime Cache life time on the current page (in seconds)
* @throws coding_exception
* @return null
*/
function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
global $DB;
// Static cache, we need to check on each page load, not only every 2 minutes.
static $loadedusers = array();
if (!isset($user->id)) {
throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
}
if (empty($user->id) or isguestuser($user->id)) {
// No permanent storage for not-logged-in users and guest.
if (!isset($user->preference)) {
$user->preference = array();
}
return;
}
$timenow = time();
if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
// Already loaded at least once on this page. Are we up to date?
if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
// No need to reload - we are on the same page and we loaded prefs just a moment ago.
return;
} else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
// No change since the lastcheck on this page.
$user->preference['_lastloaded'] = $timenow;
return;
}
}
// OK, so we have to reload all preferences.
$loadedusers[$user->id] = true;
$user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
$user->preference['_lastloaded'] = $timenow;
}
/**
* Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
*
* NOTE: internal function, do not call from other code.
*
* @package core
* @access private
* @param integer $userid the user whose prefs were changed.
*/
function mark_user_preferences_changed($userid) {
global $CFG;
if (empty($userid) or isguestuser($userid)) {
// No cache flags for guest and not-logged-in users.
return;
}
set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
}
/**
* Sets a preference for the specified user.
*
* If a $user object is submitted it's 'preference' property is used for the preferences cache.
*
* @package core
* @category preference
* @access public
* @param string $name The key to set as preference for the specified user
* @param string $value The value to set for the $name key in the specified user's
* record, null means delete current value.
* @param stdClass|int|null $user A moodle user object or id, null means current user
* @throws coding_exception
* @return bool Always true or exception
*/
function set_user_preference($name, $value, $user = null) {
global $USER, $DB;
if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
throw new coding_exception('Invalid preference name in set_user_preference() call');
}
if (is_null($value)) {
// Null means delete current.
return unset_user_preference($name, $user);
} else if (is_object($value)) {
throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
} else if (is_array($value)) {
throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
}
// Value column maximum length is 1333 characters.
$value = (string)$value;
if (core_text::strlen($value) > 1333) {
throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
}
if (is_null($user)) {
$user = $USER;
} else if (isset($user->id)) {
// It is a valid object.
} else if (is_numeric($user)) {
$user = (object)array('id' => (int)$user);
} else {
throw new coding_exception('Invalid $user parameter in set_user_preference() call');
}
check_user_preferences_loaded($user);
if (empty($user->id) or isguestuser($user->id)) {
// No permanent storage for not-logged-in users and guest.
$user->preference[$name] = $value;
return true;
}
if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
// Preference already set to this value.
return true;
}
$DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
} else {
$preference = new stdClass();
$preference->userid = $user->id;
$preference->name = $name;
$preference->value = $value;
$DB->insert_record('user_preferences', $preference);
}
// Update value in cache.
$user->preference[$name] = $value;
// Set reload flag for other sessions.
mark_user_preferences_changed($user->id);
return true;
}
/**
* Sets a whole array of preferences for the current user
*
* If a $user object is submitted it's 'preference' property is used for the preferences cache.
*
* @package core
* @category preference
* @access public
* @param array $prefarray An array of key/value pairs to be set
* @param stdClass|int|null $user A moodle user object or id, null means current user
* @return bool Always true or exception
*/
function set_user_preferences(array $prefarray, $user = null) {
foreach ($prefarray as $name => $value) {
set_user_preference($name, $value, $user);
}
return true;
}
/**
* Unsets a preference completely by deleting it from the database
*
* If a $user object is submitted it's 'preference' property is used for the preferences cache.
*
* @package core
* @category preference
* @access public
* @param string $name The key to unset as preference for the specified user
* @param stdClass|int|null $user A moodle user object or id, null means current user
* @throws coding_exception
* @return bool Always true or exception
*/
function unset_user_preference($name, $user = null) {
global $USER, $DB;
if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
throw new coding_exception('Invalid preference name in unset_user_preference() call');
}
if (is_null($user)) {
$user = $USER;
} else if (isset($user->id)) {
// It is a valid object.
} else if (is_numeric($user)) {
$user = (object)array('id' => (int)$user);
} else {
throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
}
check_user_preferences_loaded($user);
if (empty($user->id) or isguestuser($user->id)) {
// No permanent storage for not-logged-in user and guest.
unset($user->preference[$name]);
return true;
}
// Delete from DB.
$DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
// Delete the preference from cache.
unset($user->preference[$name]);
// Set reload flag for other sessions.
mark_user_preferences_changed($user->id);
return true;
}
/**
* Used to fetch user preference(s)
*
* If no arguments are supplied this function will return
* all of the current user preferences as an array.
*
* If a name is specified then this function
* attempts to return that particular preference value. If
* none is found, then the optional value $default is returned,
* otherwise null.
*
* If a $user object is submitted it's 'preference' property is used for the preferences cache.
*
* @package core
* @category preference
* @access public
* @param string $name Name of the key to use in finding a preference value
* @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
* @param stdClass|int|null $user A moodle user object or id, null means current user
* @throws coding_exception
* @return string|mixed|null A string containing the value of a single preference. An
* array with all of the preferences or null
*/
function get_user_preferences($name = null, $default = null, $user = null) {
global $USER;
if (is_null($name)) {
// All prefs.
} else if (is_numeric($name) or $name === '_lastloaded') {
throw new coding_exception('Invalid preference name in get_user_preferences() call');
}
if (is_null($user)) {
$user = $USER;
} else if (isset($user->id)) {
// Is a valid object.
} else if (is_numeric($user)) {
$user = (object)array('id' => (int)$user);
} else {
throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
}
check_user_preferences_loaded($user);
if (empty($name)) {
// All values.
return $user->preference;
} else if (isset($user->preference[$name])) {
// The single string value.
return $user->preference[$name];
} else {
// Default value (null if not specified).
return $default;
}
}
// FUNCTIONS FOR HANDLING TIME.
/**
* Given date parts in user time produce a GMT timestamp.
*
* @package core
* @category time
* @param int $year The year part to create timestamp of
* @param int $month The month part to create timestamp of
* @param int $day The day part to create timestamp of
* @param int $hour The hour part to create timestamp of
* @param int $minute The minute part to create timestamp of
* @param int $second The second part to create timestamp of
* @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
* if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
* @param bool $applydst Toggle Daylight Saving Time, default true, will be
* applied only if timezone is 99 or string.
* @return int GMT timestamp
*/
function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
// Save input timezone, required for dst offset check.
$passedtimezone = $timezone;
$timezone = get_user_timezone_offset($timezone);
if (abs($timezone) > 13) {
// Server time.
$time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
} else {
$time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
$time = usertime($time, $timezone);
// Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
$time -= dst_offset_on($time, $passedtimezone);
}
}
return $time;
}
/**
* Format a date/time (seconds) as weeks, days, hours etc as needed
*
* Given an amount of time in seconds, returns string
* formatted nicely as weeks, days, hours etc as needed
*
* @package core
* @category time
* @uses MINSECS
* @uses HOURSECS
* @uses DAYSECS
* @uses YEARSECS
* @param int $totalsecs Time in seconds
* @param stdClass $str Should be a time object
* @return string A nicely formatted date/time string
*/
function format_time($totalsecs, $str = null) {
$totalsecs = abs($totalsecs);
if (!$str) {
// Create the str structure the slow way.
$str = new stdClass();
$str->day = get_string('day');
$str->days = get_string('days');
$str->hour = get_string('hour');
$str->hours = get_string('hours');
$str->min = get_string('min');
$str->mins = get_string('mins');
$str->sec = get_string('sec');
$str->secs = get_string('secs');
$str->year = get_string('year');
$str->years = get_string('years');
}
$years = floor($totalsecs/YEARSECS);
$remainder = $totalsecs - ($years*YEARSECS);
$days = floor($remainder/DAYSECS);
$remainder = $totalsecs - ($days*DAYSECS);
$hours = floor($remainder/HOURSECS);
$remainder = $remainder - ($hours*HOURSECS);
$mins = floor($remainder/MINSECS);
$secs = $remainder - ($mins*MINSECS);
$ss = ($secs == 1) ? $str->sec : $str->secs;
$sm = ($mins == 1) ? $str->min : $str->mins;
$sh = ($hours == 1) ? $str->hour : $str->hours;
$sd = ($days == 1) ? $str->day : $str->days;
$sy = ($years == 1) ? $str->year : $str->years;
$oyears = '';
$odays = '';
$ohours = '';
$omins = '';
$osecs = '';
if ($years) {
$oyears = $years .' '. $sy;
}
if ($days) {
$odays = $days .' '. $sd;
}
if ($hours) {
$ohours = $hours .' '. $sh;
}
if ($mins) {
$omins = $mins .' '. $sm;
}
if ($secs) {
$osecs = $secs .' '. $ss;
}
if ($years) {
return trim($oyears .' '. $odays);
}
if ($days) {
return trim($odays .' '. $ohours);
}
if ($hours) {
return trim($ohours .' '. $omins);
}
if ($mins) {
return trim($omins .' '. $osecs);
}
if ($secs) {
return $osecs;
}
return get_string('now');
}
/**
* Returns a formatted string that represents a date in user time.
*
* @package core
* @category time
* @param int $date the timestamp in UTC, as obtained from the database.
* @param string $format strftime format. You should probably get this using
* get_string('strftime...', 'langconfig');
* @param int|float|string $timezone by default, uses the user's time zone. if numeric and
* not 99 then daylight saving will not be added.
* {@link http://docs.moodle.org/dev/Time_API#Timezone}
* @param bool $fixday If true (default) then the leading zero from %d is removed.
* If false then the leading zero is maintained.
* @param bool $fixhour If true (default) then the leading zero from %I is removed.
* @return string the formatted date/time.
*/
function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
$calendartype = \core_calendar\type_factory::get_calendar_instance();
return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
}
/**
* Returns a formatted date ensuring it is UTF-8.
*
* If we are running under Windows convert to Windows encoding and then back to UTF-8
* (because it's impossible to specify UTF-8 to fetch locale info in Win32).
*
* This function does not do any calculation regarding the user preferences and should
* therefore receive the final date timestamp, format and timezone. Timezone being only used
* to differentiate the use of server time or not (strftime() against gmstrftime()).
*
* @param int $date the timestamp.
* @param string $format strftime format.
* @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
* @return string the formatted date/time.
* @since 2.3.3
*/
function date_format_string($date, $format, $tz = 99) {
global $CFG;
$localewincharset = null;
// Get the calendar type user is using.
if ($CFG->ostype == 'WINDOWS') {
$calendartype = \core_calendar\type_factory::get_calendar_instance();
$localewincharset = $calendartype->locale_win_charset();
}
if (abs($tz) > 13) {
if ($localewincharset) {
$format = core_text::convert($format, 'utf-8', $localewincharset);
$datestring = strftime($format, $date);
$datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
} else {
$datestring = strftime($format, $date);
}
} else {
if ($localewincharset) {
$format = core_text::convert($format, 'utf-8', $localewincharset);
$datestring = gmstrftime($format, $date);
$datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
} else {
$datestring = gmstrftime($format, $date);
}
}
return $datestring;
}
/**
* Given a $time timestamp in GMT (seconds since epoch),
* returns an array that represents the date in user time
*
* @package core
* @category time
* @uses HOURSECS
* @param int $time Timestamp in GMT
* @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
* dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
* @return array An array that represents the date in user time
*/
function usergetdate($time, $timezone=99) {
// Save input timezone, required for dst offset check.
$passedtimezone = $timezone;
$timezone = get_user_timezone_offset($timezone);
if (abs($timezone) > 13) {
// Server time.
return getdate($time);
}
// Add daylight saving offset for string timezones only, as we can't get dst for
// float values. if timezone is 99 (user default timezone), then try update dst.
if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
$time += dst_offset_on($time, $passedtimezone);
}
$time += intval((float)$timezone * HOURSECS);
$datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
// Be careful to ensure the returned array matches that produced by getdate() above.
list(
$getdate['month'],
$getdate['weekday'],
$getdate['yday'],
$getdate['year'],
$getdate['mon'],
$getdate['wday'],
$getdate['mday'],
$getdate['hours'],
$getdate['minutes'],
$getdate['seconds']
) = explode('_', $datestring);
// Set correct datatype to match with getdate().
$getdate['seconds'] = (int)$getdate['seconds'];
$getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
$getdate['year'] = (int)$getdate['year'];
$getdate['mon'] = (int)$getdate['mon'];
$getdate['wday'] = (int)$getdate['wday'];
$getdate['mday'] = (int)$getdate['mday'];
$getdate['hours'] = (int)$getdate['hours'];
$getdate['minutes'] = (int)$getdate['minutes'];
return $getdate;
}
/**
* Given a GMT timestamp (seconds since epoch), offsets it by
* the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
*
* @package core
* @category time
* @uses HOURSECS
* @param int $date Timestamp in GMT
* @param float|int|string $timezone timezone to calculate GMT time offset before
* calculating user time, 99 is default user timezone
* {@link http://docs.moodle.org/dev/Time_API#Timezone}
* @return int
*/
function usertime($date, $timezone=99) {
$timezone = get_user_timezone_offset($timezone);
if (abs($timezone) > 13) {
return $date;
}
return $date - (int)($timezone * HOURSECS);
}
/**
* Given a time, return the GMT timestamp of the most recent midnight
* for the current user.
*
* @package core
* @category time
* @param int $date Timestamp in GMT
* @param float|int|string $timezone timezone to calculate GMT time offset before
* calculating user midnight time, 99 is default user timezone
* {@link http://docs.moodle.org/dev/Time_API#Timezone}
* @return int Returns a GMT timestamp
*/
function usergetmidnight($date, $timezone=99) {
$userdate = usergetdate($date, $timezone);
// Time of midnight of this user's day, in GMT.
return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
}
/**
* Returns a string that prints the user's timezone
*
* @package core
* @category time
* @param float|int|string $timezone timezone to calculate GMT time offset before
* calculating user timezone, 99 is default user timezone
* {@link http://docs.moodle.org/dev/Time_API#Timezone}
* @return string
*/
function usertimezone($timezone=99) {
$tz = get_user_timezone($timezone);
if (!is_float($tz)) {
return $tz;
}
if (abs($tz) > 13) {
// Server time.
return get_string('serverlocaltime');
}
if ($tz == intval($tz)) {
// Don't show .0 for whole hours.
$tz = intval($tz);
}
if ($tz == 0) {
return 'UTC';
} else if ($tz > 0) {
return 'UTC+'.$tz;
} else {
return 'UTC'.$tz;
}
}
/**
* Returns a float which represents the user's timezone difference from GMT in hours
* Checks various settings and picks the most dominant of those which have a value
*
* @package core
* @category time
* @param float|int|string $tz timezone to calculate GMT time offset for user,
* 99 is default user timezone
* {@link http://docs.moodle.org/dev/Time_API#Timezone}
* @return float
*/
function get_user_timezone_offset($tz = 99) {
$tz = get_user_timezone($tz);
if (is_float($tz)) {
return $tz;
} else {
$tzrecord = get_timezone_record($tz);
if (empty($tzrecord)) {
return 99.0;
}
return (float)$tzrecord->gmtoff / HOURMINS;
}
}
/**
* Returns an int which represents the systems's timezone difference from GMT in seconds
*
* @package core
* @category time
* @param float|int|string $tz timezone for which offset is required.
* {@link http://docs.moodle.org/dev/Time_API#Timezone}
* @return int|bool if found, false is timezone 99 or error
*/
function get_timezone_offset($tz) {
if ($tz == 99) {
return false;
}
if (is_numeric($tz)) {
return intval($tz * 60*60);
}
if (!$tzrecord = get_timezone_record($tz)) {
return false;
}
return intval($tzrecord->gmtoff * 60);
}
/**
* Returns a float or a string which denotes the user's timezone
* A float value means that a simple offset from GMT is used, while a string (it will be the name of a timezone in the database)
* means that for this timezone there are also DST rules to be taken into account
* Checks various settings and picks the most dominant of those which have a value
*
* @package core
* @category time
* @param float|int|string $tz timezone to calculate GMT time offset before
* calculating user timezone, 99 is default user timezone
* {@link http://docs.moodle.org/dev/Time_API#Timezone}
* @return float|string
*/
function get_user_timezone($tz = 99) {
global $USER, $CFG;
$timezones = array(
$tz,
isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
isset($USER->timezone) ? $USER->timezone : 99,
isset($CFG->timezone) ? $CFG->timezone : 99,
);
$tz = 99;
// Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
$tz = $next['value'];
}
return is_numeric($tz) ? (float) $tz : $tz;
}
/**
* Returns cached timezone record for given $timezonename
*
* @package core
* @param string $timezonename name of the timezone
* @return stdClass|bool timezonerecord or false
*/
function get_timezone_record($timezonename) {
global $DB;
static $cache = null;
if ($cache === null) {
$cache = array();
}
if (isset($cache[$timezonename])) {
return $cache[$timezonename];
}
return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
}
/**
* Build and store the users Daylight Saving Time (DST) table
*
* @package core
* @param int $fromyear Start year for the table, defaults to 1971
* @param int $toyear End year for the table, defaults to 2035
* @param int|float|string $strtimezone timezone to check if dst should be applied.
* @return bool
*/
function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
global $SESSION, $DB;
$usertz = get_user_timezone($strtimezone);
if (is_float($usertz)) {
// Trivial timezone, no DST.
return false;
}
if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
// We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
unset($SESSION->dst_offsets);
unset($SESSION->dst_range);
}
if (!empty($SESSION->dst_offsets) && empty($fromyear) && empty($toyear)) {
// Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
// This will be the return path most of the time, pretty light computationally.
return true;
}
// Reaching here means we either need to extend our table or create it from scratch.
// Remember which TZ we calculated these changes for.
$SESSION->dst_offsettz = $usertz;
if (empty($SESSION->dst_offsets)) {
// If we 're creating from scratch, put the two guard elements in there.
$SESSION->dst_offsets = array(1 => null, 0 => null);
}
if (empty($SESSION->dst_range)) {
// If creating from scratch.
$from = max((empty($fromyear) ? intval(date('Y')) - 3 : $fromyear), 1971);
$to = min((empty($toyear) ? intval(date('Y')) + 3 : $toyear), 2035);
// Fill in the array with the extra years we need to process.
$yearstoprocess = array();
for ($i = $from; $i <= $to; ++$i) {
$yearstoprocess[] = $i;
}
// Take note of which years we have processed for future calls.
$SESSION->dst_range = array($from, $to);
} else {
// If needing to extend the table, do the same.
$yearstoprocess = array();
$from = max((empty($fromyear) ? $SESSION->dst_range[0] : $fromyear), 1971);
$to = min((empty($toyear) ? $SESSION->dst_range[1] : $toyear), 2035);
if ($from < $SESSION->dst_range[0]) {
// Take note of which years we need to process and then note that we have processed them for future calls.
for ($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
$yearstoprocess[] = $i;
}
$SESSION->dst_range[0] = $from;
}
if ($to > $SESSION->dst_range[1]) {
// Take note of which years we need to process and then note that we have processed them for future calls.
for ($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
$yearstoprocess[] = $i;
}
$SESSION->dst_range[1] = $to;
}
}
if (empty($yearstoprocess)) {
// This means that there was a call requesting a SMALLER range than we have already calculated.
return true;
}
// From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
// Also, the array is sorted in descending timestamp order!
// Get DB data.
static $presetscache = array();
if (!isset($presetscache[$usertz])) {
$presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
'std_startday, std_weekday, std_skipweeks, std_time');
}
if (empty($presetscache[$usertz])) {
return false;
}
// Remove ending guard (first element of the array).
reset($SESSION->dst_offsets);
unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
// Add all required change timestamps.
foreach ($yearstoprocess as $y) {
// Find the record which is in effect for the year $y.
foreach ($presetscache[$usertz] as $year => $preset) {
if ($year <= $y) {
break;
}
}
$changes = dst_changes_for_year($y, $preset);
if ($changes === null) {
continue;
}
if ($changes['dst'] != 0) {
$SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
}
if ($changes['std'] != 0) {
$SESSION->dst_offsets[$changes['std']] = 0;
}
}
// Put in a guard element at the top.
$maxtimestamp = max(array_keys($SESSION->dst_offsets));
$SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = null; // DAYSECS is arbitrary, any "small" number will do.
// Sort again.
krsort($SESSION->dst_offsets);
return true;
}
/**
* Calculates the required DST change and returns a Timestamp Array
*
* @package core
* @category time
* @uses HOURSECS
* @uses MINSECS
* @param int|string $year Int or String Year to focus on
* @param object $timezone Instatiated Timezone object
* @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
*/
function dst_changes_for_year($year, $timezone) {
if ($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 &&
$timezone->std_startday == 0 && $timezone->std_weekday == 0) {
return null;
}
$monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
$monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
list($dsthour, $dstmin) = explode(':', $timezone->dst_time);
list($stdhour, $stdmin) = explode(':', $timezone->std_time);
$timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
$timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
// Instead of putting hour and minute in make_timestamp(), we add them afterwards.
// This has the advantage of being able to have negative values for hour, i.e. for timezones
// where GMT time would be in the PREVIOUS day than the local one on which DST changes.
$timedst += $dsthour * HOURSECS + $dstmin * MINSECS;
$timestd += $stdhour * HOURSECS + $stdmin * MINSECS;
return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
}
/**
* Calculates the Daylight Saving Offset for a given date/time (timestamp)
* - Note: Daylight saving only works for string timezones and not for float.
*
* @package core
* @category time
* @param int $time must NOT be compensated at all, it has to be a pure timestamp
* @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
* then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
* @return int
*/
function dst_offset_on($time, $strtimezone = null) {
global $SESSION;
if (!calculate_user_dst_table(null, null, $strtimezone) || empty($SESSION->dst_offsets)) {
return 0;
}
reset($SESSION->dst_offsets);
while (list($from, $offset) = each($SESSION->dst_offsets)) {
if ($from <= $time) {
break;
}
}
// This is the normal return path.
if ($offset !== null) {
return $offset;
}
// Reaching this point means we haven't calculated far enough, do it now:
// Calculate extra DST changes if needed and recurse. The recursion always
// moves toward the stopping condition, so will always end.
if ($from == 0) {
// We need a year smaller than $SESSION->dst_range[0].
if ($SESSION->dst_range[0] == 1971) {
return 0;
}
calculate_user_dst_table($SESSION->dst_range[0] - 5, null, $strtimezone);
return dst_offset_on($time, $strtimezone);
} else {
// We need a year larger than $SESSION->dst_range[1].
if ($SESSION->dst_range[1] == 2035) {
return 0;
}
calculate_user_dst_table(null, $SESSION->dst_range[1] + 5, $strtimezone);
return dst_offset_on($time, $strtimezone);
}
}
/**
* Calculates when the day appears in specific month
*
* @package core
* @category time
* @param int $startday starting day of the month
* @param int $weekday The day when week starts (normally taken from user preferences)
* @param int $month The month whose day is sought
* @param int $year The year of the month whose day is sought
* @return int
*/
function find_day_in_month($startday, $weekday, $month, $year) {
$calendartype = \core_calendar\type_factory::get_calendar_instance();
$daysinmonth = days_in_month($month, $year);
$daysinweek = count($calendartype->get_weekdays());
if ($weekday == -1) {
// Don't care about weekday, so return:
// abs($startday) if $startday != -1
// $daysinmonth otherwise.
return ($startday == -1) ? $daysinmonth : abs($startday);
}
// From now on we 're looking for a specific weekday.
// Give "end of month" its actual value, since we know it.
if ($startday == -1) {
$startday = -1 * $daysinmonth;
}
// Starting from day $startday, the sign is the direction.
if ($startday < 1) {
$startday = abs($startday);
$lastmonthweekday = dayofweek($daysinmonth, $month, $year);
// This is the last such weekday of the month.
$lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
if ($lastinmonth > $daysinmonth) {
$lastinmonth -= $daysinweek;
}
// Find the first such weekday <= $startday.
while ($lastinmonth > $startday) {
$lastinmonth -= $daysinweek;
}
return $lastinmonth;
} else {
$indexweekday = dayofweek($startday, $month, $year);
$diff = $weekday - $indexweekday;
if ($diff < 0) {
$diff += $daysinweek;
}
// This is the first such weekday of the month equal to or after $startday.
$firstfromindex = $startday + $diff;
return $firstfromindex;
}
}
/**
* Calculate the number of days in a given month
*
* @package core
* @category time
* @param int $month The month whose day count is sought
* @param int $year The year of the month whose day count is sought
* @return int
*/
function days_in_month($month, $year) {
$calendartype = \core_calendar\type_factory::get_calendar_instance();
return $calendartype->get_num_days_in_month($year, $month);
}
/**
* Calculate the position in the week of a specific calendar day
*
* @package core
* @category time
* @param int $day The day of the date whose position in the week is sought
* @param int $month The month of the date whose position in the week is sought
* @param int $year The year of the date whose position in the week is sought
* @return int
*/
function dayofweek($day, $month, $year) {
$calendartype = \core_calendar\type_factory::get_calendar_instance();
return $calendartype->get_weekday($year, $month, $day);
}
// USER AUTHENTICATION AND LOGIN.
/**
* Returns full login url.
*
* @return string login url
*/
function get_login_url() {
global $CFG;
$url = "$CFG->wwwroot/login/index.php";
if (!empty($CFG->loginhttps)) {
$url = str_replace('http:', 'https:', $url);
}
return $url;
}
/**
* This function checks that the current user is logged in and has the
* required privileges
*
* This function checks that the current user is logged in, and optionally
* whether they are allowed to be in a particular course and view a particular
* course module.
* If they are not logged in, then it redirects them to the site login unless
* $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
* case they are automatically logged in as guests.
* If $courseid is given and the user is not enrolled in that course then the
* user is redirected to the course enrolment page.
* If $cm is given and the course module is hidden and the user is not a teacher
* in the course then the user is redirected to the course home page.
*
* When $cm parameter specified, this function sets page layout to 'module'.
* You need to change it manually later if some other layout needed.
*
* @package core_access
* @category access
*
* @param mixed $courseorid id of the course or course object
* @param bool $autologinguest default true
* @param object $cm course module object
* @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
* true. Used to avoid (=false) some scripts (file.php...) to set that variable,
* in order to keep redirects working properly. MDL-14495
* @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
* @return mixed Void, exit, and die depending on path
* @throws coding_exception
* @throws require_login_exception
*/
function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
// Must not redirect when byteserving already started.
if (!empty($_SERVER['HTTP_RANGE'])) {
$preventredirect = true;
}
// Setup global $COURSE, themes, language and locale.
if (!empty($courseorid)) {
if (is_object($courseorid)) {
$course = $courseorid;
} else if ($courseorid == SITEID) {
$course = clone($SITE);
} else {
$course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
}
if ($cm) {
if ($cm->course != $course->id) {
throw new coding_exception('course and cm parameters in require_login() call do not match!!');
}
// Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
if (!($cm instanceof cm_info)) {
// Note: nearly all pages call get_fast_modinfo anyway and it does not make any
// db queries so this is not really a performance concern, however it is obviously
// better if you use get_fast_modinfo to get the cm before calling this.
$modinfo = get_fast_modinfo($course);
$cm = $modinfo->get_cm($cm->id);
}
}
} else {
// Do not touch global $COURSE via $PAGE->set_course(),
// the reasons is we need to be able to call require_login() at any time!!
$course = $SITE;
if ($cm) {
throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
}
}
// If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
// Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
// risk leading the user back to the AJAX request URL.
if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
$setwantsurltome = false;
}
// Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
if ($setwantsurltome) {
$SESSION->wantsurl = qualified_me();
}
redirect(get_login_url());
}
// If the user is not even logged in yet then make sure they are.
if (!isloggedin()) {
if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
// Misconfigured site guest, just redirect to login page.
redirect(get_login_url());
exit; // Never reached.
}
$lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
complete_user_login($guest);
$USER->autologinguest = true;
$SESSION->lang = $lang;
} else {
// NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
if ($preventredirect) {
throw new require_login_exception('You are not logged in');
}
if ($setwantsurltome) {
$SESSION->wantsurl = qualified_me();
}
if (!empty($_SERVER['HTTP_REFERER'])) {
$SESSION->fromurl = $_SERVER['HTTP_REFERER'];
}
redirect(get_login_url());
exit; // Never reached.
}
}
// Loginas as redirection if needed.
if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
if ($USER->loginascontext->instanceid != $course->id) {
print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
}
}
}
// Check whether the user should be changing password (but only if it is REALLY them).
if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
$userauth = get_auth_plugin($USER->auth);
if ($userauth->can_change_password() and !$preventredirect) {
if ($setwantsurltome) {
$SESSION->wantsurl = qualified_me();
}
if ($changeurl = $userauth->change_password_url()) {
// Use plugin custom url.
redirect($changeurl);
} else {
// Use moodle internal method.
if (empty($CFG->loginhttps)) {
redirect($CFG->wwwroot .'/login/change_password.php');
} else {
$wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
redirect($wwwroot .'/login/change_password.php');
}
}
} else {
print_error('nopasswordchangeforced', 'auth');
}
}
// Check that the user account is properly set up.
if (user_not_fully_set_up($USER)) {
if ($preventredirect) {
throw new require_login_exception('User not fully set-up');
}
if ($setwantsurltome) {
$SESSION->wantsurl = qualified_me();
}
redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID);
}
// Make sure the USER has a sesskey set up. Used for CSRF protection.
sesskey();
// Do not bother admins with any formalities.
if (is_siteadmin()) {
// Set the global $COURSE.
if ($cm) {
$PAGE->set_cm($cm, $course);
$PAGE->set_pagelayout('incourse');
} else if (!empty($courseorid)) {
$PAGE->set_course($course);
}
// Set accesstime or the user will appear offline which messes up messaging.
user_accesstime_log($course->id);
return;
}
// Check that the user has agreed to a site policy if there is one - do not test in case of admins.
if (!$USER->policyagreed and !is_siteadmin()) {
if (!empty($CFG->sitepolicy) and !isguestuser()) {
if ($preventredirect) {
throw new require_login_exception('Policy not agreed');
}
if ($setwantsurltome) {
$SESSION->wantsurl = qualified_me();
}
redirect($CFG->wwwroot .'/user/policy.php');
} else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
if ($preventredirect) {
throw new require_login_exception('Policy not agreed');
}
if ($setwantsurltome) {
$SESSION->wantsurl = qualified_me();
}
redirect($CFG->wwwroot .'/user/policy.php');
}
}
// Fetch the system context, the course context, and prefetch its child contexts.
$sysctx = context_system::instance();
$coursecontext = context_course::instance($course->id, MUST_EXIST);
if ($cm) {
$cmcontext = context_module::instance($cm->id, MUST_EXIST);
} else {
$cmcontext = null;
}
// If the site is currently under maintenance, then print a message.
if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
if ($preventredirect) {
throw new require_login_exception('Maintenance in progress');
}
print_maintenance_message();
}
// Make sure the course itself is not hidden.
if ($course->id == SITEID) {
// Frontpage can not be hidden.
} else {
if (is_role_switched($course->id)) {
// When switching roles ignore the hidden flag - user had to be in course to do the switch.
} else {
if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
// Originally there was also test of parent category visibility, BUT is was very slow in complex queries
// involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
if ($preventredirect) {
throw new require_login_exception('Course is hidden');
}
$PAGE->set_context(null);
// We need to override the navigation URL as the course won't have been added to the navigation and thus
// the navigation will mess up when trying to find it.
navigation_node::override_active_url(new moodle_url('/'));
notice(get_string('coursehidden'), $CFG->wwwroot .'/');
}
}
}
// Is the user enrolled?
if ($course->id == SITEID) {
// Everybody is enrolled on the frontpage.
} else {
if (\core\session\manager::is_loggedinas()) {
// Make sure the REAL person can access this course first.
$realuser = \core\session\manager::get_realuser();
if (!is_enrolled($coursecontext, $realuser->id, '', true) and
!is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
if ($preventredirect) {
throw new require_login_exception('Invalid course login-as access');
}
$PAGE->set_context(null);
echo $OUTPUT->header();
notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
}
}
$access = false;
if (is_role_switched($course->id)) {
// Ok, user had to be inside this course before the switch.
$access = true;
} else if (is_viewing($coursecontext, $USER)) {
// Ok, no need to mess with enrol.
$access = true;
} else {
if (isset($USER->enrol['enrolled'][$course->id])) {
if ($USER->enrol['enrolled'][$course->id] > time()) {
$access = true;
if (isset($USER->enrol['tempguest'][$course->id])) {
unset($USER->enrol['tempguest'][$course->id]);
remove_temp_course_roles($coursecontext);
}
} else {
// Expired.
unset($USER->enrol['enrolled'][$course->id]);
}
}
if (isset($USER->enrol['tempguest'][$course->id])) {
if ($USER->enrol['tempguest'][$course->id] == 0) {
$access = true;
} else if ($USER->enrol['tempguest'][$course->id] > time()) {
$access = true;
} else {
// Expired.
unset($USER->enrol['tempguest'][$course->id]);
remove_temp_course_roles($coursecontext);
}
}
if (!$access) {
// Cache not ok.
$until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
if ($until !== false) {
// Active participants may always access, a timestamp in the future, 0 (always) or false.
if ($until == 0) {
$until = ENROL_MAX_TIMESTAMP;
}
$USER->enrol['enrolled'][$course->id] = $until;
$access = true;
} else {
$params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
$instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
$enrols = enrol_get_plugins(true);
// First ask all enabled enrol instances in course if they want to auto enrol user.
foreach ($instances as $instance) {
if (!isset($enrols[$instance->enrol])) {
continue;
}
// Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
$until = $enrols[$instance->enrol]->try_autoenrol($instance);
if ($until !== false) {
if ($until == 0) {
$until = ENROL_MAX_TIMESTAMP;
}
$USER->enrol['enrolled'][$course->id] = $until;
$access = true;
break;
}
}
// If not enrolled yet try to gain temporary guest access.
if (!$access) {
foreach ($instances as $instance) {
if (!isset($enrols[$instance->enrol])) {
continue;
}
// Get a duration for the guest access, a timestamp in the future or false.
$until = $enrols[$instance->enrol]->try_guestaccess($instance);
if ($until !== false and $until > time()) {
$USER->enrol['tempguest'][$course->id] = $until;
$access = true;
break;
}
}
}
}
}
}
if (!$access) {
if ($preventredirect) {
throw new require_login_exception('Not enrolled');
}
if ($setwantsurltome) {
$SESSION->wantsurl = qualified_me();
}
redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
}
}
// Set the global $COURSE.
// TODO MDL-49434: setting current course/cm should be after the check $cm->uservisible .
if ($cm) {
$PAGE->set_cm($cm, $course);
$PAGE->set_pagelayout('incourse');
} else if (!empty($courseorid)) {
$PAGE->set_course($course);
}
// Check visibility of activity to current user; includes visible flag, groupmembersonly, conditional availability, etc.
if ($cm && !$cm->uservisible) {
if ($preventredirect) {
throw new require_login_exception('Activity is hidden');
}
if ($course->id != SITEID) {
$url = new moodle_url('/course/view.php', array('id' => $course->id));
} else {
$url = new moodle_url('/');
}
redirect($url, get_string('activityiscurrentlyhidden'));
}
// Finally access granted, update lastaccess times.
user_accesstime_log($course->id);
}
/**
* This function just makes sure a user is logged out.
*
* @package core_access
* @category access
*/
function require_logout() {
global $USER, $DB;
if (!isloggedin()) {
// This should not happen often, no need for hooks or events here.
\core\session\manager::terminate_current();
return;
}
// Execute hooks before action.
$authsequence = get_enabled_auth_plugins();
foreach ($authsequence as $authname) {
$authplugin = get_auth_plugin($authname);
$authplugin->prelogout_hook();
}
// Store info that gets removed during logout.
$sid = session_id();
$event = \core\event\user_loggedout::create(
array(
'userid' => $USER->id,
'objectid' => $USER->id,
'other' => array('sessionid' => $sid),
)
);
if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
$event->add_record_snapshot('sessions', $session);
}
// Delete session record and drop $_SESSION content.
\core\session\manager::terminate_current();
// Trigger event AFTER action.
$event->trigger();
}
/**
* Weaker version of require_login()
*
* This is a weaker version of {@link require_login()} which only requires login
* when called from within a course rather than the site page, unless
* the forcelogin option is turned on.
* @see require_login()
*
* @package core_access
* @category access
*
* @param mixed $courseorid The course object or id in question
* @param bool $autologinguest Allow autologin guests if that is wanted
* @param object $cm Course activity module if known
* @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
* true. Used to avoid (=false) some scripts (file.php...) to set that variable,
* in order to keep redirects working properly. MDL-14495
* @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
* @return void
* @throws coding_exception
*/
function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
global $CFG, $PAGE, $SITE;
$issite = ((is_object($courseorid) and $courseorid->id == SITEID)
or (!is_object($courseorid) and $courseorid == SITEID));
if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
// Note: nearly all pages call get_fast_modinfo anyway and it does not make any
// db queries so this is not really a performance concern, however it is obviously
// better if you use get_fast_modinfo to get the cm before calling this.
if (is_object($courseorid)) {
$course = $courseorid;
} else {
$course = clone($SITE);
}
$modinfo = get_fast_modinfo($course);
$cm = $modinfo->get_cm($cm->id);
}
if (!empty($CFG->forcelogin)) {
// Login required for both SITE and courses.
require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
} else if ($issite && !empty($cm) and !$cm->uservisible) {
// Always login for hidden activities.
require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
} else if ($issite) {
// Login for SITE not required.
if ($cm and empty($cm->visible)) {
// Hidden activities are not accessible without login.
require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
} else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
// Not-logged-in users do not have any group membership.
require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
} else {
// We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
if (!empty($courseorid)) {
if (is_object($courseorid)) {
$course = $courseorid;
} else {
$course = clone($SITE);
}
if ($cm) {
if ($cm->course != $course->id) {
throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
}
$PAGE->set_cm($cm, $course);
$PAGE->set_pagelayout('incourse');
} else {
$PAGE->set_course($course);
}
} else {
// If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
$PAGE->set_course($PAGE->course);
}
// TODO: verify conditional activities here.
user_accesstime_log(SITEID);
return;
}
} else {
// Course login always required.
require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
}
}
/**
* Require key login. Function terminates with error if key not found or incorrect.
*
* @uses NO_MOODLE_COOKIES
* @uses PARAM_ALPHANUM
* @param string $script unique script identifier
* @param int $instance optional instance id
* @return int Instance ID
*/
function require_user_key_login($script, $instance=null) {
global $DB;
if (!NO_MOODLE_COOKIES) {
print_error('sessioncookiesdisable');
}
// Extra safety.
\core\session\manager::write_close();
$keyvalue = required_param('key', PARAM_ALPHANUM);
if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
print_error('invalidkey');
}
if (!empty($key->validuntil) and $key->validuntil < time()) {
print_error('expiredkey');
}
if ($key->iprestriction) {
$remoteaddr = getremoteaddr(null);
if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
print_error('ipmismatch');
}
}
if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
print_error('invaliduserid');
}
// Emulate normal session.
enrol_check_plugins($user);
\core\session\manager::set_user($user);
// Note we are not using normal login.
if (!defined('USER_KEY_LOGIN')) {
define('USER_KEY_LOGIN', true);
}
// Return instance id - it might be empty.
return $key->instance;
}
/**
* Creates a new private user access key.
*
* @param string $script unique target identifier
* @param int $userid
* @param int $instance optional instance id
* @param string $iprestriction optional ip restricted access
* @param timestamp $validuntil key valid only until given data
* @return string access key value
*/
function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
global $DB;
$key = new stdClass();
$key->script = $script;
$key->userid = $userid;
$key->instance = $instance;
$key->iprestriction = $iprestriction;
$key->validuntil = $validuntil;
$key->timecreated = time();
// Something long and unique.
$key->value = md5($userid.'_'.time().random_string(40));
while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
// Must be unique.
$key->value = md5($userid.'_'.time().random_string(40));
}
$DB->insert_record('user_private_key', $key);
return $key->value;
}
/**
* Delete the user's new private user access keys for a particular script.
*
* @param string $script unique target identifier
* @param int $userid
* @return void
*/
function delete_user_key($script, $userid) {
global $DB;
$DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
}
/**
* Gets a private user access key (and creates one if one doesn't exist).
*
* @param string $script unique target identifier
* @param int $userid
* @param int $instance optional instance id
* @param string $iprestriction optional ip restricted access
* @param timestamp $validuntil key valid only until given data
* @return string access key value
*/
function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
global $DB;
if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
'instance' => $instance, 'iprestriction' => $iprestriction,
'validuntil' => $validuntil))) {
return $key->value;
} else {
return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
}
}
/**
* Modify the user table by setting the currently logged in user's last login to now.
*
* @return bool Always returns true
*/
function update_user_login_times() {
global $USER, $DB;
if (isguestuser()) {
// Do not update guest access times/ips for performance.
return true;
}
$now = time();
$user = new stdClass();
$user->id = $USER->id;
// Make sure all users that logged in have some firstaccess.
if ($USER->firstaccess == 0) {
$USER->firstaccess = $user->firstaccess = $now;
}
// Store the previous current as lastlogin.
$USER->lastlogin = $user->lastlogin = $USER->currentlogin;
$USER->currentlogin = $user->currentlogin = $now;
// Function user_accesstime_log() may not update immediately, better do it here.
$USER->lastaccess = $user->lastaccess = $now;
$USER->lastip = $user->lastip = getremoteaddr();
// Note: do not call user_update_user() here because this is part of the login process,
// the login event means that these fields were updated.
$DB->update_record('user', $user);
return true;
}
/**
* Determines if a user has completed setting up their account.
*
* @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
* @return bool
*/
function user_not_fully_set_up($user) {
if (isguestuser($user)) {
return false;
}
return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
}
/**
* Check whether the user has exceeded the bounce threshold
*
* @param stdClass $user A {@link $USER} object
* @return bool true => User has exceeded bounce threshold
*/
function over_bounce_threshold($user) {
global $CFG, $DB;
if (empty($CFG->handlebounces)) {
return false;
}
if (empty($user->id)) {
// No real (DB) user, nothing to do here.
return false;
}
// Set sensible defaults.
if (empty($CFG->minbounces)) {
$CFG->minbounces = 10;
}
if (empty($CFG->bounceratio)) {
$CFG->bounceratio = .20;
}
$bouncecount = 0;
$sendcount = 0;
if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
$bouncecount = $bounce->value;
}
if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
$sendcount = $send->value;
}
return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
}
/**
* Used to increment or reset email sent count
*
* @param stdClass $user object containing an id
* @param bool $reset will reset the count to 0
* @return void
*/
function set_send_count($user, $reset=false) {
global $DB;
if (empty($user->id)) {
// No real (DB) user, nothing to do here.
return;
}
if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
$pref->value = (!empty($reset)) ? 0 : $pref->value+1;
$DB->update_record('user_preferences', $pref);
} else if (!empty($reset)) {
// If it's not there and we're resetting, don't bother. Make a new one.
$pref = new stdClass();
$pref->name = 'email_send_count';
$pref->value = 1;
$pref->userid = $user->id;
$DB->insert_record('user_preferences', $pref, false);
}
}
/**
* Increment or reset user's email bounce count
*
* @param stdClass $user object containing an id
* @param bool $reset will reset the count to 0
*/
function set_bounce_count($user, $reset=false) {
global $DB;
if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
$pref->value = (!empty($reset)) ? 0 : $pref->value+1;
$DB->update_record('user_preferences', $pref);
} else if (!empty($reset)) {
// If it's not there and we're resetting, don't bother. Make a new one.
$pref = new stdClass();
$pref->name = 'email_bounce_count';
$pref->value = 1;
$pref->userid = $user->id;
$DB->insert_record('user_preferences', $pref, false);
}
}
/**
* Determines if the logged in user is currently moving an activity
*
* @param int $courseid The id of the course being tested
* @return bool
*/
function ismoving($courseid) {
global $USER;
if (!empty($USER->activitycopy)) {
return ($USER->activitycopycourse == $courseid);
}
return false;
}
/**
* Returns a persons full name
*
* Given an object containing all of the users name values, this function returns a string with the full name of the person.
* The result may depend on system settings or language. 'override' will force both names to be used even if system settings
* specify one.
*
* @param stdClass $user A {@link $USER} object to get full name of.
* @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
* @return string
*/
function fullname($user, $override=false) {
global $CFG, $SESSION;
if (!isset($user->firstname) and !isset($user->lastname)) {
return '';
}
// Get all of the name fields.
$allnames = get_all_user_name_fields();
if ($CFG->debugdeveloper) {
foreach ($allnames as $allname) {
if (!array_key_exists($allname, $user)) {
// If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
// Message has been sent, no point in sending the message multiple times.
break;
}
}
}
if (!$override) {
if (!empty($CFG->forcefirstname)) {
$user->firstname = $CFG->forcefirstname;
}
if (!empty($CFG->forcelastname)) {
$user->lastname = $CFG->forcelastname;
}
}
if (!empty($SESSION->fullnamedisplay)) {
$CFG->fullnamedisplay = $SESSION->fullnamedisplay;
}
$template = null;
// If the fullnamedisplay setting is available, set the template to that.
if (isset($CFG->fullnamedisplay)) {
$template = $CFG->fullnamedisplay;
}
// If the template is empty, or set to language, or $override is set, return the language string.
if (empty($template) || $template == 'language' || $override) {
return get_string('fullnamedisplay', null, $user);
}
$requirednames = array();
// With each name, see if it is in the display name template, and add it to the required names array if it is.
foreach ($allnames as $allname) {
if (strpos($template, $allname) !== false) {
$requirednames[] = $allname;
}
}
$displayname = $template;
// Switch in the actual data into the template.
foreach ($requirednames as $altname) {
if (isset($user->$altname)) {
// Using empty() on the below if statement causes breakages.
if ((string)$user->$altname == '') {
$displayname = str_replace($altname, 'EMPTY', $displayname);
} else {
$displayname = str_replace($altname, $user->$altname, $displayname);
}
} else {
$displayname = str_replace($altname, 'EMPTY', $displayname);
}
}
// Tidy up any misc. characters (Not perfect, but gets most characters).
// Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
// katakana and parenthesis.
$patterns = array();
// This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
// filled in by a user.
// The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
$patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
// This regular expression is to remove any double spaces in the display name.
$patterns[] = '/\s{2,}/u';
foreach ($patterns as $pattern) {
$displayname = preg_replace($pattern, ' ', $displayname);
}
// Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
$displayname = trim($displayname);
if (empty($displayname)) {
// Going with just the first name if no alternate fields are filled out. May be changed later depending on what
// people in general feel is a good setting to fall back on.
$displayname = $user->firstname;
}
return $displayname;
}
/**
* A centralised location for the all name fields. Returns an array / sql string snippet.
*
* @param bool $returnsql True for an sql select field snippet.
* @param string $tableprefix table query prefix to use in front of each field.
* @param string $prefix prefix added to the name fields e.g. authorfirstname.
* @param string $fieldprefix sql field prefix e.g. id AS userid.
* @return array|string All name fields.
*/
function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null) {
$alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
'lastnamephonetic' => 'lastnamephonetic',
'middlename' => 'middlename',
'alternatename' => 'alternatename',
'firstname' => 'firstname',
'lastname' => 'lastname');
// Let's add a prefix to the array of user name fields if provided.
if ($prefix) {
foreach ($alternatenames as $key => $altname) {
$alternatenames[$key] = $prefix . $altname;
}
}
// Create an sql field snippet if requested.
if ($returnsql) {
if ($tableprefix) {
if ($fieldprefix) {
foreach ($alternatenames as $key => $altname) {
$alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
}
} else {
foreach ($alternatenames as $key => $altname) {
$alternatenames[$key] = $tableprefix . '.' . $altname;
}
}
}
$alternatenames = implode(',', $alternatenames);
}
return $alternatenames;
}
/**
* Reduces lines of duplicated code for getting user name fields.
*
* @param object $addtoobject Object to add user name fields to.
* @param object $secondobject Object that contains user name field information.
* @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
* @param array $additionalfields Additional fields to be matched with data in the second object.
* The key can be set to the user table field name.
* @return object User name fields.
*/
function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
$fields = get_all_user_name_fields(false, null, $prefix);
if ($additionalfields) {
// Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
// the key is a number and then sets the key to the array value.
foreach ($additionalfields as $key => $value) {
if (is_numeric($key)) {
$additionalfields[$value] = $prefix . $value;
unset($additionalfields[$key]);
} else {
$additionalfields[$key] = $prefix . $value;
}
}
$fields = array_merge($fields, $additionalfields);
}
foreach ($fields as $key => $field) {
// Important that we have all of the user name fields present in the object that we are sending back.
$addtoobject->$key = '';
if (isset($secondobject->$field)) {
$addtoobject->$key = $secondobject->$field;
}
}
return $addtoobject;
}
/**
* Returns an array of values in order of occurance in a provided string.
* The key in the result is the character postion in the string.
*
* @param array $values Values to be found in the string format
* @param string $stringformat The string which may contain values being searched for.
* @return array An array of values in order according to placement in the string format.
*/
function order_in_string($values, $stringformat) {
$valuearray = array();
foreach ($values as $value) {
$pattern = "/$value\b/";
// Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
if (preg_match($pattern, $stringformat)) {
$replacement = "thing";
// Replace the value with something more unique to ensure we get the right position when using strpos().
$newformat = preg_replace($pattern, $replacement, $stringformat);
$position = strpos($newformat, $replacement);
$valuearray[$position] = $value;
}
}
ksort($valuearray);
return $valuearray;
}
/**
* Checks if current user is shown any extra fields when listing users.
*
* @param object $context Context
* @param array $already Array of fields that we're going to show anyway
* so don't bother listing them
* @return array Array of field names from user table, not including anything
* listed in $already
*/
function get_extra_user_fields($context, $already = array()) {
global $CFG;
// Only users with permission get the extra fields.
if (!has_capability('moodle/site:viewuseridentity', $context)) {
return array();
}
// Split showuseridentity on comma.
if (empty($CFG->showuseridentity)) {
// Explode gives wrong result with empty string.
$extra = array();
} else {
$extra = explode(',', $CFG->showuseridentity);
}
$renumber = false;
foreach ($extra as $key => $field) {
if (in_array($field, $already)) {
unset($extra[$key]);
$renumber = true;
}
}
if ($renumber) {
// For consistency, if entries are removed from array, renumber it
// so they are numbered as you would expect.
$extra = array_merge($extra);
}
return $extra;
}
/**
* If the current user is to be shown extra user fields when listing or
* selecting users, returns a string suitable for including in an SQL select
* clause to retrieve those fields.
*
* @param context $context Context
* @param string $alias Alias of user table, e.g. 'u' (default none)
* @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
* @param array $already Array of fields that we're going to include anyway so don't list them (default none)
* @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
*/
function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
$fields = get_extra_user_fields($context, $already);
$result = '';
// Add punctuation for alias.
if ($alias !== '') {
$alias .= '.';
}
foreach ($fields as $field) {
$result .= ', ' . $alias . $field;
if ($prefix) {
$result .= ' AS ' . $prefix . $field;
}
}
return $result;
}
/**
* Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
* @param string $field Field name, e.g. 'phone1'
* @return string Text description taken from language file, e.g. 'Phone number'
*/
function get_user_field_name($field) {
// Some fields have language strings which are not the same as field name.
switch ($field) {
case 'phone1' : {
return get_string('phone');
}
case 'url' : {
return get_string('webpage');
}
case 'icq' : {
return get_string('icqnumber');
}
case 'skype' : {
return get_string('skypeid');
}
case 'aim' : {
return get_string('aimid');
}
case 'yahoo' : {
return get_string('yahooid');
}
case 'msn' : {
return get_string('msnid');
}
}
// Otherwise just use the same lang string.
return get_string($field);
}
/**
* Returns whether a given authentication plugin exists.
*
* @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
* @return boolean Whether the plugin is available.
*/
function exists_auth_plugin($auth) {
global $CFG;
if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
}
return false;
}
/**
* Checks if a given plugin is in the list of enabled authentication plugins.
*
* @param string $auth Authentication plugin.
* @return boolean Whether the plugin is enabled.
*/
function is_enabled_auth($auth) {
if (empty($auth)) {
return false;
}
$enabled = get_enabled_auth_plugins();
return in_array($auth, $enabled);
}
/**
* Returns an authentication plugin instance.
*
* @param string $auth name of authentication plugin
* @return auth_plugin_base An instance of the required authentication plugin.
*/
function get_auth_plugin($auth) {
global $CFG;
// Check the plugin exists first.
if (! exists_auth_plugin($auth)) {
print_error('authpluginnotfound', 'debug', '', $auth);
}
// Return auth plugin instance.
require_once("{$CFG->dirroot}/auth/$auth/auth.php");
$class = "auth_plugin_$auth";
return new $class;
}
/**
* Returns array of active auth plugins.
*
* @param bool $fix fix $CFG->auth if needed
* @return array
*/
function get_enabled_auth_plugins($fix=false) {
global $CFG;
$default = array('manual', 'nologin');
if (empty($CFG->auth)) {
$auths = array();
} else {
$auths = explode(',', $CFG->auth);
}
if ($fix) {
$auths = array_unique($auths);
foreach ($auths as $k => $authname) {
if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
unset($auths[$k]);
}
}
$newconfig = implode(',', $auths);
if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
set_config('auth', $newconfig);
}
}
return (array_merge($default, $auths));
}
/**
* Returns true if an internal authentication method is being used.
* if method not specified then, global default is assumed
*
* @param string $auth Form of authentication required
* @return bool
*/
function is_internal_auth($auth) {
// Throws error if bad $auth.
$authplugin = get_auth_plugin($auth);
return $authplugin->is_internal();
}
/**
* Returns true if the user is a 'restored' one.
*
* Used in the login process to inform the user and allow him/her to reset the password
*
* @param string $username username to be checked
* @return bool
*/
function is_restored_user($username) {
global $CFG, $DB;
return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
}
/**
* Returns an array of user fields
*
* @return array User field/column names
*/
function get_user_fieldnames() {
global $DB;
$fieldarray = $DB->get_columns('user');
unset($fieldarray['id']);
$fieldarray = array_keys($fieldarray);
return $fieldarray;
}
/**
* Creates a bare-bones user record
*
* @todo Outline auth types and provide code example
*
* @param string $username New user's username to add to record
* @param string $password New user's password to add to record
* @param string $auth Form of authentication required
* @return stdClass A complete user object
*/
function create_user_record($username, $password, $auth = 'manual') {
global $CFG, $DB;
require_once($CFG->dirroot.'/user/profile/lib.php');
require_once($CFG->dirroot.'/user/lib.php');
// Just in case check text case.
$username = trim(core_text::strtolower($username));
$authplugin = get_auth_plugin($auth);
$customfields = $authplugin->get_custom_user_profile_fields();
$newuser = new stdClass();
if ($newinfo = $authplugin->get_userinfo($username)) {
$newinfo = truncate_userinfo($newinfo);
foreach ($newinfo as $key => $value) {
if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
$newuser->$key = $value;
}
}
}
if (!empty($newuser->email)) {
if (email_is_not_allowed($newuser->email)) {
unset($newuser->email);
}
}
if (!isset($newuser->city)) {
$newuser->city = '';
}
$newuser->auth = $auth;
$newuser->username = $username;
// Fix for MDL-8480
// user CFG lang for user if $newuser->lang is empty
// or $user->lang is not an installed language.
if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
$newuser->lang = $CFG->lang;
}
$newuser->confirmed = 1;
$newuser->lastip = getremoteaddr();
$newuser->timecreated = time();
$newuser->timemodified = $newuser->timecreated;
$newuser->mnethostid = $CFG->mnet_localhost_id;
$newuser->id = user_create_user($newuser, false, false);
// Save user profile data.
profile_save_data($newuser);
$user = get_complete_user_data('id', $newuser->id);
if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
set_user_preference('auth_forcepasswordchange', 1, $user);
}
// Set the password.
update_internal_user_password($user, $password);
// Trigger event.
\core\event\user_created::create_from_userid($newuser->id)->trigger();
return $user;
}
/**
* Will update a local user record from an external source (MNET users can not be updated using this method!).
*
* @param string $username user's username to update the record
* @return stdClass A complete user object
*/
function update_user_record($username) {
global $DB, $CFG;
require_once($CFG->dirroot."/user/profile/lib.php");
require_once($CFG->dirroot.'/user/lib.php');
// Just in case check text case.
$username = trim(core_text::strtolower($username));
$oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
$newuser = array();
$userauth = get_auth_plugin($oldinfo->auth);
if ($newinfo = $userauth->get_userinfo($username)) {
$newinfo = truncate_userinfo($newinfo);
$customfields = $userauth->get_custom_user_profile_fields();
foreach ($newinfo as $key => $value) {
$key = strtolower($key);
$iscustom = in_array($key, $customfields);
if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
// Unknown or must not be changed.
continue;
}
$confval = $userauth->config->{'field_updatelocal_' . $key};
$lockval = $userauth->config->{'field_lock_' . $key};
if (empty($confval) || empty($lockval)) {
continue;
}
if ($confval === 'onlogin') {
// MDL-4207 Don't overwrite modified user profile values with
// empty LDAP values when 'unlocked if empty' is set. The purpose
// of the setting 'unlocked if empty' is to allow the user to fill
// in a value for the selected field _if LDAP is giving
// nothing_ for this field. Thus it makes sense to let this value
// stand in until LDAP is giving a value for this field.
if (!(empty($value) && $lockval === 'unlockedifempty')) {
if ($iscustom || (in_array($key, $userauth->userfields) &&
((string)$oldinfo->$key !== (string)$value))) {
$newuser[$key] = (string)$value;
}
}
}
}
if ($newuser) {
$newuser['id'] = $oldinfo->id;
$newuser['timemodified'] = time();
user_update_user((object) $newuser, false, false);
// Save user profile data.
profile_save_data((object) $newuser);
// Trigger event.
\core\event\user_updated::create_from_userid($newuser['id'])->trigger();
}
}
return get_complete_user_data('id', $oldinfo->id);
}
/**
* Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
*
* @param array $info Array of user properties to truncate if needed
* @return array The now truncated information that was passed in
*/
function truncate_userinfo(array $info) {
// Define the limits.
$limit = array(
'username' => 100,
'idnumber' => 255,
'firstname' => 100,
'lastname' => 100,
'email' => 100,
'icq' => 15,
'phone1' => 20,
'phone2' => 20,
'institution' => 255,
'department' => 255,
'address' => 255,
'city' => 120,
'country' => 2,
'url' => 255,
);
// Apply where needed.
foreach (array_keys($info) as $key) {
if (!empty($limit[$key])) {
$info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
}
}
return $info;
}
/**
* Marks user deleted in internal user database and notifies the auth plugin.
* Also unenrols user from all roles and does other cleanup.
*
* Any plugin that needs to purge user data should register the 'user_deleted' event.
*
* @param stdClass $user full user object before delete
* @return boolean success
* @throws coding_exception if invalid $user parameter detected
*/
function delete_user(stdClass $user) {
global $CFG, $DB;
require_once($CFG->libdir.'/grouplib.php');
require_once($CFG->libdir.'/gradelib.php');
require_once($CFG->dirroot.'/message/lib.php');
require_once($CFG->dirroot.'/tag/lib.php');
require_once($CFG->dirroot.'/user/lib.php');
// Make sure nobody sends bogus record type as parameter.
if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
throw new coding_exception('Invalid $user parameter in delete_user() detected');
}
// Better not trust the parameter and fetch the latest info this will be very expensive anyway.
if (!$user = $DB->get_record('user', array('id' => $user->id))) {
debugging('Attempt to delete unknown user account.');
return false;
}
// There must be always exactly one guest record, originally the guest account was identified by username only,
// now we use $CFG->siteguest for performance reasons.
if ($user->username === 'guest' or isguestuser($user)) {
debugging('Guest user account can not be deleted.');
return false;
}
// Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
// if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
if ($user->auth === 'manual' and is_siteadmin($user)) {
debugging('Local administrator accounts can not be deleted.');
return false;
}
// Keep user record before updating it, as we have to pass this to user_deleted event.
$olduser = clone $user;
// Keep a copy of user context, we need it for event.
$usercontext = context_user::instance($user->id);
// Delete all grades - backup is kept in grade_grades_history table.
grade_user_delete($user->id);
// Move unread messages from this user to read.
message_move_userfrom_unread2read($user->id);
// TODO: remove from cohorts using standard API here.
// Remove user tags.
tag_set('user', $user->id, array());
// Unconditionally unenrol from all courses.
enrol_user_delete($user);
// Unenrol from all roles in all contexts.
// This might be slow but it is really needed - modules might do some extra cleanup!
role_unassign_all(array('userid' => $user->id));
// Now do a brute force cleanup.
// Remove from all cohorts.
$DB->delete_records('cohort_members', array('userid' => $user->id));
// Remove from all groups.
$DB->delete_records('groups_members', array('userid' => $user->id));
// Brute force unenrol from all courses.
$DB->delete_records('user_enrolments', array('userid' => $user->id));
// Purge user preferences.
$DB->delete_records('user_preferences', array('userid' => $user->id));
// Purge user extra profile info.
$DB->delete_records('user_info_data', array('userid' => $user->id));
// Last course access not necessary either.
$DB->delete_records('user_lastaccess', array('userid' => $user->id));
// Remove all user tokens.
$DB->delete_records('external_tokens', array('userid' => $user->id));
// Unauthorise the user for all services.
$DB->delete_records('external_services_users', array('userid' => $user->id));
// Remove users private keys.
$DB->delete_records('user_private_key', array('userid' => $user->id));
// Remove users customised pages.
$DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
// Force logout - may fail if file based sessions used, sorry.
\core\session\manager::kill_user_sessions($user->id);
// Workaround for bulk deletes of users with the same email address.
$delname = clean_param($user->email . "." . time(), PARAM_USERNAME);
while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
$delname++;
}
// Mark internal user record as "deleted".
$updateuser = new stdClass();
$updateuser->id = $user->id;
$updateuser->deleted = 1;
$updateuser->username = $delname; // Remember it just in case.
$updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
$updateuser->idnumber = ''; // Clear this field to free it up.
$updateuser->picture = 0;
$updateuser->timemodified = time();
// Don't trigger update event, as user is being deleted.
user_update_user($updateuser, false, false);
// Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
context_helper::delete_instance(CONTEXT_USER, $user->id);
// Any plugin that needs to cleanup should register this event.
// Trigger event.
$event = \core\event\user_deleted::create(
array(
'objectid' => $user->id,
'context' => $usercontext,
'other' => array(
'username' => $user->username,
'email' => $user->email,
'idnumber' => $user->idnumber,
'picture' => $user->picture,
'mnethostid' => $user->mnethostid
)
)
);
$event->add_record_snapshot('user', $olduser);
$event->trigger();
// We will update the user's timemodified, as it will be passed to the user_deleted event, which
// should know about this updated property persisted to the user's table.
$user->timemodified = $updateuser->timemodified;
// Notify auth plugin - do not block the delete even when plugin fails.
$authplugin = get_auth_plugin($user->auth);
$authplugin->user_delete($user);
return true;
}
/**
* Retrieve the guest user object.
*
* @return stdClass A {@link $USER} object
*/
function guest_user() {
global $CFG, $DB;
if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
$newuser->confirmed = 1;
$newuser->lang = $CFG->lang;
$newuser->lastip = getremoteaddr();
}
return $newuser;
}
/**
* Authenticates a user against the chosen authentication mechanism
*
* Given a username and password, this function looks them
* up using the currently selected authentication mechanism,
* and if the authentication is successful, it returns a
* valid $user object from the 'user' table.
*
* Uses auth_ functions from the currently active auth module
*
* After authenticate_user_login() returns success, you will need to
* log that the user has logged in, and call complete_user_login() to set
* the session up.
*
* Note: this function works only with non-mnet accounts!
*
* @param string $username User's username
* @param string $password User's password
* @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
* @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
* @return stdClass|false A {@link $USER} object or false if error
*/
function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
global $CFG, $DB;
require_once("$CFG->libdir/authlib.php");
$authsenabled = get_enabled_auth_plugins();
if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
// Use manual if auth not set.
$auth = empty($user->auth) ? 'manual' : $user->auth;
if (!empty($user->suspended)) {
add_to_log(SITEID, 'login', 'error', 'index.php', $username);
error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
$failurereason = AUTH_LOGIN_SUSPENDED;
return false;
}
if ($auth=='nologin' or !is_enabled_auth($auth)) {
add_to_log(SITEID, 'login', 'error', 'index.php', $username);
error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
// Legacy way to suspend user.
$failurereason = AUTH_LOGIN_SUSPENDED;
return false;
}
$auths = array($auth);
} else {
// Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
$failurereason = AUTH_LOGIN_NOUSER;
return false;
}
// Do not try to authenticate non-existent accounts when user creation is not disabled.
if (!empty($CFG->authpreventaccountcreation)) {
add_to_log(SITEID, 'login', 'error', 'index.php', $username);
error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".$_SERVER['HTTP_USER_AGENT']);
$failurereason = AUTH_LOGIN_NOUSER;
return false;
}
// User does not exist.
$auths = $authsenabled;
$user = new stdClass();
$user->id = 0;
}
if ($ignorelockout) {
// Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
// or this function is called from a SSO script.
} else if ($user->id) {
// Verify login lockout after other ways that may prevent user login.
if (login_is_lockedout($user)) {
add_to_log(SITEID, 'login', 'error', 'index.php', $username);
error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
$failurereason = AUTH_LOGIN_LOCKOUT;
return false;
}
} else {
// We can not lockout non-existing accounts.
}
foreach ($auths as $auth) {
$authplugin = get_auth_plugin($auth);
// On auth fail fall through to the next plugin.
if (!$authplugin->user_login($username, $password)) {
continue;
}
// Successful authentication.
if ($user->id) {
// User already exists in database.
if (empty($user->auth)) {
// For some reason auth isn't set yet.
$DB->set_field('user', 'auth', $auth, array('username' => $username));
$user->auth = $auth;
}
// If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
// the current hash algorithm while we have access to the user's password.
update_internal_user_password($user, $password);
if ($authplugin->is_synchronised_with_external()) {
// Update user record from external DB.
$user = update_user_record($username);
}
} else {
// Create account, we verified above that user creation is allowed.
$user = create_user_record($username, $password, $auth);
}
$authplugin->sync_roles($user);
foreach ($authsenabled as $hau) {
$hauth = get_auth_plugin($hau);
$hauth->user_authenticated_hook($user, $username, $password);
}
if (empty($user->id)) {
$failurereason = AUTH_LOGIN_NOUSER;
return false;
}
if (!empty($user->suspended)) {
// Just in case some auth plugin suspended account.
add_to_log(SITEID, 'login', 'error', 'index.php', $username);
error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
$failurereason = AUTH_LOGIN_SUSPENDED;
return false;
}
login_attempt_valid($user);
$failurereason = AUTH_LOGIN_OK;
return $user;
}
// Failed if all the plugins have failed.
add_to_log(SITEID, 'login', 'error', 'index.php', $username);
if (debugging('', DEBUG_ALL)) {
error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
}
if ($user->id) {
login_attempt_failed($user);
$failurereason = AUTH_LOGIN_FAILED;
} else {
$failurereason = AUTH_LOGIN_NOUSER;
}
return false;
}
/**
* Call to complete the user login process after authenticate_user_login()
* has succeeded. It will setup the $USER variable and other required bits
* and pieces.
*
* NOTE:
* - It will NOT log anything -- up to the caller to decide what to log.
* - this function does not set any cookies any more!
*
* @param stdClass $user
* @return stdClass A {@link $USER} object - BC only, do not use
*/
function complete_user_login($user) {
global $CFG, $USER;
\core\session\manager::login_user($user);
// Reload preferences from DB.
unset($USER->preference);
check_user_preferences_loaded($USER);
// Update login times.
update_user_login_times();
// Extra session prefs init.
set_login_session_preferences();
// Trigger login event.
$event = \core\event\user_loggedin::create(
array(
'userid' => $USER->id,
'objectid' => $USER->id,
'other' => array('username' => $USER->username),
)
);
$event->trigger();
if (isguestuser()) {
// No need to continue when user is THE guest.
return $USER;
}
if (CLI_SCRIPT) {
// We can redirect to password change URL only in browser.
return $USER;
}
// Select password change url.
$userauth = get_auth_plugin($USER->auth);
// Check whether the user should be changing password.
if (get_user_preferences('auth_forcepasswordchange', false)) {
if ($userauth->can_change_password()) {
if ($changeurl = $userauth->change_password_url()) {
redirect($changeurl);
} else {
redirect($CFG->httpswwwroot.'/login/change_password.php');
}
} else {
print_error('nopasswordchangeforced', 'auth');
}
}
return $USER;
}
/**
* Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
*
* @param string $password String to check.
* @return boolean True if the $password matches the format of an md5 sum.
*/
function password_is_legacy_hash($password) {
return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
}
/**
* Checks whether the password compatibility library will work with the current
* version of PHP. This cannot be done using PHP version numbers since the fix
* has been backported to earlier versions in some distributions.
*
* See https://github.com/ircmaxell/password_compat/issues/10 for more details.
*
* @return bool True if the library is NOT supported.
*/
function password_compat_not_supported() {
$hash = '$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG';
// Create a one off application cache to store bcrypt support status as
// the support status doesn't change and crypt() is slow.
$cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'password_compat');
if (!$bcryptsupport = $cache->get('bcryptsupport')) {
$test = crypt('password', $hash);
// Cache string instead of boolean to avoid MDL-37472.
if ($test == $hash) {
$bcryptsupport = 'supported';
} else {
$bcryptsupport = 'not supported';
}
$cache->set('bcryptsupport', $bcryptsupport);
}
// Return true if bcrypt *not* supported.
return ($bcryptsupport !== 'supported');
}
/**
* Compare password against hash stored in user object to determine if it is valid.
*
* If necessary it also updates the stored hash to the current format.
*
* @param stdClass $user (Password property may be updated).
* @param string $password Plain text password.
* @return bool True if password is valid.
*/
function validate_internal_user_password($user, $password) {
global $CFG;
require_once($CFG->libdir.'/password_compat/lib/password.php');
if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
// Internal password is not used at all, it can not validate.
return false;
}
// If hash isn't a legacy (md5) hash, validate using the library function.
if (!password_is_legacy_hash($user->password)) {
return password_verify($password, $user->password);
}
// Otherwise we need to check for a legacy (md5) hash instead. If the hash
// is valid we can then update it to the new algorithm.
$sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
$validated = false;
if ($user->password === md5($password.$sitesalt)
or $user->password === md5($password)
or $user->password === md5(addslashes($password).$sitesalt)
or $user->password === md5(addslashes($password))) {
// Note: we are intentionally using the addslashes() here because we
// need to accept old password hashes of passwords with magic quotes.
$validated = true;
} else {
for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
$alt = 'passwordsaltalt'.$i;
if (!empty($CFG->$alt)) {
if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
$validated = true;
break;
}
}
}
}
if ($validated) {
// If the password matches the existing md5 hash, update to the
// current hash algorithm while we have access to the user's password.
update_internal_user_password($user, $password);
}
return $validated;
}
/**
* Calculate hash for a plain text password.
*
* @param string $password Plain text password to be hashed.
* @param bool $fasthash If true, use a low cost factor when generating the hash
* This is much faster to generate but makes the hash
* less secure. It is used when lots of hashes need to
* be generated quickly.
* @return string The hashed password.
*
* @throws moodle_exception If a problem occurs while generating the hash.
*/
function hash_internal_user_password($password, $fasthash = false) {
global $CFG;
require_once($CFG->libdir.'/password_compat/lib/password.php');
// Use the legacy hashing algorithm (md5) if PHP is not new enough to support bcrypt properly.
if (password_compat_not_supported()) {
if (isset($CFG->passwordsaltmain)) {
return md5($password.$CFG->passwordsaltmain);
} else {
return md5($password);
}
}
// Set the cost factor to 4 for fast hashing, otherwise use default cost.
$options = ($fasthash) ? array('cost' => 4) : array();
$generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
if ($generatedhash === false || $generatedhash === null) {
throw new moodle_exception('Failed to generate password hash.');
}
return $generatedhash;
}
/**
* Update password hash in user object (if necessary).
*
* The password is updated if:
* 1. The password has changed (the hash of $user->password is different
* to the hash of $password).
* 2. The existing hash is using an out-of-date algorithm (or the legacy
* md5 algorithm).
*
* Updating the password will modify the $user object and the database
* record to use the current hashing algorithm.
*
* @param stdClass $user User object (password property may be updated).
* @param string $password Plain text password.
* @return bool Always returns true.
*/
function update_internal_user_password($user, $password) {
global $CFG, $DB;
require_once($CFG->libdir.'/password_compat/lib/password.php');
// Use the legacy hashing algorithm (md5) if PHP doesn't support bcrypt properly.
$legacyhash = password_compat_not_supported();
// Figure out what the hashed password should be.
$authplugin = get_auth_plugin($user->auth);
if ($authplugin->prevent_local_passwords()) {
$hashedpassword = AUTH_PASSWORD_NOT_CACHED;
} else {
$hashedpassword = hash_internal_user_password($password);
}
if ($legacyhash || $hashedpassword == AUTH_PASSWORD_NOT_CACHED) {
$passwordchanged = ($user->password !== $hashedpassword);
$algorithmchanged = false;
} else {
if (isset($user->password)) {
// If verification fails then it means the password has changed.
$passwordchanged = !password_verify($password, $user->password);
$algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
} else {
$passwordchanged = true;
}
}
if ($passwordchanged || $algorithmchanged) {
$DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
$user->password = $hashedpassword;
// Trigger event.
$event = \core\event\user_updated::create(array(
'objectid' => $user->id,
'context' => context_user::instance($user->id)
));
$event->add_record_snapshot('user', $user);
$event->trigger();
}
return true;
}
/**
* Get a complete user record, which includes all the info in the user record.
*
* Intended for setting as $USER session variable
*
* @param string $field The user field to be checked for a given value.
* @param string $value The value to match for $field.
* @param int $mnethostid
* @return mixed False, or A {@link $USER} object.
*/
function get_complete_user_data($field, $value, $mnethostid = null) {
global $CFG, $DB;
if (!$field || !$value) {
return false;
}
// Build the WHERE clause for an SQL query.
$params = array('fieldval' => $value);
$constraints = "$field = :fieldval AND deleted <> 1";
// If we are loading user data based on anything other than id,
// we must also restrict our search based on mnet host.
if ($field != 'id') {
if (empty($mnethostid)) {
// If empty, we restrict to local users.
$mnethostid = $CFG->mnet_localhost_id;
}
}
if (!empty($mnethostid)) {
$params['mnethostid'] = $mnethostid;
$constraints .= " AND mnethostid = :mnethostid";
}
// Get all the basic user data.
if (! $user = $DB->get_record_select('user', $constraints, $params)) {
return false;
}
// Get various settings and preferences.
// Preload preference cache.
check_user_preferences_loaded($user);
// Load course enrolment related stuff.
$user->lastcourseaccess = array(); // During last session.
$user->currentcourseaccess = array(); // During current session.
if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
foreach ($lastaccesses as $lastaccess) {
$user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
}
}
$sql = "SELECT g.id, g.courseid
FROM {groups} g, {groups_members} gm
WHERE gm.groupid=g.id AND gm.userid=?";
// This is a special hack to speedup calendar display.
$user->groupmember = array();
if (!isguestuser($user)) {
if ($groups = $DB->get_records_sql($sql, array($user->id))) {
foreach ($groups as $group) {
if (!array_key_exists($group->courseid, $user->groupmember)) {
$user->groupmember[$group->courseid] = array();
}
$user->groupmember[$group->courseid][$group->id] = $group->id;
}
}
}
// Add the custom profile fields to the user record.
$user->profile = array();
if (!isguestuser($user)) {
require_once($CFG->dirroot.'/user/profile/lib.php');
profile_load_custom_fields($user);
}
// Rewrite some variables if necessary.
if (!empty($user->description)) {
// No need to cart all of it around.
$user->description = true;
}
if (isguestuser($user)) {
// Guest language always same as site.
$user->lang = $CFG->lang;
// Name always in current language.
$user->firstname = get_string('guestuser');
$user->lastname = ' ';
}
return $user;
}
/**
* Validate a password against the configured password policy
*
* @param string $password the password to be checked against the password policy
* @param string $errmsg the error message to display when the password doesn't comply with the policy.
* @return bool true if the password is valid according to the policy. false otherwise.
*/
function check_password_policy($password, &$errmsg) {
global $CFG;
if (empty($CFG->passwordpolicy)) {
return true;
}
$errmsg = '';
if (core_text::strlen($password) < $CFG->minpasswordlength) {
$errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
}
if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
$errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
}
if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
$errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
}
if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
$errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
}
if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
$errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
}
if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
$errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
}
if ($errmsg == '') {
return true;
} else {
return false;
}
}
/**
* When logging in, this function is run to set certain preferences for the current SESSION.
*/
function set_login_session_preferences() {
global $SESSION;
$SESSION->justloggedin = true;
unset($SESSION->lang);
unset($SESSION->load_navigation_admin);
}
/**
* Delete a course, including all related data from the database, and any associated files.
*
* @param mixed $courseorid The id of the course or course object to delete.
* @param bool $showfeedback Whether to display notifications of each action the function performs.
* @return bool true if all the removals succeeded. false if there were any failures. If this
* method returns false, some of the removals will probably have succeeded, and others
* failed, but you have no way of knowing which.
*/
function delete_course($courseorid, $showfeedback = true) {
global $DB;
if (is_object($courseorid)) {
$courseid = $courseorid->id;
$course = $courseorid;
} else {
$courseid = $courseorid;
if (!$course = $DB->get_record('course', array('id' => $courseid))) {
return false;
}
}
$context = context_course::instance($courseid);
// Frontpage course can not be deleted!!
if ($courseid == SITEID) {
return false;
}
// Make the course completely empty.
remove_course_contents($courseid, $showfeedback);
// Delete the course and related context instance.
context_helper::delete_instance(CONTEXT_COURSE, $courseid);
$DB->delete_records("course", array("id" => $courseid));
$DB->delete_records("course_format_options", array("courseid" => $courseid));
// Trigger a course deleted event.
$event = \core\event\course_deleted::create(array(
'objectid' => $course->id,
'context' => $context,
'other' => array(
'shortname' => $course->shortname,
'fullname' => $course->fullname,
'idnumber' => $course->idnumber
)
));
$event->add_record_snapshot('course', $course);
$event->trigger();
return true;
}
/**
* Clear a course out completely, deleting all content but don't delete the course itself.
*
* This function does not verify any permissions.
*
* Please note this function also deletes all user enrolments,
* enrolment instances and role assignments by default.
*
* $options:
* - 'keep_roles_and_enrolments' - false by default
* - 'keep_groups_and_groupings' - false by default
*
* @param int $courseid The id of the course that is being deleted
* @param bool $showfeedback Whether to display notifications of each action the function performs.
* @param array $options extra options
* @return bool true if all the removals succeeded. false if there were any failures. If this
* method returns false, some of the removals will probably have succeeded, and others
* failed, but you have no way of knowing which.
*/
function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
global $CFG, $DB, $OUTPUT;
require_once($CFG->libdir.'/badgeslib.php');
require_once($CFG->libdir.'/completionlib.php');
require_once($CFG->libdir.'/questionlib.php');
require_once($CFG->libdir.'/gradelib.php');
require_once($CFG->dirroot.'/group/lib.php');
require_once($CFG->dirroot.'/tag/coursetagslib.php');
require_once($CFG->dirroot.'/comment/lib.php');
require_once($CFG->dirroot.'/rating/lib.php');
require_once($CFG->dirroot.'/notes/lib.php');
// Handle course badges.
badges_handle_course_deletion($courseid);
// NOTE: these concatenated strings are suboptimal, but it is just extra info...
$strdeleted = get_string('deleted').' - ';
// Some crazy wishlist of stuff we should skip during purging of course content.
$options = (array)$options;
$course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
$coursecontext = context_course::instance($courseid);
$fs = get_file_storage();
// Delete course completion information, this has to be done before grades and enrols.
$cc = new completion_info($course);
$cc->clear_criteria();
if ($showfeedback) {
echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
}
// Remove all data from gradebook - this needs to be done before course modules
// because while deleting this information, the system may need to reference
// the course modules that own the grades.
remove_course_grades($courseid, $showfeedback);
remove_grade_letters($coursecontext, $showfeedback);
// Delete course blocks in any all child contexts,
// they may depend on modules so delete them first.
$childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
foreach ($childcontexts as $childcontext) {
blocks_delete_all_for_context($childcontext->id);
}
unset($childcontexts);
blocks_delete_all_for_context($coursecontext->id);
if ($showfeedback) {
echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
}
// Delete every instance of every module,
// this has to be done before deleting of course level stuff.
$locations = core_component::get_plugin_list('mod');
foreach ($locations as $modname => $moddir) {
if ($modname === 'NEWMODULE') {
continue;
}
if ($module = $DB->get_record('modules', array('name' => $modname))) {
include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
$moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
$moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
if ($instances = $DB->get_records($modname, array('course' => $course->id))) {
foreach ($instances as $instance) {
if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
// Delete activity context questions and question categories.
question_delete_activity($cm, $showfeedback);
}
if (function_exists($moddelete)) {
// This purges all module data in related tables, extra user prefs, settings, etc.
$moddelete($instance->id);
} else {
// NOTE: we should not allow installation of modules with missing delete support!
debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
$DB->delete_records($modname, array('id' => $instance->id));
}
if ($cm) {
// Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
$DB->delete_records('course_modules', array('id' => $cm->id));
}
}
}
if (function_exists($moddeletecourse)) {
// Execute ptional course cleanup callback.
$moddeletecourse($course, $showfeedback);
}
if ($instances and $showfeedback) {
echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
}
} else {
// Ooops, this module is not properly installed, force-delete it in the next block.
}
}
// We have tried to delete everything the nice way - now let's force-delete any remaining module data.
// Remove all data from availability and completion tables that is associated
// with course-modules belonging to this course. Note this is done even if the
// features are not enabled now, in case they were enabled previously.
$DB->delete_records_select('course_modules_completion',
'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
array($courseid));
$DB->delete_records_select('course_modules_availability',
'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
array($courseid));
$DB->delete_records_select('course_modules_avail_fields',
'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
array($courseid));
// Remove course-module data.
$cms = $DB->get_records('course_modules', array('course' => $course->id));
foreach ($cms as $cm) {
if ($module = $DB->get_record('modules', array('id' => $cm->module))) {
try {
$DB->delete_records($module->name, array('id' => $cm->instance));
} catch (Exception $e) {
// Ignore weird or missing table problems.
}
}
context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
$DB->delete_records('course_modules', array('id' => $cm->id));
}
if ($showfeedback) {
echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
}
// Cleanup the rest of plugins.
$cleanuplugintypes = array('report', 'coursereport', 'format');
foreach ($cleanuplugintypes as $type) {
$plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
foreach ($plugins as $plugin => $pluginfunction) {
$pluginfunction($course->id, $showfeedback);
}
if ($showfeedback) {
echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
}
}
// Delete questions and question categories.
question_delete_course($course, $showfeedback);
if ($showfeedback) {
echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
}
// Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
$childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
foreach ($childcontexts as $childcontext) {
$childcontext->delete();
}
unset($childcontexts);
// Remove all roles and enrolments by default.
if (empty($options['keep_roles_and_enrolments'])) {
// This hack is used in restore when deleting contents of existing course.
role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
enrol_course_delete($course);
if ($showfeedback) {
echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
}
}
// Delete any groups, removing members and grouping/course links first.
if (empty($options['keep_groups_and_groupings'])) {
groups_delete_groupings($course->id, $showfeedback);
groups_delete_groups($course->id, $showfeedback);
}
// Filters be gone!
filter_delete_all_for_context($coursecontext->id);
// Notes, you shall not pass!
note_delete_all($course->id);
// Die comments!
comment::delete_comments($coursecontext->id);
// Ratings are history too.
$delopt = new stdclass();
$delopt->contextid = $coursecontext->id;
$rm = new rating_manager();
$rm->delete_ratings($delopt);
// Delete course tags.
coursetag_delete_course_tags($course->id, $showfeedback);
// Delete calendar events.
$DB->delete_records('event', array('courseid' => $course->id));
$fs->delete_area_files($coursecontext->id, 'calendar');
// Delete all related records in other core tables that may have a courseid
// This array stores the tables that need to be cleared, as
// table_name => column_name that contains the course id.
$tablestoclear = array(
'log' => 'course', // Course logs (NOTE: this might be changed in the future).
'backup_courses' => 'courseid', // Scheduled backup stuff.
'user_lastaccess' => 'courseid', // User access info.
);
foreach ($tablestoclear as $table => $col) {
$DB->delete_records($table, array($col => $course->id));
}
// Delete all course backup files.
$fs->delete_area_files($coursecontext->id, 'backup');
// Cleanup course record - remove links to deleted stuff.
$oldcourse = new stdClass();
$oldcourse->id = $course->id;
$oldcourse->summary = '';
$oldcourse->cacherev = 0;
$oldcourse->legacyfiles = 0;
$oldcourse->enablecompletion = 0;
if (!empty($options['keep_groups_and_groupings'])) {
$oldcourse->defaultgroupingid = 0;
}
$DB->update_record('course', $oldcourse);
// Delete course sections and availability options.
$DB->delete_records_select('course_sections_availability',
'coursesectionid IN (SELECT id from {course_sections} WHERE course=?)',
array($course->id));
$DB->delete_records_select('course_sections_avail_fields',
'coursesectionid IN (SELECT id from {course_sections} WHERE course=?)',
array($course->id));
$DB->delete_records('course_sections', array('course' => $course->id));
// Delete legacy, section and any other course files.
$fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
// Delete all remaining stuff linked to context such as files, comments, ratings, etc.
if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
// Easy, do not delete the context itself...
$coursecontext->delete_content();
} else {
// Hack alert!!!!
// We can not drop all context stuff because it would bork enrolments and roles,
// there might be also files used by enrol plugins...
}
// Delete legacy files - just in case some files are still left there after conversion to new file api,
// also some non-standard unsupported plugins may try to store something there.
fulldelete($CFG->dataroot.'/'.$course->id);
// Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
$cachemodinfo = cache::make('core', 'coursemodinfo');
$cachemodinfo->delete($courseid);
// Trigger a course content deleted event.
$event = \core\event\course_content_deleted::create(array(
'objectid' => $course->id,
'context' => $coursecontext,
'other' => array('shortname' => $course->shortname,
'fullname' => $course->fullname,
'options' => $options) // Passing this for legacy reasons.
));
$event->add_record_snapshot('course', $course);
$event->trigger();
return true;
}
/**
* Change dates in module - used from course reset.
*
* @param string $modname forum, assignment, etc
* @param array $fields array of date fields from mod table
* @param int $timeshift time difference
* @param int $courseid
* @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
* @return bool success
*/
function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
global $CFG, $DB;
include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
$return = true;
$params = array($timeshift, $courseid);
foreach ($fields as $field) {
$updatesql = "UPDATE {".$modname."}
SET $field = $field + ?
WHERE course=? AND $field<>0";
if ($modid) {
$updatesql .= ' AND id=?';
$params[] = $modid;
}
$return = $DB->execute($updatesql, $params) && $return;
}
$refreshfunction = $modname.'_refresh_events';
if (function_exists($refreshfunction)) {
$refreshfunction($courseid);
}
return $return;
}
/**
* This function will empty a course of user data.
* It will retain the activities and the structure of the course.
*
* @param object $data an object containing all the settings including courseid (without magic quotes)
* @return array status array of array component, item, error
*/
function reset_course_userdata($data) {
global $CFG, $DB;
require_once($CFG->libdir.'/gradelib.php');
require_once($CFG->libdir.'/completionlib.php');
require_once($CFG->dirroot.'/group/lib.php');
$data->courseid = $data->id;
$context = context_course::instance($data->courseid);
$eventparams = array(
'context' => $context,
'courseid' => $data->id,
'other' => array(
'reset_options' => (array) $data
)
);
$event = \core\event\course_reset_started::create($eventparams);
$event->trigger();
// Calculate the time shift of dates.
if (!empty($data->reset_start_date)) {
// Time part of course startdate should be zero.
$data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
} else {
$data->timeshift = 0;
}
// Result array: component, item, error.
$status = array();
// Start the resetting.
$componentstr = get_string('general');
// Move the course start time.
if (!empty($data->reset_start_date) and $data->timeshift) {
// Change course start data.
$DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
// Update all course and group events - do not move activity events.
$updatesql = "UPDATE {event}
SET timestart = timestart + ?
WHERE courseid=? AND instance=0";
$DB->execute($updatesql, array($data->timeshift, $data->courseid));
$status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
}
if (!empty($data->reset_logs)) {
$DB->delete_records('log', array('course' => $data->courseid));
$status[] = array('component' => $componentstr, 'item' => get_string('deletelogs'), 'error' => false);
}
if (!empty($data->reset_events)) {
$DB->delete_records('event', array('courseid' => $data->courseid));
$status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
}
if (!empty($data->reset_notes)) {
require_once($CFG->dirroot.'/notes/lib.php');
note_delete_all($data->courseid);
$status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
}
if (!empty($data->delete_blog_associations)) {
require_once($CFG->dirroot.'/blog/lib.php');
blog_remove_associations_for_course($data->courseid);
$status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
}
if (!empty($data->reset_completion)) {
// Delete course and activity completion information.
$course = $DB->get_record('course', array('id' => $data->courseid));
$cc = new completion_info($course);
$cc->delete_all_completion_data();
$status[] = array('component' => $componentstr,
'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
}
$componentstr = get_string('roles');
if (!empty($data->reset_roles_overrides)) {
$children = $context->get_child_contexts();
foreach ($children as $child) {
$DB->delete_records('role_capabilities', array('contextid' => $child->id));
}
$DB->delete_records('role_capabilities', array('contextid' => $context->id));
// Force refresh for logged in users.
$context->mark_dirty();
$status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
}
if (!empty($data->reset_roles_local)) {
$children = $context->get_child_contexts();
foreach ($children as $child) {
role_unassign_all(array('contextid' => $child->id));
}
// Force refresh for logged in users.
$context->mark_dirty();
$status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
}
// First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
$data->unenrolled = array();
if (!empty($data->unenrol_users)) {
$plugins = enrol_get_plugins(true);
$instances = enrol_get_instances($data->courseid, true);
foreach ($instances as $key => $instance) {
if (!isset($plugins[$instance->enrol])) {
unset($instances[$key]);
continue;
}
}
foreach ($data->unenrol_users as $withroleid) {
if ($withroleid) {
$sql = "SELECT ue.*
FROM {user_enrolments} ue
JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
$params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
} else {
// Without any role assigned at course context.
$sql = "SELECT ue.*
FROM {user_enrolments} ue
JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
WHERE ra.id IS null";
$params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
}
$rs = $DB->get_recordset_sql($sql, $params);
foreach ($rs as $ue) {
if (!isset($instances[$ue->enrolid])) {
continue;
}
$instance = $instances[$ue->enrolid];
$plugin = $plugins[$instance->enrol];
if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
continue;
}
$plugin->unenrol_user($instance, $ue->userid);
$data->unenrolled[$ue->userid] = $ue->userid;
}
$rs->close();
}
}
if (!empty($data->unenrolled)) {
$status[] = array(
'component' => $componentstr,
'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
'error' => false
);
}
$componentstr = get_string('groups');
// Remove all group members.
if (!empty($data->reset_groups_members)) {
groups_delete_group_members($data->courseid);
$status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
}
// Remove all groups.
if (!empty($data->reset_groups_remove)) {
groups_delete_groups($data->courseid, false);
$status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
}
// Remove all grouping members.
if (!empty($data->reset_groupings_members)) {
groups_delete_groupings_groups($data->courseid, false);
$status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
}
// Remove all groupings.
if (!empty($data->reset_groupings_remove)) {
groups_delete_groupings($data->courseid, false);
$status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
}
// Look in every instance of every module for data to delete.
$unsupportedmods = array();
if ($allmods = $DB->get_records('modules') ) {
foreach ($allmods as $mod) {
$modname = $mod->name;
$modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
$moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
if (file_exists($modfile)) {
if (!$DB->count_records($modname, array('course' => $data->courseid))) {
continue; // Skip mods with no instances.
}
include_once($modfile);
if (function_exists($moddeleteuserdata)) {
$modstatus = $moddeleteuserdata($data);
if (is_array($modstatus)) {
$status = array_merge($status, $modstatus);
} else {
debugging('Module '.$modname.' returned incorrect staus - must be an array!');
}
} else {
$unsupportedmods[] = $mod;
}
} else {
debugging('Missing lib.php in '.$modname.' module!');
}
}
}
// Mention unsupported mods.
if (!empty($unsupportedmods)) {
foreach ($unsupportedmods as $mod) {
$status[] = array(
'component' => get_string('modulenameplural', $mod->name),
'item' => '',
'error' => get_string('resetnotimplemented')
);
}
}
$componentstr = get_string('gradebook', 'grades');
// Reset gradebook,.
if (!empty($data->reset_gradebook_items)) {
remove_course_grades($data->courseid, false);
grade_grab_course_grades($data->courseid);
grade_regrade_final_grades($data->courseid);
$status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
} else if (!empty($data->reset_gradebook_grades)) {
grade_course_reset($data->courseid);
$status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
}
// Reset comments.
if (!empty($data->reset_comments)) {
require_once($CFG->dirroot.'/comment/lib.php');
comment::reset_course_page_comments($context);
}
$event = \core\event\course_reset_ended::create($eventparams);
$event->trigger();
return $status;
}
/**
* Generate an email processing address.
*
* @param int $modid
* @param string $modargs
* @return string Returns email processing address
*/
function generate_email_processing_address($modid, $modargs) {
global $CFG;
$header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
}
/**
* ?
*
* @todo Finish documenting this function
*
* @param string $modargs
* @param string $body Currently unused
*/
function moodle_process_email($modargs, $body) {
global $DB;
// The first char should be an unencoded letter. We'll take this as an action.
switch ($modargs{0}) {
case 'B': { // Bounce.
list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
// Check the half md5 of their email.
$md5check = substr(md5($user->email), 0, 16);
if ($md5check == substr($modargs, -16)) {
set_bounce_count($user);
}
// Else maybe they've already changed it?
}
}
break;
// Maybe more later?
}
}
// CORRESPONDENCE.
/**
* Get mailer instance, enable buffering, flush buffer or disable buffering.
*
* @param string $action 'get', 'buffer', 'close' or 'flush'
* @return moodle_phpmailer|null mailer instance if 'get' used or nothing
*/
function get_mailer($action='get') {
global $CFG;
/** @var moodle_phpmailer $mailer */
static $mailer = null;
static $counter = 0;
if (!isset($CFG->smtpmaxbulk)) {
$CFG->smtpmaxbulk = 1;
}
if ($action == 'get') {
$prevkeepalive = false;
if (isset($mailer) and $mailer->Mailer == 'smtp') {
if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
$counter++;
// Reset the mailer.
$mailer->Priority = 3;
$mailer->CharSet = 'UTF-8'; // Our default.
$mailer->ContentType = "text/plain";
$mailer->Encoding = "8bit";
$mailer->From = "root@localhost";
$mailer->FromName = "Root User";
$mailer->Sender = "";
$mailer->Subject = "";
$mailer->Body = "";
$mailer->AltBody = "";
$mailer->ConfirmReadingTo = "";
$mailer->clearAllRecipients();
$mailer->clearReplyTos();
$mailer->clearAttachments();
$mailer->clearCustomHeaders();
return $mailer;
}
$prevkeepalive = $mailer->SMTPKeepAlive;
get_mailer('flush');
}
require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
$mailer = new moodle_phpmailer();
$counter = 1;
if ($CFG->smtphosts == 'qmail') {
// Use Qmail system.
$mailer->isQmail();
} else if (empty($CFG->smtphosts)) {
// Use PHP mail() = sendmail.
$mailer->isMail();
} else {
// Use SMTP directly.
$mailer->isSMTP();
if (!empty($CFG->debugsmtp)) {
$mailer->SMTPDebug = true;
}
// Specify main and backup servers.
$mailer->Host = $CFG->smtphosts;
// Specify secure connection protocol.
$mailer->SMTPSecure = $CFG->smtpsecure;
// Use previous keepalive.
$mailer->SMTPKeepAlive = $prevkeepalive;
if ($CFG->smtpuser) {
// Use SMTP authentication.
$mailer->SMTPAuth = true;
$mailer->Username = $CFG->smtpuser;
$mailer->Password = $CFG->smtppass;
}
}
return $mailer;
}
$nothing = null;
// Keep smtp session open after sending.
if ($action == 'buffer') {
if (!empty($CFG->smtpmaxbulk)) {
get_mailer('flush');
$m = get_mailer();
if ($m->Mailer == 'smtp') {
$m->SMTPKeepAlive = true;
}
}
return $nothing;
}
// Close smtp session, but continue buffering.
if ($action == 'flush') {
if (isset($mailer) and $mailer->Mailer == 'smtp') {
if (!empty($mailer->SMTPDebug)) {
echo '<pre>'."\n";
}
$mailer->SmtpClose();
if (!empty($mailer->SMTPDebug)) {
echo '</pre>';
}
}
return $nothing;
}
// Close smtp session, do not buffer anymore.
if ($action == 'close') {
if (isset($mailer) and $mailer->Mailer == 'smtp') {
get_mailer('flush');
$mailer->SMTPKeepAlive = false;
}
$mailer = null; // Better force new instance.
return $nothing;
}
}
/**
* Send an email to a specified user
*
* @param stdClass $user A {@link $USER} object
* @param stdClass $from A {@link $USER} object
* @param string $subject plain text subject line of the email
* @param string $messagetext plain text version of the message
* @param string $messagehtml complete html version of the message (optional)
* @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
* @param string $attachname the name of the file (extension indicates MIME)
* @param bool $usetrueaddress determines whether $from email address should
* be sent out. Will be overruled by user profile setting for maildisplay
* @param string $replyto Email address to reply to
* @param string $replytoname Name of reply to recipient
* @param int $wordwrapwidth custom word wrap width, default 79
* @return bool Returns true if mail was sent OK and false if there was an error.
*/
function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
$usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
global $CFG;
if (empty($user) or empty($user->id)) {
debugging('Can not send email to null user', DEBUG_DEVELOPER);
return false;
}
if (empty($user->email)) {
debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
return false;
}
if (!empty($user->deleted)) {
debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
return false;
}
if (!empty($CFG->noemailever)) {
// Hidden setting for development sites, set in config.php if needed.
debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
return true;
}
if (!empty($CFG->divertallemailsto)) {
$subject = "[DIVERTED {$user->email}] $subject";
$user = clone($user);
$user->email = $CFG->divertallemailsto;
}
// Skip mail to suspended users.
if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
return true;
}
if (!validate_email($user->email)) {
// We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
$invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
error_log($invalidemail);
if (CLI_SCRIPT) {
mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
}
return false;
}
if (over_bounce_threshold($user)) {
$bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
error_log($bouncemsg);
if (CLI_SCRIPT) {
mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
}
return false;
}
// If the user is a remote mnet user, parse the email text for URL to the
// wwwroot and modify the url to direct the user's browser to login at their
// home site (identity provider - idp) before hitting the link itself.
if (is_mnet_remote_user($user)) {
require_once($CFG->dirroot.'/mnet/lib.php');
$jumpurl = mnet_get_idp_jump_url($user);
$callback = partial('mnet_sso_apply_indirection', $jumpurl);
$messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
$callback,
$messagetext);
$messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
$callback,
$messagehtml);
}
$mail = get_mailer();
if (!empty($mail->SMTPDebug)) {
echo '<pre>' . "\n";
}
$temprecipients = array();
$tempreplyto = array();
$supportuser = core_user::get_support_user();
// Make up an email address for handling bounces.
if (!empty($CFG->handlebounces)) {
$modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
$mail->Sender = generate_email_processing_address(0, $modargs);
} else {
$mail->Sender = $supportuser->email;
}
if (!empty($CFG->emailonlyfromnoreplyaddress)) {
$usetrueaddress = false;
if (empty($replyto) && $from->maildisplay) {
$replyto = $from->email;
$replytoname = fullname($from);
}
}
if (is_string($from)) { // So we can pass whatever we want if there is need.
$mail->From = $CFG->noreplyaddress;
$mail->FromName = $from;
} else if ($usetrueaddress and $from->maildisplay) {
$mail->From = $from->email;
$mail->FromName = fullname($from);
} else {
$mail->From = $CFG->noreplyaddress;
$mail->FromName = fullname($from);
if (empty($replyto)) {
$tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
}
}
if (!empty($replyto)) {
$tempreplyto[] = array($replyto, $replytoname);
}
$mail->Subject = substr($subject, 0, 900);
$temprecipients[] = array($user->email, fullname($user));
// Set word wrap.
$mail->WordWrap = $wordwrapwidth;
if (!empty($from->customheaders)) {
// Add custom headers.
if (is_array($from->customheaders)) {
foreach ($from->customheaders as $customheader) {
$mail->addCustomHeader($customheader);
}
} else {
$mail->addCustomHeader($from->customheaders);
}
}
if (!empty($from->priority)) {
$mail->Priority = $from->priority;
}
if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
// Don't ever send HTML to users who don't want it.
$mail->isHTML(true);
$mail->Encoding = 'quoted-printable';
$mail->Body = $messagehtml;
$mail->AltBody = "\n$messagetext\n";
} else {
$mail->IsHTML(false);
$mail->Body = "\n$messagetext\n";
}
if ($attachment && $attachname) {
if (preg_match( "~\\.\\.~" , $attachment )) {
// Security check for ".." in dir path.
$temprecipients[] = array($supportuser->email, fullname($supportuser, true));
$mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
} else {
require_once($CFG->libdir.'/filelib.php');
$mimetype = mimeinfo('type', $attachname);
$attachmentpath = $attachment;
// Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
$attachpath = str_replace('\\', '/', $attachmentpath);
// Make sure both variables are normalised before comparing.
$temppath = str_replace('\\', '/', $CFG->tempdir);
// If the attachment is a full path to a file in the tempdir, use it as is,
// otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
if (strpos($attachpath, $temppath) !== 0) {
$attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
}
$mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
}
}
// Check if the email should be sent in an other charset then the default UTF-8.
if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
// Use the defined site mail charset or eventually the one preferred by the recipient.
$charset = $CFG->sitemailcharset;
if (!empty($CFG->allowusermailcharset)) {
if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
$charset = $useremailcharset;
}
}
// Convert all the necessary strings if the charset is supported.
$charsets = get_list_of_charsets();
unset($charsets['UTF-8']);
if (in_array($charset, $charsets)) {
$mail->CharSet = $charset;
$mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
$mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
$mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
$mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
foreach ($temprecipients as $key => $values) {
$temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
}
foreach ($tempreplyto as $key => $values) {
$tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
}
}
}
foreach ($temprecipients as $values) {
$mail->addAddress($values[0], $values[1]);
}
foreach ($tempreplyto as $values) {
$mail->addReplyTo($values[0], $values[1]);
}
if ($mail->send()) {
set_send_count($user);
if (!empty($mail->SMTPDebug)) {
echo '</pre>';
}
return true;
} else {
add_to_log(SITEID, 'library', 'mailer', qualified_me(), 'ERROR: '. $mail->ErrorInfo);
if (CLI_SCRIPT) {
mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
}
if (!empty($mail->SMTPDebug)) {
echo '</pre>';
}
return false;
}
}
/**
* Generate a signoff for emails based on support settings
*
* @return string
*/
function generate_email_signoff() {
global $CFG;
$signoff = "\n";
if (!empty($CFG->supportname)) {
$signoff .= $CFG->supportname."\n";
}
if (!empty($CFG->supportemail)) {
$signoff .= $CFG->supportemail."\n";
}
if (!empty($CFG->supportpage)) {
$signoff .= $CFG->supportpage."\n";
}
return $signoff;
}
/**
* Sets specified user's password and send the new password to the user via email.
*
* @param stdClass $user A {@link $USER} object
* @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
* @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
*/
function setnew_password_and_mail($user, $fasthash = false) {
global $CFG, $DB;
// We try to send the mail in language the user understands,
// unfortunately the filter_string() does not support alternative langs yet
// so multilang will not work properly for site->fullname.
$lang = empty($user->lang) ? $CFG->lang : $user->lang;
$site = get_site();
$supportuser = core_user::get_support_user();
$newpassword = generate_password();
$hashedpassword = hash_internal_user_password($newpassword, $fasthash);
$DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
$user->password = $hashedpassword;
// Trigger event.
$event = \core\event\user_updated::create(array(
'objectid' => $user->id,
'context' => context_user::instance($user->id)
));
$event->add_record_snapshot('user', $user);
$event->trigger();
$a = new stdClass();
$a->firstname = fullname($user, true);
$a->sitename = format_string($site->fullname);
$a->username = $user->username;
$a->newpassword = $newpassword;
$a->link = $CFG->wwwroot .'/login/';
$a->signoff = generate_email_signoff();
$message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
$subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
// Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
return email_to_user($user, $supportuser, $subject, $message);
}
/**
* Resets specified user's password and send the new password to the user via email.
*
* @param stdClass $user A {@link $USER} object
* @return bool Returns true if mail was sent OK and false if there was an error.
*/
function reset_password_and_mail($user) {
global $CFG;
$site = get_site();
$supportuser = core_user::get_support_user();
$userauth = get_auth_plugin($user->auth);
if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
return false;
}
$newpassword = generate_password();
if (!$userauth->user_update_password($user, $newpassword)) {
print_error("cannotsetpassword");
}
$a = new stdClass();
$a->firstname = $user->firstname;
$a->lastname = $user->lastname;
$a->sitename = format_string($site->fullname);
$a->username = $user->username;
$a->newpassword = $newpassword;
$a->link = $CFG->httpswwwroot .'/login/change_password.php';
$a->signoff = generate_email_signoff();
$message = get_string('newpasswordtext', '', $a);
$subject = format_string($site->fullname) .': '. get_string('changedpassword');
unset_user_preference('create_password', $user); // Prevent cron from generating the password.
// Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
return email_to_user($user, $supportuser, $subject, $message);
}
/**
* Send email to specified user with confirmation text and activation link.
*
* @param stdClass $user A {@link $USER} object
* @return bool Returns true if mail was sent OK and false if there was an error.
*/
function send_confirmation_email($user) {
global $CFG;
$site = get_site();
$supportuser = core_user::get_support_user();
$data = new stdClass();
$data->firstname = fullname($user);
$data->sitename = format_string($site->fullname);
$data->admin = generate_email_signoff();
$subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
$username = urlencode($user->username);
$username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
$data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
$message = get_string('emailconfirmation', '', $data);
$messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
$user->mailformat = 1; // Always send HTML version as well.
// Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
}
/**
* Sends a password change confirmation email.
*
* @param stdClass $user A {@link $USER} object
* @param stdClass $resetrecord An object tracking metadata regarding password reset request
* @return bool Returns true if mail was sent OK and false if there was an error.
*/
function send_password_change_confirmation_email($user, $resetrecord) {
global $CFG;
$site = get_site();
$supportuser = core_user::get_support_user();
$pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
$data = new stdClass();
$data->firstname = $user->firstname;
$data->lastname = $user->lastname;
$data->username = $user->username;
$data->sitename = format_string($site->fullname);
$data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
$data->admin = generate_email_signoff();
$data->resetminutes = $pwresetmins;
$message = get_string('emailresetconfirmation', '', $data);
$subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
// Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
return email_to_user($user, $supportuser, $subject, $message);
}
/**
* Sends an email containinginformation on how to change your password.
*
* @param stdClass $user A {@link $USER} object
* @return bool Returns true if mail was sent OK and false if there was an error.
*/
function send_password_change_info($user) {
global $CFG;
$site = get_site();
$supportuser = core_user::get_support_user();
$systemcontext = context_system::instance();
$data = new stdClass();
$data->firstname = $user->firstname;
$data->lastname = $user->lastname;
$data->sitename = format_string($site->fullname);
$data->admin = generate_email_signoff();
$userauth = get_auth_plugin($user->auth);
if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
$message = get_string('emailpasswordchangeinfodisabled', '', $data);
$subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
// Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
return email_to_user($user, $supportuser, $subject, $message);
}
if ($userauth->can_change_password() and $userauth->change_password_url()) {
// We have some external url for password changing.
$data->link .= $userauth->change_password_url();
} else {
// No way to change password, sorry.
$data->link = '';
}
if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
$message = get_string('emailpasswordchangeinfo', '', $data);
$subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
} else {
$message = get_string('emailpasswordchangeinfofail', '', $data);
$subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
}
// Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
return email_to_user($user, $supportuser, $subject, $message);
}
/**
* Check that an email is allowed. It returns an error message if there was a problem.
*
* @param string $email Content of email
* @return string|false
*/
function email_is_not_allowed($email) {
global $CFG;
if (!empty($CFG->allowemailaddresses)) {
$allowed = explode(' ', $CFG->allowemailaddresses);
foreach ($allowed as $allowedpattern) {
$allowedpattern = trim($allowedpattern);
if (!$allowedpattern) {
continue;
}
if (strpos($allowedpattern, '.') === 0) {
if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
// Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
return false;
}
} else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
return false;
}
}
return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
} else if (!empty($CFG->denyemailaddresses)) {
$denied = explode(' ', $CFG->denyemailaddresses);
foreach ($denied as $deniedpattern) {
$deniedpattern = trim($deniedpattern);
if (!$deniedpattern) {
continue;
}
if (strpos($deniedpattern, '.') === 0) {
if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
// Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
}
} else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
}
}
}
return false;
}
// FILE HANDLING.
/**
* Returns local file storage instance
*
* @return file_storage
*/
function get_file_storage() {
global $CFG;
static $fs = null;
if ($fs) {
return $fs;
}
require_once("$CFG->libdir/filelib.php");
if (isset($CFG->filedir)) {
$filedir = $CFG->filedir;
} else {
$filedir = $CFG->dataroot.'/filedir';
}
if (isset($CFG->trashdir)) {
$trashdirdir = $CFG->trashdir;
} else {
$trashdirdir = $CFG->dataroot.'/trashdir';
}
$fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
return $fs;
}
/**
* Returns local file storage instance
*
* @return file_browser
*/
function get_file_browser() {
global $CFG;
static $fb = null;
if ($fb) {
return $fb;
}
require_once("$CFG->libdir/filelib.php");
$fb = new file_browser();
return $fb;
}
/**
* Returns file packer
*
* @param string $mimetype default application/zip
* @return file_packer
*/
function get_file_packer($mimetype='application/zip') {
global $CFG;
static $fp = array();
if (isset($fp[$mimetype])) {
return $fp[$mimetype];
}
switch ($mimetype) {
case 'application/zip':
case 'application/vnd.moodle.profiling':
$classname = 'zip_packer';
break;
case 'application/x-gzip' :
$classname = 'tgz_packer';
break;
case 'application/vnd.moodle.backup':
$classname = 'mbz_packer';
break;
default:
return false;
}
require_once("$CFG->libdir/filestorage/$classname.php");
$fp[$mimetype] = new $classname();
return $fp[$mimetype];
}
/**
* Returns current name of file on disk if it exists.
*
* @param string $newfile File to be verified
* @return string Current name of file on disk if true
*/
function valid_uploaded_file($newfile) {
if (empty($newfile)) {
return '';
}
if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
return $newfile['tmp_name'];
} else {
return '';
}
}
/**
* Returns the maximum size for uploading files.
*
* There are seven possible upload limits:
* 1. in Apache using LimitRequestBody (no way of checking or changing this)
* 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
* 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
* 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
* 5. by the Moodle admin in $CFG->maxbytes
* 6. by the teacher in the current course $course->maxbytes
* 7. by the teacher for the current module, eg $assignment->maxbytes
*
* These last two are passed to this function as arguments (in bytes).
* Anything defined as 0 is ignored.
* The smallest of all the non-zero numbers is returned.
*
* @todo Finish documenting this function
*
* @param int $sitebytes Set maximum size
* @param int $coursebytes Current course $course->maxbytes (in bytes)
* @param int $modulebytes Current module ->maxbytes (in bytes)
* @return int The maximum size for uploading files.
*/
function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
if (! $filesize = ini_get('upload_max_filesize')) {
$filesize = '5M';
}
$minimumsize = get_real_size($filesize);
if ($postsize = ini_get('post_max_size')) {
$postsize = get_real_size($postsize);
if ($postsize < $minimumsize) {
$minimumsize = $postsize;
}
}
if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
$minimumsize = $sitebytes;
}
if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
$minimumsize = $coursebytes;
}
if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
$minimumsize = $modulebytes;
}
return $minimumsize;
}
/**
* Returns the maximum size for uploading files for the current user
*
* This function takes in account {@link get_max_upload_file_size()} the user's capabilities
*
* @param context $context The context in which to check user capabilities
* @param int $sitebytes Set maximum size
* @param int $coursebytes Current course $course->maxbytes (in bytes)
* @param int $modulebytes Current module ->maxbytes (in bytes)
* @param stdClass $user The user
* @return int The maximum size for uploading files.
*/
function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
global $USER;
if (empty($user)) {
$user = $USER;
}
if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
}
return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
}
/**
* Returns an array of possible sizes in local language
*
* Related to {@link get_max_upload_file_size()} - this function returns an
* array of possible sizes in an array, translated to the
* local language.
*
* The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
*
* If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
* with the value set to 0. This option will be the first in the list.
*
* @uses SORT_NUMERIC
* @param int $sitebytes Set maximum size
* @param int $coursebytes Current course $course->maxbytes (in bytes)
* @param int $modulebytes Current module ->maxbytes (in bytes)
* @param int|array $custombytes custom upload size/s which will be added to list,
* Only value/s smaller then maxsize will be added to list.
* @return array
*/
function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
global $CFG;
if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
return array();
}
if ($sitebytes == 0) {
// Will get the minimum of upload_max_filesize or post_max_size.
$sitebytes = get_max_upload_file_size();
}
$filesize = array();
$sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
5242880, 10485760, 20971520, 52428800, 104857600);
// If custombytes is given and is valid then add it to the list.
if (is_number($custombytes) and $custombytes > 0) {
$custombytes = (int)$custombytes;
if (!in_array($custombytes, $sizelist)) {
$sizelist[] = $custombytes;
}
} else if (is_array($custombytes)) {
$sizelist = array_unique(array_merge($sizelist, $custombytes));
}
// Allow maxbytes to be selected if it falls outside the above boundaries.
if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
// Note: get_real_size() is used in order to prevent problems with invalid values.
$sizelist[] = get_real_size($CFG->maxbytes);
}
foreach ($sizelist as $sizebytes) {
if ($sizebytes < $maxsize && $sizebytes > 0) {
$filesize[(string)intval($sizebytes)] = display_size($sizebytes);
}
}
$limitlevel = '';
$displaysize = '';
if ($modulebytes &&
(($modulebytes < $coursebytes || $coursebytes == 0) &&
($modulebytes < $sitebytes || $sitebytes == 0))) {
$limitlevel = get_string('activity', 'core');
$displaysize = display_size($modulebytes);
$filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
} else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
$limitlevel = get_string('course', 'core');
$displaysize = display_size($coursebytes);
$filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
} else if ($sitebytes) {
$limitlevel = get_string('site', 'core');
$displaysize = display_size($sitebytes);
$filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
}
krsort($filesize, SORT_NUMERIC);
if ($limitlevel) {
$params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
$filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
}
return $filesize;
}
/**
* Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
*
* If excludefiles is defined, then that file/directory is ignored
* If getdirs is true, then (sub)directories are included in the output
* If getfiles is true, then files are included in the output
* (at least one of these must be true!)
*
* @todo Finish documenting this function. Add examples of $excludefile usage.
*
* @param string $rootdir A given root directory to start from
* @param string|array $excludefiles If defined then the specified file/directory is ignored
* @param bool $descend If true then subdirectories are recursed as well
* @param bool $getdirs If true then (sub)directories are included in the output
* @param bool $getfiles If true then files are included in the output
* @return array An array with all the filenames in all subdirectories, relative to the given rootdir
*/
function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
$dirs = array();
if (!$getdirs and !$getfiles) { // Nothing to show.
return $dirs;
}
if (!is_dir($rootdir)) { // Must be a directory.
return $dirs;
}
if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
return $dirs;
}
if (!is_array($excludefiles)) {
$excludefiles = array($excludefiles);
}
while (false !== ($file = readdir($dir))) {
$firstchar = substr($file, 0, 1);
if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
continue;
}
$fullfile = $rootdir .'/'. $file;
if (filetype($fullfile) == 'dir') {
if ($getdirs) {
$dirs[] = $file;
}
if ($descend) {
$subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
foreach ($subdirs as $subdir) {
$dirs[] = $file .'/'. $subdir;
}
}
} else if ($getfiles) {
$dirs[] = $file;
}
}
closedir($dir);
asort($dirs);
return $dirs;
}
/**
* Adds up all the files in a directory and works out the size.
*
* @param string $rootdir The directory to start from
* @param string $excludefile A file to exclude when summing directory size
* @return int The summed size of all files and subfiles within the root directory
*/
function get_directory_size($rootdir, $excludefile='') {
global $CFG;
// Do it this way if we can, it's much faster.
if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
$command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
$output = null;
$return = null;
exec($command, $output, $return);
if (is_array($output)) {
// We told it to return k.
return get_real_size(intval($output[0]).'k');
}
}
if (!is_dir($rootdir)) {
// Must be a directory.
return 0;
}
if (!$dir = @opendir($rootdir)) {
// Can't open it for some reason.
return 0;
}
$size = 0;
while (false !== ($file = readdir($dir))) {
$firstchar = substr($file, 0, 1);
if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
continue;
}
$fullfile = $rootdir .'/'. $file;
if (filetype($fullfile) == 'dir') {
$size += get_directory_size($fullfile, $excludefile);
} else {
$size += filesize($fullfile);
}
}
closedir($dir);
return $size;
}
/**
* Converts bytes into display form
*
* @static string $gb Localized string for size in gigabytes
* @static string $mb Localized string for size in megabytes
* @static string $kb Localized string for size in kilobytes
* @static string $b Localized string for size in bytes
* @param int $size The size to convert to human readable form
* @return string
*/
function display_size($size) {
static $gb, $mb, $kb, $b;
if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
return get_string('unlimited');
}
if (empty($gb)) {
$gb = get_string('sizegb');
$mb = get_string('sizemb');
$kb = get_string('sizekb');
$b = get_string('sizeb');
}
if ($size >= 1073741824) {
$size = round($size / 1073741824 * 10) / 10 . $gb;
} else if ($size >= 1048576) {
$size = round($size / 1048576 * 10) / 10 . $mb;
} else if ($size >= 1024) {
$size = round($size / 1024 * 10) / 10 . $kb;
} else {
$size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
}
return $size;
}
/**
* Cleans a given filename by removing suspicious or troublesome characters
*
* @see clean_param()
* @param string $string file name
* @return string cleaned file name
*/
function clean_filename($string) {
return clean_param($string, PARAM_FILE);
}
// STRING TRANSLATION.
/**
* Returns the code for the current language
*
* @category string
* @return string
*/
function current_language() {
global $CFG, $USER, $SESSION, $COURSE;
if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
// Course language can override all other settings for this page.
$return = $COURSE->lang;
} else if (!empty($SESSION->lang)) {
// Session language can override other settings.
$return = $SESSION->lang;
} else if (!empty($USER->lang)) {
$return = $USER->lang;
} else if (isset($CFG->lang)) {
$return = $CFG->lang;
} else {
$return = 'en';
}
// Just in case this slipped in from somewhere by accident.
$return = str_replace('_utf8', '', $return);
return $return;
}
/**
* Returns parent language of current active language if defined
*
* @category string
* @param string $lang null means current language
* @return string
*/
function get_parent_language($lang=null) {
global $COURSE, $SESSION;
// Let's hack around the current language.
if (!empty($lang)) {
$oldcourselang = empty($COURSE->lang) ? '' : $COURSE->lang;
$oldsessionlang = empty($SESSION->lang) ? '' : $SESSION->lang;
$COURSE->lang = '';
$SESSION->lang = $lang;
}
$parentlang = get_string('parentlanguage', 'langconfig');
if ($parentlang === 'en') {
$parentlang = '';
}
// Let's hack around the current language.
if (!empty($lang)) {
$COURSE->lang = $oldcourselang;
$SESSION->lang = $oldsessionlang;
}
return $parentlang;
}
/**
* Returns current string_manager instance.
*
* The param $forcereload is needed for CLI installer only where the string_manager instance
* must be replaced during the install.php script life time.
*
* @category string
* @param bool $forcereload shall the singleton be released and new instance created instead?
* @return core_string_manager
*/
function get_string_manager($forcereload=false) {
global $CFG;
static $singleton = null;
if ($forcereload) {
$singleton = null;
}
if ($singleton === null) {
if (empty($CFG->early_install_lang)) {
if (empty($CFG->langlist)) {
$translist = array();
} else {
$translist = explode(',', $CFG->langlist);
}
$singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
} else {
$singleton = new core_string_manager_install();
}
}
return $singleton;
}
/**
* Returns a localized string.
*
* Returns the translated string specified by $identifier as
* for $module. Uses the same format files as STphp.
* $a is an object, string or number that can be used
* within translation strings
*
* eg 'hello {$a->firstname} {$a->lastname}'
* or 'hello {$a}'
*
* If you would like to directly echo the localized string use
* the function {@link print_string()}
*
* Example usage of this function involves finding the string you would
* like a local equivalent of and using its identifier and module information
* to retrieve it.<br/>
* If you open moodle/lang/en/moodle.php and look near line 278
* you will find a string to prompt a user for their word for 'course'
* <code>
* $string['course'] = 'Course';
* </code>
* So if you want to display the string 'Course'
* in any language that supports it on your site
* you just need to use the identifier 'course'
* <code>
* $mystring = '<strong>'. get_string('course') .'</strong>';
* or
* </code>
* If the string you want is in another file you'd take a slightly
* different approach. Looking in moodle/lang/en/calendar.php you find
* around line 75:
* <code>
* $string['typecourse'] = 'Course event';
* </code>
* If you want to display the string "Course event" in any language
* supported you would use the identifier 'typecourse' and the module 'calendar'
* (because it is in the file calendar.php):
* <code>
* $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
* </code>
*
* As a last resort, should the identifier fail to map to a string
* the returned string will be [[ $identifier ]]
*
* In Moodle 2.3 there is a new argument to this function $lazyload.
* Setting $lazyload to true causes get_string to return a lang_string object
* rather than the string itself. The fetching of the string is then put off until
* the string object is first used. The object can be used by calling it's out
* method or by casting the object to a string, either directly e.g.
* (string)$stringobject
* or indirectly by using the string within another string or echoing it out e.g.
* echo $stringobject
* return "<p>{$stringobject}</p>";
* It is worth noting that using $lazyload and attempting to use the string as an
* array key will cause a fatal error as objects cannot be used as array keys.
* But you should never do that anyway!
* For more information {@link lang_string}
*
* @category string
* @param string $identifier The key identifier for the localized string
* @param string $component The module where the key identifier is stored,
* usually expressed as the filename in the language pack without the
* .php on the end but can also be written as mod/forum or grade/export/xls.
* If none is specified then moodle.php is used.
* @param string|object|array $a An object, string or number that can be used
* within translation strings
* @param bool $lazyload If set to true a string object is returned instead of
* the string itself. The string then isn't calculated until it is first used.
* @return string The localized string.
* @throws coding_exception
*/
function get_string($identifier, $component = '', $a = null, $lazyload = false) {
global $CFG;
// If the lazy load argument has been supplied return a lang_string object
// instead.
// We need to make sure it is true (and a bool) as you will see below there
// used to be a forth argument at one point.
if ($lazyload === true) {
return new lang_string($identifier, $component, $a);
}
if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
}
// There is now a forth argument again, this time it is a boolean however so
// we can still check for the old extralocations parameter.
if (!is_bool($lazyload) && !empty($lazyload)) {
debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
}
if (strpos($component, '/') !== false) {
debugging('The module name you passed to get_string is the deprecated format ' .
'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
$componentpath = explode('/', $component);
switch ($componentpath[0]) {
case 'mod':
$component = $componentpath[1];
break;
case 'blocks':
case 'block':
$component = 'block_'.$componentpath[1];
break;
case 'enrol':
$component = 'enrol_'.$componentpath[1];
break;
case 'format':
$component = 'format_'.$componentpath[1];
break;
case 'grade':
$component = 'grade'.$componentpath[1].'_'.$componentpath[2];
break;
}
}
$result = get_string_manager()->get_string($identifier, $component, $a);
// Debugging feature lets you display string identifier and component.
if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
$result .= ' {' . $identifier . '/' . $component . '}';
}
return $result;
}
/**
* Converts an array of strings to their localized value.
*
* @param array $array An array of strings
* @param string $component The language module that these strings can be found in.
* @return stdClass translated strings.
*/
function get_strings($array, $component = '') {
$string = new stdClass;
foreach ($array as $item) {
$string->$item = get_string($item, $component);
}
return $string;
}
/**
* Prints out a translated string.
*
* Prints out a translated string using the return value from the {@link get_string()} function.
*
* Example usage of this function when the string is in the moodle.php file:<br/>
* <code>
* echo '<strong>';
* print_string('course');
* echo '</strong>';
* </code>
*
* Example usage of this function when the string is not in the moodle.php file:<br/>
* <code>
* echo '<h1>';
* print_string('typecourse', 'calendar');
* echo '</h1>';
* </code>
*
* @category string
* @param string $identifier The key identifier for the localized string
* @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
* @param string|object|array $a An object, string or number that can be used within translation strings
*/
function print_string($identifier, $component = '', $a = null) {
echo get_string($identifier, $component, $a);
}
/**
* Returns a list of charset codes
*
* Returns a list of charset codes. It's hardcoded, so they should be added manually
* (checking that such charset is supported by the texlib library!)
*
* @return array And associative array with contents in the form of charset => charset
*/
function get_list_of_charsets() {
$charsets = array(
'EUC-JP' => 'EUC-JP',
'ISO-2022-JP'=> 'ISO-2022-JP',
'ISO-8859-1' => 'ISO-8859-1',
'SHIFT-JIS' => 'SHIFT-JIS',
'GB2312' => 'GB2312',
'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
'UTF-8' => 'UTF-8');
asort($charsets);
return $charsets;
}
/**
* Returns a list of valid and compatible themes
*
* @return array
*/
function get_list_of_themes() {
global $CFG;
$themes = array();
if (!empty($CFG->themelist)) { // Use admin's list of themes.
$themelist = explode(',', $CFG->themelist);
} else {
$themelist = array_keys(core_component::get_plugin_list("theme"));
}
foreach ($themelist as $key => $themename) {
$theme = theme_config::load($themename);
$themes[$themename] = $theme;
}
core_collator::asort_objects_by_method($themes, 'get_theme_name');
return $themes;
}
/**
* Returns a list of timezones in the current language
*
* @return array
*/
function get_list_of_timezones() {
global $DB;
static $timezones;
if (!empty($timezones)) { // This function has been called recently.
return $timezones;
}
$timezones = array();
if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
foreach ($rawtimezones as $timezone) {
if (!empty($timezone->name)) {
if (get_string_manager()->string_exists(strtolower($timezone->name), 'timezones')) {
$timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
} else {
$timezones[$timezone->name] = $timezone->name;
}
if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found.
$timezones[$timezone->name] = $timezone->name;
}
}
}
}
asort($timezones);
for ($i = -13; $i <= 13; $i += .5) {
$tzstring = 'UTC';
if ($i < 0) {
$timezones[sprintf("%.1f", $i)] = $tzstring . $i;
} else if ($i > 0) {
$timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
} else {
$timezones[sprintf("%.1f", $i)] = $tzstring;
}
}
return $timezones;
}
/**
* Factory function for emoticon_manager
*
* @return emoticon_manager singleton
*/
function get_emoticon_manager() {
static $singleton = null;
if (is_null($singleton)) {
$singleton = new emoticon_manager();
}
return $singleton;
}
/**
* Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
*
* Whenever this manager mentiones 'emoticon object', the following data
* structure is expected: stdClass with properties text, imagename, imagecomponent,
* altidentifier and altcomponent
*
* @see admin_setting_emoticons
*
* @copyright 2010 David Mudrak
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class emoticon_manager {
/**
* Returns the currently enabled emoticons
*
* @return array of emoticon objects
*/
public function get_emoticons() {
global $CFG;
if (empty($CFG->emoticons)) {
return array();
}
$emoticons = $this->decode_stored_config($CFG->emoticons);
if (!is_array($emoticons)) {
// Something is wrong with the format of stored setting.
debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
return array();
}
return $emoticons;
}
/**
* Converts emoticon object into renderable pix_emoticon object
*
* @param stdClass $emoticon emoticon object
* @param array $attributes explicit HTML attributes to set
* @return pix_emoticon
*/
public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
$stringmanager = get_string_manager();
if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
$alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
} else {
$alt = s($emoticon->text);
}
return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
}
/**
* Encodes the array of emoticon objects into a string storable in config table
*
* @see self::decode_stored_config()
* @param array $emoticons array of emtocion objects
* @return string
*/
public function encode_stored_config(array $emoticons) {
return json_encode($emoticons);
}
/**
* Decodes the string into an array of emoticon objects
*
* @see self::encode_stored_config()
* @param string $encoded
* @return string|null
*/
public function decode_stored_config($encoded) {
$decoded = json_decode($encoded);
if (!is_array($decoded)) {
return null;
}
return $decoded;
}
/**
* Returns default set of emoticons supported by Moodle
*
* @return array of sdtClasses
*/
public function default_emoticons() {
return array(
$this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
$this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
$this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
$this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
$this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
$this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
$this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
$this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
$this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
$this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
$this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
$this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
$this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
$this->prepare_emoticon_object(":(", 's/sad', 'sad'),
$this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
$this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
$this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
$this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
$this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
$this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
$this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
$this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
$this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
$this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
$this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
$this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
$this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
$this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
$this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
$this->prepare_emoticon_object("( )", 's/egg', 'egg'),
);
}
/**
* Helper method preparing the stdClass with the emoticon properties
*
* @param string|array $text or array of strings
* @param string $imagename to be used by {@link pix_emoticon}
* @param string $altidentifier alternative string identifier, null for no alt
* @param string $altcomponent where the alternative string is defined
* @param string $imagecomponent to be used by {@link pix_emoticon}
* @return stdClass
*/
protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
$altcomponent = 'core_pix', $imagecomponent = 'core') {
return (object)array(
'text' => $text,
'imagename' => $imagename,
'imagecomponent' => $imagecomponent,
'altidentifier' => $altidentifier,
'altcomponent' => $altcomponent,
);
}
}
// ENCRYPTION.
/**
* rc4encrypt
*
* @param string $data Data to encrypt.
* @return string The now encrypted data.
*/
function rc4encrypt($data) {
return endecrypt(get_site_identifier(), $data, '');
}
/**
* rc4decrypt
*
* @param string $data Data to decrypt.
* @return string The now decrypted data.
*/
function rc4decrypt($data) {
return endecrypt(get_site_identifier(), $data, 'de');
}
/**
* Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
*
* @todo Finish documenting this function
*
* @param string $pwd The password to use when encrypting or decrypting
* @param string $data The data to be decrypted/encrypted
* @param string $case Either 'de' for decrypt or '' for encrypt
* @return string
*/
function endecrypt ($pwd, $data, $case) {
if ($case == 'de') {
$data = urldecode($data);
}
$key[] = '';
$box[] = '';
$pwdlength = strlen($pwd);
for ($i = 0; $i <= 255; $i++) {
$key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
$box[$i] = $i;
}
$x = 0;
for ($i = 0; $i <= 255; $i++) {
$x = ($x + $box[$i] + $key[$i]) % 256;
$tempswap = $box[$i];
$box[$i] = $box[$x];
$box[$x] = $tempswap;
}
$cipher = '';
$a = 0;
$j = 0;
for ($i = 0; $i < strlen($data); $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$temp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $temp;
$k = $box[(($box[$a] + $box[$j]) % 256)];
$cipherby = ord(substr($data, $i, 1)) ^ $k;
$cipher .= chr($cipherby);
}
if ($case == 'de') {
$cipher = urldecode(urlencode($cipher));
} else {
$cipher = urlencode($cipher);
}
return $cipher;
}
// ENVIRONMENT CHECKING.
/**
* This method validates a plug name. It is much faster than calling clean_param.
*
* @param string $name a string that might be a plugin name.
* @return bool if this string is a valid plugin name.
*/
function is_valid_plugin_name($name) {
// This does not work for 'mod', bad luck, use any other type.
return core_component::is_valid_plugin_name('tool', $name);
}
/**
* Get a list of all the plugins of a given type that define a certain API function
* in a certain file. The plugin component names and function names are returned.
*
* @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
* @param string $function the part of the name of the function after the
* frankenstyle prefix. e.g 'hook' if you are looking for functions with
* names like report_courselist_hook.
* @param string $file the name of file within the plugin that defines the
* function. Defaults to lib.php.
* @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
* and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
*/
function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
$pluginfunctions = array();
$pluginswithfile = core_component::get_plugin_list_with_file($plugintype, $file, true);
foreach ($pluginswithfile as $plugin => $notused) {
$fullfunction = $plugintype . '_' . $plugin . '_' . $function;
if (function_exists($fullfunction)) {
// Function exists with standard name. Store, indexed by frankenstyle name of plugin.
$pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
} else if ($plugintype === 'mod') {
// For modules, we also allow plugin without full frankenstyle but just starting with the module name.
$shortfunction = $plugin . '_' . $function;
if (function_exists($shortfunction)) {
$pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
}
}
}
return $pluginfunctions;
}
/**
* Lists plugin-like directories within specified directory
*
* This function was originally used for standard Moodle plugins, please use
* new core_component::get_plugin_list() now.
*
* This function is used for general directory listing and backwards compatility.
*
* @param string $directory relative directory from root
* @param string $exclude dir name to exclude from the list (defaults to none)
* @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
* @return array Sorted array of directory names found under the requested parameters
*/
function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
global $CFG;
$plugins = array();
if (empty($basedir)) {
$basedir = $CFG->dirroot .'/'. $directory;
} else {
$basedir = $basedir .'/'. $directory;
}
if ($CFG->debugdeveloper and empty($exclude)) {
// Make sure devs do not use this to list normal plugins,
// this is intended for general directories that are not plugins!
$subtypes = core_component::get_plugin_types();
if (in_array($basedir, $subtypes)) {
debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
}
unset($subtypes);
}
if (file_exists($basedir) && filetype($basedir) == 'dir') {
if (!$dirhandle = opendir($basedir)) {
debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
return array();
}
while (false !== ($dir = readdir($dirhandle))) {
// Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
$dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
continue;
}
if (filetype($basedir .'/'. $dir) != 'dir') {
continue;
}
$plugins[] = $dir;
}
closedir($dirhandle);
}
if ($plugins) {
asort($plugins);
}
return $plugins;
}
/**
* Invoke plugin's callback functions
*
* @param string $type plugin type e.g. 'mod'
* @param string $name plugin name
* @param string $feature feature name
* @param string $action feature's action
* @param array $params parameters of callback function, should be an array
* @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
* @return mixed
*
* @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
*/
function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
}
/**
* Invoke component's callback functions
*
* @param string $component frankenstyle component name, e.g. 'mod_quiz'
* @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
* @param array $params parameters of callback function
* @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
* @return mixed
*/
function component_callback($component, $function, array $params = array(), $default = null) {
$functionname = component_callback_exists($component, $function);
if ($functionname) {
// Function exists, so just return function result.
$ret = call_user_func_array($functionname, $params);
if (is_null($ret)) {
return $default;
} else {
return $ret;
}
}
return $default;
}
/**
* Determine if a component callback exists and return the function name to call. Note that this
* function will include the required library files so that the functioname returned can be
* called directly.
*
* @param string $component frankenstyle component name, e.g. 'mod_quiz'
* @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
* @return mixed Complete function name to call if the callback exists or false if it doesn't.
* @throws coding_exception if invalid component specfied
*/
function component_callback_exists($component, $function) {
global $CFG; // This is needed for the inclusions.
$cleancomponent = clean_param($component, PARAM_COMPONENT);
if (empty($cleancomponent)) {
throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
}
$component = $cleancomponent;
list($type, $name) = core_component::normalize_component($component);
$component = $type . '_' . $name;
$oldfunction = $name.'_'.$function;
$function = $component.'_'.$function;
$dir = core_component::get_component_directory($component);
if (empty($dir)) {
throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
}
// Load library and look for function.
if (file_exists($dir.'/lib.php')) {
require_once($dir.'/lib.php');
}
if (!function_exists($function) and function_exists($oldfunction)) {
if ($type !== 'mod' and $type !== 'core') {
debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
}
$function = $oldfunction;
}
if (function_exists($function)) {
return $function;
}
return false;
}
/**
* Checks whether a plugin supports a specified feature.
*
* @param string $type Plugin type e.g. 'mod'
* @param string $name Plugin name e.g. 'forum'
* @param string $feature Feature code (FEATURE_xx constant)
* @param mixed $default default value if feature support unknown
* @return mixed Feature result (false if not supported, null if feature is unknown,
* otherwise usually true but may have other feature-specific value such as array)
* @throws coding_exception
*/
function plugin_supports($type, $name, $feature, $default = null) {
global $CFG;
if ($type === 'mod' and $name === 'NEWMODULE') {
// Somebody forgot to rename the module template.
return false;
}
$component = clean_param($type . '_' . $name, PARAM_COMPONENT);
if (empty($component)) {
throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
}
$function = null;
if ($type === 'mod') {
// We need this special case because we support subplugins in modules,
// otherwise it would end up in infinite loop.
if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
include_once("$CFG->dirroot/mod/$name/lib.php");
$function = $component.'_supports';
if (!function_exists($function)) {
// Legacy non-frankenstyle function name.
$function = $name.'_supports';
}
}
} else {
if (!$path = core_component::get_plugin_directory($type, $name)) {
// Non existent plugin type.
return false;
}
if (file_exists("$path/lib.php")) {
include_once("$path/lib.php");
$function = $component.'_supports';
}
}
if ($function and function_exists($function)) {
$supports = $function($feature);
if (is_null($supports)) {
// Plugin does not know - use default.
return $default;
} else {
return $supports;
}
}
// Plugin does not care, so use default.
return $default;
}
/**
* Returns true if the current version of PHP is greater that the specified one.
*
* @todo Check PHP version being required here is it too low?
*
* @param string $version The version of php being tested.
* @return bool
*/
function check_php_version($version='5.2.4') {
return (version_compare(phpversion(), $version) >= 0);
}
/**
* Determine if moodle installation requires update.
*
* Checks version numbers of main code and all plugins to see
* if there are any mismatches.
*
* @return bool
*/
function moodle_needs_upgrading() {
global $CFG;
if (empty($CFG->version)) {
return true;
}
// There is no need to purge plugininfo caches here because
// these caches are not used during upgrade and they are purged after
// every upgrade.
if (empty($CFG->allversionshash)) {
return true;
}
$hash = core_component::get_all_versions_hash();
return ($hash !== $CFG->allversionshash);
}
/**
* Returns the major version of this site
*
* Moodle version numbers consist of three numbers separated by a dot, for
* example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
* called major version. This function extracts the major version from either
* $CFG->release (default) or eventually from the $release variable defined in
* the main version.php.
*
* @param bool $fromdisk should the version if source code files be used
* @return string|false the major version like '2.3', false if could not be determined
*/
function moodle_major_version($fromdisk = false) {
global $CFG;
if ($fromdisk) {
$release = null;
require($CFG->dirroot.'/version.php');
if (empty($release)) {
return false;
}
} else {
if (empty($CFG->release)) {
return false;
}
$release = $CFG->release;
}
if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
return $matches[0];
} else {
return false;
}
}
// MISCELLANEOUS.
/**
* Sets the system locale
*
* @category string
* @param string $locale Can be used to force a locale
*/
function moodle_setlocale($locale='') {
global $CFG;
static $currentlocale = ''; // Last locale caching.
$oldlocale = $currentlocale;
// Fetch the correct locale based on ostype.
if ($CFG->ostype == 'WINDOWS') {
$stringtofetch = 'localewin';
} else {
$stringtofetch = 'locale';
}
// The priority is the same as in get_string() - parameter, config, course, session, user, global language.
if (!empty($locale)) {
$currentlocale = $locale;
} else if (!empty($CFG->locale)) { // Override locale for all language packs.
$currentlocale = $CFG->locale;
} else {
$currentlocale = get_string($stringtofetch, 'langconfig');
}
// Do nothing if locale already set up.
if ($oldlocale == $currentlocale) {
return;
}
// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
// Some day, numeric, monetary and other categories should be set too, I think. :-/.
// Get current values.
$monetary= setlocale (LC_MONETARY, 0);
$numeric = setlocale (LC_NUMERIC, 0);
$ctype = setlocale (LC_CTYPE, 0);
if ($CFG->ostype != 'WINDOWS') {
$messages= setlocale (LC_MESSAGES, 0);
}
// Set locale to all.
$result = setlocale (LC_ALL, $currentlocale);
// If setting of locale fails try the other utf8 or utf-8 variant,
// some operating systems support both (Debian), others just one (OSX).
if ($result === false) {
if (stripos($currentlocale, '.UTF-8') !== false) {
$newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
setlocale (LC_ALL, $newlocale);
} else if (stripos($currentlocale, '.UTF8') !== false) {
$newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
setlocale (LC_ALL, $newlocale);
}
}
// Set old values.
setlocale (LC_MONETARY, $monetary);
setlocale (LC_NUMERIC, $numeric);
if ($CFG->ostype != 'WINDOWS') {
setlocale (LC_MESSAGES, $messages);
}
if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
// To workaround a well-known PHP problem with Turkish letter Ii.
setlocale (LC_CTYPE, $ctype);
}
}
/**
* Count words in a string.
*
* Words are defined as things between whitespace.
*
* @category string
* @param string $string The text to be searched for words.
* @return int The count of words in the specified string
*/
function count_words($string) {
$string = strip_tags($string);
return count(preg_split("/\w\b/", $string)) - 1;
}
/**
* Count letters in a string.
*
* Letters are defined as chars not in tags and different from whitespace.
*
* @category string
* @param string $string The text to be searched for letters.
* @return int The count of letters in the specified text.
*/
function count_letters($string) {
$string = strip_tags($string); // Tags are out now.
$string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
return core_text::strlen($string);
}
/**
* Generate and return a random string of the specified length.
*
* @param int $length The length of the string to be created.
* @return string
*/
function random_string ($length=15) {
$pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$pool .= 'abcdefghijklmnopqrstuvwxyz';
$pool .= '0123456789';
$poollen = strlen($pool);
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= substr($pool, (mt_rand()%($poollen)), 1);
}
return $string;
}
/**
* Generate a complex random string (useful for md5 salts)
*
* This function is based on the above {@link random_string()} however it uses a
* larger pool of characters and generates a string between 24 and 32 characters
*
* @param int $length Optional if set generates a string to exactly this length
* @return string
*/
function complex_random_string($length=null) {
$pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
$poollen = strlen($pool);
if ($length===null) {
$length = floor(rand(24, 32));
}
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $pool[(mt_rand()%$poollen)];
}
return $string;
}
/**
* Given some text (which may contain HTML) and an ideal length,
* this function truncates the text neatly on a word boundary if possible
*
* @category string
* @param string $text text to be shortened
* @param int $ideal ideal string length
* @param boolean $exact if false, $text will not be cut mid-word
* @param string $ending The string to append if the passed string is truncated
* @return string $truncate shortened string
*/
function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
// If the plain text is shorter than the maximum length, return the whole text.
if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
return $text;
}
// Splits on HTML tags. Each open/close/empty tag will be the first thing
// and only tag in its 'line'.
preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
$totallength = core_text::strlen($ending);
$truncate = '';
// This array stores information about open and close tags and their position
// in the truncated string. Each item in the array is an object with fields
// ->open (true if open), ->tag (tag name in lower case), and ->pos
// (byte position in truncated text).
$tagdetails = array();
foreach ($lines as $linematchings) {
// If there is any html-tag in this line, handle it and add it (uncounted) to the output.
if (!empty($linematchings[1])) {
// If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
// Record closing tag.
$tagdetails[] = (object) array(
'open' => false,
'tag' => core_text::strtolower($tagmatchings[1]),
'pos' => core_text::strlen($truncate),
);
} else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
// Record opening tag.
$tagdetails[] = (object) array(
'open' => true,
'tag' => core_text::strtolower($tagmatchings[1]),
'pos' => core_text::strlen($truncate),
);
}
}
// Add html-tag to $truncate'd text.
$truncate .= $linematchings[1];
}
// Calculate the length of the plain text part of the line; handle entities as one character.
$contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
if ($totallength + $contentlength > $ideal) {
// The number of characters which are left.
$left = $ideal - $totallength;
$entitieslength = 0;
// Search for html entities.
if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $linematchings[2], $entities, PREG_OFFSET_CAPTURE)) {
// Calculate the real length of all entities in the legal range.
foreach ($entities[0] as $entity) {
if ($entity[1]+1-$entitieslength <= $left) {
$left--;
$entitieslength += core_text::strlen($entity[0]);
} else {
// No more characters left.
break;
}
}
}
$breakpos = $left + $entitieslength;
// If the words shouldn't be cut in the middle...
if (!$exact) {
// Search the last occurence of a space.
for (; $breakpos > 0; $breakpos--) {
if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
if ($char === '.' or $char === ' ') {
$breakpos += 1;
break;
} else if (strlen($char) > 2) {
// Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
$breakpos += 1;
break;
}
}
}
}
if ($breakpos == 0) {
// This deals with the test_shorten_text_no_spaces case.
$breakpos = $left + $entitieslength;
} else if ($breakpos > $left + $entitieslength) {
// This deals with the previous for loop breaking on the first char.
$breakpos = $left + $entitieslength;
}
$truncate .= core_text::substr($linematchings[2], 0, $breakpos);
// Maximum length is reached, so get off the loop.
break;
} else {
$truncate .= $linematchings[2];
$totallength += $contentlength;
}
// If the maximum length is reached, get off the loop.
if ($totallength >= $ideal) {
break;
}
}
// Add the defined ending to the text.
$truncate .= $ending;
// Now calculate the list of open html tags based on the truncate position.
$opentags = array();
foreach ($tagdetails as $taginfo) {
if ($taginfo->open) {
// Add tag to the beginning of $opentags list.
array_unshift($opentags, $taginfo->tag);
} else {
// Can have multiple exact same open tags, close the last one.
$pos = array_search($taginfo->tag, array_reverse($opentags, true));
if ($pos !== false) {
unset($opentags[$pos]);
}
}
}
// Close all unclosed html-tags.
foreach ($opentags as $tag) {
$truncate .= '</' . $tag . '>';
}
return $truncate;
}
/**
* Given dates in seconds, how many weeks is the date from startdate
* The first week is 1, the second 2 etc ...
*
* @param int $startdate Timestamp for the start date
* @param int $thedate Timestamp for the end date
* @return string
*/
function getweek ($startdate, $thedate) {
if ($thedate < $startdate) {
return 0;
}
return floor(($thedate - $startdate) / WEEKSECS) + 1;
}
/**
* Returns a randomly generated password of length $maxlen. inspired by
*
* {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
* {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
*
* @param int $maxlen The maximum size of the password being generated.
* @return string
*/
function generate_password($maxlen=10) {
global $CFG;
if (empty($CFG->passwordpolicy)) {
$fillers = PASSWORD_DIGITS;
$wordlist = file($CFG->wordlist);
$word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
$word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
$filler1 = $fillers[rand(0, strlen($fillers) - 1)];
$password = $word1 . $filler1 . $word2;
} else {
$minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
$digits = $CFG->minpassworddigits;
$lower = $CFG->minpasswordlower;
$upper = $CFG->minpasswordupper;
$nonalphanum = $CFG->minpasswordnonalphanum;
$total = $lower + $upper + $digits + $nonalphanum;
// Var minlength should be the greater one of the two ( $minlen and $total ).
$minlen = $minlen < $total ? $total : $minlen;
// Var maxlen can never be smaller than minlen.
$maxlen = $minlen > $maxlen ? $minlen : $maxlen;
$additional = $maxlen - $total;
// Make sure we have enough characters to fulfill
// complexity requirements.
$passworddigits = PASSWORD_DIGITS;
while ($digits > strlen($passworddigits)) {
$passworddigits .= PASSWORD_DIGITS;
}
$passwordlower = PASSWORD_LOWER;
while ($lower > strlen($passwordlower)) {
$passwordlower .= PASSWORD_LOWER;
}
$passwordupper = PASSWORD_UPPER;
while ($upper > strlen($passwordupper)) {
$passwordupper .= PASSWORD_UPPER;
}
$passwordnonalphanum = PASSWORD_NONALPHANUM;
while ($nonalphanum > strlen($passwordnonalphanum)) {
$passwordnonalphanum .= PASSWORD_NONALPHANUM;
}
// Now mix and shuffle it all.
$password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
substr(str_shuffle ($passwordupper), 0, $upper) .
substr(str_shuffle ($passworddigits), 0, $digits) .
substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
substr(str_shuffle ($passwordlower .
$passwordupper .
$passworddigits .
$passwordnonalphanum), 0 , $additional));
}
return substr ($password, 0, $maxlen);
}
/**
* Given a float, prints it nicely.
* Localized floats must not be used in calculations!
*
* The stripzeros feature is intended for making numbers look nicer in small
* areas where it is not necessary to indicate the degree of accuracy by showing
* ending zeros. If you turn it on with $decimalpoints set to 3, for example,
* then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
*
* @param float $float The float to print
* @param int $decimalpoints The number of decimal places to print.
* @param bool $localized use localized decimal separator
* @param bool $stripzeros If true, removes final zeros after decimal point
* @return string locale float
*/
function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
if (is_null($float)) {
return '';
}
if ($localized) {
$separator = get_string('decsep', 'langconfig');
} else {
$separator = '.';
}
$result = number_format($float, $decimalpoints, $separator, '');
if ($stripzeros) {
// Remove zeros and final dot if not needed.
$result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
}
return $result;
}
/**
* Converts locale specific floating point/comma number back to standard PHP float value
* Do NOT try to do any math operations before this conversion on any user submitted floats!
*
* @param string $localefloat locale aware float representation
* @param bool $strict If true, then check the input and return false if it is not a valid number.
* @return mixed float|bool - false or the parsed float.
*/
function unformat_float($localefloat, $strict = false) {
$localefloat = trim($localefloat);
if ($localefloat == '') {
return null;
}
$localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
$localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
if ($strict && !is_numeric($localefloat)) {
return false;
}
return (float)$localefloat;
}
/**
* Given a simple array, this shuffles it up just like shuffle()
* Unlike PHP's shuffle() this function works on any machine.
*
* @param array $array The array to be rearranged
* @return array
*/
function swapshuffle($array) {
$last = count($array) - 1;
for ($i = 0; $i <= $last; $i++) {
$from = rand(0, $last);
$curr = $array[$i];
$array[$i] = $array[$from];
$array[$from] = $curr;
}
return $array;
}
/**
* Like {@link swapshuffle()}, but works on associative arrays
*
* @param array $array The associative array to be rearranged
* @return array
*/
function swapshuffle_assoc($array) {
$newarray = array();
$newkeys = swapshuffle(array_keys($array));
foreach ($newkeys as $newkey) {
$newarray[$newkey] = $array[$newkey];
}
return $newarray;
}
/**
* Given an arbitrary array, and a number of draws,
* this function returns an array with that amount
* of items. The indexes are retained.
*
* @todo Finish documenting this function
*
* @param array $array
* @param int $draws
* @return array
*/
function draw_rand_array($array, $draws) {
$return = array();
$last = count($array);
if ($draws > $last) {
$draws = $last;
}
while ($draws > 0) {
$last--;
$keys = array_keys($array);
$rand = rand(0, $last);
$return[$keys[$rand]] = $array[$keys[$rand]];
unset($array[$keys[$rand]]);
$draws--;
}
return $return;
}
/**
* Calculate the difference between two microtimes
*
* @param string $a The first Microtime
* @param string $b The second Microtime
* @return string
*/
function microtime_diff($a, $b) {
list($adec, $asec) = explode(' ', $a);
list($bdec, $bsec) = explode(' ', $b);
return $bsec - $asec + $bdec - $adec;
}
/**
* Given a list (eg a,b,c,d,e) this function returns
* an array of 1->a, 2->b, 3->c etc
*
* @param string $list The string to explode into array bits
* @param string $separator The separator used within the list string
* @return array The now assembled array
*/
function make_menu_from_list($list, $separator=',') {
$array = array_reverse(explode($separator, $list), true);
foreach ($array as $key => $item) {
$outarray[$key+1] = trim($item);
}
return $outarray;
}
/**
* Creates an array that represents all the current grades that
* can be chosen using the given grading type.
*
* Negative numbers
* are scales, zero is no grade, and positive numbers are maximum
* grades.
*
* @todo Finish documenting this function or better deprecated this completely!
*
* @param int $gradingtype
* @return array
*/
function make_grades_menu($gradingtype) {
global $DB;
$grades = array();
if ($gradingtype < 0) {
if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
return make_menu_from_list($scale->scale);
}
} else if ($gradingtype > 0) {
for ($i=$gradingtype; $i>=0; $i--) {
$grades[$i] = $i .' / '. $gradingtype;
}
return $grades;
}
return $grades;
}
/**
* This function returns the number of activities using the given scale in the given course.
*
* @param int $courseid The course ID to check.
* @param int $scaleid The scale ID to check
* @return int
*/
function course_scale_used($courseid, $scaleid) {
global $CFG, $DB;
$return = 0;
if (!empty($scaleid)) {
if ($cms = get_course_mods($courseid)) {
foreach ($cms as $cm) {
// Check cm->name/lib.php exists.
if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
$functionname = $cm->modname.'_scale_used';
if (function_exists($functionname)) {
if ($functionname($cm->instance, $scaleid)) {
$return++;
}
}
}
}
}
// Check if any course grade item makes use of the scale.
$return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
// Check if any outcome in the course makes use of the scale.
$return += $DB->count_records_sql("SELECT COUNT('x')
FROM {grade_outcomes_courses} goc,
{grade_outcomes} go
WHERE go.id = goc.outcomeid
AND go.scaleid = ? AND goc.courseid = ?",
array($scaleid, $courseid));
}
return $return;
}
/**
* This function returns the number of activities using scaleid in the entire site
*
* @param int $scaleid
* @param array $courses
* @return int
*/
function site_scale_used($scaleid, &$courses) {
$return = 0;
if (!is_array($courses) || count($courses) == 0) {
$courses = get_courses("all", false, "c.id, c.shortname");
}
if (!empty($scaleid)) {
if (is_array($courses) && count($courses) > 0) {
foreach ($courses as $course) {
$return += course_scale_used($course->id, $scaleid);
}
}
}
return $return;
}
/**
* make_unique_id_code
*
* @todo Finish documenting this function
*
* @uses $_SERVER
* @param string $extra Extra string to append to the end of the code
* @return string
*/
function make_unique_id_code($extra = '') {
$hostname = 'unknownhost';
if (!empty($_SERVER['HTTP_HOST'])) {
$hostname = $_SERVER['HTTP_HOST'];
} else if (!empty($_ENV['HTTP_HOST'])) {
$hostname = $_ENV['HTTP_HOST'];
} else if (!empty($_SERVER['SERVER_NAME'])) {
$hostname = $_SERVER['SERVER_NAME'];
} else if (!empty($_ENV['SERVER_NAME'])) {
$hostname = $_ENV['SERVER_NAME'];
}
$date = gmdate("ymdHis");
$random = random_string(6);
if ($extra) {
return $hostname .'+'. $date .'+'. $random .'+'. $extra;
} else {
return $hostname .'+'. $date .'+'. $random;
}
}
/**
* Function to check the passed address is within the passed subnet
*
* The parameter is a comma separated string of subnet definitions.
* Subnet strings can be in one of three formats:
* 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
* 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy (a range of IP addresses in the last group)
* 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
* Code for type 1 modified from user posted comments by mediator at
* {@link http://au.php.net/manual/en/function.ip2long.php}
*
* @param string $addr The address you are checking
* @param string $subnetstr The string of subnet addresses
* @return bool
*/
function address_in_subnet($addr, $subnetstr) {
if ($addr == '0.0.0.0') {
return false;
}
$subnets = explode(',', $subnetstr);
$found = false;
$addr = trim($addr);
$addr = cleanremoteaddr($addr, false); // Normalise.
if ($addr === null) {
return false;
}
$addrparts = explode(':', $addr);
$ipv6 = strpos($addr, ':');
foreach ($subnets as $subnet) {
$subnet = trim($subnet);
if ($subnet === '') {
continue;
}
if (strpos($subnet, '/') !== false) {
// 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
list($ip, $mask) = explode('/', $subnet);
$mask = trim($mask);
if (!is_number($mask)) {
continue; // Incorect mask number, eh?
}
$ip = cleanremoteaddr($ip, false); // Normalise.
if ($ip === null) {
continue;
}
if (strpos($ip, ':') !== false) {
// IPv6.
if (!$ipv6) {
continue;
}
if ($mask > 128 or $mask < 0) {
continue; // Nonsense.
}
if ($mask == 0) {
return true; // Any address.
}
if ($mask == 128) {
if ($ip === $addr) {
return true;
}
continue;
}
$ipparts = explode(':', $ip);
$modulo = $mask % 16;
$ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
$addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
if (implode(':', $ipnet) === implode(':', $addrnet)) {
if ($modulo == 0) {
return true;
}
$pos = ($mask-$modulo)/16;
$ipnet = hexdec($ipparts[$pos]);
$addrnet = hexdec($addrparts[$pos]);
$mask = 0xffff << (16 - $modulo);
if (($addrnet & $mask) == ($ipnet & $mask)) {
return true;
}
}
} else {
// IPv4.
if ($ipv6) {
continue;
}
if ($mask > 32 or $mask < 0) {
continue; // Nonsense.
}
if ($mask == 0) {
return true;
}
if ($mask == 32) {
if ($ip === $addr) {
return true;
}
continue;
}
$mask = 0xffffffff << (32 - $mask);
if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
return true;
}
}
} else if (strpos($subnet, '-') !== false) {
// 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy. A range of IP addresses in the last group.
$parts = explode('-', $subnet);
if (count($parts) != 2) {
continue;
}
if (strpos($subnet, ':') !== false) {
// IPv6.
if (!$ipv6) {
continue;
}
$ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
if ($ipstart === null) {
continue;
}
$ipparts = explode(':', $ipstart);
$start = hexdec(array_pop($ipparts));
$ipparts[] = trim($parts[1]);
$ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
if ($ipend === null) {
continue;
}
$ipparts[7] = '';
$ipnet = implode(':', $ipparts);
if (strpos($addr, $ipnet) !== 0) {
continue;
}
$ipparts = explode(':', $ipend);
$end = hexdec($ipparts[7]);
$addrend = hexdec($addrparts[7]);
if (($addrend >= $start) and ($addrend <= $end)) {
return true;
}
} else {
// IPv4.
if ($ipv6) {
continue;
}
$ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
if ($ipstart === null) {
continue;
}
$ipparts = explode('.', $ipstart);
$ipparts[3] = trim($parts[1]);
$ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
if ($ipend === null) {
continue;
}
if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
return true;
}
}
} else {
// 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
if (strpos($subnet, ':') !== false) {
// IPv6.
if (!$ipv6) {
continue;
}
$parts = explode(':', $subnet);
$count = count($parts);
if ($parts[$count-1] === '') {
unset($parts[$count-1]); // Trim trailing :'s.
$count--;
$subnet = implode('.', $parts);
}
$isip = cleanremoteaddr($subnet, false); // Normalise.
if ($isip !== null) {
if ($isip === $addr) {
return true;
}
continue;
} else if ($count > 8) {
continue;
}
$zeros = array_fill(0, 8-$count, '0');
$subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
if (address_in_subnet($addr, $subnet)) {
return true;
}
} else {
// IPv4.
if ($ipv6) {
continue;
}
$parts = explode('.', $subnet);
$count = count($parts);
if ($parts[$count-1] === '') {
unset($parts[$count-1]); // Trim trailing .
$count--;
$subnet = implode('.', $parts);
}
if ($count == 4) {
$subnet = cleanremoteaddr($subnet, false); // Normalise.
if ($subnet === $addr) {
return true;
}
continue;
} else if ($count > 4) {
continue;
}
$zeros = array_fill(0, 4-$count, '0');
$subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
if (address_in_subnet($addr, $subnet)) {
return true;
}
}
}
}
return false;
}
/**
* For outputting debugging info
*
* @param string $string The string to write
* @param string $eol The end of line char(s) to use
* @param string $sleep Period to make the application sleep
* This ensures any messages have time to display before redirect
*/
function mtrace($string, $eol="\n", $sleep=0) {
if (defined('STDOUT') and !PHPUNIT_TEST) {
fwrite(STDOUT, $string.$eol);
} else {
echo $string . $eol;
}
flush();
// Delay to keep message on user's screen in case of subsequent redirect.
if ($sleep) {
sleep($sleep);
}
}
/**
* Replace 1 or more slashes or backslashes to 1 slash
*
* @param string $path The path to strip
* @return string the path with double slashes removed
*/
function cleardoubleslashes ($path) {
return preg_replace('/(\/|\\\){1,}/', '/', $path);
}
/**
* Is current ip in give list?
*
* @param string $list
* @return bool
*/
function remoteip_in_list($list) {
$inlist = false;
$clientip = getremoteaddr(null);
if (!$clientip) {
// Ensure access on cli.
return true;
}
$list = explode("\n", $list);
foreach ($list as $subnet) {
$subnet = trim($subnet);
if (address_in_subnet($clientip, $subnet)) {
$inlist = true;
break;
}
}
return $inlist;
}
/**
* Returns most reliable client address
*
* @param string $default If an address can't be determined, then return this
* @return string The remote IP address
*/
function getremoteaddr($default='0.0.0.0') {
global $CFG;
if (empty($CFG->getremoteaddrconf)) {
// This will happen, for example, before just after the upgrade, as the
// user is redirected to the admin screen.
$variablestoskip = 0;
} else {
$variablestoskip = $CFG->getremoteaddrconf;
}
if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
return $address ? $address : $default;
}
}
if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$address = cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
return $address ? $address : $default;
}
}
if (!empty($_SERVER['REMOTE_ADDR'])) {
$address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
return $address ? $address : $default;
} else {
return $default;
}
}
/**
* Cleans an ip address. Internal addresses are now allowed.
* (Originally local addresses were not allowed.)
*
* @param string $addr IPv4 or IPv6 address
* @param bool $compress use IPv6 address compression
* @return string normalised ip address string, null if error
*/
function cleanremoteaddr($addr, $compress=false) {
$addr = trim($addr);
// TODO: maybe add a separate function is_addr_public() or something like this.
if (strpos($addr, ':') !== false) {
// Can be only IPv6.
$parts = explode(':', $addr);
$count = count($parts);
if (strpos($parts[$count-1], '.') !== false) {
// Legacy ipv4 notation.
$last = array_pop($parts);
$ipv4 = cleanremoteaddr($last, true);
if ($ipv4 === null) {
return null;
}
$bits = explode('.', $ipv4);
$parts[] = dechex($bits[0]).dechex($bits[1]);
$parts[] = dechex($bits[2]).dechex($bits[3]);
$count = count($parts);
$addr = implode(':', $parts);
}
if ($count < 3 or $count > 8) {
return null; // Severly malformed.
}
if ($count != 8) {
if (strpos($addr, '::') === false) {
return null; // Malformed.
}
// Uncompress.
$insertat = array_search('', $parts, true);
$missing = array_fill(0, 1 + 8 - $count, '0');
array_splice($parts, $insertat, 1, $missing);
foreach ($parts as $key => $part) {
if ($part === '') {
$parts[$key] = '0';
}
}
}
$adr = implode(':', $parts);
if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
return null; // Incorrect format - sorry.
}
// Normalise 0s and case.
$parts = array_map('hexdec', $parts);
$parts = array_map('dechex', $parts);
$result = implode(':', $parts);
if (!$compress) {
return $result;
}
if ($result === '0:0:0:0:0:0:0:0') {
return '::'; // All addresses.
}
$compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
if ($compressed !== $result) {
return $compressed;
}
$compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
if ($compressed !== $result) {
return $compressed;
}
$compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
if ($compressed !== $result) {
return $compressed;
}
return $result;
}
// First get all things that look like IPv4 addresses.
$parts = array();
if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
return null;
}
unset($parts[0]);
foreach ($parts as $key => $match) {
if ($match > 255) {
return null;
}
$parts[$key] = (int)$match; // Normalise 0s.
}
return implode('.', $parts);
}
/**
* This function will make a complete copy of anything it's given,
* regardless of whether it's an object or not.
*
* @param mixed $thing Something you want cloned
* @return mixed What ever it is you passed it
*/
function fullclone($thing) {
return unserialize(serialize($thing));
}
/**
* If new messages are waiting for the current user, then insert
* JavaScript to pop up the messaging window into the page
*
* @return void
*/
function message_popup_window() {
global $USER, $DB, $PAGE, $CFG;
if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
return;
}
if (!isloggedin() || isguestuser()) {
return;
}
if (!isset($USER->message_lastpopup)) {
$USER->message_lastpopup = 0;
} else if ($USER->message_lastpopup > (time()-120)) {
// Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
return;
}
// A quick query to check whether the user has new messages.
$messagecount = $DB->count_records('message', array('useridto' => $USER->id));
if ($messagecount < 1) {
return;
}
// There are unread messages so now do a more complex but slower query.
$messagesql = "SELECT m.id, c.blocked
FROM {message} m
JOIN {message_working} mw ON m.id=mw.unreadmessageid
JOIN {message_processors} p ON mw.processorid=p.id
JOIN {user} u ON m.useridfrom=u.id
LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
AND c.userid = m.useridto
WHERE m.useridto = :userid
AND p.name='popup'";
// If the user was last notified over an hour ago we can re-notify them of old messages
// so don't worry about when the new message was sent.
$lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
if (!$lastnotifiedlongago) {
$messagesql .= 'AND m.timecreated > :lastpopuptime';
}
$waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
$validmessages = 0;
foreach ($waitingmessages as $messageinfo) {
if ($messageinfo->blocked) {
// Message is from a user who has since been blocked so just mark it read.
// Get the full message to mark as read.
$messageobject = $DB->get_record('message', array('id' => $messageinfo->id));
message_mark_message_read($messageobject, time());
} else {
$validmessages++;
}
}
if ($validmessages > 0) {
$strmessages = get_string('unreadnewmessages', 'message', $validmessages);
$strgomessage = get_string('gotomessages', 'message');
$strstaymessage = get_string('ignore', 'admin');
$notificationsound = null;
$beep = get_user_preferences('message_beepnewmessage', '');
if (!empty($beep)) {
// Browsers will work down this list until they find something they support.
$sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
$sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
$sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
$sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
$notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
}
$url = $CFG->wwwroot.'/message/index.php';
$content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
html_writer::start_tag('div', array('id' => 'newmessagetext')).
$strmessages.
html_writer::end_tag('div').
$notificationsound.
html_writer::start_tag('div', array('id' => 'newmessagelinks')).
html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).' '.
html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
html_writer::end_tag('div');
html_writer::end_tag('div');
$PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
$USER->message_lastpopup = time();
}
}
/**
* Used to make sure that $min <= $value <= $max
*
* Make sure that value is between min, and max
*
* @param int $min The minimum value
* @param int $value The value to check
* @param int $max The maximum value
* @return int
*/
function bounded_number($min, $value, $max) {
if ($value < $min) {
return $min;
}
if ($value > $max) {
return $max;
}
return $value;
}
/**
* Check if there is a nested array within the passed array
*
* @param array $array
* @return bool true if there is a nested array false otherwise
*/
function array_is_nested($array) {
foreach ($array as $value) {
if (is_array($value)) {
return true;
}
}
return false;
}
/**
* get_performance_info() pairs up with init_performance_info()
* loaded in setup.php. Returns an array with 'html' and 'txt'
* values ready for use, and each of the individual stats provided
* separately as well.
*
* @return array
*/
function get_performance_info() {
global $CFG, $PERF, $DB, $PAGE;
$info = array();
$info['html'] = ''; // Holds userfriendly HTML representation.
$info['txt'] = me() . ' '; // Holds log-friendly representation.
$info['realtime'] = microtime_diff($PERF->starttime, microtime());
$info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
$info['txt'] .= 'time: '.$info['realtime'].'s ';
if (function_exists('memory_get_usage')) {
$info['memory_total'] = memory_get_usage();
$info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
$info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
$info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
}
if (function_exists('memory_get_peak_usage')) {
$info['memory_peak'] = memory_get_peak_usage();
$info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
$info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
}
$inc = get_included_files();
$info['includecount'] = count($inc);
$info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
$info['txt'] .= 'includecount: '.$info['includecount'].' ';
if (!empty($CFG->early_install_lang) or empty($PAGE)) {
// We can not track more performance before installation or before PAGE init, sorry.
return $info;
}
$filtermanager = filter_manager::instance();
if (method_exists($filtermanager, 'get_performance_summary')) {
list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
$info = array_merge($filterinfo, $info);
foreach ($filterinfo as $key => $value) {
$info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
$info['txt'] .= "$key: $value ";
}
}
$stringmanager = get_string_manager();
if (method_exists($stringmanager, 'get_performance_summary')) {
list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
$info = array_merge($filterinfo, $info);
foreach ($filterinfo as $key => $value) {
$info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
$info['txt'] .= "$key: $value ";
}
}
$jsmodules = $PAGE->requires->get_loaded_modules();
if ($jsmodules) {
$yuicount = 0;
$othercount = 0;
$details = '';
foreach ($jsmodules as $module => $backtraces) {
if (strpos($module, 'yui') === 0) {
$yuicount += 1;
} else {
$othercount += 1;
}
if (!empty($CFG->yuimoduledebug)) {
// Hidden feature for developers working on YUI module infrastructure.
$details .= "<div class='yui-module'><p>$module</p>";
foreach ($backtraces as $backtrace) {
$details .= "<div class='backtrace'>$backtrace</div>";
}
$details .= '</div>';
}
}
$info['html'] .= "<span class='includedyuimodules'>Included YUI modules: $yuicount</span> ";
$info['txt'] .= "includedyuimodules: $yuicount ";
$info['html'] .= "<span class='includedjsmodules'>Other JavaScript modules: $othercount</span> ";
$info['txt'] .= "includedjsmodules: $othercount ";
if ($details) {
$info['html'] .= '<div id="yui-module-debug" class="notifytiny">'.$details.'</div>';
}
}
if (!empty($PERF->logwrites)) {
$info['logwrites'] = $PERF->logwrites;
$info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
$info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
}
$info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
$info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
$info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
$info['dbtime'] = round($DB->perf_get_queries_time(), 5);
$info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
$info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
if (function_exists('posix_times')) {
$ptimes = posix_times();
if (is_array($ptimes)) {
foreach ($ptimes as $key => $val) {
$info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
}
$info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
$info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
}
}
// Grab the load average for the last minute.
// /proc will only work under some linux configurations
// while uptime is there under MacOSX/Darwin and other unices.
if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
list($serverload) = explode(' ', $loadavg[0]);
unset($loadavg);
} else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
$serverload = $matches[1];
} else {
trigger_error('Could not parse uptime output!');
}
}
if (!empty($serverload)) {
$info['serverload'] = $serverload;
$info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
$info['txt'] .= "serverload: {$info['serverload']} ";
}
// Display size of session if session started.
if ($si = \core\session\manager::get_performance_info()) {
$info['sessionsize'] = $si['size'];
$info['html'] .= $si['html'];
$info['txt'] .= $si['txt'];
}
if ($stats = cache_helper::get_stats()) {
$html = '<span class="cachesused">';
$html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
$text = 'Caches used (hits/misses/sets): ';
$hits = 0;
$misses = 0;
$sets = 0;
foreach ($stats as $definition => $stores) {
$html .= '<span class="cache-definition-stats">';
$html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
$text .= "$definition {";
foreach ($stores as $store => $data) {
$hits += $data['hits'];
$misses += $data['misses'];
$sets += $data['sets'];
if ($data['hits'] == 0 and $data['misses'] > 0) {
$cachestoreclass = 'nohits';
} else if ($data['hits'] < $data['misses']) {
$cachestoreclass = 'lowhits';
} else {
$cachestoreclass = 'hihits';
}
$text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
$html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
}
$html .= '</span>';
$text .= '} ';
}
$html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
$html .= '</span> ';
$info['cachesused'] = "$hits / $misses / $sets";
$info['html'] .= $html;
$info['txt'] .= $text.'. ';
} else {
$info['cachesused'] = '0 / 0 / 0';
$info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
$info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
}
$info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
return $info;
}
/**
* Legacy function.
*
* @todo Document this function linux people
*/
function apd_get_profiling() {
return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
}
/**
* Delete directory or only its content
*
* @param string $dir directory path
* @param bool $contentonly
* @return bool success, true also if dir does not exist
*/
function remove_dir($dir, $contentonly=false) {
if (!file_exists($dir)) {
// Nothing to do.
return true;
}
if (!$handle = opendir($dir)) {
return false;
}
$result = true;
while (false!==($item = readdir($handle))) {
if ($item != '.' && $item != '..') {
if (is_dir($dir.'/'.$item)) {
$result = remove_dir($dir.'/'.$item) && $result;
} else {
$result = unlink($dir.'/'.$item) && $result;
}
}
}
closedir($handle);
if ($contentonly) {
clearstatcache(); // Make sure file stat cache is properly invalidated.
return $result;
}
$result = rmdir($dir); // If anything left the result will be false, no need for && $result.
clearstatcache(); // Make sure file stat cache is properly invalidated.
return $result;
}
/**
* Detect if an object or a class contains a given property
* will take an actual object or the name of a class
*
* @param mix $obj Name of class or real object to test
* @param string $property name of property to find
* @return bool true if property exists
*/
function object_property_exists( $obj, $property ) {
if (is_string( $obj )) {
$properties = get_class_vars( $obj );
} else {
$properties = get_object_vars( $obj );
}
return array_key_exists( $property, $properties );
}
/**
* Converts an object into an associative array
*
* This function converts an object into an associative array by iterating
* over its public properties. Because this function uses the foreach
* construct, Iterators are respected. It works recursively on arrays of objects.
* Arrays and simple values are returned as is.
*
* If class has magic properties, it can implement IteratorAggregate
* and return all available properties in getIterator()
*
* @param mixed $var
* @return array
*/
function convert_to_array($var) {
$result = array();
// Loop over elements/properties.
foreach ($var as $key => $value) {
// Recursively convert objects.
if (is_object($value) || is_array($value)) {
$result[$key] = convert_to_array($value);
} else {
// Simple values are untouched.
$result[$key] = $value;
}
}
return $result;
}
/**
* Detect a custom script replacement in the data directory that will
* replace an existing moodle script
*
* @return string|bool full path name if a custom script exists, false if no custom script exists
*/
function custom_script_path() {
global $CFG, $SCRIPT;
if ($SCRIPT === null) {
// Probably some weird external script.
return false;
}
$scriptpath = $CFG->customscripts . $SCRIPT;
// Check the custom script exists.
if (file_exists($scriptpath) and is_file($scriptpath)) {
return $scriptpath;
} else {
return false;
}
}
/**
* Returns whether or not the user object is a remote MNET user. This function
* is in moodlelib because it does not rely on loading any of the MNET code.
*
* @param object $user A valid user object
* @return bool True if the user is from a remote Moodle.
*/
function is_mnet_remote_user($user) {
global $CFG;
if (!isset($CFG->mnet_localhost_id)) {
include_once($CFG->dirroot . '/mnet/lib.php');
$env = new mnet_environment();
$env->init();
unset($env);
}
return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
}
/**
* This function will search for browser prefereed languages, setting Moodle
* to use the best one available if $SESSION->lang is undefined
*/
function setup_lang_from_browser() {
global $CFG, $SESSION, $USER;
if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
// Lang is defined in session or user profile, nothing to do.
return;
}
if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
return;
}
// Extract and clean langs from headers.
$rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
$rawlangs = explode(',', $rawlangs); // Convert to array.
$langs = array();
$order = 1.0;
foreach ($rawlangs as $lang) {
if (strpos($lang, ';') === false) {
$langs[(string)$order] = $lang;
$order = $order-0.01;
} else {
$parts = explode(';', $lang);
$pos = strpos($parts[1], '=');
$langs[substr($parts[1], $pos+1)] = $parts[0];
}
}
krsort($langs, SORT_NUMERIC);
// Look for such langs under standard locations.
foreach ($langs as $lang) {
// Clean it properly for include.
$lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
if (get_string_manager()->translation_exists($lang, false)) {
// Lang exists, set it in session.
$SESSION->lang = $lang;
// We have finished. Go out.
break;
}
}
return;
}
/**
* Check if $url matches anything in proxybypass list
*
* Any errors just result in the proxy being used (least bad)
*
* @param string $url url to check
* @return boolean true if we should bypass the proxy
*/
function is_proxybypass( $url ) {
global $CFG;
// Sanity check.
if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
return false;
}
// Get the host part out of the url.
if (!$host = parse_url( $url, PHP_URL_HOST )) {
return false;
}
// Get the possible bypass hosts into an array.
$matches = explode( ',', $CFG->proxybypass );
// Check for a match.
// (IPs need to match the left hand side and hosts the right of the url,
// but we can recklessly check both as there can't be a false +ve).
foreach ($matches as $match) {
$match = trim($match);
// Try for IP match (Left side).
$lhs = substr($host, 0, strlen($match));
if (strcasecmp($match, $lhs)==0) {
return true;
}
// Try for host match (Right side).
$rhs = substr($host, -strlen($match));
if (strcasecmp($match, $rhs)==0) {
return true;
}
}
// Nothing matched.
return false;
}
/**
* Check if the passed navigation is of the new style
*
* @param mixed $navigation
* @return bool true for yes false for no
*/
function is_newnav($navigation) {
if (is_array($navigation) && !empty($navigation['newnav'])) {
return true;
} else {
return false;
}
}
/**
* Checks whether the given variable name is defined as a variable within the given object.
*
* This will NOT work with stdClass objects, which have no class variables.
*
* @param string $var The variable name
* @param object $object The object to check
* @return boolean
*/
function in_object_vars($var, $object) {
$classvars = get_class_vars(get_class($object));
$classvars = array_keys($classvars);
return in_array($var, $classvars);
}
/**
* Returns an array without repeated objects.
* This function is similar to array_unique, but for arrays that have objects as values
*
* @param array $array
* @param bool $keepkeyassoc
* @return array
*/
function object_array_unique($array, $keepkeyassoc = true) {
$duplicatekeys = array();
$tmp = array();
foreach ($array as $key => $val) {
// Convert objects to arrays, in_array() does not support objects.
if (is_object($val)) {
$val = (array)$val;
}
if (!in_array($val, $tmp)) {
$tmp[] = $val;
} else {
$duplicatekeys[] = $key;
}
}
foreach ($duplicatekeys as $key) {
unset($array[$key]);
}
return $keepkeyassoc ? $array : array_values($array);
}
/**
* Is a userid the primary administrator?
*
* @param int $userid int id of user to check
* @return boolean
*/
function is_primary_admin($userid) {
$primaryadmin = get_admin();
if ($userid == $primaryadmin->id) {
return true;
} else {
return false;
}
}
/**
* Returns the site identifier
*
* @return string $CFG->siteidentifier, first making sure it is properly initialised.
*/
function get_site_identifier() {
global $CFG;
// Check to see if it is missing. If so, initialise it.
if (empty($CFG->siteidentifier)) {
set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
}
// Return it.
return $CFG->siteidentifier;
}
/**
* Check whether the given password has no more than the specified
* number of consecutive identical characters.
*
* @param string $password password to be checked against the password policy
* @param integer $maxchars maximum number of consecutive identical characters
* @return bool
*/
function check_consecutive_identical_characters($password, $maxchars) {
if ($maxchars < 1) {
return true; // Zero 0 is to disable this check.
}
if (strlen($password) <= $maxchars) {
return true; // Too short to fail this test.
}
$previouschar = '';
$consecutivecount = 1;
foreach (str_split($password) as $char) {
if ($char != $previouschar) {
$consecutivecount = 1;
} else {
$consecutivecount++;
if ($consecutivecount > $maxchars) {
return false; // Check failed already.
}
}
$previouschar = $char;
}
return true;
}
/**
* Helper function to do partial function binding.
* so we can use it for preg_replace_callback, for example
* this works with php functions, user functions, static methods and class methods
* it returns you a callback that you can pass on like so:
*
* $callback = partial('somefunction', $arg1, $arg2);
* or
* $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
* or even
* $obj = new someclass();
* $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
*
* and then the arguments that are passed through at calltime are appended to the argument list.
*
* @param mixed $function a php callback
* @param mixed $arg1,... $argv arguments to partially bind with
* @return array Array callback
*/
function partial() {
if (!class_exists('partial')) {
/**
* Used to manage function binding.
* @copyright 2009 Penny Leach
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class partial{
/** @var array */
public $values = array();
/** @var string The function to call as a callback. */
public $func;
/**
* Constructor
* @param string $func
* @param array $args
*/
public function __construct($func, $args) {
$this->values = $args;
$this->func = $func;
}
/**
* Calls the callback function.
* @return mixed
*/
public function method() {
$args = func_get_args();
return call_user_func_array($this->func, array_merge($this->values, $args));
}
}
}
$args = func_get_args();
$func = array_shift($args);
$p = new partial($func, $args);
return array($p, 'method');
}
/**
* helper function to load up and initialise the mnet environment
* this must be called before you use mnet functions.
*
* @return mnet_environment the equivalent of old $MNET global
*/
function get_mnet_environment() {
global $CFG;
require_once($CFG->dirroot . '/mnet/lib.php');
static $instance = null;
if (empty($instance)) {
$instance = new mnet_environment();
$instance->init();
}
return $instance;
}
/**
* during xmlrpc server code execution, any code wishing to access
* information about the remote peer must use this to get it.
*
* @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
*/
function get_mnet_remote_client() {
if (!defined('MNET_SERVER')) {
debugging(get_string('notinxmlrpcserver', 'mnet'));
return false;
}
global $MNET_REMOTE_CLIENT;
if (isset($MNET_REMOTE_CLIENT)) {
return $MNET_REMOTE_CLIENT;
}
return false;
}
/**
* during the xmlrpc server code execution, this will be called
* to setup the object returned by {@link get_mnet_remote_client}
*
* @param mnet_remote_client $client the client to set up
* @throws moodle_exception
*/
function set_mnet_remote_client($client) {
if (!defined('MNET_SERVER')) {
throw new moodle_exception('notinxmlrpcserver', 'mnet');
}
global $MNET_REMOTE_CLIENT;
$MNET_REMOTE_CLIENT = $client;
}
/**
* return the jump url for a given remote user
* this is used for rewriting forum post links in emails, etc
*
* @param stdclass $user the user to get the idp url for
*/
function mnet_get_idp_jump_url($user) {
global $CFG;
static $mnetjumps = array();
if (!array_key_exists($user->mnethostid, $mnetjumps)) {
$idp = mnet_get_peer_host($user->mnethostid);
$idpjumppath = mnet_get_app_jumppath($idp->applicationid);
$mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
}
return $mnetjumps[$user->mnethostid];
}
/**
* Gets the homepage to use for the current user
*
* @return int One of HOMEPAGE_*
*/
function get_home_page() {
global $CFG;
if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
if ($CFG->defaulthomepage == HOMEPAGE_MY) {
return HOMEPAGE_MY;
} else {
return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
}
}
return HOMEPAGE_SITE;
}
/**
* Gets the name of a course to be displayed when showing a list of courses.
* By default this is just $course->fullname but user can configure it. The
* result of this function should be passed through print_string.
* @param stdClass|course_in_list $course Moodle course object
* @return string Display name of course (either fullname or short + fullname)
*/
function get_course_display_name_for_list($course) {
global $CFG;
if (!empty($CFG->courselistshortnames)) {
if (!($course instanceof stdClass)) {
$course = (object)convert_to_array($course);
}
return get_string('courseextendednamedisplay', '', $course);
} else {
return $course->fullname;
}
}
/**
* The lang_string class
*
* This special class is used to create an object representation of a string request.
* It is special because processing doesn't occur until the object is first used.
* The class was created especially to aid performance in areas where strings were
* required to be generated but were not necessarily used.
* As an example the admin tree when generated uses over 1500 strings, of which
* normally only 1/3 are ever actually printed at any time.
* The performance advantage is achieved by not actually processing strings that
* arn't being used, as such reducing the processing required for the page.
*
* How to use the lang_string class?
* There are two methods of using the lang_string class, first through the
* forth argument of the get_string function, and secondly directly.
* The following are examples of both.
* 1. Through get_string calls e.g.
* $string = get_string($identifier, $component, $a, true);
* $string = get_string('yes', 'moodle', null, true);
* 2. Direct instantiation
* $string = new lang_string($identifier, $component, $a, $lang);
* $string = new lang_string('yes');
*
* How do I use a lang_string object?
* The lang_string object makes use of a magic __toString method so that you
* are able to use the object exactly as you would use a string in most cases.
* This means you are able to collect it into a variable and then directly
* echo it, or concatenate it into another string, or similar.
* The other thing you can do is manually get the string by calling the
* lang_strings out method e.g.
* $string = new lang_string('yes');
* $string->out();
* Also worth noting is that the out method can take one argument, $lang which
* allows the developer to change the language on the fly.
*
* When should I use a lang_string object?
* The lang_string object is designed to be used in any situation where a
* string may not be needed, but needs to be generated.
* The admin tree is a good example of where lang_string objects should be
* used.
* A more practical example would be any class that requries strings that may
* not be printed (after all classes get renderer by renderers and who knows
* what they will do ;))
*
* When should I not use a lang_string object?
* Don't use lang_strings when you are going to use a string immediately.
* There is no need as it will be processed immediately and there will be no
* advantage, and in fact perhaps a negative hit as a class has to be
* instantiated for a lang_string object, however get_string won't require
* that.
*
* Limitations:
* 1. You cannot use a lang_string object as an array offset. Doing so will
* result in PHP throwing an error. (You can use it as an object property!)
*
* @package core
* @category string
* @copyright 2011 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class lang_string {
/** @var string The strings identifier */
protected $identifier;
/** @var string The strings component. Default '' */
protected $component = '';
/** @var array|stdClass Any arguments required for the string. Default null */
protected $a = null;
/** @var string The language to use when processing the string. Default null */
protected $lang = null;
/** @var string The processed string (once processed) */
protected $string = null;
/**
* A special boolean. If set to true then the object has been woken up and
* cannot be regenerated. If this is set then $this->string MUST be used.
* @var bool
*/
protected $forcedstring = false;
/**
* Constructs a lang_string object
*
* This function should do as little processing as possible to ensure the best
* performance for strings that won't be used.
*
* @param string $identifier The strings identifier
* @param string $component The strings component
* @param stdClass|array $a Any arguments the string requires
* @param string $lang The language to use when processing the string.
* @throws coding_exception
*/
public function __construct($identifier, $component = '', $a = null, $lang = null) {
if (empty($component)) {
$component = 'moodle';
}
$this->identifier = $identifier;
$this->component = $component;
$this->lang = $lang;
// We MUST duplicate $a to ensure that it if it changes by reference those
// changes are not carried across.
// To do this we always ensure $a or its properties/values are strings
// and that any properties/values that arn't convertable are forgotten.
if (!empty($a)) {
if (is_scalar($a)) {
$this->a = $a;
} else if ($a instanceof lang_string) {
$this->a = $a->out();
} else if (is_object($a) or is_array($a)) {
$a = (array)$a;
$this->a = array();
foreach ($a as $key => $value) {
// Make sure conversion errors don't get displayed (results in '').
if (is_array($value)) {
$this->a[$key] = '';
} else if (is_object($value)) {
if (method_exists($value, '__toString')) {
$this->a[$key] = $value->__toString();
} else {
$this->a[$key] = '';
}
} else {
$this->a[$key] = (string)$value;
}
}
}
}
if (debugging(false, DEBUG_DEVELOPER)) {
if (clean_param($this->identifier, PARAM_STRINGID) == '') {
throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
}
if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
throw new coding_exception('Invalid string compontent. Please check your string definition');
}
if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
}
}
}
/**
* Processes the string.
*
* This function actually processes the string, stores it in the string property
* and then returns it.
* You will notice that this function is VERY similar to the get_string method.
* That is because it is pretty much doing the same thing.
* However as this function is an upgrade it isn't as tolerant to backwards
* compatibility.
*
* @return string
* @throws coding_exception
*/
protected function get_string() {
global $CFG;
// Check if we need to process the string.
if ($this->string === null) {
// Check the quality of the identifier.
if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition', DEBUG_DEVELOPER);
}
// Process the string.
$this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
// Debugging feature lets you display string identifier and component.
if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
$this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
}
}
// Return the string.
return $this->string;
}
/**
* Returns the string
*
* @param string $lang The langauge to use when processing the string
* @return string
*/
public function out($lang = null) {
if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
if ($this->forcedstring) {
debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
return $this->get_string();
}
$translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
return $translatedstring->out();
}
return $this->get_string();
}
/**
* Magic __toString method for printing a string
*
* @return string
*/
public function __toString() {
return $this->get_string();
}
/**
* Magic __set_state method used for var_export
*
* @return string
*/
public function __set_state() {
return $this->get_string();
}
/**
* Prepares the lang_string for sleep and stores only the forcedstring and
* string properties... the string cannot be regenerated so we need to ensure
* it is generated for this.
*
* @return string
*/
public function __sleep() {
$this->get_string();
$this->forcedstring = true;
return array('forcedstring', 'string', 'lang');
}
}
| dixidix/simulacion | lib/moodlelib.php | PHP | gpl-3.0 | 345,417 |
<html><body>Grocer Pano:<br>
Bad choice! You lose! The correct sequence was silver - silver - blood.
</body></html> | karolusw/l2j | game/data/scripts/quests/Q00336_CoinsOfMagic/30078-44.html | HTML | gpl-3.0 | 115 |
<?php
/**
* @package DigiCom
* @author ThemeXpert http://www.themexpert.com
* @copyright Copyright (c) 2010-2015 ThemeXpert. All rights reserved.
* @license GNU General Public License version 3 or later; see LICENSE.txt
* @since 1.0.0
*/
defined('_JEXEC') or die;
class DigiComViewOrder extends JViewLegacy
{
protected $state;
protected $item;
protected $form;
protected $configs;
function display( $tpl = null )
{
$app = JFactory::getApplication();
$this->state = $this->get('State');
$this->item = $this->get('Item');
$this->form = $this->get('Form');
$this->configs = $this->get('configs');
JToolBarHelper::title( JText::_( 'COM_DIGICOM_ORDER_DETAILS_TOOLBAR_TITLE_SITE' ), 'generic.png' );
$bar = JToolBar::getInstance('toolbar');
// Instantiate a new JLayoutFile instance and render the layout
$layout = new JLayoutFile('toolbar.title');
$title=array(
'title' => JText::_( 'COM_DIGICOM_ORDER_DETAILS_TOOLBAR_TITLE' ),
'class' => 'title'
);
$bar->appendButton('Custom', $layout->render($title), 'title');
$layout = new JLayoutFile('toolbar.settings');
$bar->appendButton('Custom', $layout->render(array()), 'settings');
$layout = new JLayoutFile('toolbar.video');
$bar->appendButton('Custom', $layout->render(array()), 'video');
JToolBarHelper::apply('order.apply');
JToolBarHelper::save('order.save');
JToolBarHelper::Cancel('order.cancel');
DigiComHelperDigiCom::addSubmenu('orders');
$this->sidebar = JHtmlSidebar::render();
parent::display( $tpl );
}
}
| Suki00789/escb-mysql | site/administrator/components/com_digicom/views/order/view.html.php | PHP | gpl-3.0 | 1,549 |
#******************************************************************************
#
# Makefile - Rules for building the dk-tm4c129x-boost-dlp7970abp examples.
#
# Copyright (c) 2013-2017 Texas Instruments Incorporated. All rights reserved.
# Software License Agreement
#
# Texas Instruments (TI) is supplying this software for use solely and
# exclusively on TI's microcontroller products. The software is owned by
# TI and/or its suppliers, and is protected under applicable copyright
# laws. You may not combine this software with "viral" open-source
# software in order to form a larger program.
#
# THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
# NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
# NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
# CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
# DAMAGES, FOR ANY REASON WHATSOEVER.
#
# This is part of revision 2.1.4.178 of the DK-TM4C129X Firmware Package.
#
#******************************************************************************
#
# A list of the directories containing the examples.
#
DIRS=nfc_p2p_demo
#
# The default rule, which causes the examples to be built.
#
all:
@for i in ${DIRS}; \
do \
make -C $${i} || exit $$?; \
done
#
# The rule to clean out all the build products.
#
clean:
@rm -rf ${wildcard *~} __dummy__
@-for i in ${DIRS}; \
do \
make -C $${i} clean; \
done
| jhnphm/xbs_xbd | platforms/ek-tm4c129exl_16mhz/hal/tivaware/examples/boards/dk-tm4c129x-boost-dlp7970abp/Makefile | Makefile | gpl-3.0 | 1,635 |
/*
* (C) 2003-2006 Gabest
* (C) 2006-2014 see Authors.txt
*
* This file is part of MPC-HC.
*
* MPC-HC 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.
*
* MPC-HC 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/>.
*
*/
#pragma once
#include <atlcoll.h>
#include "StatusLabel.h"
class CMainFrame;
// CPlayerInfoBar
class CPlayerInfoBar : public CDialogBar
{
DECLARE_DYNAMIC(CPlayerInfoBar)
private:
CMainFrame* m_pMainFrame;
CAutoPtrArray<CStatusLabel> m_label;
CAutoPtrArray<CStatusLabel> m_info;
CToolTipCtrl m_tooltip;
void Relayout();
public:
CPlayerInfoBar(CMainFrame* pMainFrame);
virtual ~CPlayerInfoBar();
BOOL Create(CWnd* pParentWnd);
void SetLine(CString label, CString info);
void GetLine(CString label, CString& info);
void RemoveLine(CString label);
void RemoveAllLines();
protected:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual CSize CalcFixedLayout(BOOL bStretch, BOOL bHorz);
virtual BOOL PreTranslateMessage(MSG* pMsg);
public:
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnSize(UINT nType, int cx, int cy);
DECLARE_MESSAGE_MAP()
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
};
| cccp/mpc-hc | src/mpc-hc/PlayerInfoBar.h | C | gpl-3.0 | 1,804 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.