code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
(function( $ ) {
'use strict';
/**
* All of the code for your admin-facing JavaScript source
* should reside in this file.
*
* This enables you to define handlers, for when the DOM is ready:
*
* $(function() {
*
* });
*
* When the window is loaded:
*
* $( window ).load(function() {
*
* });
*/
$(function() {
console.log("Hallo Welt");
});
})( jQuery );
| BenRichter/wp-offline-saver | admin/js/offline-saver-admin.js | JavaScript | gpl-2.0 | 395 |
/////////////////////////////////////////////////////////////////////////////
//
// (c) 2007 BinaryComponents Ltd. All Rights Reserved.
//
// http://www.binarycomponents.com/
//
/////////////////////////////////////////////////////////////////////////////
using System;
using System.Drawing;
using System.Windows.Forms;
using BinaryComponents.SuperList.Helper;
using BinaryComponents.Utility.Assemblies;
using BinaryComponents.Utility.Collections;
using System.Resources;
using System.Globalization;
namespace BinaryComponents.SuperList.Sections
{
public abstract class OptionsToolbarSection : Section
{
protected OptionsToolbarSection(ListControl listControl)
: base(listControl)
{
}
public abstract int IdealWidth
{
get;
}
public abstract int MinimumWidth
{
get;
}
public abstract bool Visible
{
get;
set;
}
}
public class ToolStripOptionsToolbarSection : OptionsToolbarSection
{
public ToolStripOptionsToolbarSection(ListControl listControl)
: base(listControl)
{
_listControl = listControl;
_toolStrip = new ToolStrip();
_toolStrip.AutoSize = true;
_toolStrip.Visible = false;
_toolStrip.Anchor = AnchorStyles.None;
_toolStrip.Dock = DockStyle.None;
_toolStrip.GripStyle = ToolStripGripStyle.Hidden;
_toolStrip.TabIndex = 0;
_toolStrip.Text = "List options";
_toolStrip.CanOverflow = true;
_toolStrip.Renderer = new MyRenderer();
_toolStrip.BackColor = Color.Transparent;
_toolStrip.Layout += _toolStrip_Layout;
AddDefaultToolStripButtons();
_toolStrip.CreateControl();
listControl.Controls.Add(_toolStrip);
listControl.Columns.GroupedItems.DataChanged += GroupedItems_DataChanged;
HandleEnablingGroupButtons();
}
public override void Dispose()
{
if (_columnButton != null)
{
_columnButton.Click -= _columnButton_Click;
_columnButton = null;
}
if (_collapseGroupButton != null)
{
_collapseGroupButton.Click -= _collapseGroupButton_Click;
_collapseGroupButton = null;
}
if (_expandGroupsButton != null)
{
_expandGroupsButton.Click -= _expandGroupsButton_Click;
_expandGroupsButton = null;
}
if (_toolStrip != null)
{
_toolStrip.Dispose();
_toolStrip = null;
}
}
public void AddToolStripItems(params ToolStripItem[] items)
{
_toolStrip.Items.AddRange(items);
_toolStrip.AutoSize = true;
}
public override int IdealWidth
{
get
{
return _toolStrip.PreferredSize.Width;
}
}
public override int MinimumWidth
{
get
{
return 12;
}
}
public override void Layout(GraphicsSettings gs, Size maximumSize)
{
_toolStrip.MaximumSize = new Size(maximumSize.Width, 0);
Size = new Size(_toolStrip.Size.Width, maximumSize.Height);
}
public override Point Location
{
get
{
return base.Location;
}
set
{
base.Location = value;
_toolStrip.Location = new Point(value.X, value.Y + (Size.Height - _toolStrip.Size.Height)/2);
}
}
public override bool Visible
{
get
{
return _toolStrip.Visible;
}
set
{
_toolStrip.Visible = value;
}
}
public ListSection ListSection
{
get
{
return ((ListControl) Host).ListSection;
}
}
public void ShowColumnChooser(Point pt)
{
AvailableSectionsForm columnChooserForm = CreateAvailableSectionsForm();
columnChooserForm.ColumnList = _listControl.Columns;
columnChooserForm.Location = pt;
columnChooserForm.Show(_listControl);
}
public override void ChangeLanguage(CultureInfo culture)
{
_columnButton.Text = ResourceHelper.Instance.GetString("ToolStripOptionsToolbarSection.Columns", culture);
_columnButton.ToolTipText = ResourceHelper.Instance.GetString("ToolStripOptionsToolbarSection.ColumnsTooltip", culture);
_collapseGroupButton.ToolTipText = ResourceHelper.Instance.GetString("ToolStripOptionsToolbarSection.CollapseTooltip", culture);
_expandGroupsButton.ToolTipText = ResourceHelper.Instance.GetString("ToolStripOptionsToolbarSection.ExpandTooltip", culture);
}
#region Default buttons
protected virtual void AddDefaultToolStripButtons()
{
ManifestResources res = new ManifestResources("BinaryComponents.SuperList.Resources");
_columnButton = new ToolStripButton();
_columnButton.Name = "_columnButton";
_columnButton.Image = res.GetIcon("ColumnsButton.ico").ToBitmap();
_columnButton.Text = ResourceHelper.Instance.GetString("ToolStripOptionsToolbarSection.Columns");
_columnButton.Click += _columnButton_Click;
_columnButton.ToolTipText = ResourceHelper.Instance.GetString("ToolStripOptionsToolbarSection.ColumnsTooltip");
_columnButton.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
_collapseGroupButton = new ToolStripButton();
_collapseGroupButton.Visible = true;
_collapseGroupButton.Name = "collapseAllGroupsButton";
_collapseGroupButton.Image = res.GetIcon("CollapseAllGroupsButton.ico").ToBitmap();
_collapseGroupButton.Click += _collapseGroupButton_Click;
_collapseGroupButton.DisplayStyle = ToolStripItemDisplayStyle.Image;
_collapseGroupButton.ToolTipText = ResourceHelper.Instance.GetString("ToolStripOptionsToolbarSection.CollapseTooltip");
_expandGroupsButton = new ToolStripButton();
_expandGroupsButton.Visible = true;
_expandGroupsButton.Name = "expandAllGroupsButton";
_expandGroupsButton.Image = res.GetIcon("ExpandAllGroupsButton.ico").ToBitmap();
_expandGroupsButton.Click += _expandGroupsButton_Click;
_expandGroupsButton.DisplayStyle = ToolStripItemDisplayStyle.Image;
_expandGroupsButton.ToolTipText = ResourceHelper.Instance.GetString("ToolStripOptionsToolbarSection.ExpandTooltip");
AddToolStripItems(new ToolStripItem[] {_columnButton, _collapseGroupButton, _expandGroupsButton});
}
private void _columnButton_Click(object sender, EventArgs e)
{
ShowColumnChooser(new Point(Cursor.Position.X, Rectangle.Bottom + _listControl.PointToScreen(Location).Y));
}
private void _collapseGroupButton_Click(object sender, EventArgs e)
{
ListSection.SetGlobalGroupState(ListSection.GroupState.Collapsed);
}
private void _expandGroupsButton_Click(object sender, EventArgs e)
{
ListSection.SetGlobalGroupState(ListSection.GroupState.Expanded);
}
#endregion
protected virtual AvailableSectionsForm CreateAvailableSectionsForm()
{
return new AvailableSectionsForm();
}
private void _toolStrip_Layout(object sender, LayoutEventArgs e)
{
Host.LazyLayout(null);
}
private void GroupedItems_DataChanged(object sender, EventingList<Column>.EventInfo e)
{
HandleEnablingGroupButtons();
}
private void HandleEnablingGroupButtons()
{
if (_collapseGroupButton != null)
{
_collapseGroupButton.Enabled = _listControl.Columns.GroupedItems.Count > 0;
}
if (_expandGroupsButton != null)
{
_expandGroupsButton.Enabled = _listControl.Columns.GroupedItems.Count > 0;
}
}
private class MyRenderer : ToolStripProfessionalRenderer
{
protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e)
{
if (e.ToolStrip is ToolStripOverflow)
{
base.OnRenderToolStripBorder(e);
}
}
}
private delegate void ButtonClicked();
private ToolStrip _toolStrip;
private ToolStripButton _collapseGroupButton;
private ToolStripButton _expandGroupsButton;
private ToolStripButton _columnButton;
private ListControl _listControl;
}
} | CecleCW/ProductMan | ProductMan/SuperList/Sections/OptionsToolbarSection.cs | C# | gpl-2.0 | 9,455 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TestBase4.TestCases.AReferencedAssembly;
using TestBase4.TestCases.ReferencedAssembly2;
namespace TestBase4.TestCases
{
/// <summary>
/// "Referenced Assembly" as in <see cref="Assembly.GetReferencedAssemblies"/> --
/// may not mean what you think it means. Adding an assembly as a reference to a project does <em>not</em> make
/// it a referenced assembly. Only if your code actually refers to a Type from that assembly
/// does it become referenced.
/// </summary>
static class ForceReferencesToReferencedAssemblies
{
public static object Force()
{
// ReSharper disable once UnusedVariable
var ref1 = new SomeOtherTypeInReferencedAssembly();
var ref2 = new SomeOtherTypeInReferencedAssembly2();
return new object[] { ref1, ref2 };
}
}
}
| chrisfcarroll/TestBase4 | TestBase4.TestCases/ForceReferencesToReferencedAssemblies.cs | C# | gpl-2.0 | 1,000 |
<?php
/**
* @package Redirect-On-Login (com_redirectonlogin)
* @version 3.1.0
* @copyright Copyright (C) 2008 - 2013 Carsten Engel. All rights reserved.
* @license GPL versions free/trial/pro
* @author http://www.pages-and-items.com
* @joomla Joomla is Free Software
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
class redirectonloginController extends JController{
public $db;
public $rol_config;
public $rol_demo_seconds_left;
public $rol_version = '3.1.0';
private $rol_version_type = 'free';
private $helper;
function display(){
// Set a default view if none exists
if (!JRequest::getVar('view')){
JRequest::setVar('view', 'configuration' );
}
//set title
JToolBarHelper::title('Redirect on login','rol_icon');
if(JRequest::getVar('layout', '')!='csv'){
//display css
$document = JFactory::getDocument();
$document->addStyleSheet('components/com_redirectonlogin/css/redirectonlogin3.css');
$version = new JVersion;
echo '<div';
if($version->RELEASE >= '3.0'){
echo ' class="joomla3"';
}
echo '>';
//display trial-version stuff
$this->display_trial_version_stuff();
//display message if not enabled
$this->not_enabled_message();
if($version->RELEASE >= '3.0'){
//bootstrap selects
JHtml::_('bootstrap.tooltip');
JHtml::_('behavior.multiselect');
JHtml::_('formbehavior.chosen', 'select');
}else{
//make sure mootools is loaded
JHTML::_('behavior.mootools');
// Load the submenu
$this->helper->addSubmenu(JRequest::getWord('view', 'redirectonlogin'));
}
}
parent::display();
//display footer
if(JRequest::getVar('layout', '')!='csv'){
echo '</div>';
$this->display_footer();
}
}
function __construct(){
$this->db = JFactory::getDBO();
$this->rol_config = $this->get_config();
$this->helper = $this->get_helper();
parent::__construct();
}
function usergroup_save(){
// Check for request forgeries
JRequest::checkToken() or jexit('Invalid Token');
$group_id = intval(JRequest::getVar('group_id', ''));
$redirect_id = intval(JRequest::getVar('redirect_id', ''));
$frontend_type = JRequest::getVar('redirect_frontend_type', '');
$frontend_url = JRequest::getVar('frontend_url', '');
$frontend_type_logout = JRequest::getVar('redirect_frontend_type_logout', '');
$frontend_url_logout = JRequest::getVar('frontend_url_logout', '');
$backend_type = JRequest::getVar('redirect_backend_type', '');
$backend_url = JRequest::getVar('backend_url', '');
$backend_component = JRequest::getVar('backend_component', '');
$opening_site = JRequest::getVar('opening_site', '');
$opening_site_url = JRequest::getVar('opening_site_url', '');
$opening_site_home = JRequest::getVar('opening_site_home', '');
$menuitem_login = JRequest::getVar('menuitem_login', 0);
$menuitem_open = JRequest::getVar('menuitem_open', 0);
$menuitem_logout = JRequest::getVar('menuitem_logout', 0);
$dynamic_login = JRequest::getVar('dynamic_login', 0);
$dynamic_open = JRequest::getVar('dynamic_open', 0);
$dynamic_logout = JRequest::getVar('dynamic_logout', 0);
$open_type = JRequest::getVar('open_type', 'url');
$inherit_login = JRequest::getVar('inherit_login', 0);
$inherit_open = JRequest::getVar('inherit_open', 0);
$inherit_logout = JRequest::getVar('inherit_logout', 0);
$inherit_backend = JRequest::getVar('inherit_backend', 0);
$database = JFactory::getDBO();
if($redirect_id){
//update
$database->setQuery( "UPDATE #__redirectonlogin_groups SET group_id='$group_id', frontend_type='$frontend_type', frontend_url='$frontend_url', frontend_type_logout='$frontend_type_logout', frontend_url_logout='$frontend_url_logout', backend_type='$backend_type', backend_url='$backend_url', backend_component='$backend_component', opening_site='$opening_site', opening_site_url='$opening_site_url', opening_site_home='$opening_site_home', menuitem_login='$menuitem_login', menuitem_open='$menuitem_open', menuitem_logout='$menuitem_logout', dynamic_login='$dynamic_login', dynamic_open='$dynamic_open', dynamic_logout='$dynamic_logout', open_type='$open_type', inherit_login='$inherit_login', inherit_open='$inherit_open', inherit_logout='$inherit_logout', inherit_backend='$inherit_backend' WHERE id='$redirect_id' " );
$database->query();
}else{
//insert
$database->setQuery( "INSERT INTO #__redirectonlogin_groups SET group_id='$group_id', frontend_type='$frontend_type', frontend_url='$frontend_url', frontend_type_logout='$frontend_type_logout', frontend_url_logout='$frontend_url_logout', backend_type='$backend_type', backend_url='$backend_url', backend_component='$backend_component', opening_site='$opening_site', opening_site_url='$opening_site_url', opening_site_home='$opening_site_home', menuitem_login='$menuitem_login', menuitem_open='$menuitem_open', menuitem_logout='$menuitem_logout', dynamic_login='$dynamic_login', dynamic_open='$dynamic_open', dynamic_logout='$dynamic_logout', open_type='$open_type', inherit_login='$inherit_login', inherit_open='$inherit_open', inherit_logout='$inherit_logout', inherit_backend='$inherit_backend' ");
$database->query();
}
//redirect
$url = 'index.php?option=com_redirectonlogin&view=usergroups';
if(JRequest::getVar('apply', 0)){
$url = 'index.php?option=com_redirectonlogin&view=usergroup&group_id='.$group_id;
}
$app = JFactory::getApplication();
$app->redirect($url, JText::_('COM_REDIRECTONLOGIN_REDIRECT_SAVED'));
}
function accesslevel_save(){
// Check for request forgeries
JRequest::checkToken() or jexit('Invalid Token');
$redirect_id = intval(JRequest::getVar('redirect_id', ''));
$group_id = intval(JRequest::getVar('group_id', ''));
$frontend_type = JRequest::getVar('redirect_type', 'none');
$frontend_url = JRequest::getVar('frontend_url', '');
$frontend_type_logout = JRequest::getVar('redirect_type_logout', 'none');
$frontend_url_logout = JRequest::getVar('frontend_url_logout', '');
$opening_site = JRequest::getVar('opening_site', '');
$opening_site_url = JRequest::getVar('opening_site_url', '');
$opening_site_home = JRequest::getVar('opening_site_home', '');
$menuitem_login = JRequest::getVar('menuitem_login', 0);
$menuitem_open = JRequest::getVar('menuitem_open', 0);
$menuitem_logout = JRequest::getVar('menuitem_logout', 0);
$dynamic_login = JRequest::getVar('dynamic_login', 0);
$dynamic_open = JRequest::getVar('dynamic_open', 0);
$dynamic_logout = JRequest::getVar('dynamic_logout', 0);
$open_type = JRequest::getVar('open_type', 'url');
$inherit_login = JRequest::getVar('inherit_login', 0);
$inherit_open = JRequest::getVar('inherit_open', 0);
$inherit_logout = JRequest::getVar('inherit_logout', 0);
$database = JFactory::getDBO();
if($redirect_id){
//update
$database->setQuery( "UPDATE #__redirectonlogin_levels SET frontend_type='$frontend_type', frontend_url='$frontend_url', frontend_type_logout='$frontend_type_logout', frontend_url_logout='$frontend_url_logout', opening_site='$opening_site', opening_site_url='$opening_site_url', opening_site_home='$opening_site_home', menuitem_login='$menuitem_login', menuitem_open='$menuitem_open', menuitem_logout='$menuitem_logout', dynamic_login='$dynamic_login', dynamic_open='$dynamic_open', dynamic_logout='$dynamic_logout', open_type='$open_type', inherit_login='$inherit_login', inherit_open='$inherit_open', inherit_logout='$inherit_logout' WHERE id='$redirect_id' ");
$database->query();
}else{
//insert
$database->setQuery( "INSERT INTO #__redirectonlogin_levels SET group_id='$group_id', frontend_type='$frontend_type', frontend_url='$frontend_url', frontend_type_logout='$frontend_type_logout', frontend_url_logout='$frontend_url_logout', opening_site='$opening_site', opening_site_url='$opening_site_url', opening_site_home='$opening_site_home', menuitem_login='$menuitem_login', menuitem_open='$menuitem_open', menuitem_logout='$menuitem_logout', dynamic_login='$dynamic_login', dynamic_open='$dynamic_open', dynamic_logout='$dynamic_logout', open_type='$open_type', inherit_login='$inherit_login', inherit_open='$inherit_open', inherit_logout='$inherit_logout' ");
$database->query();
}
//redirect
$url = 'index.php?option=com_redirectonlogin&view=accesslevels';
if(JRequest::getVar('apply', 0)){
$url = 'index.php?option=com_redirectonlogin&view=accesslevel&group_id='.$group_id;
}
$app = JFactory::getApplication();
$app->redirect($url, JText::_('COM_REDIRECTONLOGIN_REDIRECT_SAVED'));
}
function get_config(){
$database = JFactory::getDBO();
$database->setQuery("SELECT config "
."FROM #__redirectonlogin_config "
."WHERE id='1' "
."LIMIT 1"
);
$raw = $database->loadResult();
$params = explode( "\n", $raw);
for($n = 0; $n < count($params); $n++){
$temp = explode('=',$params[$n]);
$var = $temp[0];
$value = '';
if(count($temp)==2){
$value = trim($temp[1]);
/*
if($value=='false'){
$value = false;
}
if($value=='true'){
$value = true;
}
*/
}
$config[$var] = $value;
}
//reformat redirect urls
$config['redirect_url_backend'] = str_replace('[equal]','=',$config['redirect_url_backend']);
$config['redirect_component_backend'] = str_replace('[equal]','=',$config['redirect_component_backend']);
$config['redirect_url_frontend'] = str_replace('[equal]','=',$config['redirect_url_frontend']);
$config['redirect_url_frontend_logout'] = str_replace('[equal]','=',$config['redirect_url_frontend_logout']);
$config['opening_site_url'] = str_replace('[equal]','=',$config['opening_site_url']);
//get default message
if($config['logout_message_frontend']=='COM_REDIRECTONLOGIN_YOU_CANT_LOGIN'){
$config['logout_message_frontend'] = JText::_('COM_REDIRECTONLOGIN_YOU_CANT_LOGIN');
}
if($config['logout_message_backend']=='COM_REDIRECTONLOGIN_YOU_CANT_LOGIN'){
$config['logout_message_backend'] = JText::_('COM_REDIRECTONLOGIN_YOU_CANT_LOGIN');
}
return $config;
}
function config_save(){
// Check for request forgeries
JRequest::checkToken() or jexit('Invalid Token');
$redirect_url_backend = JRequest::getVar('redirect_url_backend', '', 'post');
$redirect_url_backend = str_replace('=','[equal]',$redirect_url_backend);
$redirect_url_backend = addslashes($redirect_url_backend);
$redirect_url_frontend = JRequest::getVar('redirect_url_frontend', '', 'post');
$redirect_url_frontend = str_replace('=','[equal]',$redirect_url_frontend);
$redirect_url_frontend = addslashes($redirect_url_frontend);
$redirect_url_frontend_logout = JRequest::getVar('redirect_url_frontend_logout', '', 'post');
$redirect_url_frontend_logout = str_replace('=','[equal]',$redirect_url_frontend_logout);
$redirect_url_frontend_logout = addslashes($redirect_url_frontend_logout);
$redirect_component_backend = JRequest::getVar('redirect_component_backend', '', 'post');
$redirect_component_backend = str_replace('=','[equal]',$redirect_component_backend);
$opening_site_url = JRequest::getVar('opening_site_url', '', 'post');
$opening_site_url = str_replace('=','[equal]',$opening_site_url);
$opening_site_url = addslashes($opening_site_url);
$config = 'enable_redirection='.JRequest::getVar('enable_redirection', '', 'post').'
redirect_type_backend='.JRequest::getVar('redirect_type_backend', 'none', 'post').'
redirect_component_backend='.$redirect_component_backend.'
redirect_url_backend='.$redirect_url_backend.'
frontend_u_or_a='.JRequest::getVar('frontend_u_or_a', '', 'post').'
redirect_type_frontend='.JRequest::getVar('redirect_type_frontend', 'none', 'post').'
redirect_url_frontend='.$redirect_url_frontend.'
redirect_type_frontend_logout='.JRequest::getVar('redirect_type_frontend_logout', 'none', 'post').'
redirect_url_frontend_logout='.$redirect_url_frontend_logout.'
version_checker='.JRequest::getVar('version_checker', '', 'post').'
logout_message_frontend='.addslashes(JRequest::getVar('logout_message_frontend', '', 'post')).'
logout_message_backend='.addslashes(JRequest::getVar('logout_message_backend', '', 'post')).'
opening_site='.JRequest::getVar('opening_site', '', 'post').'
opening_site_url='.$opening_site_url.'
opening_site_type='.JRequest::getVar('opening_site_type', '', 'post').'
opening_site_home='.JRequest::getVar('opening_site_home', '', 'post').'
menuitem_login='.JRequest::getVar('menuitem_login', '', 'post').'
menuitem_open='.JRequest::getVar('menuitem_open', '', 'post').'
menuitem_logout='.JRequest::getVar('menuitem_logout', '', 'post').'
dynamic_login='.JRequest::getVar('dynamic_login', '', 'post').'
dynamic_open='.JRequest::getVar('dynamic_open', '', 'post').'
dynamic_logout='.JRequest::getVar('dynamic_logout', '', 'post').'
opening_site_type2='.JRequest::getVar('opening_site_type2', '', 'post').'
after_no_access_page='.JRequest::getVar('after_no_access_page', '', 'post').'
multilanguage_menu_association='.JRequest::getVar('multilanguage_menu_association', '', 'post').'
lang_type_login_front='.JRequest::getVar('lang_type_login_front', '', 'post').'
lang_type_login_back='.JRequest::getVar('lang_type_login_back', '', 'post').'
';
//update config
$this->db->setQuery( "UPDATE #__redirectonlogin_config SET config='$config' WHERE id='1' ");
$this->db->query();
$app = JFactory::getApplication();
$app->redirect('index.php?option=com_redirectonlogin&view=configuration', JText::_('COM_REDIRECTONLOGIN_CONFIGURATION_SAVED'));
}
function save_order_accesslevels(){
$levels_order = JRequest::getVar('order', array(), 'post', 'array');
$levels_id = JRequest::getVar('level_id', array(), 'post', 'array');
$order_ids = JRequest::getVar('order_id', array(), 'post', 'array');
for($n = 0; $n < count($levels_id); $n++){
$level_order = $levels_order[$n];
$level_id = $levels_id[$n];
$order_id = $order_ids[$n];
if($order_id){
//update order
$this->db->setQuery( "UPDATE #__redirectonlogin_order_levels SET redirect_order='$level_order' WHERE id='$order_id' ");
$this->db->query();
}else{
//insert order
$this->db->setQuery( "INSERT INTO #__redirectonlogin_order_levels SET level_id='$level_id', redirect_order='$level_order' ");
$this->db->query();
}
}
$app = JFactory::getApplication();
$app->redirect('index.php?option=com_redirectonlogin&view=accesslevels', JText::_('COM_REDIRECTONLOGIN_ACCESSLEVEL_ORDER_SAVED'));
}
function save_order_groups_front(){
$orders_front = JRequest::getVar('order_front', array(), 'post', 'array');
$group_ids = JRequest::getVar('group_id', array(), 'post', 'array');
$order_ids = JRequest::getVar('order_id', array(), 'post', 'array');
for($n = 0; $n < count($group_ids); $n++){
$order = $orders_front[$n];
$group_id = $group_ids[$n];
$order_id = $order_ids[$n];
if($order_id){
//update order
$this->db->setQuery( "UPDATE #__redirectonlogin_order_groups SET redirect_order_front='$order' WHERE id='$order_id' ");
$this->db->query();
}else{
//insert order
$this->db->setQuery( "INSERT INTO #__redirectonlogin_order_groups SET group_id='$group_id', redirect_order_front='$order' ");
$this->db->query();
}
}
$app = JFactory::getApplication();
$app->redirect('index.php?option=com_redirectonlogin&view=usergroups', JText::_('COM_REDIRECTONLOGIN_USERGROUP_ORDER_SAVED_FRONTEND'));
}
function save_order_groups_back(){
$orders_back = JRequest::getVar('order_back', array(), 'post', 'array');
$group_ids = JRequest::getVar('group_id', array(), 'post', 'array');
$order_ids = JRequest::getVar('order_id', array(), 'post', 'array');
for($n = 0; $n < count($group_ids); $n++){
$order = $orders_back[$n];
$group_id = $group_ids[$n];
$order_id = $order_ids[$n];
if($order_id){
//update order
$this->db->setQuery( "UPDATE #__redirectonlogin_order_groups SET redirect_order_back='$order' WHERE id='$order_id' ");
$this->db->query();
}else{
//insert order
$this->db->setQuery( "INSERT INTO #__redirectonlogin_order_groups SET group_id='$group_id', redirect_order_back='$order' ");
$this->db->query();
}
}
$app = JFactory::getApplication();
$app->redirect('index.php?option=com_redirectonlogin&view=usergroups', JText::_('COM_REDIRECTONLOGIN_USERGROUP_ORDER_SAVED_BACKEND'));
}
function user_save(){
// Check for request forgeries
JRequest::checkToken() or jexit('Invalid Token');
$user_id = intval(JRequest::getVar('user_id', ''));
$redirect_id = intval(JRequest::getVar('redirect_id', ''));
$frontend_type = JRequest::getVar('redirect_frontend_type', '');
$frontend_url = addslashes(JRequest::getVar('frontend_url', ''));
$frontend_type_logout = JRequest::getVar('redirect_frontend_type_logout', '');
$frontend_url_logout = addslashes(JRequest::getVar('frontend_url_logout', ''));
$backend_type = JRequest::getVar('redirect_backend_type', '');
$backend_url = addslashes(JRequest::getVar('backend_url', ''));
$backend_component = JRequest::getVar('backend_component', '');
$opening_site = JRequest::getVar('opening_site', '');
$opening_site_url = addslashes(JRequest::getVar('opening_site_url', ''));
$opening_site_home = JRequest::getVar('opening_site_home', '');
$menuitem_login = JRequest::getVar('menuitem_login', 0);
$menuitem_open = JRequest::getVar('menuitem_open', 0);
$menuitem_logout = JRequest::getVar('menuitem_logout', 0);
$dynamic_login = JRequest::getVar('dynamic_login', 0);
$dynamic_open = JRequest::getVar('dynamic_open', 0);
$dynamic_logout = JRequest::getVar('dynamic_logout', 0);
$open_type = JRequest::getVar('open_type', 'url');
$database = JFactory::getDBO();
if($redirect_id){
//update
$database->setQuery( "UPDATE #__redirectonlogin_users SET user_id='$user_id', frontend_type='$frontend_type', frontend_url='$frontend_url', frontend_type_logout='$frontend_type_logout', frontend_url_logout='$frontend_url_logout', backend_type='$backend_type', backend_url='$backend_url', backend_component='$backend_component', opening_site='$opening_site', opening_site_url='$opening_site_url', opening_site_home='$opening_site_home', menuitem_login='$menuitem_login', menuitem_open='$menuitem_open', menuitem_logout='$menuitem_logout', dynamic_login='$dynamic_login', dynamic_open='$dynamic_open', dynamic_logout='$dynamic_logout', open_type='$open_type' WHERE id='$redirect_id'" );
$database->query();
}else{
//insert
$database->setQuery( "INSERT INTO #__redirectonlogin_users SET user_id='$user_id', frontend_type='$frontend_type', frontend_url='$frontend_url', frontend_type_logout='$frontend_type_logout', frontend_url_logout='$frontend_url_logout', backend_type='$backend_type', backend_url='$backend_url', backend_component='$backend_component', opening_site='$opening_site', opening_site_url='$opening_site_url', opening_site_home='$opening_site_home', menuitem_login='$menuitem_login', menuitem_open='$menuitem_open', menuitem_logout='$menuitem_logout', dynamic_login='$dynamic_login', dynamic_open='$dynamic_open', dynamic_logout='$dynamic_logout', open_type='$open_type' ");
$database->query();
}
//redirect
$url = 'index.php?option=com_redirectonlogin&view=users';
if(JRequest::getVar('apply', 0)){
$url = 'index.php?option=com_redirectonlogin&view=user&user_id='.$user_id;
}
$app = JFactory::getApplication();
$app->redirect($url, JText::_('COM_REDIRECTONLOGIN_REDIRECT_SAVED'));
}
function enable_plugin_user(){
$database = JFactory::getDBO();
$database->setQuery( "UPDATE #__extensions SET enabled='1' WHERE element='redirectonlogin' AND folder='user' AND type='plugin' " );
$database->query();
$app = JFactory::getApplication();
$url = 'index.php?option=com_redirectonlogin&view=configuration';
$message = JText::_('COM_REDIRECTONLOGIN_PLUGIN_ENABLED');
if(!file_exists(dirname(__FILE__).'/../../../plugins/user/redirectonlogin/redirectonlogin.php')){
$message = JText::_('COM_REDIRECTONLOGIN_NOT_INSTALLED').' '.JText::_('COM_REDIRECTONLOGIN_NOT_PUBLISHED');
}
$app->redirect($url, $message);
}
function enable_plugin_system(){
$database = JFactory::getDBO();
$database->setQuery( "UPDATE #__extensions SET enabled='1' WHERE element='redirectonlogin' AND folder='system' AND type='plugin' " );
$database->query();
$app = JFactory::getApplication();
$url = 'index.php?option=com_redirectonlogin&view=configuration';
$message = JText::_('COM_REDIRECTONLOGIN_PLUGIN_ENABLED');
if(!file_exists(dirname(__FILE__).'/../../../plugins/system/redirectonlogin/redirectonlogin.php')){
$message = JText::_('COM_REDIRECTONLOGIN_NOT_INSTALLED').' '.JText::_('COM_REDIRECTONLOGIN_NOT_PUBLISHED');
}
$app->redirect($url, $message);
}
function get_usergroups($user_id){
$database = JFactory::getDBO();
$database->setQuery("SELECT m.group_id "
."FROM #__user_usergroup_map AS m "
."WHERE m.user_id='$user_id' "
);
$rows = $database->loadObjectList();
$group_ids = array();
foreach($rows as $row){
$group_ids[] = $row->group_id;
}
return $group_ids;
}
function get_first_usergroup($user_id, $front_back){
$database = JFactory::getDBO();
$database->setQuery("SELECT m.group_id "
."FROM #__user_usergroup_map AS m "
."LEFT JOIN #__redirectonlogin_order_groups AS o "
."ON o.group_id=m.group_id "
."WHERE m.user_id='$user_id' "
."ORDER BY o.redirect_order_".$front_back." ASC "
."LIMIT 1"
);
$usergroup = $database->loadResult();
return $usergroup;
}
function display_footer(){
echo '<div class="smallgrey" id="rol_footer">';
echo '<table>';
echo '<tr>';
echo '<td class="text_right">';
echo '<a href="http://www.pages-and-items.com" target="_blank">Redirect-On-Login</a>';
echo '</td>';
echo '<td class="five_pix">';
echo '©';
echo '</td>';
echo '<td>';
echo '2010 - 2012 Carsten Engel';
echo '</td>';
echo '</tr>';
echo '<tr>';
echo '<td class="text_right">';
echo $this->rol_strtolower(JText::_('JVERSION'));
echo '</td>';
echo '<td class="five_pix">';
echo '=';
echo '</td>';
echo '<td>';
echo $this->rol_version.' ('.$this->rol_version_type.' '.$this->rol_strtolower(JText::_('JVERSION')).')';
if($this->rol_version_type!='trial'){
echo ' <a href="http://www.gnu.org/licenses/gpl-2.0.html" target="blank">GNU/GPL License</a>';
}
echo '</td>';
echo '</tr>';
//version checker
if($this->rol_config['version_checker']){
echo '<tr>';
echo '<td class="text_right">';
echo JText::_('COM_REDIRECTONLOGIN_LATEST_VERSION');
echo '</td>';
echo '<td class="five_pix">';
echo '=';
echo '</td>';
echo '<td>';
$app = JFactory::getApplication();
$latest_version_message = $app->getUserState( "com_redirectonlogin.latest_version_message", '');
if($latest_version_message==''){
$latest_version_message = JText::_('COM_REDIRECTONLOGIN_VERSION_CHECKER_NOT_AVAILABLE');
$url = 'http://www.pages-and-items.com/latest_version.php?extension=redirectonlogin';
$file_object = @fopen($url, "r");
if($file_object == TRUE){
$version = fread($file_object, 1000);
$latest_version_message = $version;
if($this->rol_version!=$version){
$latest_version_message .= ' <span style="color: red;">'.JText::_('COM_REDIRECTONLOGIN_NEWER_VERSION').'</span>';
if($this->rol_version_type=='pro'){
$download_url = 'http://www.pages-and-items.com/my-extensions';
}else{
$download_url = 'http://www.pages-and-items.com/extensions/redirect-on-login';
}
$latest_version_message .= ' <a href="'.$download_url.'" target="_blank">'.JText::_('COM_REDIRECTONLOGIN_DOWNLOAD').'</a>';
}else{
$latest_version_message .= ' <span style="color: #5F9E30;">'.JText::_('COM_REDIRECTONLOGIN_IS_LATEST_VERSION').'</span>';
}
fclose($file_object);
}
$app->setUserState( "com_redirectonlogin.latest_version_message", $latest_version_message );
}
echo $latest_version_message;
echo '</td>';
echo '</tr>';
}
echo '<tr>';
echo '<td class="text_right" colspan="2">';
echo $this->rol_strtolower(JText::_('COM_REDIRECTONLOGIN_REVIEW_B'));
echo '</td>';
echo '<td>';
if($this->rol_version_type=='pro'){
$url_jed = '22806';
}else{
$url_jed = '15257';
}
echo '<a href="http://extensions.joomla.org/extensions/access-a-security/site-access/login-redirect/'.$url_jed.'" target="_blank">';
echo 'Joomla! Extensions Directory</a>';
echo '</td>';
echo '</tr>';
echo '</table>';
echo '</div>';
}
function display_trial_version_stuff(){
if($this->rol_version_type=='trial'){
echo '<div style="text-align: center;">';
echo '<div style="color: red;">';
echo JText::_('COM_REDIRECTONLOGIN_DEMO_DAYS_LEFT');
echo ': ';
if(round((($this->rol_demo_seconds_left/60)/60)/24)<=0){
echo '0';
}else{
echo round((($this->rol_demo_seconds_left/60)/60)/24);
}
echo '</div>';
echo JText::_('COM_REDIRECTONLOGIN_DEMO_DAYS_LEFT_TIP');
echo '<br /><a href="http://www.pages-and-items.com/index.php?page=shop.browse&category_id=6&option=com_virtuemart&Itemid=71&vmcchk=1&Itemid=71" target="_blank">';
echo ucfirst(JText::_('COM_REDIRECTONLOGIN_BUY_THE_PRO'));
echo '</a>';
echo '</div>';
}
}
function trial_expired(){
echo '<div style="text-align: left; width: 350px; margin: 100px auto;">';
echo '<h2>trialversion has expired.</h2>';
echo JText::_('COM_REDIRECTONLOGIN_DEMO_DAYS_LEFT_TIP');
echo '<br /><br /><a href="http://www.pages-and-items.com/" target="_blank">purchase Redirect-On-Login</a>.';
echo '</div>';
}
function get_components_array(){
//get components from menu items
$this->db->setQuery("SELECT path, link as adminlink "
."FROM #__menu "
."WHERE menutype='_adminmenu' AND type='component' "
);
$components_menuitems = $this->db->loadObjectList();
$components_array = array();
$links_array = array();
foreach ($components_menuitems as $components_menuitem){
$name = strtolower($components_menuitem->path);
$link = $components_menuitem->adminlink;
if(!in_array($link, $links_array)){
//prevent double links
$links_array[] = $link;
$components_array[] = array($name, $link);
}
}
//get installed extensions
$this->db->setQuery("SELECT name, element "
."FROM #__extensions "
."WHERE enabled='1' AND type='component' AND element<>'com_admin' AND element<>'com_login' "
);
$components_extensions = $this->db->loadObjectList();
foreach ($components_extensions as $components_extension){
$name = $components_extension->name;
$link = 'index.php?option='.$components_extension->element;
if(substr($name, 0, 4)=='com_'){
$name = substr($name, 4);
}
if(!in_array($link, $links_array)){
//prevent double links
$links_array[] = $link;
$components_array[] = array($name, $link);
}
}
//reorder on name
foreach ($components_array as $key => $row) {
$order[$key] = $row[0];
}
$sort_order = SORT_ASC;//workaround for ioncube
array_multisort($order, $sort_order, $components_array);
return $components_array;
}
function ajax_version_checker(){
$message = JText::_('COM_REDIRECTONLOGIN_VERSION_CHECKER_NOT_AVAILABLE');
$url = 'http://www.pages-and-items.com/latest_version.php?extension=redirectonlogin';
$file_object = @fopen($url, "r");
if($file_object == TRUE){
$version = fread($file_object, 1000);
$message = JText::_('COM_REDIRECTONLOGIN_LATEST_VERSION').' = '.$version;
if($this->rol_version!=$version){
$message .= '<div><span style="color: red;">'.JText::_('COM_REDIRECTONLOGIN_NEWER_VERSION').'</span>.</div>';
if($this->rol_version_type=='pro'){
$download_url = 'http://www.pages-and-items.com/my-extensions';
}else{
$download_url = 'http://www.pages-and-items.com/extensions/redirect-on-login';
}
$message .= '<div><a href="'.$download_url.'" target="_blank">'.JText::_('COM_REDIRECTONLOGIN_DOWNLOAD').'</a></div>';
}else{
$message .= '<div><span style="color: #5F9E30;">'.JText::_('COM_REDIRECTONLOGIN_IS_LATEST_VERSION').'</span>.</div>';
}
fclose($file_object);
}
echo $message;
exit;
}
function rol_strtolower($string){
if(function_exists('mb_strtolower')){
$string = mb_strtolower($string, 'UTF-8');
}
return $string;
}
function not_enabled_message(){
if($this->rol_config['enable_redirection']=='no'){
echo '<p style="color: red;">'.JText::_('COM_REDIRECTONLOGIN_IS_NOT_ENABLED').'. '.JText::_('COM_REDIRECTONLOGIN_ENABLE_THIS_IN').' <a href="index.php?option=com_redirectonlogin&view=configuration">'.$this->rol_strtolower(JText::_('COM_REDIRECTONLOGIN_CONFIGURATION')).'</a>.</p>';
}
}
function dynamicredirect_save(){
$database = JFactory::getDBO();
// Check for request forgeries
JRequest::checkToken() or jexit('Invalid Token');
$redirect_id = intval(JRequest::getVar('redirect_id', ''));
$redirect_name = addslashes(JRequest::getVar('redirect_name', ''));
$value = JRequest::getVar('redirect_code','','post','string', JREQUEST_ALLOWRAW);
$value = str_replace('=','[equal]',$value);
$new_line = '
';
$value = str_replace($new_line,'[newline]',$value);
$value = addslashes($value);
$redirect_type = JRequest::getVar('redirect_type', '');
if($redirect_id){
//update
$database->setQuery( "UPDATE #__redirectonlogin_dynamics SET name='$redirect_name', value='$value', type='$redirect_type' WHERE id='$redirect_id'" );
$database->query();
}else{
//insert
$database->setQuery( "INSERT INTO #__redirectonlogin_dynamics SET name='$redirect_name', value='$value', type='$redirect_type' ");
$database->query();
//get new id
$redirect_id = $database->insertid();
}
//redirect
$url = 'index.php?option=com_redirectonlogin&view=dynamicredirects';
if(JRequest::getVar('apply', 0)){
$url = 'index.php?option=com_redirectonlogin&view=dynamicredirect&id='.$redirect_id;
}
$this->setRedirect($url, JText::_('COM_REDIRECTONLOGIN_REDIRECT_SAVED'));
}
function save_order_dynamic_redirects(){
$database = JFactory::getDBO();
$dynamic_redirect_order = JRequest::getVar('order', array(), 'post', 'array');
$dynamic_redirect_id = JRequest::getVar('dynamic_redirect_id', array(), 'post', 'array');
$order_ids = JRequest::getVar('order_id', array(), 'post', 'array');
for($n = 0; $n < count($dynamic_redirect_id); $n++){
$redirect_order = $dynamic_redirect_order[$n];
$redirect_id = $dynamic_redirect_id[$n];
$order_id = $order_ids[$n];
//update order
$database->setQuery( "UPDATE #__redirectonlogin_dynamics SET ordering='$redirect_order' WHERE id='$redirect_id' ");
$database->query();
}
$url = 'index.php?option=com_redirectonlogin&view=dynamicredirects';
$this->setRedirect($url, JText::_('COM_REDIRECTONLOGIN_ORDER_SAVED'));
}
function dynamicredirect_delete(){
$database = JFactory::getDBO();
// Check for request forgeries
JRequest::checkToken() or jexit('Invalid Token');
$cid = JRequest::getVar('cid', null, 'post', 'array');
if (!is_array($cid) || count($cid) < 1) {
echo JText::_('COM_REDIRECTONLOGIN_NO_DYNAMIC_REDIRECTS_SELECTED');
exit();
}
if (count($cid)){
$ids = implode(',', $cid);
//delete dynamic redirects
$database->setQuery("DELETE FROM #__redirectonlogin_dynamics WHERE id IN ($ids)");
$database->query();
}
$this->setRedirect("index.php?option=com_redirectonlogin&view=dynamicredirects", JText::_('COM_REDIRECTONLOGIN_REDIRECTS_DELETED'));
}
function get_version_type(){
//so that private var is available for templates
return $this->rol_version_type;
}
function get_helper(){
$ds = DIRECTORY_SEPARATOR;
require_once(JPATH_ROOT.$ds.'administrator'.$ds.'components'.$ds.'com_redirectonlogin'.$ds.'helpers'.$ds.'redirectonlogin.php');
$helper = new redirectonloginHelper();
return $helper;
}
function add_submenu($vName = 'redirectonlogin'){
$vName = JFactory::getApplication()->input->get('view');
JHtmlSidebar::addEntry(
JText::_('COM_REDIRECTONLOGIN_CONFIGURATION'),
'index.php?option=com_redirectonlogin&view=configuration',
$vName == 'configuration'
);
JHtmlSidebar::addEntry(
JText::_('COM_REDIRECTONLOGIN_USERGROUPS'),
'index.php?option=com_redirectonlogin&view=usergroups',
$vName == 'usergroups' || $vName == 'usergroup'
);
JHtmlSidebar::addEntry(
JText::_('COM_REDIRECTONLOGIN_ACCESSLEVELS'),
'index.php?option=com_redirectonlogin&view=accesslevels',
$vName == 'accesslevels' || $vName == 'accesslevel'
);
JHtmlSidebar::addEntry(
JText::_('COM_REDIRECTONLOGIN_USERS'),
'index.php?option=com_redirectonlogin&view=users',
$vName == 'users' || $vName == 'user'
);
JHtmlSidebar::addEntry(
JText::_('COM_REDIRECTONLOGIN_DYNAMIC_REDIRECTS'),
'index.php?option=com_redirectonlogin&view=dynamicredirects',
$vName == 'dynamicredirects' || $vName == 'dynamicredirect'
);
JHtmlSidebar::addEntry(
JText::_('COM_REDIRECTONLOGIN_SUPPORT'),
'index.php?option=com_redirectonlogin&view=support',
$vName == 'support'
);
}
}
?> | tannpv/pepmobile | administrator/components/com_redirectonlogin/controller.php | PHP | gpl-2.0 | 33,665 |
/*
* Swiper 2.2 - Mobile Touch Slider
* http://www.idangero.us/sliders/swiper/
*
* Copyright 2012-2013, Vladimir Kharlampidi
* The iDangero.us
* http://www.idangero.us/
*
* Licensed under GPL & MIT
*
* Updated on: September 15, 2013
*/
var Swiper = function (selector, params) {
/*=========================
A little bit dirty but required part for IE8 and old FF support
===========================*/
if (document.body.__defineGetter__) {
if (HTMLElement) {
var element = HTMLElement.prototype;
if (element.__defineGetter__) {
element.__defineGetter__("outerHTML", function () { return new XMLSerializer().serializeToString(this); } );
}
}
}
if (!window.getComputedStyle) {
window.getComputedStyle = function (el, pseudo) {
this.el = el;
this.getPropertyValue = function (prop) {
var re = /(\-([a-z]){1})/g;
if (prop === 'float') prop = 'styleFloat';
if (re.test(prop)) {
prop = prop.replace(re, function () {
return arguments[2].toUpperCase();
});
}
return el.currentStyle[prop] ? el.currentStyle[prop] : null;
}
return this;
}
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
}
if (!document.querySelectorAll) {
if (!window.jQuery) return;
}
function $$(selector, context) {
if (document.querySelectorAll)
return (context || document).querySelectorAll(selector);
else
return jQuery(selector, context);
}
/*=========================
Check for correct selector
===========================*/
if(typeof selector === 'undefined') return;
if(!(selector.nodeType)){
if ($$(selector).length === 0) return;
}
/*=========================
_this
===========================*/
var _this = this;
/*=========================
Default Flags and vars
===========================*/
_this.touches = {
start:0,
startX:0,
startY:0,
current:0,
currentX:0,
currentY:0,
diff:0,
abs:0
};
_this.positions = {
start:0,
abs:0,
diff:0,
current:0
};
_this.times = {
start:0,
end:0
};
_this.id = (new Date()).getTime();
_this.container = (selector.nodeType) ? selector : $$(selector)[0];
_this.isTouched = false;
_this.isMoved = false;
_this.activeIndex = 0;
_this.activeLoaderIndex = 0;
_this.activeLoopIndex = 0;
_this.previousIndex = null;
_this.velocity = 0;
_this.snapGrid = [];
_this.slidesGrid = [];
_this.imagesToLoad = [];
_this.imagesLoaded = 0;
_this.wrapperLeft=0;
_this.wrapperRight=0;
_this.wrapperTop=0;
_this.wrapperBottom=0;
var wrapper, slideSize, wrapperSize, direction, isScrolling, containerSize;
/*=========================
Default Parameters
===========================*/
var defaults = {
mode : 'horizontal', // or 'vertical'
touchRatio : 1,
speed : 300,
freeMode : false,
freeModeFluid : false,
momentumRatio: 1,
momentumBounce: true,
momentumBounceRatio: 1,
slidesPerView : 1,
slidesPerGroup : 1,
simulateTouch : true,
followFinger : true,
shortSwipes : true,
moveStartThreshold:false,
autoplay: false,
onlyExternal : false,
createPagination : true,
pagination : false,
paginationElement: 'span',
paginationClickable: false,
paginationAsRange: true,
resistance : true, // or false or 100%
scrollContainer : false,
preventLinks : true,
noSwiping : false, // or class
noSwipingClass : 'swiper-no-swiping', //:)
initialSlide: 0,
keyboardControl: false,
mousewheelControl : false,
mousewheelDebounce: 600,
useCSS3Transforms : true,
//Loop mode
loop:false,
loopAdditionalSlides:0,
//Auto Height
calculateHeight: false,
//Images Preloader
updateOnImagesReady : true,
//Form elements
releaseFormElements : true,
//Watch for active slide, useful when use effects on different slide states
watchActiveIndex: false,
//Slides Visibility Fit
visibilityFullFit : false,
//Slides Offset
offsetPxBefore : 0,
offsetPxAfter : 0,
offsetSlidesBefore : 0,
offsetSlidesAfter : 0,
centeredSlides: false,
//Queue callbacks
queueStartCallbacks : false,
queueEndCallbacks : false,
//Auto Resize
autoResize : true,
resizeReInit : false,
//DOMAnimation
DOMAnimation : true,
//Slides Loader
loader: {
slides:[], //array with slides
slidesHTMLType:'inner', // or 'outer'
surroundGroups: 1, //keep preloaded slides groups around view
logic: 'reload', //or 'change'
loadAllSlides: false
},
//Namespace
slideElement : 'div',
slideClass : 'swiper-slide',
slideActiveClass : 'swiper-slide-active',
slideVisibleClass : 'swiper-slide-visible',
wrapperClass : 'swiper-wrapper',
paginationElementClass: 'swiper-pagination-switch',
paginationActiveClass : 'swiper-active-switch',
paginationVisibleClass : 'swiper-visible-switch'
}
params = params || {};
for (var prop in defaults) {
if (prop in params && typeof params[prop]==='object') {
for (var subProp in defaults[prop]) {
if (! (subProp in params[prop])) {
params[prop][subProp] = defaults[prop][subProp];
}
}
}
else if (! (prop in params)) {
params[prop] = defaults[prop]
}
}
_this.params = params;
if (params.scrollContainer) {
params.freeMode = true;
params.freeModeFluid = true;
}
if (params.loop) {
params.resistance = '100%';
}
var isH = params.mode==='horizontal';
/*=========================
Define Touch Events
===========================*/
_this.touchEvents = {
touchStart : _this.support.touch || !params.simulateTouch ? 'touchstart' : (_this.browser.ie10 ? 'MSPointerDown' : 'mousedown'),
touchMove : _this.support.touch || !params.simulateTouch ? 'touchmove' : (_this.browser.ie10 ? 'MSPointerMove' : 'mousemove'),
touchEnd : _this.support.touch || !params.simulateTouch ? 'touchend' : (_this.browser.ie10 ? 'MSPointerUp' : 'mouseup')
};
/*=========================
Wrapper
===========================*/
for (var i = _this.container.childNodes.length - 1; i >= 0; i--) {
if (_this.container.childNodes[i].className) {
var _wrapperClasses = _this.container.childNodes[i].className.split(' ')
for (var j = 0; j < _wrapperClasses.length; j++) {
if (_wrapperClasses[j]===params.wrapperClass) {
wrapper = _this.container.childNodes[i];
}
};
}
};
_this.wrapper = wrapper;
/*=========================
Slide API
===========================*/
_this._extendSwiperSlide = function (el) {
el.append = function () {
if (params.loop) {
el.insertAfter(_this.slides.length-_this.loopedSlides);
_this.removeLoopedSlides();
_this.calcSlides();
_this.createLoop();
}
else {
_this.wrapper.appendChild(el);
}
_this.reInit();
return el;
}
el.prepend = function () {
if (params.loop) {
_this.wrapper.insertBefore(el, _this.slides[_this.loopedSlides]);
_this.removeLoopedSlides();
_this.calcSlides();
_this.createLoop();
}
else {
_this.wrapper.insertBefore(el, _this.wrapper.firstChild);
}
_this.reInit();
return el;
}
el.insertAfter = function (index) {
if(typeof index === 'undefined') return false;
var beforeSlide;
if (params.loop) {
beforeSlide = _this.slides[index + 1 + _this.loopedSlides];
_this.wrapper.insertBefore(el, beforeSlide);
_this.removeLoopedSlides();
_this.calcSlides();
_this.createLoop();
}
else {
beforeSlide = _this.slides[index + 1];
_this.wrapper.insertBefore(el, beforeSlide)
}
_this.reInit();
return el;
}
el.clone = function () {
return _this._extendSwiperSlide(el.cloneNode(true))
}
el.remove = function () {
_this.wrapper.removeChild(el);
_this.reInit();
}
el.html = function (html) {
if (typeof html === 'undefined') {
return el.innerHTML;
}
else {
el.innerHTML = html;
return el;
}
}
el.index = function () {
var index;
for (var i = _this.slides.length - 1; i >= 0; i--) {
if(el === _this.slides[i]) index = i;
}
return index;
}
el.isActive = function () {
if (el.index() === _this.activeIndex) return true;
else return false;
}
if (!el.swiperSlideDataStorage) el.swiperSlideDataStorage={};
el.getData = function (name) {
return el.swiperSlideDataStorage[name];
}
el.setData = function (name, value) {
el.swiperSlideDataStorage[name] = value;
return el;
}
el.data = function (name, value) {
if (!value) {
return el.getAttribute('data-'+name);
}
else {
el.setAttribute('data-'+name,value);
return el;
}
}
el.getWidth = function (outer) {
return _this.h.getWidth(el, outer);
}
el.getHeight = function (outer) {
return _this.h.getHeight(el, outer);
}
el.getOffset = function() {
return _this.h.getOffset(el);
}
return el;
}
//Calculate information about number of slides
_this.calcSlides = function (forceCalcSlides) {
var oldNumber = _this.slides ? _this.slides.length : false;
_this.slides = [];
_this.displaySlides = [];
for (var i = 0; i < _this.wrapper.childNodes.length; i++) {
if (_this.wrapper.childNodes[i].className) {
var _className = _this.wrapper.childNodes[i].className;
var _slideClasses = _className.split(' ');
for (var j = 0; j < _slideClasses.length; j++) {
if(_slideClasses[j]===params.slideClass) {
_this.slides.push(_this.wrapper.childNodes[i]);
}
}
}
}
for (i = _this.slides.length - 1; i >= 0; i--) {
_this._extendSwiperSlide(_this.slides[i]);
}
if (!oldNumber) return;
if(oldNumber!==_this.slides.length || forceCalcSlides) {
// Number of slides has been changed
removeSlideEvents();
addSlideEvents();
_this.updateActiveSlide();
if (params.createPagination && _this.params.pagination) _this.createPagination();
_this.callPlugins('numberOfSlidesChanged');
}
}
//Create Slide
_this.createSlide = function (html, slideClassList, el) {
var slideClassList = slideClassList || _this.params.slideClass;
var el = el||params.slideElement;
var newSlide = document.createElement(el);
newSlide.innerHTML = html||'';
newSlide.className = slideClassList;
return _this._extendSwiperSlide(newSlide);
}
//Append Slide
_this.appendSlide = function (html, slideClassList, el) {
if (!html) return;
if (html.nodeType) {
return _this._extendSwiperSlide(html).append()
}
else {
return _this.createSlide(html, slideClassList, el).append()
}
}
_this.prependSlide = function (html, slideClassList, el) {
if (!html) return;
if (html.nodeType) {
return _this._extendSwiperSlide(html).prepend()
}
else {
return _this.createSlide(html, slideClassList, el).prepend()
}
}
_this.insertSlideAfter = function (index, html, slideClassList, el) {
if (typeof index === 'undefined') return false;
if (html.nodeType) {
return _this._extendSwiperSlide(html).insertAfter(index);
}
else {
return _this.createSlide(html, slideClassList, el).insertAfter(index);
}
}
_this.removeSlide = function (index) {
if (_this.slides[index]) {
if (params.loop) {
if (!_this.slides[index+_this.loopedSlides]) return false;
_this.slides[index+_this.loopedSlides].remove();
_this.removeLoopedSlides();
_this.calcSlides();
_this.createLoop();
}
else _this.slides[index].remove();
return true;
}
else return false;
}
_this.removeLastSlide = function () {
if (_this.slides.length>0) {
if (params.loop) {
_this.slides[_this.slides.length - 1 - _this.loopedSlides].remove();
_this.removeLoopedSlides();
_this.calcSlides();
_this.createLoop();
}
else _this.slides[ (_this.slides.length-1) ].remove();
return true;
}
else {
return false;
}
}
_this.removeAllSlides = function () {
for (var i = _this.slides.length - 1; i >= 0; i--) {
_this.slides[i].remove()
}
}
_this.getSlide = function (index) {
return _this.slides[index]
}
_this.getLastSlide = function () {
return _this.slides[ _this.slides.length-1 ]
}
_this.getFirstSlide = function () {
return _this.slides[0]
}
//Currently Active Slide
_this.activeSlide = function () {
return _this.slides[_this.activeIndex]
}
/*=========================
Plugins API
===========================*/
var _plugins = [];
for (var plugin in _this.plugins) {
if (params[plugin]) {
var p = _this.plugins[plugin](_this, params[plugin]);
if (p) _plugins.push( p );
}
}
_this.callPlugins = function(method, args) {
if (!args) args = {}
for (var i=0; i<_plugins.length; i++) {
if (method in _plugins[i]) {
_plugins[i][method](args);
}
}
}
/*=========================
WP8 Fix
===========================*/
if (_this.browser.ie10 && !params.onlyExternal) {
_this.wrapper.classList.add('swiper-wp8-' + (isH ? 'horizontal' : 'vertical'));
}
/*=========================
Free Mode Class
===========================*/
if (params.freeMode) {
_this.container.className+=' swiper-free-mode';
}
/*==================================================
Init/Re-init/Resize Fix
====================================================*/
_this.initialized = false;
_this.init = function(force, forceCalcSlides) {
var _width = _this.h.getWidth(_this.container);
var _height = _this.h.getHeight(_this.container);
if (_width===_this.width && _height===_this.height && !force) return;
_this.width = _width;
_this.height = _height;
containerSize = isH ? _width : _height;
var wrapper = _this.wrapper;
if (force) {
_this.calcSlides(forceCalcSlides);
}
if (params.slidesPerView==='auto') {
//Auto mode
var slidesWidth = 0;
var slidesHeight = 0;
//Unset Styles
if (params.slidesOffset>0) {
wrapper.style.paddingLeft = '';
wrapper.style.paddingRight = '';
wrapper.style.paddingTop = '';
wrapper.style.paddingBottom = '';
}
wrapper.style.width = '';
wrapper.style.height = '';
if (params.offsetPxBefore>0) {
if (isH) _this.wrapperLeft = params.offsetPxBefore;
else _this.wrapperTop = params.offsetPxBefore;
}
if (params.offsetPxAfter>0) {
if (isH) _this.wrapperRight = params.offsetPxAfter;
else _this.wrapperBottom = params.offsetPxAfter;
}
if (params.centeredSlides) {
if (isH) {
_this.wrapperLeft = (containerSize - this.slides[0].getWidth(true) )/2;
_this.wrapperRight = (containerSize - _this.slides[ _this.slides.length-1 ].getWidth(true))/2;
}
else {
_this.wrapperTop = (containerSize - _this.slides[0].getHeight(true))/2;
_this.wrapperBottom = (containerSize - _this.slides[ _this.slides.length-1 ].getHeight(true))/2;
}
}
if (isH) {
if (_this.wrapperLeft>=0) wrapper.style.paddingLeft = _this.wrapperLeft+'px';
if (_this.wrapperRight>=0) wrapper.style.paddingRight = _this.wrapperRight+'px';
}
else {
if (_this.wrapperTop>=0) wrapper.style.paddingTop = _this.wrapperTop+'px';
if (_this.wrapperBottom>=0) wrapper.style.paddingBottom = _this.wrapperBottom+'px';
}
var slideLeft = 0;
var centeredSlideLeft=0;
_this.snapGrid = [];
_this.slidesGrid = [];
var slideMaxHeight = 0;
for(var i = 0; i<_this.slides.length; i++) {
var slideWidth = _this.slides[i].getWidth(true);
var slideHeight = _this.slides[i].getHeight(true);
if (params.calculateHeight) {
slideMaxHeight = Math.max(slideMaxHeight, slideHeight)
}
var _slideSize = isH ? slideWidth : slideHeight;
if (params.centeredSlides) {
var nextSlideWidth = i === _this.slides.length-1 ? 0 : _this.slides[i+1].getWidth(true);
var nextSlideHeight = i === _this.slides.length-1 ? 0 : _this.slides[i+1].getHeight(true);
var nextSlideSize = isH ? nextSlideWidth : nextSlideHeight;
if (_slideSize>containerSize) {
for (var j=0; j<=Math.floor(_slideSize/(containerSize+_this.wrapperLeft)); j++) {
if (j === 0) _this.snapGrid.push(slideLeft+_this.wrapperLeft);
else _this.snapGrid.push(slideLeft+_this.wrapperLeft+containerSize*j);
}
_this.slidesGrid.push(slideLeft+_this.wrapperLeft);
}
else {
_this.snapGrid.push(centeredSlideLeft);
_this.slidesGrid.push(centeredSlideLeft);
}
centeredSlideLeft += _slideSize/2 + nextSlideSize/2;
}
else {
if (_slideSize>containerSize) {
for (var j=0; j<=Math.floor(_slideSize/containerSize); j++) {
_this.snapGrid.push(slideLeft+containerSize*j);
}
}
else {
_this.snapGrid.push(slideLeft);
}
_this.slidesGrid.push(slideLeft);
}
slideLeft += _slideSize;
slidesWidth += slideWidth;
slidesHeight += slideHeight;
}
if (params.calculateHeight) _this.height = slideMaxHeight;
if(isH) {
wrapperSize = slidesWidth + _this.wrapperRight + _this.wrapperLeft;
wrapper.style.width = (slidesWidth)+'px';
wrapper.style.height = (_this.height)+'px';
}
else {
wrapperSize = slidesHeight + _this.wrapperTop + _this.wrapperBottom;
wrapper.style.width = (_this.width)+'px';
wrapper.style.height = (slidesHeight)+'px';
}
}
else if (params.scrollContainer) {
//Scroll Container
wrapper.style.width = '';
wrapper.style.height = '';
var wrapperWidth = _this.slides[0].getWidth(true);
var wrapperHeight = _this.slides[0].getHeight(true);
wrapperSize = isH ? wrapperWidth : wrapperHeight;
wrapper.style.width = wrapperWidth+'px';
wrapper.style.height = wrapperHeight+'px';
slideSize = isH ? wrapperWidth : wrapperHeight;
}
else {
//For usual slides
if (params.calculateHeight) {
var slideMaxHeight = 0;
var wrapperHeight = 0;
//ResetWrapperSize
if (!isH) _this.container.style.height= '';
wrapper.style.height='';
for (var i=0; i<_this.slides.length; i++) {
//ResetSlideSize
_this.slides[i].style.height='';
slideMaxHeight = Math.max( _this.slides[i].getHeight(true), slideMaxHeight );
if (!isH) wrapperHeight+=_this.slides[i].getHeight(true);
}
var slideHeight = slideMaxHeight;
_this.height = slideHeight;
if (isH) wrapperHeight = slideHeight;
else containerSize = slideHeight, _this.container.style.height= containerSize+'px';
}
else {
var slideHeight = isH ? _this.height : _this.height/params.slidesPerView;
var wrapperHeight = isH ? _this.height : _this.slides.length*slideHeight;
}
var slideWidth = isH ? _this.width/params.slidesPerView : _this.width;
var wrapperWidth = isH ? _this.slides.length*slideWidth : _this.width;
slideSize = isH ? slideWidth : slideHeight;
if (params.offsetSlidesBefore>0) {
if (isH) _this.wrapperLeft = slideSize*params.offsetSlidesBefore;
else _this.wrapperTop = slideSize*params.offsetSlidesBefore;
}
if (params.offsetSlidesAfter>0) {
if (isH) _this.wrapperRight = slideSize*params.offsetSlidesAfter;
else _this.wrapperBottom = slideSize*params.offsetSlidesAfter;
}
if (params.offsetPxBefore>0) {
if (isH) _this.wrapperLeft = params.offsetPxBefore;
else _this.wrapperTop = params.offsetPxBefore;
}
if (params.offsetPxAfter>0) {
if (isH) _this.wrapperRight = params.offsetPxAfter;
else _this.wrapperBottom = params.offsetPxAfter;
}
if (params.centeredSlides) {
if (isH) {
_this.wrapperLeft = (containerSize - slideSize)/2;
_this.wrapperRight = (containerSize - slideSize)/2;
}
else {
_this.wrapperTop = (containerSize - slideSize)/2;
_this.wrapperBottom = (containerSize - slideSize)/2;
}
}
if (isH) {
if (_this.wrapperLeft>0) wrapper.style.paddingLeft = _this.wrapperLeft+'px';
if (_this.wrapperRight>0) wrapper.style.paddingRight = _this.wrapperRight+'px';
}
else {
if (_this.wrapperTop>0) wrapper.style.paddingTop = _this.wrapperTop+'px';
if (_this.wrapperBottom>0) wrapper.style.paddingBottom = _this.wrapperBottom+'px';
}
wrapperSize = isH ? wrapperWidth + _this.wrapperRight + _this.wrapperLeft : wrapperHeight + _this.wrapperTop + _this.wrapperBottom;
wrapper.style.width = wrapperWidth+'px';
wrapper.style.height = wrapperHeight+'px';
var slideLeft = 0;
_this.snapGrid = [];
_this.slidesGrid = [];
for (var i=0; i<_this.slides.length; i++) {
_this.snapGrid.push(slideLeft);
_this.slidesGrid.push(slideLeft);
slideLeft+=slideSize;
_this.slides[i].style.width = slideWidth+'px';
_this.slides[i].style.height = slideHeight+'px';
}
}
if (!_this.initialized) {
_this.callPlugins('onFirstInit');
if (params.onFirstInit) params.onFirstInit(_this);
}
else {
_this.callPlugins('onInit');
if (params.onInit) params.onInit(_this);
}
_this.initialized = true;
}
_this.reInit = function (forceCalcSlides) {
_this.init(true, forceCalcSlides);
}
_this.resizeFix = function (reInit) {
_this.callPlugins('beforeResizeFix');
_this.init(params.resizeReInit || reInit);
// swipe to active slide in fixed mode
if (!params.freeMode) {
_this.swipeTo((params.loop ? _this.activeLoopIndex : _this.activeIndex), 0, false);
}
// move wrapper to the beginning in free mode
else if (_this.getWrapperTranslate() < -maxWrapperPosition()) {
_this.setWrapperTransition(0);
_this.setWrapperTranslate(-maxWrapperPosition());
}
_this.callPlugins('afterResizeFix');
}
/*==========================================
Max and Min Positions
============================================*/
function maxWrapperPosition() {
var a = (wrapperSize - containerSize);
if (params.freeMode) {
a = wrapperSize - containerSize;
}
// if (params.loop) a -= containerSize;
if (params.slidesPerView > _this.slides.length) a = 0;
if (a<0) a = 0;
return a;
}
function minWrapperPosition() {
var a = 0;
// if (params.loop) a = containerSize;
return a;
}
/*==========================================
Event Listeners
============================================*/
function initEvents() {
var bind = _this.h.addEventListener;
//Touch Events
if (!_this.browser.ie10) {
if (_this.support.touch) {
bind(_this.wrapper, 'touchstart', onTouchStart);
bind(_this.wrapper, 'touchmove', onTouchMove);
bind(_this.wrapper, 'touchend', onTouchEnd);
}
if (params.simulateTouch) {
bind(_this.wrapper, 'mousedown', onTouchStart);
bind(document, 'mousemove', onTouchMove);
bind(document, 'mouseup', onTouchEnd);
}
}
else {
bind(_this.wrapper, _this.touchEvents.touchStart, onTouchStart);
bind(document, _this.touchEvents.touchMove, onTouchMove);
bind(document, _this.touchEvents.touchEnd, onTouchEnd);
}
//Resize Event
if (params.autoResize) {
bind(window, 'resize', _this.resizeFix);
}
//Slide Events
addSlideEvents();
//Mousewheel
_this._wheelEvent = false;
if (params.mousewheelControl) {
if ( document.onmousewheel !== undefined ) {
_this._wheelEvent = "mousewheel";
}
try {
WheelEvent("wheel");
_this._wheelEvent = "wheel";
} catch (e) {}
if ( !_this._wheelEvent ) {
_this._wheelEvent = "DOMMouseScroll";
}
if (_this._wheelEvent) {
bind(_this.container, _this._wheelEvent, handleMousewheel);
}
}
//Keyboard
if (params.keyboardControl) {
bind(document, 'keydown', handleKeyboardKeys);
}
if (params.updateOnImagesReady) {
_this.imagesToLoad = $$('img', _this.container);
for (var i=0; i<_this.imagesToLoad.length; i++) {
_loadImage(_this.imagesToLoad[i].getAttribute('src'))
}
}
function _loadImage(src) {
var image = new Image();
image.onload = function(){
_this.imagesLoaded++;
if (_this.imagesLoaded==_this.imagesToLoad.length) {
_this.reInit();
if (params.onImagesReady) params.onImagesReady(_this);
}
}
image.src = src;
}
}
//Remove Event Listeners
_this.destroy = function(removeResizeFix){
var unbind = _this.h.removeEventListener;
//Touch Events
if (!_this.browser.ie10) {
if (_this.support.touch) {
unbind(_this.wrapper, 'touchstart', onTouchStart);
unbind(_this.wrapper, 'touchmove', onTouchMove);
unbind(_this.wrapper, 'touchend', onTouchEnd);
}
if (params.simulateTouch) {
unbind(_this.wrapper, 'mousedown', onTouchStart);
unbind(document, 'mousemove', onTouchMove);
unbind(document, 'mouseup', onTouchEnd);
}
}
else {
unbind(_this.wrapper, _this.touchEvents.touchStart, onTouchStart);
unbind(document, _this.touchEvents.touchMove, onTouchMove);
unbind(document, _this.touchEvents.touchEnd, onTouchEnd);
}
//Resize Event
if (params.autoResize) {
unbind(window, 'resize', _this.resizeFix);
}
//Init Slide Events
removeSlideEvents();
//Pagination
if (params.paginationClickable) {
removePaginationEvents();
}
//Mousewheel
if (params.mousewheelControl && _this._wheelEvent) {
unbind(_this.container, _this._wheelEvent, handleMousewheel);
}
//Keyboard
if (params.keyboardControl) {
unbind(document, 'keydown', handleKeyboardKeys);
}
//Stop autoplay
if (params.autoplay) {
_this.stopAutoplay();
}
_this.callPlugins('onDestroy');
//Destroy variable
_this = null;
}
function addSlideEvents() {
var bind = _this.h.addEventListener,
i;
//Prevent Links Events
if (params.preventLinks) {
var links = $$('a', _this.container);
for (i=0; i<links.length; i++) {
bind(links[i], 'click', preventClick);
}
}
//Release Form Elements
if (params.releaseFormElements) {
var formElements = $$('input, textarea, select', _this.container);
for (i=0; i<formElements.length; i++) {
bind(formElements[i], _this.touchEvents.touchStart, releaseForms, true);
}
}
//Slide Clicks & Touches
if (params.onSlideClick) {
for (i=0; i<_this.slides.length; i++) {
bind(_this.slides[i], 'click', slideClick);
}
}
if (params.onSlideTouch) {
for (i=0; i<_this.slides.length; i++) {
bind(_this.slides[i], _this.touchEvents.touchStart, slideTouch);
}
}
}
function removeSlideEvents() {
var unbind = _this.h.removeEventListener,
i;
//Slide Clicks & Touches
if (params.onSlideClick) {
for (i=0; i<_this.slides.length; i++) {
unbind(_this.slides[i], 'click', slideClick);
}
}
if (params.onSlideTouch) {
for (i=0; i<_this.slides.length; i++) {
unbind(_this.slides[i], _this.touchEvents.touchStart, slideTouch);
}
}
//Release Form Elements
if (params.releaseFormElements) {
var formElements = $$('input, textarea, select', _this.container);
for (i=0; i<formElements.length; i++) {
unbind(formElements[i], _this.touchEvents.touchStart, releaseForms, true);
}
}
//Prevent Links Events
if (params.preventLinks) {
var links = $$('a', _this.container);
for (i=0; i<links.length; i++) {
unbind(links[i], 'click', preventClick);
}
}
}
/*==========================================
Keyboard Control
============================================*/
function handleKeyboardKeys (e) {
var kc = e.keyCode || e.charCode;
if (kc==37 || kc==39 || kc==38 || kc==40) {
var inView = false;
//Check that swiper should be inside of visible area of window
var swiperOffset = _this.h.getOffset( _this.container );
var scrollLeft = _this.h.windowScroll().left;
var scrollTop = _this.h.windowScroll().top;
var windowWidth = _this.h.windowWidth();
var windowHeight = _this.h.windowHeight();
var swiperCoord = [
[swiperOffset.left, swiperOffset.top],
[swiperOffset.left + _this.width, swiperOffset.top],
[swiperOffset.left, swiperOffset.top + _this.height],
[swiperOffset.left + _this.width, swiperOffset.top + _this.height]
]
for (var i=0; i<swiperCoord.length; i++) {
var point = swiperCoord[i];
if (
point[0]>=scrollLeft && point[0]<=scrollLeft+windowWidth &&
point[1]>=scrollTop && point[1]<=scrollTop+windowHeight
) {
inView = true;
}
}
if (!inView) return;
}
if (isH) {
if (kc==37 || kc==39) {
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
}
if (kc == 39) _this.swipeNext();
if (kc == 37) _this.swipePrev();
}
else {
if (kc==38 || kc==40) {
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
}
if (kc == 40) _this.swipeNext();
if (kc == 38) _this.swipePrev();
}
}
/*==========================================
Mousewheel Control
============================================*/
var allowScrollChange = true;
function handleMousewheel (e) {
var we = _this._wheelEvent;
var delta;
//Opera & IE
if (e.detail) delta = -e.detail;
//WebKits
else if (we == 'mousewheel') delta = e.wheelDelta;
//Old FireFox
else if (we == 'DOMMouseScroll') delta = -e.detail;
//New FireFox
else if (we == 'wheel') {
delta = Math.abs(e.deltaX)>Math.abs(e.deltaY) ? - e.deltaX : - e.deltaY;
}
if (!params.freeMode) {
if(delta<0) _this.swipeNext();
else _this.swipePrev();
}
else {
//Freemode or scrollContainer:
var position = _this.getWrapperTranslate() + delta;
if (position > 0) position = 0;
if (position < -maxWrapperPosition()) position = -maxWrapperPosition();
_this.setWrapperTransition(0);
_this.setWrapperTranslate(position);
_this.updateActiveSlide(position);
}
if (params.autoplay) _this.stopAutoplay();
if(e.preventDefault) e.preventDefault();
else e.returnValue = false;
return false;
}
/*=========================
Grab Cursor
===========================*/
if (params.grabCursor) {
var containerStyle = _this.container.style;
containerStyle.cursor = 'move';
containerStyle.cursor = 'grab';
containerStyle.cursor = '-moz-grab';
containerStyle.cursor = '-webkit-grab';
}
/*=========================
Slides Events Handlers
===========================*/
_this.allowSlideClick = true;
function slideClick(event) {
if (_this.allowSlideClick) {
setClickedSlide(event);
params.onSlideClick(_this);
}
}
function slideTouch(event) {
setClickedSlide(event);
params.onSlideTouch(_this);
}
function setClickedSlide(event) {
// IE 6-8 support
if (!event.currentTarget) {
var element = event.srcElement;
do {
if (element.className.indexOf(params.slideClass) > -1) {
break;
}
}
while (element = element.parentNode);
_this.clickedSlide = element;
}
else {
_this.clickedSlide = event.currentTarget;
}
_this.clickedSlideIndex = _this.slides.indexOf(_this.clickedSlide);
_this.clickedSlideLoopIndex = _this.clickedSlideIndex - (_this.loopedSlides || 0);
}
_this.allowLinks = true;
function preventClick(e) {
if (!_this.allowLinks) {
if(e.preventDefault) e.preventDefault();
else e.returnValue = false;
return false;
}
}
function releaseForms(e) {
if (e.stopPropagation) e.stopPropagation();
else e.returnValue = false;
return false;
}
/*==================================================
Event Handlers
====================================================*/
var isTouchEvent = false;
var allowThresholdMove;
var allowMomentumBounce = true;
function onTouchStart(event) {
//vc gallery when using lightbox fix
if(jQuery(event.target).parents('.swiper-container').attr('data-desktop-swipe') == 'false' && !Modernizr.touch) return false;
//deactivate touch if only one slide
if(jQuery(event.target).parents('.swiper-container').find('.swiper-slide').length == 1) return false;
//deactivate touch for duplicate transitions
if(jQuery(event.target).parents('.swiper-container').find('.swiper-slide.duplicate-transition').length > 0) return false;
if (params.preventLinks) _this.allowLinks = true;
//Exit if slider is already was touched
if (_this.isTouched || params.onlyExternal) {
return false;
}
if (params.noSwiping && (event.target || event.srcElement) && noSwipingSlide(event.target || event.srcElement)) return false;
allowMomentumBounce = false;
//Check For Nested Swipers
_this.isTouched = true;
isTouchEvent = event.type=='touchstart';
if (!isTouchEvent || event.targetTouches.length == 1 ) {
_this.callPlugins('onTouchStartBegin');
if(!isTouchEvent) {
if(event.preventDefault) event.preventDefault();
else event.returnValue = false;
}
var pageX = isTouchEvent ? event.targetTouches[0].pageX : (event.pageX || event.clientX);
var pageY = isTouchEvent ? event.targetTouches[0].pageY : (event.pageY || event.clientY);
//Start Touches to check the scrolling
_this.touches.startX = _this.touches.currentX = pageX;
_this.touches.startY = _this.touches.currentY = pageY;
_this.touches.start = _this.touches.current = isH ? pageX : pageY;
//Set Transition Time to 0
_this.setWrapperTransition(0);
//Get Start Translate Position
_this.positions.start = _this.positions.current = _this.getWrapperTranslate();
//Set Transform
_this.setWrapperTranslate(_this.positions.start);
//TouchStartTime
_this.times.start = (new Date()).getTime();
//Unset Scrolling
isScrolling = undefined;
//Set Treshold
if (params.moveStartThreshold>0) allowThresholdMove = false;
//CallBack
if (params.onTouchStart) params.onTouchStart(_this);
_this.callPlugins('onTouchStartEnd');
}
}
var velocityPrevPosition, velocityPrevTime;
function onTouchMove(event) {
// If slider is not touched - exit
if (!_this.isTouched || params.onlyExternal) return;
if (isTouchEvent && event.type=='mousemove') return;
var pageX = isTouchEvent ? event.targetTouches[0].pageX : (event.pageX || event.clientX);
var pageY = isTouchEvent ? event.targetTouches[0].pageY : (event.pageY || event.clientY);
//check for scrolling
if ( typeof isScrolling === 'undefined' && isH) {
isScrolling = !!( isScrolling || Math.abs(pageY - _this.touches.startY) > Math.abs( pageX - _this.touches.startX ) );
}
if ( typeof isScrolling === 'undefined' && !isH) {
isScrolling = !!( isScrolling || Math.abs(pageY - _this.touches.startY) < Math.abs( pageX - _this.touches.startX ) );
}
if (isScrolling ) {
_this.isTouched = false;
return;
}
//Check For Nested Swipers
if (event.assignedToSwiper) {
_this.isTouched = false;
return;
}
event.assignedToSwiper = true;
//Block inner links
if (params.preventLinks) {
_this.allowLinks = false;
}
if (params.onSlideClick) {
_this.allowSlideClick = false;
}
//Stop AutoPlay if exist
if (params.autoplay) {
_this.stopAutoplay();
}
if (!isTouchEvent || event.touches.length == 1) {
//Moved Flag
if (!_this.isMoved) {
_this.callPlugins('onTouchMoveStart');
if (params.loop) {
_this.fixLoop();
_this.positions.start = _this.getWrapperTranslate();
}
if (params.onTouchMoveStart) params.onTouchMoveStart(_this);
}
_this.isMoved = true;
// cancel event
if(event.preventDefault) event.preventDefault();
else event.returnValue = false;
_this.touches.current = isH ? pageX : pageY ;
_this.positions.current = (_this.touches.current - _this.touches.start) * params.touchRatio + _this.positions.start;
//Resistance Callbacks
if(_this.positions.current > 0 && params.onResistanceBefore) {
params.onResistanceBefore(_this, _this.positions.current);
}
if(_this.positions.current < -maxWrapperPosition() && params.onResistanceAfter) {
params.onResistanceAfter(_this, Math.abs(_this.positions.current + maxWrapperPosition()));
}
//Resistance
if (params.resistance && params.resistance!='100%') {
//Resistance for Negative-Back sliding
if(_this.positions.current > 0) {
var resistance = 1 - _this.positions.current/containerSize/2;
if (resistance < 0.5)
_this.positions.current = (containerSize/2);
else
_this.positions.current = _this.positions.current * resistance;
}
//Resistance for After-End Sliding
if ( _this.positions.current < -maxWrapperPosition() ) {
var diff = (_this.touches.current - _this.touches.start)*params.touchRatio + (maxWrapperPosition()+_this.positions.start);
var resistance = (containerSize+diff)/(containerSize);
var newPos = _this.positions.current-diff*(1-resistance)/2;
var stopPos = -maxWrapperPosition() - containerSize/2;
if (newPos < stopPos || resistance<=0)
_this.positions.current = stopPos;
else
_this.positions.current = newPos;
}
}
if (params.resistance && params.resistance=='100%') {
//Resistance for Negative-Back sliding
if(_this.positions.current > 0 && !(params.freeMode&&!params.freeModeFluid)) {
_this.positions.current = 0;
}
//Resistance for After-End Sliding
if ( (_this.positions.current) < -maxWrapperPosition() && !(params.freeMode&&!params.freeModeFluid)) {
_this.positions.current = -maxWrapperPosition();
}
}
//Move Slides
if (!params.followFinger) return;
if (!params.moveStartThreshold) {
_this.setWrapperTranslate(_this.positions.current);
}
else {
if ( Math.abs(_this.touches.current - _this.touches.start)>params.moveStartThreshold || allowThresholdMove) {
allowThresholdMove = true;
_this.setWrapperTranslate(_this.positions.current);
}
else {
_this.positions.current = _this.positions.start;
}
}
if (params.freeMode || params.watchActiveIndex) {
_this.updateActiveSlide(_this.positions.current);
}
//Grab Cursor
//Grab Cursor
if (params.grabCursor) {
_this.container.style.cursor = 'move';
_this.container.style.cursor = 'grabbing';
_this.container.style.cursor = '-moz-grabbing';
_this.container.style.cursor = '-webkit-grabbing';
}
//Velocity
if (!velocityPrevPosition) velocityPrevPosition = _this.touches.current;
if (!velocityPrevTime) velocityPrevTime = (new Date).getTime();
_this.velocity = (_this.touches.current - velocityPrevPosition)/((new Date).getTime() - velocityPrevTime)/2;
if (Math.abs(_this.touches.current - velocityPrevPosition)<2) _this.velocity=0;
velocityPrevPosition = _this.touches.current;
velocityPrevTime = (new Date).getTime();
//Callbacks
_this.callPlugins('onTouchMoveEnd');
if (params.onTouchMove) params.onTouchMove(_this);
return false;
}
}
function onTouchEnd(event) {
//Check For scrolling
if (isScrolling) {
_this.swipeReset();
}
// If slider is not touched exit
if ( params.onlyExternal || !_this.isTouched ) return;
_this.isTouched = false
//Return Grab Cursor
if (params.grabCursor) {
_this.container.style.cursor = 'move';
_this.container.style.cursor = 'grab';
_this.container.style.cursor = '-moz-grab';
_this.container.style.cursor = '-webkit-grab';
}
//Check for Current Position
if (!_this.positions.current && _this.positions.current!==0) {
_this.positions.current = _this.positions.start
}
//For case if slider touched but not moved
if (params.followFinger) {
_this.setWrapperTranslate(_this.positions.current);
}
// TouchEndTime
_this.times.end = (new Date()).getTime();
//Difference
_this.touches.diff = _this.touches.current - _this.touches.start
_this.touches.abs = Math.abs(_this.touches.diff)
_this.positions.diff = _this.positions.current - _this.positions.start
_this.positions.abs = Math.abs(_this.positions.diff)
var diff = _this.positions.diff ;
var diffAbs =_this.positions.abs ;
var timeDiff = _this.times.end - _this.times.start
if(diffAbs < 5 && (timeDiff) < 300 && _this.allowLinks == false) {
if (!params.freeMode && diffAbs!=0) _this.swipeReset()
//Release inner links
if (params.preventLinks) {
_this.allowLinks = true;
}
if (params.onSlideClick) {
_this.allowSlideClick = true;
}
}
setTimeout(function () {
//Release inner links
if (params.preventLinks) {
_this.allowLinks = true;
}
if (params.onSlideClick) {
_this.allowSlideClick = true;
}
}, 100);
var maxPosition = maxWrapperPosition();
//Not moved or Prevent Negative Back Sliding/After-End Sliding
if (!_this.isMoved && params.freeMode) {
_this.isMoved = false;
if (params.onTouchEnd) params.onTouchEnd(_this);
_this.callPlugins('onTouchEnd');
return;
}
if (!_this.isMoved || _this.positions.current > 0 || _this.positions.current < -maxPosition) {
_this.swipeReset();
if (params.onTouchEnd) params.onTouchEnd(_this);
_this.callPlugins('onTouchEnd');
return;
}
_this.isMoved = false;
//Free Mode
if (params.freeMode) {
if ( params.freeModeFluid ) {
var momentumDuration = 1000*params.momentumRatio;
var momentumDistance = _this.velocity*momentumDuration;
var newPosition = _this.positions.current + momentumDistance
var doBounce = false;
var afterBouncePosition;
var bounceAmount = Math.abs( _this.velocity )*20*params.momentumBounceRatio;
if (newPosition < -maxPosition) {
if (params.momentumBounce && _this.support.transitions) {
if (newPosition + maxPosition < -bounceAmount) newPosition = -maxPosition-bounceAmount;
afterBouncePosition = -maxPosition;
doBounce=true;
allowMomentumBounce = true;
}
else newPosition = -maxPosition;
}
if (newPosition > 0) {
if (params.momentumBounce && _this.support.transitions) {
if (newPosition>bounceAmount) newPosition = bounceAmount;
afterBouncePosition = 0
doBounce = true;
allowMomentumBounce = true;
}
else newPosition = 0;
}
//Fix duration
if (_this.velocity!=0) momentumDuration = Math.abs((newPosition - _this.positions.current)/_this.velocity)
_this.setWrapperTranslate(newPosition);
_this.setWrapperTransition( momentumDuration );
if (params.momentumBounce && doBounce) {
_this.wrapperTransitionEnd(function () {
if (!allowMomentumBounce) return;
if (params.onMomentumBounce) params.onMomentumBounce(_this);
_this.setWrapperTranslate(afterBouncePosition);
_this.setWrapperTransition(300);
})
}
_this.updateActiveSlide(newPosition)
}
if (!params.freeModeFluid || timeDiff >= 300) _this.updateActiveSlide(_this.positions.current)
if (params.onTouchEnd) params.onTouchEnd(_this)
_this.callPlugins('onTouchEnd');
return;
}
//Direction
direction = diff < 0 ? "toNext" : "toPrev"
//Short Touches
if (direction=="toNext" && ( timeDiff <= 300 ) ) {
if (diffAbs < 30 || !params.shortSwipes) _this.swipeReset()
else _this.swipeNext(true);
}
if (direction=="toPrev" && ( timeDiff <= 300 ) ) {
if (diffAbs < 30 || !params.shortSwipes) _this.swipeReset()
else _this.swipePrev(true);
}
//Long Touches
var targetSlideSize = 0;
if(params.slidesPerView == 'auto') {
//Define current slide's width
var currentPosition = Math.abs(_this.getWrapperTranslate());
var slidesOffset = 0;
var _slideSize;
for (var i=0; i<_this.slides.length; i++) {
_slideSize = isH ? _this.slides[i].getWidth(true) : _this.slides[i].getHeight(true);
slidesOffset+= _slideSize;
if (slidesOffset>currentPosition) {
targetSlideSize = _slideSize;
break;
}
}
if (targetSlideSize>containerSize) targetSlideSize = containerSize;
}
else {
targetSlideSize = slideSize * params.slidesPerView;
}
if (direction=="toNext" && ( timeDiff > 300 ) ) {
if (diffAbs >= targetSlideSize*0.5) {
_this.swipeNext(true)
}
else {
_this.swipeReset()
}
}
if (direction=="toPrev" && ( timeDiff > 300 ) ) {
if (diffAbs >= targetSlideSize*0.5) {
_this.swipePrev(true);
}
else {
_this.swipeReset()
}
}
if (params.onTouchEnd) params.onTouchEnd(_this)
_this.callPlugins('onTouchEnd');
}
/*==================================================
noSwiping Bubble Check by Isaac Strack
====================================================*/
function noSwipingSlide(el){
/*This function is specifically designed to check the parent elements for the noSwiping class, up to the wrapper.
We need to check parents because while onTouchStart bubbles, _this.isTouched is checked in onTouchStart, which stops the bubbling.
So, if a text box, for example, is the initial target, and the parent slide container has the noSwiping class, the _this.isTouched
check will never find it, and what was supposed to be noSwiping is able to be swiped.
This function will iterate up and check for the noSwiping class in parents, up through the wrapperClass.*/
// First we create a truthy variable, which is that swiping is allowd (noSwiping = false)
var noSwiping = false;
// Now we iterate up (parentElements) until we reach the node with the wrapperClass.
do{
// Each time, we check to see if there's a 'swiper-no-swiping' class (noSwipingClass).
if (el.className.indexOf(params.noSwipingClass)>-1)
{
noSwiping = true; // If there is, we set noSwiping = true;
}
el = el.parentElement; // now we iterate up (parent node)
} while(!noSwiping && el.parentElement && el.className.indexOf(params.wrapperClass)==-1); // also include el.parentElement truthy, just in case.
// because we didn't check the wrapper itself, we do so now, if noSwiping is false:
if (!noSwiping && el.className.indexOf(params.wrapperClass)>-1 && el.className.indexOf(params.noSwipingClass)>-1)
noSwiping = true; // if the wrapper has the noSwipingClass, we set noSwiping = true;
return noSwiping;
}
/*==================================================
Swipe Functions
====================================================*/
_this.swipeNext = function(internal){
if (!internal && params.loop) _this.fixLoop();
_this.callPlugins('onSwipeNext');
var currentPosition = _this.getWrapperTranslate();
var newPosition = currentPosition;
if (params.slidesPerView=='auto') {
for (var i=0; i<_this.snapGrid.length; i++) {
if (-currentPosition >= _this.snapGrid[i] && -currentPosition<_this.snapGrid[i+1]) {
newPosition = -_this.snapGrid[i+1]
break;
}
}
}
else {
var groupSize = slideSize * params.slidesPerGroup;
newPosition = -(Math.floor(Math.abs(currentPosition)/Math.floor(groupSize))*groupSize + groupSize);
}
if (newPosition < - maxWrapperPosition()) {
newPosition = - maxWrapperPosition()
};
if (newPosition == currentPosition) return false;
swipeToPosition(newPosition, 'next');
return true
}
_this.swipePrev = function(internal){
if (!internal && params.loop) _this.fixLoop();
if (!internal && params.autoplay) _this.stopAutoplay();
_this.callPlugins('onSwipePrev');
var currentPosition = Math.ceil(_this.getWrapperTranslate());
var newPosition;
if (params.slidesPerView=='auto') {
newPosition = 0;
for (var i=1; i<_this.snapGrid.length; i++) {
if (-currentPosition == _this.snapGrid[i]) {
newPosition = -_this.snapGrid[i-1]
break;
}
if (-currentPosition > _this.snapGrid[i] && -currentPosition<_this.snapGrid[i+1]) {
newPosition = -_this.snapGrid[i]
break;
}
}
}
else {
var groupSize = slideSize * params.slidesPerGroup;
newPosition = -(Math.ceil(-currentPosition/groupSize)-1)*groupSize;
}
if (newPosition > 0) newPosition = 0;
if (newPosition == currentPosition) return false;
swipeToPosition(newPosition, 'prev');
return true;
}
_this.swipeReset = function(){
_this.callPlugins('onSwipeReset');
var currentPosition = _this.getWrapperTranslate();
var groupSize = slideSize * params.slidesPerGroup;
var newPosition;
var maxPosition = -maxWrapperPosition();
if (params.slidesPerView=='auto') {
newPosition = 0;
for (var i=0; i<_this.snapGrid.length; i++) {
if (-currentPosition===_this.snapGrid[i]) return;
if (-currentPosition >= _this.snapGrid[i] && -currentPosition<_this.snapGrid[i+1]) {
if(_this.positions.diff>0) newPosition = -_this.snapGrid[i+1]
else newPosition = -_this.snapGrid[i]
break;
}
}
if (-currentPosition >= _this.snapGrid[_this.snapGrid.length-1]) newPosition = -_this.snapGrid[_this.snapGrid.length-1];
if (currentPosition <= -maxWrapperPosition()) newPosition = -maxWrapperPosition()
}
else {
newPosition = currentPosition<0 ? Math.round(currentPosition/groupSize)*groupSize : 0
}
if (params.scrollContainer) {
newPosition = currentPosition<0 ? currentPosition : 0;
}
if (newPosition < -maxWrapperPosition()) {
newPosition = -maxWrapperPosition()
}
if (params.scrollContainer && (containerSize>slideSize)) {
newPosition = 0;
}
if (newPosition == currentPosition) return false;
swipeToPosition(newPosition, 'reset');
return true;
}
_this.swipeTo = function(index, speed, runCallbacks) {
index = parseInt(index, 10);
_this.callPlugins('onSwipeTo', {index:index, speed:speed});
if (params.loop) index = index + _this.loopedSlides;
var currentPosition = _this.getWrapperTranslate();
if (index > (_this.slides.length-1) || index < 0) return;
var newPosition
if (params.slidesPerView=='auto') {
newPosition = -_this.slidesGrid[ index ];
}
else {
newPosition = -index*slideSize;
}
if (newPosition < - maxWrapperPosition()) {
newPosition = - maxWrapperPosition();
};
if (newPosition == currentPosition) return false;
runCallbacks = runCallbacks===false ? false : true;
swipeToPosition(newPosition, 'to', {index:index, speed:speed, runCallbacks:runCallbacks});
return true;
}
function swipeToPosition(newPosition, action, toOptions) {
var speed = (action=='to' && toOptions.speed >= 0) ? toOptions.speed : params.speed;
if (_this.support.transitions || !params.DOMAnimation) {
_this.setWrapperTranslate(newPosition);
_this.setWrapperTransition(speed);
}
else {
//Try the DOM animation
var currentPosition = _this.getWrapperTranslate();
var animationStep = Math.ceil( (newPosition - currentPosition)/speed*(1000/60) );
var direction = currentPosition > newPosition ? 'toNext' : 'toPrev';
var condition = direction=='toNext' ? currentPosition > newPosition : currentPosition < newPosition;
if (_this._DOMAnimating) return;
anim();
}
function anim(){
currentPosition += animationStep;
condition = direction=='toNext' ? currentPosition > newPosition : currentPosition < newPosition;
if (condition) {
_this.setWrapperTranslate(Math.round(currentPosition));
_this._DOMAnimating = true
window.setTimeout(function(){
anim()
}, 1000 / 60)
}
else {
if (params.onSlideChangeEnd) params.onSlideChangeEnd(_this);
_this.setWrapperTranslate(newPosition);
_this._DOMAnimating = false;
}
}
//Update Active Slide Index
_this.updateActiveSlide(newPosition);
//Callbacks
if (params.onSlideNext && action=='next') {
params.onSlideNext(_this, newPosition);
}
if (params.onSlidePrev && action=='prev') {
params.onSlidePrev(_this, newPosition);
}
//"Reset" Callback
if (params.onSlideReset && action=='reset') {
params.onSlideReset(_this, newPosition);
}
//"Next", "Prev" and "To" Callbacks
if (action=='next' || action=='prev' || (action=='to' && toOptions.runCallbacks==true))
slideChangeCallbacks();
}
/*==================================================
Transition Callbacks
====================================================*/
//Prevent Multiple Callbacks
_this._queueStartCallbacks = false;
_this._queueEndCallbacks = false;
function slideChangeCallbacks() {
//Transition Start Callback
_this.callPlugins('onSlideChangeStart');
if (params.onSlideChangeStart) {
if (params.queueStartCallbacks && _this.support.transitions) {
if (_this._queueStartCallbacks) return;
_this._queueStartCallbacks = true;
params.onSlideChangeStart(_this)
_this.wrapperTransitionEnd(function(){
_this._queueStartCallbacks = false;
})
}
else params.onSlideChangeStart(_this)
}
//Transition End Callback
if (params.onSlideChangeEnd) {
if (_this.support.transitions) {
if (params.queueEndCallbacks) {
if (_this._queueEndCallbacks) return;
_this._queueEndCallbacks = true;
_this.wrapperTransitionEnd(params.onSlideChangeEnd)
}
else {
_this.wrapperTransitionEnd(function(){ _this.fixLoop(); params.onSlideChangeEnd(_this); });
}
}
else {
if (!params.DOMAnimation) {
setTimeout(function(){
params.onSlideChangeEnd(_this)
},10)
}
}
}
}
/*==================================================
Update Active Slide Index
====================================================*/
_this.updateActiveSlide = function(position) {
if (!_this.initialized) return;
if (_this.slides.length==0) return;
_this.previousIndex = _this.activeIndex;
if (typeof position=='undefined') position = _this.getWrapperTranslate();
if (position>0) position=0;
if (params.slidesPerView == 'auto') {
var slidesOffset = 0;
_this.activeIndex = _this.slidesGrid.indexOf(-position);
if (_this.activeIndex<0) {
for (var i=0; i<_this.slidesGrid.length-1; i++) {
if (-position>_this.slidesGrid[i] && -position<_this.slidesGrid[i+1]) {
break;
}
}
var leftDistance = Math.abs( _this.slidesGrid[i] + position )
var rightDistance = Math.abs( _this.slidesGrid[i+1] + position )
if (leftDistance<=rightDistance) _this.activeIndex = i;
else _this.activeIndex = i+1;
}
}
else {
_this.activeIndex = Math[params.visibilityFullFit ? 'ceil' : 'round']( -position/slideSize );
}
if (_this.activeIndex == _this.slides.length ) _this.activeIndex = _this.slides.length - 1;
if (_this.activeIndex < 0) _this.activeIndex = 0;
// Check for slide
if (!_this.slides[_this.activeIndex]) return;
// Calc Visible slides
_this.calcVisibleSlides(position);
// Mark visible and active slides with additonal classes
var activeClassRegexp = new RegExp( "\\s*" + params.slideActiveClass );
var inViewClassRegexp = new RegExp( "\\s*" + params.slideVisibleClass );
for (var i = 0; i < _this.slides.length; i++) {
_this.slides[ i ].className = _this.slides[ i ].className.replace( activeClassRegexp, '' ).replace( inViewClassRegexp, '' );
if ( _this.visibleSlides.indexOf( _this.slides[ i ] )>=0 ) {
_this.slides[ i ].className += ' ' + params.slideVisibleClass;
}
}
_this.slides[ _this.activeIndex ].className += ' ' + params.slideActiveClass;
//Update loop index
if (params.loop) {
var ls = _this.loopedSlides;
_this.activeLoopIndex = _this.activeIndex - ls;
if (_this.activeLoopIndex >= _this.slides.length - ls*2 ) {
_this.activeLoopIndex = _this.slides.length - ls*2 - _this.activeLoopIndex;
}
if (_this.activeLoopIndex<0) {
_this.activeLoopIndex = _this.slides.length - ls*2 + _this.activeLoopIndex;
}
}
else {
_this.activeLoopIndex = _this.activeIndex;
}
//Update Pagination
if (params.pagination) {
_this.updatePagination(position);
}
}
/*==================================================
Pagination
====================================================*/
_this.createPagination = function (firstInit) {
if (params.paginationClickable && _this.paginationButtons) {
removePaginationEvents();
}
var paginationHTML = "";
var numOfSlides = _this.slides.length;
var numOfButtons = numOfSlides;
if (params.loop) numOfButtons -= _this.loopedSlides*2
for (var i = 0; i < numOfButtons; i++) {
paginationHTML += '<'+params.paginationElement+' class="'+params.paginationElementClass+'"></'+params.paginationElement+'>'
}
_this.paginationContainer = params.pagination.nodeType ? params.pagination : $$(params.pagination)[0];
_this.paginationContainer.innerHTML = paginationHTML;
_this.paginationButtons = $$('.'+params.paginationElementClass, _this.paginationContainer);
if (!firstInit) _this.updatePagination()
_this.callPlugins('onCreatePagination');
if (params.paginationClickable) {
addPaginationEvents();
}
}
function removePaginationEvents() {
var pagers = _this.paginationButtons;
for (var i=0; i<pagers.length; i++) {
_this.h.removeEventListener(pagers[i], 'click', paginationClick);
}
}
function addPaginationEvents() {
var pagers = _this.paginationButtons;
for (var i=0; i<pagers.length; i++) {
_this.h.addEventListener(pagers[i], 'click', paginationClick);
}
}
function paginationClick(e){
var index;
var target = e.target || e.srcElement;
var pagers = _this.paginationButtons;
for (var i=0; i<pagers.length; i++) {
if (target===pagers[i]) index = i;
}
_this.swipeTo(index)
}
_this.updatePagination = function(position) {
if (!params.pagination) return;
if (_this.slides.length<1) return;
var activePagers = $$('.'+params.paginationActiveClass, _this.paginationContainer);
if(!activePagers) return;
//Reset all Buttons' class to not active
var pagers = _this.paginationButtons;
if (pagers.length==0) return;
for (var i=0; i < pagers.length; i++) {
pagers[i].className = params.paginationElementClass
}
var indexOffset = params.loop ? _this.loopedSlides : 0;
if (params.paginationAsRange) {
if (!_this.visibleSlides) _this.calcVisibleSlides(position)
//Get Visible Indexes
var visibleIndexes = [];
for (var i = 0; i < _this.visibleSlides.length; i++) {
var visIndex = _this.slides.indexOf( _this.visibleSlides[i] ) - indexOffset
if (params.loop && visIndex<0) {
visIndex = _this.slides.length - _this.loopedSlides*2 + visIndex;
}
if (params.loop && visIndex>=_this.slides.length-_this.loopedSlides*2) {
visIndex = _this.slides.length - _this.loopedSlides*2 - visIndex;
visIndex = Math.abs(visIndex)
}
visibleIndexes.push( visIndex )
}
for (i=0; i<visibleIndexes.length; i++) {
if (pagers[ visibleIndexes[i] ]) pagers[ visibleIndexes[i] ].className += ' ' + params.paginationVisibleClass;
}
if (params.loop) {
pagers[ _this.activeLoopIndex ].className += ' ' + params.paginationActiveClass;
}
else {
pagers[ _this.activeIndex ].className += ' ' + params.paginationActiveClass;
}
}
else {
if (params.loop) {
pagers[ _this.activeLoopIndex ].className+=' '+params.paginationActiveClass+' '+params.paginationVisibleClass;
}
else {
pagers[ _this.activeIndex ].className+=' '+params.paginationActiveClass+' '+params.paginationVisibleClass;
}
}
}
_this.calcVisibleSlides = function(position){
var visibleSlides = [];
var _slideLeft = 0, _slideSize = 0, _slideRight = 0;
if (isH && _this.wrapperLeft>0) position = position+_this.wrapperLeft;
if (!isH && _this.wrapperTop>0) position = position+_this.wrapperTop;
for (var i=0; i<_this.slides.length; i++) {
_slideLeft += _slideSize;
if (params.slidesPerView == 'auto')
_slideSize = isH ? _this.h.getWidth(_this.slides[i],true) : _this.h.getHeight(_this.slides[i],true);
else _slideSize = slideSize;
_slideRight = _slideLeft + _slideSize;
var isVisibile = false;
if (params.visibilityFullFit) {
if (_slideLeft >= -position && _slideRight <= -position+containerSize) isVisibile = true;
if (_slideLeft <= -position && _slideRight >= -position+containerSize) isVisibile = true;
}
else {
if (_slideRight > -position && _slideRight <= ((-position+containerSize))) isVisibile = true;
if (_slideLeft >= -position && _slideLeft < ((-position+containerSize))) isVisibile = true;
if (_slideLeft < -position && _slideRight > ((-position+containerSize))) isVisibile = true;
}
if (isVisibile) visibleSlides.push(_this.slides[i])
}
if (visibleSlides.length==0) visibleSlides = [ _this.slides[ _this.activeIndex ] ]
_this.visibleSlides = visibleSlides;
}
/*==========================================
Autoplay
============================================*/
_this.autoPlayIntervalId = undefined;
_this.startAutoplay = function () {
if (typeof _this.autoPlayIntervalId !== 'undefined') return false;
if (params.autoplay && !params.loop) {
_this.autoPlayIntervalId = setInterval(function(){
if (!_this.swipeNext(true)) _this.swipeTo(0);
}, params.autoplay)
}
if (params.autoplay && params.loop) {
_this.autoPlayIntervalId = setInterval(function(){
_this.swipeNext();
}, params.autoplay)
}
_this.callPlugins('onAutoplayStart');
}
_this.stopAutoplay = function () {
if (_this.autoPlayIntervalId) clearInterval(_this.autoPlayIntervalId);
_this.autoPlayIntervalId = undefined;
_this.callPlugins('onAutoplayStop');
}
/*==================================================
Loop
====================================================*/
_this.loopCreated = false;
_this.removeLoopedSlides = function(){
if (_this.loopCreated) {
for (var i=0; i<_this.slides.length; i++) {
if (_this.slides[i].getData('looped')===true) _this.wrapper.removeChild(_this.slides[i]);
}
}
}
_this.createLoop = function() {
if (_this.slides.length==0) return;
_this.loopedSlides = params.slidesPerView + params.loopAdditionalSlides;
if (_this.loopedSlides > _this.slides.length) {
_this.loopedSlides = _this.slides.length;
}
var slideFirstHTML = '',
slideLastHTML = '',
i;
//Grab First Slides
for (i=0; i<_this.loopedSlides; i++) {
slideFirstHTML += _this.slides[i].outerHTML;
}
//Grab Last Slides
for (i=_this.slides.length-_this.loopedSlides; i<_this.slides.length; i++) {
slideLastHTML += _this.slides[i].outerHTML;
}
wrapper.innerHTML = slideLastHTML + wrapper.innerHTML + slideFirstHTML;
_this.loopCreated = true;
_this.calcSlides();
//Update Looped Slides with special class
for (i=0; i<_this.slides.length; i++) {
if (i<_this.loopedSlides || i>=_this.slides.length-_this.loopedSlides) _this.slides[i].setData('looped', true);
}
_this.callPlugins('onCreateLoop');
}
_this.fixLoop = function() {
if(_this.params.loop == true) {
var newIndex;
//Fix For Negative Oversliding
if (_this.activeIndex < _this.loopedSlides) {
newIndex = _this.slides.length - _this.loopedSlides*3 + _this.activeIndex;
_this.swipeTo(newIndex, 0, false);
}
//Fix For Positive Oversliding
else if (_this.activeIndex > _this.slides.length - params.slidesPerView*2) {
newIndex = -_this.slides.length + _this.activeIndex + _this.loopedSlides
_this.swipeTo(newIndex, 0, false);
}
}
}
/*==================================================
Slides Loader
====================================================*/
_this.loadSlides = function(){
var slidesHTML = '';
_this.activeLoaderIndex = 0;
var slides = params.loader.slides;
var slidesToLoad = params.loader.loadAllSlides ? slides.length : params.slidesPerView*(1+params.loader.surroundGroups);
for (var i=0; i< slidesToLoad; i++) {
if (params.loader.slidesHTMLType=='outer') slidesHTML+=slides[i];
else {
slidesHTML+='<'+params.slideElement+' class="'+params.slideClass+'" data-swiperindex="'+i+'">'+slides[i]+'</'+params.slideElement+'>';
}
}
_this.wrapper.innerHTML = slidesHTML;
_this.calcSlides(true);
//Add permanent transitionEnd callback
if (!params.loader.loadAllSlides) {
_this.wrapperTransitionEnd(_this.reloadSlides, true);
}
}
_this.reloadSlides = function(){
var slides = params.loader.slides;
var newActiveIndex = parseInt(_this.activeSlide().data('swiperindex'),10)
if (newActiveIndex<0 || newActiveIndex>slides.length-1) return //<-- Exit
_this.activeLoaderIndex = newActiveIndex;
var firstIndex = Math.max(0, newActiveIndex - params.slidesPerView*params.loader.surroundGroups)
var lastIndex = Math.min(newActiveIndex+params.slidesPerView*(1+params.loader.surroundGroups)-1, slides.length-1)
//Update Transforms
if (newActiveIndex>0) {
var newTransform = -slideSize*(newActiveIndex-firstIndex)
_this.setWrapperTranslate(newTransform);
_this.setWrapperTransition(0);
}
//New Slides
if (params.loader.logic==='reload') {
_this.wrapper.innerHTML = '';
var slidesHTML = '';
for (var i = firstIndex; i<=lastIndex; i++) {
slidesHTML += params.loader.slidesHTMLType == 'outer' ? slides[i] : '<'+params.slideElement+' class="'+params.slideClass+'" data-swiperindex="'+i+'">'+slides[i]+'</'+params.slideElement+'>';
}
_this.wrapper.innerHTML = slidesHTML;
}
else {
var minExistIndex=1000;
var maxExistIndex=0;
for (var i=0; i<_this.slides.length; i++) {
var index = _this.slides[i].data('swiperindex');
if (index<firstIndex || index>lastIndex) {
_this.wrapper.removeChild(_this.slides[i]);
}
else {
minExistIndex = Math.min(index, minExistIndex)
maxExistIndex = Math.max(index, maxExistIndex)
}
}
for (var i=firstIndex; i<=lastIndex; i++) {
if (i<minExistIndex) {
var newSlide = document.createElement(params.slideElement);
newSlide.className = params.slideClass;
newSlide.setAttribute('data-swiperindex',i);
newSlide.innerHTML = slides[i];
_this.wrapper.insertBefore(newSlide, _this.wrapper.firstChild);
}
if (i>maxExistIndex) {
var newSlide = document.createElement(params.slideElement);
newSlide.className = params.slideClass;
newSlide.setAttribute('data-swiperindex',i);
newSlide.innerHTML = slides[i];
_this.wrapper.appendChild(newSlide);
}
}
}
//reInit
_this.reInit(true);
}
/*==================================================
Make Swiper
====================================================*/
function makeSwiper(){
_this.calcSlides();
if (params.loader.slides.length>0 && _this.slides.length==0) {
_this.loadSlides();
}
if (params.loop) {
_this.createLoop();
}
_this.init();
initEvents();
if (params.pagination && params.createPagination) {
_this.createPagination(true);
}
if (params.loop || params.initialSlide>0) {
_this.swipeTo( params.initialSlide, 0, false );
}
else {
_this.updateActiveSlide(0);
}
if (params.autoplay) {
_this.startAutoplay();
}
}
makeSwiper();
}
Swiper.prototype = {
plugins : {},
/*==================================================
Wrapper Operations
====================================================*/
wrapperTransitionEnd : function(callback, permanent) {
var a = this,
el = a.wrapper,
events = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'],
i;
function fireCallBack() {
callback(a);
if (a.params.queueEndCallbacks) a._queueEndCallbacks = false;
if (!permanent) {
for (i=0; i<events.length; i++) {
a.h.removeEventListener(el, events[i], fireCallBack);
}
}
}
if (callback) {
for (i=0; i<events.length; i++) {
a.h.addEventListener(el, events[i], fireCallBack);
}
}
},
getWrapperTranslate : function (axis) {
var el = this.wrapper,
matrix, curTransform, curStyle, transformMatrix;
// automatic axis detection
if (typeof axis == 'undefined') {
axis = this.params.mode == 'horizontal' ? 'x' : 'y';
}
curStyle = window.getComputedStyle(el, null);
if (window.WebKitCSSMatrix) {
transformMatrix = new WebKitCSSMatrix(curStyle.webkitTransform);
}
else {
transformMatrix = curStyle.MozTransform || curStyle.OTransform || curStyle.MsTransform || curStyle.msTransform || curStyle.transform || curStyle.getPropertyValue("transform").replace("translate(", "matrix(1, 0, 0, 1,");
matrix = transformMatrix.toString().split(',');
}
if (this.support.transforms && this.params.useCSS3Transforms) {
if (axis=='x') {
//Latest Chrome and webkits Fix
if (window.WebKitCSSMatrix)
curTransform = transformMatrix.m41;
//Crazy IE10 Matrix
else if (matrix.length==16)
curTransform = parseFloat( matrix[12] );
//Normal Browsers
else
curTransform = parseFloat( matrix[4] );
}
if (axis=='y') {
//Latest Chrome and webkits Fix
if (window.WebKitCSSMatrix)
curTransform = transformMatrix.m42;
//Crazy IE10 Matrix
else if (matrix.length==16)
curTransform = parseFloat( matrix[13] );
//Normal Browsers
else
curTransform = parseFloat( matrix[5] );
}
}
else {
if (axis=='x') curTransform = parseFloat(el.style.left,10) || 0;
if (axis=='y') curTransform = parseFloat(el.style.top,10) || 0;
}
return curTransform || 0;
},
setWrapperTranslate : function (x, y, z) {
var es = this.wrapper.style,
coords = {x: 0, y: 0, z: 0},
translate;
// passed all coordinates
if (arguments.length == 3) {
coords.x = x;
coords.y = y;
coords.z = z;
}
// passed one coordinate and optional axis
else {
if (typeof y == 'undefined') {
y = this.params.mode == 'horizontal' ? 'x' : 'y';
}
coords[y] = x;
}
if (this.support.transforms && this.params.useCSS3Transforms) {
translate = this.support.transforms3d ? 'translate3d(' + coords.x + 'px, ' + coords.y + 'px, ' + coords.z + 'px)' : 'translate(' + coords.x + 'px, ' + coords.y + 'px)';
es.webkitTransform = es.MsTransform = es.msTransform = es.MozTransform = es.OTransform = es.transform = translate;
}
else {
es.left = coords.x + 'px';
es.top = coords.y + 'px';
}
this.callPlugins('onSetWrapperTransform', coords);
},
setWrapperTransition : function (duration) {
var es = this.wrapper.style;
es.webkitTransitionDuration = es.MsTransitionDuration = es.msTransitionDuration = es.MozTransitionDuration = es.OTransitionDuration = es.transitionDuration = (duration / 1000) + 's';
this.callPlugins('onSetWrapperTransition', {duration: duration});
},
/*==================================================
Helpers
====================================================*/
h : {
getWidth: function (el, outer) {
var width = window.getComputedStyle(el, null).getPropertyValue('width')
var returnWidth = parseFloat(width);
//IE Fixes
if(isNaN(returnWidth) || width.indexOf('%')>0) {
returnWidth = el.offsetWidth - parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-left')) - parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-right'));
}
if (outer) returnWidth += parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-left')) + parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-right'))
return returnWidth;
},
getHeight: function(el, outer) {
if (outer) return el.offsetHeight;
var height = window.getComputedStyle(el, null).getPropertyValue('height')
var returnHeight = parseFloat(height);
//IE Fixes
if(isNaN(returnHeight) || height.indexOf('%')>0) {
returnHeight = el.offsetHeight - parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-top')) - parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-bottom'));
}
if (outer) returnHeight += parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-top')) + parseFloat(window.getComputedStyle(el, null).getPropertyValue('padding-bottom'))
return returnHeight;
},
getOffset: function(el) {
var box = el.getBoundingClientRect();
var body = document.body;
var clientTop = el.clientTop || body.clientTop || 0;
var clientLeft = el.clientLeft || body.clientLeft || 0;
var scrollTop = window.pageYOffset || el.scrollTop;
var scrollLeft = window.pageXOffset || el.scrollLeft;
if (document.documentElement && !window.pageYOffset) {
//IE7-8
scrollTop = document.documentElement.scrollTop;
scrollLeft = document.documentElement.scrollLeft;
}
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
},
windowWidth : function() {
if (window.innerWidth) return window.innerWidth
else if (document.documentElement && document.documentElement.clientWidth) return document.documentElement.clientWidth;
},
windowHeight : function() {
if (window.innerHeight) return window.innerHeight
else if (document.documentElement && document.documentElement.clientHeight) return document.documentElement.clientHeight;
},
windowScroll : function() {
var left=0, top=0;
if (typeof pageYOffset != 'undefined') {
return {
left: window.pageXOffset,
top: window.pageYOffset
}
}
else if (document.documentElement) {
return {
left: document.documentElement.scrollLeft,
top: document.documentElement.scrollTop
}
}
},
addEventListener : function (el, event, listener, useCapture) {
if (typeof useCapture == 'undefined') {
useCapture = false;
}
if (el.addEventListener) {
el.addEventListener(event, listener, useCapture);
}
else if (el.attachEvent) {
el.attachEvent('on' + event, listener);
}
},
removeEventListener : function (el, event, listener, useCapture) {
if (typeof useCapture == 'undefined') {
useCapture = false;
}
if (el.removeEventListener) {
el.removeEventListener(event, listener, useCapture);
}
else if (el.detachEvent) {
el.detachEvent('on' + event, listener);
}
}
},
setTransform : function (el, transform) {
var es = el.style
es.webkitTransform = es.MsTransform = es.msTransform = es.MozTransform = es.OTransform = es.transform = transform
},
setTranslate : function (el, translate) {
var es = el.style
var pos = {
x : translate.x || 0,
y : translate.y || 0,
z : translate.z || 0
};
var transformString = this.support.transforms3d ? 'translate3d('+(pos.x)+'px,'+(pos.y)+'px,'+(pos.z)+'px)' : 'translate('+(pos.x)+'px,'+(pos.y)+'px)';
es.webkitTransform = es.MsTransform = es.msTransform = es.MozTransform = es.OTransform = es.transform = transformString;
if (!this.support.transforms) {
es.left = pos.x+'px'
es.top = pos.y+'px'
}
},
setTransition : function (el, duration) {
var es = el.style
es.webkitTransitionDuration = es.MsTransitionDuration = es.msTransitionDuration = es.MozTransitionDuration = es.OTransitionDuration = es.transitionDuration = duration+'ms';
},
/*==================================================
Feature Detection
====================================================*/
support: {
touch : (window.Modernizr && Modernizr.touch===true) || (function() {
return !!(("ontouchstart" in window) || window.DocumentTouch && document instanceof DocumentTouch);
})(),
transforms3d : (window.Modernizr && Modernizr.csstransforms3d===true) || (function() {
var div = document.createElement('div').style;
return ("webkitPerspective" in div || "MozPerspective" in div || "OPerspective" in div || "MsPerspective" in div || "perspective" in div);
})(),
transforms : (window.Modernizr && Modernizr.csstransforms===true) || (function(){
var div = document.createElement('div').style;
return ('transform' in div || 'WebkitTransform' in div || 'MozTransform' in div || 'msTransform' in div || 'MsTransform' in div || 'OTransform' in div);
})(),
transitions : (window.Modernizr && Modernizr.csstransitions===true) || (function(){
var div = document.createElement('div').style;
return ('transition' in div || 'WebkitTransition' in div || 'MozTransition' in div || 'msTransition' in div || 'MsTransition' in div || 'OTransition' in div);
})()
},
browser : {
ie8 : (function(){
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv != -1 && rv < 9;
})(),
ie10 : window.navigator.msPointerEnabled
}
}
/*=========================
jQuery & Zepto Plugins
===========================*/
if (window.jQuery||window.Zepto) {
(function($){
$.fn.swiper = function(params) {
var s = new Swiper($(this)[0], params)
$(this).data('swiper',s);
return s;
}
})(window.jQuery||window.Zepto)
}
// component
if ( typeof( module ) !== 'undefined' )
{
module.exports = Swiper;
}
Array.prototype.getKeyByValue = function( value ) {
for( var prop in this ) {
if( this.hasOwnProperty( prop ) ) {
if( this[ prop ] === value )
return prop;
}
}
}
jQuery(document).ready(function($){
var doneVideoInit = false;
var $captionTrans = 0;
//move parallax sliders to correct dom location
var parallaxSlider = $('.parallax_slider_outer.first-section');
function parallaxSliderPos(){
if(parallaxSlider.parent().attr('class') == 'wpb_wrapper') { parallaxSlider.parents('.wpb_row').remove(); }
parallaxSlider.insertBefore('.container-wrap');
}
parallaxSliderPos();
var $smoothSrollWidth = ($('body').attr('data-smooth-scrolling') == '1') ? 0 : 0; //will come back to this
if($('body > #boxed').length == 0 && $('.nectar-slider-wrap[data-full-width="true"]').parent().attr('id') != 'portfolio-extra' && $('.nectar-slider-wrap[data-full-width="true"]').parents('#post-area:not(".span_12")').length == 0){
$('.nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .nectar-slider-wrap').css('left', -(($(window).width()-$smoothSrollWidth)/2 - $('.main-content').width()/2))+'px';
$('.nectar-slider-wrap[data-full-width="true"] .swiper-container, .nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .swiper-container, .parallax_slider_outer.first-section .nectar-slider-wrap').css('width',$(window).width());
}
else if( $('.nectar-slider-wrap[data-full-width="true"]').parent().attr('id') == 'portfolio-extra' && $('#full_width_portfolio').length != 0){
$('.nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .nectar-slider-wrap').css('left', -(($(window).width()-$smoothSrollWidth)/2 - $('.main-content').width()/2))+'px';
$('.nectar-slider-wrap[data-full-width="true"] .swiper-container, .nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .swiper-container, .parallax_slider_outer.first-section .nectar-slider-wrap').css('width',$(window).width());
}
else {
var $container = ($('body > #boxed').length == 0) ? '#post-area' : '.container-wrap';
//backup incase only slider is used with nothing else in boxed mode
if($($container).width() == '0' && $('body > #boxed').length > 0) $container = '#boxed';
$('.nectar-slider-wrap[data-full-width="true"] .swiper-container, .nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .swiper-container, .parallax_slider_outer.first-section .nectar-slider-wrap').css('width',$($container).width());
}
//show slider once full width calcs have taken place
$('.nectar-slider-wrap').show();
//set bg colors / textures after js has made the slider fullwidth
$('.swiper-container, .swiper-slide').css('background-color','#000');
$('.video-texture').css('opacity','1');
//nectar sliders
var $nectarSliders = [];
$('.nectar-slider-wrap').each(function(i){
var $arrows = $(this).find('.swiper-container').attr('data-arrows');
var $bullets = $(this).find('.swiper-container').attr('data-bullets');
var $swipe = $(this).find('.swiper-container').attr('data-desktop-swipe');
var $loop = $(this).find('.swiper-container').attr('data-loop');
//swipe
if($swipe == 'true' && $('#'+$(this).attr('id') +' .swiper-wrapper > div').length > 1 ){
var $grab = 1;
var $desktopSwipe = 1;
} else {
var $grab = 0;
var $desktopSwipe = 0;
}
//bullets
if($bullets == 'true' && $(this).find('.swiper-wrapper > div').length > 1){
$bullets = '#'+$(this).attr('id')+' .slider-pagination';
} else {
$bullets = null;
}
//loop
$useLoop = ($loop == 'true' && $(this).find('.swiper-wrapper > div').length > 1 && !$('html').hasClass('no-video')) ? true : false;
if($useLoop == false) $(this).find('.swiper-container').attr('data-loop','false');
$nectarSliders[i] = new Swiper('#'+$(this).attr('id')+' .swiper-container', {
loop: $useLoop,
grabCursor: $grab,
touchRatio: 0.6,
speed: 525,
useCSS3Transforms: false,
pagination : $bullets,
simulateTouch: $desktopSwipe,
onSlideChangeEnd: captionTransition,
onSlideChangeStart: sliderArrowCount,
onTouchMove: clearAutoplay,
onFirstInit: nectarInit
});
$nectarSliders[i].swipeReset();
//webkit looped slider first video fix
if(navigator.userAgent.indexOf('Chrome') > 0) {
if( jQuery(this).find('.swiper-slide:nth-child(2) video').length > 0 && jQuery(this).find('.swiper-container').attr('data-loop') == 'true') {
var webmSource = jQuery(this).find('.swiper-slide:nth-child(2) video source[type="video/webm"]').attr('src') + "?"+Math.ceil(Math.random()*1000);
var firstVideo = jQuery(this).find('.swiper-slide:nth-child(2) video').get(0);
firstVideo.src = webmSource;
firstVideo.load();
}
}
function nectarInit(){
if(doneVideoInit == true) return;
//videos
$('.swiper-slide .slider-video').mediaelementplayer({
enableKeyboard: false,
iPadUseNativeControls: false,
pauseOtherPlayers: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false
});
//if using pp - init it after slide loads
if($().prettyPhoto) prettyPhotoInit();
doneVideoInit = true;
}
//Navigation arrows
if($arrows == 'true' && $('#'+$(this).attr('id') +' .swiper-wrapper > div').length > 1 ){
$('.slide-count i').transition({ scale: 0.5, opacity: 0 });
//hover event
$('.swiper-container .slider-prev, .swiper-container .slider-next').hover(function(){
$(this).find('.slide-count i').clearQueue().stop(true,true).delay(100).transition({ scale: 1, opacity: 1 },200);
$(this).stop(true,true).animate({
'width' : '120px'
},300,'easeOutCubic');
$(this).find('.slide-count span').clearQueue().stop().delay(100).animate({
'opacity' : '1'
},225,'easeOutCubic');
},function(){
$('.slide-count i').stop(true,true).transition({ scale: 0, opacity: 0 },200);
$(this).stop().delay(150).animate({
'width' : '64px'
},300,'easeOutCubic');
$(this).find('.slide-count span').stop(true,true).animate({
'opacity' : '0'
},200,'easeOutCubic');
});
//add slide counts
var $slideCount = ($(this).find('.swiper-container').attr('data-loop') != 'true' ) ? $('#'+$(this).attr('id') + ' .swiper-wrapper > div').length : $('#'+$(this).attr('id') + ' .swiper-wrapper > div').length - 2;
//ie8
if($('html').hasClass('no-video')) $slideCount = $('#'+$(this).attr('id') + ' .swiper-wrapper > div').length;
$('#'+$(this).attr('id')+' .slider-prev .slide-count .slide-total').html( $slideCount );
$('#'+$(this).attr('id')+' .slider-next .slide-count .slide-total').html( $slideCount );
//prev
$('#'+$(this).attr('id')+' .slider-prev').click(function(e) {
if($(this).hasClass('inactive')) return false;
var $that = $(this);
//non looped slider
if($(this).parents('.swiper-container').attr('data-loop') != 'true') {
if( $(this).parents('.swiper-container').find('.swiper-slide-active').index()+1 == 1 && !$('html').hasClass('no-video')){
//make sure the animation is complete
var $timeout;
clearTimeout($timeout);
$timeout = setTimeout(function(){ $that.removeClass('inactive'); } ,700);
$(this).parents('.swiper-container').find('.swiper-wrapper').stop(true,false).css('transition','none').animate({
'left' : parseInt($(this).parents('.swiper-container').find('.swiper-wrapper').css('left')) + 20
},200,function(){
$(this).parents('.swiper-container').find('.swiper-wrapper').stop(true,false).css('transition','left,top');
$nectarSliders[i].swipeReset();
});
$(this).addClass('inactive');
}
}
e.preventDefault();
$nectarSliders[i].swipePrev();
});
//next
$('#'+$(this).attr('id')+' .slider-next').click(function(e) {
if($(this).hasClass('inactive')) return false;
var $that = $(this);
var $slideNum = $(this).parents('.swiper-container').find('.swiper-wrapper > div').length;
//non looped slider
if($(this).parents('.swiper-container').attr('data-loop') != 'true') {
if( $(this).parents('.swiper-container').find('.swiper-slide-active').index()+1 == $slideNum && !$('html').hasClass('no-video')) {
//make sure the animation is complete
var $timeout;
clearTimeout($timeout);
$timeout = setTimeout(function(){ $that.removeClass('inactive'); } ,700);
$(this).parents('.swiper-container').find('.swiper-wrapper').stop(true,false).css('transition','none').animate({
'left' : parseInt($(this).parents('.swiper-container').find('.swiper-wrapper').css('left')) - 20
},200,function(){
$(this).parents('.swiper-container').find('.swiper-wrapper').stop(true,false).css('transition','left,top');
$nectarSliders[i].swipeReset();
});
$(this).addClass('inactive');
}
}
e.preventDefault();
$nectarSliders[i].swipeNext();
});
}
//Clickable pagination
if($bullets != null && $('#'+$(this).attr('id') +' .swiper-wrapper > div').length > 1 ){
$('#'+$(this).attr('id')+' .slider-pagination .swiper-pagination-switch').click(function(){
$nectarSliders[i].swipeTo($(this).index());
});
}
});
//add class to first video slide
$('.swiper-wrapper').each(function(){
if($(this).find('.swiper-slide:nth-child(2) video').length > 0) $(this).find('.swiper-slide:nth-child(2)').addClass('first_video_slide');
});
//initial slide load
$('.nectar-slider-wrap').each(function(i){
var $sliderWrapCount = $('.nectar-slider-wrap').length;
var $that = $(this);
if($(this).find('.swiper-slide-active video').length > 0){
if(!$('html').hasClass('no-video')){
$(this).find('.swiper-slide-active:first video').get(0).addEventListener('canplay',function(){
showSliderControls();
resizeToCover();
sliderLoadIn($that);
captionTransition($nectarSliders[i]);
});
}
//ie8
else {
showSliderControls();
resizeToCover();
sliderLoadIn($that);
captionTransition($nectarSliders[i]);
}
}
else {
var $firstBg = $(this).find('.swiper-slide-active').attr('style');
var pattern = /url\(["']?([^'")]+)['"]?\)/;
var match = pattern.exec($firstBg);
if (match) {
var slideImg = new Image();
slideImg.src = match[1];
$(slideImg).load(function(){
showSliderControls();
sliderLoadIn($that);
captionTransition($nectarSliders[i]);
});
}
}
//mobile check
if(navigator.userAgent.match(/(Android|iPod|iPhone|iPad|IEMobile|Opera Mini)/)){
captionTransition($nectarSliders[i]);
showSliderControls();
resizeToCover();
$('.nectar-slider-wrap').find('.nectar-slider-loading').fadeOut(800,'easeInOutExpo');
$('.nectar-slider-wrap .mobile-video-image').show();
$('.nectar-slider-wrap .video-wrap').remove();
}
});
var $animating = false;
//fullscreen height
fullscreenSlider();
function fullscreenSlider(){
var $adminBarHeight = ($('#wpadminbar').length > 0) ? 28 : 0 ;
$('.nectar-slider-wrap').each(function(){
if($(this).attr('data-fullscreen') == 'true' && $(this).attr('data-full-width') == 'true') {
//first slider on page
if($(this).hasClass('first-section') && $(this).index() == 0){
$(this).find('.swiper-container').attr('data-height',$(window).height() - $(this).offset().top + 2);
}
//first parallax slider on page
else if($(this).parents('.parallax_slider_outer').length > 0 && $(this).parents('#full_width_portfolio').length == 0){
$(this).find('.swiper-container').attr('data-height',$(window).height() - $(this).parent().offset().top + 2);
}
//first portfolio slider on page
else if($(this).parents('#full_width_portfolio').length > 0 && $(this).attr('data-parallax') != 'true' && $(this).index() == 0){
$(this).find('.swiper-container').attr('data-height',$(window).height() - $(this).offset().top + 2);
}
//first portfolio parallax slider on page
else if($(this).parents('#full_width_portfolio').length > 0 && $(this).attr('data-parallax') == 'true'){
$(this).find('.swiper-container').attr('data-height',$(window).height() - $(this).offset().top + 2 );
}
//all others
else {
$(this).find('.swiper-container').attr('data-height',$(window).height());
}
}
});
}
$(window).resize(fullscreenSlider);
//responsive slider
var $sliderHeights = [];
var $existingSliders = [];
////get slider heights
$('.swiper-container').each(function(i){
$sliderHeights[i] = parseInt($(this).attr('data-height'));
$existingSliders[i] = $(this).parent().attr('id');
});
////helper function
function sliderColumnDesktopWidth(parentCol) {
var $parentColWidth = 1100;
var $columnNumberParsed = $(parentCol).attr('class').match(/\d+/);
if($columnNumberParsed == '2') { $parentColWidth = 170 }
else if($columnNumberParsed == '3') { $parentColWidth = 260 }
else if($columnNumberParsed == '4') { $parentColWidth = 340 }
else if($columnNumberParsed == '6') { $parentColWidth = 530 }
else if($columnNumberParsed == '8') { $parentColWidth = 700 }
else if($columnNumberParsed == '9') { $parentColWidth = 805 }
else if($columnNumberParsed == '10') { $parentColWidth = 916.3 }
else if($columnNumberParsed == '12') { $parentColWidth = 1100 }
return $parentColWidth;
}
sliderSize();
$(window).resize(sliderSize);
function sliderSize(){
//check for mobile first
if( window.innerWidth < 1000 && window.innerWidth > 690 ) {
//fullwidth sliders
$('.nectar-slider-wrap[data-full-width="true"]:not([data-fullscreen="true"])').each(function(i){
currentKey = $existingSliders.getKeyByValue($(this).attr('id'));
$(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey]/1.4 )
});
//column sliders
$('.nectar-slider-wrap[data-full-width="false"]').each(function(i){
currentKey = $existingSliders.getKeyByValue($(this).attr('id'));
var $currentSliderHeight = $sliderHeights[currentKey];
var $parentCol = ($(this).parents('.wpb_column').length > 0) ? $(this).parents('.wpb_column') : $(this).parents('.col') ;
if($parentCol.length == 0) $parentCol = $('.main-content');
var $parentColWidth = sliderColumnDesktopWidth($parentCol);
var $aspectRatio = $currentSliderHeight/$parentColWidth;
$(this).find('.swiper-container').attr('data-height',$aspectRatio*$parentCol.width());
});
//boxed sliders
$('.nectar-slider-wrap[data-full-width="boxed-full-width"]').each(function(i){
currentKey = $existingSliders.getKeyByValue($(this).attr('id'));
$(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey]/1.9 )
});
}
else if( window.innerWidth <= 690 ) {
//fullwidth sliders
$('.nectar-slider-wrap[data-full-width="true"]:not([data-fullscreen="true"])').each(function(i){
currentKey = $existingSliders.getKeyByValue($(this).attr('id'));
$(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey]/2.7 )
});
//column sliders
$('.nectar-slider-wrap[data-full-width="false"]').each(function(i){
currentKey = $existingSliders.getKeyByValue($(this).attr('id'));
var $currentSliderHeight = $sliderHeights[currentKey];
var $parentCol = ($(this).parents('.wpb_column').length > 0) ? $(this).parents('.wpb_column') : $(this).parents('.col') ;
if($parentCol.length == 0) $parentCol = $('.main-content');
var $parentColWidth = sliderColumnDesktopWidth($parentCol);
var $aspectRatio = $currentSliderHeight/$parentColWidth;
$(this).find('.swiper-container').attr('data-height',$aspectRatio*$parentCol.width());
});
//boxed sliders
$('.nectar-slider-wrap[data-full-width="boxed-full-width"]').each(function(i){
currentKey = $existingSliders.getKeyByValue($(this).attr('id'));
$(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey]/2.9 )
});
}
else if( window.innerWidth < 1300 && window.innerWidth >= 1000 ) {
//fullwidth sliders
$('.nectar-slider-wrap[data-full-width="true"]:not([data-fullscreen="true"])').each(function(i){
currentKey = $existingSliders.getKeyByValue($(this).attr('id'));
$(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey]/1.2 )
});
//column sliders
$('.nectar-slider-wrap[data-full-width="false"]').each(function(i){
currentKey = $existingSliders.getKeyByValue($(this).attr('id'));
var $currentSliderHeight = $sliderHeights[currentKey];
var $parentCol = ($(this).parents('.wpb_column').length > 0) ? $(this).parents('.wpb_column') : $(this).parents('.col') ;
if($parentCol.length == 0) $parentCol = $('.main-content');
var $parentColWidth = sliderColumnDesktopWidth($parentCol);
var $aspectRatio = $currentSliderHeight/$parentColWidth;
$(this).find('.swiper-container').attr('data-height',$aspectRatio*$parentCol.width());
});
//boxed sliders
$('.nectar-slider-wrap[data-full-width="boxed-full-width"]').each(function(i){
currentKey = $existingSliders.getKeyByValue($(this).attr('id'));
$(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey]/1.2 )
});
}
else {
//fullwidth sliders
$('.nectar-slider-wrap[data-full-width="true"]:not([data-fullscreen="true"])').each(function(i){
currentKey = $existingSliders.getKeyByValue($(this).attr('id'));
$(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey] )
});
//boxed sliders
$('.nectar-slider-wrap[data-full-width="false"], .nectar-slider-wrap[data-full-width="boxed-full-width"]').each(function(i){
currentKey = $existingSliders.getKeyByValue($(this).attr('id'));
$(this).find('.swiper-container').attr('data-height',$sliderHeights[currentKey] )
});
}
}
//slider height
var min_w = 1500; // minimum video width allowed
var vid_w_orig; // original video dimensions
var vid_h_orig;
vid_w_orig = 1280;
vid_h_orig = 720;
var $headerHeight = $('header').height()-1;
$(window).resize(function () { resizeToCover(); slideContentPos(); });
$(window).trigger('resize');
function resizeToCover() {
$('.nectar-slider-wrap').each(function(i){
//width resize
if($('body > #boxed').length == 0 && $('.nectar-slider-wrap[data-full-width="true"]').parent().attr('id') != 'portfolio-extra' && $(this).parents('#post-area:not(".span_12")').length == 0){
$('.nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .nectar-slider-wrap').css('left', -(($(window).width()-$smoothSrollWidth)/2 - $('.main-content').width()/2))+'px';
$('.nectar-slider-wrap[data-full-width="true"] .swiper-container, .nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .swiper-container, .parallax_slider_outer.first-section .nectar-slider-wrap').css('width',$(window).width());
}
else if( $('.nectar-slider-wrap[data-full-width="true"]').parent().attr('id') == 'portfolio-extra' && $('#full_width_portfolio').length != 0){
$('.nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .nectar-slider-wrap').css('left', -(($(window).width()-$smoothSrollWidth)/2 - $('.main-content').width()/2))+'px';
$('.nectar-slider-wrap[data-full-width="true"] .swiper-container, .nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .swiper-container, .parallax_slider_outer.first-section .nectar-slider-wrap').css('width',$(window).width());
}
else {
var $container = ($('body > #boxed').length == 0) ? '#post-area' : '.container-wrap';
//backup incase only slider is used with nothing else in boxed mode
if($($container).width() == '0' && $('body > #boxed').length > 0) $container = '#boxed';
$('.nectar-slider-wrap[data-full-width="true"] .swiper-container, .nectar-slider-wrap[data-full-width="true"], .parallax_slider_outer.first-section .swiper-container, .parallax_slider_outer.first-section .nectar-slider-wrap').css('width',$($container).width());
}
var $sliderHeight = parseInt($(this).find('.swiper-container').attr('data-height'));
var isFullWidthCompatible = ($(this).attr('data-full-width') == 'true') ? 'true' : 'false';
if($(this).parent().attr('id') == 'portfolio-extra' && $('#full_width_portfolio').length == 0 || $(this).parents('#post-area').length > 0) { isFullWidthCompatible = 'false'; };
var $sliderWidth = (isFullWidthCompatible == 'true') ? $(window).width()-$smoothSrollWidth : $(this).width();
$(this).parents('.parallax_slider_outer').css('height',$sliderHeight);
$(this).css('height',$sliderHeight);
$(this).find('.swiper-container, .swiper-slide').css({'height':$sliderHeight+2, 'top':'-1px'});
$(this).find('.swiper-container').css('width', $sliderWidth);
//$(this).find('.swiper-slide').css('width', $sliderWidth);
// set the video viewport to the window size
$(this).find('.video-wrap').width($sliderWidth+2);
$(this).find('.video-wrap').height($sliderHeight+2);
// use largest scale factor of horizontal/vertical
var scale_h = $sliderWidth / vid_w_orig;
var scale_v = ($sliderHeight - $headerHeight) / vid_h_orig;
var scale = scale_h > scale_v ? scale_h : scale_v;
//update minium width to never allow excess space
min_w = 1280/720 * ($sliderHeight+20);
// don't allow scaled width < minimum video width
if (scale * vid_w_orig < min_w) {scale = min_w / vid_w_orig;}
// now scale the video
$(this).find('video, .mejs-overlay, .mejs-poster').width(Math.ceil(scale * vid_w_orig +2));
$(this).find('video, .mejs-overlay, .mejs-poster').height(Math.ceil(scale * vid_h_orig +2));
// and center it by scrolling the video viewport
$(this).find('.video-wrap').scrollLeft(($(this).find('video').width() - $sliderWidth) / 2);
$(this).find('.swiper-slide').each(function(){
//video alignment
if($(this).find('.video-wrap').length > 0){
//align middle
if($(this).attr('data-bg-alignment') == 'center'){
$(this).find('.video-wrap, .mejs-overlay, .mejs-poster').scrollTop(($(this).find('video').height() - ($sliderHeight)) / 2);
}
//align bottom
else if($(this).attr('data-bg-alignment') == 'bottom'){
$(this).find('.video-wrap').scrollTop(($(this).find('video').height() - ($sliderHeight+2)));
}
//align top
else {
$(this).find('.video-wrap').scrollTop(0);
}
}
});
});
};
//caption transitions
function captionTransition(obj){
resizeToCover();
var $containerClass;
(typeof obj == 'undefined') ? $containerClass = 'div[id^=ns-id-]' : $containerClass = '#'+$(obj.container).parents('.nectar-slider-wrap').attr('id'); ;
var fromLeft = Math.abs(parseInt($($containerClass+' .swiper-wrapper').css('left')));
var currentSlide = Math.round(fromLeft/$($containerClass+' .swiper-slide').width());
var $slideNum = $($containerClass+':first .swiper-wrapper > div').length;
if(isNaN(currentSlide)) currentSlide = 0;
//make sure user isn't going back to same slide
if( $($containerClass+' .swiper-slide:nth-child('+ (currentSlide + 1) +')').find('.content *').length > 0 ) {
if($($containerClass+' .swiper-slide:nth-child('+ (currentSlide + 1) +')').find('.content *').css('opacity') != '0' && !$('html').hasClass('no-video')) {
//play video if there's one
playVideoBG(currentSlide + 1, $containerClass);
if(!$($containerClass+' .swiper-slide:nth-child('+ (currentSlide + 1) +')').hasClass('autorotate-shown')) {
return false;
} else {
$($containerClass+' .swiper-slide').removeClass('autorotate-shown');
}
}
}
//hide all
if(!$('html').hasClass('no-video')) {
$($containerClass+' .swiper-slide .content p, '+$containerClass+' .swiper-slide .content h2, '+$containerClass+' .swiper-slide .content .buttons').stop(true,true).animate({'opacity':0, 'padding-top': 25},1);
}
//pause video if there's one
$($containerClass+' .swiper-slide').each(function(){
if($(this).find('.video-wrap video').length > 0 && !$('html').hasClass('no-video')) { $(this).find('.video-wrap video').get(0).pause(); }
});
$($containerClass+' .swiper-slide:not(".swiper-slide-active")').each(function(){
if($(this).find('.video-wrap video').length > 0) {
if($(this).find('.video-wrap video').get(0).currentTime != 0 ) $(this).find('.video-wrap video').get(0).currentTime = 0;
}
});
if($($containerClass +' .swiper-container').attr('data-loop') == 'true') {
//webkit video fix
if( $($containerClass+' .swiper-slide-active').index()+1 == 2 && $($containerClass+' .swiper-slide-active video').length > 0 && !$('html').hasClass('no-video')) {
$($containerClass+' .swiper-slide:last-child').find('.video-wrap video').get(0).play();
$($containerClass+' .swiper-slide:last-child').find('.video-wrap video').get(0).pause();
}
if( $($containerClass+' .swiper-slide-active').index()+1 == $slideNum-1 && $($containerClass+' .swiper-slide-active video').length > 0 && !$('html').hasClass('no-video')) {
$($containerClass+' .swiper-slide:first-child').find('.video-wrap video').get(0).play();
$($containerClass+' .swiper-slide:first-child').find('.video-wrap video').get(0).pause();
}
if($($containerClass+' .swiper-slide-active').index()+1 != 2 && $($containerClass+' .swiper-slide:nth-child(2) video').length > 0 && !$('html').hasClass('no-video')) {
$($containerClass+' .swiper-slide:last-child').find('.video-wrap video').get(0).play();
$($containerClass+' .swiper-slide:last-child').find('.video-wrap video').get(0).pause();
$($containerClass+' .swiper-slide:nth-child(2) video').get(0).pause();
if($($containerClass+' .swiper-slide:nth-child(2) video').get(0).currentTime != 0 ) $($containerClass+' .swiper-slide:nth-child(2) video').get(0).currentTime = 0;
}
//also show duplicate slide if applicable
////first
if( $($containerClass+' .swiper-slide-active').index()+1 == $slideNum-1 ){
$($containerClass+' .swiper-slide:nth-child(1)').find('.content').children().each(function(i){
$(this).stop().delay(i*90).animate({
'opacity' : 1,
'padding-top' : 0
},{ duration: 400, easing: 'easeOutQuad'});
});
}
////last
if( $($containerClass+' .swiper-slide-active').index()+1 == 2 ){
$($containerClass+' .swiper-slide:nth-child('+ ($slideNum) + ')').find('.content').children().each(function(i){
$(this).stop().delay(i*90).animate({
'opacity' : 1,
'padding-top' : 0
},{ duration: 400, easing: 'easeOutQuad'});
});
}
}//if using loop
//play video if there's one
playVideoBG(currentSlide + 1, $containerClass);
//fadeIn active slide
$($containerClass+' .swiper-slide:nth-child('+ (currentSlide + 1) +')').find('.content').children().each(function(i){
$(this).stop().delay(i*90).animate({
'opacity' : 1,
'padding-top' : 0
},{ duration: 400, easing: 'easeOutQuad'});
});
//light and dark controls
if($($containerClass+' .swiper-slide:nth-child('+ (currentSlide + 1) +')').attr('data-color-scheme') == 'dark') {
$($containerClass).find('.slider-pagination').addClass('dark-cs');
$($containerClass).find('.slider-prev, .slider-next').addClass('dark-cs');
} else {
$($containerClass).find('.slider-pagination').removeClass('dark-cs');
$($containerClass).find('.slider-prev, .slider-next').removeClass('dark-cs');
}
$captionTrans++;
if($captionTrans == $('.swiper-wrapper').length) { $('div.first_video_slide').addClass('nulled') }
}
//used in caption transition
function playVideoBG(nthChild, containerClass){
if($(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.video-wrap video').length > 0){
if(!$('html').hasClass('no-video')) $(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.video-wrap video').get(0).play();
if(!$(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-overlay.mejs-overlay-play').hasClass('playing') && $(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-overlay.mejs-overlay-play').hasClass('mobile-played')) { $(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-overlay.mejs-overlay-play').addClass('playing'); }
if(!$(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-poster').hasClass('playing') && $(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-poster').hasClass('mobile-played')) $(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-poster').addClass('playing');
var $that = $(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-overlay.mejs-overlay-play');
var $that2 = $(containerClass+' .swiper-slide:nth-child('+ (nthChild) +')').find('.mejs-poster');
if($that.hasClass('playing') && $that.hasClass('mobile-played')) {
setTimeout(function(){ $that.addClass('behind-buttons'); $that2.addClass('behind-buttons');},200);
} else {
$that.removeClass('behind-buttons'); $that2.removeClass('behind-buttons');
}
}
}
var $startingSlide = null;
function slideContentPos(){
$('.swiper-wrapper').each(function(){
//etxra space if first slider in section
var $extraHeight = ($(this).parents('.nectar-slider-wrap').hasClass('first-section') || $(this).parents('.parallax_slider_outer').hasClass('first-section')) ? 30 : 0;
var $sliderHeight = parseInt($(this).parents('.swiper-container').attr('data-height'));
$(this).find('.swiper-slide').each(function(){
var $contentHeight = $(this).find('.content').height();
var $contentItems = $(this).find('.content > *').length;
if($(this).find('.content > *').css('padding-top') == '25px') $contentHeight = $contentHeight - 25*$contentItems;
if($(this).attr('data-y-pos') == 'top'){
var $topHeight = ($contentHeight/2) < (($sliderHeight/4) - 30) ? (($sliderHeight/4) - ($contentHeight/2)) + 20 : $sliderHeight/8;
$(this).find('.content').css('top', $topHeight + 'px');
}
else if($(this).attr('data-y-pos') == 'middle') {
$(this).find('.content').css('top', ($sliderHeight/2) - ($contentHeight/2) + 'px');
}
else {
if($contentHeight > 180) {
$(this).find('.content').css('top', ($sliderHeight/2) - ($contentHeight/10) + 'px');
} else {
$(this).find('.content').css('top', ($sliderHeight/2) + ($contentHeight/9) + 'px');
}
}
});
});
}
function showSliderControls() {
$('.swiper-container .slider-prev, .swiper-container .slider-next, .slider-pagination').animate({'opacity':1},550,'easeOutSine');
}
var sliderLength = $('.swiper-container').length;
var sliderLoadedLength = 0;
function sliderLoadIn(slider) {
slider.find('.nectar-slider-loading').fadeOut(800,'easeInOutExpo');
///make sure to init smooth scrolling after slider height exists
var $smoothActive = $('body').attr('data-smooth-scrolling');
if( $smoothActive == 1 && $(window).width() > 690 && $('body').outerHeight(true) > $(window).height() && $('#ascrail2000').length == 0 && !navigator.userAgent.match(/(Android|iPod|iPhone|iPad|IEMobile|Opera Mini)/)){ niceScrollInit(); resizeToCover(); }
//check for sliders in tabbed
sliderLoadedLength++;
if($('.tabbed').find('.swiper-container').length > 0 && sliderLoadedLength == sliderLength) {
setTimeout(function(){ $('.tabbed > ul li:first-child a').click(); }, 200);
}
}
//play video user is hovering over
$('.swiper-slide').mouseover(function(){
if($(this).find('video').length > 0 && $(this).find('video').get(0).paused == true && $animating == false){
$(this).find('video').get(0).play();
}
});
//mobile play event
$('body').on('click', '.mejs-overlay.mejs-overlay-play',function(){
$(this).toggleClass('playing');
$(this).addClass('mobile-played');
$(this).parent().find('.mejs-poster').toggleClass('playing');
$(this).parent().find('.mejs-poster').addClass('mobile-played');
var $that = $(this);
var $that2 = $(this).parent().find('.mejs-poster');
if($(this).hasClass('playing') && $(this).hasClass('mobile-played')) {
setTimeout(function(){ $that.addClass('behind-buttons'); $that2.addClass('behind-buttons'); },200);
} else {
setTimeout(function(){ $that.removeClass('behind-buttons'); $that2.removeClass('behind-buttons'); },1);
}
});
//autoplay
var autoplay = [];
var sliderAutoplayCount = -1;
var $sliderHeight = parseInt($(this).find('.swiper-container').attr('data-height'));
var portfolioHeaderHeight = ($('.project-title.parallax-effect').length > 0) ? 100 : 0;
$('.nectar-slider-wrap').each(function(i){
var $autoplayVal = $(this).attr('data-autorotate');
var $that = $(this);
var $sliderNum = i;
if(typeof $autoplayVal !='undefined' && $autoplayVal.length != '0' && parseInt($autoplayVal)) {
nectarSlideRotateInit($that,$autoplayVal,$sliderNum);
}
});
function nectarSlideRotateInit(slider,interval,sliderNum){
autoplay[sliderAutoplayCount] = setInterval(function(){ nectarSlideRotate(slider, sliderNum); } ,interval);
$('#'+slider.attr('id')).attr('autoplay-id',sliderAutoplayCount);
$('#'+slider.attr('id') + ' a.slider-prev, #'+slider.attr('id') + ' a.slider-next, #' + slider.attr('id') + ' .slider-pagination span').click(function(e){
if(typeof e.clientY != 'undefined'){
clearInterval(autoplay[$('#'+slider.attr('id')).attr('autoplay-id')]);
}
});
sliderAutoplayCount++;
}
function nectarSlideRotate(slider, sliderNum){
if($nectarSliders[sliderNum].activeIndex + 1 < $(slider).find('.swiper-wrapper > div.swiper-slide').length){
$nectarSliders[sliderNum].swipeNext();
} else {
$nectarSliders[sliderNum].swipeTo(0,800);
}
}
function clearAutoplay(e){
var $autoplayVal = $('#'+$(e.container).parent().attr('id')).attr('data-autorotate');
if(typeof $autoplayVal !='undefined' && $autoplayVal.length != '0' && parseInt($autoplayVal)) {
clearInterval(autoplay[$('#'+$(e.container).parent().attr('id')).attr('autoplay-id')]);
}
}
var animationQueue = null;
function sliderArrowCount(e){
//cache slider obj
var $obj = e;
$animating = true;
var $slideNum = $($obj.container).find('.swiper-wrapper > div').length;
$activeIndex = ($($obj.container).attr('data-loop') == 'true') ? $obj.activeIndex : $obj.activeIndex + 1;
//add slide counts
$($obj.container).find('.slider-prev .slide-count .slide-current').html( $activeIndex );
$($obj.container).find('.slider-next .slide-count .slide-current').html( $activeIndex );
if($($obj.container).attr('data-loop') == 'true'){
//duplicate first slide
if( $($obj.container).find('.swiper-slide-active').index()+1 == 1) {
$($obj.container).find('.slider-next .slide-count .slide-current, .slider-prev .slide-count .slide-current').html( $slideNum - 2 );
}
//duplicate last slide
else if( $($obj.container).find('.swiper-slide-active').index()+1 == $slideNum) {
$($obj.container).find('.slider-next .slide-count .slide-current, .slider-prev .slide-count .slide-current').html( 1 );
}
}
if($obj.activeIndex >= 10) { $($obj.container).find('.slider-next .slide-count .slide-current').addClass('double-digits'); } else {
$($obj.container).find('.slider-next .slide-count .slide-current').removeClass('double-digits');
}
$($obj.container).find('.swiper-slide:not(".swiper-slide-active")').each(function(){
if($(this).find('.video-wrap video').length > 0) {
if($(this).find('.video-wrap video').get(0).currentTime != 0 ) $(this).find('.video-wrap video').get(0).currentTime = 0;
}
});
//don't allow swiping on duplicate transition
if($($obj.container).attr('data-loop') == 'true'){
if($obj.previousIndex == 1 && $obj.activeIndex == 0 || $obj.previousIndex == $slideNum - 2 && $obj.activeIndex == $slideNum - 1 ){
$('.swiper-slide').addClass('duplicate-transition');
}
}
clearTimeout(animationQueue);
animationQueue = setTimeout(function(){ $animating = false; $('.swiper-slide').removeClass('duplicate-transition'); },800)
}
//functions to add or remove slider for webkit parallax fix
function hideSlider() {
if( $(window).scrollTop()/($sliderHeight + portfolioHeaderHeight + 125) >= 1){
$('.parallax_slider_outer .nectar-slider-wrap, .project-title.parallax-effect').css('visibility','hidden').hide();
$(window).bind('scroll',showSlider);
$(window).unbind('scroll',hideSlider);
}
}
function showSlider() {
if( $(window).scrollTop()/($sliderHeight + portfolioHeaderHeight + 125) <= 1){
$('.parallax_slider_outer .nectar-slider-wrap, .project-title.parallax-effect').css('visibility','visible').show();
slideContentPos();
resizeToCover();
//show content on current slide - could have been hidden from autorotate when slider was hidden
if($('.parallax_slider_outer').length > 0) {
var fromLeft = Math.abs(parseInt($('.parallax_slider_outer .nectar-slider-wrap .swiper-wrapper').css('left')));
var currentSlide = Math.round(fromLeft/$('.parallax_slider_outer .nectar-slider-wrap .swiper-slide').width());
$('.parallax_slider_outer .swiper-wrapper .swiper-slide:eq(' + currentSlide + ')').find('.content').children().each(function(i){
$(this).stop(true,true).css({ 'opacity' : 1, 'padding-top' : 0 });
});
$('.parallax_slider_outer .swiper-wrapper .swiper-slide:eq(' + currentSlide + ')').addClass('autorotate-shown');
}
$(window).bind('scroll',hideSlider);
$(window).unbind('scroll',showSlider);
}
}
function sliderCorrectDisplayCheck() {
if( $(window).scrollTop()/($sliderHeight + portfolioHeaderHeight + 125) >= 1){
hideSlider();
}
$(window).unbind('scroll',sliderCorrectDisplayCheck);
}
var $sliderHeight = parseInt($('.parallax_slider_outer.first-section .swiper-container').attr('data-height'));
var $adminBarHeight = ($('#wpadminbar').length > 0) ? 28 : 0;
function sliderParallaxInit() {
if($('#portfolio-extra').length > 0 && $('#full_width_portfolio').length == 0) { return false; }
$(window).scroll(function(){
if($('#boxed').length == 0) {
if(navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) { return false; }
$('.parallax_slider_outer.first-section .nectar-slider-wrap[data-parallax="true"]').stop(true,true).transition({ y: $(window).scrollTop()*-.2 },0);
$('.parallax_slider_outer.first-section .swiper-slide:not(".static"):not(".caption-no-fade") .content, .parallax_slider_outer.first-section .nectar-slider-wrap[data-parallax="true"] .swiper-container .slider-next, .parallax_slider_outer.first-section .nectar-slider-wrap[data-parallax="true"] .swiper-container .slider-prev').stop(true,true).transition({ y: $(window).scrollTop()*-.14 },0);
$('#full_width_portfolio .project-title.parallax-effect').transition({ y: $(window).scrollTop()*-.2 },0);
$('.parallax_slider_outer.first-section .swiper-slide:not(".caption-no-fade") .content, .parallax_slider_outer.first-section .nectar-slider-wrap[data-parallax="true"] .swiper-container .slider-next, .parallax_slider_outer.first-section .nectar-slider-wrap[data-parallax="true"] .swiper-container .slider-prev').css('opacity', 1-($(window).scrollTop()/($sliderHeight-120)) );
}
});
//hide slider to not mess up parallax section
var portfolioHeaderHeight = ($('.project-title.parallax-effect').length > 0) ? 100 : 0;
function displayParallaxSliderInit() {
if( $(window).scrollTop()/($sliderHeight + portfolioHeaderHeight + 90) >= 1){
$(window).bind('scroll', hideSlider);
$(window).unbind('scroll',showSlider);
} else {
$(window).bind('scroll', showSlider);
$(window).unbind('scroll', hideSlider);
}
}
displayParallaxSliderInit();
$(window).bind('scroll',sliderCorrectDisplayCheck);
$('.page-header-no-bg, #page-header-wrap, #page-header-bg').remove();
$('.project-title').addClass('parallax-effect').css({
'top': $('#header-space').outerHeight() + $adminBarHeight + 'px'
});
//caption alignment if portfolio fullwidth parallax
if($('.project-title.parallax-effect').length > 0) {
$('.parallax_slider_outer.first-section .swiper-slide .content, .nectar-slider-wrap.first-section .swiper-slide .content').css('margin-top','0px');
$('.swiper-container .slider-prev, .swiper-container .slider-next').css('margin-top','-28px');
}
//if using wooCommerce sitewide notice
if($('.demo_store').length > 0) $('.project-title.parallax-effect').css('margin-top','-25px');
if($('#full_width_portfolio').length > 0){
$('.parallax_slider_outer.first-section').css('margin-top','93px');
}
$(window).resize(function(){
$sliderHeight = parseInt($('.parallax_slider_outer.first-section .swiper-container').attr('data-height'));
$('.project-title').css({
'top': $('#header-space').outerHeight() + $adminBarHeight + 'px'
});
});
}
//parallax
if($('.parallax_slider_outer').length > 0 && !navigator.userAgent.match(/(Android|iPod|iPhone|iPad|IEMobile|Opera Mini)/)){
sliderParallaxInit();
} else if($('.parallax_slider_outer').length > 0 && navigator.userAgent.match(/(Android|iPod|iPhone|iPad|IEMobile|Opera Mini)/)) {
$('.project-title').addClass('parallax-effect').css({
'top': $('#header-space').outerHeight() + $adminBarHeight + 'px'
});
}
function niceScrollInit(){
$("html").niceScroll({
scrollspeed: 60,
mousescrollstep: 40,
cursorwidth: 15,
cursorborder: 0,
cursorcolor: '#2D3032',
cursorborderradius: 6,
autohidemode: false,
horizrailenabled: false
});
if($('#boxed').length == 0){
$('body, body #header-outer, body #header-secondary-outer, body #search-outer').css('padding-right','16px');
}
$('html').addClass('no-overflow-y');
}
//pause video backgrounds if popup video player is started
$('.portfolio-items a.pp:contains(Video), .swiper-container .buttons a.pp').click(function(){
$('.swiper-slide').each(function(){
if($(this).find('.video-wrap video').length > 0) {
$(this).find('.video-wrap video').get(0).pause();
}
});
});
//solid button hover effect
$.cssHooks.backgroundColor = {
get: function(elem) {
if (elem.currentStyle)
var bg = elem.currentStyle["backgroundColor"];
else if (window.getComputedStyle)
var bg = document.defaultView.getComputedStyle(elem,
null).getPropertyValue("background-color");
if (bg.search("rgb") == -1)
return bg;
else {
bg = bg.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
}
}
}
function shadeColor(color, shade) {
var colorInt = parseInt(color.substring(1),16);
var R = (colorInt & 0xFF0000) >> 16;
var G = (colorInt & 0x00FF00) >> 8;
var B = (colorInt & 0x0000FF) >> 0;
R = R + Math.floor((shade/255)*R);
G = G + Math.floor((shade/255)*G);
B = B + Math.floor((shade/255)*B);
var newColorInt = (R<<16) + (G<<8) + (B);
var newColorStr = "#"+newColorInt.toString(16);
return newColorStr;
}
$('.swiper-slide').each(function(){
$(this).find('.solid_color').each(function(){
var $currentColor = $(this).find('a').css('background-color');
var $hoverColor = shadeColor($currentColor, -16);
$(this).find('a').hover(function(){
$(this).attr('style','background-color:'+$hoverColor+'!important;');
},function(){
$(this).attr('style','');
});
});
});
function prettyPhotoInit(){
$(".nectar-slider-wrap a[rel^='prettyPhoto']").prettyPhoto({
theme: 'dark_rounded',
allow_resize: true,
default_width: 690,
opacity: 0.85,
animation_speed: 'normal',
default_height: 388,
social_tools: '',
markup: '<div class="pp_pic_holder"> \
<div class="ppt"> </div> \
<div class="pp_details"> \
<div class="pp_nav"> \
<a href="#" class="pp_arrow_previous"> <i class="icon-salient-left-arrow-thin icon-default-style"></i> </a> \
<a href="#" class="pp_arrow_next"> <i class="icon-salient-right-arrow-thin icon-default-style"></i> </a> \
<p class="currentTextHolder">0/0</p> \
</div> \
<a class="pp_close" href="#">Close</a> \
</div> \
<div class="pp_content_container"> \
<div class="pp_left"> \
<div class="pp_right"> \
<div class="pp_content"> \
<div class="pp_fade"> \
<div class="pp_hoverContainer"> \
</div> \
<div id="pp_full_res"></div> \
</div> \
</div> \
</div> \
</div> \
</div> \
</div> \
<div class="pp_loaderIcon"></div> \
<div class="pp_overlay"></div>'
});
}
});
| calebcauthon/twoshakesofhappy_www | wp-content/themes/salient/js/nectar-slider.js | JavaScript | gpl-2.0 | 143,574 |
<?php
/* themes/bootstrap/templates/input/form-element-label.html.twig */
class __TwigTemplate_2354354cef59de02f70fe1144f1a4083879f91af2173de96ec49e7588478ad73 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())
{
$tags = array("set" => 20, "if" => 28);
$filters = array();
$functions = array();
try {
$this->env->getExtension('sandbox')->checkSecurity(
array('set', 'if'),
array(),
array()
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setTemplateFile($this->getTemplateName());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 20
$context["classes"] = array(0 => "control-label", 1 => ((( // line 22
(isset($context["title_display"]) ? $context["title_display"] : null) == "after")) ? ("option") : ("")), 2 => ((( // line 23
(isset($context["title_display"]) ? $context["title_display"] : null) == "invisible")) ? ("sr-only") : ("")), 3 => (( // line 24
(isset($context["required"]) ? $context["required"] : null)) ? ("js-form-required") : ("")), 4 => (( // line 25
(isset($context["required"]) ? $context["required"] : null)) ? ("form-required") : ("")));
// line 28
if (( !twig_test_empty((isset($context["title"]) ? $context["title"] : null)) || (isset($context["required"]) ? $context["required"] : null))) {
// line 29
echo "<label";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => (isset($context["classes"]) ? $context["classes"] : null)), "method"), "html", null, true));
echo ">";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["element"]) ? $context["element"] : null), "html", null, true));
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["title"]) ? $context["title"] : null), "html", null, true));
// line 30
if ((isset($context["description"]) ? $context["description"] : null)) {
// line 31
echo "<p class=\"help-block\">";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["description"]) ? $context["description"] : null), "html", null, true));
echo "</p>";
}
// line 33
echo "</label>";
// line 34
if ((((isset($context["required"]) ? $context["required"] : null) && ((isset($context["title_display"]) ? $context["title_display"] : null) == "before")) || ((isset($context["title_display"]) ? $context["title_display"] : null) == "after"))) {
// line 35
echo "<span class=\"form-required\">*</span>";
}
}
}
public function getTemplateName()
{
return "themes/bootstrap/templates/input/form-element-label.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 68 => 35, 66 => 34, 64 => 33, 59 => 31, 57 => 30, 51 => 29, 49 => 28, 47 => 25, 46 => 24, 45 => 23, 44 => 22, 43 => 20,);
}
}
/* {#*/
/* /***/
/* * @file*/
/* * Default theme implementation for a form element label.*/
/* **/
/* * Available variables:*/
/* * - element: an input element.*/
/* * - title: The label's text.*/
/* * - title_display: Elements title_display setting.*/
/* * - description: element description.*/
/* * - required: An indicator for whether the associated form element is required.*/
/* * - attributes: A list of HTML attributes for the label.*/
/* **/
/* * @see template_preprocess_form_element_label()*/
/* **/
/* * @ingroup templates*/
/* *//* */
/* #}*/
/* {%-*/
/* set classes = [*/
/* 'control-label',*/
/* title_display == 'after' ? 'option',*/
/* title_display == 'invisible' ? 'sr-only',*/
/* required ? 'js-form-required',*/
/* required ? 'form-required',*/
/* ]*/
/* -%}*/
/* {%- if title is not empty or required -%}*/
/* <label{{ attributes.addClass(classes) }}>{{ element }}{{ title }}*/
/* {%- if description -%}*/
/* <p class="help-block">{{ description }}</p>*/
/* {%- endif -%}*/
/* </label>*/
/* {%- if required and title_display == 'before' or title_display == 'after'-%}*/
/* <span class="form-required">*</span>*/
/* {%- endif -%}*/
/* {%- endif -%}*/
/* */
| deryfebriantara/symfonyId | sites/default/files/php/twig/5f824940_form-element-label.html.twig_e0c8a63f3b0b48ed3558d578ef47b789cd3f238cc627840ac50fc59ef423cc38/9aaa7c0638dd7945f276f16f3231b99db32ab31f72831a88b8a28085933b6980.php | PHP | gpl-2.0 | 5,618 |
<?php
/*
* @deprecated since 6.0, the classname Tx_Extbase_Persistence_Exception_UnsupportedRelation and this file is obsolete
* and will be removed with 6.2. The class was renamed and is now located at:
* typo3/sysext/extbase/Classes/Persistence/Generic/Exception/UnsupportedRelationException.php
*/
require_once \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('extbase') . 'Classes/Persistence/Generic/Exception/UnsupportedRelationException.php';
?> | tonglin/pdPm | public_html/typo3_src-6.1.7/typo3/sysext/extbase/Classes/Persistence/Exception/UnsupportedRelation.php | PHP | gpl-2.0 | 467 |
<?php
namespace duncan3dc\Serial;
use duncan3dc\Serial\Exceptions\PhpException;
class Php extends AbstractSerial
{
/**
* Convert an array to a php serialized string.
*
* {@inheritDoc}
*/
public static function encode($array)
{
if (count($array) < 1) {
return "";
}
try {
$string = serialize($array);
} catch (\Exception $e) {
throw new PhpException("Serialize Error: " . $e->getMessage());
}
return $string;
}
/**
* Convert a php serialized string to an array.
*
* {@inheritDoc}
*/
public static function decode($string)
{
if (!$string) {
return [];
}
try {
$array = unserialize($string);
} catch (\Exception $e) {
throw new PhpException("Serialize Error: " . $e->getMessage());
}
return $array;
}
}
| jeedom/plugin-sonos | vendor/duncan3dc/serial/src/Php.php | PHP | gpl-2.0 | 950 |
/**
* @author Eric D. Dill eddill@ncsu.edu
* @author James D. Martin jdmartin@ncsu.edu
* Copyright © 2010-2013 North Carolina State University. All rights reserved
*/
package email;
import java.util.Properties;
public class PropertiesFactory {
public static Properties getGmailProperties() {
Properties gmail = new Properties();
gmail.put("mail.smtp.auth", "true");
gmail.put("mail.smtp.starttls.enable", "true");
gmail.put("mail.smtp.host", "smtp.gmail.com");
gmail.put("mail.smtp.port", "587");
return gmail;
}
}
| TheMartinLab/GlobalPackages | misc/email/PropertiesFactory.java | Java | gpl-2.0 | 536 |
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use app\models\Lookup;
/* @var $this yii\web\View */
/* @var $searchModel app\models\PostSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = '文章管理';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="post-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('新建文章', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
// ['class' => 'yii\grid\SerialColumn'],
'id',
'title',
'content:ntext',
'tags:ntext',
[
'attribute' => 'status',
'value' =>
function($model) {
return Lookup::item("PostStatus", $model->status);
}
],
//'status',
// 'create_time:datetime',
// 'update_time:datetime',
'author.username',
['class' => 'yii\grid\ActionColumn'],
],
]);
?>
</div>
| liuayong/Yii2Blog | views/post/index.php | PHP | gpl-2.0 | 1,072 |
#include "config.h"
#include "libssl.hh"
#ifdef HAVE_LIBSSL
#include <atomic>
#include <fstream>
#include <cstring>
#include <mutex>
#include <pthread.h>
#include <openssl/conf.h>
#include <openssl/err.h>
#include <openssl/ocsp.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#ifdef HAVE_LIBSODIUM
#include <sodium.h>
#endif /* HAVE_LIBSODIUM */
#if (OPENSSL_VERSION_NUMBER < 0x1010000fL || (defined LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2090100fL)
/* OpenSSL < 1.1.0 needs support for threading/locking in the calling application. */
#include "lock.hh"
static std::vector<std::mutex> openssllocks;
extern "C" {
static void openssl_pthreads_locking_callback(int mode, int type, const char *file, int line)
{
if (mode & CRYPTO_LOCK) {
openssllocks.at(type).lock();
} else {
openssllocks.at(type).unlock();
}
}
static unsigned long openssl_pthreads_id_callback()
{
return (unsigned long)pthread_self();
}
}
static void openssl_thread_setup()
{
openssllocks = std::vector<std::mutex>(CRYPTO_num_locks());
CRYPTO_set_id_callback(&openssl_pthreads_id_callback);
CRYPTO_set_locking_callback(&openssl_pthreads_locking_callback);
}
static void openssl_thread_cleanup()
{
CRYPTO_set_locking_callback(nullptr);
openssllocks.clear();
}
#endif /* (OPENSSL_VERSION_NUMBER < 0x1010000fL || (defined LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2090100fL) */
static std::atomic<uint64_t> s_users;
static int s_ticketsKeyIndex{-1};
static int s_countersIndex{-1};
static int s_keyLogIndex{-1};
void registerOpenSSLUser()
{
if (s_users.fetch_add(1) == 0) {
#ifdef HAVE_OPENSSL_INIT_CRYPTO
/* load the default configuration file (or one specified via OPENSSL_CONF),
which can then be used to load engines */
OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, nullptr);
#endif
#if (OPENSSL_VERSION_NUMBER < 0x1010000fL || (defined LIBRESSL_VERSION_NUMBER && LIBRESSL_VERSION_NUMBER < 0x2090100fL))
SSL_load_error_strings();
OpenSSL_add_ssl_algorithms();
openssl_thread_setup();
#endif
s_ticketsKeyIndex = SSL_CTX_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
if (s_ticketsKeyIndex == -1) {
throw std::runtime_error("Error getting an index for tickets key");
}
s_countersIndex = SSL_CTX_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
if (s_countersIndex == -1) {
throw std::runtime_error("Error getting an index for counters");
}
s_keyLogIndex = SSL_CTX_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
if (s_keyLogIndex == -1) {
throw std::runtime_error("Error getting an index for TLS key logging");
}
}
}
void unregisterOpenSSLUser()
{
if (s_users.fetch_sub(1) == 1) {
#if (OPENSSL_VERSION_NUMBER < 0x1010000fL || (defined LIBRESSL_VERSION_NUMBER && LIBRESSL_VERSION_NUMBER < 0x2090100fL))
ERR_free_strings();
EVP_cleanup();
CONF_modules_finish();
CONF_modules_free();
CONF_modules_unload(1);
CRYPTO_cleanup_all_ex_data();
openssl_thread_cleanup();
#endif
}
}
void* libssl_get_ticket_key_callback_data(SSL* s)
{
SSL_CTX* sslCtx = SSL_get_SSL_CTX(s);
if (sslCtx == nullptr) {
return nullptr;
}
return SSL_CTX_get_ex_data(sslCtx, s_ticketsKeyIndex);
}
void libssl_set_ticket_key_callback_data(SSL_CTX* ctx, void* data)
{
SSL_CTX_set_ex_data(ctx, s_ticketsKeyIndex, data);
}
int libssl_ticket_key_callback(SSL *s, OpenSSLTLSTicketKeysRing& keyring, unsigned char keyName[TLS_TICKETS_KEY_NAME_SIZE], unsigned char *iv, EVP_CIPHER_CTX *ectx, HMAC_CTX *hctx, int enc)
{
if (enc) {
const auto key = keyring.getEncryptionKey();
if (key == nullptr) {
return -1;
}
return key->encrypt(keyName, iv, ectx, hctx);
}
bool activeEncryptionKey = false;
const auto key = keyring.getDecryptionKey(keyName, activeEncryptionKey);
if (key == nullptr) {
/* we don't know this key, just create a new ticket */
return 0;
}
if (key->decrypt(iv, ectx, hctx) == false) {
return -1;
}
if (!activeEncryptionKey) {
/* this key is not active, please encrypt the ticket content with the currently active one */
return 2;
}
return 1;
}
static long libssl_server_name_callback(SSL* ssl, int* al, void* arg)
{
(void) al;
(void) arg;
if (SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name)) {
return SSL_TLSEXT_ERR_OK;
}
return SSL_TLSEXT_ERR_NOACK;
}
static void libssl_info_callback(const SSL *ssl, int where, int ret)
{
SSL_CTX* sslCtx = SSL_get_SSL_CTX(ssl);
if (sslCtx == nullptr) {
return;
}
TLSErrorCounters* counters = reinterpret_cast<TLSErrorCounters*>(SSL_CTX_get_ex_data(sslCtx, s_countersIndex));
if (counters == nullptr) {
return;
}
if (where & SSL_CB_ALERT) {
const long lastError = ERR_peek_last_error();
switch (ERR_GET_REASON(lastError)) {
#ifdef SSL_R_DH_KEY_TOO_SMALL
case SSL_R_DH_KEY_TOO_SMALL:
++counters->d_dhKeyTooSmall;
break;
#endif /* SSL_R_DH_KEY_TOO_SMALL */
case SSL_R_NO_SHARED_CIPHER:
++counters->d_noSharedCipher;
break;
case SSL_R_UNKNOWN_PROTOCOL:
++counters->d_unknownProtocol;
break;
case SSL_R_UNSUPPORTED_PROTOCOL:
#ifdef SSL_R_VERSION_TOO_LOW
case SSL_R_VERSION_TOO_LOW:
#endif /* SSL_R_VERSION_TOO_LOW */
++counters->d_unsupportedProtocol;
break;
case SSL_R_INAPPROPRIATE_FALLBACK:
++counters->d_inappropriateFallBack;
break;
case SSL_R_UNKNOWN_CIPHER_TYPE:
++counters->d_unknownCipherType;
break;
case SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE:
++counters->d_unknownKeyExchangeType;
break;
case SSL_R_UNSUPPORTED_ELLIPTIC_CURVE:
++counters->d_unsupportedEC;
break;
default:
break;
}
}
}
void libssl_set_error_counters_callback(std::unique_ptr<SSL_CTX, void(*)(SSL_CTX*)>& ctx, TLSErrorCounters* counters)
{
SSL_CTX_set_ex_data(ctx.get(), s_countersIndex, counters);
SSL_CTX_set_info_callback(ctx.get(), libssl_info_callback);
}
int libssl_ocsp_stapling_callback(SSL* ssl, const std::map<int, std::string>& ocspMap)
{
auto pkey = SSL_get_privatekey(ssl);
if (pkey == nullptr) {
return SSL_TLSEXT_ERR_NOACK;
}
/* look for an OCSP response for the corresponding private key type (RSA, ECDSA..) */
const auto& data = ocspMap.find(EVP_PKEY_base_id(pkey));
if (data == ocspMap.end()) {
return SSL_TLSEXT_ERR_NOACK;
}
/* we need to allocate a copy because OpenSSL will free the pointer passed to SSL_set_tlsext_status_ocsp_resp() */
void* copy = OPENSSL_malloc(data->second.size());
if (copy == nullptr) {
return SSL_TLSEXT_ERR_NOACK;
}
memcpy(copy, data->second.data(), data->second.size());
SSL_set_tlsext_status_ocsp_resp(ssl, copy, data->second.size());
return SSL_TLSEXT_ERR_OK;
}
static bool libssl_validate_ocsp_response(const std::string& response)
{
auto responsePtr = reinterpret_cast<const unsigned char *>(response.data());
std::unique_ptr<OCSP_RESPONSE, void(*)(OCSP_RESPONSE*)> resp(d2i_OCSP_RESPONSE(nullptr, &responsePtr, response.size()), OCSP_RESPONSE_free);
if (resp == nullptr) {
throw std::runtime_error("Unable to parse OCSP response");
}
int status = OCSP_response_status(resp.get());
if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
throw std::runtime_error("OCSP response status is not successful: " + std::to_string(status));
}
std::unique_ptr<OCSP_BASICRESP, void(*)(OCSP_BASICRESP*)> basic(OCSP_response_get1_basic(resp.get()), OCSP_BASICRESP_free);
if (basic == nullptr) {
throw std::runtime_error("Error getting a basic OCSP response");
}
if (OCSP_resp_count(basic.get()) != 1) {
throw std::runtime_error("More than one single response in an OCSP basic response");
}
auto singleResponse = OCSP_resp_get0(basic.get(), 0);
if (singleResponse == nullptr) {
throw std::runtime_error("Error getting a single response from the basic OCSP response");
}
int reason;
ASN1_GENERALIZEDTIME* revTime = nullptr;
ASN1_GENERALIZEDTIME* thisUpdate = nullptr;
ASN1_GENERALIZEDTIME* nextUpdate = nullptr;
auto singleResponseStatus = OCSP_single_get0_status(singleResponse, &reason, &revTime, &thisUpdate, &nextUpdate);
if (singleResponseStatus != V_OCSP_CERTSTATUS_GOOD) {
throw std::runtime_error("Invalid status for OCSP single response (" + std::to_string(singleResponseStatus) + ")");
}
if (thisUpdate == nullptr || nextUpdate == nullptr) {
throw std::runtime_error("Error getting validity of OCSP single response");
}
auto validityResult = OCSP_check_validity(thisUpdate, nextUpdate, /* 5 minutes of leeway */ 5 * 60, -1);
if (validityResult == 0) {
throw std::runtime_error("OCSP single response is not yet, or no longer, valid");
}
return true;
}
std::map<int, std::string> libssl_load_ocsp_responses(const std::vector<std::string>& ocspFiles, std::vector<int> keyTypes)
{
std::map<int, std::string> ocspResponses;
if (ocspFiles.size() > keyTypes.size()) {
throw std::runtime_error("More OCSP files than certificates and keys loaded!");
}
size_t count = 0;
for (const auto& filename : ocspFiles) {
std::ifstream file(filename, std::ios::binary);
std::string content;
while(file) {
char buffer[4096];
file.read(buffer, sizeof(buffer));
if (file.bad()) {
file.close();
throw std::runtime_error("Unable to load OCSP response from '" + filename + "'");
}
content.append(buffer, file.gcount());
}
file.close();
try {
libssl_validate_ocsp_response(content);
ocspResponses.insert({keyTypes.at(count), std::move(content)});
}
catch (const std::exception& e) {
throw std::runtime_error("Error checking the validity of OCSP response from '" + filename + "': " + e.what());
}
++count;
}
return ocspResponses;
}
int libssl_get_last_key_type(std::unique_ptr<SSL_CTX, void(*)(SSL_CTX*)>& ctx)
{
#ifdef HAVE_SSL_CTX_GET0_PRIVATEKEY
auto pkey = SSL_CTX_get0_privatekey(ctx.get());
#else
auto temp = std::unique_ptr<SSL, void(*)(SSL*)>(SSL_new(ctx.get()), SSL_free);
if (!temp) {
return -1;
}
auto pkey = SSL_get_privatekey(temp.get());
#endif
if (!pkey) {
return -1;
}
return EVP_PKEY_base_id(pkey);
}
#ifdef HAVE_OCSP_BASIC_SIGN
bool libssl_generate_ocsp_response(const std::string& certFile, const std::string& caCert, const std::string& caKey, const std::string& outFile, int ndays, int nmin)
{
const EVP_MD* rmd = EVP_sha256();
auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fopen(certFile.c_str(), "r"), fclose);
if (!fp) {
throw std::runtime_error("Unable to open '" + certFile + "' when loading the certificate to generate an OCSP response");
}
auto cert = std::unique_ptr<X509, void(*)(X509*)>(PEM_read_X509_AUX(fp.get(), nullptr, nullptr, nullptr), X509_free);
fp = std::unique_ptr<FILE, int(*)(FILE*)>(fopen(caCert.c_str(), "r"), fclose);
if (!fp) {
throw std::runtime_error("Unable to open '" + caCert + "' when loading the issuer certificate to generate an OCSP response");
}
auto issuer = std::unique_ptr<X509, void(*)(X509*)>(PEM_read_X509_AUX(fp.get(), nullptr, nullptr, nullptr), X509_free);
fp = std::unique_ptr<FILE, int(*)(FILE*)>(fopen(caKey.c_str(), "r"), fclose);
if (!fp) {
throw std::runtime_error("Unable to open '" + caKey + "' when loading the issuer key to generate an OCSP response");
}
auto issuerKey = std::unique_ptr<EVP_PKEY, void(*)(EVP_PKEY*)>(PEM_read_PrivateKey(fp.get(), nullptr, nullptr, nullptr), EVP_PKEY_free);
fp.reset();
auto bs = std::unique_ptr<OCSP_BASICRESP, void(*)(OCSP_BASICRESP*)>(OCSP_BASICRESP_new(), OCSP_BASICRESP_free);
auto thisupd = std::unique_ptr<ASN1_TIME, void(*)(ASN1_TIME*)>(X509_gmtime_adj(nullptr, 0), ASN1_TIME_free);
auto nextupd = std::unique_ptr<ASN1_TIME, void(*)(ASN1_TIME*)>(X509_time_adj_ex(nullptr, ndays, nmin * 60, nullptr), ASN1_TIME_free);
auto cid = std::unique_ptr<OCSP_CERTID, void(*)(OCSP_CERTID*)>(OCSP_cert_to_id(rmd, cert.get(), issuer.get()), OCSP_CERTID_free);
OCSP_basic_add1_status(bs.get(), cid.get(), V_OCSP_CERTSTATUS_GOOD, 0, nullptr, thisupd.get(), nextupd.get());
if (OCSP_basic_sign(bs.get(), issuer.get(), issuerKey.get(), rmd, nullptr, OCSP_NOCERTS) != 1) {
throw std::runtime_error("Error while signing the OCSP response");
}
auto resp = std::unique_ptr<OCSP_RESPONSE, void(*)(OCSP_RESPONSE*)>(OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs.get()), OCSP_RESPONSE_free);
auto bio = std::unique_ptr<BIO, void(*)(BIO*)>(BIO_new_file(outFile.c_str(), "wb"), BIO_vfree);
if (!bio) {
throw std::runtime_error("Error opening file for writing the OCSP response");
}
// i2d_OCSP_RESPONSE_bio(bio.get(), resp.get()) is unusable from C++ because of an invalid cast
ASN1_i2d_bio((i2d_of_void*)i2d_OCSP_RESPONSE, bio.get(), (unsigned char*)resp.get());
return true;
}
#endif /* HAVE_OCSP_BASIC_SIGN */
LibsslTLSVersion libssl_tls_version_from_string(const std::string& str)
{
if (str == "tls1.0") {
return LibsslTLSVersion::TLS10;
}
if (str == "tls1.1") {
return LibsslTLSVersion::TLS11;
}
if (str == "tls1.2") {
return LibsslTLSVersion::TLS12;
}
if (str == "tls1.3") {
return LibsslTLSVersion::TLS13;
}
throw std::runtime_error("Unknown TLS version '" + str);
}
const std::string& libssl_tls_version_to_string(LibsslTLSVersion version)
{
static const std::map<LibsslTLSVersion, std::string> versions = {
{ LibsslTLSVersion::TLS10, "tls1.0" },
{ LibsslTLSVersion::TLS11, "tls1.1" },
{ LibsslTLSVersion::TLS12, "tls1.2" },
{ LibsslTLSVersion::TLS13, "tls1.3" }
};
const auto& it = versions.find(version);
if (it == versions.end()) {
throw std::runtime_error("Unknown TLS version (" + std::to_string((int)version) + ")");
}
return it->second;
}
bool libssl_set_min_tls_version(std::unique_ptr<SSL_CTX, void(*)(SSL_CTX*)>& ctx, LibsslTLSVersion version)
{
#if defined(HAVE_SSL_CTX_SET_MIN_PROTO_VERSION) || defined(SSL_CTX_set_min_proto_version)
/* These functions have been introduced in 1.1.0, and the use of SSL_OP_NO_* is deprecated
Warning: SSL_CTX_set_min_proto_version is a function-like macro in OpenSSL */
int vers;
switch(version) {
case LibsslTLSVersion::TLS10:
vers = TLS1_VERSION;
break;
case LibsslTLSVersion::TLS11:
vers = TLS1_1_VERSION;
break;
case LibsslTLSVersion::TLS12:
vers = TLS1_2_VERSION;
break;
case LibsslTLSVersion::TLS13:
#ifdef TLS1_3_VERSION
vers = TLS1_3_VERSION;
#else
return false;
#endif /* TLS1_3_VERSION */
break;
default:
return false;
}
if (SSL_CTX_set_min_proto_version(ctx.get(), vers) != 1) {
return false;
}
return true;
#else
long vers = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
switch(version) {
case LibsslTLSVersion::TLS10:
break;
case LibsslTLSVersion::TLS11:
vers |= SSL_OP_NO_TLSv1;
break;
case LibsslTLSVersion::TLS12:
vers |= SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1;
break;
case LibsslTLSVersion::TLS13:
vers |= SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2;
break;
default:
return false;
}
long options = SSL_CTX_get_options(ctx.get());
SSL_CTX_set_options(ctx.get(), options | vers);
return true;
#endif
}
OpenSSLTLSTicketKeysRing::OpenSSLTLSTicketKeysRing(size_t capacity)
{
d_ticketKeys.set_capacity(capacity);
}
OpenSSLTLSTicketKeysRing::~OpenSSLTLSTicketKeysRing()
{
}
void OpenSSLTLSTicketKeysRing::addKey(std::shared_ptr<OpenSSLTLSTicketKey> newKey)
{
WriteLock wl(&d_lock);
d_ticketKeys.push_front(newKey);
}
std::shared_ptr<OpenSSLTLSTicketKey> OpenSSLTLSTicketKeysRing::getEncryptionKey()
{
ReadLock rl(&d_lock);
return d_ticketKeys.front();
}
std::shared_ptr<OpenSSLTLSTicketKey> OpenSSLTLSTicketKeysRing::getDecryptionKey(unsigned char name[TLS_TICKETS_KEY_NAME_SIZE], bool& activeKey)
{
ReadLock rl(&d_lock);
for (auto& key : d_ticketKeys) {
if (key->nameMatches(name)) {
activeKey = (key == d_ticketKeys.front());
return key;
}
}
return nullptr;
}
size_t OpenSSLTLSTicketKeysRing::getKeysCount()
{
ReadLock rl(&d_lock);
return d_ticketKeys.size();
}
void OpenSSLTLSTicketKeysRing::loadTicketsKeys(const std::string& keyFile)
{
bool keyLoaded = false;
std::ifstream file(keyFile);
try {
do {
auto newKey = std::make_shared<OpenSSLTLSTicketKey>(file);
addKey(newKey);
keyLoaded = true;
}
while (!file.fail());
}
catch (const std::exception& e) {
/* if we haven't been able to load at least one key, fail */
if (!keyLoaded) {
throw;
}
}
file.close();
}
void OpenSSLTLSTicketKeysRing::rotateTicketsKey(time_t now)
{
auto newKey = std::make_shared<OpenSSLTLSTicketKey>();
addKey(newKey);
}
OpenSSLTLSTicketKey::OpenSSLTLSTicketKey()
{
if (RAND_bytes(d_name, sizeof(d_name)) != 1) {
throw std::runtime_error("Error while generating the name of the OpenSSL TLS ticket key");
}
if (RAND_bytes(d_cipherKey, sizeof(d_cipherKey)) != 1) {
throw std::runtime_error("Error while generating the cipher key of the OpenSSL TLS ticket key");
}
if (RAND_bytes(d_hmacKey, sizeof(d_hmacKey)) != 1) {
throw std::runtime_error("Error while generating the HMAC key of the OpenSSL TLS ticket key");
}
#ifdef HAVE_LIBSODIUM
sodium_mlock(d_name, sizeof(d_name));
sodium_mlock(d_cipherKey, sizeof(d_cipherKey));
sodium_mlock(d_hmacKey, sizeof(d_hmacKey));
#endif /* HAVE_LIBSODIUM */
}
OpenSSLTLSTicketKey::OpenSSLTLSTicketKey(ifstream& file)
{
file.read(reinterpret_cast<char*>(d_name), sizeof(d_name));
file.read(reinterpret_cast<char*>(d_cipherKey), sizeof(d_cipherKey));
file.read(reinterpret_cast<char*>(d_hmacKey), sizeof(d_hmacKey));
if (file.fail()) {
throw std::runtime_error("Unable to load a ticket key from the OpenSSL tickets key file");
}
#ifdef HAVE_LIBSODIUM
sodium_mlock(d_name, sizeof(d_name));
sodium_mlock(d_cipherKey, sizeof(d_cipherKey));
sodium_mlock(d_hmacKey, sizeof(d_hmacKey));
#endif /* HAVE_LIBSODIUM */
}
OpenSSLTLSTicketKey::~OpenSSLTLSTicketKey()
{
#ifdef HAVE_LIBSODIUM
sodium_munlock(d_name, sizeof(d_name));
sodium_munlock(d_cipherKey, sizeof(d_cipherKey));
sodium_munlock(d_hmacKey, sizeof(d_hmacKey));
#else
OPENSSL_cleanse(d_name, sizeof(d_name));
OPENSSL_cleanse(d_cipherKey, sizeof(d_cipherKey));
OPENSSL_cleanse(d_hmacKey, sizeof(d_hmacKey));
#endif /* HAVE_LIBSODIUM */
}
bool OpenSSLTLSTicketKey::nameMatches(const unsigned char name[TLS_TICKETS_KEY_NAME_SIZE]) const
{
return (memcmp(d_name, name, sizeof(d_name)) == 0);
}
int OpenSSLTLSTicketKey::encrypt(unsigned char keyName[TLS_TICKETS_KEY_NAME_SIZE], unsigned char *iv, EVP_CIPHER_CTX *ectx, HMAC_CTX *hctx) const
{
memcpy(keyName, d_name, sizeof(d_name));
if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) != 1) {
return -1;
}
if (EVP_EncryptInit_ex(ectx, TLS_TICKETS_CIPHER_ALGO(), nullptr, d_cipherKey, iv) != 1) {
return -1;
}
if (HMAC_Init_ex(hctx, d_hmacKey, sizeof(d_hmacKey), TLS_TICKETS_MAC_ALGO(), nullptr) != 1) {
return -1;
}
return 1;
}
bool OpenSSLTLSTicketKey::decrypt(const unsigned char* iv, EVP_CIPHER_CTX *ectx, HMAC_CTX *hctx) const
{
if (HMAC_Init_ex(hctx, d_hmacKey, sizeof(d_hmacKey), TLS_TICKETS_MAC_ALGO(), nullptr) != 1) {
return false;
}
if (EVP_DecryptInit_ex(ectx, TLS_TICKETS_CIPHER_ALGO(), nullptr, d_cipherKey, iv) != 1) {
return false;
}
return true;
}
std::unique_ptr<SSL_CTX, void(*)(SSL_CTX*)> libssl_init_server_context(const TLSConfig& config,
std::map<int, std::string>& ocspResponses)
{
auto ctx = std::unique_ptr<SSL_CTX, void(*)(SSL_CTX*)>(SSL_CTX_new(SSLv23_server_method()), SSL_CTX_free);
int sslOptions =
SSL_OP_NO_SSLv2 |
SSL_OP_NO_SSLv3 |
SSL_OP_NO_COMPRESSION |
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
SSL_OP_SINGLE_DH_USE |
SSL_OP_SINGLE_ECDH_USE;
if (!config.d_enableTickets || config.d_numberOfTicketsKeys == 0) {
/* for TLS 1.3 this means no stateless tickets, but stateful tickets might still be issued,
which is something we don't want. */
sslOptions |= SSL_OP_NO_TICKET;
/* really disable all tickets */
#ifdef HAVE_SSL_CTX_SET_NUM_TICKETS
SSL_CTX_set_num_tickets(ctx.get(), 0);
#endif /* HAVE_SSL_CTX_SET_NUM_TICKETS */
}
if (config.d_sessionTimeout > 0) {
SSL_CTX_set_timeout(ctx.get(), config.d_sessionTimeout);
}
if (config.d_preferServerCiphers) {
sslOptions |= SSL_OP_CIPHER_SERVER_PREFERENCE;
#ifdef SSL_OP_PRIORITIZE_CHACHA
sslOptions |= SSL_OP_PRIORITIZE_CHACHA;
#endif /* SSL_OP_PRIORITIZE_CHACHA */
}
SSL_CTX_set_options(ctx.get(), sslOptions);
if (!libssl_set_min_tls_version(ctx, config.d_minTLSVersion)) {
throw std::runtime_error("Failed to set the minimum version to '" + libssl_tls_version_to_string(config.d_minTLSVersion));
}
#ifdef SSL_CTX_set_ecdh_auto
SSL_CTX_set_ecdh_auto(ctx.get(), 1);
#endif
if (config.d_maxStoredSessions == 0) {
/* disable stored sessions entirely */
SSL_CTX_set_session_cache_mode(ctx.get(), SSL_SESS_CACHE_OFF);
}
else {
/* use the internal built-in cache to store sessions */
SSL_CTX_set_session_cache_mode(ctx.get(), SSL_SESS_CACHE_SERVER);
SSL_CTX_sess_set_cache_size(ctx.get(), config.d_maxStoredSessions);
}
/* we need to set this callback to acknowledge the server name sent by the client,
otherwise it will not stored in the session and will not be accessible when the
session is resumed, causing SSL_get_servername to return nullptr */
SSL_CTX_set_tlsext_servername_callback(ctx.get(), &libssl_server_name_callback);
std::vector<int> keyTypes;
/* load certificate and private key */
for (const auto& pair : config.d_certKeyPairs) {
if (SSL_CTX_use_certificate_chain_file(ctx.get(), pair.first.c_str()) != 1) {
ERR_print_errors_fp(stderr);
throw std::runtime_error("An error occurred while trying to load the TLS server certificate file: " + pair.first);
}
if (SSL_CTX_use_PrivateKey_file(ctx.get(), pair.second.c_str(), SSL_FILETYPE_PEM) != 1) {
ERR_print_errors_fp(stderr);
throw std::runtime_error("An error occurred while trying to load the TLS server private key file: " + pair.second);
}
if (SSL_CTX_check_private_key(ctx.get()) != 1) {
ERR_print_errors_fp(stderr);
throw std::runtime_error("The key from '" + pair.second + "' does not match the certificate from '" + pair.first + "'");
}
/* store the type of the new key, we might need it later to select the right OCSP stapling response */
auto keyType = libssl_get_last_key_type(ctx);
if (keyType < 0) {
throw std::runtime_error("The key from '" + pair.second + "' has an unknown type");
}
keyTypes.push_back(keyType);
}
if (!config.d_ocspFiles.empty()) {
try {
ocspResponses = libssl_load_ocsp_responses(config.d_ocspFiles, keyTypes);
}
catch(const std::exception& e) {
throw std::runtime_error("Unable to load OCSP responses: " + std::string(e.what()));
}
}
if (!config.d_ciphers.empty() && SSL_CTX_set_cipher_list(ctx.get(), config.d_ciphers.c_str()) != 1) {
throw std::runtime_error("The TLS ciphers could not be set: " + config.d_ciphers);
}
#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
if (!config.d_ciphers13.empty() && SSL_CTX_set_ciphersuites(ctx.get(), config.d_ciphers13.c_str()) != 1) {
throw std::runtime_error("The TLS 1.3 ciphers could not be set: " + config.d_ciphers13);
}
#endif /* HAVE_SSL_CTX_SET_CIPHERSUITES */
return ctx;
}
#ifdef HAVE_SSL_CTX_SET_KEYLOG_CALLBACK
static void libssl_key_log_file_callback(const SSL* ssl, const char* line)
{
SSL_CTX* sslCtx = SSL_get_SSL_CTX(ssl);
if (sslCtx == nullptr) {
return;
}
auto fp = reinterpret_cast<FILE*>(SSL_CTX_get_ex_data(sslCtx, s_keyLogIndex));
if (fp == nullptr) {
return;
}
fprintf(fp, "%s\n", line);
fflush(fp);
}
#endif /* HAVE_SSL_CTX_SET_KEYLOG_CALLBACK */
std::unique_ptr<FILE, int(*)(FILE*)> libssl_set_key_log_file(std::unique_ptr<SSL_CTX, void(*)(SSL_CTX*)>& ctx, const std::string& logFile)
{
#ifdef HAVE_SSL_CTX_SET_KEYLOG_CALLBACK
auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fopen(logFile.c_str(), "a"), fclose);
if (!fp) {
throw std::runtime_error("Error opening TLS log file '" + logFile + "'");
}
SSL_CTX_set_ex_data(ctx.get(), s_keyLogIndex, fp.get());
SSL_CTX_set_keylog_callback(ctx.get(), &libssl_key_log_file_callback);
return fp;
#else
return std::unique_ptr<FILE, int(*)(FILE*)>(nullptr, fclose);
#endif /* HAVE_SSL_CTX_SET_KEYLOG_CALLBACK */
}
std::string libssl_get_error_string()
{
BIO *mem = BIO_new(BIO_s_mem());
ERR_print_errors(mem);
char *p;
size_t len = BIO_get_mem_data(mem, &p);
std::string msg(p, len);
// replace newlines by /
if (msg.back() == '\n') {
msg.pop_back();
}
std::replace(msg.begin(), msg.end(), '\n', '/');
BIO_free(mem);
return msg;
}
#endif /* HAVE_LIBSSL */
| rgacogne/pdns | pdns/libssl.cc | C++ | gpl-2.0 | 25,123 |
<?php
/*
Language: English - en (US)
Author: www.activehelper.com
Homepage: http://www.activehelper.com
Live Help Version: 2.1+
translation in Greek language by www.citiview.gr
Language codes and locale directories confirm to the ISO639 two letter standard.
Please consult the Live Help Language Setting options for the appropriate code.
Please forward your translated file and appropriate directories to support@activehelper.com
if you would like your translation to be included in the Live Help download, this allows other
users to use your translation. Thank you for supporting our Live Help software.
You are permitted to modify the language file from below this point as appropriate.
*/
$chat_transcript_label = 'Αντίγραφο συνομιλίων';
$print_chat_transcript_label = 'Εκτύπωση αντιγράφου συνομιλίων';
$welcome_to_label = 'Καλώς ήρθατε στο';
$our_live_help_label = 'Live Help.';
$enter_guest_details_label = 'Θα χαρούμε να απαντήσουμε σε κάθε σας ερώτηση ή απορία. Παρακαλώ συμπληρώστε την φόρμα για να συνεχίσετε στην συνομιλία.';
$else_send_message_label = 'Εναλλακτικά μπορείτε να αφήσετε ένα';
$offline_message_label = 'Μήνυμα';
$continue_label = 'Εναρξη συνομιλίας';
$select_language_label = 'Γλώσσα';
$logout_label = 'Αποσύδεση';
$name_label = 'Όνομα';
$email_label = 'Email';
$department_label = 'Τμήμα';
$send_copy_session ='Αποστολή αντιγράφου της συνομιλίας στο email σας.';
$chat_transcript ='Ο κωδικός συνομιλίας σας (ChatID: ';
$thank_you_patience_label = 'Η αίτηση συνομιλίας σας έχει προωθηθεί στον πρώτο διαθέσιμο τεχνικό μας. Μπορείτε να ακυρώσετε πατώντας "Αποσύνδεση".';
$currently_label = 'Είστε στη θέση αναμονής νούμερο';
$users_waiting_label = ' στη σειρά.';
$refresh_label = 'Ανανέωση';
$connecting_label = 'Συνδέεστε με ένα εκπρόσωπο';
$please_wait_heavy_load_label = 'Η ομάδα υποστήριξης δεν μπορεί να ανταποκριθεί άμεσα λόγω φόρτου εργασίας. Η αίτησή σας θα απαντηθεί το συντομότερο δυνατόν. Ευχαριστούμε για την υπομονή σας';
$continue_waiting_label = 'Συνέχεια αναμονής';
$offline_support_label = 'Υποστήριξη Offline';
$redirecting_label = 'Θα μεταφερθείτε στην offline υποστήριξη σε 15 δευτερόλεπτα';
$now_chatting_with_label = 'Συνομιλείτε με τον';
$joined_conversation_label = 'συνδέθηκε στην συζήτηση.';
$unfortunately_offline_label = '';
$fill_details_below_label = 'Παρακαλω συμπληρώστε τα ακόλουθα στοιχεία και θα επικοινωνήσουμε μαζί σας ';
$leave_msg_label = 'Αφήστε μήνυμα';
$your_name_label = 'Όνομα';
$your_email_label = 'E-mail';
$your_phone_label = 'τηλέφωνο';
$your_company_label = 'εταιρεία';
$message_label = 'Ερώτηση';
$security_code_label = 'Κωδικός ασφαλείας';
$thank_you_enquiry_label = 'Ευχαριστούμε για το μήνυμα σας.';
$contacted_soon_label = 'Θα επικοινωνήσουμε μαζί σας το συντομότερο δυνατόν.';
$send_msg_label = 'Αποστολή μηνύματος';
$send_another_msg_label = 'Στείλτε και άλλο μήνυμα';
$close_window_label = 'Κλείσιμο παραθύρου';
$send_copy_label = 'Αποστολή αντιγράφου αυτού του μηνύματος.';
$invalid_email_error_label = 'Η διεύθυνση e-mail που εισάγατε είναι λανθασμένη .';
$invalid_security_error_label = 'Ο κωδικός ασφαλείας που εισάγατε είναι λανθασμένος.';
$empty_user_details_label = 'Παρακαλώ εισάγετε το όνομα σας και το email σας.';
$empty_email_details_label = 'Παρακαλώ εισάγετε το email σας.';
$empty_valid_email_details_label = 'Παρακαλώ εισάγετε ένα πραγματικό email.';
$logout_message_label = 'Ευχαριστούμε που επικοινωνήσατε μαζί μας.';
$further_assistance_label = 'Ήταν ευχαρίστησή μας να σας εξυπηρετήσουμε σήμερα. Αν χρειάζεστε περαιτέρω βοήθεια μη διστάσετε να επικοινωνήσετε με την ομάδα υποστήριξης.';
$below_print_transcript_label = 'Παρακάτω μπορείτε να τυπώσετε ένα αντίγραφο τις συνομιλίας για μελλοντική χρήση';
$please_rate_service_label = 'Θα χαρούμε αν αξιολογήσετε την επίδοση του εκπροσώπου μας. Αυτό θα μας βοηθήσει στο να γίνουμε καλύτεροι και να σας προσφέρουμε ποιοτικότερες υπηρεσίες.';
$rate_service_label = 'Βαθμολογήστε την εμπειρία υποστήριξης που είχατε';
$excellent_label = 'Άριστη';
$very_good_label = 'Πολύ Καλή';
$good_label = 'Καλή';
$fair_label = 'Μέτρια';
$poor_label = 'Φτωχή';
$rate_label = 'Βαθμός';
$rating_thank_you_label = 'Ευχαριστούμε για την βαθμολογία, εκτιμούμε την άποψη σας.';
$closed_user_message_label ='Το αίτημα υποστήριξης έχει κλείσει.';
$_service_label = 'Για τη βελτίωση της εξυπηρέτησης των πελατών μας, παρακαλούμε αποσυνδεθείτε και βαθμολογείστε το';
$rate_operator_label = 'Χειριστής';
$ignore_user_message_label = 'Το αίτημά σας για στήριξη έχει απορριφθεί από το προσωπικό μας ,παρακαλούμε να κλείσετε το παράθυρο ή να αποσυθνδεθείτε από το σύστημα Live υποστήριξης. Δεν είστε εξουσιοδοτημένοι να επανασυνδεθείτε με την παρούσα υπηρεσία αυτή την δεδομένη στιγμή.';
$also_send_message_label = 'Αν αντιμετωπίζετε πρόβλημα σύνδεσης με την υπηρεσία Live Υποστήριξης, μπορείτε να στείλετε email στο τεχνικό μας τμήμα';
$cookies_error_label = 'Παρακαλούμε να ενεργοποιήσετε τα cookies';
$cookies_enable_label = 'Θα πρέπει να ενεργοποιήσετε τα cookies για να συνομιλήσετε με ένα χειριστή της Live υποστήριξης.';
$cookies_else_label = 'Αν έχετε ενεργοποιήσει τα cookies στο πρόγραμμα περιήγησής σας παρακαλώ στείλτε email στο τμημα υποστήριξης, καθώς μπορεί να υπάρχει ένα ζήτημα με την εφαρμογή Live υποστήριξης.';
$typing_status_label = 'Typing Status';
$live_support_timer_label = 'χρόνος';
$welcome_note_i18 = "Καλώς ήρθατε στην Live υποστήριξη. Mία στιγμή παρακαλώ.";
$Offline_msg_from_email = "Είμαστε τώρα αποσυνδεδεμένοι!";
$waiting_gif = "Αναμονή...";
$user_typing_gif = "Εκτυπώνω...";
$ref_nomber_message_i18 = "Αριθμός αναφοράς σας για αυτή τη συζήτηση είναι ";
?>
| ihooper/bluespan | sites/all/modules/contrib/activehelper_livehelp/server/i18n/gr/lang_guest_gr.php | PHP | gpl-2.0 | 8,129 |
<?php
/**
* Hello Model for Hello World Component
*
* @package Joomla.Tutorials
* @subpackage Components
* @link http://docs.joomla.org/Developing_a_Model-View-Controller_Component_-_Part_4
* @license GNU/GPL
*/
// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.application.component.model');
/**
* Hello Hello Model
*
* @package Joomla.Tutorials
* @subpackage Components
*/
class ModelsModelModel extends JModel
{
/**
* Constructor that retrieves the ID from the request
*
* @access public
* @return void
*/
function __construct()
{
parent::__construct();
$array = JRequest::getVar('cid', 0, '', 'array');
$o = JRequest::getVar('cat', 0, 'POST', 'int');
$this->setId((int)$array[0], $o);
}
/**
* Method to set the Category identifier
*
* @access public
* @param int Category identifier
* @return void
*/
function setId($id, $o)
{
// Set id and wipe data
$this->_id = $id;
$this->_origin = $o;
$this->_data = null;
}
function getOrigin(){
return $this->_origin;
}
/**
* Method to get a Category
* @return object with data
*/
function &getData()
{
// Load the data
if (empty( $this->_data )) {
$query = ' SELECT * FROM #__models '.
' WHERE id = '.$this->_id;
$this->_db->setQuery( $query );
$this->_data = $this->_db->loadObject();
}
if (!$this->_data) {
$this->_data = new stdClass();
$this->_data->id = 0;
$this->_data->name= null;
$this->_data->published = 0;
$this->_data->category = 0;
$this->_data->gender = 0;
$this->_data->age = 0;
$this->_data->size = 0;
$this->_data->height = 0;
$this->_data->weight = 0;
$this->_data->bust = 0;
$this->_data->waist = 0;
$this->_data->hips = 0;
$this->_data->shoes = 0;
$this->_data->eyes = 0;
$this->_data->hair = 0;
}
return $this->_data;
}
function getLists(){
$row =& JTable::getInstance('model', 'Table');
$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
$id = $cid[0];
$row->load($id);
$lists = array();
$categories = array();
//listar categorias
$db =& JFactory::getDBO();
$query = "SELECT count(*) FROM #__models_cat";
$db->setQuery( $query );
$total = $db->loadResult();
$query = "SELECT * FROM #__models_cat";
$db->setQuery( $query );
$row2 = $db->loadObjectList();
if ($db->getErrorNum()) {
echo $db->stderr();
return false;
}
foreach($row2 as $category){
$categories[$category->id]=array('value' => $category->id,
'text' => $category->name);
}
$lists['models'] = JHTML::_('select.genericList',
$categories, 'category', 'class="inputbox" '. '', 'value',
'text', $row->category );
$gender = array(
'0' => array('value' => 'f',
'text' => 'Female'),
'1' => array('value' => 'm',
'text' => 'Male')
);
$lists['gender'] = JHTML::_('select.genericlist',$gender,'gender',
'class="inputbox" ', 'value',
'text', $row->gender);
$lists['published'] = JHTML::_('select.booleanlist', 'published',
'class="inputbox"', $row->published);
$lists['upload'] = JHTML::_('behavior.modal');
$lists['editPhotos'] = 'index.php?option=com_models&controller=photo&cid[]='. $row->id;
return $lists;
}
/**
* Method to store a record
*
* @access public
* @return boolean True on success
*/
function store()
{
$row =& $this->getTable('Model');
$data = JRequest::get( 'post' );
// Bind the form fields to the hello table
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Make sure the hello record is valid
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Store the web link table to the database
if (!$row->store()) {
$this->setError( $row->getErrorMsg() );
return false;
}
return true;
}
function publish($publish)
{
$cid = JRequest::getVar( 'cid', array(), '', 'array' );
$row =& $this->getTable('Model');
$row->publish($cid, $publish);
return true;
}
/**
* Method to delete record(s)
*
* @access public
* @return boolean True on success
*/
function delete()
{
$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
$row =& $this->getTable('Model');
if (count( $cids )) {
foreach($cids as $cid) {
if (!$row->delete( $cid )) {
$this->setError( $row->getErrorMsg() );
return false;
}
}
}
return true;
}
} | lucashappy/ibmodels | administrator/components/com_models/models/model.php | PHP | gpl-2.0 | 4,887 |
package main
import (
"flag"
)
var BASE_SIZE = 10
var AUTO_SPAWN = true
var EXIF_DIR = "./exif_tool/exiftool"
var TEMP_DIR = "./temp"
func main() {
port := flag.String("port", "9999", "Enter a server port number")
root_dir := flag.String("root", "/", "Enter default root path")
auth_name := flag.String("auth-name", "admin", "Enter auth name")
auth_pass := flag.String("auth-pass", "admin", "Enter auth pass")
max_procs := flag.Int("max-prox", 10, "Enter number of ExifTool processes")
exif_dir := flag.String("exif-path", "./exif_tool/exiftool", "Enter path to exiftool")
auto_spawn := flag.Bool("auto-spawn", false, "Should I autospawn processes")
flag.Parse()
BASE_SIZE = *max_procs
AUTO_SPAWN = *auto_spawn
EXIF_DIR = *exif_dir
r := RESTHandler{}
r.Run(*port, *auth_name, *auth_pass, *root_dir)
}
| MichaelLeachim/CoExif | main.go | GO | gpl-2.0 | 819 |
/*
* Copyright (c) 2010 Mark Liversedge (liversedge@gmail.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "Athlete.h"
#include "Context.h"
#include "Colors.h"
#include "RideCache.h"
#include "RideCacheModel.h"
#include "RideItem.h"
#include "RideNavigator.h"
#include "RideNavigatorProxy.h"
#include "SearchFilterBox.h"
#include "TabView.h"
#include "HelpWhatsThis.h"
#include <QtGui>
#include <QString>
#include <QTreeView>
#include <QStyle>
#include <QStyleFactory>
#include <QScrollBar>
RideNavigator::RideNavigator(Context *context, bool mainwindow) : context(context), active(false), _groupBy(-1)
{
// get column headings
// default column layouts etc
_columns = QString(tr("*|Workout Code|Date|"));
_widths = QString("0|100|100|");
_sortByIndex = 2;
_sortByOrder = 0;
currentColumn = -1;
this->mainwindow = mainwindow;
_groupBy = -1;
fontHeight = QFontMetrics(QFont()).height();
ColorEngine ce(context);
reverseColor = ce.reverseColor;
currentItem = NULL;
init = false;
mainLayout = new QVBoxLayout(this);
mainLayout->setSpacing(0);
if (mainwindow) mainLayout->setContentsMargins(0,0,0,0);
else mainLayout->setContentsMargins(2,2,2,2); // so we can resize!
searchFilter = new SearchFilter(this);
searchFilter->setSourceModel(context->athlete->rideCache->model()); // filter out/in search results
groupByModel = new GroupByModel(this);
groupByModel->setSourceModel(searchFilter);
sortModel = new BUGFIXQSortFilterProxyModel(this);
sortModel->setSourceModel(groupByModel);
sortModel->setDynamicSortFilter(true);
if (!mainwindow) {
searchFilterBox = new SearchFilterBox(this, context, false);
mainLayout->addWidget(searchFilterBox);
HelpWhatsThis *searchHelp = new HelpWhatsThis(searchFilterBox);
searchFilterBox->setWhatsThis(searchHelp->getWhatsThisText(HelpWhatsThis::SearchFilterBox));
}
// get setup
tableView = new RideTreeView;
delegate = new NavigatorCellDelegate(this);
tableView->setAnimated(true);
tableView->setItemDelegate(delegate);
tableView->setModel(sortModel);
tableView->setSortingEnabled(true);
tableView->setAlternatingRowColors(false);
tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); // read-only
mainLayout->addWidget(tableView);
tableView->expandAll();
tableView->header()->setCascadingSectionResizes(true); // easier to resize this way
tableView->setContextMenuPolicy(Qt::CustomContextMenu);
tableView->header()->setStretchLastSection(false);
tableView->header()->setMinimumSectionSize(0);
tableView->header()->setFocusPolicy(Qt::NoFocus);
#ifdef Q_OS_WIN
QStyle *cde = QStyleFactory::create(OS_STYLE);
tableView->verticalScrollBar()->setStyle(cde);
#endif
#ifdef Q_OS_MAC
tableView->header()->setSortIndicatorShown(false); // blue looks nasty
tableView->setAttribute(Qt::WA_MacShowFocusRect, 0);
#endif
tableView->installEventFilter(this);
tableView->viewport()->installEventFilter(this);
tableView->setMouseTracking(true);
tableView->setFrameStyle(QFrame::NoFrame);
tableView->setAcceptDrops(true);
tableView->setColumnWidth(1, 100);
HelpWhatsThis *helpTableView = new HelpWhatsThis(tableView);
if (mainwindow)
tableView->setWhatsThis(helpTableView->getWhatsThisText(HelpWhatsThis::SideBarRidesView_Rides));
else
tableView->setWhatsThis(helpTableView->getWhatsThisText(HelpWhatsThis::ChartDiary_Navigator));
// good to go
tableView->show();
resetView();
// refresh when config changes (metric/imperial?)
connect(context, SIGNAL(configChanged(qint32)), this, SLOT(configChanged(qint32)));
// refresh when rides added/removed
connect(context, SIGNAL(rideAdded(RideItem*)), this, SLOT(refresh()));
connect(context, SIGNAL(rideDeleted(RideItem*)), this, SLOT(rideDeleted(RideItem*)));
// user selected a ride on the ride list, we should reflect that too..
connect(tableView, SIGNAL(rowSelected(QItemSelection)), this, SLOT(selectionChanged(QItemSelection)));
// user hit return or double clicked a ride !
connect(tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(selectRide(QModelIndex)));
// user moved columns
connect(tableView->header(), SIGNAL(sectionMoved(int,int,int)), this, SLOT(columnsChanged()));
connect(tableView->header(), SIGNAL(sectionResized(int,int,int)), this, SLOT(columnsResized(int, int, int)));
// user sorted by column
connect(tableView->header(), SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), this, SLOT(cursorRide()));
connect(tableView,SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(showTreeContextMenuPopup(const QPoint &)));
connect(tableView->header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), this, SLOT(setSortBy(int,Qt::SortOrder)));
// repaint etc when background refresh is working
connect(context, SIGNAL(refreshStart()), this, SLOT(backgroundRefresh()));
connect(context, SIGNAL(refreshEnd()), this, SLOT(backgroundRefresh()));
connect(context, SIGNAL(refreshUpdate(QDate)), this, SLOT(backgroundRefresh())); // we might miss 1st one
if (!mainwindow) {
connect(searchFilterBox, SIGNAL(searchResults(QStringList)), this, SLOT(searchStrings(QStringList)));
connect(searchFilterBox, SIGNAL(searchClear()), this, SLOT(clearSearch()));
}
// we accept drag and drop operations
setAcceptDrops(true);
// lets go
configChanged(CONFIG_APPEARANCE | CONFIG_NOTECOLOR | CONFIG_FIELDS);
}
RideNavigator::~RideNavigator()
{
delete tableView;
delete groupByModel;
}
void
RideNavigator::configChanged(qint32 state)
{
ColorEngine ce(context);
fontHeight = QFontMetrics(QFont()).height();
reverseColor = ce.reverseColor;
// hide ride list scroll bar ?
#ifndef Q_OS_MAC
tableView->setStyleSheet(TabView::ourStyleSheet());
if (mainwindow) {
if (appsettings->value(this, GC_RIDESCROLL, true).toBool() == false)
tableView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
else
tableView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
//if (appsettings->value(this, GC_RIDEHEAD, true).toBool() == false)
//tableView->header()->hide();
//else
tableView->header()->show();
tableView->header()->setStyleSheet(
QString("QHeaderView { background-color: %1; color: %2; }"
"QHeaderView::section { background-color: %1; color: %2; "
" border: 0px ; }")
.arg(GColor(CPLOTBACKGROUND).name())
.arg(GCColor::invertColor(GColor(CPLOTBACKGROUND)).name()));
}
#endif
// if the fields changed we need to reset indexes etc
if (state & CONFIG_FIELDS) resetView();
refresh();
}
void
RideNavigator::rideDeleted(RideItem*item)
{
if (currentItem == item) currentItem = NULL;
refresh();
}
void
RideNavigator::refresh()
{
active=false;
setWidth(geometry().width());
cursorRide();
}
void
RideNavigator::backgroundRefresh()
{
tableView->doItemsLayout();
}
void
RideNavigator::resizeEvent(QResizeEvent*)
{
// ignore if main window .. we get told to resize
// by the splitter mover
if (mainwindow) return;
setWidth(geometry().width());
}
void
RideNavigator::resetView()
{
active = true;
QList<QString> cols = _columns.split("|", QString::SkipEmptyParts);
int widco = _widths.split("|", QString::SkipEmptyParts).count();
// something is wrong with the config ? reset
if (widco != cols.count() || widco <= 1) {
_columns = QString(tr("*|Workout Code|Date|"));
_widths = QString("0|100|100|");
cols = _columns.split("|", QString::SkipEmptyParts);
}
// to account for translations
QMap <QString, QString> internalNameMap;
nameMap.clear();
columnMetrics.clear();
// add the standard columns to the map
nameMap.insert("filename", tr("File"));
internalNameMap.insert("File", tr("File"));
nameMap.insert("timestamp", tr("Last updated"));
internalNameMap.insert("Last updated", tr("Last updated"));
nameMap.insert("ride_date", tr("Date"));
internalNameMap.insert("Date", tr("Date"));
nameMap.insert("ride_time", tr("Time")); // virtual columns show time from ride_date
internalNameMap.insert("Time", tr("Time"));
nameMap.insert("fingerprint", tr("Config Checksum"));
internalNameMap.insert("Config Checksum", tr("Config Checksum"));
// add metrics to the map
const RideMetricFactory &factory = RideMetricFactory::instance();
for (int i=0; i<factory.metricCount(); i++) {
QString converted = QTextEdit(factory.rideMetric(factory.metricName(i))->name()).toPlainText();
// from sql column name to friendly metric name
nameMap.insert(QString("X%1").arg(factory.metricName(i)), converted);
// from (english) internalName to (translated) Name
internalNameMap.insert(factory.rideMetric(factory.metricName(i))->internalName(), converted);
// from friendly metric name to metric pointer
columnMetrics.insert(converted, factory.rideMetric(factory.metricName(i)));
}
// add metadata fields...
SpecialFields sp; // all the special fields are in here...
foreach(FieldDefinition field, context->athlete->rideMetadata()->getFields()) {
if (!sp.isMetric(field.name) && (field.type < 5 || field.type == 7)) {
nameMap.insert(QString("Z%1").arg(sp.makeTechName(field.name)), sp.displayName(field.name));
internalNameMap.insert(field.name, sp.displayName(field.name));
}
}
// cols list needs to be mapped to match logicalHeadings
for (int i = 0; i < cols.count(); i++)
cols[i] = internalNameMap.value(cols[i], cols[i]);
logicalHeadings.clear();
tableView->reset();
tableView->header()->reset();
// setup the logical heading list
for (int i=0; i<tableView->header()->count(); i++) {
QString friendly, techname = sortModel->headerData(i, Qt::Horizontal).toString();
if ((friendly = nameMap.value(techname, "unknown")) != "unknown") {
sortModel->setHeaderData(i, Qt::Horizontal, friendly);
logicalHeadings << friendly;
} else
logicalHeadings << techname;
}
// hide everything, we show what we want later
for (int i=0; i<tableView->header()->count(); i++) {
int index = tableView->header()->logicalIndex(i);
tableView->setColumnHidden(index, true);
tableView->setColumnWidth(index, 0);
}
// now re-order the columns according to the
// prevailing preferences. They are listed in
// the order we want them, column zero is the
// group by column, so we leave that alone
for(int i=1; i<cols.count(); i++) {
tableView->header()->moveSection(tableView->header()->visualIndex(logicalHeadings.indexOf(cols[i])), i);
}
// initialise to whatever groupBy we want to start with
tableView->sortByColumn(sortByIndex(), static_cast<Qt::SortOrder>(sortByOrder()));;
//tableView->setColumnHidden(0, true);
tableView->setColumnWidth(0,0);
// set the column widths
int columnnumber=0;
foreach(QString size, _widths.split("|", QString::SkipEmptyParts)) {
if (columnnumber >= cols.count()) break;
int index = tableView->header()->logicalIndex(columnnumber);
tableView->setColumnHidden(index, false);
tableView->setColumnWidth(index, columnnumber ? size.toInt() : 0);
columnnumber++;
}
setGroupByColumn();
active = false;
resizeEvent(NULL);
// Select the current ride
cursorRide();
// get height
tableView->doItemsLayout();
columnsChanged();
}
void RideNavigator::searchStrings(QStringList list)
{
searchFilter->setStrings(list);
setWidth(geometry().width());
}
void RideNavigator::clearSearch()
{
searchFilter->clearStrings();
QApplication::processEvents(); // repaint/resize list view - scrollbar..
setWidth(geometry().width()); // before we update column sizes!
}
void RideNavigator::setWidth(int x)
{
// use helper function
setColumnWidth(x, false);
}
// make sure the columns are all neat and tidy when the ride navigator is shown
void
RideNavigator::showEvent(QShowEvent *)
{
init = true;
//setWidth(geometry().width());
}
// routines called by the sidebar to let the user
// update the columns/grouping without using right-click
QStringList
RideNavigator::columnNames() const
{
return visualHeadings;
}
void
RideNavigator::setGroupByColumnName(QString name)
{
if (name == "") {
noGroups();
} else {
int logical = logicalHeadings.indexOf(name);
if (logical >= 0) {
currentColumn = logical;
setGroupByColumn();
}
}
}
void
RideNavigator::columnsChanged()
{
// do the work - (column changed, but no "inWidget" column resize)
calcColumnsChanged(false);
}
void
RideNavigator::columnsResized(int logicalIndex, int oldSize, int newSize)
{
// do the work - resize only
calcColumnsChanged(true, logicalIndex, oldSize, newSize);
}
bool
RideNavigator::eventFilter(QObject *object, QEvent *e)
{
// not for the table?
if (object != (QObject *)tableView) return false;
// what happnned?
switch(e->type())
{
case QEvent::ContextMenu:
{
//borderMenu(((QMouseEvent *)e)->pos());
borderMenu(tableView->mapFromGlobal(QCursor::pos()));
return true; // I'll take that thanks
break;
}
case QEvent::KeyPress:
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(e);
if (keyEvent->modifiers() & Qt::ControlModifier) {
// Ctrl+Key
switch (keyEvent->key()) {
case Qt::Key_C: // defacto standard for copy
return true;
case Qt::Key_V: // defacto standard for paste
return true;
case Qt::Key_X: // defacto standard for cut
return true;
case Qt::Key_Y: // emerging standard for redo
return true;
case Qt::Key_Z: // common standard for undo
return true;
case Qt::Key_0:
return true;
default:
return false;
}
} else {
// Not Ctrl ...
switch (keyEvent->key()) {
case Qt::Key_Return:
case Qt::Key_Enter:
selectRide(tableView->currentIndex());
return true;
default:
return false;
}
}
break;
}
case QEvent::WindowActivate:
{
active=true;
// set the column widths
int columnnumber=0;
foreach(QString size, _widths.split("|", QString::SkipEmptyParts)) {
tableView->setColumnWidth(columnnumber, size.toInt());
}
active=false;
setWidth(geometry().width()); // calculate width...
}
break;
default:
break;
}
return false;
}
void
RideNavigator::borderMenu(const QPoint &pos)
{
// Which column did we right click on?
//
// if not in the border then do nothing, this
// context menu should only be shown when
// the user right clicks on a column heading.
int column=0;
if (pos.y() <= tableView->header()->height())
column = tableView->header()->logicalIndexAt(pos);
else return; // not in the border
QMenu menu(tableView);
// reset viaual headings first
columnsChanged();
// don't allow user to delete last column!
// need to also include '*' column 0 wide in count hence 2 not 1
if (visualHeadings.count() > 2) {
QAction *delCol = new QAction(tr("Remove Column"), tableView);
delCol->setEnabled(true);
menu.addAction(delCol);
connect(delCol, SIGNAL(triggered()), this, SLOT(removeColumn()));
}
QAction *insCol = new QAction(tr("Column Chooser"), tableView);
insCol->setEnabled(true);
menu.addAction(insCol);
connect(insCol, SIGNAL(triggered()), this, SLOT(showColumnChooser()));
QAction *toggleGroupBy = new QAction(_groupBy >= 0 ? tr("Do Not Show in Groups") : tr("Show In Groups"), tableView);
toggleGroupBy->setEnabled(column!=1?true:false); // No group for Ride Time
menu.addAction(toggleGroupBy);
connect(toggleGroupBy, SIGNAL(triggered()), this, SLOT(setGroupByColumn()));
// set current column...
currentColumn = column;
menu.exec(tableView->mapToGlobal(QPoint(pos.x(), pos.y())));
}
void
RideNavigator::setGroupByColumn()
{
// toggle
setGroupBy(_groupBy >= 0 ? -1 : currentColumn);
// set proxy model
groupByModel->setGroupBy(_groupBy);
// lets expand column 0 for the groupBy heading
for (int i=0; i < groupByModel->groupCount(); i++) {
tableView->setFirstColumnSpanned (i, QModelIndex(), true);
}
// now show em
tableView->expandAll();
// reselect current ride - since selectionmodel
// is changed by setGroupBy()
cursorRide();
}
void
RideNavigator::setSortBy(int index, Qt::SortOrder order)
{
_sortByIndex = index;
_sortByOrder = static_cast<int>(order);
}
void
RideNavigator::calcColumnsChanged(bool resized, int logicalIndex, int oldSize, int newSize ) {
// double use - for "changing" and "only resizing" of the columns
if (active == true) return;
active = true;
visualHeadings.clear(); // they have moved
// get the names used
for (int i=0; i<tableView->header()->count(); i++) {
if (tableView->header()->isSectionHidden(tableView->header()->logicalIndex(i)) != true) {
int index = tableView->header()->logicalIndex(i);
visualHeadings << logicalHeadings[index];
}
}
// write to config
QString headings;
foreach(QString name, visualHeadings)
headings += name + "|";
_columns = headings;
// correct width and store result
setColumnWidth(geometry().width(), resized, logicalIndex, oldSize, newSize); // calculate width...
// get column widths
QString widths;
for (int i=0; i<tableView->header()->count(); i++) {
int index = tableView->header()->logicalIndex(i);
if (tableView->header()->isSectionHidden(index) != true) {
widths += QString("%1|").arg(tableView->columnWidth(index));
}
}
_widths = widths;
active = false;
}
void
RideNavigator::setColumnWidth(int x, bool resized, int logicalIndex, int oldWidth, int newWidth) {
// double use - for use after any change (e.g. widget size,..) "changing" and "only resizing" of the columns
if (init == false) return;
active = true;
#if !defined (Q_OS_MAC) || (defined (Q_OS_MAC) && (QT_VERSION < 0x050000)) // on QT5 the scrollbars have no width
if (tableView->verticalScrollBar()->isVisible())
x -= tableView->verticalScrollBar()->width()
+ 0 ; // !! no longer account for content margins of 3,3,3,3 was + 6
#else // we're on a mac with QT5 .. so dodgy way of spotting preferences for scrollbars...
// this is a nasty hack, to see if the 'always on' preference for scrollbars is set we
// look at the scrollbar width which is 15 in this case (it is 16 when they 'appear' when
// needed. No doubt this will change over time and need to be fixed by referencing the
// Mac system preferences via an NSScroller - but that will be a massive hassle.
if (tableView->verticalScrollBar()->isVisible() && tableView->verticalScrollBar()->width() == 15)
x -= tableView->verticalScrollBar()->width() + 0 ;
#endif
// take the margins into account top
x -= mainLayout->contentsMargins().left() + mainLayout->contentsMargins().right();
// ** NOTE **
// When iterating over the section headings we
// always use the tableview not the sortmodel
// so we can skip over the virtual column 0
// which is used to group by, is visible but
// must have a width of 0. This is why all
// the for loops start with i=1
tableView->setColumnWidth(0,0); // in case use grabbed it
// is it narrower than the headings?
int headwidth=0;
int n=0;
for (int i=1; i<tableView->header()->count(); i++)
if (tableView->header()->isSectionHidden(i) == false) {
headwidth += tableView->columnWidth(i);
n++;
}
if (!resized) {
// headwidth is no, x is to-be width
// we need to 'stretch' the sections
// proportionally to fit into new
// layout
int setwidth=0;
int newwidth=0;
for (int i=1; i<tableView->header()->count(); i++) {
if (tableView->header()->isSectionHidden(i) == false) {
newwidth = (double)((((double)tableView->columnWidth(i)/(double)headwidth)) * (double)x);
if (newwidth < 20) newwidth = 20;
QString columnName = tableView->model()->headerData(i, Qt::Horizontal).toString();
if (columnName == "*") newwidth = 0;
tableView->setColumnWidth(i, newwidth);
setwidth += newwidth;
}
}
// UGH. Now account for the fact that the smaller columns
// didn't take their fair share of a negative resize
// so we need to snip off from the larger columns.
if (setwidth != x) {
// how many columns we got to snip from?
int colsleft = 0;
for (int i=1; i<tableView->header()->count(); i++)
if (tableView->header()->isSectionHidden(i) == false && tableView->columnWidth(i)>20)
colsleft++;
// run through ... again.. snipping off some pixels
if (colsleft) {
int snip = (setwidth-x) / colsleft; //could be negative too
for (int i=1; i<tableView->header()->count(); i++) {
if (tableView->header()->isSectionHidden(i) == false && tableView->columnWidth(i)>20) {
tableView->setColumnWidth(i, tableView->columnWidth(i)-snip);
setwidth -= snip;
}
}
}
}
if (setwidth < x)
delegate->setWidth(pwidth=setwidth);
else
delegate->setWidth(pwidth=x);
} else {
// columns are resized - for each affected column this function is called
// and makes sure that
// a) nothing gets smaller than 20 and
// b) last section is not moved over the right border / does not fill the widget to the right border
// first step: make sure that the current column got smaller than 20 by resizing
if (newWidth < 20) {
tableView->setColumnWidth(logicalIndex, oldWidth);
// correct the headwidth by the added space
headwidth += (oldWidth - newWidth);
}
// get the index of the most right column (since here all further resizing will start)
int visIndex = 0;
// find the most right visible column
for (int i=1; i<tableView->header()->count(); i++) {
if (tableView->header()->isSectionHidden(i) == false &&
tableView->header()->visualIndex(i) > visIndex)
visIndex = tableView->header()->visualIndex(i);
}
if (headwidth > x) {
// now make sure that no column disappears right border of the table view
// by taking the overlapping part "cut" from last column(s)
int cut = headwidth - x;
// now resize, but not smaller than 20 (from right to left of Visible Columns)
while (cut >0 && visIndex > 0) {
int logIndex = tableView->header()->logicalIndex(visIndex);
int k = tableView->columnWidth(logIndex);
if (k - cut >= 20) {
tableView->setColumnWidth(logIndex, k-cut);
cut = 0;
} else {
tableView->setColumnWidth(logIndex, 20);
cut -= (k-20);
}
visIndex--;
}
} else {
// since QT on fast mouse moves resizes more columns then expected
// give all available space to the last visible column
int logIndex = tableView->header()->logicalIndex(visIndex);
int k = tableView->columnWidth(logIndex);
tableView->setColumnWidth(logIndex, (k+x-headwidth));
}
}
// make the scrollbars go away
tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
active = false;
}
//
// This function is called for every row in the ridecache
// and wants to know what group string or 'name' you want
// to put this row into. It is passed the heading value
// as a string, and the row value for this column.
//
// It should return a string that will be used in the first
// column tree to group rows together.
//
// It is intended to allow us to do clever groupings, such
// as grouping dates as 'This week', 'Last week' etc or
// Power values into zones etc.
//
class groupRange {
public:
class range {
public:
double low, high;
QString name;
range(double low, double high, QString name) : low(low), high(high), name(name) {}
range() : low(0), high(0), name("") {}
};
QString column; // column name
QList<range> ranges; // list of ranges we can put them in
};
static QList<groupRange> groupRanges;
bool
GroupByModel::initGroupRanges()
{
groupRange::range add;
groupRange addColumn;
// TSS
addColumn.column = "TSS";
add = groupRange::range( 0.0, 0.0, tr("Zero or not present")); addColumn.ranges << add;
add = groupRange::range( 0, 150, tr("Low Stress")); addColumn.ranges << add;
add = groupRange::range( 150, 300, tr("Medium Stress")); addColumn.ranges << add;
add = groupRange::range( 300, 450, tr("High Stress")); addColumn.ranges << add;
add = groupRange::range( 450, 0.00, tr("Very High Stress")); addColumn.ranges << add;
groupRanges << addColumn;
addColumn.ranges.clear();
// Intensity Factor
addColumn.column = "IF";
add = groupRange::range( 0.0, 0.0, tr("Zero or not present")); addColumn.ranges << add;
add = groupRange::range( 0.0, 0.55, tr("Active Recovery")); addColumn.ranges << add;
add = groupRange::range( 0.55, 0.75, tr("Endurance")); addColumn.ranges << add;
add = groupRange::range( 0.75, 0.90, tr("Tempo")); addColumn.ranges << add;
add = groupRange::range( 0.90, 1.05, tr("Threshold")); addColumn.ranges << add;
add = groupRange::range( 1.05, 1.2, tr("VO2Max")); addColumn.ranges << add;
add = groupRange::range( 1.2, 1.5, tr("Anaerobic Capacity")); addColumn.ranges << add;
add = groupRange::range( 1.5, 0.0, tr("Maximal")); addColumn.ranges << add;
groupRanges << addColumn;
addColumn.ranges.clear();
// Variability Index
addColumn.column = "VI";
add = groupRange::range( 0.0, 1.0, tr("Zero or not present")); addColumn.ranges << add;
add = groupRange::range( 1.0, 1.05, tr("Isopower")); addColumn.ranges << add;
add = groupRange::range( 1.05, 1.1, tr("Steady")); addColumn.ranges << add;
add = groupRange::range( 1.1, 1.2, tr("Variable")); addColumn.ranges << add;
add = groupRange::range( 1.2, 0.0, tr("Highly Variable")); addColumn.ranges << add;
groupRanges << addColumn;
addColumn.ranges.clear();
// Duration (seconds)
addColumn.column = "Duration";
add = groupRange::range( 0.0, 3600.0, tr("Less than an hour")); addColumn.ranges << add;
add = groupRange::range( 3600, 5400, tr("Less than 90 minutes")); addColumn.ranges << add;
add = groupRange::range( 5400, 10800, tr("Less than 3 hours")); addColumn.ranges << add;
add = groupRange::range( 10800, 18000, tr("Less than 5 hours")); addColumn.ranges << add;
add = groupRange::range( 18000, 0.0, tr("More than 5 hours")); addColumn.ranges << add;
groupRanges << addColumn;
addColumn.ranges.clear();
// Distance (km)
addColumn.column = "Distance";
add = groupRange::range( 0.0, 0.0, tr("Zero or not present")); addColumn.ranges << add;
add = groupRange::range( 0.0, 40.0, tr("Short")); addColumn.ranges << add;
add = groupRange::range( 40, 80.00, tr("Medium")); addColumn.ranges << add;
add = groupRange::range( 80, 140, tr("Long")); addColumn.ranges << add;
add = groupRange::range( 140, 0, tr("Very Long")); addColumn.ranges << add;
groupRanges << addColumn;
addColumn.ranges.clear();
return true;
}
static bool _initGroupRanges = false;
// Perhaps a groupName function on the metrics would be useful
QString
GroupByModel::groupFromValue(QString headingName, QString value, double rank, double count) const
{
if (!_initGroupRanges)
_initGroupRanges = initGroupRanges();
// Check for predefined thresholds / zones / bands for this metric/column
foreach (groupRange orange, groupRanges) {
if (orange.column == headingName) {
double number = value.toDouble();
// use thresholds defined for this column/metric
foreach(groupRange::range range, orange.ranges) {
// 0-x is lower, x-0 is upper, 0-0 is no data and x-x is a range
if (range.low == 0.0 && range.high == 0.0 && number == 0.0) return range.name;
else if (range.high != 0.0 && range.low == 0.0 && number < range.high) return range.name;
else if (range.low != 0.0 && range.high == 0.0 && number >= range.low) return range.name;
else if (number < range.high && number >= range.low) return range.name;
}
return tr("Undefined");
}
}
// Use upper quartile for anything left that is a metric
if (rideNavigator->columnMetrics.value(headingName, NULL) != NULL) {
double quartile = rank / count;
if (value.toDouble() == 0) return QString(tr("Zero or not present"));
else if (rank < 10) return QString(tr("Best 10"));
else if (quartile <= 0.25) return QString (tr("Quartile 1: 0% - 25%"));
else if (quartile <= 0.50) return QString (tr("Quartile 2: 25% - 50%"));
else if (quartile <= 0.75) return QString (tr("Quartile 3: 50% - 75%"));
else if (quartile <= 1) return QString (tr("Quartile 4: 75% - 100%"));
} else {
if (headingName == tr("Date")) {
// get the date from value string
QDateTime dateTime = QDateTime::fromString(value, Qt::ISODate);
QDateTime today = QDateTime::currentDateTime();
if (today.date().weekNumber() == dateTime.date().weekNumber()
&& today.date().year() == dateTime.date().year())
return tr("This week");
else if (today.date().month() == dateTime.date().month()
&& today.date().year() == dateTime.date().year())
return tr("This month");
else if (today.date().month() == (dateTime.date().month()+1)
&& today.date().year() == dateTime.date().year())
return tr("Last month");
else {
return dateTime.toString(tr("yyyy-MM (MMMM)"));
}
}
// not a metric, i.e. metadata
return value;
}
// if all else fails just return the value and group by
// that. Which is a fair approach for text fields for example
return value;
}
void
RideNavigator::removeColumn()
{
active = true;
tableView->setColumnHidden(currentColumn, true);
active = false;
setWidth(geometry().width()); // calculate width...
columnsChanged(); // need to do after, just once
columnsChanged(); // need to do after, and again
}
void
RideNavigator::showColumnChooser()
{
ColumnChooser *selector = new ColumnChooser(logicalHeadings);
selector->show();
}
// user selected a different ride somewhere else, we need to align with that
void
RideNavigator::setRide(RideItem*rideItem)
{
if (currentItem == rideItem) return;
for (int i=0; i<tableView->model()->rowCount(); i++) {
QModelIndex group = tableView->model()->index(i,0,QModelIndex());
for (int j=0; j<tableView->model()->rowCount(group); j++) {
QString fileName = tableView->model()->data(tableView->model()->index(j,3, group), Qt::DisplayRole).toString();
if (fileName == rideItem->fileName) {
// we set current index to column 2 (date/time) since we can be guaranteed it is always show (all others are removable)
QItemSelection row(tableView->model()->index(j,0,group),
tableView->model()->index(j,tableView->model()->columnCount()-1, group));
tableView->selectionModel()->select(row, QItemSelectionModel::Rows | QItemSelectionModel::ClearAndSelect);
tableView->selectionModel()->setCurrentIndex(tableView->model()->index(j,0,group), QItemSelectionModel::NoUpdate);
tableView->scrollTo(tableView->model()->index(j,3,group), QAbstractItemView::PositionAtCenter);
currentItem = rideItem;
repaint();
active = false;
return;
}
}
}
}
void
RideNavigator::selectionChanged(QItemSelection selected)
{
QModelIndex ref = selected.indexes().first();
QModelIndex fileIndex = tableView->model()->index(ref.row(), 3, ref.parent());
QString filename = tableView->model()->data(fileIndex, Qt::DisplayRole).toString();
// lets make sure we know what we've selected, so we don't
// select it twice
foreach(RideItem *item, context->athlete->rideCache->rides()) {
if (item->fileName == filename) {
currentItem = item;
break;
}
}
// lets notify others
context->athlete->selectRideFile(filename);
}
void
RideNavigator::selectRide(const QModelIndex &index)
{
// we don't use this at present, but hitting return
// or double clicking a ride will cause this to get called....
QModelIndex fileIndex = tableView->model()->index(index.row(), 3, index.parent()); // column 2 for filename ?
QString filename = tableView->model()->data(fileIndex, Qt::DisplayRole).toString();
// do nothing .. but maybe later do something ?
//context->athlete->selectRideFile(filename);
}
void
RideNavigator::cursorRide()
{
if (currentItem == NULL) return;
// find our ride and scroll to it
for (int i=0; i<tableView->model()->rowCount(); i++) {
QModelIndex group = tableView->model()->index(i,0,QModelIndex());
for (int j=0; j<tableView->model()->rowCount(group); j++) {
QString fileName = tableView->model()->data(tableView->model()->index(j,2, group), Qt::UserRole+1).toString();
if (fileName == currentItem->fileName) {
// we set current index to column 2 (date/time) since we can be guaranteed it is always show (all others are removable)
tableView->scrollTo(tableView->model()->index(j,3,group));
return;
}
}
}
}
// Drag and drop columns from the chooser...
void
RideNavigator::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->data("application/x-columnchooser") != "")
event->acceptProposedAction(); // whatever you wanna drop we will try and process!
else
event->ignore();
}
void
RideNavigator::dropEvent(QDropEvent *event)
{
QByteArray rawData = event->mimeData()->data("application/x-columnchooser");
QDataStream stream(&rawData, QIODevice::ReadOnly);
stream.setVersion(QDataStream::Qt_4_6);
QString name;
stream >> name;
tableView->setColumnHidden(logicalHeadings.indexOf(name), false);
tableView->setColumnWidth(logicalHeadings.indexOf(name), 50);
tableView->header()->moveSection(tableView->header()->visualIndex(logicalHeadings.indexOf(name)), 1);
columnsChanged();
}
NavigatorCellDelegate::NavigatorCellDelegate(RideNavigator *rideNavigator, QObject *parent) :
QItemDelegate(parent), rideNavigator(rideNavigator), pwidth(300)
{
}
// Editing functions are null since the model is read-only
QWidget *NavigatorCellDelegate::createEditor(QWidget *, const QStyleOptionViewItem &, const QModelIndex &) const { return NULL; }
void NavigatorCellDelegate::commitAndCloseEditor() { }
void NavigatorCellDelegate::setEditorData(QWidget *, const QModelIndex &) const { }
void NavigatorCellDelegate::updateEditorGeometry(QWidget *, const QStyleOptionViewItem &, const QModelIndex &) const {}
void NavigatorCellDelegate::setModelData(QWidget *, QAbstractItemModel *, const QModelIndex &) const { }
bool NavigatorCellDelegate::helpEvent(QHelpEvent*, QAbstractItemView*, const QStyleOptionViewItem&, const QModelIndex&) { return true; }
QSize NavigatorCellDelegate::sizeHint(const QStyleOptionViewItem & /*option*/, const QModelIndex &index) const
{
QSize s;
if (rideNavigator->groupByModel->mapToSource(rideNavigator->sortModel->mapToSource(index)) != QModelIndex() &&
rideNavigator->groupByModel->data(rideNavigator->sortModel->mapToSource(index), Qt::UserRole).toString() != "") {
s.setHeight((rideNavigator->fontHeight+2) * 3);
} else s.setHeight(rideNavigator->fontHeight + 2);
return s;
}
// anomalies are underlined in red, otherwise straight paintjob
void NavigatorCellDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
// paint background for user defined color ?
bool rideBG = appsettings->value(this,GC_RIDEBG,false).toBool();
// state of item
bool hover = option.state & QStyle::State_MouseOver;
bool selected = option.state & QStyle::State_Selected;
bool focus = option.state & QStyle::State_HasFocus;
//bool isRun = rideNavigator->tableView->model()->data(index, Qt::UserRole+2).toBool();
// format the cell depending upon what it is...
QString columnName = rideNavigator->tableView->model()->headerData(index.column(), Qt::Horizontal).toString();
const RideMetric *m;
QString value;
// are we a selected cell ? need to paint accordingly
//bool selected = false;
//if (rideNavigator->tableView->selectionModel()->selectedIndexes().count()) { // zero if no rides in list
//if (rideNavigator->tableView->selectionModel()->selectedIndexes().value(0).row() == index.row())
//selected = true;
//}
if ((m=rideNavigator->columnMetrics.value(columnName, NULL)) != NULL) {
// get double from sqlmodel
value = index.model()->data(index, Qt::DisplayRole).toString();
// get rid of 0 its ugly
if (value =="nan" || value == "0" || value == "0.0" || value == "0.00") value="";
} else {
// is this the ride date/time ?
value = index.model()->data(index, Qt::DisplayRole).toString();
if (columnName == tr("Date")) {
QDateTime dateTime = QDateTime::fromString(value, Qt::ISODate);
value = dateTime.toString(tr("MMM d, yyyy")); // same format as ride list
} else if (columnName == tr("Time")) {
QDateTime dateTime = QDateTime::fromString(value, Qt::ISODate);
value = dateTime.toString("hh:mm:ss"); // same format as ride list
} else if (columnName == tr("Last updated")) {
QDateTime dateTime;
dateTime.setTime_t(index.model()->data(index, Qt::DisplayRole).toInt());
value = dateTime.toString(tr("ddd MMM d, yyyy hh:mm")); // same format as ride list
}
}
QStyleOptionViewItem myOption = option;
// groupBy in bold please
if (columnName == "*") {
QFont enbolden = option.font;
enbolden.setWeight(QFont::Bold);
myOption.font = enbolden;
}
// normal render
bool isnormal=false;
QString calendarText = rideNavigator->tableView->model()->data(index, Qt::UserRole).toString();
QColor userColor = rideNavigator->tableView->model()->data(index, Qt::BackgroundRole).value<QBrush>().color();
if (userColor == QColor(1,1,1)) {
rideBG = false; // default so don't swap round...
isnormal = true; // just default so no bg or box
userColor = GColor(CPLOTMARKER);
}
// basic background
QBrush background = QBrush(GColor(CPLOTBACKGROUND));
// runs are darker
//if (isRun) {
//background.setColor(background.color().darker(150));
//userColor = userColor.darker(150);
//}
if (columnName != "*") {
myOption.displayAlignment = Qt::AlignLeft | Qt::AlignTop;
QRectF bigger(myOption.rect.x(), myOption.rect.y(), myOption.rect.width()+1, myOption.rect.height()+1);
if (hover) painter->fillRect(myOption.rect, QColor(Qt::lightGray));
else painter->fillRect(bigger, rideBG ? userColor : background);
// clear first
drawDisplay(painter, myOption, myOption.rect, ""); //added
// draw border of each cell
QPen rpen;
rpen.setWidth(1);
rpen.setColor(GColor(CPLOTGRID));
QPen isColor = painter->pen();
QFont isFont = painter->font();
painter->setPen(rpen);
painter->drawLine(0,myOption.rect.y(),rideNavigator->pwidth-1,myOption.rect.y());
painter->drawLine(0,myOption.rect.y()+myOption.rect.height(),rideNavigator->pwidth-1,myOption.rect.y()+myOption.rect.height());
painter->drawLine(0,myOption.rect.y()+myOption.rect.height(),0,myOption.rect.y()+myOption.rect.height());
painter->drawLine(rideNavigator->pwidth-1, myOption.rect.y(), rideNavigator->pwidth-1, myOption.rect.y()+myOption.rect.height());
// indent first column and draw all in plotmarker color
myOption.rect.setHeight(rideNavigator->fontHeight + 2); //added
myOption.font.setWeight(QFont::Bold);
QFont boldened = painter->font();
boldened.setWeight(QFont::Bold);
painter->setFont(boldened);
if (!selected) {
// not selected, so invert ride plot color
if (hover) painter->setPen(QColor(Qt::black));
else painter->setPen(rideBG ? rideNavigator->reverseColor : userColor);
} else if (!focus) { // selected but out of focus //
painter->setPen(QColor(Qt::black));
}
QRect normal(myOption.rect.x(), myOption.rect.y()+1, myOption.rect.width(), myOption.rect.height());
if (myOption.rect.x() == 0) {
// first line ?
QRect indented(myOption.rect.x()+5, myOption.rect.y()+1, myOption.rect.width()-5, myOption.rect.height());
painter->drawText(indented, value); //added
} else {
painter->drawText(normal, value); //added
}
painter->setPen(isColor);
painter->setFont(isFont);
// now get the calendar text to appear ...
if (calendarText != "") {
QRect high(myOption.rect.x()+myOption.rect.width() - 7, myOption.rect.y(), 7, (rideNavigator->fontHeight+2) * 3);
myOption.rect.setX(0);
myOption.rect.setY(myOption.rect.y() + rideNavigator->fontHeight + 2);//was +23
myOption.rect.setWidth(rideNavigator->pwidth);
myOption.rect.setHeight(rideNavigator->fontHeight * 2); //was 36
myOption.font.setPointSize(myOption.font.pointSize());
myOption.font.setWeight(QFont::Normal);
if (hover) painter->fillRect(myOption.rect, QColor(Qt::lightGray));
else painter->fillRect(myOption.rect, rideBG ? userColor : background.color());
drawDisplay(painter, myOption, myOption.rect, "");
myOption.rect.setX(10); // wider notes display
myOption.rect.setWidth(pwidth-20);// wider notes display
painter->setFont(myOption.font);
QPen isColor = painter->pen();
if (!selected) {
// not selected, so invert ride plot color
if (hover) painter->setPen(QPen(Qt::black));
else painter->setPen(rideBG ? rideNavigator->reverseColor : GCColor::invertColor(GColor(CPLOTBACKGROUND)));
}
painter->drawText(myOption.rect, Qt::AlignLeft | Qt::TextWordWrap, calendarText);
painter->setPen(isColor);
#if (defined (Q_OS_MAC) && (QT_VERSION >= 0x050000)) // on QT5 the scrollbars have no width
if (!selected && !rideBG && high.x()+12 > rideNavigator->geometry().width() && !isnormal) {
#else
if (!selected && !rideBG && high.x()+32 > rideNavigator->geometry().width() && !isnormal) {
#endif
painter->fillRect(high, userColor);
} else {
// border
QPen rpen;
rpen.setWidth(1);
rpen.setColor(GColor(CPLOTGRID));
QPen isColor = painter->pen();
QFont isFont = painter->font();
painter->setPen(rpen);
painter->drawLine(rideNavigator->pwidth-1, myOption.rect.y(), rideNavigator->pwidth-1, myOption.rect.y()+myOption.rect.height());
painter->setPen(isColor);
}
}
} else {
if (value != "") {
myOption.displayAlignment = Qt::AlignLeft | Qt::AlignBottom;
myOption.rect.setX(0);
myOption.rect.setHeight(rideNavigator->fontHeight + 2);
myOption.rect.setWidth(rideNavigator->pwidth);
painter->fillRect(myOption.rect, GColor(CPLOTBACKGROUND));
}
QPen isColor = painter->pen();
painter->setPen(QPen(GColor(CPLOTMARKER)));
myOption.palette.setColor(QPalette::WindowText, QColor(GColor(CPLOTMARKER))); //XXX
painter->drawText(myOption.rect, value);
painter->setPen(isColor);
}
}
ColumnChooser::ColumnChooser(QList<QString>&logicalHeadings)
{
// wipe away everything when you close please...
setWindowTitle(tr("Column Chooser"));
setAttribute(Qt::WA_DeleteOnClose);
setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint | Qt::Tool);
clicked = new QSignalMapper(this); // maps each button click event
connect(clicked, SIGNAL(mapped(const QString &)), this, SLOT(buttonClicked(const QString &)));
QVBoxLayout *us = new QVBoxLayout(this);
us->setSpacing(0);
us->setContentsMargins(0,0,0,0);
scrollarea = new QScrollArea(this);
us->addWidget(scrollarea);
QWidget *but = new QWidget(this);
buttons = new QVBoxLayout(but);
buttons->setSpacing(0);
buttons->setContentsMargins(0,0,0,0);
QFont small;
small.setPointSize(8);
QList<QString> buttonNames = logicalHeadings;
qSort(buttonNames);
foreach (QString column, buttonNames) {
if (column == "*") continue;
// setup button
QPushButton *add = new QPushButton(column, this);
add->setFont(small);
add->setContentsMargins(0,0,0,0);
buttons->addWidget(add);
connect(add, SIGNAL(pressed()), clicked, SLOT(map()));
clicked->setMapping(add, column);
}
scrollarea->setWidget(but);
but->setFixedWidth(230);
scrollarea->setFixedWidth(250);
setFixedWidth(250);
}
void
ColumnChooser::buttonClicked(QString name)
{
// setup the drag data
QMimeData *mimeData = new QMimeData;
// we need to pack into a byte array (since UTF8() conversion is not reliable in QT4.8 vs QT 5.3)
QByteArray rawData;
QDataStream stream(&rawData, QIODevice::WriteOnly);
stream.setVersion(QDataStream::Qt_4_6);
stream << name;
// send raw
mimeData->setData("application/x-columnchooser", rawData);
// create a drag event
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->exec(Qt::MoveAction);
}
void
RideNavigator::showTreeContextMenuPopup(const QPoint &pos)
{
// map to global does not take into account the height of the header (??)
// so we take it off the result of map to global
// in the past this called mainwindow routinesfor the menu -- that was
// a bad design since it coupled the ride navigator with the gui
// we emit signals now, which only the sidebar is interested in trapping
// so the activity log for example doesn't have a context menu now
emit customContextMenuRequested(tableView->mapToGlobal(pos+QPoint(0,tableView->header()->geometry().height())));
}
RideTreeView::RideTreeView()
{
#if (defined WIN32) && (QT_VERSION > 0x050000) && (QT_VERSION < 0x050301)
// don't allow ride drop on Windows with QT5 until 5.3.1 when they fixed the bug
#else
setDragDropMode(QAbstractItemView::InternalMove);
setDragEnabled(true);
setDragDropOverwriteMode(false);
setDropIndicatorShown(true);
#endif
#ifdef Q_OS_MAC
setAttribute(Qt::WA_MacShowFocusRect, 0);
#endif
}
| iwasaki-FTP225/gc | src/RideNavigator.cpp | C++ | gpl-2.0 | 50,179 |
/*
* Copyright (C) 2005-2017 Team Kodi
* http://kodi.tv
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KODI; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "General.h"
#include "addons/kodi-addon-dev-kit/include/kodi/General.h"
#include "Application.h"
#include "CompileInfo.h"
#include "ServiceBroker.h"
#include "addons/binary-addons/AddonDll.h"
#include "addons/binary-addons/BinaryAddonManager.h"
#include "addons/settings/GUIDialogAddonSettings.h"
#include "dialogs/GUIDialogKaiToast.h"
#include "filesystem/Directory.h"
#include "filesystem/SpecialProtocol.h"
#include "guilib/LocalizeStrings.h"
#ifdef TARGET_POSIX
#include "linux/XMemUtils.h"
#endif
#include "settings/Settings.h"
#include "utils/CharsetConverter.h"
#include "utils/log.h"
#include "utils/LangCodeExpander.h"
#include "utils/md5.h"
#include "utils/StringUtils.h"
#include "utils/URIUtils.h"
#include <string.h>
using namespace kodi; // addon-dev-kit namespace
namespace ADDON
{
void Interface_General::Init(AddonGlobalInterface* addonInterface)
{
addonInterface->toKodi->kodi = static_cast<AddonToKodiFuncTable_kodi*>(malloc(sizeof(AddonToKodiFuncTable_kodi)));
addonInterface->toKodi->kodi->get_addon_info = get_addon_info;
addonInterface->toKodi->kodi->open_settings_dialog = open_settings_dialog;
addonInterface->toKodi->kodi->get_localized_string = get_localized_string;
addonInterface->toKodi->kodi->unknown_to_utf8 = unknown_to_utf8;
addonInterface->toKodi->kodi->get_language = get_language;
addonInterface->toKodi->kodi->queue_notification = queue_notification;
addonInterface->toKodi->kodi->get_md5 = get_md5;
addonInterface->toKodi->kodi->get_temp_path = get_temp_path;
addonInterface->toKodi->kodi->get_region = get_region;
addonInterface->toKodi->kodi->get_free_mem = get_free_mem;
addonInterface->toKodi->kodi->get_global_idle_time = get_global_idle_time;
addonInterface->toKodi->kodi->get_current_skin_id = get_current_skin_id;
addonInterface->toKodi->kodi->kodi_version = kodi_version;
}
void Interface_General::DeInit(AddonGlobalInterface* addonInterface)
{
if (addonInterface->toKodi && /* <-- needed as long as the old addon way is used */
addonInterface->toKodi->kodi)
{
free(addonInterface->toKodi->kodi);
addonInterface->toKodi->kodi = nullptr;
}
}
char* Interface_General::get_addon_info(void* kodiBase, const char* id)
{
CAddonDll* addon = static_cast<CAddonDll*>(kodiBase);
if (addon == nullptr || id == nullptr)
{
CLog::Log(LOGERROR, "Interface_General::%s - invalid data (addon='%p', id='%p')", __FUNCTION__, addon, id);
return nullptr;
}
std::string str;
if (strcmpi(id, "author") == 0)
str = addon->Author();
else if (strcmpi(id, "changelog") == 0)
str = addon->ChangeLog();
else if (strcmpi(id, "description") == 0)
str = addon->Description();
else if (strcmpi(id, "disclaimer") == 0)
str = addon->Disclaimer();
else if (strcmpi(id, "fanart") == 0)
str = addon->FanArt();
else if (strcmpi(id, "icon") == 0)
str = addon->Icon();
else if (strcmpi(id, "id") == 0)
str = addon->ID();
else if (strcmpi(id, "name") == 0)
str = addon->Name();
else if (strcmpi(id, "path") == 0)
str = addon->Path();
else if (strcmpi(id, "profile") == 0)
str = addon->Profile();
else if (strcmpi(id, "summary") == 0)
str = addon->Summary();
else if (strcmpi(id, "type") == 0)
str = ADDON::CAddonInfo::TranslateType(addon->Type());
else if (strcmpi(id, "version") == 0)
str = addon->Version().asString();
else
{
CLog::Log(LOGERROR, "Interface_General::%s - add-on '%s' requests invalid id '%s'",
__FUNCTION__, addon->Name().c_str(), id);
return nullptr;
}
char* buffer = strdup(str.c_str());
return buffer;
}
bool Interface_General::open_settings_dialog(void* kodiBase)
{
CAddonDll* addon = static_cast<CAddonDll*>(kodiBase);
if (addon == nullptr)
{
CLog::Log(LOGERROR, "Interface_General::%s - invalid data (addon='%p')", __FUNCTION__, addon);
return false;
}
// show settings dialog
AddonPtr addonInfo;
if (CAddonMgr::GetInstance().GetAddon(addon->ID(), addonInfo))
{
CLog::Log(LOGERROR, "Interface_General::%s - Could not get addon information for '%s'", __FUNCTION__, addon->ID().c_str());
return false;
}
return CGUIDialogAddonSettings::ShowForAddon(addonInfo);
}
char* Interface_General::get_localized_string(void* kodiBase, long label_id)
{
CAddonDll* addon = static_cast<CAddonDll*>(kodiBase);
if (!addon)
{
CLog::Log(LOGERROR, "Interface_General::%s - invalid data (addon='%p')", __FUNCTION__, addon);
return nullptr;
}
if (g_application.m_bStop)
return nullptr;
std::string label = g_localizeStrings.GetAddonString(addon->ID(), label_id);
if (label.empty())
label = g_localizeStrings.Get(label_id);
char* buffer = strdup(label.c_str());
return buffer;
}
char* Interface_General::unknown_to_utf8(void* kodiBase, const char* source, bool* ret, bool failOnBadChar)
{
CAddonDll* addon = static_cast<CAddonDll*>(kodiBase);
if (!addon || !source || !ret)
{
CLog::Log(LOGERROR, "Interface_General::%s - invalid data (addon='%p', source='%p', ret='%p')", __FUNCTION__, addon, source, ret);
return nullptr;
}
std::string string;
*ret = g_charsetConverter.unknownToUTF8(source, string, failOnBadChar);
char* buffer = strdup(string.c_str());
return buffer;
}
char* Interface_General::get_language(void* kodiBase, int format, bool region)
{
CAddonDll* addon = static_cast<CAddonDll*>(kodiBase);
if (!addon)
{
CLog::Log(LOGERROR, "Interface_General::%s - invalid data (addon='%p')", __FUNCTION__, addon);
return nullptr;
}
std::string string = g_langInfo.GetEnglishLanguageName();
switch (format)
{
case LANG_FMT_ISO_639_1:
{
std::string langCode;
g_LangCodeExpander.ConvertToISO6391(string, langCode);
string = langCode;
if (region)
{
std::string region2Code;
g_LangCodeExpander.ConvertToISO6391(g_langInfo.GetRegionLocale(), region2Code);
if (!region2Code.empty())
string += "-" + region2Code;
}
break;
}
case LANG_FMT_ISO_639_2:
{
std::string langCode;
g_LangCodeExpander.ConvertToISO6392B(string, langCode);
string = langCode;
if (region)
{
std::string region3Code;
g_LangCodeExpander.ConvertToISO6392B(g_langInfo.GetRegionLocale(), region3Code);
if (!region3Code.empty())
string += "-" + region3Code;
}
break;
}
case LANG_FMT_ENGLISH_NAME:
default:
{
if (region)
string += "-" + g_langInfo.GetCurrentRegion();
break;
}
}
char* buffer = strdup(string.c_str());
return buffer;
}
bool Interface_General::queue_notification(void* kodiBase, int type, const char* header,
const char* message, const char* imageFile,
unsigned int displayTime, bool withSound,
unsigned int messageTime)
{
CAddonDll* addon = static_cast<CAddonDll*>(kodiBase);
if (addon == nullptr || message == nullptr)
{
CLog::Log(LOGERROR, "Interface_General::%s - invalid data (addon='%p', message='%p')", __FUNCTION__, addon, message);
return false;
}
std::string usedHeader;
if (header && strlen(header) > 0)
usedHeader = header;
else
usedHeader = addon->Name();
QueueMsg qtype = static_cast<QueueMsg>(type);
if (qtype != QUEUE_OWN_STYLE)
{
CGUIDialogKaiToast::eMessageType usedType;
switch (qtype)
{
case QUEUE_WARNING:
usedType = CGUIDialogKaiToast::Warning;
withSound = true;
CLog::Log(LOGDEBUG, "Interface_General::%s - %s - Warning Message: '%s'", __FUNCTION__, addon->Name().c_str(), message);
break;
case QUEUE_ERROR:
usedType = CGUIDialogKaiToast::Error;
withSound = true;
CLog::Log(LOGDEBUG, "Interface_General::%s - %s - Error Message : '%s'", __FUNCTION__, addon->Name().c_str(), message);
break;
case QUEUE_INFO:
default:
usedType = CGUIDialogKaiToast::Info;
withSound = false;
CLog::Log(LOGDEBUG, "Interface_General::%s - %s - Info Message : '%s'", __FUNCTION__, addon->Name().c_str(), message);
break;
}
if (imageFile && strlen(imageFile) > 0)
{
CLog::Log(LOGERROR, "Interface_General::%s - To use given image file '%s' must be type value set to 'QUEUE_OWN_STYLE'", __FUNCTION__, imageFile);
}
CGUIDialogKaiToast::QueueNotification(usedType, usedHeader, message, 3000, withSound);
}
else
{
CGUIDialogKaiToast::QueueNotification(imageFile, usedHeader, message, displayTime, withSound, messageTime);
}
return true;
}
void Interface_General::get_md5(void* kodiBase, const char* text, char* md5)
{
CAddonDll* addon = static_cast<CAddonDll*>(kodiBase);
if (addon == nullptr || text == nullptr)
{
CLog::Log(LOGERROR, "Interface_General::%s - invalid data (addon='%p', text='%p')", __FUNCTION__, addon, text);
return;
}
std::string md5Int = XBMC::XBMC_MD5::GetMD5(std::string(text));
strncpy(md5, md5Int.c_str(), 40);
}
char* Interface_General::get_temp_path(void* kodiBase)
{
CAddonDll* addon = static_cast<CAddonDll*>(kodiBase);
if (addon == nullptr)
{
CLog::Log(LOGERROR, "Interface_General::%s - called with empty kodi instance pointer", __FUNCTION__);
return nullptr;
}
const std::string tempPath = URIUtils::AddFileToFolder(CServiceBroker::GetBinaryAddonManager().GetTempAddonBasePath(), addon->ID());
if (!XFILE::CDirectory::Exists(tempPath))
XFILE::CDirectory::Create(tempPath);
return strdup(CSpecialProtocol::TranslatePath(tempPath).c_str());
}
char* Interface_General::get_region(void* kodiBase, const char* id)
{
CAddonDll* addon = static_cast<CAddonDll*>(kodiBase);
if (addon == nullptr || id == nullptr)
{
CLog::Log(LOGERROR, "Interface_General::%s - invalid data (addon='%p', id='%p')", __FUNCTION__, addon, id);
return nullptr;
}
std::string result;
if (strcmpi(id, "datelong") == 0)
{
result = g_langInfo.GetDateFormat(true);
StringUtils::Replace(result, "DDDD", "%A");
StringUtils::Replace(result, "MMMM", "%B");
StringUtils::Replace(result, "D", "%d");
StringUtils::Replace(result, "YYYY", "%Y");
}
else if (strcmpi(id, "dateshort") == 0)
{
result = g_langInfo.GetDateFormat(false);
StringUtils::Replace(result, "MM", "%m");
StringUtils::Replace(result, "DD", "%d");
#ifdef TARGET_WINDOWS
StringUtils::Replace(result, "M", "%#m");
StringUtils::Replace(result, "D", "%#d");
#else
StringUtils::Replace(result, "M", "%-m");
StringUtils::Replace(result, "D", "%-d");
#endif
StringUtils::Replace(result, "YYYY", "%Y");
}
else if (strcmpi(id, "tempunit") == 0)
result = g_langInfo.GetTemperatureUnitString();
else if (strcmpi(id, "speedunit") == 0)
result = g_langInfo.GetSpeedUnitString();
else if (strcmpi(id, "time") == 0)
{
result = g_langInfo.GetTimeFormat();
StringUtils::Replace(result, "H", "%H");
StringUtils::Replace(result, "h", "%I");
StringUtils::Replace(result, "mm", "%M");
StringUtils::Replace(result, "ss", "%S");
StringUtils::Replace(result, "xx", "%p");
}
else if (strcmpi(id, "meridiem") == 0)
result = StringUtils::Format("%s/%s",
g_langInfo.GetMeridiemSymbol(MeridiemSymbolAM).c_str(),
g_langInfo.GetMeridiemSymbol(MeridiemSymbolPM).c_str());
else
{
CLog::Log(LOGERROR, "Interface_General::%s - add-on '%s' requests invalid id '%s'",
__FUNCTION__, addon->Name().c_str(), id);
return nullptr;
}
char* buffer = strdup(result.c_str());
return buffer;
}
void Interface_General::get_free_mem(void* kodiBase, long* free, long* total, bool as_bytes)
{
CAddonDll* addon = static_cast<CAddonDll*>(kodiBase);
if (addon == nullptr || free == nullptr || total == nullptr)
{
CLog::Log(LOGERROR, "Interface_General::%s - invalid data (addon='%p', free='%p', total='%p')", __FUNCTION__, addon, free, total);
return;
}
MEMORYSTATUSEX stat;
stat.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&stat);
*free = static_cast<long>(stat.ullAvailPhys);
*total = static_cast<long>(stat.ullTotalPhys);
if (!as_bytes)
{
*free = *free / ( 1024 * 1024 );
*total = *total / ( 1024 * 1024 );
}
}
int Interface_General::get_global_idle_time(void* kodiBase)
{
CAddonDll* addon = static_cast<CAddonDll*>(kodiBase);
if (addon == nullptr)
{
CLog::Log(LOGERROR, "Interface_General::%s - invalid data (addon='%p')", __FUNCTION__, addon);
return -1;
}
return g_application.GlobalIdleTime();
}
char* Interface_General::get_current_skin_id(void* kodiBase)
{
CAddonDll* addon = static_cast<CAddonDll*>(kodiBase);
if (addon == nullptr)
{
CLog::Log(LOGERROR, "Interface_General::%s - invalid data (addon='%p')", __FUNCTION__, addon);
return nullptr;
}
return strdup(CServiceBroker::GetSettings().GetString(CSettings::SETTING_LOOKANDFEEL_SKIN).c_str());
}
void Interface_General::kodi_version(void* kodiBase, char** compile_name, int* major, int* minor, char** revision, char** tag, char** tagversion)
{
CAddonDll* addon = static_cast<CAddonDll*>(kodiBase);
if (addon == nullptr || compile_name == nullptr || major == nullptr || minor == nullptr ||
revision == nullptr || tag == nullptr || tagversion == nullptr)
{
CLog::Log(LOGERROR, "Interface_General::%s - invalid data (addon='%p', compile_name='%p', major='%p', minor='%p', revision='%p', tag='%p', tagversion='%p')",
__FUNCTION__, addon, compile_name, major, minor, revision, tag, tagversion);
return;
}
*compile_name = strdup(CCompileInfo::GetAppName());
*major = CCompileInfo::GetMajor();
*minor = CCompileInfo::GetMinor();
*revision = strdup(CCompileInfo::GetSCMID());
std::string tagStr = CCompileInfo::GetSuffix();
if (StringUtils::StartsWithNoCase(tagStr, "alpha"))
{
*tag = strdup("alpha");
*tagversion = strdup(StringUtils::Mid(tagStr, 5).c_str());
}
else if (StringUtils::StartsWithNoCase(tagStr, "beta"))
{
*tag = strdup("beta");
*tagversion = strdup(StringUtils::Mid(tagStr, 4).c_str());
}
else if (StringUtils::StartsWithNoCase(tagStr, "rc"))
{
*tag = strdup("releasecandidate");
*tagversion = strdup(StringUtils::Mid(tagStr, 2).c_str());
}
else if (tagStr.empty())
*tag = strdup("stable");
else
*tag = strdup("prealpha");
}
} /* namespace ADDON */
| cedricde/xbmc | xbmc/addons/interfaces/General.cpp | C++ | gpl-2.0 | 15,299 |
/*
* Copyright (C) 2002-2011 The DOSBox Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "dosbox.h"
#if C_DEBUG
#include <string.h>
#include <list>
#include <ctype.h>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
#include "debug.h"
#include "cross.h" //snprintf
#include "cpu.h"
#include "video.h"
#include "pic.h"
#include "mapper.h"
#include "cpu.h"
#include "callback.h"
#include "inout.h"
#include "mixer.h"
#include "timer.h"
#include "paging.h"
#include "support.h"
#include "shell.h"
#include "programs.h"
#include "debug_inc.h"
#include "../cpu/lazyflags.h"
#include "keyboard.h"
#include "setup.h"
#ifdef WIN32
void WIN32_Console();
#else
#include <termios.h>
#include <unistd.h>
static struct termios consolesettings;
#endif
int old_cursor_state;
// Forwards
static void DrawCode(void);
static void DEBUG_RaiseTimerIrq(void);
static void SaveMemory(Bitu seg, Bitu ofs1, Bit32u num);
static void SaveMemoryBin(Bitu seg, Bitu ofs1, Bit32u num);
static void LogMCBS(void);
static void LogGDT(void);
static void LogLDT(void);
static void LogIDT(void);
static void LogPages(char* selname);
static void LogCPUInfo(void);
static void OutputVecTable(char* filename);
static void DrawVariables(void);
char* AnalyzeInstruction(char* inst, bool saveSelector);
Bit32u GetHexValue(char* str, char*& hex);
#if 0
class DebugPageHandler : public PageHandler {
public:
Bitu readb(PhysPt /*addr*/) {
}
Bitu readw(PhysPt /*addr*/) {
}
Bitu readd(PhysPt /*addr*/) {
}
void writeb(PhysPt /*addr*/,Bitu /*val*/) {
}
void writew(PhysPt /*addr*/,Bitu /*val*/) {
}
void writed(PhysPt /*addr*/,Bitu /*val*/) {
}
};
#endif
class DEBUG;
DEBUG* pDebugcom = 0;
bool exitLoop = false;
// Heavy Debugging Vars for logging
#if C_HEAVY_DEBUG
static ofstream cpuLogFile;
static bool cpuLog = false;
static int cpuLogCounter = 0;
static int cpuLogType = 1; // log detail
static bool zeroProtect = false;
bool logHeavy = false;
#endif
static struct {
Bit32u eax,ebx,ecx,edx,esi,edi,ebp,esp,eip;
} oldregs;
static char curSelectorName[3] = { 0,0,0 };
static Segment oldsegs[6];
static Bitu oldflags,oldcpucpl;
DBGBlock dbg;
Bitu cycle_count;
static bool debugging;
static void SetColor(Bitu test) {
if (test) {
if (has_colors()) { wattrset(dbg.win_reg,COLOR_PAIR(PAIR_BYELLOW_BLACK));}
} else {
if (has_colors()) { wattrset(dbg.win_reg,0);}
}
}
#define MAXCMDLEN 254
struct SCodeViewData {
int cursorPos;
Bit16u firstInstSize;
Bit16u useCS;
Bit32u useEIPlast, useEIPmid;
Bit32u useEIP;
Bit16u cursorSeg;
Bit32u cursorOfs;
bool ovrMode;
char inputStr[MAXCMDLEN+1];
char suspInputStr[MAXCMDLEN+1];
int inputPos;
} codeViewData;
static Bit16u dataSeg;
static Bit32u dataOfs;
static bool showExtend = true;
static void ClearInputLine(void) {
codeViewData.inputStr[0] = 0;
codeViewData.inputPos = 0;
}
// History stuff
#define MAX_HIST_BUFFER 50
static list<string> histBuff;
static list<string>::iterator histBuffPos = histBuff.end();
/***********/
/* Helpers */
/***********/
Bit32u PhysMakeProt(Bit16u selector, Bit32u offset)
{
Descriptor desc;
if (cpu.gdt.GetDescriptor(selector,desc)) return desc.GetBase()+offset;
return 0;
};
Bit32u GetAddress(Bit16u seg, Bit32u offset)
{
if (seg==SegValue(cs)) return SegPhys(cs)+offset;
if (cpu.pmode && !(reg_flags & FLAG_VM)) {
Descriptor desc;
if (cpu.gdt.GetDescriptor(seg,desc)) return PhysMakeProt(seg,offset);
}
return (seg<<4)+offset;
}
static char empty_sel[] = { ' ',' ',0 };
bool GetDescriptorInfo(char* selname, char* out1, char* out2)
{
Bitu sel;
Descriptor desc;
if (strstr(selname,"cs") || strstr(selname,"CS")) sel = SegValue(cs);
else if (strstr(selname,"ds") || strstr(selname,"DS")) sel = SegValue(ds);
else if (strstr(selname,"es") || strstr(selname,"ES")) sel = SegValue(es);
else if (strstr(selname,"fs") || strstr(selname,"FS")) sel = SegValue(fs);
else if (strstr(selname,"gs") || strstr(selname,"GS")) sel = SegValue(gs);
else if (strstr(selname,"ss") || strstr(selname,"SS")) sel = SegValue(ss);
else {
sel = GetHexValue(selname,selname);
if (*selname==0) selname=empty_sel;
}
if (cpu.gdt.GetDescriptor(sel,desc)) {
switch (desc.Type()) {
case DESC_TASK_GATE:
sprintf(out1,"%s: s:%08X type:%02X p",selname,desc.GetSelector(),desc.desc.gate.type);
sprintf(out2," TaskGate dpl : %01X %1X",desc.desc.gate.dpl,desc.desc.gate.p);
return true;
case DESC_LDT:
case DESC_286_TSS_A:
case DESC_286_TSS_B:
case DESC_386_TSS_A:
case DESC_386_TSS_B:
sprintf(out1,"%s: b:%08X type:%02X pag",selname,desc.GetBase(),desc.desc.seg.type);
sprintf(out2," l:%08X dpl : %01X %1X%1X%1X",desc.GetLimit(),desc.desc.seg.dpl,desc.desc.seg.p,desc.desc.seg.avl,desc.desc.seg.g);
return true;
case DESC_286_CALL_GATE:
case DESC_386_CALL_GATE:
sprintf(out1,"%s: s:%08X type:%02X p params: %02X",selname,desc.GetSelector(),desc.desc.gate.type,desc.desc.gate.paramcount);
sprintf(out2," o:%08X dpl : %01X %1X",desc.GetOffset(),desc.desc.gate.dpl,desc.desc.gate.p);
return true;
case DESC_286_INT_GATE:
case DESC_286_TRAP_GATE:
case DESC_386_INT_GATE:
case DESC_386_TRAP_GATE:
sprintf(out1,"%s: s:%08X type:%02X p",selname,desc.GetSelector(),desc.desc.gate.type);
sprintf(out2," o:%08X dpl : %01X %1X",desc.GetOffset(),desc.desc.gate.dpl,desc.desc.gate.p);
return true;
}
sprintf(out1,"%s: b:%08X type:%02X parbg",selname,desc.GetBase(),desc.desc.seg.type);
sprintf(out2," l:%08X dpl : %01X %1X%1X%1X%1X%1X",desc.GetLimit(),desc.desc.seg.dpl,desc.desc.seg.p,desc.desc.seg.avl,desc.desc.seg.r,desc.desc.seg.big,desc.desc.seg.g);
return true;
} else {
strcpy(out1," ");
strcpy(out2," ");
}
return false;
};
/********************/
/* DebugVar stuff */
/********************/
class CDebugVar
{
public:
CDebugVar(char* _name, PhysPt _adr) { adr=_adr; safe_strncpy(name,_name,16); };
char* GetName(void) { return name; };
PhysPt GetAdr (void) { return adr; };
private:
PhysPt adr;
char name[16];
public:
static void InsertVariable (char* name, PhysPt adr);
static CDebugVar* FindVar (PhysPt adr);
static void DeleteAll ();
static bool SaveVars (char* name);
static bool LoadVars (char* name);
static std::list<CDebugVar*> varList;
};
std::list<CDebugVar*> CDebugVar::varList;
/********************/
/* Breakpoint stuff */
/********************/
bool skipFirstInstruction = false;
enum EBreakpoint { BKPNT_UNKNOWN, BKPNT_PHYSICAL, BKPNT_INTERRUPT, BKPNT_MEMORY, BKPNT_MEMORY_PROT, BKPNT_MEMORY_LINEAR };
#define BPINT_ALL 0x100
class CBreakpoint
{
public:
CBreakpoint(void);
void SetAddress (Bit16u seg, Bit32u off) { location = GetAddress(seg,off); type = BKPNT_PHYSICAL; segment = seg; offset = off; };
void SetAddress (PhysPt adr) { location = adr; type = BKPNT_PHYSICAL; };
void SetInt (Bit8u _intNr, Bit16u ah) { intNr = _intNr, ahValue = ah; type = BKPNT_INTERRUPT; };
void SetOnce (bool _once) { once = _once; };
void SetType (EBreakpoint _type) { type = _type; };
void SetValue (Bit8u value) { ahValue = value; };
bool IsActive (void) { return active; };
void Activate (bool _active);
EBreakpoint GetType (void) { return type; };
bool GetOnce (void) { return once; };
PhysPt GetLocation (void) { if (GetType()!=BKPNT_INTERRUPT) return location; else return 0; };
Bit16u GetSegment (void) { return segment; };
Bit32u GetOffset (void) { return offset; };
Bit8u GetIntNr (void) { if (GetType()==BKPNT_INTERRUPT) return intNr; else return 0; };
Bit16u GetValue (void) { if (GetType()!=BKPNT_PHYSICAL) return ahValue; else return 0; };
// statics
static CBreakpoint* AddBreakpoint (Bit16u seg, Bit32u off, bool once);
static CBreakpoint* AddIntBreakpoint (Bit8u intNum, Bit16u ah, bool once);
static CBreakpoint* AddMemBreakpoint (Bit16u seg, Bit32u off);
static void ActivateBreakpoints (PhysPt adr, bool activate);
static bool CheckBreakpoint (PhysPt adr);
static bool CheckBreakpoint (Bitu seg, Bitu off);
static bool CheckIntBreakpoint (PhysPt adr, Bit8u intNr, Bit16u ahValue);
static bool IsBreakpoint (PhysPt where);
static bool IsBreakpointDrawn (PhysPt where);
static bool DeleteBreakpoint (PhysPt where);
static bool DeleteByIndex (Bit16u index);
static void DeleteAll (void);
static void ShowList (void);
private:
EBreakpoint type;
// Physical
PhysPt location;
Bit8u oldData;
Bit16u segment;
Bit32u offset;
// Int
Bit8u intNr;
Bit16u ahValue;
// Shared
bool active;
bool once;
static std::list<CBreakpoint*> BPoints;
public:
static CBreakpoint* ignoreOnce;
};
CBreakpoint::CBreakpoint(void):
location(0),
active(false),once(false),
segment(0),offset(0),intNr(0),ahValue(0),
type(BKPNT_UNKNOWN) { };
void CBreakpoint::Activate(bool _active)
{
#if !C_HEAVY_DEBUG
if (GetType()==BKPNT_PHYSICAL) {
if (_active) {
// Set 0xCC and save old value
Bit8u data = mem_readb(location);
if (data!=0xCC) {
oldData = data;
mem_writeb(location,0xCC);
};
} else {
// Remove 0xCC and set old value
if (mem_readb (location)==0xCC) {
mem_writeb(location,oldData);
};
}
}
#endif
active = _active;
};
// Statics
std::list<CBreakpoint*> CBreakpoint::BPoints;
CBreakpoint* CBreakpoint::ignoreOnce = 0;
Bitu ignoreAddressOnce = 0;
CBreakpoint* CBreakpoint::AddBreakpoint(Bit16u seg, Bit32u off, bool once)
{
CBreakpoint* bp = new CBreakpoint();
bp->SetAddress (seg,off);
bp->SetOnce (once);
BPoints.push_front (bp);
return bp;
};
CBreakpoint* CBreakpoint::AddIntBreakpoint(Bit8u intNum, Bit16u ah, bool once)
{
CBreakpoint* bp = new CBreakpoint();
bp->SetInt (intNum,ah);
bp->SetOnce (once);
BPoints.push_front (bp);
return bp;
};
CBreakpoint* CBreakpoint::AddMemBreakpoint(Bit16u seg, Bit32u off)
{
CBreakpoint* bp = new CBreakpoint();
bp->SetAddress (seg,off);
bp->SetOnce (false);
bp->SetType (BKPNT_MEMORY);
BPoints.push_front (bp);
return bp;
};
void CBreakpoint::ActivateBreakpoints(PhysPt adr, bool activate)
{
// activate all breakpoints
std::list<CBreakpoint*>::iterator i;
CBreakpoint* bp;
for(i=BPoints.begin(); i != BPoints.end(); i++) {
bp = (*i);
// Do not activate, when bp is an actual address
if (activate && (bp->GetType()==BKPNT_PHYSICAL) && (bp->GetLocation()==adr)) {
// Do not activate :)
continue;
}
bp->Activate(activate);
};
};
bool CBreakpoint::CheckBreakpoint(Bitu seg, Bitu off)
// Checks if breakpoint is valid and should stop execution
{
if ((ignoreAddressOnce!=0) && (GetAddress(seg,off)==ignoreAddressOnce)) {
ignoreAddressOnce = 0;
return false;
} else
ignoreAddressOnce = 0;
// Search matching breakpoint
std::list<CBreakpoint*>::iterator i;
CBreakpoint* bp;
for(i=BPoints.begin(); i != BPoints.end(); i++) {
bp = (*i);
if ((bp->GetType()==BKPNT_PHYSICAL) && bp->IsActive() && (bp->GetSegment()==seg) && (bp->GetOffset()==off)) {
// Ignore Once ?
if (ignoreOnce==bp) {
ignoreOnce=0;
bp->Activate(true);
return false;
};
// Found,
if (bp->GetOnce()) {
// delete it, if it should only be used once
(BPoints.erase)(i);
bp->Activate(false);
delete bp;
} else {
ignoreOnce = bp;
};
return true;
}
#if C_HEAVY_DEBUG
// Memory breakpoint support
else if (bp->IsActive()) {
if ((bp->GetType()==BKPNT_MEMORY) || (bp->GetType()==BKPNT_MEMORY_PROT) || (bp->GetType()==BKPNT_MEMORY_LINEAR)) {
// Watch Protected Mode Memoryonly in pmode
if (bp->GetType()==BKPNT_MEMORY_PROT) {
// Check if pmode is active
if (!cpu.pmode) return false;
// Check if descriptor is valid
Descriptor desc;
if (!cpu.gdt.GetDescriptor(bp->GetSegment(),desc)) return false;
if (desc.GetLimit()==0) return false;
}
Bitu address;
if (bp->GetType()==BKPNT_MEMORY_LINEAR) address = bp->GetOffset();
else address = GetAddress(bp->GetSegment(),bp->GetOffset());
Bit8u value=0;
if (mem_readb_checked(address,&value)) return false;
if (bp->GetValue() != value) {
// Yup, memory value changed
DEBUG_ShowMsg("DEBUG: Memory breakpoint %s: %04X:%04X - %02X -> %02X\n",(bp->GetType()==BKPNT_MEMORY_PROT)?"(Prot)":"",bp->GetSegment(),bp->GetOffset(),bp->GetValue(),value);
bp->SetValue(value);
return true;
};
}
};
#endif
};
return false;
};
bool CBreakpoint::CheckIntBreakpoint(PhysPt adr, Bit8u intNr, Bit16u ahValue)
// Checks if interrupt breakpoint is valid and should stop execution
{
if ((ignoreAddressOnce!=0) && (adr==ignoreAddressOnce)) {
ignoreAddressOnce = 0;
return false;
} else
ignoreAddressOnce = 0;
// Search matching breakpoint
std::list<CBreakpoint*>::iterator i;
CBreakpoint* bp;
for(i=BPoints.begin(); i != BPoints.end(); i++) {
bp = (*i);
if ((bp->GetType()==BKPNT_INTERRUPT) && bp->IsActive() && (bp->GetIntNr()==intNr)) {
if ((bp->GetValue()==BPINT_ALL) || (bp->GetValue()==ahValue)) {
// Ignore it once ?
if (ignoreOnce==bp) {
ignoreOnce=0;
bp->Activate(true);
return false;
};
// Found
if (bp->GetOnce()) {
// delete it, if it should only be used once
(BPoints.erase)(i);
bp->Activate(false);
delete bp;
} else {
ignoreOnce = bp;
}
return true;
}
};
};
return false;
};
void CBreakpoint::DeleteAll()
{
std::list<CBreakpoint*>::iterator i;
CBreakpoint* bp;
for(i=BPoints.begin(); i != BPoints.end(); i++) {
bp = (*i);
bp->Activate(false);
delete bp;
};
(BPoints.clear)();
};
bool CBreakpoint::DeleteByIndex(Bit16u index)
{
// Search matching breakpoint
int nr = 0;
std::list<CBreakpoint*>::iterator i;
CBreakpoint* bp;
for(i=BPoints.begin(); i != BPoints.end(); i++) {
if (nr==index) {
bp = (*i);
(BPoints.erase)(i);
bp->Activate(false);
delete bp;
return true;
}
nr++;
};
return false;
};
bool CBreakpoint::DeleteBreakpoint(PhysPt where)
{
// Search matching breakpoint
std::list<CBreakpoint*>::iterator i;
CBreakpoint* bp;
for(i=BPoints.begin(); i != BPoints.end(); i++) {
bp = (*i);
if ((bp->GetType()==BKPNT_PHYSICAL) && (bp->GetLocation()==where)) {
(BPoints.erase)(i);
bp->Activate(false);
delete bp;
return true;
}
};
return false;
};
bool CBreakpoint::IsBreakpoint(PhysPt adr)
// is there a breakpoint at address ?
{
// Search matching breakpoint
std::list<CBreakpoint*>::iterator i;
CBreakpoint* bp;
for(i=BPoints.begin(); i != BPoints.end(); i++) {
bp = (*i);
if ((bp->GetType()==BKPNT_PHYSICAL) && (bp->GetSegment()==adr)) {
return true;
};
if ((bp->GetType()==BKPNT_PHYSICAL) && (bp->GetLocation()==adr)) {
return true;
};
};
return false;
};
bool CBreakpoint::IsBreakpointDrawn(PhysPt adr)
// valid breakpoint, that should be drawn ?
{
// Search matching breakpoint
std::list<CBreakpoint*>::iterator i;
CBreakpoint* bp;
for(i=BPoints.begin(); i != BPoints.end(); i++) {
bp = (*i);
if ((bp->GetType()==BKPNT_PHYSICAL) && (bp->GetLocation()==adr)) {
// Only draw, if breakpoint is not only once,
return !bp->GetOnce();
};
};
return false;
};
void CBreakpoint::ShowList(void)
{
// iterate list
int nr = 0;
std::list<CBreakpoint*>::iterator i;
for(i=BPoints.begin(); i != BPoints.end(); i++) {
CBreakpoint* bp = (*i);
if (bp->GetType()==BKPNT_PHYSICAL) {
DEBUG_ShowMsg("%02X. BP %04X:%04X\n",nr,bp->GetSegment(),bp->GetOffset());
} else if (bp->GetType()==BKPNT_INTERRUPT) {
if (bp->GetValue()==BPINT_ALL) DEBUG_ShowMsg("%02X. BPINT %02X\n",nr,bp->GetIntNr());
else DEBUG_ShowMsg("%02X. BPINT %02X AH=%02X\n",nr,bp->GetIntNr(),bp->GetValue());
} else if (bp->GetType()==BKPNT_MEMORY) {
DEBUG_ShowMsg("%02X. BPMEM %04X:%04X (%02X)\n",nr,bp->GetSegment(),bp->GetOffset(),bp->GetValue());
} else if (bp->GetType()==BKPNT_MEMORY_PROT) {
DEBUG_ShowMsg("%02X. BPPM %04X:%08X (%02X)\n",nr,bp->GetSegment(),bp->GetOffset(),bp->GetValue());
} else if (bp->GetType()==BKPNT_MEMORY_LINEAR ) {
DEBUG_ShowMsg("%02X. BPLM %08X (%02X)\n",nr,bp->GetOffset(),bp->GetValue());
};
nr++;
}
};
bool DEBUG_Breakpoint(void)
{
/* First get the phyiscal address and check for a set Breakpoint */
if (!CBreakpoint::CheckBreakpoint(SegValue(cs),reg_eip)) return false;
// Found. Breakpoint is valid
PhysPt where=GetAddress(SegValue(cs),reg_eip);
CBreakpoint::ActivateBreakpoints(where,false); // Deactivate all breakpoints
return true;
};
bool DEBUG_IntBreakpoint(Bit8u intNum)
{
/* First get the phyiscal address and check for a set Breakpoint */
PhysPt where=GetAddress(SegValue(cs),reg_eip);
if (!CBreakpoint::CheckIntBreakpoint(where,intNum,reg_ah)) return false;
// Found. Breakpoint is valid
CBreakpoint::ActivateBreakpoints(where,false); // Deactivate all breakpoints
return true;
};
static bool StepOver()
{
exitLoop = false;
PhysPt start=GetAddress(SegValue(cs),reg_eip);
char dline[200];Bitu size;
size=DasmI386(dline, start, reg_eip, cpu.code.big);
if (strstr(dline,"call") || strstr(dline,"int") || strstr(dline,"loop") || strstr(dline,"rep")) {
CBreakpoint::AddBreakpoint (SegValue(cs),reg_eip+size, true);
CBreakpoint::ActivateBreakpoints(start, true);
debugging=false;
DrawCode();
DOSBOX_SetNormalLoop();
return true;
}
return false;
};
bool DEBUG_ExitLoop(void)
{
#if C_HEAVY_DEBUG
DrawVariables();
#endif
if (exitLoop) {
exitLoop = false;
return true;
}
return false;
};
/********************/
/* Draw windows */
/********************/
static void DrawData(void) {
Bit8u ch;
Bit32u add = dataOfs;
Bit32u address;
/* Data win */
for (int y=0; y<8; y++) {
// Address
if (add<0x10000) mvwprintw (dbg.win_data,1+y,0,"%04X:%04X ",dataSeg,add);
else mvwprintw (dbg.win_data,1+y,0,"%04X:%08X ",dataSeg,add);
for (int x=0; x<16; x++) {
address = GetAddress(dataSeg,add);
if (mem_readb_checked(address,&ch)) ch=0;
mvwprintw (dbg.win_data,1+y,14+3*x,"%02X",ch);
if (ch<32 || !isprint(*reinterpret_cast<unsigned char*>(&ch))) ch='.';
mvwprintw (dbg.win_data,1+y,63+x,"%c",ch);
add++;
};
}
wrefresh(dbg.win_data);
};
static void DrawRegisters(void) {
/* Main Registers */
SetColor(reg_eax!=oldregs.eax);oldregs.eax=reg_eax;mvwprintw (dbg.win_reg,0,4,"%08X",reg_eax);
SetColor(reg_ebx!=oldregs.ebx);oldregs.ebx=reg_ebx;mvwprintw (dbg.win_reg,1,4,"%08X",reg_ebx);
SetColor(reg_ecx!=oldregs.ecx);oldregs.ecx=reg_ecx;mvwprintw (dbg.win_reg,2,4,"%08X",reg_ecx);
SetColor(reg_edx!=oldregs.edx);oldregs.edx=reg_edx;mvwprintw (dbg.win_reg,3,4,"%08X",reg_edx);
SetColor(reg_esi!=oldregs.esi);oldregs.esi=reg_esi;mvwprintw (dbg.win_reg,0,18,"%08X",reg_esi);
SetColor(reg_edi!=oldregs.edi);oldregs.edi=reg_edi;mvwprintw (dbg.win_reg,1,18,"%08X",reg_edi);
SetColor(reg_ebp!=oldregs.ebp);oldregs.ebp=reg_ebp;mvwprintw (dbg.win_reg,2,18,"%08X",reg_ebp);
SetColor(reg_esp!=oldregs.esp);oldregs.esp=reg_esp;mvwprintw (dbg.win_reg,3,18,"%08X",reg_esp);
SetColor(reg_eip!=oldregs.eip);oldregs.eip=reg_eip;mvwprintw (dbg.win_reg,1,42,"%08X",reg_eip);
SetColor(SegValue(ds)!=oldsegs[ds].val);oldsegs[ds].val=SegValue(ds);mvwprintw (dbg.win_reg,0,31,"%04X",SegValue(ds));
SetColor(SegValue(es)!=oldsegs[es].val);oldsegs[es].val=SegValue(es);mvwprintw (dbg.win_reg,0,41,"%04X",SegValue(es));
SetColor(SegValue(fs)!=oldsegs[fs].val);oldsegs[fs].val=SegValue(fs);mvwprintw (dbg.win_reg,0,51,"%04X",SegValue(fs));
SetColor(SegValue(gs)!=oldsegs[gs].val);oldsegs[gs].val=SegValue(gs);mvwprintw (dbg.win_reg,0,61,"%04X",SegValue(gs));
SetColor(SegValue(ss)!=oldsegs[ss].val);oldsegs[ss].val=SegValue(ss);mvwprintw (dbg.win_reg,0,71,"%04X",SegValue(ss));
SetColor(SegValue(cs)!=oldsegs[cs].val);oldsegs[cs].val=SegValue(cs);mvwprintw (dbg.win_reg,1,31,"%04X",SegValue(cs));
/*Individual flags*/
Bitu changed_flags = reg_flags ^ oldflags;
oldflags = reg_flags;
SetColor(changed_flags&FLAG_CF);
mvwprintw (dbg.win_reg,1,53,"%01X",GETFLAG(CF) ? 1:0);
SetColor(changed_flags&FLAG_ZF);
mvwprintw (dbg.win_reg,1,56,"%01X",GETFLAG(ZF) ? 1:0);
SetColor(changed_flags&FLAG_SF);
mvwprintw (dbg.win_reg,1,59,"%01X",GETFLAG(SF) ? 1:0);
SetColor(changed_flags&FLAG_OF);
mvwprintw (dbg.win_reg,1,62,"%01X",GETFLAG(OF) ? 1:0);
SetColor(changed_flags&FLAG_AF);
mvwprintw (dbg.win_reg,1,65,"%01X",GETFLAG(AF) ? 1:0);
SetColor(changed_flags&FLAG_PF);
mvwprintw (dbg.win_reg,1,68,"%01X",GETFLAG(PF) ? 1:0);
SetColor(changed_flags&FLAG_DF);
mvwprintw (dbg.win_reg,1,71,"%01X",GETFLAG(DF) ? 1:0);
SetColor(changed_flags&FLAG_IF);
mvwprintw (dbg.win_reg,1,74,"%01X",GETFLAG(IF) ? 1:0);
SetColor(changed_flags&FLAG_TF);
mvwprintw (dbg.win_reg,1,77,"%01X",GETFLAG(TF) ? 1:0);
SetColor(changed_flags&FLAG_IOPL);
mvwprintw (dbg.win_reg,2,72,"%01X",GETFLAG(IOPL)>>12);
SetColor(cpu.cpl ^ oldcpucpl);
mvwprintw (dbg.win_reg,2,78,"%01X",cpu.cpl);
oldcpucpl=cpu.cpl;
if (cpu.pmode) {
if (reg_flags & FLAG_VM) mvwprintw(dbg.win_reg,0,76,"VM86");
else if (cpu.code.big) mvwprintw(dbg.win_reg,0,76,"Pr32");
else mvwprintw(dbg.win_reg,0,76,"Pr16");
} else
mvwprintw(dbg.win_reg,0,76,"Real");
// Selector info, if available
if ((cpu.pmode) && curSelectorName[0]) {
char out1[200], out2[200];
GetDescriptorInfo(curSelectorName,out1,out2);
mvwprintw(dbg.win_reg,2,28,out1);
mvwprintw(dbg.win_reg,3,28,out2);
}
wattrset(dbg.win_reg,0);
mvwprintw(dbg.win_reg,3,60,"%u ",cycle_count);
wrefresh(dbg.win_reg);
};
static void DrawCode(void) {
bool saveSel;
Bit32u disEIP = codeViewData.useEIP;
PhysPt start = GetAddress(codeViewData.useCS,codeViewData.useEIP);
char dline[200];Bitu size;Bitu c;
static char line20[21] = " ";
for (int i=0;i<10;i++) {
saveSel = false;
if (has_colors()) {
if ((codeViewData.useCS==SegValue(cs)) && (disEIP == reg_eip)) {
wattrset(dbg.win_code,COLOR_PAIR(PAIR_GREEN_BLACK));
if (codeViewData.cursorPos==-1) {
codeViewData.cursorPos = i; // Set Cursor
}
if (i == codeViewData.cursorPos) {
codeViewData.cursorSeg = SegValue(cs);
codeViewData.cursorOfs = disEIP;
}
saveSel = (i == codeViewData.cursorPos);
} else if (i == codeViewData.cursorPos) {
wattrset(dbg.win_code,COLOR_PAIR(PAIR_BLACK_GREY));
codeViewData.cursorSeg = codeViewData.useCS;
codeViewData.cursorOfs = disEIP;
saveSel = true;
} else if (CBreakpoint::IsBreakpointDrawn(start)) {
wattrset(dbg.win_code,COLOR_PAIR(PAIR_GREY_RED));
} else {
wattrset(dbg.win_code,0);
}
}
Bitu drawsize=size=DasmI386(dline, start, disEIP, cpu.code.big);
bool toolarge = false;
mvwprintw(dbg.win_code,i,0,"%04X:%04X ",codeViewData.useCS,disEIP);
if (drawsize>10) { toolarge = true; drawsize = 9; };
for (c=0;c<drawsize;c++) {
Bit8u value;
if (mem_readb_checked(start+c,&value)) value=0;
wprintw(dbg.win_code,"%02X",value);
}
if (toolarge) { waddstr(dbg.win_code,".."); drawsize++; };
// Spacepad up to 20 characters
if(drawsize && (drawsize < 11)) {
line20[20 - drawsize*2] = 0;
waddstr(dbg.win_code,line20);
line20[20 - drawsize*2] = ' ';
} else waddstr(dbg.win_code,line20);
char empty_res[] = { 0 };
char* res = empty_res;
if (showExtend) res = AnalyzeInstruction(dline, saveSel);
// Spacepad it up to 28 characters
size_t dline_len = strlen(dline);
if(dline_len < 28) for (c = dline_len; c < 28;c++) dline[c] = ' '; dline[28] = 0;
waddstr(dbg.win_code,dline);
// Spacepad it up to 20 characters
size_t res_len = strlen(res);
if(res_len && (res_len < 21)) {
waddstr(dbg.win_code,res);
line20[20-res_len] = 0;
waddstr(dbg.win_code,line20);
line20[20-res_len] = ' ';
} else waddstr(dbg.win_code,line20);
start+=size;
disEIP+=size;
if (i==0) codeViewData.firstInstSize = size;
if (i==4) codeViewData.useEIPmid = disEIP;
}
codeViewData.useEIPlast = disEIP;
wattrset(dbg.win_code,0);
if (!debugging) {
mvwprintw(dbg.win_code,10,0,"%s","(Running)");
wclrtoeol(dbg.win_code);
} else {
//TODO long lines
char* dispPtr = codeViewData.inputStr;
char* curPtr = &codeViewData.inputStr[codeViewData.inputPos];
mvwprintw(dbg.win_code,10,0,"%c-> %s%c",
(codeViewData.ovrMode?'O':'I'),dispPtr,(*curPtr?' ':'_'));
wclrtoeol(dbg.win_code); // not correct in pdcurses if full line
if (*curPtr) {
mvwchgat(dbg.win_code,10,(curPtr-dispPtr+4),1,0,(PAIR_BLACK_GREY),NULL);
}
}
wrefresh(dbg.win_code);
}
static void SetCodeWinStart()
{
if ((SegValue(cs)==codeViewData.useCS) && (reg_eip>=codeViewData.useEIP) && (reg_eip<=codeViewData.useEIPlast)) {
// in valid window - scroll ?
if (reg_eip>=codeViewData.useEIPmid) codeViewData.useEIP += codeViewData.firstInstSize;
} else {
// totally out of range.
codeViewData.useCS = SegValue(cs);
codeViewData.useEIP = reg_eip;
}
codeViewData.cursorPos = -1; // Recalc Cursor position
};
/********************/
/* User input */
/********************/
Bit32u GetHexValue(char* str, char*& hex)
{
Bit32u value = 0;
Bit32u regval = 0;
hex = str;
while (*hex==' ') hex++;
if (strstr(hex,"EAX")==hex) { hex+=3; regval = reg_eax; };
if (strstr(hex,"EBX")==hex) { hex+=3; regval = reg_ebx; };
if (strstr(hex,"ECX")==hex) { hex+=3; regval = reg_ecx; };
if (strstr(hex,"EDX")==hex) { hex+=3; regval = reg_edx; };
if (strstr(hex,"ESI")==hex) { hex+=3; regval = reg_esi; };
if (strstr(hex,"EDI")==hex) { hex+=3; regval = reg_edi; };
if (strstr(hex,"EBP")==hex) { hex+=3; regval = reg_ebp; };
if (strstr(hex,"ESP")==hex) { hex+=3; regval = reg_esp; };
if (strstr(hex,"EIP")==hex) { hex+=3; regval = reg_eip; };
if (strstr(hex,"AX")==hex) { hex+=2; regval = reg_ax; };
if (strstr(hex,"BX")==hex) { hex+=2; regval = reg_bx; };
if (strstr(hex,"CX")==hex) { hex+=2; regval = reg_cx; };
if (strstr(hex,"DX")==hex) { hex+=2; regval = reg_dx; };
if (strstr(hex,"SI")==hex) { hex+=2; regval = reg_si; };
if (strstr(hex,"DI")==hex) { hex+=2; regval = reg_di; };
if (strstr(hex,"BP")==hex) { hex+=2; regval = reg_bp; };
if (strstr(hex,"SP")==hex) { hex+=2; regval = reg_sp; };
if (strstr(hex,"IP")==hex) { hex+=2; regval = reg_ip; };
if (strstr(hex,"CS")==hex) { hex+=2; regval = SegValue(cs); };
if (strstr(hex,"DS")==hex) { hex+=2; regval = SegValue(ds); };
if (strstr(hex,"ES")==hex) { hex+=2; regval = SegValue(es); };
if (strstr(hex,"FS")==hex) { hex+=2; regval = SegValue(fs); };
if (strstr(hex,"GS")==hex) { hex+=2; regval = SegValue(gs); };
if (strstr(hex,"SS")==hex) { hex+=2; regval = SegValue(ss); };
while (*hex) {
if ((*hex>='0') && (*hex<='9')) value = (value<<4)+*hex-'0';
else if ((*hex>='A') && (*hex<='F')) value = (value<<4)+*hex-'A'+10;
else {
if(*hex == '+') {hex++;return regval + value + GetHexValue(hex,hex); };
if(*hex == '-') {hex++;return regval + value - GetHexValue(hex,hex); };
break; // No valid char
}
hex++;
};
return regval + value;
};
bool ChangeRegister(char* str)
{
char* hex = str;
while (*hex==' ') hex++;
if (strstr(hex,"EAX")==hex) { hex+=3; reg_eax = GetHexValue(hex,hex); } else
if (strstr(hex,"EBX")==hex) { hex+=3; reg_ebx = GetHexValue(hex,hex); } else
if (strstr(hex,"ECX")==hex) { hex+=3; reg_ecx = GetHexValue(hex,hex); } else
if (strstr(hex,"EDX")==hex) { hex+=3; reg_edx = GetHexValue(hex,hex); } else
if (strstr(hex,"ESI")==hex) { hex+=3; reg_esi = GetHexValue(hex,hex); } else
if (strstr(hex,"EDI")==hex) { hex+=3; reg_edi = GetHexValue(hex,hex); } else
if (strstr(hex,"EBP")==hex) { hex+=3; reg_ebp = GetHexValue(hex,hex); } else
if (strstr(hex,"ESP")==hex) { hex+=3; reg_esp = GetHexValue(hex,hex); } else
if (strstr(hex,"EIP")==hex) { hex+=3; reg_eip = GetHexValue(hex,hex); } else
if (strstr(hex,"AX")==hex) { hex+=2; reg_ax = (Bit16u)GetHexValue(hex,hex); } else
if (strstr(hex,"BX")==hex) { hex+=2; reg_bx = (Bit16u)GetHexValue(hex,hex); } else
if (strstr(hex,"CX")==hex) { hex+=2; reg_cx = (Bit16u)GetHexValue(hex,hex); } else
if (strstr(hex,"DX")==hex) { hex+=2; reg_dx = (Bit16u)GetHexValue(hex,hex); } else
if (strstr(hex,"SI")==hex) { hex+=2; reg_si = (Bit16u)GetHexValue(hex,hex); } else
if (strstr(hex,"DI")==hex) { hex+=2; reg_di = (Bit16u)GetHexValue(hex,hex); } else
if (strstr(hex,"BP")==hex) { hex+=2; reg_bp = (Bit16u)GetHexValue(hex,hex); } else
if (strstr(hex,"SP")==hex) { hex+=2; reg_sp = (Bit16u)GetHexValue(hex,hex); } else
if (strstr(hex,"IP")==hex) { hex+=2; reg_ip = (Bit16u)GetHexValue(hex,hex); } else
if (strstr(hex,"CS")==hex) { hex+=2; SegSet16(cs,(Bit16u)GetHexValue(hex,hex)); } else
if (strstr(hex,"DS")==hex) { hex+=2; SegSet16(ds,(Bit16u)GetHexValue(hex,hex)); } else
if (strstr(hex,"ES")==hex) { hex+=2; SegSet16(es,(Bit16u)GetHexValue(hex,hex)); } else
if (strstr(hex,"FS")==hex) { hex+=2; SegSet16(fs,(Bit16u)GetHexValue(hex,hex)); } else
if (strstr(hex,"GS")==hex) { hex+=2; SegSet16(gs,(Bit16u)GetHexValue(hex,hex)); } else
if (strstr(hex,"SS")==hex) { hex+=2; SegSet16(ss,(Bit16u)GetHexValue(hex,hex)); } else
if (strstr(hex,"AF")==hex) { hex+=2; SETFLAGBIT(AF,GetHexValue(hex,hex)); } else
if (strstr(hex,"CF")==hex) { hex+=2; SETFLAGBIT(CF,GetHexValue(hex,hex)); } else
if (strstr(hex,"DF")==hex) { hex+=2; SETFLAGBIT(DF,GetHexValue(hex,hex)); } else
if (strstr(hex,"IF")==hex) { hex+=2; SETFLAGBIT(IF,GetHexValue(hex,hex)); } else
if (strstr(hex,"OF")==hex) { hex+=2; SETFLAGBIT(OF,GetHexValue(hex,hex)); } else
if (strstr(hex,"ZF")==hex) { hex+=2; SETFLAGBIT(ZF,GetHexValue(hex,hex)); } else
if (strstr(hex,"PF")==hex) { hex+=2; SETFLAGBIT(PF,GetHexValue(hex,hex)); } else
if (strstr(hex,"SF")==hex) { hex+=2; SETFLAGBIT(SF,GetHexValue(hex,hex)); } else
{ return false; };
return true;
};
bool ParseCommand(char* str) {
char* found = str;
for(char* idx = found;*idx != 0; idx++)
*idx = toupper(*idx);
found = trim(found);
string s_found(found);
istringstream stream(s_found);
string command;
stream >> command;
string::size_type next = s_found.find_first_not_of(' ',command.size());
if(next == string::npos) next = command.size();
(s_found.erase)(0,next);
found = const_cast<char*>(s_found.c_str());
if (command == "MEMDUMP") { // Dump memory to file
Bit16u seg = (Bit16u)GetHexValue(found,found); found++;
Bit32u ofs = GetHexValue(found,found); found++;
Bit32u num = GetHexValue(found,found); found++;
SaveMemory(seg,ofs,num);
return true;
};
if (command == "MEMDUMPBIN") { // Dump memory to file bineary
Bit16u seg = (Bit16u)GetHexValue(found,found); found++;
Bit32u ofs = GetHexValue(found,found); found++;
Bit32u num = GetHexValue(found,found); found++;
SaveMemoryBin(seg,ofs,num);
return true;
};
if (command == "IV") { // Insert variable
Bit16u seg = (Bit16u)GetHexValue(found,found); found++;
Bit32u ofs = (Bit16u)GetHexValue(found,found); found++;
char name[16];
for (int i=0; i<16; i++) {
if (found[i] && (found[i]!=' ')) name[i] = found[i];
else { name[i] = 0; break; };
};
name[15] = 0;
if(!name[0]) return false;
DEBUG_ShowMsg("DEBUG: Created debug var %s at %04X:%04X\n",name,seg,ofs);
CDebugVar::InsertVariable(name,GetAddress(seg,ofs));
return true;
};
if (command == "SV") { // Save variables
char name[13];
for (int i=0; i<12; i++) {
if (found[i] && (found[i]!=' ')) name[i] = found[i];
else { name[i] = 0; break; };
};
name[12] = 0;
if(!name[0]) return false;
DEBUG_ShowMsg("DEBUG: Variable list save (%s) : %s.\n",name,(CDebugVar::SaveVars(name)?"ok":"failure"));
return true;
};
if (command == "LV") { // load variables
char name[13];
for (int i=0; i<12; i++) {
if (found[i] && (found[i]!=' ')) name[i] = found[i];
else { name[i] = 0; break; };
};
name[12] = 0;
if(!name[0]) return false;
DEBUG_ShowMsg("DEBUG: Variable list load (%s) : %s.\n",name,(CDebugVar::LoadVars(name)?"ok":"failure"));
return true;
};
if (command == "SR") { // Set register value
DEBUG_ShowMsg("DEBUG: Set Register %s.\n",(ChangeRegister(found)?"success":"failure"));
return true;
};
if (command == "SM") { // Set memory with following values
Bit16u seg = (Bit16u)GetHexValue(found,found); found++;
Bit32u ofs = GetHexValue(found,found); found++;
Bit16u count = 0;
while (*found) {
while (*found==' ') found++;
if (*found) {
Bit8u value = (Bit8u)GetHexValue(found,found);
if(*found) found++;
mem_writeb_checked(GetAddress(seg,ofs+count),value);
count++;
}
};
DEBUG_ShowMsg("DEBUG: Memory changed.\n");
return true;
};
if (command == "BP") { // Add new breakpoint
Bit16u seg = (Bit16u)GetHexValue(found,found);found++; // skip ":"
Bit32u ofs = GetHexValue(found,found);
CBreakpoint::AddBreakpoint(seg,ofs,false);
DEBUG_ShowMsg("DEBUG: Set breakpoint at %04X:%04X\n",seg,ofs);
return true;
};
#if C_HEAVY_DEBUG
if (command == "BPM") { // Add new breakpoint
Bit16u seg = (Bit16u)GetHexValue(found,found);found++; // skip ":"
Bit32u ofs = GetHexValue(found,found);
CBreakpoint::AddMemBreakpoint(seg,ofs);
DEBUG_ShowMsg("DEBUG: Set memory breakpoint at %04X:%04X\n",seg,ofs);
return true;
};
if (command == "BPPM") { // Add new breakpoint
Bit16u seg = (Bit16u)GetHexValue(found,found);found++; // skip ":"
Bit32u ofs = GetHexValue(found,found);
CBreakpoint* bp = CBreakpoint::AddMemBreakpoint(seg,ofs);
if (bp) {
bp->SetType(BKPNT_MEMORY_PROT);
DEBUG_ShowMsg("DEBUG: Set prot-mode memory breakpoint at %04X:%08X\n",seg,ofs);
}
return true;
};
if (command == "BPLM") { // Add new breakpoint
Bit32u ofs = GetHexValue(found,found);
CBreakpoint* bp = CBreakpoint::AddMemBreakpoint(0,ofs);
if (bp) bp->SetType(BKPNT_MEMORY_LINEAR);
DEBUG_ShowMsg("DEBUG: Set linear memory breakpoint at %08X\n",ofs);
return true;
};
#endif
if (command == "BPINT") { // Add Interrupt Breakpoint
Bit8u intNr = (Bit8u)GetHexValue(found,found);
bool all = !(*found);found++;
Bit8u valAH = (Bit8u)GetHexValue(found,found);
if ((valAH==0x00) && (*found=='*' || all)) {
CBreakpoint::AddIntBreakpoint(intNr,BPINT_ALL,false);
DEBUG_ShowMsg("DEBUG: Set interrupt breakpoint at INT %02X\n",intNr);
} else {
CBreakpoint::AddIntBreakpoint(intNr,valAH,false);
DEBUG_ShowMsg("DEBUG: Set interrupt breakpoint at INT %02X AH=%02X\n",intNr,valAH);
}
return true;
};
if (command == "BPLIST") {
DEBUG_ShowMsg("Breakpoint list:\n");
DEBUG_ShowMsg("-------------------------------------------------------------------------\n");
CBreakpoint::ShowList();
return true;
};
if (command == "BPDEL") { // Delete Breakpoints
Bit8u bpNr = (Bit8u)GetHexValue(found,found);
if ((bpNr==0x00) && (*found=='*')) { // Delete all
CBreakpoint::DeleteAll();
DEBUG_ShowMsg("DEBUG: Breakpoints deleted.\n");
} else {
// delete single breakpoint
DEBUG_ShowMsg("DEBUG: Breakpoint deletion %s.\n",(CBreakpoint::DeleteByIndex(bpNr)?"success":"failure"));
}
return true;
};
if (command == "C") { // Set code overview
Bit16u codeSeg = (Bit16u)GetHexValue(found,found); found++;
Bit32u codeOfs = GetHexValue(found,found);
DEBUG_ShowMsg("DEBUG: Set code overview to %04X:%04X\n",codeSeg,codeOfs);
codeViewData.useCS = codeSeg;
codeViewData.useEIP = codeOfs;
codeViewData.cursorPos = 0;
return true;
};
if (command == "D") { // Set data overview
dataSeg = (Bit16u)GetHexValue(found,found); found++;
dataOfs = GetHexValue(found,found);
DEBUG_ShowMsg("DEBUG: Set data overview to %04X:%04X\n",dataSeg,dataOfs);
return true;
};
#if C_HEAVY_DEBUG
if (command == "LOG") { // Create Cpu normal log file
cpuLogType = 1;
command = "logcode";
}
if (command == "LOGS") { // Create Cpu short log file
cpuLogType = 0;
command = "logcode";
}
if (command == "LOGL") { // Create Cpu long log file
cpuLogType = 2;
command = "logcode";
}
if (command == "logcode") { //Shared code between all logs
DEBUG_ShowMsg("DEBUG: Starting log\n");
cpuLogFile.open("LOGCPU.TXT");
if (!cpuLogFile.is_open()) {
DEBUG_ShowMsg("DEBUG: Logfile couldn't be created.\n");
return false;
}
//Initialize log object
cpuLogFile << hex << noshowbase << setfill('0') << uppercase;
cpuLog = true;
cpuLogCounter = GetHexValue(found,found);
debugging = false;
CBreakpoint::ActivateBreakpoints(SegPhys(cs)+reg_eip,true);
ignoreAddressOnce = SegPhys(cs)+reg_eip;
DOSBOX_SetNormalLoop();
return true;
};
#endif
if (command == "INTT") { //trace int.
Bit8u intNr = (Bit8u)GetHexValue(found,found);
DEBUG_ShowMsg("DEBUG: Tracing INT %02X\n",intNr);
CPU_HW_Interrupt(intNr);
SetCodeWinStart();
return true;
};
if (command == "INT") { // start int.
Bit8u intNr = (Bit8u)GetHexValue(found,found);
DEBUG_ShowMsg("DEBUG: Starting INT %02X\n",intNr);
CBreakpoint::AddBreakpoint(SegValue(cs),reg_eip, true);
CBreakpoint::ActivateBreakpoints(SegPhys(cs)+reg_eip-1,true);
debugging = false;
DrawCode();
DOSBOX_SetNormalLoop();
CPU_HW_Interrupt(intNr);
return true;
};
if (command == "SELINFO") {
while (found[0] == ' ') found++;
char out1[200],out2[200];
GetDescriptorInfo(found,out1,out2);
DEBUG_ShowMsg("SelectorInfo %s:\n%s\n%s\n",found,out1,out2);
return true;
};
if (command == "DOS") {
stream >> command;
if (command == "MCBS") LogMCBS();
return true;
}
if (command == "GDT") {LogGDT(); return true;}
if (command == "LDT") {LogLDT(); return true;}
if (command == "IDT") {LogIDT(); return true;}
if (command == "PAGING") {LogPages(found); return true;}
if (command == "CPU") {LogCPUInfo(); return true;}
if (command == "INTVEC") {
if (found[0] != 0) {
OutputVecTable(found);
return true;
}
};
if (command == "INTHAND") {
if (found[0] != 0) {
Bit8u intNr = (Bit8u)GetHexValue(found,found);
DEBUG_ShowMsg("DEBUG: Set code overview to interrupt handler %X\n",intNr);
codeViewData.useCS = mem_readw(intNr*4+2);
codeViewData.useEIP = mem_readw(intNr*4);
codeViewData.cursorPos = 0;
return true;
}
};
if(command == "EXTEND") { //Toggle additional data.
showExtend = !showExtend;
return true;
};
if(command == "TIMERIRQ") { //Start a timer irq
DEBUG_RaiseTimerIrq();
DEBUG_ShowMsg("Debug: Timer Int started.\n");
return true;
};
#if C_HEAVY_DEBUG
if (command == "HEAVYLOG") { // Create Cpu log file
logHeavy = !logHeavy;
DEBUG_ShowMsg("DEBUG: Heavy cpu logging %s.\n",logHeavy?"on":"off");
return true;
};
if (command == "ZEROPROTECT") { //toggle zero protection
zeroProtect = !zeroProtect;
DEBUG_ShowMsg("DEBUG: Zero code execution protection %s.\n",zeroProtect?"on":"off");
return true;
};
#endif
if (command == "HELP" || command == "?") {
DEBUG_ShowMsg("Debugger commands (enter all values in hex or as register):\n");
DEBUG_ShowMsg("--------------------------------------------------------------------------\n");
DEBUG_ShowMsg("F3/F6 - Previous command in history.\n");
DEBUG_ShowMsg("F4/F7 - Next command in history.\n");
DEBUG_ShowMsg("F5 - Run.\n");
DEBUG_ShowMsg("F9 - Set/Remove breakpoint.\n");
DEBUG_ShowMsg("F10/F11 - Step over / trace into instruction.\n");
DEBUG_ShowMsg("ALT + D/E/S/X/B - Set data view to DS:SI/ES:DI/SS:SP/DS:DX/ES:BX.\n");
DEBUG_ShowMsg("Escape - Clear input line.");
DEBUG_ShowMsg("Up/Down - Move code view cursor.\n");
DEBUG_ShowMsg("Page Up/Down - Scroll data view.\n");
DEBUG_ShowMsg("Home/End - Scroll log messages.\n");
DEBUG_ShowMsg("BP [segment]:[offset] - Set breakpoint.\n");
DEBUG_ShowMsg("BPINT [intNr] * - Set interrupt breakpoint.\n");
DEBUG_ShowMsg("BPINT [intNr] [ah] - Set interrupt breakpoint with ah.\n");
#if C_HEAVY_DEBUG
DEBUG_ShowMsg("BPM [segment]:[offset] - Set memory breakpoint (memory change).\n");
DEBUG_ShowMsg("BPPM [selector]:[offset]- Set pmode-memory breakpoint (memory change).\n");
DEBUG_ShowMsg("BPLM [linear address] - Set linear memory breakpoint (memory change).\n");
#endif
DEBUG_ShowMsg("BPLIST - List breakpoints.\n");
DEBUG_ShowMsg("BPDEL [bpNr] / * - Delete breakpoint nr / all.\n");
DEBUG_ShowMsg("C / D [segment]:[offset] - Set code / data view address.\n");
DEBUG_ShowMsg("DOS MCBS - Show Memory Control Block chain.\n");
DEBUG_ShowMsg("INT [nr] / INTT [nr] - Execute / Trace into interrupt.\n");
#if C_HEAVY_DEBUG
DEBUG_ShowMsg("LOG [num] - Write cpu log file.\n");
DEBUG_ShowMsg("LOGS/LOGL [num] - Write short/long cpu log file.\n");
DEBUG_ShowMsg("HEAVYLOG - Enable/Disable automatic cpu log when dosbox exits.\n");
DEBUG_ShowMsg("ZEROPROTECT - Enable/Disable zero code execution detecion.\n");
#endif
DEBUG_ShowMsg("SR [reg] [value] - Set register value.\n");
DEBUG_ShowMsg("SM [seg]:[off] [val] [.]..- Set memory with following values.\n");
DEBUG_ShowMsg("IV [seg]:[off] [name] - Create var name for memory address.\n");
DEBUG_ShowMsg("SV [filename] - Save var list in file.\n");
DEBUG_ShowMsg("LV [filename] - Load var list from file.\n");
DEBUG_ShowMsg("MEMDUMP [seg]:[off] [len] - Write memory to file memdump.txt.\n");
DEBUG_ShowMsg("MEMDUMPBIN [s]:[o] [len] - Write memory to file memdump.bin.\n");
DEBUG_ShowMsg("SELINFO [segName] - Show selector info.\n");
DEBUG_ShowMsg("INTVEC [filename] - Writes interrupt vector table to file.\n");
DEBUG_ShowMsg("INTHAND [intNum] - Set code view to interrupt handler.\n");
DEBUG_ShowMsg("CPU - Display CPU status information.\n");
DEBUG_ShowMsg("GDT - Lists descriptors of the GDT.\n");
DEBUG_ShowMsg("LDT - Lists descriptors of the LDT.\n");
DEBUG_ShowMsg("IDT - Lists descriptors of the IDT.\n");
DEBUG_ShowMsg("PAGING [page] - Display content of page table.\n");
DEBUG_ShowMsg("EXTEND - Toggle additional info.\n");
DEBUG_ShowMsg("TIMERIRQ - Run the system timer.\n");
DEBUG_ShowMsg("HELP - Help\n");
return true;
};
return false;
};
char* AnalyzeInstruction(char* inst, bool saveSelector) {
static char result[256];
char instu[256];
char prefix[3];
Bit16u seg;
strcpy(instu,inst);
upcase(instu);
result[0] = 0;
char* pos = strchr(instu,'[');
if (pos) {
// Segment prefix ?
if (*(pos-1)==':') {
char* segpos = pos-3;
prefix[0] = tolower(*segpos);
prefix[1] = tolower(*(segpos+1));
prefix[2] = 0;
seg = (Bit16u)GetHexValue(segpos,segpos);
} else {
if (strstr(pos,"SP") || strstr(pos,"BP")) {
seg = SegValue(ss);
strcpy(prefix,"ss");
} else {
seg = SegValue(ds);
strcpy(prefix,"ds");
};
};
pos++;
Bit32u adr = GetHexValue(pos,pos);
while (*pos!=']') {
if (*pos=='+') {
pos++;
adr += GetHexValue(pos,pos);
} else if (*pos=='-') {
pos++;
adr -= GetHexValue(pos,pos);
} else
pos++;
};
Bit32u address = GetAddress(seg,adr);
if (!(get_tlb_readhandler(address)->flags & PFLAG_INIT)) {
static char outmask[] = "%s:[%04X]=%02X";
if (cpu.pmode) outmask[6] = '8';
switch (DasmLastOperandSize()) {
case 8 : { Bit8u val = mem_readb(address);
outmask[12] = '2';
sprintf(result,outmask,prefix,adr,val);
} break;
case 16: { Bit16u val = mem_readw(address);
outmask[12] = '4';
sprintf(result,outmask,prefix,adr,val);
} break;
case 32: { Bit32u val = mem_readd(address);
outmask[12] = '8';
sprintf(result,outmask,prefix,adr,val);
} break;
}
} else {
sprintf(result,"[illegal]");
}
// Variable found ?
CDebugVar* var = CDebugVar::FindVar(address);
if (var) {
// Replace occurence
char* pos1 = strchr(inst,'[');
char* pos2 = strchr(inst,']');
if (pos1 && pos2) {
char temp[256];
strcpy(temp,pos2); // save end
pos1++; *pos1 = 0; // cut after '['
strcat(inst,var->GetName()); // add var name
strcat(inst,temp); // add end
};
};
// show descriptor info, if available
if ((cpu.pmode) && saveSelector) {
strcpy(curSelectorName,prefix);
};
};
// If it is a callback add additional info
pos = strstr(inst,"callback");
if (pos) {
pos += 9;
Bitu nr = GetHexValue(pos,pos);
const char* descr = CALLBACK_GetDescription(nr);
if (descr) {
strcat(inst," ("); strcat(inst,descr); strcat(inst,")");
}
};
// Must be a jump
if (instu[0] == 'J')
{
bool jmp = false;
switch (instu[1]) {
case 'A' : { jmp = (get_CF()?false:true) && (get_ZF()?false:true); // JA
} break;
case 'B' : { if (instu[2] == 'E') {
jmp = (get_CF()?true:false) || (get_ZF()?true:false); // JBE
} else {
jmp = get_CF()?true:false; // JB
}
} break;
case 'C' : { if (instu[2] == 'X') {
jmp = reg_cx == 0; // JCXZ
} else {
jmp = get_CF()?true:false; // JC
}
} break;
case 'E' : { jmp = get_ZF()?true:false; // JE
} break;
case 'G' : { if (instu[2] == 'E') {
jmp = (get_SF()?true:false)==(get_OF()?true:false); // JGE
} else {
jmp = (get_ZF()?false:true) && ((get_SF()?true:false)==(get_OF()?true:false)); // JG
}
} break;
case 'L' : { if (instu[2] == 'E') {
jmp = (get_ZF()?true:false) || ((get_SF()?true:false)!=(get_OF()?true:false)); // JLE
} else {
jmp = (get_SF()?true:false)!=(get_OF()?true:false); // JL
}
} break;
case 'M' : { jmp = true; // JMP
} break;
case 'N' : { switch (instu[2]) {
case 'B' :
case 'C' : { jmp = get_CF()?false:true; // JNB / JNC
} break;
case 'E' : { jmp = get_ZF()?false:true; // JNE
} break;
case 'O' : { jmp = get_OF()?false:true; // JNO
} break;
case 'P' : { jmp = get_PF()?false:true; // JNP
} break;
case 'S' : { jmp = get_SF()?false:true; // JNS
} break;
case 'Z' : { jmp = get_ZF()?false:true; // JNZ
} break;
}
} break;
case 'O' : { jmp = get_OF()?true:false; // JO
} break;
case 'P' : { if (instu[2] == 'O') {
jmp = get_PF()?false:true; // JPO
} else {
jmp = get_SF()?true:false; // JP / JPE
}
} break;
case 'S' : { jmp = get_SF()?true:false; // JS
} break;
case 'Z' : { jmp = get_ZF()?true:false; // JZ
} break;
}
if (jmp) {
pos = strchr(instu,'$');
if (pos) {
pos = strchr(instu,'+');
if (pos) {
strcpy(result,"(down)");
} else {
strcpy(result,"(up)");
}
}
} else {
sprintf(result,"(no jmp)");
}
}
return result;
};
Bit32u DEBUG_CheckKeys(void) {
Bits ret=0;
int key=getch();
if (key>0) {
#if defined(WIN32) && defined(__PDCURSES__)
switch (key) {
case PADENTER: key=0x0A; break;
case PADSLASH: key='/'; break;
case PADSTAR: key='*'; break;
case PADMINUS: key='-'; break;
case PADPLUS: key='+'; break;
case ALT_D:
if (ungetch('D') != ERR) key=27;
break;
case ALT_E:
if (ungetch('E') != ERR) key=27;
break;
case ALT_X:
if (ungetch('X') != ERR) key=27;
break;
case ALT_B:
if (ungetch('B') != ERR) key=27;
break;
case ALT_S:
if (ungetch('S') != ERR) key=27;
break;
}
#endif
switch (toupper(key)) {
case 27: // escape (a bit slow): Clears line. and processes alt commands.
key=getch();
if(key < 0) { //Purely escape Clear line
ClearInputLine();
break;
}
switch(toupper(key)) {
case 'D' : // ALT - D: DS:SI
dataSeg = SegValue(ds);
if (cpu.pmode && !(reg_flags & FLAG_VM)) dataOfs = reg_esi;
else dataOfs = reg_si;
break;
case 'E' : //ALT - E: es:di
dataSeg = SegValue(es);
if (cpu.pmode && !(reg_flags & FLAG_VM)) dataOfs = reg_edi;
else dataOfs = reg_di;
break;
case 'X': //ALT - X: ds:dx
dataSeg = SegValue(ds);
if (cpu.pmode && !(reg_flags & FLAG_VM)) dataOfs = reg_edx;
else dataOfs = reg_dx;
break;
case 'B' : //ALT -B: es:bx
dataSeg = SegValue(es);
if (cpu.pmode && !(reg_flags & FLAG_VM)) dataOfs = reg_ebx;
else dataOfs = reg_bx;
break;
case 'S': //ALT - S: ss:sp
dataSeg = SegValue(ss);
if (cpu.pmode && !(reg_flags & FLAG_VM)) dataOfs = reg_esp;
else dataOfs = reg_sp;
break;
default:
break;
}
break;
case KEY_PPAGE : dataOfs -= 16; break;
case KEY_NPAGE : dataOfs += 16; break;
case KEY_DOWN: // down
if (codeViewData.cursorPos<9) codeViewData.cursorPos++;
else codeViewData.useEIP += codeViewData.firstInstSize;
break;
case KEY_UP: // up
if (codeViewData.cursorPos>0) codeViewData.cursorPos--;
else {
Bitu bytes = 0;
char dline[200];
Bitu size = 0;
Bit32u newEIP = codeViewData.useEIP - 1;
if(codeViewData.useEIP) {
for (; bytes < 10; bytes++) {
PhysPt start = GetAddress(codeViewData.useCS,newEIP);
size = DasmI386(dline, start, newEIP, cpu.code.big);
if(codeViewData.useEIP == newEIP+size) break;
newEIP--;
}
if (bytes>=10) newEIP = codeViewData.useEIP - 1;
}
codeViewData.useEIP = newEIP;
}
break;
case KEY_HOME: // Home: scroll log page up
DEBUG_RefreshPage(-1);
break;
case KEY_END: // End: scroll log page down
DEBUG_RefreshPage(1);
break;
case KEY_IC: // Insert: toggle insert/overwrite
codeViewData.ovrMode = !codeViewData.ovrMode;
break;
case KEY_LEFT: // move to the left in command line
if (codeViewData.inputPos > 0) codeViewData.inputPos--;
break;
case KEY_RIGHT: // move to the right in command line
if (codeViewData.inputStr[codeViewData.inputPos]) codeViewData.inputPos++;
break;
case KEY_F(6): // previous command (f1-f4 generate rubbish at my place)
case KEY_F(3): // previous command
if (histBuffPos == histBuff.begin()) break;
if (histBuffPos == histBuff.end()) {
// copy inputStr to suspInputStr so we can restore it
safe_strncpy(codeViewData.suspInputStr, codeViewData.inputStr, sizeof(codeViewData.suspInputStr));
}
safe_strncpy(codeViewData.inputStr,(*--histBuffPos).c_str(),sizeof(codeViewData.inputStr));
codeViewData.inputPos = strlen(codeViewData.inputStr);
break;
case KEY_F(7): // next command (f1-f4 generate rubbish at my place)
case KEY_F(4): // next command
if (histBuffPos == histBuff.end()) break;
if (++histBuffPos != histBuff.end()) {
safe_strncpy(codeViewData.inputStr,(*histBuffPos).c_str(),sizeof(codeViewData.inputStr));
} else {
// copy suspInputStr back into inputStr
safe_strncpy(codeViewData.inputStr, codeViewData.suspInputStr, sizeof(codeViewData.inputStr));
}
codeViewData.inputPos = strlen(codeViewData.inputStr);
break;
case KEY_F(5): // Run Program
debugging=false;
CBreakpoint::ActivateBreakpoints(SegPhys(cs)+reg_eip,true);
ignoreAddressOnce = SegPhys(cs)+reg_eip;
DOSBOX_SetNormalLoop();
break;
case KEY_F(9): // Set/Remove Breakpoint
{ PhysPt ptr = GetAddress(codeViewData.cursorSeg,codeViewData.cursorOfs);
if (CBreakpoint::IsBreakpoint(ptr)) {
CBreakpoint::DeleteBreakpoint(ptr);
DEBUG_ShowMsg("DEBUG: Breakpoint deletion success.\n");
}
else {
CBreakpoint::AddBreakpoint(codeViewData.cursorSeg, codeViewData.cursorOfs, false);
DEBUG_ShowMsg("DEBUG: Set breakpoint at %04X:%04X\n",codeViewData.cursorSeg,codeViewData.cursorOfs);
}
}
break;
case KEY_F(10): // Step over inst
if (StepOver()) return 0;
else {
exitLoop = false;
skipFirstInstruction = true; // for heavy debugger
CPU_Cycles = 1;
ret=(*cpudecoder)();
SetCodeWinStart();
CBreakpoint::ignoreOnce = 0;
}
break;
case KEY_F(11): // trace into
exitLoop = false;
skipFirstInstruction = true; // for heavy debugger
CPU_Cycles = 1;
ret = (*cpudecoder)();
SetCodeWinStart();
CBreakpoint::ignoreOnce = 0;
break;
case 0x0A: //Parse typed Command
codeViewData.inputStr[MAXCMDLEN] = '\0';
if(ParseCommand(codeViewData.inputStr)) {
char* cmd = ltrim(codeViewData.inputStr);
if (histBuff.empty() || *--histBuff.end()!=cmd)
histBuff.push_back(cmd);
if (histBuff.size() > MAX_HIST_BUFFER) histBuff.pop_front();
histBuffPos = histBuff.end();
ClearInputLine();
} else {
codeViewData.inputPos = strlen(codeViewData.inputStr);
}
break;
case KEY_BACKSPACE: //backspace (linux)
case 0x7f: // backspace in some terminal emulators (linux)
case 0x08: // delete
if (codeViewData.inputPos == 0) break;
codeViewData.inputPos--;
// fallthrough
case KEY_DC: // delete character
if ((codeViewData.inputPos<0) || (codeViewData.inputPos>=MAXCMDLEN)) break;
if (codeViewData.inputStr[codeViewData.inputPos] != 0) {
codeViewData.inputStr[MAXCMDLEN] = '\0';
for(char* p=&codeViewData.inputStr[codeViewData.inputPos];(*p=*(p+1));p++) {}
}
break;
default:
if ((key>=32) && (key<127)) {
if ((codeViewData.inputPos<0) || (codeViewData.inputPos>=MAXCMDLEN)) break;
codeViewData.inputStr[MAXCMDLEN] = '\0';
if (codeViewData.inputStr[codeViewData.inputPos] == 0) {
codeViewData.inputStr[codeViewData.inputPos++] = char(key);
codeViewData.inputStr[codeViewData.inputPos] = '\0';
} else if (!codeViewData.ovrMode) {
int len = (int) strlen(codeViewData.inputStr);
if (len < MAXCMDLEN) {
for(len++;len>codeViewData.inputPos;len--)
codeViewData.inputStr[len]=codeViewData.inputStr[len-1];
codeViewData.inputStr[codeViewData.inputPos++] = char(key);
}
} else {
codeViewData.inputStr[codeViewData.inputPos++] = char(key);
}
} else if (key==killchar()) {
ClearInputLine();
}
break;
}
if (ret<0) return ret;
if (ret>0) {
if (GCC_UNLIKELY(ret >= CB_MAX))
ret = 0;
else
ret = (*CallBack_Handlers[ret])();
if (ret) {
exitLoop=true;
CPU_Cycles=CPU_CycleLeft=0;
return ret;
}
}
ret=0;
DEBUG_DrawScreen();
}
return ret;
};
Bitu DEBUG_Loop(void) {
//TODO Disable sound
GFX_Events();
// Interrupt started ? - then skip it
Bit16u oldCS = SegValue(cs);
Bit32u oldEIP = reg_eip;
PIC_runIRQs();
SDL_Delay(1);
if ((oldCS!=SegValue(cs)) || (oldEIP!=reg_eip)) {
CBreakpoint::AddBreakpoint(oldCS,oldEIP,true);
CBreakpoint::ActivateBreakpoints(SegPhys(cs)+reg_eip,true);
debugging=false;
DOSBOX_SetNormalLoop();
return 0;
}
return DEBUG_CheckKeys();
}
void DEBUG_Enable(bool pressed) {
if (!pressed)
return;
static bool showhelp=false;
debugging=true;
SetCodeWinStart();
DEBUG_DrawScreen();
DOSBOX_SetLoop(&DEBUG_Loop);
if(!showhelp) {
showhelp=true;
DEBUG_ShowMsg("***| TYPE HELP (+ENTER) TO GET AN OVERVIEW OF ALL COMMANDS |***\n");
}
KEYBOARD_ClrBuffer();
}
void DEBUG_DrawScreen(void) {
DrawData();
DrawCode();
DrawRegisters();
DrawVariables();
}
static void DEBUG_RaiseTimerIrq(void) {
PIC_ActivateIRQ(0);
}
// Display the content of the MCB chain starting with the MCB at the specified segment.
static void LogMCBChain(Bit16u mcb_segment) {
DOS_MCB mcb(mcb_segment);
char filename[9]; // 8 characters plus a terminating NUL
const char *psp_seg_note;
PhysPt dataAddr = PhysMake(dataSeg,dataOfs);// location being viewed in the "Data Overview"
// loop forever, breaking out of the loop once we've processed the last MCB
while (true) {
// verify that the type field is valid
if (mcb.GetType()!=0x4d && mcb.GetType()!=0x5a) {
LOG(LOG_MISC,LOG_ERROR)("MCB chain broken at %04X:0000!",mcb_segment);
return;
}
mcb.GetFileName(filename);
// some PSP segment values have special meanings
switch (mcb.GetPSPSeg()) {
case MCB_FREE:
psp_seg_note = "(free)";
break;
case MCB_DOS:
psp_seg_note = "(DOS)";
break;
default:
psp_seg_note = "";
}
LOG(LOG_MISC,LOG_ERROR)(" %04X %12u %04X %-7s %s",mcb_segment,mcb.GetSize() << 4,mcb.GetPSPSeg(), psp_seg_note, filename);
// print a message if dataAddr is within this MCB's memory range
PhysPt mcbStartAddr = PhysMake(mcb_segment+1,0);
PhysPt mcbEndAddr = PhysMake(mcb_segment+1+mcb.GetSize(),0);
if (dataAddr >= mcbStartAddr && dataAddr < mcbEndAddr) {
LOG(LOG_MISC,LOG_ERROR)(" (data addr %04hX:%04X is %u bytes past this MCB)",dataSeg,dataOfs,dataAddr - mcbStartAddr);
}
// if we've just processed the last MCB in the chain, break out of the loop
if (mcb.GetType()==0x5a) {
break;
}
// else, move to the next MCB in the chain
mcb_segment+=mcb.GetSize()+1;
mcb.SetPt(mcb_segment);
}
}
// Display the content of all Memory Control Blocks.
static void LogMCBS(void)
{
LOG(LOG_MISC,LOG_ERROR)("MCB Seg Size (bytes) PSP Seg (notes) Filename");
LOG(LOG_MISC,LOG_ERROR)("Conventional memory:");
LogMCBChain(dos.firstMCB);
LOG(LOG_MISC,LOG_ERROR)("Upper memory:");
LogMCBChain(dos_infoblock.GetStartOfUMBChain());
}
static void LogGDT(void)
{
char out1[512];
Descriptor desc;
Bitu length = cpu.gdt.GetLimit();
PhysPt address = cpu.gdt.GetBase();
PhysPt max = address + length;
Bitu i = 0;
LOG(LOG_MISC,LOG_ERROR)("GDT Base:%08X Limit:%08X",address,length);
while (address<max) {
desc.Load(address);
sprintf(out1,"%04X: b:%08X type: %02X parbg",(i<<3),desc.GetBase(),desc.desc.seg.type);
LOG(LOG_MISC,LOG_ERROR)(out1);
sprintf(out1," l:%08X dpl : %01X %1X%1X%1X%1X%1X",desc.GetLimit(),desc.desc.seg.dpl,desc.desc.seg.p,desc.desc.seg.avl,desc.desc.seg.r,desc.desc.seg.big,desc.desc.seg.g);
LOG(LOG_MISC,LOG_ERROR)(out1);
address+=8; i++;
};
};
static void LogLDT(void) {
char out1[512];
Descriptor desc;
Bitu ldtSelector = cpu.gdt.SLDT();
if (!cpu.gdt.GetDescriptor(ldtSelector,desc)) return;
Bitu length = desc.GetLimit();
PhysPt address = desc.GetBase();
PhysPt max = address + length;
Bitu i = 0;
LOG(LOG_MISC,LOG_ERROR)("LDT Base:%08X Limit:%08X",address,length);
while (address<max) {
desc.Load(address);
sprintf(out1,"%04X: b:%08X type: %02X parbg",(i<<3)|4,desc.GetBase(),desc.desc.seg.type);
LOG(LOG_MISC,LOG_ERROR)(out1);
sprintf(out1," l:%08X dpl : %01X %1X%1X%1X%1X%1X",desc.GetLimit(),desc.desc.seg.dpl,desc.desc.seg.p,desc.desc.seg.avl,desc.desc.seg.r,desc.desc.seg.big,desc.desc.seg.g);
LOG(LOG_MISC,LOG_ERROR)(out1);
address+=8; i++;
};
};
static void LogIDT(void) {
char out1[512];
Descriptor desc;
Bitu address = 0;
while (address<256*8) {
if (cpu.idt.GetDescriptor(address,desc)) {
sprintf(out1,"%04X: sel:%04X off:%02X",address/8,desc.GetSelector(),desc.GetOffset());
LOG(LOG_MISC,LOG_ERROR)(out1);
}
address+=8;
};
};
void LogPages(char* selname) {
char out1[512];
if (paging.enabled) {
Bitu sel = GetHexValue(selname,selname);
if ((sel==0x00) && ((*selname==0) || (*selname=='*'))) {
for (int i=0; i<0xfffff; i++) {
Bitu table_addr=(paging.base.page<<12)+(i >> 10)*4;
X86PageEntry table;
table.load=phys_readd(table_addr);
if (table.block.p) {
X86PageEntry entry;
Bitu entry_addr=(table.block.base<<12)+(i & 0x3ff)*4;
entry.load=phys_readd(entry_addr);
if (entry.block.p) {
sprintf(out1,"page %05Xxxx -> %04Xxxx flags [uw] %x:%x::%x:%x [d=%x|a=%x]",
i,entry.block.base,entry.block.us,table.block.us,
entry.block.wr,table.block.wr,entry.block.d,entry.block.a);
LOG(LOG_MISC,LOG_ERROR)(out1);
}
}
}
} else {
Bitu table_addr=(paging.base.page<<12)+(sel >> 10)*4;
X86PageEntry table;
table.load=phys_readd(table_addr);
if (table.block.p) {
X86PageEntry entry;
Bitu entry_addr=(table.block.base<<12)+(sel & 0x3ff)*4;
entry.load=phys_readd(entry_addr);
sprintf(out1,"page %05Xxxx -> %04Xxxx flags [puw] %x:%x::%x:%x::%x:%x",sel,entry.block.base,entry.block.p,table.block.p,entry.block.us,table.block.us,entry.block.wr,table.block.wr);
LOG(LOG_MISC,LOG_ERROR)(out1);
} else {
sprintf(out1,"pagetable %03X not present, flags [puw] %x::%x::%x",(sel >> 10),table.block.p,table.block.us,table.block.wr);
LOG(LOG_MISC,LOG_ERROR)(out1);
}
}
}
};
static void LogCPUInfo(void) {
char out1[512];
sprintf(out1,"cr0:%08X cr2:%08X cr3:%08X cpl=%x",cpu.cr0,paging.cr2,paging.cr3,cpu.cpl);
LOG(LOG_MISC,LOG_ERROR)(out1);
sprintf(out1,"eflags:%08X [vm=%x iopl=%x nt=%x]",reg_flags,GETFLAG(VM)>>17,GETFLAG(IOPL)>>12,GETFLAG(NT)>>14);
LOG(LOG_MISC,LOG_ERROR)(out1);
sprintf(out1,"GDT base=%08X limit=%08X",cpu.gdt.GetBase(),cpu.gdt.GetLimit());
LOG(LOG_MISC,LOG_ERROR)(out1);
sprintf(out1,"IDT base=%08X limit=%08X",cpu.idt.GetBase(),cpu.idt.GetLimit());
LOG(LOG_MISC,LOG_ERROR)(out1);
Bitu sel=CPU_STR();
Descriptor desc;
if (cpu.gdt.GetDescriptor(sel,desc)) {
sprintf(out1,"TR selector=%04X, base=%08X limit=%08X*%X",sel,desc.GetBase(),desc.GetLimit(),desc.desc.seg.g?0x4000:1);
LOG(LOG_MISC,LOG_ERROR)(out1);
}
sel=CPU_SLDT();
if (cpu.gdt.GetDescriptor(sel,desc)) {
sprintf(out1,"LDT selector=%04X, base=%08X limit=%08X*%X",sel,desc.GetBase(),desc.GetLimit(),desc.desc.seg.g?0x4000:1);
LOG(LOG_MISC,LOG_ERROR)(out1);
}
};
#if C_HEAVY_DEBUG
static void LogInstruction(Bit16u segValue, Bit32u eipValue, ofstream& out) {
static char empty[23] = { 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,0 };
PhysPt start = GetAddress(segValue,eipValue);
char dline[200];Bitu size;
size = DasmI386(dline, start, reg_eip, cpu.code.big);
char* res = empty;
if (showExtend && (cpuLogType > 0) ) {
res = AnalyzeInstruction(dline,false);
if (!res || !(*res)) res = empty;
Bitu reslen = strlen(res);
if (reslen<22) for (Bitu i=0; i<22-reslen; i++) res[reslen+i] = ' '; res[22] = 0;
};
Bitu len = strlen(dline);
if (len<30) for (Bitu i=0; i<30-len; i++) dline[len + i] = ' '; dline[30] = 0;
// Get register values
if(cpuLogType == 0) {
out << setw(4) << SegValue(cs) << ":" << setw(4) << reg_eip << " " << dline;
} else if (cpuLogType == 1) {
out << setw(4) << SegValue(cs) << ":" << setw(8) << reg_eip << " " << dline << " " << res;
} else if (cpuLogType == 2) {
char ibytes[200]=""; char tmpc[200];
for (Bitu i=0; i<size; i++) {
Bit8u value;
if (mem_readb_checked(start+i,&value)) sprintf(tmpc,"%s","?? ");
else sprintf(tmpc,"%02X ",value);
strcat(ibytes,tmpc);
}
len = strlen(ibytes);
if (len<21) { for (Bitu i=0; i<21-len; i++) ibytes[len + i] =' '; ibytes[21]=0;} //NOTE THE BRACKETS
out << setw(4) << SegValue(cs) << ":" << setw(8) << reg_eip << " " << dline << " " << res << " " << ibytes;
}
out << " EAX:" << setw(8) << reg_eax << " EBX:" << setw(8) << reg_ebx
<< " ECX:" << setw(8) << reg_ecx << " EDX:" << setw(8) << reg_edx
<< " ESI:" << setw(8) << reg_esi << " EDI:" << setw(8) << reg_edi
<< " EBP:" << setw(8) << reg_ebp << " ESP:" << setw(8) << reg_esp
<< " DS:" << setw(4) << SegValue(ds)<< " ES:" << setw(4) << SegValue(es);
if(cpuLogType == 0) {
out << " SS:" << setw(4) << SegValue(ss) << " C" << (get_CF()>0) << " Z" << (get_ZF()>0)
<< " S" << (get_SF()>0) << " O" << (get_OF()>0) << " I" << GETFLAGBOOL(IF);
} else {
out << " FS:" << setw(4) << SegValue(fs) << " GS:" << setw(4) << SegValue(gs)
<< " SS:" << setw(4) << SegValue(ss)
<< " CF:" << (get_CF()>0) << " ZF:" << (get_ZF()>0) << " SF:" << (get_SF()>0)
<< " OF:" << (get_OF()>0) << " AF:" << (get_AF()>0) << " PF:" << (get_PF()>0)
<< " IF:" << GETFLAGBOOL(IF);
}
if(cpuLogType == 2) {
out << " TF:" << GETFLAGBOOL(TF) << " VM:" << GETFLAGBOOL(VM) <<" FLG:" << setw(8) << reg_flags
<< " CR0:" << setw(8) << cpu.cr0;
}
out << endl;
};
#endif
// DEBUG.COM stuff
class DEBUG : public Program {
public:
DEBUG() { pDebugcom = this; active = false; };
~DEBUG() { pDebugcom = 0; };
bool IsActive() { return active; };
void Run(void)
{
if(cmd->FindExist("/NOMOUSE",false)) {
real_writed(0,0x33<<2,0);
return;
}
char filename[128];
char args[256];
cmd->FindCommand(1,temp_line);
safe_strncpy(filename,temp_line.c_str(),128);
// Read commandline
Bit16u i =2;
args[0] = 0;
for (;cmd->FindCommand(i++,temp_line)==true;) {
strncat(args,temp_line.c_str(),256);
strncat(args," ",256);
}
// Start new shell and execute prog
active = true;
// Save cpu state....
Bit16u oldcs = SegValue(cs);
Bit32u oldeip = reg_eip;
Bit16u oldss = SegValue(ss);
Bit32u oldesp = reg_esp;
// Workaround : Allocate Stack Space
Bit16u segment;
Bit16u size = 0x200 / 0x10;
if (DOS_AllocateMemory(&segment,&size)) {
SegSet16(ss,segment);
reg_sp = 0x200;
// Start shell
DOS_Shell shell;
shell.Execute(filename,args);
DOS_FreeMemory(segment);
}
// set old reg values
SegSet16(ss,oldss);
reg_esp = oldesp;
SegSet16(cs,oldcs);
reg_eip = oldeip;
};
private:
bool active;
};
void DEBUG_CheckExecuteBreakpoint(Bit16u seg, Bit32u off)
{
if (pDebugcom && pDebugcom->IsActive()) {
CBreakpoint::AddBreakpoint(seg,off,true);
CBreakpoint::ActivateBreakpoints(SegPhys(cs)+reg_eip,true);
pDebugcom = 0;
};
};
Bitu DEBUG_EnableDebugger(void)
{
exitLoop = true;
DEBUG_Enable(true);
CPU_Cycles=CPU_CycleLeft=0;
return 0;
};
static void DEBUG_ProgramStart(Program * * make) {
*make=new DEBUG;
}
// INIT
void DEBUG_SetupConsole(void) {
#ifdef WIN32
WIN32_Console();
#else
tcgetattr(0,&consolesettings);
printf("\e[8;50;80t"); //resize terminal
fflush(NULL);
#endif
memset((void *)&dbg,0,sizeof(dbg));
debugging=false;
// dbg.active_win=3;
/* Start the Debug Gui */
DBGUI_StartUp();
}
void DEBUG_ShutDown(Section * /*sec*/) {
CBreakpoint::DeleteAll();
CDebugVar::DeleteAll();
curs_set(old_cursor_state);
endwin();
#ifndef WIN32
tcsetattr(0, TCSANOW,&consolesettings);
// printf("\e[0m\e[2J"); //Seems to destroy scrolling
printf("\ec");
fflush(NULL);
#endif
}
Bitu debugCallback;
void DEBUG_Init(Section* sec) {
// MSG_Add("DEBUG_CONFIGFILE_HELP","Debugger related options.\n");
DEBUG_DrawScreen();
/* Add some keyhandlers */
MAPPER_AddHandler(DEBUG_Enable,MK_pause,MMOD2,"debugger","Debugger");
/* Reset code overview and input line */
memset((void*)&codeViewData,0,sizeof(codeViewData));
/* setup debug.com */
PROGRAMS_MakeFile("DEBUG.COM",DEBUG_ProgramStart);
/* Setup callback */
debugCallback=CALLBACK_Allocate();
CALLBACK_Setup(debugCallback,DEBUG_EnableDebugger,CB_RETF,"debugger");
/* shutdown function */
sec->AddDestroyFunction(&DEBUG_ShutDown);
}
// DEBUGGING VAR STUFF
void CDebugVar::InsertVariable(char* name, PhysPt adr)
{
varList.push_back(new CDebugVar(name,adr));
};
void CDebugVar::DeleteAll(void)
{
std::list<CDebugVar*>::iterator i;
CDebugVar* bp;
for(i=varList.begin(); i != varList.end(); i++) {
bp = static_cast<CDebugVar*>(*i);
delete bp;
};
(varList.clear)();
};
CDebugVar* CDebugVar::FindVar(PhysPt pt)
{
std::list<CDebugVar*>::iterator i;
CDebugVar* bp;
for(i=varList.begin(); i != varList.end(); i++) {
bp = static_cast<CDebugVar*>(*i);
if (bp->GetAdr()==pt) return bp;
};
return 0;
};
bool CDebugVar::SaveVars(char* name) {
if (varList.size()>65535) return false;
FILE* f = fopen(name,"wb+");
if (!f) return false;
// write number of vars
Bit16u num = (Bit16u)varList.size();
fwrite(&num,1,sizeof(num),f);
std::list<CDebugVar*>::iterator i;
CDebugVar* bp;
for(i=varList.begin(); i != varList.end(); i++) {
bp = static_cast<CDebugVar*>(*i);
// name
fwrite(bp->GetName(),1,16,f);
// adr
PhysPt adr = bp->GetAdr();
fwrite(&adr,1,sizeof(adr),f);
};
fclose(f);
return true;
};
bool CDebugVar::LoadVars(char* name)
{
FILE* f = fopen(name,"rb");
if (!f) return false;
// read number of vars
Bit16u num;
fread(&num,1,sizeof(num),f);
for (Bit16u i=0; i<num; i++) {
char name[16];
// name
fread(name,1,16,f);
// adr
PhysPt adr;
fread(&adr,1,sizeof(adr),f);
// insert
InsertVariable(name,adr);
};
fclose(f);
return true;
};
static void SaveMemory(Bitu seg, Bitu ofs1, Bit32u num) {
FILE* f = fopen("MEMDUMP.TXT","wt");
if (!f) {
DEBUG_ShowMsg("DEBUG: Memory dump failed.\n");
return;
}
char buffer[128];
char temp[16];
while (num>16) {
sprintf(buffer,"%04X:%04X ",seg,ofs1);
for (Bit16u x=0; x<16; x++) {
Bit8u value;
if (mem_readb_checked(GetAddress(seg,ofs1+x),&value)) sprintf(temp,"%s","?? ");
else sprintf(temp,"%02X ",value);
strcat(buffer,temp);
}
ofs1+=16;
num-=16;
fprintf(f,"%s\n",buffer);
}
if (num>0) {
sprintf(buffer,"%04X:%04X ",seg,ofs1);
for (Bit16u x=0; x<num; x++) {
Bit8u value;
if (mem_readb_checked(GetAddress(seg,ofs1+x),&value)) sprintf(temp,"%s","?? ");
else sprintf(temp,"%02X ",value);
strcat(buffer,temp);
}
fprintf(f,"%s\n",buffer);
}
fclose(f);
DEBUG_ShowMsg("DEBUG: Memory dump success.\n");
}
static void SaveMemoryBin(Bitu seg, Bitu ofs1, Bit32u num) {
FILE* f = fopen("MEMDUMP.BIN","wb");
if (!f) {
DEBUG_ShowMsg("DEBUG: Memory binary dump failed.\n");
return;
}
for (Bitu x = 0; x < num;x++) {
Bit8u val;
if (mem_readb_checked(GetAddress(seg,ofs1+x),&val)) val=0;
fwrite(&val,1,1,f);
}
fclose(f);
DEBUG_ShowMsg("DEBUG: Memory dump binary success.\n");
}
static void OutputVecTable(char* filename) {
FILE* f = fopen(filename, "wt");
if (!f)
{
DEBUG_ShowMsg("DEBUG: Output of interrupt vector table failed.\n");
return;
}
for (int i=0; i<256; i++)
fprintf(f,"INT %02X: %04X:%04X\n", i, mem_readw(i*4+2), mem_readw(i*4));
fclose(f);
DEBUG_ShowMsg("DEBUG: Interrupt vector table written to %s.\n", filename);
}
#define DEBUG_VAR_BUF_LEN 16
static void DrawVariables(void) {
if (CDebugVar::varList.empty()) return;
std::list<CDebugVar*>::iterator i;
CDebugVar *dv;
char buffer[DEBUG_VAR_BUF_LEN];
int idx = 0;
for(i=CDebugVar::varList.begin(); i != CDebugVar::varList.end(); i++, idx++) {
if (idx == 4*3) {
/* too many variables */
break;
}
dv = static_cast<CDebugVar*>(*i);
Bit16u value;
if (mem_readw_checked(dv->GetAdr(),&value))
snprintf(buffer,DEBUG_VAR_BUF_LEN, "%s", "??????");
else
snprintf(buffer,DEBUG_VAR_BUF_LEN, "0x%04x", value);
int y = idx / 3;
int x = (idx % 3) * 26;
mvwprintw(dbg.win_var, y, x, dv->GetName());
mvwprintw(dbg.win_var, y, (x + DEBUG_VAR_BUF_LEN + 1) , buffer);
}
wrefresh(dbg.win_var);
};
#undef DEBUG_VAR_BUF_LEN
// HEAVY DEBUGGING STUFF
#if C_HEAVY_DEBUG
const Bit32u LOGCPUMAX = 20000;
static Bit32u logCount = 0;
struct TLogInst {
Bit16u s_cs;
Bit32u eip;
Bit32u eax;
Bit32u ebx;
Bit32u ecx;
Bit32u edx;
Bit32u esi;
Bit32u edi;
Bit32u ebp;
Bit32u esp;
Bit16u s_ds;
Bit16u s_es;
Bit16u s_fs;
Bit16u s_gs;
Bit16u s_ss;
bool c;
bool z;
bool s;
bool o;
bool a;
bool p;
bool i;
char dline[31];
char res[23];
};
TLogInst logInst[LOGCPUMAX];
void DEBUG_HeavyLogInstruction(void) {
static char empty[23] = { 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,0 };
PhysPt start = GetAddress(SegValue(cs),reg_eip);
char dline[200];
DasmI386(dline, start, reg_eip, cpu.code.big);
char* res = empty;
if (showExtend) {
res = AnalyzeInstruction(dline,false);
if (!res || !(*res)) res = empty;
Bitu reslen = strlen(res);
if (reslen<22) for (Bitu i=0; i<22-reslen; i++) res[reslen+i] = ' '; res[22] = 0;
};
Bitu len = strlen(dline);
if (len < 30) for (Bitu i=0; i < 30-len; i++) dline[len+i] = ' ';
dline[30] = 0;
TLogInst & inst = logInst[logCount];
strcpy(inst.dline,dline);
inst.s_cs = SegValue(cs);
inst.eip = reg_eip;
strcpy(inst.res,res);
inst.eax = reg_eax;
inst.ebx = reg_ebx;
inst.ecx = reg_ecx;
inst.edx = reg_edx;
inst.esi = reg_esi;
inst.edi = reg_edi;
inst.ebp = reg_ebp;
inst.esp = reg_esp;
inst.s_ds = SegValue(ds);
inst.s_es = SegValue(es);
inst.s_fs = SegValue(fs);
inst.s_gs = SegValue(gs);
inst.s_ss = SegValue(ss);
inst.c = get_CF()>0;
inst.z = get_ZF()>0;
inst.s = get_SF()>0;
inst.o = get_OF()>0;
inst.a = get_AF()>0;
inst.p = get_PF()>0;
inst.i = GETFLAGBOOL(IF);
if (++logCount >= LOGCPUMAX) logCount = 0;
};
void DEBUG_HeavyWriteLogInstruction(void) {
if (!logHeavy) return;
logHeavy = false;
DEBUG_ShowMsg("DEBUG: Creating cpu log LOGCPU_INT_CD.TXT\n");
ofstream out("LOGCPU_INT_CD.TXT");
if (!out.is_open()) {
DEBUG_ShowMsg("DEBUG: Failed.\n");
return;
}
out << hex << noshowbase << setfill('0') << uppercase;
Bit32u startLog = logCount;
do {
// Write Instructions
TLogInst & inst = logInst[startLog];
out << setw(4) << inst.s_cs << ":" << setw(8) << inst.eip << " "
<< inst.dline << " " << inst.res << " EAX:" << setw(8)<< inst.eax
<< " EBX:" << setw(8) << inst.ebx << " ECX:" << setw(8) << inst.ecx
<< " EDX:" << setw(8) << inst.edx << " ESI:" << setw(8) << inst.esi
<< " EDI:" << setw(8) << inst.edi << " EBP:" << setw(8) << inst.ebp
<< " ESP:" << setw(8) << inst.esp << " DS:" << setw(4) << inst.s_ds
<< " ES:" << setw(4) << inst.s_es<< " FS:" << setw(4) << inst.s_fs
<< " GS:" << setw(4) << inst.s_gs<< " SS:" << setw(4) << inst.s_ss
<< " CF:" << inst.c << " ZF:" << inst.z << " SF:" << inst.s
<< " OF:" << inst.o << " AF:" << inst.a << " PF:" << inst.p
<< " IF:" << inst.i << endl;
/* fprintf(f,"%04X:%08X %s %s EAX:%08X EBX:%08X ECX:%08X EDX:%08X ESI:%08X EDI:%08X EBP:%08X ESP:%08X DS:%04X ES:%04X FS:%04X GS:%04X SS:%04X CF:%01X ZF:%01X SF:%01X OF:%01X AF:%01X PF:%01X IF:%01X\n",
logInst[startLog].s_cs,logInst[startLog].eip,logInst[startLog].dline,logInst[startLog].res,logInst[startLog].eax,logInst[startLog].ebx,logInst[startLog].ecx,logInst[startLog].edx,logInst[startLog].esi,logInst[startLog].edi,logInst[startLog].ebp,logInst[startLog].esp,
logInst[startLog].s_ds,logInst[startLog].s_es,logInst[startLog].s_fs,logInst[startLog].s_gs,logInst[startLog].s_ss,
logInst[startLog].c,logInst[startLog].z,logInst[startLog].s,logInst[startLog].o,logInst[startLog].a,logInst[startLog].p,logInst[startLog].i);*/
if (++startLog >= LOGCPUMAX) startLog = 0;
} while (startLog != logCount);
out.close();
DEBUG_ShowMsg("DEBUG: Done.\n");
};
bool DEBUG_HeavyIsBreakpoint(void) {
static Bitu zero_count = 0;
if (cpuLog) {
if (cpuLogCounter>0) {
LogInstruction(SegValue(cs),reg_eip,cpuLogFile);
cpuLogCounter--;
}
if (cpuLogCounter<=0) {
cpuLogFile.close();
DEBUG_ShowMsg("DEBUG: cpu log LOGCPU.TXT created\n");
cpuLog = false;
DEBUG_EnableDebugger();
return true;
}
}
// LogInstruction
if (logHeavy) DEBUG_HeavyLogInstruction();
if (zeroProtect) {
Bit32u value=0;
if (!mem_readd_checked(SegPhys(cs)+reg_eip,&value)) {
if (value == 0) zero_count++;
else zero_count = 0;
}
if (GCC_UNLIKELY(zero_count == 10)) E_Exit("running zeroed code");
}
if (skipFirstInstruction) {
skipFirstInstruction = false;
return false;
}
if (CBreakpoint::CheckBreakpoint(SegValue(cs),reg_eip)) {
return true;
}
return false;
}
#endif // HEAVY DEBUG
#endif // DEBUG
| b-zaar/boxon | src/debug/debug.cpp | C++ | gpl-2.0 | 76,186 |
<?php
/**
* Fires before the display of the group membership request form.
*
* @since BuddyPress (1.1.0)
*/
do_action( 'bp_before_group_request_membership_content' ); ?>
<?php if ( !bp_group_has_requested_membership() ) : ?>
<p>
<?php
printf(
__( "You are requesting to become a member of the group '%s'.", 'thrive' ),
bp_get_group_name( false ) );
?>
</p>
<form action="<?php bp_group_form_action('request-membership' ); ?>" method="post" name="request-membership-form" id="request-membership-form" class="standard-form">
<label for="group-request-membership-comments"><?php _e( 'Comments (optional)', 'thrive' ); ?></label>
<textarea name="group-request-membership-comments" id="group-request-membership-comments"></textarea>
<?php
/**
* Fires after the textarea for the group membership request form.
*
* @since BuddyPress (1.1.0)
*/
do_action( 'bp_group_request_membership_content' ); ?>
<p><input type="submit" name="group-request-send" id="group-request-send" value="<?php esc_attr_e( 'Send Request', 'thrive' ); ?>" />
<?php wp_nonce_field( 'groups_request_membership' ); ?>
</form><!-- #request-membership-form -->
<?php endif; ?>
<?php
/**
* Fires after the display of the group membership request form.
*
* @since BuddyPress (1.1.0)
*/
do_action( 'bp_after_group_request_membership_content' ); ?>
| klfmedia/intranet | wp-content/themes/thrive/buddypress/groups/single/request-membership.php | PHP | gpl-2.0 | 1,374 |
package io.ravitej.selenium.extensions.tests;
import io.ravitej.selenium.extensions.WebDriverExtensions;
import org.apache.commons.lang3.tuple.Pair;
import org.assertj.core.api.SoftAssertions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver.TargetLocator;
import java.io.File;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests for WebDriverExtensions.
*
* @author Ravitej Aluru
*/
public class WebDriverExtensionsTests {
private WebDriver mockWebDriver = mock(WebDriver.class, Mockito.withSettings().extraInterfaces(TakesScreenshot.class));
private TargetLocator mockTargetLocator = mock(TargetLocator.class);
private Alert mockAlert = mock(Alert.class);
private File mockFile = mock(File.class);
@Before
public void beforeTest() {
when(mockWebDriver.switchTo()).thenReturn(mockTargetLocator);
when(mockTargetLocator.alert()).thenReturn(mockAlert);
}
@Test
public void is_alert_displayed_should_return_true_and_alert_text_if_alert_displayed() {
final String alertText = "some mockAlert text";
when(mockAlert.getText()).thenReturn(alertText);
Pair<Boolean, String> p = WebDriverExtensions.isAlertDisplayed(mockWebDriver);
assertThat(p).extracting("key", "value").containsExactly(true, alertText);
}
@Test
public void is_alert_displayed_should_return_false_and_empty_string_if_alert_is_not_displayed() {
when(mockAlert.getText()).thenThrow(NoAlertPresentException.class);
Pair<Boolean, String> p = WebDriverExtensions.isAlertDisplayed(mockWebDriver);
assertThat(p).extracting("key", "value").containsExactly(false, "");
}
@Test
public void take_screenshot_should_return_file_if_successful_on_first_attempt() {
when(((TakesScreenshot) mockWebDriver).getScreenshotAs(OutputType.FILE)).thenReturn(mockFile);
File screenshot = WebDriverExtensions.takeScreenshot(mockWebDriver);
SoftAssertions.assertSoftly(softly -> {
softly.assertThat(screenshot)
.isInstanceOf(File.class)
.isNotNull();
});
}
@Test
public void take_screenshot_should_return_file_if_successful_on_second_attempt() {
when(((TakesScreenshot) mockWebDriver).getScreenshotAs(OutputType.FILE))
.thenThrow(new WebDriverException())
.thenReturn(mockFile);
File screenshot = WebDriverExtensions.takeScreenshot(mockWebDriver);
SoftAssertions.assertSoftly(softly -> {
softly.assertThat(screenshot)
.isInstanceOf(File.class)
.isNotNull();
});
}
@Test
public void take_screenshot_should_throw_webdriverexception_if_not_successful_on_second_attempt() {
when(((TakesScreenshot) mockWebDriver).getScreenshotAs(OutputType.FILE))
.thenThrow(new WebDriverException());
assertThatExceptionOfType(WebDriverException.class).isThrownBy(() -> {
WebDriverExtensions.takeScreenshot(mockWebDriver);
});
}
@Test
public void take_screenshot_should_wait_for_given_amount_of_time_if_not_successful_on_first_attempt() {
when(((TakesScreenshot) mockWebDriver).getScreenshotAs(OutputType.FILE))
.thenThrow(new WebDriverException())
.thenReturn(mockFile);
final long waitTime = 1000;
long before = System.currentTimeMillis();
WebDriverExtensions.takeScreenshot(mockWebDriver, waitTime);
long after = System.currentTimeMillis();
//checking that the method took at least 1 second to execute since the waitTime is 1 second.
assertThat(after - before).isGreaterThanOrEqualTo(waitTime);
}
} | ravitej-aluru/UI-Automation-Framework.Java | selenium-extensions/src/test/java/io/ravitej/selenium/extensions/tests/WebDriverExtensionsTests.java | Java | gpl-2.0 | 4,010 |
<?php
namespace Autocondat\ProfileBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Autocondat\ProfileBundle\Entity\PermisosRole;
use Autocondat\ProfileBundle\Form\PermisosRoleType;
/**
* PermisosRole controller.
*
* @Route("/permisos_role")
*/
class PermisosRoleController extends Controller
{
/**
* Lists all PermisosRole entities.
*
* @Route("/", name="permisos_role")
* @Method("GET")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('AutocondatProfileBundle:PermisosRole')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Creates a new PermisosRole entity.
*
* @Route("/", name="permisos_role_create")
* @Method("POST")
* @Template("AutocondatProfileBundle:PermisosRole:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new PermisosRole();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('permisos_role_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a PermisosRole entity.
*
* @param PermisosRole $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(PermisosRole $entity)
{
$form = $this->createForm(new PermisosRoleType(), $entity, array(
'action' => $this->generateUrl('permisos_role_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new PermisosRole entity.
*
* @Route("/new", name="permisos_role_new")
* @Method("GET")
* @Template()
*/
public function newAction()
{
$entity = new PermisosRole();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a PermisosRole entity.
*
* @Route("/{id}", name="permisos_role_show")
* @Method("GET")
* @Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AutocondatProfileBundle:PermisosRole')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find PermisosRole entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing PermisosRole entity.
*
* @Route("/{id}/edit", name="permisos_role_edit")
* @Method("GET")
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AutocondatProfileBundle:PermisosRole')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find PermisosRole entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a PermisosRole entity.
*
* @param PermisosRole $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(PermisosRole $entity)
{
$form = $this->createForm(new PermisosRoleType(), $entity, array(
'action' => $this->generateUrl('permisos_role_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing PermisosRole entity.
*
* @Route("/{id}", name="permisos_role_update")
* @Method("PUT")
* @Template("AutocondatProfileBundle:PermisosRole:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AutocondatProfileBundle:PermisosRole')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find PermisosRole entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('permisos_role_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a PermisosRole entity.
*
* @Route("/{id}", name="permisos_role_delete")
* @Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('AutocondatProfileBundle:PermisosRole')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find PermisosRole entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('permisos_role'));
}
/**
* Creates a form to delete a PermisosRole entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('permisos_role_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
| erparom/autocondat_ecr | src/Autocondat/ProfileBundle/Controller/PermisosRoleController.php | PHP | gpl-2.0 | 6,996 |
<?php
namespace Notification\Messages\Code\Tables;
use Doctrine\ORM\Mapping as ORM;
/**
* Messages
*
* @ORM\Table(name="notification_messages")
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Messages extends \Kazist\Table\BaseTable
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @var string
*
* @ORM\Column(name="message", type="text", nullable=false)
*/
protected $message;
/**
* @var integer
*
* @ORM\Column(name="created_by", type="integer", length=11, nullable=false)
*/
protected $created_by;
/**
* @var \DateTime
*
* @ORM\Column(name="date_created", type="datetime", nullable=false)
*/
protected $date_created;
/**
* @var integer
*
* @ORM\Column(name="modified_by", type="integer", length=11, nullable=false)
*/
protected $modified_by;
/**
* @var \DateTime
*
* @ORM\Column(name="date_modified", type="datetime", nullable=false)
*/
protected $date_modified;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set message
*
* @param string $message
*
* @return Messages
*/
public function setMessage($message)
{
$this->message = $message;
return $this;
}
/**
* Get message
*
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* Get createdBy
*
* @return integer
*/
public function getCreatedBy()
{
return $this->created_by;
}
/**
* Get dateCreated
*
* @return \DateTime
*/
public function getDateCreated()
{
return $this->date_created;
}
/**
* Get modifiedBy
*
* @return integer
*/
public function getModifiedBy()
{
return $this->modified_by;
}
/**
* Get dateModified
*
* @return \DateTime
*/
public function getDateModified()
{
return $this->date_modified;
}
/**
* @ORM\PreUpdate
*/
public function onPreUpdate()
{
// Add your code here
}
}
| kazist/kazist | applications/Notification/Messages/Code/Tables/Messages.php | PHP | gpl-2.0 | 2,373 |
/*
* Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Common.h"
#include "SharedDefines.h"
#include "WorldPacket.h"
#include "Opcodes.h"
#include "Log.h"
#include "Player.h"
#include "ObjectMgr.h"
#include "WorldSession.h"
#include "Object.h"
#include "Chat.h"
#include "BattleGroundMgr.h"
#include "BattleGroundWS.h"
#include "BattleGround.h"
#include "ArenaTeam.h"
#include "Language.h"
#include "ScriptMgr.h"
#include "World.h"
void WorldSession::HandleBattlemasterHelloOpcode(WorldPacket & recv_data)
{
ObjectGuid guid;
recv_data >> guid;
DEBUG_LOG("WORLD: Recvd CMSG_BATTLEMASTER_HELLO Message from %s", guid.GetString().c_str());
Creature *pCreature = GetPlayer()->GetMap()->GetCreature(guid);
if (!pCreature)
return;
if (!pCreature->isBattleMaster()) // it's not battlemaster
return;
// Stop the npc if moving
if (!pCreature->IsStopped())
pCreature->StopMoving();
BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(pCreature->GetEntry());
if (bgTypeId == BATTLEGROUND_TYPE_NONE)
return;
if (!_player->GetBGAccessByLevel(bgTypeId))
{
// temp, must be gossip message...
SendNotification(LANG_YOUR_BG_LEVEL_REQ_ERROR);
return;
}
SendBattlegGroundList(guid, bgTypeId);
}
void WorldSession::SendBattlegGroundList( ObjectGuid guid, BattleGroundTypeId bgTypeId )
{
WorldPacket data;
sBattleGroundMgr.BuildBattleGroundListPacket(&data, guid, _player, bgTypeId, 0);
SendPacket( &data );
}
void WorldSession::HandleBattlemasterJoinOpcode( WorldPacket & recv_data )
{
ObjectGuid guid;
uint32 bgTypeId_;
uint32 instanceId;
uint8 joinAsGroup;
bool isPremade = false;
Group * grp;
recv_data >> guid; // battlemaster guid
recv_data >> bgTypeId_; // battleground type id (DBC id)
recv_data >> instanceId; // instance id, 0 if First Available selected
recv_data >> joinAsGroup; // join as group
if (!sBattlemasterListStore.LookupEntry(bgTypeId_))
{
sLog.outError("Battleground: invalid bgtype (%u) received. possible cheater? player guid %u",bgTypeId_,_player->GetGUIDLow());
return;
}
BattleGroundTypeId bgTypeId = BattleGroundTypeId(bgTypeId_);
DEBUG_LOG( "WORLD: Recvd CMSG_BATTLEMASTER_JOIN Message from %s", guid.GetString().c_str());
// can do this, since it's battleground, not arena
BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(bgTypeId, ARENA_TYPE_NONE);
BattleGroundQueueTypeId bgQueueTypeIdRandom = BattleGroundMgr::BGQueueTypeId(BATTLEGROUND_RB, ARENA_TYPE_NONE);
// ignore if player is already in BG
if (_player->InBattleGround())
return;
// prevent joining from instances
uint32 mapid = _player->GetMapId();
if(mapid != 0 && mapid != 1 && mapid != 530 && mapid != 571 && mapid !=13)
{
SendNotification("You cannot join from here");
return;
}
// get bg instance or bg template if instance not found
BattleGround *bg = NULL;
if (instanceId)
bg = sBattleGroundMgr.GetBattleGroundThroughClientInstance(instanceId, bgTypeId);
if (!bg && !(bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId)))
{
sLog.outError("Battleground: no available bg / template found");
return;
}
// expected bracket entry
PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bg->GetMapId(),_player->getLevel());
if (!bracketEntry)
return;
GroupJoinBattlegroundResult err;
// check queue conditions
if (!joinAsGroup)
{
// check Deserter debuff
if (!_player->CanJoinToBattleground())
{
WorldPacket data;
sBattleGroundMgr.BuildGroupJoinedBattlegroundPacket(&data, ERR_GROUP_JOIN_BATTLEGROUND_DESERTERS);
_player->GetSession()->SendPacket(&data);
return;
}
if (_player->GetBattleGroundQueueIndex(bgQueueTypeIdRandom) < PLAYER_MAX_BATTLEGROUND_QUEUES)
{
//player is already in random queue
WorldPacket data;
sBattleGroundMgr.BuildGroupJoinedBattlegroundPacket(&data, ERR_IN_RANDOM_BG);
_player->GetSession()->SendPacket(&data);
return;
}
if(_player->InBattleGroundQueue() && bgTypeId == BATTLEGROUND_RB)
{
//player is already in queue, can't start random queue
WorldPacket data;
sBattleGroundMgr.BuildGroupJoinedBattlegroundPacket(&data, ERR_IN_NON_RANDOM_BG);
_player->GetSession()->SendPacket(&data);
return;
}
// check if already in queue
if (_player->GetBattleGroundQueueIndex(bgQueueTypeId) < PLAYER_MAX_BATTLEGROUND_QUEUES)
//player is already in this queue
return;
// check if has free queue slots
if (!_player->HasFreeBattleGroundQueueId())
{
WorldPacket data;
sBattleGroundMgr.BuildGroupJoinedBattlegroundPacket(&data, ERR_BATTLEGROUND_TOO_MANY_QUEUES);
_player->GetSession()->SendPacket(&data);
return;
}
}
else
{
grp = _player->GetGroup();
// no group found, error
if (!grp)
return;
if (grp->GetLeaderGuid() != _player->GetObjectGuid())
return;
bool have_bots = false;
for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* member = itr->getSource();
if (!member)
continue; // this should never happen
if (member->GetPlayerbotAI())
{
ChatHandler(_player).PSendSysMessage("|cffff0000You cannot get in battleground queue as premade because you have bots in your group. Adding you in queue as single player.");
have_bots = true;
joinAsGroup = false;
break;
}
}
if (!have_bots)
{
err = grp->CanJoinBattleGroundQueue(bg, bgQueueTypeId, 0, bg->GetMaxPlayersPerTeam(), false, 0);
isPremade = sWorld.getConfig(CONFIG_UINT32_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH) &&
(grp->GetMembersCount() >= bg->GetMinPlayersPerTeam());
}
}
// if we're here, then the conditions to join a bg are met. We can proceed in joining.
// _player->GetGroup() was already checked, grp is already initialized
BattleGroundQueue& bgQueue = sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId];
if (joinAsGroup)
{
GroupQueueInfo *ginfo = NULL;
uint32 avgTime = 0;
if(err > 0)
{
DEBUG_LOG("Battleground: the following players are joining as group:");
ginfo = bgQueue.AddGroup(_player, grp, bgTypeId, bracketEntry, ARENA_TYPE_NONE, false, isPremade, 0, 0);
avgTime = bgQueue.GetAverageQueueWaitTime(ginfo, bracketEntry->GetBracketId());
}
for(GroupReference *itr = grp->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player *member = itr->getSource();
if(!member)
continue; // this should never happen
WorldPacket data;
if(err <= 0)
{
sBattleGroundMgr.BuildGroupJoinedBattlegroundPacket(&data, err);
member->GetSession()->SendPacket(&data);
continue;
}
// add to queue
uint32 queueSlot = member->AddBattleGroundQueueId(bgQueueTypeId);
// send status packet (in queue)
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_QUEUE, avgTime, 0, ginfo->arenaType);
member->GetSession()->SendPacket(&data);
sBattleGroundMgr.BuildGroupJoinedBattlegroundPacket(&data, err);
member->GetSession()->SendPacket(&data);
DEBUG_LOG("Battleground: player joined queue for bg queue type %u bg type %u: GUID %u, NAME %s",bgQueueTypeId,bgTypeId,member->GetGUIDLow(), member->GetName());
}
DEBUG_LOG("Battleground: group end");
}
else
{
GroupQueueInfo * ginfo = bgQueue.AddGroup(_player, NULL, bgTypeId, bracketEntry, ARENA_TYPE_NONE, false, isPremade, 0, 0);
uint32 avgTime = bgQueue.GetAverageQueueWaitTime(ginfo, bracketEntry->GetBracketId());
// already checked if queueSlot is valid, now just get it
uint32 queueSlot = _player->AddBattleGroundQueueId(bgQueueTypeId);
WorldPacket data;
// send status packet (in queue)
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_QUEUE, avgTime, 0, ginfo->arenaType);
SendPacket(&data);
DEBUG_LOG("Battleground: player joined queue for bg queue type %u bg type %u: GUID %u, NAME %s",bgQueueTypeId,bgTypeId,_player->GetGUIDLow(), _player->GetName());
}
sBattleGroundMgr.ScheduleQueueUpdate(0, ARENA_TYPE_NONE, bgQueueTypeId, bgTypeId, bracketEntry->GetBracketId());
}
void WorldSession::HandleBattleGroundPlayerPositionsOpcode( WorldPacket & /*recv_data*/ )
{
// empty opcode
DEBUG_LOG("WORLD: Recvd MSG_BATTLEGROUND_PLAYER_POSITIONS Message");
BattleGround *bg = _player->GetBattleGround();
if(!bg) // can't be received if player not in battleground
return;
switch( bg->GetTypeID(true) )
{
case BATTLEGROUND_WS:
{
uint32 count1 = 0; // always constant zero?
uint32 count2 = 0; // count of next fields
Player *ali_plr = sObjectMgr.GetPlayer(((BattleGroundWS*)bg)->GetAllianceFlagPickerGuid());
if (ali_plr)
++count2;
Player *horde_plr = sObjectMgr.GetPlayer(((BattleGroundWS*)bg)->GetHordeFlagPickerGuid());
if (horde_plr)
++count2;
WorldPacket data(MSG_BATTLEGROUND_PLAYER_POSITIONS, (4+4+16*count1+16*count2));
data << count1; // alliance flag holders count - obsolete, now always 0
/*for(uint8 i = 0; i < count1; ++i)
{
data << ObjectGuid(0); // guid
data << (float)0; // x
data << (float)0; // y
}*/
data << count2; // horde flag holders count - obsolete, now count of next fields
if (ali_plr)
{
data << ObjectGuid(ali_plr->GetObjectGuid());
data << float(ali_plr->GetPositionX());
data << float(ali_plr->GetPositionY());
}
if (horde_plr)
{
data << ObjectGuid(horde_plr->GetObjectGuid());
data << float(horde_plr->GetPositionX());
data << float(horde_plr->GetPositionY());
}
SendPacket(&data);
}
break;
case BATTLEGROUND_EY:
//TODO : fix me!
break;
case BATTLEGROUND_AB:
case BATTLEGROUND_AV:
{
//for other BG types - send default
WorldPacket data(MSG_BATTLEGROUND_PLAYER_POSITIONS, (4+4));
data << uint32(0);
data << uint32(0);
SendPacket(&data);
}
break;
default:
//maybe it is sent also in arena - do nothing
break;
}
}
void WorldSession::HandlePVPLogDataOpcode( WorldPacket & /*recv_data*/ )
{
DEBUG_LOG( "WORLD: Recvd MSG_PVP_LOG_DATA Message");
BattleGround *bg = _player->GetBattleGround();
if (!bg)
return;
// arena finish version will send in BattleGround::EndBattleGround directly
if (bg->isArena())
return;
WorldPacket data;
sBattleGroundMgr.BuildPvpLogDataPacket(&data, bg);
SendPacket(&data);
DEBUG_LOG( "WORLD: Sent MSG_PVP_LOG_DATA Message");
}
void WorldSession::HandleBattlefieldListOpcode( WorldPacket &recv_data )
{
DEBUG_LOG( "WORLD: Recvd CMSG_BATTLEFIELD_LIST Message");
uint32 bgTypeId;
recv_data >> bgTypeId; // id from DBC
uint8 fromWhere;
recv_data >> fromWhere; // 0 - battlemaster (lua: ShowBattlefieldList), 1 - UI (lua: RequestBattlegroundInstanceInfo)
uint8 unk1;
recv_data >> unk1; // unknown 3.2.2
BattlemasterListEntry const* bl = sBattlemasterListStore.LookupEntry(bgTypeId);
if (!bl)
{
sLog.outError("Battleground: invalid bgtype received.");
return;
}
WorldPacket data;
sBattleGroundMgr.BuildBattleGroundListPacket(&data, ObjectGuid(), _player, BattleGroundTypeId(bgTypeId), fromWhere);
SendPacket( &data );
}
void WorldSession::HandleBattleFieldPortOpcode( WorldPacket &recv_data )
{
DEBUG_LOG( "WORLD: Recvd CMSG_BATTLEFIELD_PORT Message");
uint8 type; // arenatype if arena
uint8 unk2; // unk, can be 0x0 (may be if was invited?) and 0x1
uint32 bgTypeId_; // type id from dbc
uint16 unk; // 0x1F90 constant?
uint8 action; // enter battle 0x1, leave queue 0x0
recv_data >> type >> unk2 >> bgTypeId_ >> unk >> action;
if (!sBattlemasterListStore.LookupEntry(bgTypeId_))
{
sLog.outError("BattlegroundHandler: invalid bgtype (%u) received.", bgTypeId_);
return;
}
if (type && !IsArenaTypeValid(ArenaType(type)))
{
sLog.outError("BattlegroundHandler: Invalid CMSG_BATTLEFIELD_PORT received from player (%u), arena type wrong: %u.", _player->GetGUIDLow(), type);
return;
}
if (!_player->InBattleGroundQueue())
{
sLog.outError("BattlegroundHandler: Invalid CMSG_BATTLEFIELD_PORT received from player (%u), he is not in bg_queue.", _player->GetGUIDLow());
return;
}
//get GroupQueueInfo from BattleGroundQueue
BattleGroundTypeId bgTypeId = BattleGroundTypeId(bgTypeId_);
BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(bgTypeId, ArenaType(type));
BattleGroundQueue& bgQueue = sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId];
//we must use temporary variable, because GroupQueueInfo pointer can be deleted in BattleGroundQueue::RemovePlayer() function
GroupQueueInfo ginfo;
if (!bgQueue.GetPlayerGroupInfoData(_player->GetObjectGuid(), &ginfo))
{
sLog.outError("BattlegroundHandler: itrplayerstatus not found.");
return;
}
// if action == 1, then instanceId is required
if (!ginfo.IsInvitedToBGInstanceGUID && action == 1)
{
sLog.outError("BattlegroundHandler: instance not found.");
return;
}
BattleGround *bg = sBattleGroundMgr.GetBattleGround(ginfo.IsInvitedToBGInstanceGUID, bgTypeId);
// bg template might and must be used in case of leaving queue, when instance is not created yet
if (!bg && action == 0)
bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
if (!bg)
{
sLog.outError("BattlegroundHandler: bg_template not found for type id %u.", bgTypeId);
return;
}
// expected bracket entry
PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bg->GetMapId(),_player->getLevel());
if (!bracketEntry)
return;
//some checks if player isn't cheating - it is not exactly cheating, but we cannot allow it
if (action == 1 && ginfo.arenaType == ARENA_TYPE_NONE)
{
//if player is trying to enter battleground (not arena!) and he has deserter debuff, we must just remove him from queue
if (!_player->CanJoinToBattleground())
{
//send bg command result to show nice message
WorldPacket data2;
sBattleGroundMgr.BuildGroupJoinedBattlegroundPacket(&data2, ERR_GROUP_JOIN_BATTLEGROUND_DESERTERS);
_player->GetSession()->SendPacket(&data2);
action = 0;
DEBUG_LOG("Battleground: player %s (%u) has a deserter debuff, do not port him to battleground!", _player->GetName(), _player->GetGUIDLow());
}
//if player don't match battleground max level, then do not allow him to enter! (this might happen when player leveled up during his waiting in queue
if (_player->getLevel() > bg->GetMaxLevel())
{
sLog.outError("Battleground: Player %s (%u) has level (%u) higher than maxlevel (%u) of battleground (%u)! Do not port him to battleground!",
_player->GetName(), _player->GetGUIDLow(), _player->getLevel(), bg->GetMaxLevel(), bg->GetTypeID());
action = 0;
}
}
uint32 queueSlot = _player->GetBattleGroundQueueIndex(bgQueueTypeId);
WorldPacket data;
switch( action )
{
case 1: // port to battleground
if (!_player->IsInvitedForBattleGroundQueueType(bgQueueTypeId))
return; // cheating?
if (!_player->InBattleGround())
_player->SetBattleGroundEntryPoint();
// resurrect the player
if (!_player->isAlive())
{
_player->ResurrectPlayer(1.0f);
_player->SpawnCorpseBones();
}
// stop taxi flight at port
if (_player->IsTaxiFlying())
{
_player->GetMotionMaster()->MovementExpired();
_player->m_taxi.ClearTaxiDestinations();
}
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_IN_PROGRESS, 0, bg->GetStartTime(), bg->GetArenaType());
_player->GetSession()->SendPacket(&data);
// remove battleground queue status from BGmgr
bgQueue.RemovePlayer(_player->GetObjectGuid(), false);
// this is still needed here if battleground "jumping" shouldn't add deserter debuff
// also this is required to prevent stuck at old battleground after SetBattleGroundId set to new
if (BattleGround *currentBg = _player->GetBattleGround())
currentBg->RemovePlayerAtLeave(_player->GetObjectGuid(), false, true);
// set the destination instance id
_player->SetBattleGroundId(bg->GetInstanceID(), bgTypeId);
// set the destination team
_player->SetBGTeam(ginfo.GroupTeam);
// bg->HandleBeforeTeleportToBattleGround(_player);
_player->RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
_player->RemoveSpellsCausingAura(SPELL_AURA_FLY);
sBattleGroundMgr.SendToBattleGround(_player, ginfo.IsInvitedToBGInstanceGUID, bgTypeId);
// add only in HandleMoveWorldPortAck()
// bg->AddPlayer(_player,team);
DEBUG_LOG("Battleground: player %s (%u) joined battle for bg %u, bgtype %u, queue type %u.", _player->GetName(), _player->GetGUIDLow(), bg->GetInstanceID(), bg->GetTypeID(), bgQueueTypeId);
break;
case 0: // leave queue
// if player leaves rated arena match before match start, it is counted as he played but he lost
/*if (ginfo.IsRated && ginfo.IsInvitedToBGInstanceGUID)
{
ArenaTeam * at = sObjectMgr.GetArenaTeamById(ginfo.ArenaTeamId);
if (at)
{
DEBUG_LOG("UPDATING memberLost's personal arena rating for %s by opponents rating: %u, because he has left queue!", _player->GetGuidStr().c_str(), ginfo.OpponentsTeamRating);
at->MemberLost(_player, ginfo.OpponentsTeamRating);
at->SaveToDB();
}
}*/
_player->RemoveBattleGroundQueueId(bgQueueTypeId); // must be called this way, because if you move this call to queue->removeplayer, it causes bugs
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_NONE, 0, 0, ARENA_TYPE_NONE);
bgQueue.RemovePlayer(_player->GetObjectGuid(), true);
// player left queue, we should update it - do not update Arena Queue
if (ginfo.arenaType == ARENA_TYPE_NONE)
sBattleGroundMgr.ScheduleQueueUpdate(ginfo.ArenaTeamRating, ginfo.arenaType, bgQueueTypeId, bgTypeId, bracketEntry->GetBracketId());
SendPacket(&data);
DEBUG_LOG("Battleground: player %s (%u) left queue for bgtype %u, queue type %u.", _player->GetName(), _player->GetGUIDLow(), bg->GetTypeID(), bgQueueTypeId);
break;
default:
sLog.outError("Battleground port: unknown action %u", action);
break;
}
}
void WorldSession::HandleLeaveBattlefieldOpcode( WorldPacket& recv_data )
{
DEBUG_LOG( "WORLD: Recvd CMSG_LEAVE_BATTLEFIELD Message");
recv_data.read_skip<uint8>(); // unk1
recv_data.read_skip<uint8>(); // unk2
recv_data.read_skip<uint32>(); // BattleGroundTypeId
recv_data.read_skip<uint16>(); // unk3
//if(bgTypeId >= MAX_BATTLEGROUND_TYPES) // cheating? but not important in this case
// return;
// not allow leave battleground in combat
if (_player->isInCombat())
if (BattleGround* bg = _player->GetBattleGround())
if (bg->GetStatus() != STATUS_WAIT_LEAVE)
return;
_player->LeaveBattleground();
}
void WorldSession::HandleBattlefieldStatusOpcode( WorldPacket & /*recv_data*/ )
{
// empty opcode
DEBUG_LOG( "WORLD: Battleground status" );
WorldPacket data;
// we must update all queues here
BattleGround *bg = NULL;
for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
{
BattleGroundQueueTypeId bgQueueTypeId = _player->GetBattleGroundQueueTypeId(i);
if (!bgQueueTypeId)
continue;
BattleGroundTypeId bgTypeId = BattleGroundMgr::BGTemplateId(bgQueueTypeId);
ArenaType arenaType = BattleGroundMgr::BGArenaType(bgQueueTypeId);
if (bgTypeId == _player->GetBattleGroundTypeId())
{
bg = _player->GetBattleGround();
//i cannot check any variable from player class because player class doesn't know if player is in 2v2 / 3v3 or 5v5 arena
//so i must use bg pointer to get that information
if (bg && bg->GetArenaType() == arenaType)
{
// this line is checked, i only don't know if GetStartTime is changing itself after bg end!
// send status in BattleGround
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, i, STATUS_IN_PROGRESS, bg->GetEndTime(), bg->GetStartTime(), arenaType);
SendPacket(&data);
continue;
}
}
//we are sending update to player about queue - he can be invited there!
//get GroupQueueInfo for queue status
BattleGroundQueue& bgQueue = sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId];
GroupQueueInfo ginfo;
if (!bgQueue.GetPlayerGroupInfoData(_player->GetObjectGuid(), &ginfo))
continue;
if (ginfo.IsInvitedToBGInstanceGUID)
{
bg = sBattleGroundMgr.GetBattleGround(ginfo.IsInvitedToBGInstanceGUID, bgTypeId);
if (!bg)
continue;
uint32 remainingTime = WorldTimer::getMSTimeDiff(WorldTimer::getMSTime(), ginfo.RemoveInviteTime);
// send status invited to BattleGround
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, i, STATUS_WAIT_JOIN, remainingTime, 0, arenaType);
SendPacket(&data);
}
else
{
bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
if (!bg)
continue;
// expected bracket entry
PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bg->GetMapId(),_player->getLevel());
if (!bracketEntry)
continue;
uint32 avgTime = bgQueue.GetAverageQueueWaitTime(&ginfo, bracketEntry->GetBracketId());
// send status in BattleGround Queue
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, i, STATUS_WAIT_QUEUE, avgTime, WorldTimer::getMSTimeDiff(ginfo.JoinTime, WorldTimer::getMSTime()), arenaType);
SendPacket(&data);
}
}
}
void WorldSession::HandleAreaSpiritHealerQueryOpcode( WorldPacket & recv_data )
{
DEBUG_LOG("WORLD: CMSG_AREA_SPIRIT_HEALER_QUERY");
BattleGround *bg = _player->GetBattleGround();
if (!bg)
return;
ObjectGuid guid;
recv_data >> guid;
Creature *unit = GetPlayer()->GetMap()->GetCreature(guid);
if (!unit)
return;
if(!unit->isSpiritService()) // it's not spirit service
return;
unit->SendAreaSpiritHealerQueryOpcode(GetPlayer());
}
void WorldSession::HandleAreaSpiritHealerQueueOpcode( WorldPacket & recv_data )
{
DEBUG_LOG("WORLD: CMSG_AREA_SPIRIT_HEALER_QUEUE");
BattleGround *bg = _player->GetBattleGround();
if (!bg)
return;
ObjectGuid guid;
recv_data >> guid;
Creature *unit = GetPlayer()->GetMap()->GetCreature(guid);
if (!unit)
return;
if(!unit->isSpiritService()) // it's not spirit service
return;
sScriptMgr.OnGossipHello(GetPlayer(), unit);
}
void WorldSession::HandleBattlemasterJoinArena( WorldPacket & recv_data )
{
DEBUG_LOG("WORLD: CMSG_BATTLEMASTER_JOIN_ARENA");
//recv_data.hexlike();
ObjectGuid guid; // arena Battlemaster guid
uint8 arenaslot; // 2v2, 3v3 or 5v5
uint8 asGroup; // asGroup
uint8 isRated; // isRated
recv_data >> guid >> arenaslot >> asGroup >> isRated;
// ignore if we already in BG or BG queue
if (_player->InBattleGround())
return;
Creature *unit = GetPlayer()->GetMap()->GetCreature(guid);
if (!unit)
return;
if(!unit->isBattleMaster()) // it's not battle master
return;
ArenaType arenatype;
uint32 arenaRating = 0;
switch(arenaslot)
{
case 0:
arenatype = ARENA_TYPE_2v2;
break;
case 1:
arenatype = ARENA_TYPE_3v3;
break;
case 2:
arenatype = ARENA_TYPE_5v5;
break;
default:
sLog.outError("Unknown arena slot %u at HandleBattlemasterJoinArena()", arenaslot);
return;
}
// check existence
BattleGround* bg = sBattleGroundMgr.GetBattleGroundTemplate(BATTLEGROUND_AA);
if (!bg)
{
sLog.outError("Battleground: template bg (all arenas) not found");
return;
}
BattleGroundTypeId bgTypeId = bg->GetTypeID();
BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(bgTypeId, arenatype);
PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bg->GetMapId(),_player->getLevel());
if (!bracketEntry)
return;
GroupJoinBattlegroundResult err;
Group * grp = NULL;
// check queue conditions
if (!asGroup)
{
// you can't join in this way by client
if (isRated)
return;
// check if already in queue
if (_player->GetBattleGroundQueueIndex(bgQueueTypeId) < PLAYER_MAX_BATTLEGROUND_QUEUES)
//player is already in this queue
return;
// check if has free queue slots
if (!_player->HasFreeBattleGroundQueueId())
return;
}
else
{
grp = _player->GetGroup();
// no group found, error
if (!grp)
return;
if (grp->GetLeaderGuid() != _player->GetObjectGuid())
return;
// may be Group::CanJoinBattleGroundQueue should be moved to player class...
err = grp->CanJoinBattleGroundQueue(bg, bgQueueTypeId, arenatype, arenatype, (bool)isRated, arenaslot);
}
uint32 ateamId = 0;
if (isRated)
{
ateamId = _player->GetArenaTeamId(arenaslot);
// check real arena team existence only here (if it was moved to group->CanJoin .. () then we would have to get it twice)
ArenaTeam * at = sObjectMgr.GetArenaTeamById(ateamId);
if (!at)
{
_player->GetSession()->SendNotInArenaTeamPacket(arenatype);
return;
}
// get the team rating for queue
arenaRating = at->GetRating();
// the arena team id must match for everyone in the group
// get the personal ratings for queue
uint32 avg_pers_rating = 0;
for(Group::member_citerator citr = grp->GetMemberSlots().begin(); citr != grp->GetMemberSlots().end(); ++citr)
{
ArenaTeamMember const* at_member = at->GetMember(citr->guid);
if (!at_member) // group member joining to arena must be in leader arena team
return;
avg_pers_rating += at_member->matchmaker_rating;
}
avg_pers_rating /= grp->GetMembersCount();
/* Save mmr before enter arena (matchmaker rating fix) */
at->SetBattleRating(avg_pers_rating);
arenaRating = avg_pers_rating;
}
BattleGroundQueue &bgQueue = sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId];
if (asGroup)
{
uint32 avgTime = 0;
if(err > 0)
{
DEBUG_LOG("Battleground: arena join as group start");
if (isRated)
DEBUG_LOG("Battleground: arena team id %u, leader %s queued with rating %u for type %u",_player->GetArenaTeamId(arenaslot),_player->GetName(),arenaRating,arenatype);
GroupQueueInfo * ginfo = bgQueue.AddGroup(_player, grp, bgTypeId, bracketEntry, arenatype, isRated, false, arenaRating, ateamId);
avgTime = bgQueue.GetAverageQueueWaitTime(ginfo, bracketEntry->GetBracketId());
}
for(GroupReference *itr = grp->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player *member = itr->getSource();
if(!member)
continue;
WorldPacket data;
if(err <= 0)
{
sBattleGroundMgr.BuildGroupJoinedBattlegroundPacket(&data, err);
member->GetSession()->SendPacket(&data);
continue;
}
// add to queue
uint32 queueSlot = member->AddBattleGroundQueueId(bgQueueTypeId);
// send status packet (in queue)
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_QUEUE, avgTime, 0, arenatype);
member->GetSession()->SendPacket(&data);
sBattleGroundMgr.BuildGroupJoinedBattlegroundPacket(&data, err);
member->GetSession()->SendPacket(&data);
DEBUG_LOG("Battleground: player joined queue for arena as group bg queue type %u bg type %u: GUID %u, NAME %s", bgQueueTypeId, bgTypeId, member->GetGUIDLow(), member->GetName());
}
DEBUG_LOG("Battleground: arena join as group end");
}
else
{
GroupQueueInfo * ginfo = bgQueue.AddGroup(_player, NULL, bgTypeId, bracketEntry, arenatype, isRated, false, arenaRating, ateamId);
uint32 avgTime = bgQueue.GetAverageQueueWaitTime(ginfo, bracketEntry->GetBracketId());
uint32 queueSlot = _player->AddBattleGroundQueueId(bgQueueTypeId);
WorldPacket data;
// send status packet (in queue)
sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_QUEUE, avgTime, 0, arenatype);
SendPacket(&data);
DEBUG_LOG("Battleground: player joined queue for arena, skirmish, bg queue type %u bg type %u: GUID %u, NAME %s",bgQueueTypeId,bgTypeId,_player->GetGUIDLow(), _player->GetName());
}
sBattleGroundMgr.ScheduleQueueUpdate(arenaRating, arenatype, bgQueueTypeId, bgTypeId, bracketEntry->GetBracketId());
}
void WorldSession::HandleReportPvPAFK( WorldPacket & recv_data )
{
ObjectGuid playerGuid;
recv_data >> playerGuid;
Player *reportedPlayer = sObjectMgr.GetPlayer(playerGuid);
if (!reportedPlayer)
{
DEBUG_LOG("WorldSession::HandleReportPvPAFK: player not found");
return;
}
DEBUG_LOG("WorldSession::HandleReportPvPAFK: %s reported %s", _player->GetName(), reportedPlayer->GetName());
reportedPlayer->ReportedAfkBy(_player);
}
| Erotix8210/WoWBaseEmu | src/game/BattleGroundHandler.cpp | C++ | gpl-2.0 | 34,375 |
<?php
namespace Repository;
class AccessoRepository extends Repository
{
public function getTableName()
{
return 'accesso';
}
} | savez/presence-detector | ws/src/Repository/AccessoRepository.php | PHP | gpl-2.0 | 149 |
package com.androidgames.framework.gl;
import javax.microedition.khronos.opengles.GL10;
import android.util.FloatMath;
import com.androidgames.framework.impl.GLGraphics;
import com.androidgames.framework.math.Vector2;
public class SpriteBatcher {
final float[] verticesBuffer;
int bufferIndex;
final Vertices vertices;
int numSprites;
public SpriteBatcher(GLGraphics glGraphics, int maxSprites) {
this.verticesBuffer = new float[maxSprites*4*4];
this.vertices = new Vertices(glGraphics, maxSprites*4, maxSprites*6, false, true);
this.bufferIndex = 0;
this.numSprites = 0;
short[] indices = new short[maxSprites*6];
int len = indices.length;
short j = 0;
for (int i = 0; i < len; i += 6, j += 4) {
indices[i + 0] = (short)(j + 0);
indices[i + 1] = (short)(j + 1);
indices[i + 2] = (short)(j + 2);
indices[i + 3] = (short)(j + 2);
indices[i + 4] = (short)(j + 3);
indices[i + 5] = (short)(j + 0);
}
vertices.setIndices(indices, 0, indices.length);
}
public void beginBatch(Texture texture) {
texture.bind();
numSprites = 0;
bufferIndex = 0;
}
public void endBatch() {
vertices.setVertices(verticesBuffer, 0, bufferIndex);
vertices.bind();
vertices.draw(GL10.GL_TRIANGLES, 0, numSprites * 6);
vertices.unbind();
}
public void drawSprite(float x, float y, float width, float height, TextureRegion region) {
float halfWidth = width / 2;
float halfHeight = height / 2;
float x1 = x - halfWidth;
float y1 = y - halfHeight;
float x2 = x + halfWidth;
float y2 = y + halfHeight;
verticesBuffer[bufferIndex++] = x1;
verticesBuffer[bufferIndex++] = y1;
verticesBuffer[bufferIndex++] = region.u1;
verticesBuffer[bufferIndex++] = region.v2;
verticesBuffer[bufferIndex++] = x2;
verticesBuffer[bufferIndex++] = y1;
verticesBuffer[bufferIndex++] = region.u2;
verticesBuffer[bufferIndex++] = region.v2;
verticesBuffer[bufferIndex++] = x2;
verticesBuffer[bufferIndex++] = y2;
verticesBuffer[bufferIndex++] = region.u2;
verticesBuffer[bufferIndex++] = region.v1;
verticesBuffer[bufferIndex++] = x1;
verticesBuffer[bufferIndex++] = y2;
verticesBuffer[bufferIndex++] = region.u1;
verticesBuffer[bufferIndex++] = region.v1;
numSprites++;
}
public void drawSprite(float x, float y, float width, float height, float angle, TextureRegion region) {
float halfWidth = width / 2;
float halfHeight = height / 2;
float rad = angle * Vector2.TO_RADIANS;
float cos = FloatMath.cos(rad);
float sin = FloatMath.sin(rad);
float x1 = -halfWidth * cos - (-halfHeight) * sin;
float y1 = -halfWidth * sin + (-halfHeight) * cos;
float x2 = halfWidth * cos - (-halfHeight) * sin;
float y2 = halfWidth * sin + (-halfHeight) * cos;
float x3 = halfWidth * cos - halfHeight * sin;
float y3 = halfWidth * sin + halfHeight * cos;
float x4 = -halfWidth * cos - halfHeight * sin;
float y4 = -halfWidth * sin + halfHeight * cos;
x1 += x;
y1 += y;
x2 += x;
y2 += y;
x3 += x;
y3 += y;
x4 += x;
y4 += y;
verticesBuffer[bufferIndex++] = x1;
verticesBuffer[bufferIndex++] = y1;
verticesBuffer[bufferIndex++] = region.u1;
verticesBuffer[bufferIndex++] = region.v2;
verticesBuffer[bufferIndex++] = x2;
verticesBuffer[bufferIndex++] = y2;
verticesBuffer[bufferIndex++] = region.u2;
verticesBuffer[bufferIndex++] = region.v2;
verticesBuffer[bufferIndex++] = x3;
verticesBuffer[bufferIndex++] = y3;
verticesBuffer[bufferIndex++] = region.u2;
verticesBuffer[bufferIndex++] = region.v1;
verticesBuffer[bufferIndex++] = x4;
verticesBuffer[bufferIndex++] = y4;
verticesBuffer[bufferIndex++] = region.u1;
verticesBuffer[bufferIndex++] = region.v1;
numSprites++;
}
}
| ncuongce/SleepyTrout | src/com/androidgames/framework/gl/SpriteBatcher.java | Java | gpl-2.0 | 4,487 |
/*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui.Adapters;
import android.content.Context;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.LongSparseArray;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.SQLite.SQLiteCursor;
import org.telegram.SQLite.SQLitePreparedStatement;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ChatObject;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.MediaDataController;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.Utilities;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Cells.DialogCell;
import org.telegram.ui.Cells.GraySectionCell;
import org.telegram.ui.Cells.HashtagSearchCell;
import org.telegram.ui.Cells.HintDialogCell;
import org.telegram.ui.Cells.ProfileSearchCell;
import org.telegram.ui.Cells.TextCell;
import org.telegram.ui.Components.FlickerLoadingView;
import org.telegram.ui.Components.ForegroundColorSpanThemable;
import org.telegram.ui.Components.RecyclerListView;
import org.telegram.ui.FilteredSearchView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
private Context mContext;
private Runnable searchRunnable;
private Runnable searchRunnable2;
private ArrayList<TLObject> searchResult = new ArrayList<>();
private ArrayList<CharSequence> searchResultNames = new ArrayList<>();
private ArrayList<MessageObject> searchResultMessages = new ArrayList<>();
private ArrayList<String> searchResultHashtags = new ArrayList<>();
private String lastSearchText;
private boolean searchWas;
private int reqId = 0;
private int lastReqId;
private DialogsSearchAdapterDelegate delegate;
private int needMessagesSearch;
private boolean messagesSearchEndReached;
private String lastMessagesSearchString;
private String currentMessagesQuery;
private int nextSearchRate;
private int lastSearchId;
private int lastGlobalSearchId;
private int lastLocalSearchId;
private int lastMessagesSearchId;
private int dialogsType;
private SearchAdapterHelper searchAdapterHelper;
private RecyclerListView innerListView;
private int selfUserId;
private int currentAccount = UserConfig.selectedAccount;
private ArrayList<RecentSearchObject> recentSearchObjects = new ArrayList<>();
private LongSparseArray<RecentSearchObject> recentSearchObjectsById = new LongSparseArray<>();
private ArrayList<TLRPC.User> localTipUsers = new ArrayList<>();
private ArrayList<FiltersView.DateData> localTipDates = new ArrayList<>();
private FilteredSearchView.Delegate filtersDelegate;
private int folderId;
public boolean isSearching() {
return waitingResponseCount > 0;
}
public static class DialogSearchResult {
public TLObject object;
public int date;
public CharSequence name;
}
protected static class RecentSearchObject {
TLObject object;
int date;
long did;
}
public interface DialogsSearchAdapterDelegate {
void searchStateChanged(boolean searching, boolean animated);
void didPressedOnSubDialog(long did);
void needRemoveHint(int did);
void needClearList();
void runResultsEnterAnimation();
}
private class CategoryAdapterRecycler extends RecyclerListView.SelectionAdapter {
public void setIndex(int value) {
notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = new HintDialogCell(mContext);
view.setLayoutParams(new RecyclerView.LayoutParams(AndroidUtilities.dp(80), AndroidUtilities.dp(86)));
return new RecyclerListView.Holder(view);
}
@Override
public boolean isEnabled(RecyclerView.ViewHolder holder) {
return true;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
HintDialogCell cell = (HintDialogCell) holder.itemView;
TLRPC.TL_topPeer peer = MediaDataController.getInstance(currentAccount).hints.get(position);
TLRPC.Dialog dialog = new TLRPC.TL_dialog();
TLRPC.Chat chat = null;
TLRPC.User user = null;
int did = 0;
if (peer.peer.user_id != 0) {
did = peer.peer.user_id;
user = MessagesController.getInstance(currentAccount).getUser(peer.peer.user_id);
} else if (peer.peer.channel_id != 0) {
did = -peer.peer.channel_id;
chat = MessagesController.getInstance(currentAccount).getChat(peer.peer.channel_id);
} else if (peer.peer.chat_id != 0) {
did = -peer.peer.chat_id;
chat = MessagesController.getInstance(currentAccount).getChat(peer.peer.chat_id);
}
cell.setTag(did);
String name = "";
if (user != null) {
name = UserObject.getFirstName(user);
} else if (chat != null) {
name = chat.title;
}
cell.setDialog(did, true, name);
}
@Override
public int getItemCount() {
return MediaDataController.getInstance(currentAccount).hints.size();
}
}
public DialogsSearchAdapter(Context context, int messagesSearch, int type, int folderId) {
this.folderId = folderId;
searchAdapterHelper = new SearchAdapterHelper(false);
searchAdapterHelper.setDelegate(new SearchAdapterHelper.SearchAdapterHelperDelegate() {
@Override
public void onDataSetChanged(int searchId) {
waitingResponseCount--;
lastGlobalSearchId = searchId;
if (lastLocalSearchId != searchId) {
searchResult.clear();
}
if (lastMessagesSearchId != searchId) {
searchResultMessages.clear();
}
searchWas = true;
if (delegate != null) {
delegate.searchStateChanged(waitingResponseCount > 0, true);
}
notifyDataSetChanged();
if (delegate != null) {
delegate.runResultsEnterAnimation();
}
}
@Override
public void onSetHashtags(ArrayList<SearchAdapterHelper.HashtagObject> arrayList, HashMap<String, SearchAdapterHelper.HashtagObject> hashMap) {
for (int a = 0; a < arrayList.size(); a++) {
searchResultHashtags.add(arrayList.get(a).hashtag);
}
if (delegate != null) {
delegate.searchStateChanged(waitingResponseCount > 0, false);
}
notifyDataSetChanged();
}
@Override
public boolean canApplySearchResults(int searchId) {
return searchId == lastSearchId;
}
});
mContext = context;
needMessagesSearch = messagesSearch;
dialogsType = type;
selfUserId = UserConfig.getInstance(currentAccount).getClientUserId();
loadRecentSearch();
MediaDataController.getInstance(currentAccount).loadHints(true);
}
public RecyclerListView getInnerListView() {
return innerListView;
}
public void setDelegate(DialogsSearchAdapterDelegate delegate) {
this.delegate = delegate;
}
public boolean isMessagesSearchEndReached() {
return messagesSearchEndReached;
}
public void loadMoreSearchMessages() {
if (reqId != 0) {
return;
}
searchMessagesInternal(lastMessagesSearchString, lastMessagesSearchId);
}
public String getLastSearchString() {
return lastMessagesSearchString;
}
private void searchMessagesInternal(final String query, int searchId) {
if (needMessagesSearch == 0 || TextUtils.isEmpty(lastMessagesSearchString) && TextUtils.isEmpty(query)) {
return;
}
if (reqId != 0) {
ConnectionsManager.getInstance(currentAccount).cancelRequest(reqId, true);
reqId = 0;
}
if (TextUtils.isEmpty(query)) {
searchResultMessages.clear();
lastReqId = 0;
lastMessagesSearchString = null;
searchWas = false;
notifyDataSetChanged();
return;
}
final TLRPC.TL_messages_searchGlobal req = new TLRPC.TL_messages_searchGlobal();
req.limit = 20;
req.q = query;
req.filter = new TLRPC.TL_inputMessagesFilterEmpty();
if (query.equals(lastMessagesSearchString) && !searchResultMessages.isEmpty()) {
MessageObject lastMessage = searchResultMessages.get(searchResultMessages.size() - 1);
req.offset_id = lastMessage.getId();
req.offset_rate = nextSearchRate;
int id;
if (lastMessage.messageOwner.peer_id.channel_id != 0) {
id = -lastMessage.messageOwner.peer_id.channel_id;
} else if (lastMessage.messageOwner.peer_id.chat_id != 0) {
id = -lastMessage.messageOwner.peer_id.chat_id;
} else {
id = lastMessage.messageOwner.peer_id.user_id;
}
req.offset_peer = MessagesController.getInstance(currentAccount).getInputPeer(id);
} else {
req.offset_rate = 0;
req.offset_id = 0;
req.offset_peer = new TLRPC.TL_inputPeerEmpty();
}
lastMessagesSearchString = query;
final int currentReqId = ++lastReqId;
reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> {
final ArrayList<MessageObject> messageObjects = new ArrayList<>();
if (error == null) {
TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
SparseArray<TLRPC.Chat> chatsMap = new SparseArray<>();
SparseArray<TLRPC.User> usersMap = new SparseArray<>();
for (int a = 0; a < res.chats.size(); a++) {
TLRPC.Chat chat = res.chats.get(a);
chatsMap.put(chat.id, chat);
}
for (int a = 0; a < res.users.size(); a++) {
TLRPC.User user = res.users.get(a);
usersMap.put(user.id, user);
}
for (int a = 0; a < res.messages.size(); a++) {
TLRPC.Message message = res.messages.get(a);
MessageObject messageObject = new MessageObject(currentAccount, message, usersMap, chatsMap, false, true);
messageObjects.add(messageObject);
messageObject.setQuery(query);
}
}
AndroidUtilities.runOnUIThread(() -> {
if (currentReqId == lastReqId && (searchId <= 0 || searchId == lastSearchId)) {
waitingResponseCount--;
if (error == null) {
currentMessagesQuery = query;
TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
MessagesStorage.getInstance(currentAccount).putUsersAndChats(res.users, res.chats, true, true);
MessagesController.getInstance(currentAccount).putUsers(res.users, false);
MessagesController.getInstance(currentAccount).putChats(res.chats, false);
if (req.offset_id == 0) {
searchResultMessages.clear();
}
nextSearchRate = res.next_rate;
for (int a = 0; a < res.messages.size(); a++) {
TLRPC.Message message = res.messages.get(a);
long did = MessageObject.getDialogId(message);
Integer maxId = MessagesController.getInstance(currentAccount).deletedHistory.get(did);
if (maxId != null && message.id <= maxId) {
continue;
}
searchResultMessages.add(messageObjects.get(a));
long dialog_id = MessageObject.getDialogId(message);
ConcurrentHashMap<Long, Integer> read_max = message.out ? MessagesController.getInstance(currentAccount).dialogs_read_outbox_max : MessagesController.getInstance(currentAccount).dialogs_read_inbox_max;
Integer value = read_max.get(dialog_id);
if (value == null) {
value = MessagesStorage.getInstance(currentAccount).getDialogReadMax(message.out, dialog_id);
read_max.put(dialog_id, value);
}
message.unread = value < message.id;
}
searchWas = true;
messagesSearchEndReached = res.messages.size() != 20;
if (searchId > 0) {
lastMessagesSearchId = searchId;
if (lastLocalSearchId != searchId) {
searchResult.clear();
}
if (lastGlobalSearchId != searchId) {
searchAdapterHelper.clear();
}
}
notifyDataSetChanged();
if (delegate != null) {
delegate.searchStateChanged(waitingResponseCount > 0, true);
delegate.runResultsEnterAnimation();
}
}
}
reqId = 0;
});
}, ConnectionsManager.RequestFlagFailOnServerErrors);
}
public boolean hasRecentSearch() {
return dialogsType != 2 && dialogsType != 4 && dialogsType != 5 && dialogsType != 6 && (!recentSearchObjects.isEmpty() || !MediaDataController.getInstance(currentAccount).hints.isEmpty());
}
public boolean isRecentSearchDisplayed() {
return needMessagesSearch != 2 && !searchWas && (!recentSearchObjects.isEmpty() || !MediaDataController.getInstance(currentAccount).hints.isEmpty()) && dialogsType != 2 && dialogsType != 4 && dialogsType != 5 && dialogsType != 6;
}
public void loadRecentSearch() {
MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> {
try {
SQLiteCursor cursor = MessagesStorage.getInstance(currentAccount).getDatabase().queryFinalized("SELECT did, date FROM search_recent WHERE 1");
ArrayList<Integer> usersToLoad = new ArrayList<>();
ArrayList<Integer> chatsToLoad = new ArrayList<>();
ArrayList<Integer> encryptedToLoad = new ArrayList<>();
ArrayList<TLRPC.User> encUsers = new ArrayList<>();
final ArrayList<RecentSearchObject> arrayList = new ArrayList<>();
final LongSparseArray<RecentSearchObject> hashMap = new LongSparseArray<>();
while (cursor.next()) {
long did = cursor.longValue(0);
boolean add = false;
int lower_id = (int) did;
int high_id = (int) (did >> 32);
if (lower_id != 0) {
if (lower_id > 0) {
if (dialogsType != 2 && !usersToLoad.contains(lower_id)) {
usersToLoad.add(lower_id);
add = true;
}
} else {
if (!chatsToLoad.contains(-lower_id)) {
chatsToLoad.add(-lower_id);
add = true;
}
}
} else if (dialogsType == 0 || dialogsType == 3) {
if (!encryptedToLoad.contains(high_id)) {
encryptedToLoad.add(high_id);
add = true;
}
}
if (add) {
RecentSearchObject recentSearchObject = new RecentSearchObject();
recentSearchObject.did = did;
recentSearchObject.date = cursor.intValue(1);
arrayList.add(recentSearchObject);
hashMap.put(recentSearchObject.did, recentSearchObject);
}
}
cursor.dispose();
ArrayList<TLRPC.User> users = new ArrayList<>();
if (!encryptedToLoad.isEmpty()) {
ArrayList<TLRPC.EncryptedChat> encryptedChats = new ArrayList<>();
MessagesStorage.getInstance(currentAccount).getEncryptedChatsInternal(TextUtils.join(",", encryptedToLoad), encryptedChats, usersToLoad);
for (int a = 0; a < encryptedChats.size(); a++) {
hashMap.get((long) encryptedChats.get(a).id << 32).object = encryptedChats.get(a);
}
}
if (!chatsToLoad.isEmpty()) {
ArrayList<TLRPC.Chat> chats = new ArrayList<>();
MessagesStorage.getInstance(currentAccount).getChatsInternal(TextUtils.join(",", chatsToLoad), chats);
for (int a = 0; a < chats.size(); a++) {
TLRPC.Chat chat = chats.get(a);
long did = -chat.id;
if (chat.migrated_to != null) {
RecentSearchObject recentSearchObject = hashMap.get(did);
hashMap.remove(did);
if (recentSearchObject != null) {
arrayList.remove(recentSearchObject);
}
} else {
hashMap.get(did).object = chat;
}
}
}
if (!usersToLoad.isEmpty()) {
MessagesStorage.getInstance(currentAccount).getUsersInternal(TextUtils.join(",", usersToLoad), users);
for (int a = 0; a < users.size(); a++) {
TLRPC.User user = users.get(a);
RecentSearchObject recentSearchObject = hashMap.get(user.id);
if (recentSearchObject != null) {
recentSearchObject.object = user;
}
}
}
Collections.sort(arrayList, (lhs, rhs) -> {
if (lhs.date < rhs.date) {
return 1;
} else if (lhs.date > rhs.date) {
return -1;
} else {
return 0;
}
});
AndroidUtilities.runOnUIThread(() -> setRecentSearch(arrayList, hashMap));
} catch (Exception e) {
FileLog.e(e);
}
});
}
public void putRecentSearch(final long did, TLObject object) {
RecentSearchObject recentSearchObject = recentSearchObjectsById.get(did);
if (recentSearchObject == null) {
recentSearchObject = new RecentSearchObject();
recentSearchObjectsById.put(did, recentSearchObject);
} else {
recentSearchObjects.remove(recentSearchObject);
}
recentSearchObjects.add(0, recentSearchObject);
recentSearchObject.did = did;
recentSearchObject.object = object;
recentSearchObject.date = (int) (System.currentTimeMillis() / 1000);
notifyDataSetChanged();
MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> {
try {
SQLitePreparedStatement state = MessagesStorage.getInstance(currentAccount).getDatabase().executeFast("REPLACE INTO search_recent VALUES(?, ?)");
state.requery();
state.bindLong(1, did);
state.bindInteger(2, (int) (System.currentTimeMillis() / 1000));
state.step();
state.dispose();
} catch (Exception e) {
FileLog.e(e);
}
});
}
public void clearRecentSearch() {
recentSearchObjectsById = new LongSparseArray<>();
recentSearchObjects = new ArrayList<>();
notifyDataSetChanged();
MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> {
try {
MessagesStorage.getInstance(currentAccount).getDatabase().executeFast("DELETE FROM search_recent WHERE 1").stepThis().dispose();
} catch (Exception e) {
FileLog.e(e);
}
});
}
public void removeRecentSearch(long did) {
RecentSearchObject object = recentSearchObjectsById.get(did);
if (object == null) {
return;
}
recentSearchObjectsById.remove(did);
recentSearchObjects.remove(object);
notifyDataSetChanged();
MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> {
try {
MessagesStorage.getInstance(currentAccount).getDatabase().executeFast("DELETE FROM search_recent WHERE did = " + did).stepThis().dispose();
} catch (Exception e) {
FileLog.e(e);
}
});
}
public void addHashtagsFromMessage(CharSequence message) {
searchAdapterHelper.addHashtagsFromMessage(message);
}
private void setRecentSearch(ArrayList<RecentSearchObject> arrayList, LongSparseArray<RecentSearchObject> hashMap) {
recentSearchObjects = arrayList;
recentSearchObjectsById = hashMap;
for (int a = 0; a < recentSearchObjects.size(); a++) {
RecentSearchObject recentSearchObject = recentSearchObjects.get(a);
if (recentSearchObject.object instanceof TLRPC.User) {
MessagesController.getInstance(currentAccount).putUser((TLRPC.User) recentSearchObject.object, true);
} else if (recentSearchObject.object instanceof TLRPC.Chat) {
MessagesController.getInstance(currentAccount).putChat((TLRPC.Chat) recentSearchObject.object, true);
} else if (recentSearchObject.object instanceof TLRPC.EncryptedChat) {
MessagesController.getInstance(currentAccount).putEncryptedChat((TLRPC.EncryptedChat) recentSearchObject.object, true);
}
}
notifyDataSetChanged();
}
private void searchDialogsInternal(final String query, final int searchId) {
if (needMessagesSearch == 2) {
return;
}
String q = query.trim().toLowerCase();
if (q.length() == 0) {
lastSearchId = 0;
updateSearchResults(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), lastSearchId);
return;
}
MessagesStorage.getInstance(currentAccount).getStorageQueue().postRunnable(() -> {
ArrayList<TLObject> resultArray = new ArrayList<>();
ArrayList<CharSequence> resultArrayNames = new ArrayList<>();
ArrayList<TLRPC.User> encUsers = new ArrayList<>();
MessagesStorage.getInstance(currentAccount).localSearch(dialogsType, q, resultArray, resultArrayNames, encUsers, -1);
updateSearchResults(resultArray, resultArrayNames, encUsers, searchId);
FiltersView.fillTipDates(q, localTipDates);
AndroidUtilities.runOnUIThread(() -> {
if (filtersDelegate != null) {
filtersDelegate.updateFiltersView(false, null, localTipDates);
}
});
});
}
private void updateSearchResults(final ArrayList<TLObject> result, final ArrayList<CharSequence> names, final ArrayList<TLRPC.User> encUsers, final int searchId) {
AndroidUtilities.runOnUIThread(() -> {
waitingResponseCount--;
if (searchId != lastSearchId) {
return;
}
lastLocalSearchId = searchId;
if (lastGlobalSearchId != searchId) {
searchAdapterHelper.clear();
}
if (lastMessagesSearchId != searchId) {
searchResultMessages.clear();
}
searchWas = true;
for (int a = 0; a < result.size(); a++) {
TLObject obj = result.get(a);
if (obj instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) obj;
MessagesController.getInstance(currentAccount).putUser(user, true);
} else if (obj instanceof TLRPC.Chat) {
TLRPC.Chat chat = (TLRPC.Chat) obj;
MessagesController.getInstance(currentAccount).putChat(chat, true);
} else if (obj instanceof TLRPC.EncryptedChat) {
TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) obj;
MessagesController.getInstance(currentAccount).putEncryptedChat(chat, true);
}
}
MessagesController.getInstance(currentAccount).putUsers(encUsers, true);
searchResult = result;
searchResultNames = names;
searchAdapterHelper.mergeResults(searchResult);
notifyDataSetChanged();
if (delegate != null) {
delegate.searchStateChanged(waitingResponseCount > 0, true);
delegate.runResultsEnterAnimation();
}
});
}
public boolean isHashtagSearch() {
return !searchResultHashtags.isEmpty();
}
public void clearRecentHashtags() {
searchAdapterHelper.clearRecentHashtags();
searchResultHashtags.clear();
notifyDataSetChanged();
}
int waitingResponseCount;
public void searchDialogs(String text) {
if (text != null && text.equals(lastSearchText)) {
return;
}
lastSearchText = text;
if (searchRunnable != null) {
Utilities.searchQueue.cancelRunnable(searchRunnable);
searchRunnable = null;
}
if (searchRunnable2 != null) {
AndroidUtilities.cancelRunOnUIThread(searchRunnable2);
searchRunnable2 = null;
}
String query;
if (text != null) {
query = text.trim();
} else {
query = null;
}
if (TextUtils.isEmpty(query)) {
searchAdapterHelper.unloadRecentHashtags();
searchResult.clear();
searchResultNames.clear();
searchResultHashtags.clear();
searchAdapterHelper.mergeResults(null);
searchAdapterHelper.queryServerSearch(null, true, true, true, true, dialogsType == 2, 0, dialogsType == 0, 0, 0);
searchWas = false;
lastSearchId = 0;
waitingResponseCount = 0;
if (delegate != null) {
delegate.searchStateChanged(false, true);
}
searchMessagesInternal(null, 0);
notifyDataSetChanged();
localTipDates.clear();
if (filtersDelegate != null) {
filtersDelegate.updateFiltersView(false, null, localTipDates);
}
} else {
if (needMessagesSearch != 2 && (query.startsWith("#") && query.length() == 1)) {
messagesSearchEndReached = true;
if (searchAdapterHelper.loadRecentHashtags()) {
searchResultMessages.clear();
searchResultHashtags.clear();
ArrayList<SearchAdapterHelper.HashtagObject> hashtags = searchAdapterHelper.getHashtags();
for (int a = 0; a < hashtags.size(); a++) {
searchResultHashtags.add(hashtags.get(a).hashtag);
}
waitingResponseCount = 0;
notifyDataSetChanged();
if (delegate != null) {
delegate.searchStateChanged(false, false);
}
}
} else {
searchResultHashtags.clear();
}
final int searchId = ++lastSearchId;
waitingResponseCount = 3;
notifyDataSetChanged();
if (delegate != null) {
delegate.searchStateChanged(true, false);
}
Utilities.searchQueue.postRunnable(searchRunnable = () -> {
searchRunnable = null;
searchDialogsInternal(query, searchId);
AndroidUtilities.runOnUIThread(searchRunnable2 = () -> {
searchRunnable2 = null;
if (searchId != lastSearchId) {
return;
}
if (needMessagesSearch != 2) {
searchAdapterHelper.queryServerSearch(query, true, dialogsType != 4, true, dialogsType != 4, dialogsType == 2, 0, dialogsType == 0, 0, searchId);
} else {
waitingResponseCount -= 2;
}
if (needMessagesSearch == 0) {
waitingResponseCount--;
} else {
searchMessagesInternal(text, searchId);
}
});
}, 300);
}
}
@Override
public int getItemCount() {
if (waitingResponseCount == 3) {
return 0;
}
if (isRecentSearchDisplayed()) {
return (!recentSearchObjects.isEmpty() ? recentSearchObjects.size() + 1 : 0) + (!MediaDataController.getInstance(currentAccount).hints.isEmpty() ? 1 : 0);
}
int count = 0;
if (!searchResultHashtags.isEmpty()) {
count += searchResultHashtags.size() + 1;
return count;
}
count += searchResult.size();
int localServerCount = searchAdapterHelper.getLocalServerSearch().size();
int globalCount = searchAdapterHelper.getGlobalSearch().size();
int phoneCount = searchAdapterHelper.getPhoneSearch().size();
int messagesCount = searchResultMessages.size();
count += localServerCount;
if (globalCount != 0) {
count += globalCount + 1;
}
if (phoneCount != 0) {
count += phoneCount;
}
if (messagesCount != 0) {
count += messagesCount + 1 + (messagesSearchEndReached ? 0 : 1);
}
return count;
}
public Object getItem(int i) {
if (isRecentSearchDisplayed()) {
int offset = (!MediaDataController.getInstance(currentAccount).hints.isEmpty() ? 1 : 0);
if (i > offset && i - 1 - offset < recentSearchObjects.size()) {
TLObject object = recentSearchObjects.get(i - 1 - offset).object;
if (object instanceof TLRPC.User) {
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(((TLRPC.User) object).id);
if (user != null) {
object = user;
}
} else if (object instanceof TLRPC.Chat) {
TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(((TLRPC.Chat) object).id);
if (chat != null) {
object = chat;
}
}
return object;
} else {
return null;
}
}
if (!searchResultHashtags.isEmpty()) {
if (i > 0) {
return searchResultHashtags.get(i - 1);
} else {
return null;
}
}
ArrayList<TLObject> globalSearch = searchAdapterHelper.getGlobalSearch();
ArrayList<TLObject> localServerSearch = searchAdapterHelper.getLocalServerSearch();
ArrayList<Object> phoneSearch = searchAdapterHelper.getPhoneSearch();
int localCount = searchResult.size();
int localServerCount = localServerSearch.size();
int phoneCount = phoneSearch.size();
int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1;
int messagesCount = searchResultMessages.isEmpty() ? 0 : searchResultMessages.size() + 1;
if (i >= 0 && i < localCount) {
return searchResult.get(i);
} else {
i -= localCount;
if (i >= 0 && i < localServerCount) {
return localServerSearch.get(i);
} else {
i -= localServerCount;
if (i >= 0 && i < phoneCount) {
return phoneSearch.get(i);
} else {
i -= phoneCount;
if (i > 0 && i < globalCount) {
return globalSearch.get(i - 1);
} else {
i -= globalCount;
if (i > 0 && i < messagesCount) {
return searchResultMessages.get(i - 1);
}
}
}
}
}
return null;
}
public boolean isGlobalSearch(int i) {
if (isRecentSearchDisplayed()) {
return false;
}
if (!searchResultHashtags.isEmpty()) {
return false;
}
ArrayList<TLObject> globalSearch = searchAdapterHelper.getGlobalSearch();
ArrayList<TLObject> localServerSearch = searchAdapterHelper.getLocalServerSearch();
int localCount = searchResult.size();
int localServerCount = localServerSearch.size();
int phoneCount = searchAdapterHelper.getPhoneSearch().size();
int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1;
int messagesCount = searchResultMessages.isEmpty() ? 0 : searchResultMessages.size() + 1;
if (i >= 0 && i < localCount) {
return false;
} else {
i -= localCount;
if (i >= 0 && i < localServerCount) {
return false;
} else {
i -= localServerCount;
if (i > 0 && i < phoneCount) {
return false;
} else {
i -= phoneCount;
if (i > 0 && i < globalCount) {
return true;
} else {
i -= globalCount;
if (i > 0 && i < messagesCount) {
return false;
}
}
}
}
}
return false;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public boolean isEnabled(RecyclerView.ViewHolder holder) {
int type = holder.getItemViewType();
return type != 1 && type != 3;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
switch (viewType) {
case 0:
view = new ProfileSearchCell(mContext);
break;
case 1:
view = new GraySectionCell(mContext);
break;
case 2:
view = new DialogCell(mContext, false, true);
break;
case 3:
FlickerLoadingView flickerLoadingView = new FlickerLoadingView(mContext);
flickerLoadingView.setViewType(FlickerLoadingView.DIALOG_TYPE);
flickerLoadingView.setIsSingleCell(true);
view = flickerLoadingView;
break;
case 4:
view = new HashtagSearchCell(mContext);
break;
case 5:
RecyclerListView horizontalListView = new RecyclerListView(mContext) {
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
if (getParent() != null && getParent().getParent() != null) {
getParent().getParent().requestDisallowInterceptTouchEvent(canScrollHorizontally(-1) || canScrollHorizontally(1));
}
return super.onInterceptTouchEvent(e);
}
};
horizontalListView.setTag(9);
horizontalListView.setItemAnimator(null);
horizontalListView.setLayoutAnimation(null);
LinearLayoutManager layoutManager = new LinearLayoutManager(mContext) {
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
};
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
horizontalListView.setLayoutManager(layoutManager);
//horizontalListView.setDisallowInterceptTouchEvents(true);
horizontalListView.setAdapter(new CategoryAdapterRecycler());
horizontalListView.setOnItemClickListener((view1, position) -> {
if (delegate != null) {
delegate.didPressedOnSubDialog((Integer) view1.getTag());
}
});
horizontalListView.setOnItemLongClickListener((view12, position) -> {
if (delegate != null) {
delegate.needRemoveHint((Integer) view12.getTag());
}
return true;
});
view = horizontalListView;
innerListView = horizontalListView;
break;
case 6:
view = new TextCell(mContext, 16, false);
break;
}
if (viewType == 5) {
view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, AndroidUtilities.dp(86)));
} else {
view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
}
return new RecyclerListView.Holder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0: {
ProfileSearchCell cell = (ProfileSearchCell) holder.itemView;
TLRPC.User user = null;
TLRPC.Chat chat = null;
TLRPC.EncryptedChat encryptedChat = null;
CharSequence username = null;
CharSequence name = null;
boolean isRecent = false;
String un = null;
Object obj = getItem(position);
if (obj instanceof TLRPC.User) {
user = (TLRPC.User) obj;
un = user.username;
} else if (obj instanceof TLRPC.Chat) {
chat = MessagesController.getInstance(currentAccount).getChat(((TLRPC.Chat) obj).id);
if (chat == null) {
chat = (TLRPC.Chat) obj;
}
un = chat.username;
} else if (obj instanceof TLRPC.EncryptedChat) {
encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(((TLRPC.EncryptedChat) obj).id);
user = MessagesController.getInstance(currentAccount).getUser(encryptedChat.user_id);
}
if (isRecentSearchDisplayed()) {
isRecent = true;
cell.useSeparator = position != getItemCount() - 1;
} else {
ArrayList<TLObject> globalSearch = searchAdapterHelper.getGlobalSearch();
ArrayList<Object> phoneSearch = searchAdapterHelper.getPhoneSearch();
int localCount = searchResult.size();
int localServerCount = searchAdapterHelper.getLocalServerSearch().size();
int phoneCount = phoneSearch.size();
int phoneCount2 = phoneCount;
if (phoneCount > 0 && phoneSearch.get(phoneCount - 1) instanceof String) {
phoneCount2 -= 2;
}
int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1;
cell.useSeparator = (position != getItemCount() - 1 && position != localCount + phoneCount2 + localServerCount - 1 && position != localCount + globalCount + phoneCount + localServerCount - 1);
if (position < searchResult.size()) {
name = searchResultNames.get(position);
if (name != null && user != null && user.username != null && user.username.length() > 0) {
if (name.toString().startsWith("@" + user.username)) {
username = name;
name = null;
}
}
} else {
String foundUserName = searchAdapterHelper.getLastFoundUsername();
if (!TextUtils.isEmpty(foundUserName)) {
String nameSearch = null;
String nameSearchLower = null;
int index;
if (user != null) {
nameSearch = ContactsController.formatName(user.first_name, user.last_name);
} else if (chat != null) {
nameSearch = chat.title;
}
if (nameSearch != null && (index = AndroidUtilities.indexOfIgnoreCase(nameSearch, foundUserName)) != -1) {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(nameSearch);
spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4), index, index + foundUserName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
name = spannableStringBuilder;
} else if (un != null) {
if (foundUserName.startsWith("@")) {
foundUserName = foundUserName.substring(1);
}
try {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
spannableStringBuilder.append("@");
spannableStringBuilder.append(un);
if ((index = AndroidUtilities.indexOfIgnoreCase(un, foundUserName)) != -1) {
int len = foundUserName.length();
if (index == 0) {
len++;
} else {
index++;
}
spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4), index, index + len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
username = spannableStringBuilder;
} catch (Exception e) {
username = un;
FileLog.e(e);
}
}
}
}
}
boolean savedMessages = false;
if (user != null && user.id == selfUserId) {
name = LocaleController.getString("SavedMessages", R.string.SavedMessages);
username = null;
savedMessages = true;
}
if (chat != null && chat.participants_count != 0) {
String membersString;
if (ChatObject.isChannel(chat) && !chat.megagroup) {
membersString = LocaleController.formatPluralString("Subscribers", chat.participants_count);
} else {
membersString = LocaleController.formatPluralString("Members", chat.participants_count);
}
if (username instanceof SpannableStringBuilder) {
((SpannableStringBuilder) username).append(", ").append(membersString);
} else if (!TextUtils.isEmpty(username)) {
username = TextUtils.concat(username, ", ", membersString);
} else {
username = membersString;
}
}
cell.setData(user != null ? user : chat, encryptedChat, name, username, isRecent, savedMessages);
break;
}
case 1: {
GraySectionCell cell = (GraySectionCell) holder.itemView;
if (isRecentSearchDisplayed()) {
int offset = (!MediaDataController.getInstance(currentAccount).hints.isEmpty() ? 1 : 0);
if (position < offset) {
cell.setText(LocaleController.getString("ChatHints", R.string.ChatHints));
} else {
cell.setText(LocaleController.getString("Recent", R.string.Recent), LocaleController.getString("ClearButton", R.string.ClearButton), v -> {
if (delegate != null) {
delegate.needClearList();
}
});
}
} else if (!searchResultHashtags.isEmpty()) {
cell.setText(LocaleController.getString("Hashtags", R.string.Hashtags), LocaleController.getString("ClearButton", R.string.ClearButton), v -> {
if (delegate != null) {
delegate.needClearList();
}
});
} else {
ArrayList<TLObject> globalSearch = searchAdapterHelper.getGlobalSearch();
int localCount = searchResult.size();
int localServerCount = searchAdapterHelper.getLocalServerSearch().size();
int phoneCount = searchAdapterHelper.getPhoneSearch().size();
int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1;
int messagesCount = searchResultMessages.isEmpty() ? 0 : searchResultMessages.size() + 1;
position -= localCount + localServerCount;
if (position >= 0 && position < phoneCount) {
cell.setText(LocaleController.getString("PhoneNumberSearch", R.string.PhoneNumberSearch));
} else {
position -= phoneCount;
if (position >= 0 && position < globalCount) {
cell.setText(LocaleController.getString("GlobalSearch", R.string.GlobalSearch));
} else {
cell.setText(LocaleController.getString("SearchMessages", R.string.SearchMessages));
}
}
}
break;
}
case 2: {
DialogCell cell = (DialogCell) holder.itemView;
cell.useSeparator = (position != getItemCount() - 1);
MessageObject messageObject = (MessageObject) getItem(position);
cell.setDialog(messageObject.getDialogId(), messageObject, messageObject.messageOwner.date, false);
break;
}
case 4: {
HashtagSearchCell cell = (HashtagSearchCell) holder.itemView;
cell.setText(searchResultHashtags.get(position - 1));
cell.setNeedDivider(position != searchResultHashtags.size());
break;
}
case 5: {
RecyclerListView recyclerListView = (RecyclerListView) holder.itemView;
((CategoryAdapterRecycler) recyclerListView.getAdapter()).setIndex(position / 2);
break;
}
case 6: {
String str = (String) getItem(position);
TextCell cell = (TextCell) holder.itemView;
cell.setColors(null, Theme.key_windowBackgroundWhiteBlueText2);
cell.setText(LocaleController.formatString("AddContactByPhone", R.string.AddContactByPhone, PhoneFormat.getInstance().format("+" + str)), false);
break;
}
}
}
@Override
public int getItemViewType(int i) {
if (isRecentSearchDisplayed()) {
int offset = (!MediaDataController.getInstance(currentAccount).hints.isEmpty() ? 1 : 0);
if (i < offset) {
return 5;
}
if (i == offset) {
return 1;
}
return 0;
}
if (!searchResultHashtags.isEmpty()) {
return i == 0 ? 1 : 4;
}
ArrayList<TLObject> globalSearch = searchAdapterHelper.getGlobalSearch();
int localCount = searchResult.size();
int localServerCount = searchAdapterHelper.getLocalServerSearch().size();
int phoneCount = searchAdapterHelper.getPhoneSearch().size();
int globalCount = globalSearch.isEmpty() ? 0 : globalSearch.size() + 1;
int messagesCount = searchResultMessages.isEmpty() ? 0 : searchResultMessages.size() + 1;
if (i >= 0 && i < localCount) {
return 0;
} else {
i -= localCount;
if (i >= 0 && i < localServerCount) {
return 0;
} else {
i -= localServerCount;
if (i >= 0 && i < phoneCount) {
Object object = getItem(i);
if (object instanceof String) {
String str = (String) object;
if ("section".equals(str)) {
return 1;
} else {
return 6;
}
}
return 0;
} else {
i -= phoneCount;
if (i >= 0 && i < globalCount) {
if (i == 0) {
return 1;
} else {
return 0;
}
} else {
i -= globalCount;
if (i >= 0 && i < messagesCount) {
if (i == 0) {
return 1;
} else {
return 2;
}
}
}
}
}
}
return 3;
}
public void setFiltersDelegate(FilteredSearchView.Delegate filtersDelegate, boolean update) {
this.filtersDelegate = filtersDelegate;
if (filtersDelegate != null && update) {
filtersDelegate.updateFiltersView(false, null, localTipDates);
}
}
}
| tkpb/Telegram | TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java | Java | gpl-2.0 | 53,484 |
<?php
/**
* Comment function
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
if ( ! function_exists( 'wolf_comment' ) ) {
/**
* Basic Comments function
*
* @param object $comment
* @param array $args
* @param int $depth
* @return void
*/
function wolf_comment( $comment, $args, $depth ) {
$GLOBALS['comment'] = $comment;
switch ( $comment->comment_type ) :
case 'pingback' :
case 'trackback' :
// Display trackbacks differently than normal comments. ?>
<li id="comment-<?php comment_ID(); ?>" <?php comment_class(); ?>>
<p><?php _e( 'Pingback:', 'wolf' ); ?> <?php comment_author_link(); ?> <?php edit_comment_link( __( 'Edit', 'wolf' ), '<span class="ping-meta"><span class="edit-link">', '</span></span>' ); ?></p>
<?php
break;
default :
// Proceed with normal comments.
?>
<li id="li-comment-<?php comment_ID(); ?>">
<article id="comment-<?php comment_ID(); ?>" <?php comment_class(); ?>>
<div class="comment-author vcard">
<?php echo get_avatar( $comment, 80 ); ?>
</div><!-- .comment-author -->
<header class="comment-meta">
<cite class="fn"><?php comment_author_link(); ?></cite>
<?php printf( __( '%s ago', 'wolf' ), human_time_diff( get_comment_time( 'U' ), current_time( 'timestamp' ) ) ); ?>
<?php edit_comment_link( __( 'Edit', 'wolf' ), '<span class="edit-link">', '<span>' );
?>
</header><!-- .comment-meta -->
<div class="comment-content">
<?php if ( '0' == $comment->comment_approved ) { ?>
<p class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'wolf' ); ?></p>
<?php } ?>
<?php comment_text(); ?>
</div><!-- .comment-content -->
<div class="reply">
<?php comment_reply_link( array_merge( $args, array( 'reply_text' => __( 'Reply', 'wolf' ), 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
</div><!-- .reply -->
</article><!-- #comment-## -->
<?php
break;
endswitch; // End comment_type check.
}
} // ends check for wolf_comment() | estrategasdigitales/dictobas | wp-content/themes/decibel/includes/comments.php | PHP | gpl-2.0 | 2,161 |
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing author: Naveen Michaud-Agrawal (Johns Hopkins U)
K-space terms added by Stan Moore (BYU)
------------------------------------------------------------------------- */
#include <mpi.h>
#include <string.h>
#include "compute_group_group.h"
#include "atom.h"
#include "update.h"
#include "force.h"
#include "pair.h"
#include "neighbor.h"
#include "neigh_request.h"
#include "neigh_list.h"
#include "group.h"
#include "kspace.h"
#include "error.h"
#include <math.h>
#include "comm.h"
#include "domain.h"
#include "math_const.h"
using namespace LAMMPS_NS;
using namespace MathConst;
#define SMALL 0.00001
enum{OFF,INTER,INTRA};
/* ---------------------------------------------------------------------- */
ComputeGroupGroup::ComputeGroupGroup(LAMMPS *lmp, int narg, char **arg) :
Compute(lmp, narg, arg),
group2(NULL)
{
if (narg < 4) error->all(FLERR,"Illegal compute group/group command");
scalar_flag = vector_flag = 1;
size_vector = 3;
extscalar = 1;
extvector = 1;
int n = strlen(arg[3]) + 1;
group2 = new char[n];
strcpy(group2,arg[3]);
jgroup = group->find(group2);
if (jgroup == -1)
error->all(FLERR,"Compute group/group group ID does not exist");
jgroupbit = group->bitmask[jgroup];
pairflag = 1;
kspaceflag = 0;
boundaryflag = 1;
molflag = OFF;
int iarg = 4;
while (iarg < narg) {
if (strcmp(arg[iarg],"pair") == 0) {
if (iarg+2 > narg)
error->all(FLERR,"Illegal compute group/group command");
if (strcmp(arg[iarg+1],"yes") == 0) pairflag = 1;
else if (strcmp(arg[iarg+1],"no") == 0) pairflag = 0;
else error->all(FLERR,"Illegal compute group/group command");
iarg += 2;
} else if (strcmp(arg[iarg],"kspace") == 0) {
if (iarg+2 > narg)
error->all(FLERR,"Illegal compute group/group command");
if (strcmp(arg[iarg+1],"yes") == 0) kspaceflag = 1;
else if (strcmp(arg[iarg+1],"no") == 0) kspaceflag = 0;
else error->all(FLERR,"Illegal compute group/group command");
iarg += 2;
} else if (strcmp(arg[iarg],"boundary") == 0) {
if (iarg+2 > narg)
error->all(FLERR,"Illegal compute group/group command");
if (strcmp(arg[iarg+1],"yes") == 0) boundaryflag = 1;
else if (strcmp(arg[iarg+1],"no") == 0) boundaryflag = 0;
else error->all(FLERR,"Illegal compute group/group command");
iarg += 2;
} else if (strcmp(arg[iarg],"molecule") == 0) {
if (iarg+2 > narg)
error->all(FLERR,"Illegal compute group/group command");
if (strcmp(arg[iarg+1],"off") == 0) molflag = OFF;
else if (strcmp(arg[iarg+1],"inter") == 0) molflag = INTER;
else if (strcmp(arg[iarg+1],"intra") == 0) molflag = INTRA;
else error->all(FLERR,"Illegal compute group/group command");
if (molflag != OFF && atom->molecule_flag == 0)
error->all(FLERR,"Compute group/group molecule requires molecule IDs");
iarg += 2;
} else error->all(FLERR,"Illegal compute group/group command");
}
vector = new double[3];
}
/* ---------------------------------------------------------------------- */
ComputeGroupGroup::~ComputeGroupGroup()
{
delete [] group2;
delete [] vector;
}
/* ---------------------------------------------------------------------- */
void ComputeGroupGroup::init()
{
// if non-hybrid, then error if single_enable = 0
// if hybrid, let hybrid determine if sub-style sets single_enable = 0
if (pairflag && force->pair == NULL)
error->all(FLERR,"No pair style defined for compute group/group");
if (force->pair_match("hybrid",0) == NULL && force->pair->single_enable == 0)
error->all(FLERR,"Pair style does not support compute group/group");
// error if Kspace style does not compute group/group interactions
if (kspaceflag && force->kspace == NULL)
error->all(FLERR,"No Kspace style defined for compute group/group");
if (kspaceflag && force->kspace->group_group_enable == 0)
error->all(FLERR,"Kspace style does not support compute group/group");
if (pairflag) {
pair = force->pair;
cutsq = force->pair->cutsq;
} else pair = NULL;
if (kspaceflag) kspace = force->kspace;
else kspace = NULL;
// compute Kspace correction terms
if (kspaceflag) {
kspace_correction();
if (fabs(e_correction) > SMALL && comm->me == 0) {
char str[128];
sprintf(str,"Both groups in compute group/group have a net charge; "
"the Kspace boundary correction to energy will be non-zero");
error->warning(FLERR,str);
}
}
// recheck that group 2 has not been deleted
jgroup = group->find(group2);
if (jgroup == -1)
error->all(FLERR,"Compute group/group group ID does not exist");
jgroupbit = group->bitmask[jgroup];
// need an occasional half neighbor list
if (pairflag) {
int irequest = neighbor->request(this,instance_me);
neighbor->requests[irequest]->pair = 0;
neighbor->requests[irequest]->compute = 1;
neighbor->requests[irequest]->occasional = 1;
}
}
/* ---------------------------------------------------------------------- */
void ComputeGroupGroup::init_list(int id, NeighList *ptr)
{
list = ptr;
}
/* ---------------------------------------------------------------------- */
double ComputeGroupGroup::compute_scalar()
{
invoked_scalar = invoked_vector = update->ntimestep;
scalar = 0.0;
vector[0] = vector[1] = vector[2] = 0.0;
if (pairflag) pair_contribution();
if (kspaceflag) kspace_contribution();
return scalar;
}
/* ---------------------------------------------------------------------- */
void ComputeGroupGroup::compute_vector()
{
invoked_scalar = invoked_vector = update->ntimestep;
scalar = 0.0;
vector[0] = vector[1] = vector[2] = 0.0;
if (pairflag) pair_contribution();
if (kspaceflag) kspace_contribution();
}
/* ---------------------------------------------------------------------- */
void ComputeGroupGroup::pair_contribution()
{
int i,j,ii,jj,inum,jnum,itype,jtype;
double xtmp,ytmp,ztmp,delx,dely,delz;
double rsq,eng,fpair,factor_coul,factor_lj;
int *ilist,*jlist,*numneigh,**firstneigh;
double **x = atom->x;
tagint *molecule = atom->molecule;
int *type = atom->type;
int *mask = atom->mask;
int nlocal = atom->nlocal;
double *special_coul = force->special_coul;
double *special_lj = force->special_lj;
int newton_pair = force->newton_pair;
// invoke half neighbor list (will copy or build if necessary)
neighbor->build_one(list);
inum = list->inum;
ilist = list->ilist;
numneigh = list->numneigh;
firstneigh = list->firstneigh;
// loop over neighbors of my atoms
// skip if I,J are not in 2 groups
double one[4];
one[0] = one[1] = one[2] = one[3] = 0.0;
for (ii = 0; ii < inum; ii++) {
i = ilist[ii];
// skip if atom I is not in either group
if (!(mask[i] & groupbit || mask[i] & jgroupbit)) continue;
xtmp = x[i][0];
ytmp = x[i][1];
ztmp = x[i][2];
itype = type[i];
jlist = firstneigh[i];
jnum = numneigh[i];
for (jj = 0; jj < jnum; jj++) {
j = jlist[jj];
factor_lj = special_lj[sbmask(j)];
factor_coul = special_coul[sbmask(j)];
j &= NEIGHMASK;
// skip if atom J is not in either group
if (!(mask[j] & groupbit || mask[j] & jgroupbit)) continue;
// skip if atoms I,J are only in the same group
int ij_flag = 0;
int ji_flag = 0;
if (mask[i] & groupbit && mask[j] & jgroupbit) ij_flag = 1;
if (mask[j] & groupbit && mask[i] & jgroupbit) ji_flag = 1;
if (!ij_flag && !ji_flag) continue;
// skip if molecule IDs of atoms I,J do not satisfy molflag setting
if (molflag != OFF) {
if (molflag == INTER) {
if (molecule[i] == molecule[j]) continue;
} else {
if (molecule[i] != molecule[j]) continue;
}
}
delx = xtmp - x[j][0];
dely = ytmp - x[j][1];
delz = ztmp - x[j][2];
rsq = delx*delx + dely*dely + delz*delz;
jtype = type[j];
if (rsq < cutsq[itype][jtype]) {
eng = pair->single(i,j,itype,jtype,rsq,factor_coul,factor_lj,fpair);
// energy only computed once so tally full amount
// force tally is jgroup acting on igroup
if (newton_pair || j < nlocal) {
one[0] += eng;
if (ij_flag) {
one[1] += delx*fpair;
one[2] += dely*fpair;
one[3] += delz*fpair;
}
if (ji_flag) {
one[1] -= delx*fpair;
one[2] -= dely*fpair;
one[3] -= delz*fpair;
}
// energy computed twice so tally half amount
// only tally force if I own igroup atom
} else {
one[0] += 0.5*eng;
if (ij_flag) {
one[1] += delx*fpair;
one[2] += dely*fpair;
one[3] += delz*fpair;
}
}
}
}
}
double all[4];
MPI_Allreduce(one,all,4,MPI_DOUBLE,MPI_SUM,world);
scalar += all[0];
vector[0] += all[1]; vector[1] += all[2]; vector[2] += all[3];
}
/* ---------------------------------------------------------------------- */
void ComputeGroupGroup::kspace_contribution()
{
double *vector_kspace = force->kspace->f2group;
force->kspace->compute_group_group(groupbit,jgroupbit,0);
scalar += 2.0*force->kspace->e2group;
vector[0] += vector_kspace[0];
vector[1] += vector_kspace[1];
vector[2] += vector_kspace[2];
// subtract extra A <--> A Kspace interaction so energy matches
// real-space style of compute group-group
// add extra Kspace term to energy
force->kspace->compute_group_group(groupbit,jgroupbit,1);
scalar -= force->kspace->e2group;
// self energy correction term
scalar -= e_self;
// k=0 boundary correction term
if (boundaryflag) {
double xprd = domain->xprd;
double yprd = domain->yprd;
double zprd = domain->zprd;
// adjustment of z dimension for 2d slab Ewald
// 3d Ewald just uses zprd since slab_volfactor = 1.0
double volume = xprd*yprd*zprd*force->kspace->slab_volfactor;
scalar -= e_correction/volume;
}
}
/* ---------------------------------------------------------------------- */
void ComputeGroupGroup::kspace_correction()
{
// total charge of groups A & B, needed for correction term
double qsqsum_group,qsum_A,qsum_B;
qsqsum_group = qsum_A = qsum_B = 0.0;
double *q = atom->q;
int *mask = atom->mask;
int groupbit_A = groupbit;
int groupbit_B = jgroupbit;
for (int i = 0; i < atom->nlocal; i++) {
if ((mask[i] & groupbit_A) && (mask[i] & groupbit_B))
qsqsum_group += q[i]*q[i];
if (mask[i] & groupbit_A) qsum_A += q[i];
if (mask[i] & groupbit_B) qsum_B += q[i];
}
double tmp;
MPI_Allreduce(&qsqsum_group,&tmp,1,MPI_DOUBLE,MPI_SUM,world);
qsqsum_group = tmp;
MPI_Allreduce(&qsum_A,&tmp,1,MPI_DOUBLE,MPI_SUM,world);
qsum_A = tmp;
MPI_Allreduce(&qsum_B,&tmp,1,MPI_DOUBLE,MPI_SUM,world);
qsum_B = tmp;
double g_ewald = force->kspace->g_ewald;
double scale = 1.0;
const double qscale = force->qqrd2e * scale;
// self-energy correction
e_self = qscale * g_ewald*qsqsum_group/MY_PIS;
e_correction = 2.0*qsum_A*qsum_B;
// subtract extra AA terms
qsum_A = qsum_B = 0.0;
for (int i = 0; i < atom->nlocal; i++) {
if (!((mask[i] & groupbit_A) && (mask[i] & groupbit_B)))
continue;
if (mask[i] & groupbit_A) qsum_A += q[i];
if (mask[i] & groupbit_B) qsum_B += q[i];
}
MPI_Allreduce(&qsum_A,&tmp,1,MPI_DOUBLE,MPI_SUM,world);
qsum_A = tmp;
MPI_Allreduce(&qsum_B,&tmp,1,MPI_DOUBLE,MPI_SUM,world);
qsum_B = tmp;
// k=0 energy correction term (still need to divide by volume above)
e_correction -= qsum_A*qsum_B;
e_correction *= qscale * MY_PI2 / (g_ewald*g_ewald);
}
| aurix/lammps-induced-dipole-polarization-pair-style | src/compute_group_group.cpp | C++ | gpl-2.0 | 12,488 |
<?php
class Form_Login extends Zend_Form {
public function init(){
$login = new Zend_Form_Element_Text('login');
$login->setLabel('Login');
$login->setRequired();
$this->addElement($login);
$this->addElement('password', 'password', array(
'label' => 'Password',
'required' => TRUE
));
$this->addElement('submit', 'Connect');
}
} | Darkvador-a/Portfolio | src/application/forms/Login.php | PHP | gpl-2.0 | 455 |
(function($){
"use strict";
// wpb_el_type_position
$('.wpb-element-edit-modal .ewf-position-box div').click(function(){
// e.preventDefault();
$(this).closest('.ewf-position-box').find('div').removeClass('active');
$(this).addClass('active');
console.log('execute param position shit!');
var value = 'none';
if ($(this).hasClass('ewf-pb-top')) { value = 'top'; }
if ($(this).hasClass('ewf-pb-top-right')) { value = 'top-right'; }
if ($(this).hasClass('ewf-pb-top-left')) { value = 'top-left'; }
if ($(this).hasClass('ewf-pb-bottom')) { value = 'bottom'; }
if ($(this).hasClass('ewf-pb-bottom-right')) { value = 'bottom-right'; }
if ($(this).hasClass('ewf-pb-bottom-left')) { value = 'bottom-left'; }
if ($(this).hasClass('ewf-pb-left')) { value = 'left'; }
if ($(this).hasClass('ewf-pb-right')) { value = 'right'; }
$(this).closest('.edit_form_line').find('input.wpb_vc_param_value').val(value);
});
})(window.jQuery); | narendra-addweb/SwitchedOn | wp-content/themes/sapphire-wp/framework/composer/params/ewf-param-position/ewf-param-position.js | JavaScript | gpl-2.0 | 1,050 |
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*/
/* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
//#ifndef _CFG_SETTING_IMGSENSOR_H_
//#define _CFG_SETTING_IMGSENSOR_H_
#include "camera_custom_imgsensor_cfg.h"
using namespace NSCamCustomSensor;
namespace NSCamCustomSensor {
/*******************************************************************************
* Image Sensor Orientation
*******************************************************************************/
SensorOrientation_T const&
getSensorOrientation()
{
static SensorOrientation_T const inst = {
u4Degree_0 : 90, // main sensor in degree (0, 90, 180, 270)
u4Degree_1 : 270, // sub sensor in degree (0, 90, 180, 270)
u4Degree_2 : 90, // main2 sensor in degree (0, 90, 180, 270)
};
return inst;
}
/*******************************************************************************
* Return fake orientation for front sensor or not
* MTRUE: return 90 for front sensor in degree 0,
* return 270 for front sensor in degree 180.
* MFALSE: not return fake orientation.
*******************************************************************************/
MBOOL isRetFakeSubOrientation()
{
return MFALSE;
}
/*******************************************************************************
* Return fake orientation for back sensor or not
* MTRUE: return 90 for back sensor in degree 0,
* return 270 for back sensor in degree 180.
* MFALSE: not return fake orientation.
*******************************************************************************/
MBOOL isRetFakeMainOrientation()
{
return MFALSE;
}
/*******************************************************************************
* Return fake orientation for back (3D) sensor or not
* MTRUE: return 90 for back sensor in degree 0,
* return 270 for back sensor in degree 180.
* MFALSE: not return fake orientation.
*******************************************************************************/
MBOOL isRetFakeMain2Orientation()
{
return MFALSE;
}
/*******************************************************************************
* Sensor Input Data Bit Order
* Return:
* 0 : raw data input [9:2]
* 1 : raw data input [7:0]
* -1 : error
*******************************************************************************/
MINT32
getSensorInputDataBitOrder(EDevId const eDevId)
{
switch (eDevId)
{
case eDevId_ImgSensor0:
return 1;
case eDevId_ImgSensor1:
return 0;
case eDevId_ImgSensor2:
return 0;
default:
break;
}
return -1;
}
/*******************************************************************************
* Sensor Pixel Clock Inverse in PAD side.
* Return:
* 0 : no inverse
* 1 : inverse
* -1 : error
*******************************************************************************/
MINT32
getSensorPadPclkInv(EDevId const eDevId)
{
switch (eDevId)
{
case eDevId_ImgSensor0:
return 0;
case eDevId_ImgSensor1:
return 0;
case eDevId_ImgSensor2:
return 0;
default:
break;
}
return -1;
}
/*******************************************************************************
* Sensor Placement Facing Direction
* Return:
* 0 : Back side
* 1 : Front side (LCD side)
* -1 : error
*******************************************************************************/
MINT32
getSensorFacingDirection(EDevId const eDevId)
{
switch (eDevId)
{
case eDevId_ImgSensor0:
return 0;
case eDevId_ImgSensor1:
return 1;
case eDevId_ImgSensor2:
return 0;
default:
break;
}
return -1;
}
/*******************************************************************************
* Image Sensor Module FOV
*******************************************************************************/
SensorViewAngle_T const&
getSensorViewAngle()
{
static SensorViewAngle_T const inst = {
MainSensorHorFOV : 63,
MainSensorVerFOV : 49,
SubSensorHorFOV : 60,
SubSensorVerFOV : 40,
Main2SensorHorFOV : 0, //not support
Main2SensorVerFOV : 0,
};
return inst;
}
};
//#endif // _CFG_SETTING_IMGSENSOR_H_
| lenovo-a3-dev/kernel_lenovo_a3 | mediatek/custom/lenovo89_tb_twn_a_jb2/hal/imgsensor/src/cfg_setting_imgsensor.cpp | C++ | gpl-2.0 | 6,495 |
from razer.client import DeviceManager
from razer.client import constants as razer_constants
# Create a DeviceManager. This is used to get specific devices
device_manager = DeviceManager()
print("Found {} Razer devices".format(len(device_manager.devices)))
print()
# Disable daemon effect syncing.
# Without this, the daemon will try to set the lighting effect to every device.
device_manager.sync_effects = False
# Iterate over each device and set the wave effect
for device in device_manager.devices:
print("Setting {} to wave".format(device.name))
# Set the effect to wave.
# wave requires a direction, but different effect have different arguments.
device.fx.wave(razer_constants.WAVE_LEFT)
| z3ntu/razer-drivers | examples/basic_effect.py | Python | gpl-2.0 | 718 |
"""Pets now have a description
Revision ID: 0c431867c679
Revises: 5b1bdc1f3125
Create Date: 2016-11-07 18:36:25.912155
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0c431867c679'
down_revision = '5b1bdc1f3125'
branch_labels = None
depends_on = None
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('pet', sa.Column('description', sa.Text(), nullable=False))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('pet', 'description')
### end Alembic commands ###
| asif-mahmud/Pyramid-Apps | pethouse/alembic/versions/0c431867c679_pets_now_have_a_description.py | Python | gpl-2.0 | 659 |
package controler;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.Observable;
import java.util.Observer;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
// INTERNE
import model.Model;
import ressources.URLIcons;
/**
* Listener pour le bouton trait.
*
* @author Alexandre Thorez
* @author Fabien Huitelec
* @author Pierre-Édouard Caron
*
* @version 0.4 finale
*/
public class ActionOutilTrait extends AbstractAction implements Observer {
private Model model;
private JButton bouton;
/**
* Ne comporte pas de nom, autrement
* l'affichage ne s'effectuerait pas correctement
*
* @param model Modèle du MVC
*/
public ActionOutilTrait(Model model, JButton bouton) {
this.model = model;
model.addObserver(this);
this.bouton = bouton;
// Values
this.putValue(SHORT_DESCRIPTION, "Sélectionne l'outil trait");
this.putValue(SMALL_ICON, new ImageIcon(URLIcons.CRAYON));
}
/**
* Sélectionne l'outil trait dans le modèle.
*/
public void actionPerformed(ActionEvent e) {
model.setObjetCourant("trait");
model.deselectionnerToutesLesFormes();
}
/**
* Crée des bordures lorsque cet outil est sélectionné dans le modèle.
*
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
@Override
public void update(Observable arg0, Object arg1) {
if (model.getObjetCourant().equals("trait")) {
bouton.setBackground(new Color(220, 220, 220));
bouton.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.GRAY));
} else {
bouton.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.GRAY));
bouton.setBackground(Color.WHITE);
}
}
} | caronpe/dessinvectoriel | controler/ActionOutilTrait.java | Java | gpl-2.0 | 1,809 |
package command;
import org.junit.Test;
/**
* Created by eder on 19/10/15.
*/
public class RemoteCeilingFanTest {
@Test
public void testRemoteControlCeilingFan(){
RemoteControl remoteControl = new RemoteControl();
CeilingFan ceilingFan = new CeilingFan("Living room");
CeilingFanHightCommand ceilingFanHightCommand = new CeilingFanHightCommand(ceilingFan);
CeilingFanMediumCommand ceilingFanMediumCommand = new CeilingFanMediumCommand(ceilingFan);
CeilingFanOffCommand ceilingFanOffCommand = new CeilingFanOffCommand(ceilingFan);
remoteControl.setCommand(0, ceilingFanHightCommand, ceilingFanOffCommand);
remoteControl.setCommand(1, ceilingFanMediumCommand, ceilingFanOffCommand);
remoteControl.onButtonWasPushed(0);
remoteControl.offButtonWasPushed(0);
System.out.println(remoteControl);
remoteControl.undoButtonWasPushed();
remoteControl.onButtonWasPushed(1);
System.out.println(remoteControl);
remoteControl.undoButtonWasPushed();
}
}
| EderRoger/design_pattern | test/src/command/RemoteCeilingFanTest.java | Java | gpl-2.0 | 1,075 |
class movie:
"""Stores movie metadata"""
# The constructor takes
# - The Title
# - The youtube trailer
# - The poster image URL
def __init__(self, title, youtube_trailer, poster_url):
self.title = title
self.trailer_youtube_url = youtube_trailer
self.poster_image_url = poster_url
| amilendra/Udacity_FullStack_P1_MovieTracker | media.py | Python | gpl-2.0 | 338 |
/**
* All Tax meta class
*
* JS used for the custom fields and other form items.
*
* Copyright 2012 Ohad Raz (admin@bainternet.info)
* @since 1.0
*/
var $ =jQuery.noConflict();
function update_repeater_fields(){
/**
* Datepicker Field.
*
* @since 1.0
*/
$('.at-date').each( function() {
var $this = $(this),
format = $this.attr('rel');
$this.datepicker( { showButtonPanel: true, dateFormat: format } );
});
/**
* Timepicker Field.
*
* @since 1.0
*/
$('.at-time').each( function() {
var $this = $(this),
format = $this.attr('rel');
$this.timepicker( { showSecond: true, timeFormat: format } );
});
/**
* Colorpicker Field.
*
* @since 1.0
*/
/*
/**
* Select Color Field.
*
* @since 1.0
*/
$('.at-color-select').click( function(){
var $this = $(this);
var id = $this.attr('rel');
$(this).siblings('.at-color-picker').farbtastic("#" + id).toggle();
return false;
});
/**
* Add Files.
*
* @since 1.0
*/
$('.at-add-file').click( function() {
var $first = $(this).parent().find('.file-input:first');
$first.clone().insertAfter($first).show();
return false;
});
/**
* Delete File.
*
* @since 1.0
*/
$('.at-upload').delegate( '.at-delete-file', 'click' , function() {
var $this = $(this),
$parent = $this.parent(),
data = $this.attr('rel');
$.post( ajaxurl, { action: 'at_delete_file', data: data }, function(response) {
response == '0' ? ( alert( 'File has been successfully deleted.' ), $parent.remove() ) : alert( 'You do NOT have permission to delete this file.' );
});
return false;
});
/**
* Reorder Images.
*
* @since 1.0
*/
$('.at-images').each( function() {
var $this = $(this), order, data;
$this.sortable( {
placeholder: 'ui-state-highlight',
update: function (){
order = $this.sortable('serialize');
data = order + '|' + $this.siblings('.at-images-data').val();
$.post(ajaxurl, {action: 'at_reorder_images', data: data}, function(response){
response == '0' ? alert( 'Order saved!' ) : alert( "You don't have permission to reorder images." );
});
}
});
});
/**
* Thickbox Upload
*
* @since 1.0
*/
$('.at-upload-button').click( function() {
var data = $(this).attr('rel').split('|'),
post_id = data[0],
field_id = data[1],
backup = window.send_to_editor; // backup the original 'send_to_editor' function which adds images to the editor
// change the function to make it adds images to our section of uploaded images
window.send_to_editor = function(html) {
$('#at-images-' + field_id).append( $(html) );
tb_remove();
window.send_to_editor = backup;
};
// note that we pass the field_id and post_id here
tb_show('', 'media-upload.php?post_id=' + post_id + '&field_id=' + field_id + '&type=image&TB_iframe=true');
return false;
});
}
jQuery(document).ready(function($) {
/**
* repater Field
* @since 1.1
*/
/*$( ".at-repeater-item" ).live('click', function() {
var $this = $(this);
$this.siblings().toggle();
});
jQuery(".at-repater-block").click(function(){
jQuery(this).find('table').toggle();
});
*/
//edit
$(".at-re-toggle").live('click', function() {
$(this).prev().toggle('slow');
});
/**
* Datepicker Field.
*
* @since 1.0
*/
$('.at-date').each( function() {
var $this = $(this),
format = $this.attr('rel');
$this.datepicker( { showButtonPanel: true, dateFormat: format } );
});
/**
* Timepicker Field.
*
* @since 1.0
*/
$('.at-time').each( function() {
var $this = $(this),
format = $this.attr('rel');
$this.timepicker( { showSecond: true, timeFormat: format } );
});
/**
* Colorpicker Field.
*
* @since 1.0
* better handler for color picker with repeater fields support
* which now works both when button is clicked and when field gains focus.
*/
$('.at-color').live('focus', function() {
var $this = $(this);
$(this).siblings('.at-color-picker').farbtastic($this).toggle();
});
$('.at-color').live('focusout', function() {
var $this = $(this);
$(this).siblings('.at-color-picker').farbtastic($this).toggle();
});
/**
* Add Files.
*
* @since 1.0
*/
$('.at-add-file').click( function() {
var $first = $(this).parent().find('.file-input:first');
$first.clone().insertAfter($first).show();
return false;
});
/**
* Delete File.
*
* @since 1.0
*/
$('.at-upload').delegate( '.at-delete-file', 'click' , function() {
var $this = $(this),
$parent = $this.parent(),
data = $this.attr('rel');
$.post( ajaxurl, { action: 'at_delete_file', data: data }, function(response) {
response == '0' ? ( alert( 'File has been successfully deleted.' ), $parent.remove() ) : alert( 'You do NOT have permission to delete this file.' );
});
return false;
});
/**
* Thickbox Upload
*
* @since 1.0
*/
$('.at-upload-button').click( function() {
var data = $(this).attr('rel').split('|'),
post_id = data[0],
field_id = data[1],
backup = window.send_to_editor; // backup the original 'send_to_editor' function which adds images to the editor
// change the function to make it adds images to our section of uploaded images
window.send_to_editor = function(html) {
$('#at-images-' + field_id).append( $(html) );
tb_remove();
window.send_to_editor = backup;
};
// note that we pass the field_id and post_id here
tb_show('', 'media-upload.php?post_id=' + post_id + '&field_id=' + field_id + '&type=image&TB_iframe=true');
return false;
});
/**
* Helper Function
*
* Get Query string value by name.
*
* @since 1.0
*/
function get_query_var( name ) {
var match = RegExp('[?&]' + name + '=([^&#]*)').exec(location.href);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
//new image upload field
function load_images_muploader(){
jQuery(".mupload_img_holder").each(function(i,v){
if (jQuery(this).next().next().val() != ''){
if (!jQuery(this).children().size() > 0){
jQuery(this).append('<img src="' + jQuery(this).next().next().val() + '" style="height: 150px;width: 150px;" />');
jQuery(this).next().next().next().val("Delete");
jQuery(this).next().next().next().removeClass('at-upload_image_button').addClass('at-delete_image_button');
}
}
});
}
load_images_muploader();
//delete img button
jQuery('.at-delete_image_button').live('click', function(e){
var field_id = jQuery(this).attr("rel");
var at_id = jQuery(this).prev().prev();
var at_src = jQuery(this).prev();
var t_button = jQuery(this);
data = {
action: 'at_delete_mupload',
_wpnonce: $('#nonce-delete-mupload_' + field_id).val(),
post_id: get_query_var('tag_ID'),
field_id: field_id,
attachment_id: jQuery(at_id).val()
};
$.getJSON(ajaxurl, data, function(response) {
if ('success' == response.status){
jQuery(t_button).val("Upload Image");
jQuery(t_button).removeClass('at-delete_image_button').addClass('at-upload_image_button');
//clear html values
jQuery(at_id).val('');
jQuery(at_src).val('');
jQuery(at_id).prev().html('');
load_images_muploader();
}else{
alert(response.message);
}
});
return false;
});
//upload button
var formfield1;
var formfield2;
jQuery('.at-upload_image_button').live('click',function(e){
formfield1 = jQuery(this).prev();
formfield2 = jQuery(this).prev().prev();
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
//store old send to editor function
window.restore_send_to_editor = window.send_to_editor;
//overwrite send to editor function
window.send_to_editor = function(html) {
imgurl = jQuery('img',html).attr('src');
img_calsses = jQuery('img',html).attr('class').split(" ");
att_id = '';
jQuery.each(img_calsses,function(i,val){
if (val.indexOf("wp-image") != -1){
att_id = val.replace('wp-image-', "");
}
});
jQuery(formfield2).val(att_id);
jQuery(formfield1).val(imgurl);
load_images_muploader();
tb_remove();
//restore old send to editor function
window.send_to_editor = window.restore_send_to_editor;
}
return false;
});
}); | FeGHeidelberg/wp_feg-heidelberg_de | wp-content/themes/churchope/backend/js/tax-meta-clss.js | JavaScript | gpl-2.0 | 8,497 |
/*
This file is part of Jedi Knight 2.
Jedi Knight 2 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.
Jedi Knight 2 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Jedi Knight 2. If not, see <http://www.gnu.org/licenses/>.
*/
// Copyright 2001-2013 Raven Software
// leave this line at the top for all g_xxxx.cpp files...
#include "g_headers.h"
#include "g_local.h"
#include "g_functions.h"
#include "g_items.h"
#include "wp_saber.h"
extern qboolean missionInfo_Updated;
extern void CrystalAmmoSettings(gentity_t *ent);
extern void G_CreateG2AttachedWeaponModel( gentity_t *ent, const char *weaponModel );
extern void ChangeWeapon( gentity_t *ent, int newWeapon );
extern void G_SoundOnEnt( gentity_t *ent, soundChannel_t channel, const char *soundPath );
extern qboolean PM_InKnockDown( playerState_t *ps );
extern qboolean PM_InGetUp( playerState_t *ps );
extern cvar_t *g_spskill;
#define MAX_BACTA_HEAL_AMOUNT 25
/*
Items are any object that a player can touch to gain some effect.
Pickup will return the number of seconds until they should respawn.
all items should pop when dropped in lava or slime
Respawnable items don't actually go away when picked up, they are
just made invisible and untouchable. This allows them to ride
movers and respawn apropriately.
*/
// Item Spawn flags
#define ITMSF_SUSPEND 1
#define ITMSF_TEAM 2
#define ITMSF_MONSTER 4
#define ITMSF_NOTSOLID 8
#define ITMSF_VERTICAL 16
#define ITMSF_INVISIBLE 32
//======================================================================
/*
===============
G_InventorySelectable
===============
*/
qboolean G_InventorySelectable( int index,gentity_t *other)
{
if (other->client->ps.inventory[index])
{
return qtrue;
}
return qfalse;
}
extern qboolean INV_GoodieKeyGive( gentity_t *target );
extern qboolean INV_SecurityKeyGive( gentity_t *target, const char *keyname );
int Pickup_Holdable( gentity_t *ent, gentity_t *other )
{
int i,original;
other->client->ps.stats[STAT_ITEMS] |= (1<<ent->item->giTag);
if ( ent->item->giTag == INV_SECURITY_KEY )
{//give the key
//FIXME: temp message
gi.SendServerCommand( 0, "cp @INGAME_YOU_TOOK_SECURITY_KEY" );
INV_SecurityKeyGive( other, ent->message );
}
else if ( ent->item->giTag == INV_GOODIE_KEY )
{//give the key
//FIXME: temp message
gi.SendServerCommand( 0, "cp @INGAME_YOU_TOOK_SUPPLY_KEY" );
INV_GoodieKeyGive( other );
}
else
{// Picking up a normal item?
other->client->ps.inventory[ent->item->giTag]++;
}
// Got a security key
// Set the inventory select, just in case it hasn't
original = cg.inventorySelect;
for ( i = 0 ; i < INV_MAX ; i++ )
{
if ((cg.inventorySelect < INV_ELECTROBINOCULARS) || (cg.inventorySelect >= INV_MAX))
{
cg.inventorySelect = (INV_MAX - 1);
}
if ( G_InventorySelectable( cg.inventorySelect,other ) )
{
return 60;
}
cg.inventorySelect++;
}
cg.inventorySelect = original;
return 60;
}
//======================================================================
int Add_Ammo2 (gentity_t *ent, int ammoType, int count)
{
if (ammoType != AMMO_FORCE)
{
ent->client->ps.ammo[ammoType] += count;
// since the ammo is the weapon in this case, picking up ammo should actually give you the weapon
switch( ammoType )
{
case AMMO_THERMAL:
ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_THERMAL );
break;
case AMMO_DETPACK:
ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_DET_PACK );
break;
case AMMO_TRIPMINE:
ent->client->ps.stats[STAT_WEAPONS] |= ( 1 << WP_TRIP_MINE );
break;
}
if ( ent->client->ps.ammo[ammoType] > ammoData[ammoType].max )
{
ent->client->ps.ammo[ammoType] = ammoData[ammoType].max;
return qfalse;
}
}
else
{
if ( ent->client->ps.forcePower >= ammoData[ammoType].max )
{//if have full force, just get 25 extra per crystal
ent->client->ps.forcePower += 25;
}
else
{//else if don't have full charge, give full amount, up to max + 25
ent->client->ps.forcePower += count;
if ( ent->client->ps.forcePower >= ammoData[ammoType].max + 25 )
{//cap at max + 25
ent->client->ps.forcePower = ammoData[ammoType].max + 25;
}
}
if ( ent->client->ps.forcePower >= ammoData[ammoType].max*2 )
{//always cap at twice a full charge
ent->client->ps.forcePower = ammoData[ammoType].max*2;
return qfalse; // can't hold any more
}
}
return qtrue;
}
//-------------------------------------------------------
void Add_Ammo (gentity_t *ent, int weapon, int count)
{
Add_Ammo2(ent,weaponData[weapon].ammoIndex,count);
}
//-------------------------------------------------------
int Pickup_Ammo (gentity_t *ent, gentity_t *other)
{
int quantity;
if ( ent->count ) {
quantity = ent->count;
} else {
quantity = ent->item->quantity;
}
Add_Ammo2 (other, ent->item->giTag, quantity);
return 30;
}
//======================================================================
void Add_Batteries( gentity_t *ent, int *count )
{
if ( ent->client && ent->client->ps.batteryCharge < MAX_BATTERIES && *count )
{
if ( *count + ent->client->ps.batteryCharge > MAX_BATTERIES )
{
// steal what we need, then leave the rest for later
*count -= ( MAX_BATTERIES - ent->client->ps.batteryCharge );
ent->client->ps.batteryCharge = MAX_BATTERIES;
}
else
{
// just drain all of the batteries
ent->client->ps.batteryCharge += *count;
*count = 0;
}
G_AddEvent( ent, EV_BATTERIES_CHARGED, 0 );
}
}
//-------------------------------------------------------
int Pickup_Battery( gentity_t *ent, gentity_t *other )
{
int quantity;
if ( ent->count )
{
quantity = ent->count;
}
else
{
quantity = ent->item->quantity;
}
// There may be some left over in quantity if the player is close to full, but with pickup items, this amount will just be lost
Add_Batteries( other, &quantity );
return 30;
}
//======================================================================
extern void WP_SaberInitBladeData( gentity_t *ent );
extern void CG_ChangeWeapon( int num );
int Pickup_Weapon (gentity_t *ent, gentity_t *other)
{
int quantity;
qboolean hadWeapon = qfalse;
/*
if ( ent->count || (ent->activator && !ent->activator->s.number) )
{
quantity = ent->count;
}
else
{
quantity = ent->item->quantity;
}
*/
// dropped items are always picked up
if ( ent->flags & FL_DROPPED_ITEM )
{
quantity = ent->count;
}
else
{//wasn't dropped
quantity = ent->item->quantity?ent->item->quantity:50;
}
// add the weapon
if ( other->client->ps.stats[STAT_WEAPONS] & ( 1 << ent->item->giTag ) )
{
hadWeapon = qtrue;
}
other->client->ps.stats[STAT_WEAPONS] |= ( 1 << ent->item->giTag );
if ( ent->item->giTag == WP_SABER && !hadWeapon )
{
WP_SaberInitBladeData( other );
}
if ( other->s.number )
{//NPC
if ( other->s.weapon == WP_NONE )
{//NPC with no weapon picked up a weapon, change to this weapon
//FIXME: clear/set the alt-fire flag based on the picked up weapon and my class?
other->client->ps.weapon = ent->item->giTag;
other->client->ps.weaponstate = WEAPON_RAISING;
ChangeWeapon( other, ent->item->giTag );
if ( ent->item->giTag == WP_SABER )
{
other->client->ps.saberActive = qtrue;
G_CreateG2AttachedWeaponModel( other, other->client->ps.saberModel );
}
else
{
G_CreateG2AttachedWeaponModel( other, weaponData[ent->item->giTag].weaponMdl );
}
}
}
if ( quantity )
{
// Give ammo
Add_Ammo( other, ent->item->giTag, quantity );
}
return 5;
}
//======================================================================
int ITM_AddHealth (gentity_t *ent, int count)
{
ent->health += count;
if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH]) // Past max health
{
ent->health = ent->client->ps.stats[STAT_MAX_HEALTH];
return qfalse;
}
return qtrue;
}
int Pickup_Health (gentity_t *ent, gentity_t *other) {
int max;
int quantity;
max = other->client->ps.stats[STAT_MAX_HEALTH];
if ( ent->count ) {
quantity = ent->count;
} else {
quantity = ent->item->quantity;
}
other->health += quantity;
if (other->health > max ) {
other->health = max;
}
if ( ent->item->giTag == 100 ) { // mega health respawns slow
return 120;
}
return 30;
}
//======================================================================
int ITM_AddArmor (gentity_t *ent, int count)
{
ent->client->ps.stats[STAT_ARMOR] += count;
if (ent->client->ps.stats[STAT_ARMOR] > ent->client->ps.stats[STAT_MAX_HEALTH])
{
ent->client->ps.stats[STAT_ARMOR] = ent->client->ps.stats[STAT_MAX_HEALTH];
return qfalse;
}
return qtrue;
}
int Pickup_Armor( gentity_t *ent, gentity_t *other ) {
// make sure that the shield effect is on
other->client->ps.powerups[PW_BATTLESUIT] = Q3_INFINITE;
other->client->ps.stats[STAT_ARMOR] += ent->item->quantity;
if ( other->client->ps.stats[STAT_ARMOR] > other->client->ps.stats[STAT_MAX_HEALTH] ) {
other->client->ps.stats[STAT_ARMOR] = other->client->ps.stats[STAT_MAX_HEALTH];
}
return 30;
}
//======================================================================
int Pickup_Holocron( gentity_t *ent, gentity_t *other )
{
int forcePower = ent->item->giTag;
int forceLevel = ent->count;
// check if out of range
if( forceLevel < 0 || forceLevel >= NUM_FORCE_POWER_LEVELS )
{
gi.Printf(" Pickup_Holocron : count %d not in valid range\n", forceLevel );
return 1;
}
// don't pick up if already known AND your level is higher than pickup level
if ( ( other->client->ps.forcePowersKnown & ( 1 << forcePower )) )
{
//don't pickup if item is lower than current level
if( other->client->ps.forcePowerLevel[forcePower] >= forceLevel )
{
return 1;
}
}
other->client->ps.forcePowerLevel[forcePower] = forceLevel;
other->client->ps.forcePowersKnown |= ( 1 << forcePower );
missionInfo_Updated = qtrue; // Activate flashing text
gi.cvar_set("cg_updatedDataPadForcePower1", va("%d",forcePower+1)); // The +1 is offset in the print routine.
cg_updatedDataPadForcePower1.integer = forcePower+1;
gi.cvar_set("cg_updatedDataPadForcePower2", "0"); // The +1 is offset in the print routine.
cg_updatedDataPadForcePower2.integer = 0;
gi.cvar_set("cg_updatedDataPadForcePower3", "0"); // The +1 is offset in the print routine.
cg_updatedDataPadForcePower3.integer = 0;
return 1;
}
//======================================================================
/*
===============
RespawnItem
===============
*/
void RespawnItem( gentity_t *ent ) {
}
qboolean CheckItemCanBePickedUpByNPC( gentity_t *item, gentity_t *pickerupper )
{
if ( !item->item ) {
return qfalse;
}
if ( item->item->giType == IT_HOLDABLE &&
item->item->giTag == INV_SECURITY_KEY ) {
return qfalse;
}
if ( (item->flags&FL_DROPPED_ITEM)
&& item->activator != &g_entities[0]
&& pickerupper->s.number
&& pickerupper->s.weapon == WP_NONE
&& pickerupper->enemy
&& pickerupper->painDebounceTime < level.time
&& pickerupper->NPC && pickerupper->NPC->surrenderTime < level.time //not surrendering
&& !(pickerupper->NPC->scriptFlags&SCF_FORCED_MARCH) ) // not being forced to march
{//non-player, in combat, picking up a dropped item that does NOT belong to the player and it *not* a security key
if ( level.time - item->s.time < 3000 )//was 5000
{
return qfalse;
}
return qtrue;
}
return qfalse;
}
/*
===============
Touch_Item
===============
*/
extern cvar_t *g_timescale;
void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace) {
int respawn = 0;
if (!other->client)
return;
if (other->health < 1)
return; // dead people can't pickup
if ( other->client->ps.pm_time > 0 )
{//cant pick up when out of control
return;
}
// Only monsters can pick it up
if ((ent->spawnflags & ITMSF_MONSTER) && (other->client->playerTeam == TEAM_PLAYER))
{
return;
}
// Only starfleet can pick it up
if ((ent->spawnflags & ITMSF_TEAM) && (other->client->playerTeam != TEAM_PLAYER))
{
return;
}
if ( other->client->NPC_class == CLASS_ATST ||
other->client->NPC_class == CLASS_GONK ||
other->client->NPC_class == CLASS_MARK1 ||
other->client->NPC_class == CLASS_MARK2 ||
other->client->NPC_class == CLASS_MOUSE ||
other->client->NPC_class == CLASS_PROBE ||
other->client->NPC_class == CLASS_PROTOCOL ||
other->client->NPC_class == CLASS_R2D2 ||
other->client->NPC_class == CLASS_R5D2 ||
other->client->NPC_class == CLASS_SEEKER ||
other->client->NPC_class == CLASS_REMOTE ||
other->client->NPC_class == CLASS_SENTRY )
{//FIXME: some flag would be better
//droids can't pick up items/weapons!
return;
}
//FIXME: need to make them run toward a dropped weapon when fleeing without one?
//FIXME: need to make them come out of flee mode when pick up their old weapon?
if ( CheckItemCanBePickedUpByNPC( ent, other ) )
{
if ( other->NPC && other->NPC->goalEntity && other->NPC->goalEntity->enemy == ent )
{//they were running to pick me up, they did, so clear goal
other->NPC->goalEntity = NULL;
other->NPC->squadState = SQUAD_STAND_AND_SHOOT;
}
}
else if (!(ent->spawnflags & ITMSF_TEAM) && !(ent->spawnflags & ITMSF_MONSTER))
{// Only player can pick it up
if ( other->s.number != 0 ) // Not the player?
{
return;
}
}
// the same pickup rules are used for client side and server side
if ( !BG_CanItemBeGrabbed( &ent->s, &other->client->ps ) ) {
return;
}
if ( other->client )
{
if ( other->client->ps.eFlags&EF_FORCE_GRIPPED )
{//can't pick up anything while being gripped
return;
}
if ( PM_InKnockDown( &other->client->ps ) && !PM_InGetUp( &other->client->ps ) )
{//can't pick up while in a knockdown
return;
}
}
if (!ent->item) { //not an item!
gi.Printf( "Touch_Item: %s is not an item!\n", ent->classname);
return;
}
qboolean bHadWeapon = qfalse;
// call the item-specific pickup function
switch( ent->item->giType )
{
case IT_WEAPON:
if ( other->NPC && other->s.weapon == WP_NONE )
{//Make them duck and sit here for a few seconds
int pickUpTime = Q_irand( 1000, 3000 );
TIMER_Set( other, "duck", pickUpTime );
TIMER_Set( other, "roamTime", pickUpTime );
TIMER_Set( other, "stick", pickUpTime );
TIMER_Set( other, "verifyCP", pickUpTime );
TIMER_Set( other, "attackDelay", 600 );
respawn = 0;
}
if ( other->client->ps.stats[STAT_WEAPONS] & ( 1 << ent->item->giTag ) )
{
bHadWeapon = qtrue;
}
respawn = Pickup_Weapon(ent, other);
break;
case IT_AMMO:
respawn = Pickup_Ammo(ent, other);
break;
case IT_ARMOR:
respawn = Pickup_Armor(ent, other);
break;
case IT_HEALTH:
respawn = Pickup_Health(ent, other);
break;
case IT_HOLDABLE:
respawn = Pickup_Holdable(ent, other);
break;
case IT_BATTERY:
respawn = Pickup_Battery( ent, other );
break;
case IT_HOLOCRON:
respawn = Pickup_Holocron( ent, other );
break;
default:
return;
}
if ( !respawn )
{
return;
}
// play the normal pickup sound
if ( !other->s.number && g_timescale->value < 1.0f )
{//SIGH... with timescale on, you lose events left and right
extern void CG_ItemPickup( int itemNum, qboolean bHadItem );
// but we're SP so we'll cheat
cgi_S_StartSound( NULL, other->s.number, CHAN_AUTO, cgi_S_RegisterSound( ent->item->pickup_sound ) );
// show icon and name on status bar
CG_ItemPickup( ent->s.modelindex, bHadWeapon );
}
else
{
if ( bHadWeapon )
{
G_AddEvent( other, EV_ITEM_PICKUP, -ent->s.modelindex );
}
else
{
G_AddEvent( other, EV_ITEM_PICKUP, ent->s.modelindex );
}
}
// fire item targets
G_UseTargets (ent, other);
// wait of -1 will not respawn
// if ( ent->wait == -1 )
{
//why not just remove me?
G_FreeEntity( ent );
/*
//NOTE: used to do this: (for respawning?)
ent->svFlags |= SVF_NOCLIENT;
ent->s.eFlags |= EF_NODRAW;
ent->contents = 0;
ent->unlinkAfterEvent = qtrue;
*/
return;
}
}
//======================================================================
/*
================
LaunchItem
Spawns an item and tosses it forward
================
*/
gentity_t *LaunchItem( gitem_t *item, vec3_t origin, vec3_t velocity, char *target ) {
gentity_t *dropped;
dropped = G_Spawn();
dropped->s.eType = ET_ITEM;
dropped->s.modelindex = item - bg_itemlist; // store item number in modelindex
dropped->s.modelindex2 = 1; // This is non-zero is it's a dropped item
dropped->classname = item->classname;
dropped->item = item;
// try using the "correct" mins/maxs first
VectorSet( dropped->mins, item->mins[0], item->mins[1], item->mins[2] );
VectorSet( dropped->maxs, item->maxs[0], item->maxs[1], item->maxs[2] );
if ((!dropped->mins[0] && !dropped->mins[1] && !dropped->mins[2]) &&
(!dropped->maxs[0] && !dropped->maxs[1] && !dropped->maxs[2]))
{
VectorSet( dropped->maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS );
VectorScale( dropped->maxs, -1, dropped->mins );
}
dropped->contents = CONTENTS_TRIGGER|CONTENTS_ITEM;//CONTENTS_TRIGGER;//not CONTENTS_BODY for dropped items, don't need to ID them
if ( target && target[0] )
{
dropped->target = G_NewString( target );
}
else
{
// if not targeting something, auto-remove after 30 seconds
// only if it's NOT a security or goodie key
if (dropped->item->giTag != INV_SECURITY_KEY )
{
dropped->e_ThinkFunc = thinkF_G_FreeEntity;
dropped->nextthink = level.time + 30000;
}
if ( dropped->item->giType == IT_AMMO && dropped->item->giTag == AMMO_FORCE )
{
dropped->nextthink = -1;
dropped->e_ThinkFunc = thinkF_NULL;
}
}
dropped->e_TouchFunc = touchF_Touch_Item;
if ( item->giType == IT_WEAPON )
{
// give weapon items zero pitch, a random yaw, and rolled onto their sides...but would be bad to do this for a bowcaster
if ( item->giTag != WP_BOWCASTER
&& item->giTag != WP_THERMAL
&& item->giTag != WP_TRIP_MINE
&& item->giTag != WP_DET_PACK )
{
VectorSet( dropped->s.angles, 0, crandom() * 180, 90.0f );
G_SetAngles( dropped, dropped->s.angles );
}
}
G_SetOrigin( dropped, origin );
dropped->s.pos.trType = TR_GRAVITY;
dropped->s.pos.trTime = level.time;
VectorCopy( velocity, dropped->s.pos.trDelta );
dropped->s.eFlags |= EF_BOUNCE_HALF;
dropped->flags = FL_DROPPED_ITEM;
gi.linkentity (dropped);
return dropped;
}
/*
================
Drop_Item
Spawns an item and tosses it forward
================
*/
gentity_t *Drop_Item( gentity_t *ent, gitem_t *item, float angle, qboolean copytarget ) {
gentity_t *dropped = NULL;
vec3_t velocity;
vec3_t angles;
VectorCopy( ent->s.apos.trBase, angles );
angles[YAW] += angle;
angles[PITCH] = 0; // always forward
AngleVectors( angles, velocity, NULL, NULL );
VectorScale( velocity, 150, velocity );
velocity[2] += 200 + crandom() * 50;
if ( copytarget )
{
dropped = LaunchItem( item, ent->s.pos.trBase, velocity, ent->opentarget );
}
else
{
dropped = LaunchItem( item, ent->s.pos.trBase, velocity, NULL );
}
dropped->activator = ent;//so we know who we belonged to so they can pick it back up later
dropped->s.time = level.time;//mark this time so we aren't picked up instantly by the guy who dropped us
return dropped;
}
/*
================
Use_Item
Respawn the item
================
*/
void Use_Item( gentity_t *ent, gentity_t *other, gentity_t *activator )
{
if ( (ent->svFlags&SVF_PLAYER_USABLE) && other && !other->s.number )
{//used directly by the player, pick me up
GEntity_TouchFunc( ent, other, NULL );
}
else
{//use me
if ( ent->spawnflags & 32 ) // invisible
{
// If it was invisible, first use makes it visible....
ent->s.eFlags &= ~EF_NODRAW;
ent->contents = CONTENTS_TRIGGER|CONTENTS_ITEM;
ent->spawnflags &= ~32;
return;
}
G_ActivateBehavior( ent, BSET_USE );
RespawnItem( ent );
}
}
//======================================================================
/*
================
FinishSpawningItem
Traces down to find where an item should rest, instead of letting them
free fall from their spawn points
================
*/
#ifndef FINAL_BUILD
extern int delayedShutDown;
#endif
void FinishSpawningItem( gentity_t *ent ) {
trace_t tr;
vec3_t dest;
gitem_t *item;
int itemNum;
itemNum=1;
for ( item = bg_itemlist + 1 ; item->classname ; item++,itemNum++)
{
if (!strcmp(item->classname,ent->classname))
{
break;
}
}
// Set bounding box for item
VectorSet( ent->mins, item->mins[0],item->mins[1] ,item->mins[2]);
VectorSet( ent->maxs, item->maxs[0],item->maxs[1] ,item->maxs[2]);
if ((!ent->mins[0] && !ent->mins[1] && !ent->mins[2]) &&
(!ent->maxs[0] && !ent->maxs[1] && !ent->maxs[2]))
{
VectorSet (ent->mins, -ITEM_RADIUS, -ITEM_RADIUS, -2);//to match the comments in the items.dat file!
VectorSet (ent->maxs, ITEM_RADIUS, ITEM_RADIUS, ITEM_RADIUS);
}
if ((item->quantity) && (item->giType == IT_AMMO))
{
ent->count = item->quantity;
}
if ((item->quantity) && (item->giType == IT_BATTERY))
{
ent->count = item->quantity;
}
// if ( item->giType == IT_WEAPON ) // NOTE: james thought it was ok to just always do this?
{
ent->s.radius = 20;
VectorSet( ent->s.modelScale, 1.0f, 1.0f, 1.0f );
gi.G2API_InitGhoul2Model( ent->ghoul2, ent->item->world_model, G_ModelIndex( ent->item->world_model ), NULL_HANDLE, NULL_HANDLE, 0, 0);
}
// Set crystal ammo amount based on skill level
/* if ((itemNum == ITM_AMMO_CRYSTAL_BORG) ||
(itemNum == ITM_AMMO_CRYSTAL_DN) ||
(itemNum == ITM_AMMO_CRYSTAL_FORGE) ||
(itemNum == ITM_AMMO_CRYSTAL_SCAVENGER) ||
(itemNum == ITM_AMMO_CRYSTAL_STASIS))
{
CrystalAmmoSettings(ent);
}
*/
ent->s.eType = ET_ITEM;
ent->s.modelindex = ent->item - bg_itemlist; // store item number in modelindex
ent->s.modelindex2 = 0; // zero indicates this isn't a dropped item
ent->contents = CONTENTS_TRIGGER|CONTENTS_ITEM;//CONTENTS_BODY;//CONTENTS_TRIGGER|
ent->e_TouchFunc = touchF_Touch_Item;
// useing an item causes it to respawn
ent->e_UseFunc = useF_Use_Item;
ent->svFlags |= SVF_PLAYER_USABLE;//so player can pick it up
// Hang in air?
ent->s.origin[2] += 1;//just to get it off the damn ground because coplanar = insolid
if ( ent->spawnflags & ITMSF_SUSPEND)
{
// suspended
G_SetOrigin( ent, ent->s.origin );
}
else
{
// drop to floor
VectorSet( dest, ent->s.origin[0], ent->s.origin[1], MIN_WORLD_COORD );
gi.trace( &tr, ent->s.origin, ent->mins, ent->maxs, dest, ent->s.number, MASK_SOLID|CONTENTS_PLAYERCLIP, G2_NOCOLLIDE, 0 );
if ( tr.startsolid )
{
if ( &g_entities[tr.entityNum] != NULL )
{
gi.Printf (S_COLOR_RED"FinishSpawningItem: removing %s startsolid at %s (in a %s)\n", ent->classname, vtos(ent->s.origin), g_entities[tr.entityNum].classname );
}
else
{
gi.Printf (S_COLOR_RED"FinishSpawningItem: removing %s startsolid at %s (in a %s)\n", ent->classname, vtos(ent->s.origin) );
}
assert( 0 && "item starting in solid");
#ifndef FINAL_BUILD
if (!g_entities[ENTITYNUM_WORLD].s.radius){ //not a region
delayedShutDown = level.time + 100;
}
#endif
G_FreeEntity( ent );
return;
}
// allow to ride movers
ent->s.groundEntityNum = tr.entityNum;
G_SetOrigin( ent, tr.endpos );
}
/* ? don't need this
// team slaves and targeted items aren't present at start
if ( ( ent->flags & FL_TEAMSLAVE ) || ent->targetname ) {
ent->s.eFlags |= EF_NODRAW;
ent->contents = 0;
return;
}
*/
if ( ent->spawnflags & ITMSF_INVISIBLE ) // invisible
{
ent->s.eFlags |= EF_NODRAW;
ent->contents = 0;
}
if ( ent->spawnflags & ITMSF_NOTSOLID ) // not solid
{
ent->contents = 0;
}
gi.linkentity (ent);
}
char itemRegistered[MAX_ITEMS+1];
/*
==============
ClearRegisteredItems
==============
*/
void ClearRegisteredItems( void ) {
for ( int i = 0; i < bg_numItems; i++ )
{
itemRegistered[i] = '0';
}
itemRegistered[ bg_numItems ] = 0;
RegisterItem( FindItemForWeapon( WP_BRYAR_PISTOL ) ); //these are given in g_client, ClientSpawn(), but MUST be registered HERE, BEFORE cgame starts.
RegisterItem( FindItemForWeapon( WP_STUN_BATON ) ); //these are given in g_client, ClientSpawn(), but MUST be registered HERE, BEFORE cgame starts.
RegisterItem( FindItemForInventory( INV_ELECTROBINOCULARS ));
// saber or baton is cached in SP_info_player_deathmatch now.
extern void Player_CacheFromPrevLevel(void);//g_client.cpp
Player_CacheFromPrevLevel(); //reads from transition carry-over;
}
/*
===============
RegisterItem
The item will be added to the precache list
===============
*/
void RegisterItem( gitem_t *item ) {
if ( !item ) {
G_Error( "RegisterItem: NULL" );
}
itemRegistered[ item - bg_itemlist ] = '1';
gi.SetConfigstring(CS_ITEMS, itemRegistered); //Write the needed items to a config string
}
/*
===============
SaveRegisteredItems
Write the needed items to a config string
so the client will know which ones to precache
===============
*/
void SaveRegisteredItems( void ) {
/* char string[MAX_ITEMS+1];
int i;
int count;
count = 0;
for ( i = 0 ; i < bg_numItems ; i++ ) {
if ( itemRegistered[i] ) {
count++;
string[i] = '1';
} else {
string[i] = '0';
}
}
string[ bg_numItems ] = 0;
gi.Printf( "%i items registered\n", count );
gi.SetConfigstring(CS_ITEMS, string);
*/
gi.SetConfigstring(CS_ITEMS, itemRegistered);
}
/*
============
item_spawn_use
if an item is given a targetname, it will be spawned in when used
============
*/
void item_spawn_use( gentity_t *self, gentity_t *other, gentity_t *activator )
//-----------------------------------------------------------------------------
{
self->nextthink = level.time + 50;
self->e_ThinkFunc = thinkF_FinishSpawningItem;
// I could be fancy and add a count or something like that to be able to spawn the item numerous times...
self->e_UseFunc = useF_NULL;
}
/*
============
G_SpawnItem
Sets the clipping size and plants the object on the floor.
Items can't be immediately dropped to floor, because they might
be on an entity that hasn't spawned yet.
============
*/
void G_SpawnItem (gentity_t *ent, gitem_t *item) {
G_SpawnFloat( "random", "0", &ent->random );
G_SpawnFloat( "wait", "0", &ent->wait );
RegisterItem( item );
ent->item = item;
// targetname indicates they want to spawn it later
if( ent->targetname )
{
ent->e_UseFunc = useF_item_spawn_use;
}
else
{ // some movers spawn on the second frame, so delay item
// spawns until the third frame so they can ride trains
ent->nextthink = level.time + START_TIME_MOVERS_SPAWNED + 50;
ent->e_ThinkFunc = thinkF_FinishSpawningItem;
}
ent->physicsBounce = 0.50; // items are bouncy
// Set a default infoString text color
// NOTE: if we want to do cool cross-hair colors for items, we can just modify this, but for now, don't do it
VectorSet( ent->startRGBA, 1.0f, 1.0f, 1.0f );
}
/*
================
G_BounceItem
================
*/
void G_BounceItem( gentity_t *ent, trace_t *trace ) {
vec3_t velocity;
float dot;
int hitTime;
// reflect the velocity on the trace plane
hitTime = level.previousTime + ( level.time - level.previousTime ) * trace->fraction;
EvaluateTrajectoryDelta( &ent->s.pos, hitTime, velocity );
dot = DotProduct( velocity, trace->plane.normal );
VectorMA( velocity, -2*dot, trace->plane.normal, ent->s.pos.trDelta );
// cut the velocity to keep from bouncing forever
VectorScale( ent->s.pos.trDelta, ent->physicsBounce, ent->s.pos.trDelta );
// check for stop
if ( trace->plane.normal[2] > 0 && ent->s.pos.trDelta[2] < 40 ) {
G_SetOrigin( ent, trace->endpos );
ent->s.groundEntityNum = trace->entityNum;
return;
}
VectorAdd( ent->currentOrigin, trace->plane.normal, ent->currentOrigin);
VectorCopy( ent->currentOrigin, ent->s.pos.trBase );
ent->s.pos.trTime = level.time;
}
/*
================
G_RunItem
================
*/
void G_RunItem( gentity_t *ent ) {
vec3_t origin;
trace_t tr;
int contents;
int mask;
// if groundentity has been set to -1, it may have been pushed off an edge
if ( ent->s.groundEntityNum == ENTITYNUM_NONE )
{
if ( ent->s.pos.trType != TR_GRAVITY )
{
ent->s.pos.trType = TR_GRAVITY;
ent->s.pos.trTime = level.time;
}
}
if ( ent->s.pos.trType == TR_STATIONARY )
{
// check think function
G_RunThink( ent );
if ( !g_gravity->value )
{
ent->s.pos.trType = TR_GRAVITY;
ent->s.pos.trTime = level.time;
ent->s.pos.trDelta[0] += crandom() * 40.0f; // I dunno, just do this??
ent->s.pos.trDelta[1] += crandom() * 40.0f;
ent->s.pos.trDelta[2] += random() * 20.0f;
}
return;
}
// get current position
EvaluateTrajectory( &ent->s.pos, level.time, origin );
// trace a line from the previous position to the current position
if ( ent->clipmask )
{
mask = ent->clipmask;
}
else
{
mask = MASK_SOLID|CONTENTS_PLAYERCLIP;//shouldn't be able to get anywhere player can't
}
int ignore = ENTITYNUM_NONE;
if ( ent->owner )
{
ignore = ent->owner->s.number;
}
else if ( ent->activator )
{
ignore = ent->activator->s.number;
}
gi.trace( &tr, ent->currentOrigin, ent->mins, ent->maxs, origin, ignore, mask, G2_NOCOLLIDE, 0 );
VectorCopy( tr.endpos, ent->currentOrigin );
if ( tr.startsolid )
{
tr.fraction = 0;
}
gi.linkentity( ent ); // FIXME: avoid this for stationary?
// check think function
G_RunThink( ent );
if ( tr.fraction == 1 )
{
if ( g_gravity->value <= 0 )
{
if ( ent->s.apos.trType != TR_LINEAR )
{
VectorCopy( ent->currentAngles, ent->s.apos.trBase );
ent->s.apos.trType = TR_LINEAR;
ent->s.apos.trDelta[1] = Q_flrand( -300, 300 );
ent->s.apos.trDelta[0] = Q_flrand( -10, 10 );
ent->s.apos.trDelta[2] = Q_flrand( -10, 10 );
ent->s.apos.trTime = level.time;
}
}
//friction in zero-G
if ( !g_gravity->value )
{
float friction = 0.975f;
/*friction -= ent->mass/1000.0f;
if ( friction < 0.1 )
{
friction = 0.1f;
}
*/
VectorScale( ent->s.pos.trDelta, friction, ent->s.pos.trDelta );
VectorCopy( ent->currentOrigin, ent->s.pos.trBase );
ent->s.pos.trTime = level.time;
}
return;
}
// if it is in a nodrop volume, remove it
contents = gi.pointcontents( ent->currentOrigin, -1 );
if ( contents & CONTENTS_NODROP )
{
G_FreeEntity( ent );
return;
}
if ( !tr.startsolid )
{
G_BounceItem( ent, &tr );
}
}
/*
================
ItemUse_Bacta
================
*/
void ItemUse_Bacta(gentity_t *ent)
{
if (!ent || !ent->client)
{
return;
}
if (ent->health >= ent->client->ps.stats[STAT_MAX_HEALTH] || !ent->client->ps.inventory[INV_BACTA_CANISTER] )
{
return;
}
ent->health += MAX_BACTA_HEAL_AMOUNT;
if (ent->health > ent->client->ps.stats[STAT_MAX_HEALTH])
{
ent->health = ent->client->ps.stats[STAT_MAX_HEALTH];
}
ent->client->ps.inventory[INV_BACTA_CANISTER]--;
G_SoundOnEnt( ent, CHAN_VOICE, va( "sound/weapons/force/heal%d.mp3", Q_irand( 1, 4 ) ) );
}
| BruceJohnJennerLawso/OtherJK | codeJK2/game/g_items.cpp | C++ | gpl-2.0 | 31,183 |
<?php
defined('ZOTOP') OR die('No direct access allowed.');
/**
* ipbanned
*
* @package system
* @author zotop team
* @copyright (c)2009-2011 zotop team
* @license http://zotop.com/license.html
*/
class system_model_ipbanned extends model
{
protected $pk = 'ip';
protected $table = 'ipbanned';
/**
* 添加
*
*/
public function add($data)
{
if ( empty($data['ip']) ) return $this->error(t('ip不能为空'));
if ( empty($data['expires']) ) return $this->error(t('有效期不能为空'));
if ( !preg_match("/\A((([0-9]?[0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))\.){3}(([0-9]?[0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))\Z/",$data['ip']))
{
return $this->error(t('IP格式错误'));
}
// 将字符串转化为时间戳
$data['expires'] = strtotime($data['expires']);
return $this->insert($data, true);
}
/**
* 保存前处理数据
*
*/
public function edit($data, $ip)
{
if ( empty($data['ip']) ) return $this->error(t('ip不能为空'));
if ( empty($data['expires']) ) return $this->error(t('有效期不能为空'));
if( !preg_match("/\A((([0-9]?[0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))\.){3}(([0-9]?[0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))\Z/",$data['ip']))
{
return $this->error(t('IP格式错误'));
}
// 将字符串转化为时间戳
$data['expires'] = strtotime($data['expires']);
return $this->update($data, $ip);
}
/*
* 是否禁止ip
*
* @params string $ip ip
*
* @return bool
*/
public function isbanned($ip)
{
return $this->where('ip','=',$ip)->where('expires','>',ZOTOP_TIME)->exists();
}
/*
* 添加一个禁止IP,有效期为小时
*
* @params string $ip ip
* @params string $expires 禁止时间,单位小时
* @return bool
*/
public function banned($ip, $expires=72)
{
$expires = ZOTOP_TIME + intval($expires)*60*60;
if ( $this->where('ip','=',$ip)->exists() )
{
return $this->update(array('expires'=>$expires),$ip);
}
return $this->insert(array(
'ip'=>$ip,
'expires'=>$expires
),true);
}
}
?> | zotopteam/zotop | zotop/apps/system/models/ipbanned.php | PHP | gpl-2.0 | 2,109 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright held by original author
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Description
All to do with adding cell layers
\*---------------------------------------------------------------------------*/
#include "autoLayerDriver.H"
#include "fvMesh.H"
#include "Time.H"
#include "meshRefinement.H"
#include "removePoints.H"
#include "pointFields.H"
#include "motionSmoother.H"
#include "mathematicalConstants.H"
#include "pointSet.H"
#include "faceSet.H"
#include "cellSet.H"
#include "directTopoChange.H"
#include "mapPolyMesh.H"
#include "addPatchCellLayer.H"
#include "mapDistributePolyMesh.H"
#include "OFstream.H"
#include "layerParameters.H"
#include "combineFaces.H"
#include "IOmanip.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace Foam
{
defineTypeNameAndDebug(autoLayerDriver, 0);
} // End namespace Foam
// * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * //
Foam::label Foam::autoLayerDriver::mergePatchFacesUndo
(
const scalar minCos,
const scalar concaveCos,
const dictionary& motionDict
)
{
fvMesh& mesh = meshRefiner_.mesh();
// Patch face merging engine
combineFaces faceCombiner(mesh, true);
// Pick up all candidate cells on boundary
labelHashSet boundaryCells(mesh.nFaces()-mesh.nInternalFaces());
{
labelList patchIDs(meshRefiner_.meshedPatches());
const polyBoundaryMesh& patches = mesh.boundaryMesh();
forAll(patchIDs, i)
{
label patchI = patchIDs[i];
const polyPatch& patch = patches[patchI];
if (!patch.coupled())
{
forAll(patch, i)
{
boundaryCells.insert(mesh.faceOwner()[patch.start()+i]);
}
}
}
}
// Get all sets of faces that can be merged
labelListList allFaceSets
(
faceCombiner.getMergeSets
(
minCos,
concaveCos,
boundaryCells
)
);
label nFaceSets = returnReduce(allFaceSets.size(), sumOp<label>());
Info<< "Merging " << nFaceSets << " sets of faces." << nl << endl;
if (nFaceSets > 0)
{
if (debug)
{
faceSet allSets(mesh, "allFaceSets", allFaceSets.size());
forAll(allFaceSets, setI)
{
forAll(allFaceSets[setI], i)
{
allSets.insert(allFaceSets[setI][i]);
}
}
Pout<< "Writing all faces to be merged to set "
<< allSets.objectPath() << endl;
allSets.write();
}
// Topology changes container
directTopoChange meshMod(mesh);
// Merge all faces of a set into the first face of the set.
faceCombiner.setRefinement(allFaceSets, meshMod);
// Experimental: store data for all the points that have been deleted
meshRefiner_.storeData
(
faceCombiner.savedPointLabels(), // points to store
labelList(0), // faces to store
labelList(0) // cells to store
);
// Change the mesh (no inflation)
autoPtr<mapPolyMesh> map = meshMod.changeMesh(mesh, false, true);
// Update fields
mesh.updateMesh(map);
// Move mesh (since morphing does not do this)
if (map().hasMotionPoints())
{
mesh.movePoints(map().preMotionPoints());
}
else
{
// Delete mesh volumes.
mesh.clearOut();
}
if (meshRefiner_.overwrite())
{
mesh.setInstance(meshRefiner_.oldInstance());
}
faceCombiner.updateMesh(map);
meshRefiner_.updateMesh(map, labelList(0));
for (label iteration = 0; iteration < 100; iteration++)
{
Info<< nl
<< "Undo iteration " << iteration << nl
<< "----------------" << endl;
// Check mesh for errors
// ~~~~~~~~~~~~~~~~~~~~~
faceSet errorFaces
(
mesh,
"errorFaces",
mesh.nFaces()-mesh.nInternalFaces()
);
bool hasErrors = motionSmoother::checkMesh
(
false, // report
mesh,
motionDict,
errorFaces
);
//if (checkEdgeConnectivity)
//{
// Info<< "Checking edge-face connectivity (duplicate faces"
// << " or non-consecutive shared vertices)" << endl;
//
// label nOldSize = errorFaces.size();
//
// hasErrors =
// mesh.checkFaceFaces
// (
// false,
// &errorFaces
// )
// || hasErrors;
//
// Info<< "Detected additional "
// << returnReduce(errorFaces.size()-nOldSize, sumOp<label>())
// << " faces with illegal face-face connectivity"
// << endl;
//}
if (!hasErrors)
{
break;
}
if (debug)
{
Pout<< "Writing all faces in error to faceSet "
<< errorFaces.objectPath() << nl << endl;
errorFaces.write();
}
// Check any master cells for using any of the error faces
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DynamicList<label> mastersToRestore(allFaceSets.size());
forAll(allFaceSets, setI)
{
label masterFaceI = faceCombiner.masterFace()[setI];
if (masterFaceI != -1)
{
label masterCellII = mesh.faceOwner()[masterFaceI];
const cell& cFaces = mesh.cells()[masterCellII];
forAll(cFaces, i)
{
if (errorFaces.found(cFaces[i]))
{
mastersToRestore.append(masterFaceI);
break;
}
}
}
}
mastersToRestore.shrink();
label nRestore = returnReduce
(
mastersToRestore.size(),
sumOp<label>()
);
Info<< "Masters that need to be restored:"
<< nRestore << endl;
if (debug)
{
faceSet restoreSet
(
mesh,
"mastersToRestore",
labelHashSet(mastersToRestore)
);
Pout<< "Writing all " << mastersToRestore.size()
<< " masterfaces to be restored to set "
<< restoreSet.objectPath() << endl;
restoreSet.write();
}
if (nRestore == 0)
{
break;
}
// Undo
// ~~~~
// Topology changes container
directTopoChange meshMod(mesh);
// Merge all faces of a set into the first face of the set.
// Experimental:mark all points/faces/cells that have been restored.
Map<label> restoredPoints(0);
Map<label> restoredFaces(0);
Map<label> restoredCells(0);
faceCombiner.setUnrefinement
(
mastersToRestore,
meshMod,
restoredPoints,
restoredFaces,
restoredCells
);
// Change the mesh (no inflation)
autoPtr<mapPolyMesh> map = meshMod.changeMesh(mesh, false, true);
// Update fields
mesh.updateMesh(map);
// Move mesh (since morphing does not do this)
if (map().hasMotionPoints())
{
mesh.movePoints(map().preMotionPoints());
}
else
{
// Delete mesh volumes.
mesh.clearOut();
}
if (meshRefiner_.overwrite())
{
mesh.setInstance(meshRefiner_.oldInstance());
}
faceCombiner.updateMesh(map);
// Renumber restore maps
inplaceMapKey(map().reversePointMap(), restoredPoints);
inplaceMapKey(map().reverseFaceMap(), restoredFaces);
inplaceMapKey(map().reverseCellMap(), restoredCells);
// Experimental:restore all points/face/cells in maps
meshRefiner_.updateMesh
(
map,
labelList(0), // changedFaces
restoredPoints,
restoredFaces,
restoredCells
);
Info<< endl;
}
if (debug)
{
Pout<< "Writing merged-faces mesh to time "
<< meshRefiner_.timeName() << nl << endl;
mesh.write();
}
}
else
{
Info<< "No faces merged ..." << endl;
}
return nFaceSets;
}
// Remove points. pointCanBeDeleted is parallel synchronised.
Foam::autoPtr<Foam::mapPolyMesh> Foam::autoLayerDriver::doRemovePoints
(
removePoints& pointRemover,
const boolList& pointCanBeDeleted
)
{
fvMesh& mesh = meshRefiner_.mesh();
// Topology changes container
directTopoChange meshMod(mesh);
pointRemover.setRefinement(pointCanBeDeleted, meshMod);
// Change the mesh (no inflation)
autoPtr<mapPolyMesh> map = meshMod.changeMesh(mesh, false, true);
// Update fields
mesh.updateMesh(map);
// Move mesh (since morphing does not do this)
if (map().hasMotionPoints())
{
mesh.movePoints(map().preMotionPoints());
}
else
{
// Delete mesh volumes.
mesh.clearOut();
}
if (meshRefiner_.overwrite())
{
mesh.setInstance(meshRefiner_.oldInstance());
}
pointRemover.updateMesh(map);
meshRefiner_.updateMesh(map, labelList(0));
return map;
}
// Restore faces (which contain removed points)
Foam::autoPtr<Foam::mapPolyMesh> Foam::autoLayerDriver::doRestorePoints
(
removePoints& pointRemover,
const labelList& facesToRestore
)
{
fvMesh& mesh = meshRefiner_.mesh();
// Topology changes container
directTopoChange meshMod(mesh);
// Determine sets of points and faces to restore
labelList localFaces, localPoints;
pointRemover.getUnrefimentSet
(
facesToRestore,
localFaces,
localPoints
);
// Undo the changes on the faces that are in error.
pointRemover.setUnrefinement
(
localFaces,
localPoints,
meshMod
);
// Change the mesh (no inflation)
autoPtr<mapPolyMesh> map = meshMod.changeMesh(mesh, false, true);
// Update fields
mesh.updateMesh(map);
// Move mesh (since morphing does not do this)
if (map().hasMotionPoints())
{
mesh.movePoints(map().preMotionPoints());
}
else
{
// Delete mesh volumes.
mesh.clearOut();
}
if (meshRefiner_.overwrite())
{
mesh.setInstance(meshRefiner_.oldInstance());
}
pointRemover.updateMesh(map);
meshRefiner_.updateMesh(map, labelList(0));
return map;
}
// Collect all faces that are both in candidateFaces and in the set.
// If coupled face also collects the coupled face.
Foam::labelList Foam::autoLayerDriver::collectFaces
(
const labelList& candidateFaces,
const labelHashSet& set
) const
{
const fvMesh& mesh = meshRefiner_.mesh();
// Has face been selected?
boolList selected(mesh.nFaces(), false);
forAll(candidateFaces, i)
{
label faceI = candidateFaces[i];
if (set.found(faceI))
{
selected[faceI] = true;
}
}
syncTools::syncFaceList
(
mesh,
selected,
orEqOp<bool>(), // combine operator
false // separation
);
labelList selectedFaces(findIndices(selected, true));
return selectedFaces;
}
// Pick up faces of cells of faces in set.
Foam::labelList Foam::autoLayerDriver::growFaceCellFace
(
const labelHashSet& set
) const
{
const fvMesh& mesh = meshRefiner_.mesh();
boolList selected(mesh.nFaces(), false);
forAllConstIter(faceSet, set, iter)
{
label faceI = iter.key();
label own = mesh.faceOwner()[faceI];
const cell& ownFaces = mesh.cells()[own];
forAll(ownFaces, ownFaceI)
{
selected[ownFaces[ownFaceI]] = true;
}
if (mesh.isInternalFace(faceI))
{
label nbr = mesh.faceNeighbour()[faceI];
const cell& nbrFaces = mesh.cells()[nbr];
forAll(nbrFaces, nbrFaceI)
{
selected[nbrFaces[nbrFaceI]] = true;
}
}
}
syncTools::syncFaceList
(
mesh,
selected,
orEqOp<bool>(), // combine operator
false // separation
);
return findIndices(selected, true);
}
// Remove points not used by any face or points used by only two faces where
// the edges are in line
Foam::label Foam::autoLayerDriver::mergeEdgesUndo
(
const scalar minCos,
const dictionary& motionDict
)
{
fvMesh& mesh = meshRefiner_.mesh();
Info<< nl
<< "Merging all points on surface that" << nl
<< "- are used by only two boundary faces and" << nl
<< "- make an angle with a cosine of more than " << minCos
<< "." << nl << endl;
// Point removal analysis engine with undo
removePoints pointRemover(mesh, true);
// Count usage of points
boolList pointCanBeDeleted;
label nRemove = pointRemover.countPointUsage(minCos, pointCanBeDeleted);
if (nRemove > 0)
{
Info<< "Removing " << nRemove
<< " straight edge points ..." << nl << endl;
// Remove points
// ~~~~~~~~~~~~~
doRemovePoints(pointRemover, pointCanBeDeleted);
for (label iteration = 0; iteration < 100; iteration++)
{
Info<< nl
<< "Undo iteration " << iteration << nl
<< "----------------" << endl;
// Check mesh for errors
// ~~~~~~~~~~~~~~~~~~~~~
faceSet errorFaces
(
mesh,
"errorFaces",
mesh.nFaces()-mesh.nInternalFaces()
);
bool hasErrors = motionSmoother::checkMesh
(
false, // report
mesh,
motionDict,
errorFaces
);
//if (checkEdgeConnectivity)
//{
// Info<< "Checking edge-face connectivity (duplicate faces"
// << " or non-consecutive shared vertices)" << endl;
//
// label nOldSize = errorFaces.size();
//
// hasErrors =
// mesh.checkFaceFaces
// (
// false,
// &errorFaces
// )
// || hasErrors;
//
// Info<< "Detected additional "
// << returnReduce(errorFaces.size()-nOldSize,sumOp<label>())
// << " faces with illegal face-face connectivity"
// << endl;
//}
if (!hasErrors)
{
break;
}
if (debug)
{
Pout<< "**Writing all faces in error to faceSet "
<< errorFaces.objectPath() << nl << endl;
errorFaces.write();
}
labelList masterErrorFaces
(
collectFaces
(
pointRemover.savedFaceLabels(),
errorFaces
)
);
label n = returnReduce(masterErrorFaces.size(), sumOp<label>());
Info<< "Detected " << n
<< " error faces on boundaries that have been merged."
<< " These will be restored to their original faces." << nl
<< endl;
if (n == 0)
{
if (hasErrors)
{
Info<< "Detected "
<< returnReduce(errorFaces.size(), sumOp<label>())
<< " error faces in mesh."
<< " Restoring neighbours of faces in error." << nl
<< endl;
labelList expandedErrorFaces
(
growFaceCellFace
(
errorFaces
)
);
doRestorePoints(pointRemover, expandedErrorFaces);
}
break;
}
doRestorePoints(pointRemover, masterErrorFaces);
}
if (debug)
{
Pout<< "Writing merged-edges mesh to time "
<< meshRefiner_.timeName() << nl << endl;
mesh.write();
}
}
else
{
Info<< "No straight edges simplified and no points removed ..." << endl;
}
return nRemove;
}
// For debugging: Dump displacement to .obj files
void Foam::autoLayerDriver::dumpDisplacement
(
const fileName& prefix,
const indirectPrimitivePatch& pp,
const vectorField& patchDisp,
const List<extrudeMode>& extrudeStatus
)
{
OFstream dispStr(prefix + "_disp.obj");
Info<< "Writing all displacements to " << dispStr.name() << nl << endl;
label vertI = 0;
forAll(patchDisp, patchPointI)
{
const point& pt = pp.localPoints()[patchPointI];
meshTools::writeOBJ(dispStr, pt); vertI++;
meshTools::writeOBJ(dispStr, pt + patchDisp[patchPointI]); vertI++;
dispStr << "l " << vertI-1 << ' ' << vertI << nl;
}
OFstream illStr(prefix + "_illegal.obj");
Info<< "Writing invalid displacements to " << illStr.name() << nl << endl;
vertI = 0;
forAll(patchDisp, patchPointI)
{
if (extrudeStatus[patchPointI] != EXTRUDE)
{
const point& pt = pp.localPoints()[patchPointI];
meshTools::writeOBJ(illStr, pt); vertI++;
meshTools::writeOBJ(illStr, pt + patchDisp[patchPointI]); vertI++;
illStr << "l " << vertI-1 << ' ' << vertI << nl;
}
}
}
// Check that primitivePatch is not multiply connected. Collect non-manifold
// points in pointSet.
void Foam::autoLayerDriver::checkManifold
(
const indirectPrimitivePatch& fp,
pointSet& nonManifoldPoints
)
{
// Check for non-manifold points (surface pinched at point)
fp.checkPointManifold(false, &nonManifoldPoints);
// Check for edge-faces (surface pinched at edge)
const labelListList& edgeFaces = fp.edgeFaces();
forAll(edgeFaces, edgeI)
{
const labelList& eFaces = edgeFaces[edgeI];
if (eFaces.size() > 2)
{
const edge& e = fp.edges()[edgeI];
nonManifoldPoints.insert(fp.meshPoints()[e[0]]);
nonManifoldPoints.insert(fp.meshPoints()[e[1]]);
}
}
}
void Foam::autoLayerDriver::checkMeshManifold() const
{
const fvMesh& mesh = meshRefiner_.mesh();
Info<< nl << "Checking mesh manifoldness ..." << endl;
// Get all outside faces
labelList outsideFaces(mesh.nFaces() - mesh.nInternalFaces());
for (label faceI = mesh.nInternalFaces(); faceI < mesh.nFaces(); faceI++)
{
outsideFaces[faceI - mesh.nInternalFaces()] = faceI;
}
pointSet nonManifoldPoints
(
mesh,
"nonManifoldPoints",
mesh.nPoints() / 100
);
// Build primitivePatch out of faces and check it for problems.
checkManifold
(
indirectPrimitivePatch
(
IndirectList<face>(mesh.faces(), outsideFaces),
mesh.points()
),
nonManifoldPoints
);
label nNonManif = returnReduce(nonManifoldPoints.size(), sumOp<label>());
if (nNonManif > 0)
{
Info<< "Outside of mesh is multiply connected across edges or"
<< " points." << nl
<< "This is not a fatal error but might cause some unexpected"
<< " behaviour." << nl
<< "Writing " << nNonManif
<< " points where this happens to pointSet "
<< nonManifoldPoints.name() << endl;
nonManifoldPoints.write();
}
Info<< endl;
}
// Unset extrusion on point. Returns true if anything unset.
bool Foam::autoLayerDriver::unmarkExtrusion
(
const label patchPointI,
pointField& patchDisp,
labelList& patchNLayers,
List<extrudeMode>& extrudeStatus
)
{
if (extrudeStatus[patchPointI] == EXTRUDE)
{
extrudeStatus[patchPointI] = NOEXTRUDE;
patchNLayers[patchPointI] = 0;
patchDisp[patchPointI] = vector::zero;
return true;
}
else if (extrudeStatus[patchPointI] == EXTRUDEREMOVE)
{
extrudeStatus[patchPointI] = NOEXTRUDE;
patchNLayers[patchPointI] = 0;
patchDisp[patchPointI] = vector::zero;
return true;
}
else
{
return false;
}
}
// Unset extrusion on face. Returns true if anything unset.
bool Foam::autoLayerDriver::unmarkExtrusion
(
const face& localFace,
pointField& patchDisp,
labelList& patchNLayers,
List<extrudeMode>& extrudeStatus
)
{
bool unextruded = false;
forAll(localFace, fp)
{
if
(
unmarkExtrusion
(
localFace[fp],
patchDisp,
patchNLayers,
extrudeStatus
)
)
{
unextruded = true;
}
}
return unextruded;
}
// No extrusion at non-manifold points.
void Foam::autoLayerDriver::handleNonManifolds
(
const indirectPrimitivePatch& pp,
const labelList& meshEdges,
pointField& patchDisp,
labelList& patchNLayers,
List<extrudeMode>& extrudeStatus
) const
{
const fvMesh& mesh = meshRefiner_.mesh();
Info<< nl << "Handling non-manifold points ..." << endl;
// Detect non-manifold points
Info<< nl << "Checking patch manifoldness ..." << endl;
pointSet nonManifoldPoints(mesh, "nonManifoldPoints", pp.nPoints());
// 1. Local check
checkManifold(pp, nonManifoldPoints);
label nNonManif = returnReduce(nonManifoldPoints.size(), sumOp<label>());
Info<< "Outside of local patch is multiply connected across edges or"
<< " points at " << nNonManif << " points." << endl;
const labelList& meshPoints = pp.meshPoints();
// 2. Parallel check
// For now disable extrusion at any shared edges.
const labelHashSet sharedEdgeSet(mesh.globalData().sharedEdgeLabels());
forAll(pp.edges(), edgeI)
{
if (sharedEdgeSet.found(meshEdges[edgeI]))
{
const edge& e = mesh.edges()[meshEdges[edgeI]];
Pout<< "Disabling extrusion at edge "
<< mesh.points()[e[0]] << mesh.points()[e[1]]
<< " since it is non-manifold across coupled patches."
<< endl;
nonManifoldPoints.insert(e[0]);
nonManifoldPoints.insert(e[1]);
}
}
// 3b. extrusion can produce multiple faces between 2 cells
// across processor boundary
// This occurs when a coupled face shares more than 1 edge with a
// non-coupled boundary face.
// This is now correctly handled by addPatchCellLayer in that it
// extrudes a single face from the stringed up edges.
nNonManif = returnReduce(nonManifoldPoints.size(), sumOp<label>());
if (nNonManif > 0)
{
Info<< "Outside of patches is multiply connected across edges or"
<< " points at " << nNonManif << " points." << nl
<< "Writing " << nNonManif
<< " points where this happens to pointSet "
<< nonManifoldPoints.name() << nl
<< "and setting layer thickness to zero on these points."
<< endl;
nonManifoldPoints.write();
forAll(meshPoints, patchPointI)
{
if (nonManifoldPoints.found(meshPoints[patchPointI]))
{
unmarkExtrusion
(
patchPointI,
patchDisp,
patchNLayers,
extrudeStatus
);
}
}
}
Info<< "Set displacement to zero for all " << nNonManif
<< " non-manifold points" << endl;
}
// Parallel feature edge detection. Assumes non-manifold edges already handled.
void Foam::autoLayerDriver::handleFeatureAngle
(
const indirectPrimitivePatch& pp,
const labelList& meshEdges,
const scalar minCos,
pointField& patchDisp,
labelList& patchNLayers,
List<extrudeMode>& extrudeStatus
) const
{
const fvMesh& mesh = meshRefiner_.mesh();
Info<< nl << "Handling feature edges ..." << endl;
if (minCos < 1-SMALL)
{
// Normal component of normals of connected faces.
vectorField edgeNormal(mesh.nEdges(), wallPoint::greatPoint);
const labelListList& edgeFaces = pp.edgeFaces();
forAll(edgeFaces, edgeI)
{
const labelList& eFaces = pp.edgeFaces()[edgeI];
label meshEdgeI = meshEdges[edgeI];
forAll(eFaces, i)
{
nomalsCombine()
(
edgeNormal[meshEdgeI],
pp.faceNormals()[eFaces[i]]
);
}
}
syncTools::syncEdgeList
(
mesh,
edgeNormal,
nomalsCombine(),
wallPoint::greatPoint, // null value
false // no separation
);
label vertI = 0;
autoPtr<OFstream> str;
if (debug)
{
str.reset(new OFstream(mesh.time().path()/"featureEdges.obj"));
Info<< "Writing feature edges to " << str().name() << endl;
}
label nFeats = 0;
// Now on coupled edges the edgeNormal will have been truncated and
// only be still be the old value where two faces have the same normal
forAll(edgeFaces, edgeI)
{
const labelList& eFaces = pp.edgeFaces()[edgeI];
label meshEdgeI = meshEdges[edgeI];
const vector& n = edgeNormal[meshEdgeI];
if (n != wallPoint::greatPoint)
{
scalar cos = n & pp.faceNormals()[eFaces[0]];
if (cos < minCos)
{
const edge& e = pp.edges()[edgeI];
unmarkExtrusion
(
e[0],
patchDisp,
patchNLayers,
extrudeStatus
);
unmarkExtrusion
(
e[1],
patchDisp,
patchNLayers,
extrudeStatus
);
nFeats++;
if (str.valid())
{
meshTools::writeOBJ(str(), pp.localPoints()[e[0]]);
vertI++;
meshTools::writeOBJ(str(), pp.localPoints()[e[1]]);
vertI++;
str()<< "l " << vertI-1 << ' ' << vertI << nl;
}
}
}
}
Info<< "Set displacement to zero for points on "
<< returnReduce(nFeats, sumOp<label>())
<< " feature edges" << endl;
}
}
// No extrusion on cells with warped faces. Calculates the thickness of the
// layer and compares it to the space the warped face takes up. Disables
// extrusion if layer thickness is more than faceRatio of the thickness of
// the face.
void Foam::autoLayerDriver::handleWarpedFaces
(
const indirectPrimitivePatch& pp,
const scalar faceRatio,
const scalar edge0Len,
const labelList& cellLevel,
pointField& patchDisp,
labelList& patchNLayers,
List<extrudeMode>& extrudeStatus
) const
{
const fvMesh& mesh = meshRefiner_.mesh();
Info<< nl << "Handling cells with warped patch faces ..." << nl;
const pointField& points = mesh.points();
label nWarpedFaces = 0;
forAll(pp, i)
{
const face& f = pp[i];
if (f.size() > 3)
{
label faceI = pp.addressing()[i];
label ownLevel = cellLevel[mesh.faceOwner()[faceI]];
scalar edgeLen = edge0Len/(1<<ownLevel);
// Normal distance to face centre plane
const point& fc = mesh.faceCentres()[faceI];
const vector& fn = pp.faceNormals()[i];
scalarField vProj(f.size());
forAll(f, fp)
{
vector n = points[f[fp]] - fc;
vProj[fp] = (n & fn);
}
// Get normal 'span' of face
scalar minVal = min(vProj);
scalar maxVal = max(vProj);
if ((maxVal - minVal) > faceRatio * edgeLen)
{
if
(
unmarkExtrusion
(
pp.localFaces()[i],
patchDisp,
patchNLayers,
extrudeStatus
)
)
{
nWarpedFaces++;
}
}
}
}
Info<< "Set displacement to zero on "
<< returnReduce(nWarpedFaces, sumOp<label>())
<< " warped faces since layer would be > " << faceRatio
<< " of the size of the bounding box." << endl;
}
//// No extrusion on cells with multiple patch faces. There ususally is a reason
//// why combinePatchFaces hasn't succeeded.
//void Foam::autoLayerDriver::handleMultiplePatchFaces
//(
// const indirectPrimitivePatch& pp,
// pointField& patchDisp,
// labelList& patchNLayers,
// List<extrudeMode>& extrudeStatus
//) const
//{
// const fvMesh& mesh = meshRefiner_.mesh();
//
// Info<< nl << "Handling cells with multiple patch faces ..." << nl;
//
// const labelListList& pointFaces = pp.pointFaces();
//
// // Cells that should not get an extrusion layer
// cellSet multiPatchCells(mesh, "multiPatchCells", pp.size());
//
// // Detect points that use multiple faces on same cell.
// forAll(pointFaces, patchPointI)
// {
// const labelList& pFaces = pointFaces[patchPointI];
//
// labelHashSet pointCells(pFaces.size());
//
// forAll(pFaces, i)
// {
// label cellI = mesh.faceOwner()[pp.addressing()[pFaces[i]]];
//
// if (!pointCells.insert(cellI))
// {
// // Second or more occurrence of cell so cell has two or more
// // pp faces connected to this point.
// multiPatchCells.insert(cellI);
// }
// }
// }
//
// label nMultiPatchCells = returnReduce
// (
// multiPatchCells.size(),
// sumOp<label>()
// );
//
// Info<< "Detected " << nMultiPatchCells
// << " cells with multiple (connected) patch faces." << endl;
//
// label nChanged = 0;
//
// if (nMultiPatchCells > 0)
// {
// Info<< "Writing " << nMultiPatchCells
// << " cells with multiple (connected) patch faces to cellSet "
// << multiPatchCells.objectPath() << endl;
// multiPatchCells.write();
//
//
// // Go through all points and remove extrusion on any cell in
// // multiPatchCells
// // (has to be done in separate loop since having one point on
// // multipatches has to reset extrusion on all points of cell)
//
// forAll(pointFaces, patchPointI)
// {
// if (extrudeStatus[patchPointI] != NOEXTRUDE)
// {
// const labelList& pFaces = pointFaces[patchPointI];
//
// forAll(pFaces, i)
// {
// label cellI =
// mesh.faceOwner()[pp.addressing()[pFaces[i]]];
//
// if (multiPatchCells.found(cellI))
// {
// if
// (
// unmarkExtrusion
// (
// patchPointI,
// patchDisp,
// patchNLayers,
// extrudeStatus
// )
// )
// {
// nChanged++;
// }
// }
// }
// }
// }
//
// reduce(nChanged, sumOp<label>());
// }
//
// Info<< "Prevented extrusion on " << nChanged
// << " points due to multiple patch faces." << nl << endl;
//}
// No extrusion on faces with differing number of layers for points
void Foam::autoLayerDriver::setNumLayers
(
const labelList& patchToNLayers,
const labelList& patchIDs,
const indirectPrimitivePatch& pp,
pointField& patchDisp,
labelList& patchNLayers,
List<extrudeMode>& extrudeStatus
) const
{
const fvMesh& mesh = meshRefiner_.mesh();
Info<< nl << "Handling points with inconsistent layer specification ..."
<< endl;
// Get for every point (really only nessecary on patch external points)
// the max and min of any patch faces using it.
labelList maxLayers(patchNLayers.size(), labelMin);
labelList minLayers(patchNLayers.size(), labelMax);
forAll(patchIDs, i)
{
label patchI = patchIDs[i];
const labelList& meshPoints = mesh.boundaryMesh()[patchI].meshPoints();
label wantedLayers = patchToNLayers[patchI];
forAll(meshPoints, patchPointI)
{
label ppPointI = pp.meshPointMap()[meshPoints[patchPointI]];
maxLayers[ppPointI] = max(wantedLayers, maxLayers[ppPointI]);
minLayers[ppPointI] = min(wantedLayers, minLayers[ppPointI]);
}
}
syncTools::syncPointList
(
mesh,
pp.meshPoints(),
maxLayers,
maxEqOp<label>(),
labelMin, // null value
false // no separation
);
syncTools::syncPointList
(
mesh,
pp.meshPoints(),
minLayers,
minEqOp<label>(),
labelMax, // null value
false // no separation
);
// Unmark any point with different min and max
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//label nConflicts = 0;
forAll(maxLayers, i)
{
if (maxLayers[i] == labelMin || minLayers[i] == labelMax)
{
FatalErrorIn("setNumLayers(..)")
<< "Patchpoint:" << i << " coord:" << pp.localPoints()[i]
<< " maxLayers:" << maxLayers
<< " minLayers:" << minLayers
<< abort(FatalError);
}
else if (maxLayers[i] == minLayers[i])
{
// Ok setting.
patchNLayers[i] = maxLayers[i];
}
else
{
// Inconsistent num layers between patch faces using point
//if
//(
// unmarkExtrusion
// (
// i,
// patchDisp,
// patchNLayers,
// extrudeStatus
// )
//)
//{
// nConflicts++;
//}
patchNLayers[i] = maxLayers[i];
}
}
//reduce(nConflicts, sumOp<label>());
//
//Info<< "Set displacement to zero for " << nConflicts
// << " points due to points being on multiple regions"
// << " with inconsistent nLayers specification." << endl;
}
// Grow no-extrusion layer
void Foam::autoLayerDriver::growNoExtrusion
(
const indirectPrimitivePatch& pp,
pointField& patchDisp,
labelList& patchNLayers,
List<extrudeMode>& extrudeStatus
)
{
Info<< nl << "Growing non-extrusion points by one layer ..." << endl;
List<extrudeMode> grownExtrudeStatus(extrudeStatus);
const faceList& localFaces = pp.localFaces();
label nGrown = 0;
forAll(localFaces, faceI)
{
const face& f = localFaces[faceI];
bool hasSqueeze = false;
forAll(f, fp)
{
if (extrudeStatus[f[fp]] == NOEXTRUDE)
{
hasSqueeze = true;
break;
}
}
if (hasSqueeze)
{
// Squeeze all points of face
forAll(f, fp)
{
if
(
extrudeStatus[f[fp]] == NOEXTRUDE
&& grownExtrudeStatus[f[fp]] != NOEXTRUDE
)
{
grownExtrudeStatus[f[fp]] = NOEXTRUDE;
nGrown++;
}
}
}
}
extrudeStatus.transfer(grownExtrudeStatus);
forAll(extrudeStatus, patchPointI)
{
if (extrudeStatus[patchPointI] == NOEXTRUDE)
{
patchDisp[patchPointI] = vector::zero;
patchNLayers[patchPointI] = 0;
}
}
reduce(nGrown, sumOp<label>());
Info<< "Set displacement to zero for an additional " << nGrown
<< " points." << endl;
}
void Foam::autoLayerDriver::calculateLayerThickness
(
const indirectPrimitivePatch& pp,
const labelList& patchIDs,
const scalarField& patchExpansionRatio,
const bool relativeSizes,
const scalarField& patchFinalLayerThickness,
const scalarField& patchMinThickness,
const labelList& cellLevel,
const labelList& patchNLayers,
const scalar edge0Len,
scalarField& thickness,
scalarField& minThickness,
scalarField& expansionRatio
) const
{
const fvMesh& mesh = meshRefiner_.mesh();
const polyBoundaryMesh& patches = mesh.boundaryMesh();
// Rework patch-wise layer parameters into minimum per point
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Reuse input fields
expansionRatio.setSize(pp.nPoints());
expansionRatio = GREAT;
thickness.setSize(pp.nPoints());
thickness = GREAT;
minThickness.setSize(pp.nPoints());
minThickness = GREAT;
forAll(patchIDs, i)
{
label patchI = patchIDs[i];
const labelList& meshPoints = patches[patchI].meshPoints();
forAll(meshPoints, patchPointI)
{
label ppPointI = pp.meshPointMap()[meshPoints[patchPointI]];
expansionRatio[ppPointI] = min
(
expansionRatio[ppPointI],
patchExpansionRatio[patchI]
);
thickness[ppPointI] = min
(
thickness[ppPointI],
patchFinalLayerThickness[patchI]
);
minThickness[ppPointI] = min
(
minThickness[ppPointI],
patchMinThickness[patchI]
);
}
}
syncTools::syncPointList
(
mesh,
pp.meshPoints(),
expansionRatio,
minEqOp<scalar>(),
GREAT, // null value
false // no separation
);
syncTools::syncPointList
(
mesh,
pp.meshPoints(),
thickness,
minEqOp<scalar>(),
GREAT, // null value
false // no separation
);
syncTools::syncPointList
(
mesh,
pp.meshPoints(),
minThickness,
minEqOp<scalar>(),
GREAT, // null value
false // no separation
);
// Now the thicknesses are set according to the minimum of connected
// patches.
// Rework relative thickness into absolute
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// by multiplying with the internal cell size.
if (relativeSizes)
{
if (min(patchMinThickness) < 0 || max(patchMinThickness) > 2)
{
FatalErrorIn("calculateLayerThickness(..)")
<< "Thickness should be factor of local undistorted cell size."
<< " Valid values are [0..2]." << nl
<< " minThickness:" << patchMinThickness
<< exit(FatalError);
}
// Determine per point the max cell level of connected cells
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
labelList maxPointLevel(pp.nPoints(), labelMin);
forAll(pp, i)
{
label ownLevel = cellLevel[mesh.faceOwner()[pp.addressing()[i]]];
const face& f = pp.localFaces()[i];
forAll(f, fp)
{
maxPointLevel[f[fp]] = max(maxPointLevel[f[fp]], ownLevel);
}
}
syncTools::syncPointList
(
mesh,
pp.meshPoints(),
maxPointLevel,
maxEqOp<label>(),
labelMin, // null value
false // no separation
);
forAll(maxPointLevel, pointI)
{
// Find undistorted edge size for this level.
scalar edgeLen = edge0Len/(1<<maxPointLevel[pointI]);
thickness[pointI] *= edgeLen;
minThickness[pointI] *= edgeLen;
}
}
// Rework thickness (of final layer) into overall thickness of all layers
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
forAll(thickness, pointI)
{
// Calculate layer thickness based on expansion ratio
// and final layer height
if (expansionRatio[pointI] == 1)
{
thickness[pointI] *= patchNLayers[pointI];
}
else
{
scalar invExpansion = 1.0 / expansionRatio[pointI];
label nLay = patchNLayers[pointI];
thickness[pointI] *=
(1.0 - pow(invExpansion, nLay))
/ (1.0 - invExpansion);
}
}
//Info<< "calculateLayerThickness : min:" << gMin(thickness)
// << " max:" << gMax(thickness) << endl;
}
// Synchronize displacement among coupled patches.
void Foam::autoLayerDriver::syncPatchDisplacement
(
const motionSmoother& meshMover,
const scalarField& minThickness,
pointField& patchDisp,
labelList& patchNLayers,
List<extrudeMode>& extrudeStatus
) const
{
const fvMesh& mesh = meshRefiner_.mesh();
const labelList& meshPoints = meshMover.patch().meshPoints();
label nChangedTotal = 0;
while (true)
{
label nChanged = 0;
// Sync displacement (by taking min)
syncTools::syncPointList
(
mesh,
meshPoints,
patchDisp,
minEqOp<vector>(),
wallPoint::greatPoint, // null value
false // no separation
);
// Unmark if displacement too small
forAll(patchDisp, i)
{
if (mag(patchDisp[i]) < minThickness[i])
{
if
(
unmarkExtrusion
(
i,
patchDisp,
patchNLayers,
extrudeStatus
)
)
{
nChanged++;
}
}
}
labelList syncPatchNLayers(patchNLayers);
syncTools::syncPointList
(
mesh,
meshPoints,
syncPatchNLayers,
minEqOp<label>(),
labelMax, // null value
false // no separation
);
// Reset if differs
forAll(syncPatchNLayers, i)
{
if (syncPatchNLayers[i] != patchNLayers[i])
{
if
(
unmarkExtrusion
(
i,
patchDisp,
patchNLayers,
extrudeStatus
)
)
{
nChanged++;
}
}
}
syncTools::syncPointList
(
mesh,
meshPoints,
syncPatchNLayers,
maxEqOp<label>(),
labelMin, // null value
false // no separation
);
// Reset if differs
forAll(syncPatchNLayers, i)
{
if (syncPatchNLayers[i] != patchNLayers[i])
{
if
(
unmarkExtrusion
(
i,
patchDisp,
patchNLayers,
extrudeStatus
)
)
{
nChanged++;
}
}
}
nChangedTotal += nChanged;
if (!returnReduce(nChanged, sumOp<label>()))
{
break;
}
}
Info<< "Prevented extrusion on "
<< returnReduce(nChangedTotal, sumOp<label>())
<< " coupled patch points during syncPatchDisplacement." << endl;
}
// Calculate displacement vector for all patch points. Uses pointNormal.
// Checks that displaced patch point would be visible from all centres
// of the faces using it.
// extrudeStatus is both input and output and gives the status of each
// patch point.
void Foam::autoLayerDriver::getPatchDisplacement
(
const motionSmoother& meshMover,
const scalarField& thickness,
const scalarField& minThickness,
pointField& patchDisp,
labelList& patchNLayers,
List<extrudeMode>& extrudeStatus
) const
{
Info<< nl << "Determining displacement for added points"
<< " according to pointNormal ..." << endl;
const fvMesh& mesh = meshRefiner_.mesh();
const indirectPrimitivePatch& pp = meshMover.patch();
const vectorField& faceNormals = pp.faceNormals();
const labelListList& pointFaces = pp.pointFaces();
const pointField& localPoints = pp.localPoints();
const labelList& meshPoints = pp.meshPoints();
// Determine pointNormal
// ~~~~~~~~~~~~~~~~~~~~~
pointField pointNormals(pp.nPoints(), vector::zero);
{
labelList nPointFaces(pp.nPoints(), 0);
forAll(faceNormals, faceI)
{
const face& f = pp.localFaces()[faceI];
forAll(f, fp)
{
pointNormals[f[fp]] += faceNormals[faceI];
nPointFaces[f[fp]] ++;
}
}
syncTools::syncPointList
(
mesh,
meshPoints,
pointNormals,
plusEqOp<vector>(),
vector::zero, // null value
false // no separation
);
syncTools::syncPointList
(
mesh,
meshPoints,
nPointFaces,
plusEqOp<label>(),
0, // null value
false // no separation
);
forAll(pointNormals, i)
{
pointNormals[i] /= nPointFaces[i];
}
}
// Determine local length scale on patch
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Start off from same thickness everywhere (except where no extrusion)
patchDisp = thickness*pointNormals;
// Check if no extrude possible.
forAll(pointNormals, patchPointI)
{
label meshPointI = pp.meshPoints()[patchPointI];
if (extrudeStatus[patchPointI] == NOEXTRUDE)
{
// Do not use unmarkExtrusion; forcibly set to zero extrusion.
patchNLayers[patchPointI] = 0;
patchDisp[patchPointI] = vector::zero;
}
else
{
// Get normal
const vector& n = pointNormals[patchPointI];
if (!meshTools::visNormal(n, faceNormals, pointFaces[patchPointI]))
{
Pout<< "No valid normal for point " << meshPointI
<< ' ' << pp.points()[meshPointI]
<< "; setting displacement to " << patchDisp[patchPointI]
<< endl;
extrudeStatus[patchPointI] = EXTRUDEREMOVE;
}
}
}
// At illegal points make displacement average of new neighbour positions
forAll(extrudeStatus, patchPointI)
{
if (extrudeStatus[patchPointI] == EXTRUDEREMOVE)
{
point avg(vector::zero);
label nPoints = 0;
const labelList& pEdges = pp.pointEdges()[patchPointI];
forAll(pEdges, i)
{
label edgeI = pEdges[i];
label otherPointI = pp.edges()[edgeI].otherVertex(patchPointI);
if (extrudeStatus[otherPointI] != NOEXTRUDE)
{
avg += localPoints[otherPointI] + patchDisp[otherPointI];
nPoints++;
}
}
if (nPoints > 0)
{
Pout<< "Displacement at illegal point "
<< localPoints[patchPointI]
<< " set to " << (avg / nPoints - localPoints[patchPointI])
<< endl;
patchDisp[patchPointI] =
avg / nPoints
- localPoints[patchPointI];
}
}
}
// Make sure displacement is equal on both sides of coupled patches.
syncPatchDisplacement
(
meshMover,
minThickness,
patchDisp,
patchNLayers,
extrudeStatus
);
Info<< endl;
}
// Truncates displacement
// - for all patchFaces in the faceset displacement gets set to zero
// - all displacement < minThickness gets set to zero
Foam::label Foam::autoLayerDriver::truncateDisplacement
(
const motionSmoother& meshMover,
const scalarField& minThickness,
const faceSet& illegalPatchFaces,
pointField& patchDisp,
labelList& patchNLayers,
List<extrudeMode>& extrudeStatus
) const
{
const polyMesh& mesh = meshMover.mesh();
const indirectPrimitivePatch& pp = meshMover.patch();
label nChanged = 0;
const Map<label>& meshPointMap = pp.meshPointMap();
forAllConstIter(faceSet, illegalPatchFaces, iter)
{
label faceI = iter.key();
if (mesh.isInternalFace(faceI))
{
FatalErrorIn("truncateDisplacement(..)")
<< "Faceset " << illegalPatchFaces.name()
<< " contains internal face " << faceI << nl
<< "It should only contain patch faces" << abort(FatalError);
}
const face& f = mesh.faces()[faceI];
forAll(f, fp)
{
if (meshPointMap.found(f[fp]))
{
label patchPointI = meshPointMap[f[fp]];
if (extrudeStatus[patchPointI] != NOEXTRUDE)
{
unmarkExtrusion
(
patchPointI,
patchDisp,
patchNLayers,
extrudeStatus
);
nChanged++;
}
}
}
}
forAll(patchDisp, patchPointI)
{
if (mag(patchDisp[patchPointI]) < minThickness[patchPointI])
{
if
(
unmarkExtrusion
(
patchPointI,
patchDisp,
patchNLayers,
extrudeStatus
)
)
{
nChanged++;
}
}
else if (extrudeStatus[patchPointI] == NOEXTRUDE)
{
// Make sure displacement is 0. Should already be so but ...
patchDisp[patchPointI] = vector::zero;
patchNLayers[patchPointI] = 0;
}
}
const faceList& localFaces = pp.localFaces();
while (true)
{
syncPatchDisplacement
(
meshMover,
minThickness,
patchDisp,
patchNLayers,
extrudeStatus
);
// Make sure that a face doesn't have two non-consecutive areas
// not extruded (e.g. quad where vertex 0 and 2 are not extruded
// but 1 and 3 are) since this gives topological errors.
label nPinched = 0;
forAll(localFaces, i)
{
const face& localF = localFaces[i];
// Count number of transitions from unsnapped to snapped.
label nTrans = 0;
extrudeMode prevMode = extrudeStatus[localF.prevLabel(0)];
forAll(localF, fp)
{
extrudeMode fpMode = extrudeStatus[localF[fp]];
if (prevMode == NOEXTRUDE && fpMode != NOEXTRUDE)
{
nTrans++;
}
prevMode = fpMode;
}
if (nTrans > 1)
{
// Multiple pinches. Reset whole face as unextruded.
if
(
unmarkExtrusion
(
localF,
patchDisp,
patchNLayers,
extrudeStatus
)
)
{
nPinched++;
nChanged++;
}
}
}
reduce(nPinched, sumOp<label>());
Info<< "truncateDisplacement : Unextruded " << nPinched
<< " faces due to non-consecutive vertices being extruded." << endl;
// Make sure that a face has consistent number of layers for all
// its vertices.
label nDiffering = 0;
//forAll(localFaces, i)
//{
// const face& localF = localFaces[i];
//
// label numLayers = -1;
//
// forAll(localF, fp)
// {
// if (patchNLayers[localF[fp]] > 0)
// {
// if (numLayers == -1)
// {
// numLayers = patchNLayers[localF[fp]];
// }
// else if (numLayers != patchNLayers[localF[fp]])
// {
// // Differing number of layers
// if
// (
// unmarkExtrusion
// (
// localF,
// patchDisp,
// patchNLayers,
// extrudeStatus
// )
// )
// {
// nDiffering++;
// nChanged++;
// }
// break;
// }
// }
// }
//}
//
//reduce(nDiffering, sumOp<label>());
//
//Info<< "truncateDisplacement : Unextruded " << nDiffering
// << " faces due to having differing number of layers." << endl;
if (nPinched+nDiffering == 0)
{
break;
}
}
return nChanged;
}
// Setup layer information (at points and faces) to modify mesh topology in
// regions where layer mesh terminates.
void Foam::autoLayerDriver::setupLayerInfoTruncation
(
const motionSmoother& meshMover,
const labelList& patchNLayers,
const List<extrudeMode>& extrudeStatus,
const label nBufferCellsNoExtrude,
labelList& nPatchPointLayers,
labelList& nPatchFaceLayers
) const
{
Info<< nl << "Setting up information for layer truncation ..." << endl;
const indirectPrimitivePatch& pp = meshMover.patch();
const polyMesh& mesh = meshMover.mesh();
if (nBufferCellsNoExtrude < 0)
{
Info<< nl << "Performing no layer truncation."
<< " nBufferCellsNoExtrude set to less than 0 ..." << endl;
// Face layers if any point get extruded
forAll(pp.localFaces(), patchFaceI)
{
const face& f = pp.localFaces()[patchFaceI];
forAll(f, fp)
{
if (patchNLayers[f[fp]] > 0)
{
nPatchFaceLayers[patchFaceI] = patchNLayers[f[fp]];
break;
}
}
}
nPatchPointLayers = patchNLayers;
}
else
{
// Determine max point layers per face.
labelList maxLevel(pp.size(), 0);
forAll(pp.localFaces(), patchFaceI)
{
const face& f = pp.localFaces()[patchFaceI];
// find patch faces where layer terminates (i.e contains extrude
// and noextrude points).
bool noExtrude = false;
label mLevel = 0;
forAll(f, fp)
{
if (extrudeStatus[f[fp]] == NOEXTRUDE)
{
noExtrude = true;
}
mLevel = max(mLevel, patchNLayers[f[fp]]);
}
if (mLevel > 0)
{
// So one of the points is extruded. Check if all are extruded
// or is a mix.
if (noExtrude)
{
nPatchFaceLayers[patchFaceI] = 1;
maxLevel[patchFaceI] = mLevel;
}
else
{
maxLevel[patchFaceI] = mLevel;
}
}
}
// We have the seed faces (faces with nPatchFaceLayers != maxLevel)
// Now do a meshwave across the patch where we pick up neighbours
// of seed faces.
// Note: quite inefficient. Could probably be coded better.
const labelListList& pointFaces = pp.pointFaces();
label nLevels = gMax(patchNLayers);
// flag neighbouring patch faces with number of layers to grow
for (label ilevel = 1; ilevel < nLevels; ilevel++)
{
label nBuffer;
if (ilevel == 1)
{
nBuffer = nBufferCellsNoExtrude - 1;
}
else
{
nBuffer = nBufferCellsNoExtrude;
}
for (label ibuffer = 0; ibuffer < nBuffer + 1; ibuffer++)
{
labelList tempCounter(nPatchFaceLayers);
boolList foundNeighbour(pp.nPoints(), false);
forAll(pp.meshPoints(), patchPointI)
{
forAll(pointFaces[patchPointI], pointFaceI)
{
label faceI = pointFaces[patchPointI][pointFaceI];
if
(
nPatchFaceLayers[faceI] != -1
&& maxLevel[faceI] > 0
)
{
foundNeighbour[patchPointI] = true;
break;
}
}
}
syncTools::syncPointList
(
mesh,
pp.meshPoints(),
foundNeighbour,
orEqOp<bool>(),
false, // null value
false // no separation
);
forAll(pp.meshPoints(), patchPointI)
{
if (foundNeighbour[patchPointI])
{
forAll(pointFaces[patchPointI], pointFaceI)
{
label faceI = pointFaces[patchPointI][pointFaceI];
if
(
nPatchFaceLayers[faceI] == -1
&& maxLevel[faceI] > 0
&& ilevel < maxLevel[faceI]
)
{
tempCounter[faceI] = ilevel;
}
}
}
}
nPatchFaceLayers = tempCounter;
}
}
forAll(pp.localFaces(), patchFaceI)
{
if (nPatchFaceLayers[patchFaceI] == -1)
{
nPatchFaceLayers[patchFaceI] = maxLevel[patchFaceI];
}
}
forAll(pp.meshPoints(), patchPointI)
{
if (extrudeStatus[patchPointI] != NOEXTRUDE)
{
forAll(pointFaces[patchPointI], pointFaceI)
{
label face = pointFaces[patchPointI][pointFaceI];
nPatchPointLayers[patchPointI] = max
(
nPatchPointLayers[patchPointI],
nPatchFaceLayers[face]
);
}
}
else
{
nPatchPointLayers[patchPointI] = 0;
}
}
syncTools::syncPointList
(
mesh,
pp.meshPoints(),
nPatchPointLayers,
maxEqOp<label>(),
0, // null value
false // no separation
);
}
}
// Does any of the cells use a face from faces?
bool Foam::autoLayerDriver::cellsUseFace
(
const polyMesh& mesh,
const labelList& cellLabels,
const labelHashSet& faces
)
{
forAll(cellLabels, i)
{
const cell& cFaces = mesh.cells()[cellLabels[i]];
forAll(cFaces, cFaceI)
{
if (faces.found(cFaces[cFaceI]))
{
return true;
}
}
}
return false;
}
// Checks the newly added cells and locally unmarks points so they
// will not get extruded next time round. Returns global number of unmarked
// points (0 if all was fine)
Foam::label Foam::autoLayerDriver::checkAndUnmark
(
const addPatchCellLayer& addLayer,
const dictionary& meshQualityDict,
const indirectPrimitivePatch& pp,
const fvMesh& newMesh,
pointField& patchDisp,
labelList& patchNLayers,
List<extrudeMode>& extrudeStatus
)
{
// Check the resulting mesh for errors
Info<< nl << "Checking mesh with layer ..." << endl;
faceSet wrongFaces(newMesh, "wrongFaces", newMesh.nFaces()/1000);
motionSmoother::checkMesh(false, newMesh, meshQualityDict, wrongFaces);
Info<< "Detected " << returnReduce(wrongFaces.size(), sumOp<label>())
<< " illegal faces"
<< " (concave, zero area or negative cell pyramid volume)"
<< endl;
// Undo local extrusion if
// - any of the added cells in error
label nChanged = 0;
// Get all cells in the layer.
labelListList addedCells
(
addPatchCellLayer::addedCells
(
newMesh,
addLayer.layerFaces()
)
);
// Check if any of the faces in error uses any face of an added cell
forAll(addedCells, oldPatchFaceI)
{
// Get the cells (in newMesh labels) per old patch face (in mesh
// labels)
const labelList& fCells = addedCells[oldPatchFaceI];
if (cellsUseFace(newMesh, fCells, wrongFaces))
{
// Unmark points on old mesh
if
(
unmarkExtrusion
(
pp.localFaces()[oldPatchFaceI],
patchDisp,
patchNLayers,
extrudeStatus
)
)
{
nChanged++;
}
}
}
return returnReduce(nChanged, sumOp<label>());
}
//- Count global number of extruded faces
Foam::label Foam::autoLayerDriver::countExtrusion
(
const indirectPrimitivePatch& pp,
const List<extrudeMode>& extrudeStatus
)
{
// Count number of extruded patch faces
label nExtruded = 0;
{
const faceList& localFaces = pp.localFaces();
forAll(localFaces, i)
{
const face& localFace = localFaces[i];
forAll(localFace, fp)
{
if (extrudeStatus[localFace[fp]] != NOEXTRUDE)
{
nExtruded++;
break;
}
}
}
}
return returnReduce(nExtruded, sumOp<label>());
}
// Collect layer faces and layer cells into bools for ease of handling
void Foam::autoLayerDriver::getLayerCellsFaces
(
const polyMesh& mesh,
const addPatchCellLayer& addLayer,
boolList& flaggedCells,
boolList& flaggedFaces
)
{
flaggedCells.setSize(mesh.nCells());
flaggedCells = false;
flaggedFaces.setSize(mesh.nFaces());
flaggedFaces = false;
// Mark all faces in the layer
const labelListList& layerFaces = addLayer.layerFaces();
// Mark all cells in the layer.
labelListList addedCells(addPatchCellLayer::addedCells(mesh, layerFaces));
forAll(addedCells, oldPatchFaceI)
{
const labelList& added = addedCells[oldPatchFaceI];
forAll(added, i)
{
flaggedCells[added[i]] = true;
}
}
forAll(layerFaces, oldPatchFaceI)
{
const labelList& layer = layerFaces[oldPatchFaceI];
if (layer.size())
{
for (label i = 1; i < layer.size()-1; i++)
{
flaggedFaces[layer[i]] = true;
}
}
}
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::autoLayerDriver::autoLayerDriver(meshRefinement& meshRefiner)
:
meshRefiner_(meshRefiner)
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
void Foam::autoLayerDriver::mergePatchFacesUndo
(
const layerParameters& layerParams,
const dictionary& motionDict
)
{
scalar minCos = Foam::cos
(
layerParams.featureAngle()
* mathematicalConstant::pi/180.0
);
scalar concaveCos = Foam::cos
(
layerParams.concaveAngle()
* mathematicalConstant::pi/180.0
);
Info<< nl
<< "Merging all faces of a cell" << nl
<< "---------------------------" << nl
<< " - which are on the same patch" << nl
<< " - which make an angle < " << layerParams.featureAngle()
<< " degrees"
<< nl
<< " (cos:" << minCos << ')' << nl
<< " - as long as the resulting face doesn't become concave"
<< " by more than "
<< layerParams.concaveAngle() << " degrees" << nl
<< " (0=straight, 180=fully concave)" << nl
<< endl;
label nChanged = mergePatchFacesUndo(minCos, concaveCos, motionDict);
nChanged += mergeEdgesUndo(minCos, motionDict);
}
void Foam::autoLayerDriver::addLayers
(
const layerParameters& layerParams,
const dictionary& motionDict,
const label nAllowableErrors,
motionSmoother& meshMover,
decompositionMethod& decomposer,
fvMeshDistribute& distributor
)
{
fvMesh& mesh = meshRefiner_.mesh();
const indirectPrimitivePatch& pp = meshMover.patch();
const labelList& meshPoints = pp.meshPoints();
// Precalculate mesh edge labels for patch edges
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
labelList meshEdges(pp.nEdges());
forAll(pp.edges(), edgeI)
{
const edge& ppEdge = pp.edges()[edgeI];
label v0 = meshPoints[ppEdge[0]];
label v1 = meshPoints[ppEdge[1]];
meshEdges[edgeI] = meshTools::findEdge
(
mesh.edges(),
mesh.pointEdges()[v0],
v0,
v1
);
}
// Displacement for all pp.localPoints.
vectorField patchDisp(pp.nPoints(), vector::one);
// Number of layers for all pp.localPoints. Note: only valid if
// extrudeStatus = EXTRUDE.
labelList patchNLayers(pp.nPoints(), 0);
// Whether to add edge for all pp.localPoints.
List<extrudeMode> extrudeStatus(pp.nPoints(), EXTRUDE);
// Get number of layer per point from number of layers per patch
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
setNumLayers
(
layerParams.numLayers(), // per patch the num layers
meshMover.adaptPatchIDs(), // patches that are being moved
pp, // indirectpatch for all faces moving
patchDisp,
patchNLayers,
extrudeStatus
);
// Disable extrusion on non-manifold points
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
handleNonManifolds
(
pp,
meshEdges,
patchDisp,
patchNLayers,
extrudeStatus
);
// Disable extrusion on feature angles
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
handleFeatureAngle
(
pp,
meshEdges,
layerParams.featureAngle()*mathematicalConstant::pi/180.0,
patchDisp,
patchNLayers,
extrudeStatus
);
// Disable extrusion on warped faces
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Undistorted edge length
const scalar edge0Len = meshRefiner_.meshCutter().level0EdgeLength();
const labelList& cellLevel = meshRefiner_.meshCutter().cellLevel();
handleWarpedFaces
(
pp,
layerParams.maxFaceThicknessRatio(),
edge0Len,
cellLevel,
patchDisp,
patchNLayers,
extrudeStatus
);
//// Disable extrusion on cells with multiple patch faces
//// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//handleMultiplePatchFaces
//(
// pp,
//
// patchDisp,
// patchNLayers,
// extrudeStatus
//);
// Grow out region of non-extrusion
for (label i = 0; i < layerParams.nGrow(); i++)
{
growNoExtrusion
(
pp,
patchDisp,
patchNLayers,
extrudeStatus
);
}
// Determine (wanted) point-wise layer thickness and expansion ratio
scalarField thickness(pp.nPoints());
scalarField minThickness(pp.nPoints());
scalarField expansionRatio(pp.nPoints());
calculateLayerThickness
(
pp,
meshMover.adaptPatchIDs(),
layerParams.expansionRatio(),
layerParams.relativeSizes(), // thickness relative to cellsize?
layerParams.finalLayerThickness(), // wanted thicknes
layerParams.minThickness(), // minimum thickness
cellLevel,
patchNLayers,
edge0Len,
thickness,
minThickness,
expansionRatio
);
// Print a bit
{
const polyBoundaryMesh& patches = mesh.boundaryMesh();
// Find maximum length of a patch name, for a nicer output
label maxPatchNameLen = 0;
forAll(meshMover.adaptPatchIDs(), i)
{
label patchI = meshMover.adaptPatchIDs()[i];
word patchName = patches[patchI].name();
maxPatchNameLen = max(maxPatchNameLen,label(patchName.size()));
}
Info<< nl
<< setf(ios_base::left) << setw(maxPatchNameLen) << "patch"
<< setw(0) << " faces layers avg thickness[m]" << nl
<< setf(ios_base::left) << setw(maxPatchNameLen) << " "
<< setw(0) << " near-wall overall" << nl
<< setf(ios_base::left) << setw(maxPatchNameLen) << "-----"
<< setw(0) << " ----- ------ --------- -------" << endl;
forAll(meshMover.adaptPatchIDs(), i)
{
label patchI = meshMover.adaptPatchIDs()[i];
const labelList& meshPoints = patches[patchI].meshPoints();
//scalar maxThickness = -VGREAT;
//scalar minThickness = VGREAT;
scalar sumThickness = 0;
scalar sumNearWallThickness = 0;
forAll(meshPoints, patchPointI)
{
label ppPointI = pp.meshPointMap()[meshPoints[patchPointI]];
//maxThickness = max(maxThickness, thickness[ppPointI]);
//minThickness = min(minThickness, thickness[ppPointI]);
sumThickness += thickness[ppPointI];
label nLay = patchNLayers[ppPointI];
if (nLay > 0)
{
if (expansionRatio[ppPointI] == 1)
{
sumNearWallThickness += thickness[ppPointI]/nLay;
}
else
{
scalar s =
(1.0-pow(expansionRatio[ppPointI], nLay))
/ (1.0-expansionRatio[ppPointI]);
sumNearWallThickness += thickness[ppPointI]/s;
}
}
}
label totNPoints = returnReduce(meshPoints.size(), sumOp<label>());
// For empty patches, totNPoints is 0.
scalar avgThickness = 0;
scalar avgNearWallThickness = 0;
if (totNPoints > 0)
{
//reduce(maxThickness, maxOp<scalar>());
//reduce(minThickness, minOp<scalar>());
avgThickness =
returnReduce(sumThickness, sumOp<scalar>())
/ totNPoints;
avgNearWallThickness =
returnReduce(sumNearWallThickness, sumOp<scalar>())
/ totNPoints;
}
Info<< setf(ios_base::left) << setw(maxPatchNameLen)
<< patches[patchI].name() << setprecision(3)
<< " " << setw(8)
<< returnReduce(patches[patchI].size(), sumOp<scalar>())
<< " " << setw(6) << layerParams.numLayers()[patchI]
<< " " << setw(8) << avgNearWallThickness
<< " " << setw(8) << avgThickness
//<< " " << setw(8) << minThickness
//<< " " << setw(8) << maxThickness
<< endl;
}
Info<< endl;
}
// Calculate wall to medial axis distance for smoothing displacement
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pointScalarField pointMedialDist
(
IOobject
(
"pointMedialDist",
meshRefiner_.timeName(),
mesh,
IOobject::NO_READ,
IOobject::NO_WRITE,
false
),
meshMover.pMesh(),
dimensionedScalar("pointMedialDist", dimless, 0.0)
);
pointVectorField dispVec
(
IOobject
(
"dispVec",
meshRefiner_.timeName(),
mesh,
IOobject::NO_READ,
IOobject::NO_WRITE,
false
),
meshMover.pMesh(),
dimensionedVector("dispVec", dimless, vector::zero)
);
pointScalarField medialRatio
(
IOobject
(
"medialRatio",
meshRefiner_.timeName(),
mesh,
IOobject::NO_READ,
IOobject::NO_WRITE,
false
),
meshMover.pMesh(),
dimensionedScalar("medialRatio", dimless, 0.0)
);
// Setup information for medial axis smoothing. Calculates medial axis
// and a smoothed displacement direction.
// - pointMedialDist : distance to medial axis
// - dispVec : normalised direction of nearest displacement
// - medialRatio : ratio of medial distance to wall distance.
// (1 at wall, 0 at medial axis)
medialAxisSmoothingInfo
(
meshMover,
layerParams.nSmoothNormals(),
layerParams.nSmoothSurfaceNormals(),
layerParams.minMedianAxisAngleCos(),
dispVec,
medialRatio,
pointMedialDist
);
// Saved old points
pointField oldPoints(mesh.points());
// Last set of topology changes. (changing mesh clears out directTopoChange)
directTopoChange savedMeshMod(mesh.boundaryMesh().size());
boolList flaggedCells;
boolList flaggedFaces;
for (label iteration = 0; iteration < layerParams.nLayerIter(); iteration++)
{
Info<< nl
<< "Layer addition iteration " << iteration << nl
<< "--------------------------" << endl;
// Unset the extrusion at the pp.
const dictionary& meshQualityDict =
(
iteration < layerParams.nRelaxedIter()
? motionDict
: motionDict.subDict("relaxed")
);
if (iteration >= layerParams.nRelaxedIter())
{
Info<< "Switched to relaxed meshQuality constraints." << endl;
}
// Make sure displacement is equal on both sides of coupled patches.
syncPatchDisplacement
(
meshMover,
minThickness,
patchDisp,
patchNLayers,
extrudeStatus
);
// Displacement acc. to pointnormals
getPatchDisplacement
(
meshMover,
thickness,
minThickness,
patchDisp,
patchNLayers,
extrudeStatus
);
// Shrink mesh by displacement value first.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
{
pointField oldPatchPos(pp.localPoints());
//// Laplacian displacement shrinking.
//shrinkMeshDistance
//(
// debug,
// meshMover,
// -patchDisp, // Shrink in opposite direction of addedPoints
// layerParams.nSmoothDisp(),
// layerParams.nSnap()
//);
// Medial axis based shrinking
shrinkMeshMedialDistance
(
meshMover,
meshQualityDict,
layerParams.nSmoothThickness(),
layerParams.maxThicknessToMedialRatio(),
nAllowableErrors,
layerParams.nSnap(),
layerParams.layerTerminationCos(),
thickness,
minThickness,
dispVec,
medialRatio,
pointMedialDist,
extrudeStatus,
patchDisp,
patchNLayers
);
// Update patchDisp (since not all might have been honoured)
patchDisp = oldPatchPos - pp.localPoints();
}
// Truncate displacements that are too small (this will do internal
// ones, coupled ones have already been truncated by syncPatch)
faceSet dummySet(mesh, "wrongPatchFaces", 0);
truncateDisplacement
(
meshMover,
minThickness,
dummySet,
patchDisp,
patchNLayers,
extrudeStatus
);
// Dump to .obj file for debugging.
if (debug)
{
dumpDisplacement
(
mesh.time().path()/"layer",
pp,
patchDisp,
extrudeStatus
);
const_cast<Time&>(mesh.time())++;
Info<< "Writing shrunk mesh to " << meshRefiner_.timeName() << endl;
// See comment in autoSnapDriver why we should not remove meshPhi
// using mesh.clearPout().
mesh.write();
}
// Mesh topo change engine
directTopoChange meshMod(mesh);
// Grow layer of cells on to patch. Handles zero sized displacement.
addPatchCellLayer addLayer(mesh);
// Determine per point/per face number of layers to extrude. Also
// handles the slow termination of layers when going switching layers
labelList nPatchPointLayers(pp.nPoints(),-1);
labelList nPatchFaceLayers(pp.localFaces().size(),-1);
setupLayerInfoTruncation
(
meshMover,
patchNLayers,
extrudeStatus,
layerParams.nBufferCellsNoExtrude(),
nPatchPointLayers,
nPatchFaceLayers
);
// Calculate displacement for first layer for addPatchLayer.
// (first layer = layer of cells next to the original mesh)
vectorField firstDisp(patchNLayers.size(), vector::zero);
forAll(patchNLayers, i)
{
if (patchNLayers[i] > 0)
{
if (expansionRatio[i] == 1.0)
{
firstDisp[i] = patchDisp[i]/nPatchPointLayers[i];
}
else
{
label nLay = nPatchPointLayers[i];
scalar h =
pow(expansionRatio[i], nLay - 1)
* (1.0 - expansionRatio[i])
/ (1.0 - pow(expansionRatio[i], nLay));
firstDisp[i] = h*patchDisp[i];
}
}
}
scalarField invExpansionRatio = 1.0 / expansionRatio;
// Add topo regardless of whether extrudeStatus is extruderemove.
// Not add layer if patchDisp is zero.
addLayer.setRefinement
(
invExpansionRatio,
pp,
nPatchFaceLayers, // layers per face
nPatchPointLayers, // layers per point
firstDisp, // thickness of layer nearest internal mesh
meshMod
);
if (debug)
{
const_cast<Time&>(mesh.time())++;
}
// Store mesh changes for if mesh is correct.
savedMeshMod = meshMod;
// With the stored topo changes we create a new mesh so we can
// undo if neccesary.
autoPtr<fvMesh> newMeshPtr;
autoPtr<mapPolyMesh> map = meshMod.makeMesh
(
newMeshPtr,
IOobject
(
//mesh.name()+"_layer",
mesh.name(),
static_cast<polyMesh&>(mesh).instance(),
mesh.time(), // register with runTime
static_cast<polyMesh&>(mesh).readOpt(),
static_cast<polyMesh&>(mesh).writeOpt()
), // io params from original mesh but new name
mesh, // original mesh
true // parallel sync
);
fvMesh& newMesh = newMeshPtr();
//?neccesary? Update fields
newMesh.updateMesh(map);
if (meshRefiner_.overwrite())
{
newMesh.setInstance(meshRefiner_.oldInstance());
}
// Update numbering on addLayer:
// - cell/point labels to be newMesh.
// - patchFaces to remain in oldMesh order.
addLayer.updateMesh
(
map,
identity(pp.size()),
identity(pp.nPoints())
);
// Collect layer faces and cells for outside loop.
getLayerCellsFaces
(
newMesh,
addLayer,
flaggedCells,
flaggedFaces
);
if (debug)
{
Info<< "Writing layer mesh to " << meshRefiner_.timeName() << endl;
newMesh.write();
cellSet addedCellSet
(
newMesh,
"addedCells",
labelHashSet(findIndices(flaggedCells, true))
);
Info<< "Writing "
<< returnReduce(addedCellSet.size(), sumOp<label>())
<< " added cells to cellSet "
<< addedCellSet.name() << endl;
addedCellSet.write();
faceSet layerFacesSet
(
newMesh,
"layerFaces",
labelHashSet(findIndices(flaggedCells, true))
);
Info<< "Writing "
<< returnReduce(layerFacesSet.size(), sumOp<label>())
<< " faces inside added layer to faceSet "
<< layerFacesSet.name() << endl;
layerFacesSet.write();
}
label nTotChanged = checkAndUnmark
(
addLayer,
meshQualityDict,
pp,
newMesh,
patchDisp,
patchNLayers,
extrudeStatus
);
Info<< "Extruding " << countExtrusion(pp, extrudeStatus)
<< " out of " << returnReduce(pp.size(), sumOp<label>())
<< " faces. Removed extrusion at " << nTotChanged << " faces."
<< endl;
if (nTotChanged == 0)
{
break;
}
// Reset mesh points and start again
meshMover.movePoints(oldPoints);
meshMover.correct();
Info<< endl;
}
// At this point we have a (shrunk) mesh and a set of topology changes
// which will make a valid mesh with layer. Apply these changes to the
// current mesh.
// Apply the stored topo changes to the current mesh.
autoPtr<mapPolyMesh> map = savedMeshMod.changeMesh(mesh, false);
// Update fields
mesh.updateMesh(map);
// Move mesh (since morphing does not do this)
if (map().hasMotionPoints())
{
mesh.movePoints(map().preMotionPoints());
}
else
{
// Delete mesh volumes.
mesh.clearOut();
}
if (meshRefiner_.overwrite())
{
mesh.setInstance(meshRefiner_.oldInstance());
}
meshRefiner_.updateMesh(map, labelList(0));
// Do final balancing
// ~~~~~~~~~~~~~~~~~~
if (Pstream::parRun())
{
Info<< nl
<< "Doing final balancing" << nl
<< "---------------------" << nl
<< endl;
if (debug)
{
const_cast<Time&>(mesh.time())++;
}
// Balance. No restriction on face zones and baffles.
autoPtr<mapDistributePolyMesh> map = meshRefiner_.balance
(
false,
false,
decomposer,
distributor
);
// Re-distribute flag of layer faces and cells
map().distributeCellData(flaggedCells);
map().distributeFaceData(flaggedFaces);
}
// Write mesh
// ~~~~~~~~~~
cellSet addedCellSet
(
mesh,
"addedCells",
labelHashSet(findIndices(flaggedCells, true))
);
Info<< "Writing "
<< returnReduce(addedCellSet.size(), sumOp<label>())
<< " added cells to cellSet "
<< addedCellSet.name() << endl;
addedCellSet.write();
faceSet layerFacesSet
(
mesh,
"layerFaces",
labelHashSet(findIndices(flaggedFaces, true))
);
Info<< "Writing "
<< returnReduce(layerFacesSet.size(), sumOp<label>())
<< " faces inside added layer to faceSet "
<< layerFacesSet.name() << endl;
layerFacesSet.write();
}
void Foam::autoLayerDriver::doLayers
(
const dictionary& shrinkDict,
const dictionary& motionDict,
const layerParameters& layerParams,
decompositionMethod& decomposer,
fvMeshDistribute& distributor
)
{
fvMesh& mesh = meshRefiner_.mesh();
Info<< nl
<< "Shrinking and layer addition phase" << nl
<< "----------------------------------" << nl
<< endl;
Info<< "Using mesh parameters " << motionDict << nl << endl;
// Merge coplanar boundary faces
mergePatchFacesUndo(layerParams, motionDict);
// Per patch the number of layers (0 if no layer)
const labelList& numLayers = layerParams.numLayers();
// Patches that need to get a layer
DynamicList<label> patchIDs(numLayers.size());
label nFacesWithLayers = 0;
forAll(numLayers, patchI)
{
if (numLayers[patchI] > 0)
{
patchIDs.append(patchI);
nFacesWithLayers += mesh.boundaryMesh()[patchI].size();
}
}
patchIDs.shrink();
if (returnReduce(nFacesWithLayers, sumOp<label>()) == 0)
{
Info<< nl << "No layers to generate ..." << endl;
}
else
{
autoPtr<indirectPrimitivePatch> ppPtr
(
meshRefinement::makePatch
(
mesh,
patchIDs
)
);
indirectPrimitivePatch& pp = ppPtr();
// Construct iterative mesh mover.
Info<< "Constructing mesh displacer ..." << endl;
{
pointMesh pMesh(mesh); // const pointMesh& pMesh = pointMesh::New(mesh);
motionSmoother meshMover
(
mesh,
pp,
patchIDs,
meshRefinement::makeDisplacementField(pMesh, patchIDs),
motionDict
);
// Check that outside of mesh is not multiply connected.
checkMeshManifold();
// Check initial mesh
Info<< "Checking initial mesh ..." << endl;
labelHashSet wrongFaces(mesh.nFaces()/100);
motionSmoother::checkMesh(false, mesh, motionDict, wrongFaces);
const label nInitErrors = returnReduce
(
wrongFaces.size(),
sumOp<label>()
);
Info<< "Detected " << nInitErrors << " illegal faces"
<< " (concave, zero area or negative cell pyramid volume)"
<< endl;
// Do all topo changes
addLayers
(
layerParams,
motionDict,
nInitErrors,
meshMover,
decomposer,
distributor
);
}
}
}
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/openfoam-extend-Core-OpenFOAM-1.5-dev | src/autoMesh/autoHexMesh/autoHexMeshDriver/autoLayerDriver.C | C++ | gpl-2.0 | 91,729 |
<?php
/**
* ChronoCMS version 1.0
* Copyright (c) 2012 ChronoCMS.com, All rights reserved.
* Author: (ChronoCMS.com Team)
* license: Please read LICENSE.txt
* Visit http://www.ChronoCMS.com for regular updates and information.
**/
namespace GCore\Libs;
defined('_JEXEC') or die('Restricted access');
defined("GCORE_SITE") or die;
class Validate {
public static function required($value){
return !is_null($value);
}
public static function not_empty($value){
if(is_array($value)){
return (bool)count($value);
}else{
return (bool)strlen($value);
}
}
public static function is_empty($value){
if(isset($value)){
if(is_array($value)){
return !(bool)count($value);
}else{
return !(bool)strlen($value);
}
}
}
public static function no_spaces($value){
if(strpos($value, ' ') === false){
return true;
}
return false;
}
public static function match($value, $match){
return ($value == $match);
}
public static function regex($value, $regex){
return preg_match($regex, $value);
}
public static function alpha($value){
return preg_match('/^[a-z ._-]+$/i', $value);
}
public static function alphanumeric($value){
return preg_match('/^[a-z0-9 ._-]+$/i', $value);
}
public static function digit($value){
return preg_match('/^[-+]?[0-9]+$/', $value);
}
public static function nodigit($value){
return preg_match('/^[^0-9]+$/', $value);
}
public static function number($value){
return preg_match('/^[-+]?\d*\.?\d+$/', $value);
}
public static function email($value){
return preg_match('/^([a-zA-Z0-9_\.\-\+%])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/', $value);
}
public static function phone($value){
return preg_match('/^\+{0,1}[0-9 \(\)\.\-]+$/', $value);
}
public static function phone_inter($value){
return preg_match('/^\+{0,1}[0-9 \(\)\.\-]+$/', $value);
}
public static function url($value){
return preg_match('/^(http|https|ftp)\:\/\/[a-z0-9\-\.]+\.[a-z]{2,3}(:[a-z0-9]*)?\/?([a-z0-9\-\._\?\,\'\/\\\+&%\$#\=~])*$/i', $value);
}
} | zanderkyle/zandergraphics | administrator/components/com_chronocontact/libs/validate.php | PHP | gpl-2.0 | 2,052 |
/*******************************************************************************
Copyright 2010 Whole Foods Co-op
This file is part of IT CORE.
IT CORE 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.
IT CORE 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
in the file license.txt along with IT CORE; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*********************************************************************************/
/*************************************************************
* SPH_Magellan_Locking
* SerialPortHandler implementation for the magellan scale
*
* Sets up a serial connection in the constructor
*
* Polls for data in Read(), writing responses back to the
* scale as needed and pushing data into the correct
* WebBrowser frame
*
* Sends beep requests to the scale in PageLoaded(Uri) as
* determined by frame #1
*************************************************************/
/* --COMMENTS - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* 27Oct2012 Eric Lee Added Code 39 handling to ParseData()
*/
using System;
using System.IO;
using System.IO.Ports;
using System.Threading;
namespace SPH {
public class SPH_Magellan_Locking : SerialPortHandler {
private bool got_weight;
private Object writeLock = new Object();
public SPH_Magellan_Locking(string p) : base(p){
sp = new SerialPort();
sp.PortName = this.port;
sp.BaudRate = 9600;
sp.DataBits = 7;
sp.StopBits = StopBits.One;
sp.Parity = Parity.Odd;
sp.RtsEnable = true;
sp.Handshake = Handshake.None;
sp.ReadTimeout = 500;
got_weight = false;
sp.Open();
}
private void safeWrite(string msg)
{
lock (writeLock) {
sp.Write(msg);
}
}
override public void HandleMsg(string msg){
if (msg == "errorBeep"){
Beeps(3);
}
else if (msg == "beepTwice"){
Beeps(2);
}
else if (msg == "goodBeep"){
Beeps(1);
}
else if (msg == "twoPairs"){
Thread.Sleep(300);
Beeps(2);
Thread.Sleep(300);
Beeps(2);
}
else if (msg == "rePoll"){
got_weight = false;
safeWrite("S14\r");
}
}
private void Beeps(int num){
int count = 0;
while(count < num){
safeWrite("S334\r");
Thread.Sleep(150);
count++;
}
}
override public void Read()
{
string buffer = "";
if (this.verbose_mode > 0)
System.Console.WriteLine("Reading serial data");
safeWrite("S14\r");
while (SPH_Running) {
try {
int b = sp.ReadByte();
if (b == 13) {
if (this.verbose_mode > 0)
System.Console.WriteLine("RECV FROM SCALE: "+buffer);
buffer = this.ParseData(buffer);
if (buffer != null){
if (this.verbose_mode > 0)
System.Console.WriteLine("PASS TO POS: "+buffer);
this.PushOutput(buffer);
}
buffer = "";
} else {
buffer += ((char)b).ToString();
}
} catch {
Thread.Sleep(100);
}
}
}
private void PushOutput(string s){
/* trying to maintain thread safety between
* two apps in different languages....
*
* 1. Create a new file for each bit of output
* 2. Give each file a unique name (i.e., don't
* overwrite earlier output)
* 3. Generate files in a temporary directory, then
* move the finished files to the output directory
* (i.e., so they aren't read too early)
*/
/*
int ticks = Environment.TickCount;
char sep = System.IO.Path.DirectorySeparatorChar;
while(File.Exists(MAGELLAN_OUTPUT_DIR+sep+ticks))
ticks++;
TextWriter sw = new StreamWriter(MAGELLAN_OUTPUT_DIR+sep+"tmp"+sep+ticks);
sw = TextWriter.Synchronized(sw);
sw.WriteLine(s);
sw.Close();
File.Move(MAGELLAN_OUTPUT_DIR+sep+"tmp"+sep+ticks,
MAGELLAN_OUTPUT_DIR+sep+ticks);
*/
parent.MsgSend(s);
}
private string ParseData(string s){
if (s.Substring(0,3) == "S11")
safeWrite("S14\r");
else if(s.Substring(0,4) == "S141"){
safeWrite("S14\r");
if(got_weight){
got_weight = false;
return "S141";
}
}
else if(s.Substring(0,4) == "S142"){
safeWrite("S11\r");
return "S142";
}
else if(s.Substring(0,4) == "S143"){
safeWrite("S11\r");
got_weight = false;
return "S110000";
}
else if(s.Substring(0,4) == "S144"){
safeWrite("S14\r");
if (!got_weight){
got_weight = true;
return "S11"+s.Substring(4);
}
}
else if(s.Substring(0,4) == "S145"){
safeWrite("S11\r");
return "S145";
}
else if (s.Substring(0,3) == "S14"){
safeWrite("S11\r");
return s;
}
else if (s.Substring(0,4) == "S08A" ||
s.Substring(0,4) == "S08F")
return s.Substring(4);
else if (s.Substring(0,4) == "S08E")
return this.ExpandUPCE(s.Substring(4));
else if (s.Substring(0,4) == "S08R")
return "GS1~"+s.Substring(3);
else if (s.Substring(0,5) == "S08B1")
return s.Substring(5);
else if (s.Substring(0,5) == "S08B3")
return s.Substring(5);
else
return s;
return null;
}
private string ExpandUPCE(string upc){
string lead = upc.Substring(0,upc.Length-1);
string tail = upc.Substring(upc.Length-1);
if (tail == "0" || tail == "1" || tail == "2")
return lead.Substring(0,3)+tail+"0000"+lead.Substring(3);
else if (tail == "3")
return lead.Substring(0,4)+"00000"+lead.Substring(4);
else if (tail == "4")
return lead.Substring(0,5)+"00000"+lead.Substring(5);
else
return lead+"0000"+tail;
}
}
}
| GeorgeStreetCoop/CORE-POS | pos/is4c-nf/scale-drivers/drivers/NewMagellan/SPH_Magellan_Locking.cs | C# | gpl-2.0 | 7,069 |
/*
* Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package openjdk7.com.sun.tools.javac.code;
/**
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public enum BoundKind {
EXTENDS("? extends "),
SUPER("? super "),
UNBOUND("?");
private final String name;
BoundKind(String name) {
this.name = name;
}
public String toString() { return name; }
}
| loverdos/javac-openjdk7 | src/main/java/openjdk7/com/sun/tools/javac/code/BoundKind.java | Java | gpl-2.0 | 1,721 |
/*
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 com.github.smeny.jpc.emulator.execution.opcodes.pm;
import com.github.smeny.jpc.emulator.execution.*;
import com.github.smeny.jpc.emulator.execution.decoder.*;
import com.github.smeny.jpc.emulator.processor.*;
import com.github.smeny.jpc.emulator.processor.fpu64.*;
import static com.github.smeny.jpc.emulator.processor.Processor.*;
public class fxch_ST0_ST2 extends Executable
{
public fxch_ST0_ST2(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
}
public Branch execute(Processor cpu)
{
double tmp = cpu.fpu.ST(0);
cpu.fpu.setST(0, cpu.fpu.ST(2));
cpu.fpu.setST(2, tmp);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | smeny/JPC | src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/pm/fxch_ST0_ST2.java | Java | gpl-2.0 | 1,856 |
/**
* Copyright (c) 2009--2010 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.frontend.action.systems.monitoring;
import com.redhat.rhn.domain.server.Server;
import com.redhat.rhn.frontend.struts.RequestContext;
import com.redhat.rhn.frontend.struts.RhnAction;
import com.redhat.rhn.frontend.taglibs.list.helper.ListHelper;
import com.redhat.rhn.frontend.taglibs.list.helper.Listable;
import com.redhat.rhn.manager.monitoring.MonitoringManager;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* ProbesListSetupAction
* @version $Rev: 59372 $
*/
public class ProbesListSetupAction extends RhnAction implements Listable {
/**
*
* {@inheritDoc}
*/
public ActionForward execute(ActionMapping mapping,
ActionForm formIn,
HttpServletRequest request,
HttpServletResponse response) {
ListHelper helper = new ListHelper(this, request);
helper.execute();
RequestContext requestContext = new RequestContext(request);
Server server = requestContext.lookupAndBindServer();
request.setAttribute("sid", server.getId());
return mapping.findForward("default");
}
/**
*
* {@inheritDoc}
*/
public List getResult(RequestContext rctx) {
Server server = rctx.lookupAndBindServer();
return MonitoringManager.getInstance().
probesForSystem(rctx.getCurrentUser(), server, null);
}
}
| colloquium/spacewalk | java/code/src/com/redhat/rhn/frontend/action/systems/monitoring/ProbesListSetupAction.java | Java | gpl-2.0 | 2,226 |
package com.yh.hr.res.pt.queryhelper;
import com.yh.hr.res.pt.dto.PtReportHistoryDTO;
import com.yh.platform.core.dao.DaoUtil;
import com.yh.platform.core.exception.ServiceException;
import com.yh.platform.core.util.BeanHelper;
import org.apache.commons.collections.CollectionUtils;
import java.util.List;
/**
* 获取报表历史数据
*/
public class PtReportHistoryQueryHelper {
/**
* 查询报表历史
* @param taskOid
* @param reportType
* @return
* @throws ServiceException
*/
public static PtReportHistoryDTO getPtReportHistory(Long taskOid, String reportType) throws ServiceException {
final StringBuffer hBuffer = new StringBuffer("from PtReportHistory pt where 1 =1 ");
hBuffer.append(" and pt.taskOid =" + taskOid);
hBuffer.append(" and pt.reportType ='" + reportType+"'");
List<PtReportHistoryDTO> list = BeanHelper.copyProperties(DaoUtil.find(hBuffer.toString()), PtReportHistoryDTO.class);
if(CollectionUtils.isNotEmpty(list))
{
return list.get(0);
}
return null;
}
} | meijmOrg/Repo-test | freelance-hr-res/src/java/com/yh/hr/res/pt/queryhelper/PtReportHistoryQueryHelper.java | Java | gpl-2.0 | 1,027 |
//
// Copyright (c) 2013 Benjamin Kaufmann
//
// This file is part of Clasp. See http://www.cs.uni-potsdam.de/clasp/
//
// Clasp 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.
//
// Clasp 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 Clasp; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
#if defined(_MSC_VER)
#pragma warning (disable : 4146) // unary minus operator applied to unsigned type, result still unsigned
#pragma warning (disable : 4996) // 'std::_Fill_n' was declared deprecated
#endif
#include <clasp/logic_program.h>
#include <clasp/shared_context.h>
#include <clasp/solver.h>
#include <clasp/minimize_constraint.h>
#include <clasp/util/misc_types.h>
#include <clasp/asp_preprocessor.h>
#include <clasp/clause.h>
#include <clasp/dependency_graph.h>
#include <clasp/parser.h>
#include <stdexcept>
#include <sstream>
#include <climits>
namespace Clasp { namespace Asp {
/////////////////////////////////////////////////////////////////////////////////////////
// class LpStats
/////////////////////////////////////////////////////////////////////////////////////////
void LpStats::reset() {
std::memset(this, 0, sizeof(LpStats));
}
uint32 LpStats::rules() const {
uint32 sum = 0;
for (uint32 i = 0; i != NUM_RULE_TYPES; ++i) { sum += rules_[i].second; }
return sum;
}
void LpStats::accu(const LpStats& o) {
bodies += o.bodies;
atoms += o.atoms;
auxAtoms += o.auxAtoms;
ufsNodes += o.ufsNodes;
if (sccs == PrgNode::noScc || o.sccs == PrgNode::noScc) {
sccs = o.sccs;
nonHcfs = o.nonHcfs;
}
else {
sccs += o.sccs;
nonHcfs+= o.nonHcfs;
}
for (int i = 0; i != sizeof(eqs_)/sizeof(eqs_[0]); ++i) {
eqs_[i] += o.eqs_[i];
}
for (int i = 0; i != sizeof(rules_)/sizeof(rules_[0]); ++i) {
rules_[i].first += o.rules_[i].first;
rules_[i].second += o.rules_[i].second;
}
}
double LpStats::operator[](const char* key) const {
#define RETURN_IF(x) if (std::strcmp(key, #x) == 0) return double(x)
#define MAP_IF(x, A) if (std::strcmp(key, x) == 0) return double( (A) )
RETURN_IF(bodies);
RETURN_IF(atoms);
RETURN_IF(auxAtoms);
RETURN_IF(sccs);
RETURN_IF(nonHcfs);
RETURN_IF(gammas);
RETURN_IF(ufsNodes);
MAP_IF("rules" , rules());
MAP_IF("basicRules" , rules(BASICRULE).first);
MAP_IF("choiceRules" , rules(CHOICERULE).first);
MAP_IF("constraintRules" , rules(CONSTRAINTRULE).first);
MAP_IF("weightRules" , rules(WEIGHTRULE).first);
MAP_IF("disjunctiveRules" , rules(DISJUNCTIVERULE).first);
MAP_IF("optimizeRules" , rules(OPTIMIZERULE).first);
MAP_IF("basicRulesTr" , rules(BASICRULE).second);
MAP_IF("choiceRulesTr" , rules(CHOICERULE).second);
MAP_IF("constraintRulesTr" , rules(CONSTRAINTRULE).second);
MAP_IF("weightRulesTr" , rules(WEIGHTRULE).second);
MAP_IF("disjunctiveRulesTr", rules(DISJUNCTIVERULE).second);
MAP_IF("optimizeRulesTr" , rules(OPTIMIZERULE).second);
MAP_IF("eqs" , eqs());
MAP_IF("atomEqs" , eqs(Var_t::atom_var));
MAP_IF("bodyEqs" , eqs(Var_t::body_var));
MAP_IF("otherEqs" , eqs(Var_t::atom_body_var));
#undef RETURN_IF
return -1.0;
}
const char* LpStats::keys(const char* path) {
if (!path || !*path) {
return "bodies\0atoms\0auxAtoms\0sccs\0nonHcfs\0gammas\0ufsNodes\0rules\0"
"basicRules\0choiceRules\0constraintRules\0weightRules\0disjunctiveRules\0optimizeRules\0"
"basicRulesTr\0choiceRulesTr\0constraintRulesTr\0weightRulesTr\0disjunctiveRulesTr\0optimizeRulesTr\0"
"eqs\0atomEqs\0bodyEqs\0otherEqs\0";
}
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
// class LogicProgram
/////////////////////////////////////////////////////////////////////////////////////////
namespace {
struct LessBodySize {
LessBodySize(const BodyList& bl) : bodies_(&bl) {}
bool operator()(Var b1, Var b2 ) const {
return (*bodies_)[b1]->size() < (*bodies_)[b2]->size()
|| ((*bodies_)[b1]->size() == (*bodies_)[b2]->size() && (*bodies_)[b1]->type() < (*bodies_)[b2]->type());
}
private:
const BodyList* bodies_;
};
// Adds nogoods representing this node to the solver.
template <class NT>
bool toConstraint(NT* node, const LogicProgram& prg, ClauseCreator& c) {
if (node->value() != value_free && !prg.ctx()->addUnary(node->trueLit())) {
return false;
}
return !node->relevant() || node->addConstraints(prg, c);
}
}
LogicProgram::LogicProgram() : nonHcfCfg_(0), minimize_(0), incData_(0) { accu = 0; }
LogicProgram::~LogicProgram() { dispose(true); }
LogicProgram::Incremental::Incremental() : startAtom(1), startAux(1), startScc(0) {}
void LogicProgram::dispose(bool force) {
// remove rules
std::for_each( bodies_.begin(), bodies_.end(), DestroyObject() );
std::for_each( disjunctions_.begin(), disjunctions_.end(), DestroyObject() );
AtomList().swap(sccAtoms_);
BodyList().swap(bodies_);
DisjList().swap(disjunctions_);
bodyIndex_.clear();
disjIndex_.clear();
MinimizeRule* r = minimize_;
while (r) {
MinimizeRule* t = r;
r = r->next_;
delete t;
}
minimize_ = 0;
for (RuleList::size_type i = 0; i != extended_.size(); ++i) {
delete extended_[i];
}
extended_.clear();
VarVec().swap(initialSupp_);
rule_.clear();
if (force) {
std::for_each( atoms_.begin(), atoms_.end(), DeleteObject() );
AtomList().swap(atoms_);
delete incData_;
VarVec().swap(propQ_);
ruleState_.clearAll();
}
else if (incData_) {
// clean up atoms
// reset prop queue
propQ_.assign(1, getFalseId());
uint32 startAux = incData_->startAux;
assert(startAux <= atoms_.size());
// remove rule associations
for (VarVec::size_type i = 1; i != startAux; ++i) {
PrgAtom* a = atoms_[i];
// remove any dangling references
a->clearSupports();
a->clearDeps(PrgAtom::dep_all);
a->setIgnoreScc(false);
if (a->eq() && getEqAtom(i) >= startAux) {
// atom i is equivalent to some aux atom
// make i the new root
PrgAtom* eq = atoms_[getEqAtom(i)];
assert(!eq->eq());
eq->setEq(i);
a->resetId(i, false);
a->setLiteral(eq->literal());
}
if (a->relevant()) {
ValueRep v = a->value();
a->setValue(value_free);
if (!a->frozen()) {
a->resetId(i, false);
if (ctx()->master()->value(a->var()) != value_free) {
v = ctx()->master()->isTrue(a->literal()) ? value_true : value_false;
}
assert(!a->eq() || a->id() < startAux);
}
if (v != value_free) { assignValue(a, v); }
}
else if (!a->eq() && a->value() == value_false) {
a->setEq(getFalseId());
}
}
// delete any introduced aux atoms
// this is safe because aux atoms are never part of the input program
// it is necessary in order to free their ids, i.e. the id of an aux atom
// from step I might be needed for a program atom in step I+1
for (VarVec::size_type i = startAux; i != atoms_.size(); ++i) {
delete atoms_[i];
}
atoms_.erase(atoms_.begin()+startAux, atoms_.end());
}
activeHead_.clear();
activeBody_.reset();
stats.reset();
}
bool LogicProgram::doStartProgram() {
dispose(true);
// atom 0 is always false
atoms_.push_back( new PrgAtom(0, false) );
assignValue(getAtom(0), value_false);
getFalseAtom()->setLiteral(negLit(0));
nonHcfCfg_= 0;
incData_ = 0;
ctx()->symbolTable().clear();
ctx()->symbolTable().startInit();
return true;
}
void LogicProgram::setOptions(const AspOptions& opts) {
opts_ = opts;
if (opts_.suppMod) {
if (opts_.iters != 5 && ctx()) { ctx()->report(warning(Event::subsystem_prepare, "'supp-models' implies 'eq=0'")); }
opts_.noEq();
opts_.noScc();
}
}
bool LogicProgram::doParse(StreamSource& prg) { return DefaultLparseParser(*this).parse(prg); }
bool LogicProgram::doUpdateProgram() {
CLASP_ASSERT_CONTRACT(frozen() || !incData_);
if (!incData_) { incData_ = new Incremental(); }
if (!frozen()) { return true; }
// delete bodies/disjunctions...
dispose(false);
setFrozen(false);
incData_->startAtom = (uint32)atoms_.size();
incData_->startAux = (uint32)atoms_.size();
incData_->update.clear();
incData_->frozen.swap(incData_->update);
ctx()->symbolTable().startInit();
// add supported atoms from previous steps
// {ai | ai in P}.
PrgBody* support = incData_->startAux > 1 ? getBodyFor(activeBody_) : 0;
for (VarVec::size_type i = 1; i != incData_->startAux; ++i) {
PrgAtom* a = atoms_[i];
if (a->relevant() && !a->frozen() && a->value() != value_false) {
a->setIgnoreScc(true);
support->addHead(a, PrgEdge::CHOICE_EDGE);
}
}
return true;
}
bool LogicProgram::doEndProgram() {
if (!frozen() && ctx()->ok()) {
prepareProgram(!opts_.noSCC);
addConstraints();
if (accu) { accu->accu(stats); }
}
return ctx()->ok();
}
bool LogicProgram::clone(SharedContext& oCtx, bool shareSymbols) {
assert(frozen());
if (&oCtx == ctx()) {
return true;
}
oCtx.cloneVars(*ctx(), shareSymbols ? SharedContext::init_share_symbols : SharedContext::init_copy_symbols);
SharedContext* t = ctx();
setCtx(&oCtx);
bool r = addConstraints();
setCtx(t);
return r;
}
void LogicProgram::addMinimize() {
CLASP_ASSERT_CONTRACT(frozen());
if (hasMinimize()) {
if (opts_.iters != 0) { simplifyMinimize(); }
WeightLitVec lits;
for (MinimizeRule* r = minimize_; r; r = r->next_) {
for (WeightLitVec::iterator it = r->lits_.begin(); it != r->lits_.end(); ++it) {
PrgAtom* h = resize(it->first.var()); // checks for eq
lits.push_back(WeightLiteral(it->first.sign() ? ~h->literal() : h->literal(), it->second));
}
addMinRule(lits);
lits.clear();
}
}
}
void LogicProgram::write(std::ostream& os) {
const char* const delimiter = "0";
// first write all minimize rules - revert order!
PodVector<MinimizeRule*>::type mr;
for (MinimizeRule* r = minimize_; r; r = r->next_) {
mr.push_back(r);
}
std::stringstream body;
for (PodVector<MinimizeRule*>::type::reverse_iterator rit = mr.rbegin(); rit != mr.rend(); ++rit) {
MinimizeRule* r = *rit;
transform(*r, activeBody_);
writeBody(activeBody_, body);
os << OPTIMIZERULE << " " << 0 << " " << body.str() << "\n";
body.clear();
body.str("");
}
std::stringstream choice;
uint32 numChoice = 0;
uint32 falseAtom = 0;
bool oldFreeze = frozen();
setFrozen(false);
// write all bodies together with their heads
for (BodyList::iterator it = bodies_.begin(); it != bodies_.end(); ++it) {
PrgBody* b = *it;
if (b->relevant() && (b->hasVar() || b->value() == value_false) && transform(*b, activeBody_)) {
writeBody(activeBody_, body);
if (b->hasHeads() && b->value() != value_false) {
for (PrgBody::head_iterator it = b->heads_begin(); it != b->heads_end(); ++it) {
PrgHead* head = getHead(*it);
if (head->hasVar()) {
if (it->isAtom()) {
if (it->isNormal()) {
os << activeBody_.ruleType() << " " << it->node() << " " << body.str() << "\n";
}
else if (it->isChoice()) {
choice << it->node() << " ";
++numChoice;
}
}
else if (it->isDisj()) {
PrgDisj* d = static_cast<PrgDisj*>(head);
os << DISJUNCTIVERULE << " " << d->size() << " ";
for (PrgDisj::atom_iterator a = d->begin(), aEnd = d->end(); a != aEnd; ++a) {
os << a->node() << " ";
}
os << body.str() << "\n";
}
}
}
if (numChoice) {
os << CHOICERULE << " " << numChoice << " " << choice.str() << body.str() << "\n";
}
}
else if (b->value() == value_false) {
// write integrity constraint
if (falseAtom == 0 && (falseAtom = findLpFalseAtom()) == 0) {
setCompute(falseAtom = newAtom(), false);
}
os << activeBody_.ruleType() << " " << falseAtom << " " << body.str() << "\n";
}
body.clear();
body.str("");
choice.clear(); choice.str(""); numChoice = 0;
}
}
// write eq-atoms, symbol-table and compute statement
std::stringstream bp, bm, symTab;
Literal comp;
SymbolTable::const_iterator sym = ctx()->symbolTable().begin();
for (AtomList::size_type i = 1; i < atoms_.size(); ++i) {
// write the equivalent atoms
if (atoms_[i]->eq()) {
os << "1 " << i << " 1 0 " << getEqAtom(Var(i)) << " \n";
}
if ( (i == falseAtom || atoms_[i]->inUpper()) && atoms_[i]->value() != value_free ) {
std::stringstream& str = atoms_[i]->value() == value_false ? bm : bp;
str << i << "\n";
}
if (sym != ctx()->symbolTable().end() && Var(i) == sym->first) {
if (sym->second.lit != negLit(sentVar) && !sym->second.name.empty()) {
symTab << i << " " << sym->second.name.c_str() << "\n";
}
++sym;
}
}
os << delimiter << "\n";
os << symTab.str();
os << delimiter << "\n";
os << "B+\n" << bp.str() << "0\n"
<< "B-\n" << bm.str() << "0\n1\n";
setFrozen(oldFreeze);
}
/////////////////////////////////////////////////////////////////////////////////////////
// Program mutating functions
/////////////////////////////////////////////////////////////////////////////////////////
#define check_not_frozen() CLASP_ASSERT_CONTRACT_MSG(!frozen(), "Can't update frozen program!")
#define check_modular(x, atomId) (void)( (!!(x)) || (throw RedefinitionError((atomId), this->getAtomName((atomId))), 0))
RedefinitionError::RedefinitionError(unsigned atomId, const char* name) : std::logic_error(clasp_format_error("Program not modular: Redefinition of atom <%u,'%s'>", atomId, name)) {
}
Var LogicProgram::newAtom() {
check_not_frozen();
Var id = static_cast<Var>(atoms_.size());
atoms_.push_back( new PrgAtom(id) );
return id;
}
LogicProgram& LogicProgram::setAtomName(Var atomId, const char* name) {
check_not_frozen();
check_modular(atomId >= startAtom(), atomId);
resize(atomId);
ctx()->symbolTable().addUnique(atomId, name);
return *this;
}
LogicProgram& LogicProgram::setCompute(Var atomId, bool pos) {
resize(atomId);
ValueRep v = pos ? value_weak_true : value_false;
PrgAtom* a = atoms_[atomId];
assert(!a->hasVar() || a->state() != PrgAtom::state_normal);
assignValue(a, v);
return *this;
}
LogicProgram& LogicProgram::freeze(Var atomId, ValueRep value) {
check_not_frozen();
CLASP_ASSERT_CONTRACT_MSG(incData_, "LogicProgram::updateProgram() not called!");
assert(incData_->frozen.empty());
PrgAtom* a = resize(atomId);
if (!a->inFlux() && (a->frozen() || (atomId >= startAtom() && !a->supports()))) {
CLASP_ASSERT_CONTRACT(value == value_false || value == value_true);
if (!a->frozen()) { incData_->update.push_back(atomId); }
a->setState(value == value_false ? PrgAtom::state_freeze : PrgAtom::state_freeze_true);
}
// else: atom is defined or from a previous step - ignore!
return *this;
}
LogicProgram& LogicProgram::unfreeze(Var atomId) {
check_not_frozen();
CLASP_ASSERT_CONTRACT_MSG(incData_, "LogicProgram::updateProgram() not called!");
PrgAtom* a = resize(atomId);
if (!a->inFlux() && (atomId >= startAtom() || a->frozen())) {
if (!a->frozen()) { incData_->update.push_back(atomId); }
a->setState(PrgAtom::state_in_flux);
}
// else: atom is from a previous step - ignore!
return *this;
}
LogicProgram& LogicProgram::addRule(const Rule& r) {
check_not_frozen();
// simplify rule
RuleType t = simplifyRule(r, activeHead_, activeBody_);
if (t != ENDRULE) { // rule is relevant
upRules(t, 1);
if (handleNatively(t, activeBody_)) { // and can be handled natively
addRuleImpl(t, activeHead_, activeBody_);
}
else {
bool aux = transformNoAux(t, activeBody_) == false;
Rule* temp = new Rule();
temp->setType(t);
temp->setBound(activeBody_.bound());
temp->heads.swap(activeHead_);
temp->body.swap(activeBody_.lits);
if (aux) {
// Since rule transformation needs aux atoms, we must
// defer the transformation until all rules were added
// because only then we can safely assign new unique consecutive atom ids.
extended_.push_back(temp);
}
else {
RuleTransform rt;
incTr(t, rt.transformNoAux(*this, *temp));
delete temp;
}
}
}
activeBody_.reset();
return *this;
}
#undef check_not_frozen
/////////////////////////////////////////////////////////////////////////////////////////
// Query functions
/////////////////////////////////////////////////////////////////////////////////////////
Literal LogicProgram::getLiteral(Var atomId) const {
CLASP_ASSERT_CONTRACT_MSG(atomId < atoms_.size(), "Atom out of bounds!");
return getAtom(getEqAtom(atomId))->literal();
}
void LogicProgram::doGetAssumptions(LitVec& out) const {
if (incData_) {
for (VarVec::const_iterator it = incData_->frozen.begin(), end = incData_->frozen.end(); it != end; ++it) {
out.push_back( getAtom(getEqAtom(*it))->assumption() );
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////
// Program definition - private
/////////////////////////////////////////////////////////////////////////////////////////
void LogicProgram::addRuleImpl(RuleType r, const VarVec& heads, BodyInfo& body) {
if (r != OPTIMIZERULE) {
assert(!heads.empty() && (r != DISJUNCTIVERULE || heads.size() > 1));
PrgBody* b = getBodyFor(body);
// only a non-false body can define atoms
if (b->value() != value_false) {
EdgeType t = r != CHOICERULE ? PrgEdge::NORMAL_EDGE : PrgEdge::CHOICE_EDGE;
uint32 headHash = 0;
bool ignoreScc = opts_.noSCC || b->size() == 0;
for (VarVec::const_iterator it = heads.begin(), end = heads.end(); it != end; ++it) {
PrgAtom* a = resize(*it);
if (a->frozen() && a->supports() == 0) { unfreeze(*it); }
check_modular(*it >= startAtom() || a->inFlux() || a->value() == value_false, *it);
if (r != DISJUNCTIVERULE) {
// Note: b->heads may now contain duplicates. They are removed in PrgBody::simplifyHeads.
b->addHead(a, t);
if (ignoreScc) { a->setIgnoreScc(ignoreScc); }
}
else {
headHash += hashId(*it);
ruleState_.addToHead(*it);
}
}
if (r == DISJUNCTIVERULE) {
assert(headHash != 0);
PrgDisj* d = getDisjFor(heads, headHash);
b->addHead(d, t);
}
}
}
else {
CLASP_ASSERT_CONTRACT(heads.empty());
LogicProgram::MinimizeRule* mr = new LogicProgram::MinimizeRule;
mr->lits_ = body.lits;
mr->next_ = minimize_;
minimize_ = mr;
}
}
bool LogicProgram::assignValue(PrgAtom* a, ValueRep v) {
if (a->eq()) { a = getAtom(getEqAtom(a->id())); }
ValueRep old = a->value();
if (old == value_weak_true && v != value_weak_true) old = value_free;
if (!a->assignValue(v)) { setConflict(); return false; }
if (old == value_free) { propQ_.push_back(a->id()); }
return true;
}
bool LogicProgram::assignValue(PrgHead* h, ValueRep v) {
return !h->isAtom() || assignValue(static_cast<PrgAtom*>(h), v);
}
bool LogicProgram::handleNatively(RuleType r, const BodyInfo& body) const {
ExtendedRuleMode m = opts_.erMode;
if (r == BASICRULE || r == OPTIMIZERULE || m == mode_native) {
return true;
}
else if (m == mode_transform_integ || m == mode_transform_scc || m == mode_transform_nhcf) {
return true;
}
else if (m == mode_transform) {
return r == DISJUNCTIVERULE;
}
else if (m == mode_transform_dynamic) {
return (r != CONSTRAINTRULE && r != WEIGHTRULE)
|| transformNoAux(r, body) == false;
}
else if (m == mode_transform_choice) {
return r != CHOICERULE;
}
else if (m == mode_transform_card) {
return r != CONSTRAINTRULE;
}
else if (m == mode_transform_weight) {
return r != CONSTRAINTRULE && r != WEIGHTRULE;
}
assert(false && "unhandled extended rule mode");
return true;
}
bool LogicProgram::transformNoAux(RuleType r, const BodyInfo& body) const {
return r != CHOICERULE && (body.bound() == 1 || (body.size() <= 6 && choose(body.size(), body.bound()) <= 15));
}
void LogicProgram::transformExtended() {
uint32 a = numAtoms();
if (incData_) {
// remember starting position of aux atoms so
// that we can remove them on next incremental step
incData_->startAux = (uint32)atoms_.size();
}
RuleTransform tm;
for (RuleList::size_type i = 0; i != extended_.size(); ++i) {
incTr(extended_[i]->type(), tm.transform(*this, *extended_[i]));
delete extended_[i];
}
extended_.clear();
incTrAux(numAtoms() - a);
}
void LogicProgram::transformIntegrity(uint32 maxAux) {
if (stats.rules(CONSTRAINTRULE).second == 0) { return; }
// find all constraint rules that are integrity constraints
BodyList integrity;
for (uint32 i = 0, end = static_cast<uint32>(bodies_.size()); i != end; ++i) {
PrgBody* b = bodies_[i];
if (b->relevant() && b->type() == BodyInfo::COUNT_BODY && b->value() == value_false) {
integrity.push_back(b);
}
}
if (!integrity.empty() && (integrity.size() == 1 || (atoms_.size()/double(bodies_.size()) > 0.5 && integrity.size() / double(bodies_.size()) < 0.01))) {
uint32 A = static_cast<uint32>(atoms_.size());
// transform integrity constraints
for (BodyList::size_type i = 0; i != integrity.size(); ++i) {
PrgBody* b = integrity[i];
uint32 est = b->bound()*( b->sumW()-b->bound() );
if (est > maxAux) {
// reached limit on aux atoms - stop transformation
break;
}
maxAux -= est;
// transform rule
Rule* r;
extended_.push_back(r = new Rule());
r->setType(CONSTRAINTRULE);
r->setBound(b->bound());
r->addHead(getFalseId());
for (uint32 g = 0; g != b->size(); ++g) {
r->addToBody(b->goal(g).var(), !b->goal(g).sign());
}
setFrozen(false);
transformExtended();
setFrozen(true);
// propagate integrity condition to new rules
propQ_.push_back(getFalseId());
propagate(true);
b->markRemoved();
}
// create vars for new atoms/bodies
for (uint32 i = A; i != atoms_.size(); ++i) {
PrgAtom* a = atoms_[i];
for (PrgAtom::sup_iterator it = a->supps_begin(); it != a->supps_end(); ++it) {
PrgBody* nb = bodies_[it->node()];
assert(nb->value() != value_false);
nb->assignVar(*this);
}
a->assignVar(*this, a->supports() ? *a->supps_begin() : PrgEdge::noEdge());
}
}
}
// replace equivalent atoms in minimize rules
void LogicProgram::simplifyMinimize() {
assert(hasMinimize());
for (LogicProgram::MinimizeRule* r = minimize_; r; r = r->next_) {
for (WeightLitVec::iterator it = r->lits_.begin(); it != r->lits_.end(); ++it) {
it->first = Literal(getEqAtom(it->first.var()), it->first.sign());
}
}
}
void LogicProgram::updateFrozenAtoms() {
if (!incData_) { return; }
assert(incData_->frozen.empty());
activeHead_.clear();
activeBody_.reset();
PrgBody* support = 0;
VarVec::iterator j = incData_->update.begin();
for (VarVec::iterator it = j, end = incData_->update.end(); it != end; ++it) {
Var id = getEqAtom(*it);
PrgAtom* a = getAtom(id);
if (a->inFlux()) {
assert(a->id() == id && a->scc() == PrgNode::noScc && !a->inUpper());
a->setState(PrgAtom::state_normal);
if (id < startAtom()) {
// unfreeze previously frozen atom
a->markSeen(false);
a->markDirty();
*j++ = id; // keep in list so that we can later perform completion
}
}
else if (a->frozen()) {
assert(a->relevant() && a->supports() == 0);
a->resetId(id, false);
if (!support) { support = getBodyFor(activeBody_); }
a->setIgnoreScc(true);
support->addHead(a, PrgEdge::CHOICE_EDGE);
incData_->frozen.push_back(id); // still frozen
}
}
incData_->update.erase(j, incData_->update.end());
}
void LogicProgram::prepareProgram(bool checkSccs) {
assert(!frozen());
transformExtended();
if (opts_.normalize) { /* normalize(); */ assert(false); }
stats.atoms = numAtoms() - (startAtom()-1);
stats.bodies= numBodies();
updateFrozenAtoms();
setFrozen(true);
Preprocessor p;
if (hasConflict() || !propagate(true) || !p.preprocess(*this, opts_.iters != 0 && !opts_.suppMod ? Preprocessor::full_eq : Preprocessor::no_eq, opts_.iters, opts_.dfOrder)) {
setConflict();
return;
}
if (opts_.erMode == mode_transform_integ || opts_.erMode == mode_transform_dynamic) {
transformIntegrity(std::min(uint32(15000), uint32(numAtoms())<<1));
}
addMinimize();
uint32 sccs = 0;
if (checkSccs) {
uint32 startScc = incData_ ? incData_->startScc : 0;
SccChecker c(*this, sccAtoms_, startScc);
sccs = c.sccs();
stats.sccs = (sccs-startScc);
if (incData_) { incData_->startScc = c.sccs(); }
if (!disjunctions_.empty() || (opts_.erMode == mode_transform_scc && sccs)) {
// reset node ids changed by scc checking
for (uint32 i = 0; i != bodies_.size(); ++i) {
if (getBody(i)->relevant()) { getBody(i)->resetId(i, true); }
}
for (uint32 i = 0; i != atoms_.size(); ++i) {
if (getAtom(i)->relevant()) { getAtom(i)->resetId(i, true); }
}
}
}
else { stats.sccs = PrgNode::noScc; }
finalizeDisjunctions(p, sccs);
prepareComponents();
stats.atoms = numAtoms() - (startAtom()-1);
bodyIndex_.clear();
disjIndex_.clear();
}
// replace disjunctions with gamma (shifted) and delta (component-shifted) rules
void LogicProgram::finalizeDisjunctions(Preprocessor& p, uint32 numSccs) {
if (disjunctions_.empty()) { return; }
VarVec head; BodyList supports;
disjIndex_.clear();
SccMap sccMap;
sccMap.resize(numSccs, 0);
enum SccFlag { seen_scc = 1u, is_scc_non_hcf = 128u };
// replace disjunctions with shifted rules and non-hcf-disjunctions
DisjList temp; temp.swap(disjunctions_);
setFrozen(false);
uint32 shifted = 0, added = 0;
stats.nonHcfs = uint32(nonHcfs_.size());
for (uint32 i = 0, end = temp.size(); i != end; ++i) {
PrgDisj* d = temp[i];
Literal dx = d->inUpper() ? d->literal() : negLit(0);
PrgEdge e = PrgEdge::newEdge(i, PrgEdge::CHOICE_EDGE, PrgEdge::DISJ_NODE);
d->resetId(i, true); // id changed during scc checking
// remove from program and
// replace with shifted rules or component-shifted disjunction
head.clear(); supports.clear();
for (PrgDisj::atom_iterator it = d->begin(), end = d->end(); it != end; ++it) {
PrgAtom* at = getAtom(it->node());
at->removeSupport(e);
if (at->inUpper()) {
head.push_back(it->node());
if (at->scc() != PrgNode::noScc) { sccMap[at->scc()] = seen_scc; }
}
}
EdgeVec temp;
d->clearSupports(temp);
for (EdgeVec::iterator it = temp.begin(), end = temp.end(); it != end; ++it) {
PrgBody* b = getBody(it->node());
if (b->relevant() && b->value() != value_false) { supports.push_back(b); }
b->removeHead(d, PrgEdge::NORMAL_EDGE);
}
d->destroy();
// create shortcut for supports to avoid duplications during shifting
Literal supportLit = dx != negLit(0) ? getEqAtomLit(dx, supports, p, sccMap) : dx;
// create shifted rules and split disjunctions into non-hcf components
for (VarVec::iterator hIt = head.begin(), hEnd = head.end(); hIt != hEnd; ++hIt) {
uint32 scc = getAtom(*hIt)->scc();
if (scc == PrgNode::noScc || (sccMap[scc] & seen_scc) != 0) {
if (scc != PrgNode::noScc) { sccMap[scc] &= ~seen_scc; }
else { scc = UINT32_MAX; }
rule_.clear(); rule_.setType(DISJUNCTIVERULE);
rule_.addHead(*hIt);
if (supportLit.var() != 0) { rule_.addToBody(supportLit.var(), !supportLit.sign()); }
else if (supportLit.sign()){ continue; }
for (VarVec::iterator oIt = head.begin(); oIt != hEnd; ++oIt) {
if (oIt != hIt) {
if (getAtom(*oIt)->scc() == scc) { rule_.addHead(*oIt); }
else { rule_.addToBody(*oIt, false); }
}
}
RuleType t = simplifyRule(rule_, activeHead_, activeBody_);
PrgBody* B = t != ENDRULE ? assignBodyFor(activeBody_, PrgEdge::NORMAL_EDGE, true) : 0;
if (!B || B->value() == value_false) { continue; }
if (t == BASICRULE) {
++shifted;
B->addHead(getAtom(activeHead_[0]), PrgEdge::NORMAL_EDGE);
}
else if (t == DISJUNCTIVERULE) {
PrgDisj* x = getDisjFor(activeHead_, 0);
B->addHead(x, PrgEdge::NORMAL_EDGE);
x->assignVar(*this, *x->supps_begin());
x->setInUpper(true);
x->markSeen(true);
++added;
if ((sccMap[scc] & is_scc_non_hcf) == 0) {
sccMap[scc] |= is_scc_non_hcf;
nonHcfs_.add(scc);
}
if (!options().noGamma) {
rule_.setType(BASICRULE);
for (uint32 i = 1; i != rule_.heads.size(); ++i) { rule_.addToBody(rule_.heads[i], false); }
rule_.heads.resize(1);
WeightLitVec::iterator bIt = rule_.body.end();
for (uint32 i = x->size();;) {
t = simplifyRule(rule_, activeHead_, activeBody_);
B = t != ENDRULE ? assignBodyFor(activeBody_, PrgEdge::GAMMA_EDGE, true) : 0;
if (B && B->value() != value_false) { B->addHead(getAtom(activeHead_[0]), PrgEdge::GAMMA_EDGE); ++stats.gammas; }
if (--i == 0) { break; }
Var h = rule_.heads[0];
rule_.heads[0] = (--bIt)->first.var();
*bIt = WeightLiteral(negLit(h), 1);
}
}
}
}
}
}
stats.rules(DISJUNCTIVERULE).second = added;
stats.rules(BASICRULE).second += shifted;
stats.nonHcfs = uint32(nonHcfs_.size()) - stats.nonHcfs;
setFrozen(true);
}
// optionally transform extended rules in sccs
void LogicProgram::prepareComponents() {
int trRec = opts_.erMode == mode_transform_scc;
// HACK: force transformation of extended rules in non-hcf components
// REMOVE this once minimality check supports aggregates
if (!disjunctions_.empty() && trRec != 1) {
trRec = 2;
}
if (trRec != 0) {
BodyList ext;
EdgeVec heads;
for (BodyList::const_iterator it = bodies_.begin(), end = bodies_.end(); it != end; ++it) {
if ((*it)->type() != BodyInfo::NORMAL_BODY && (*it)->hasVar() && (*it)->value() != value_false) {
uint32 scc = (*it)->scc(*this);
if (scc != PrgNode::noScc && (trRec == 1 || nonHcfs_.find(scc))) {
ext.push_back(*it);
}
}
}
if (ext.empty()) { return; }
struct Tr : public RuleTransform::ProgramAdapter {
Tr(LogicProgram* x) : self(x), scc(0) {}
Var newAtom() {
Var x = self->newAtom();
PrgAtom* a = self->getAtom(x);
self->sccAtoms_.push_back(a);
a->setScc(scc);
a->markSeen(true);
atoms.push_back(x);
return x;
}
void addRule(Rule& nr) {
if (self->simplifyRule(nr, self->activeHead_, self->activeBody_) != ENDRULE) {
PrgBody* B = self->assignBodyFor(self->activeBody_, PrgEdge::NORMAL_EDGE, false);
if (B->value() != value_false) {
B->addHead(self->getAtom(self->activeHead_[0]), PrgEdge::NORMAL_EDGE);
}
}
}
LogicProgram* self;
uint32 scc;
VarVec atoms;
} tr(this);
RuleTransform trans;
setFrozen(false);
if (incData_) { incData_->startAux = (uint32)atoms_.size(); }
for (BodyList::const_iterator it = ext.begin(), end = ext.end(); it != end; ++it) {
uint32 scc = (*it)->scc(*this);
rule_.clear();
rule_.setType((*it)->type() == BodyInfo::COUNT_BODY ? CONSTRAINTRULE : WEIGHTRULE);
rule_.setBound((*it)->bound());
tr.scc = scc;
for (uint32 i = 0; i != (*it)->size(); ++i) {
rule_.addToBody((*it)->goal(i).var(), (*it)->goal(i).sign() == false, (*it)->weight(i));
}
heads.assign((*it)->heads_begin(), (*it)->heads_end());
for (EdgeVec::const_iterator hIt = heads.begin(); hIt != heads.end(); ++hIt) {
assert(hIt->isAtom());
if (getAtom(hIt->node())->scc() == scc) {
(*it)->removeHead(getAtom(hIt->node()), hIt->type());
rule_.heads.assign(1, hIt->node());
if (simplifyRule(rule_, activeHead_, activeBody_) != ENDRULE) {
trans.transform(tr, rule_);
}
}
}
}
incTrAux(tr.atoms.size());
while (!tr.atoms.empty()) {
PrgAtom* ax = getAtom(tr.atoms.back());
tr.atoms.pop_back();
if (ax->supports()) {
ax->setInUpper(true);
ax->assignVar(*this, *ax->supps_begin());
}
else { assignValue(ax, value_false); }
}
setFrozen(true);
}
}
// add (completion) nogoods
bool LogicProgram::addConstraints() {
ClauseCreator gc(ctx()->master());
if (options().iters == 0) {
gc.addDefaultFlags(ClauseCreator::clause_force_simplify);
}
ctx()->startAddConstraints();
ctx()->symbolTable().endInit();
CLASP_ASSERT_CONTRACT(ctx()->symbolTable().curBegin() == ctx()->symbolTable().end() || startAtom() <= ctx()->symbolTable().curBegin()->first);
// handle initial conflict, if any
if (!ctx()->ok() || !ctx()->addUnary(getFalseAtom()->trueLit())) {
return false;
}
// add bodies from this step
for (BodyList::const_iterator it = bodies_.begin(); it != bodies_.end(); ++it) {
if (!toConstraint((*it), *this, gc)) { return false; }
}
// add atoms thawed in this step
for (VarIter it = unfreeze_begin(), end = unfreeze_end(); it != end; ++it) {
if (!toConstraint(getAtom(*it), *this, gc)) { return false; }
}
// add atoms from this step and finalize symbol table
typedef SymbolTable::const_iterator symbol_iterator;
const bool freezeAll = incData_ && ctx()->satPrepro.get() != 0;
symbol_iterator sym = ctx()->symbolTable().lower_bound(ctx()->symbolTable().curBegin(), startAtom());
symbol_iterator symEnd = ctx()->symbolTable().end();
Var atomId = startAtom();
for (AtomList::const_iterator it = atoms_.begin()+atomId, end = atoms_.end(); it != end; ++it, ++atomId) {
if (!toConstraint(*it, *this, gc)) { return false; }
if (freezeAll && (*it)->hasVar()) { ctx()->setFrozen((*it)->var(), true); }
if (sym != symEnd && atomId == sym->first) {
sym->second.lit = atoms_[getEqAtom(atomId)]->literal();
++sym;
}
}
if (!sccAtoms_.empty()) {
if (ctx()->sccGraph.get() == 0) {
ctx()->sccGraph = new SharedDependencyGraph(nonHcfCfg_);
}
uint32 oldNodes = ctx()->sccGraph->nodes();
ctx()->sccGraph->addSccs(*this, sccAtoms_, nonHcfs_);
stats.ufsNodes = ctx()->sccGraph->nodes()-oldNodes;
sccAtoms_.clear();
}
return true;
}
#undef check_modular
/////////////////////////////////////////////////////////////////////////////////////////
// misc/helper functions
/////////////////////////////////////////////////////////////////////////////////////////
PrgAtom* LogicProgram::resize(Var atomId) {
while (atoms_.size() <= AtomList::size_type(atomId)) {
newAtom();
}
return atoms_[getEqAtom(atomId)];
}
bool LogicProgram::propagate(bool backprop) {
assert(frozen());
bool oldB = opts_.backprop;
opts_.backprop = backprop;
for (VarVec::size_type i = 0; i != propQ_.size(); ++i) {
PrgAtom* a = getAtom(propQ_[i]);
if (!a->relevant()) { continue; }
if (!a->propagateValue(*this, backprop)) {
setConflict();
return false;
}
if (a->hasVar() && a->id() < startAtom() && !ctx()->addUnary(a->trueLit())) {
setConflict();
return false;
}
}
opts_.backprop = oldB;
propQ_.clear();
return true;
}
// Simplifies the rule's body:
// - removes duplicate literals: {a,b,a} -> {a, b}.
// - checks for contradictions : {a, not a}
// - removes literals with weight 0 : LB [a = 0, b = 2, c = 0, ...] -> LB [b = 2, ...]
// - reduces weights > bound() to bound: 2 [a=1, b=3] -> 2 [a=1, b=2]
// - merges duplicate literals : LB [a=w1, b=w2, a=w3] -> LB [a=w1+w3, b=w2]
// - checks for contradiction, i.e.
// rule body contains both p and not p and both are needed
// - replaces weight constraint with cardinality constraint
// if all body weights are equal
// - replaces weight/cardinality constraint with normal body
// if sumW - minW < bound()
RuleType LogicProgram::simplifyBody(const Rule& r, BodyInfo& info) {
info.reset();
WeightLitVec& sBody= info.lits;
if (r.bodyHasBound() && r.bound() <= 0) {
return BASICRULE;
}
sBody.reserve(r.body.size());
RuleType resType = r.type();
weight_t w = 0;
weight_t BOUND = r.bodyHasBound() ? r.bound() : std::numeric_limits<weight_t>::max();
weight_t bound = r.bodyHasBound() ? r.bound() : static_cast<weight_t>(r.body.size());
uint32 pos = 0;
uint32 hash = 0;
bool dirty = r.bodyHasWeights();
Literal lit;
for (WeightLitVec::const_iterator it = r.body.begin(), bEnd = r.body.end(); it != bEnd; ++it) {
if (it->second == 0) continue; // skip irrelevant lits
CLASP_ASSERT_CONTRACT_MSG(it->second>0, "Positive weight expected!");
PrgAtom* a = resize(it->first.var());
lit = Literal(a->id(), it->first.sign());// replace any eq atoms
w = std::min(it->second, BOUND); // reduce weights to bound
if (a->value() != value_free || !a->relevant()) {
bool vSign = a->value() == value_false || !a->relevant();
if (vSign != lit.sign()) {
// literal is false - drop rule?
if (r.bodyIsSet()) { resType = ENDRULE; break; }
continue;
}
else if (a->value() != value_weak_true && r.type() != OPTIMIZERULE) {
// literal is true - drop from rule
if ((bound -= w) <= 0) {
while (!sBody.empty()) { ruleState_.clear(sBody.back().first.var()); sBody.pop_back(); }
pos = hash = 0;
break;
}
continue;
}
}
if (!ruleState_.inBody(lit)) { // literal not seen yet
ruleState_.addToBody(lit); // add to simplified body
sBody.push_back(WeightLiteral(lit, w));
pos += !lit.sign();
hash+= !lit.sign() ? hashId(lit.var()) : hashId(-lit.var());
}
else if (!r.bodyIsSet()) { // Merge duplicate lits
WeightLiteral& oldLit = info[info.findLit(lit)];
weight_t oldW = oldLit.second;
CLASP_ASSERT_CONTRACT_MSG((INT_MAX-oldW)>= w, "Integer overflow!");
w = std::min(oldW + w, BOUND); // remember new weight
oldLit.second = w;
dirty = true;
if (resType == CONSTRAINTRULE) {
resType = WEIGHTRULE;
}
}
dirty |= ruleState_.inBody(~lit);
}
weight_t minW = 1;
weight_t maxW = 1;
wsum_t realSum = (wsum_t)sBody.size();
wsum_t sumW = (wsum_t)sBody.size();
if (dirty) {
minW = std::numeric_limits<weight_t>::max();
realSum = sumW = 0;
for (WeightLitVec::size_type i = 0; i != sBody.size(); ++i) {
lit = sBody[i].first; w = sBody[i].second;
minW = std::min(minW, w);
maxW = std::max(maxW, w);
sumW+= w;
if (!ruleState_.inBody(~lit)) { realSum += w; }
else if (r.bodyIsSet()) { resType = ENDRULE; break; }
else if (lit.sign()) {
// body contains lit and ~lit: we can achieve at most max(weight(lit), weight(~lit))
realSum += std::max(w, info[info.findLit(~lit)].second);
}
}
if (resType == OPTIMIZERULE) { bound = 0; }
}
if (resType != ENDRULE && r.bodyHasBound()) {
if (bound <= 0) { resType = BASICRULE; bound = 0; }
else if (realSum < bound) { resType = ENDRULE; }
else if ((sumW - minW) < bound) { resType = BASICRULE; bound = (weight_t)sBody.size(); }
else if (minW == maxW) { resType = CONSTRAINTRULE; bound = (bound+(minW-1))/minW; }
}
info.init(resType, bound, hash, pos);
return resType;
}
RuleType LogicProgram::simplifyRule(const Rule& r, VarVec& head, BodyInfo& body) {
RuleType type = simplifyBody(r, body);
head.clear();
if (type != ENDRULE && type != OPTIMIZERULE) {
bool blocked = false, taut = false;
weight_t sum = -1;
for (VarVec::const_iterator it = r.heads.begin(), end = r.heads.end(); it != end; ++it) {
if (!ruleState_.isSet(*it, RuleState::any_flag)) {
head.push_back(*it);
ruleState_.addToHead(*it);
}
else if (!ruleState_.isSet(*it, RuleState::head_flag)) {
weight_t wPos = ruleState_.inBody(posLit(*it)) ? body.weight(posLit(*it)) : 0;
weight_t wNeg = ruleState_.inBody(negLit(*it)) ? body.weight(negLit(*it)) : 0;
if (sum == -1) sum = body.sum();
if ((sum - wPos) < body.bound()) {
taut = (type != CHOICERULE);
}
else if ((sum - wNeg) < body.bound()) {
blocked = (type != CHOICERULE);
}
else {
head.push_back(*it);
ruleState_.addToHead(*it);
}
}
}
for (VarVec::const_iterator it = head.begin(), end = head.end(); it != end; ++it) {
ruleState_.clear(*it);
}
if (blocked && type != DISJUNCTIVERULE) {
head.clear();
head.push_back(0);
}
else if (taut && (type == DISJUNCTIVERULE || head.empty())) {
head.clear();
type = ENDRULE;
}
else if (type == DISJUNCTIVERULE && head.size() == 1) {
type = BASICRULE;
}
else if (head.empty()) {
type = ENDRULE;
}
}
for (WeightLitVec::size_type i = 0; i != body.size(); ++i) {
ruleState_.clear(body[i].first.var());
}
return type;
}
// create new atom aux representing supports, i.e.
// aux == S1 v ... v Sn
Literal LogicProgram::getEqAtomLit(Literal lit, const BodyList& supports, Preprocessor& p, const SccMap& sccMap) {
if (supports.empty() || lit == negLit(0)) { return negLit(0); }
if (supports.size() == 1 && supports[0]->size() < 2) {
return supports[0]->size() == 0 ? posLit(0) : supports[0]->goal(0);
}
if (p.getRootAtom(lit) != varMax) { return posLit(p.getRootAtom(lit)); }
incTrAux(1);
Var auxV = newAtom();
PrgAtom* aux = getAtom(auxV);
uint32 scc = PrgNode::noScc;
aux->setLiteral(lit);
aux->markSeen(true);
p.setRootAtom(aux->literal(), auxV);
for (BodyList::const_iterator sIt = supports.begin(); sIt != supports.end(); ++sIt) {
PrgBody* b = *sIt;
if (b->relevant() && b->value() != value_false) {
for (uint32 g = 0; scc == PrgNode::noScc && g != b->size() && !b->goal(g).sign(); ++g) {
uint32 aScc = getAtom(b->goal(g).var())->scc();
if (aScc != PrgNode::noScc && (sccMap[aScc] & 1u)) { scc = aScc; }
}
b->addHead(aux, PrgEdge::NORMAL_EDGE);
if (b->value() != aux->value()) { assignValue(aux, b->value()); }
aux->setInUpper(true);
}
}
if (!aux->inUpper()) {
aux->setValue(value_false);
return negLit(0);
}
else if (scc != PrgNode::noScc) {
aux->setScc(scc);
sccAtoms_.push_back(aux);
}
return posLit(auxV);
}
PrgBody* LogicProgram::getBodyFor(BodyInfo& body, bool addDeps) {
uint32 bodyId = equalBody(bodyIndex_.equal_range(body.hash), body);
if (bodyId != varMax) {
return getBody(bodyId);
}
// no corresponding body exists, create a new object
bodyId = (uint32)bodies_.size();
PrgBody* b = PrgBody::create(*this, bodyId, body, addDeps);
bodyIndex_.insert(IndexMap::value_type(body.hash, bodyId));
bodies_.push_back(b);
if (b->isSupported()) {
initialSupp_.push_back(bodyId);
}
return b;
}
PrgBody* LogicProgram::assignBodyFor(BodyInfo& body, EdgeType depEdge, bool simpStrong) {
PrgBody* b = getBodyFor(body, depEdge != PrgEdge::GAMMA_EDGE);
if (!b->hasVar() && !b->seen()) {
uint32 eqId;
b->markDirty();
b->simplify(*this, simpStrong, &eqId);
if (eqId != b->id()) {
assert(b->id() == bodies_.size()-1);
removeBody(b, body.hash);
bodies_.pop_back();
if (depEdge != PrgEdge::GAMMA_EDGE) {
for (uint32 i = 0; i != b->size(); ++i) {
getAtom(b->goal(i).var())->removeDep(b->id(), !b->goal(i).sign());
}
}
b->destroy();
b = bodies_[eqId];
}
}
b->markSeen(true);
b->assignVar(*this);
return b;
}
uint32 LogicProgram::equalBody(const IndexRange& range, BodyInfo& body) const {
bool sorted = false;
for (IndexIter it = range.first; it != range.second; ++it) {
PrgBody& o = *bodies_[it->second];
if (o.type() == body.type() && o.size() == body.size() && o.bound() == body.bound() && (body.posSize() == 0u || o.goal(body.posSize()-1).sign() == false)) {
// bodies are structurally equivalent - check if they contain the same literals
if ((o.relevant() || (o.eq() && getBody(o.id())->relevant())) && o.eqLits(body.lits, sorted)) {
assert(o.id() == it->second || o.eq());
return o.id();
}
}
}
return varMax;
}
uint32 LogicProgram::findEqBody(PrgBody* b, uint32 hash) {
LogicProgram::IndexRange eqRange = bodyIndex_.equal_range(hash);
// check for existing body
if (eqRange.first != eqRange.second) {
activeBody_.reset();
WeightLitVec& lits = activeBody_.lits;
uint32 p = 0;
for (uint32 i = 0, end = b->size(); i != end; ++i) {
lits.push_back(WeightLiteral(b->goal(i), b->weight(i)));
p += !lits.back().first.sign();
}
activeBody_.init(b->type(), b->bound(), hash, p);
return equalBody(eqRange, activeBody_);
}
return varMax;
}
PrgDisj* LogicProgram::getDisjFor(const VarVec& heads, uint32 headHash) {
PrgDisj* d = 0;
if (headHash) {
LogicProgram::IndexRange eqRange = disjIndex_.equal_range(headHash);
for (; eqRange.first != eqRange.second; ++eqRange.first) {
PrgDisj& o = *disjunctions_[eqRange.first->second];
if (o.relevant() && o.size() == heads.size() && ruleState_.allMarked(heads, RuleState::head_flag)) {
assert(o.id() == eqRange.first->second);
d = &o;
break;
}
}
for (VarVec::const_iterator it = heads.begin(), end = heads.end(); it != end; ++it) {
ruleState_.clear(*it);
}
}
if (!d) {
// no corresponding disjunction exists, create a new object
// and link it to all atoms
uint32 id = disjunctions_.size();
d = PrgDisj::create(id, heads);
disjunctions_.push_back(d);
PrgEdge edge = PrgEdge::newEdge(id, PrgEdge::CHOICE_EDGE, PrgEdge::DISJ_NODE);
for (VarVec::const_iterator it = heads.begin(), end = heads.end(); it != end; ++it) {
getAtom(*it)->addSupport(edge);
}
if (headHash) {
disjIndex_.insert(IndexMap::value_type(headHash, d->id()));
}
}
return d;
}
// body has changed - update index
uint32 LogicProgram::update(PrgBody* body, uint32 oldHash, uint32 newHash) {
uint32 id = removeBody(body, oldHash);
if (body->relevant()) {
uint32 eqId = findEqBody(body, newHash);
if (eqId == varMax) {
// No equivalent body found.
// Add new entry to index
bodyIndex_.insert(IndexMap::value_type(newHash, id));
}
return eqId;
}
return varMax;
}
// body b has changed - remove old entry from body node index
uint32 LogicProgram::removeBody(PrgBody* b, uint32 hash) {
IndexRange ra = bodyIndex_.equal_range(hash);
uint32 id = b->id();
for (; ra.first != ra.second; ++ra.first) {
if (bodies_[ra.first->second] == b) {
id = ra.first->second;
bodyIndex_.erase(ra.first);
break;
}
}
return id;
}
PrgAtom* LogicProgram::mergeEqAtoms(PrgAtom* a, Var rootId) {
rootId = getEqAtom(rootId);
PrgAtom* root = getAtom(rootId);
assert(!a->eq() && !root->eq());
if (a->ignoreScc()) { root->setIgnoreScc(true); }
if (a->frozen()) { root->setState(std::max(a->state(), root->state())); }
if (!mergeValue(a, root)) { setConflict(); return 0; }
assert(a->value() == root->value() || (root->value() == value_true && a->value() == value_weak_true));
a->setEq(rootId);
incEqs(Var_t::atom_var);
return root;
}
// returns whether posSize(root) <= posSize(body)
bool LogicProgram::positiveLoopSafe(PrgBody* body, PrgBody* root) const {
uint32 i = 0, end = std::min(body->size(), root->size());
while (i != end && body->goal(i).sign() == root->goal(i).sign()) { ++i; }
return i == root->size() || root->goal(i).sign();
}
PrgBody* LogicProgram::mergeEqBodies(PrgBody* b, Var rootId, bool hashEq, bool atomsAssigned) {
rootId = getEqNode(bodies_, rootId);
PrgBody* root = getBody(rootId);
bool bp = options().backprop;
if (b == root) { return root; }
assert(!b->eq() && !root->eq() && (hashEq || b->literal() == root->literal()));
if (!b->simplifyHeads(*this, atomsAssigned) || (b->value() != root->value() && (!mergeValue(b, root) || !root->propagateValue(*this, bp) || !b->propagateValue(*this, bp)))) {
setConflict();
return 0;
}
assert(b->value() == root->value());
if (hashEq || positiveLoopSafe(b, root)) {
b->setLiteral(root->literal());
if (!root->mergeHeads(*this, *b, atomsAssigned, !hashEq)) {
setConflict();
return 0;
}
incEqs(Var_t::body_var);
b->setEq(rootId);
return root;
}
return b;
}
uint32 LogicProgram::findLpFalseAtom() const {
for (VarVec::size_type i = 1; i < atoms_.size(); ++i) {
if (!atoms_[i]->eq() && atoms_[i]->value() == value_false) {
return i;
}
}
return 0;
}
const char* LogicProgram::getAtomName(Var id) const {
if (const SymbolTable::symbol_type* x = ctx()->symbolTable().find(id)) {
return x->name.c_str();
}
return "";
}
VarVec& LogicProgram::getSupportedBodies(bool sorted) {
if (sorted) {
std::stable_sort(initialSupp_.begin(), initialSupp_.end(), LessBodySize(bodies_));
}
return initialSupp_;
}
bool LogicProgram::transform(const PrgBody& body, BodyInfo& out) const {
out.reset();
out.lits.reserve(body.size());
uint32 p = 0, end = body.size();
while (p != end && !body.goal(p).sign()) { ++p; }
uint32 R[2][2] = { {p, end}, {0, p} };
weight_t sw = 0, st = 0;
for (uint32 range = 0; range != 2; ++range) {
for (uint32 x = R[range][0]; x != R[range][1]; ++x) {
WeightLiteral wl(body.goal(x), body.weight(x));
if (getAtom(wl.first.var())->hasVar()) {
sw += wl.second;
out.lits.push_back(wl);
}
else if (wl.first.sign()) {
st += wl.second;
}
}
}
out.init(body.type(), std::max(body.bound() - st, weight_t(0)), 0, p);
return sw >= out.bound();
}
void LogicProgram::transform(const MinimizeRule& body, BodyInfo& out) const {
out.reset();
uint32 pos = 0;
for (WeightLitVec::const_iterator it = body.lits_.begin(), end = body.lits_.end(); it != end; ++it) {
if (it->first.sign() && getAtom(it->first.var())->hasVar()) {
out.lits.push_back(*it);
}
}
for (WeightLitVec::const_iterator it = body.lits_.begin(), end = body.lits_.end(); it != end; ++it) {
if (!it->first.sign() && getAtom(it->first.var())->hasVar()) {
out.lits.push_back(*it);
++pos;
}
}
out.init(BodyInfo::SUM_BODY, -1, 0, pos);
}
void LogicProgram::writeBody(const BodyInfo& body, std::ostream& out) const {
if (body.type() == BodyInfo::SUM_BODY && body.bound() != -1) { out << body.bound() << " "; }
out << body.size() << " ";
out << (body.size() - body.posSize()) << " ";
if (body.type() == BodyInfo::COUNT_BODY) { out << body.bound() << " "; }
for (WeightLitVec::const_iterator it = body.lits.begin(), end = body.lits.end(); it != end; ++it) {
out << it->first.var() << " ";
}
if (body.type() == BodyInfo::SUM_BODY) {
for (WeightLitVec::const_iterator it = body.lits.begin(), end = body.lits.end(); it != end; ++it) {
out << it->second << " ";
}
}
}
} } // end namespace Asp
| utexas-bwi/clasp | libclasp/src/logic_program.cpp | C++ | gpl-2.0 | 50,249 |
/* Cabal - Legacy Game Implementations
*
* Cabal is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
// Based on the ScummVM (GPLv2+) file of the same name
#include "backends/graphics/opengl/opengl-graphics.h"
#include "backends/graphics/opengl/texture.h"
#include "backends/graphics/opengl/debug.h"
#include "backends/graphics/opengl/extensions.h"
#include "common/textconsole.h"
#include "common/translation.h"
#include "common/algorithm.h"
#include "common/file.h"
#ifdef USE_OSD
#include "common/tokenizer.h"
#include "common/rect.h"
#endif
#include "graphics/conversion.h"
#ifdef USE_OSD
#include "graphics/fontman.h"
#include "graphics/font.h"
#endif
namespace OpenGL {
OpenGLGraphicsManager::OpenGLGraphicsManager()
: _currentState(), _oldState(), _transactionMode(kTransactionNone), _screenChangeID(1 << (sizeof(int) * 8 - 2)),
_outputScreenWidth(0), _outputScreenHeight(0), _displayX(0), _displayY(0),
_displayWidth(0), _displayHeight(0), _defaultFormat(), _defaultFormatAlpha(),
_gameScreen(nullptr), _gameScreenShakeOffset(0), _overlay(nullptr),
_overlayVisible(false), _cursor(nullptr),
_cursorX(0), _cursorY(0), _cursorDisplayX(0),_cursorDisplayY(0), _cursorHotspotX(0), _cursorHotspotY(0),
_cursorHotspotXScaled(0), _cursorHotspotYScaled(0), _cursorWidthScaled(0), _cursorHeightScaled(0),
_cursorKeyColor(0), _cursorVisible(false), _cursorDontScale(false), _cursorPaletteEnabled(false),
_forceRedraw(false), _scissorOverride(3)
#ifdef USE_OSD
, _osdAlpha(0), _osdFadeStartTime(0), _osd(nullptr)
#endif
{
memset(_gamePalette, 0, sizeof(_gamePalette));
}
OpenGLGraphicsManager::~OpenGLGraphicsManager() {
delete _gameScreen;
delete _overlay;
delete _cursor;
#ifdef USE_OSD
delete _osd;
#endif
}
bool OpenGLGraphicsManager::hasFeature(OSystem::Feature f) {
switch (f) {
case OSystem::kFeatureAspectRatioCorrection:
case OSystem::kFeatureCursorPalette:
return true;
case OSystem::kFeatureOverlaySupportsAlpha:
return _defaultFormatAlpha.aBits() > 3;
default:
return false;
}
}
void OpenGLGraphicsManager::setFeatureState(OSystem::Feature f, bool enable) {
switch (f) {
case OSystem::kFeatureAspectRatioCorrection:
assert(_transactionMode != kTransactionNone);
_currentState.aspectRatioCorrection = enable;
break;
case OSystem::kFeatureCursorPalette:
_cursorPaletteEnabled = enable;
updateCursorPalette();
break;
default:
break;
}
}
bool OpenGLGraphicsManager::getFeatureState(OSystem::Feature f) {
switch (f) {
case OSystem::kFeatureAspectRatioCorrection:
return _currentState.aspectRatioCorrection;
case OSystem::kFeatureCursorPalette:
return _cursorPaletteEnabled;
default:
return false;
}
}
namespace {
const OSystem::GraphicsMode glGraphicsModes[] = {
{ "opengl_linear", _s("OpenGL"), GFX_LINEAR },
{ "opengl_nearest", _s("OpenGL (No filtering)"), GFX_NEAREST },
{ nullptr, nullptr, 0 }
};
} // End of anonymous namespace
const OSystem::GraphicsMode *OpenGLGraphicsManager::getSupportedGraphicsModes() const {
return glGraphicsModes;
}
int OpenGLGraphicsManager::getDefaultGraphicsMode() const {
return GFX_LINEAR;
}
bool OpenGLGraphicsManager::setGraphicsMode(int mode) {
assert(_transactionMode != kTransactionNone);
switch (mode) {
case GFX_LINEAR:
case GFX_NEAREST:
_currentState.graphicsMode = mode;
if (_gameScreen) {
_gameScreen->enableLinearFiltering(mode == GFX_LINEAR);
}
if (_cursor) {
_cursor->enableLinearFiltering(mode == GFX_LINEAR);
}
return true;
default:
warning("OpenGLGraphicsManager::setGraphicsMode(%d): Unknown graphics mode", mode);
return false;
}
}
int OpenGLGraphicsManager::getGraphicsMode() const {
return _currentState.graphicsMode;
}
Graphics::PixelFormat OpenGLGraphicsManager::getScreenFormat() const {
return _currentState.gameFormat;
}
void OpenGLGraphicsManager::beginGFXTransaction() {
assert(_transactionMode == kTransactionNone);
// Start a transaction.
_oldState = _currentState;
_transactionMode = kTransactionActive;
}
OSystem::TransactionError OpenGLGraphicsManager::endGFXTransaction() {
assert(_transactionMode == kTransactionActive);
uint transactionError = OSystem::kTransactionSuccess;
bool setupNewGameScreen = false;
if ( _oldState.gameWidth != _currentState.gameWidth
|| _oldState.gameHeight != _currentState.gameHeight) {
setupNewGameScreen = true;
}
if (_oldState.gameFormat != _currentState.gameFormat) {
setupNewGameScreen = true;
}
// Check whether the requested format can actually be used.
Common::List<Graphics::PixelFormat> supportedFormats = getSupportedFormats();
// In case the requested format is not usable we will fall back to CLUT8.
if (Common::find(supportedFormats.begin(), supportedFormats.end(), _currentState.gameFormat) == supportedFormats.end()) {
_currentState.gameFormat = Graphics::PixelFormat::createFormatCLUT8();
transactionError |= OSystem::kTransactionFormatNotSupported;
}
do {
uint requestedWidth = _currentState.gameWidth;
uint requestedHeight = _currentState.gameHeight;
const uint desiredAspect = getDesiredGameScreenAspect();
requestedHeight = intToFrac(requestedWidth) / desiredAspect;
if (!loadVideoMode(requestedWidth, requestedHeight, _currentState.gameFormat)
// HACK: This is really nasty but we don't have any guarantees of
// a context existing before, which means we don't know the maximum
// supported texture size before this. Thus, we check whether the
// requested game resolution is supported over here.
|| ( _currentState.gameWidth > (uint)Texture::getMaximumTextureSize()
|| _currentState.gameHeight > (uint)Texture::getMaximumTextureSize())) {
if (_transactionMode == kTransactionActive) {
// Try to setup the old state in case its valid and is
// actually different from the new one.
if (_oldState.valid && _oldState != _currentState) {
// Give some hints on what failed to set up.
if ( _oldState.gameWidth != _currentState.gameWidth
|| _oldState.gameHeight != _currentState.gameHeight) {
transactionError |= OSystem::kTransactionSizeChangeFailed;
}
if (_oldState.gameFormat != _currentState.gameFormat) {
transactionError |= OSystem::kTransactionFormatNotSupported;
}
if (_oldState.aspectRatioCorrection != _currentState.aspectRatioCorrection) {
transactionError |= OSystem::kTransactionAspectRatioFailed;
}
if (_oldState.graphicsMode != _currentState.graphicsMode) {
transactionError |= OSystem::kTransactionModeSwitchFailed;
}
// Roll back to the old state.
_currentState = _oldState;
_transactionMode = kTransactionRollback;
// Try to set up the old state.
continue;
}
}
// DON'T use error(), as this tries to bring up the debug
// console, which WON'T WORK now that we might no have a
// proper screen.
warning("OpenGLGraphicsManager::endGFXTransaction: Could not load any graphics mode!");
g_system->quit();
}
// In case we reach this we have a valid state, yay.
_transactionMode = kTransactionNone;
_currentState.valid = true;
} while (_transactionMode == kTransactionRollback);
if (setupNewGameScreen) {
delete _gameScreen;
_gameScreen = nullptr;
_gameScreen = createTexture(_currentState.gameFormat);
assert(_gameScreen);
if (_gameScreen->hasPalette()) {
_gameScreen->setPalette(0, 256, _gamePalette);
}
_gameScreen->allocate(_currentState.gameWidth, _currentState.gameHeight);
_gameScreen->enableLinearFiltering(_currentState.graphicsMode == GFX_LINEAR);
// We fill the screen to all black or index 0 for CLUT8.
if (_currentState.gameFormat.bytesPerPixel == 1) {
_gameScreen->fill(0);
} else {
_gameScreen->fill(_gameScreen->getSurface()->getFormat().RGBToColor(0, 0, 0));
}
}
// Update our display area and cursor scaling. This makes sure we pick up
// aspect ratio correction and game screen changes correctly.
recalculateDisplayArea();
recalculateCursorScaling();
// Something changed, so update the screen change ID.
++_screenChangeID;
// Since transactionError is a ORd list of TransactionErrors this is
// clearly wrong. But our API is simply broken.
return (OSystem::TransactionError)transactionError;
}
int OpenGLGraphicsManager::getScreenChangeID() const {
return _screenChangeID;
}
void OpenGLGraphicsManager::initSize(uint width, uint height, const Graphics::PixelFormat *format) {
Graphics::PixelFormat requestedFormat;
if (!format) {
requestedFormat = Graphics::PixelFormat::createFormatCLUT8();
} else {
requestedFormat = *format;
}
_currentState.gameFormat = requestedFormat;
_currentState.gameWidth = width;
_currentState.gameHeight = height;
}
int16 OpenGLGraphicsManager::getWidth() {
return _currentState.gameWidth;
}
int16 OpenGLGraphicsManager::getHeight() {
return _currentState.gameHeight;
}
void OpenGLGraphicsManager::copyRectToScreen(const void *buf, int pitch, int x, int y, int w, int h) {
_gameScreen->copyRectToTexture(x, y, w, h, buf, pitch);
}
void OpenGLGraphicsManager::fillScreen(uint32 col) {
// FIXME: This does not conform to the OSystem specs because fillScreen
// is always taking CLUT8 color values and use color indexed mode. This is,
// however, plain odd and probably was a forgotten when we introduced
// RGB support. Thus, we simply do the "sane" thing here and hope OSystem
// gets fixed one day.
_gameScreen->fill(col);
}
void OpenGLGraphicsManager::setShakePos(int shakeOffset) {
if (_gameScreenShakeOffset != shakeOffset) {
_gameScreenShakeOffset = shakeOffset;
_forceRedraw = true;
}
}
void OpenGLGraphicsManager::updateScreen() {
if (!_gameScreen) {
return;
}
// We only update the screen when there actually have been any changes.
if ( !_forceRedraw
&& !_gameScreen->isDirty()
&& !(_overlayVisible && _overlay->isDirty())
&& !(_cursorVisible && _cursor && _cursor->isDirty())
&& _osdAlpha == 0) {
return;
}
_forceRedraw = false;
// Clear the screen buffer.
if (_scissorOverride && !_overlayVisible) {
// In certain cases we need to assure that the whole screen area is
// cleared. For example, when switching from overlay visible to
// invisible, we need to assure that all contents are cleared to
// properly remove all overlay contents.
GLCALL(glDisable(GL_SCISSOR_TEST));
GLCALL(glClear(GL_COLOR_BUFFER_BIT));
GLCALL(glEnable(GL_SCISSOR_TEST));
--_scissorOverride;
} else {
GLCALL(glClear(GL_COLOR_BUFFER_BIT));
}
const GLfloat shakeOffset = _gameScreenShakeOffset * (GLfloat)_displayHeight / _gameScreen->getHeight();
// First step: Draw the (virtual) game screen.
_gameScreen->draw(_displayX, _displayY + shakeOffset, _displayWidth, _displayHeight);
// Second step: Draw the overlay if visible.
if (_overlayVisible) {
_overlay->draw(0, 0, _outputScreenWidth, _outputScreenHeight);
}
// Third step: Draw the cursor if visible.
if (_cursorVisible && _cursor) {
// Adjust game screen shake position, but only when the overlay is not
// visible.
const GLfloat cursorOffset = _overlayVisible ? 0 : shakeOffset;
_cursor->draw(_cursorDisplayX - _cursorHotspotXScaled,
_cursorDisplayY - _cursorHotspotYScaled + cursorOffset,
_cursorWidthScaled, _cursorHeightScaled);
}
#ifdef USE_OSD
// Fourth step: Draw the OSD.
if (_osdAlpha > 0) {
Common::StackLock lock(_osdMutex);
// Update alpha value.
const int diff = g_system->getMillis() - _osdFadeStartTime;
if (diff > 0) {
if (diff >= kOSDFadeOutDuration) {
// Back to full transparency.
_osdAlpha = 0;
} else {
// Do a fade out.
_osdAlpha = kOSDInitialAlpha - diff * kOSDInitialAlpha / kOSDFadeOutDuration;
}
}
// Set the OSD transparency.
GLCALL(glColor4f(1.0f, 1.0f, 1.0f, _osdAlpha / 100.0f));
// Draw the OSD texture.
_osd->draw(0, 0, _outputScreenWidth, _outputScreenHeight);
// Reset color.
GLCALL(glColor4f(1.0f, 1.0f, 1.0f, 1.0f));
}
#endif
refreshScreen();
}
Graphics::Surface *OpenGLGraphicsManager::lockScreen() {
return _gameScreen->getSurface();
}
void OpenGLGraphicsManager::unlockScreen() {
_gameScreen->flagDirty();
}
void OpenGLGraphicsManager::setFocusRectangle(const Common::Rect& rect) {
}
void OpenGLGraphicsManager::clearFocusRectangle() {
}
int16 OpenGLGraphicsManager::getOverlayWidth() {
if (_overlay) {
return _overlay->getWidth();
} else {
return 0;
}
}
int16 OpenGLGraphicsManager::getOverlayHeight() {
if (_overlay) {
return _overlay->getHeight();
} else {
return 0;
}
}
void OpenGLGraphicsManager::showOverlay() {
_overlayVisible = true;
_forceRedraw = true;
// Allow drawing inside full screen area.
GLCALL(glDisable(GL_SCISSOR_TEST));
// Update cursor position.
setMousePosition(_cursorX, _cursorY);
}
void OpenGLGraphicsManager::hideOverlay() {
_overlayVisible = false;
_forceRedraw = true;
// Limit drawing to screen area.
GLCALL(glEnable(GL_SCISSOR_TEST));
_scissorOverride = 3;
// Update cursor position.
setMousePosition(_cursorX, _cursorY);
}
Graphics::PixelFormat OpenGLGraphicsManager::getOverlayFormat() const {
return _overlay->getFormat();
}
void OpenGLGraphicsManager::copyRectToOverlay(const void *buf, int pitch, int x, int y, int w, int h) {
_overlay->copyRectToTexture(x, y, w, h, buf, pitch);
}
void OpenGLGraphicsManager::clearOverlay() {
_overlay->fill(0);
}
void OpenGLGraphicsManager::grabOverlay(void *buf, int pitch) {
const Graphics::Surface *overlayData = _overlay->getSurface();
const byte *src = (const byte *)overlayData->getPixels();
byte *dst = (byte *)buf;
for (uint h = overlayData->getHeight(); h > 0; --h) {
memcpy(dst, src, overlayData->getWidth() * overlayData->getFormat().bytesPerPixel);
dst += pitch;
src += overlayData->getPitch();
}
}
bool OpenGLGraphicsManager::showMouse(bool visible) {
// In case the mouse cursor visibility changed we need to redraw the whole
// screen even when nothing else changed.
if (_cursorVisible != visible) {
_forceRedraw = true;
}
bool last = _cursorVisible;
_cursorVisible = visible;
return last;
}
void OpenGLGraphicsManager::warpMouse(int x, int y) {
int16 currentX = _cursorX;
int16 currentY = _cursorY;
adjustMousePosition(currentX, currentY);
// Check whether the (virtual) coordinate actually changed. If not, then
// simply do nothing. This avoids ugly "jittering" due to the actual
// output screen having a bigger resolution than the virtual coordinates.
if (currentX == x && currentY == y) {
return;
}
// Scale the virtual coordinates into actual physical coordinates.
if (_overlayVisible) {
if (!_overlay) {
return;
}
// It might be confusing that we actually have to handle something
// here when the overlay is visible. This is because for very small
// resolutions we have a minimal overlay size and have to adjust
// for that.
x = (x * _outputScreenWidth) / _overlay->getWidth();
y = (y * _outputScreenHeight) / _overlay->getHeight();
} else {
if (!_gameScreen) {
return;
}
x = (x * _outputScreenWidth) / _gameScreen->getWidth();
y = (y * _outputScreenHeight) / _gameScreen->getHeight();
}
setMousePosition(x, y);
setInternalMousePosition(x, y);
}
namespace {
template<typename DstPixel, typename SrcPixel>
void applyColorKey(DstPixel *dst, const SrcPixel *src, uint w, uint h, uint dstPitch, uint srcPitch, SrcPixel keyColor, DstPixel alphaMask) {
const uint srcAdd = srcPitch - w * sizeof(SrcPixel);
const uint dstAdd = dstPitch - w * sizeof(DstPixel);
while (h-- > 0) {
for (uint x = w; x > 0; --x, ++dst, ++src) {
if (*src == keyColor) {
*dst &= ~alphaMask;
}
}
dst = (DstPixel *)((byte *)dst + dstAdd);
src = (const SrcPixel *)((const byte *)src + srcAdd);
}
}
} // End of anonymous namespace
void OpenGLGraphicsManager::setMouseCursor(const void *buf, uint w, uint h, int hotspotX, int hotspotY, uint32 keycolor, bool dontScale, const Graphics::PixelFormat *format) {
Graphics::PixelFormat inputFormat;
if (format) {
inputFormat = *format;
} else {
inputFormat = Graphics::PixelFormat::createFormatCLUT8();
}
// In case the color format has changed we will need to create the texture.
if (!_cursor || _cursor->getFormat() != inputFormat) {
delete _cursor;
_cursor = nullptr;
GLenum glIntFormat, glFormat, glType;
Graphics::PixelFormat textureFormat;
if (inputFormat.bytesPerPixel == 1 || (inputFormat.aBits() && getGLPixelFormat(inputFormat, glIntFormat, glFormat, glType))) {
// There is two cases when we can use the cursor format directly.
// The first is when it's CLUT8, here color key handling can
// always be applied because we use the alpha channel of
// _defaultFormatAlpha for that.
// The other is when the input format has alpha bits and
// furthermore is directly supported.
textureFormat = inputFormat;
} else {
textureFormat = _defaultFormatAlpha;
}
_cursor = createTexture(textureFormat, true);
assert(_cursor);
_cursor->enableLinearFiltering(_currentState.graphicsMode == GFX_LINEAR);
}
_cursorKeyColor = keycolor;
_cursorHotspotX = hotspotX;
_cursorHotspotY = hotspotY;
_cursorDontScale = dontScale;
_cursor->allocate(w, h);
if (inputFormat.bytesPerPixel == 1) {
// For CLUT8 cursors we can simply copy the input data into the
// texture.
_cursor->copyRectToTexture(0, 0, w, h, buf, w * inputFormat.bytesPerPixel);
} else {
// Otherwise it is a bit more ugly because we have to handle a key
// color properly.
Graphics::Surface *dst = _cursor->getSurface();
const uint srcPitch = w * inputFormat.bytesPerPixel;
// Copy the cursor data to the actual texture surface. This will make
// sure that the data is also converted to the expected format.
Graphics::crossBlit((byte *)dst->getPixels(), (const byte *)buf, dst->getPitch(), srcPitch,
w, h, dst->getFormat(), inputFormat);
// We apply the color key by setting the alpha bits of the pixels to
// fully transparent.
const uint32 aMask = (0xFF >> dst->getFormat().aLoss) << dst->getFormat().aShift;
if (dst->getFormat().bytesPerPixel == 2) {
if (inputFormat.bytesPerPixel == 2) {
applyColorKey<uint16, uint16>((uint16 *)dst->getPixels(), (const uint16 *)buf, w, h,
dst->getPitch(), srcPitch, keycolor, aMask);
} else if (inputFormat.bytesPerPixel == 4) {
applyColorKey<uint16, uint32>((uint16 *)dst->getPixels(), (const uint32 *)buf, w, h,
dst->getPitch(), srcPitch, keycolor, aMask);
}
} else {
if (inputFormat.bytesPerPixel == 2) {
applyColorKey<uint32, uint16>((uint32 *)dst->getPixels(), (const uint16 *)buf, w, h,
dst->getPitch(), srcPitch, keycolor, aMask);
} else if (inputFormat.bytesPerPixel == 4) {
applyColorKey<uint32, uint32>((uint32 *)dst->getPixels(), (const uint32 *)buf, w, h,
dst->getPitch(), srcPitch, keycolor, aMask);
}
}
// Flag the texture as dirty.
_cursor->flagDirty();
}
// In case we actually use a palette set that up properly.
if (inputFormat.bytesPerPixel == 1) {
updateCursorPalette();
}
// Update the scaling.
recalculateCursorScaling();
}
void OpenGLGraphicsManager::setCursorPalette(const byte *colors, uint start, uint num) {
// FIXME: For some reason client code assumes that usage of this function
// automatically enables the cursor palette.
_cursorPaletteEnabled = true;
memcpy(_cursorPalette + start * 3, colors, num * 3);
updateCursorPalette();
}
void OpenGLGraphicsManager::displayMessageOnOSD(const char *msg) {
#ifdef USE_OSD
// HACK: Actually no client code should use graphics functions from
// another thread. But the MT-32 emulator still does, thus we need to
// make sure this doesn't happen while a updateScreen call is done.
Common::StackLock lock(_osdMutex);
// Slip up the lines.
Common::Array<Common::String> osdLines;
Common::StringTokenizer tokenizer(msg, "\n");
while (!tokenizer.empty()) {
osdLines.push_back(tokenizer.nextToken());
}
// Do the actual drawing like the SDL backend.
const Graphics::Font *font = getFontOSD();
Graphics::Surface *dst = _osd->getSurface();
_osd->fill(0);
_osd->flagDirty();
// Determine a rect which would contain the message string (clipped to the
// screen dimensions).
const int vOffset = 6;
const int lineSpacing = 1;
const int lineHeight = font->getFontHeight() + 2 * lineSpacing;
int width = 0;
int height = lineHeight * osdLines.size() + 2 * vOffset;
for (uint i = 0; i < osdLines.size(); i++) {
width = MAX(width, font->getStringWidth(osdLines[i]) + 14);
}
// Clip the rect
width = MIN<int>(width, dst->getWidth());
height = MIN<int>(height, dst->getHeight());
int dstX = (dst->getWidth() - width) / 2;
int dstY = (dst->getHeight() - height) / 2;
// Draw a dark gray rect.
const uint32 color = dst->getFormat().RGBToColor(40, 40, 40);
dst->fillRect(Common::Rect(dstX, dstY, dstX + width, dstY + height), color);
// Render the message, centered, and in white
const uint32 white = dst->getFormat().RGBToColor(255, 255, 255);
for (uint i = 0; i < osdLines.size(); ++i) {
font->drawString(dst, osdLines[i],
dstX, dstY + i * lineHeight + vOffset + lineSpacing, width,
white, Graphics::kTextAlignCenter);
}
// Init the OSD display parameters.
_osdAlpha = kOSDInitialAlpha;
_osdFadeStartTime = g_system->getMillis() + kOSDFadeOutDelay;
#endif
}
void OpenGLGraphicsManager::setPalette(const byte *colors, uint start, uint num) {
assert(_gameScreen->hasPalette());
memcpy(_gamePalette + start * 3, colors, num * 3);
_gameScreen->setPalette(start, num, colors);
// We might need to update the cursor palette here.
updateCursorPalette();
}
void OpenGLGraphicsManager::grabPalette(byte *colors, uint start, uint num) {
assert(_gameScreen->hasPalette());
memcpy(colors, _gamePalette + start * 3, num * 3);
}
void OpenGLGraphicsManager::setActualScreenSize(uint width, uint height) {
_outputScreenWidth = width;
_outputScreenHeight = height;
// Setup coordinates system.
GLCALL(glViewport(0, 0, _outputScreenWidth, _outputScreenHeight));
GLCALL(glMatrixMode(GL_PROJECTION));
GLCALL(glLoadIdentity());
#ifdef USE_GLES
GLCALL(glOrthof(0, _outputScreenWidth, _outputScreenHeight, 0, -1, 1));
#else
GLCALL(glOrtho(0, _outputScreenWidth, _outputScreenHeight, 0, -1, 1));
#endif
GLCALL(glMatrixMode(GL_MODELVIEW));
GLCALL(glLoadIdentity());
uint overlayWidth = width;
uint overlayHeight = height;
// WORKAROUND: We can only support surfaces up to the maximum supported
// texture size. Thus, in case we encounter a physical size bigger than
// this maximum texture size we will simply use an overlay as big as
// possible and then scale it to the physical display size. This sounds
// bad but actually all recent chips should support full HD resolution
// anyway. Thus, it should not be a real issue for modern hardware.
if ( overlayWidth > (uint)Texture::getMaximumTextureSize()
|| overlayHeight > (uint)Texture::getMaximumTextureSize()) {
const frac_t outputAspect = intToFrac(_outputScreenWidth) / _outputScreenHeight;
if (outputAspect > (frac_t)FRAC_ONE) {
overlayWidth = Texture::getMaximumTextureSize();
overlayHeight = intToFrac(overlayWidth) / outputAspect;
} else {
overlayHeight = Texture::getMaximumTextureSize();
overlayWidth = fracToInt(overlayHeight * outputAspect);
}
}
// HACK: We limit the minimal overlay size to 256x200, which is the
// minimum of the dimensions of the two resolutions 256x240 (NES) and
// 320x200 (many DOS games use this). This hopefully assure that our
// GUI has working layouts.
overlayWidth = MAX<uint>(overlayWidth, 256);
overlayHeight = MAX<uint>(overlayHeight, 200);
if (!_overlay || _overlay->getFormat() != _defaultFormatAlpha) {
delete _overlay;
_overlay = nullptr;
_overlay = createTexture(_defaultFormatAlpha);
assert(_overlay);
// We always filter the overlay with GL_LINEAR. This assures it's
// readable in case it needs to be scaled and does not affect it
// otherwise.
_overlay->enableLinearFiltering(true);
}
_overlay->allocate(overlayWidth, overlayHeight);
_overlay->fill(0);
#ifdef USE_OSD
if (!_osd || _osd->getFormat() != _defaultFormatAlpha) {
delete _osd;
_osd = nullptr;
_osd = createTexture(_defaultFormatAlpha);
assert(_osd);
// We always filter the osd with GL_LINEAR. This assures it's
// readable in case it needs to be scaled and does not affect it
// otherwise.
_osd->enableLinearFiltering(true);
}
_osd->allocate(_overlay->getWidth(), _overlay->getHeight());
_osd->fill(0);
#endif
// Re-setup the scaling for the screen and cursor
recalculateDisplayArea();
recalculateCursorScaling();
// Something changed, so update the screen change ID.
++_screenChangeID;
}
void OpenGLGraphicsManager::notifyContextCreate(const Graphics::PixelFormat &defaultFormat, const Graphics::PixelFormat &defaultFormatAlpha) {
// Initialize all extensions.
initializeGLExtensions();
// Disable 3D properties.
GLCALL(glDisable(GL_CULL_FACE));
GLCALL(glDisable(GL_DEPTH_TEST));
GLCALL(glDisable(GL_LIGHTING));
GLCALL(glDisable(GL_FOG));
GLCALL(glDisable(GL_DITHER));
GLCALL(glShadeModel(GL_FLAT));
GLCALL(glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST));
// Default to black as clear color.
GLCALL(glClearColor(0.0f, 0.0f, 0.0f, 0.0f));
GLCALL(glColor4f(1.0f, 1.0f, 1.0f, 1.0f));
// Setup alpha blend (for overlay and cursor).
GLCALL(glEnable(GL_BLEND));
GLCALL(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
// Enable rendering with vertex and coord arrays.
GLCALL(glEnableClientState(GL_VERTEX_ARRAY));
GLCALL(glEnableClientState(GL_TEXTURE_COORD_ARRAY));
GLCALL(glEnable(GL_TEXTURE_2D));
// Setup scissor state accordingly.
if (_overlayVisible) {
GLCALL(glDisable(GL_SCISSOR_TEST));
} else {
GLCALL(glEnable(GL_SCISSOR_TEST));
}
// Clear the whole screen for the first three frames to assure any
// leftovers are cleared.
_scissorOverride = 3;
// We use a "pack" alignment (when reading from textures) to 4 here,
// since the only place where we really use it is the BMP screenshot
// code and that requires the same alignment too.
GLCALL(glPixelStorei(GL_PACK_ALIGNMENT, 4));
// Query information needed by textures.
Texture::queryTextureInformation();
// Refresh the output screen dimensions if some are set up.
if (_outputScreenWidth != 0 && _outputScreenHeight != 0) {
setActualScreenSize(_outputScreenWidth, _outputScreenHeight);
}
// TODO: Should we try to convert textures into one of those formats if
// possible? For example, when _gameScreen is CLUT8 we might want to use
// defaultFormat now.
_defaultFormat = defaultFormat;
_defaultFormatAlpha = defaultFormatAlpha;
if (_gameScreen) {
_gameScreen->recreateInternalTexture();
}
if (_overlay) {
_overlay->recreateInternalTexture();
}
if (_cursor) {
_cursor->recreateInternalTexture();
}
#ifdef USE_OSD
if (_osd) {
_osd->recreateInternalTexture();
}
#endif
}
void OpenGLGraphicsManager::notifyContextDestroy() {
if (_gameScreen) {
_gameScreen->releaseInternalTexture();
}
if (_overlay) {
_overlay->releaseInternalTexture();
}
if (_cursor) {
_cursor->releaseInternalTexture();
}
#ifdef USE_OSD
if (_osd) {
_osd->releaseInternalTexture();
}
#endif
}
void OpenGLGraphicsManager::adjustMousePosition(int16 &x, int16 &y) {
if (_overlayVisible) {
// It might be confusing that we actually have to handle something
// here when the overlay is visible. This is because for very small
// resolutions we have a minimal overlay size and have to adjust
// for that.
// This can also happen when the overlay is smaller than the actual
// display size because of texture size limitations.
if (_overlay) {
x = (x * _overlay->getWidth()) / _outputScreenWidth;
y = (y * _overlay->getHeight()) / _outputScreenHeight;
}
} else if (_gameScreen) {
const int16 width = _gameScreen->getWidth();
const int16 height = _gameScreen->getHeight();
x = (x * width) / (int)_outputScreenWidth;
y = (y * height) / (int)_outputScreenHeight;
}
}
void OpenGLGraphicsManager::setMousePosition(int x, int y) {
// Whenever the mouse position changed we force a screen redraw to reflect
// changes properly.
if (_cursorX != x || _cursorY != y) {
_forceRedraw = true;
}
_cursorX = x;
_cursorY = y;
if (_overlayVisible) {
_cursorDisplayX = x;
_cursorDisplayY = y;
} else {
_cursorDisplayX = _displayX + (x * _displayWidth) / _outputScreenWidth;
_cursorDisplayY = _displayY + (y * _displayHeight) / _outputScreenHeight;
}
}
Texture *OpenGLGraphicsManager::createTexture(const Graphics::PixelFormat &format, bool wantAlpha) {
GLenum glIntFormat, glFormat, glType;
if (format.bytesPerPixel == 1) {
const Graphics::PixelFormat &virtFormat = wantAlpha ? _defaultFormatAlpha : _defaultFormat;
const bool supported = getGLPixelFormat(virtFormat, glIntFormat, glFormat, glType);
if (!supported) {
return nullptr;
} else {
return new TextureCLUT8(glIntFormat, glFormat, glType, virtFormat);
}
} else {
const bool supported = getGLPixelFormat(format, glIntFormat, glFormat, glType);
if (!supported) {
return nullptr;
} else {
return new Texture(glIntFormat, glFormat, glType, format);
}
}
}
bool OpenGLGraphicsManager::getGLPixelFormat(const Graphics::PixelFormat &pixelFormat, GLenum &glIntFormat, GLenum &glFormat, GLenum &glType) const {
#ifdef SCUMM_LITTLE_ENDIAN
if (pixelFormat == Graphics::PixelFormat(4, 8, 8, 8, 8, 0, 8, 16, 24)) { // ABGR8888
#else
if (pixelFormat == Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0)) { // RGBA8888
#endif
glIntFormat = GL_RGBA;
glFormat = GL_RGBA;
glType = GL_UNSIGNED_BYTE;
return true;
} else if (pixelFormat == Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0)) { // RGB565
glIntFormat = GL_RGB;
glFormat = GL_RGB;
glType = GL_UNSIGNED_SHORT_5_6_5;
return true;
} else if (pixelFormat == Graphics::PixelFormat(2, 5, 5, 5, 1, 11, 6, 1, 0)) { // RGBA5551
glIntFormat = GL_RGBA;
glFormat = GL_RGBA;
glType = GL_UNSIGNED_SHORT_5_5_5_1;
return true;
} else if (pixelFormat == Graphics::PixelFormat(2, 4, 4, 4, 4, 12, 8, 4, 0)) { // RGBA4444
glIntFormat = GL_RGBA;
glFormat = GL_RGBA;
glType = GL_UNSIGNED_SHORT_4_4_4_4;
return true;
#ifndef USE_GLES
#ifdef SCUMM_LITTLE_ENDIAN
} else if (pixelFormat == Graphics::PixelFormat(4, 8, 8, 8, 8, 24, 16, 8, 0)) { // RGBA8888
glIntFormat = GL_RGBA;
glFormat = GL_RGBA;
glType = GL_UNSIGNED_INT_8_8_8_8;
return true;
#endif
} else if (pixelFormat == Graphics::PixelFormat(2, 5, 5, 5, 0, 10, 5, 0, 0)) { // RGB555
// GL_BGRA does not exist in every GLES implementation so should not be configured if
// USE_GLES is set.
glIntFormat = GL_RGB;
glFormat = GL_BGRA;
glType = GL_UNSIGNED_SHORT_1_5_5_5_REV;
return true;
} else if (pixelFormat == Graphics::PixelFormat(4, 8, 8, 8, 8, 16, 8, 0, 24)) { // ARGB8888
glIntFormat = GL_RGBA;
glFormat = GL_BGRA;
glType = GL_UNSIGNED_INT_8_8_8_8_REV;
return true;
} else if (pixelFormat == Graphics::PixelFormat(2, 4, 4, 4, 4, 8, 4, 0, 12)) { // ARGB4444
glIntFormat = GL_RGBA;
glFormat = GL_BGRA;
glType = GL_UNSIGNED_SHORT_4_4_4_4_REV;
return true;
#ifdef SCUMM_BIG_ENDIAN
} else if (pixelFormat == Graphics::PixelFormat(4, 8, 8, 8, 8, 0, 8, 16, 24)) { // ABGR8888
glIntFormat = GL_RGBA;
glFormat = GL_RGBA;
glType = GL_UNSIGNED_INT_8_8_8_8_REV;
return true;
#endif
} else if (pixelFormat == Graphics::PixelFormat(4, 8, 8, 8, 8, 8, 16, 24, 0)) { // BGRA8888
glIntFormat = GL_RGBA;
glFormat = GL_BGRA;
glType = GL_UNSIGNED_INT_8_8_8_8;
return true;
} else if (pixelFormat == Graphics::PixelFormat(2, 5, 6, 5, 0, 0, 5, 11, 0)) { // BGR565
glIntFormat = GL_RGB;
glFormat = GL_BGR;
glType = GL_UNSIGNED_SHORT_5_6_5;
return true;
} else if (pixelFormat == Graphics::PixelFormat(2, 5, 5, 5, 1, 1, 6, 11, 0)) { // BGRA5551
glIntFormat = GL_RGBA;
glFormat = GL_BGRA;
glType = GL_UNSIGNED_SHORT_5_5_5_1;
return true;
} else if (pixelFormat == Graphics::PixelFormat(2, 4, 4, 4, 4, 0, 4, 8, 12)) { // ABGR4444
glIntFormat = GL_RGBA;
glFormat = GL_RGBA;
glType = GL_UNSIGNED_SHORT_4_4_4_4_REV;
return true;
} else if (pixelFormat == Graphics::PixelFormat(2, 4, 4, 4, 4, 4, 8, 12, 0)) { // BGRA4444
glIntFormat = GL_RGBA;
glFormat = GL_BGRA;
glType = GL_UNSIGNED_SHORT_4_4_4_4;
return true;
#endif
} else {
return false;
}
}
frac_t OpenGLGraphicsManager::getDesiredGameScreenAspect() const {
const uint width = _currentState.gameWidth;
const uint height = _currentState.gameHeight;
if (_currentState.aspectRatioCorrection) {
// In case we enable aspect ratio correction we force a 4/3 ratio.
// But just for 320x200 and 640x400 games, since other games do not need
// this.
if ((width == 320 && height == 200) || (width == 640 && height == 400)) {
return intToFrac(4) / 3;
}
}
return intToFrac(width) / height;
}
void OpenGLGraphicsManager::recalculateDisplayArea() {
if (!_gameScreen || _outputScreenHeight == 0) {
return;
}
const frac_t outputAspect = intToFrac(_outputScreenWidth) / _outputScreenHeight;
const frac_t desiredAspect = getDesiredGameScreenAspect();
_displayWidth = _outputScreenWidth;
_displayHeight = _outputScreenHeight;
// Adjust one dimension for mantaining the aspect ratio.
if (outputAspect < desiredAspect) {
_displayHeight = intToFrac(_displayWidth) / desiredAspect;
} else if (outputAspect > desiredAspect) {
_displayWidth = fracToInt(_displayHeight * desiredAspect);
}
// We center the screen in the middle for now.
_displayX = (_outputScreenWidth - _displayWidth ) / 2;
_displayY = (_outputScreenHeight - _displayHeight) / 2;
// Setup drawing limitation for game graphics.
// This invovles some trickery because OpenGL's viewport coordinate system
// is upside down compared to ours.
GLCALL(glScissor(_displayX,
_outputScreenHeight - _displayHeight - _displayY,
_displayWidth,
_displayHeight));
// Clear the whole screen for the first three frames to remove leftovers.
_scissorOverride = 3;
// Update the cursor position to adjust for new display area.
setMousePosition(_cursorX, _cursorY);
// Force a redraw to assure screen is properly redrawn.
_forceRedraw = true;
}
void OpenGLGraphicsManager::updateCursorPalette() {
if (!_cursor || !_cursor->hasPalette()) {
return;
}
if (_cursorPaletteEnabled) {
_cursor->setPalette(0, 256, _cursorPalette);
} else {
_cursor->setPalette(0, 256, _gamePalette);
}
// We remove all alpha bits from the palette entry of the color key.
// This makes sure its properly handled as color key.
const Graphics::PixelFormat &hardwareFormat = _cursor->getHardwareFormat();
const uint32 aMask = (0xFF >> hardwareFormat.aLoss) << hardwareFormat.aShift;
if (hardwareFormat.bytesPerPixel == 2) {
uint16 *palette = (uint16 *)_cursor->getPalette() + _cursorKeyColor;
*palette &= ~aMask;
} else if (hardwareFormat.bytesPerPixel == 4) {
uint32 *palette = (uint32 *)_cursor->getPalette() + _cursorKeyColor;
*palette &= ~aMask;
} else {
warning("OpenGLGraphicsManager::updateCursorPalette: Unsupported pixel depth %d", hardwareFormat.bytesPerPixel);
}
}
void OpenGLGraphicsManager::recalculateCursorScaling() {
if (!_cursor || !_gameScreen) {
return;
}
// By default we use the unscaled versions.
_cursorHotspotXScaled = _cursorHotspotX;
_cursorHotspotYScaled = _cursorHotspotY;
_cursorWidthScaled = _cursor->getWidth();
_cursorHeightScaled = _cursor->getHeight();
// In case scaling is actually enabled we will scale the cursor according
// to the game screen.
if (!_cursorDontScale) {
const frac_t screenScaleFactorX = intToFrac(_displayWidth) / _gameScreen->getWidth();
const frac_t screenScaleFactorY = intToFrac(_displayHeight) / _gameScreen->getHeight();
_cursorHotspotXScaled = fracToInt(_cursorHotspotXScaled * screenScaleFactorX);
_cursorWidthScaled = fracToInt(_cursorWidthScaled * screenScaleFactorX);
_cursorHotspotYScaled = fracToInt(_cursorHotspotYScaled * screenScaleFactorY);
_cursorHeightScaled = fracToInt(_cursorHeightScaled * screenScaleFactorY);
}
}
#ifdef USE_OSD
const Graphics::Font *OpenGLGraphicsManager::getFontOSD() {
return FontMan.getFontByUsage(Graphics::FontManager::kLocalizedFont);
}
#endif
void OpenGLGraphicsManager::saveScreenshot(const Common::String &filename) const {
const uint width = _outputScreenWidth;
const uint height = _outputScreenHeight;
// A line of a BMP image must have a size divisible by 4.
// We calculate the padding bytes needed here.
// Since we use a 3 byte per pixel mode, we can use width % 4 here, since
// it is equal to 4 - (width * 3) % 4. (4 - (width * Bpp) % 4, is the
// usual way of computing the padding bytes required).
const uint linePaddingSize = width % 4;
const uint lineSize = width * 3 + linePaddingSize;
// Allocate memory for screenshot
uint8 *pixels = new uint8[lineSize * height];
// Get pixel data from OpenGL buffer
GLCALL(glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels));
// BMP stores as BGR. Since we can't assume that GL_BGR is supported we
// will swap the components from the RGB we read to BGR on our own.
for (uint y = height; y-- > 0;) {
uint8 *line = pixels + y * lineSize;
for (uint x = width; x > 0; --x, line += 3) {
SWAP(line[0], line[2]);
}
}
// Open file
Common::DumpFile out;
out.open(filename);
// Write BMP header
out.writeByte('B');
out.writeByte('M');
out.writeUint32LE(height * lineSize + 54);
out.writeUint32LE(0);
out.writeUint32LE(54);
out.writeUint32LE(40);
out.writeUint32LE(width);
out.writeUint32LE(height);
out.writeUint16LE(1);
out.writeUint16LE(24);
out.writeUint32LE(0);
out.writeUint32LE(0);
out.writeUint32LE(0);
out.writeUint32LE(0);
out.writeUint32LE(0);
out.writeUint32LE(0);
// Write pixel data to BMP
out.write(pixels, lineSize * height);
// Free allocated memory
delete[] pixels;
}
} // End of namespace OpenGL
| project-cabal/cabal | backends/graphics/opengl/opengl-graphics.cpp | C++ | gpl-2.0 | 39,193 |
/*
Google HTML5 slides template
Authors: Luke Mahé (code)
Marcin Wichary (code and design)
Dominic Mazzoni (browser compatibility)
Charles Chen (ChromeVox support)
URL: http://code.google.com/p/html5slides/
*/
var PERMANENT_URL_PREFIX = 'https://magni.me/presentation-pugbo-php54/';
var SLIDE_CLASSES = ['far-past', 'past', 'current', 'next', 'far-next'];
var PM_TOUCH_SENSITIVITY = 15;
var curSlide;
/* ---------------------------------------------------------------------- */
/* classList polyfill by Eli Grey
* (http://purl.eligrey.com/github/classList.js/blob/master/classList.js) */
if (typeof document !== "undefined" && !("classList" in document.createElement("a"))) {
(function (view) {
var
classListProp = "classList"
, protoProp = "prototype"
, elemCtrProto = (view.HTMLElement || view.Element)[protoProp]
, objCtr = Object
strTrim = String[protoProp].trim || function () {
return this.replace(/^\s+|\s+$/g, "");
}
, arrIndexOf = Array[protoProp].indexOf || function (item) {
for (var i = 0, len = this.length; i < len; i++) {
if (i in this && this[i] === item) {
return i;
}
}
return -1;
}
// Vendors: please allow content code to instantiate DOMExceptions
, DOMEx = function (type, message) {
this.name = type;
this.code = DOMException[type];
this.message = message;
}
, checkTokenAndGetIndex = function (classList, token) {
if (token === "") {
throw new DOMEx(
"SYNTAX_ERR"
, "An invalid or illegal string was specified"
);
}
if (/\s/.test(token)) {
throw new DOMEx(
"INVALID_CHARACTER_ERR"
, "String contains an invalid character"
);
}
return arrIndexOf.call(classList, token);
}
, ClassList = function (elem) {
var
trimmedClasses = strTrim.call(elem.className)
, classes = trimmedClasses ? trimmedClasses.split(/\s+/) : []
;
for (var i = 0, len = classes.length; i < len; i++) {
this.push(classes[i]);
}
this._updateClassName = function () {
elem.className = this.toString();
};
}
, classListProto = ClassList[protoProp] = []
, classListGetter = function () {
return new ClassList(this);
}
;
// Most DOMException implementations don't allow calling DOMException's toString()
// on non-DOMExceptions. Error's toString() is sufficient here.
DOMEx[protoProp] = Error[protoProp];
classListProto.item = function (i) {
return this[i] || null;
};
classListProto.contains = function (token) {
token += "";
return checkTokenAndGetIndex(this, token) !== -1;
};
classListProto.add = function (token) {
token += "";
if (checkTokenAndGetIndex(this, token) === -1) {
this.push(token);
this._updateClassName();
}
};
classListProto.remove = function (token) {
token += "";
var index = checkTokenAndGetIndex(this, token);
if (index !== -1) {
this.splice(index, 1);
this._updateClassName();
}
};
classListProto.toggle = function (token) {
token += "";
if (checkTokenAndGetIndex(this, token) === -1) {
this.add(token);
} else {
this.remove(token);
}
};
classListProto.toString = function () {
return this.join(" ");
};
if (objCtr.defineProperty) {
var classListPropDesc = {
get: classListGetter
, enumerable: true
, configurable: true
};
try {
objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
} catch (ex) { // IE 8 doesn't support enumerable:true
if (ex.number === -0x7FF5EC54) {
classListPropDesc.enumerable = false;
objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
}
}
} else if (objCtr[protoProp].__defineGetter__) {
elemCtrProto.__defineGetter__(classListProp, classListGetter);
}
}(self));
}
/* ---------------------------------------------------------------------- */
/* Slide movement */
function getSlideEl(no) {
if ((no < 0) || (no >= slideEls.length)) {
return null;
} else {
return slideEls[no];
}
};
function updateSlideClass(slideNo, className) {
var el = getSlideEl(slideNo);
if (!el) {
return;
}
if (className) {
el.classList.add(className);
}
for (var i in SLIDE_CLASSES) {
if (className != SLIDE_CLASSES[i]) {
el.classList.remove(SLIDE_CLASSES[i]);
}
}
};
function updateSlides() {
for (var i = 0; i < slideEls.length; i++) {
switch (i) {
case curSlide - 2:
updateSlideClass(i, 'far-past');
break;
case curSlide - 1:
updateSlideClass(i, 'past');
break;
case curSlide:
updateSlideClass(i, 'current');
break;
case curSlide + 1:
updateSlideClass(i, 'next');
break;
case curSlide + 2:
updateSlideClass(i, 'far-next');
break;
default:
updateSlideClass(i);
break;
}
}
triggerLeaveEvent(curSlide - 1);
triggerEnterEvent(curSlide);
window.setTimeout(function() {
// Hide after the slide
disableSlideFrames(curSlide - 2);
}, 301);
enableSlideFrames(curSlide - 1);
enableSlideFrames(curSlide + 2);
if (isChromeVoxActive()) {
speakAndSyncToNode(slideEls[curSlide]);
}
updateHash();
};
function buildNextItem() {
var toBuild = slideEls[curSlide].querySelectorAll('.to-build');
if (!toBuild.length) {
return false;
}
toBuild[0].classList.remove('to-build', '');
if (isChromeVoxActive()) {
speakAndSyncToNode(toBuild[0]);
}
return true;
};
function prevSlide() {
if (curSlide > 0) {
curSlide--;
updateSlides();
}
};
function nextSlide() {
if (buildNextItem()) {
return;
}
if (curSlide < slideEls.length - 1) {
curSlide++;
updateSlides();
}
};
/* Slide events */
function triggerEnterEvent(no) {
var el = getSlideEl(no);
if (!el) {
return;
}
var onEnter = el.getAttribute('onslideenter');
if (onEnter) {
new Function(onEnter).call(el);
}
var evt = document.createEvent('Event');
evt.initEvent('slideenter', true, true);
evt.slideNumber = no + 1; // Make it readable
el.dispatchEvent(evt);
};
function triggerLeaveEvent(no) {
var el = getSlideEl(no);
if (!el) {
return;
}
var onLeave = el.getAttribute('onslideleave');
if (onLeave) {
new Function(onLeave).call(el);
}
var evt = document.createEvent('Event');
evt.initEvent('slideleave', true, true);
evt.slideNumber = no + 1; // Make it readable
el.dispatchEvent(evt);
};
/* Touch events */
function handleTouchStart(event) {
if (event.touches.length == 1) {
touchDX = 0;
touchDY = 0;
touchStartX = event.touches[0].pageX;
touchStartY = event.touches[0].pageY;
document.body.addEventListener('touchmove', handleTouchMove, true);
document.body.addEventListener('touchend', handleTouchEnd, true);
}
};
function handleTouchMove(event) {
if (event.touches.length > 1) {
cancelTouch();
} else {
touchDX = event.touches[0].pageX - touchStartX;
touchDY = event.touches[0].pageY - touchStartY;
}
};
function handleTouchEnd(event) {
var dx = Math.abs(touchDX);
var dy = Math.abs(touchDY);
if ((dx > PM_TOUCH_SENSITIVITY) && (dy < (dx * 2 / 3))) {
if (touchDX > 0) {
prevSlide();
} else {
nextSlide();
}
}
cancelTouch();
};
function cancelTouch() {
document.body.removeEventListener('touchmove', handleTouchMove, true);
document.body.removeEventListener('touchend', handleTouchEnd, true);
};
/* Preloading frames */
function disableSlideFrames(no) {
var el = getSlideEl(no);
if (!el) {
return;
}
var frames = el.getElementsByTagName('iframe');
for (var i = 0, frame; frame = frames[i]; i++) {
disableFrame(frame);
}
};
function enableSlideFrames(no) {
var el = getSlideEl(no);
if (!el) {
return;
}
var frames = el.getElementsByTagName('iframe');
for (var i = 0, frame; frame = frames[i]; i++) {
enableFrame(frame);
}
};
function disableFrame(frame) {
frame.src = 'about:blank';
};
function enableFrame(frame) {
var src = frame._src;
if (frame.src != src && src != 'about:blank') {
frame.src = src;
}
};
function setupFrames() {
var frames = document.querySelectorAll('iframe');
for (var i = 0, frame; frame = frames[i]; i++) {
frame._src = frame.src;
disableFrame(frame);
}
enableSlideFrames(curSlide);
enableSlideFrames(curSlide + 1);
enableSlideFrames(curSlide + 2);
};
function setupInteraction() {
/* Clicking and tapping */
var el = document.createElement('div');
el.className = 'slide-area';
el.id = 'prev-slide-area';
el.addEventListener('click', prevSlide, false);
document.querySelector('section.slides').appendChild(el);
var el = document.createElement('div');
el.className = 'slide-area';
el.id = 'next-slide-area';
el.addEventListener('click', nextSlide, false);
document.querySelector('section.slides').appendChild(el);
/* Swiping */
document.body.addEventListener('touchstart', handleTouchStart, false);
}
/* ChromeVox support */
function isChromeVoxActive() {
if (typeof(cvox) == 'undefined') {
return false;
} else {
return true;
}
};
function speakAndSyncToNode(node) {
if (!isChromeVoxActive()) {
return;
}
cvox.ChromeVox.navigationManager.switchToStrategy(
cvox.ChromeVoxNavigationManager.STRATEGIES.LINEARDOM, 0, true);
cvox.ChromeVox.navigationManager.syncToNode(node);
cvox.ChromeVoxUserCommands.finishNavCommand('');
var target = node;
while (target.firstChild) {
target = target.firstChild;
}
cvox.ChromeVox.navigationManager.syncToNode(target);
};
function speakNextItem() {
if (!isChromeVoxActive()) {
return;
}
cvox.ChromeVox.navigationManager.switchToStrategy(
cvox.ChromeVoxNavigationManager.STRATEGIES.LINEARDOM, 0, true);
cvox.ChromeVox.navigationManager.next(true);
if (!cvox.DomUtil.isDescendantOfNode(
cvox.ChromeVox.navigationManager.getCurrentNode(), slideEls[curSlide])){
var target = slideEls[curSlide];
while (target.firstChild) {
target = target.firstChild;
}
cvox.ChromeVox.navigationManager.syncToNode(target);
cvox.ChromeVox.navigationManager.next(true);
}
cvox.ChromeVoxUserCommands.finishNavCommand('');
};
function speakPrevItem() {
if (!isChromeVoxActive()) {
return;
}
cvox.ChromeVox.navigationManager.switchToStrategy(
cvox.ChromeVoxNavigationManager.STRATEGIES.LINEARDOM, 0, true);
cvox.ChromeVox.navigationManager.previous(true);
if (!cvox.DomUtil.isDescendantOfNode(
cvox.ChromeVox.navigationManager.getCurrentNode(), slideEls[curSlide])){
var target = slideEls[curSlide];
while (target.lastChild){
target = target.lastChild;
}
cvox.ChromeVox.navigationManager.syncToNode(target);
cvox.ChromeVox.navigationManager.previous(true);
}
cvox.ChromeVoxUserCommands.finishNavCommand('');
};
/* Hash functions */
function getCurSlideFromHash() {
var slideNo = parseInt(location.hash.substr(1));
if (slideNo) {
curSlide = slideNo - 1;
} else {
curSlide = 0;
}
};
function updateHash() {
location.replace('#' + (curSlide + 1));
};
/* Event listeners */
function handleBodyKeyDown(event) {
switch (event.keyCode) {
case 39: // right arrow
case 13: // Enter
case 32: // space
case 34: // PgDn
nextSlide();
event.preventDefault();
break;
case 37: // left arrow
case 8: // Backspace
case 33: // PgUp
prevSlide();
event.preventDefault();
break;
case 40: // down arrow
if (isChromeVoxActive()) {
speakNextItem();
} else {
nextSlide();
}
event.preventDefault();
break;
case 38: // up arrow
if (isChromeVoxActive()) {
speakPrevItem();
} else {
prevSlide();
}
event.preventDefault();
break;
}
};
function addEventListeners() {
document.addEventListener('keydown', handleBodyKeyDown, false);
};
/* Initialization */
function addPrettify() {
var els = document.querySelectorAll('pre');
for (var i = 0, el; el = els[i]; i++) {
if (!el.classList.contains('noprettyprint')) {
el.classList.add('prettyprint');
}
}
var el = document.createElement('script');
el.type = 'text/javascript';
el.src = PERMANENT_URL_PREFIX + 'js/prettify.js';
el.onload = function() {
prettyPrint();
}
document.body.appendChild(el);
};
function addFontStyle() {
var el = document.createElement('link');
el.rel = 'stylesheet';
el.type = 'text/css';
el.href = 'https://fonts.googleapis.com/css?family=' +
'Open+Sans:regular,semibold,italic,italicsemibold|Droid+Sans+Mono';
document.body.appendChild(el);
};
function addGeneralStyle() {
var el = document.createElement('link');
el.rel = 'stylesheet';
el.type = 'text/css';
el.href = PERMANENT_URL_PREFIX + 'styles/styles.css';
document.body.appendChild(el);
var el = document.createElement('meta');
el.name = 'viewport';
el.content = 'width=1100,height=750';
document.querySelector('head').appendChild(el);
var el = document.createElement('meta');
el.name = 'apple-mobile-web-app-capable';
el.content = 'yes';
document.querySelector('head').appendChild(el);
};
function makeBuildLists() {
for (var i = curSlide, slide; slide = slideEls[i]; i++) {
var items = slide.querySelectorAll('.build > *');
for (var j = 0, item; item = items[j]; j++) {
if (item.classList) {
item.classList.add('to-build');
}
}
}
};
function handleDomLoaded() {
slideEls = document.querySelectorAll('section.slides > article');
setupFrames();
addFontStyle();
addGeneralStyle();
addPrettify();
addEventListeners();
updateSlides();
setupInteraction();
makeBuildLists();
document.body.classList.add('loaded');
};
function initialize() {
getCurSlideFromHash();
if (window['_DEBUG']) {
PERMANENT_URL_PREFIX = '../';
}
if (window['_DCL']) {
handleDomLoaded();
} else {
document.addEventListener('DOMContentLoaded', handleDomLoaded, false);
}
}
// If ?debug exists then load the script relative instead of absolute
if (!window['_DEBUG'] && document.location.href.indexOf('?debug') !== -1) {
document.addEventListener('DOMContentLoaded', function() {
// Avoid missing the DomContentLoaded event
window['_DCL'] = true
}, false);
window['_DEBUG'] = true;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '../slides.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(script, s);
// Remove this script
s.parentNode.removeChild(s);
} else {
initialize();
}
| ilbonzo/presentation-pugbo-php54 | js/slides.js | JavaScript | gpl-2.0 | 14,822 |
/*
* Copyright (C) 2009 Swedish Institute of Computer Science (SICS) Copyright (C)
* 2009 Royal Institute of Technology (KTH)
*
* KompicsToolbox is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package se.sics.nstream.hops.kafka.avro;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.buffer.Unpooled;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.generic.GenericRecordBuilder;
import org.apache.avro.io.BinaryDecoder;
import org.apache.avro.io.BinaryEncoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.EncoderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Alex Ormenisan <aaor@kth.se>
*/
public class AvroParser {
private static final Logger LOG = LoggerFactory.getLogger(AvroParser.class);
public static GenericRecord blobToAvro(Schema schema, ByteBuf data) {
int readPos = data.readerIndex();
GenericDatumReader<GenericRecord> reader = new GenericDatumReader<>(schema);
try (InputStream in = new ByteBufInputStream(data)) {
BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(in, null);
try {
GenericRecord record = reader.read(null, decoder);
readPos = data.readerIndex() - decoder.inputStream().available();
data.readerIndex(readPos);
return record;
} catch (EOFException ex) {
data.readerIndex(readPos);
return null;
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static List<GenericRecord> blobToAvroList(Schema schema, InputStream in) {
List<GenericRecord> records = new ArrayList<>();
GenericDatumReader<GenericRecord> reader = new GenericDatumReader<>(schema);
BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(in, null);
try {
while (true) {
GenericRecord record = reader.read(null, decoder);
records.add(record);
}
} catch (EOFException ex) {
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return records;
}
public static byte[] avroToBlob(Schema schema, GenericRecord record) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema);
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
try {
writer.write(record, encoder);
encoder.flush();
} catch (Exception ex) {
throw new RuntimeException("hmmm", ex);
}
byte[] bData = out.toByteArray();
return bData;
}
public static byte[] nAvroToBlob(Schema schema, int nrMsgs, Random rand) {
ByteBuf buf = Unpooled.buffer();
OutputStream out = new ByteBufOutputStream(buf);
GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema);
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
GenericRecordBuilder grb;
for (int i = 0; i < nrMsgs; i++) {
grb = new GenericRecordBuilder(schema);
for (Schema.Field field : schema.getFields()) {
//TODO Alex - I assume each field is a string
grb.set(field, "val" + (1000 + rand.nextInt(1000)));
}
try {
writer.write(grb.build(), encoder);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
try {
encoder.flush();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
byte[] result = new byte[buf.writerIndex()];
buf.readBytes(result);
return result;
}
}
| Decentrify/GVoD | hops/core/src/main/java/se/sics/nstream/hops/kafka/avro/AvroParser.java | Java | gpl-2.0 | 4,973 |
package com.kartoflane.superluminal2.ui.sidebar.data;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import com.kartoflane.superluminal2.Superluminal;
import com.kartoflane.superluminal2.components.enums.Images;
import com.kartoflane.superluminal2.components.enums.OS;
import com.kartoflane.superluminal2.core.Cache;
import com.kartoflane.superluminal2.core.Manager;
import com.kartoflane.superluminal2.mvc.controllers.AbstractController;
import com.kartoflane.superluminal2.mvc.controllers.ImageController;
import com.kartoflane.superluminal2.utils.UIUtils;
import com.kartoflane.superluminal2.utils.Utils;
public class ImageDataComposite extends Composite implements DataComposite
{
private ImageController controller = null;
private Label label = null;
private Button btnFollowHull;
private Label lblFollowHelp;
public ImageDataComposite( Composite parent, ImageController control )
{
super( parent, SWT.NONE );
setLayout( new GridLayout( 2, false ) );
controller = control;
label = new Label( this, SWT.NONE );
label.setAlignment( SWT.CENTER );
label.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) );
String alias = control.getAlias();
label.setText( "Image" + ( alias == null ? "" : " (" + alias + ")" ) );
Label separator = new Label( this, SWT.SEPARATOR | SWT.HORIZONTAL );
separator.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ) );
btnFollowHull = new Button( this, SWT.CHECK );
btnFollowHull.setLayoutData( new GridData( SWT.LEFT, SWT.CENTER, true, false, 1, 1 ) );
btnFollowHull.setText( "Follow Hull" );
lblFollowHelp = new Label( this, SWT.NONE );
lblFollowHelp.setLayoutData( new GridData( SWT.RIGHT, SWT.CENTER, false, false, 1, 1 ) );
lblFollowHelp.setImage( Cache.checkOutImage( this, "cpath:/assets/help.png" ) );
String msg = "When checked, this object will follow the hull image, so that " +
"when hull is moved, this object is moved as well.";
UIUtils.addTooltip( lblFollowHelp, Utils.wrapOSNot( msg, Superluminal.WRAP_WIDTH, Superluminal.WRAP_TOLERANCE, OS.MACOSX() ) );
btnFollowHull.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e )
{
if ( btnFollowHull.getSelection() ) {
controller.setParent( Manager.getCurrentShip().getImageController( Images.HULL ) );
}
else {
controller.setParent( Manager.getCurrentShip().getShipController() );
}
controller.updateFollowOffset();
}
}
);
updateData();
}
@Override
public void updateData()
{
String alias = controller.getAlias();
label.setText( "Image" + ( alias == null ? "" : " (" + alias + ")" ) );
ImageController hullController = Manager.getCurrentShip().getImageController( Images.HULL );
btnFollowHull.setVisible( controller != hullController );
btnFollowHull.setSelection( controller.getParent() == hullController );
lblFollowHelp.setVisible( controller != hullController );
}
@Override
public void setController( AbstractController controller )
{
this.controller = (ImageController)controller;
}
public void reloadController()
{
}
@Override
public void dispose()
{
Cache.checkInImage( this, "cpath:/assets/help.png" );
super.dispose();
}
}
| kartoFlane/superluminal2 | src/java/com/kartoflane/superluminal2/ui/sidebar/data/ImageDataComposite.java | Java | gpl-2.0 | 3,552 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("benchmark_itextsharp_pdf_from_html_thumb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("benchmark_itextsharp_pdf_from_html_thumb")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f83d77a5-c710-4008-b9de-8f05cbbf0f5d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| hudsonmendes/benchmark-itextsharp-pdf-from-html-thumb | Properties/AssemblyInfo.cs | C# | gpl-2.0 | 1,456 |
/*
* Copyright (C) 2011 University of Szeged
* Copyright (C) 2011 Gabor Loki <loki@webkit.org>
* 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 UNIVERSITY OF SZEGED ``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 UNIVERSITY OF SZEGED OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(THREADING_GENERIC)
#include "ParallelJobs.h"
#include <wtf/NumberOfCores.h>
namespace WTF {
Vector< RefPtr<ParallelEnvironment::ThreadPrivate> >* ParallelEnvironment::s_threadPool = 0;
ParallelEnvironment::ParallelEnvironment(ThreadFunction threadFunction, size_t sizeOfParameter, int requestedJobNumber) :
m_threadFunction(threadFunction),
m_sizeOfParameter(sizeOfParameter)
{
ASSERT_ARG(requestedJobNumber, requestedJobNumber >= 1);
int maxNumberOfCores = numberOfProcessorCores();
if (!requestedJobNumber || requestedJobNumber > maxNumberOfCores)
requestedJobNumber = static_cast<unsigned>(maxNumberOfCores);
if (!s_threadPool)
s_threadPool = new Vector< RefPtr<ThreadPrivate> >();
// The main thread should be also a worker.
int maxNumberOfNewThreads = requestedJobNumber - 1;
for (int i = 0; i < maxNumberOfCores && m_threads.size() < static_cast<unsigned>(maxNumberOfNewThreads); ++i) {
if (s_threadPool->size() < static_cast<unsigned>(i) + 1U)
s_threadPool->append(ThreadPrivate::create());
if ((*s_threadPool)[i]->tryLockFor(this))
m_threads.append((*s_threadPool)[i]);
}
m_numberOfJobs = m_threads.size() + 1;
}
void ParallelEnvironment::execute(void* parameters)
{
unsigned char* currentParameter = static_cast<unsigned char*>(parameters);
size_t i;
for (i = 0; i < m_threads.size(); ++i) {
m_threads[i]->execute(m_threadFunction, currentParameter);
currentParameter += m_sizeOfParameter;
}
// The work for the main thread.
(*m_threadFunction)(currentParameter);
// Wait until all jobs are done.
for (i = 0; i < m_threads.size(); ++i)
m_threads[i]->waitForFinish();
}
bool ParallelEnvironment::ThreadPrivate::tryLockFor(ParallelEnvironment* parent)
{
bool locked = m_mutex.tryLock();
if (!locked)
return false;
if (m_parent) {
m_mutex.unlock();
return false;
}
if (!m_thread) {
m_thread = Thread::create("Parallel worker", [this] {
LockHolder lock(m_mutex);
while (true) {
if (m_running) {
(*m_threadFunction)(m_parameters);
m_running = false;
m_parent = nullptr;
m_threadCondition.notifyOne();
}
m_threadCondition.wait(m_mutex);
}
});
}
m_parent = parent;
m_mutex.unlock();
return true;
}
void ParallelEnvironment::ThreadPrivate::execute(ThreadFunction threadFunction, void* parameters)
{
LockHolder lock(m_mutex);
m_threadFunction = threadFunction;
m_parameters = parameters;
m_running = true;
m_threadCondition.notifyOne();
}
void ParallelEnvironment::ThreadPrivate::waitForFinish()
{
LockHolder lock(m_mutex);
while (m_running)
m_threadCondition.wait(m_mutex);
}
} // namespace WTF
#endif // ENABLE(THREADING_GENERIC)
| teamfx/openjfx-8u-dev-rt | modules/web/src/main/native/Source/WTF/wtf/ParallelJobsGeneric.cpp | C++ | gpl-2.0 | 4,438 |
<?php
// Exit if accessed directly
if ( !defined('ABSPATH')) exit;
/**
* Sidebar Right Half Template
*
*
* @file sidebar-right-half.php
* @package Responsive
* @author Emil Uzelac
* @copyright 2003 - 2012 ThemeID
* @license license.txt
* @version Release: 1.0
* @filesource wp-content/themes/responsive/sidebar-right-half.php
* @link http://codex.wordpress.org/Theme_Development#Widgets_.28sidebar.php.29
* @since available since Release 1.0
*/
?>
</div>
<div id="widgets" class="grid col-460 fit">
<?php responsive_widgets(); // above widgets hook ?>
<?php if (!dynamic_sidebar('right-sidebar')) : ?>
<div class="widget-wrapper-right">
</div><!-- end of .widget-wrapper -->
<?php endif; //end of sidebar-right-half ?>
<?php responsive_widgets_end(); // after widgets hook ?>
</div><!-- end of #widgets --> | ianknauer/TeF_wordpress | wp-content/themes/Trottier/sidebar-home.php | PHP | gpl-2.0 | 977 |
from __future__ import with_statement
from fabric.api import task
@task
def md5():
"""
Check MD5 sums (unavailable, empty, with content)
"""
import hashlib
from fabric.api import cd, hide, run, settings
import fabtools
with cd('/tmp'):
run('touch f1')
assert fabtools.files.md5sum('f1') == hashlib.md5('').hexdigest()
run('echo -n hello > f2')
assert fabtools.files.md5sum('f2') == hashlib.md5('hello').hexdigest()
with settings(hide('warnings')):
assert fabtools.files.md5sum('doesnotexist') is None
| juanantoniofm/accesible-moodle | fabtools/tests/fabfiles/md5.py | Python | gpl-2.0 | 590 |
require 'rubygems'
require 'oauth'
module YammerAPI
class Client
def initialize(app_key, app_secret)
@consumer = OAuth::Consumer.new(app_key, app_secret,
{:site => "https://www.yammer.com"}
)
end
def user_authenticated?
not @user.nil?
end
def access_token
@access_token.token
end
def access_token_secret
@access_token.secret
end
def set_credentials(token, secret)
@access_token = OAuth::AccessToken.new(@consumer, token, secret)
end
def start_oauth
@request_token = @consumer.get_request_token
@request_token.authorize_url
end
def finish_oauth(auth_code)
@access_token = @request_token.get_access_token(:oauth_verifier => auth_code)
end
def fetch_messages()
Message.fetch_latest(@access_token)
end
end
end
| sitharus/kumara | lib/client.rb | Ruby | gpl-2.0 | 915 |
// Copyright 2012,2013 Vaughn Vernon
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.saasovation.agilepm.application.product;
import java.util.UUID;
import com.saasovation.agilepm.application.ProductApplicationCommonTest;
import com.saasovation.agilepm.domain.model.discussion.DiscussionAvailability;
import com.saasovation.agilepm.domain.model.product.Product;
import com.saasovation.agilepm.domain.model.product.ProductId;
import com.saasovation.agilepm.domain.model.team.ProductOwner;
public class ProductApplicationServiceTest extends ProductApplicationCommonTest {
public ProductApplicationServiceTest() {
super();
}
public void testDiscussionProcess() throws Exception {
Product product = this.persistedProductForTest();
this.productApplicationService.requestProductDiscussion(
new RequestProductDiscussionCommand(
product.tenantId().id(),
product.productId().id()));
this.productApplicationService.startDiscussionInitiation(
new StartDiscussionInitiationCommand(
product.tenantId().id(),
product.productId().id()));
Product productWithStartedDiscussionInitiation =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertNotNull(productWithStartedDiscussionInitiation.discussionInitiationId());
String discussionId = UUID.randomUUID().toString().toUpperCase();
InitiateDiscussionCommand command =
new InitiateDiscussionCommand(
product.tenantId().id(),
product.productId().id(),
discussionId);
this.productApplicationService.initiateDiscussion(command);
Product productWithInitiatedDiscussion =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertEquals(discussionId, productWithInitiatedDiscussion.discussion().descriptor().id());
}
public void testNewProduct() throws Exception {
ProductOwner productOwner = this.persistedProductOwnerForTest();
String newProductId =
this.productApplicationService.newProduct(
new NewProductCommand(
"T-12345",
productOwner.productOwnerId().id(),
"My Product",
"The description of My Product."));
Product newProduct =
this.productRepository
.productOfId(
productOwner.tenantId(),
new ProductId(newProductId));
assertNotNull(newProduct);
assertEquals("My Product", newProduct.name());
assertEquals("The description of My Product.", newProduct.description());
}
public void testNewProductWithDiscussion() throws Exception {
ProductOwner productOwner = this.persistedProductOwnerForTest();
String newProductId =
this.productApplicationService.newProductWithDiscussion(
new NewProductCommand(
"T-12345",
productOwner.productOwnerId().id(),
"My Product",
"The description of My Product."));
Product newProduct =
this.productRepository
.productOfId(
productOwner.tenantId(),
new ProductId(newProductId));
assertNotNull(newProduct);
assertEquals("My Product", newProduct.name());
assertEquals("The description of My Product.", newProduct.description());
assertEquals(DiscussionAvailability.REQUESTED, newProduct.discussion().availability());
}
public void testRequestProductDiscussion() throws Exception {
Product product = this.persistedProductForTest();
this.productApplicationService.requestProductDiscussion(
new RequestProductDiscussionCommand(
product.tenantId().id(),
product.productId().id()));
Product productWithRequestedDiscussion =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertEquals(DiscussionAvailability.REQUESTED, productWithRequestedDiscussion.discussion().availability());
}
public void testRetryProductDiscussionRequest() throws Exception {
Product product = this.persistedProductForTest();
this.productApplicationService.requestProductDiscussion(
new RequestProductDiscussionCommand(
product.tenantId().id(),
product.productId().id()));
Product productWithRequestedDiscussion =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertEquals(DiscussionAvailability.REQUESTED, productWithRequestedDiscussion.discussion().availability());
this.productApplicationService.startDiscussionInitiation(
new StartDiscussionInitiationCommand(
product.tenantId().id(),
product.productId().id()));
Product productWithDiscussionInitiation =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertNotNull(productWithDiscussionInitiation.discussionInitiationId());
this.productApplicationService.retryProductDiscussionRequest(
new RetryProductDiscussionRequestCommand(
product.tenantId().id(),
productWithDiscussionInitiation.discussionInitiationId()));
Product productWithRetriedRequestedDiscussion =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertEquals(DiscussionAvailability.REQUESTED, productWithRetriedRequestedDiscussion.discussion().availability());
}
public void testStartDiscussionInitiation() throws Exception {
Product product = this.persistedProductForTest();
this.productApplicationService.requestProductDiscussion(
new RequestProductDiscussionCommand(
product.tenantId().id(),
product.productId().id()));
Product productWithRequestedDiscussion =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertEquals(DiscussionAvailability.REQUESTED, productWithRequestedDiscussion.discussion().availability());
assertNull(productWithRequestedDiscussion.discussionInitiationId());
this.productApplicationService.startDiscussionInitiation(
new StartDiscussionInitiationCommand(
product.tenantId().id(),
product.productId().id()));
Product productWithDiscussionInitiation =
this.productRepository
.productOfId(
product.tenantId(),
product.productId());
assertNotNull(productWithDiscussionInitiation.discussionInitiationId());
}
public void testTimeOutProductDiscussionRequest() throws Exception {
// TODO: student assignment
}
}
| LeonardCohen/coding | IDDD_Samples-master/agilepm/src/test/java/com/saasovation/agilepm/application/product/ProductApplicationServiceTest.java | Java | gpl-2.0 | 8,537 |
package com.atux.desktop.promocion;
import com.atux.bean.precios.Local;
import com.atux.bean.precios.LocalFlt;
import com.atux.bean.promocion.Promocion;
import com.atux.bean.promocion.PromocionDetalle;
import com.atux.bean.promocion.PromocionLocal;
import com.atux.config.APDD;
import com.atux.desktop.comun.picks.SeleccionarLocalPst;
import com.atux.dominio.promocion.PromocionService;
import com.atux.service.qryMapper.ProveedorQryMapper;
import com.aw.core.report.ReportUtils;
import com.aw.stereotype.AWPresenter;
import com.aw.swing.mvp.Presenter;
import com.aw.swing.mvp.action.Action;
import com.aw.swing.mvp.action.ActionDialog;
import com.aw.swing.mvp.action.types.*;
import com.aw.swing.mvp.binding.component.support.ColumnInfo;
import com.aw.swing.mvp.grid.GridInfoProvider;
import com.aw.swing.mvp.grid.GridProvider;
import com.aw.swing.mvp.navigation.Flow;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.swing.*;
import java.io.File;
import java.util.List;
/**
* Created by JAVA on 15/11/2014.
*/
@AWPresenter(title = "Proveedor - Precio")
public class PromocionPst extends Presenter<Promocion> {
protected final Log LOG = LogFactory.getLog(getClass());
private FrmPromocion vsr;
@Autowired
ProveedorQryMapper proveedorQryMapper;
@Autowired
PromocionService promocionService;
JFileChooser chooser = new JFileChooser();
GridProvider gdp;
GridProvider gdpLocal;
@Autowired
APDD apdd;
public PromocionPst() {
setBackBean(new Promocion());
setShowAuditInfo(false);
}
@Override
protected void registerBinding() {
bindingMgr.bind(vsr.txtCoPromocion, "coPromocion").setUIReadOnly(true);
bindingMgr.bind(vsr.txtNoPromocion, "noPromocion");
bindingMgr.bind(vsr.txtMensajeCorto, "mensajeCorto");
bindingMgr.bind(vsr.txtMensajeLargo, "mensajeLargo");
bindingMgr.bind(vsr.txtObservacion, "observacion");
bindingMgr.bind(vsr.txtFeIchanicio, "fechaInicio");
bindingMgr.bind(vsr.txtFechaFin, "fechaFin");
bindingMgr.bind(vsr.chkEstado, "esPromocion").registerTrueFalse("A", "I");
}
@Override
protected void registerGridProviders() {
gdp = gridProviderMgr.registerGridProvider(new IPDetalle());
gdpLocal = gridProviderMgr.registerGridProvider(new IPLocal());
}
private class IPDetalle extends GridInfoProvider<Promocion> {
public ColumnInfo[] getColumnInfo() {
ColumnInfo[] columns = new ColumnInfo[]{
new ColumnInfo("Código", "coProducto", 50, ColumnInfo.LEFT),
new ColumnInfo("Producto", "deProducto", 80, ColumnInfo.LEFT),
new ColumnInfo("Cant. Ent.", "caEntero", 30, ColumnInfo.RIGHT),
new ColumnInfo("Cant. Frac.", "caFraccion", 30, ColumnInfo.RIGHT),
new ColumnInfo("Prom. Código", "coProductoP", 50, ColumnInfo.LEFT),
new ColumnInfo("Prom. Producto", "deProductoP", 80, ColumnInfo.LEFT),
new ColumnInfo("Prom. Cant. Ent.", "caEnteroP", 30, ColumnInfo.RIGHT),
new ColumnInfo("Prom. Cant Frac.", "caFraccionP", 30, ColumnInfo.RIGHT),
new ColumnInfo("Estado", "esProductoPlan", 80, ColumnInfo.LEFT).setDropDownFormatter(apdd.ES_TABLA),
};
return columns;
}
public List<PromocionDetalle> getValues(Promocion precioLista) {
return precioLista.getDetalle();
}
}
private class IPLocal extends GridInfoProvider<Promocion> {
public ColumnInfo[] getColumnInfo() {
ColumnInfo[] columns = new ColumnInfo[]{
new ColumnInfo("Código", "coLocal", 50, ColumnInfo.LEFT),
new ColumnInfo("Local", "deLocal", 80, ColumnInfo.LEFT)
};
return columns;
}
public List<PromocionLocal> getValues(Promocion precioLista) {
return precioLista.getDetalleLocal();
}
}
@Override
protected void afterInitComponents() {
}
protected void registerActions() {
actionRsr.registerAction("Nuevo", new InsertAction(PromocionDetalle.class), gdp)
.notNeedVisualComponent()
.refreshGridAtEnd()
.noExecValidation()
.setKeyTrigger(ActionDialog.KEY_F2)
.setTargetPstClass(PromocionCrudPst.class);
actionRsr.registerAction("Delete", new DeleteItemAction() {
@Override
protected Object executeIntern() throws Throwable {
getBackBean().getDetalle().remove(gdp.getSelectedRow());
return null;
}
}, gdp)
.notNeedVisualComponent()
.needSelectedRow()
.refreshGridAtEnd()
.setKeyTrigger(ActionDialog.KEY_F4)
;
actionRsr.registerAction("DeleteLocal", new DeleteItemAction() {
@Override
protected Object executeIntern() throws Throwable {
getBackBean().getDetalleLocal().remove(gdpLocal.getSelectedRow());
return null;
}
}, gdpLocal)
.notNeedVisualComponent()
.needSelectedRow()
.refreshGridAtEnd()
.setKeyTrigger(ActionDialog.KEY_F4)
;
actionRsr.registerAction("Guardar", new Action() {
@Override
protected Object executeIntern() throws Throwable {
promocionService.grabar(getBackBean());
return null;
}
}).notNeedVisualComponent()
.setKeyTrigger(ActionDialog.KEY_F10)
.closeViewAtEnd();
actionRsr.registerAction("Seleccionar", new ShowPstAction(LocalFlt.class){
@Override
public Object executeOnReturn(Flow initialFlow, Flow endFlow) {
// endFlow.getAttribute(Flow.BACK_BEAN_NAME);
List<Local> localList= (List<Local>) endFlow.getAttribute("selectedRows");
for (Local local : localList) {
PromocionLocal promocionLocal=new PromocionLocal();
promocionLocal.setCoLocal(local.getCoLocal());
promocionLocal.setDeLocal(local.getDeLocal());
getBackBean().getDetalleLocal().add(promocionLocal);
}
return super.executeOnReturn(initialFlow, endFlow);
}
}, gdpLocal)
.refreshGridAtEnd()
.notNeedVisualComponent()
.noExecValidation()
.setKeyTrigger(ActionDialog.KEY_F6)
.setTargetPstClass(SeleccionarLocalPst.class)
;
}
public void descargarAction() {
try {
ReportUtils.showReport(new File(getClass().getResource("/plantilla_precio_proveedor.xls").toURI()).getAbsolutePath());
} catch (Throwable e) {
logger.error("Error ", e);
}
}
public void examinarAction() {
int returnVal = chooser.showOpenDialog(vsr.pnlMain);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
//This is where a real application would open the file.
logger.info("Opening: " + file.getName() + "." + "\n");
} else {
logger.info("Open command cancelled by user." + "\n");
}
}
}
| AlanGuerraQuispe/SisAtuxPerfumeria | atux-desktop/src/main/java/com/atux/desktop/promocion/PromocionPst.java | Java | gpl-2.0 | 7,829 |
/*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MySQLConnection.h"
#include "QueryHolder.h"
#include "PreparedStatement.h"
#include "Log.h"
bool SQLQueryHolder::SetQuery(size_t index, const char *sql)
{
if (m_queries.size() <= index)
{
sLog->outError(LOG_FILTER_SQL, "Query index (%u) out of range (size: %u) for query: %s", uint32(index), (uint32)m_queries.size(), sql);
return false;
}
/// not executed yet, just stored (it's not called a holder for nothing)
SQLElementData element;
element.type = SQL_ELEMENT_RAW;
element.element.query = strdup(sql);
SQLResultSetUnion result;
result.qresult = NULL;
m_queries[index] = SQLResultPair(element, result);
return true;
}
bool SQLQueryHolder::SetPQuery(size_t index, const char *format, ...)
{
if (!format)
{
sLog->outError(LOG_FILTER_SQL, "Query (index: %u) is empty.", uint32(index));
return false;
}
va_list ap;
char szQuery [MAX_QUERY_LEN];
va_start(ap, format);
int res = vsnprintf(szQuery, MAX_QUERY_LEN, format, ap);
va_end(ap);
if (res == -1)
{
sLog->outError(LOG_FILTER_SQL, "SQL Query truncated (and not execute) for format: %s", format);
return false;
}
return SetQuery(index, szQuery);
}
bool SQLQueryHolder::SetPreparedQuery(size_t index, PreparedStatement* stmt)
{
if (m_queries.size() <= index)
{
sLog->outError(LOG_FILTER_SQL, "Query index (%u) out of range (size: %u) for prepared statement", uint32(index), (uint32)m_queries.size());
return false;
}
/// not executed yet, just stored (it's not called a holder for nothing)
SQLElementData element;
element.type = SQL_ELEMENT_PREPARED;
element.element.stmt = stmt;
SQLResultSetUnion result;
result.presult = NULL;
m_queries[index] = SQLResultPair(element, result);
return true;
}
QueryResult SQLQueryHolder::GetResult(size_t index)
{
// Don't call to this function if the index is of an ad-hoc statement
if (index < m_queries.size())
{
ResultSet* result = m_queries[index].second.qresult;
if (!result || !result->GetRowCount() || !result->NextRow())
return QueryResult(NULL);
return QueryResult(result);
}
else
return QueryResult(NULL);
}
PreparedQueryResult SQLQueryHolder::GetPreparedResult(size_t index)
{
// Don't call to this function if the index is of a prepared statement
if (index < m_queries.size())
{
PreparedResultSet* result = m_queries[index].second.presult;
if (!result || !result->GetRowCount())
return PreparedQueryResult(NULL);
return PreparedQueryResult(result);
}
else
return PreparedQueryResult(NULL);
}
void SQLQueryHolder::SetResult(size_t index, ResultSet* result)
{
if (result && !result->GetRowCount())
{
delete result;
result = NULL;
}
/// store the result in the holder
if (index < m_queries.size())
m_queries[index].second.qresult = result;
}
void SQLQueryHolder::SetPreparedResult(size_t index, PreparedResultSet* result)
{
if (result && !result->GetRowCount())
{
delete result;
result = NULL;
}
/// store the result in the holder
if (index < m_queries.size())
m_queries[index].second.presult = result;
}
SQLQueryHolder::~SQLQueryHolder()
{
for (size_t i = 0; i < m_queries.size(); i++)
{
/// if the result was never used, free the resources
/// results used already (getresult called) are expected to be deleted
if (SQLElementData* data = &m_queries[i].first)
{
switch (data->type)
{
case SQL_ELEMENT_RAW:
free((void*)(const_cast<char*>(data->element.query)));
break;
case SQL_ELEMENT_PREPARED:
delete data->element.stmt;
break;
}
}
}
}
void SQLQueryHolder::SetSize(size_t size)
{
/// to optimize push_back, reserve the number of queries about to be executed
m_queries.resize(size);
}
bool SQLQueryHolderTask::Execute()
{
if (!m_holder)
return false;
/// we can do this, we are friends
std::vector<SQLQueryHolder::SQLResultPair> &queries = m_holder->m_queries;
for (size_t i = 0; i < queries.size(); i++)
{
/// execute all queries in the holder and pass the results
if (SQLElementData* data = &queries[i].first)
{
switch (data->type)
{
case SQL_ELEMENT_RAW:
{
char const* sql = data->element.query;
if (sql)
m_holder->SetResult(i, m_conn->Query(sql));
break;
}
case SQL_ELEMENT_PREPARED:
{
PreparedStatement* stmt = data->element.stmt;
if (stmt)
m_holder->SetPreparedResult(i, m_conn->Query(stmt));
break;
}
}
}
}
m_result.set(m_holder);
return true;
}
| Spade17/4.3.4-Core | src/server/shared/Database/QueryHolder.cpp | C++ | gpl-2.0 | 5,905 |
package com.example.murat.gezi_yorum.Fragments;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.example.murat.gezi_yorum.Entity.Constants;
import com.example.murat.gezi_yorum.Entity.User;
import com.example.murat.gezi_yorum.R;
import com.example.murat.gezi_yorum.Utils.NotificationsAdapter;
import com.example.murat.gezi_yorum.Utils.URLRequestHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Shows notification
*/
public class Notifications extends Fragment {
private ListView trip_invitation_notifications;
private ListView friendship_requests;
private Handler handler;
private JSONArray trip_invitation_notificationsList;
private JSONArray friendship_requestsList;
private User user;
private Boolean isPaused;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle(getString(R.string.notification));
trip_invitation_notifications = view.findViewById(R.id.notifications);
friendship_requests = view.findViewById(R.id.friend_notifications);
handler = new Handler();
user = new User(getContext().getSharedPreferences(Constants.PREFNAME, Context.MODE_PRIVATE));
new Thread(new Runnable() {
@Override
public void run() {
JSONObject request = new JSONObject();
try {
request.put("token", user.token);
request.put("username", user.username);
String url = Constants.APP + "checkTripRequest";
URLRequestHandler urlhandler = new URLRequestHandler(request.toString(), url);
if(urlhandler.getResponseMessage()){
String notitificationsResponse = urlhandler.getResponse();
trip_invitation_notificationsList = new JSONArray(notitificationsResponse);
}
url = Constants.APP + "getFriendRequests";
urlhandler = new URLRequestHandler(request.toString(), url);
if(urlhandler.getResponseMessage()){
String notitificationsResponse = urlhandler.getResponse();
friendship_requestsList = new JSONArray(notitificationsResponse);
}
} catch (JSONException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
@Override
public void run() {
if(!isPaused)
loadAdapter();
}
});
}
}).start();
}
@Override
public void onResume() {
super.onResume();
isPaused = false;
}
@Override
public void onPause() {
super.onPause();
isPaused = true;
}
public void loadAdapter(){
if(trip_invitation_notificationsList != null && trip_invitation_notificationsList.length() > 0) {
trip_invitation_notifications.setAdapter(
new NotificationsAdapter(getContext(), trip_invitation_notificationsList, NotificationsAdapter.TRIP, this)
);
}else {
getView().findViewById(R.id.trip_not_text).setVisibility(View.GONE);
}
if(friendship_requestsList != null && friendship_requestsList.length() > 0) {
friendship_requests.setAdapter(
new NotificationsAdapter(getContext(), friendship_requestsList, NotificationsAdapter.FRIENDSHIP,this)
);
}else {
getView().findViewById(R.id.friend_not_text).setVisibility(View.GONE);
}
if((trip_invitation_notificationsList == null || trip_invitation_notificationsList.length() == 0)
&& (friendship_requestsList == null || friendship_requestsList.length() == 0)) {
getActivity().findViewById(R.id.nothing).setVisibility(View.VISIBLE);
}
}
public void acceptOrDenyFriendRequest(int i){
friendship_requestsList.remove(i);
friendship_requests.setAdapter(
new NotificationsAdapter(getContext(), friendship_requestsList, NotificationsAdapter.FRIENDSHIP,this)
);
}
public void denyTripRequest(int i){
trip_invitation_notificationsList.remove(i);
trip_invitation_notifications.setAdapter(
new NotificationsAdapter(getContext(), trip_invitation_notificationsList, NotificationsAdapter.TRIP,this)
);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.notifications_fragment, container,false);
}
}
| bugdetector/Gezi-Yorum | app/src/main/java/com/example/murat/gezi_yorum/Fragments/Notifications.java | Java | gpl-2.0 | 5,164 |
package ee.esutoniagodesu.domain.jmet.table;
import org.hibernate.annotations.Immutable;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Immutable
@Table(name = "kwginf", schema = "jmet")
public final class Kwginf implements Serializable {
private static final long serialVersionUID = 4247060263515704962L;
private short id;
private String kw;
private String descr;
@Basic
@Column(name = "descr", nullable = true, insertable = true, updatable = true, length = 255)
public String getDescr() {
return descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
@Id
@Column(name = "id", nullable = false, insertable = true, updatable = true)
public short getId() {
return id;
}
public void setId(short id) {
this.id = id;
}
@Basic
@Column(name = "kw", nullable = false, insertable = true, updatable = true, length = 20)
public String getKw() {
return kw;
}
public void setKw(String kw) {
this.kw = kw;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Kwginf kwginf = (Kwginf) o;
if (id != kwginf.id) return false;
if (descr != null ? !descr.equals(kwginf.descr) : kwginf.descr != null) return false;
if (kw != null ? !kw.equals(kwginf.kw) : kwginf.kw != null) return false;
return true;
}
public int hashCode() {
int result = (int) id;
result = 31 * result + (kw != null ? kw.hashCode() : 0);
result = 31 * result + (descr != null ? descr.hashCode() : 0);
return result;
}
}
| esutoniagodesu/egd-web | src/main/java/ee/esutoniagodesu/domain/jmet/table/Kwginf.java | Java | gpl-2.0 | 1,728 |
/*
* Copyright (c) 2001, 2016, 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_VM_GC_SHARED_COLLECTEDHEAP_HPP
#define SHARE_VM_GC_SHARED_COLLECTEDHEAP_HPP
#include "gc/shared/gcCause.hpp"
#include "gc/shared/gcWhen.hpp"
#include "memory/allocation.hpp"
#include "runtime/handles.hpp"
#include "runtime/perfData.hpp"
#include "runtime/safepoint.hpp"
#include "utilities/events.hpp"
// A "CollectedHeap" is an implementation of a java heap for HotSpot. This
// is an abstract class: there may be many different kinds of heaps. This
// class defines the functions that a heap must implement, and contains
// infrastructure common to all heaps.
class AdaptiveSizePolicy;
class BarrierSet;
class CollectorPolicy;
class GCHeapSummary;
class GCTimer;
class GCTracer;
class MetaspaceSummary;
class Thread;
class ThreadClosure;
class VirtualSpaceSummary;
class nmethod;
class GCMessage : public FormatBuffer<1024> {
public:
bool is_before;
public:
GCMessage() {}
};
class CollectedHeap;
class GCHeapLog : public EventLogBase<GCMessage> {
private:
void log_heap(CollectedHeap* heap, bool before);
public:
GCHeapLog() : EventLogBase<GCMessage>("GC Heap History") {}
void log_heap_before(CollectedHeap* heap) {
log_heap(heap, true);
}
void log_heap_after(CollectedHeap* heap) {
log_heap(heap, false);
}
};
//
// CollectedHeap
// GenCollectedHeap
// G1CollectedHeap
// ParallelScavengeHeap
//
class CollectedHeap : public CHeapObj<mtInternal> {
friend class VMStructs;
friend class JVMCIVMStructs;
friend class IsGCActiveMark; // Block structured external access to _is_gc_active
private:
#ifdef ASSERT
static int _fire_out_of_memory_count;
#endif
GCHeapLog* _gc_heap_log;
// Used in support of ReduceInitialCardMarks; only consulted if COMPILER2
// or INCLUDE_JVMCI is being used
bool _defer_initial_card_mark;
MemRegion _reserved;
protected:
BarrierSet* _barrier_set;
bool _is_gc_active;
// Used for filler objects (static, but initialized in ctor).
static size_t _filler_array_max_size;
unsigned int _total_collections; // ... started
unsigned int _total_full_collections; // ... started
NOT_PRODUCT(volatile size_t _promotion_failure_alot_count;)
NOT_PRODUCT(volatile size_t _promotion_failure_alot_gc_number;)
// Reason for current garbage collection. Should be set to
// a value reflecting no collection between collections.
GCCause::Cause _gc_cause;
GCCause::Cause _gc_lastcause;
PerfStringVariable* _perf_gc_cause;
PerfStringVariable* _perf_gc_lastcause;
// Constructor
CollectedHeap();
// Do common initializations that must follow instance construction,
// for example, those needing virtual calls.
// This code could perhaps be moved into initialize() but would
// be slightly more awkward because we want the latter to be a
// pure virtual.
void pre_initialize();
// Create a new tlab. All TLAB allocations must go through this.
virtual HeapWord* allocate_new_tlab(size_t size);
// Accumulate statistics on all tlabs.
virtual void accumulate_statistics_all_tlabs();
// Reinitialize tlabs before resuming mutators.
virtual void resize_all_tlabs();
// Allocate from the current thread's TLAB, with broken-out slow path.
inline static HeapWord* allocate_from_tlab(KlassHandle klass, Thread* thread, size_t size);
static HeapWord* allocate_from_tlab_slow(KlassHandle klass, Thread* thread, size_t size);
// Allocate an uninitialized block of the given size, or returns NULL if
// this is impossible.
inline static HeapWord* common_mem_allocate_noinit(KlassHandle klass, size_t size, TRAPS);
// Like allocate_init, but the block returned by a successful allocation
// is guaranteed initialized to zeros.
inline static HeapWord* common_mem_allocate_init(KlassHandle klass, size_t size, TRAPS);
// Helper functions for (VM) allocation.
inline static void post_allocation_setup_common(KlassHandle klass, HeapWord* obj);
inline static void post_allocation_setup_no_klass_install(KlassHandle klass,
HeapWord* objPtr);
inline static void post_allocation_setup_obj(KlassHandle klass, HeapWord* obj, int size);
inline static void post_allocation_setup_array(KlassHandle klass,
HeapWord* obj, int length);
inline static void post_allocation_setup_class(KlassHandle klass, HeapWord* obj, int size);
// Clears an allocated object.
inline static void init_obj(HeapWord* obj, size_t size);
// Filler object utilities.
static inline size_t filler_array_hdr_size();
static inline size_t filler_array_min_size();
DEBUG_ONLY(static void fill_args_check(HeapWord* start, size_t words);)
DEBUG_ONLY(static void zap_filler_array(HeapWord* start, size_t words, bool zap = true);)
// Fill with a single array; caller must ensure filler_array_min_size() <=
// words <= filler_array_max_size().
static inline void fill_with_array(HeapWord* start, size_t words, bool zap = true);
// Fill with a single object (either an int array or a java.lang.Object).
static inline void fill_with_object_impl(HeapWord* start, size_t words, bool zap = true);
virtual void trace_heap(GCWhen::Type when, const GCTracer* tracer);
// Verification functions
virtual void check_for_bad_heap_word_value(HeapWord* addr, size_t size)
PRODUCT_RETURN;
virtual void check_for_non_bad_heap_word_value(HeapWord* addr, size_t size)
PRODUCT_RETURN;
debug_only(static void check_for_valid_allocation_state();)
public:
enum Name {
GenCollectedHeap,
ParallelScavengeHeap,
G1CollectedHeap
};
static inline size_t filler_array_max_size() {
return _filler_array_max_size;
}
virtual Name kind() const = 0;
virtual const char* name() const = 0;
/**
* Returns JNI error code JNI_ENOMEM if memory could not be allocated,
* and JNI_OK on success.
*/
virtual jint initialize() = 0;
// In many heaps, there will be a need to perform some initialization activities
// after the Universe is fully formed, but before general heap allocation is allowed.
// This is the correct place to place such initialization methods.
virtual void post_initialize() = 0;
// Stop any onging concurrent work and prepare for exit.
virtual void stop() {}
void initialize_reserved_region(HeapWord *start, HeapWord *end);
MemRegion reserved_region() const { return _reserved; }
address base() const { return (address)reserved_region().start(); }
virtual size_t capacity() const = 0;
virtual size_t used() const = 0;
// Return "true" if the part of the heap that allocates Java
// objects has reached the maximal committed limit that it can
// reach, without a garbage collection.
virtual bool is_maximal_no_gc() const = 0;
// Support for java.lang.Runtime.maxMemory(): return the maximum amount of
// memory that the vm could make available for storing 'normal' java objects.
// This is based on the reserved address space, but should not include space
// that the vm uses internally for bookkeeping or temporary storage
// (e.g., in the case of the young gen, one of the survivor
// spaces).
virtual size_t max_capacity() const = 0;
// Returns "TRUE" if "p" points into the reserved area of the heap.
bool is_in_reserved(const void* p) const {
return _reserved.contains(p);
}
bool is_in_reserved_or_null(const void* p) const {
return p == NULL || is_in_reserved(p);
}
// Returns "TRUE" iff "p" points into the committed areas of the heap.
// This method can be expensive so avoid using it in performance critical
// code.
virtual bool is_in(const void* p) const = 0;
DEBUG_ONLY(bool is_in_or_null(const void* p) const { return p == NULL || is_in(p); })
// Let's define some terms: a "closed" subset of a heap is one that
//
// 1) contains all currently-allocated objects, and
//
// 2) is closed under reference: no object in the closed subset
// references one outside the closed subset.
//
// Membership in a heap's closed subset is useful for assertions.
// Clearly, the entire heap is a closed subset, so the default
// implementation is to use "is_in_reserved". But this may not be too
// liberal to perform useful checking. Also, the "is_in" predicate
// defines a closed subset, but may be too expensive, since "is_in"
// verifies that its argument points to an object head. The
// "closed_subset" method allows a heap to define an intermediate
// predicate, allowing more precise checking than "is_in_reserved" at
// lower cost than "is_in."
// One important case is a heap composed of disjoint contiguous spaces,
// such as the Garbage-First collector. Such heaps have a convenient
// closed subset consisting of the allocated portions of those
// contiguous spaces.
// Return "TRUE" iff the given pointer points into the heap's defined
// closed subset (which defaults to the entire heap).
virtual bool is_in_closed_subset(const void* p) const {
return is_in_reserved(p);
}
bool is_in_closed_subset_or_null(const void* p) const {
return p == NULL || is_in_closed_subset(p);
}
// An object is scavengable if its location may move during a scavenge.
// (A scavenge is a GC which is not a full GC.)
virtual bool is_scavengable(const void *p) = 0;
void set_gc_cause(GCCause::Cause v) {
if (UsePerfData) {
_gc_lastcause = _gc_cause;
_perf_gc_lastcause->set_value(GCCause::to_string(_gc_lastcause));
_perf_gc_cause->set_value(GCCause::to_string(v));
}
_gc_cause = v;
}
GCCause::Cause gc_cause() { return _gc_cause; }
// General obj/array allocation facilities.
inline static oop obj_allocate(KlassHandle klass, int size, TRAPS);
inline static oop array_allocate(KlassHandle klass, int size, int length, TRAPS);
inline static oop array_allocate_nozero(KlassHandle klass, int size, int length, TRAPS);
inline static oop class_allocate(KlassHandle klass, int size, TRAPS);
inline static void post_allocation_install_obj_klass(KlassHandle klass,
oop obj);
// Raw memory allocation facilities
// The obj and array allocate methods are covers for these methods.
// mem_allocate() should never be
// called to allocate TLABs, only individual objects.
virtual HeapWord* mem_allocate(size_t size,
bool* gc_overhead_limit_was_exceeded) = 0;
// Utilities for turning raw memory into filler objects.
//
// min_fill_size() is the smallest region that can be filled.
// fill_with_objects() can fill arbitrary-sized regions of the heap using
// multiple objects. fill_with_object() is for regions known to be smaller
// than the largest array of integers; it uses a single object to fill the
// region and has slightly less overhead.
static size_t min_fill_size() {
return size_t(align_object_size(oopDesc::header_size()));
}
static void fill_with_objects(HeapWord* start, size_t words, bool zap = true);
static void fill_with_object(HeapWord* start, size_t words, bool zap = true);
static void fill_with_object(MemRegion region, bool zap = true) {
fill_with_object(region.start(), region.word_size(), zap);
}
static void fill_with_object(HeapWord* start, HeapWord* end, bool zap = true) {
fill_with_object(start, pointer_delta(end, start), zap);
}
// Return the address "addr" aligned by "alignment_in_bytes" if such
// an address is below "end". Return NULL otherwise.
inline static HeapWord* align_allocation_or_fail(HeapWord* addr,
HeapWord* end,
unsigned short alignment_in_bytes);
// Some heaps may offer a contiguous region for shared non-blocking
// allocation, via inlined code (by exporting the address of the top and
// end fields defining the extent of the contiguous allocation region.)
// This function returns "true" iff the heap supports this kind of
// allocation. (Default is "no".)
virtual bool supports_inline_contig_alloc() const {
return false;
}
// These functions return the addresses of the fields that define the
// boundaries of the contiguous allocation area. (These fields should be
// physically near to one another.)
virtual HeapWord** top_addr() const {
guarantee(false, "inline contiguous allocation not supported");
return NULL;
}
virtual HeapWord** end_addr() const {
guarantee(false, "inline contiguous allocation not supported");
return NULL;
}
// Some heaps may be in an unparseable state at certain times between
// collections. This may be necessary for efficient implementation of
// certain allocation-related activities. Calling this function before
// attempting to parse a heap ensures that the heap is in a parsable
// state (provided other concurrent activity does not introduce
// unparsability). It is normally expected, therefore, that this
// method is invoked with the world stopped.
// NOTE: if you override this method, make sure you call
// super::ensure_parsability so that the non-generational
// part of the work gets done. See implementation of
// CollectedHeap::ensure_parsability and, for instance,
// that of GenCollectedHeap::ensure_parsability().
// The argument "retire_tlabs" controls whether existing TLABs
// are merely filled or also retired, thus preventing further
// allocation from them and necessitating allocation of new TLABs.
virtual void ensure_parsability(bool retire_tlabs);
// Section on thread-local allocation buffers (TLABs)
// If the heap supports thread-local allocation buffers, it should override
// the following methods:
// Returns "true" iff the heap supports thread-local allocation buffers.
// The default is "no".
virtual bool supports_tlab_allocation() const = 0;
// The amount of space available for thread-local allocation buffers.
virtual size_t tlab_capacity(Thread *thr) const = 0;
// The amount of used space for thread-local allocation buffers for the given thread.
virtual size_t tlab_used(Thread *thr) const = 0;
virtual size_t max_tlab_size() const;
// An estimate of the maximum allocation that could be performed
// for thread-local allocation buffers without triggering any
// collection or expansion activity.
virtual size_t unsafe_max_tlab_alloc(Thread *thr) const {
guarantee(false, "thread-local allocation buffers not supported");
return 0;
}
// Can a compiler initialize a new object without store barriers?
// This permission only extends from the creation of a new object
// via a TLAB up to the first subsequent safepoint. If such permission
// is granted for this heap type, the compiler promises to call
// defer_store_barrier() below on any slow path allocation of
// a new object for which such initializing store barriers will
// have been elided.
virtual bool can_elide_tlab_store_barriers() const = 0;
// If a compiler is eliding store barriers for TLAB-allocated objects,
// there is probably a corresponding slow path which can produce
// an object allocated anywhere. The compiler's runtime support
// promises to call this function on such a slow-path-allocated
// object before performing initializations that have elided
// store barriers. Returns new_obj, or maybe a safer copy thereof.
virtual oop new_store_pre_barrier(JavaThread* thread, oop new_obj);
// Answers whether an initializing store to a new object currently
// allocated at the given address doesn't need a store
// barrier. Returns "true" if it doesn't need an initializing
// store barrier; answers "false" if it does.
virtual bool can_elide_initializing_store_barrier(oop new_obj) = 0;
// If a compiler is eliding store barriers for TLAB-allocated objects,
// we will be informed of a slow-path allocation by a call
// to new_store_pre_barrier() above. Such a call precedes the
// initialization of the object itself, and no post-store-barriers will
// be issued. Some heap types require that the barrier strictly follows
// the initializing stores. (This is currently implemented by deferring the
// barrier until the next slow-path allocation or gc-related safepoint.)
// This interface answers whether a particular heap type needs the card
// mark to be thus strictly sequenced after the stores.
virtual bool card_mark_must_follow_store() const = 0;
// If the CollectedHeap was asked to defer a store barrier above,
// this informs it to flush such a deferred store barrier to the
// remembered set.
virtual void flush_deferred_store_barrier(JavaThread* thread);
// Should return true if the reference pending list lock is
// acquired from non-Java threads, such as a concurrent GC thread.
virtual bool needs_reference_pending_list_locker_thread() const {
return false;
}
// Perform a collection of the heap; intended for use in implementing
// "System.gc". This probably implies as full a collection as the
// "CollectedHeap" supports.
virtual void collect(GCCause::Cause cause) = 0;
// Perform a full collection
virtual void do_full_collection(bool clear_all_soft_refs) = 0;
// This interface assumes that it's being called by the
// vm thread. It collects the heap assuming that the
// heap lock is already held and that we are executing in
// the context of the vm thread.
virtual void collect_as_vm_thread(GCCause::Cause cause);
// Returns the barrier set for this heap
BarrierSet* barrier_set() { return _barrier_set; }
void set_barrier_set(BarrierSet* barrier_set);
// Returns "true" iff there is a stop-world GC in progress. (I assume
// that it should answer "false" for the concurrent part of a concurrent
// collector -- dld).
bool is_gc_active() const { return _is_gc_active; }
// Total number of GC collections (started)
unsigned int total_collections() const { return _total_collections; }
unsigned int total_full_collections() const { return _total_full_collections;}
// Increment total number of GC collections (started)
// Should be protected but used by PSMarkSweep - cleanup for 1.4.2
void increment_total_collections(bool full = false) {
_total_collections++;
if (full) {
increment_total_full_collections();
}
}
void increment_total_full_collections() { _total_full_collections++; }
// Return the AdaptiveSizePolicy for the heap.
virtual AdaptiveSizePolicy* size_policy() = 0;
// Return the CollectorPolicy for the heap
virtual CollectorPolicy* collector_policy() const = 0;
// Iterate over all objects, calling "cl.do_object" on each.
virtual void object_iterate(ObjectClosure* cl) = 0;
// Similar to object_iterate() except iterates only
// over live objects.
virtual void safe_object_iterate(ObjectClosure* cl) = 0;
// NOTE! There is no requirement that a collector implement these
// functions.
//
// A CollectedHeap is divided into a dense sequence of "blocks"; that is,
// each address in the (reserved) heap is a member of exactly
// one block. The defining characteristic of a block is that it is
// possible to find its size, and thus to progress forward to the next
// block. (Blocks may be of different sizes.) Thus, blocks may
// represent Java objects, or they might be free blocks in a
// free-list-based heap (or subheap), as long as the two kinds are
// distinguishable and the size of each is determinable.
// Returns the address of the start of the "block" that contains the
// address "addr". We say "blocks" instead of "object" since some heaps
// may not pack objects densely; a chunk may either be an object or a
// non-object.
virtual HeapWord* block_start(const void* addr) const = 0;
// Requires "addr" to be the start of a chunk, and returns its size.
// "addr + size" is required to be the start of a new chunk, or the end
// of the active area of the heap.
virtual size_t block_size(const HeapWord* addr) const = 0;
// Requires "addr" to be the start of a block, and returns "TRUE" iff
// the block is an object.
virtual bool block_is_obj(const HeapWord* addr) const = 0;
// Returns the longest time (in ms) that has elapsed since the last
// time that any part of the heap was examined by a garbage collection.
virtual jlong millis_since_last_gc() = 0;
// Perform any cleanup actions necessary before allowing a verification.
virtual void prepare_for_verify() = 0;
// Generate any dumps preceding or following a full gc
private:
void full_gc_dump(GCTimer* timer, bool before);
public:
void pre_full_gc_dump(GCTimer* timer);
void post_full_gc_dump(GCTimer* timer);
VirtualSpaceSummary create_heap_space_summary();
GCHeapSummary create_heap_summary();
MetaspaceSummary create_metaspace_summary();
// Print heap information on the given outputStream.
virtual void print_on(outputStream* st) const = 0;
// The default behavior is to call print_on() on tty.
virtual void print() const {
print_on(tty);
}
// Print more detailed heap information on the given
// outputStream. The default behavior is to call print_on(). It is
// up to each subclass to override it and add any additional output
// it needs.
virtual void print_extended_on(outputStream* st) const {
print_on(st);
}
virtual void print_on_error(outputStream* st) const;
// Print all GC threads (other than the VM thread)
// used by this heap.
virtual void print_gc_threads_on(outputStream* st) const = 0;
// The default behavior is to call print_gc_threads_on() on tty.
void print_gc_threads() {
print_gc_threads_on(tty);
}
// Iterator for all GC threads (other than VM thread)
virtual void gc_threads_do(ThreadClosure* tc) const = 0;
// Print any relevant tracing info that flags imply.
// Default implementation does nothing.
virtual void print_tracing_info() const = 0;
void print_heap_before_gc();
void print_heap_after_gc();
// Registering and unregistering an nmethod (compiled code) with the heap.
// Override with specific mechanism for each specialized heap type.
virtual void register_nmethod(nmethod* nm);
virtual void unregister_nmethod(nmethod* nm);
void trace_heap_before_gc(const GCTracer* gc_tracer);
void trace_heap_after_gc(const GCTracer* gc_tracer);
// Heap verification
virtual void verify(VerifyOption option) = 0;
// Non product verification and debugging.
#ifndef PRODUCT
// Support for PromotionFailureALot. Return true if it's time to cause a
// promotion failure. The no-argument version uses
// this->_promotion_failure_alot_count as the counter.
inline bool promotion_should_fail(volatile size_t* count);
inline bool promotion_should_fail();
// Reset the PromotionFailureALot counters. Should be called at the end of a
// GC in which promotion failure occurred.
inline void reset_promotion_should_fail(volatile size_t* count);
inline void reset_promotion_should_fail();
#endif // #ifndef PRODUCT
#ifdef ASSERT
static int fired_fake_oom() {
return (CIFireOOMAt > 1 && _fire_out_of_memory_count >= CIFireOOMAt);
}
#endif
public:
// Copy the current allocation context statistics for the specified contexts.
// For each context in contexts, set the corresponding entries in the totals
// and accuracy arrays to the current values held by the statistics. Each
// array should be of length len.
// Returns true if there are more stats available.
virtual bool copy_allocation_context_stats(const jint* contexts,
jlong* totals,
jbyte* accuracy,
jint len) {
return false;
}
/////////////// Unit tests ///////////////
NOT_PRODUCT(static void test_is_in();)
};
// Class to set and reset the GC cause for a CollectedHeap.
class GCCauseSetter : StackObj {
CollectedHeap* _heap;
GCCause::Cause _previous_cause;
public:
GCCauseSetter(CollectedHeap* heap, GCCause::Cause cause) {
assert(SafepointSynchronize::is_at_safepoint(),
"This method manipulates heap state without locking");
_heap = heap;
_previous_cause = _heap->gc_cause();
_heap->set_gc_cause(cause);
}
~GCCauseSetter() {
assert(SafepointSynchronize::is_at_safepoint(),
"This method manipulates heap state without locking");
_heap->set_gc_cause(_previous_cause);
}
};
#endif // SHARE_VM_GC_SHARED_COLLECTEDHEAP_HPP
| FauxFaux/jdk9-hotspot | src/share/vm/gc/shared/collectedHeap.hpp | C++ | gpl-2.0 | 25,700 |
showWord(["n. ","Boutik, magazen, kote yo vann. Nan ri sa a, gen anpil konmès."
]) | georgejhunt/HaitiDictionary.activity | data/words/konm~es_k~om~es_.js | JavaScript | gpl-2.0 | 83 |
<?php
if ( ! defined( 'ABSPATH' ) ) exit;
/**
* Unfortunately WordPress supports PHP 5.2 even though
* everyone should now be using at least PHP 5.3.
*
* To be compatible with PHP 5.2 below you will find functions
* that are required in order to make this plugin work correctly.
*/
add_action( 'admin_notices', 'jmfe_old_php_notice' );
add_action( 'admin_init', 'jmfe_old_php_notice_ignore' );
// PHP 5.2 does not have array_replace_recursive
if ( ! function_exists( 'array_replace_recursive' ) ) {
function array_replace_recursive( $array, $array1 ) {
if ( ! function_exists( 'compat_array_recurse' ) ) {
function compat_array_recurse( $array, $array1 ) {
foreach ( $array1 as $key => $value ) {
// create new key in $array, if it is empty or not an array
if ( ! isset( $array[ $key ] ) || ( isset( $array[ $key ] ) && ! is_array( $array[ $key ] ) ) ) {
$array[ $key ] = array();
}
// overwrite the value in the base array
if ( is_array( $value ) ) {
$value = compat_array_recurse( $array[ $key ], $value );
}
$array[ $key ] = $value;
}
return $array;
}
}
// handle the arguments, merge one by one
$args = func_get_args();
$array = $args[ 0 ];
if ( ! is_array( $array ) ) {
return $array;
}
for ( $i = 1; $i < count( $args ); $i ++ ) {
if ( is_array( $args[ $i ] ) ) {
$array = compat_array_recurse( $array, $args[ $i ] );
}
}
return $array;
}
}
if ( ! function_exists( 'jmfe_old_php_notice' ) ) {
function jmfe_old_php_notice() {
$user_id = get_current_user_id();
if ( ! get_option( 'jmfe_old_php_notice' ) ) {
echo '<div class="error"><p>';
printf( __( 'Your server is using a <strong>VERY OLD</strong> and unsupported version of PHP, version 5.2 or older. <a href="%1$s" target="_blank">EOL (End of Life)</a> for PHP 5.2 was about <strong>%2$s ago</strong>!!<br /><br />It is <strong>strongly</strong> recommended that you upgrade to PHP 5.3 or newer...you can upgrade PHP or <a href="%3$s">Hide this Notice Forever!</a><br/><br />Did you know im also the Founder and CEO of Host Tornado?<br/><a href="%4$s" target="_blank">Contact me</a> for an exclusive sMyles Plugins customer promo code discount for any shared <strong>SSD (Solid State Drive)</strong> hosting packages! Data centers in Florida USA, Arizona USA, Montreal Canada, and France. Your site will run faster than it ever has, or your money back!', 'wp-job-manager-field-editor' ), 'http://php.net/eol.php', human_time_diff( '1294272000', current_time( 'timestamp' ) ), '?jmfe_old_php_notice=0', 'https://plugins.smyl.es/contact' );
echo "</p></div>";
}
}
}
if ( ! function_exists( 'jmfe_old_php_notice_ignore' ) ) {
function jmfe_old_php_notice_ignore() {
if ( isset( $_GET[ 'jmfe_old_php_notice' ] ) && '0' == $_GET[ 'jmfe_old_php_notice' ] ) {
add_option( 'jmfe_old_php_notice', 'true' );
}
}
}
if ( ! function_exists( 'str_getcsv' ) ) {
function str_getcsv( $input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n' ) {
if ( is_string( $input ) && ! empty( $input ) ) {
$output = array();
$tmp = preg_split( "/" . $eol . "/", $input );
if ( is_array( $tmp ) && ! empty( $tmp ) ) {
while ( list( $line_num, $line ) = each( $tmp ) ) {
if ( preg_match( "/" . $escape . $enclosure . "/", $line ) ) {
while ( $strlen = strlen( $line ) ) {
$pos_delimiter = strpos( $line, $delimiter );
$pos_enclosure_start = strpos( $line, $enclosure );
if (
is_int( $pos_delimiter ) && is_int( $pos_enclosure_start )
&& ( $pos_enclosure_start < $pos_delimiter )
) {
$enclosed_str = substr( $line, 1 );
$pos_enclosure_end = strpos( $enclosed_str, $enclosure );
$enclosed_str = substr( $enclosed_str, 0, $pos_enclosure_end );
$output[ $line_num ][ ] = $enclosed_str;
$offset = $pos_enclosure_end + 3;
} else {
if ( empty( $pos_delimiter ) && empty( $pos_enclosure_start ) ) {
$output[ $line_num ][ ] = substr( $line, 0 );
$offset = strlen( $line );
} else {
$output[ $line_num ][ ] = substr( $line, 0, $pos_delimiter );
$offset = (
! empty( $pos_enclosure_start )
&& ( $pos_enclosure_start < $pos_delimiter )
)
? $pos_enclosure_start
: $pos_delimiter + 1;
}
}
$line = substr( $line, $offset );
}
} else {
$line = preg_split( "/" . $delimiter . "/", $line );
/*
* Validating against pesky extra line breaks creating false rows.
*/
if ( is_array( $line ) && ! empty( $line[ 0 ] ) ) {
$output[ $line_num ] = $line;
}
}
}
return $output;
} else {
return FALSE;
}
} else {
return FALSE;
}
}
} | Zduhamel/PT-JOB-FUSION | wp-content/plugins/wp-job-manager-field-editor/includes/compatibility.php | PHP | gpl-2.0 | 4,925 |
<div class="post-container">
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php if ( has_post_thumbnail() ) : ?>
<a class="featured-media" title="<?php the_title_attribute(); ?>" href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('post-thumb'); ?>
</a> <!-- /featured-media -->
<?php endif; ?>
<?php
$post_title = get_the_title();
if ( !empty( $post_title ) ) :
?>
<div class="post-header">
<h2 class="post-title"><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
</div> <!-- /post-header -->
<?php endif; ?>
<?php if ( empty( $post_title ) ) : ?>
<div class="posts-meta">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_time(get_option('date_format')); ?></a>
</div>
<?php endif; ?>
</div> <!-- /post -->
</div> <!-- /post-container --> | immist/herbarium-theme | wp-content/themes/fukasawa/content.php | PHP | gpl-2.0 | 1,018 |
<?php
/**
* @package Search - ZOO
* @author YOOtheme http://www.yootheme.com
* @copyright Copyright (C) YOOtheme GmbH
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
jimport('joomla.plugin.plugin');
class plgSearchZoosearchcal extends JPlugin {
/* menu item mapping */
public $menu;
public $app;
/*
Function: plgSearchZoosearch
Constructor.
Parameters:
$subject - Array
$params - Array
Returns:
Void
*/
public function plgSearchZoosearchcal($subject, $params) {
// make sure ZOO exists
if (!JComponentHelper::getComponent('com_zoo', true)->enabled) {
return;
}
parent::__construct($subject, $params);
// load config
jimport('joomla.filesystem.file');
if (!JFile::exists(JPATH_ADMINISTRATOR.'/components/com_zoo/config.php') || !JComponentHelper::getComponent('com_zoo', true)->enabled) {
return;
}
require_once(JPATH_ADMINISTRATOR.'/components/com_zoo/config.php');
$this->app = App::getInstance('zoo');
}
/*
Function: onSearchAreas
Get search areas.
Returns:
Array - Search areas
*/
public function onSearchAreas() {
static $areas = array();
return $areas;
}
/*
Function: onSearch
Get search results. The sql must return the following fields that are used in a common display routine: href, title, section, created, text, browsernav
Parameters:
$text - Target search string
$phrase - Matching option, exact|any|all
$ordering - Ordering option, newest|oldest|popular|alpha|category
$areas - An array if the search it to be restricted to areas, null if search all
Returns:
Array - Search results
*/
public function onContentSearch($text, $phrase = '', $ordering = '', $areas = null) {
$db = $this->app->database;
// init vars
$now = $db->Quote($this->app->date->create()->toSQL());
$null = $db->Quote($db->getNullDate());
$text = trim($text);
// return empty array, if no search text provided
if (empty($text)) {
return array();
}
// get plugin info
$plugin = JPluginHelper::getPlugin('search', 'zoosearchcal');
$params = $this->app->parameter->create($plugin->params);
$fulltext = $params->get('search_fulltext', 0) && strlen($text) > 3 && intval($db->getVersion()) >= 4;
$limit = $params->get('search_limit', 50);
$elements = array();
foreach ($this->app->application->groups() as $application) {
foreach($application->getTypes() as $type) {
foreach ($type->getElements() as $element) {
if (!$element->canAccess()) {
$elements[] = $db->Quote($element->identifier);
}
}
}
}
$access = $elements ? 'NOT element_id in ('.implode(',', $elements).')' : '1';
// prepare search query
switch ($phrase) {
case 'exact':
if ($fulltext) {
$text = $db->escape($text);
$where[] = "MATCH(a.name) AGAINST ('\"{$text}\"' IN BOOLEAN MODE)";
$where[] = "MATCH(b.value) AGAINST ('\"{$text}\"' IN BOOLEAN MODE) AND $access";
$where[] = "MATCH(c.name) AGAINST ('\"{$text}\"' IN BOOLEAN MODE)";
$where = implode(" OR ", $where);
} else {
$text = $db->Quote('%'.$db->escape($text, true).'%', false);
$like = array();
$like[] = 'a.name LIKE '.$text;
$like[] = "b.value LIKE $text AND $access";
$like[] = 'c.name LIKE '.$text;
$where = '(' .implode(') OR (', $like).')';
}
break;
case 'all':
case 'any':
default:
if ($fulltext) {
$text = $db->escape($text);
$where[] = "MATCH(a.name) AGAINST ('{$text}' IN BOOLEAN MODE)";
$where[] = "MATCH(b.value) AGAINST ('{$text}' IN BOOLEAN MODE) AND $access";
$where[] = "MATCH(c.name) AGAINST ('{$text}' IN BOOLEAN MODE)";
$where = implode(" OR ", $where);
} else {
$words = explode(' ', $text);
$wheres = array();
foreach ($words as $word) {
$word = $db->Quote('%'.$db->escape($word, true).'%', false);
$like = array();
$like[] = 'a.name LIKE '.$word;
$like[] = 'EXISTS (SELECT value FROM '.ZOO_TABLE_SEARCH.' WHERE a.id = item_id AND value LIKE '.$word.' AND '.$access.')';
$like[] = 'EXISTS (SELECT name FROM '.ZOO_TABLE_TAG.' WHERE a.id = item_id AND name LIKE '.$word.')';
$wheres[] = implode(' OR ', $like);
}
$where = '('.implode(($phrase == 'all' ? ') AND (' : ') OR ('), $wheres).')';
}
}
// set search ordering
switch ($ordering) {
case 'newest':
$order = 'a.created DESC';
break;
case 'oldest':
$order = 'a.created ASC';
break;
case 'popular':
$order = 'a.hits DESC';
break;
case 'alpha':
case 'category':
default:
$order = 'a.name ASC';
}
// set query options
$select = "DISTINCT a.*";
$from = ZOO_TABLE_ITEM." AS a"
." LEFT JOIN ".ZOO_TABLE_SEARCH." AS b ON a.id = b.item_id"
." LEFT JOIN ".ZOO_TABLE_TAG." AS c ON a.id = c.item_id";
$conditions = array("(".$where.")"
." AND a.searchable = 1"
." AND a.application_id = 4"
." AND a." . $this->app->user->getDBAccessString()
." AND (a.state = 1"
." AND (a.publish_up = ".$null." OR a.publish_up <= ".$now.")"
." AND (a.publish_down = ".$null." OR a.publish_down >= ".$now."))");
// execute query
$items = $this->app->table->item->all(compact('select', 'from', 'conditions', 'order', 'limit'));
// create search result rows
$rows = array();
if (!empty($items)) {
// set renderer
$renderer = $this->app->renderer->create('item')->addPath(array($this->app->path->path('component.site:'), $this->app->path->path('plugins:search/zoosearchcal/')));
foreach ($items as $item) {
$row = new stdClass();
$row->title = $item->name;
$row->text = $renderer->render('item.default', array('item' => $item));
$row->href = $this->app->route->item($item);
$row->created = $item->created;
$row->section = 'Calendrier';
$row->browsernav = 2;
$image = $item->getElement('527bd38b-0069-41b5-8052-a375832fbfb9');
$ImgUrl = $item->getElement('9b37c3fc-56cf-42c5-9334-a8079c4dfafc');
if(isset($ImgUrl)) $row->product_full_image = 'http://free.pagepeeker.com/v2/thumbs.php?size=m&url=' . $ImgUrl->getElementData()->get('value');
else if(!isset($image)){
$image = $item->getElement('1c50202a-eac4-45d3-a2e2-c76d8da0e1e8');
if(isset($image)) $row->product_full_image = $image->getElementData()->get('file');
}
$rows[] = $row;
}
}
return $rows;
}
public function registerZOOEvents() {
if ($this->app) {
$this->app->event->dispatcher->connect('type:assignelements', array($this, 'assignElements'));
}
}
public function assignElements() {
$this->app->system->application->enqueueMessage(JText::_('Only text based elements are allowed in the search layouts'), 'notice');
}
} | knigherrant/decopatio | plugins/search/zoosearchcal/zoosearchcal.php | PHP | gpl-2.0 | 7,125 |
/*
* Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.imageio.stream;
import java.io.Closeable;
import java.io.IOException;
import sun.java2d.DisposerRecord;
/**
* Convenience class that closes a given resource (e.g. RandomAccessFile),
* typically associated with an Image{Input,Output}Stream, prior to the
* stream being garbage collected.
*/
public class CloseableDisposerRecord implements DisposerRecord {
private Closeable closeable;
public CloseableDisposerRecord(Closeable closeable) {
this.closeable = closeable;
}
public synchronized void dispose() {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
} finally {
closeable = null;
}
}
}
}
| TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/com/sun/imageio/stream/CloseableDisposerRecord.java | Java | gpl-2.0 | 1,969 |
@extends("admin.main")
@section("content")
<h1 class="title">Post add</h1>
@include('errors.list')
{!! Form::open(["action" => "Admin\PostsController@store", "method" => "POST", "class" => "form-horizontal"]) !!}
<!--- Title Field --->
<div class="form-group">
{!! Form::label('title', 'Title:') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
<!--- Description Field --->
<div class="form-group">
{!! Form::label('description', 'Description:') !!}
{!! Form::textarea('description', null, ['class' => 'form-control html']) !!}
</div>
<!--- Content Field --->
<div class="form-group">
{!! Form::label('content', 'Content:') !!}
{!! Form::textarea('content', null, ['class' => 'form-control html']) !!}
</div>
<div class="form-group">
{!! Form::label('content', 'Cover:') !!}
<div class="input-group">
<input type="text" name="cover" class="form-control" id="js-cover-input" placeholder="Path or url">
<span class="input-group-btn">
<button class="btn btn-default js-uploader" type="button" data-input="#js-cover-input">Choose</button>
</span>
</div><!-- /input-group -->
</div><!-- /input-group -->
<div class="col-xs-5 state-box">
<!--- Select state Field --->
<div class="form-group col-xs-5">
{!! Form::label('state', 'State:') !!}
{!! Form::select('state', [0 => "Disabled", 1 => "Enabled", 2 => "Show after date"], 1, ['class' => 'form-control']) !!}
</div>
<!--- Show date Field --->
<div class="form-group col-xs-6">
{!! Form::label('Show after:', 'Show date:') !!}
{!! Form::text('Show after:', null, ['class' => 'form-control datepicker']) !!}
</div>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
<div class="form-group">
<button class="btn btn-default">Add</button>
</div>
{!! Form::close() !!}
@include('admin.upload')
@endsection | avengerweb/my-own-blog | resources/views/admin/blog/posts/add.blade.php | PHP | gpl-2.0 | 2,111 |
/*
*@BEGIN LICENSE
*
* PSI4: an ab initio quantum chemistry software package
*
* 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.
*
*@END LICENSE
*/
/*! \file
\ingroup CCHBAR
\brief Enter brief description of file here
*/
#include <cstdio>
#include <libdpd/dpd.h>
#include "MOInfo.h"
#include "Params.h"
#define EXTERN
#include "globals.h"
namespace psi { namespace cchbar {
/* Wabei_UHF(): Computes all contributions to the abei spin case of
** the Wabei HBAR matrix elements. The final product is stored in
** (ei,ab) ordering and is referred to on disk as "Wabei".
**
** The spin-orbital expression for the Wabei elements is:
**
** Wabei = <ab||ei> - Fme t_mi^ab + t_i^f <ab||ef>
** - P(ab) t_m^b <am||ef>t_i^f + 1/2 tau_mn^ab <mn||ef> t_i^f
** + 1/2 <mn||ei> tau_mn^ab - P(ab) <mb||ef> t_mi^af
** - P(ab) t_m^a { <mb||ei> - t_ni^bf <mn||ef> }
**
** (cf. Gauss and Stanton, JCP 103, 3561-3577 (1995).)
**
** For the abei spin case, we evaluate these contractions with two
** target orderings, (ab,ei) and (ei,ab), depending on the term.
** After all terms have been evaluated, the (ab,ei) terms are sorted
** into (ei,ab) ordering and both groups arer added together.
**
** TDC, June 2002
*/
void Wabei_UHF(void)
{
dpdfile2 Fme, T1;
dpdbuf4 F, W, T2, B, Z, Z1, Z2, D, T, E, C;
/**** Term I ****/
/** W(ei,ab) <--- <ei||ab> **/
global_dpd_->buf4_init(&F, PSIF_CC_FINTS, 0, 31, 17, 31, 15, 1, "F <ai|bc>");
global_dpd_->buf4_copy(&F, PSIF_CC_HBAR, "Weiab");
global_dpd_->buf4_close(&F);
/**** Term II ****/
/** W(ei,ab) <--- - F_me t_mi^ab **/
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 10, 17, 12, 17, 0, "tijab");
global_dpd_->file2_init(&Fme, PSIF_CC_OEI, 0, 2, 3, "Fme");
global_dpd_->buf4_init(&W, PSIF_CC_HBAR, 0, 31, 17, 31, 17, 0, "Weiab");
global_dpd_->contract244(&Fme, &T2, &W, 0, 0, 0, -1.0, 1.0);
global_dpd_->buf4_close(&W);
global_dpd_->file2_close(&Fme);
global_dpd_->buf4_close(&T2);
/**** Term III ****/
/** <ab||ef> t_i^f **/
global_dpd_->buf4_init(&W, PSIF_CC_TMP0, 0, 17, 31, 17, 31, 0, "W'(ab,ei)");
global_dpd_->buf4_init(&B, PSIF_CC_BINTS, 0, 17, 15, 15, 15, 1, "B <ab|cd>");
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 2, 3, "tia");
global_dpd_->contract424(&B, &T1, &W, 3, 1, 0, 1.0, 0.0);
global_dpd_->file2_close(&T1);
global_dpd_->buf4_close(&B);
global_dpd_->buf4_close(&W);
/**** Term IV ****/
/** Wabei <-- t_m^b <ma||ef> t_i^f - t_m^a <mb||ef> t_i^f
Evaluate in two steps:
(1) Z_mbei = <mb||ef> t_i^f
(2) Wabei <-- t_m^b Z_maei - t_m^a Z_mbei
**/
/** Z(mb,ei) <-- - <mb||ef> t_i^f **/
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 30, 31, 30, 31, 0, "Z(mb,ei)");
global_dpd_->buf4_init(&F, PSIF_CC_FINTS, 0, 30, 15, 30, 15, 1, "F <ia|bc>");
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 2, 3, "tia");
global_dpd_->contract424(&F, &T1, &Z, 3, 1, 0, -1.0, 0.0);
global_dpd_->file2_close(&T1);
global_dpd_->buf4_close(&F);
global_dpd_->buf4_close(&Z);
/** t_m^a Z(mb,ei) --> Z1(ab,ei) **/
global_dpd_->buf4_init(&Z1, PSIF_CC_TMP0, 0, 15, 31, 15, 31, 0, "Z1(ab,ei)");
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 30, 31, 30, 31, 0, "Z(mb,ei)");
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 2, 3, "tia");
global_dpd_->contract244(&T1, &Z, &Z1, 0, 0, 0, 1.0, 0.0);
global_dpd_->file2_close(&T1);
global_dpd_->buf4_close(&Z);
global_dpd_->buf4_sort(&Z1, PSIF_CC_TMP0, qprs, 15, 31, "Z2(ba,ei)");
global_dpd_->buf4_close(&Z1);
/** Z1(ab,ei) - Z2(ba,ei) --> Z(ab,ei) **/
global_dpd_->buf4_init(&Z1, PSIF_CC_TMP0, 0, 15, 31, 15, 31, 0, "Z1(ab,ei)");
global_dpd_->buf4_init(&Z2, PSIF_CC_TMP0, 0, 15, 31, 15, 31, 0, "Z2(ba,ei)");
global_dpd_->buf4_axpy(&Z2, &Z1, -1.0);
global_dpd_->buf4_close(&Z2);
global_dpd_->buf4_init(&W, PSIF_CC_TMP0, 0, 15, 31, 17, 31, 0, "W'(ab,ei)");
global_dpd_->buf4_axpy(&Z1, &W, 1.0);
global_dpd_->buf4_close(&W);
global_dpd_->buf4_close(&Z1);
/**** Term V ****/
/** Wabei <-- 1/2 tau_mn^ab <mn||ef> t_i^f
Evaluate in two steps:
(1) Z_mnei = <mn||ei> t_i^f
(2) Wabei <-- 1/2 tau_mn^ab Z_mnei
Store target in W'(ab,ei)
**/
/** Z(mn,ei) <-- <mn||ef> t_i^f **/
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 12, 31, 12, 31, 0, "Z(mn,ei)");
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 12, 15, 12, 15, 0, "D <ij||ab> (i>j,ab)");
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 2, 3, "tia");
global_dpd_->contract424(&D, &T1, &Z, 3, 1, 0, 1, 0);
global_dpd_->file2_close(&T1);
global_dpd_->buf4_close(&D);
global_dpd_->buf4_close(&Z);
/** tau_mn^ab Z(mn,ei) --> W'(ab,ei) **/
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 12, 31, 12, 31, 0, "Z(mn,ei)");
global_dpd_->buf4_init(&W, PSIF_CC_TMP0, 0, 17, 31, 17, 31, 0, "W'(ab,ei)");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 12, 17, 12, 17, 0, "tauijab");
global_dpd_->contract444(&T2, &Z, &W, 1, 1, 1, 1);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&W);
global_dpd_->buf4_close(&Z);
/**** Term VI ****/
/** tau_mn^ab <mn||ei> --> W'(ab,ei) **/
global_dpd_->buf4_init(&W, PSIF_CC_TMP0, 0, 17, 31, 17, 31, 0, "W'(ab,ei)");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 12, 17, 12, 17, 0, "tauijab");
global_dpd_->buf4_init(&E, PSIF_CC_EINTS, 0, 12, 31, 12, 31, 0, "E <ij||ka> (i>j,ak)");
global_dpd_->contract444(&T2, &E, &W, 1, 1, -1, 1);
global_dpd_->buf4_close(&E);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&W);
/**** Term VII ****/
/** Wabei <-- <bm||ef> t_im^af + <bM|eF> t_iM^aF - <am||ef> t_im^bf - <aM|eF> t_iM^bF
Evaluate in six steps:
(1) Sort <bm||ef> and <bM|eF> to F(be,mf) and F(be,MF) ordering.
(2) Z(be,ia) = F(be,mf) T(ia,mf) + F(be,MF) T(ia,MF)
(3) Sort Z(be,ia) --> Z'(ei,ab)
(4) Sort Z'(ei,ab) --> Z''(ei,ba)
(5) AXPY: Z'(ei,ab) = Z'(ei,ab) - Z''(ei,ba)
(6) AXPY: W(ei,ab) <-- Z'(ei,ab)
NB: The storage for the sorts is expensive and will eventually require out-of-core
codes.
**/
/** <bm||ef> --> F(be,mf) **/
global_dpd_->buf4_init(&F, PSIF_CC_FINTS, 0, 31, 15, 31, 15, 1, "F <ai|bc>");
global_dpd_->buf4_sort(&F, PSIF_CC_FINTS, prqs, 15, 30, "F <ai||bc> (ab,ic)");
global_dpd_->buf4_close(&F);
/** <bM|eF> --> (be,MF) **/
global_dpd_->buf4_init(&F, PSIF_CC_FINTS, 0, 25, 29, 25, 29, 0, "F <aI|bC>");
global_dpd_->buf4_sort(&F, PSIF_CC_FINTS, prqs, 15, 20, "F <aI|bC> (ab,IC)");
global_dpd_->buf4_close(&F);
/** <bm||ef> t_im^af --> Z(be,ia) **/
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 15, 30, 15, 30, 0, "Z(be,ia)");
global_dpd_->buf4_init(&F, PSIF_CC_FINTS, 0, 15, 30, 15, 30, 0, "F <ai||bc> (ab,ic)");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 30, 30, 30, 30, 0, "tiajb");
global_dpd_->contract444(&F, &T2, &Z, 0, 0, -1, 0);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&F);
global_dpd_->buf4_close(&Z);
/** <bm|eF> t_iM^aF --> Z(be,ia) **/
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 15, 30, 15, 30, 0, "Z(be,ia)");
global_dpd_->buf4_init(&F, PSIF_CC_FINTS, 0, 15, 20, 15, 20, 0, "F <aI|bC> (ab,IC)");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 30, 20, 30, 20, 0, "tiaJB");
global_dpd_->contract444(&F, &T2, &Z, 0, 0, -1, 1);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&F);
global_dpd_->buf4_close(&Z);
/** Z(be,ia) --> Z'(ei,ab) **/
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 15, 30, 15, 30, 0, "Z(be,ia)");
global_dpd_->buf4_sort(&Z, PSIF_CC_TMP0, qrsp, 31, 15, "Z'(ei,ab)");
global_dpd_->buf4_close(&Z);
/** Z'(ei,ab) --> Z''(ei,ba) **/
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 31, 15, 31, 15, 0, "Z'(ei,ab)");
global_dpd_->buf4_sort(&Z, PSIF_CC_TMP0, pqsr, 31, 15, "Z''(ei,ba)");
global_dpd_->buf4_close(&Z);
/** Z'(ei,ab) = Z'(ei,ab) - Z''(ei,ba) **/
global_dpd_->buf4_init(&Z1, PSIF_CC_TMP0, 0, 31, 15, 31, 15, 0, "Z'(ei,ab)");
global_dpd_->buf4_init(&Z2, PSIF_CC_TMP0, 0, 31, 15, 31, 15, 0, "Z''(ei,ba)");
global_dpd_->buf4_axpy(&Z2, &Z1, -1);
global_dpd_->buf4_close(&Z2);
global_dpd_->buf4_close(&Z1);
/** W(ei,ab) <-- Z'(ei,ab) **/
global_dpd_->buf4_init(&W, PSIF_CC_HBAR, 0, 31, 15, 31, 17, 0, "Weiab");
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 31, 15, 31, 15, 0, "Z'(ei,ab)");
global_dpd_->buf4_axpy(&Z, &W, 1);
global_dpd_->buf4_close(&Z);
global_dpd_->buf4_close(&W);
/**** Terms VIII and IX ****/
/** Wabei <-- -P(ab) t_m^a { <mb||ei> + t_in^bf <mn||ef> + t_iN^bF <mN|eF> }
Evaluate in two steps:
(1) Z_mbei = <mb||ei> + t_in^bf <mn||ef> + tiN^bF <mN|eF>
(2) Wabei <-- - t_m^a Z_mbei + t_m^b Z_maei
Store target in W'(ab,ei)
**/
/** Z(mb,ei) <-- <mb||ei> **/
global_dpd_->buf4_init(&C, PSIF_CC_CINTS, 0, 30, 31, 30, 31, 0, "C <ia||jb> (ia,bj)");
global_dpd_->buf4_copy(&C, PSIF_CC_TMP0, "Z(mb,ei)");
global_dpd_->buf4_close(&C);
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 30, 31, 30, 31, 0, "Z(mb,ei)");
global_dpd_->buf4_scm(&Z, -1);
global_dpd_->buf4_close(&Z);
/** <mn||ef> t_in^bf --> Z(me,ib) **/
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 30, 30, 30, 30, 0, "Z(me,ib)");
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 30, 30, 30, 30, 0, "D <ij||ab> (ia,jb)");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 30, 30, 30, 30, 0, "tiajb");
global_dpd_->contract444(&D, &T2, &Z, 0, 0, 1, 0);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&D);
global_dpd_->buf4_close(&Z);
/** <mN|eF> t_iN^bF --> Z(me,ib) **/
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 30, 30, 30, 30, 0, "Z(me,ib)");
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 30, 20, 30, 20, 0, "D <Ij|Ab> (ia,JB)");
global_dpd_->buf4_init(&T2, PSIF_CC_TAMPS, 0, 30, 20, 30, 20, 0, "tiaJB");
global_dpd_->contract444(&D, &T2, &Z, 0, 0, 1, 1);
global_dpd_->buf4_close(&T2);
global_dpd_->buf4_close(&D);
global_dpd_->buf4_close(&Z);
/** Z(me,ib) --> Z(mb,ei) **/
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 30, 30, 30, 30, 0, "Z(me,ib)");
global_dpd_->buf4_sort_axpy(&Z, PSIF_CC_TMP0, psqr, 30, 31, "Z(mb,ei)", 1);
global_dpd_->buf4_close(&Z);
/** Z(ab,ei) <-- -t_m^a Z(mb,ei) **/
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 15, 31, 15, 31, 0, "Z(ab,ei)");
global_dpd_->buf4_init(&Z1, PSIF_CC_TMP0, 0, 30, 31, 30, 31, 0, "Z(mb,ei)");
global_dpd_->file2_init(&T1, PSIF_CC_OEI, 0, 2, 3, "tia");
global_dpd_->contract244(&T1, &Z1, &Z, 0, 0, 0, -1, 0);
global_dpd_->file2_close(&T1);
global_dpd_->buf4_close(&Z1);
global_dpd_->buf4_close(&Z);
/** Z(ab,ei) --> Z'(ba,ei) **/
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 15, 31, 15, 31, 0, "Z(ab,ei)");
global_dpd_->buf4_sort(&Z, PSIF_CC_TMP0, qprs, 15, 31, "Z'(ba,ei)");
global_dpd_->buf4_close(&Z);
/** Z(ab,ei) = Z(ab,ei) - Z'(ba,ei) **/
global_dpd_->buf4_init(&Z1, PSIF_CC_TMP0, 0, 15, 31, 15, 31, 0, "Z(ab,ei)");
global_dpd_->buf4_init(&Z2, PSIF_CC_TMP0, 0, 15, 31, 15, 31, 0, "Z'(ba,ei)");
global_dpd_->buf4_axpy(&Z2, &Z1, -1);
global_dpd_->buf4_close(&Z2);
global_dpd_->buf4_close(&Z1);
/** Z(ab,ei) --> W'(ab,ei) **/
global_dpd_->buf4_init(&Z, PSIF_CC_TMP0, 0, 15, 31, 15, 31, 0, "Z(ab,ei)");
global_dpd_->buf4_init(&W, PSIF_CC_TMP0, 0, 15, 31, 17, 31, 0, "W'(ab,ei)");
global_dpd_->buf4_axpy(&Z, &W, 1.0);
global_dpd_->buf4_close(&W);
global_dpd_->buf4_close(&Z);
/**** Combine accumulated W'(ab,ei) and W(ei,ab) terms into Weiab ****/
global_dpd_->buf4_init(&W, PSIF_CC_TMP0, 0, 17, 31, 17, 31, 0, "W'(ab,ei)");
global_dpd_->buf4_sort_axpy(&W, PSIF_CC_HBAR, rspq, 31, 17, "Weiab", 1);
global_dpd_->buf4_close(&W);
}
}} // namespace psi::cchbar
| spring01/libPSI | src/bin/cchbar/Wabei_BBBB_UHF.cc | C++ | gpl-2.0 | 12,328 |
package org.insightcentre.unlp.naisc.wordalign;
import java.util.Map;
/**
* A factory for making word alignment feature extractors
*
* @author John McCrae <john@mccr.ae>
*/
public interface WordAlignmentFeatureExtractorFactory {
/**
* An identifier for this WAFE
* @return The identifier
*/
String id();
/**
* Creata a new word alignment feature extractor
* @param params The parameters of the configuration file
* @return The WAFE
*/
WordAlignmentFeatureExtractor make(Map<String, Object> params);
}
| jmccrae/naisc | word-align/src/main/java/org/insightcentre/unlp/naisc/wordalign/WordAlignmentFeatureExtractorFactory.java | Java | gpl-2.0 | 560 |
<?php
/**
* @package EasyDiscuss
* @copyright Copyright (C) 2010 Stack Ideas Private Limited. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* EasyDiscuss is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
defined('_JEXEC') or die('Restricted access');
require_once DISCUSS_ADMIN_ROOT . '/views.php';
class EasyDiscussViewSpools extends EasyDiscussAdminView
{
public function display($tpl = null)
{
// Initialise variables
$mainframe = JFactory::getApplication();
$filter_state = $mainframe->getUserStateFromRequest( 'com_easydiscuss.spools.filter_state', 'filter_state', '*', 'word' );
$search = $mainframe->getUserStateFromRequest( 'com_easydiscuss.spools.search', 'search', '', 'string' );
$search = trim(JString::strtolower( $search ) );
$order = $mainframe->getUserStateFromRequest( 'com_easydiscuss.spools.filter_order', 'filter_order', 'created', 'cmd' );
$orderDirection = $mainframe->getUserStateFromRequest( 'com_easydiscuss.spools.filter_order_Dir', 'filter_order_Dir', 'asc', 'word' );
$mails = $this->get( 'Data' );
$pagination = $this->get( 'Pagination' );
$this->assign( 'mails' , $mails );
$this->assign( 'pagination' , $pagination );
$this->assign( 'state' , JHTML::_('grid.state', $filter_state , JText::_( 'COM_EASYDISCUSS_SENT' ) , JText::_( 'COM_EASYDISCUSS_PENDING' ) ) );
$this->assign( 'search' , $search );
$this->assign( 'order' , $order );
$this->assign( 'orderDirection' , $orderDirection );
parent::display($tpl);
}
public function registerToolbar()
{
JToolBarHelper::title( JText::_( 'COM_EASYDISCUSS_SPOOLS_TITLE' ), 'spools' );
JToolBarHelper::custom( 'home', 'arrow-left', '', JText::_( 'COM_EASYDISCUSS_TOOLBAR_HOME' ), false);
JToolBarHelper::divider();
JToolbarHelper::deleteList();
JToolBarHelper::divider();
JToolBarHelper::custom('purge','purge','icon-32-unpublish.png', 'COM_EASYDISCUSS_SPOOLS_PURGE_ALL_BUTTON', false);
}
}
| awc737/rcc-joomla | administrator/components/com_easydiscuss/views/spools/view.html.php | PHP | gpl-2.0 | 2,228 |
<?
/**********************************************************************
* N/X - Web Content Management System
* Copyright 2002 Sven Weih, FZI Research Center for Information Technologies
* www.fzi.de
*
* This file is part of N/X.
* The initial has been setup as a small diploma thesis (Studienarbeit) at the FZI.
* It was be coached by Prof. Werner Zorn and Dipl.-Inform Thomas Gauweiler.
*
* N/X 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.
*
* N/X 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 N/X; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
**********************************************************************/
/**
* Create a new Set for updating one or several records to the database.
* Do not call directly but use the addUpdate method!
* @package Database
*/
class UpdateSet extends SaveSet {
/**
* standard constructor
* @param string Name of the table you want to modify
* @param string Where-Condition for SQL-Clause
*/
function UpdateSet($table, $row_identifier) { SaveSet::SaveSet($table, $row_identifier); }
/**
* generates and executes the Updatestatement towards the database.
*/
function execute() {
global $db, $errors;
if ($this->counter > 0) {
$str = "UPDATE $this->table SET ";
$commaflag = false;
for ($i = 0; $i < $this->counter; $i++) {
if ($commaflag)
$str .= ", ";
$str .= $this->columns[$i] . " = " . $this->values[$i];
$commaflag = true;
}
$str .= " WHERE $this->row_identifier";
global $debug;
if ($debug)
echo "UPDATE: $str <br>";
$query = new query($db, $str);
if (trim($db->error()) != "0:")
$errors .= "-DBUpdate";
}
}
}
?> | sweih/nxr | cms/api/database/updateset.php | PHP | gpl-2.0 | 2,342 |
@extends('defaults.masterpage')
@section('header')
{{ HTML::style('css/main.css') }}
<title>Edit Booking</title>
@stop
@section('content')
<center>
<div id="cover" >
{{Form::open(['route'=>'booking.store'])}}
<table id = "tabler" >
<tr>
<th colspan = "2"> Fill The Form To Edit An Appoindment</th>
</tr>
<tr>
<td> {{Form::label('file_number','File Number:')}}</td>
<td> {{Form::input('text','file_number')}}{{ $errors->first('name', '<span class=error>:message></span>') }}</td>
</tr>
<tr>
<td>{{Form::label('section_to_visit','Visiting Section:')}}</td>
<td>{{Form::input('text','section_to_visit')}}</td>
</tr>
<tr>
<td>{{Form::label('doctor_assigned','Doctor Assigned:')}}</td>
<td>{{Form::input('text','doctor_assigned')}}</td>
</tr>
<tr>
<td>{{Form::submit('Book Up')}}</td>
</tr>
</table>
{{Form::close()}}
</div>
</center>
@stop
@section('footer')
<center><p>A luke Dennis production . dennisluke44@gmail.com</p></center>
@stop | Meritei/FINAL-MTRH | Mtrh/app/views/booking/edit.blade.php | PHP | gpl-2.0 | 1,163 |
tinyMCE.addI18n("ru.len-slider",{
title : "Шорткод для вставки LenSlider"
}); | gritz99/SOAP | wp-content/plugins/len-slider/js/langs/ru.js | JavaScript | gpl-2.0 | 97 |
namespace Api.HelpPage.Areas.HelpPage.ModelDescriptions
{
/// <summary>
///
/// </summary>
public class DictionaryModelDescription : KeyValuePairModelDescription
{
}
} | victorxata/bartrade.rocks | Api.HelpPage/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs | C# | gpl-2.0 | 192 |
<?php
/* * *************************************************************************************************** */
// Generate option tabs content
/* * *************************************************************************************************** */
function nimbus_field_engine() {
global $allowedtags, $NIMBUS_FONT_FACES, $NIMBUS_OPTIONS_ARR;
$option_name = THEME_OPTIONS;
$theme_options = get_option(THEME_OPTIONS);
$options = $NIMBUS_OPTIONS_ARR;
$section_return = array();
foreach ($options as $option) {
$section_return[$option['tab']] = '';
}
foreach ($options as $option) {
// Set option variables
if (isset($option['classes'])) {
$classes = $option['classes'];
}
if (isset($option['label'])) {
$label = $option['label'];
}
// Set field number variable
if (($option['type'] == "tab")) {
unset($field_num);
$field_num = 1;
}
// Do stuff excluding tabs and html.
if (($option['type'] != "tab") && ($option['type'] != "html")) {
// Set value for default and override with saved option if set.
$value = '';
if (isset($option['default'])) {
$value = $option['default'];
}
if (isset($theme_options[($option['id'])])) {
$value = $theme_options[($option['id'])];
}
// Begin option, wrap all with basic title and wrappers.
$section_return[$option['tab']] .= '<div id="' . $option['id'] . '_option_wrapper" class="option_wrapper">' . "\n";
$section_return[$option['tab']] .= '<div class="option_info_column">' . "\n";
$section_return[$option['tab']] .= '<div class="option_number">' . $field_num . '</div>' . "\n";
/*
if (isset($option['info'])) {
$section_return[$option['tab']] .= '<a class="info_box_button" href="#' . $option['id'] . '_info"><img src="' . get_template_directory_uri() . '/nimbus/images/info_button.png" alt="Info Window" /></a>' . "\n";
}
*/
if (isset($option['video'])) {
$section_return[$option['tab']] .= '<img src="' . get_template_directory_uri() . '/nimbus/images/vid_button.png" alt="Video Window" />' . "\n";
}
$section_return[$option['tab']] .= '</div>' . "\n";
$section_return[$option['tab']] .= '<div id="' . $option['id'] . '_option_right" class="option_right">' . "\n";
$section_return[$option['tab']] .= '<p class="option_name">' . $option['name'] . '</p>' . "\n";
// Include descrtiption if availible.
if (isset($option['desc'])) {
$section_return[$option['tab']] .= '<p class="option_description">' . $option['desc'] . '</p>' . "\n";
}
}
// Construct text field.
if ($option['type'] == "text") {
$section_return[$option['tab']] .= '<input id="' . $option['id'] . '" class="' . $classes . '" name="' . esc_attr($option_name . '[' . $option['id'] . ']') . '" type="text" value="' . esc_attr($value) . '" />' . "\n";
$field_num++;
// Construct textarea.
} elseif ($option['type'] == "textarea") {
$section_return[$option['tab']] .= '<textarea id="' . $option['id'] . '" class="' . $classes . '" name="' . esc_attr($option_name . '[' . $option['id'] . ']') . '" >' . esc_textarea($value) . '</textarea>' . "\n";
$field_num++;
// Construct select.
} elseif ($option['type'] == "select") {
$section_return[$option['tab']] .= '<select class="' . $classes . '" name="' . esc_attr($option_name . '[' . $option['id'] . ']') . '" id="' . esc_attr($option['id']) . '">' . "\n";
foreach ($option['options'] as $key => $select) {
$section_return[$option['tab']] .= '<option ' . selected($value, $key, false) . ' value="' . esc_attr($key) . '">' . esc_html($select) . '</option>' . "\n";
}
$section_return[$option['tab']] .= '</select>' . "\n";
$field_num++;
// Construct Font Select.
} elseif ($option['type'] == "typography") {
// Font Face
$section_return[$option['tab']] .= '<div class="split_select_left">' . "\n";
$section_return[$option['tab']] .= '<p>Font Face: ( * Google Web Font )</p>' . "\n";
$section_return[$option['tab']] .= '<select class="' . $classes . '" name="' . esc_attr($option_name . '[' . $option['id'] . '][face]') . '" id="' . esc_attr($option['id'] . '_face') . '">' . "\n";
$faces = $NIMBUS_FONT_FACES;
ksort($faces);
foreach ($faces as $key => $face) {
$section_return[$option['tab']] .= '<option value="' . esc_attr($key) . '" ' . selected($value['face'], $key, false) . '>' . esc_html($face['name']) . '</option>' . "\n";
}
$section_return[$option['tab']] .= '</select>' . "\n";
$section_return[$option['tab']] .= '</div>' . "\n";
// Font Size
$section_return[$option['tab']] .= '<div class="split_select_right">' . "\n";
$section_return[$option['tab']] .= '<p>Font Size</p>' . "\n";
$section_return[$option['tab']] .= '<select class="' . $classes . '" name="' . esc_attr($option_name . '[' . $option['id'] . '][size]') . '" id="' . esc_attr($option['id'] . '_size') . '">' . "\n";
for ($i = 6; $i < 66; $i++) {
$font_size = $i . 'px';
$section_return[$option['tab']] .= '<option value="' . esc_attr($font_size) . '" ' . selected($value['size'], $font_size, false) . '>' . esc_html($font_size) . '</option>' . "\n";
}
$section_return[$option['tab']] .= '</select>' . "\n";
$section_return[$option['tab']] .= '</div><div class="clear10"></div>' . "\n";
// Line-Height
$section_return[$option['tab']] .= '<div class="split_select_left">' . "\n";
$section_return[$option['tab']] .= '<p>Line Height</p>' . "\n";
$section_return[$option['tab']] .= '<select class="' . $classes . '" name="' . esc_attr($option_name . '[' . $option['id'] . '][line]') . '" id="' . esc_attr($option['id'] . '_line') . '">' . "\n";
$line_begin = 0.5;
$line_increment = 0.1;
for ($i = 0; $i < 16; $i++) {
$line_height = ($line_begin + $line_increment * $i) . 'em';
$section_return[$option['tab']] .= '<option value="' . esc_attr($line_height) . '" ' . selected($value['line'], $line_height, false) . '>' . esc_html($line_height) . '</option>' . "\n";
}
$section_return[$option['tab']] .= '</select>' . "\n";
$section_return[$option['tab']] .= '</div>' . "\n";
// Font Style
$section_return[$option['tab']] .= '<div class="split_select_right">' . "\n";
$section_return[$option['tab']] .= '<p>Font Style</p>' . "\n";
$styles = nimbus_font_styles();
$section_return[$option['tab']] .= '<select class="' . $classes . '" name="' . $option_name . '[' . $option['id'] . '][style]" id="' . $option['id'] . '_style">' . "\n";
foreach ($styles as $key => $style) {
$section_return[$option['tab']] .= '<option value="' . esc_attr($key) . '" ' . selected($value['style'], $key, false) . '>' . $style . '</option>' . "\n";
}
$section_return[$option['tab']] .= '</select>' . "\n";
$section_return[$option['tab']] .= '</div><div class="clear10"></div>' . "\n";
// Text Transform
$section_return[$option['tab']] .= '<div class="split_select_left">' . "\n";
$section_return[$option['tab']] .= '<p>Font Case</p>' . "\n";
$cases = nimbus_font_transform();
$section_return[$option['tab']] .= '<select class="' . $classes . '" name="' . $option_name . '[' . $option['id'] . '][fonttrans]" id="' . $option['id'] . '_case">' . "\n";
foreach ($cases as $key => $case) {
$section_return[$option['tab']] .= '<option value="' . esc_attr($key) . '" ' . selected($value['fonttrans'], $key, false) . '>' . $case . '</option>' . "\n";
}
$section_return[$option['tab']] .= '</select>' . "\n";
$section_return[$option['tab']] .= '</div>' . "\n";
// Font Color
$section_return[$option['tab']] .= '<div class="split_select_right_color">' . "\n";
$section_return[$option['tab']] .= '<p>Font Color</p>' . "\n";
$section_return[$option['tab']] .= '<div id="' . esc_attr($option['id']) . '_color_picker" class="colorSelector"><div style="' . esc_attr('background-color:' . $value['color']) . '"></div></div>';
$section_return[$option['tab']] .= '<input class="' . $classes . ' hex_field" name="' . esc_attr($option_name . '[' . $option['id'] . '][color]') . '" id="' . esc_attr($option['id'] . '_color') . '" type="text" value="' . esc_attr($value['color']) . '" />';
$section_return[$option['tab']] .= '</div><div class="clear10"></div>' . "\n";
$field_num++;
// Construct checkbox.
} elseif ($option['type'] == "checkbox") {
$section_return[$option['tab']] .= '<input id="' . $option['id'] . '" class="' . $classes . '" type="checkbox" name="' . esc_attr($option_name . '[' . $option['id'] . ']') . '" ' . checked($value, 1, false) . ' /><span class="checkbox_label">' . $label . '</span>';
$field_num++;
// Construct multiple checkboxes
} elseif ($option['type'] == "multicheck") {
foreach ($option['options'] as $key => $multi) {
$checked = '';
$label = $multi;
$multi = preg_replace('/[^a-zA-Z0-9._\-]/', '', strtolower($key));
$id = $option_name . '-' . $option['id'] . '-' . $multi;
$name = $option_name . '[' . $option['id'] . '][' . $multi . ']';
if (isset($value[$multi])) {
$checked = checked($value[$multi], 1, false);
}
$section_return[$option['tab']] .= '<input id="' . esc_attr($id) . '" class="' . $classes . '" type="checkbox" name="' . esc_attr($name) . '" ' . $checked . ' /><label for="' . esc_attr($id) . '">' . esc_html($label) . '</label><br />';
}
$field_num++;
// Construct radio.
} elseif ($option['type'] == "radio") {
$name = $option_name . '[' . $option['id'] . ']';
foreach ($option['options'] as $key => $radio) {
$id = $option_name . '-' . $option['id'] . '-' . $key;
$section_return[$option['tab']] .= '<input class="' . $classes . '" type="radio" name="' . esc_attr($name) . '" id="' . esc_attr($id) . '" value="' . esc_attr($key) . '" ' . checked($value, $key, false) . ' /><label for="' . esc_attr($id) . '">' . esc_html($radio) . '</label><br />';
}
$field_num++;
// Font Face/Color
} elseif ($option['type'] == "font") {
// Font Face
$section_return[$option['tab']] .= '<div class="split_select_left">' . "\n";
$section_return[$option['tab']] .= '<p>Font Face</p>' . "\n";
$section_return[$option['tab']] .= '<select class="' . $classes . '" name="' . esc_attr($option_name . '[' . $option['id'] . '][face]') . '" id="' . esc_attr($option['id'] . '_face') . '">' . "\n";
$faces = $NIMBUS_FONT_FACES;
ksort($faces);
foreach ($faces as $key => $face) {
$section_return[$option['tab']] .= '<option value="' . esc_attr($key) . '" ' . selected($value['face'], $key, false) . '>' . esc_html($face['name']) . '</option>' . "\n";
}
$section_return[$option['tab']] .= '</select>' . "\n";
$section_return[$option['tab']] .= '</div>' . "\n";
// Font Color
$section_return[$option['tab']] .= '<div class="split_select_right_color">' . "\n";
$section_return[$option['tab']] .= '<p>Font Color</p>' . "\n";
$section_return[$option['tab']] .= '<div id="' . esc_attr($option['id']) . '_color_picker" class="colorSelector"><div style="' . esc_attr('background-color:' . $value['color']) . '"></div></div>';
$section_return[$option['tab']] .= '<input class="' . $classes . ' hex_field" name="' . esc_attr($option_name . '[' . $option['id'] . '][color]') . '" id="' . esc_attr($option['id'] . '_color') . '" type="text" value="' . esc_attr($value['color']) . '" />';
$section_return[$option['tab']] .= '</div><div class="clear10"></div>' . "\n";
$field_num++;
// Font Face Only
} elseif ($option['type'] == "face") {
// Font Face
$section_return[$option['tab']] .= '<div class="split_select_left">' . "\n";
$section_return[$option['tab']] .= '<p>Font Face</p>' . "\n";
$section_return[$option['tab']] .= '<select class="' . $classes . '" name="' . esc_attr($option_name . '[' . $option['id'] . '][face]') . '" id="' . esc_attr($option['id'] . '_face') . '">' . "\n";
$faces = $NIMBUS_FONT_FACES;
ksort($faces);
foreach ($faces as $key => $face) {
$section_return[$option['tab']] .= '<option value="' . esc_attr($key) . '" ' . selected($value['face'], $key, false) . '>' . esc_html($face['name']) . '</option>' . "\n";
}
$section_return[$option['tab']] .= '</select>' . "\n";
$section_return[$option['tab']] .= '</div>' . "\n";
$field_num++;
// Construct color picker.
} elseif ($option['type'] == "color") {
$section_return[$option['tab']] .= '<div id="' . esc_attr($option['id'] . '_picker') . '" class="colorSelector"><div style="' . esc_attr('background-color:' . $value) . '"></div></div>';
$section_return[$option['tab']] .= '<input class="' . $classes . ' hex_field" name="' . esc_attr($option_name . '[' . $option['id'] . ']') . '" id="' . esc_attr($option['id']) . '" type="text" value="' . esc_attr($value) . '" />';
$field_num++;
// Construct image.
} elseif ($option['type'] == "image") {
$section_return[$option['tab']] .= '<input id="' . $option['id'] . '" class="upload_image ' . $classes . '" name="' . esc_attr($option_name . '[' . $option['id'] . ']') . '" type="text" value="' . esc_attr($value) . '" />';
$section_return[$option['tab']] .= '<input type="button" name="upload_image_button" class="upload_image_button nimbus_button_blue" value="Browse" />';
//$section_return[$option['tab']] .= '<img src="' . $value . '" />';
$field_num++;
// pro account
} elseif ($option['type'] == "pro") {
$join_text = __('This feature is available to Nimbus Themes members.', 'nimbus');
$join_link_text = __('Join today!!.', 'nimbus');
$section_return[$option['tab']] .= '<p><span style="color:#fc7e2a;">' . $join_text . '</span> <a href="http://www.nimbusthemes.com/?utm_source=wp_opulus&utm_medium=theme&utm_content=panel_link&utm_campaign=opulus">' . $join_link_text . '</a></p>';
$field_num++;
// item_html
} elseif ($option['type'] == "item_html") {
$section_return[$option['tab']] .= $option['html'];
$field_num++;
// Construct tabs.
} elseif ($option['type'] == "tab") {
$section_return[$option['tab']] .= '<li><a href="#' . $option['url'] . '" id="' . $option['id'] . '" class="' . $classes . '">' . $option['name'] . '</a></li>';
// Construct html.
} elseif ($option['type'] == "html") {
$section_return[$option['tab']] .= $option['html'];
}
// Close field wrap html.
if (($option['type'] != "tab") && ($option['type'] != "html")) {
$section_return[$option['tab']] .= '<div class="clear30"></div></div><div class="clear20"></div></div>';
}
/*
if (isset($option['info'])) {
$section_return[$option['tab']] .= '<div style="display: none;">';
$section_return[$option['tab']] .= '<div id="' . $option['id'] . '_info" class="info_box">';
$section_return[$option['tab']] .= '<h2>' . $option['name'] . '</h2>';
$section_return[$option['tab']] .= $option['info'];
$section_return[$option['tab']] .= '</div>';
$section_return[$option['tab']] .= '</div>';
}
*/
}
return $section_return;
}
| aliuwahab/saveghana | wp-content/themes/wp-opulus/nimbus/options_engine.php | PHP | gpl-2.0 | 17,082 |
<?php
/**
* @package HikaMarket for Joomla!
* @version 4.0.0
* @author Obsidev S.A.R.L.
* @copyright (C) 2011-2021 OBSIDEV. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><?php
class market_order_status_notificationPreviewMaker {
public $displaySubmitButton = false;
public $type = 'order';
public function prepareMail($data = null) {
if(empty($data))
return $this->getDefaultData();
$orderClass = hikashop_get('class.order');
$order = $orderClass->loadFullOrder((int)$data);
if(empty($order->mail_status))
$order->mail_status = hikamarket::orderStatus(@$order->order_status);
else
$order->mail_status = hikamarket::orderStatus($order->mail_status);
if(isset($order->hikamarket->vendor)) {
$order->vendor = $order->hikamarket->vendor;
} else {
$vendorClass = hikamarket::get('class.vendor');
$vendor_id = max(1, (int)$order->order_vendor_id);
$order->vendor = $vendorClass->get($vendor_id);
}
$mailClass = hikamarket::get('class.mail');
$mail = $mailClass->load('order_status_notification', $order);
$mail->hikamarket = true;
if(empty($mail->subject))
$mail->subject = 'MARKET_ORDER_STATUS_NOTIFICATION_SUBJECT';
$mail->dst_email = $order->vendor->vendor_email;
$mail->dst_name = $order->vendor->vendor_name;
return $mail;
}
public function getDefaultData() {
}
public function getSelector($data) {
$nameboxType = hikashop_get('type.namebox');
$html = $nameboxType->display(
'data',
(int)$data,
hikashopNameboxType::NAMEBOX_SINGLE,
'order',
array(
'delete' => false,
'default_text' => '<em>'.JText::_('HIKA_NONE').'</em>',
'returnOnEmpty' => false,
)
);
if(!$html){
hikashop_display(JText::_('PLEASE_FIRST_CREATE_AN_ORDER'), 'info');
return;
}
if(empty($data)) {
echo hikashop_display(Jtext::_('PLEASE_SELECT_AN_ORDER_FOR_THE_PREVIEW'));
}
?>
<dl class="hika_options">
<dt><?php echo JText::_('HIKASHOP_ORDER'); ?></dt>
<dd><?php echo $html; ?></dd>
</dl>
<script type="text/javascript">
window.Oby.ready(function() {
var w = window;
if(!w.oNameboxes['data'])
return;
w.oNameboxes['data'].register('set', function(e) {
hikashop.submitform('preview','adminForm');
});
});
</script>
<?php
}
}
| emundus/v6 | media/com_hikamarket/mail/order_status_notification.preview.php | PHP | gpl-2.0 | 2,333 |
# -*- coding: utf-8 -*-
"""
Emotiv acquisition :
Reverse engineering and original crack code written by
Cody Brocious (http://github.com/daeken)
Kyle Machulis (http://github.com/qdot)
Many thanks for their contribution.
Need python-crypto.
"""
import multiprocessing as mp
import numpy as np
import msgpack
import time
from collections import OrderedDict
from .base import DeviceBase
import platform
WINDOWS = (platform.system() == "Windows")
try:
import pywinusb.hid as hid
except:
pass
import os
from subprocess import check_output
from Crypto.Cipher import AES
from Crypto import Random
import Queue
tasks = Queue.Queue()
_channel_names = [ 'F3', 'F4', 'P7', 'FC6', 'F7', 'F8','T7','P8','FC5','AF4','T8','O2','O1','AF3']
sensorBits = {
'F3': [10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7],
'FC5': [28, 29, 30, 31, 16, 17, 18, 19, 20, 21, 22, 23, 8, 9],
'AF3': [46, 47, 32, 33, 34, 35, 36, 37, 38, 39, 24, 25, 26, 27],
'F7': [48, 49, 50, 51, 52, 53, 54, 55, 40, 41, 42, 43, 44, 45],
'T7': [66, 67, 68, 69, 70, 71, 56, 57, 58, 59, 60, 61, 62, 63],
'P7': [84, 85, 86, 87, 72, 73, 74, 75, 76, 77, 78, 79, 64, 65],
'O1': [102, 103, 88, 89, 90, 91, 92, 93, 94, 95, 80, 81, 82, 83],
'O2': [140, 141, 142, 143, 128, 129, 130, 131, 132, 133, 134, 135, 120, 121],
'P8': [158, 159, 144, 145, 146, 147, 148, 149, 150, 151, 136, 137, 138, 139],
'T8': [160, 161, 162, 163, 164, 165, 166, 167, 152, 153, 154, 155, 156, 157],
'F8': [178, 179, 180, 181, 182, 183, 168, 169, 170, 171, 172, 173, 174, 175],
'AF4': [196, 197, 198, 199, 184, 185, 186, 187, 188, 189, 190, 191, 176, 177],
'FC6': [214, 215, 200, 201, 202, 203, 204, 205, 206, 207, 192, 193, 194, 195],
'F4': [216, 217, 218, 219, 220, 221, 222, 223, 208, 209, 210, 211, 212, 213]
}
quality_bits = [99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112]
def create_analog_subdevice_param(channel_names):
n = len(channel_names)
d = {
'type' : 'AnalogInput',
'nb_channel' : n,
'params' :{ },
'by_channel_params' : {
'channel_indexes' : range(n),
'channel_names' : channel_names,
}
}
return d
def get_info(device):
info = { }
info['class'] = 'EmotivMultiSignals'
if WINDOWS:
# EMOTIV
info['device_path'] = device.device_path
info['board_name'] = '{} #{}'.format(device.vendor_name, device.serial_number).replace('\n', '').replace('\r', '')
info['serial'] = device.serial_number
info['hid'] = device
else:
info['device_path'] = device
name = device_path.strip('/dev/')
realInputPath = os.path.realpath("/sys/class/hidraw/" + name)
path = '/'.join(realInputPath.split('/')[:-4])
with open(path + "/manufacturer", 'r') as f:
manufacturer = f.readline()
with open(path + "/serial", 'r') as f:
serial = f.readline().strip()
info['board_name'] = '{} #{}'.format(manufacturer, serial).replace('\n', '').replace('\r', '')
info['serial'] = serial
# PYACQ
info['global_params'] = {'buffer_length' : 60.,}
info['subdevices'] = [ ]
info['subdevices'].append(create_analog_subdevice_param(_channel_names))
quality_name = ['Quality {}'.format(n) for n in _channel_names]
info['subdevices'].append(create_analog_subdevice_param(quality_name))
info['subdevices'].append(create_analog_subdevice_param([ 'X','Y']))
return info
def dump(obj):
for attr in dir(obj):
print "obj.%s = %s" % (attr, getattr(obj, attr))
class EmotivMultiSignals(DeviceBase):
def __init__(self, **kargs):
DeviceBase.__init__(self, **kargs)
@classmethod
def get_available_devices(cls):
devices = OrderedDict()
if WINDOWS:
try:
for device in hid.find_all_hid_devices():
print "device : ", device
if (device.product_name == 'Emotiv RAW DATA' or device.product_name == 'EPOC BCI'):
devices['Emotiv '+device.serial_number] = get_info(device)
finally:
pass
else:
serials = { }
for name in os.listdir("/sys/class/hidraw"):
realInputPath = os.path.realpath("/sys/class/hidraw/" + name)
path = '/'.join(realInputPath.split('/')[:-4])
try:
with open(path + "/manufacturer", 'r') as f:
manufacturer = f.readline()
if "emotiv" in manufacturer.lower():
with open(path + "/serial", 'r') as f:
serial = f.readline().strip()
if serial not in serials:
serials[serial] = [ ]
serials[serial].append(name)
except IOError as e:
print "Couldn't open file: %s" % e
for serial, names in serials.items():
device_path = '/dev/'+names[1]
info = get_info(device_path)
devices['Emotiv '+device_path] = info
return devices
def configure(self, buffer_length = 60,
subdevices = None,
):
self.params = {'buffer_length' : buffer_length,
'subdevices' : subdevices,
}
self.__dict__.update(self.params)
self.configured = True
def initialize(self):
devices = EmotivMultiSignals.get_available_devices()
self.device = devices.values()[0]
if self.subdevices is None:
self.subdevices = self.device['subdevices']
self.sampling_rate = 128.
self.packet_size = 1
l = int(self.sampling_rate*self.buffer_length)
self.buffer_length = (l - l%self.packet_size)/self.sampling_rate
self.name = '{}'.format(self.device['board_name'])
self.streams = [ ]
for s, sub in enumerate(self.subdevices):
stream = self.streamhandler.new_AnalogSignalSharedMemStream(name = self.name+str(s) , sampling_rate = self.sampling_rate,
nb_channel = sub['nb_channel'], buffer_length = self.buffer_length,
packet_size = self.packet_size, dtype = np.float64,
channel_names = sub['by_channel_params']['channel_names'],
channel_indexes = sub['by_channel_params']['channel_indexes'],
)
self.streams.append(stream)
def start(self):
self.stop_flag = mp.Value('i', 0) #flag pultiproc = global
self.process = mp.Process(target = emotiv_mainLoop, args=(self.stop_flag, self.streams, self.device) )
self.process.start()
print 'FakeMultiAnalogChannel started:', self.name
self.running = True
def stop(self):
self.stop_flag.value = 1
self.process.join()
print 'FakeMultiAnalogChannel stopped:', self.name
self.running = False
def close(self):
if WINDOWS:
self.device['hid'].close()
else:
pass
# for ii in self.streams:
# self.streams[ii].stop()
def setupCrypto(serial):
type = 0 #feature[5]
type &= 0xF
type = 0
#I believe type == True is for the Dev headset, I'm not using that. That's the point of this library in the first place I thought.
k = ['\0'] * 16
k[0] = serial[-1]
k[1] = '\0'
k[2] = serial[-2]
if type:
k[3] = 'H'
k[4] = serial[-1]
k[5] = '\0'
k[6] = serial[-2]
k[7] = 'T'
k[8] = serial[-3]
k[9] = '\x10'
k[10] = serial[-4]
k[11] = 'B'
else:
k[3] = 'T'
k[4] = serial[-3]
k[5] = '\x10'
k[6] = serial[-4]
k[7] = 'B'
k[8] = serial[-1]
k[9] = '\0'
k[10] = serial[-2]
k[11] = 'H'
k[12] = serial[-3]
k[13] = '\0'
k[14] = serial[-4]
k[15] = 'P'
#It doesn't make sense to have more than one greenlet handling this as data needs to be in order anyhow. I guess you could assign an ID or something
#to each packet but that seems like a waste also or is it? The ID might be useful if your using multiple headsets or usb sticks.
key = ''.join(k)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_ECB, iv)
return cipher
def get_level(data, bits):
level = 0
for i in range(13, -1, -1):
level <<= 1
b, o = (bits[i] / 8) + 1, bits[i] % 8
level |= (ord(data[b]) >> o) & 1
return level
def emotiv_mainLoop(stop_flag, streams, device):
import zmq
abs_pos = pos = 0
#setup cryto
cipher = setupCrypto(device['serial'])
streamChan, streamImp, streamGyro = streams
#Data channels socket
context = zmq.Context()
socket_chan = context.socket(zmq.PUB)
socket_chan.bind("tcp://*:{}".format(streamChan['port']))
#Impedance channels socket
socket_imp = context.socket(zmq.PUB)
socket_imp.bind("tcp://*:{}".format(streamImp['port']))
#Gyro channels socket
socket_gyro = context.socket(zmq.PUB)
socket_gyro.bind("tcp://*:{}".format(streamGyro['port']))
packet_size = streamChan['packet_size']
sampling_rate = streamChan['sampling_rate']
np_arr_chan = streamChan['shared_array'].to_numpy_array()
np_arr_imp = streamImp['shared_array'].to_numpy_array()
np_arr_gyro = streamGyro['shared_array'].to_numpy_array()
half_size = np_arr_chan.shape[1]/2 # same for the others
impedance_qualities = { }
for name in _channel_names + ['X', 'Y', 'Unknown']:
impedance_qualities[name] = 0.
if WINDOWS:
device['hid'].open()
device['hid'].set_raw_data_handler(emotiv_handler)
else:
hidraw = open(device['device_path'])
while True:
# READ DATA
if WINDOWS:
crypted_data = tasks.get(True)
else:
crypted_data = hidraw.read(32)
# PROCESS
data = cipher.decrypt(crypted_data[:16]) + cipher.decrypt(crypted_data[16:])
# current impedance quality
sensor_num = ord(data[0])
num_to_name = { 0 : 'F3', 1:'FC5', 2 : 'AF3', 3 : 'F7', 4:'T7', 5 : 'P7',
6 : 'O1', 7 : 'O2', 8: 'P8', 9 : 'T8', 10: 'F8', 11 : 'AF4',
12 : 'FC6', 13: 'F4', 14 : 'F8', 15:'AF4',
64 : 'F3', 65 : 'FC5', 66 : 'AF3', 67 : 'F7', 68 : 'T7', 69 : 'P7',
70 : 'O1', 71 : 'O2', 72: 'P8', 73 : 'T8', 74: 'F8', 75 : 'AF4',
76 : 'FC6', 77: 'F4', 78 : 'F8', 79:'AF4',
80 : 'FC6',
}
if sensor_num in num_to_name:
sensor_name = num_to_name[sensor_num]
impedance_qualities[sensor_name] = get_level(data, quality_bits) / 540
for c, channel_name in enumerate(_channel_names):
bits = sensorBits[channel_name]
# channel value
value = get_level(data, bits)
np_arr_chan[c,pos] = value
np_arr_chan[c,pos+half_size] = value
#channel qualities
np_arr_imp[c,pos] = impedance_qualities[channel_name]
np_arr_imp[c,pos+half_size] = impedance_qualities[channel_name]
gyroX = ord(data[29]) - 106
gyroY = ord(data[30]) - 105
np_arr_gyro[:,pos] = [gyroX, gyroY]
np_arr_gyro[:,pos+half_size] = [gyroX, gyroY]
abs_pos += packet_size
pos = abs_pos%half_size
socket_chan.send(msgpack.dumps(abs_pos))
socket_imp.send(msgpack.dumps(abs_pos))
socket_gyro.send(msgpack.dumps(abs_pos))
if stop_flag.value:
print 'will stop'
break
# Windows handler
def emotiv_handler(data):
"""
Receives packets from headset for Windows. Sends them to the crypto process
"""
assert data[0] == 0
tasks.put_nowait(''.join(map(chr, data[1:])))
return True
Emotiv = EmotivMultiSignals
| Hemisphere-Project/Telemir-DatabitMe | Telemir-EEG/pyacq/pyacq/core/devices/emotiv.py | Python | gpl-2.0 | 12,623 |
// $Id: ahah.js,v 1.1.2.1 2009/03/21 19:43:51 mfer Exp $
/**
* Provides AJAX-like page updating via AHAH (Asynchronous HTML and HTTP).
*
* AHAH is a method of making a request via Javascript while viewing an HTML
* page. The request returns a small chunk of HTML, which is then directly
* injected into the page.
*
* Drupal uses this file to enhance form elements with #ahah[path] and
* #ahah[wrapper] properties. If set, this file will automatically be included
* to provide AHAH capabilities.
*/
/**
* Attaches the ahah behavior to each ahah form element.
*/
Drupal.behaviors.ahah = function(context) {
for (var base in Drupal.settings.ahah) {
if (!$('#'+ base + '.ahah-processed').size()) {
var element_settings = Drupal.settings.ahah[base];
$(element_settings.selector).each(function() {
element_settings.element = this;
var ahah = new Drupal.ahah(base, element_settings);
});
$('#'+ base).addClass('ahah-processed');
}
}
};
/**
* AHAH object.
*/
Drupal.ahah = function(base, element_settings) {
// Set the properties for this object.
this.element = element_settings.element;
this.selector = element_settings.selector;
this.event = element_settings.event;
this.keypress = element_settings.keypress;
this.url = element_settings.url;
this.wrapper = '#'+ element_settings.wrapper;
this.effect = element_settings.effect;
this.method = element_settings.method;
this.progress = element_settings.progress;
this.button = element_settings.button || { };
if (this.effect == 'none') {
this.showEffect = 'show';
this.hideEffect = 'hide';
this.showSpeed = '';
}
else if (this.effect == 'fade') {
this.showEffect = 'fadeIn';
this.hideEffect = 'fadeOut';
this.showSpeed = 'slow';
}
else {
this.showEffect = this.effect + 'Toggle';
this.hideEffect = this.effect + 'Toggle';
this.showSpeed = 'slow';
}
// Record the form action and target, needed for iFrame file uploads.
var form = $(this.element).parents('form');
this.form_action = form.attr('action');
this.form_target = form.attr('target');
this.form_encattr = form.attr('encattr');
// Set the options for the ajaxSubmit function.
// The 'this' variable will not persist inside of the options object.
var ahah = this;
var options = {
url: ahah.url,
data: ahah.button,
beforeSubmit: function(form_values, element_settings, options) {
return ahah.beforeSubmit(form_values, element_settings, options);
},
success: function(response, status) {
// Sanity check for browser support (object expected).
// When using iFrame uploads, responses must be returned as a string.
if (typeof(response) == 'string') {
response = Drupal.parseJson(response);
}
return ahah.success(response, status);
},
complete: function(response, status) {
if (status == 'error' || status == 'parsererror') {
return ahah.error(response, ahah.url);
}
},
dataType: 'json',
type: 'POST'
};
// Bind the ajaxSubmit function to the element event.
$(element_settings.element).bind(element_settings.event, function() {
$(element_settings.element).parents('form').ajaxSubmit(options);
return false;
});
// If necessary, enable keyboard submission so that AHAH behaviors
// can be triggered through keyboard input as well as e.g. a mousedown
// action.
if (element_settings.keypress) {
$(element_settings.element).keypress(function(event) {
// Detect enter key.
if (event.keyCode == 13) {
$(element_settings.element).trigger(element_settings.event);
return false;
}
});
}
};
/**
* Handler for the form redirection submission.
*/
Drupal.ahah.prototype.beforeSubmit = function (form_values, element, options) {
// Disable the element that received the change.
$(this.element).addClass('progress-disabled').attr('disabled', true);
// Insert progressbar or throbber.
if (this.progress.type == 'bar') {
var progressBar = new Drupal.progressBar('ahah-progress-' + this.element.id, eval(this.progress.update_callback), this.progress.method, eval(this.progress.error_callback));
if (this.progress.message) {
progressBar.setProgress(-1, this.progress.message);
}
if (this.progress.url) {
progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500);
}
this.progress.element = $(progressBar.element).addClass('ahah-progress ahah-progress-bar');
this.progress.object = progressBar;
$(this.element).after(this.progress.element);
}
else if (this.progress.type == 'throbber') {
this.progress.element = $('<div class="ahah-progress ahah-progress-throbber"><div class="throbber"> </div></div>');
if (this.progress.message) {
$('.throbber', this.progress.element).after('<div class="message">' + this.progress.message + '</div>')
}
$(this.element).after(this.progress.element);
}
};
/**
* Handler for the form redirection completion.
*/
Drupal.ahah.prototype.success = function (response, status) {
var wrapper = $(this.wrapper);
var form = $(this.element).parents('form');
// Manually insert HTML into the jQuery object, using $() directly crashes
// Safari with long string lengths. http://dev.jquery.com/ticket/1152
var new_content = $('<div></div>').html(response.data);
// Restore the previous action and target to the form.
form.attr('action', this.form_action);
this.form_target ? form.attr('target', this.form_target) : form.removeAttr('target');
this.form_encattr ? form.attr('target', this.form_encattr) : form.removeAttr('encattr');
// Remove the progress element.
if (this.progress.element) {
$(this.progress.element).remove();
}
if (this.progress.object) {
this.progress.object.stopMonitoring();
}
$(this.element).removeClass('progress-disabled').attr('disabled', false);
// Add the new content to the page.
Drupal.freezeHeight();
if (this.method == 'replace') {
wrapper.empty().append(new_content);
}
else {
wrapper[this.method](new_content);
}
// Immediately hide the new content if we're using any effects.
if (this.showEffect != 'show') {
new_content.hide();
}
// Determine what effect use and what content will receive the effect, then
// show the new content.
if ($('.ahah-new-content', new_content).size() > 0) {
$('.ahah-new-content', new_content).hide();
new_content.show();
$(".ahah-new-content", new_content)[this.showEffect](this.showSpeed);
}
else if (this.showEffect != 'show') {
new_content[this.showEffect](this.showSpeed);
}
// Attach all javascript behaviors to the new content, if it was successfully
// added to the page, this if statement allows #ahah[wrapper] to be optional.
if (new_content.parents('html').length > 0) {
Drupal.attachBehaviors(new_content);
}
Drupal.unfreezeHeight();
};
/**
* Handler for the form redirection error.
*/
Drupal.ahah.prototype.error = function (response, uri) {
alert(Drupal.ahahError(response, uri));
// Resore the previous action and target to the form.
$(this.element).parent('form').attr( { action: this.form_action, target: this.form_target} );
// Remove the progress element.
if (this.progress.element) {
$(this.progress.element).remove();
}
if (this.progress.object) {
this.progress.object.stopMonitoring();
}
// Undo hide.
$(this.wrapper).show();
// Re-enable the element.
$(this.element).removeClass('progess-disabled').attr('disabled', false);
};
| punithagk/mpm | profiles/uberdrupal/modules/jquery_update/replace/ahah.js | JavaScript | gpl-2.0 | 7,824 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Travelling.Caching
{
public enum CacheOverdueType
{
None = 0,
AbsoluteExpiration=1,
NoSlidingExpiration=2
}
}
| binlyzhuo/travelling | src/Travelling.Caching/CacheOverdueType.cs | C# | gpl-2.0 | 246 |
#ifndef _COMMON_DEFS_
#define _COMMON_DEFS_
enum EOS_TYPE {SRK, VDW, PR, GHC};
enum FLASH_TYPE {SIMPLE };
enum SIM_TYPE {LIQDENSITY, VAPDENSITY, TPFLASH, PT_DIAGRAM, DEW_POINT, BUBBLE_POINT, PUREPSAT};
#endif
| edwardthomas/phase-equilibria-software | PVT_calc/Source/commonDefs.hpp | C++ | gpl-2.0 | 214 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace SenseNet.ContentRepository.Schema
{
public static class DynamicContentTools
{
public static IDictionary<string, FieldMetadata> GetFieldMetadata(Type type)
{
return GetFieldMetadata(type, null);
}
public static IDictionary<string, FieldMetadata> GetFieldMetadata(Type type, Func<FieldMetadata, bool> isHiddenCallback)
{
var data = new Dictionary<string, FieldMetadata>();
foreach (var propertyInfo in type.GetProperties(BindingFlags.FlattenHierarchy|BindingFlags.Instance|BindingFlags.Public))
{
if (!propertyInfo.CanRead)
continue;
var fieldType = FieldManager.GetSuggestedFieldType(propertyInfo.PropertyType);
var fieldMeta = new FieldMetadata
{
PropertyInfo = propertyInfo,
FieldName = propertyInfo.Name,
PropertyType = propertyInfo.PropertyType,
FieldType = fieldType,
CanRead = propertyInfo.CanRead,
CanWrite = propertyInfo.CanWrite
};
if (fieldType != null && (isHiddenCallback == null || isHiddenCallback(fieldMeta)))
data.Add(propertyInfo.Name, fieldMeta);
}
return data;
}
public static string GenerateCtd(ISupportsDynamicFields handler, ContentType baseContentType)
{
var ctdFormat = @"<ContentType name=""{0}"" parentType=""{1}"" handler=""{2}"" xmlns=""{4}"">
<Fields>
{3}
</Fields>
</ContentType>";
var fieldFormat = @" <Field name=""{0}"" handler=""{1}"">
<DisplayName>{2}</DisplayName>
<Description>{3}</Description>
<Bind property=""{4}"" />
</Field>
";
var enumFieldFormat = @" <Field name=""{0}"" handler=""{1}"">
<DisplayName>{2}</DisplayName>
<Description>{3}</Description>
<Bind property=""{4}"" />
<Configuration>
<AllowMultiple>false</AllowMultiple>
<AllowExtraValue>false</AllowExtraValue>
<Options>
<Enum type='{5}' />
</Options>
</Configuration>
</Field>
";
var handlerType = handler.GetType();
var nameAttr = baseContentType.Name;
var parentAttr = baseContentType.Name;
var handlerAttr = handlerType.FullName;
var fields = new StringBuilder();
var dynamicFieldMetadata = handler.GetDynamicFieldMetadata();
foreach (var propertyName in dynamicFieldMetadata.Keys)
{
var dynamicField = dynamicFieldMetadata[propertyName];
if (dynamicField.FieldSetting == null)
{
var proptype = dynamicField.PropertyType;
var fieldType = dynamicField.FieldType;
if (typeof (Enum).IsAssignableFrom(proptype))
{
fields.AppendFormat(enumFieldFormat, dynamicField.FieldName, fieldType, dynamicField.DisplayName,
dynamicField.Description, propertyName, proptype.FullName);
}
else
{
fields.AppendFormat(fieldFormat, dynamicField.FieldName, fieldType,
dynamicField.DisplayName, dynamicField.Description, propertyName);
}
}
else
{
fields.Append(dynamicField.FieldSetting.ToXml());
}
}
return String.Format(ctdFormat, nameAttr, parentAttr, handlerAttr,
fields, ContentType.ContentDefinitionXmlNamespace);
}
public static Type GetSuggestedFieldType(Type propertyType)
{
return FieldManager.GetSuggestedFieldType(propertyType);
}
}
}
| SenseNet/sensenet | src/ContentRepository/Schema/DynamicContentTools.cs | C# | gpl-2.0 | 4,315 |
<?php
/**
* Helper class for the Constant Contact API.
*
* @since 1.5.4
*/
final class FLBuilderServiceConstantContact extends FLBuilderService {
/**
* The ID for this service.
*
* @since 1.5.4
* @var string $id
*/
public $id = 'constant-contact';
/**
* The api url for this service.
*
* @since 1.5.4
* @var string $api_url
*/
public $api_url = 'https://api.constantcontact.com/v2/';
/**
* Test the API connection.
*
* @since 1.5.4
* @param array $fields {
* @type string $api_key A valid API key.
* @type string $access_token A valid access token.
* }
* @return array{
* @type bool|string $error The error message or false if no error.
* @type array $data An array of data used to make the connection.
* }
*/
public function connect( $fields = array() ) {
$response = array(
'error' => false,
'data' => array(),
);
// Make sure we have an API key.
if ( ! isset( $fields['api_key'] ) || empty( $fields['api_key'] ) ) {
$response['error'] = __( 'Error: You must provide an API key.', 'fl-builder' );
} elseif ( ! isset( $fields['access_token'] ) || empty( $fields['access_token'] ) ) {
$response['error'] = __( 'Error: You must provide an access token.', 'fl-builder' );
} else { // Try to connect and store the connection data.
$url = $this->api_url . 'lists?api_key=' . $fields['api_key'] . '&access_token=' . $fields['access_token'];
$request = json_decode( wp_remote_retrieve_body( wp_remote_get( $url ) ) );
if ( ! is_array( $request ) || ( isset( $request[0] ) && isset( $request[0]->error_message ) ) ) {
/* translators: %s: error */
$response['error'] = sprintf( __( 'Error: Could not connect to Constant Contact. %s', 'fl-builder' ), $request[0]->error_message );
} else {
$response['data'] = array(
'api_key' => $fields['api_key'],
'access_token' => $fields['access_token'],
);
}
}
return $response;
}
/**
* Renders the markup for the connection settings.
*
* @since 1.5.4
* @return string The connection settings markup.
*/
public function render_connect_settings() {
ob_start();
FLBuilder::render_settings_field( 'api_key', array(
'row_class' => 'fl-builder-service-connect-row',
'class' => 'fl-builder-service-connect-input',
'type' => 'text',
'label' => __( 'API Key', 'fl-builder' ),
'help' => __( 'Your Constant Contact API key.', 'fl-builder' ),
'preview' => array(
'type' => 'none',
),
));
FLBuilder::render_settings_field( 'access_token', array(
'row_class' => 'fl-builder-service-connect-row',
'class' => 'fl-builder-service-connect-input',
'type' => 'text',
'label' => __( 'Access Token', 'fl-builder' ),
'help' => __( 'Your Constant Contact access token.', 'fl-builder' ),
/* translators: 1: account link: 2: api key link */
'description' => sprintf( __( 'You must register a <a%1$s>Developer Account</a> with Constant Contact to obtain an API key and access token. Please see <a%2$s>Getting an API key</a> for complete instructions.', 'fl-builder' ), ' href="https://constantcontact.mashery.com/member/register" target="_blank"', ' href="https://developer.constantcontact.com/home/api-keys.html" target="_blank"' ),
'preview' => array(
'type' => 'none',
),
));
return ob_get_clean();
}
/**
* Render the markup for service specific fields.
*
* @since 1.5.4
* @param string $account The name of the saved account.
* @param object $settings Saved module settings.
* @return array {
* @type bool|string $error The error message or false if no error.
* @type string $html The field markup.
* }
*/
public function render_fields( $account, $settings ) {
$account_data = $this->get_account_data( $account );
$api_key = $account_data['api_key'];
$access_token = $account_data['access_token'];
$url = $this->api_url . 'lists?api_key=' . $api_key . '&access_token=' . $access_token;
$request = json_decode( wp_remote_retrieve_body( wp_remote_get( $url ) ) );
$response = array(
'error' => false,
'html' => '',
);
if ( ! is_array( $request ) || ( isset( $request[0] ) && isset( $request[0]->error_message ) ) ) {
/* translators: %s: error */
$response['error'] = sprintf( __( 'Error: Could not connect to Constant Contact. %s', 'fl-builder' ), $request[0]->error_message );
} else {
$response['html'] = $this->render_list_field( $request, $settings );
}
return $response;
}
/**
* Render markup for the list field.
*
* @since 1.5.4
* @param array $lists List data from the API.
* @param object $settings Saved module settings.
* @return string The markup for the list field.
* @access private
*/
private function render_list_field( $lists, $settings ) {
ob_start();
$options = array(
'' => __( 'Choose...', 'fl-builder' ),
);
foreach ( $lists as $list ) {
$options[ $list->id ] = $list->name;
}
FLBuilder::render_settings_field( 'list_id', array(
'row_class' => 'fl-builder-service-field-row',
'class' => 'fl-builder-service-list-select',
'type' => 'select',
'label' => _x( 'List', 'An email list from a third party provider.', 'fl-builder' ),
'options' => $options,
'preview' => array(
'type' => 'none',
),
), $settings);
return ob_get_clean();
}
/**
* Subscribe an email address to Constant Contact.
*
* @since 1.5.4
* @param object $settings A module settings object.
* @param string $email The email to subscribe.
* @param string $name Optional. The full name of the person subscribing.
* @return array {
* @type bool|string $error The error message or false if no error.
* }
*/
public function subscribe( $settings, $email, $name = false ) {
$account_data = $this->get_account_data( $settings->service_account );
$response = array(
'error' => false,
);
if ( ! $account_data ) {
$response['error'] = __( 'There was an error subscribing to Constant Contact. The account is no longer connected.', 'fl-builder' );
} else {
$api_key = $account_data['api_key'];
$access_token = $account_data['access_token'];
$url = $this->api_url . 'contacts?api_key=' . $api_key . '&access_token=' . $access_token . '&email=' . $email;
$request = wp_remote_get( $url );
$contact = json_decode( wp_remote_retrieve_body( $request ) );
$list_id = $settings->list_id;
// This contact exists.
if ( ! empty( $contact->results ) ) {
$args = array();
$data = $contact->results[0];
// Check if already subscribed to this list.
if ( ! empty( $data->lists ) ) {
// Return early if already added.
foreach ( $data->lists as $key => $list ) {
if ( isset( $list->id ) && $list_id == $list->id ) {
return $response;
}
}
// Add an existing contact to the list.
$new_list = new stdClass;
$new_list->id = $list_id;
$new_list->status = 'ACTIVE';
$data->lists[ count( $data->lists ) ] = $new_list;
} else {
// Add an existing contact that has no list.
$data->lists = array();
$new_list = new stdClass;
$new_list->id = $list_id;
$new_list->status = 'ACTIVE';
$data->lists[0] = $new_list;
}
$args['body'] = json_encode( $data );
$args['method'] = 'PUT';
$args['headers']['Content-Type'] = 'application/json';
$args['headers']['Content-Length'] = strlen( $args['body'] );
$url = $this->api_url . 'contacts/' . $contact->results[0]->id . '?api_key=' . $api_key . '&access_token=' . $access_token . '&action_by=ACTION_BY_VISITOR';
$update = wp_remote_request( $url, $args );
$res = json_decode( wp_remote_retrieve_body( $update ) );
if ( isset( $res->error_key ) ) {
/* translators: %s: error */
$response['error'] = sprintf( __( 'There was an error subscribing to Constant Contact. %s', 'fl-builder' ), $res->error_key );
}
} else {
// @codingStandardsIgnoreLine
$args = $data = array();
$data['email_addresses'] = array();
$data['email_addresses'][0]['id'] = $list_id;
$data['email_addresses'][0]['status'] = 'ACTIVE';
$data['email_addresses'][0]['confirm_status'] = 'CONFIRMED';
$data['email_addresses'][0]['email_address'] = $email;
$data['lists'] = array();
$data['lists'][0]['id'] = $list_id;
if ( $name ) {
$names = explode( ' ', $name );
if ( isset( $names[0] ) ) {
$data['first_name'] = $names[0];
}
if ( isset( $names[1] ) ) {
$data['last_name'] = $names[1];
}
}
$args['body'] = json_encode( $data );
$args['headers']['Content-Type'] = 'application/json';
$args['headers']['Content-Length'] = strlen( json_encode( $data ) );
$url = $this->api_url . 'contacts?api_key=' . $api_key . '&access_token=' . $access_token . '&action_by=ACTION_BY_VISITOR';
$create = wp_remote_post( $url, $args );
if ( isset( $create->error_key ) ) {
/* translators: %s: error */
$response['error'] = sprintf( __( 'There was an error subscribing to Constant Contact. %s', 'fl-builder' ), $create->error_key );
}
}
}
return $response;
}
}
| isabisa/nccdi | wp-content/plugins/bb-plugin/classes/class-fl-builder-service-constant-contact.php | PHP | gpl-2.0 | 9,692 |
/* Copyright (c) 2013 Dropbox, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "json11.hpp"
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <limits>
namespace json11 {
static const int max_depth = 200;
using std::string;
using std::vector;
using std::multimap;
using std::make_shared;
using std::initializer_list;
using std::move;
/* Helper for representing null - just a do-nothing struct, plus comparison
* operators so the helpers in JsonValue work. We can't use nullptr_t because
* it may not be orderable.
*/
struct NullStruct {
bool operator==(NullStruct) const { return true; }
bool operator<(NullStruct) const { return false; }
};
/* * * * * * * * * * * * * * * * * * * *
* Serialization
*/
static void dump(NullStruct, string &out) {
out += "null";
}
static void dump(double value, string &out) {
if (std::isfinite(value)) {
char buf[32];
snprintf(buf, sizeof buf, "%.17g", value);
out += buf;
} else {
out += "null";
}
}
static void dump(int value, string &out) {
char buf[32];
snprintf(buf, sizeof buf, "%d", value);
out += buf;
}
static void dump(bool value, string &out) {
out += value ? "true" : "false";
}
static void dump(const string &value, string &out) {
out += '"';
for (size_t i = 0; i < value.length(); i++) {
const char ch = value[i];
if (ch == '\\') {
out += "\\\\";
} else if (ch == '"') {
out += "\\\"";
} else if (ch == '\b') {
out += "\\b";
} else if (ch == '\f') {
out += "\\f";
} else if (ch == '\n') {
out += "\\n";
} else if (ch == '\r') {
out += "\\r";
} else if (ch == '\t') {
out += "\\t";
} else if (static_cast<uint8_t>(ch) <= 0x1f) {
char buf[8];
snprintf(buf, sizeof buf, "\\u%04x", ch);
out += buf;
} else if (static_cast<uint8_t>(ch) == 0xe2 && static_cast<uint8_t>(value[i+1]) == 0x80
&& static_cast<uint8_t>(value[i+2]) == 0xa8) {
out += "\\u2028";
i += 2;
} else if (static_cast<uint8_t>(ch) == 0xe2 && static_cast<uint8_t>(value[i+1]) == 0x80
&& static_cast<uint8_t>(value[i+2]) == 0xa9) {
out += "\\u2029";
i += 2;
} else {
out += ch;
}
}
out += '"';
}
static void dump(const Json::array &values, string &out) {
bool first = true;
out += "[";
for (const auto &value : values) {
if (!first)
out += ", ";
value.dump(out);
first = false;
}
out += "]";
}
static void dump(const Json::object &values, string &out) {
bool first = true;
out += "{";
for (const auto &kv : values) {
if (!first)
out += ", ";
dump(kv.first, out);
out += ": ";
kv.second.dump(out);
first = false;
}
out += "}";
}
void Json::dump(string &out) const {
m_ptr->dump(out);
}
/* * * * * * * * * * * * * * * * * * * *
* Value wrappers
*/
template <Json::Type tag, typename T>
class Value : public JsonValue {
protected:
// Constructors
explicit Value(const T &value) : m_value(value) {}
explicit Value(T &&value) : m_value(move(value)) {}
// Get type tag
Json::Type type() const override {
return tag;
}
// Comparisons
bool equals(const JsonValue * other) const override {
return m_value == static_cast<const Value<tag, T> *>(other)->m_value;
}
bool less(const JsonValue * other) const override {
return m_value < static_cast<const Value<tag, T> *>(other)->m_value;
}
const T m_value;
void dump(string &out) const override { json11::dump(m_value, out); }
};
class JsonDouble final : public Value<Json::NUMBER, double> {
double number_value() const override { return m_value; }
int int_value() const override { return static_cast<int>(m_value); }
bool equals(const JsonValue * other) const override { return m_value == other->number_value(); }
bool less(const JsonValue * other) const override { return m_value < other->number_value(); }
public:
explicit JsonDouble(double value) : Value(value) {}
};
class JsonInt final : public Value<Json::NUMBER, int> {
double number_value() const override { return m_value; }
int int_value() const override { return m_value; }
bool equals(const JsonValue * other) const override { return m_value == other->number_value(); }
bool less(const JsonValue * other) const override { return m_value < other->number_value(); }
public:
explicit JsonInt(int value) : Value(value) {}
};
class JsonBoolean final : public Value<Json::BOOL, bool> {
bool bool_value() const override { return m_value; }
public:
explicit JsonBoolean(bool value) : Value(value) {}
};
class JsonString final : public Value<Json::STRING, string> {
const string &string_value() const override { return m_value; }
public:
explicit JsonString(const string &value) : Value(value) {}
explicit JsonString(string &&value) : Value(move(value)) {}
};
class JsonArray final : public Value<Json::ARRAY, Json::array> {
const Json::array &array_items() const override { return m_value; }
const Json & operator[](size_t i) const override;
public:
explicit JsonArray(const Json::array &value) : Value(value) {}
explicit JsonArray(Json::array &&value) : Value(move(value)) {}
};
class JsonObject final : public Value<Json::OBJECT, Json::object> {
const Json::object &object_items() const override { return m_value; }
const Json & operator[](const string &key) const override;
public:
explicit JsonObject(const Json::object &value) : Value(value) {}
explicit JsonObject(Json::object &&value) : Value(move(value)) {}
};
class JsonNull final : public Value<Json::NUL, NullStruct> {
public:
JsonNull() : Value({}) {}
};
/* * * * * * * * * * * * * * * * * * * *
* Static globals - static-init-safe
*/
struct Statics {
const std::shared_ptr<JsonValue> null = make_shared<JsonNull>();
const std::shared_ptr<JsonValue> t = make_shared<JsonBoolean>(true);
const std::shared_ptr<JsonValue> f = make_shared<JsonBoolean>(false);
const string empty_string;
const vector<Json> empty_vector;
const multimap<string, Json> empty_map;
Statics() {}
};
static const Statics & statics() {
static const Statics s {};
return s;
}
static const Json & static_null() {
// This has to be separate, not in Statics, because Json() accesses statics().null.
static const Json json_null;
return json_null;
}
/* * * * * * * * * * * * * * * * * * * *
* Constructors
*/
Json::Json() noexcept : m_ptr(statics().null) {}
Json::Json(std::nullptr_t) noexcept : m_ptr(statics().null) {}
Json::Json(double value) : m_ptr(make_shared<JsonDouble>(value)) {}
Json::Json(int value) : m_ptr(make_shared<JsonInt>(value)) {}
Json::Json(bool value) : m_ptr(value ? statics().t : statics().f) {}
Json::Json(const string &value) : m_ptr(make_shared<JsonString>(value)) {}
Json::Json(string &&value) : m_ptr(make_shared<JsonString>(move(value))) {}
Json::Json(const char * value) : m_ptr(make_shared<JsonString>(value)) {}
Json::Json(const Json::array &values) : m_ptr(make_shared<JsonArray>(values)) {}
Json::Json(Json::array &&values) : m_ptr(make_shared<JsonArray>(move(values))) {}
Json::Json(const Json::object &values) : m_ptr(make_shared<JsonObject>(values)) {}
Json::Json(Json::object &&values) : m_ptr(make_shared<JsonObject>(move(values))) {}
/* * * * * * * * * * * * * * * * * * * *
* Accessors
*/
Json::Type Json::type() const { return m_ptr->type(); }
double Json::number_value() const { return m_ptr->number_value(); }
int Json::int_value() const { return m_ptr->int_value(); }
bool Json::bool_value() const { return m_ptr->bool_value(); }
const string & Json::string_value() const { return m_ptr->string_value(); }
const vector<Json> & Json::array_items() const { return m_ptr->array_items(); }
const multimap<string, Json> & Json::object_items() const { return m_ptr->object_items(); }
const Json & Json::operator[] (size_t i) const { return (*m_ptr)[i]; }
const Json & Json::operator[] (const string &key) const { return (*m_ptr)[key]; }
double JsonValue::number_value() const { return 0; }
int JsonValue::int_value() const { return 0; }
bool JsonValue::bool_value() const { return false; }
const string & JsonValue::string_value() const { return statics().empty_string; }
const vector<Json> & JsonValue::array_items() const { return statics().empty_vector; }
const multimap<string, Json> & JsonValue::object_items() const { return statics().empty_map; }
const Json & JsonValue::operator[] (size_t) const { return static_null(); }
const Json & JsonValue::operator[] (const string &) const { return static_null(); }
const Json & JsonObject::operator[] (const string &key) const {
auto iter = m_value.find(key);
return (iter == m_value.end()) ? static_null() : iter->second;
}
const Json & JsonArray::operator[] (size_t i) const {
if (i >= m_value.size()) return static_null();
else return m_value[i];
}
/* * * * * * * * * * * * * * * * * * * *
* Comparison
*/
bool Json::operator== (const Json &other) const {
if (m_ptr == other.m_ptr)
return true;
if (m_ptr->type() != other.m_ptr->type())
return false;
return m_ptr->equals(other.m_ptr.get());
}
bool Json::operator< (const Json &other) const {
if (m_ptr == other.m_ptr)
return false;
if (m_ptr->type() != other.m_ptr->type())
return m_ptr->type() < other.m_ptr->type();
return m_ptr->less(other.m_ptr.get());
}
/* * * * * * * * * * * * * * * * * * * *
* Parsing
*/
/* esc(c)
*
* Format char c suitable for printing in an error message.
*/
static inline string esc(char c) {
char buf[12];
if (static_cast<uint8_t>(c) >= 0x20 && static_cast<uint8_t>(c) <= 0x7f) {
snprintf(buf, sizeof buf, "'%c' (%d)", c, c);
} else {
snprintf(buf, sizeof buf, "(%d)", c);
}
return string(buf);
}
static inline bool in_range(long x, long lower, long upper) {
return (x >= lower && x <= upper);
}
namespace {
/* JsonParser
*
* Object that tracks all state of an in-progress parse.
*/
struct JsonParser final {
/* State
*/
const string &str;
size_t i;
string &err;
bool failed;
const JsonParse strategy;
/* fail(msg, err_ret = Json())
*
* Mark this parse as failed.
*/
Json fail(string &&msg) {
return fail(move(msg), Json());
}
template <typename T>
T fail(string &&msg, const T err_ret) {
if (!failed)
err = std::move(msg);
failed = true;
return err_ret;
}
/* consume_whitespace()
*
* Advance until the current character is non-whitespace.
*/
void consume_whitespace() {
while (str[i] == ' ' || str[i] == '\r' || str[i] == '\n' || str[i] == '\t')
i++;
}
/* consume_comment()
*
* Advance comments (c-style inline and multiline).
*/
bool consume_comment() {
bool comment_found = false;
if (str[i] == '/') {
i++;
if (i == str.size())
return fail("unexpected end of input after start of comment", false);
if (str[i] == '/') { // inline comment
i++;
// advance until next line, or end of input
while (i < str.size() && str[i] != '\n') {
i++;
}
comment_found = true;
}
else if (str[i] == '*') { // multiline comment
i++;
if (i > str.size()-2)
return fail("unexpected end of input inside multi-line comment", false);
// advance until closing tokens
while (!(str[i] == '*' && str[i+1] == '/')) {
i++;
if (i > str.size()-2)
return fail(
"unexpected end of input inside multi-line comment", false);
}
i += 2;
comment_found = true;
}
else
return fail("malformed comment", false);
}
return comment_found;
}
/* consume_garbage()
*
* Advance until the current character is non-whitespace and non-comment.
*/
void consume_garbage() {
consume_whitespace();
if(strategy == JsonParse::COMMENTS) {
bool comment_found = false;
do {
comment_found = consume_comment();
if (failed) return;
consume_whitespace();
}
while(comment_found);
}
}
/* get_next_token()
*
* Return the next non-whitespace character. If the end of the input is reached,
* flag an error and return 0.
*/
char get_next_token() {
consume_garbage();
if (failed) return (char)0;
if (i == str.size())
return fail("unexpected end of input", (char)0);
return str[i++];
}
/* encode_utf8(pt, out)
*
* Encode pt as UTF-8 and add it to out.
*/
void encode_utf8(long pt, string & out) {
if (pt < 0)
return;
if (pt < 0x80) {
out += static_cast<char>(pt);
} else if (pt < 0x800) {
out += static_cast<char>((pt >> 6) | 0xC0);
out += static_cast<char>((pt & 0x3F) | 0x80);
} else if (pt < 0x10000) {
out += static_cast<char>((pt >> 12) | 0xE0);
out += static_cast<char>(((pt >> 6) & 0x3F) | 0x80);
out += static_cast<char>((pt & 0x3F) | 0x80);
} else {
out += static_cast<char>((pt >> 18) | 0xF0);
out += static_cast<char>(((pt >> 12) & 0x3F) | 0x80);
out += static_cast<char>(((pt >> 6) & 0x3F) | 0x80);
out += static_cast<char>((pt & 0x3F) | 0x80);
}
}
/* parse_string()
*
* Parse a string, starting at the current position.
*/
string parse_string() {
string out;
long last_escaped_codepoint = -1;
while (true) {
if (i == str.size())
return fail("unexpected end of input in string", "");
char ch = str[i++];
if (ch == '"') {
encode_utf8(last_escaped_codepoint, out);
return out;
}
if (in_range(ch, 0, 0x1f))
return fail("unescaped " + esc(ch) + " in string", "");
// The usual case: non-escaped characters
if (ch != '\\') {
encode_utf8(last_escaped_codepoint, out);
last_escaped_codepoint = -1;
out += ch;
continue;
}
// Handle escapes
if (i == str.size())
return fail("unexpected end of input in string", "");
ch = str[i++];
if (ch == 'u') {
// Extract 4-byte escape sequence
string esc = str.substr(i, 4);
// Explicitly check length of the substring. The following loop
// relies on std::string returning the terminating NUL when
// accessing str[length]. Checking here reduces brittleness.
if (esc.length() < 4) {
return fail("bad \\u escape: " + esc, "");
}
for (size_t j = 0; j < 4; j++) {
if (!in_range(esc[j], 'a', 'f') && !in_range(esc[j], 'A', 'F')
&& !in_range(esc[j], '0', '9'))
return fail("bad \\u escape: " + esc, "");
}
long codepoint = strtol(esc.data(), nullptr, 16);
// JSON specifies that characters outside the BMP shall be encoded as a pair
// of 4-hex-digit \u escapes encoding their surrogate pair components. Check
// whether we're in the middle of such a beast: the previous codepoint was an
// escaped lead (high) surrogate, and this is a trail (low) surrogate.
if (in_range(last_escaped_codepoint, 0xD800, 0xDBFF)
&& in_range(codepoint, 0xDC00, 0xDFFF)) {
// Reassemble the two surrogate pairs into one astral-plane character, per
// the UTF-16 algorithm.
encode_utf8((((last_escaped_codepoint - 0xD800) << 10)
| (codepoint - 0xDC00)) + 0x10000, out);
last_escaped_codepoint = -1;
} else {
encode_utf8(last_escaped_codepoint, out);
last_escaped_codepoint = codepoint;
}
i += 4;
continue;
}
encode_utf8(last_escaped_codepoint, out);
last_escaped_codepoint = -1;
if (ch == 'b') {
out += '\b';
} else if (ch == 'f') {
out += '\f';
} else if (ch == 'n') {
out += '\n';
} else if (ch == 'r') {
out += '\r';
} else if (ch == 't') {
out += '\t';
} else if (ch == '"' || ch == '\\' || ch == '/') {
out += ch;
} else {
return fail("invalid escape character " + esc(ch), "");
}
}
}
/* parse_number()
*
* Parse a double.
*/
Json parse_number() {
size_t start_pos = i;
if (str[i] == '-')
i++;
// Integer part
if (str[i] == '0') {
i++;
if (in_range(str[i], '0', '9'))
return fail("leading 0s not permitted in numbers");
} else if (in_range(str[i], '1', '9')) {
i++;
while (in_range(str[i], '0', '9'))
i++;
} else {
return fail("invalid " + esc(str[i]) + " in number");
}
if (str[i] != '.' && str[i] != 'e' && str[i] != 'E'
&& (i - start_pos) <= static_cast<size_t>(std::numeric_limits<int>::digits10)) {
return std::atoi(str.c_str() + start_pos);
}
// Decimal part
if (str[i] == '.') {
i++;
if (!in_range(str[i], '0', '9'))
return fail("at least one digit required in fractional part");
while (in_range(str[i], '0', '9'))
i++;
}
// Exponent part
if (str[i] == 'e' || str[i] == 'E') {
i++;
if (str[i] == '+' || str[i] == '-')
i++;
if (!in_range(str[i], '0', '9'))
return fail("at least one digit required in exponent");
while (in_range(str[i], '0', '9'))
i++;
}
return std::strtod(str.c_str() + start_pos, nullptr);
}
/* expect(str, res)
*
* Expect that 'str' starts at the character that was just read. If it does, advance
* the input and return res. If not, flag an error.
*/
Json expect(const string &expected, Json res) {
assert(i != 0);
i--;
if (str.compare(i, expected.length(), expected) == 0) {
i += expected.length();
return res;
} else {
return fail("parse error: expected " + expected + ", got " + str.substr(i, expected.length()));
}
}
/* parse_json()
*
* Parse a JSON object.
*/
Json parse_json(int depth) {
if (depth > max_depth) {
return fail("exceeded maximum nesting depth");
}
char ch = get_next_token();
if (failed)
return Json();
if (ch == '-' || (ch >= '0' && ch <= '9')) {
i--;
return parse_number();
}
if (ch == 't')
return expect("true", true);
if (ch == 'f')
return expect("false", false);
if (ch == 'n')
return expect("null", Json());
if (ch == '"')
return parse_string();
if (ch == '{') {
multimap<string, Json> data;
ch = get_next_token();
if (ch == '}')
return data;
while (1) {
if (ch != '"')
return fail("expected '\"' in object, got " + esc(ch));
string key = parse_string();
if (failed)
return Json();
ch = get_next_token();
if (ch != ':')
return fail("expected ':' in object, got " + esc(ch));
data.insert(std::make_pair(std::move(key), parse_json(depth + 1)));
if (failed)
return Json();
ch = get_next_token();
if (ch == '}')
break;
if (ch != ',')
return fail("expected ',' in object, got " + esc(ch));
ch = get_next_token();
}
return data;
}
if (ch == '[') {
vector<Json> data;
ch = get_next_token();
if (ch == ']')
return data;
while (1) {
i--;
data.push_back(parse_json(depth + 1));
if (failed)
return Json();
ch = get_next_token();
if (ch == ']')
break;
if (ch != ',')
return fail("expected ',' in list, got " + esc(ch));
ch = get_next_token();
(void)ch;
}
return data;
}
return fail("expected value, got " + esc(ch));
}
};
}//namespace {
Json Json::parse(const string &in, string &err, JsonParse strategy) {
JsonParser parser { in, 0, err, false, strategy };
Json result = parser.parse_json(0);
// Check for any trailing garbage
parser.consume_garbage();
if (parser.failed)
return Json();
if (parser.i != in.size())
return parser.fail("unexpected trailing " + esc(in[parser.i]));
return result;
}
// Documented in json11.hpp
vector<Json> Json::parse_multi(const string &in,
std::string::size_type &parser_stop_pos,
string &err,
JsonParse strategy) {
JsonParser parser { in, 0, err, false, strategy };
parser_stop_pos = 0;
vector<Json> json_vec;
while (parser.i != in.size() && !parser.failed) {
json_vec.push_back(parser.parse_json(0));
if (parser.failed)
break;
// Check for another object
parser.consume_garbage();
if (parser.failed)
break;
parser_stop_pos = parser.i;
}
return json_vec;
}
/* * * * * * * * * * * * * * * * * * * *
* Shape-checking
*/
bool Json::has_shape(const shape & types, string & err) const {
if (!is_object()) {
err = "expected JSON object, got " + dump();
return false;
}
for (auto & item : types) {
if ((*this)[item.first].type() != item.second) {
err = "bad type for " + item.first + " in " + dump();
return false;
}
}
return true;
}
} // namespace json11
| aholler/snetmanmon | json11/json11.cpp | C++ | gpl-2.0 | 24,950 |
/*
This file is part of KOrganizer.
Copyright (c) 2008 Thomas Thrainer <tom_t@gmx.at>
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.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "todoviewview.h"
#include <KLocalizedString>
#include <KMenu>
#include <QAction>
#include <QContextMenuEvent>
#include <QEvent>
#include <QHeaderView>
#include <QMouseEvent>
TodoViewView::TodoViewView( QWidget *parent )
: QTreeView( parent ), mHeaderPopup( 0 ), mIgnoreNextMouseRelease( false )
{
header()->installEventFilter( this );
setAlternatingRowColors( true );
connect( &mExpandTimer, SIGNAL(timeout()), SLOT(expandParent()) );
mExpandTimer.setInterval( 1000 );
header()->setStretchLastSection( false );
}
bool TodoViewView::isEditing( const QModelIndex &index ) const
{
return state() & QAbstractItemView::EditingState &&
currentIndex() == index;
}
bool TodoViewView::eventFilter( QObject *watched, QEvent *event )
{
Q_UNUSED( watched );
if ( event->type() == QEvent::ContextMenu ) {
QContextMenuEvent *e = static_cast<QContextMenuEvent *>( event );
if ( !mHeaderPopup ) {
mHeaderPopup = new KMenu( this );
mHeaderPopup->addTitle( i18n( "View Columns" ) );
// First entry can't be disabled
for ( int i = 1; i < model()->columnCount(); ++i ) {
QAction *tmp =
mHeaderPopup->addAction( model()->headerData( i, Qt::Horizontal ).toString() );
tmp->setData( QVariant( i ) );
tmp->setCheckable( true );
mColumnActions << tmp;
}
connect( mHeaderPopup, SIGNAL(triggered(QAction*)),
this, SLOT(toggleColumnHidden(QAction*)) );
}
foreach ( QAction *action, mColumnActions ) {
int column = action->data().toInt();
action->setChecked( !isColumnHidden( column ) );
}
mHeaderPopup->popup( mapToGlobal( e->pos() ) );
return true;
}
return false;
}
void TodoViewView::toggleColumnHidden( QAction *action )
{
if ( action->isChecked() ) {
showColumn( action->data().toInt() );
} else {
hideColumn( action->data().toInt() );
}
emit visibleColumnCountChanged();
}
QModelIndex TodoViewView::moveCursor( CursorAction cursorAction,
Qt::KeyboardModifiers modifiers )
{
QModelIndex current = currentIndex();
if ( !current.isValid() ) {
return QTreeView::moveCursor( cursorAction, modifiers );
}
switch ( cursorAction ) {
case MoveNext:
{
// try to find an editable item right of the current one
QModelIndex tmp = getNextEditableIndex(
current.sibling( current.row(), current.column() + 1 ), 1 );
if ( tmp.isValid() ) {
return tmp;
}
// check if the current item is expanded, and find an editable item
// just below it if so
current = current.sibling( current.row(), 0 );
if ( isExpanded( current ) ) {
tmp = getNextEditableIndex( current.child( 0, 0 ), 1 );
if ( tmp.isValid() ) {
return tmp;
}
}
// find an editable item in the item below the currently edited one
tmp = getNextEditableIndex( current.sibling( current.row() + 1, 0 ), 1 );
if ( tmp.isValid() ) {
return tmp;
}
// step back a hierarchy level, and search for an editable item there
while ( current.isValid() ) {
current = current.parent();
tmp = getNextEditableIndex( current.sibling( current.row() + 1, 0 ), 1 );
if ( tmp.isValid() ) {
return tmp;
}
}
return QModelIndex();
}
case MovePrevious:
{
// try to find an editable item left of the current one
QModelIndex tmp = getNextEditableIndex(
current.sibling( current.row(), current.column() - 1 ), -1 );
if ( tmp.isValid() ) {
return tmp;
}
int lastCol = model()->columnCount( QModelIndex() ) - 1;
// search on top of the item, also include expanded items
tmp = current.sibling( current.row() - 1, 0 );
while ( tmp.isValid() && isExpanded( tmp ) ) {
tmp = tmp.child( model()->rowCount( tmp ) - 1, 0 );
}
if ( tmp.isValid() ) {
tmp = getNextEditableIndex( tmp.sibling( tmp.row(), lastCol ), -1 );
if ( tmp.isValid() ) {
return tmp;
}
}
// step back a hierarchy level, and search for an editable item there
current = current.parent();
return getNextEditableIndex( current.sibling( current.row(), lastCol ), -1 );
}
default:
break;
}
return QTreeView::moveCursor( cursorAction, modifiers );
}
QModelIndex TodoViewView::getNextEditableIndex( const QModelIndex &cur, int inc )
{
if ( !cur.isValid() ) {
return QModelIndex();
}
QModelIndex tmp;
int colCount = model()->columnCount( QModelIndex() );
int end = inc == 1 ? colCount : -1;
for ( int c = cur.column(); c != end; c += inc ) {
tmp = cur.sibling( cur.row(), c );
if ( ( tmp.flags() & Qt::ItemIsEditable ) && !isIndexHidden( tmp ) ) {
return tmp;
}
}
return QModelIndex();
}
void TodoViewView::mouseReleaseEvent ( QMouseEvent *event )
{
mExpandTimer.stop();
if ( mIgnoreNextMouseRelease ) {
mIgnoreNextMouseRelease = false;
return;
}
if ( !indexAt( event->pos() ).isValid() ) {
clearSelection();
event->accept();
} else {
QTreeView::mouseReleaseEvent( event );
}
}
void TodoViewView::mouseMoveEvent( QMouseEvent *event )
{
mExpandTimer.stop();
QTreeView::mouseMoveEvent( event );
}
void TodoViewView::mousePressEvent( QMouseEvent *event )
{
mExpandTimer.stop();
QModelIndex index = indexAt( event->pos() );
if ( index.isValid() && event->button() == Qt::LeftButton ) {
mExpandTimer.start();
}
QTreeView::mousePressEvent( event );
}
void TodoViewView::expandParent()
{
QModelIndex index = indexAt( viewport()->mapFromGlobal( QCursor::pos() ) );
if ( index.isValid() ) {
mIgnoreNextMouseRelease = true;
QKeyEvent keyEvent = QKeyEvent( QEvent::KeyPress, Qt::Key_Asterisk, Qt::NoModifier );
QTreeView::keyPressEvent( &keyEvent );
}
}
| kolab-groupware/kdepim | calendarviews/todo/todoviewview.cpp | C++ | gpl-2.0 | 6,944 |
<?php
/**
* @package ZOO Component
* @file _menu.php
* @version 2.0.1 May 2010
* @author YOOtheme http://www.yootheme.com
* @copyright Copyright (C) 2007 - 2010 YOOtheme GmbH
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
// render menu
$menu = YMenu::getInstance('nav')
->addFilter(array('ZooMenuFilter', 'activeFilter'))
->addFilter(array('ZooMenuFilter', 'nameFilter'))
->applyFilter();
echo '<div id="nav"><div class="bar"></div>'.$menu->render(array('YMenuDecorator', 'index')).'</div>';
/*
Class: ZooMenuFilter
Filter for menu class.
*/
class ZooMenuFilter {
public static function activeFilter(YMenuItem $item) {
// init vars
$id = '';
$app = Zoo::getApplication();
$controller = YRequest::getWord('controller');
$task = YRequest::getWord('task');
$classes = array();
// application context
if (!empty($app)) {
$id = $app->id.'-'.$controller;
}
// application configuration
if ($controller == 'configuration' && $task) {
if (in_array($task, array('importfrom', 'import', 'importexport'))) {
$id .= '-importexport';
} else {
$id .= '-'.$task;
}
}
// new application
if ($controller == 'new') {
$id = 'new';
}
// application manager
if ($controller == 'manager') {
$id = 'manager';
if (in_array($task, array('types', 'addtype', 'edittype', 'editelements', 'assignelements'))) {
$id .= '-types';
} elseif ($task) {
$id .= '-'.$task;
}
}
// save current class attribute
$class = $item->getAttribute('class');
if (!empty($class)) {
$classes[] = $class;
}
// set active class
if ($item->getId() == $id || $item->hasChild($id, true)) {
$classes[] = 'active';
}
// replace the old class attribute
$item->setAttribute('class', implode(' ', $classes));
}
public static function nameFilter(YMenuItem $item) {
if ($item->getId() != 'new' && $item->getId() != 'manager') {
$item->setName(htmlspecialchars($item->getName(), ENT_QUOTES, 'UTF-8'));
}
}
} | alecerosiete/webBancaria | administrator/components/com_zoo/partials/_menu.php | PHP | gpl-2.0 | 2,104 |
/**
* ownCloud Android client application
*
* @author Bartek Przybylski
* @author Tobias Kaminsky
* @author David A. Velasco
* @author masensio
* Copyright (C) 2011 Bartek Przybylski
* Copyright (C) 2016 ownCloud Inc.
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.adapter;
import android.accounts.Account;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.datamodel.ThumbnailsCacheManager;
import com.owncloud.android.db.PreferenceManager;
import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.files.RemoteFile;
import com.owncloud.android.lib.resources.shares.OCShare;
import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
import com.owncloud.android.ui.activity.ComponentsGetter;
import com.owncloud.android.ui.fragment.ExtendedListFragment;
import com.owncloud.android.ui.interfaces.OCFileListFragmentInterface;
import com.owncloud.android.utils.DisplayUtils;
import com.owncloud.android.utils.FileStorageUtils;
import com.owncloud.android.utils.MimeTypeUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.Vector;
/**
* This Adapter populates a ListView with all files and folders in an ownCloud
* instance.
*/
public class FileListListAdapter extends BaseAdapter {
private Context mContext;
private Vector<OCFile> mFilesAll = new Vector<OCFile>();
private Vector<OCFile> mFiles = null;
private boolean mJustFolders;
private boolean mShowHiddenFiles;
private FileDataStorageManager mStorageManager;
private Account mAccount;
private ComponentsGetter mTransferServiceGetter;
private OCFileListFragmentInterface OCFileListFragmentInterface;
private FilesFilter mFilesFilter;
private OCFile currentDirectory;
private static final String TAG = FileListListAdapter.class.getSimpleName();
public FileListListAdapter(
boolean justFolders,
Context context,
ComponentsGetter transferServiceGetter,
OCFileListFragmentInterface OCFileListFragmentInterface
) {
this.OCFileListFragmentInterface = OCFileListFragmentInterface;
mJustFolders = justFolders;
mContext = context;
mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
mTransferServiceGetter = transferServiceGetter;
// Read sorting order, default to sort by name ascending
FileStorageUtils.mSortOrder = PreferenceManager.getSortOrder(mContext);
FileStorageUtils.mSortAscending = PreferenceManager.getSortAscending(mContext);
// Fetch preferences for showing hidden files
mShowHiddenFiles = PreferenceManager.showHiddenFilesEnabled(mContext);
// initialise thumbnails cache on background thread
new ThumbnailsCacheManager.InitDiskCacheTask().execute();
}
public FileListListAdapter(
boolean justFolders,
Context context,
ComponentsGetter transferServiceGetter,
OCFileListFragmentInterface OCFileListFragmentInterface,
FileDataStorageManager fileDataStorageManager
) {
this(justFolders, context, transferServiceGetter, OCFileListFragmentInterface);
mStorageManager = fileDataStorageManager;
}
@Override
public boolean areAllItemsEnabled() {
return true;
}
@Override
public boolean isEnabled(int position) {
return true;
}
@Override
public int getCount() {
return mFiles != null ? mFiles.size() : 0;
}
@Override
public Object getItem(int position) {
if (mFiles == null || mFiles.size() <= position) {
return null;
}
return mFiles.get(position);
}
public void setFavoriteAttributeForItemID(String fileId, boolean favorite) {
for (int i = 0; i < mFiles.size(); i++) {
if (mFiles.get(i).getRemoteId().equals(fileId)) {
mFiles.get(i).setFavorite(favorite);
break;
}
}
for (int i = 0; i < mFilesAll.size(); i++) {
if (mFilesAll.get(i).getRemoteId().equals(fileId)) {
mFilesAll.get(i).setFavorite(favorite);
break;
}
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
}
@Override
public long getItemId(int position) {
if (mFiles == null || mFiles.size() <= position) {
return 0;
}
return mFiles.get(position).getFileId();
}
@Override
public int getItemViewType(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
OCFile file = null;
LayoutInflater inflator = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (mFiles != null && mFiles.size() > position) {
file = mFiles.get(position);
}
// Find out which layout should be displayed
ViewType viewType;
if (parent instanceof GridView) {
if (file != null && (MimeTypeUtil.isImage(file) || MimeTypeUtil.isVideo(file))) {
viewType = ViewType.GRID_IMAGE;
} else {
viewType = ViewType.GRID_ITEM;
}
} else {
viewType = ViewType.LIST_ITEM;
}
// create view only if differs, otherwise reuse
if (convertView == null || convertView.getTag() != viewType) {
switch (viewType) {
case GRID_IMAGE:
view = inflator.inflate(R.layout.grid_image, parent, false);
view.setTag(ViewType.GRID_IMAGE);
break;
case GRID_ITEM:
view = inflator.inflate(R.layout.grid_item, parent, false);
view.setTag(ViewType.GRID_ITEM);
break;
case LIST_ITEM:
view = inflator.inflate(R.layout.list_item, parent, false);
view.setTag(ViewType.LIST_ITEM);
break;
}
}
if (file != null) {
ImageView fileIcon = (ImageView) view.findViewById(R.id.thumbnail);
fileIcon.setTag(file.getFileId());
TextView fileName;
String name = file.getFileName();
switch (viewType) {
case LIST_ITEM:
TextView fileSizeV = (TextView) view.findViewById(R.id.file_size);
TextView fileSizeSeparatorV = (TextView) view.findViewById(R.id.file_separator);
TextView lastModV = (TextView) view.findViewById(R.id.last_mod);
lastModV.setVisibility(View.VISIBLE);
lastModV.setText(DisplayUtils.getRelativeTimestamp(mContext, file.getModificationTimestamp()));
fileSizeSeparatorV.setVisibility(View.VISIBLE);
fileSizeV.setVisibility(View.VISIBLE);
fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
case GRID_ITEM:
// filename
fileName = (TextView) view.findViewById(R.id.Filename);
name = file.getFileName();
fileName.setText(name);
case GRID_IMAGE:
// sharedIcon
ImageView sharedIconV = (ImageView) view.findViewById(R.id.sharedIcon);
if (file.isSharedViaLink()) {
sharedIconV.setImageResource(R.drawable.shared_via_link);
sharedIconV.setVisibility(View.VISIBLE);
sharedIconV.bringToFront();
} else if (file.isSharedWithSharee() || file.isSharedWithMe()) {
sharedIconV.setImageResource(R.drawable.shared_via_users);
sharedIconV.setVisibility(View.VISIBLE);
sharedIconV.bringToFront();
} else {
sharedIconV.setVisibility(View.GONE);
}
// local state
ImageView localStateView = (ImageView) view.findViewById(R.id.localFileIndicator);
localStateView.bringToFront();
FileDownloaderBinder downloaderBinder =
mTransferServiceGetter.getFileDownloaderBinder();
FileUploaderBinder uploaderBinder =
mTransferServiceGetter.getFileUploaderBinder();
OperationsServiceBinder opsBinder =
mTransferServiceGetter.getOperationsServiceBinder();
localStateView.setVisibility(View.INVISIBLE); // default first
if ( //synchronizing
opsBinder != null &&
opsBinder.isSynchronizing(mAccount, file)
) {
localStateView.setImageResource(R.drawable.ic_synchronizing);
localStateView.setVisibility(View.VISIBLE);
} else if ( // downloading
downloaderBinder != null &&
downloaderBinder.isDownloading(mAccount, file)
) {
localStateView.setImageResource(R.drawable.ic_synchronizing);
localStateView.setVisibility(View.VISIBLE);
} else if ( //uploading
uploaderBinder != null &&
uploaderBinder.isUploading(mAccount, file)
) {
localStateView.setImageResource(R.drawable.ic_synchronizing);
localStateView.setVisibility(View.VISIBLE);
} else if (file.getEtagInConflict() != null) { // conflict
localStateView.setImageResource(R.drawable.ic_synchronizing_error);
localStateView.setVisibility(View.VISIBLE);
} else if (file.isDown()) {
localStateView.setImageResource(R.drawable.ic_synced);
localStateView.setVisibility(View.VISIBLE);
}
break;
}
// For all Views
if (file.getIsFavorite()) {
view.findViewById(R.id.favorite_action).setVisibility(View.VISIBLE);
} else {
view.findViewById(R.id.favorite_action).setVisibility(View.GONE);
}
ImageView checkBoxV = (ImageView) view.findViewById(R.id.custom_checkbox);
checkBoxV.setVisibility(View.GONE);
view.setBackgroundColor(Color.WHITE);
AbsListView parentList = (AbsListView) parent;
if (parentList.getChoiceMode() != AbsListView.CHOICE_MODE_NONE &&
parentList.getCheckedItemCount() > 0
) {
if (parentList.isItemChecked(position)) {
view.setBackgroundColor(mContext.getResources().getColor(
R.color.selected_item_background));
checkBoxV.setImageResource(
R.drawable.ic_checkbox_marked);
} else {
view.setBackgroundColor(Color.WHITE);
checkBoxV.setImageResource(
R.drawable.ic_checkbox_blank_outline);
}
checkBoxV.setVisibility(View.VISIBLE);
}
// this if-else is needed even though kept-in-sync icon is visible by default
// because android reuses views in listview
if (!file.isAvailableOffline()) {
view.findViewById(R.id.keptOfflineIcon).setVisibility(View.GONE);
} else {
view.findViewById(R.id.keptOfflineIcon).setVisibility(View.VISIBLE);
}
// No Folder
if (!file.isFolder()) {
if ((MimeTypeUtil.isImage(file) || MimeTypeUtil.isVideo(file)) && file.getRemoteId() != null) {
// Thumbnail in Cache?
Bitmap thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(file.getRemoteId());
if (thumbnail != null && !file.needsUpdateThumbnail()) {
if (MimeTypeUtil.isVideo(file)) {
Bitmap withOverlay = ThumbnailsCacheManager.addVideoOverlay(thumbnail);
fileIcon.setImageBitmap(withOverlay);
} else {
fileIcon.setImageBitmap(thumbnail);
}
} else {
// generate new Thumbnail
if (ThumbnailsCacheManager.cancelPotentialThumbnailWork(file, fileIcon)) {
try {
final ThumbnailsCacheManager.ThumbnailGenerationTask task =
new ThumbnailsCacheManager.ThumbnailGenerationTask(
fileIcon, mStorageManager, mAccount
);
if (thumbnail == null) {
if (MimeTypeUtil.isVideo(file)) {
thumbnail = ThumbnailsCacheManager.mDefaultVideo;
} else {
thumbnail = ThumbnailsCacheManager.mDefaultImg;
}
}
final ThumbnailsCacheManager.AsyncThumbnailDrawable asyncDrawable =
new ThumbnailsCacheManager.AsyncThumbnailDrawable(
mContext.getResources(),
thumbnail,
task
);
fileIcon.setImageDrawable(asyncDrawable);
task.execute(file);
} catch (IllegalArgumentException e) {
Log_OC.d(TAG, "ThumbnailGenerationTask : " + e.getMessage());
}
}
}
if (file.getMimetype().equalsIgnoreCase("image/png")) {
fileIcon.setBackgroundColor(mContext.getResources()
.getColor(R.color.background_color));
}
} else {
fileIcon.setImageResource(MimeTypeUtil.getFileTypeIconId(file.getMimetype(),
file.getFileName()));
}
} else {
// Folder
fileIcon.setImageResource(
MimeTypeUtil.getFolderTypeIconId(
file.isSharedWithMe() || file.isSharedWithSharee(),
file.isSharedViaLink()
)
);
}
}
return view;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isEmpty() {
return (mFiles == null || mFiles.isEmpty());
}
/**
* Change the adapted directory for a new one
*
* @param directory New folder to adapt. Can be NULL, meaning
* "no content to adapt".
* @param updatedStorageManager Optional updated storage manager; used to replace
* mStorageManager if is different (and not NULL)
*/
public void swapDirectory(OCFile directory, FileDataStorageManager updatedStorageManager
, boolean onlyOnDevice) {
if (updatedStorageManager != null && !updatedStorageManager.equals(mStorageManager)) {
mStorageManager = updatedStorageManager;
mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
}
if (mStorageManager != null) {
mFiles = mStorageManager.getFolderContent(directory, onlyOnDevice);
if (mJustFolders) {
mFiles = getFolders(mFiles);
}
if (!mShowHiddenFiles) {
mFiles = filterHiddenFiles(mFiles);
}
mFiles = FileStorageUtils.sortOcFolder(mFiles);
mFilesAll.clear();
mFilesAll.addAll(mFiles);
currentDirectory = directory;
} else {
mFiles = null;
mFilesAll.clear();
}
notifyDataSetChanged();
}
private void searchForLocalFileInDefaultPath(OCFile file) {
if (file.getStoragePath() == null && !file.isFolder()) {
File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
if (f.exists()) {
file.setStoragePath(f.getAbsolutePath());
file.setLastSyncDateForData(f.lastModified());
}
}
}
public void setData(ArrayList<Object> objects, ExtendedListFragment.SearchType searchType) {
mFiles = new Vector<>();
if (searchType.equals(ExtendedListFragment.SearchType.SHARED_FILTER)) {
ArrayList<OCShare> shares = new ArrayList<>();
for (int i = 0; i < objects.size(); i++) {
// check type before cast as of long running data fetch it is possible that old result is filled
if (objects.get(i) instanceof OCShare) {
OCShare ocShare = (OCShare) objects.get(i);
shares.add(ocShare);
OCFile ocFile = mStorageManager.getFileByPath(ocShare.getPath());
if (!mFiles.contains(ocFile)) {
mFiles.add(ocFile);
}
}
}
mStorageManager.saveShares(shares);
} else {
for (int i = 0; i < objects.size(); i++) {
OCFile ocFile = FileStorageUtils.fillOCFile((RemoteFile) objects.get(i));
searchForLocalFileInDefaultPath(ocFile);
mFiles.add(ocFile);
}
}
if (!searchType.equals(ExtendedListFragment.SearchType.PHOTO_SEARCH) &&
!searchType.equals(ExtendedListFragment.SearchType.PHOTOS_SEARCH_FILTER) &&
!searchType.equals(ExtendedListFragment.SearchType.RECENTLY_MODIFIED_SEARCH) &&
!searchType.equals(ExtendedListFragment.SearchType.RECENTLY_MODIFIED_SEARCH_FILTER)) {
mFiles = FileStorageUtils.sortOcFolder(mFiles);
} else {
mFiles = FileStorageUtils.sortOcFolderDescDateModified(mFiles);
}
mFilesAll = new Vector<>();
mFilesAll.addAll(mFiles);
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
OCFileListFragmentInterface.finishedFiltering();
}
});
}
/**
* Filter for getting only the folders
*
* @param files Collection of files to filter
* @return Folders in the input
*/
public Vector<OCFile> getFolders(Vector<OCFile> files) {
Vector<OCFile> ret = new Vector<>();
OCFile current;
for (int i = 0; i < files.size(); i++) {
current = files.get(i);
if (current.isFolder()) {
ret.add(current);
}
}
return ret;
}
public void setSortOrder(Integer order, boolean ascending) {
PreferenceManager.setSortOrder(mContext, order);
PreferenceManager.setSortAscending(mContext, ascending);
FileStorageUtils.mSortOrder = order;
FileStorageUtils.mSortAscending = ascending;
mFiles = FileStorageUtils.sortOcFolder(mFiles);
notifyDataSetChanged();
}
public ArrayList<OCFile> getCheckedItems(AbsListView parentList) {
SparseBooleanArray checkedPositions = parentList.getCheckedItemPositions();
ArrayList<OCFile> files = new ArrayList<>();
Object item;
for (int i = 0; i < checkedPositions.size(); i++) {
if (checkedPositions.valueAt(i)) {
item = getItem(checkedPositions.keyAt(i));
if (item != null) {
files.add((OCFile) item);
}
}
}
return files;
}
public Filter getFilter() {
if (mFilesFilter == null) {
mFilesFilter = new FilesFilter();
}
return mFilesFilter;
}
private class FilesFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
Vector<OCFile> filteredFiles = new Vector<>();
if (!TextUtils.isEmpty(constraint)) {
for (int i = 0; i < mFilesAll.size(); i++) {
OCFile currentFile = mFilesAll.get(i);
if (currentFile.getParentRemotePath().equals(currentDirectory.getRemotePath()) &&
currentFile.getFileName().toLowerCase().contains(constraint.toString().toLowerCase()) &&
!filteredFiles.contains(currentFile)) {
filteredFiles.add(currentFile);
}
}
}
results.values = filteredFiles;
results.count = filteredFiles.size();
return results;
}
@Override
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
Vector<OCFile> ocFiles = (Vector<OCFile>) results.values;
mFiles = new Vector<>();
if (ocFiles != null && ocFiles.size() > 0) {
mFiles.addAll(ocFiles);
if (!mShowHiddenFiles) {
mFiles = filterHiddenFiles(mFiles);
}
mFiles = FileStorageUtils.sortOcFolder(mFiles);
}
notifyDataSetChanged();
OCFileListFragmentInterface.finishedFiltering();
}
}
/**
* Filter for hidden files
*
* @param files Collection of files to filter
* @return Non-hidden files
*/
public Vector<OCFile> filterHiddenFiles(Vector<OCFile> files) {
Vector<OCFile> ret = new Vector<>();
OCFile current;
for (int i = 0; i < files.size(); i++) {
current = files.get(i);
if (!current.isHidden() && !ret.contains(current)) {
ret.add(current);
}
}
return ret;
}
}
| aleister09/android | src/main/java/com/owncloud/android/ui/adapter/FileListListAdapter.java | Java | gpl-2.0 | 25,342 |
/*
* Copyright (c) 2010 Mark Liversedge (liversedge@gmail.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "CalDAV.h"
#include "MainWindow.h"
#include "Athlete.h"
CalDAV::CalDAV(Context *context) : context(context), mode(None)
{
nam = new QNetworkAccessManager(this);
connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestReply(QNetworkReply*)));
connect(nam, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), this,
SLOT(userpass(QNetworkReply*,QAuthenticator*)));
// connect(nam, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), this,
// SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
}
//
// GET event directory listing
//
bool
CalDAV::download()
{
QString url = appsettings->cvalue(context->athlete->cyclist, GC_DVURL, "").toString();
if (url == "") return false; // not configured
QNetworkRequest request = QNetworkRequest(QUrl(url));
QByteArray *queryText = new QByteArray( "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
"<C:calendar-query xmlns:D=\"DAV:\""
" xmlns:C=\"urn:ietf:params:xml:ns:caldav\">"
" <D:prop>"
" <D:getetag/>"
" <C:calendar-data/>"
" </D:prop>"
" <C:filter>"
" <C:comp-filter name=\"VCALENDAR\">"
" <C:comp-filter name=\"VEVENT\">"
" <C:time-range end=\"20200101T000000Z\" start=\"20000101T000000Z\"/>"
" </C:comp-filter>"
" </C:comp-filter>"
" </C:filter>"
"</C:calendar-query>\r\n");
request.setRawHeader("Depth", "0");
request.setRawHeader("Content-Type", "application/xml; charset=\"utf-8\"");
request.setRawHeader("Content-Length", (QString("%1").arg(queryText->size())).toLatin1());
QBuffer *query = new QBuffer(queryText);
mode = Events;
QNetworkReply *reply = nam->sendCustomRequest(request, "REPORT", query);
if (reply->error() != QNetworkReply::NoError) {
QMessageBox::warning(context->mainWindow, tr("CalDAV REPORT url error"), reply->errorString());
mode = None;
return false;
}
return true;
}
//
// Get OPTIONS available
//
bool
CalDAV::options()
{
QString url = appsettings->cvalue(context->athlete->cyclist, GC_DVURL, "").toString();
if (url == "") return false; // not configured
QNetworkRequest request = QNetworkRequest(QUrl(url));
QByteArray *queryText = new QByteArray("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
"<D:options xmlns:D=\"DAV:\">"
" <C:calendar-home-set xmlns:C=\"urn:ietf:params:xml:ns:caldav\"/>"
"</D:options>");
request.setRawHeader("Depth", "0");
request.setRawHeader("Content-Type", "text/xml; charset=\"utf-8\"");
request.setRawHeader("Content-Length", (QString("%1").arg(queryText->size())).toLatin1());
QBuffer *query = new QBuffer(queryText);
mode = Options;
QNetworkReply *reply = nam->sendCustomRequest(request, "OPTIONS", query);
if (reply->error() != QNetworkReply::NoError) {
QMessageBox::warning(context->mainWindow, tr("CalDAV OPTIONS url error"), reply->errorString());
mode = None;
return false;
}
return true;
}
//
// Get URI Properties via PROPFIND
//
bool
CalDAV::propfind()
{
QString url = appsettings->cvalue(context->athlete->cyclist, GC_DVURL, "").toString();
if (url == "") return false; // not configured
QNetworkRequest request = QNetworkRequest(QUrl(url));
QByteArray *queryText = new QByteArray( "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
"<D:propfind xmlns:D=\"DAV:\""
" xmlns:C=\"urn:ietf:params:xml:ns:caldav\">"
" <D:prop>"
" <D:displayname/>"
" <C:calendar-timezone/> "
" <C:supported-calendar-component-set/> "
" </D:prop>"
"</D:propfind>\r\n");
request.setRawHeader("Content-Type", "text/xml; charset=\"utf-8\"");
request.setRawHeader("Content-Length", (QString("%1").arg(queryText->size())).toLatin1());
request.setRawHeader("Depth", "0");
QBuffer *query = new QBuffer(queryText);
mode = PropFind;
QNetworkReply *reply = nam->sendCustomRequest(request, "PROPFIND" , query);
if (reply->error() != QNetworkReply::NoError) {
QMessageBox::warning(context->mainWindow, tr("CalDAV OPTIONS url error"), reply->errorString());
mode = None;
return false;
}
return true;
}
//
// REPORT of "all" VEVENTS
//
bool
CalDAV::report()
{
QString url = appsettings->cvalue(context->athlete->cyclist, GC_DVURL, "").toString();
if (url == "") return false; // not configured
QNetworkRequest request = QNetworkRequest(QUrl(url));
QByteArray *queryText = new QByteArray("<x1:calendar-query xmlns:x1=\"urn:ietf:params:xml:ns:caldav\">"
"<x0:prop xmlns:x0=\"DAV:\">"
"<x0:getetag/>"
"<x1:calendar-data/>"
"</x0:prop>"
"<x1:filter>"
"<x1:comp-filter name=\"VCALENDAR\">"
"<x1:comp-filter name=\"VEVENT\">"
"<x1:time-range end=\"21001231\" start=\"20000101T000000Z\"/>"
"</x1:comp-filter>"
"</x1:comp-filter>"
"</x1:filter>"
"</x1:calendar-query>");
QBuffer *query = new QBuffer(queryText);
mode = Report;
QNetworkReply *reply = nam->sendCustomRequest(request, "REPORT", query);
if (reply->error() != QNetworkReply::NoError) {
QMessageBox::warning(context->mainWindow, tr("CalDAV REPORT url error"), reply->errorString());
mode = None;
return false;
}
return true;
}
// utility function to create a VCALENDAR from a single RideItem
static
icalcomponent *createEvent(RideItem *rideItem)
{
// calendar
icalcomponent *root = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
// calendar version
icalproperty *version = icalproperty_new_version("2.0");
icalcomponent_add_property(root, version);
icalcomponent *event = icalcomponent_new(ICAL_VEVENT_COMPONENT);
//
// Unique ID
//
QString id = rideItem->ride()->id();
if (id == "") {
id = QUuid::createUuid().toString() + "@" + "goldencheetah.org";
rideItem->ride()->setId(id);
rideItem->notifyRideMetadataChanged();
rideItem->setDirty(true); // need to save this!
}
icalproperty *uid = icalproperty_new_uid(id.toLatin1());
icalcomponent_add_property(event, uid);
//
// START DATE
//
struct icaltimetype atime;
QDateTime utc = rideItem->dateTime.toUTC();
atime.year = utc.date().year();
atime.month = utc.date().month();
atime.day = utc.date().day();
atime.hour = utc.time().hour();
atime.minute = utc.time().minute();
atime.second = utc.time().second();
atime.is_utc = 1; // this is UTC is_utc is redundant but kept for completeness
atime.is_date = 0; // this is a date AND time
atime.is_daylight = 0; // no daylight savings - its UTC
atime.zone = icaltimezone_get_utc_timezone(); // set UTC timezone
icalproperty *dtstart = icalproperty_new_dtstart(atime);
icalcomponent_add_property(event, dtstart);
//
// DURATION
//
// override values?
QMap<QString,QString> lookup;
lookup = rideItem->ride()->metricOverrides.value("workout_time");
int secs = lookup.value("value", "0.0").toDouble();
// from last - first timestamp?
if (!rideItem->ride()->dataPoints().isEmpty() && rideItem->ride()->dataPoints().last() != NULL) {
if (!secs) secs = rideItem->ride()->dataPoints().last()->secs;
}
// ok, got secs so now create in vcard
struct icaldurationtype dur;
dur.is_neg = 0;
dur.days = dur.weeks = 0;
dur.hours = secs/3600;
dur.minutes = secs%3600/60;
dur.seconds = secs%60;
icalcomponent_set_duration(event, dur);
// set title & description
QString title = rideItem->ride()->getTag("Title", ""); // *new* 'special' metadata field
if (title == "") title = rideItem->ride()->getTag("Sport", "") + " Workout";
icalcomponent_set_summary(event, title.toLatin1());
// set description using standard stuff
icalcomponent_set_description(event, rideItem->ride()->getTag("Calendar Text", "").toLatin1());
// attach ridefile
// google doesn't support attachments yet. There is a labs option to use google docs
// but it is only available to Google Apps customers.
// put the event into root
icalcomponent_add_component(root, event);
return root;
}
// extract <calendar-data> entries and concatenate
// into a single string. This is from a query response
// where the VEVENTS are embedded within an XML document
static QString extractComponents(QString document)
{
QString returning = "";
// parse the document and extract the multistatus node (there is only one of those)
QDomDocument doc;
if (document == "" || doc.setContent(document) == false) return "";
QDomNode multistatus = doc.documentElement();
if (multistatus.isNull()) return "";
// Google Calendar retains the namespace prefix in the results
// Apple MobileMe doesn't. This means the element names will
// possibly need a prefix...
QString Dprefix = "";
QString Cprefix = "";
if (multistatus.nodeName().startsWith("D:")) {
Dprefix = "D:";
Cprefix = "C:";
}
// read all the responses within the multistatus
for (QDomNode response = multistatus.firstChildElement(Dprefix + "response");
response.nodeName() == (Dprefix + "response"); response = response.nextSiblingElement(Dprefix + "response")) {
// skate over the nest of crap to get at the calendar-data
QDomNode propstat = response.firstChildElement(Dprefix + "propstat");
QDomNode prop = propstat.firstChildElement(Dprefix + "prop");
QDomNode calendardata = prop.firstChildElement(Cprefix + "calendar-data");
// extract the calendar entry - top and tail the other crap
QString text = calendardata.toElement().text();
int start = text.indexOf("BEGIN:VEVENT");
int stop = text.indexOf("END:VEVENT");
if (start == -1 || stop == -1) continue;
returning += text.mid(start, stop-start+10) + "\n";
}
return returning;
}
//
// PUT a ride item
//
bool
CalDAV::upload(RideItem *rideItem)
{
// is this a valid ride?
if (!rideItem || !rideItem->ride()) return false;
QString url = appsettings->cvalue(context->athlete->cyclist, GC_DVURL, "").toString();
if (url == "") return false; // not configured
// lets upload to calendar
url += rideItem->fileName;
url += ".ics";
// form the request
QNetworkRequest request = QNetworkRequest(QUrl(url));
request.setRawHeader("Content-Type", "text/calendar");
request.setRawHeader("Content-Length", "xxxx");
// create the ICal event
icalcomponent *vcard = createEvent(rideItem);
QByteArray vcardtext(icalcomponent_as_ical_string(vcard));
icalcomponent_free(vcard);
mode = Put;
QNetworkReply *reply = nam->put(request, vcardtext);
if (reply->error() != QNetworkReply::NoError) {
mode = None;
QMessageBox::warning(context->mainWindow, tr("CalDAV Calendar url error"), reply->errorString());
return false;
}
return true;
}
//
// All queries/commands respond here
//
void
CalDAV::requestReply(QNetworkReply *reply)
{
QString response = reply->readAll();
switch (mode) {
case Report:
case Events:
context->athlete->rideCalendar->refreshRemote(extractComponents(response));
break;
default:
case Options:
case PropFind:
case Put:
//nothing at the moment
break;
}
mode = None;
}
//
// Provide user credentials, called when receive a 401
//
void
CalDAV::userpass(QNetworkReply*,QAuthenticator*a)
{
QString user = appsettings->cvalue(context->athlete->cyclist, GC_DVUSER, "").toString();
QString pass = appsettings->cvalue(context->athlete->cyclist, GC_DVPASS, "").toString();
a->setUser(user);
a->setPassword(pass);
}
//
// Trap SSL errors, does nothing ... for now
//
void
CalDAV::sslErrors(QNetworkReply*,QList<QSslError>&)
{
}
| chet0xhenry/GoldenCheetah | src/CalDAV.cpp | C++ | gpl-2.0 | 13,932 |
/**
* JHylaFax - A java client for HylaFAX.
*
* Copyright (C) 2005 by Steffen Pingel <steffenp@gmx.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package net.sf.jhylafax;
import static net.sf.jhylafax.JHylaFAX.i18n;
import gnu.hylafax.HylaFAXClient;
import javax.swing.JFrame;
import net.sf.jhylafax.fax.FaxJob;
import net.sf.jhylafax.fax.HylaFAXClientHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xnap.commons.gui.ErrorDialog;
import org.xnap.commons.io.Job;
import org.xnap.commons.io.ProgressMonitor;
import org.xnap.commons.io.UserAbortException;
/**
* A dialog for polling of faxes.
*
* @author Steffen Pingel
*/
public class PollDialog extends AbstractFaxDialog {
private final static Log logger = LogFactory.getLog(PollDialog.class);
public PollDialog(JFrame owner) {
super(owner);
addNumberTextField();
addDateControls();
FaxJob job = new FaxJob();
HylaFAXClientHelper.initializeFromSettings(job);
setJob(job);
updateLabels();
pack();
}
@Override
public boolean apply() {
if (!super.apply()) {
return false;
}
Job<?> ioJob = new Job() {
public Object run(ProgressMonitor monitor) throws Exception
{
monitor.setTotalSteps(4);
HylaFAXClient client = JHylaFAX.getInstance().getConnection(monitor);
monitor.work(1);
gnu.hylafax.Job pollJob = client.createJob();
HylaFAXClientHelper.applyParameter(pollJob, getJob());
pollJob.setProperty("POLL", "\"\" \"\"");
monitor.work(1);
client.submit(pollJob);
monitor.work(2);
return null;
}
};
try {
JHylaFAX.getInstance().runJob(PollDialog.this, ioJob);
JHylaFAX.getInstance().updateTables();
}
catch (UserAbortException e) {
return false;
}
catch (Exception e) {
logger.debug("Error polling fax", e);
ErrorDialog.showError(this, i18n.tr("Could not poll fax"),
i18n.tr("JHylaFAX Error"),
e);
return false;
}
return true;
}
public void updateLabels() {
super.updateLabels();
setTitle(i18n.tr("Poll Fax"));
}
}
| Distrotech/jhylafax | src/java/net/sf/jhylafax/PollDialog.java | Java | gpl-2.0 | 2,766 |
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2017 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
/** @file
* @brief
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Phone Class
**/
class Phone extends CommonDBTM {
// From CommonDBTM
public $dohistory = true;
static protected $forward_entity_to = array('Infocom', 'NetworkPort', 'ReservationItem');
static $rightname = 'phone';
protected $usenotepad = true;
static function getTypeName($nb=0) {
//TRANS: Test of comment for translation (mark : //TRANS)
return _n('Phone', 'Phones', $nb);
}
/**
* @see CommonDBTM::useDeletedToLockIfDynamic()
*
* @since version 0.84
**/
function useDeletedToLockIfDynamic() {
return false;
}
function defineTabs($options=array()) {
$ong = array();
$this->addDefaultFormTab($ong);
$this->addStandardTab('Item_Devices', $ong, $options);
$this->addStandardTab('Computer_Item', $ong, $options);
$this->addStandardTab('NetworkPort', $ong, $options);
$this->addStandardTab('Infocom', $ong, $options);
$this->addStandardTab('Contract_Item', $ong, $options);
$this->addStandardTab('Document_Item', $ong, $options);
$this->addStandardTab('KnowbaseItem_Item', $ong, $options);
$this->addStandardTab('Ticket', $ong, $options);
$this->addStandardTab('Item_Problem', $ong, $options);
$this->addStandardTab('Change_Item', $ong, $options);
$this->addStandardTab('Link', $ong, $options);
$this->addStandardTab('Notepad', $ong, $options);
$this->addStandardTab('Reservation', $ong, $options);
$this->addStandardTab('Log', $ong, $options);
return $ong;
}
function prepareInputForAdd($input) {
if (isset($input["id"]) && ($input["id"] > 0)) {
$input["_oldID"] = $input["id"];
}
unset($input['id']);
unset($input['withtemplate']);
return $input;
}
function post_addItem() {
global $DB, $CFG_GLPI;
// Manage add from template
if (isset($this->input["_oldID"])) {
// ADD Devices
Item_devices::cloneItem($this->getType(), $this->input["_oldID"], $this->fields['id']);
// ADD Infocoms
Infocom::cloneItem($this->getType(), $this->input["_oldID"], $this->fields['id']);
// ADD Ports
NetworkPort::cloneItem($this->getType(), $this->input["_oldID"], $this->fields['id']);
// ADD Contract
Contract_Item::cloneItem($this->getType(), $this->input["_oldID"], $this->fields['id']);
// ADD Documents
Document_Item::cloneItem($this->getType(), $this->input["_oldID"], $this->fields['id']);
// ADD Computers
Computer_Item::cloneItem($this->getType(), $this->input["_oldID"], $this->fields['id']);
//Add KB links
KnowbaseItem_Item::cloneItem($this->getType(), $this->input["_oldID"], $this->fields['id']);
}
}
function cleanDBonPurge() {
global $DB;
$ci = new Computer_Item();
$ci->cleanDBonItemDelete(__CLASS__, $this->fields['id']);
$ip = new Item_Problem();
$ip->cleanDBonItemDelete(__CLASS__, $this->fields['id']);
$ci = new Change_Item();
$ci->cleanDBonItemDelete(__CLASS__, $this->fields['id']);
$ip = new Item_Project();
$ip->cleanDBonItemDelete(__CLASS__, $this->fields['id']);
Item_Devices::cleanItemDeviceDBOnItemDelete($this->getType(), $this->fields['id'],
(!empty($this->input['keep_devices'])));
}
/**
* Print the phone form
*
* @param $ID integer ID of the item
* @param $options array
* - target filename : where to go when done.
* - withtemplate boolean : template or basic item
*
* @return boolean item found
**/
function showForm($ID, $options=array()) {
global $CFG_GLPI;
$target = $this->getFormURL();
$withtemplate = $this->initForm($ID, $options);
$this->showFormHeader($options);
echo "<tr class='tab_bg_1'>";
//TRANS: %1$s is a string, %2$s a second one without spaces between them : to change for RTL
echo "<td>".sprintf(__('%1$s%2$s'), __('Name'),
(isset($options['withtemplate']) && $options['withtemplate']?"*":"")).
"</td>";
echo "<td>";
$objectName = autoName($this->fields["name"], "name",
(isset($options['withtemplate']) && ($options['withtemplate'] == 2)),
$this->getType(), $this->fields["entities_id"]);
Html::autocompletionTextField($this, 'name', array('value' => $objectName));
echo "</td>";
echo "<td>".__('Status')."</td>";
echo "<td>";
State::dropdown(array('value' => $this->fields["states_id"],
'entity' => $this->fields["entities_id"],
'condition' => "`is_visible_phone`='1'"));
echo "</td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Location')."</td>";
echo "<td>";
Location::dropdown(array('value' => $this->fields["locations_id"],
'entity' => $this->fields["entities_id"]));
echo "</td>";
echo "<td>".__('Type')."</td>";
echo "<td>";
PhoneType::dropdown(array('value' => $this->fields["phonetypes_id"]));
echo "</td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Technician in charge of the hardware')."</td>";
echo "<td>";
User::dropdown(array('name' => 'users_id_tech',
'value' => $this->fields["users_id_tech"],
'right' => 'own_ticket',
'entity' => $this->fields["entities_id"]));
echo "</td>";
echo "<td>".__('Manufacturer')."</td>";
echo "<td>";
Manufacturer::dropdown(array('value' => $this->fields["manufacturers_id"]));
echo "</td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Group in charge of the hardware')."</td>";
echo "<td>";
Group::dropdown(array('name' => 'groups_id_tech',
'value' => $this->fields['groups_id_tech'],
'entity' => $this->fields['entities_id'],
'condition' => '`is_assign`'));
echo "</td>";
echo "<td>".__('Model')."</td>";
echo "<td>";
PhoneModel::dropdown(array('value' => $this->fields["phonemodels_id"]));
echo "</td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Alternate username number')."</td>";
echo "<td>";
Html::autocompletionTextField($this, "contact_num");
echo "</td>";
echo "<td>".__('Serial number')."</td>";
echo "<td>";
Html::autocompletionTextField($this, "serial");
echo "</td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Alternate username')."</td><td>";
Html::autocompletionTextField($this, "contact");
echo "</td>";
echo "<td>".sprintf(__('%1$s%2$s'), __('Inventory number'),
(isset($options['withtemplate']) && $options['withtemplate']?"*":"")).
"</td>";
echo "<td>";
$objectName = autoName($this->fields["otherserial"], "otherserial",
(isset($options['withtemplate']) && ($options['withtemplate'] == 2)),
$this->getType(), $this->fields["entities_id"]);
Html::autocompletionTextField($this, 'otherserial', array('value' => $objectName));
echo "</td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('User')."</td>";
echo "<td>";
User::dropdown(array('value' => $this->fields["users_id"],
'entity' => $this->fields["entities_id"],
'right' => 'all'));
echo "</td>";
echo "<td>".__('Management type')."</td>";
echo "<td>";
Dropdown::showGlobalSwitch($this->fields["id"],
array('withtemplate' => $withtemplate,
'value' => $this->fields["is_global"],
'management_restrict'
=> $CFG_GLPI["phones_management_restrict"],
'target' => $target));
echo "</td></tr>\n";
$rowspan = 6;
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Group')."</td>";
echo "<td>";
Group::dropdown(array('value' => $this->fields["groups_id"],
'entity' => $this->fields["entities_id"],
'condition' => '`is_itemgroup`'));
echo "</td>";
echo "<td rowspan='$rowspan'>".__('Comments')."</td>";
echo "<td rowspan='$rowspan'>
<textarea cols='45' rows='".($rowspan+3)."' name='comment' >".$this->fields["comment"];
echo "</textarea></td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Brand')."</td>";
echo "<td>";
Html::autocompletionTextField($this, "brand");
echo "</td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Power supply')."</td>";
echo "<td>";
PhonePowerSupply::dropdown(array('value' => $this->fields["phonepowersupplies_id"]));
echo "</td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>"._n('Firmware', 'Firmwares', 1)."</td>";
echo "<td>";
Html::autocompletionTextField($this, "firmware");
echo "</td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>"._x('quantity', 'Number of lines')."</td><td>";
Html::autocompletionTextField($this, "number_line");
echo "</td></tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Flags')."</td>";
echo "<td>";
// micro?
echo "\n<table><tr><td>".__('Headset')."</td>";
echo "<td> ";
Dropdown::showYesNo("have_headset", $this->fields["have_headset"]);
echo "</td></tr>";
// hp?
echo "<tr><td>".__('Speaker')."</td>";
echo "<td> ";
Dropdown::showYesNo("have_hp", $this->fields["have_hp"]);
echo "</td></tr></table>\n";
echo "</td>";
echo "</tr>\n";
if (!empty($ID)
&& $this->fields["is_dynamic"]) {
echo "<tr class='tab_bg_1'><td colspan='4'>";
Plugin::doHook("autoinventory_information", $this);
echo "</td></tr>";
}
$this->showFormButtons($options);
return true;
}
/**
* Return the linked items (in computers_items)
*
* @return an array of linked items like array('Computer' => array(1,2), 'Printer' => array(5,6))
* @since version 0.84.4
**/
function getLinkedItems() {
global $DB;
$query = "SELECT 'Computer', `computers_id`
FROM `glpi_computers_items`
WHERE `itemtype` = '".$this->getType()."'
AND `items_id` = '" . $this->fields['id']."'";
$tab = array();
foreach ($DB->request($query) as $data) {
$tab['Computer'][$data['computers_id']] = $data['computers_id'];
}
return $tab;
}
/**
* @see CommonDBTM::getSpecificMassiveActions()
**/
function getSpecificMassiveActions($checkitem=NULL) {
$actions = parent::getSpecificMassiveActions($checkitem);
if (static::canUpdate()) {
Computer_Item::getMassiveActionsForItemtype($actions, __CLASS__, 0, $checkitem);
MassiveAction::getAddTransferList($actions);
$kb_item = new KnowbaseItem();
$kb_item->getEmpty();
if ($kb_item->canViewItem()) {
$actions['KnowbaseItem_Item'.MassiveAction::CLASS_ACTION_SEPARATOR.'add'] = _x('button', 'Link knowledgebase article');
}
}
return $actions;
}
function getSearchOptionsNew() {
$tab = [];
$tab[] = [
'id' => 'common',
'name' => __('Characteristics')
];
$tab[] = [
'id' => '1',
'table' => $this->getTable(),
'field' => 'name',
'name' => __('Name'),
'datatype' => 'itemlink',
'massiveaction' => false
];
$tab[] = [
'id' => '2',
'table' => $this->getTable(),
'field' => 'id',
'name' => __('ID'),
'massiveaction' => false,
'datatype' => 'number'
];
$tab = array_merge($tab, Location::getSearchOptionsToAddNew());
$tab[] = [
'id' => '4',
'table' => 'glpi_phonetypes',
'field' => 'name',
'name' => __('Type'),
'datatype' => 'dropdown'
];
$tab[] = [
'id' => '40',
'table' => 'glpi_phonemodels',
'field' => 'name',
'name' => __('Model'),
'datatype' => 'dropdown'
];
$tab[] = [
'id' => '31',
'table' => 'glpi_states',
'field' => 'completename',
'name' => __('Status'),
'datatype' => 'dropdown',
'condition' => '`is_visible_phone`'
];
$tab[] = [
'id' => '5',
'table' => $this->getTable(),
'field' => 'serial',
'name' => __('Serial number'),
'datatype' => 'string'
];
$tab[] = [
'id' => '6',
'table' => $this->getTable(),
'field' => 'otherserial',
'name' => __('Inventory number'),
'datatype' => 'string'
];
$tab[] = [
'id' => '7',
'table' => $this->getTable(),
'field' => 'contact',
'name' => __('Alternate username'),
'datatype' => 'string'
];
$tab[] = [
'id' => '8',
'table' => $this->getTable(),
'field' => 'contact_num',
'name' => __('Alternate username number'),
'datatype' => 'string'
];
$tab[] = [
'id' => '9',
'table' => $this->getTable(),
'field' => 'number_line',
'name' => _x('quantity', 'Number of lines'),
'datatype' => 'string'
];
$tab[] = [
'id' => '70',
'table' => 'glpi_users',
'field' => 'name',
'name' => __('User'),
'datatype' => 'dropdown',
'right' => 'all'
];
$tab[] = [
'id' => '71',
'table' => 'glpi_groups',
'field' => 'completename',
'name' => __('Group'),
'condition' => '`is_itemgroup`',
'datatype' => 'dropdown'
];
$tab[] = [
'id' => '19',
'table' => $this->getTable(),
'field' => 'date_mod',
'name' => __('Last update'),
'datatype' => 'datetime',
'massiveaction' => false
];
$tab[] = [
'id' => '121',
'table' => $this->getTable(),
'field' => 'date_creation',
'name' => __('Creation date'),
'datatype' => 'datetime',
'massiveaction' => false
];
$tab[] = [
'id' => '16',
'table' => $this->getTable(),
'field' => 'comment',
'name' => __('Comments'),
'datatype' => 'text'
];
$tab[] = [
'id' => '11',
'table' => $this->getTable(),
'field' => 'brand',
'name' => __('Brand'),
'datatype' => 'string'
];
$tab[] = [
'id' => '23',
'table' => 'glpi_manufacturers',
'field' => 'name',
'name' => __('Manufacturer'),
'datatype' => 'dropdown'
];
$tab[] = [
'id' => '32',
'table' => $this->getTable(),
'field' => 'firmware',
'name' => __('Firmware'),
'datatype' => 'string'
];
$tab[] = [
'id' => '24',
'table' => 'glpi_users',
'field' => 'name',
'linkfield' => 'users_id_tech',
'name' => __('Technician in charge of the hardware'),
'datatype' => 'dropdown',
'right' => 'own_ticket'
];
$tab[] = [
'id' => '49',
'table' => 'glpi_groups',
'field' => 'completename',
'linkfield' => 'groups_id_tech',
'name' => __('Group in charge of the hardware'),
'condition' => '`is_assign`',
'datatype' => 'dropdown'
];
$tab[] = [
'id' => '42',
'table' => 'glpi_phonepowersupplies',
'field' => 'name',
'name' => __('Power supply'),
'datatype' => 'dropdown'
];
$tab[] = [
'id' => '43',
'table' => $this->getTable(),
'field' => 'have_headset',
'name' => __('Headset'),
'datatype' => 'bool'
];
$tab[] = [
'id' => '44',
'table' => $this->getTable(),
'field' => 'have_hp',
'name' => __('Speaker'),
'datatype' => 'bool'
];
$tab[] = [
'id' => '80',
'table' => 'glpi_entities',
'field' => 'completename',
'name' => __('Entity'),
'massiveaction' => false,
'datatype' => 'dropdown'
];
$tab[] = [
'id' => '82',
'table' => $this->getTable(),
'field' => 'is_global',
'name' => __('Global management'),
'datatype' => 'bool',
'massiveaction' => false
];
// add objectlock search options
$tab = array_merge($tab, ObjectLock::getSearchOptionsToAddNew(get_class($this)));
$tab = array_merge($tab, Notepad::getSearchOptionsToAddNew());
return $tab;
}
}
| eltharin/glpi | inc/phone.class.php | PHP | gpl-2.0 | 20,642 |
<?php
if (!defined('_JEXEC') && !defined('_PROPAYMENT')) die('Direct Access to '.basename(__FILE__).' is not allowed.');
?>
17/02/2013 10:03:13 - ** ELABORAZIONE SERVER EGIPSY **
importo:175,20
divisa:EUR
esito:307033
ordine nymero:000000000000f7fd0398
transazione:00305B0EA8EC294665749024
negoziante:398752500002
mac ricevuto :B0383EF92717C76B9A26A57C64CFF27A
mac calcolato :B0383EF92717C76B9A26A57C64CFF27A
esito passato :1
Risultato: OK; Esito: 307033
Numero ordine: f7fd0398
17/02/2013 10:03:22 - ** ELABORAZIONE REDIRECT EGIPSY **
importo:175,20
divisa:EUR
esito:307033
ordine numero:000000000000f7fd0398
transazione:00305B0EA8EC294665749024
negoziante:398752500002
mac ricevuto :B0383EF92717C76B9A26A57C64CFF27A
mac calcolato :B0383EF92717C76B9A26A57C64CFF27A
esito passato :1
codice autorizazione307033
Risultato: OK; Esito: 307033
Numero ordine: f7fd0398
| alesconti/FF_2015 | propayment/log/2013-02-17.log.php | PHP | gpl-2.0 | 895 |
/**
*
*/
package com.airnoise.services;
import java.sql.SQLException;
import com.airnoise.core.exception.PersistenceException;
import com.airnoise.dao.DataBaseManager;
/**
* @author tomio
*
*/
public class DataBaseManagementService {
private DataBaseManager manager;
public DataBaseManagementService(DataBaseManager manager) {
this.manager = manager;
}
public void createDB() throws PersistenceException {
try {
this.manager.getDataBaseManagementDAO().createDB();
} catch (SQLException e) {
throw new PersistenceException("Error creating database", e);
}
}
public void reinitializeDB() throws PersistenceException {
try {
this.manager.getDataBaseManagementDAO().reinitializeDB();
} catch (SQLException e) {
throw new PersistenceException("Error reinitializing the database", e);
}
}
}
| mio-to/airnoise | airnoise/dao/src/main/java/com/airnoise/services/DataBaseManagementService.java | Java | gpl-2.0 | 947 |
<?php
/**
* @package Joomla.Component.Builder
*
* @created 30th April, 2015
* @author Llewellyn van der Merwe <http://www.joomlacomponentbuilder.com>
* @gitea Joomla Component Builder <https://git.vdm.dev/joomla/Component-Builder>
* @github Joomla Component Builder <https://github.com/vdm-io/Joomla-Component-Builder>
* @copyright Copyright (C) 2015 Vast Development Method. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
$edit = "index.php?option=com_componentbuilder&view=templates&task=template.edit";
?>
<?php foreach ($this->items as $i => $item): ?>
<?php
$canCheckin = $this->user->authorise('core.manage', 'com_checkin') || $item->checked_out == $this->user->id || $item->checked_out == 0;
$userChkOut = JFactory::getUser($item->checked_out);
$canDo = ComponentbuilderHelper::getActions('template',$item,'templates');
?>
<tr class="row<?php echo $i % 2; ?>">
<td class="order nowrap center hidden-phone">
<?php if ($canDo->get('core.edit.state')): ?>
<?php
$iconClass = '';
if (!$this->saveOrder)
{
$iconClass = ' inactive tip-top" hasTooltip" title="' . JHtml::tooltipText('JORDERINGDISABLED');
}
?>
<span class="sortable-handler<?php echo $iconClass; ?>">
<i class="icon-menu"></i>
</span>
<?php if ($this->saveOrder) : ?>
<input type="text" style="display:none" name="order[]" size="5"
value="<?php echo $item->ordering; ?>" class="width-20 text-area-order " />
<?php endif; ?>
<?php else: ?>
⋮
<?php endif; ?>
</td>
<td class="nowrap center">
<?php if ($canDo->get('core.edit')): ?>
<?php if ($item->checked_out) : ?>
<?php if ($canCheckin) : ?>
<?php echo JHtml::_('grid.id', $i, $item->id); ?>
<?php else: ?>
□
<?php endif; ?>
<?php else: ?>
<?php echo JHtml::_('grid.id', $i, $item->id); ?>
<?php endif; ?>
<?php else: ?>
□
<?php endif; ?>
</td>
<td class="nowrap">
<div>
<?php if ($canDo->get('core.edit')): ?>
<a href="<?php echo $edit; ?>&id=<?php echo $item->id; ?>"><?php echo $this->escape($item->name); ?></a>
<?php if ($item->checked_out): ?>
<?php echo JHtml::_('jgrid.checkedout', $i, $userChkOut->name, $item->checked_out_time, 'templates.', $canCheckin); ?>
<?php endif; ?>
<?php else: ?>
<?php echo $this->escape($item->name); ?>
<?php endif; ?><br />
<code><?php echo $this->loadTemplate('<?php echo ComponentbuilderHelper::safeString($item->alias); ?>'); ?></code>
</div>
</td>
<td class="hidden-phone">
<div><em>
<?php echo $this->escape($item->description); ?></em>
<ul style="list-style: none">
<li><?php echo JText::_("COM_COMPONENTBUILDER_CUSTOM_PHP"); ?>: <b>
<?php echo JText::_($item->add_php_view); ?></b></li>
</ul>
</div>
</td>
<td class="nowrap">
<div class="name">
<?php if ($this->user->authorise('dynamic_get.edit', 'com_componentbuilder.dynamic_get.' . (int)$item->dynamic_get)): ?>
<a href="index.php?option=com_componentbuilder&view=dynamic_gets&task=dynamic_get.edit&id=<?php echo $item->dynamic_get; ?>&return=<?php echo $this->return_here; ?>"><?php echo $this->escape($item->dynamic_get_name); ?></a>
<?php else: ?>
<?php echo $this->escape($item->dynamic_get_name); ?>
<?php endif; ?>
</div>
</td>
<td class="center">
<?php if ($canDo->get('core.edit.state')) : ?>
<?php if ($item->checked_out) : ?>
<?php if ($canCheckin) : ?>
<?php echo JHtml::_('jgrid.published', $item->published, $i, 'templates.', true, 'cb'); ?>
<?php else: ?>
<?php echo JHtml::_('jgrid.published', $item->published, $i, 'templates.', false, 'cb'); ?>
<?php endif; ?>
<?php else: ?>
<?php echo JHtml::_('jgrid.published', $item->published, $i, 'templates.', true, 'cb'); ?>
<?php endif; ?>
<?php else: ?>
<?php echo JHtml::_('jgrid.published', $item->published, $i, 'templates.', false, 'cb'); ?>
<?php endif; ?>
</td>
<td class="nowrap center hidden-phone">
<?php echo $item->id; ?>
</td>
</tr>
<?php endforeach; ?> | vdm-io/Joomla-Component-Builder | admin/views/templates/tmpl/default_body.php | PHP | gpl-2.0 | 4,232 |
/*
一:基本信息:
开源协议:https://github.com/xucongli1989/XCLNetTools/blob/master/LICENSE
项目地址:https://github.com/xucongli1989/XCLNetTools
Create By: XCL @ 2012
*/
using System.Web.Security;
namespace XCLNetTools.Encrypt
{
/// <summary>
/// md5相关
/// </summary>
public static class MD5
{
/// <summary>
/// MD5加密(大写)
/// <param name="str">待加密字符串</param>
/// <param name="key">是否在待加密的字符串中末尾追加该key,从而生成md5</param>
/// <returns>加密后的字符串(大写)</returns>
/// </summary>
public static string EncodeMD5(string str, string key = "")
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(string.Format("{0}{1}", str, key), "md5");
}
/// <summary>
/// 判断明文与密文是否匹配
/// 如果指定了key,则将明文与key组成的字符串的md5与md5Str进行比较
/// </summary>
/// <param name="str">明文</param>
/// <param name="md5Str">md5密文</param>
/// <param name="key">key</param>
/// <returns>是否匹配</returns>
public static bool IsEqualMD5(string str, string md5Str, string key = "")
{
return string.Equals(md5Str, MD5.EncodeMD5(str, key));
}
/// <summary>
/// 判断字符串是否为32位md5(不区分大小写)
/// </summary>
public static bool Is32MD5(string str)
{
return XCLNetTools.Common.Consts.RegMD5_32Uppercase.IsMatch((str ?? "").ToUpper());
}
}
} | xucongli1989/XCLNetTools | XCLNetTools/Encrypt/MD5.cs | C# | gpl-2.0 | 1,682 |
##
# This file is part of WhatWeb and may be subject to
# redistribution and commercial restrictions. Please see the WhatWeb
# web site for more information on licensing and terms of use.
# https://morningstarsecurity.com/research/whatweb
##
Plugin.define do
name "eXtreme-Message-Board"
authors [
"Brendan Coles <bcoles@gmail.com>", # 2010-10-12
]
version "0.1"
description "XMB is a lightweight PHP forum software with all the features you need to support a growing community."
website "http://www.xmbforum.com/"
# 304 results for "powered by XMB" @ 2010-10-12
# Dorks #
dorks [
'"powered by XMB"'
]
matches [
# Default HTML comments
{ :text => '<!-- Powered by XMB ' },
{ :text => '<!-- The XMB Group -->' },
# Version detection # Powered by text
{ :name => 'Powered by footer',
:version => /^Powered by XMB ([\d\.]+)<br \/>/ },
# Version detection # Default title
{ :name => 'Title',
:version => /<title>[^<]+- Powered by XMB ([\d\.]+) / },
# Version detection # HTML comments
{ :name => 'HTML comment',
:version => /^<!-- Powered by XMB ([\d\.]+) / },
]
end
| urbanadventurer/WhatWeb | plugins/xmb.rb | Ruby | gpl-2.0 | 1,081 |
/*
* Created on Jan 25, 2005
* Created by Alon Rohter
* Copyright (C) 2004-2005 Aelitis, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* AELITIS, SAS au capital de 46,603.30 euros
* 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
*
*/
package com.aelitis.azureus.core.peermanager.messaging;
import com.aelitis.azureus.core.networkmanager.Transport;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Decodes a message stream into separate messages.
*/
public interface MessageStreamDecoder {
/**
* Decode message stream from the given transport.
* @param transport to decode from
* @param max_bytes to decode/read from the stream
* @return number of bytes decoded
* @throws IOException on decoding error
*/
public int performStreamDecode( Transport transport, int max_bytes ) throws IOException;
/**
* Get the messages decoded from the transport, if any, from the last decode op.
* @return decoded messages, or null if no new complete messages were decoded
*/
public Message[] removeDecodedMessages();
/**
* Get the number of protocol (overhead) bytes decoded from the transport, from the last decode op.
* @return number of protocol bytes recevied
*/
public int getProtocolBytesDecoded();
/**
* Get the number of (piece) data bytes decoded from the transport, from the last decode op.
* @return number of data bytes received
*/
public int getDataBytesDecoded();
/**
* Get the percentage of the current message that has already been received (read from the transport).
* @return percentage complete (0-99), or -1 if no message is currently being received
*/
public int getPercentDoneOfCurrentMessage();
/**
* Pause message decoding.
*/
public void pauseDecoding();
/**
* Resume message decoding.
*/
public void resumeDecoding();
/**
* Destroy this decoder, i.e. perform cleanup.
* @return any bytes already-read and still remaining within the decoder
*/
public ByteBuffer destroy();
}
| thangbn/Direct-File-Downloader | src/src/com/aelitis/azureus/core/peermanager/messaging/MessageStreamDecoder.java | Java | gpl-2.0 | 2,758 |
(function($){
if (typeof UxU.utils !== 'undefined') {
$('.uxu-ticket-status-festival-length').html(UxU.utils.durationFromVisitors(info.tickets_sold));
}
})(jQuery);
| j0n/uxu-prototype | wp-content/plugins/uxu-tickets/js/uxu-tickets.js | JavaScript | gpl-2.0 | 173 |
# -*- coding: utf-8 -*-
#
# Nitrate is copyright 2010 Red Hat, Inc.
#
# Nitrate 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 warranties of TITLE, NON-INFRINGEMENT,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# The GPL text is available in the file COPYING that accompanies this
# distribution and at <http://www.gnu.org/licenses>.
#
# Authors:
# Xuqing Kuang <xkuang@redhat.com>
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call
from nitrate.core.utils.xmlrpc import XMLRPCSerializer
__all__ = (
'filter',
'get',
'get_me',
'update',
)
def get_user_dict(user):
u = XMLRPCSerializer(model = user)
u = u.serialize_model()
if u.get('password'):
del u['password']
return u
@log_call
def filter(request, query):
"""
Description: Performs a search and returns the resulting list of test cases.
Params: $query - Hash: keys must match valid search fields.
+------------------------------------------------------------------+
| Case Search Parameters |
+------------------------------------------------------------------+
| Key | Valid Values |
| id | Integer: ID |
| username | String: User name |
| first_name | String: User first name |
| last_name | String: User last name |
| email | String Email |
| is_active | Boolean: Return the active users |
| groups | ForeignKey: AuthGroup |
+------------------------------------------------------------------+
Returns: Array: Matching test cases are retuned in a list of hashes.
Example:
>>> User.filter({'username__startswith': 'x'})
"""
users = User.objects.filter(**query)
return [get_user_dict(u) for u in users]
def get(request, id):
"""
Description: Used to load an existing test case from the database.
Params: $id - Integer/String: An integer representing the ID in the database
Returns: A blessed User object Hash
Example:
>>> User.get(2206)
"""
return get_user_dict(User.objects.get(pk = id))
def get_me(request):
"""
Description: Get the information of myself.
Returns: A blessed User object Hash
Example:
>>> User.get_me()
"""
return get_user_dict(request.user)
def update(request, values = {}, id = None):
"""
Description: Updates the fields of the selected user. it also can change the
informations of other people if you have permission.
Params: $values - Hash of keys matching TestCase fields and the new values
to set each field to.
$id - Integer/String(Optional)
Integer: A single TestCase ID.
String: A comma string of User ID.
Default: The ID of myself
Returns: A blessed User object Hash
+-------------------+----------------+-----------------------------------------+
| Field | Type | Null |
+-------------------+----------------+-----------------------------------------+
| first_name | String | Optional |
| last_name | String | Optional(Required if changes category) |
| email | String | Optional |
| password | String | Optional |
| old_password | String | Required by password |
+-------------------+----------------+-----------------------------------------+
Example:
>>> User.update({'first_name': 'foo'})
>>> User.update({'password': 'foo', 'old_password': '123'})
>>> User.update({'password': 'foo', 'old_password': '123'}, 2206)
"""
if id:
u = User.objects.get(pk = id)
else:
u = request.user
editable_fields = ['first_name', 'last_name', 'email', 'password']
if not request.user.has_perm('auth.change_changeuser') and request.user != u:
raise PermissionDenied
for f in editable_fields:
if values.get(f):
if f == 'password':
if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'):
raise PermissionDenied('Old password is required')
if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')):
raise PermissionDenied('Password is incorrect')
u.set_password(values['password'])
else:
setattr(u, f, values[f])
u.save()
return get_user_dict(u)
| tkdchen/nitrate-xmlrpc | nitratexmlrpc/api/user.py | Python | gpl-2.0 | 5,535 |
<?php
// Copyright 2011 Toby Zerner, Simon Zerner
// This file is part of esoTalk. Please see the included license file for usage information.
if (!defined("IN_ESOTALK")) {
exit;
}
/**
* A model which provides functions to perform searches for conversations. Handles the implementation
* of gambits, and does search optimization.
*
* Searches are performed by the following steps:
* 1. Call getConversationIDs with a list of channel IDs to show results from and a search string.
* 2. The search string is parsed and split into terms. When a term is matched to a gambit, the
* gambit's callback function is called.
* 3. Callback functions add conversation ID filters to narrow the range of conversations being
* searched, or may alter other parts of the search query.
* 4. Using the applied ID filters, a final list of conversation IDs is retrieved and returned.
* 5. Call getResults with this list, and full details are retireved for each of the conversations.
*
* @package esoTalk
*/
class ETSearchModel extends ETModel {
/**
* An array of functional gambits. Each gambit is an array(callback, condition)
* @var array
* @see addGambit
*/
protected static $gambits = array();
/**
* An array of aliases. An alias is a string of text which is just shorthand for a more complex
* gambit. Each alias is an array(term, replacement term)
* @var array
* @see addAlias
*/
protected static $aliases = array();
/**
* Whether or not there are more results for the most recent search than what was returned.
* @var bool
*/
protected $areMoreResults = false;
/**
* The SQL query object used to construct a query that retrieves a list of matching conversation IDs.
* @var ETSQLQuery
*/
public $sql;
/**
* An array of converastion ID filters that should be run before querying the conversations table
* for a final list of conversation IDs.
* @var array
* @see addIDFilter
*/
protected $idFilters = array();
/**
* An array of fields to order the conversation IDs by.
* @var array
*/
protected $orderBy = array();
/**
* Whether or not the direction in the $orderBy fields should be reversed.
* @var bool
*/
public $orderReverse = false;
/**
* Whether or not the direction in the $orderBy fields should be reversed.
* @var bool
*/
public $limit = false;
/**
* Whether or not to include ignored conversations in the results.
* @var bool
*/
public $includeIgnored = false;
/**
* An array of fulltext keywords to filter the results by.
* @var array
*/
public $fulltext = array();
/**
* Class constructor. Sets up the inherited model functions to handle data in the search table
* (used for logging search activity -> flood control.)
*
* @return void
*/
public function __construct()
{
parent::__construct("search");
}
/**
* Add a gambit to the collection. When a search term is matched to a gambit, the specified
* callback function will be called. A match is determined by the return value of running
* $condition through eval().
*
* @param string $condition The condition to run through eval() to determine a match.
* $term represents the search term, in lowercase, in the eval() context. The condition
* should return a boolean value: true means a match, false means no match.
* Example: return $term == "sticky";
* @param array $function The function to call if the gambit is matched. Function will be called
* with parameters callback($sender, $term, $negate).
* @return void
*/
public static function addGambit($condition, $function)
{
self::$gambits[] = array($condition, $function);
}
/**
* Add an alias for another gambit to the collection. When a search term is matched
* to an alias, it will be interpreted as $realTerm.
*
* @param string $term The alias term.
* @param string $realTerm The replacement term.
* @return void
*/
public static function addAlias($term, $realTerm)
{
self::$aliases[$term] = $realTerm;
}
/**
* Add an SQL query to be run before the conversations table is queried for the final list of
* conversation IDs. The query should return a list of conversation IDs; the results then will be
* limited to conversations matching this list of IDs.
*
* See some of the default gambits for examples.
*
* @param ETSQLQuery $sql The SQL query that will return a list of matching conversation IDs.
* @param bool $negate If set to true, the returned conversation IDs will be blacklisted.
* @return void
*/
public function addIDFilter($sql, $negate = false)
{
$this->idFilters[] = array($sql, $negate);
}
/**
* Add a term to include in a fulltext search.
*
* @param string $term The term.
* @return void
*/
public function fulltext($term)
{
$this->fulltext[] = $term;
}
/**
* Apply an order to the search results. This function will ensure that a direction (ASC|DESC) is
* at the end.
*
* @param string $order The field to order the results by.
* @return void
*/
public function orderBy($order)
{
$direction = substr($order, strrpos($order, " ") + 1);
if ($direction != "ASC" and $direction != "DESC") {
$order .= " ASC";
}
$this->orderBy[] = $order;
}
/**
* Apply a custom limit to the number of search results returned.
*
* @param int $limit The limit.
* @return void
*/
public function limit($limit)
{
$this->limit = $limit;
}
/**
* Reset instance variables.
*
* @return void
*/
protected function reset()
{
$this->resultCount = 0;
$this->areMoreResults = false;
$this->sql = null;
$this->idFilters = array();
$this->orderBy = array();
$this->orderReverse = false;
$this->limit = false;
$this->includeIgnored = false;
$this->fulltext = array();
}
/**
* Determines whether or not the user is "flooding" the search system, based on the number of searches
* they have performed in the last minute.
*
* @return bool|int If the user is not flooding, returns false, but if they are, returned the number
* of seconds until they can perform another search.
*/
public function isFlooding()
{
if (C("esoTalk.search.searchesPerMinute") <= 0) {
return false;
}
$time = time();
$period = 60;
// If we have a record of their searches in the session, check how many searches they've performed in the last minute.
$searches = ET::$session->get("searches");
if (!empty($searches)) {
// Clean anything older than $period seconds out of the searches array.
foreach ($searches as $k => $v) {
if ($v < $time - $period) {
unset($searches[$k]);
}
}
// Have they performed >= [searchesPerMinute] searches in the last minute? If so, they are flooding.
if (count($searches) >= C("esoTalk.search.searchesPerMinute")) {
return $period - $time + min($searches);
}
}
// However, if we don't have a record in the session, query the database searches table.
else {
// Get the user's IP address.
$ip = (int) ip2long(ET::$session->ip);
// Have they performed >= $config["searchesPerMinute"] searches in the last minute?
$sql = ET::SQL()
->select("COUNT(ip)")
->from("search")
->where("type='conversations'")
->where("ip=:ip")->bind(":ip", $ip)
->where("time>:time")->bind(":time", $time - $period);
if ($sql->exec()->result() >= C("esoTalk.search.searchesPerMinute")) {
return $period;
}
// Log this search in the searches table.
ET::SQL()->insert("search")->set("type", "conversations")->set("ip", $ip)->set("time", $time)->exec();
// Proactively clean the searches table of searches older than $period seconds.
ET::SQL()->delete()->from("search")->where("type", "conversations")->where("time<:time")->bind(":time", $time - $period)->exec();
}
// Log this search in the session array.
$searches[] = $time;
ET::$session->store("searches", $searches);
return false;
}
/**
* Deconstruct a search string and return a list of conversation IDs that fulfill it.
*
* @param array $channelIDs A list of channel IDs to include results from.
* @param string $searchString The search string to deconstruct and find matching conversations.
* @param bool $orderBySticky Whether or not to put stickied conversations at the top.
* @return array|bool An array of matching conversation IDs, or false if there are none.
*/
public function getConversationIDs($channelIDs = array(), $searchString = "", $orderBySticky = false)
{
$this->reset();
$this->trigger("getConversationIDsBefore", array(&$channelIDs, &$searchString, &$orderBySticky));
if ($searchString and ($seconds = $this->isFlooding())) {
$this->error("search", sprintf(T("message.waitToSearch"), $seconds));
return false;
}
// Initialize the SQL query that will return the resulting conversation IDs.
$this->sql = ET::SQL()->select("c.conversationId")->from("conversation c");
// Only get conversations in the specified channels.
if ($channelIDs) {
$this->sql->where("c.channelId IN (:channelIds)")->bind(":channelIds", $channelIDs);
}
// Process the search string into individial terms. Replace all "-" signs with "+!", and then
// split the string by "+". Negated terms will then be prefixed with "!". Only keep the first
// 5 terms, just to keep the load on the database down!
$terms = !empty($searchString) ? explode("+", strtolower(str_replace("-", "+!", trim($searchString, " +-")))) : array();
$terms = array_slice(array_filter($terms), 0, 5);
// Take each term, match it with a gambit, and execute the gambit's function.
foreach ($terms as $term) {
// Are we dealing with a negated search term, ie. prefixed with a "!"?
$term = trim($term);
if ($negate = ($term[0] == "!")) {
$term = trim($term, "! ");
}
if ($term[0] == "#") {
$term = ltrim($term, "#");
// If the term is an alias, translate it into the appropriate gambit.
if (array_key_exists($term, self::$aliases)) {
$term = self::$aliases[$term];
}
// Find a matching gambit by evaluating each gambit's condition, and run its callback function.
foreach (self::$gambits as $gambit) {
list($condition, $function) = $gambit;
if (eval($condition)) {
call_user_func_array($function, array(&$this, $term, $negate));
continue 2;
}
}
}
// If we didn't find a gambit, use this term as a fulltext term.
if ($negate) {
$term = "-" . str_replace(" ", " -", $term);
}
$this->fulltext($term);
}
// If an order for the search results has not been specified, apply a default.
// Order by sticky and then last post time.
if (!count($this->orderBy)) {
if ($orderBySticky) {
$this->orderBy("c.sticky DESC");
}
$this->orderBy("c.lastPostTime DESC");
}
// If we're not including ignored conversations, add a where predicate to the query to exclude them.
if (!$this->includeIgnored and ET::$session->user) {
$q = ET::SQL()->select("conversationId")->from("member_conversation")->where("type='member'")->where("id=:memberIdIgnored")->where("ignored=1")->get();
$this->sql->where("conversationId NOT IN ($q)")->bind(":memberIdIgnored", ET::$session->userId);
}
// Now we need to loop through the ID filters and run them one-by-one. When a query returns a selection
// of conversation IDs, subsequent queries are restricted to filtering those conversation IDs,
// and so on, until we have a list of IDs to pass to the final query.
$goodConversationIDs = array();
$badConversationIDs = array();
$idCondition = "";
foreach ($this->idFilters as $v) {
list($sql, $negate) = $v;
// Apply the list of good IDs to the query.
$sql->where($idCondition);
// Get the list of conversation IDs so that the next condition can use it in its query.
$result = $sql->exec();
$ids = array();
while ($row = $result->nextRow()) {
$ids[] = (int) reset($row);
}
// If this condition is negated, then add the IDs to the list of bad conversations.
// If the condition is not negated, set the list of good conversations to the IDs, provided there are some.
if ($negate) {
$badConversationIDs = array_merge($badConversationIDs, $ids);
} elseif (count($ids)) {
$goodConversationIDs = $ids;
} else {
return false;
}
// Strip bad conversation IDs from the list of good conversation IDs.
if (count($goodConversationIDs)) {
$goodConversationIds = array_diff($goodConversationIDs, $badConversationIDs);
if (!count($goodConversationIDs)) {
return false;
}
}
// This will be the condition for the next query that restricts or eliminates conversation IDs.
if (count($goodConversationIDs)) {
$idCondition = "conversationId IN (" . implode(",", $goodConversationIDs) . ")";
} elseif (count($badConversationIDs)) {
$idCondition = "conversationId NOT IN (" . implode(",", $badConversationIDs) . ")";
}
}
// Reverse the order if necessary - swap DESC and ASC.
if ($this->orderReverse) {
foreach ($this->orderBy as $k => $v) {
$this->orderBy[$k] = strtr($this->orderBy[$k], array("DESC" => "ASC", "ASC" => "DESC"));
}
}
// Now check if there are any fulltext keywords to filter by.
if (count($this->fulltext)) {
// Run a query against the posts table to get matching conversation IDs.
$fulltextString = implode(" ", $this->fulltext);
$fulltextQuery = ET::SQL()
->select("DISTINCT conversationId")
->from("post")
->where("MATCH (title, content) AGAINST (:fulltext IN BOOLEAN MODE)")
->where($idCondition)
->orderBy("MATCH (title, content) AGAINST (:fulltextOrder) DESC")
->bind(":fulltext", $fulltextString)
->bind(":fulltextOrder", $fulltextString);
$this->trigger("fulltext", array($fulltextQuery, $this->fulltext));
$result = $fulltextQuery->exec();
$ids = array();
while ($row = $result->nextRow()) {
$ids[] = reset($row);
}
// Change the ID condition to this list of matching IDs, and order by relevance.
if (count($ids)) {
$idCondition = "conversationId IN (" . implode(",", $ids) . ")";
} else {
return false;
}
$this->orderBy = array("FIELD(c.conversationId," . implode(",", $ids) . ")");
}
// Set a default limit if none has previously been set.
if (!$this->limit) {
$this->limit = C("esoTalk.search.limit");
}
// Finish constructing the final query using the ID whitelist/blacklist we've come up with.
// Get one more result than we'll actually need so we can see if there are "more results."
if ($idCondition) {
$this->sql->where($idCondition);
}
$this->sql->orderBy($this->orderBy)->limit($this->limit + 1);
// Make sure conversations that the user isn't allowed to see are filtered out.
ET::conversationModel()->addAllowedPredicate($this->sql);
// Execute the query, and collect the final set of conversation IDs.
$result = $this->sql->exec();
$conversationIDs = array();
while ($row = $result->nextRow()) {
$conversationIDs[] = reset($row);
}
// If there's one more result than we actually need, indicate that there are "more results."
if (count($conversationIDs) == $this->limit + 1) {
array_pop($conversationIDs);
if ($this->limit < C("esoTalk.search.limitMax")) {
$this->areMoreResults = true;
}
}
return count($conversationIDs) ? $conversationIDs : false;
}
/**
* Get a full list of conversation details for a list of conversation IDs.
*
* @param array $conversationIDs The list of conversation IDs to fetch details for.
* @param bool $checkForPermission Whether or not to add a check onto the query to make sure the
* user has permission to view all of the conversations.
*/
public function getResults($conversationIDs, $checkForPermission = false)
{
// Construct a query to get details for all of the specified conversations.
$sql = ET::SQL()
->select("s.*") // Select the status fields first so that the conversation fields take precedence.
->select("c.*")
->select("sm.memberId", "startMemberId")
->select("sm.username", "startMember")
->select("sm.avatarFormat", "startMemberAvatarFormat")
->select("lpm.memberId", "lastPostMemberId")
->select("lpm.username", "lastPostMember")
->select("lpm.email", "lastPostMemberEmail")
->select("lpm.avatarFormat", "lastPostMemberAvatarFormat")
->select("IF((IF(c.lastPostTime IS NOT NULL,c.lastPostTime,c.startTime)>:markedAsRead AND (s.lastRead IS NULL OR s.lastRead<c.countPosts)),(c.countPosts - IF(s.lastRead IS NULL,0,s.lastRead)),0)", "unread")
->select("p.content", "firstPost")
->from("conversation c")
->from("member_conversation s", "s.conversationId=c.conversationId AND s.type='member' AND s.id=:memberId", "left")
->from("member sm", "c.startMemberId=sm.memberId", "left")
->from("member lpm", "c.lastPostMemberId=lpm.memberId", "left")
->from("channel ch", "c.channelId=ch.channelId", "left")
->from("post p", "c.sticky AND c.conversationId=p.conversationId AND c.startTime=p.time", "left")
->bind(":markedAsRead", ET::$session->preference("markedAllConversationsAsRead"))
->bind(":memberId", ET::$session->userId);
// If we need to, filter out all conversations that the user isn't allowed to see.
if ($checkForPermission) {
ET::conversationModel()->addAllowedPredicate($sql);
}
// Add a labels column to the query.
ET::conversationModel()->addLabels($sql);
// Limit the results to the specified conversation IDs
$sql->where("c.conversationId IN (:conversationIds)")->orderBy("FIELD(c.conversationId,:conversationIdsOrder)");
$sql->bind(":conversationIds", $conversationIDs, PDO::PARAM_INT);
$sql->bind(":conversationIdsOrder", $conversationIDs, PDO::PARAM_INT);
$this->trigger("beforeGetResults", array(&$sql));
// Execute the query and put the details of the conversations into an array.
$result = $sql->exec();
$results = array();
$model = ET::conversationModel();
while ($row = $result->nextRow()) {
// Expand the comma-separated label flags into a workable array of active labels.
$row["labels"] = $model->expandLabels($row["labels"]);
$row["replies"] = max(0, $row["countPosts"] - 1);
$results[] = $row;
}
$this->trigger("afterGetResults", array(&$results));
return $results;
}
/**
* Returns whether or not there are more results for the most recent search than were returned.
*
* @return bool
*/
public function areMoreResults()
{
return $this->areMoreResults;
}
/**
* Strip a gambit from a search string. This is useful when constructing the 'view more' link in
* the results, where we need to remove the existing #limit gambit and add a new one.
*
* @param string $searchString The search string.
* @param string $condition The condition to run through eval() to determine a match.
* $term represents the search term, in lowercase, in the eval() context. The condition
* should return a boolean value: true means a match, false means no match.
* Example: return $term == "sticky";
* @return string The new search string.
*/
public function removeGambit($searchString, $condition)
{
// Process the search string into individial terms. Replace all "-" signs with "+!", and then
// split the string by "+". Negated terms will then be prefixed with "!".
$terms = !empty($searchString) ? explode("+", strtolower(str_replace("-", "+!", trim($searchString, " +-")))) : array();
// Take each term, match it with a gambit, and execute the gambit's function.
foreach ($terms as $k => $term) {
$term = $terms[$k] = trim($term);
if ($term[0] == "#") {
$term = ltrim($term, "#");
// If the term is an alias, translate it into the appropriate gambit.
if (array_key_exists($term, self::$aliases)) {
$term = self::$aliases[$term];
}
// Find a matching gambit by evaluating each gambit's condition, and run its callback function.
if (eval($condition)) {
unset($terms[$k]);
continue;
}
}
}
return implode(" + ", $terms);
}
/**
* The "unread" gambit callback. Applies a filter to fetch only unread conversations.
*
* @param ETSearchModel $search The search model.
* @param string $term The gambit term (in this case, will simply be "unread").
* @param bool $negate Whether or not the gambit is negated.
* @return false|null
*
* @todo Make negation work on this gambit. Probably requires some kind of "OR" functionality, so that
* we can get conversations which:
* - are NOT in conversationIds with a lastRead status less than the number of posts in the conversation
* - OR which have a lastPostTime less than the markedAsRead time.
*/
public static function gambitUnread(&$search, $term, $negate)
{
if (!ET::$session->user) {
return false;
}
$q = ET::SQL()
->select("c2.conversationId")
->from("conversation c2")
->from("member_conversation s2", "c2.conversationId=s2.conversationId AND s2.type='member' AND s2.id=:gambitUnread_memberId", "left")
->where("s2.lastRead>=c2.countPosts")
->get();
$search->sql
->where("c.conversationId NOT IN ($q)")
->where("c.lastPostTime>=:gambitUnread_markedAsRead")
->bind(":gambitUnread_memberId", ET::$session->userId)
->bind(":gambitUnread_markedAsRead", ET::$session->preference("markedAllConversationsAsRead"));
}
/**
* The "starred" gambit callback. Applies a filter to fetch only starred conversations.
*
* @see gambitUnread for parameter descriptions.
*/
public static function gambitStarred(&$search, $term, $negate)
{
if (!ET::$session->user) {
return;
}
$sql = ET::SQL()
->select("DISTINCT conversationId")
->from("member_conversation")
->where("type='member'")
->where("id=:memberId")
->where("starred=1")
->bind(":memberId", ET::$session->userId);
$search->addIDFilter($sql, $negate);
}
/**
* The "private" gambit callback. Applies a filter to fetch only private conversations.
*
* @see gambitUnread for parameter descriptions.
*/
public static function gambitPrivate(&$search, $term, $negate)
{
$search->sql->where("c.private=" . ($negate ? "0" : "1"));
}
/**
* The "ignored" gambit callback. Applies a filter to fetch only ignored conversations.
*
* @see gambitUnread for parameter descriptions.
*/
public static function gambitIgnored(&$search, $term, $negate)
{
if (!ET::$session->user or $negate) {
return;
}
$search->includeIgnored = true;
$sql = ET::SQL()
->select("DISTINCT conversationId")
->from("member_conversation")
->where("type='member'")
->where("id=:memberId")
->where("ignored=1")
->bind(":memberId", ET::$session->userId);
$search->addIDFilter($sql);
}
/**
* The "draft" gambit callback. Applies a filter to fetch only conversations which the user has a
* draft in.
*
* @see gambitUnread for parameter descriptions.
*/
public static function gambitDraft(&$search, $term, $negate)
{
if (!ET::$session->user) {
return;
}
$sql = ET::SQL()
->select("DISTINCT conversationId")
->from("member_conversation")
->where("type='member'")
->where("id=:memberId")
->where("draft IS NOT NULL")
->bind(":memberId", ET::$session->userId);
$search->addIDFilter($sql, $negate);
}
/**
* The "active" gambit callback. Applies a filter to fetch only conversations which have been active
* in a certain period of time.
*
* @see gambitUnread for parameter descriptions.
*/
public function gambitActive(&$search, $term, $negate)
{
// Multiply the "amount" part (b) of the regular expression matches by the value of the "unit" part (c).
$search->matches["b"] = (int) $search->matches["b"];
switch ($search->matches["c"]) {
case T("gambit.minute"): $search->matches["b"] *= 60; break;
case T("gambit.hour"): $search->matches["b"] *= 3600; break;
case T("gambit.day"): $search->matches["b"] *= 86400; break;
case T("gambit.week"): $search->matches["b"] *= 604800; break;
case T("gambit.month"): $search->matches["b"] *= 2626560; break;
case T("gambit.year"): $search->matches["b"] *= 31536000;
}
// Set the "quantifier" part (a); default to <= (i.e. "last").
$search->matches["a"] = (!$search->matches["a"] or $search->matches["a"] == T("gambit.last")) ? "<=" : $search->matches["a"];
// If the gambit is negated, use the inverse of the selected quantifier.
if ($negate) {
switch ($search->matches["a"]) {
case "<": $search->matches["a"] = ">="; break;
case "<=": $search->matches["a"] = ">"; break;
case ">": $search->matches["a"] = "<="; break;
case ">=": $search->matches["a"] = "<";
}
}
// Apply the condition and force use of an index.
$search->sql->where("UNIX_TIMESTAMP() - {$search->matches["b"]} {$search->matches["a"]} c.lastPostTime");
$search->sql->useIndex("conversation_lastPostTime");
}
/**
* The "author" gambit callback. Applies a filter to fetch only conversations which were started by
* a particular member.
*
* @see gambitUnread for parameter descriptions.
* @todo Somehow make the use of this gambit trigger the switching of the "last post" column in the
* results table with a "started by" column.
*/
public static function gambitAuthor(&$search, $term, $negate)
{
// Get the ID of the member.
$term = trim(str_replace("\xc2\xa0", " ", substr($term, strlen(T("gambit.author:")))));
// Allow the user to refer to themselves using the "myself" keyword.
if ($term == T("gambit.myself")) {
$term = (int) ET::$session->userId;
}
// Apply the condition.
$search->sql
->where("c.startMemberId " . ($negate ? "!=" : "=") . " :authorId")
->bind(":authorId", (int) $term);
}
/**
* The "contributor" gambit callback. Applies a filter to fetch only conversations which contain posts
* by a particular member.
*
* @see gambitUnread for parameter descriptions.
*/
public static function gambitContributor(&$search, $term, $negate)
{
// Get the ID of the member.
$term = trim(str_replace("\xc2\xa0", " ", substr($term, strlen(T("gambit.contributor:")))));
// Allow the user to refer to themselves using the "myself" keyword.
if ($term == T("gambit.myself")) {
$term = (int) ET::$session->userId;
}
// Apply the condition.
$sql = ET::SQL()
->select("DISTINCT conversationId")
->from("post")
->where("memberId = :contributorId")
->bind(":contributorId", (int) $term);
$search->addIDFilter($sql, $negate);
}
/**
* The "limit" gambit callback. Specifies the number of results to display.
*
* @see gambitUnread for parameter descriptions.
*/
public static function gambitLimit(&$search, $term, $negate)
{
if ($negate) {
return;
}
// Get the number of results they want.
$limit = (int) trim(substr($term, strlen(T("gambit.limit:"))));
$limit = max(1, $limit);
if (($max = C("esoTalk.search.limitMax")) > 0) {
$limit = min($max, $limit);
}
$search->limit($limit);
}
/**
* The "replies" gambit callback. Applies a filter to fetch only conversations which have a certain
* amount of replies.
*
* @see gambitUnread for parameter descriptions.
*/
public static function gambitHasNReplies(&$search, $term, $negate)
{
// Work out which quantifier to use; default to "=".
$search->matches["a"] = (!$search->matches["a"]) ? "=" : $search->matches["a"];
// If the gambit is negated, use the inverse of the quantifier.
if ($negate) {
switch ($search->matches["a"]) {
case "<": $search->matches["a"] = ">="; break;
case "<=": $search->matches["a"] = ">"; break;
case ">": $search->matches["a"] = "<="; break;
case ">=": $search->matches["a"] = "<"; break;
case "=": $search->matches["a"] = "!=";
}
}
// Increase the amount by one as we are checking replies, but the column in the conversations
// table is a post count (it includes the original post.)
$search->matches["b"]++;
// Apply the condition.
$search->sql->where("countPosts {$search->matches["a"]} {$search->matches["b"]}");
}
/**
* The "order by replies" gambit callback. Orders the results by the number of replies they have.
*
* @see gambitUnread for parameter descriptions.
*/
public static function gambitOrderByReplies(&$search, $term, $negate)
{
$search->orderBy("c.countPosts " . ($negate ? "ASC" : "DESC"));
$search->sql->useIndex("conversation_countPosts");
}
/**
* The "order by newest" gambit callback. Orders the results by their start time.
*
* @see gambitUnread for parameter descriptions.
* @todo Somehow make the use of this gambit trigger the switching of the "last post" column in the
* results table with a "started by" column.
*/
public static function gambitOrderByNewest(&$search, $term, $negate)
{
$search->orderBy("c.startTime " . ($negate ? "ASC" : "DESC"));
$search->sql->useIndex("conversation_startTime");
}
/**
* The "sticky" gambit callback. Applies a filter to fetch only stickied conversations.
*
* @see gambitUnread for parameter descriptions.
*/
public static function gambitSticky(&$search, $term, $negate)
{
$search->sql->where("sticky=" . ($negate ? "0" : "1"));
}
/**
* The "random" gambit callback. Orders conversations randomly.
*
* @see gambitUnread for parameter descriptions.
* @todo Make this not horrendously slow on large forums. For now there is a config option to disable
* this gambit.
*/
public static function gambitRandom(&$search, $term, $negate)
{
if (!$negate) {
$search->orderBy("RAND()");
}
}
/**
* The "reverse" gambit callback. Reverses the order of conversations.
*
* @see gambitUnread for parameter descriptions.
*/
public static function gambitReverse(&$search, $term, $negate)
{
if (!$negate) {
$search->orderReverse = true;
}
}
/**
* The "locked" gambit callback. Applies a filter to fetch only locked conversations.
*
* @see gambitUnread for parameter descriptions.
*/
public static function gambitLocked(&$search, $term, $negate)
{
$search->sql->where("locked=" . ($negate ? "0" : "1"));
}
/**
* The "title" gambit callback. Applies a filter to fetch only conversation matching
* the specified title.
*
* @see gambitUnread for parameter descriptions.
*/
public static function gambitTitle(&$search, $term, $negate)
{
$term = trim(substr($term, strlen(T("gambit.title:"))));
$search->sql->where("title " . ($negate ? "NOT" : "") . " LIKE :titleTerm")
->bind(":titleTerm", "%" . $term . "%");
}
}
// Add default gambits.
ETSearchModel::addGambit('return $term == strtolower(T("gambit.starred"));', array("ETSearchModel", "gambitStarred"));
ETSearchModel::addGambit('return $term == strtolower(T("gambit.ignored"));', array("ETSearchModel", "gambitIgnored"));
ETSearchModel::addGambit('return $term == strtolower(T("gambit.draft"));', array("ETSearchModel", "gambitDraft"));
ETSearchModel::addGambit('return $term == strtolower(T("gambit.private"));', array("ETSearchModel", "gambitPrivate"));
ETSearchModel::addGambit('return $term == strtolower(T("gambit.sticky"));', array("ETSearchModel", "gambitSticky"));
ETSearchModel::addGambit('return $term == strtolower(T("gambit.locked"));', array("ETSearchModel", "gambitLocked"));
ETSearchModel::addGambit('return strpos($term, strtolower(T("gambit.author:"))) === 0;', array("ETSearchModel", "gambitAuthor"));
ETSearchModel::addGambit('return strpos($term, strtolower(T("gambit.contributor:"))) === 0;', array("ETSearchModel", "gambitContributor"));
ETSearchModel::addGambit('return preg_match(T("gambit.gambitActive"), $term, $this->matches);', array("ETSearchModel", "gambitActive"));
ETSearchModel::addGambit('return preg_match(T("gambit.gambitHasNReplies"), $term, $this->matches);', array("ETSearchModel", "gambitHasNReplies"));
ETSearchModel::addGambit('return $term == strtolower(T("gambit.order by replies"));', array("ETSearchModel", "gambitOrderByReplies"));
ETSearchModel::addGambit('return $term == strtolower(T("gambit.order by newest"));', array("ETSearchModel", "gambitOrderByNewest"));
ETSearchModel::addGambit('return $term == strtolower(T("gambit.unread"));', array("ETSearchModel", "gambitUnread"));
ETSearchModel::addGambit('return $term == strtolower(T("gambit.reverse"));', array("ETSearchModel", "gambitReverse"));
ETSearchModel::addGambit('return strpos($term, strtolower(T("gambit.limit:"))) === 0;', array("ETSearchModel", "gambitLimit"));
ETSearchModel::addGambit('return strpos($term, strtolower(T("gambit.title:"))) === 0;', array("ETSearchModel", "gambitTitle"));
if (!C("esoTalk.search.disableRandomGambit")) {
ETSearchModel::addGambit('return $term == strtolower(T("gambit.random"));', array("ETSearchModel", "gambitRandom"));
}
// Add default aliases.
ETSearchModel::addAlias(T("gambit.active today"), T("gambit.active 1 day"));
ETSearchModel::addAlias(T("gambit.has replies"), T("gambit.has >0 replies"));
ETSearchModel::addAlias(T("gambit.has no replies"), T("gambit.has 0 replies"));
ETSearchModel::addAlias(T("gambit.dead"), T("gambit.active >30 day"));
| Felli/fireside | core/models/ETSearchModel.class.php | PHP | gpl-2.0 | 34,554 |
using System;
namespace WaCore.Sample.Middlewares.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
} | HerbertBodner/webapp-core | src/WaCore.Sample.Middlewares/Models/ErrorViewModel.cs | C# | gpl-2.0 | 223 |
package org.iatoki.judgels.michael.controllers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.EnumUtils;
import org.iatoki.judgels.play.InternalLink;
import org.iatoki.judgels.play.LazyHtml;
import org.iatoki.judgels.play.controllers.AbstractJudgelsController;
import org.iatoki.judgels.play.views.html.layouts.headingLayout;
import org.iatoki.judgels.play.views.html.layouts.headingWithActionLayout;
import org.iatoki.judgels.play.views.html.layouts.tabLayout;
import org.iatoki.judgels.michael.Machine;
import org.iatoki.judgels.michael.MachineNotFoundException;
import org.iatoki.judgels.michael.services.MachineService;
import org.iatoki.judgels.michael.MachineWatcher;
import org.iatoki.judgels.michael.adapters.MachineWatcherConfAdapter;
import org.iatoki.judgels.michael.MachineWatcherNotFoundException;
import org.iatoki.judgels.michael.services.MachineWatcherService;
import org.iatoki.judgels.michael.MachineWatcherType;
import org.iatoki.judgels.michael.MachineWatcherUtils;
import org.iatoki.judgels.michael.controllers.securities.LoggedIn;
import org.iatoki.judgels.michael.views.html.machine.watcher.listMachineWatchersView;
import play.data.Form;
import play.db.jpa.Transactional;
import play.filters.csrf.AddCSRFToken;
import play.filters.csrf.RequireCSRFCheck;
import play.i18n.Messages;
import play.mvc.Result;
import play.mvc.Security;
import play.twirl.api.Html;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.util.List;
@Security.Authenticated(value = LoggedIn.class)
@Singleton
@Named
public final class MachineWatcherController extends AbstractJudgelsController {
private final MachineService machineService;
private final MachineWatcherService machineWatcherService;
@Inject
public MachineWatcherController(MachineService machineService, MachineWatcherService machineWatcherService) {
this.machineService = machineService;
this.machineWatcherService = machineWatcherService;
}
@Transactional(readOnly = true)
public Result viewMachineWatchers(long machineId) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
List<MachineWatcherType> enabledWatchers = machineWatcherService.findEnabledWatcherByMachineJid(machine.getJid());
List<MachineWatcherType> unenabledWatchers = Lists.newArrayList(MachineWatcherType.values());
unenabledWatchers.removeAll(enabledWatchers);
LazyHtml content = new LazyHtml(listMachineWatchersView.render(machine.getId(), enabledWatchers, unenabledWatchers));
content.appendLayout(c -> headingLayout.render(Messages.get("machine.watcher.list"), c));
appendTabLayout(content, machine);
ControllerUtils.getInstance().appendSidebarLayout(content);
ControllerUtils.getInstance().appendBreadcrumbsLayout(content, ImmutableList.of(
new InternalLink(Messages.get("machine.machines"), routes.MachineController.index()),
new InternalLink(Messages.get("machine.watcher.list"), routes.MachineWatcherController.viewMachineWatchers(machine.getId()))
));
ControllerUtils.getInstance().appendTemplateLayout(content, "Machine - Watchers");
return ControllerUtils.getInstance().lazyOk(content);
}
@Transactional(readOnly = true)
@AddCSRFToken
public Result activateMachineWatcher(long machineId, String watcherType) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (!machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
MachineWatcherConfAdapter adapter = MachineWatcherUtils.getMachineWatcherConfAdapter(machine, MachineWatcherType.valueOf(watcherType));
if (adapter != null) {
return showActivateMachineWatcher(machine, watcherType, adapter.getConfHtml(adapter.generateForm(), org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postActivateMachineWatcher(machine.getId(), watcherType), Messages.get("machine.watcher.activate")));
} else {
throw new UnsupportedOperationException();
}
} else {
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
}
@Transactional
@RequireCSRFCheck
public Result postActivateMachineWatcher(long machineId, String watcherType) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (!machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
MachineWatcherConfAdapter adapter = MachineWatcherUtils.getMachineWatcherConfAdapter(machine, MachineWatcherType.valueOf(watcherType));
if (adapter != null) {
Form form = adapter.bindFormFromRequest(request());
if (form.hasErrors() || form.hasGlobalErrors()) {
return showActivateMachineWatcher(machine, watcherType, adapter.getConfHtml(form, org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postActivateMachineWatcher(machine.getId(), watcherType), Messages.get("machine.watcher.activate")));
} else {
String conf = adapter.processRequestForm(form);
machineWatcherService.createWatcher(machine.getJid(), MachineWatcherType.valueOf(watcherType), conf);
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
} else {
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
}
@Transactional(readOnly = true)
@AddCSRFToken
public Result updateMachineWatcher(long machineId, String watcherType) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
MachineWatcherConfAdapter adapter = MachineWatcherUtils.getMachineWatcherConfAdapter(machine, MachineWatcherType.valueOf(watcherType));
if (adapter != null) {
MachineWatcher machineWatcher = machineWatcherService.findByMachineJidAndWatcherType(machine.getJid(), MachineWatcherType.valueOf(watcherType));
return showUpdateMachineWatcher(machine, watcherType, adapter.getConfHtml(adapter.generateForm(machineWatcher.getConf()), org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postUpdateMachineWatcher(machine.getId(), machineWatcher.getId(), watcherType), Messages.get("machine.watcher.update")));
} else {
throw new UnsupportedOperationException();
}
} else {
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
}
@Transactional
@RequireCSRFCheck
public Result postUpdateMachineWatcher(long machineId, long machineWatcherId, String watcherType) throws MachineNotFoundException, MachineWatcherNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
MachineWatcher machineWatcher = machineWatcherService.findByWatcherId(machineWatcherId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
MachineWatcherConfAdapter adapter = MachineWatcherUtils.getMachineWatcherConfAdapter(machine, MachineWatcherType.valueOf(watcherType));
if (adapter != null) {
Form form = adapter.bindFormFromRequest(request());
if (form.hasErrors() || form.hasGlobalErrors()) {
return showUpdateMachineWatcher(machine, watcherType, adapter.getConfHtml(form, org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postActivateMachineWatcher(machine.getId(), watcherType), Messages.get("machine.watcher.update")));
} else {
if (machine.getJid().equals(machineWatcher.getMachineJid())) {
String conf = adapter.processRequestForm(form);
machineWatcherService.updateWatcher(machineWatcher.getId(), machine.getJid(), MachineWatcherType.valueOf(watcherType), conf);
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
} else {
form.reject("error.notMachineWatcher");
return showUpdateMachineWatcher(machine, watcherType, adapter.getConfHtml(form, org.iatoki.judgels.michael.controllers.routes.MachineWatcherController.postActivateMachineWatcher(machine.getId(), watcherType), Messages.get("machine.watcher.update")));
}
}
} else {
throw new UnsupportedOperationException();
}
} else {
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
}
} else {
throw new UnsupportedOperationException();
}
}
@Transactional
public Result deactivateMachineWatcher(long machineId, String watcherType) throws MachineNotFoundException {
Machine machine = machineService.findByMachineId(machineId);
if (EnumUtils.isValidEnum(MachineWatcherType.class, watcherType)) {
if (machineWatcherService.isWatcherActivated(machine.getJid(), MachineWatcherType.valueOf(watcherType))) {
machineWatcherService.removeWatcher(machine.getJid(), MachineWatcherType.valueOf(watcherType));
}
return redirect(routes.MachineWatcherController.viewMachineWatchers(machine.getId()));
} else {
throw new UnsupportedOperationException();
}
}
private Result showActivateMachineWatcher(Machine machine, String watcherType, Html html) {
LazyHtml content = new LazyHtml(html);
content.appendLayout(c -> headingLayout.render(Messages.get("machine.watcher.activate"), c));
appendTabLayout(content, machine);
ControllerUtils.getInstance().appendSidebarLayout(content);
ControllerUtils.getInstance().appendBreadcrumbsLayout(content, ImmutableList.of(
new InternalLink(Messages.get("machine.machines"), routes.MachineController.index()),
new InternalLink(Messages.get("machine.watcher.list"), routes.MachineWatcherController.viewMachineWatchers(machine.getId())),
new InternalLink(Messages.get("machine.watcher.activate"), routes.MachineWatcherController.activateMachineWatcher(machine.getId(), watcherType))
));
ControllerUtils.getInstance().appendTemplateLayout(content, "Machine - Watchers");
return ControllerUtils.getInstance().lazyOk(content);
}
private Result showUpdateMachineWatcher(Machine machine, String watcherType, Html html) {
LazyHtml content = new LazyHtml(html);
content.appendLayout(c -> headingLayout.render(Messages.get("machine.watcher.update"), c));
appendTabLayout(content, machine);
ControllerUtils.getInstance().appendSidebarLayout(content);
ControllerUtils.getInstance().appendBreadcrumbsLayout(content, ImmutableList.of(
new InternalLink(Messages.get("machine.machines"), routes.MachineController.index()),
new InternalLink(Messages.get("machine.watcher.list"), routes.MachineWatcherController.viewMachineWatchers(machine.getId())),
new InternalLink(Messages.get("machine.watcher.update"), routes.MachineWatcherController.updateMachineWatcher(machine.getId(), watcherType))
));
ControllerUtils.getInstance().appendTemplateLayout(content, "Machine - Watchers");
return ControllerUtils.getInstance().lazyOk(content);
}
private void appendTabLayout(LazyHtml content, Machine machine) {
content.appendLayout(c -> tabLayout.render(ImmutableList.of(
new InternalLink(Messages.get("machine.update"), routes.MachineController.updateMachineGeneral(machine.getId())),
new InternalLink(Messages.get("machine.access"), routes.MachineAccessController.viewMachineAccesses(machine.getId())),
new InternalLink(Messages.get("machine.watcher"), routes.MachineWatcherController.viewMachineWatchers(machine.getId()))
), c));
content.appendLayout(c -> headingWithActionLayout.render(Messages.get("machine.machine") + " #" + machine.getId() + ": " + machine.getDisplayName(), new InternalLink(Messages.get("commons.enter"), routes.MachineController.viewMachine(machine.getId())), c));
}
}
| ia-toki/judgels-michael | app/org/iatoki/judgels/michael/controllers/MachineWatcherController.java | Java | gpl-2.0 | 13,764 |