repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
westernmagic/NumPDE | series2_warmup/2d-poissonlFEM/coordinate_transform.hpp | 390 | #pragma once
#include <Eigen/Core>
//! Makes a coordinate transform that maps
//!
//! e1 to a1
//! e2 to a2
//!
//! where {e1, e2} is the standard basis for R^2.
template <class Point>
Eigen::Matrix2d makeCoordinateTransform(const Point &a1, const Point &a2) {
Eigen::Matrix2d coordinateTransform;
coordinateTransform << a1(0), a2(0),
a1(1), a2(1);
return coordinateTransform;
}
| mit |
janurag/courtside | game/admin.py | 146 | from django.contrib import admin
from game.models import Game
class GameAdmin(admin.ModelAdmin):
pass
admin.site.register(Game, GameAdmin)
| mit |
codeforamerica/cityvoice | db/migrate/20130822004736_add_call_source_to_feedback_inputs.rb | 140 | class AddCallSourceToFeedbackInputs < ActiveRecord::Migration
def change
add_column :feedback_inputs, :call_source, :string
end
end
| mit |
keithbox/AngularJS-CRUD-PHP | vendor/phpoffice/phpword/src/PhpWord/Element/AbstractContainer.php | 11930 | <?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
* @copyright 2010-2018 PHPWord contributors
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
/**
* Container abstract class
*
* @method Text addText(string $text, mixed $fStyle = null, mixed $pStyle = null)
* @method TextRun addTextRun(mixed $pStyle = null)
* @method Bookmark addBookmark(string $name)
* @method Link addLink(string $target, string $text = null, mixed $fStyle = null, mixed $pStyle = null, boolean $internal = false)
* @method PreserveText addPreserveText(string $text, mixed $fStyle = null, mixed $pStyle = null)
* @method void addTextBreak(int $count = 1, mixed $fStyle = null, mixed $pStyle = null)
* @method ListItem addListItem(string $txt, int $depth = 0, mixed $font = null, mixed $list = null, mixed $para = null)
* @method ListItemRun addListItemRun(int $depth = 0, mixed $listStyle = null, mixed $pStyle = null)
* @method Footnote addFootnote(mixed $pStyle = null)
* @method Endnote addEndnote(mixed $pStyle = null)
* @method CheckBox addCheckBox(string $name, $text, mixed $fStyle = null, mixed $pStyle = null)
* @method Title addTitle(mixed $text, int $depth = 1)
* @method TOC addTOC(mixed $fontStyle = null, mixed $tocStyle = null, int $minDepth = 1, int $maxDepth = 9)
* @method PageBreak addPageBreak()
* @method Table addTable(mixed $style = null)
* @method Image addImage(string $source, mixed $style = null, bool $isWatermark = false, $name = null)
* @method OLEObject addOLEObject(string $source, mixed $style = null)
* @method TextBox addTextBox(mixed $style = null)
* @method Field addField(string $type = null, array $properties = array(), array $options = array(), mixed $text = null)
* @method Line addLine(mixed $lineStyle = null)
* @method Shape addShape(string $type, mixed $style = null)
* @method Chart addChart(string $type, array $categories, array $values, array $style = null, $seriesName = null)
* @method FormField addFormField(string $type, mixed $fStyle = null, mixed $pStyle = null)
* @method SDT addSDT(string $type)
*
* @method \PhpOffice\PhpWord\Element\OLEObject addObject(string $source, mixed $style = null) deprecated, use addOLEObject instead
*
* @since 0.10.0
*/
abstract class AbstractContainer extends AbstractElement
{
/**
* Elements collection
*
* @var \PhpOffice\PhpWord\Element\AbstractElement[]
*/
protected $elements = array();
/**
* Container type Section|Header|Footer|Footnote|Endnote|Cell|TextRun|TextBox|ListItemRun|TrackChange
*
* @var string
*/
protected $container;
/**
* Magic method to catch all 'addElement' variation
*
* This removes addText, addTextRun, etc. When adding new element, we have to
* add the model in the class docblock with `@method`.
*
* Warning: This makes capitalization matters, e.g. addCheckbox or addcheckbox won't work.
*
* @param mixed $function
* @param mixed $args
* @return \PhpOffice\PhpWord\Element\AbstractElement
*/
public function __call($function, $args)
{
$elements = array(
'Text', 'TextRun', 'Bookmark', 'Link', 'PreserveText', 'TextBreak',
'ListItem', 'ListItemRun', 'Table', 'Image', 'Object', 'OLEObject',
'Footnote', 'Endnote', 'CheckBox', 'TextBox', 'Field',
'Line', 'Shape', 'Title', 'TOC', 'PageBreak',
'Chart', 'FormField', 'SDT', 'Comment',
);
$functions = array();
foreach ($elements as $element) {
$functions['add' . strtolower($element)] = $element == 'Object' ? 'OLEObject' : $element;
}
// Run valid `add` command
$function = strtolower($function);
if (isset($functions[$function])) {
$element = $functions[$function];
// Special case for TextBreak
// @todo Remove the `$count` parameter in 1.0.0 to make this element similiar to other elements?
if ($element == 'TextBreak') {
list($count, $fontStyle, $paragraphStyle) = array_pad($args, 3, null);
if ($count === null) {
$count = 1;
}
for ($i = 1; $i <= $count; $i++) {
$this->addElement($element, $fontStyle, $paragraphStyle);
}
} else {
// All other elements
array_unshift($args, $element); // Prepend element name to the beginning of args array
return call_user_func_array(array($this, 'addElement'), $args);
}
}
return null;
}
/**
* Add element
*
* Each element has different number of parameters passed
*
* @param string $elementName
* @return \PhpOffice\PhpWord\Element\AbstractElement
*/
protected function addElement($elementName)
{
$elementClass = __NAMESPACE__ . '\\' . $elementName;
$this->checkValidity($elementName);
// Get arguments
$args = func_get_args();
$withoutP = in_array($this->container, array('TextRun', 'Footnote', 'Endnote', 'ListItemRun', 'Field'));
if ($withoutP && ($elementName == 'Text' || $elementName == 'PreserveText')) {
$args[3] = null; // Remove paragraph style for texts in textrun
}
// Create element using reflection
$reflection = new \ReflectionClass($elementClass);
$elementArgs = $args;
array_shift($elementArgs); // Shift the $elementName off the beginning of array
/** @var \PhpOffice\PhpWord\Element\AbstractElement $element Type hint */
$element = $reflection->newInstanceArgs($elementArgs);
// Set parent container
$element->setParentContainer($this);
$element->setElementIndex($this->countElements() + 1);
$element->setElementId();
$this->elements[] = $element;
return $element;
}
/**
* Get all elements
*
* @return \PhpOffice\PhpWord\Element\AbstractElement[]
*/
public function getElements()
{
return $this->elements;
}
/**
* Returns the element at the requested position
*
* @param int $index
* @return \PhpOffice\PhpWord\Element\AbstractElement|null
*/
public function getElement($index)
{
if (array_key_exists($index, $this->elements)) {
return $this->elements[$index];
}
return null;
}
/**
* Removes the element at requested index
*
* @param int|\PhpOffice\PhpWord\Element\AbstractElement $toRemove
*/
public function removeElement($toRemove)
{
if (is_int($toRemove) && array_key_exists($toRemove, $this->elements)) {
unset($this->elements[$toRemove]);
} elseif ($toRemove instanceof \PhpOffice\PhpWord\Element\AbstractElement) {
foreach ($this->elements as $key => $element) {
if ($element->getElementId() === $toRemove->getElementId()) {
unset($this->elements[$key]);
return;
}
}
}
}
/**
* Count elements
*
* @return int
*/
public function countElements()
{
return count($this->elements);
}
/**
* Check if a method is allowed for the current container
*
* @param string $method
*
* @throws \BadMethodCallException
* @return bool
*/
private function checkValidity($method)
{
$generalContainers = array(
'Section', 'Header', 'Footer', 'Footnote', 'Endnote', 'Cell', 'TextRun', 'TextBox', 'ListItemRun', 'TrackChange',
);
$validContainers = array(
'Text' => $generalContainers,
'Bookmark' => $generalContainers,
'Link' => $generalContainers,
'TextBreak' => $generalContainers,
'Image' => $generalContainers,
'OLEObject' => $generalContainers,
'Field' => $generalContainers,
'Line' => $generalContainers,
'Shape' => $generalContainers,
'FormField' => $generalContainers,
'SDT' => $generalContainers,
'TrackChange' => $generalContainers,
'TextRun' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox', 'TrackChange', 'ListItemRun'),
'ListItem' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'),
'ListItemRun' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'),
'Table' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'),
'CheckBox' => array('Section', 'Header', 'Footer', 'Cell', 'TextRun'),
'TextBox' => array('Section', 'Header', 'Footer', 'Cell'),
'Footnote' => array('Section', 'TextRun', 'Cell', 'ListItemRun'),
'Endnote' => array('Section', 'TextRun', 'Cell'),
'PreserveText' => array('Section', 'Header', 'Footer', 'Cell'),
'Title' => array('Section', 'Cell'),
'TOC' => array('Section'),
'PageBreak' => array('Section'),
'Chart' => array('Section', 'Cell'),
);
// Special condition, e.g. preservetext can only exists in cell when
// the cell is located in header or footer
$validSubcontainers = array(
'PreserveText' => array(array('Cell'), array('Header', 'Footer', 'Section')),
'Footnote' => array(array('Cell', 'TextRun'), array('Section')),
'Endnote' => array(array('Cell', 'TextRun'), array('Section')),
);
// Check if a method is valid for current container
if (isset($validContainers[$method])) {
if (!in_array($this->container, $validContainers[$method])) {
throw new \BadMethodCallException("Cannot add {$method} in {$this->container}.");
}
}
// Check if a method is valid for current container, located in other container
if (isset($validSubcontainers[$method])) {
$rules = $validSubcontainers[$method];
$containers = $rules[0];
$allowedDocParts = $rules[1];
foreach ($containers as $container) {
if ($this->container == $container && !in_array($this->getDocPart(), $allowedDocParts)) {
throw new \BadMethodCallException("Cannot add {$method} in {$this->container}.");
}
}
}
return true;
}
/**
* Create textrun element
*
* @deprecated 0.10.0
*
* @param mixed $paragraphStyle
*
* @return \PhpOffice\PhpWord\Element\TextRun
*
* @codeCoverageIgnore
*/
public function createTextRun($paragraphStyle = null)
{
return $this->addTextRun($paragraphStyle);
}
/**
* Create footnote element
*
* @deprecated 0.10.0
*
* @param mixed $paragraphStyle
*
* @return \PhpOffice\PhpWord\Element\Footnote
*
* @codeCoverageIgnore
*/
public function createFootnote($paragraphStyle = null)
{
return $this->addFootnote($paragraphStyle);
}
}
| mit |
lboynton/phph-site | test/AppTest/Service/Talk/Exception/TalkNotFoundTest.php | 625 | <?php
declare(strict_types = 1);
namespace AppTest\Service\Talk\Exception;
use App\Service\Talk\Exception\TalkNotFound;
use Ramsey\Uuid\Uuid;
/**
* @covers \App\Service\Talk\Exception\TalkNotFound
*/
class TalkNotFoundTest extends \PHPUnit_Framework_TestCase
{
public function testFromUuid()
{
$uuid = Uuid::fromString('204a5eee-a406-475d-95c2-9cb28f2b086d');
$exception = TalkNotFound::fromUuid($uuid);
self::assertInstanceOf(TalkNotFound::class, $exception);
self::assertSame('Talk with uuid 204a5eee-a406-475d-95c2-9cb28f2b086d not found', $exception->getMessage());
}
}
| mit |
babel/babel | packages/babel-parser/test/fixtures/experimental/pipeline-operator/hack-caret-proposal-yield-identifier-unparenthesized/input.js | 16 | x |> yield + ^;
| mit |
leighhalliday/delayed_paperclip | lib/delayed_paperclip.rb | 3769 | require 'delayed_paperclip/jobs'
require 'delayed_paperclip/attachment'
require 'delayed_paperclip/url_generator'
require 'delayed_paperclip/railtie'
module DelayedPaperclip
class << self
def options
@options ||= {
:background_job_class => detect_background_task,
:url_with_processing => true,
:processing_image_url => nil
}
end
def detect_background_task
return DelayedPaperclip::Jobs::ActiveJob if defined? ::ActiveJob::Base
return DelayedPaperclip::Jobs::DelayedJob if defined? ::Delayed::Job
return DelayedPaperclip::Jobs::Resque if defined? ::Resque
return DelayedPaperclip::Jobs::Sidekiq if defined? ::Sidekiq
end
def processor
options[:background_job_class]
end
def enqueue(instance_klass, instance_id, attachment_name)
processor.enqueue_delayed_paperclip(instance_klass, instance_id, attachment_name)
end
def process_job(instance_klass, instance_id, attachment_name)
instance_klass.constantize.unscoped.find(instance_id).
send(attachment_name).
process_delayed!
end
end
module Glue
def self.included(base)
base.extend(ClassMethods)
base.send :include, InstanceMethods
end
end
module ClassMethods
def process_in_background(name, options = {})
# initialize as hash
paperclip_definitions[name][:delayed] = {}
# Set Defaults
only_process_default = paperclip_definitions[name][:only_process]
only_process_default ||= []
{
:priority => 0,
:only_process => only_process_default,
:url_with_processing => DelayedPaperclip.options[:url_with_processing],
:processing_image_url => DelayedPaperclip.options[:processing_image_url],
:queue => nil
}.each do |option, default|
paperclip_definitions[name][:delayed][option] = options.key?(option) ? options[option] : default
end
# Sets callback
if respond_to?(:after_commit)
after_commit :enqueue_delayed_processing
else
after_save :enqueue_delayed_processing
end
end
def paperclip_definitions
@paperclip_definitions ||= if respond_to? :attachment_definitions
attachment_definitions
else
Paperclip::Tasks::Attachments.definitions_for(self)
end
end
end
module InstanceMethods
# First mark processing
# then enqueue
def enqueue_delayed_processing
mark_enqueue_delayed_processing
(@_enqued_for_processing || []).each do |name|
enqueue_post_processing_for(name)
end
@_enqued_for_processing_with_processing = []
@_enqued_for_processing = []
end
# setting each inididual NAME_processing to true, skipping the ActiveModel dirty setter
# Then immediately push the state to the database
def mark_enqueue_delayed_processing
unless @_enqued_for_processing_with_processing.blank? # catches nil and empty arrays
updates = @_enqued_for_processing_with_processing.collect{|n| "#{n}_processing = :true" }.join(", ")
updates = ActiveRecord::Base.send(:sanitize_sql_array, [updates, {:true => true}])
self.class.where(:id => self.id).update_all(updates)
end
end
def enqueue_post_processing_for name
DelayedPaperclip.enqueue(self.class.name, read_attribute(:id), name.to_sym)
end
def prepare_enqueueing_for name
if self.attributes.has_key? "#{name}_processing"
write_attribute("#{name}_processing", true)
@_enqued_for_processing_with_processing ||= []
@_enqued_for_processing_with_processing << name
end
@_enqued_for_processing ||= []
@_enqued_for_processing << name
end
end
end
| mit |
youdz/angular | modules/@angular/core/test/reflection/reflector_common.ts | 1013 | import {makeDecorator, makeParamDecorator, makePropDecorator} from '@angular/core/src/util/decorators';
export class ClassDecoratorMeta {
constructor(public value: any /** TODO #9100 */) {}
}
export class ParamDecoratorMeta {
constructor(public value: any /** TODO #9100 */) {}
}
export class PropDecoratorMeta {
constructor(public value: any /** TODO #9100 */) {}
}
export function classDecorator(value: any /** TODO #9100 */) {
return new ClassDecoratorMeta(value);
}
export function paramDecorator(value: any /** TODO #9100 */) {
return new ParamDecoratorMeta(value);
}
export function propDecorator(value: any /** TODO #9100 */) {
return new PropDecoratorMeta(value);
}
/** @Annotation */ export var ClassDecorator = makeDecorator(ClassDecoratorMeta);
/** @Annotation */ export var ParamDecorator = makeParamDecorator(ParamDecoratorMeta);
/** @Annotation */ export var PropDecorator = makePropDecorator(PropDecoratorMeta);
// used only in Dart
export class HasGetterAndSetterDecorators {}
| mit |
tungus28/phprealtimechat | bin/src/Connection/ChatConnection.php | 2512 | <?php
namespace Chat\Connection;
use Chat\Repository\ChatRepositoryInterface;
use Ratchet\ConnectionInterface;
class ChatConnection implements ChatConnectionInterface
{
/**
* The ConnectionInterface instance
*
* @var ConnectionInterface
*/
private $connection;
/**
* The username of this connection
*
* @var string
*/
private $name;
/**
* The ChatRepositoryInterface instance
*
* @var ChatRepositoryInterface
*/
private $repository;
/**
* ChatConnection Constructor
*
* @param ConnectionInterface $conn
* @param ChatRepositoryInterface $repository
* @param string $name
*/
public function __construct(ConnectionInterface $conn, ChatRepositoryInterface $repository, $name = "")
{
$this->connection = $conn;
$this->name = $name;
$this->repository = $repository;
}
/**
* Sends a message through the socket
*
* @param string $sender
* @param string $msg
* @return void
*/
public function sendMsg($sender, $msg)
{
$this->send([
'action' => 'message',
'username' => $sender,
'msg' => $msg
]);
}
/**
* Get the connection instance
*
* @return ConnectionInterface
*/
public function getConnection()
{
return $this->connection;
}
/**
* Set the name for this connection
*
* @param string $name
* @return void
*/
public function setName($name)
{
if ($name === "")
return;
// Check if the name exists already
if ($this->repository->getClientByName($name) !== null)
{
$this->send([
'action' => 'setname',
'success' => false,
'username' => $this->name
]);
return;
}
$this->name = $name;
$this->send([
'action' => 'setname',
'success' => true,
'username' => $this->name
]);
}
/**
* Get the username of the connection
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Send data through the socket
*
* @param array $data
* @return void
*/
private function send(array $data)
{
$this->connection->send(json_encode($data));
}
}
| mit |
sufuf3/cdnjs | ajax/libs/froala-editor/3.0.0-rc.1/js/languages/en_ca.js | 7327 | /*!
* froala_editor v3.0.0-rc.1 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms/
* Copyright 2014-2019 Froala Labs
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) :
typeof define === 'function' && define.amd ? define(['froala-editor'], factory) :
(factory(global.FroalaEditor));
}(this, (function (FE) { 'use strict';
FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE;
/**
* English spoken in Canada
*/
FE.LANGUAGE['en_ca'] = {
translation: {
// Place holder
'Type something': 'Type something',
// Basic formatting
'Bold': 'Bold',
'Italic': 'Italic',
'Underline': 'Underline',
'Strikethrough': 'Strikethrough',
// Main buttons
'Insert': 'Insert',
'Delete': 'Delete',
'Cancel': 'Cancel',
'OK': 'OK',
'Back': 'Back',
'Remove': 'Remove',
'More': 'More',
'Update': 'Update',
'Style': 'Style',
// Font
'Font Family': 'Font Family',
'Font Size': 'Font Size',
// Colors
'Colors': 'Colours',
'Background': 'Background',
'Text': 'Text',
'HEX Color': 'HEX Colour',
// Paragraphs
'Paragraph Format': 'Paragraph Format',
'Normal': 'Normal',
'Code': 'Code',
'Heading 1': 'Heading 1',
'Heading 2': 'Heading 2',
'Heading 3': 'Heading 3',
'Heading 4': 'Heading 4',
// Style
'Paragraph Style': 'Paragraph Style',
'Inline Style': 'Inline Style',
// Alignment
'Align': 'Align',
'Align Left': 'Align Left',
'Align Center': 'Align Centre',
'Align Right': 'Align Right',
'Align Justify': 'Align Justify',
'None': 'None',
// Lists
'Ordered List': 'Ordered List',
'Unordered List': 'Unordered List',
// Indent
'Decrease Indent': 'Decrease Indent',
'Increase Indent': 'Increase Indent',
// Links
'Insert Link': 'Insert Link',
'Open in new tab': 'Open in new tab',
'Open Link': 'Open Link',
'Edit Link': 'Edit Link',
'Unlink': 'Unlink',
'Choose Link': 'Choose Link',
// Images
'Insert Image': 'Insert Image',
'Upload Image': 'Upload Image',
'By URL': 'By URL',
'Browse': 'Browse',
'Drop image': 'Drop image',
'or click': 'or click',
'Manage Images': 'Manage Images',
'Loading': 'Loading',
'Deleting': 'Deleting',
'Tags': 'Tags',
'Are you sure? Image will be deleted.': 'Are you sure? Image will be deleted.',
'Replace': 'Replace',
'Uploading': 'Uploading',
'Loading image': 'Loading image',
'Display': 'Display',
'Inline': 'Inline',
'Break Text': 'Break Text',
'Alternative Text': 'Alternative Text',
'Change Size': 'Change Size',
'Width': 'Width',
'Height': 'Height',
'Something went wrong. Please try again.': 'Something went wrong. Please try again.',
'Image Caption': 'Image Caption',
'Advanced Edit': 'Advanced Edit',
// Video
'Insert Video': 'Insert Video',
'Embedded Code': 'Embedded Code',
'Paste in a video URL': 'Paste in a video URL',
'Drop video': 'Drop video',
'Your browser does not support HTML5 video.': 'Your browser does not support HTML5 video.',
'Upload Video': 'Upload Video',
// Tables
'Insert Table': 'Insert Table',
'Table Header': 'Table Header',
'Remove Table': 'Remove Table',
'Table Style': 'Table Style',
'Horizontal Align': 'Horizontal Align',
'Row': 'Row',
'Insert row above': 'Insert row above',
'Insert row below': 'Insert row below',
'Delete row': 'Delete row',
'Column': 'Column',
'Insert column before': 'Insert column before',
'Insert column after': 'Insert column after',
'Delete column': 'Delete column',
'Cell': 'Cell',
'Merge cells': 'Merge cells',
'Horizontal split': 'Horizontal split',
'Vertical split': 'Vertical split',
'Cell Background': 'Cell Background',
'Vertical Align': 'Vertical Align',
'Top': 'Top',
'Middle': 'Middle',
'Bottom': 'Bottom',
'Align Top': 'Align Top',
'Align Middle': 'Align Middle',
'Align Bottom': 'Align Bottom',
'Cell Style': 'Cell Style',
// Files
'Upload File': 'Upload File',
'Drop file': 'Drop file',
// Emoticons
'Emoticons': 'Emoticons',
// Line breaker
'Break': 'Break',
// Math
'Subscript': 'Subscript',
'Superscript': 'Superscript',
// Full screen
'Fullscreen': 'Fullscreen',
// Horizontal line
'Insert Horizontal Line': 'Insert Horizontal Line',
// Clear formatting
'Clear Formatting': 'Clear Formatting',
// Save
'Save': 'Save',
// Undo, redo
'Undo': 'Undo',
'Redo': 'Redo',
// Select all
'Select All': 'Select All',
// Code view
'Code View': 'Code View',
// Quote
'Quote': 'Quote',
'Increase': 'Increase',
'Decrease': 'Decrease',
// Quick Insert
'Quick Insert': 'Quick Insert',
// Spcial Characters
'Special Characters': 'Special Characters',
'Latin': 'Latin',
'Greek': 'Greek',
'Cyrillic': 'Cyrillic',
'Punctuation': 'Punctuation',
'Currency': 'Currency',
'Arrows': 'Arrows',
'Math': 'Math',
'Misc': 'Misc',
// Print.
'Print': 'Print',
// Spell Checker.
'Spell Checker': 'Spell Checker',
// Help
'Help': 'Help',
'Shortcuts': 'Shortcuts',
'Inline Editor': 'Inline Editor',
'Show the editor': 'Show the editor',
'Common actions': 'Common actions',
'Copy': 'Copy',
'Cut': 'Cut',
'Paste': 'Paste',
'Basic Formatting': 'Basic Formatting',
'Increase quote level': 'Increase quote level',
'Decrease quote level': 'Decrease quote level',
'Image / Video': 'Image / Video',
'Resize larger': 'Resize larger',
'Resize smaller': 'Resize smaller',
'Table': 'Table',
'Select table cell': 'Select table cell',
'Extend selection one cell': 'Extend selection one cell',
'Extend selection one row': 'Extend selection one row',
'Navigation': 'Navigation',
'Focus popup / toolbar': 'Focus popup / toolbar',
'Return focus to previous position': 'Return focus to previous position',
// Embed.ly
'Embed URL': 'Embed URL',
'Paste in a URL to embed': 'Paste in a URL to embed',
// Word Paste.
'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': 'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?',
'Keep': 'Keep',
'Clean': 'Clean',
'Word Paste Detected': 'Word Paste Detected',
// Character Counter
'Characters': 'Characters',
// More Buttons
'More Text': 'More Text',
'More Paragraph': 'More Paragraph',
'More Rich': 'More Rich',
'More Misc': 'More Misc'
},
direction: 'ltr'
};
})));
//# sourceMappingURL=en_ca.js.map
| mit |
react-medellin/components | flow-typed/npm/babel-preset-flow_vx.x.x.js | 888 | // flow-typed signature: ecc5c7711455066a3b2cda7e62a4361a
// flow-typed version: <<STUB>>/babel-preset-flow_v^6.23.0/flow_v0.47.0
/**
* This is an autogenerated libdef stub for:
*
* 'babel-preset-flow'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'babel-preset-flow' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'babel-preset-flow/lib/index' {
declare module.exports: any;
}
// Filename aliases
declare module 'babel-preset-flow/lib/index.js' {
declare module.exports: $Exports<'babel-preset-flow/lib/index'>;
}
| mit |
cfoxleyevans/RainfallAnalyzer | jfreechart-1.0.14/source/org/jfree/chart/plot/CombinedDomainCategoryPlot.java | 24743 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -------------------------------
* CombinedDomainCategoryPlot.java
* -------------------------------
* (C) Copyright 2003-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Nicolas Brodu;
*
* Changes:
* --------
* 16-May-2003 : Version 1 (DG);
* 08-Aug-2003 : Adjusted totalWeight in remove() method (DG);
* 19-Aug-2003 : Added equals() method, implemented Cloneable and
* Serializable (DG);
* 11-Sep-2003 : Fix cloning support (subplots) (NB);
* 15-Sep-2003 : Implemented PublicCloneable (DG);
* 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);
* 17-Sep-2003 : Updated handling of 'clicks' (DG);
* 04-May-2004 : Added getter/setter methods for 'gap' attribute (DG);
* 12-Nov-2004 : Implemented the Zoomable interface (DG);
* 25-Nov-2004 : Small update to clone() implementation (DG);
* 21-Feb-2005 : The getLegendItems() method now returns the fixed legend
* items if set (DG);
* 05-May-2005 : Updated draw() method parameters (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 13-Sep-2006 : Updated API docs (DG);
* 30-Oct-2006 : Added new getCategoriesForAxis() override (DG);
* 17-Apr-2007 : Added null argument checks to findSubplot() (DG);
* 14-Nov-2007 : Updated setFixedRangeAxisSpaceForSubplots() method (DG);
* 27-Mar-2008 : Add documentation for getDataRange() method (DG);
* 31-Mar-2008 : Updated getSubplots() to return EMPTY_LIST for null
* subplots, as suggested by Richard West (DG);
* 28-Apr-2008 : Fixed zooming problem (see bug 1950037) (DG);
* 26-Jun-2008 : Fixed crosshair support (DG);
* 11-Aug-2008 : Don't store totalWeight of subplots, calculate it as
* required (DG);
*
*/
package org.jfree.chart.plot;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.jfree.chart.LegendItemCollection;
import org.jfree.chart.axis.AxisSpace;
import org.jfree.chart.axis.AxisState;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.event.PlotChangeEvent;
import org.jfree.chart.event.PlotChangeListener;
import org.jfree.data.Range;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RectangleInsets;
import org.jfree.util.ObjectUtilities;
/**
* A combined category plot where the domain axis is shared.
*/
public class CombinedDomainCategoryPlot extends CategoryPlot
implements PlotChangeListener {
/** For serialization. */
private static final long serialVersionUID = 8207194522653701572L;
/** Storage for the subplot references. */
private List subplots;
/** The gap between subplots. */
private double gap;
/** Temporary storage for the subplot areas. */
private transient Rectangle2D[] subplotAreas;
// TODO: move the above to the plot state
/**
* Default constructor.
*/
public CombinedDomainCategoryPlot() {
this(new CategoryAxis());
}
/**
* Creates a new plot.
*
* @param domainAxis the shared domain axis (<code>null</code> not
* permitted).
*/
public CombinedDomainCategoryPlot(CategoryAxis domainAxis) {
super(null, domainAxis, null, null);
this.subplots = new java.util.ArrayList();
this.gap = 5.0;
}
/**
* Returns the space between subplots.
*
* @return The gap (in Java2D units).
*/
public double getGap() {
return this.gap;
}
/**
* Sets the amount of space between subplots and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param gap the gap between subplots (in Java2D units).
*/
public void setGap(double gap) {
this.gap = gap;
fireChangeEvent();
}
/**
* Adds a subplot to the combined chart and sends a {@link PlotChangeEvent}
* to all registered listeners.
* <br><br>
* The domain axis for the subplot will be set to <code>null</code>. You
* must ensure that the subplot has a non-null range axis.
*
* @param subplot the subplot (<code>null</code> not permitted).
*/
public void add(CategoryPlot subplot) {
add(subplot, 1);
}
/**
* Adds a subplot to the combined chart and sends a {@link PlotChangeEvent}
* to all registered listeners.
* <br><br>
* The domain axis for the subplot will be set to <code>null</code>. You
* must ensure that the subplot has a non-null range axis.
*
* @param subplot the subplot (<code>null</code> not permitted).
* @param weight the weight (must be >= 1).
*/
public void add(CategoryPlot subplot, int weight) {
if (subplot == null) {
throw new IllegalArgumentException("Null 'subplot' argument.");
}
if (weight < 1) {
throw new IllegalArgumentException("Require weight >= 1.");
}
subplot.setParent(this);
subplot.setWeight(weight);
subplot.setInsets(new RectangleInsets(0.0, 0.0, 0.0, 0.0));
subplot.setDomainAxis(null);
subplot.setOrientation(getOrientation());
subplot.addChangeListener(this);
this.subplots.add(subplot);
CategoryAxis axis = getDomainAxis();
if (axis != null) {
axis.configure();
}
fireChangeEvent();
}
/**
* Removes a subplot from the combined chart. Potentially, this removes
* some unique categories from the overall union of the datasets...so the
* domain axis is reconfigured, then a {@link PlotChangeEvent} is sent to
* all registered listeners.
*
* @param subplot the subplot (<code>null</code> not permitted).
*/
public void remove(CategoryPlot subplot) {
if (subplot == null) {
throw new IllegalArgumentException("Null 'subplot' argument.");
}
int position = -1;
int size = this.subplots.size();
int i = 0;
while (position == -1 && i < size) {
if (this.subplots.get(i) == subplot) {
position = i;
}
i++;
}
if (position != -1) {
this.subplots.remove(position);
subplot.setParent(null);
subplot.removeChangeListener(this);
CategoryAxis domain = getDomainAxis();
if (domain != null) {
domain.configure();
}
fireChangeEvent();
}
}
/**
* Returns the list of subplots. The returned list may be empty, but is
* never <code>null</code>.
*
* @return An unmodifiable list of subplots.
*/
public List getSubplots() {
if (this.subplots != null) {
return Collections.unmodifiableList(this.subplots);
}
else {
return Collections.EMPTY_LIST;
}
}
/**
* Returns the subplot (if any) that contains the (x, y) point (specified
* in Java2D space).
*
* @param info the chart rendering info (<code>null</code> not permitted).
* @param source the source point (<code>null</code> not permitted).
*
* @return A subplot (possibly <code>null</code>).
*/
public CategoryPlot findSubplot(PlotRenderingInfo info, Point2D source) {
if (info == null) {
throw new IllegalArgumentException("Null 'info' argument.");
}
if (source == null) {
throw new IllegalArgumentException("Null 'source' argument.");
}
CategoryPlot result = null;
int subplotIndex = info.getSubplotIndex(source);
if (subplotIndex >= 0) {
result = (CategoryPlot) this.subplots.get(subplotIndex);
}
return result;
}
/**
* Multiplies the range on the range axis/axes by the specified factor.
*
* @param factor the zoom factor.
* @param info the plot rendering info (<code>null</code> not permitted).
* @param source the source point (<code>null</code> not permitted).
*/
public void zoomRangeAxes(double factor, PlotRenderingInfo info,
Point2D source) {
zoomRangeAxes(factor, info, source, false);
}
/**
* Multiplies the range on the range axis/axes by the specified factor.
*
* @param factor the zoom factor.
* @param info the plot rendering info (<code>null</code> not permitted).
* @param source the source point (<code>null</code> not permitted).
* @param useAnchor zoom about the anchor point?
*/
public void zoomRangeAxes(double factor, PlotRenderingInfo info,
Point2D source, boolean useAnchor) {
// delegate 'info' and 'source' argument checks...
CategoryPlot subplot = findSubplot(info, source);
if (subplot != null) {
subplot.zoomRangeAxes(factor, info, source, useAnchor);
}
else {
// if the source point doesn't fall within a subplot, we do the
// zoom on all subplots...
Iterator iterator = getSubplots().iterator();
while (iterator.hasNext()) {
subplot = (CategoryPlot) iterator.next();
subplot.zoomRangeAxes(factor, info, source, useAnchor);
}
}
}
/**
* Zooms in on the range axes.
*
* @param lowerPercent the lower bound.
* @param upperPercent the upper bound.
* @param info the plot rendering info (<code>null</code> not permitted).
* @param source the source point (<code>null</code> not permitted).
*/
public void zoomRangeAxes(double lowerPercent, double upperPercent,
PlotRenderingInfo info, Point2D source) {
// delegate 'info' and 'source' argument checks...
CategoryPlot subplot = findSubplot(info, source);
if (subplot != null) {
subplot.zoomRangeAxes(lowerPercent, upperPercent, info, source);
}
else {
// if the source point doesn't fall within a subplot, we do the
// zoom on all subplots...
Iterator iterator = getSubplots().iterator();
while (iterator.hasNext()) {
subplot = (CategoryPlot) iterator.next();
subplot.zoomRangeAxes(lowerPercent, upperPercent, info, source);
}
}
}
/**
* Calculates the space required for the axes.
*
* @param g2 the graphics device.
* @param plotArea the plot area.
*
* @return The space required for the axes.
*/
protected AxisSpace calculateAxisSpace(Graphics2D g2,
Rectangle2D plotArea) {
AxisSpace space = new AxisSpace();
PlotOrientation orientation = getOrientation();
// work out the space required by the domain axis...
AxisSpace fixed = getFixedDomainAxisSpace();
if (fixed != null) {
if (orientation == PlotOrientation.HORIZONTAL) {
space.setLeft(fixed.getLeft());
space.setRight(fixed.getRight());
}
else if (orientation == PlotOrientation.VERTICAL) {
space.setTop(fixed.getTop());
space.setBottom(fixed.getBottom());
}
}
else {
CategoryAxis categoryAxis = getDomainAxis();
RectangleEdge categoryEdge = Plot.resolveDomainAxisLocation(
getDomainAxisLocation(), orientation);
if (categoryAxis != null) {
space = categoryAxis.reserveSpace(g2, this, plotArea,
categoryEdge, space);
}
else {
if (getDrawSharedDomainAxis()) {
space = getDomainAxis().reserveSpace(g2, this, plotArea,
categoryEdge, space);
}
}
}
Rectangle2D adjustedPlotArea = space.shrink(plotArea, null);
// work out the maximum height or width of the non-shared axes...
int n = this.subplots.size();
int totalWeight = 0;
for (int i = 0; i < n; i++) {
CategoryPlot sub = (CategoryPlot) this.subplots.get(i);
totalWeight += sub.getWeight();
}
this.subplotAreas = new Rectangle2D[n];
double x = adjustedPlotArea.getX();
double y = adjustedPlotArea.getY();
double usableSize = 0.0;
if (orientation == PlotOrientation.HORIZONTAL) {
usableSize = adjustedPlotArea.getWidth() - this.gap * (n - 1);
}
else if (orientation == PlotOrientation.VERTICAL) {
usableSize = adjustedPlotArea.getHeight() - this.gap * (n - 1);
}
for (int i = 0; i < n; i++) {
CategoryPlot plot = (CategoryPlot) this.subplots.get(i);
// calculate sub-plot area
if (orientation == PlotOrientation.HORIZONTAL) {
double w = usableSize * plot.getWeight() / totalWeight;
this.subplotAreas[i] = new Rectangle2D.Double(x, y, w,
adjustedPlotArea.getHeight());
x = x + w + this.gap;
}
else if (orientation == PlotOrientation.VERTICAL) {
double h = usableSize * plot.getWeight() / totalWeight;
this.subplotAreas[i] = new Rectangle2D.Double(x, y,
adjustedPlotArea.getWidth(), h);
y = y + h + this.gap;
}
AxisSpace subSpace = plot.calculateRangeAxisSpace(g2,
this.subplotAreas[i], null);
space.ensureAtLeast(subSpace);
}
return space;
}
/**
* Draws the plot on a Java 2D graphics device (such as the screen or a
* printer). Will perform all the placement calculations for each of the
* sub-plots and then tell these to draw themselves.
*
* @param g2 the graphics device.
* @param area the area within which the plot (including axis labels)
* should be drawn.
* @param anchor the anchor point (<code>null</code> permitted).
* @param parentState the state from the parent plot, if there is one.
* @param info collects information about the drawing (<code>null</code>
* permitted).
*/
public void draw(Graphics2D g2,
Rectangle2D area,
Point2D anchor,
PlotState parentState,
PlotRenderingInfo info) {
// set up info collection...
if (info != null) {
info.setPlotArea(area);
}
// adjust the drawing area for plot insets (if any)...
RectangleInsets insets = getInsets();
area.setRect(area.getX() + insets.getLeft(),
area.getY() + insets.getTop(),
area.getWidth() - insets.getLeft() - insets.getRight(),
area.getHeight() - insets.getTop() - insets.getBottom());
// calculate the data area...
setFixedRangeAxisSpaceForSubplots(null);
AxisSpace space = calculateAxisSpace(g2, area);
Rectangle2D dataArea = space.shrink(area, null);
// set the width and height of non-shared axis of all sub-plots
setFixedRangeAxisSpaceForSubplots(space);
// draw the shared axis
CategoryAxis axis = getDomainAxis();
RectangleEdge domainEdge = getDomainAxisEdge();
double cursor = RectangleEdge.coordinate(dataArea, domainEdge);
AxisState axisState = axis.draw(g2, cursor, area, dataArea,
domainEdge, info);
if (parentState == null) {
parentState = new PlotState();
}
parentState.getSharedAxisStates().put(axis, axisState);
// draw all the subplots
for (int i = 0; i < this.subplots.size(); i++) {
CategoryPlot plot = (CategoryPlot) this.subplots.get(i);
PlotRenderingInfo subplotInfo = null;
if (info != null) {
subplotInfo = new PlotRenderingInfo(info.getOwner());
info.addSubplotInfo(subplotInfo);
}
Point2D subAnchor = null;
if (anchor != null && this.subplotAreas[i].contains(anchor)) {
subAnchor = anchor;
}
plot.draw(g2, this.subplotAreas[i], subAnchor, parentState,
subplotInfo);
}
if (info != null) {
info.setDataArea(dataArea);
}
}
/**
* Sets the size (width or height, depending on the orientation of the
* plot) for the range axis of each subplot.
*
* @param space the space (<code>null</code> permitted).
*/
protected void setFixedRangeAxisSpaceForSubplots(AxisSpace space) {
Iterator iterator = this.subplots.iterator();
while (iterator.hasNext()) {
CategoryPlot plot = (CategoryPlot) iterator.next();
plot.setFixedRangeAxisSpace(space, false);
}
}
/**
* Sets the orientation of the plot (and all subplots).
*
* @param orientation the orientation (<code>null</code> not permitted).
*/
public void setOrientation(PlotOrientation orientation) {
super.setOrientation(orientation);
Iterator iterator = this.subplots.iterator();
while (iterator.hasNext()) {
CategoryPlot plot = (CategoryPlot) iterator.next();
plot.setOrientation(orientation);
}
}
/**
* Returns a range representing the extent of the data values in this plot
* (obtained from the subplots) that will be rendered against the specified
* axis. NOTE: This method is intended for internal JFreeChart use, and
* is public only so that code in the axis classes can call it. Since,
* for this class, the domain axis is a {@link CategoryAxis}
* (not a <code>ValueAxis</code}) and subplots have independent range axes,
* the JFreeChart code will never call this method (although this is not
* checked/enforced).
*
* @param axis the axis.
*
* @return The range.
*/
public Range getDataRange(ValueAxis axis) {
// override is only for documentation purposes
return super.getDataRange(axis);
}
/**
* Returns a collection of legend items for the plot.
*
* @return The legend items.
*/
public LegendItemCollection getLegendItems() {
LegendItemCollection result = getFixedLegendItems();
if (result == null) {
result = new LegendItemCollection();
if (this.subplots != null) {
Iterator iterator = this.subplots.iterator();
while (iterator.hasNext()) {
CategoryPlot plot = (CategoryPlot) iterator.next();
LegendItemCollection more = plot.getLegendItems();
result.addAll(more);
}
}
}
return result;
}
/**
* Returns an unmodifiable list of the categories contained in all the
* subplots.
*
* @return The list.
*/
public List getCategories() {
List result = new java.util.ArrayList();
if (this.subplots != null) {
Iterator iterator = this.subplots.iterator();
while (iterator.hasNext()) {
CategoryPlot plot = (CategoryPlot) iterator.next();
List more = plot.getCategories();
Iterator moreIterator = more.iterator();
while (moreIterator.hasNext()) {
Comparable category = (Comparable) moreIterator.next();
if (!result.contains(category)) {
result.add(category);
}
}
}
}
return Collections.unmodifiableList(result);
}
/**
* Overridden to return the categories in the subplots.
*
* @param axis ignored.
*
* @return A list of the categories in the subplots.
*
* @since 1.0.3
*/
public List getCategoriesForAxis(CategoryAxis axis) {
// FIXME: this code means that it is not possible to use more than
// one domain axis for the combined plots...
return getCategories();
}
/**
* Handles a 'click' on the plot.
*
* @param x x-coordinate of the click.
* @param y y-coordinate of the click.
* @param info information about the plot's dimensions.
*
*/
public void handleClick(int x, int y, PlotRenderingInfo info) {
Rectangle2D dataArea = info.getDataArea();
if (dataArea.contains(x, y)) {
for (int i = 0; i < this.subplots.size(); i++) {
CategoryPlot subplot = (CategoryPlot) this.subplots.get(i);
PlotRenderingInfo subplotInfo = info.getSubplotInfo(i);
subplot.handleClick(x, y, subplotInfo);
}
}
}
/**
* Receives a {@link PlotChangeEvent} and responds by notifying all
* listeners.
*
* @param event the event.
*/
public void plotChanged(PlotChangeEvent event) {
notifyListeners(event);
}
/**
* Tests the plot for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CombinedDomainCategoryPlot)) {
return false;
}
CombinedDomainCategoryPlot that = (CombinedDomainCategoryPlot) obj;
if (this.gap != that.gap) {
return false;
}
if (!ObjectUtilities.equal(this.subplots, that.subplots)) {
return false;
}
return super.equals(obj);
}
/**
* Returns a clone of the plot.
*
* @return A clone.
*
* @throws CloneNotSupportedException this class will not throw this
* exception, but subclasses (if any) might.
*/
public Object clone() throws CloneNotSupportedException {
CombinedDomainCategoryPlot result
= (CombinedDomainCategoryPlot) super.clone();
result.subplots = (List) ObjectUtilities.deepClone(this.subplots);
for (Iterator it = result.subplots.iterator(); it.hasNext();) {
Plot child = (Plot) it.next();
child.setParent(result);
}
return result;
}
}
| mit |
0x0mar/mitmproxy | test/test_proxy.py | 4679 | import argparse
from libmproxy import cmdline
from libmproxy.proxy import ProxyConfig, process_proxy_options
from libmproxy.proxy.connection import ServerConnection
from libmproxy.proxy.primitives import ProxyError
from libmproxy.proxy.server import DummyServer, ProxyServer, ConnectionHandler
import tutils
from libpathod import test
from netlib import http, tcp
import mock
def test_proxy_error():
p = ProxyError(111, "msg")
assert str(p)
class TestServerConnection:
def setUp(self):
self.d = test.Daemon()
def tearDown(self):
self.d.shutdown()
def test_simple(self):
sc = ServerConnection((self.d.IFACE, self.d.port))
sc.connect()
f = tutils.tflow()
f.server_conn = sc
f.request.path = "/p/200:da"
sc.send(f.request.assemble())
assert http.read_response(sc.rfile, f.request.method, 1000)
assert self.d.last_log()
sc.finish()
def test_terminate_error(self):
sc = ServerConnection((self.d.IFACE, self.d.port))
sc.connect()
sc.connection = mock.Mock()
sc.connection.recv = mock.Mock(return_value=False)
sc.connection.flush = mock.Mock(side_effect=tcp.NetLibDisconnect)
sc.finish()
def test_repr(self):
sc = tutils.tserver_conn()
assert "address:22" in repr(sc)
assert "ssl" not in repr(sc)
sc.ssl_established = True
assert "ssl" in repr(sc)
sc.sni = "foo"
assert "foo" in repr(sc)
class TestProcessProxyOptions:
def p(self, *args):
parser = tutils.MockParser()
cmdline.common_options(parser)
opts = parser.parse_args(args=args)
return parser, process_proxy_options(parser, opts)
def assert_err(self, err, *args):
tutils.raises(err, self.p, *args)
def assert_noerr(self, *args):
m, p = self.p(*args)
assert p
return p
def test_simple(self):
assert self.p()
def test_cadir(self):
with tutils.tmpdir() as cadir:
self.assert_noerr("--cadir", cadir)
@mock.patch("libmproxy.platform.resolver", None)
def test_no_transparent(self):
self.assert_err("transparent mode not supported", "-T")
@mock.patch("libmproxy.platform.resolver")
def test_modes(self, _):
self.assert_noerr("-R", "http://localhost")
self.assert_err("expected one argument", "-R")
self.assert_err("Invalid server specification", "-R", "reverse")
self.assert_noerr("-T")
self.assert_noerr("-U", "http://localhost")
self.assert_err("expected one argument", "-U")
self.assert_err("Invalid server specification", "-U", "upstream")
self.assert_err("mutually exclusive", "-R", "http://localhost", "-T")
def test_client_certs(self):
with tutils.tmpdir() as cadir:
self.assert_noerr("--client-certs", cadir)
self.assert_err("directory does not exist", "--client-certs", "nonexistent")
def test_certs(self):
with tutils.tmpdir() as cadir:
self.assert_noerr("--cert", tutils.test_data.path("data/testkey.pem"))
self.assert_err("does not exist", "--cert", "nonexistent")
def test_auth(self):
p = self.assert_noerr("--nonanonymous")
assert p.authenticator
p = self.assert_noerr("--htpasswd", tutils.test_data.path("data/htpasswd"))
assert p.authenticator
self.assert_err("malformed htpasswd file", "--htpasswd", tutils.test_data.path("data/htpasswd.invalid"))
p = self.assert_noerr("--singleuser", "test:test")
assert p.authenticator
self.assert_err("invalid single-user specification", "--singleuser", "test")
class TestProxyServer:
@tutils.SkipWindows # binding to 0.0.0.0:1 works without special permissions on Windows
def test_err(self):
conf = ProxyConfig(
port=1
)
tutils.raises("error starting proxy server", ProxyServer, conf)
def test_err_2(self):
conf = ProxyConfig(
host="invalidhost"
)
tutils.raises("error starting proxy server", ProxyServer, conf)
class TestDummyServer:
def test_simple(self):
d = DummyServer(None)
d.start_slave()
d.shutdown()
class TestConnectionHandler:
def test_fatal_error(self):
config = mock.Mock()
config.mode.get_upstream_server.side_effect = RuntimeError
c = ConnectionHandler(config, mock.MagicMock(), ("127.0.0.1", 8080), None, mock.MagicMock())
with tutils.capture_stderr(c.handle) as output:
assert "mitmproxy has crashed" in output
| mit |
matt9mg/concrete5 | concrete/blocks/express_entry_list/controller.php | 9293 | <?php
namespace Concrete\Block\ExpressEntryList;
use Concrete\Controller\Element\Search\CustomizeResults;
use \Concrete\Core\Block\BlockController;
use Concrete\Core\Entity\Express\Entity;
use Concrete\Core\Express\Entry\Search\Result\Result;
use Concrete\Core\Express\EntryList;
use Concrete\Core\Search\Column\AttributeKeyColumn;
use Concrete\Core\Search\Result\ItemColumn;
use Concrete\Core\Support\Facade\Facade;
use Symfony\Component\HttpFoundation\JsonResponse;
class Controller extends BlockController
{
protected $btInterfaceWidth = "640";
protected $btInterfaceHeight = "400";
protected $btTable = 'btExpressEntryList';
protected $entityAttributes = array();
public function on_start()
{
parent::on_start();
$this->app = Facade::getFacadeApplication();
$this->entityManager = $this->app->make('database/orm')->entityManager();
}
public function getBlockTypeDescription()
{
return t("Add a searchable Express entry list to a page.");
}
public function getBlockTypeName()
{
return t("Express Entry List");
}
public function getBlockTypeInSetName()
{
return t("List");
}
public function add()
{
$this->loadData();
$this->set('searchProperties', []);
$this->set('searchPropertiesSelected', []);
$this->set('linkedProperties', []);
}
public function edit()
{
$this->loadData();
if ($this->exEntityID) {
/**
* @var $entity Entity
*/
$entity = $this->entityManager->find('Concrete\Core\Entity\Express\Entity', $this->exEntityID);
if (is_object($entity)) {
$searchPropertiesSelected = (array) json_decode($this->searchProperties);
$linkedPropertiesSelected = (array) json_decode($this->linkedProperties);
$searchProperties = $this->getSearchPropertiesJsonArray($entity);
$columns = unserialize($this->columns);
$provider = \Core::make('Concrete\Core\Express\Search\SearchProvider', array($entity, $entity->getAttributeKeyCategory()));
if ($columns) {
$provider->setColumnSet($columns);
}
$element = new CustomizeResults($provider);
$this->set('customizeElement', $element);
$this->set('linkedPropertiesSelected', $linkedPropertiesSelected);
$this->set('searchPropertiesSelected', $searchPropertiesSelected);
$this->set('searchProperties', $searchProperties);
}
}
}
protected function getSearchPropertiesJsonArray($entity)
{
$attributes = $entity->getAttributeKeyCategory()->getList();
$select = array();
foreach($attributes as $ak) {
$o = new \stdClass;
$o->akID = $ak->getAttributeKeyID();
$o->akName = $ak->getAttributeKeyDisplayName();
$select[] = $o;
}
return $select;
}
public function view()
{
$entity = $this->entityManager->find('Concrete\Core\Entity\Express\Entity', $this->exEntityID);
if (is_object($entity)) {
$category = $entity->getAttributeKeyCategory();
$list = new EntryList($entity);
if ($this->displayLimit > 0) {
$list->setItemsPerPage(intval($this->displayLimit));
}
$set = unserialize($this->columns);
$defaultSortColumn = $set->getDefaultSortColumn();
if ($this->request->query->has($list->getQuerySortDirectionParameter())) {
$direction = $this->request->query->get($list->getQuerySortDirectionParameter());
} else {
$direction = $defaultSortColumn->getColumnDefaultSortDirection();
}
if ($this->request->query->has($list->getQuerySortColumnParameter())) {
$value = $this->request->query->get($list->getQuerySortColumnParameter());
$column = $entity->getResultColumnSet();
$value = $column->getColumnByKey($value);
if (is_object($value)) {
$list->sanitizedSortBy($value->getColumnKey(), $direction);
}
} else {
$list->sanitizedSortBy($defaultSortColumn->getColumnKey(), $direction);
}
if ($this->request->query->has('keywords') && $this->enableSearch) {
$list->filterByKeywords($this->request->query->get('keywords'));
}
$tableSearchProperties = array();
$searchPropertiesSelected = (array) json_decode($this->searchProperties);
foreach($searchPropertiesSelected as $akID) {
$ak = $category->getAttributeKeyByID($akID);
if (is_object($ak)) {
$tableSearchProperties[] = $ak;
$type = $ak->getAttributeType();
$cnt = $type->getController();
$cnt->setRequestArray($_REQUEST);
$cnt->setAttributeKey($ak);
$cnt->searchForm($list);
}
}
$result = new Result($set, $list);
$pagination = $list->getPagination();
if ($pagination->getTotalPages() > 1) {
$pagination = $pagination->renderDefaultView();
$this->set('pagination', $pagination);
}
$this->set('list', $list);
$this->set('result', $result);
$this->set('entity', $entity);
$this->set('tableSearchProperties', $tableSearchProperties);
$this->set('detailPage', $this->getDetailPageObject());
}
}
public function save($data)
{
$this->on_start();
if (isset($data['searchProperties']) && is_array($data['searchProperties'])) {
$searchProperties = $data['searchProperties'];
$data['searchProperties'] = json_encode($searchProperties);
}
if (isset($data['linkedProperties']) && is_array($data['linkedProperties'])) {
$linkedProperties = $data['linkedProperties'];
$data['linkedProperties'] = json_encode($linkedProperties);
}
$entity = $this->entityManager->find('Concrete\Core\Entity\Express\Entity', $data['exEntityID']);
if (is_object($entity)) {
$provider = $this->app->make('Concrete\Core\Express\Search\SearchProvider', array($entity, $entity->getAttributeKeyCategory()));
$set = $this->app->make('Concrete\Core\Express\Search\ColumnSet\ColumnSet');
$available = $provider->getAvailableColumnSet();
foreach ($this->request->request->get('column') as $key) {
$set->addColumn($available->getColumnByKey($key));
}
$sort = $available->getColumnByKey($this->request->request->get('fSearchDefaultSort'));
$set->setDefaultSortColumn($sort, $this->request->request->get('fSearchDefaultSortDirection'));
$data['columns'] = serialize($set);
}
parent::save($data);
}
public function action_load_entity_data()
{
$exEntityID = $this->request->request->get('exEntityID');
if ($exEntityID) {
$entity = $this->entityManager->find('Concrete\Core\Entity\Express\Entity', $exEntityID);
if (is_object($entity)) {
$provider = \Core::make('Concrete\Core\Express\Search\SearchProvider', array($entity, $entity->getAttributeKeyCategory()));
$element = new CustomizeResults($provider);
$r = new \stdClass;
ob_start();
$element->getViewObject()->render();
$r->customize = ob_get_contents();
ob_end_clean();
$r->attributes = $this->getSearchPropertiesJsonArray($entity);
return new JsonResponse($r);
}
}
\Core::make('app')->shutdown();
}
public function loadData()
{
$r = $this->entityManager->getRepository('Concrete\Core\Entity\Express\Entity');
$entityObjects = $r->findAll();
$entities = array('' => t("** Choose Entity"));
foreach($entityObjects as $entity) {
$entities[$entity->getID()] = $entity->getName();
}
$this->set('entities', $entities);
}
protected function getDetailPageObject()
{
$detailPage = false;
if ($this->detailPage) {
$c = \Page::getByID($this->detailPage);
if (is_object($c) && !$c->isError()) {
$detailPage = $c;
}
}
return $detailPage;
}
public function linkThisColumn(ItemColumn $column)
{
$detailPage = $this->getDetailPageObject();
if (!$detailPage) {
return false;
}
$linkedProperties = (array) json_decode($this->linkedProperties);
if ($column->getColumn() instanceof AttributeKeyColumn) {
if ($ak = $column->getColumn()->getAttributeKey()) {
return in_array($ak->getAttributeKeyID(), $linkedProperties);
}
}
}
}
| mit |
Azure/autorest | packages/tools/md-mock-api/definitions/index.d.ts | 138 | /**
* Yargs is missing helpers definitions.
*/
declare module "yargs/helpers" {
export const hideBin: (argv: string[]) => string[];
}
| mit |
extend1994/cdnjs | ajax/libs/jsPlumb/2.8.8/js/jsplumb.js | 642531 | /**
* jsBezier
*
* Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
*
* licensed under the MIT license.
*
* a set of Bezier curve functions that deal with Beziers, used by jsPlumb, and perhaps useful for other people. These functions work with Bezier
* curves of arbitrary degree.
*
* - functions are all in the 'jsBezier' namespace.
*
* - all input points should be in the format {x:.., y:..}. all output points are in this format too.
*
* - all input curves should be in the format [ {x:.., y:..}, {x:.., y:..}, {x:.., y:..}, {x:.., y:..} ]
*
* - 'location' as used as an input here refers to a decimal in the range 0-1 inclusive, which indicates a point some proportion along the length
* of the curve. location as output has the same format and meaning.
*
*
* Function List:
* --------------
*
* distanceFromCurve(point, curve)
*
* Calculates the distance that the given point lies from the given Bezier. Note that it is computed relative to the center of the Bezier,
* so if you have stroked the curve with a wide pen you may wish to take that into account! The distance returned is relative to the values
* of the curve and the point - it will most likely be pixels.
*
* gradientAtPoint(curve, location)
*
* Calculates the gradient to the curve at the given location, as a decimal between 0 and 1 inclusive.
*
* gradientAtPointAlongCurveFrom (curve, location)
*
* Calculates the gradient at the point on the given curve that is 'distance' units from location.
*
* nearestPointOnCurve(point, curve)
*
* Calculates the nearest point to the given point on the given curve. The return value of this is a JS object literal, containing both the
*point's coordinates and also the 'location' of the point (see above), for example: { point:{x:551,y:150}, location:0.263365 }.
*
* pointOnCurve(curve, location)
*
* Calculates the coordinates of the point on the given Bezier curve at the given location.
*
* pointAlongCurveFrom(curve, location, distance)
*
* Calculates the coordinates of the point on the given curve that is 'distance' units from location. 'distance' should be in the same coordinate
* space as that used to construct the Bezier curve. For an HTML Canvas usage, for example, distance would be a measure of pixels.
*
* locationAlongCurveFrom(curve, location, distance)
*
* Calculates the location on the given curve that is 'distance' units from location. 'distance' should be in the same coordinate
* space as that used to construct the Bezier curve. For an HTML Canvas usage, for example, distance would be a measure of pixels.
*
* perpendicularToCurveAt(curve, location, length, distance)
*
* Calculates the perpendicular to the given curve at the given location. length is the length of the line you wish for (it will be centered
* on the point at 'location'). distance is optional, and allows you to specify a point along the path from the given location as the center of
* the perpendicular returned. The return value of this is an array of two points: [ {x:...,y:...}, {x:...,y:...} ].
*
*
*/
(function() {
var root = this;
if(typeof Math.sgn == "undefined") {
Math.sgn = function(x) { return x == 0 ? 0 : x > 0 ? 1 :-1; };
}
var Vectors = {
subtract : function(v1, v2) { return {x:v1.x - v2.x, y:v1.y - v2.y }; },
dotProduct : function(v1, v2) { return (v1.x * v2.x) + (v1.y * v2.y); },
square : function(v) { return Math.sqrt((v.x * v.x) + (v.y * v.y)); },
scale : function(v, s) { return {x:v.x * s, y:v.y * s }; }
},
maxRecursion = 64,
flatnessTolerance = Math.pow(2.0,-maxRecursion-1);
/**
* Calculates the distance that the point lies from the curve.
*
* @param point a point in the form {x:567, y:3342}
* @param curve a Bezier curve in the form [{x:..., y:...}, {x:..., y:...}, {x:..., y:...}, {x:..., y:...}]. note that this is currently
* hardcoded to assume cubiz beziers, but would be better off supporting any degree.
* @return a JS object literal containing location and distance, for example: {location:0.35, distance:10}. Location is analogous to the location
* argument you pass to the pointOnPath function: it is a ratio of distance travelled along the curve. Distance is the distance in pixels from
* the point to the curve.
*/
var _distanceFromCurve = function(point, curve) {
var candidates = [],
w = _convertToBezier(point, curve),
degree = curve.length - 1, higherDegree = (2 * degree) - 1,
numSolutions = _findRoots(w, higherDegree, candidates, 0),
v = Vectors.subtract(point, curve[0]), dist = Vectors.square(v), t = 0.0;
for (var i = 0; i < numSolutions; i++) {
v = Vectors.subtract(point, _bezier(curve, degree, candidates[i], null, null));
var newDist = Vectors.square(v);
if (newDist < dist) {
dist = newDist;
t = candidates[i];
}
}
v = Vectors.subtract(point, curve[degree]);
newDist = Vectors.square(v);
if (newDist < dist) {
dist = newDist;
t = 1.0;
}
return {location:t, distance:dist};
};
/**
* finds the nearest point on the curve to the given point.
*/
var _nearestPointOnCurve = function(point, curve) {
var td = _distanceFromCurve(point, curve);
return {point:_bezier(curve, curve.length - 1, td.location, null, null), location:td.location};
};
var _convertToBezier = function(point, curve) {
var degree = curve.length - 1, higherDegree = (2 * degree) - 1,
c = [], d = [], cdTable = [], w = [],
z = [ [1.0, 0.6, 0.3, 0.1], [0.4, 0.6, 0.6, 0.4], [0.1, 0.3, 0.6, 1.0] ];
for (var i = 0; i <= degree; i++) c[i] = Vectors.subtract(curve[i], point);
for (var i = 0; i <= degree - 1; i++) {
d[i] = Vectors.subtract(curve[i+1], curve[i]);
d[i] = Vectors.scale(d[i], 3.0);
}
for (var row = 0; row <= degree - 1; row++) {
for (var column = 0; column <= degree; column++) {
if (!cdTable[row]) cdTable[row] = [];
cdTable[row][column] = Vectors.dotProduct(d[row], c[column]);
}
}
for (i = 0; i <= higherDegree; i++) {
if (!w[i]) w[i] = [];
w[i].y = 0.0;
w[i].x = parseFloat(i) / higherDegree;
}
var n = degree, m = degree-1;
for (var k = 0; k <= n + m; k++) {
var lb = Math.max(0, k - m),
ub = Math.min(k, n);
for (i = lb; i <= ub; i++) {
var j = k - i;
w[i+j].y += cdTable[j][i] * z[j][i];
}
}
return w;
};
/**
* counts how many roots there are.
*/
var _findRoots = function(w, degree, t, depth) {
var left = [], right = [],
left_count, right_count,
left_t = [], right_t = [];
switch (_getCrossingCount(w, degree)) {
case 0 : {
return 0;
}
case 1 : {
if (depth >= maxRecursion) {
t[0] = (w[0].x + w[degree].x) / 2.0;
return 1;
}
if (_isFlatEnough(w, degree)) {
t[0] = _computeXIntercept(w, degree);
return 1;
}
break;
}
}
_bezier(w, degree, 0.5, left, right);
left_count = _findRoots(left, degree, left_t, depth+1);
right_count = _findRoots(right, degree, right_t, depth+1);
for (var i = 0; i < left_count; i++) t[i] = left_t[i];
for (var i = 0; i < right_count; i++) t[i+left_count] = right_t[i];
return (left_count+right_count);
};
var _getCrossingCount = function(curve, degree) {
var n_crossings = 0, sign, old_sign;
sign = old_sign = Math.sgn(curve[0].y);
for (var i = 1; i <= degree; i++) {
sign = Math.sgn(curve[i].y);
if (sign != old_sign) n_crossings++;
old_sign = sign;
}
return n_crossings;
};
var _isFlatEnough = function(curve, degree) {
var error,
intercept_1, intercept_2, left_intercept, right_intercept,
a, b, c, det, dInv, a1, b1, c1, a2, b2, c2;
a = curve[0].y - curve[degree].y;
b = curve[degree].x - curve[0].x;
c = curve[0].x * curve[degree].y - curve[degree].x * curve[0].y;
var max_distance_above, max_distance_below;
max_distance_above = max_distance_below = 0.0;
for (var i = 1; i < degree; i++) {
var value = a * curve[i].x + b * curve[i].y + c;
if (value > max_distance_above)
max_distance_above = value;
else if (value < max_distance_below)
max_distance_below = value;
}
a1 = 0.0; b1 = 1.0; c1 = 0.0; a2 = a; b2 = b;
c2 = c - max_distance_above;
det = a1 * b2 - a2 * b1;
dInv = 1.0/det;
intercept_1 = (b1 * c2 - b2 * c1) * dInv;
a2 = a; b2 = b; c2 = c - max_distance_below;
det = a1 * b2 - a2 * b1;
dInv = 1.0/det;
intercept_2 = (b1 * c2 - b2 * c1) * dInv;
left_intercept = Math.min(intercept_1, intercept_2);
right_intercept = Math.max(intercept_1, intercept_2);
error = right_intercept - left_intercept;
return (error < flatnessTolerance)? 1 : 0;
};
var _computeXIntercept = function(curve, degree) {
var XLK = 1.0, YLK = 0.0,
XNM = curve[degree].x - curve[0].x, YNM = curve[degree].y - curve[0].y,
XMK = curve[0].x - 0.0, YMK = curve[0].y - 0.0,
det = XNM*YLK - YNM*XLK, detInv = 1.0/det,
S = (XNM*YMK - YNM*XMK) * detInv;
return 0.0 + XLK * S;
};
var _bezier = function(curve, degree, t, left, right) {
var temp = [[]];
for (var j =0; j <= degree; j++) temp[0][j] = curve[j];
for (var i = 1; i <= degree; i++) {
for (var j =0 ; j <= degree - i; j++) {
if (!temp[i]) temp[i] = [];
if (!temp[i][j]) temp[i][j] = {};
temp[i][j].x = (1.0 - t) * temp[i-1][j].x + t * temp[i-1][j+1].x;
temp[i][j].y = (1.0 - t) * temp[i-1][j].y + t * temp[i-1][j+1].y;
}
}
if (left != null)
for (j = 0; j <= degree; j++) left[j] = temp[j][0];
if (right != null)
for (j = 0; j <= degree; j++) right[j] = temp[degree-j][j];
return (temp[degree][0]);
};
var _curveFunctionCache = {};
var _getCurveFunctions = function(order) {
var fns = _curveFunctionCache[order];
if (!fns) {
fns = [];
var f_term = function() { return function(t) { return Math.pow(t, order); }; },
l_term = function() { return function(t) { return Math.pow((1-t), order); }; },
c_term = function(c) { return function(t) { return c; }; },
t_term = function() { return function(t) { return t; }; },
one_minus_t_term = function() { return function(t) { return 1-t; }; },
_termFunc = function(terms) {
return function(t) {
var p = 1;
for (var i = 0; i < terms.length; i++) p = p * terms[i](t);
return p;
};
};
fns.push(new f_term()); // first is t to the power of the curve order
for (var i = 1; i < order; i++) {
var terms = [new c_term(order)];
for (var j = 0 ; j < (order - i); j++) terms.push(new t_term());
for (var j = 0 ; j < i; j++) terms.push(new one_minus_t_term());
fns.push(new _termFunc(terms));
}
fns.push(new l_term()); // last is (1-t) to the power of the curve order
_curveFunctionCache[order] = fns;
}
return fns;
};
/**
* calculates a point on the curve, for a Bezier of arbitrary order.
* @param curve an array of control points, eg [{x:10,y:20}, {x:50,y:50}, {x:100,y:100}, {x:120,y:100}]. For a cubic bezier this should have four points.
* @param location a decimal indicating the distance along the curve the point should be located at. this is the distance along the curve as it travels, taking the way it bends into account. should be a number from 0 to 1, inclusive.
*/
var _pointOnPath = function(curve, location) {
var cc = _getCurveFunctions(curve.length - 1),
_x = 0, _y = 0;
for (var i = 0; i < curve.length ; i++) {
_x = _x + (curve[i].x * cc[i](location));
_y = _y + (curve[i].y * cc[i](location));
}
return {x:_x, y:_y};
};
var _dist = function(p1,p2) {
return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
};
var _isPoint = function(curve) {
return curve[0].x === curve[1].x && curve[0].y === curve[1].y;
};
/**
* finds the point that is 'distance' along the path from 'location'. this method returns both the x,y location of the point and also
* its 'location' (proportion of travel along the path); the method below - _pointAlongPathFrom - calls this method and just returns the
* point.
*/
var _pointAlongPath = function(curve, location, distance) {
if (_isPoint(curve)) {
return {
point:curve[0],
location:location
};
}
var prev = _pointOnPath(curve, location),
tally = 0,
curLoc = location,
direction = distance > 0 ? 1 : -1,
cur = null;
while (tally < Math.abs(distance)) {
curLoc += (0.005 * direction);
cur = _pointOnPath(curve, curLoc);
tally += _dist(cur, prev);
prev = cur;
}
return {point:cur, location:curLoc};
};
var _length = function(curve) {
if (_isPoint(curve)) return 0;
var prev = _pointOnPath(curve, 0),
tally = 0,
curLoc = 0,
direction = 1,
cur = null;
while (curLoc < 1) {
curLoc += (0.005 * direction);
cur = _pointOnPath(curve, curLoc);
tally += _dist(cur, prev);
prev = cur;
}
return tally;
};
/**
* finds the point that is 'distance' along the path from 'location'.
*/
var _pointAlongPathFrom = function(curve, location, distance) {
return _pointAlongPath(curve, location, distance).point;
};
/**
* finds the location that is 'distance' along the path from 'location'.
*/
var _locationAlongPathFrom = function(curve, location, distance) {
return _pointAlongPath(curve, location, distance).location;
};
/**
* returns the gradient of the curve at the given location, which is a decimal between 0 and 1 inclusive.
*
* thanks // http://bimixual.org/AnimationLibrary/beziertangents.html
*/
var _gradientAtPoint = function(curve, location) {
var p1 = _pointOnPath(curve, location),
p2 = _pointOnPath(curve.slice(0, curve.length - 1), location),
dy = p2.y - p1.y, dx = p2.x - p1.x;
return dy === 0 ? Infinity : Math.atan(dy / dx);
};
/**
returns the gradient of the curve at the point which is 'distance' from the given location.
if this point is greater than location 1, the gradient at location 1 is returned.
if this point is less than location 0, the gradient at location 0 is returned.
*/
var _gradientAtPointAlongPathFrom = function(curve, location, distance) {
var p = _pointAlongPath(curve, location, distance);
if (p.location > 1) p.location = 1;
if (p.location < 0) p.location = 0;
return _gradientAtPoint(curve, p.location);
};
/**
* calculates a line that is 'length' pixels long, perpendicular to, and centered on, the path at 'distance' pixels from the given location.
* if distance is not supplied, the perpendicular for the given location is computed (ie. we set distance to zero).
*/
var _perpendicularToPathAt = function(curve, location, length, distance) {
distance = distance == null ? 0 : distance;
var p = _pointAlongPath(curve, location, distance),
m = _gradientAtPoint(curve, p.location),
_theta2 = Math.atan(-1 / m),
y = length / 2 * Math.sin(_theta2),
x = length / 2 * Math.cos(_theta2);
return [{x:p.point.x + x, y:p.point.y + y}, {x:p.point.x - x, y:p.point.y - y}];
};
/**
* Calculates all intersections of the given line with the given curve.
* @param x1
* @param y1
* @param x2
* @param y2
* @param curve
* @returns {Array}
*/
var _lineIntersection = function(x1, y1, x2, y2, curve) {
var a = y2 - y1,
b = x1 - x2,
c = (x1 * (y1 - y2)) + (y1 * (x2-x1)),
coeffs = _computeCoefficients(curve),
p = [
(a*coeffs[0][0]) + (b * coeffs[1][0]),
(a*coeffs[0][1])+(b*coeffs[1][1]),
(a*coeffs[0][2])+(b*coeffs[1][2]),
(a*coeffs[0][3])+(b*coeffs[1][3]) + c
],
r = _cubicRoots.apply(null, p),
intersections = [];
if (r != null) {
for (var i = 0; i < 3; i++) {
var t = r[i],
t2 = Math.pow(t, 2),
t3 = Math.pow(t, 3),
x = [
(coeffs[0][0] * t3) + (coeffs[0][1] * t2) + (coeffs[0][2] * t) + coeffs[0][3],
(coeffs[1][0] * t3) + (coeffs[1][1] * t2) + (coeffs[1][2] * t) + coeffs[1][3]
];
// check bounds of the line
var s;
if ((x2 - x1) !== 0) {
s = (x[0] - x1) / (x2 - x1);
}
else {
s = (x[1] - y1) / (y2 - y1);
}
if (t >= 0 && t <= 1.0 && s >= 0 && s <= 1.0) {
intersections.push(x);
}
}
}
return intersections;
};
/**
* Calculates all intersections of the given box with the given curve.
* @param x X position of top left corner of box
* @param y Y position of top left corner of box
* @param w width of box
* @param h height of box
* @param curve
* @returns {Array}
*/
var _boxIntersection = function(x, y, w, h, curve) {
var i = [];
i.push.apply(i, _lineIntersection(x, y, x + w, y, curve));
i.push.apply(i, _lineIntersection(x + w, y, x + w, y + h, curve));
i.push.apply(i, _lineIntersection(x + w, y + h, x, y + h, curve));
i.push.apply(i, _lineIntersection(x, y + h, x, y, curve));
return i;
};
/**
* Calculates all intersections of the given bounding box with the given curve.
* @param boundingBox Bounding box, in { x:.., y:..., w:..., h:... } format.
* @param curve
* @returns {Array}
*/
var _boundingBoxIntersection = function(boundingBox, curve) {
var i = [];
i.push.apply(i, _lineIntersection(boundingBox.x, boundingBox.y, boundingBox.x + boundingBox.w, boundingBox.y, curve));
i.push.apply(i, _lineIntersection(boundingBox.x + boundingBox.w, boundingBox.y, boundingBox.x + boundingBox.w, boundingBox.y + boundingBox.h, curve));
i.push.apply(i, _lineIntersection(boundingBox.x + boundingBox.w, boundingBox.y + boundingBox.h, boundingBox.x, boundingBox.y + boundingBox.h, curve));
i.push.apply(i, _lineIntersection(boundingBox.x, boundingBox.y + boundingBox.h, boundingBox.x, boundingBox.y, curve));
return i;
};
function _computeCoefficientsForAxis(curve, axis) {
return [
-(curve[0][axis]) + (3*curve[1][axis]) + (-3 * curve[2][axis]) + curve[3][axis],
(3*(curve[0][axis])) - (6*(curve[1][axis])) + (3*(curve[2][axis])),
-3*curve[0][axis] + 3*curve[1][axis],
curve[0][axis]
];
}
function _computeCoefficients(curve)
{
return [
_computeCoefficientsForAxis(curve, "x"),
_computeCoefficientsForAxis(curve, "y")
];
}
function sgn(x) {
return x < 0 ? -1 : x > 0 ? 1 : 0;
}
function _cubicRoots(a, b, c, d) {
var A = b / a,
B = c / a,
C = d / a,
Q = (3*B - Math.pow(A, 2))/9,
R = (9*A*B - 27*C - 2*Math.pow(A, 3))/54,
D = Math.pow(Q, 3) + Math.pow(R, 2),
S,
T,
t = [];
if (D >= 0) // complex or duplicate roots
{
S = sgn(R + Math.sqrt(D))*Math.pow(Math.abs(R + Math.sqrt(D)),(1/3));
T = sgn(R - Math.sqrt(D))*Math.pow(Math.abs(R - Math.sqrt(D)),(1/3));
t[0] = -A/3 + (S + T);
t[1] = -A/3 - (S + T)/2;
t[2] = -A/3 - (S + T)/2;
/*discard complex roots*/
if (Math.abs(Math.sqrt(3)*(S - T)/2) !== 0) {
t[1] = -1;
t[2] = -1;
}
}
else // distinct real roots
{
var th = Math.acos(R/Math.sqrt(-Math.pow(Q, 3)));
t[0] = 2*Math.sqrt(-Q)*Math.cos(th/3) - A/3;
t[1] = 2*Math.sqrt(-Q)*Math.cos((th + 2*Math.PI)/3) - A/3;
t[2] = 2*Math.sqrt(-Q)*Math.cos((th + 4*Math.PI)/3) - A/3;
}
// discard out of spec roots
for (var i = 0; i < 3; i++) {
if (t[i] < 0 || t[i] > 1.0) {
t[i] = -1;
}
}
return t;
}
var jsBezier = this.jsBezier = {
distanceFromCurve : _distanceFromCurve,
gradientAtPoint : _gradientAtPoint,
gradientAtPointAlongCurveFrom : _gradientAtPointAlongPathFrom,
nearestPointOnCurve : _nearestPointOnCurve,
pointOnCurve : _pointOnPath,
pointAlongCurveFrom : _pointAlongPathFrom,
perpendicularToCurveAt : _perpendicularToPathAt,
locationAlongCurveFrom:_locationAlongPathFrom,
getLength:_length,
lineIntersection:_lineIntersection,
boxIntersection:_boxIntersection,
boundingBoxIntersection:_boundingBoxIntersection,
version:"0.9.0"
};
if (typeof exports !== "undefined") {
exports.jsBezier = jsBezier;
}
}).call(typeof window !== 'undefined' ? window : this);
/**
* Biltong v0.4.0
*
* Various geometry functions written as part of jsPlumb and perhaps useful for others.
*
* Copyright (c) 2017 jsPlumb
* https://jsplumbtoolkit.com
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* 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.
*/
;(function() {
"use strict";
var root = this;
var Biltong = root.Biltong = {
version:"0.4.0"
};
if (typeof exports !== "undefined") {
exports.Biltong = Biltong;
}
var _isa = function(a) { return Object.prototype.toString.call(a) === "[object Array]"; },
_pointHelper = function(p1, p2, fn) {
p1 = _isa(p1) ? p1 : [p1.x, p1.y];
p2 = _isa(p2) ? p2 : [p2.x, p2.y];
return fn(p1, p2);
},
/**
* @name Biltong.gradient
* @function
* @desc Calculates the gradient of a line between the two points.
* @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
* @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
* @return {Float} The gradient of a line between the two points.
*/
_gradient = Biltong.gradient = function(p1, p2) {
return _pointHelper(p1, p2, function(_p1, _p2) {
if (_p2[0] == _p1[0])
return _p2[1] > _p1[1] ? Infinity : -Infinity;
else if (_p2[1] == _p1[1])
return _p2[0] > _p1[0] ? 0 : -0;
else
return (_p2[1] - _p1[1]) / (_p2[0] - _p1[0]);
});
},
/**
* @name Biltong.normal
* @function
* @desc Calculates the gradient of a normal to a line between the two points.
* @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
* @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
* @return {Float} The gradient of a normal to a line between the two points.
*/
_normal = Biltong.normal = function(p1, p2) {
return -1 / _gradient(p1, p2);
},
/**
* @name Biltong.lineLength
* @function
* @desc Calculates the length of a line between the two points.
* @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
* @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
* @return {Float} The length of a line between the two points.
*/
_lineLength = Biltong.lineLength = function(p1, p2) {
return _pointHelper(p1, p2, function(_p1, _p2) {
return Math.sqrt(Math.pow(_p2[1] - _p1[1], 2) + Math.pow(_p2[0] - _p1[0], 2));
});
},
/**
* @name Biltong.quadrant
* @function
* @desc Calculates the quadrant in which the angle between the two points lies.
* @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
* @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
* @return {Integer} The quadrant - 1 for upper right, 2 for lower right, 3 for lower left, 4 for upper left.
*/
_quadrant = Biltong.quadrant = function(p1, p2) {
return _pointHelper(p1, p2, function(_p1, _p2) {
if (_p2[0] > _p1[0]) {
return (_p2[1] > _p1[1]) ? 2 : 1;
}
else if (_p2[0] == _p1[0]) {
return _p2[1] > _p1[1] ? 2 : 1;
}
else {
return (_p2[1] > _p1[1]) ? 3 : 4;
}
});
},
/**
* @name Biltong.theta
* @function
* @desc Calculates the angle between the two points.
* @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
* @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
* @return {Float} The angle between the two points.
*/
_theta = Biltong.theta = function(p1, p2) {
return _pointHelper(p1, p2, function(_p1, _p2) {
var m = _gradient(_p1, _p2),
t = Math.atan(m),
s = _quadrant(_p1, _p2);
if ((s == 4 || s== 3)) t += Math.PI;
if (t < 0) t += (2 * Math.PI);
return t;
});
},
/**
* @name Biltong.intersects
* @function
* @desc Calculates whether or not the two rectangles intersect.
* @param {Rectangle} r1 First rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
* @param {Rectangle} r2 Second rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
* @return {Boolean} True if the rectangles intersect, false otherwise.
*/
_intersects = Biltong.intersects = function(r1, r2) {
var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h,
a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h;
return ( (x1 <= a1 && a1 <= x2) && (y1 <= b1 && b1 <= y2) ) ||
( (x1 <= a2 && a2 <= x2) && (y1 <= b1 && b1 <= y2) ) ||
( (x1 <= a1 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) ||
( (x1 <= a2 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) ||
( (a1 <= x1 && x1 <= a2) && (b1 <= y1 && y1 <= b2) ) ||
( (a1 <= x2 && x2 <= a2) && (b1 <= y1 && y1 <= b2) ) ||
( (a1 <= x1 && x1 <= a2) && (b1 <= y2 && y2 <= b2) ) ||
( (a1 <= x2 && x1 <= a2) && (b1 <= y2 && y2 <= b2) );
},
/**
* @name Biltong.encloses
* @function
* @desc Calculates whether or not r2 is completely enclosed by r1.
* @param {Rectangle} r1 First rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
* @param {Rectangle} r2 Second rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
* @param {Boolean} [allowSharedEdges=false] If true, the concept of enclosure allows for one or more edges to be shared by the two rectangles.
* @return {Boolean} True if r1 encloses r2, false otherwise.
*/
_encloses = Biltong.encloses = function(r1, r2, allowSharedEdges) {
var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h,
a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h,
c = function(v1, v2, v3, v4) { return allowSharedEdges ? v1 <= v2 && v3>= v4 : v1 < v2 && v3 > v4; };
return c(x1,a1,x2,a2) && c(y1,b1,y2,b2);
},
_segmentMultipliers = [null, [1, -1], [1, 1], [-1, 1], [-1, -1] ],
_inverseSegmentMultipliers = [null, [-1, -1], [-1, 1], [1, 1], [1, -1] ],
/**
* @name Biltong.pointOnLine
* @function
* @desc Calculates a point on the line from `fromPoint` to `toPoint` that is `distance` units along the length of the line.
* @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
* @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
* @return {Point} Point on the line, in the form `{ x:..., y:... }`.
*/
_pointOnLine = Biltong.pointOnLine = function(fromPoint, toPoint, distance) {
var m = _gradient(fromPoint, toPoint),
s = _quadrant(fromPoint, toPoint),
segmentMultiplier = distance > 0 ? _segmentMultipliers[s] : _inverseSegmentMultipliers[s],
theta = Math.atan(m),
y = Math.abs(distance * Math.sin(theta)) * segmentMultiplier[1],
x = Math.abs(distance * Math.cos(theta)) * segmentMultiplier[0];
return { x:fromPoint.x + x, y:fromPoint.y + y };
},
/**
* @name Biltong.perpendicularLineTo
* @function
* @desc Calculates a line of length `length` that is perpendicular to the line from `fromPoint` to `toPoint` and passes through `toPoint`.
* @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
* @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
* @return {Line} Perpendicular line, in the form `[ { x:..., y:... }, { x:..., y:... } ]`.
*/
_perpendicularLineTo = Biltong.perpendicularLineTo = function(fromPoint, toPoint, length) {
var m = _gradient(fromPoint, toPoint),
theta2 = Math.atan(-1 / m),
y = length / 2 * Math.sin(theta2),
x = length / 2 * Math.cos(theta2);
return [{x:toPoint.x + x, y:toPoint.y + y}, {x:toPoint.x - x, y:toPoint.y - y}];
};
}).call(typeof window !== 'undefined' ? window : this);
;
(function () {
"use strict";
/**
* Creates a Touch object.
* @param view
* @param target
* @param pageX
* @param pageY
* @param screenX
* @param screenY
* @param clientX
* @param clientY
* @returns {Touch}
* @private
*/
function _touch(view, target, pageX, pageY, screenX, screenY, clientX, clientY) {
return new Touch({
target:target,
identifier:_uuid(),
pageX: pageX,
pageY: pageY,
screenX: screenX,
screenY: screenY,
clientX: clientX || screenX,
clientY: clientY || screenY
});
}
/**
* Create a synthetic touch list from the given list of Touch objects.
* @returns {Array}
* @private
*/
function _touchList() {
var list = [];
Array.prototype.push.apply(list, arguments);
list.item = function(index) { return this[index]; };
return list;
}
/**
* Create a Touch object and then insert it into a synthetic touch list, returning the list.s
* @param view
* @param target
* @param pageX
* @param pageY
* @param screenX
* @param screenY
* @param clientX
* @param clientY
* @returns {Array}
* @private
*/
function _touchAndList(view, target, pageX, pageY, screenX, screenY, clientX, clientY) {
return _touchList(_touch.apply(null, arguments));
}
var root = this,
matchesSelector = function (el, selector, ctx) {
ctx = ctx || el.parentNode;
var possibles = ctx.querySelectorAll(selector);
for (var i = 0; i < possibles.length; i++) {
if (possibles[i] === el) {
return true;
}
}
return false;
},
_gel = function (el) {
return (typeof el == "string" || el.constructor === String) ? document.getElementById(el) : el;
},
_t = function (e) {
return e.srcElement || e.target;
},
//
// gets path info for the given event - the path from target to obj, in the event's bubble chain. if doCompute
// is false we just return target for the path.
//
_pi = function(e, target, obj, doCompute) {
if (!doCompute) return { path:[target], end:1 };
else if (typeof e.path !== "undefined" && e.path.indexOf) {
return { path: e.path, end: e.path.indexOf(obj) };
} else {
var out = { path:[], end:-1 }, _one = function(el) {
out.path.push(el);
if (el === obj) {
out.end = out.path.length - 1;
}
else if (el.parentNode != null) {
_one(el.parentNode)
}
};
_one(target);
return out;
}
},
_d = function (l, fn) {
for (var i = 0, j = l.length; i < j; i++) {
if (l[i] == fn) break;
}
if (i < l.length) l.splice(i, 1);
},
guid = 1,
//
// this function generates a guid for every handler, sets it on the handler, then adds
// it to the associated object's map of handlers for the given event. this is what enables us
// to unbind all events of some type, or all events (the second of which can be requested by the user,
// but it also used by Mottle when an element is removed.)
_store = function (obj, event, fn) {
var g = guid++;
obj.__ta = obj.__ta || {};
obj.__ta[event] = obj.__ta[event] || {};
// store each handler with a unique guid.
obj.__ta[event][g] = fn;
// set the guid on the handler.
fn.__tauid = g;
return g;
},
_unstore = function (obj, event, fn) {
obj.__ta && obj.__ta[event] && delete obj.__ta[event][fn.__tauid];
// a handler might have attached extra functions, so we unbind those too.
if (fn.__taExtra) {
for (var i = 0; i < fn.__taExtra.length; i++) {
_unbind(obj, fn.__taExtra[i][0], fn.__taExtra[i][1]);
}
fn.__taExtra.length = 0;
}
// a handler might have attached an unstore callback
fn.__taUnstore && fn.__taUnstore();
},
_curryChildFilter = function (children, obj, fn, evt) {
if (children == null) return fn;
else {
var c = children.split(","),
_fn = function (e) {
_fn.__tauid = fn.__tauid;
var t = _t(e), target = t; // t is the target element on which the event occurred. it is the
// element we will wish to pass to any callbacks.
var pathInfo = _pi(e, t, obj, children != null)
if (pathInfo.end != -1) {
for (var p = 0; p < pathInfo.end; p++) {
target = pathInfo.path[p];
for (var i = 0; i < c.length; i++) {
if (matchesSelector(target, c[i], obj)) {
fn.apply(target, arguments);
}
}
}
}
};
registerExtraFunction(fn, evt, _fn);
return _fn;
}
},
//
// registers an 'extra' function on some event listener function we were given - a function that we
// created and bound to the element as part of our housekeeping, and which we want to unbind and remove
// whenever the given function is unbound.
registerExtraFunction = function (fn, evt, newFn) {
fn.__taExtra = fn.__taExtra || [];
fn.__taExtra.push([evt, newFn]);
},
DefaultHandler = function (obj, evt, fn, children) {
if (isTouchDevice && touchMap[evt]) {
var tfn = _curryChildFilter(children, obj, fn, touchMap[evt]);
_bind(obj, touchMap[evt], tfn , fn);
}
if (evt === "focus" && obj.getAttribute("tabindex") == null) {
obj.setAttribute("tabindex", "1");
}
_bind(obj, evt, _curryChildFilter(children, obj, fn, evt), fn);
},
SmartClickHandler = function (obj, evt, fn, children) {
if (obj.__taSmartClicks == null) {
var down = function (e) {
obj.__tad = _pageLocation(e);
},
up = function (e) {
obj.__tau = _pageLocation(e);
},
click = function (e) {
if (obj.__tad && obj.__tau && obj.__tad[0] === obj.__tau[0] && obj.__tad[1] === obj.__tau[1]) {
for (var i = 0; i < obj.__taSmartClicks.length; i++)
obj.__taSmartClicks[i].apply(_t(e), [ e ]);
}
};
DefaultHandler(obj, "mousedown", down, children);
DefaultHandler(obj, "mouseup", up, children);
DefaultHandler(obj, "click", click, children);
obj.__taSmartClicks = [];
}
// store in the list of callbacks
obj.__taSmartClicks.push(fn);
// the unstore function removes this function from the object's listener list for this type.
fn.__taUnstore = function () {
_d(obj.__taSmartClicks, fn);
};
},
_tapProfiles = {
"tap": {touches: 1, taps: 1},
"dbltap": {touches: 1, taps: 2},
"contextmenu": {touches: 2, taps: 1}
},
TapHandler = function (clickThreshold, dblClickThreshold) {
return function (obj, evt, fn, children) {
// if event is contextmenu, for devices which are mouse only, we want to
// use the default bind.
if (evt == "contextmenu" && isMouseDevice)
DefaultHandler(obj, evt, fn, children);
else {
// the issue here is that this down handler gets registered only for the
// child nodes in the first registration. in fact it should be registered with
// no child selector and then on down we should cycle through the registered
// functions to see if one of them matches. on mouseup we should execute ALL of
// the functions whose children are either null or match the element.
if (obj.__taTapHandler == null) {
var tt = obj.__taTapHandler = {
tap: [],
dbltap: [],
contextmenu: [],
down: false,
taps: 0,
downSelectors: []
};
var down = function (e) {
var target = _t(e), pathInfo = _pi(e, target, obj, children != null), finished = false;
for (var p = 0; p < pathInfo.end; p++) {
if (finished) return;
target = pathInfo.path[p];
for (var i = 0; i < tt.downSelectors.length; i++) {
if (tt.downSelectors[i] == null || matchesSelector(target, tt.downSelectors[i], obj)) {
tt.down = true;
setTimeout(clearSingle, clickThreshold);
setTimeout(clearDouble, dblClickThreshold);
finished = true;
break; // we only need one match on mousedown
}
}
}
},
up = function (e) {
if (tt.down) {
var target = _t(e), currentTarget, pathInfo;
tt.taps++;
var tc = _touchCount(e);
for (var eventId in _tapProfiles) {
if (_tapProfiles.hasOwnProperty(eventId)) {
var p = _tapProfiles[eventId];
if (p.touches === tc && (p.taps === 1 || p.taps === tt.taps)) {
for (var i = 0; i < tt[eventId].length; i++) {
pathInfo = _pi(e, target, obj, tt[eventId][i][1] != null);
for (var pLoop = 0; pLoop < pathInfo.end; pLoop++) {
currentTarget = pathInfo.path[pLoop];
// this is a single event registration handler.
if (tt[eventId][i][1] == null || matchesSelector(currentTarget, tt[eventId][i][1], obj)) {
tt[eventId][i][0].apply(currentTarget, [ e ]);
break;
}
}
}
}
}
}
}
},
clearSingle = function () {
tt.down = false;
},
clearDouble = function () {
tt.taps = 0;
};
DefaultHandler(obj, "mousedown", down);
DefaultHandler(obj, "mouseup", up);
}
// add this child selector (it can be null, that's fine).
obj.__taTapHandler.downSelectors.push(children);
obj.__taTapHandler[evt].push([fn, children]);
// the unstore function removes this function from the object's listener list for this type.
fn.__taUnstore = function () {
_d(obj.__taTapHandler[evt], fn);
};
}
};
},
meeHelper = function (type, evt, obj, target) {
for (var i in obj.__tamee[type]) {
if (obj.__tamee[type].hasOwnProperty(i)) {
obj.__tamee[type][i].apply(target, [ evt ]);
}
}
},
MouseEnterExitHandler = function () {
var activeElements = [];
return function (obj, evt, fn, children) {
if (!obj.__tamee) {
// __tamee holds a flag saying whether the mouse is currently "in" the element, and a list of
// both mouseenter and mouseexit functions.
obj.__tamee = { over: false, mouseenter: [], mouseexit: [] };
// register over and out functions
var over = function (e) {
var t = _t(e);
if ((children == null && (t == obj && !obj.__tamee.over)) || (matchesSelector(t, children, obj) && (t.__tamee == null || !t.__tamee.over))) {
meeHelper("mouseenter", e, obj, t);
t.__tamee = t.__tamee || {};
t.__tamee.over = true;
activeElements.push(t);
}
},
out = function (e) {
var t = _t(e);
// is the current target one of the activeElements? and is the
// related target NOT a descendant of it?
for (var i = 0; i < activeElements.length; i++) {
if (t == activeElements[i] && !matchesSelector((e.relatedTarget || e.toElement), "*", t)) {
t.__tamee.over = false;
activeElements.splice(i, 1);
meeHelper("mouseexit", e, obj, t);
}
}
};
_bind(obj, "mouseover", _curryChildFilter(children, obj, over, "mouseover"), over);
_bind(obj, "mouseout", _curryChildFilter(children, obj, out, "mouseout"), out);
}
fn.__taUnstore = function () {
delete obj.__tamee[evt][fn.__tauid];
};
_store(obj, evt, fn);
obj.__tamee[evt][fn.__tauid] = fn;
};
},
isTouchDevice = "ontouchstart" in document.documentElement,
isMouseDevice = "onmousedown" in document.documentElement,
touchMap = { "mousedown": "touchstart", "mouseup": "touchend", "mousemove": "touchmove" },
touchstart = "touchstart", touchend = "touchend", touchmove = "touchmove",
iev = (function () {
var rv = -1;
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent,
re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv;
})(),
isIELT9 = iev > -1 && iev < 9,
_genLoc = function (e, prefix) {
if (e == null) return [ 0, 0 ];
var ts = _touches(e), t = _getTouch(ts, 0);
return [t[prefix + "X"], t[prefix + "Y"]];
},
_pageLocation = function (e) {
if (e == null) return [ 0, 0 ];
if (isIELT9) {
return [ e.clientX + document.documentElement.scrollLeft, e.clientY + document.documentElement.scrollTop ];
}
else {
return _genLoc(e, "page");
}
},
_screenLocation = function (e) {
return _genLoc(e, "screen");
},
_clientLocation = function (e) {
return _genLoc(e, "client");
},
_getTouch = function (touches, idx) {
return touches.item ? touches.item(idx) : touches[idx];
},
_touches = function (e) {
return e.touches && e.touches.length > 0 ? e.touches :
e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches :
e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches :
[ e ];
},
_touchCount = function (e) {
return _touches(e).length;
},
//http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
_bind = function (obj, type, fn, originalFn) {
_store(obj, type, fn);
originalFn.__tauid = fn.__tauid;
if (obj.addEventListener)
obj.addEventListener(type, fn, false);
else if (obj.attachEvent) {
var key = type + fn.__tauid;
obj["e" + key] = fn;
// TODO look at replacing with .call(..)
obj[key] = function () {
obj["e" + key] && obj["e" + key](window.event);
};
obj.attachEvent("on" + type, obj[key]);
}
},
_unbind = function (obj, type, fn) {
if (fn == null) return;
_each(obj, function () {
var _el = _gel(this);
_unstore(_el, type, fn);
// it has been bound if there is a tauid. otherwise it was not bound and we can ignore it.
if (fn.__tauid != null) {
if (_el.removeEventListener) {
_el.removeEventListener(type, fn, false);
if (isTouchDevice && touchMap[type]) _el.removeEventListener(touchMap[type], fn, false);
}
else if (this.detachEvent) {
var key = type + fn.__tauid;
_el[key] && _el.detachEvent("on" + type, _el[key]);
_el[key] = null;
_el["e" + key] = null;
}
}
// if a touch event was also registered, deregister now.
if (fn.__taTouchProxy) {
_unbind(obj, fn.__taTouchProxy[1], fn.__taTouchProxy[0]);
}
});
},
_each = function (obj, fn) {
if (obj == null) return;
// if a list (or list-like), use it. if a string, get a list
// by running the string through querySelectorAll. else, assume
// it's an Element.
// obj.top is "unknown" in IE8.
obj = (typeof Window !== "undefined" && (typeof obj.top !== "unknown" && obj == obj.top)) ? [ obj ] :
(typeof obj !== "string") && (obj.tagName == null && obj.length != null) ? obj :
typeof obj === "string" ? document.querySelectorAll(obj)
: [ obj ];
for (var i = 0; i < obj.length; i++)
fn.apply(obj[i]);
},
_uuid = function () {
return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}));
};
/**
* Mottle offers support for abstracting out the differences
* between touch and mouse devices, plus "smart click" functionality
* (don't fire click if the mouse has moved between mousedown and mouseup),
* and synthesized click/tap events.
* @class Mottle
* @constructor
* @param {Object} params Constructor params
* @param {Number} [params.clickThreshold=250] Threshold, in milliseconds beyond which a touchstart followed by a touchend is not considered to be a click.
* @param {Number} [params.dblClickThreshold=450] Threshold, in milliseconds beyond which two successive tap events are not considered to be a click.
* @param {Boolean} [params.smartClicks=false] If true, won't fire click events if the mouse has moved between mousedown and mouseup. Note that this functionality
* requires that Mottle consume the mousedown event, and so may not be viable in all use cases.
*/
root.Mottle = function (params) {
params = params || {};
var clickThreshold = params.clickThreshold || 250,
dblClickThreshold = params.dblClickThreshold || 450,
mouseEnterExitHandler = new MouseEnterExitHandler(),
tapHandler = new TapHandler(clickThreshold, dblClickThreshold),
_smartClicks = params.smartClicks,
_doBind = function (obj, evt, fn, children) {
if (fn == null) return;
_each(obj, function () {
var _el = _gel(this);
if (_smartClicks && evt === "click")
SmartClickHandler(_el, evt, fn, children);
else if (evt === "tap" || evt === "dbltap" || evt === "contextmenu") {
tapHandler(_el, evt, fn, children);
}
else if (evt === "mouseenter" || evt == "mouseexit")
mouseEnterExitHandler(_el, evt, fn, children);
else
DefaultHandler(_el, evt, fn, children);
});
};
/**
* Removes an element from the DOM, and deregisters all event handlers for it. You should use this
* to ensure you don't leak memory.
* @method remove
* @param {String|Element} el Element, or id of the element, to remove.
* @return {Mottle} The current Mottle instance; you can chain this method.
*/
this.remove = function (el) {
_each(el, function () {
var _el = _gel(this);
if (_el.__ta) {
for (var evt in _el.__ta) {
if (_el.__ta.hasOwnProperty(evt)) {
for (var h in _el.__ta[evt]) {
if (_el.__ta[evt].hasOwnProperty(h))
_unbind(_el, evt, _el.__ta[evt][h]);
}
}
}
}
_el.parentNode && _el.parentNode.removeChild(_el);
});
return this;
};
/**
* Register an event handler, optionally as a delegate for some set of descendant elements. Note
* that this method takes either 3 or 4 arguments - if you supply 3 arguments it is assumed you have
* omitted the `children` parameter, and that the event handler should be bound directly to the given element.
* @method on
* @param {Element[]|Element|String} el Either an Element, or a CSS spec for a list of elements, or an array of Elements.
* @param {String} [children] Comma-delimited list of selectors identifying allowed children.
* @param {String} event Event ID.
* @param {Function} fn Event handler function.
* @return {Mottle} The current Mottle instance; you can chain this method.
*/
this.on = function (el, event, children, fn) {
var _el = arguments[0],
_c = arguments.length == 4 ? arguments[2] : null,
_e = arguments[1],
_f = arguments[arguments.length - 1];
_doBind(_el, _e, _f, _c);
return this;
};
/**
* Cancel delegate event handling for the given function. Note that unlike with 'on' you do not supply
* a list of child selectors here: it removes event delegation from all of the child selectors for which the
* given function was registered (if any).
* @method off
* @param {Element[]|Element|String} el Element - or ID of element - from which to remove event listener.
* @param {String} event Event ID.
* @param {Function} fn Event handler function.
* @return {Mottle} The current Mottle instance; you can chain this method.
*/
this.off = function (el, event, fn) {
_unbind(el, event, fn);
return this;
};
/**
* Triggers some event for a given element.
* @method trigger
* @param {Element} el Element for which to trigger the event.
* @param {String} event Event ID.
* @param {Event} originalEvent The original event. Should be optional of course, but currently is not, due
* to the jsPlumb use case that caused this method to be added.
* @param {Object} [payload] Optional object to set as `payload` on the generated event; useful for message passing.
* @return {Mottle} The current Mottle instance; you can chain this method.
*/
this.trigger = function (el, event, originalEvent, payload) {
// MouseEvent undefined in old IE; that's how we know it's a mouse event. A fine Microsoft paradox.
var originalIsMouse = isMouseDevice && (typeof MouseEvent === "undefined" || originalEvent == null || originalEvent.constructor === MouseEvent);
var eventToBind = (isTouchDevice && !isMouseDevice && touchMap[event]) ? touchMap[event] : event,
bindingAMouseEvent = !(isTouchDevice && !isMouseDevice && touchMap[event]);
var pl = _pageLocation(originalEvent), sl = _screenLocation(originalEvent), cl = _clientLocation(originalEvent);
_each(el, function () {
var _el = _gel(this), evt;
originalEvent = originalEvent || {
screenX: sl[0],
screenY: sl[1],
clientX: cl[0],
clientY: cl[1]
};
var _decorate = function (_evt) {
if (payload) _evt.payload = payload;
};
var eventGenerators = {
"TouchEvent": function (evt) {
var touchList = _touchAndList(window, _el, 0, pl[0], pl[1], sl[0], sl[1], cl[0], cl[1]),
init = evt.initTouchEvent || evt.initEvent;
init(eventToBind, true, true, window, null, sl[0], sl[1],
cl[0], cl[1], false, false, false, false,
touchList, touchList, touchList, 1, 0);
},
"MouseEvents": function (evt) {
evt.initMouseEvent(eventToBind, true, true, window, 0,
sl[0], sl[1],
cl[0], cl[1],
false, false, false, false, 1, _el);
}
};
if (document.createEvent) {
var ite = !bindingAMouseEvent && !originalIsMouse && (isTouchDevice && touchMap[event]),
evtName = ite ? "TouchEvent" : "MouseEvents";
evt = document.createEvent(evtName);
eventGenerators[evtName](evt);
_decorate(evt);
_el.dispatchEvent(evt);
}
else if (document.createEventObject) {
evt = document.createEventObject();
evt.eventType = evt.eventName = eventToBind;
evt.screenX = sl[0];
evt.screenY = sl[1];
evt.clientX = cl[0];
evt.clientY = cl[1];
_decorate(evt);
_el.fireEvent('on' + eventToBind, evt);
}
});
return this;
}
};
/**
* Static method to assist in 'consuming' an element: uses `stopPropagation` where available, or sets
* `e.returnValue=false` where it is not.
* @method Mottle.consume
* @param {Event} e Event to consume
* @param {Boolean} [doNotPreventDefault=false] If true, does not call `preventDefault()` on the event.
*/
root.Mottle.consume = function (e, doNotPreventDefault) {
if (e.stopPropagation)
e.stopPropagation();
else
e.returnValue = false;
if (!doNotPreventDefault && e.preventDefault)
e.preventDefault();
};
/**
* Gets the page location corresponding to the given event. For touch events this means get the page location of the first touch.
* @method Mottle.pageLocation
* @param {Event} e Event to get page location for.
* @return {Number[]} [left, top] for the given event.
*/
root.Mottle.pageLocation = _pageLocation;
/**
* Forces touch events to be turned "on". Useful for testing: even if you don't have a touch device, you can still
* trigger a touch event when this is switched on and it will be captured and acted on.
* @method setForceTouchEvents
* @param {Boolean} value If true, force touch events to be on.
*/
root.Mottle.setForceTouchEvents = function (value) {
isTouchDevice = value;
};
/**
* Forces mouse events to be turned "on". Useful for testing: even if you don't have a mouse, you can still
* trigger a mouse event when this is switched on and it will be captured and acted on.
* @method setForceMouseEvents
* @param {Boolean} value If true, force mouse events to be on.
*/
root.Mottle.setForceMouseEvents = function (value) {
isMouseDevice = value;
};
root.Mottle.version = "0.8.0";
if (typeof exports !== "undefined") {
exports.Mottle = root.Mottle;
}
}).call(typeof window === "undefined" ? this : window);
/**
drag/drop functionality for use with jsPlumb but with
no knowledge of jsPlumb. supports multiple scopes (separated by whitespace), dragging
multiple elements, constrain to parent, drop filters, drag start filters, custom
css classes.
a lot of the functionality of this script is expected to be plugged in:
addClass
removeClass
addEvent
removeEvent
getPosition
setPosition
getSize
indexOf
intersects
the name came from here:
http://mrsharpoblunto.github.io/foswig.js/
copyright 2016 jsPlumb
*/
;(function() {
"use strict";
var root = this;
var _suggest = function(list, item, head) {
if (list.indexOf(item) === -1) {
head ? list.unshift(item) : list.push(item);
return true;
}
return false;
};
var _vanquish = function(list, item) {
var idx = list.indexOf(item);
if (idx !== -1) list.splice(idx, 1);
};
var _difference = function(l1, l2) {
var d = [];
for (var i = 0; i < l1.length; i++) {
if (l2.indexOf(l1[i]) === -1)
d.push(l1[i]);
}
return d;
};
var _isString = function(f) {
return f == null ? false : (typeof f === "string" || f.constructor === String);
};
var getOffsetRect = function (elem) {
// (1)
var box = elem.getBoundingClientRect(),
body = document.body,
docElem = document.documentElement,
// (2)
scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop,
scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft,
// (3)
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
// (4)
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: Math.round(top), left: Math.round(left) };
};
var matchesSelector = function(el, selector, ctx) {
ctx = ctx || el.parentNode;
var possibles = ctx.querySelectorAll(selector);
for (var i = 0; i < possibles.length; i++) {
if (possibles[i] === el)
return true;
}
return false;
};
var findDelegateElement = function(parentElement, childElement, selector) {
if (matchesSelector(childElement, selector, parentElement)) {
return childElement;
} else {
var currentParent = childElement.parentNode;
while (currentParent != null && currentParent !== parentElement) {
if (matchesSelector(currentParent, selector, parentElement)) {
return currentParent;
} else {
currentParent = currentParent.parentNode;
}
}
}
};
var iev = (function() {
var rv = -1;
if (navigator.appName === 'Microsoft Internet Explorer') {
var ua = navigator.userAgent,
re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv;
})(),
DEFAULT_GRID_X = 10,
DEFAULT_GRID_Y = 10,
isIELT9 = iev > -1 && iev < 9,
isIE9 = iev === 9,
_pl = function(e) {
if (isIELT9) {
return [ e.clientX + document.documentElement.scrollLeft, e.clientY + document.documentElement.scrollTop ];
}
else {
var ts = _touches(e), t = _getTouch(ts, 0);
// for IE9 pageX might be null if the event was synthesized. We try for pageX/pageY first,
// falling back to clientX/clientY if necessary. In every other browser we want to use pageX/pageY.
return isIE9 ? [t.pageX || t.clientX, t.pageY || t.clientY] : [t.pageX, t.pageY];
}
},
_getTouch = function(touches, idx) { return touches.item ? touches.item(idx) : touches[idx]; },
_touches = function(e) {
return e.touches && e.touches.length > 0 ? e.touches :
e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches :
e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches :
[ e ];
},
_classes = {
draggable:"katavorio-draggable", // draggable elements
droppable:"katavorio-droppable", // droppable elements
drag : "katavorio-drag", // elements currently being dragged
selected:"katavorio-drag-selected", // elements in current drag selection
active : "katavorio-drag-active", // droppables that are targets of a currently dragged element
hover : "katavorio-drag-hover", // droppables over which a matching drag element is hovering
noSelect : "katavorio-drag-no-select", // added to the body to provide a hook to suppress text selection
ghostProxy:"katavorio-ghost-proxy", // added to a ghost proxy element in use when a drag has exited the bounds of its parent.
clonedDrag:"katavorio-clone-drag" // added to a node that is a clone of an element created at the start of a drag
},
_defaultScope = "katavorio-drag-scope",
_events = [ "stop", "start", "drag", "drop", "over", "out", "beforeStart" ],
_devNull = function() {},
_true = function() { return true; },
_foreach = function(l, fn, from) {
for (var i = 0; i < l.length; i++) {
if (l[i] != from)
fn(l[i]);
}
},
_setDroppablesActive = function(dd, val, andHover, drag) {
_foreach(dd, function(e) {
e.setActive(val);
if (val) e.updatePosition();
if (andHover) e.setHover(drag, val);
});
},
_each = function(obj, fn) {
if (obj == null) return;
obj = !_isString(obj) && (obj.tagName == null && obj.length != null) ? obj : [ obj ];
for (var i = 0; i < obj.length; i++)
fn.apply(obj[i], [ obj[i] ]);
},
_consume = function(e) {
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
else {
e.returnValue = false;
}
},
_defaultInputFilterSelector = "input,textarea,select,button,option",
//
// filters out events on all input elements, like textarea, checkbox, input, select.
_inputFilter = function(e, el, _katavorio) {
var t = e.srcElement || e.target;
return !matchesSelector(t, _katavorio.getInputFilterSelector(), el);
};
var Super = function(el, params, css, scope) {
this.params = params || {};
this.el = el;
this.params.addClass(this.el, this._class);
this.uuid = _uuid();
var enabled = true;
this.setEnabled = function(e) { enabled = e; };
this.isEnabled = function() { return enabled; };
this.toggleEnabled = function() { enabled = !enabled; };
this.setScope = function(scopes) {
this.scopes = scopes ? scopes.split(/\s+/) : [ scope ];
};
this.addScope = function(scopes) {
var m = {};
_each(this.scopes, function(s) { m[s] = true;});
_each(scopes ? scopes.split(/\s+/) : [], function(s) { m[s] = true;});
this.scopes = [];
for (var i in m) this.scopes.push(i);
};
this.removeScope = function(scopes) {
var m = {};
_each(this.scopes, function(s) { m[s] = true;});
_each(scopes ? scopes.split(/\s+/) : [], function(s) { delete m[s];});
this.scopes = [];
for (var i in m) this.scopes.push(i);
};
this.toggleScope = function(scopes) {
var m = {};
_each(this.scopes, function(s) { m[s] = true;});
_each(scopes ? scopes.split(/\s+/) : [], function(s) {
if (m[s]) delete m[s];
else m[s] = true;
});
this.scopes = [];
for (var i in m) this.scopes.push(i);
};
this.setScope(params.scope);
this.k = params.katavorio;
return params.katavorio;
};
var TRUE = function() { return true; };
var FALSE = function() { return false; };
var Drag = function(el, params, css, scope) {
this._class = css.draggable;
var k = Super.apply(this, arguments);
this.rightButtonCanDrag = this.params.rightButtonCanDrag;
var downAt = [0,0], posAtDown = null, pagePosAtDown = null, pageDelta = [0,0], moving = false, initialScroll = [0,0],
consumeStartEvent = this.params.consumeStartEvent !== false,
dragEl = this.el,
clone = this.params.clone,
scroll = this.params.scroll,
_multipleDrop = params.multipleDrop !== false,
isConstrained = false,
useGhostProxy = params.ghostProxy === true ? TRUE : params.ghostProxy && typeof params.ghostProxy === "function" ? params.ghostProxy : FALSE,
ghostProxy = function(el) { return el.cloneNode(true); },
selector = params.selector,
elementToDrag = null;
var snapThreshold = params.snapThreshold,
_snap = function(pos, gridX, gridY, thresholdX, thresholdY) {
var _dx = Math.floor(pos[0] / gridX),
_dxl = gridX * _dx,
_dxt = _dxl + gridX,
_x = Math.abs(pos[0] - _dxl) <= thresholdX ? _dxl : Math.abs(_dxt - pos[0]) <= thresholdX ? _dxt : pos[0];
var _dy = Math.floor(pos[1] / gridY),
_dyl = gridY * _dy,
_dyt = _dyl + gridY,
_y = Math.abs(pos[1] - _dyl) <= thresholdY ? _dyl : Math.abs(_dyt - pos[1]) <= thresholdY ? _dyt : pos[1];
return [ _x, _y];
};
this.posses = [];
this.posseRoles = {};
this.toGrid = function(pos) {
if (this.params.grid == null) {
return pos;
}
else {
var tx = this.params.grid ? this.params.grid[0] / 2 : snapThreshold ? snapThreshold : DEFAULT_GRID_X / 2,
ty = this.params.grid ? this.params.grid[1] / 2 : snapThreshold ? snapThreshold : DEFAULT_GRID_Y / 2;
return _snap(pos, this.params.grid[0], this.params.grid[1], tx, ty);
}
};
this.snap = function(x, y) {
if (dragEl == null) return;
x = x || (this.params.grid ? this.params.grid[0] : DEFAULT_GRID_X);
y = y || (this.params.grid ? this.params.grid[1] : DEFAULT_GRID_Y);
var p = this.params.getPosition(dragEl),
tx = this.params.grid ? this.params.grid[0] / 2 : snapThreshold,
ty = this.params.grid ? this.params.grid[1] / 2 : snapThreshold;
this.params.setPosition(dragEl, _snap(p, x, y, tx, ty));
};
this.setUseGhostProxy = function(val) {
useGhostProxy = val ? TRUE : FALSE;
};
var constrain;
var negativeFilter = function(pos) {
return (params.allowNegative === false) ? [ Math.max (0, pos[0]), Math.max(0, pos[1]) ] : pos;
};
var _setConstrain = function(value) {
constrain = typeof value === "function" ? value : value ? function(pos, dragEl, _constrainRect, _size) {
return negativeFilter([
Math.max(0, Math.min(_constrainRect.w - _size[0], pos[0])),
Math.max(0, Math.min(_constrainRect.h - _size[1], pos[1]))
]);
}.bind(this) : function(pos) { return negativeFilter(pos); };
}.bind(this);
_setConstrain(typeof this.params.constrain === "function" ? this.params.constrain : (this.params.constrain || this.params.containment));
/**
* Sets whether or not the Drag is constrained. A value of 'true' means constrain to parent bounds; a function
* will be executed and returns true if the position is allowed.
* @param value
*/
this.setConstrain = function(value) {
_setConstrain(value);
};
var revertFunction;
/**
* Sets a function to call on drag stop, which, if it returns true, indicates that the given element should
* revert to its position before the previous drag.
* @param fn
*/
this.setRevert = function(fn) {
revertFunction = fn;
};
var _assignId = function(obj) {
if (typeof obj === "function") {
obj._katavorioId = _uuid();
return obj._katavorioId;
} else {
return obj;
}
},
// a map of { spec -> [ fn, exclusion ] } entries.
_filters = {},
_testFilter = function(e) {
for (var key in _filters) {
var f = _filters[key];
var rv = f[0](e);
if (f[1]) rv = !rv;
if (!rv) return false;
}
return true;
},
_setFilter = this.setFilter = function(f, _exclude) {
if (f) {
var key = _assignId(f);
_filters[key] = [
function(e) {
var t = e.srcElement || e.target, m;
if (_isString(f)) {
m = matchesSelector(t, f, el);
}
else if (typeof f === "function") {
m = f(e, el);
}
return m;
},
_exclude !== false
];
}
},
_addFilter = this.addFilter = _setFilter,
_removeFilter = this.removeFilter = function(f) {
var key = typeof f === "function" ? f._katavorioId : f;
delete _filters[key];
};
this.clearAllFilters = function() {
_filters = {};
};
this.canDrag = this.params.canDrag || _true;
var constrainRect,
matchingDroppables = [],
intersectingDroppables = [];
this.downListener = function(e) {
var isNotRightClick = this.rightButtonCanDrag || (e.which !== 3 && e.button !== 2);
if (isNotRightClick && this.isEnabled() && this.canDrag()) {
var _f = _testFilter(e) && _inputFilter(e, this.el, this.k);
if (_f) {
if (selector) {
elementToDrag = findDelegateElement(this.el, e.target || e.srcElement, selector);
if(elementToDrag == null) {
return;
}
}
else {
elementToDrag = this.el;
}
if (clone) {
dragEl = elementToDrag.cloneNode(true);
this.params.addClass(dragEl, _classes.clonedDrag);
dragEl.setAttribute("id", null);
dragEl.style.position = "absolute";
if (this.params.parent != null) {
var p = this.params.getPosition(this.el);
dragEl.style.left = p[0] + "px";
dragEl.style.top = p[1] + "px";
this.params.parent.appendChild(dragEl);
} else {
// the clone node is added to the body; getOffsetRect gives us a value
// relative to the body.
var b = getOffsetRect(elementToDrag);
dragEl.style.left = b.left + "px";
dragEl.style.top = b.top + "px";
document.body.appendChild(dragEl);
}
} else {
dragEl = elementToDrag;
}
consumeStartEvent && _consume(e);
downAt = _pl(e);
if (dragEl && dragEl.parentNode)
{
initialScroll = [dragEl.parentNode.scrollLeft, dragEl.parentNode.scrollTop];
}
//
this.params.bind(document, "mousemove", this.moveListener);
this.params.bind(document, "mouseup", this.upListener);
k.markSelection(this);
k.markPosses(this);
this.params.addClass(document.body, css.noSelect);
_dispatch("beforeStart", {el:this.el, pos:posAtDown, e:e, drag:this});
}
else if (this.params.consumeFilteredEvents) {
_consume(e);
}
}
}.bind(this);
this.moveListener = function(e) {
if (downAt) {
if (!moving) {
var _continue = _dispatch("start", {el:this.el, pos:posAtDown, e:e, drag:this});
if (_continue !== false) {
if (!downAt) {
return;
}
this.mark(true);
moving = true;
} else {
this.abort();
}
}
// it is possible that the start event caused the drag to be aborted. So we check
// again that we are currently dragging.
if (downAt) {
intersectingDroppables.length = 0;
var pos = _pl(e), dx = pos[0] - downAt[0], dy = pos[1] - downAt[1],
z = this.params.ignoreZoom ? 1 : k.getZoom();
if (dragEl && dragEl.parentNode)
{
dx += dragEl.parentNode.scrollLeft - initialScroll[0];
dy += dragEl.parentNode.scrollTop - initialScroll[1];
}
dx /= z;
dy /= z;
this.moveBy(dx, dy, e);
k.updateSelection(dx, dy, this);
k.updatePosses(dx, dy, this);
}
}
}.bind(this);
this.upListener = function(e) {
if (downAt) {
downAt = null;
this.params.unbind(document, "mousemove", this.moveListener);
this.params.unbind(document, "mouseup", this.upListener);
this.params.removeClass(document.body, css.noSelect);
this.unmark(e);
k.unmarkSelection(this, e);
k.unmarkPosses(this, e);
this.stop(e);
//k.notifySelectionDragStop(this, e); removed in 1.1.0 under the "leave it for one release in case it breaks" rule.
// it isnt necessary to fire this as the normal stop event now includes a `selection` member that has every dragged element.
// firing this event causes consumers who use the `selection` array to process a lot more drag stop events than is necessary
k.notifyPosseDragStop(this, e);
moving = false;
if (clone) {
dragEl && dragEl.parentNode && dragEl.parentNode.removeChild(dragEl);
dragEl = null;
}
intersectingDroppables.length = 0;
if (revertFunction && revertFunction(this.el, this.params.getPosition(this.el)) === true) {
this.params.setPosition(this.el, posAtDown);
_dispatch("revert", this.el);
}
}
}.bind(this);
this.getFilters = function() { return _filters; };
this.abort = function() {
if (downAt != null) {
this.upListener();
}
};
/**
* Returns the element that was last dragged. This may be some original element from the DOM, or if `clone` is
* set, then its actually a copy of some original DOM element. In some client calls to this method, it is the
* actual element that was dragged that is desired. In others, it is the original DOM element that the user
* wishes to get - in which case, pass true for `retrieveOriginalElement`.
*
* @returns {*}
*/
this.getDragElement = function(retrieveOriginalElement) {
return retrieveOriginalElement ? elementToDrag || this.el : dragEl || this.el;
};
var listeners = {"start":[], "drag":[], "stop":[], "over":[], "out":[], "beforeStart":[], "revert":[] };
if (params.events.start) listeners.start.push(params.events.start);
if (params.events.beforeStart) listeners.beforeStart.push(params.events.beforeStart);
if (params.events.stop) listeners.stop.push(params.events.stop);
if (params.events.drag) listeners.drag.push(params.events.drag);
if (params.events.revert) listeners.revert.push(params.events.revert);
this.on = function(evt, fn) {
if (listeners[evt]) listeners[evt].push(fn);
};
this.off = function(evt, fn) {
if (listeners[evt]) {
var l = [];
for (var i = 0; i < listeners[evt].length; i++) {
if (listeners[evt][i] !== fn) l.push(listeners[evt][i]);
}
listeners[evt] = l;
}
};
var _dispatch = function(evt, value) {
var result = null;
if (listeners[evt]) {
for (var i = 0; i < listeners[evt].length; i++) {
try {
var v = listeners[evt][i](value);
if (v != null) {
result = v;
}
}
catch (e) { }
}
}
return result;
};
this.notifyStart = function(e) {
_dispatch("start", {el:this.el, pos:this.params.getPosition(dragEl), e:e, drag:this});
};
this.stop = function(e, force) {
if (force || moving) {
var positions = [],
sel = k.getSelection(),
dPos = this.params.getPosition(dragEl);
if (sel.length > 1) {
for (var i = 0; i < sel.length; i++) {
var p = this.params.getPosition(sel[i].el);
positions.push([ sel[i].el, { left: p[0], top: p[1] }, sel[i] ]);
}
}
else {
positions.push([ dragEl, {left:dPos[0], top:dPos[1]}, this ]);
}
_dispatch("stop", {
el: dragEl,
pos: ghostProxyOffsets || dPos,
finalPos:dPos,
e: e,
drag: this,
selection:positions
});
}
};
this.mark = function(andNotify) {
posAtDown = this.params.getPosition(dragEl);
pagePosAtDown = this.params.getPosition(dragEl, true);
pageDelta = [pagePosAtDown[0] - posAtDown[0], pagePosAtDown[1] - posAtDown[1]];
this.size = this.params.getSize(dragEl);
matchingDroppables = k.getMatchingDroppables(this);
_setDroppablesActive(matchingDroppables, true, false, this);
this.params.addClass(dragEl, this.params.dragClass || css.drag);
var cs;
if (this.params.getConstrainingRectangle) {
cs = this.params.getConstrainingRectangle(dragEl)
} else {
cs = this.params.getSize(dragEl.parentNode);
}
constrainRect = {w: cs[0], h: cs[1]};
if (andNotify) {
k.notifySelectionDragStart(this);
}
};
var ghostProxyOffsets;
this.unmark = function(e, doNotCheckDroppables) {
_setDroppablesActive(matchingDroppables, false, true, this);
if (isConstrained && useGhostProxy(elementToDrag)) {
ghostProxyOffsets = [dragEl.offsetLeft, dragEl.offsetTop];
elementToDrag.parentNode.removeChild(dragEl);
dragEl = elementToDrag;
}
else {
ghostProxyOffsets = null;
}
this.params.removeClass(dragEl, this.params.dragClass || css.drag);
matchingDroppables.length = 0;
isConstrained = false;
if (!doNotCheckDroppables) {
if (intersectingDroppables.length > 0 && ghostProxyOffsets) {
params.setPosition(elementToDrag, ghostProxyOffsets);
}
intersectingDroppables.sort(_rankSort);
for (var i = 0; i < intersectingDroppables.length; i++) {
var retVal = intersectingDroppables[i].drop(this, e);
if (retVal === true) break;
}
}
};
this.moveBy = function(dx, dy, e) {
intersectingDroppables.length = 0;
var desiredLoc = this.toGrid([posAtDown[0] + dx, posAtDown[1] + dy]),
cPos = constrain(desiredLoc, dragEl, constrainRect, this.size);
if (useGhostProxy(this.el)) {
if (desiredLoc[0] !== cPos[0] || desiredLoc[1] !== cPos[1]) {
if (!isConstrained) {
var gp = ghostProxy(elementToDrag);
params.addClass(gp, _classes.ghostProxy);
elementToDrag.parentNode.appendChild(gp);
dragEl = gp;
isConstrained = true;
}
cPos = desiredLoc;
}
else {
if (isConstrained) {
elementToDrag.parentNode.removeChild(dragEl);
dragEl = elementToDrag;
isConstrained = false;
}
}
}
var rect = { x:cPos[0], y:cPos[1], w:this.size[0], h:this.size[1]},
pageRect = { x:rect.x + pageDelta[0], y:rect.y + pageDelta[1], w:rect.w, h:rect.h},
focusDropElement = null;
this.params.setPosition(dragEl, cPos);
for (var i = 0; i < matchingDroppables.length; i++) {
var r2 = { x:matchingDroppables[i].pagePosition[0], y:matchingDroppables[i].pagePosition[1], w:matchingDroppables[i].size[0], h:matchingDroppables[i].size[1]};
if (this.params.intersects(pageRect, r2) && (_multipleDrop || focusDropElement == null || focusDropElement === matchingDroppables[i].el) && matchingDroppables[i].canDrop(this)) {
if (!focusDropElement) focusDropElement = matchingDroppables[i].el;
intersectingDroppables.push(matchingDroppables[i]);
matchingDroppables[i].setHover(this, true, e);
}
else if (matchingDroppables[i].isHover()) {
matchingDroppables[i].setHover(this, false, e);
}
}
_dispatch("drag", {el:this.el, pos:cPos, e:e, drag:this});
/* test to see if the parent needs to be scrolled (future)
if (scroll) {
var pnsl = dragEl.parentNode.scrollLeft, pnst = dragEl.parentNode.scrollTop;
console.log("scroll!", pnsl, pnst);
}*/
};
this.destroy = function() {
this.params.unbind(this.el, "mousedown", this.downListener);
this.params.unbind(document, "mousemove", this.moveListener);
this.params.unbind(document, "mouseup", this.upListener);
this.downListener = null;
this.upListener = null;
this.moveListener = null;
};
// init:register mousedown, and perhaps set a filter
this.params.bind(this.el, "mousedown", this.downListener);
// if handle provded, use that. otherwise, try to set a filter.
// note that a `handle` selector always results in filterExclude being set to false, ie.
// the selector defines the handle element(s).
if (this.params.handle)
_setFilter(this.params.handle, false);
else
_setFilter(this.params.filter, this.params.filterExclude);
};
var Drop = function(el, params, css, scope) {
this._class = css.droppable;
this.params = params || {};
this.rank = params.rank || 0;
this._activeClass = this.params.activeClass || css.active;
this._hoverClass = this.params.hoverClass || css.hover;
Super.apply(this, arguments);
var hover = false;
this.allowLoopback = this.params.allowLoopback !== false;
this.setActive = function(val) {
this.params[val ? "addClass" : "removeClass"](this.el, this._activeClass);
};
this.updatePosition = function() {
this.position = this.params.getPosition(this.el);
this.pagePosition = this.params.getPosition(this.el, true);
this.size = this.params.getSize(this.el);
};
this.canDrop = this.params.canDrop || function(drag) {
return true;
};
this.isHover = function() { return hover; };
this.setHover = function(drag, val, e) {
// if turning off hover but this was not the drag that caused the hover, ignore.
if (val || this.el._katavorioDragHover == null || this.el._katavorioDragHover === drag.el._katavorio) {
this.params[val ? "addClass" : "removeClass"](this.el, this._hoverClass);
this.el._katavorioDragHover = val ? drag.el._katavorio : null;
if (hover !== val) {
this.params.events[val ? "over" : "out"]({el: this.el, e: e, drag: drag, drop: this});
}
hover = val;
}
};
/**
* A drop event. `drag` is the corresponding Drag object, which may be a Drag for some specific element, or it
* may be a Drag on some element acting as a delegate for elements contained within it.
* @param drag
* @param event
* @returns {*}
*/
this.drop = function(drag, event) {
return this.params.events["drop"]({ drag:drag, e:event, drop:this });
};
this.destroy = function() {
this._class = null;
this._activeClass = null;
this._hoverClass = null;
hover = null;
};
};
var _uuid = function() {
return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
}));
};
var _rankSort = function(a,b) {
return a.rank < b.rank ? 1 : a.rank > b.rank ? -1 : 0;
};
var _gel = function(el) {
if (el == null) return null;
el = (typeof el === "string" || el.constructor === String) ? document.getElementById(el) : el;
if (el == null) return null;
el._katavorio = el._katavorio || _uuid();
return el;
};
root.Katavorio = function(katavorioParams) {
var _selection = [],
_selectionMap = {};
this._dragsByScope = {};
this._dropsByScope = {};
var _zoom = 1,
_reg = function(obj, map) {
_each(obj, function(_obj) {
for(var i = 0; i < _obj.scopes.length; i++) {
map[_obj.scopes[i]] = map[_obj.scopes[i]] || [];
map[_obj.scopes[i]].push(_obj);
}
});
},
_unreg = function(obj, map) {
var c = 0;
_each(obj, function(_obj) {
for(var i = 0; i < _obj.scopes.length; i++) {
if (map[_obj.scopes[i]]) {
var idx = katavorioParams.indexOf(map[_obj.scopes[i]], _obj);
if (idx !== -1) {
map[_obj.scopes[i]].splice(idx, 1);
c++;
}
}
}
});
return c > 0 ;
},
_getMatchingDroppables = this.getMatchingDroppables = function(drag) {
var dd = [], _m = {};
for (var i = 0; i < drag.scopes.length; i++) {
var _dd = this._dropsByScope[drag.scopes[i]];
if (_dd) {
for (var j = 0; j < _dd.length; j++) {
if (_dd[j].canDrop(drag) && !_m[_dd[j].uuid] && (_dd[j].allowLoopback || _dd[j].el !== drag.el)) {
_m[_dd[j].uuid] = true;
dd.push(_dd[j]);
}
}
}
}
dd.sort(_rankSort);
return dd;
},
_prepareParams = function(p) {
p = p || {};
var _p = {
events:{}
}, i;
for (i in katavorioParams) _p[i] = katavorioParams[i];
for (i in p) _p[i] = p[i];
// events
for (i = 0; i < _events.length; i++) {
_p.events[_events[i]] = p[_events[i]] || _devNull;
}
_p.katavorio = this;
return _p;
}.bind(this),
_mistletoe = function(existingDrag, params) {
for (var i = 0; i < _events.length; i++) {
if (params[_events[i]]) {
existingDrag.on(_events[i], params[_events[i]]);
}
}
}.bind(this),
_css = {},
overrideCss = katavorioParams.css || {},
_scope = katavorioParams.scope || _defaultScope;
// prepare map of css classes based on defaults frst, then optional overrides
for (var i in _classes) _css[i] = _classes[i];
for (var i in overrideCss) _css[i] = overrideCss[i];
var inputFilterSelector = katavorioParams.inputFilterSelector || _defaultInputFilterSelector;
/**
* Gets the selector identifying which input elements to filter from drag events.
* @method getInputFilterSelector
* @return {String} Current input filter selector.
*/
this.getInputFilterSelector = function() { return inputFilterSelector; };
/**
* Sets the selector identifying which input elements to filter from drag events.
* @method setInputFilterSelector
* @param {String} selector Input filter selector to set.
* @return {Katavorio} Current instance; method may be chained.
*/
this.setInputFilterSelector = function(selector) {
inputFilterSelector = selector;
return this;
};
/**
* Either makes the given element draggable, or identifies it as an element inside which some identified list
* of elements may be draggable.
* @param el
* @param params
* @returns {Array}
*/
this.draggable = function(el, params) {
var o = [];
_each(el, function (_el) {
_el = _gel(_el);
if (_el != null) {
if (_el._katavorioDrag == null) {
var p = _prepareParams(params);
_el._katavorioDrag = new Drag(_el, p, _css, _scope);
_reg(_el._katavorioDrag, this._dragsByScope);
o.push(_el._katavorioDrag);
katavorioParams.addClass(_el, _css.draggable);
}
else {
_mistletoe(_el._katavorioDrag, params);
}
}
}.bind(this));
return o;
};
this.droppable = function(el, params) {
var o = [];
_each(el, function(_el) {
_el = _gel(_el);
if (_el != null) {
var drop = new Drop(_el, _prepareParams(params), _css, _scope);
_el._katavorioDrop = _el._katavorioDrop || [];
_el._katavorioDrop.push(drop);
_reg(drop, this._dropsByScope);
o.push(drop);
katavorioParams.addClass(_el, _css.droppable);
}
}.bind(this));
return o;
};
/**
* @name Katavorio#select
* @function
* @desc Adds an element to the current selection (for multiple node drag)
* @param {Element|String} DOM element - or id of the element - to add.
*/
this.select = function(el) {
_each(el, function() {
var _el = _gel(this);
if (_el && _el._katavorioDrag) {
if (!_selectionMap[_el._katavorio]) {
_selection.push(_el._katavorioDrag);
_selectionMap[_el._katavorio] = [ _el, _selection.length - 1 ];
katavorioParams.addClass(_el, _css.selected);
}
}
});
return this;
};
/**
* @name Katavorio#deselect
* @function
* @desc Removes an element from the current selection (for multiple node drag)
* @param {Element|String} DOM element - or id of the element - to remove.
*/
this.deselect = function(el) {
_each(el, function() {
var _el = _gel(this);
if (_el && _el._katavorio) {
var e = _selectionMap[_el._katavorio];
if (e) {
var _s = [];
for (var i = 0; i < _selection.length; i++)
if (_selection[i].el !== _el) _s.push(_selection[i]);
_selection = _s;
delete _selectionMap[_el._katavorio];
katavorioParams.removeClass(_el, _css.selected);
}
}
});
return this;
};
this.deselectAll = function() {
for (var i in _selectionMap) {
var d = _selectionMap[i];
katavorioParams.removeClass(d[0], _css.selected);
}
_selection.length = 0;
_selectionMap = {};
};
this.markSelection = function(drag) {
_foreach(_selection, function(e) { e.mark(); }, drag);
};
this.markPosses = function(drag) {
if (drag.posses) {
_each(drag.posses, function(p) {
if (drag.posseRoles[p] && _posses[p]) {
_foreach(_posses[p].members, function (d) {
d.mark();
}, drag);
}
})
}
};
this.unmarkSelection = function(drag, event) {
_foreach(_selection, function(e) { e.unmark(event); }, drag);
};
this.unmarkPosses = function(drag, event) {
if (drag.posses) {
_each(drag.posses, function(p) {
if (drag.posseRoles[p] && _posses[p]) {
_foreach(_posses[p].members, function (d) {
d.unmark(event, true);
}, drag);
}
});
}
};
this.getSelection = function() { return _selection.slice(0); };
this.updateSelection = function(dx, dy, drag) {
_foreach(_selection, function(e) { e.moveBy(dx, dy); }, drag);
};
var _posseAction = function(fn, drag) {
if (drag.posses) {
_each(drag.posses, function(p) {
if (drag.posseRoles[p] && _posses[p]) {
_foreach(_posses[p].members, function (e) {
fn(e);
}, drag);
}
});
}
};
this.updatePosses = function(dx, dy, drag) {
_posseAction(function(e) { e.moveBy(dx, dy); }, drag);
};
this.notifyPosseDragStop = function(drag, evt) {
_posseAction(function(e) { e.stop(evt, true); }, drag);
};
this.notifySelectionDragStop = function(drag, evt) {
_foreach(_selection, function(e) { e.stop(evt, true); }, drag);
};
this.notifySelectionDragStart = function(drag, evt) {
_foreach(_selection, function(e) { e.notifyStart(evt);}, drag);
};
this.setZoom = function(z) { _zoom = z; };
this.getZoom = function() { return _zoom; };
// does the work of changing scopes
var _scopeManip = function(kObj, scopes, map, fn) {
_each(kObj, function(_kObj) {
_unreg(_kObj, map); // deregister existing scopes
_kObj[fn](scopes); // set scopes
_reg(_kObj, map); // register new ones
});
};
_each([ "set", "add", "remove", "toggle"], function(v) {
this[v + "Scope"] = function(el, scopes) {
_scopeManip(el._katavorioDrag, scopes, this._dragsByScope, v + "Scope");
_scopeManip(el._katavorioDrop, scopes, this._dropsByScope, v + "Scope");
}.bind(this);
this[v + "DragScope"] = function(el, scopes) {
_scopeManip(el.constructor === Drag ? el : el._katavorioDrag, scopes, this._dragsByScope, v + "Scope");
}.bind(this);
this[v + "DropScope"] = function(el, scopes) {
_scopeManip(el.constructor === Drop ? el : el._katavorioDrop, scopes, this._dropsByScope, v + "Scope");
}.bind(this);
}.bind(this));
this.snapToGrid = function(x, y) {
for (var s in this._dragsByScope) {
_foreach(this._dragsByScope[s], function(d) { d.snap(x, y); });
}
};
this.getDragsForScope = function(s) { return this._dragsByScope[s]; };
this.getDropsForScope = function(s) { return this._dropsByScope[s]; };
var _destroy = function(el, type, map) {
el = _gel(el);
if (el[type]) {
// remove from selection, if present.
var selIdx = _selection.indexOf(el[type]);
if (selIdx >= 0) {
_selection.splice(selIdx, 1);
}
if (_unreg(el[type], map)) {
_each(el[type], function(kObj) { kObj.destroy() });
}
delete el[type];
}
};
var _removeListener = function(el, type, evt, fn) {
el = _gel(el);
if (el[type]) {
el[type].off(evt, fn);
}
};
this.elementRemoved = function(el) {
this.destroyDraggable(el);
this.destroyDroppable(el);
};
/**
* Either completely remove drag functionality from the given element, or remove a specific event handler. If you
* call this method with a single argument - the element - all drag functionality is removed from it. Otherwise, if
* you provide an event name and listener function, this function is de-registered (if found).
* @param el Element to update
* @param {string} [evt] Optional event name to unsubscribe
* @param {Function} [fn] Optional function to unsubscribe
*/
this.destroyDraggable = function(el, evt, fn) {
if (arguments.length === 1) {
_destroy(el, "_katavorioDrag", this._dragsByScope);
} else {
_removeListener(el, "_katavorioDrag", evt, fn);
}
};
/**
* Either completely remove drop functionality from the given element, or remove a specific event handler. If you
* call this method with a single argument - the element - all drop functionality is removed from it. Otherwise, if
* you provide an event name and listener function, this function is de-registered (if found).
* @param el Element to update
* @param {string} [evt] Optional event name to unsubscribe
* @param {Function} [fn] Optional function to unsubscribe
*/
this.destroyDroppable = function(el, evt, fn) {
if (arguments.length === 1) {
_destroy(el, "_katavorioDrop", this._dropsByScope);
} else {
_removeListener(el, "_katavorioDrop", evt, fn);
}
};
this.reset = function() {
this._dragsByScope = {};
this._dropsByScope = {};
_selection = [];
_selectionMap = {};
_posses = {};
};
// ----- groups
var _posses = {};
var _processOneSpec = function(el, _spec, dontAddExisting) {
var posseId = _isString(_spec) ? _spec : _spec.id;
var active = _isString(_spec) ? true : _spec.active !== false;
var posse = _posses[posseId] || (function() {
var g = {name:posseId, members:[]};
_posses[posseId] = g;
return g;
})();
_each(el, function(_el) {
if (_el._katavorioDrag) {
if (dontAddExisting && _el._katavorioDrag.posseRoles[posse.name] != null) return;
_suggest(posse.members, _el._katavorioDrag);
_suggest(_el._katavorioDrag.posses, posse.name);
_el._katavorioDrag.posseRoles[posse.name] = active;
}
});
return posse;
};
/**
* Add the given element to the posse with the given id, creating the group if it at first does not exist.
* @method addToPosse
* @param {Element} el Element to add.
* @param {String...|Object...} spec Variable args parameters. Each argument can be a either a String, indicating
* the ID of a Posse to which the element should be added as an active participant, or an Object containing
* `{ id:"posseId", active:false/true}`. In the latter case, if `active` is not provided it is assumed to be
* true.
* @returns {Posse|Posse[]} The Posse(s) to which the element(s) was/were added.
*/
this.addToPosse = function(el, spec) {
var posses = [];
for (var i = 1; i < arguments.length; i++) {
posses.push(_processOneSpec(el, arguments[i]));
}
return posses.length === 1 ? posses[0] : posses;
};
/**
* Sets the posse(s) for the element with the given id, creating those that do not yet exist, and removing from
* the element any current Posses that are not specified by this method call. This method will not change the
* active/passive state if it is given a posse in which the element is already a member.
* @method setPosse
* @param {Element} el Element to set posse(s) on.
* @param {String...|Object...} spec Variable args parameters. Each argument can be a either a String, indicating
* the ID of a Posse to which the element should be added as an active participant, or an Object containing
* `{ id:"posseId", active:false/true}`. In the latter case, if `active` is not provided it is assumed to be
* true.
* @returns {Posse|Posse[]} The Posse(s) to which the element(s) now belongs.
*/
this.setPosse = function(el, spec) {
var posses = [];
for (var i = 1; i < arguments.length; i++) {
posses.push(_processOneSpec(el, arguments[i], true).name);
}
_each(el, function(_el) {
if (_el._katavorioDrag) {
var diff = _difference(_el._katavorioDrag.posses, posses);
var p = [];
Array.prototype.push.apply(p, _el._katavorioDrag.posses);
for (var i = 0; i < diff.length; i++) {
this.removeFromPosse(_el, diff[i]);
}
}
}.bind(this));
return posses.length === 1 ? posses[0] : posses;
};
/**
* Remove the given element from the given posse(s).
* @method removeFromPosse
* @param {Element} el Element to remove.
* @param {String...} posseId Varargs parameter: one value for each posse to remove the element from.
*/
this.removeFromPosse = function(el, posseId) {
if (arguments.length < 2) throw new TypeError("No posse id provided for remove operation");
for(var i = 1; i < arguments.length; i++) {
posseId = arguments[i];
_each(el, function (_el) {
if (_el._katavorioDrag && _el._katavorioDrag.posses) {
var d = _el._katavorioDrag;
_each(posseId, function (p) {
_vanquish(_posses[p].members, d);
_vanquish(d.posses, p);
delete d.posseRoles[p];
});
}
});
}
};
/**
* Remove the given element from all Posses to which it belongs.
* @method removeFromAllPosses
* @param {Element|Element[]} el Element to remove from Posses.
*/
this.removeFromAllPosses = function(el) {
_each(el, function(_el) {
if (_el._katavorioDrag && _el._katavorioDrag.posses) {
var d = _el._katavorioDrag;
_each(d.posses, function(p) {
_vanquish(_posses[p].members, d);
});
d.posses.length = 0;
d.posseRoles = {};
}
});
};
/**
* Changes the participation state for the element in the Posse with the given ID.
* @param {Element|Element[]} el Element(s) to change state for.
* @param {String} posseId ID of the Posse to change element state for.
* @param {Boolean} state True to make active, false to make passive.
*/
this.setPosseState = function(el, posseId, state) {
var posse = _posses[posseId];
if (posse) {
_each(el, function(_el) {
if (_el._katavorioDrag && _el._katavorioDrag.posses) {
_el._katavorioDrag.posseRoles[posse.name] = state;
}
});
}
};
};
root.Katavorio.version = "1.0.0";
if (typeof exports !== "undefined") {
exports.Katavorio = root.Katavorio;
}
}).call(typeof window !== 'undefined' ? window : this);
(function() {
var root = this;
root.jsPlumbUtil = root.jsPlumbUtil || {};
var jsPlumbUtil = root.jsPlumbUtil;
if (typeof exports !=='undefined') { exports.jsPlumbUtil = jsPlumbUtil;}
function isArray(a) {
return Object.prototype.toString.call(a) === "[object Array]";
}
jsPlumbUtil.isArray = isArray;
function isNumber(n) {
return Object.prototype.toString.call(n) === "[object Number]";
}
jsPlumbUtil.isNumber = isNumber;
function isString(s) {
return typeof s === "string";
}
jsPlumbUtil.isString = isString;
function isBoolean(s) {
return typeof s === "boolean";
}
jsPlumbUtil.isBoolean = isBoolean;
function isNull(s) {
return s == null;
}
jsPlumbUtil.isNull = isNull;
function isObject(o) {
return o == null ? false : Object.prototype.toString.call(o) === "[object Object]";
}
jsPlumbUtil.isObject = isObject;
function isDate(o) {
return Object.prototype.toString.call(o) === "[object Date]";
}
jsPlumbUtil.isDate = isDate;
function isFunction(o) {
return Object.prototype.toString.call(o) === "[object Function]";
}
jsPlumbUtil.isFunction = isFunction;
function isNamedFunction(o) {
return isFunction(o) && o.name != null && o.name.length > 0;
}
jsPlumbUtil.isNamedFunction = isNamedFunction;
function isEmpty(o) {
for (var i in o) {
if (o.hasOwnProperty(i)) {
return false;
}
}
return true;
}
jsPlumbUtil.isEmpty = isEmpty;
function clone(a) {
if (isString(a)) {
return "" + a;
}
else if (isBoolean(a)) {
return !!a;
}
else if (isDate(a)) {
return new Date(a.getTime());
}
else if (isFunction(a)) {
return a;
}
else if (isArray(a)) {
var b = [];
for (var i = 0; i < a.length; i++) {
b.push(clone(a[i]));
}
return b;
}
else if (isObject(a)) {
var c = {};
for (var j in a) {
c[j] = clone(a[j]);
}
return c;
}
else {
return a;
}
}
jsPlumbUtil.clone = clone;
function merge(a, b, collations, overwrites) {
// first change the collations array - if present - into a lookup table, because its faster.
var cMap = {}, ar, i, oMap = {};
collations = collations || [];
overwrites = overwrites || [];
for (i = 0; i < collations.length; i++) {
cMap[collations[i]] = true;
}
for (i = 0; i < overwrites.length; i++) {
oMap[overwrites[i]] = true;
}
var c = clone(a);
for (i in b) {
if (c[i] == null || oMap[i]) {
c[i] = b[i];
}
else if (isString(b[i]) || isBoolean(b[i])) {
if (!cMap[i]) {
c[i] = b[i]; // if we dont want to collate, just copy it in.
}
else {
ar = [];
// if c's object is also an array we can keep its values.
ar.push.apply(ar, isArray(c[i]) ? c[i] : [c[i]]);
ar.push.apply(ar, isBoolean(b[i]) ? b[i] : [b[i]]);
c[i] = ar;
}
}
else {
if (isArray(b[i])) {
ar = [];
// if c's object is also an array we can keep its values.
if (isArray(c[i])) {
ar.push.apply(ar, c[i]);
}
ar.push.apply(ar, b[i]);
c[i] = ar;
}
else if (isObject(b[i])) {
// overwrite c's value with an object if it is not already one.
if (!isObject(c[i])) {
c[i] = {};
}
for (var j in b[i]) {
c[i][j] = b[i][j];
}
}
}
}
return c;
}
jsPlumbUtil.merge = merge;
function replace(inObj, path, value) {
if (inObj == null) {
return;
}
var q = inObj, t = q;
path.replace(/([^\.])+/g, function (term, lc, pos, str) {
var array = term.match(/([^\[0-9]+){1}(\[)([0-9+])/), last = pos + term.length >= str.length, _getArray = function () {
return t[array[1]] || (function () {
t[array[1]] = [];
return t[array[1]];
})();
};
if (last) {
// set term = value on current t, creating term as array if necessary.
if (array) {
_getArray()[array[3]] = value;
}
else {
t[term] = value;
}
}
else {
// set to current t[term], creating t[term] if necessary.
if (array) {
var a_1 = _getArray();
t = a_1[array[3]] || (function () {
a_1[array[3]] = {};
return a_1[array[3]];
})();
}
else {
t = t[term] || (function () {
t[term] = {};
return t[term];
})();
}
}
return "";
});
return inObj;
}
jsPlumbUtil.replace = replace;
//
// chain a list of functions, supplied by [ object, method name, args ], and return on the first
// one that returns the failValue. if none return the failValue, return the successValue.
//
function functionChain(successValue, failValue, fns) {
for (var i = 0; i < fns.length; i++) {
var o = fns[i][0][fns[i][1]].apply(fns[i][0], fns[i][2]);
if (o === failValue) {
return o;
}
}
return successValue;
}
jsPlumbUtil.functionChain = functionChain;
/**
*
* Take the given model and expand out any parameters. 'functionPrefix' is optional, and if present, helps jsplumb figure out what to do if a value is a Function.
* if you do not provide it (and doNotExpandFunctions is null, or false), jsplumb will run the given values through any functions it finds, and use the function's
* output as the value in the result. if you do provide the prefix, only functions that are named and have this prefix
* will be executed; other functions will be passed as values to the output.
*
* @param model
* @param values
* @param functionPrefix
* @param doNotExpandFunctions
* @returns {any}
*/
function populate(model, values, functionPrefix, doNotExpandFunctions) {
// for a string, see if it has parameter matches, and if so, try to make the substitutions.
var getValue = function (fromString) {
var matches = fromString.match(/(\${.*?})/g);
if (matches != null) {
for (var i = 0; i < matches.length; i++) {
var val = values[matches[i].substring(2, matches[i].length - 1)] || "";
if (val != null) {
fromString = fromString.replace(matches[i], val);
}
}
}
return fromString;
};
// process one entry.
var _one = function (d) {
if (d != null) {
if (isString(d)) {
return getValue(d);
}
else if (isFunction(d) && !doNotExpandFunctions && (functionPrefix == null || (d.name || "").indexOf(functionPrefix) === 0)) {
return d(values);
}
else if (isArray(d)) {
var r = [];
for (var i = 0; i < d.length; i++) {
r.push(_one(d[i]));
}
return r;
}
else if (isObject(d)) {
var s = {};
for (var j in d) {
s[j] = _one(d[j]);
}
return s;
}
else {
return d;
}
}
};
return _one(model);
}
jsPlumbUtil.populate = populate;
function findWithFunction(a, f) {
if (a) {
for (var i = 0; i < a.length; i++) {
if (f(a[i])) {
return i;
}
}
}
return -1;
}
jsPlumbUtil.findWithFunction = findWithFunction;
function removeWithFunction(a, f) {
var idx = findWithFunction(a, f);
if (idx > -1) {
a.splice(idx, 1);
}
return idx !== -1;
}
jsPlumbUtil.removeWithFunction = removeWithFunction;
function remove(l, v) {
var idx = l.indexOf(v);
if (idx > -1) {
l.splice(idx, 1);
}
return idx !== -1;
}
jsPlumbUtil.remove = remove;
function addWithFunction(list, item, hashFunction) {
if (findWithFunction(list, hashFunction) === -1) {
list.push(item);
}
}
jsPlumbUtil.addWithFunction = addWithFunction;
function addToList(map, key, value, insertAtStart) {
var l = map[key];
if (l == null) {
l = [];
map[key] = l;
}
l[insertAtStart ? "unshift" : "push"](value);
return l;
}
jsPlumbUtil.addToList = addToList;
function suggest(list, item, insertAtHead) {
if (list.indexOf(item) === -1) {
if (insertAtHead) {
list.unshift(item);
}
else {
list.push(item);
}
return true;
}
return false;
}
jsPlumbUtil.suggest = suggest;
//
// extends the given obj (which can be an array) with the given constructor function, prototype functions, and
// class members, any of which may be null.
//
function extend(child, parent, _protoFn) {
var i;
parent = isArray(parent) ? parent : [parent];
var _copyProtoChain = function (focus) {
var proto = focus.__proto__;
while (proto != null) {
if (proto.prototype != null) {
for (var j in proto.prototype) {
if (proto.prototype.hasOwnProperty(j) && !child.prototype.hasOwnProperty(j)) {
child.prototype[j] = proto.prototype[j];
}
}
proto = proto.prototype.__proto__;
}
else {
proto = null;
}
}
};
for (i = 0; i < parent.length; i++) {
for (var j in parent[i].prototype) {
if (parent[i].prototype.hasOwnProperty(j) && !child.prototype.hasOwnProperty(j)) {
child.prototype[j] = parent[i].prototype[j];
}
}
_copyProtoChain(parent[i]);
}
var _makeFn = function (name, protoFn) {
return function () {
for (i = 0; i < parent.length; i++) {
if (parent[i].prototype[name]) {
parent[i].prototype[name].apply(this, arguments);
}
}
return protoFn.apply(this, arguments);
};
};
var _oneSet = function (fns) {
for (var k in fns) {
child.prototype[k] = _makeFn(k, fns[k]);
}
};
if (arguments.length > 2) {
for (i = 2; i < arguments.length; i++) {
_oneSet(arguments[i]);
}
}
return child;
}
jsPlumbUtil.extend = extend;
function uuid() {
return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}));
}
jsPlumbUtil.uuid = uuid;
function fastTrim(s) {
if (s == null) {
return null;
}
var str = s.replace(/^\s\s*/, ''), ws = /\s/, i = str.length;
while (ws.test(str.charAt(--i))) {
}
return str.slice(0, i + 1);
}
jsPlumbUtil.fastTrim = fastTrim;
function each(obj, fn) {
obj = obj.length == null || typeof obj === "string" ? [obj] : obj;
for (var i = 0; i < obj.length; i++) {
fn(obj[i]);
}
}
jsPlumbUtil.each = each;
function map(obj, fn) {
var o = [];
for (var i = 0; i < obj.length; i++) {
o.push(fn(obj[i]));
}
return o;
}
jsPlumbUtil.map = map;
function mergeWithParents(type, map, parentAttribute) {
parentAttribute = parentAttribute || "parent";
var _def = function (id) {
return id ? map[id] : null;
};
var _parent = function (def) {
return def ? _def(def[parentAttribute]) : null;
};
var _one = function (parent, def) {
if (parent == null) {
return def;
}
else {
var d_1 = merge(parent, def);
return _one(_parent(parent), d_1);
}
};
var _getDef = function (t) {
if (t == null) {
return {};
}
if (typeof t === "string") {
return _def(t);
}
else if (t.length) {
var done = false, i = 0, _dd = void 0;
while (!done && i < t.length) {
_dd = _getDef(t[i]);
if (_dd) {
done = true;
}
else {
i++;
}
}
return _dd;
}
};
var d = _getDef(type);
if (d) {
return _one(_parent(d), d);
}
else {
return {};
}
}
jsPlumbUtil.mergeWithParents = mergeWithParents;
jsPlumbUtil.logEnabled = true;
function log() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (jsPlumbUtil.logEnabled && typeof console !== "undefined") {
try {
var msg = arguments[arguments.length - 1];
console.log(msg);
}
catch (e) {
}
}
}
jsPlumbUtil.log = log;
/**
* Wraps one function with another, creating a placeholder for the
* wrapped function if it was null. this is used to wrap the various
* drag/drop event functions - to allow jsPlumb to be notified of
* important lifecycle events without imposing itself on the user's
* drag/drop functionality.
* @method jsPlumbUtil.wrap
* @param {Function} wrappedFunction original function to wrap; may be null.
* @param {Function} newFunction function to wrap the original with.
* @param {Object} [returnOnThisValue] Optional. Indicates that the wrappedFunction should
* not be executed if the newFunction returns a value matching 'returnOnThisValue'.
* note that this is a simple comparison and only works for primitives right now.
*/
function wrap(wrappedFunction, newFunction, returnOnThisValue) {
return function () {
var r = null;
try {
if (newFunction != null) {
r = newFunction.apply(this, arguments);
}
}
catch (e) {
log("jsPlumb function failed : " + e);
}
if ((wrappedFunction != null) && (returnOnThisValue == null || (r !== returnOnThisValue))) {
try {
r = wrappedFunction.apply(this, arguments);
}
catch (e) {
log("wrapped function failed : " + e);
}
}
return r;
};
}
jsPlumbUtil.wrap = wrap;
var EventGenerator = /** @class */ (function () {
function EventGenerator() {
var _this = this;
this._listeners = {};
this.eventsSuspended = false;
this.tick = false;
// this is a list of events that should re-throw any errors that occur during their dispatch.
this.eventsToDieOn = { "ready": true };
this.queue = [];
this.bind = function (event, listener, insertAtStart) {
var _one = function (evt) {
addToList(_this._listeners, evt, listener, insertAtStart);
listener.__jsPlumb = listener.__jsPlumb || {};
listener.__jsPlumb[uuid()] = evt;
};
if (typeof event === "string") {
_one(event);
}
else if (event.length != null) {
for (var i = 0; i < event.length; i++) {
_one(event[i]);
}
}
return _this;
};
this.fire = function (event, value, originalEvent) {
if (!this.tick) {
this.tick = true;
if (!this.eventsSuspended && this._listeners[event]) {
var l = this._listeners[event].length, i = 0, _gone = false, ret = null;
if (!this.shouldFireEvent || this.shouldFireEvent(event, value, originalEvent)) {
while (!_gone && i < l && ret !== false) {
// doing it this way rather than catching and then possibly re-throwing means that an error propagated by this
// method will have the whole call stack available in the debugger.
if (this.eventsToDieOn[event]) {
this._listeners[event][i].apply(this, [value, originalEvent]);
}
else {
try {
ret = this._listeners[event][i].apply(this, [value, originalEvent]);
}
catch (e) {
log("jsPlumb: fire failed for event " + event + " : " + e);
}
}
i++;
if (this._listeners == null || this._listeners[event] == null) {
_gone = true;
}
}
}
}
this.tick = false;
this._drain();
}
else {
this.queue.unshift(arguments);
}
return this;
};
this._drain = function () {
var n = _this.queue.pop();
if (n) {
_this.fire.apply(_this, n);
}
};
this.unbind = function (eventOrListener, listener) {
if (arguments.length === 0) {
this._listeners = {};
}
else if (arguments.length === 1) {
if (typeof eventOrListener === "string") {
delete this._listeners[eventOrListener];
}
else if (eventOrListener.__jsPlumb) {
var evt = void 0;
for (var i in eventOrListener.__jsPlumb) {
evt = eventOrListener.__jsPlumb[i];
remove(this._listeners[evt] || [], eventOrListener);
}
}
}
else if (arguments.length === 2) {
remove(this._listeners[eventOrListener] || [], listener);
}
return this;
};
this.getListener = function (forEvent) {
return _this._listeners[forEvent];
};
this.setSuspendEvents = function (val) {
_this.eventsSuspended = val;
};
this.isSuspendEvents = function () {
return _this.eventsSuspended;
};
this.silently = function (fn) {
_this.setSuspendEvents(true);
try {
fn();
}
catch (e) {
log("Cannot execute silent function " + e);
}
_this.setSuspendEvents(false);
};
this.cleanupListeners = function () {
for (var i in _this._listeners) {
_this._listeners[i] = null;
}
};
}
return EventGenerator;
}());
jsPlumbUtil.EventGenerator = EventGenerator;
}).call(typeof window !== 'undefined' ? window : this);
/*
* This file contains utility functions that run in browsers only.
*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
"use strict";
var root = this;
root.jsPlumbUtil.matchesSelector = function(el, selector, ctx) {
ctx = ctx || el.parentNode;
var possibles = ctx.querySelectorAll(selector);
for (var i = 0; i < possibles.length; i++) {
if (possibles[i] === el) {
return true;
}
}
return false;
};
root.jsPlumbUtil.consume = function(e, doNotPreventDefault) {
if (e.stopPropagation) {
e.stopPropagation();
}
else {
e.returnValue = false;
}
if (!doNotPreventDefault && e.preventDefault){
e.preventDefault();
}
};
/*
* Function: sizeElement
* Helper to size and position an element. You would typically use
* this when writing your own Connector or Endpoint implementation.
*
* Parameters:
* x - [int] x position for the element origin
* y - [int] y position for the element origin
* w - [int] width of the element
* h - [int] height of the element
*
*/
root.jsPlumbUtil.sizeElement = function(el, x, y, w, h) {
if (el) {
el.style.height = h + "px";
el.height = h;
el.style.width = w + "px";
el.width = w;
el.style.left = x + "px";
el.style.top = y + "px";
}
};
}).call(typeof window !== 'undefined' ? window : this);
/*
* This file contains the core code.
*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function () {
"use strict";
var root = this;
var _ju = root.jsPlumbUtil,
/**
* creates a timestamp, using milliseconds since 1970, but as a string.
*/
_timestamp = function () {
return "" + (new Date()).getTime();
},
// helper method to update the hover style whenever it, or paintStyle, changes.
// we use paintStyle as the foundation and merge hoverPaintStyle over the
// top.
_updateHoverStyle = function (component) {
if (component._jsPlumb.paintStyle && component._jsPlumb.hoverPaintStyle) {
var mergedHoverStyle = {};
jsPlumb.extend(mergedHoverStyle, component._jsPlumb.paintStyle);
jsPlumb.extend(mergedHoverStyle, component._jsPlumb.hoverPaintStyle);
delete component._jsPlumb.hoverPaintStyle;
// we want the fill of paintStyle to override a gradient, if possible.
if (mergedHoverStyle.gradient && component._jsPlumb.paintStyle.fill) {
delete mergedHoverStyle.gradient;
}
component._jsPlumb.hoverPaintStyle = mergedHoverStyle;
}
},
events = ["tap", "dbltap", "click", "dblclick", "mouseover", "mouseout", "mousemove", "mousedown", "mouseup", "contextmenu" ],
eventFilters = { "mouseout": "mouseleave", "mouseexit": "mouseleave" },
_updateAttachedElements = function (component, state, timestamp, sourceElement) {
var affectedElements = component.getAttachedElements();
if (affectedElements) {
for (var i = 0, j = affectedElements.length; i < j; i++) {
if (!sourceElement || sourceElement !== affectedElements[i]) {
affectedElements[i].setHover(state, true, timestamp); // tell the attached elements not to inform their own attached elements.
}
}
}
},
_splitType = function (t) {
return t == null ? null : t.split(" ");
},
_mapType = function(map, obj, typeId) {
for (var i in obj) {
map[i] = typeId;
}
},
_each = function(fn, obj) {
obj = _ju.isArray(obj) || (obj.length != null && !_ju.isString(obj)) ? obj : [ obj ];
for (var i = 0; i < obj.length; i++) {
try {
fn.apply(obj[i], [ obj[i] ]);
}
catch (e) {
_ju.log(".each iteration failed : " + e);
}
}
},
_applyTypes = function (component, params, doNotRepaint) {
if (component.getDefaultType) {
var td = component.getTypeDescriptor(), map = {};
var defType = component.getDefaultType();
var o = _ju.merge({}, defType);
_mapType(map, defType, "__default");
for (var i = 0, j = component._jsPlumb.types.length; i < j; i++) {
var tid = component._jsPlumb.types[i];
if (tid !== "__default") {
var _t = component._jsPlumb.instance.getType(tid, td);
if (_t != null) {
o = _ju.merge(o, _t, [ "cssClass" ], [ "connector" ]);
_mapType(map, _t, tid);
}
}
}
if (params) {
o = _ju.populate(o, params, "_");
}
component.applyType(o, doNotRepaint, map);
if (!doNotRepaint) {
component.repaint();
}
}
},
// ------------------------------ BEGIN jsPlumbUIComponent --------------------------------------------
jsPlumbUIComponent = root.jsPlumbUIComponent = function (params) {
_ju.EventGenerator.apply(this, arguments);
var self = this,
a = arguments,
idPrefix = self.idPrefix,
id = idPrefix + (new Date()).getTime();
this._jsPlumb = {
instance: params._jsPlumb,
parameters: params.parameters || {},
paintStyle: null,
hoverPaintStyle: null,
paintStyleInUse: null,
hover: false,
beforeDetach: params.beforeDetach,
beforeDrop: params.beforeDrop,
overlayPlacements: [],
hoverClass: params.hoverClass || params._jsPlumb.Defaults.HoverClass,
types: [],
typeCache:{}
};
this.cacheTypeItem = function(key, item, typeId) {
this._jsPlumb.typeCache[typeId] = this._jsPlumb.typeCache[typeId] || {};
this._jsPlumb.typeCache[typeId][key] = item;
};
this.getCachedTypeItem = function(key, typeId) {
return this._jsPlumb.typeCache[typeId] ? this._jsPlumb.typeCache[typeId][key] : null;
};
this.getId = function () {
return id;
};
// ----------------------------- default type --------------------------------------------
var o = params.overlays || [], oo = {};
if (this.defaultOverlayKeys) {
for (var i = 0; i < this.defaultOverlayKeys.length; i++) {
Array.prototype.push.apply(o, this._jsPlumb.instance.Defaults[this.defaultOverlayKeys[i]] || []);
}
for (i = 0; i < o.length; i++) {
// if a string, convert to object representation so that we can store the typeid on it.
// also assign an id.
var fo = jsPlumb.convertToFullOverlaySpec(o[i]);
oo[fo[1].id] = fo;
}
}
var _defaultType = {
overlays:oo,
parameters: params.parameters || {},
scope: params.scope || this._jsPlumb.instance.getDefaultScope()
};
this.getDefaultType = function() {
return _defaultType;
};
this.appendToDefaultType = function(obj) {
for (var i in obj) {
_defaultType[i] = obj[i];
}
};
// ----------------------------- end default type --------------------------------------------
// all components can generate events
if (params.events) {
for (var evtName in params.events) {
self.bind(evtName, params.events[evtName]);
}
}
// all components get this clone function.
// TODO issue 116 showed a problem with this - it seems 'a' that is in
// the clone function's scope is shared by all invocations of it, the classic
// JS closure problem. for now, jsPlumb does a version of this inline where
// it used to call clone. but it would be nice to find some time to look
// further at this.
this.clone = function () {
var o = Object.create(this.constructor.prototype);
this.constructor.apply(o, a);
return o;
}.bind(this);
// user can supply a beforeDetach callback, which will be executed before a detach
// is performed; returning false prevents the detach.
this.isDetachAllowed = function (connection) {
var r = true;
if (this._jsPlumb.beforeDetach) {
try {
r = this._jsPlumb.beforeDetach(connection);
}
catch (e) {
_ju.log("jsPlumb: beforeDetach callback failed", e);
}
}
return r;
};
// user can supply a beforeDrop callback, which will be executed before a dropped
// connection is confirmed. user can return false to reject connection.
this.isDropAllowed = function (sourceId, targetId, scope, connection, dropEndpoint, source, target) {
var r = this._jsPlumb.instance.checkCondition("beforeDrop", {
sourceId: sourceId,
targetId: targetId,
scope: scope,
connection: connection,
dropEndpoint: dropEndpoint,
source: source, target: target
});
if (this._jsPlumb.beforeDrop) {
try {
r = this._jsPlumb.beforeDrop({
sourceId: sourceId,
targetId: targetId,
scope: scope,
connection: connection,
dropEndpoint: dropEndpoint,
source: source, target: target
});
}
catch (e) {
_ju.log("jsPlumb: beforeDrop callback failed", e);
}
}
return r;
};
var domListeners = [];
// sets the component associated with listener events. for instance, an overlay delegates
// its events back to a connector. but if the connector is swapped on the underlying connection,
// then this component must be changed. This is called by setConnector in the Connection class.
this.setListenerComponent = function (c) {
for (var i = 0; i < domListeners.length; i++) {
domListeners[i][3] = c;
}
};
};
var _removeTypeCssHelper = function (component, typeIndex) {
var typeId = component._jsPlumb.types[typeIndex],
type = component._jsPlumb.instance.getType(typeId, component.getTypeDescriptor());
if (type != null && type.cssClass && component.canvas) {
component._jsPlumb.instance.removeClass(component.canvas, type.cssClass);
}
};
_ju.extend(root.jsPlumbUIComponent, _ju.EventGenerator, {
getParameter: function (name) {
return this._jsPlumb.parameters[name];
},
setParameter: function (name, value) {
this._jsPlumb.parameters[name] = value;
},
getParameters: function () {
return this._jsPlumb.parameters;
},
setParameters: function (p) {
this._jsPlumb.parameters = p;
},
getClass:function() {
return jsPlumb.getClass(this.canvas);
},
hasClass:function(clazz) {
return jsPlumb.hasClass(this.canvas, clazz);
},
addClass: function (clazz) {
jsPlumb.addClass(this.canvas, clazz);
},
removeClass: function (clazz) {
jsPlumb.removeClass(this.canvas, clazz);
},
updateClasses: function (classesToAdd, classesToRemove) {
jsPlumb.updateClasses(this.canvas, classesToAdd, classesToRemove);
},
setType: function (typeId, params, doNotRepaint) {
this.clearTypes();
this._jsPlumb.types = _splitType(typeId) || [];
_applyTypes(this, params, doNotRepaint);
},
getType: function () {
return this._jsPlumb.types;
},
reapplyTypes: function (params, doNotRepaint) {
_applyTypes(this, params, doNotRepaint);
},
hasType: function (typeId) {
return this._jsPlumb.types.indexOf(typeId) !== -1;
},
addType: function (typeId, params, doNotRepaint) {
var t = _splitType(typeId), _cont = false;
if (t != null) {
for (var i = 0, j = t.length; i < j; i++) {
if (!this.hasType(t[i])) {
this._jsPlumb.types.push(t[i]);
_cont = true;
}
}
if (_cont) {
_applyTypes(this, params, doNotRepaint);
}
}
},
removeType: function (typeId, params, doNotRepaint) {
var t = _splitType(typeId), _cont = false, _one = function (tt) {
var idx = this._jsPlumb.types.indexOf(tt);
if (idx !== -1) {
// remove css class if necessary
_removeTypeCssHelper(this, idx);
this._jsPlumb.types.splice(idx, 1);
return true;
}
return false;
}.bind(this);
if (t != null) {
for (var i = 0, j = t.length; i < j; i++) {
_cont = _one(t[i]) || _cont;
}
if (_cont) {
_applyTypes(this, params, doNotRepaint);
}
}
},
clearTypes: function (params, doNotRepaint) {
var i = this._jsPlumb.types.length;
for (var j = 0; j < i; j++) {
_removeTypeCssHelper(this, 0);
this._jsPlumb.types.splice(0, 1);
}
_applyTypes(this, params, doNotRepaint);
},
toggleType: function (typeId, params, doNotRepaint) {
var t = _splitType(typeId);
if (t != null) {
for (var i = 0, j = t.length; i < j; i++) {
var idx = this._jsPlumb.types.indexOf(t[i]);
if (idx !== -1) {
_removeTypeCssHelper(this, idx);
this._jsPlumb.types.splice(idx, 1);
}
else {
this._jsPlumb.types.push(t[i]);
}
}
_applyTypes(this, params, doNotRepaint);
}
},
applyType: function (t, doNotRepaint) {
this.setPaintStyle(t.paintStyle, doNotRepaint);
this.setHoverPaintStyle(t.hoverPaintStyle, doNotRepaint);
if (t.parameters) {
for (var i in t.parameters) {
this.setParameter(i, t.parameters[i]);
}
}
this._jsPlumb.paintStyleInUse = this.getPaintStyle();
},
setPaintStyle: function (style, doNotRepaint) {
// this._jsPlumb.paintStyle = jsPlumb.extend({}, style);
// TODO figure out if we want components to clone paintStyle so as not to share it.
this._jsPlumb.paintStyle = style;
this._jsPlumb.paintStyleInUse = this._jsPlumb.paintStyle;
_updateHoverStyle(this);
if (!doNotRepaint) {
this.repaint();
}
},
getPaintStyle: function () {
return this._jsPlumb.paintStyle;
},
setHoverPaintStyle: function (style, doNotRepaint) {
//this._jsPlumb.hoverPaintStyle = jsPlumb.extend({}, style);
// TODO figure out if we want components to clone paintStyle so as not to share it.
this._jsPlumb.hoverPaintStyle = style;
_updateHoverStyle(this);
if (!doNotRepaint) {
this.repaint();
}
},
getHoverPaintStyle: function () {
return this._jsPlumb.hoverPaintStyle;
},
destroy: function (force) {
if (force || this.typeId == null) {
this.cleanupListeners(); // this is on EventGenerator
this.clone = null;
this._jsPlumb = null;
}
},
isHover: function () {
return this._jsPlumb.hover;
},
setHover: function (hover, ignoreAttachedElements, timestamp) {
// while dragging, we ignore these events. this keeps the UI from flashing and
// swishing and whatevering.
if (this._jsPlumb && !this._jsPlumb.instance.currentlyDragging && !this._jsPlumb.instance.isHoverSuspended()) {
this._jsPlumb.hover = hover;
var method = hover ? "addClass" : "removeClass";
if (this.canvas != null) {
if (this._jsPlumb.instance.hoverClass != null) {
this._jsPlumb.instance[method](this.canvas, this._jsPlumb.instance.hoverClass);
}
if (this._jsPlumb.hoverClass != null) {
this._jsPlumb.instance[method](this.canvas, this._jsPlumb.hoverClass);
}
}
if (this._jsPlumb.hoverPaintStyle != null) {
this._jsPlumb.paintStyleInUse = hover ? this._jsPlumb.hoverPaintStyle : this._jsPlumb.paintStyle;
if (!this._jsPlumb.instance.isSuspendDrawing()) {
timestamp = timestamp || _timestamp();
this.repaint({timestamp: timestamp, recalc: false});
}
}
// get the list of other affected elements, if supported by this component.
// for a connection, its the endpoints. for an endpoint, its the connections! surprise.
if (this.getAttachedElements && !ignoreAttachedElements) {
_updateAttachedElements(this, hover, _timestamp(), this);
}
}
}
});
// ------------------------------ END jsPlumbUIComponent --------------------------------------------
var _jsPlumbInstanceIndex = 0,
getInstanceIndex = function () {
var i = _jsPlumbInstanceIndex + 1;
_jsPlumbInstanceIndex++;
return i;
};
var jsPlumbInstance = root.jsPlumbInstance = function (_defaults) {
this.version = "2.8.8";
this.Defaults = {
Anchor: "Bottom",
Anchors: [ null, null ],
ConnectionsDetachable: true,
ConnectionOverlays: [ ],
Connector: "Bezier",
Container: null,
DoNotThrowErrors: false,
DragOptions: { },
DropOptions: { },
Endpoint: "Dot",
EndpointOverlays: [ ],
Endpoints: [ null, null ],
EndpointStyle: { fill: "#456" },
EndpointStyles: [ null, null ],
EndpointHoverStyle: null,
EndpointHoverStyles: [ null, null ],
HoverPaintStyle: null,
LabelStyle: { color: "black" },
LogEnabled: false,
Overlays: [ ],
MaxConnections: 1,
PaintStyle: { "stroke-width": 4, stroke: "#456" },
ReattachConnections: false,
RenderMode: "svg",
Scope: "jsPlumb_DefaultScope"
};
if (_defaults) {
jsPlumb.extend(this.Defaults, _defaults);
}
this.logEnabled = this.Defaults.LogEnabled;
this._connectionTypes = {};
this._endpointTypes = {};
_ju.EventGenerator.apply(this);
var _currentInstance = this,
_instanceIndex = getInstanceIndex(),
_bb = _currentInstance.bind,
_initialDefaults = {},
_zoom = 1,
_info = function (el) {
if (el == null) {
return null;
}
else if (el.nodeType === 3 || el.nodeType === 8) {
return { el:el, text:true };
}
else {
var _el = _currentInstance.getElement(el);
return { el: _el, id: (_ju.isString(el) && _el == null) ? el : _getId(_el) };
}
};
this.getInstanceIndex = function () {
return _instanceIndex;
};
// CONVERTED
this.setZoom = function (z, repaintEverything) {
_zoom = z;
_currentInstance.fire("zoom", _zoom);
if (repaintEverything) {
_currentInstance.repaintEverything();
}
return true;
};
// CONVERTED
this.getZoom = function () {
return _zoom;
};
for (var i in this.Defaults) {
_initialDefaults[i] = this.Defaults[i];
}
var _container, _containerDelegations = [];
this.unbindContainer = function() {
if (_container != null && _containerDelegations.length > 0) {
for (var i = 0; i < _containerDelegations.length; i++) {
_currentInstance.off(_container, _containerDelegations[i][0], _containerDelegations[i][1]);
}
}
};
this.setContainer = function (c) {
this.unbindContainer();
// get container as dom element.
c = this.getElement(c);
// move existing connections and endpoints, if any.
this.select().each(function (conn) {
conn.moveParent(c);
});
this.selectEndpoints().each(function (ep) {
ep.moveParent(c);
});
// set container.
var previousContainer = _container;
_container = c;
_containerDelegations.length = 0;
var eventAliases = {
"endpointclick":"endpointClick",
"endpointdblclick":"endpointDblClick"
};
var _oneDelegateHandler = function (id, e, componentType) {
var t = e.srcElement || e.target,
jp = (t && t.parentNode ? t.parentNode._jsPlumb : null) || (t ? t._jsPlumb : null) || (t && t.parentNode && t.parentNode.parentNode ? t.parentNode.parentNode._jsPlumb : null);
if (jp) {
jp.fire(id, jp, e);
var alias = componentType ? eventAliases[componentType + id] || id : id;
// jsplumb also fires every event coming from components/overlays. That's what the test for `jp.component` is for.
_currentInstance.fire(alias, jp.component || jp, e);
}
};
var _addOneDelegate = function(eventId, selector, fn) {
_containerDelegations.push([eventId, fn]);
_currentInstance.on(_container, eventId, selector, fn);
};
// delegate one event on the container to jsplumb elements. it might be possible to
// abstract this out: each of endpoint, connection and overlay could register themselves with
// jsplumb as "component types" or whatever, and provide a suitable selector. this would be
// done by the renderer (although admittedly from 2.0 onwards we're not supporting vml anymore)
var _oneDelegate = function (id) {
// connections.
_addOneDelegate(id, ".jtk-connector", function (e) {
_oneDelegateHandler(id, e);
});
// endpoints. note they can have an enclosing div, or not.
_addOneDelegate(id, ".jtk-endpoint", function (e) {
_oneDelegateHandler(id, e, "endpoint");
});
// overlays
_addOneDelegate(id, ".jtk-overlay", function (e) {
_oneDelegateHandler(id, e);
});
};
for (var i = 0; i < events.length; i++) {
_oneDelegate(events[i]);
}
// managed elements
for (var elId in managedElements) {
var el = managedElements[elId].el;
if (el.parentNode === previousContainer) {
previousContainer.removeChild(el);
_container.appendChild(el);
}
}
};
this.getContainer = function () {
return _container;
};
this.bind = function (event, fn) {
if ("ready" === event && initialized) {
fn();
}
else {
_bb.apply(_currentInstance, [event, fn]);
}
};
_currentInstance.importDefaults = function (d) {
for (var i in d) {
_currentInstance.Defaults[i] = d[i];
}
if (d.Container) {
_currentInstance.setContainer(d.Container);
}
return _currentInstance;
};
_currentInstance.restoreDefaults = function () {
_currentInstance.Defaults = jsPlumb.extend({}, _initialDefaults);
return _currentInstance;
};
var log = null,
initialized = false,
// TODO remove from window scope
connections = [],
// map of element id -> endpoint lists. an element can have an arbitrary
// number of endpoints on it, and not all of them have to be connected
// to anything.
endpointsByElement = {},
endpointsByUUID = {},
managedElements = {},
offsets = {},
offsetTimestamps = {},
draggableStates = {},
connectionBeingDragged = false,
sizes = [],
_suspendDrawing = false,
_suspendedAt = null,
DEFAULT_SCOPE = this.Defaults.Scope,
_curIdStamp = 1,
_idstamp = function () {
return "" + _curIdStamp++;
},
//
// appends an element to some other element, which is calculated as follows:
//
// 1. if Container exists, use that element.
// 2. if the 'parent' parameter exists, use that.
// 3. otherwise just use the root element.
//
//
_appendElement = function (el, parent) {
if (_container) {
_container.appendChild(el);
}
else if (!parent) {
this.appendToRoot(el);
}
else {
this.getElement(parent).appendChild(el);
}
}.bind(this),
//
// Draws an endpoint and its connections. this is the main entry point into drawing connections as well
// as endpoints, since jsPlumb is endpoint-centric under the hood.
//
// @param element element to draw (of type library specific element object)
// @param ui UI object from current library's event system. optional.
// @param timestamp timestamp for this paint cycle. used to speed things up a little by cutting down the amount of offset calculations we do.
// @param clearEdits defaults to false; indicates that mouse edits for connectors should be cleared
///
_draw = function (element, ui, timestamp, clearEdits) {
if (!_suspendDrawing) {
var id = _getId(element),
repaintEls,
dm = _currentInstance.getDragManager();
if (dm) {
repaintEls = dm.getElementsForDraggable(id);
}
if (timestamp == null) {
timestamp = _timestamp();
}
// update the offset of everything _before_ we try to draw anything.
var o = _updateOffset({ elId: id, offset: ui, recalc: false, timestamp: timestamp });
if (repaintEls && o && o.o) {
for (var i in repaintEls) {
_updateOffset({
elId: repaintEls[i].id,
offset: {
left: o.o.left + repaintEls[i].offset.left,
top: o.o.top + repaintEls[i].offset.top
},
recalc: false,
timestamp: timestamp
});
}
}
_currentInstance.anchorManager.redraw(id, ui, timestamp, null, clearEdits);
if (repaintEls) {
for (var j in repaintEls) {
_currentInstance.anchorManager.redraw(repaintEls[j].id, ui, timestamp, repaintEls[j].offset, clearEdits, true);
}
}
}
},
//
// gets an Endpoint by uuid.
//
_getEndpoint = function (uuid) {
return endpointsByUUID[uuid];
},
/**
* inits a draggable if it's not already initialised.
* TODO: somehow abstract this to the adapter, because the concept of "draggable" has no
* place on the server.
*/
_initDraggableIfNecessary = function (element, isDraggable, dragOptions, id, fireEvent) {
// move to DragManager?
if (!jsPlumb.headless) {
var _draggable = isDraggable == null ? false : isDraggable;
if (_draggable) {
if (jsPlumb.isDragSupported(element, _currentInstance)) {
var options = dragOptions || _currentInstance.Defaults.DragOptions;
options = jsPlumb.extend({}, options); // make a copy.
if (!jsPlumb.isAlreadyDraggable(element, _currentInstance)) {
var dragEvent = jsPlumb.dragEvents.drag,
stopEvent = jsPlumb.dragEvents.stop,
startEvent = jsPlumb.dragEvents.start,
_started = false;
_manage(id, element);
options[startEvent] = _ju.wrap(options[startEvent], function () {
_currentInstance.setHoverSuspended(true);
_currentInstance.select({source: element}).addClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true);
_currentInstance.select({target: element}).addClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true);
_currentInstance.setConnectionBeingDragged(true);
if (options.canDrag) {
return dragOptions.canDrag();
}
}, false);
options[dragEvent] = _ju.wrap(options[dragEvent], function () {
var ui = _currentInstance.getUIPosition(arguments, _currentInstance.getZoom());
if (ui != null) {
_draw(element, ui, null, true);
if (_started) {
_currentInstance.addClass(element, "jtk-dragged");
}
_started = true;
}
});
options[stopEvent] = _ju.wrap(options[stopEvent], function () {
var elements = arguments[0].selection, uip;
var _one = function (_e) {
if (_e[1] != null) {
// run the reported offset through the code that takes parent containers
// into account, to adjust if necessary (issue 554)
uip = _currentInstance.getUIPosition([{
el:_e[2].el,
pos:[_e[1].left, _e[1].top]
}]);
_draw(_e[2].el, uip);
}
_currentInstance.removeClass(_e[0], "jtk-dragged");
_currentInstance.select({source: _e[2].el}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true);
_currentInstance.select({target: _e[2].el}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true);
_currentInstance.getDragManager().dragEnded(_e[2].el);
};
for (var i = 0; i < elements.length; i++) {
_one(elements[i]);
}
_started = false;
_currentInstance.setHoverSuspended(false);
_currentInstance.setConnectionBeingDragged(false);
});
var elId = _getId(element); // need ID
draggableStates[elId] = true;
var draggable = draggableStates[elId];
options.disabled = draggable == null ? false : !draggable;
_currentInstance.initDraggable(element, options);
_currentInstance.getDragManager().register(element);
if (fireEvent) {
_currentInstance.fire("elementDraggable", {el:element, options:options});
}
}
else {
// already draggable. attach any start, drag or stop listeners to the current Drag.
if (dragOptions.force) {
_currentInstance.initDraggable(element, options);
}
}
}
}
}
},
_scopeMatch = function (e1, e2) {
var s1 = e1.scope.split(/\s/), s2 = e2.scope.split(/\s/);
for (var i = 0; i < s1.length; i++) {
for (var j = 0; j < s2.length; j++) {
if (s2[j] === s1[i]) {
return true;
}
}
}
return false;
},
_mergeOverrides = function (def, values) {
var m = jsPlumb.extend({}, def);
for (var i in values) {
if (values[i]) {
m[i] = values[i];
}
}
return m;
},
/*
* prepares a final params object that can be passed to _newConnection, taking into account defaults, events, etc.
*/
_prepareConnectionParams = function (params, referenceParams) {
var _p = jsPlumb.extend({ }, params);
if (referenceParams) {
jsPlumb.extend(_p, referenceParams);
}
// hotwire endpoints passed as source or target to sourceEndpoint/targetEndpoint, respectively.
if (_p.source) {
if (_p.source.endpoint) {
_p.sourceEndpoint = _p.source;
}
else {
_p.source = _currentInstance.getElement(_p.source);
}
}
if (_p.target) {
if (_p.target.endpoint) {
_p.targetEndpoint = _p.target;
}
else {
_p.target = _currentInstance.getElement(_p.target);
}
}
// test for endpoint uuids to connect
if (params.uuids) {
_p.sourceEndpoint = _getEndpoint(params.uuids[0]);
_p.targetEndpoint = _getEndpoint(params.uuids[1]);
}
// now ensure that if we do have Endpoints already, they're not full.
// source:
if (_p.sourceEndpoint && _p.sourceEndpoint.isFull()) {
_ju.log(_currentInstance, "could not add connection; source endpoint is full");
return;
}
// target:
if (_p.targetEndpoint && _p.targetEndpoint.isFull()) {
_ju.log(_currentInstance, "could not add connection; target endpoint is full");
return;
}
// if source endpoint mandates connection type and nothing specified in our params, use it.
if (!_p.type && _p.sourceEndpoint) {
_p.type = _p.sourceEndpoint.connectionType;
}
// copy in any connectorOverlays that were specified on the source endpoint.
// it doesnt copy target endpoint overlays. i'm not sure if we want it to or not.
if (_p.sourceEndpoint && _p.sourceEndpoint.connectorOverlays) {
_p.overlays = _p.overlays || [];
for (var i = 0, j = _p.sourceEndpoint.connectorOverlays.length; i < j; i++) {
_p.overlays.push(_p.sourceEndpoint.connectorOverlays[i]);
}
}
// scope
if (_p.sourceEndpoint && _p.sourceEndpoint.scope) {
_p.scope = _p.sourceEndpoint.scope;
}
// pointer events
if (!_p["pointer-events"] && _p.sourceEndpoint && _p.sourceEndpoint.connectorPointerEvents) {
_p["pointer-events"] = _p.sourceEndpoint.connectorPointerEvents;
}
var _addEndpoint = function (el, def, idx) {
return _currentInstance.addEndpoint(el, _mergeOverrides(def, {
anchor: _p.anchors ? _p.anchors[idx] : _p.anchor,
endpoint: _p.endpoints ? _p.endpoints[idx] : _p.endpoint,
paintStyle: _p.endpointStyles ? _p.endpointStyles[idx] : _p.endpointStyle,
hoverPaintStyle: _p.endpointHoverStyles ? _p.endpointHoverStyles[idx] : _p.endpointHoverStyle
}));
};
// check for makeSource/makeTarget specs.
var _oneElementDef = function (type, idx, defs, matchType) {
if (_p[type] && !_p[type].endpoint && !_p[type + "Endpoint"] && !_p.newConnection) {
var tid = _getId(_p[type]), tep = defs[tid];
tep = tep ? tep[matchType] : null;
if (tep) {
// if not enabled, return.
if (!tep.enabled) {
return false;
}
var newEndpoint = tep.endpoint != null && tep.endpoint._jsPlumb ? tep.endpoint : _addEndpoint(_p[type], tep.def, idx);
if (newEndpoint.isFull()) {
return false;
}
_p[type + "Endpoint"] = newEndpoint;
if (!_p.scope && tep.def.scope) {
_p.scope = tep.def.scope;
} // provide scope if not already provided and endpoint def has one.
if (tep.uniqueEndpoint) {
if (!tep.endpoint) {
tep.endpoint = newEndpoint;
newEndpoint.setDeleteOnEmpty(false);
}
else {
newEndpoint.finalEndpoint = tep.endpoint;
}
} else {
newEndpoint.setDeleteOnEmpty(true);
}
//
// copy in connector overlays if present on the source definition.
//
if (idx === 0 && tep.def.connectorOverlays) {
_p.overlays = _p.overlays || [];
Array.prototype.push.apply(_p.overlays, tep.def.connectorOverlays);
}
}
}
};
if (_oneElementDef("source", 0, this.sourceEndpointDefinitions, _p.type || "default") === false) {
return;
}
if (_oneElementDef("target", 1, this.targetEndpointDefinitions, _p.type || "default") === false) {
return;
}
// last, ensure scopes match
if (_p.sourceEndpoint && _p.targetEndpoint) {
if (!_scopeMatch(_p.sourceEndpoint, _p.targetEndpoint)) {
_p = null;
}
}
return _p;
}.bind(_currentInstance),
_newConnection = function (params) {
var connectionFunc = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType();
params._jsPlumb = _currentInstance;
params.newConnection = _newConnection;
params.newEndpoint = _newEndpoint;
params.endpointsByUUID = endpointsByUUID;
params.endpointsByElement = endpointsByElement;
params.finaliseConnection = _finaliseConnection;
params.id = "con_" + _idstamp();
var con = new connectionFunc(params);
// if the connection is draggable, then maybe we need to tell the target endpoint to init the
// dragging code. it won't run again if it already configured to be draggable.
if (con.isDetachable()) {
con.endpoints[0].initDraggable("_jsPlumbSource");
con.endpoints[1].initDraggable("_jsPlumbTarget");
}
return con;
},
//
// adds the connection to the backing model, fires an event if necessary and then redraws
//
_finaliseConnection = _currentInstance.finaliseConnection = function (jpc, params, originalEvent, doInformAnchorManager) {
params = params || {};
// add to list of connections (by scope).
if (!jpc.suspendedEndpoint) {
connections.push(jpc);
}
jpc.pending = null;
// turn off isTemporarySource on the source endpoint (only viable on first draw)
jpc.endpoints[0].isTemporarySource = false;
// always inform the anchor manager
// except that if jpc has a suspended endpoint it's not true to say the
// connection is new; it has just (possibly) moved. the question is whether
// to make that call here or in the anchor manager. i think perhaps here.
if (doInformAnchorManager !== false) {
_currentInstance.anchorManager.newConnection(jpc);
}
// force a paint
_draw(jpc.source);
// fire an event
if (!params.doNotFireConnectionEvent && params.fireEvent !== false) {
var eventArgs = {
connection: jpc,
source: jpc.source, target: jpc.target,
sourceId: jpc.sourceId, targetId: jpc.targetId,
sourceEndpoint: jpc.endpoints[0], targetEndpoint: jpc.endpoints[1]
};
_currentInstance.fire("connection", eventArgs, originalEvent);
}
},
/*
factory method to prepare a new endpoint. this should always be used instead of creating Endpoints
manually, since this method attaches event listeners and an id.
*/
_newEndpoint = function (params, id) {
var endpointFunc = _currentInstance.Defaults.EndpointType || jsPlumb.Endpoint;
var _p = jsPlumb.extend({}, params);
_p._jsPlumb = _currentInstance;
_p.newConnection = _newConnection;
_p.newEndpoint = _newEndpoint;
_p.endpointsByUUID = endpointsByUUID;
_p.endpointsByElement = endpointsByElement;
_p.fireDetachEvent = fireDetachEvent;
_p.elementId = id || _getId(_p.source);
var ep = new endpointFunc(_p);
ep.id = "ep_" + _idstamp();
_manage(_p.elementId, _p.source);
if (!jsPlumb.headless) {
_currentInstance.getDragManager().endpointAdded(_p.source, id);
}
return ep;
},
/*
* performs the given function operation on all the connections found
* for the given element id; this means we find all the endpoints for
* the given element, and then for each endpoint find the connectors
* connected to it. then we pass each connection in to the given
* function.
*/
_operation = function (elId, func, endpointFunc) {
var endpoints = endpointsByElement[elId];
if (endpoints && endpoints.length) {
for (var i = 0, ii = endpoints.length; i < ii; i++) {
for (var j = 0, jj = endpoints[i].connections.length; j < jj; j++) {
var retVal = func(endpoints[i].connections[j]);
// if the function passed in returns true, we exit.
// most functions return false.
if (retVal) {
return;
}
}
if (endpointFunc) {
endpointFunc(endpoints[i]);
}
}
}
},
_setDraggable = function (element, draggable) {
return jsPlumb.each(element, function (el) {
if (_currentInstance.isDragSupported(el)) {
draggableStates[_currentInstance.getAttribute(el, "id")] = draggable;
_currentInstance.setElementDraggable(el, draggable);
}
});
},
/*
* private method to do the business of hiding/showing.
*
* @param el
* either Id of the element in question or a library specific
* object for the element.
* @param state
* String specifying a value for the css 'display' property
* ('block' or 'none').
*/
_setVisible = function (el, state, alsoChangeEndpoints) {
state = state === "block";
var endpointFunc = null;
if (alsoChangeEndpoints) {
endpointFunc = function (ep) {
ep.setVisible(state, true, true);
};
}
var info = _info(el);
_operation(info.id, function (jpc) {
if (state && alsoChangeEndpoints) {
// this test is necessary because this functionality is new, and i wanted to maintain backwards compatibility.
// this block will only set a connection to be visible if the other endpoint in the connection is also visible.
var oidx = jpc.sourceId === info.id ? 1 : 0;
if (jpc.endpoints[oidx].isVisible()) {
jpc.setVisible(true);
}
}
else { // the default behaviour for show, and what always happens for hide, is to just set the visibility without getting clever.
jpc.setVisible(state);
}
}, endpointFunc);
},
/*
* toggles the draggable state of the given element(s).
* el is either an id, or an element object, or a list of ids/element objects.
*/
_toggleDraggable = function (el) {
var state;
jsPlumb.each(el, function (el) {
var elId = _currentInstance.getAttribute(el, "id");
state = draggableStates[elId] == null ? false : draggableStates[elId];
state = !state;
draggableStates[elId] = state;
_currentInstance.setDraggable(el, state);
return state;
}.bind(this));
return state;
},
/**
* private method to do the business of toggling hiding/showing.
*/
_toggleVisible = function (elId, changeEndpoints) {
var endpointFunc = null;
if (changeEndpoints) {
endpointFunc = function (ep) {
var state = ep.isVisible();
ep.setVisible(!state);
};
}
_operation(elId, function (jpc) {
var state = jpc.isVisible();
jpc.setVisible(!state);
}, endpointFunc);
},
// TODO comparison performance
_getCachedData = function (elId) {
var o = offsets[elId];
if (!o) {
return _updateOffset({elId: elId});
}
else {
return {o: o, s: sizes[elId]};
}
},
/**
* gets an id for the given element, creating and setting one if
* necessary. the id is of the form
*
* jsPlumb_<instance index>_<index in instance>
*
* where "index in instance" is a monotonically increasing integer that starts at 0,
* for each instance. this method is used not only to assign ids to elements that do not
* have them but also to connections and endpoints.
*/
_getId = function (element, uuid, doNotCreateIfNotFound) {
if (_ju.isString(element)) {
return element;
}
if (element == null) {
return null;
}
var id = _currentInstance.getAttribute(element, "id");
if (!id || id === "undefined") {
// check if fixed uuid parameter is given
if (arguments.length === 2 && arguments[1] !== undefined) {
id = uuid;
}
else if (arguments.length === 1 || (arguments.length === 3 && !arguments[2])) {
id = "jsPlumb_" + _instanceIndex + "_" + _idstamp();
}
if (!doNotCreateIfNotFound) {
_currentInstance.setAttribute(element, "id", id);
}
}
return id;
};
this.setConnectionBeingDragged = function (v) {
connectionBeingDragged = v;
};
this.isConnectionBeingDragged = function () {
return connectionBeingDragged;
};
/**
* Returns a map of all the elements this jsPlumbInstance is currently managing.
* @returns {Object} Map of [id-> {el, endpoint[], connection, position}] information.
*/
this.getManagedElements = function() {
return managedElements;
};
this.connectorClass = "jtk-connector";
this.connectorOutlineClass = "jtk-connector-outline";
this.connectedClass = "jtk-connected";
this.hoverClass = "jtk-hover";
this.endpointClass = "jtk-endpoint";
this.endpointConnectedClass = "jtk-endpoint-connected";
this.endpointFullClass = "jtk-endpoint-full";
this.endpointDropAllowedClass = "jtk-endpoint-drop-allowed";
this.endpointDropForbiddenClass = "jtk-endpoint-drop-forbidden";
this.overlayClass = "jtk-overlay";
this.draggingClass = "jtk-dragging";// CONVERTED
this.elementDraggingClass = "jtk-element-dragging";// CONVERTED
this.sourceElementDraggingClass = "jtk-source-element-dragging"; // CONVERTED
this.targetElementDraggingClass = "jtk-target-element-dragging";// CONVERTED
this.endpointAnchorClassPrefix = "jtk-endpoint-anchor";
this.hoverSourceClass = "jtk-source-hover";
this.hoverTargetClass = "jtk-target-hover";
this.dragSelectClass = "jtk-drag-select";
this.Anchors = {};
this.Connectors = { "svg": {} };
this.Endpoints = { "svg": {} };
this.Overlays = { "svg": {} } ;
this.ConnectorRenderers = {};
this.SVG = "svg";
// --------------------------- jsPlumbInstance public API ---------------------------------------------------------
this.addEndpoint = function (el, params, referenceParams) {
referenceParams = referenceParams || {};
var p = jsPlumb.extend({}, referenceParams);
jsPlumb.extend(p, params);
p.endpoint = p.endpoint || _currentInstance.Defaults.Endpoint;
p.paintStyle = p.paintStyle || _currentInstance.Defaults.EndpointStyle;
var results = [],
inputs = (_ju.isArray(el) || (el.length != null && !_ju.isString(el))) ? el : [ el ];
for (var i = 0, j = inputs.length; i < j; i++) {
p.source = _currentInstance.getElement(inputs[i]);
_ensureContainer(p.source);
var id = _getId(p.source), e = _newEndpoint(p, id);
// ensure element is managed.
var myOffset = _manage(id, p.source).info.o;
_ju.addToList(endpointsByElement, id, e);
if (!_suspendDrawing) {
e.paint({
anchorLoc: e.anchor.compute({ xy: [ myOffset.left, myOffset.top ], wh: sizes[id], element: e, timestamp: _suspendedAt }),
timestamp: _suspendedAt
});
}
results.push(e);
}
return results.length === 1 ? results[0] : results;
};
this.addEndpoints = function (el, endpoints, referenceParams) {
var results = [];
for (var i = 0, j = endpoints.length; i < j; i++) {
var e = _currentInstance.addEndpoint(el, endpoints[i], referenceParams);
if (_ju.isArray(e)) {
Array.prototype.push.apply(results, e);
}
else {
results.push(e);
}
}
return results;
};
this.animate = function (el, properties, options) {
if (!this.animationSupported) {
return false;
}
options = options || {};
var del = _currentInstance.getElement(el),
id = _getId(del),
stepFunction = jsPlumb.animEvents.step,
completeFunction = jsPlumb.animEvents.complete;
options[stepFunction] = _ju.wrap(options[stepFunction], function () {
_currentInstance.revalidate(id);
});
// onComplete repaints, just to make sure everything looks good at the end of the animation.
options[completeFunction] = _ju.wrap(options[completeFunction], function () {
_currentInstance.revalidate(id);
});
_currentInstance.doAnimate(del, properties, options);
};
/**
* checks for a listener for the given condition, executing it if found, passing in the given value.
* condition listeners would have been attached using "bind" (which is, you could argue, now overloaded, since
* firing click events etc is a bit different to what this does). i thought about adding a "bindCondition"
* or something, but decided against it, for the sake of simplicity. jsPlumb will never fire one of these
* condition events anyway.
*/
this.checkCondition = function (conditionName, args) {
var l = _currentInstance.getListener(conditionName),
r = true;
if (l && l.length > 0) {
var values = Array.prototype.slice.call(arguments, 1);
try {
for (var i = 0, j = l.length; i < j; i++) {
r = r && l[i].apply(l[i], values);
}
}
catch (e) {
_ju.log(_currentInstance, "cannot check condition [" + conditionName + "]" + e);
}
}
return r;
};
this.connect = function (params, referenceParams) {
// prepare a final set of parameters to create connection with
var _p = _prepareConnectionParams(params, referenceParams), jpc;
// TODO probably a nicer return value if the connection was not made. _prepareConnectionParams
// will return null (and log something) if either endpoint was full. what would be nicer is to
// create a dedicated 'error' object.
if (_p) {
if (_p.source == null && _p.sourceEndpoint == null) {
_ju.log("Cannot establish connection - source does not exist");
return;
}
if (_p.target == null && _p.targetEndpoint == null) {
_ju.log("Cannot establish connection - target does not exist");
return;
}
_ensureContainer(_p.source);
// create the connection. it is not yet registered
jpc = _newConnection(_p);
// now add it the model, fire an event, and redraw
_finaliseConnection(jpc, _p);
}
return jpc;
};
var stTypes = [
{ el: "source", elId: "sourceId", epDefs: "sourceEndpointDefinitions" },
{ el: "target", elId: "targetId", epDefs: "targetEndpointDefinitions" }
];
var _set = function (c, el, idx, doNotRepaint) {
var ep, _st = stTypes[idx], cId = c[_st.elId], cEl = c[_st.el], sid, sep,
oldEndpoint = c.endpoints[idx];
var evtParams = {
index: idx,
originalSourceId: idx === 0 ? cId : c.sourceId,
newSourceId: c.sourceId,
originalTargetId: idx === 1 ? cId : c.targetId,
newTargetId: c.targetId,
connection: c
};
if (el.constructor === jsPlumb.Endpoint) {
ep = el;
ep.addConnection(c);
el = ep.element;
}
else {
sid = _getId(el);
sep = this[_st.epDefs][sid];
if (sid === c[_st.elId]) {
ep = null; // dont change source/target if the element is already the one given.
}
else if (sep) {
for (var t in sep) {
if (!sep[t].enabled) {
return;
}
ep = sep[t].endpoint != null && sep[t].endpoint._jsPlumb ? sep[t].endpoint : this.addEndpoint(el, sep[t].def);
if (sep[t].uniqueEndpoint) {
sep[t].endpoint = ep;
}
ep.addConnection(c);
}
}
else {
ep = c.makeEndpoint(idx === 0, el, sid);
}
}
if (ep != null) {
oldEndpoint.detachFromConnection(c);
c.endpoints[idx] = ep;
c[_st.el] = ep.element;
c[_st.elId] = ep.elementId;
evtParams[idx === 0 ? "newSourceId" : "newTargetId"] = ep.elementId;
fireMoveEvent(evtParams);
if (!doNotRepaint) {
c.repaint();
}
}
evtParams.element = el;
return evtParams;
}.bind(this);
this.setSource = function (connection, el, doNotRepaint) {
var p = _set(connection, el, 0, doNotRepaint);
this.anchorManager.sourceChanged(p.originalSourceId, p.newSourceId, connection, p.el);
};
this.setTarget = function (connection, el, doNotRepaint) {
var p = _set(connection, el, 1, doNotRepaint);
this.anchorManager.updateOtherEndpoint(p.originalSourceId, p.originalTargetId, p.newTargetId, connection);
};
this.deleteEndpoint = function (object, dontUpdateHover, deleteAttachedObjects) {
var endpoint = (typeof object === "string") ? endpointsByUUID[object] : object;
if (endpoint) {
_currentInstance.deleteObject({ endpoint: endpoint, dontUpdateHover: dontUpdateHover, deleteAttachedObjects:deleteAttachedObjects });
}
return _currentInstance;
};
this.deleteEveryEndpoint = function () {
var _is = _currentInstance.setSuspendDrawing(true);
for (var id in endpointsByElement) {
var endpoints = endpointsByElement[id];
if (endpoints && endpoints.length) {
for (var i = 0, j = endpoints.length; i < j; i++) {
_currentInstance.deleteEndpoint(endpoints[i], true);
}
}
}
endpointsByElement = {};
managedElements = {};
endpointsByUUID = {};
offsets = {};
offsetTimestamps = {};
_currentInstance.anchorManager.reset();
var dm = _currentInstance.getDragManager();
if (dm) {
dm.reset();
}
if (!_is) {
_currentInstance.setSuspendDrawing(false);
}
return _currentInstance;
};
var fireDetachEvent = function (jpc, doFireEvent, originalEvent) {
// may have been given a connection, or in special cases, an object
var connType = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType(),
argIsConnection = jpc.constructor === connType,
params = argIsConnection ? {
connection: jpc,
source: jpc.source, target: jpc.target,
sourceId: jpc.sourceId, targetId: jpc.targetId,
sourceEndpoint: jpc.endpoints[0], targetEndpoint: jpc.endpoints[1]
} : jpc;
if (doFireEvent) {
_currentInstance.fire("connectionDetached", params, originalEvent);
}
// always fire this. used by internal jsplumb stuff.
_currentInstance.fire("internal.connectionDetached", params, originalEvent);
_currentInstance.anchorManager.connectionDetached(params);
};
var fireMoveEvent = _currentInstance.fireMoveEvent = function (params, evt) {
_currentInstance.fire("connectionMoved", params, evt);
};
this.unregisterEndpoint = function (endpoint) {
if (endpoint._jsPlumb.uuid) {
endpointsByUUID[endpoint._jsPlumb.uuid] = null;
}
_currentInstance.anchorManager.deleteEndpoint(endpoint);
// TODO at least replace this with a removeWithFunction call.
for (var e in endpointsByElement) {
var endpoints = endpointsByElement[e];
if (endpoints) {
var newEndpoints = [];
for (var i = 0, j = endpoints.length; i < j; i++) {
if (endpoints[i] !== endpoint) {
newEndpoints.push(endpoints[i]);
}
}
endpointsByElement[e] = newEndpoints;
}
if (endpointsByElement[e].length < 1) {
delete endpointsByElement[e];
}
}
};
var IS_DETACH_ALLOWED = "isDetachAllowed";
var BEFORE_DETACH = "beforeDetach";
var CHECK_CONDITION = "checkCondition";
/**
* Deletes a Connection.
* @method deleteConnection
* @param connection Connection to delete
* @param {Object} [params] Optional delete parameters
* @param {Boolean} [params.doNotFireEvent=false] If true, a connection detached event will not be fired. Otherwise one will.
* @param {Boolean} [params.force=false] If true, the connection will be deleted even if a beforeDetach interceptor tries to stop the deletion.
* @returns {Boolean} True if the connection was deleted, false otherwise.
*/
this.deleteConnection = function(connection, params) {
if (connection != null) {
params = params || {};
if (params.force || _ju.functionChain(true, false, [
[ connection.endpoints[0], IS_DETACH_ALLOWED, [ connection ] ],
[ connection.endpoints[1], IS_DETACH_ALLOWED, [ connection ] ],
[ connection, IS_DETACH_ALLOWED, [ connection ] ],
[ _currentInstance, CHECK_CONDITION, [ BEFORE_DETACH, connection ] ]
])) {
connection.setHover(false);
fireDetachEvent(connection, !connection.pending && params.fireEvent !== false, params.originalEvent);
connection.endpoints[0].detachFromConnection(connection);
connection.endpoints[1].detachFromConnection(connection);
_ju.removeWithFunction(connections, function (_c) {
return connection.id === _c.id;
});
connection.cleanup();
connection.destroy();
return true;
}
}
return false;
};
/**
* Remove all Connections from all elements, but leaves Endpoints in place ((unless a connection is set to auto delete its Endpoints).
* @method deleteEveryConnection
* @param {Object} [params] optional params object for the call
* @param {Boolean} [params.fireEvent=true] Whether or not to fire detach events
* @param {Boolean} [params.forceDetach=false] If true, this call will ignore any `beforeDetach` interceptors.
* @returns {Number} The number of connections that were deleted.
*/
this.deleteEveryConnection = function (params) {
params = params || {};
var count = connections.length, deletedCount = 0;
_currentInstance.batch(function () {
for (var i = 0; i < count; i++) {
deletedCount += _currentInstance.deleteConnection(connections[0], params) ? 1 : 0;
}
});
return deletedCount;
};
/**
* Removes all an element's Connections.
* @method deleteConnectionsForElement
* @param {Object} el Either the id of the element, or a selector for the element.
* @param {Object} [params] Optional parameters.
* @param {Boolean} [params.fireEvent=true] Whether or not to fire the detach event.
* @param {Boolean} [params.forceDetach=false] If true, this call will ignore any `beforeDetach` interceptors.
* @return {jsPlumbInstance} The current jsPlumb instance.
*/
this.deleteConnectionsForElement = function (el, params) {
params = params || {};
el = _currentInstance.getElement(el);
var id = _getId(el), endpoints = endpointsByElement[id];
if (endpoints && endpoints.length) {
for (var i = 0, j = endpoints.length; i < j; i++) {
endpoints[i].deleteEveryConnection(params);
}
}
return _currentInstance;
};
/// not public. but of course its exposed. how to change this.
this.deleteObject = function (params) {
var result = {
endpoints: {},
connections: {},
endpointCount: 0,
connectionCount: 0
},
deleteAttachedObjects = params.deleteAttachedObjects !== false;
var unravelConnection = function (connection) {
if (connection != null && result.connections[connection.id] == null) {
if (!params.dontUpdateHover && connection._jsPlumb != null) {
connection.setHover(false);
}
result.connections[connection.id] = connection;
result.connectionCount++;
}
};
var unravelEndpoint = function (endpoint) {
if (endpoint != null && result.endpoints[endpoint.id] == null) {
if (!params.dontUpdateHover && endpoint._jsPlumb != null) {
endpoint.setHover(false);
}
result.endpoints[endpoint.id] = endpoint;
result.endpointCount++;
if (deleteAttachedObjects) {
for (var i = 0; i < endpoint.connections.length; i++) {
var c = endpoint.connections[i];
unravelConnection(c);
}
}
}
};
if (params.connection) {
unravelConnection(params.connection);
}
else {
unravelEndpoint(params.endpoint);
}
// loop through connections
for (var i in result.connections) {
var c = result.connections[i];
if (c._jsPlumb) {
_ju.removeWithFunction(connections, function (_c) {
return c.id === _c.id;
});
fireDetachEvent(c, params.fireEvent === false ? false : !c.pending, params.originalEvent);
var doNotCleanup = params.deleteAttachedObjects == null ? null : !params.deleteAttachedObjects;
c.endpoints[0].detachFromConnection(c, null, doNotCleanup);
c.endpoints[1].detachFromConnection(c, null, doNotCleanup);
c.cleanup(true);
c.destroy(true);
}
}
// loop through endpoints
for (var j in result.endpoints) {
var e = result.endpoints[j];
if (e._jsPlumb) {
_currentInstance.unregisterEndpoint(e);
// FIRE some endpoint deleted event?
e.cleanup(true);
e.destroy(true);
}
}
return result;
};
this.draggable = function (el, options) {
var info;
_each(function(_el) {
info = _info(_el);
if (info.el) {
_initDraggableIfNecessary(info.el, true, options, info.id, true);
}
}, el);
return _currentInstance;
};
this.droppable = function(el, options) {
var info;
options = options || {};
options.allowLoopback = false;
_each(function(_el) {
info = _info(_el);
if (info.el) {
_currentInstance.initDroppable(info.el, options);
}
}, el);
return _currentInstance;
};
// helpers for select/selectEndpoints
var _setOperation = function (list, func, args, selector) {
for (var i = 0, j = list.length; i < j; i++) {
list[i][func].apply(list[i], args);
}
return selector(list);
},
_getOperation = function (list, func, args) {
var out = [];
for (var i = 0, j = list.length; i < j; i++) {
out.push([ list[i][func].apply(list[i], args), list[i] ]);
}
return out;
},
setter = function (list, func, selector) {
return function () {
return _setOperation(list, func, arguments, selector);
};
},
getter = function (list, func) {
return function () {
return _getOperation(list, func, arguments);
};
},
prepareList = function (input, doNotGetIds) {
var r = [];
if (input) {
if (typeof input === 'string') {
if (input === "*") {
return input;
}
r.push(input);
}
else {
if (doNotGetIds) {
r = input;
}
else {
if (input.length) {
for (var i = 0, j = input.length; i < j; i++) {
r.push(_info(input[i]).id);
}
}
else {
r.push(_info(input).id);
}
}
}
}
return r;
},
filterList = function (list, value, missingIsFalse) {
if (list === "*") {
return true;
}
return list.length > 0 ? list.indexOf(value) !== -1 : !missingIsFalse;
};
// get some connections, specifying source/target/scope
this.getConnections = function (options, flat) {
if (!options) {
options = {};
} else if (options.constructor === String) {
options = { "scope": options };
}
var scope = options.scope || _currentInstance.getDefaultScope(),
scopes = prepareList(scope, true),
sources = prepareList(options.source),
targets = prepareList(options.target),
results = (!flat && scopes.length > 1) ? {} : [],
_addOne = function (scope, obj) {
if (!flat && scopes.length > 1) {
var ss = results[scope];
if (ss == null) {
ss = results[scope] = [];
}
ss.push(obj);
} else {
results.push(obj);
}
};
for (var j = 0, jj = connections.length; j < jj; j++) {
var c = connections[j],
sourceId = c.proxies && c.proxies[0] ? c.proxies[0].originalEp.elementId : c.sourceId,
targetId = c.proxies && c.proxies[1] ? c.proxies[1].originalEp.elementId : c.targetId;
if (filterList(scopes, c.scope) && filterList(sources, sourceId) && filterList(targets, targetId)) {
_addOne(c.scope, c);
}
}
return results;
};
var _curryEach = function (list, executor) {
return function (f) {
for (var i = 0, ii = list.length; i < ii; i++) {
f(list[i]);
}
return executor(list);
};
},
_curryGet = function (list) {
return function (idx) {
return list[idx];
};
};
var _makeCommonSelectHandler = function (list, executor) {
var out = {
length: list.length,
each: _curryEach(list, executor),
get: _curryGet(list)
},
setters = ["setHover", "removeAllOverlays", "setLabel", "addClass", "addOverlay", "removeOverlay",
"removeOverlays", "showOverlay", "hideOverlay", "showOverlays", "hideOverlays", "setPaintStyle",
"setHoverPaintStyle", "setSuspendEvents", "setParameter", "setParameters", "setVisible",
"repaint", "addType", "toggleType", "removeType", "removeClass", "setType", "bind", "unbind" ],
getters = ["getLabel", "getOverlay", "isHover", "getParameter", "getParameters", "getPaintStyle",
"getHoverPaintStyle", "isVisible", "hasType", "getType", "isSuspendEvents" ],
i, ii;
for (i = 0, ii = setters.length; i < ii; i++) {
out[setters[i]] = setter(list, setters[i], executor);
}
for (i = 0, ii = getters.length; i < ii; i++) {
out[getters[i]] = getter(list, getters[i]);
}
return out;
};
var _makeConnectionSelectHandler = function (list) {
var common = _makeCommonSelectHandler(list, _makeConnectionSelectHandler);
return jsPlumb.extend(common, {
// setters
setDetachable: setter(list, "setDetachable", _makeConnectionSelectHandler),
setReattach: setter(list, "setReattach", _makeConnectionSelectHandler),
setConnector: setter(list, "setConnector", _makeConnectionSelectHandler),
delete: function () {
for (var i = 0, ii = list.length; i < ii; i++) {
_currentInstance.deleteConnection(list[i]);
}
},
// getters
isDetachable: getter(list, "isDetachable"),
isReattach: getter(list, "isReattach")
});
};
var _makeEndpointSelectHandler = function (list) {
var common = _makeCommonSelectHandler(list, _makeEndpointSelectHandler);
return jsPlumb.extend(common, {
setEnabled: setter(list, "setEnabled", _makeEndpointSelectHandler),
setAnchor: setter(list, "setAnchor", _makeEndpointSelectHandler),
isEnabled: getter(list, "isEnabled"),
deleteEveryConnection: function () {
for (var i = 0, ii = list.length; i < ii; i++) {
list[i].deleteEveryConnection();
}
},
"delete": function () {
for (var i = 0, ii = list.length; i < ii; i++) {
_currentInstance.deleteEndpoint(list[i]);
}
}
});
};
this.select = function (params) {
params = params || {};
params.scope = params.scope || "*";
return _makeConnectionSelectHandler(params.connections || _currentInstance.getConnections(params, true));
};
this.selectEndpoints = function (params) {
params = params || {};
params.scope = params.scope || "*";
var noElementFilters = !params.element && !params.source && !params.target,
elements = noElementFilters ? "*" : prepareList(params.element),
sources = noElementFilters ? "*" : prepareList(params.source),
targets = noElementFilters ? "*" : prepareList(params.target),
scopes = prepareList(params.scope, true);
var ep = [];
for (var el in endpointsByElement) {
var either = filterList(elements, el, true),
source = filterList(sources, el, true),
sourceMatchExact = sources !== "*",
target = filterList(targets, el, true),
targetMatchExact = targets !== "*";
// if they requested 'either' then just match scope. otherwise if they requested 'source' (not as a wildcard) then we have to match only endpoints that have isSource set to to true, and the same thing with isTarget.
if (either || source || target) {
inner:
for (var i = 0, ii = endpointsByElement[el].length; i < ii; i++) {
var _ep = endpointsByElement[el][i];
if (filterList(scopes, _ep.scope, true)) {
var noMatchSource = (sourceMatchExact && sources.length > 0 && !_ep.isSource),
noMatchTarget = (targetMatchExact && targets.length > 0 && !_ep.isTarget);
if (noMatchSource || noMatchTarget) {
continue inner;
}
ep.push(_ep);
}
}
}
}
return _makeEndpointSelectHandler(ep);
};
// get all connections managed by the instance of jsplumb.
this.getAllConnections = function () {
return connections;
};
this.getDefaultScope = function () {
return DEFAULT_SCOPE;
};
// get an endpoint by uuid.
this.getEndpoint = _getEndpoint;
/**
* Gets the list of Endpoints for a given element.
* @method getEndpoints
* @param {String|Element|Selector} el The element to get endpoints for.
* @return {Endpoint[]} An array of Endpoints for the specified element.
*/
this.getEndpoints = function (el) {
return endpointsByElement[_info(el).id] || [];
};
// gets the default endpoint type. used when subclassing. see wiki.
this.getDefaultEndpointType = function () {
return jsPlumb.Endpoint;
};
// gets the default connection type. used when subclassing. see wiki.
this.getDefaultConnectionType = function () {
return jsPlumb.Connection;
};
/*
* Gets an element's id, creating one if necessary. really only exposed
* for the lib-specific functionality to access; would be better to pass
* the current instance into the lib-specific code (even though this is
* a static call. i just don't want to expose it to the public API).
*/
this.getId = _getId;
this.appendElement = _appendElement;
var _hoverSuspended = false;
this.isHoverSuspended = function () {
return _hoverSuspended;
};
this.setHoverSuspended = function (s) {
_hoverSuspended = s;
};
// set an element's connections to be hidden
this.hide = function (el, changeEndpoints) {
_setVisible(el, "none", changeEndpoints);
return _currentInstance;
};
// exposed for other objects to use to get a unique id.
this.idstamp = _idstamp;
// this.connectorsInitialized = false;
// this.registerConnectorType = function (connector, name) {
// connectorTypes.push([connector, name]);
// };
// ensure that, if the current container exists, it is a DOM element and not a selector.
// if it does not exist and `candidate` is supplied, the offset parent of that element will be set as the Container.
// this is used to do a better default behaviour for the case that the user has not set a container:
// addEndpoint, makeSource, makeTarget and connect all call this method with the offsetParent of the
// element in question (for connect it is the source element). So if no container is set, it is inferred
// to be the offsetParent of the first element the user tries to connect.
var _ensureContainer = function (candidate) {
if (!_container && candidate) {
var can = _currentInstance.getElement(candidate);
if (can.offsetParent) {
_currentInstance.setContainer(can.offsetParent);
}
}
};
var _getContainerFromDefaults = function () {
if (_currentInstance.Defaults.Container) {
_currentInstance.setContainer(_currentInstance.Defaults.Container);
}
};
// check if a given element is managed or not. if not, add to our map. if drawing is not suspended then
// we'll also stash its dimensions; otherwise we'll do this in a lazy way through updateOffset.
var _manage = _currentInstance.manage = function (id, element, _transient) {
if (!managedElements[id]) {
managedElements[id] = {
el: element,
endpoints: [],
connections: []
};
managedElements[id].info = _updateOffset({ elId: id, timestamp: _suspendedAt });
if (!_transient) {
_currentInstance.fire("manageElement", { id:id, info:managedElements[id].info, el:element });
}
}
return managedElements[id];
};
var _unmanage = function(id) {
if (managedElements[id]) {
delete managedElements[id];
_currentInstance.fire("unmanageElement", id);
}
};
/**
* updates the offset and size for a given element, and stores the
* values. if 'offset' is not null we use that (it would have been
* passed in from a drag call) because it's faster; but if it is null,
* or if 'recalc' is true in order to force a recalculation, we get the current values.
* @method updateOffset
*/
var _updateOffset = function (params) {
var timestamp = params.timestamp, recalc = params.recalc, offset = params.offset, elId = params.elId, s;
if (_suspendDrawing && !timestamp) {
timestamp = _suspendedAt;
}
if (!recalc) {
if (timestamp && timestamp === offsetTimestamps[elId]) {
return {o: params.offset || offsets[elId], s: sizes[elId]};
}
}
if (recalc || (!offset && offsets[elId] == null)) { // if forced repaint or no offset available, we recalculate.
// get the current size and offset, and store them
s = managedElements[elId] ? managedElements[elId].el : null;
if (s != null) {
sizes[elId] = _currentInstance.getSize(s);
offsets[elId] = _currentInstance.getOffset(s);
offsetTimestamps[elId] = timestamp;
}
} else {
offsets[elId] = offset || offsets[elId];
if (sizes[elId] == null) {
s = managedElements[elId].el;
if (s != null) {
sizes[elId] = _currentInstance.getSize(s);
}
}
offsetTimestamps[elId] = timestamp;
}
if (offsets[elId] && !offsets[elId].right) {
offsets[elId].right = offsets[elId].left + sizes[elId][0];
offsets[elId].bottom = offsets[elId].top + sizes[elId][1];
offsets[elId].width = sizes[elId][0];
offsets[elId].height = sizes[elId][1];
offsets[elId].centerx = offsets[elId].left + (offsets[elId].width / 2);
offsets[elId].centery = offsets[elId].top + (offsets[elId].height / 2);
}
return {o: offsets[elId], s: sizes[elId]};
};
this.updateOffset = _updateOffset;
/**
* callback from the current library to tell us to prepare ourselves (attach
* mouse listeners etc; can't do that until the library has provided a bind method)
*/
this.init = function () {
if (!initialized) {
_getContainerFromDefaults();
_currentInstance.anchorManager = new root.jsPlumb.AnchorManager({jsPlumbInstance: _currentInstance});
initialized = true;
_currentInstance.fire("ready", _currentInstance);
}
}.bind(this);
this.log = log;
this.jsPlumbUIComponent = jsPlumbUIComponent;
/*
* Creates an anchor with the given params.
*
*
* Returns: The newly created Anchor.
* Throws: an error if a named anchor was not found.
*/
this.makeAnchor = function () {
var pp, _a = function (t, p) {
if (root.jsPlumb.Anchors[t]) {
return new root.jsPlumb.Anchors[t](p);
}
if (!_currentInstance.Defaults.DoNotThrowErrors) {
throw { msg: "jsPlumb: unknown anchor type '" + t + "'" };
}
};
if (arguments.length === 0) {
return null;
}
var specimen = arguments[0], elementId = arguments[1], jsPlumbInstance = arguments[2], newAnchor = null;
// if it appears to be an anchor already...
if (specimen.compute && specimen.getOrientation) {
return specimen;
} //TODO hazy here about whether it should be added or is already added somehow.
// is it the name of an anchor type?
else if (typeof specimen === "string") {
newAnchor = _a(arguments[0], {elementId: elementId, jsPlumbInstance: _currentInstance});
}
// is it an array? it will be one of:
// an array of [spec, params] - this defines a single anchor, which may be dynamic, but has parameters.
// an array of arrays - this defines some dynamic anchors
// an array of numbers - this defines a single anchor.
else if (_ju.isArray(specimen)) {
if (_ju.isArray(specimen[0]) || _ju.isString(specimen[0])) {
// if [spec, params] format
if (specimen.length === 2 && _ju.isObject(specimen[1])) {
// if first arg is a string, its a named anchor with params
if (_ju.isString(specimen[0])) {
pp = root.jsPlumb.extend({elementId: elementId, jsPlumbInstance: _currentInstance}, specimen[1]);
newAnchor = _a(specimen[0], pp);
}
// otherwise first arg is array, second is params. we treat as a dynamic anchor, which is fine
// even if the first arg has only one entry. you could argue all anchors should be implicitly dynamic in fact.
else {
pp = root.jsPlumb.extend({elementId: elementId, jsPlumbInstance: _currentInstance, anchors: specimen[0]}, specimen[1]);
newAnchor = new root.jsPlumb.DynamicAnchor(pp);
}
}
else {
newAnchor = new jsPlumb.DynamicAnchor({anchors: specimen, selector: null, elementId: elementId, jsPlumbInstance: _currentInstance});
}
}
else {
var anchorParams = {
x: specimen[0], y: specimen[1],
orientation: (specimen.length >= 4) ? [ specimen[2], specimen[3] ] : [0, 0],
offsets: (specimen.length >= 6) ? [ specimen[4], specimen[5] ] : [ 0, 0 ],
elementId: elementId,
jsPlumbInstance: _currentInstance,
cssClass: specimen.length === 7 ? specimen[6] : null
};
newAnchor = new root.jsPlumb.Anchor(anchorParams);
newAnchor.clone = function () {
return new root.jsPlumb.Anchor(anchorParams);
};
}
}
if (!newAnchor.id) {
newAnchor.id = "anchor_" + _idstamp();
}
return newAnchor;
};
/**
* makes a list of anchors from the given list of types or coords, eg
* ["TopCenter", "RightMiddle", "BottomCenter", [0, 1, -1, -1] ]
*/
this.makeAnchors = function (types, elementId, jsPlumbInstance) {
var r = [];
for (var i = 0, ii = types.length; i < ii; i++) {
if (typeof types[i] === "string") {
r.push(root.jsPlumb.Anchors[types[i]]({elementId: elementId, jsPlumbInstance: jsPlumbInstance}));
}
else if (_ju.isArray(types[i])) {
r.push(_currentInstance.makeAnchor(types[i], elementId, jsPlumbInstance));
}
}
return r;
};
/**
* Makes a dynamic anchor from the given list of anchors (which may be in shorthand notation as strings or dimension arrays, or Anchor
* objects themselves) and the given, optional, anchorSelector function (jsPlumb uses a default if this is not provided; most people will
* not need to provide this - i think).
*/
this.makeDynamicAnchor = function (anchors, anchorSelector) {
return new root.jsPlumb.DynamicAnchor({anchors: anchors, selector: anchorSelector, elementId: null, jsPlumbInstance: _currentInstance});
};
// --------------------- makeSource/makeTarget ----------------------------------------------
this.targetEndpointDefinitions = {};
this.sourceEndpointDefinitions = {};
var selectorFilter = function (evt, _el, selector, _instance, negate) {
var t = evt.target || evt.srcElement, ok = false,
sel = _instance.getSelector(_el, selector);
for (var j = 0; j < sel.length; j++) {
if (sel[j] === t) {
ok = true;
break;
}
}
return negate ? !ok : ok;
};
var _makeElementDropHandler = function (elInfo, p, dropOptions, isSource, isTarget) {
var proxyComponent = new jsPlumbUIComponent(p);
var _drop = p._jsPlumb.EndpointDropHandler({
jsPlumb: _currentInstance,
enabled: function () {
return elInfo.def.enabled;
},
isFull: function () {
var targetCount = _currentInstance.select({target: elInfo.id}).length;
return elInfo.def.maxConnections > 0 && targetCount >= elInfo.def.maxConnections;
},
element: elInfo.el,
elementId: elInfo.id,
isSource: isSource,
isTarget: isTarget,
addClass: function (clazz) {
_currentInstance.addClass(elInfo.el, clazz);
},
removeClass: function (clazz) {
_currentInstance.removeClass(elInfo.el, clazz);
},
onDrop: function (jpc) {
var source = jpc.endpoints[0];
source.anchor.unlock();
},
isDropAllowed: function () {
return proxyComponent.isDropAllowed.apply(proxyComponent, arguments);
},
isRedrop:function(jpc) {
return (jpc.suspendedElement != null && jpc.suspendedEndpoint != null && jpc.suspendedEndpoint.element === elInfo.el);
},
getEndpoint: function (jpc) {
// make a new Endpoint for the target, or get it from the cache if uniqueEndpoint
// is set. if its a redrop the new endpoint will be immediately cleaned up.
var newEndpoint = elInfo.def.endpoint;
// if no cached endpoint, or there was one but it has been cleaned up
// (ie. detached), create a new one
if (newEndpoint == null || newEndpoint._jsPlumb == null) {
var eps = _currentInstance.deriveEndpointAndAnchorSpec(jpc.getType().join(" "), true);
var pp = eps.endpoints ? root.jsPlumb.extend(p, {
endpoint:elInfo.def.def.endpoint || eps.endpoints[1]
}) :p;
if (eps.anchors) {
pp = root.jsPlumb.extend(pp, {
anchor:elInfo.def.def.anchor || eps.anchors[1]
});
}
newEndpoint = _currentInstance.addEndpoint(elInfo.el, pp);
newEndpoint._mtNew = true;
}
if (p.uniqueEndpoint) {
elInfo.def.endpoint = newEndpoint;
}
newEndpoint.setDeleteOnEmpty(true);
// if connection is detachable, init the new endpoint to be draggable, to support that happening.
if (jpc.isDetachable()) {
newEndpoint.initDraggable();
}
// if the anchor has a 'positionFinder' set, then delegate to that function to find
// out where to locate the anchor.
if (newEndpoint.anchor.positionFinder != null) {
var dropPosition = _currentInstance.getUIPosition(arguments, _currentInstance.getZoom()),
elPosition = _currentInstance.getOffset(elInfo.el),
elSize = _currentInstance.getSize(elInfo.el),
ap = dropPosition == null ? [0,0] : newEndpoint.anchor.positionFinder(dropPosition, elPosition, elSize, newEndpoint.anchor.constructorParams);
newEndpoint.anchor.x = ap[0];
newEndpoint.anchor.y = ap[1];
// now figure an orientation for it..kind of hard to know what to do actually. probably the best thing i can do is to
// support specifying an orientation in the anchor's spec. if one is not supplied then i will make the orientation
// be what will cause the most natural link to the source: it will be pointing at the source, but it needs to be
// specified in one axis only, and so how to make that choice? i think i will use whichever axis is the one in which
// the target is furthest away from the source.
}
return newEndpoint;
},
maybeCleanup: function (ep) {
if (ep._mtNew && ep.connections.length === 0) {
_currentInstance.deleteObject({endpoint: ep});
}
else {
delete ep._mtNew;
}
}
});
// wrap drop events as needed and initialise droppable
var dropEvent = root.jsPlumb.dragEvents.drop;
dropOptions.scope = dropOptions.scope || (p.scope || _currentInstance.Defaults.Scope);
dropOptions[dropEvent] = _ju.wrap(dropOptions[dropEvent], _drop, true);
dropOptions.rank = p.rank || 0;
// if target, return true from the over event. this will cause katavorio to stop setting drops to hover
// if multipleDrop is set to false.
if (isTarget) {
dropOptions[root.jsPlumb.dragEvents.over] = function () { return true; };
}
// vanilla jsplumb only
if (p.allowLoopback === false) {
dropOptions.canDrop = function (_drag) {
var de = _drag.getDragElement()._jsPlumbRelatedElement;
return de !== elInfo.el;
};
}
_currentInstance.initDroppable(elInfo.el, dropOptions, "internal");
return _drop;
};
// see API docs
this.makeTarget = function (el, params, referenceParams) {
// put jsplumb ref into params without altering the params passed in
var p = root.jsPlumb.extend({_jsPlumb: this}, referenceParams);
root.jsPlumb.extend(p, params);
var maxConnections = p.maxConnections || -1,
_doOne = function (el) {
// get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these,
// and use the endpoint definition if found.
// decode the info for this element (id and element)
var elInfo = _info(el),
elid = elInfo.id,
dropOptions = root.jsPlumb.extend({}, p.dropOptions || {}),
type = p.connectionType || "default";
this.targetEndpointDefinitions[elid] = this.targetEndpointDefinitions[elid] || {};
_ensureContainer(elid);
// if this is a group and the user has not mandated a rank, set to -1 so that Nodes takes
// precedence.
if (elInfo.el._isJsPlumbGroup && dropOptions.rank == null) {
dropOptions.rank = -1;
}
// store the definition
var _def = {
def: root.jsPlumb.extend({}, p),
uniqueEndpoint: p.uniqueEndpoint,
maxConnections: maxConnections,
enabled: true
};
if (p.createEndpoint) {
_def.uniqueEndpoint = true;
_def.endpoint = _currentInstance.addEndpoint(el, _def.def);
_def.endpoint.setDeleteOnEmpty(false);
}
elInfo.def = _def;
this.targetEndpointDefinitions[elid][type] = _def;
_makeElementDropHandler(elInfo, p, dropOptions, p.isSource === true, true);
// stash the definition on the drop
elInfo.el._katavorioDrop[elInfo.el._katavorioDrop.length - 1].targetDef = _def;
}.bind(this);
// make an array if only given one element
var inputs = el.length && el.constructor !== String ? el : [ el ];
// register each one in the list.
for (var i = 0, ii = inputs.length; i < ii; i++) {
_doOne(inputs[i]);
}
return this;
};
// see api docs
this.unmakeTarget = function (el, doNotClearArrays) {
var info = _info(el);
_currentInstance.destroyDroppable(info.el, "internal");
if (!doNotClearArrays) {
delete this.targetEndpointDefinitions[info.id];
}
return this;
};
// see api docs
this.makeSource = function (el, params, referenceParams) {
var p = root.jsPlumb.extend({_jsPlumb: this}, referenceParams);
root.jsPlumb.extend(p, params);
var type = p.connectionType || "default";
var aae = _currentInstance.deriveEndpointAndAnchorSpec(type);
p.endpoint = p.endpoint || aae.endpoints[0];
p.anchor = p.anchor || aae.anchors[0];
var maxConnections = p.maxConnections || -1,
onMaxConnections = p.onMaxConnections,
_doOne = function (elInfo) {
// get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these,
// and use the endpoint definition if found.
var elid = elInfo.id,
_del = this.getElement(elInfo.el);
this.sourceEndpointDefinitions[elid] = this.sourceEndpointDefinitions[elid] || {};
_ensureContainer(elid);
var _def = {
def:root.jsPlumb.extend({}, p),
uniqueEndpoint: p.uniqueEndpoint,
maxConnections: maxConnections,
enabled: true
};
if (p.createEndpoint) {
_def.uniqueEndpoint = true;
_def.endpoint = _currentInstance.addEndpoint(el, _def.def);
_def.endpoint.setDeleteOnEmpty(false);
}
this.sourceEndpointDefinitions[elid][type] = _def;
elInfo.def = _def;
var stopEvent = root.jsPlumb.dragEvents.stop,
dragEvent = root.jsPlumb.dragEvents.drag,
dragOptions = root.jsPlumb.extend({ }, p.dragOptions || {}),
existingDrag = dragOptions.drag,
existingStop = dragOptions.stop,
ep = null,
endpointAddedButNoDragYet = false;
// set scope if its not set in dragOptions but was passed in in params
dragOptions.scope = dragOptions.scope || p.scope;
dragOptions[dragEvent] = _ju.wrap(dragOptions[dragEvent], function () {
if (existingDrag) {
existingDrag.apply(this, arguments);
}
endpointAddedButNoDragYet = false;
});
dragOptions[stopEvent] = _ju.wrap(dragOptions[stopEvent], function () {
if (existingStop) {
existingStop.apply(this, arguments);
}
this.currentlyDragging = false;
if (ep._jsPlumb != null) { // if not cleaned up...
// reset the anchor to the anchor that was initially provided. the one we were using to drag
// the connection was just a placeholder that was located at the place the user pressed the
// mouse button to initiate the drag.
var anchorDef = p.anchor || this.Defaults.Anchor,
oldAnchor = ep.anchor,
oldConnection = ep.connections[0];
var newAnchor = this.makeAnchor(anchorDef, elid, this),
_el = ep.element;
// if the anchor has a 'positionFinder' set, then delegate to that function to find
// out where to locate the anchor. issue 117.
if (newAnchor.positionFinder != null) {
var elPosition = _currentInstance.getOffset(_el),
elSize = this.getSize(_el),
dropPosition = { left: elPosition.left + (oldAnchor.x * elSize[0]), top: elPosition.top + (oldAnchor.y * elSize[1]) },
ap = newAnchor.positionFinder(dropPosition, elPosition, elSize, newAnchor.constructorParams);
newAnchor.x = ap[0];
newAnchor.y = ap[1];
}
ep.setAnchor(newAnchor, true);
ep.repaint();
this.repaint(ep.elementId);
if (oldConnection != null) {
this.repaint(oldConnection.targetId);
}
}
}.bind(this));
// when the user presses the mouse, add an Endpoint, if we are enabled.
var mouseDownListener = function (e) {
// on right mouse button, abort.
if (e.which === 3 || e.button === 2) {
return;
}
// TODO store def on element.
var def = this.sourceEndpointDefinitions[elid][type];
// if disabled, return.
if (!def.enabled) {
return;
}
elid = this.getId(this.getElement(elInfo.el)); // elid might have changed since this method was called to configure the element.
// if a filter was given, run it, and return if it says no.
if (p.filter) {
var r = _ju.isString(p.filter) ? selectorFilter(e, elInfo.el, p.filter, this, p.filterExclude) : p.filter(e, elInfo.el);
if (r === false) {
return;
}
}
// if maxConnections reached
var sourceCount = this.select({source: elid}).length;
if (def.maxConnections >= 0 && (sourceCount >= def.maxConnections)) {
if (onMaxConnections) {
onMaxConnections({
element: elInfo.el,
maxConnections: maxConnections
}, e);
}
return false;
}
// find the position on the element at which the mouse was pressed; this is where the endpoint
// will be located.
var elxy = root.jsPlumb.getPositionOnElement(e, _del, _zoom);
// we need to override the anchor in here, and force 'isSource', but we don't want to mess with
// the params passed in, because after a connection is established we're going to reset the endpoint
// to have the anchor we were given.
var tempEndpointParams = {};
root.jsPlumb.extend(tempEndpointParams, p);
tempEndpointParams.isTemporarySource = true;
tempEndpointParams.anchor = [ elxy[0], elxy[1] , 0, 0];
tempEndpointParams.dragOptions = dragOptions;
if (def.def.scope) {
tempEndpointParams.scope = def.def.scope;
}
ep = this.addEndpoint(elid, tempEndpointParams);
endpointAddedButNoDragYet = true;
ep.setDeleteOnEmpty(true);
// if unique endpoint and it's already been created, push it onto the endpoint we create. at the end
// of a successful connection we'll switch to that endpoint.
// TODO this is the same code as the programmatic endpoints create on line 1050 ish
if (def.uniqueEndpoint) {
if (!def.endpoint) {
def.endpoint = ep;
ep.setDeleteOnEmpty(false);
}
else {
ep.finalEndpoint = def.endpoint;
}
}
var _delTempEndpoint = function () {
// this mouseup event is fired only if no dragging occurred, by jquery and yui, but for mootools
// it is fired even if dragging has occurred, in which case we would blow away a perfectly
// legitimate endpoint, were it not for this check. the flag is set after adding an
// endpoint and cleared in a drag listener we set in the dragOptions above.
_currentInstance.off(ep.canvas, "mouseup", _delTempEndpoint);
_currentInstance.off(elInfo.el, "mouseup", _delTempEndpoint);
if (endpointAddedButNoDragYet) {
endpointAddedButNoDragYet = false;
_currentInstance.deleteEndpoint(ep);
}
};
_currentInstance.on(ep.canvas, "mouseup", _delTempEndpoint);
_currentInstance.on(elInfo.el, "mouseup", _delTempEndpoint);
// optionally check for attributes to extract from the source element
var payload = {};
if (def.def.extract) {
for (var att in def.def.extract) {
var v = (e.srcElement || e.target).getAttribute(att);
if (v) {
payload[def.def.extract[att]] = v;
}
}
}
// and then trigger its mousedown event, which will kick off a drag, which will start dragging
// a new connection from this endpoint.
_currentInstance.trigger(ep.canvas, "mousedown", e, payload);
_ju.consume(e);
}.bind(this);
this.on(elInfo.el, "mousedown", mouseDownListener);
_def.trigger = mouseDownListener;
// if a filter was provided, set it as a dragFilter on the element,
// to prevent the element drag function from kicking in when we want to
// drag a new connection
if (p.filter && (_ju.isString(p.filter) || _ju.isFunction(p.filter))) {
_currentInstance.setDragFilter(elInfo.el, p.filter);
}
var dropOptions = root.jsPlumb.extend({}, p.dropOptions || {});
_makeElementDropHandler(elInfo, p, dropOptions, true, p.isTarget === true);
}.bind(this);
var inputs = el.length && el.constructor !== String ? el : [ el ];
for (var i = 0, ii = inputs.length; i < ii; i++) {
_doOne(_info(inputs[i]));
}
return this;
};
// see api docs
this.unmakeSource = function (el, connectionType, doNotClearArrays) {
var info = _info(el);
_currentInstance.destroyDroppable(info.el, "internal");
var eldefs = this.sourceEndpointDefinitions[info.id];
if (eldefs) {
for (var def in eldefs) {
if (connectionType == null || connectionType === def) {
var mouseDownListener = eldefs[def].trigger;
if (mouseDownListener) {
_currentInstance.off(info.el, "mousedown", mouseDownListener);
}
if (!doNotClearArrays) {
delete this.sourceEndpointDefinitions[info.id][def];
}
}
}
}
return this;
};
// see api docs
this.unmakeEverySource = function () {
for (var i in this.sourceEndpointDefinitions) {
_currentInstance.unmakeSource(i, null, true);
}
this.sourceEndpointDefinitions = {};
return this;
};
var _getScope = function (el, types, connectionType) {
types = _ju.isArray(types) ? types : [ types ];
var id = _getId(el);
connectionType = connectionType || "default";
for (var i = 0; i < types.length; i++) {
var eldefs = this[types[i]][id];
if (eldefs && eldefs[connectionType]) {
return eldefs[connectionType].def.scope || this.Defaults.Scope;
}
}
}.bind(this);
var _setScope = function (el, scope, types, connectionType) {
types = _ju.isArray(types) ? types : [ types ];
var id = _getId(el);
connectionType = connectionType || "default";
for (var i = 0; i < types.length; i++) {
var eldefs = this[types[i]][id];
if (eldefs && eldefs[connectionType]) {
eldefs[connectionType].def.scope = scope;
}
}
}.bind(this);
this.getScope = function (el, scope) {
return _getScope(el, [ "sourceEndpointDefinitions", "targetEndpointDefinitions" ]);
};
this.getSourceScope = function (el) {
return _getScope(el, "sourceEndpointDefinitions");
};
this.getTargetScope = function (el) {
return _getScope(el, "targetEndpointDefinitions");
};
this.setScope = function (el, scope, connectionType) {
this.setSourceScope(el, scope, connectionType);
this.setTargetScope(el, scope, connectionType);
};
this.setSourceScope = function (el, scope, connectionType) {
_setScope(el, scope, "sourceEndpointDefinitions", connectionType);
// we get the source scope during the mousedown event, but we also want to set this.
this.setDragScope(el, scope);
};
this.setTargetScope = function (el, scope, connectionType) {
_setScope(el, scope, "targetEndpointDefinitions", connectionType);
this.setDropScope(el, scope);
};
// see api docs
this.unmakeEveryTarget = function () {
for (var i in this.targetEndpointDefinitions) {
_currentInstance.unmakeTarget(i, true);
}
this.targetEndpointDefinitions = {};
return this;
};
// does the work of setting a source enabled or disabled.
var _setEnabled = function (type, el, state, toggle, connectionType) {
var a = type === "source" ? this.sourceEndpointDefinitions : this.targetEndpointDefinitions,
originalState, info, newState;
connectionType = connectionType || "default";
// a selector or an array
if (el.length && !_ju.isString(el)) {
originalState = [];
for (var i = 0, ii = el.length; i < ii; i++) {
info = _info(el[i]);
if (a[info.id] && a[info.id][connectionType]) {
originalState[i] = a[info.id][connectionType].enabled;
newState = toggle ? !originalState[i] : state;
a[info.id][connectionType].enabled = newState;
_currentInstance[newState ? "removeClass" : "addClass"](info.el, "jtk-" + type + "-disabled");
}
}
}
// otherwise a DOM element or a String ID.
else {
info = _info(el);
var id = info.id;
if (a[id] && a[id][connectionType]) {
originalState = a[id][connectionType].enabled;
newState = toggle ? !originalState : state;
a[id][connectionType].enabled = newState;
_currentInstance[newState ? "removeClass" : "addClass"](info.el, "jtk-" + type + "-disabled");
}
}
return originalState;
}.bind(this);
var _first = function (el, fn) {
if (_ju.isString(el) || !el.length) {
return fn.apply(this, [ el ]);
}
else if (el.length) {
return fn.apply(this, [ el[0] ]);
}
}.bind(this);
this.toggleSourceEnabled = function (el, connectionType) {
_setEnabled("source", el, null, true, connectionType);
return this.isSourceEnabled(el, connectionType);
};
this.setSourceEnabled = function (el, state, connectionType) {
return _setEnabled("source", el, state, null, connectionType);
};
this.isSource = function (el, connectionType) {
connectionType = connectionType || "default";
return _first(el, function (_el) {
var eldefs = this.sourceEndpointDefinitions[_info(_el).id];
return eldefs != null && eldefs[connectionType] != null;
}.bind(this));
};
this.isSourceEnabled = function (el, connectionType) {
connectionType = connectionType || "default";
return _first(el, function (_el) {
var sep = this.sourceEndpointDefinitions[_info(_el).id];
return sep && sep[connectionType] && sep[connectionType].enabled === true;
}.bind(this));
};
this.toggleTargetEnabled = function (el, connectionType) {
_setEnabled("target", el, null, true, connectionType);
return this.isTargetEnabled(el, connectionType);
};
this.isTarget = function (el, connectionType) {
connectionType = connectionType || "default";
return _first(el, function (_el) {
var eldefs = this.targetEndpointDefinitions[_info(_el).id];
return eldefs != null && eldefs[connectionType] != null;
}.bind(this));
};
this.isTargetEnabled = function (el, connectionType) {
connectionType = connectionType || "default";
return _first(el, function (_el) {
var tep = this.targetEndpointDefinitions[_info(_el).id];
return tep && tep[connectionType] && tep[connectionType].enabled === true;
}.bind(this));
};
this.setTargetEnabled = function (el, state, connectionType) {
return _setEnabled("target", el, state, null, connectionType);
};
// --------------------- end makeSource/makeTarget ----------------------------------------------
this.ready = function (fn) {
_currentInstance.bind("ready", fn);
};
var _elEach = function(el, fn) {
// support both lists...
if (typeof el === 'object' && el.length) {
for (var i = 0, ii = el.length; i < ii; i++) {
fn(el[i]);
}
}
else {// ...and single strings or elements.
fn(el);
}
return _currentInstance;
};
// repaint some element's endpoints and connections
this.repaint = function (el, ui, timestamp) {
return _elEach(el, function(_el) {
_draw(_el, ui, timestamp);
});
};
this.revalidate = function (el, timestamp, isIdAlready) {
return _elEach(el, function(_el) {
var elId = isIdAlready ? _el : _currentInstance.getId(_el);
_currentInstance.updateOffset({ elId: elId, recalc: true, timestamp:timestamp });
var dm = _currentInstance.getDragManager();
if (dm) {
dm.updateOffsets(elId);
}
_currentInstance.repaint(_el);
});
};
// repaint every endpoint and connection.
this.repaintEverything = function () {
// TODO this timestamp causes continuous anchors to not repaint properly.
// fix this. do not just take out the timestamp. it runs a lot faster with
// the timestamp included.
var timestamp = _timestamp(), elId;
for (elId in endpointsByElement) {
_currentInstance.updateOffset({ elId: elId, recalc: true, timestamp: timestamp });
}
for (elId in endpointsByElement) {
_draw(elId, null, timestamp);
}
return this;
};
this.removeAllEndpoints = function (el, recurse, affectedElements) {
affectedElements = affectedElements || [];
var _one = function (_el) {
var info = _info(_el),
ebe = endpointsByElement[info.id],
i, ii;
if (ebe) {
affectedElements.push(info);
for (i = 0, ii = ebe.length; i < ii; i++) {
_currentInstance.deleteEndpoint(ebe[i], false);
}
}
delete endpointsByElement[info.id];
if (recurse) {
if (info.el && info.el.nodeType !== 3 && info.el.nodeType !== 8) {
for (i = 0, ii = info.el.childNodes.length; i < ii; i++) {
_one(info.el.childNodes[i]);
}
}
}
};
_one(el);
return this;
};
var _doRemove = function(info, affectedElements) {
_currentInstance.removeAllEndpoints(info.id, true, affectedElements);
var dm = _currentInstance.getDragManager();
var _one = function(_info) {
if (dm) {
dm.elementRemoved(_info.id);
}
_currentInstance.anchorManager.clearFor(_info.id);
_currentInstance.anchorManager.removeFloatingConnection(_info.id);
if (_currentInstance.isSource(_info.el)) {
_currentInstance.unmakeSource(_info.el);
}
if (_currentInstance.isTarget(_info.el)) {
_currentInstance.unmakeTarget(_info.el);
}
_currentInstance.destroyDraggable(_info.el);
_currentInstance.destroyDroppable(_info.el);
delete _currentInstance.floatingConnections[_info.id];
delete managedElements[_info.id];
delete offsets[_info.id];
if (_info.el) {
_currentInstance.removeElement(_info.el);
_info.el._jsPlumb = null;
}
};
// remove all affected child elements
for (var ae = 1; ae < affectedElements.length; ae++) {
_one(affectedElements[ae]);
}
// and always remove the requested one from the dom.
_one(info);
};
/**
* Remove the given element, including cleaning up all endpoints registered for it.
* This is exposed in the public API but also used internally by jsPlumb when removing the
* element associated with a connection drag.
*/
this.remove = function (el, doNotRepaint) {
var info = _info(el), affectedElements = [];
if (info.text) {
info.el.parentNode.removeChild(info.el);
}
else if (info.id) {
_currentInstance.batch(function () {
_doRemove(info, affectedElements);
}, doNotRepaint === true);
}
return _currentInstance;
};
this.empty = function (el, doNotRepaint) {
var affectedElements = [];
var _one = function(el, dontRemoveFocus) {
var info = _info(el);
if (info.text) {
info.el.parentNode.removeChild(info.el);
}
else if (info.el) {
while(info.el.childNodes.length > 0) {
_one(info.el.childNodes[0]);
}
if (!dontRemoveFocus) {
_doRemove(info, affectedElements);
}
}
};
_currentInstance.batch(function() {
_one(el, true);
}, doNotRepaint === false);
return _currentInstance;
};
this.reset = function (doNotUnbindInstanceEventListeners) {
_currentInstance.silently(function() {
_hoverSuspended = false;
_currentInstance.removeAllGroups();
_currentInstance.removeGroupManager();
_currentInstance.deleteEveryEndpoint();
if (!doNotUnbindInstanceEventListeners) {
_currentInstance.unbind();
}
this.targetEndpointDefinitions = {};
this.sourceEndpointDefinitions = {};
connections.length = 0;
if (this.doReset) {
this.doReset();
}
}.bind(this));
};
var _clearObject = function (obj) {
if (obj.canvas && obj.canvas.parentNode) {
obj.canvas.parentNode.removeChild(obj.canvas);
}
obj.cleanup();
obj.destroy();
};
this.clear = function () {
_currentInstance.select().each(_clearObject);
_currentInstance.selectEndpoints().each(_clearObject);
endpointsByElement = {};
endpointsByUUID = {};
};
this.setDefaultScope = function (scope) {
DEFAULT_SCOPE = scope;
return _currentInstance;
};
// sets whether or not some element should be currently draggable.
this.setDraggable = _setDraggable;
this.deriveEndpointAndAnchorSpec = function(type, dontPrependDefault) {
var bits = ((dontPrependDefault ? "" : "default ") + type).split(/[\s]/), eps = null, ep = null, a = null, as = null;
for (var i = 0; i < bits.length; i++) {
var _t = _currentInstance.getType(bits[i], "connection");
if (_t) {
if (_t.endpoints) {
eps = _t.endpoints;
}
if (_t.endpoint) {
ep = _t.endpoint;
}
if (_t.anchors) {
as = _t.anchors;
}
if (_t.anchor) {
a = _t.anchor;
}
}
}
return { endpoints: eps ? eps : [ ep, ep ], anchors: as ? as : [a, a ]};
};
// sets the id of some element, changing whatever we need to to keep track.
this.setId = function (el, newId, doNotSetAttribute) {
//
var id;
if (_ju.isString(el)) {
id = el;
}
else {
el = this.getElement(el);
id = this.getId(el);
}
var sConns = this.getConnections({source: id, scope: '*'}, true),
tConns = this.getConnections({target: id, scope: '*'}, true);
newId = "" + newId;
if (!doNotSetAttribute) {
el = this.getElement(id);
this.setAttribute(el, "id", newId);
}
else {
el = this.getElement(newId);
}
endpointsByElement[newId] = endpointsByElement[id] || [];
for (var i = 0, ii = endpointsByElement[newId].length; i < ii; i++) {
endpointsByElement[newId][i].setElementId(newId);
endpointsByElement[newId][i].setReferenceElement(el);
}
delete endpointsByElement[id];
this.sourceEndpointDefinitions[newId] = this.sourceEndpointDefinitions[id];
delete this.sourceEndpointDefinitions[id];
this.targetEndpointDefinitions[newId] = this.targetEndpointDefinitions[id];
delete this.targetEndpointDefinitions[id];
this.anchorManager.changeId(id, newId);
var dm = this.getDragManager();
if (dm) {
dm.changeId(id, newId);
}
managedElements[newId] = managedElements[id];
delete managedElements[id];
var _conns = function (list, epIdx, type) {
for (var i = 0, ii = list.length; i < ii; i++) {
list[i].endpoints[epIdx].setElementId(newId);
list[i].endpoints[epIdx].setReferenceElement(el);
list[i][type + "Id"] = newId;
list[i][type] = el;
}
};
_conns(sConns, 0, "source");
_conns(tConns, 1, "target");
this.repaint(newId);
};
this.setDebugLog = function (debugLog) {
log = debugLog;
};
this.setSuspendDrawing = function (val, repaintAfterwards) {
var curVal = _suspendDrawing;
_suspendDrawing = val;
if (val) {
_suspendedAt = new Date().getTime();
} else {
_suspendedAt = null;
}
if (repaintAfterwards) {
this.repaintEverything();
}
return curVal;
};
// returns whether or not drawing is currently suspended.
this.isSuspendDrawing = function () {
return _suspendDrawing;
};
// return timestamp for when drawing was suspended.
this.getSuspendedAt = function () {
return _suspendedAt;
};
this.batch = function (fn, doNotRepaintAfterwards) {
var _wasSuspended = this.isSuspendDrawing();
if (!_wasSuspended) {
this.setSuspendDrawing(true);
}
try {
fn();
}
catch (e) {
_ju.log("Function run while suspended failed", e);
}
if (!_wasSuspended) {
this.setSuspendDrawing(false, !doNotRepaintAfterwards);
}
};
this.doWhileSuspended = this.batch;
this.getCachedData = _getCachedData;
this.timestamp = _timestamp;
this.show = function (el, changeEndpoints) {
_setVisible(el, "block", changeEndpoints);
return _currentInstance;
};
// TODO: update this method to return the current state.
this.toggleVisible = _toggleVisible;
this.toggleDraggable = _toggleDraggable;
this.addListener = this.bind;
var floatingConnections = [];
this.registerFloatingConnection = function(info, conn, ep) {
floatingConnections[info.id] = conn;
// only register for the target endpoint; we will not be dragging the source at any time
// before this connection is either discarded or made into a permanent connection.
_ju.addToList(endpointsByElement, info.id, ep);
};
this.getFloatingConnectionFor = function(id) {
return floatingConnections[id];
};
};
_ju.extend(root.jsPlumbInstance, _ju.EventGenerator, {
setAttribute: function (el, a, v) {
this.setAttribute(el, a, v);
},
getAttribute: function (el, a) {
return this.getAttribute(root.jsPlumb.getElement(el), a);
},
convertToFullOverlaySpec: function(spec) {
if (_ju.isString(spec)) {
spec = [ spec, { } ];
}
spec[1].id = spec[1].id || _ju.uuid();
return spec;
},
registerConnectionType: function (id, type) {
this._connectionTypes[id] = root.jsPlumb.extend({}, type);
if (type.overlays) {
var to = {};
for (var i = 0; i < type.overlays.length; i++) {
// if a string, convert to object representation so that we can store the typeid on it.
// also assign an id.
var fo = this.convertToFullOverlaySpec(type.overlays[i]);
to[fo[1].id] = fo;
}
this._connectionTypes[id].overlays = to;
}
},
registerConnectionTypes: function (types) {
for (var i in types) {
this.registerConnectionType(i, types[i]);
}
},
registerEndpointType: function (id, type) {
this._endpointTypes[id] = root.jsPlumb.extend({}, type);
if (type.overlays) {
var to = {};
for (var i = 0; i < type.overlays.length; i++) {
// if a string, convert to object representation so that we can store the typeid on it.
// also assign an id.
var fo = this.convertToFullOverlaySpec(type.overlays[i]);
to[fo[1].id] = fo;
}
this._endpointTypes[id].overlays = to;
}
},
registerEndpointTypes: function (types) {
for (var i in types) {
this.registerEndpointType(i, types[i]);
}
},
getType: function (id, typeDescriptor) {
return typeDescriptor === "connection" ? this._connectionTypes[id] : this._endpointTypes[id];
},
setIdChanged: function (oldId, newId) {
this.setId(oldId, newId, true);
},
// set parent: change the parent for some node and update all the registrations we need to.
setParent: function (el, newParent) {
var _dom = this.getElement(el),
_id = this.getId(_dom),
_pdom = this.getElement(newParent),
_pid = this.getId(_pdom),
dm = this.getDragManager();
_dom.parentNode.removeChild(_dom);
_pdom.appendChild(_dom);
if (dm) {
dm.setParent(_dom, _id, _pdom, _pid);
}
},
extend: function (o1, o2, names) {
var i;
if (names) {
for (i = 0; i < names.length; i++) {
o1[names[i]] = o2[names[i]];
}
}
else {
for (i in o2) {
o1[i] = o2[i];
}
}
return o1;
},
floatingConnections: {},
getFloatingAnchorIndex: function (jpc) {
return jpc.endpoints[0].isFloating() ? 0 : jpc.endpoints[1].isFloating() ? 1 : -1;
}
});
// --------------------- static instance + module registration -------------------------------------------
// create static instance and assign to window if window exists.
var jsPlumb = new jsPlumbInstance();
// register on 'root' (lets us run on server or browser)
root.jsPlumb = jsPlumb;
// add 'getInstance' method to static instance
jsPlumb.getInstance = function (_defaults, overrideFns) {
var j = new jsPlumbInstance(_defaults);
if (overrideFns) {
for (var ovf in overrideFns) {
j[ovf] = overrideFns[ovf];
}
}
j.init();
return j;
};
jsPlumb.each = function (spec, fn) {
if (spec == null) {
return;
}
if (typeof spec === "string") {
fn(jsPlumb.getElement(spec));
}
else if (spec.length != null) {
for (var i = 0; i < spec.length; i++) {
fn(jsPlumb.getElement(spec[i]));
}
}
else {
fn(spec);
} // assume it's an element.
};
// CommonJS
if (typeof exports !== 'undefined') {
exports.jsPlumb = jsPlumb;
}
// --------------------- end static instance + AMD registration -------------------------------------------
}).call(typeof window !== 'undefined' ? window : this);
/*
* This file contains the base functionality for DOM type adapters.
*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;
(function () {
var root = this, _ju = root.jsPlumbUtil;
var _genLoc = function (prefix, e) {
if (e == null) {
return [ 0, 0 ];
}
var ts = _touches(e), t = _getTouch(ts, 0);
return [t[prefix + "X"], t[prefix + "Y"]];
},
_pageLocation = _genLoc.bind(this, "page"),
_screenLocation = _genLoc.bind(this, "screen"),
_clientLocation = _genLoc.bind(this, "client"),
_getTouch = function (touches, idx) {
return touches.item ? touches.item(idx) : touches[idx];
},
_touches = function (e) {
return e.touches && e.touches.length > 0 ? e.touches :
e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches :
e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches :
[ e ];
};
/**
Manages dragging for some instance of jsPlumb.
TODO instead of this being accessed directly, it should subscribe to events on the jsPlumb instance: every method
in here is called directly by jsPlumb. But what should happen is that we have unpublished events that this listens
to. The only trick is getting one of these instantiated with every jsPlumb instance: it needs to have a hook somehow.
Basically the general idea is to pull ALL the drag code out (prototype method registrations plus this) into a
dedicated drag script), that does not necessarily need to be included.
*/
var DragManager = function (_currentInstance) {
var _draggables = {}, _dlist = [], _delements = {}, _elementsWithEndpoints = {},
// elementids mapped to the draggable to which they belong.
_draggablesForElements = {};
/**
register some element as draggable. right now the drag init stuff is done elsewhere, and it is
possible that will continue to be the case.
*/
this.register = function (el) {
var id = _currentInstance.getId(el),
parentOffset;
if (!_draggables[id]) {
_draggables[id] = el;
_dlist.push(el);
_delements[id] = {};
}
// look for child elements that have endpoints and register them against this draggable.
var _oneLevel = function (p) {
if (p) {
for (var i = 0; i < p.childNodes.length; i++) {
if (p.childNodes[i].nodeType !== 3 && p.childNodes[i].nodeType !== 8) {
var cEl = jsPlumb.getElement(p.childNodes[i]),
cid = _currentInstance.getId(p.childNodes[i], null, true);
if (cid && _elementsWithEndpoints[cid] && _elementsWithEndpoints[cid] > 0) {
if (!parentOffset) {
parentOffset = _currentInstance.getOffset(el);
}
var cOff = _currentInstance.getOffset(cEl);
_delements[id][cid] = {
id: cid,
offset: {
left: cOff.left - parentOffset.left,
top: cOff.top - parentOffset.top
}
};
_draggablesForElements[cid] = id;
}
_oneLevel(p.childNodes[i]);
}
}
}
};
_oneLevel(el);
};
// refresh the offsets for child elements of this element.
this.updateOffsets = function (elId, childOffsetOverrides) {
if (elId != null) {
childOffsetOverrides = childOffsetOverrides || {};
var domEl = jsPlumb.getElement(elId),
id = _currentInstance.getId(domEl),
children = _delements[id],
parentOffset;
if (children) {
for (var i in children) {
if (children.hasOwnProperty(i)) {
var cel = jsPlumb.getElement(i),
cOff = childOffsetOverrides[i] || _currentInstance.getOffset(cel);
// do not update if we have a value already and we'd just be writing 0,0
if (cel.offsetParent == null && _delements[id][i] != null) {
continue;
}
if (!parentOffset) {
parentOffset = _currentInstance.getOffset(domEl);
}
_delements[id][i] = {
id: i,
offset: {
left: cOff.left - parentOffset.left,
top: cOff.top - parentOffset.top
}
};
_draggablesForElements[i] = id;
}
}
}
}
};
/**
notification that an endpoint was added to the given el. we go up from that el's parent
node, looking for a parent that has been registered as a draggable. if we find one, we add this
el to that parent's list of elements to update on drag (if it is not there already)
*/
this.endpointAdded = function (el, id) {
id = id || _currentInstance.getId(el);
var b = document.body,
p = el.parentNode;
_elementsWithEndpoints[id] = _elementsWithEndpoints[id] ? _elementsWithEndpoints[id] + 1 : 1;
while (p != null && p !== b) {
var pid = _currentInstance.getId(p, null, true);
if (pid && _draggables[pid]) {
var pLoc = _currentInstance.getOffset(p);
if (_delements[pid][id] == null) {
var cLoc = _currentInstance.getOffset(el);
_delements[pid][id] = {
id: id,
offset: {
left: cLoc.left - pLoc.left,
top: cLoc.top - pLoc.top
}
};
_draggablesForElements[id] = pid;
}
break;
}
p = p.parentNode;
}
};
this.endpointDeleted = function (endpoint) {
if (_elementsWithEndpoints[endpoint.elementId]) {
_elementsWithEndpoints[endpoint.elementId]--;
if (_elementsWithEndpoints[endpoint.elementId] <= 0) {
for (var i in _delements) {
if (_delements.hasOwnProperty(i) && _delements[i]) {
delete _delements[i][endpoint.elementId];
delete _draggablesForElements[endpoint.elementId];
}
}
}
}
};
this.changeId = function (oldId, newId) {
_delements[newId] = _delements[oldId];
_delements[oldId] = {};
_draggablesForElements[newId] = _draggablesForElements[oldId];
_draggablesForElements[oldId] = null;
};
this.getElementsForDraggable = function (id) {
return _delements[id];
};
this.elementRemoved = function (elementId) {
var elId = _draggablesForElements[elementId];
if (elId) {
delete _delements[elId][elementId];
delete _draggablesForElements[elementId];
}
};
this.reset = function () {
_draggables = {};
_dlist = [];
_delements = {};
_elementsWithEndpoints = {};
};
//
// notification drag ended. We check automatically if need to update some
// ancestor's offsets.
//
this.dragEnded = function (el) {
if (el.offsetParent != null) {
var id = _currentInstance.getId(el),
ancestor = _draggablesForElements[id];
if (ancestor) {
this.updateOffsets(ancestor);
}
}
};
this.setParent = function (el, elId, p, pId, currentChildLocation) {
var current = _draggablesForElements[elId];
if (!_delements[pId]) {
_delements[pId] = {};
}
var pLoc = _currentInstance.getOffset(p),
cLoc = currentChildLocation || _currentInstance.getOffset(el);
if (current && _delements[current]) {
delete _delements[current][elId];
}
_delements[pId][elId] = {
id:elId,
offset : {
left: cLoc.left - pLoc.left,
top: cLoc.top - pLoc.top
}
};
_draggablesForElements[elId] = pId;
};
this.clearParent = function(el, elId) {
var current = _draggablesForElements[elId];
if (current) {
delete _delements[current][elId];
delete _draggablesForElements[elId];
}
};
this.revalidateParent = function(el, elId, childOffset) {
var current = _draggablesForElements[elId];
if (current) {
var co = {};
co[elId] = childOffset;
this.updateOffsets(current, co);
_currentInstance.revalidate(current);
}
};
this.getDragAncestor = function (el) {
var de = jsPlumb.getElement(el),
id = _currentInstance.getId(de),
aid = _draggablesForElements[id];
if (aid) {
return jsPlumb.getElement(aid);
}
else {
return null;
}
};
};
var trim = function (str) {
return str == null ? null : (str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''));
},
_setClassName = function (el, cn, classList) {
cn = trim(cn);
if (typeof el.className.baseVal !== "undefined") {
el.className.baseVal = cn;
}
else {
el.className = cn;
}
// recent (i currently have 61.0.3163.100) version of chrome do not update classList when you set the base val
// of an svg element's className. in the long run we'd like to move to just using classList anyway
try {
var cl = el.classList;
if (cl != null) {
while (cl.length > 0) {
cl.remove(cl.item(0));
}
for (var i = 0; i < classList.length; i++) {
if (classList[i]) {
cl.add(classList[i]);
}
}
}
}
catch(e) {
// not fatal
jsPlumbUtil.log("JSPLUMB: cannot set class list", e);
}
},
_getClassName = function (el) {
return (typeof el.className.baseVal === "undefined") ? el.className : el.className.baseVal;
},
_classManip = function (el, classesToAdd, classesToRemove) {
classesToAdd = classesToAdd == null ? [] : _ju.isArray(classesToAdd) ? classesToAdd : classesToAdd.split(/\s+/);
classesToRemove = classesToRemove == null ? [] : _ju.isArray(classesToRemove) ? classesToRemove : classesToRemove.split(/\s+/);
var className = _getClassName(el),
curClasses = className.split(/\s+/);
var _oneSet = function (add, classes) {
for (var i = 0; i < classes.length; i++) {
if (add) {
if (curClasses.indexOf(classes[i]) === -1) {
curClasses.push(classes[i]);
}
}
else {
var idx = curClasses.indexOf(classes[i]);
if (idx !== -1) {
curClasses.splice(idx, 1);
}
}
}
};
_oneSet(true, classesToAdd);
_oneSet(false, classesToRemove);
_setClassName(el, curClasses.join(" "), curClasses);
};
root.jsPlumb.extend(root.jsPlumbInstance.prototype, {
headless: false,
pageLocation: _pageLocation,
screenLocation: _screenLocation,
clientLocation: _clientLocation,
getDragManager:function() {
if (this.dragManager == null) {
this.dragManager = new DragManager(this);
}
return this.dragManager;
},
// CONVERTED
createElement:function(tag, style, clazz, atts) {
return this.createElementNS(null, tag, style, clazz, atts);
},
// CONVERTED
createElementNS:function(ns, tag, style, clazz, atts) {
var e = ns == null ? document.createElement(tag) : document.createElementNS(ns, tag);
var i;
style = style || {};
for (i in style) {
e.style[i] = style[i];
}
if (clazz) {
e.className = clazz;
}
atts = atts || {};
for (i in atts) {
e.setAttribute(i, "" + atts[i]);
}
return e;
},
// CONVERTED
getAttribute: function (el, attName) {
return el.getAttribute != null ? el.getAttribute(attName) : null;
},
// CONVERTED
setAttribute: function (el, a, v) {
if (el.setAttribute != null) {
el.setAttribute(a, v);
}
},
// CONVERTED
setAttributes: function (el, atts) {
for (var i in atts) {
if (atts.hasOwnProperty(i)) {
el.setAttribute(i, atts[i]);
}
}
},
appendToRoot: function (node) {
document.body.appendChild(node);
},
getRenderModes: function () {
return [ "svg" ];
},
getClass:_getClassName,
addClass: function (el, clazz) {
jsPlumb.each(el, function (e) {
_classManip(e, clazz);
});
},
hasClass: function (el, clazz) {
el = jsPlumb.getElement(el);
if (el.classList) {
return el.classList.contains(clazz);
}
else {
return _getClassName(el).indexOf(clazz) !== -1;
}
},
removeClass: function (el, clazz) {
jsPlumb.each(el, function (e) {
_classManip(e, null, clazz);
});
},
toggleClass:function(el, clazz) {
if (jsPlumb.hasClass(el, clazz)) {
jsPlumb.removeClass(el, clazz);
} else {
jsPlumb.addClass(el, clazz);
}
},
updateClasses: function (el, toAdd, toRemove) {
jsPlumb.each(el, function (e) {
_classManip(e, toAdd, toRemove);
});
},
setClass: function (el, clazz) {
if (clazz != null) {
jsPlumb.each(el, function (e) {
_setClassName(e, clazz, clazz.split(/\s+/));
});
}
},
setPosition: function (el, p) {
el.style.left = p.left + "px";
el.style.top = p.top + "px";
},
getPosition: function (el) {
var _one = function (prop) {
var v = el.style[prop];
return v ? v.substring(0, v.length - 2) : 0;
};
return {
left: _one("left"),
top: _one("top")
};
},
getStyle:function(el, prop) {
if (typeof window.getComputedStyle !== 'undefined') {
return getComputedStyle(el, null).getPropertyValue(prop);
} else {
return el.currentStyle[prop];
}
},
getSelector: function (ctx, spec) {
var sel = null;
if (arguments.length === 1) {
sel = ctx.nodeType != null ? ctx : document.querySelectorAll(ctx);
}
else {
sel = ctx.querySelectorAll(spec);
}
return sel;
},
getOffset:function(el, relativeToRoot, container) {
el = jsPlumb.getElement(el);
container = container || this.getContainer();
var out = {
left: el.offsetLeft,
top: el.offsetTop
},
op = (relativeToRoot || (container != null && (el !== container && el.offsetParent !== container))) ? el.offsetParent : null,
_maybeAdjustScroll = function(offsetParent) {
if (offsetParent != null && offsetParent !== document.body && (offsetParent.scrollTop > 0 || offsetParent.scrollLeft > 0)) {
out.left -= offsetParent.scrollLeft;
out.top -= offsetParent.scrollTop;
}
}.bind(this);
while (op != null) {
out.left += op.offsetLeft;
out.top += op.offsetTop;
_maybeAdjustScroll(op);
op = relativeToRoot ? op.offsetParent :
op.offsetParent === container ? null : op.offsetParent;
}
// if container is scrolled and the element (or its offset parent) is not absolute or fixed, adjust accordingly.
if (container != null && !relativeToRoot && (container.scrollTop > 0 || container.scrollLeft > 0)) {
var pp = el.offsetParent != null ? this.getStyle(el.offsetParent, "position") : "static",
p = this.getStyle(el, "position");
if (p !== "absolute" && p !== "fixed" && pp !== "absolute" && pp !== "fixed") {
out.left -= container.scrollLeft;
out.top -= container.scrollTop;
}
}
return out;
},
//
// return x+y proportion of the given element's size corresponding to the location of the given event.
//
getPositionOnElement: function (evt, el, zoom) {
var box = typeof el.getBoundingClientRect !== "undefined" ? el.getBoundingClientRect() : { left: 0, top: 0, width: 0, height: 0 },
body = document.body,
docElem = document.documentElement,
scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop,
scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft,
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
pst = 0,
psl = 0,
top = box.top + scrollTop - clientTop + (pst * zoom),
left = box.left + scrollLeft - clientLeft + (psl * zoom),
cl = jsPlumb.pageLocation(evt),
w = box.width || (el.offsetWidth * zoom),
h = box.height || (el.offsetHeight * zoom),
x = (cl[0] - left) / w,
y = (cl[1] - top) / h;
return [ x, y ];
},
/**
* Gets the absolute position of some element as read from the left/top properties in its style.
* @method getAbsolutePosition
* @param {Element} el The element to retrieve the absolute coordinates from. **Note** this is a DOM element, not a selector from the underlying library.
* @return {Number[]} [left, top] pixel values.
*/
getAbsolutePosition: function (el) {
var _one = function (s) {
var ss = el.style[s];
if (ss) {
return parseFloat(ss.substring(0, ss.length - 2));
}
};
return [ _one("left"), _one("top") ];
},
/**
* Sets the absolute position of some element by setting the left/top properties in its style.
* @method setAbsolutePosition
* @param {Element} el The element to set the absolute coordinates on. **Note** this is a DOM element, not a selector from the underlying library.
* @param {Number[]} xy x and y coordinates
* @param {Number[]} [animateFrom] Optional previous xy to animate from.
* @param {Object} [animateOptions] Options for the animation.
*/
setAbsolutePosition: function (el, xy, animateFrom, animateOptions) {
if (animateFrom) {
this.animate(el, {
left: "+=" + (xy[0] - animateFrom[0]),
top: "+=" + (xy[1] - animateFrom[1])
}, animateOptions);
}
else {
el.style.left = xy[0] + "px";
el.style.top = xy[1] + "px";
}
},
/**
* gets the size for the element, in an array : [ width, height ].
*/
getSize: function (el) {
return [ el.offsetWidth, el.offsetHeight ];
},
getWidth: function (el) {
return el.offsetWidth;
},
getHeight: function (el) {
return el.offsetHeight;
},
getRenderMode : function() { return "svg"; }
});
}).call(typeof window !== 'undefined' ? window : this);
/*
* 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
"use strict";
var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
// ------------------------------ BEGIN OverlayCapablejsPlumbUIComponent --------------------------------------------
var _internalLabelOverlayId = "__label",
// this is a shortcut helper method to let people add a label as
// overlay.
_makeLabelOverlay = function (component, params) {
var _params = {
cssClass: params.cssClass,
labelStyle: component.labelStyle,
id: _internalLabelOverlayId,
component: component,
_jsPlumb: component._jsPlumb.instance // TODO not necessary, since the instance can be accessed through the component.
},
mergedParams = _jp.extend(_params, params);
return new _jp.Overlays[component._jsPlumb.instance.getRenderMode()].Label(mergedParams);
},
_processOverlay = function (component, o) {
var _newOverlay = null;
if (_ju.isArray(o)) { // this is for the shorthand ["Arrow", { width:50 }] syntax
// there's also a three arg version:
// ["Arrow", { width:50 }, {location:0.7}]
// which merges the 3rd arg into the 2nd.
var type = o[0],
// make a copy of the object so as not to mess up anyone else's reference...
p = _jp.extend({component: component, _jsPlumb: component._jsPlumb.instance}, o[1]);
if (o.length === 3) {
_jp.extend(p, o[2]);
}
_newOverlay = new _jp.Overlays[component._jsPlumb.instance.getRenderMode()][type](p);
} else if (o.constructor === String) {
_newOverlay = new _jp.Overlays[component._jsPlumb.instance.getRenderMode()][o]({component: component, _jsPlumb: component._jsPlumb.instance});
} else {
_newOverlay = o;
}
_newOverlay.id = _newOverlay.id || _ju.uuid();
component.cacheTypeItem("overlay", _newOverlay, _newOverlay.id);
component._jsPlumb.overlays[_newOverlay.id] = _newOverlay;
return _newOverlay;
};
_jp.OverlayCapableJsPlumbUIComponent = function (params) {
root.jsPlumbUIComponent.apply(this, arguments);
this._jsPlumb.overlays = {};
this._jsPlumb.overlayPositions = {};
if (params.label) {
this.getDefaultType().overlays[_internalLabelOverlayId] = ["Label", {
label: params.label,
location: params.labelLocation || this.defaultLabelLocation || 0.5,
labelStyle: params.labelStyle || this._jsPlumb.instance.Defaults.LabelStyle,
id:_internalLabelOverlayId
}];
}
this.setListenerComponent = function (c) {
if (this._jsPlumb) {
for (var i in this._jsPlumb.overlays) {
this._jsPlumb.overlays[i].setListenerComponent(c);
}
}
};
};
_jp.OverlayCapableJsPlumbUIComponent.applyType = function (component, t) {
if (t.overlays) {
// loop through the ones in the type. if already present on the component,
// dont remove or re-add.
var keep = {}, i;
for (i in t.overlays) {
var existing = component._jsPlumb.overlays[t.overlays[i][1].id];
if (existing) {
// maybe update from data, if there were parameterised values for instance.
existing.updateFrom(t.overlays[i][1]);
keep[t.overlays[i][1].id] = true;
}
else {
var c = component.getCachedTypeItem("overlay", t.overlays[i][1].id);
if (c != null) {
c.reattach(component._jsPlumb.instance, component);
c.setVisible(true);
// maybe update from data, if there were parameterised values for instance.
c.updateFrom(t.overlays[i][1]);
component._jsPlumb.overlays[c.id] = c;
}
else {
c = component.addOverlay(t.overlays[i], true);
}
keep[c.id] = true;
}
}
// now loop through the full overlays and remove those that we dont want to keep
for (i in component._jsPlumb.overlays) {
if (keep[component._jsPlumb.overlays[i].id] == null) {
component.removeOverlay(component._jsPlumb.overlays[i].id, true); // remove overlay but dont clean it up.
// that would remove event listeners etc; overlays are never discarded by the types stuff, they are
// just detached/reattached.
}
}
}
};
_ju.extend(_jp.OverlayCapableJsPlumbUIComponent, root.jsPlumbUIComponent, {
setHover: function (hover, ignoreAttachedElements) {
if (this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) {
for (var i in this._jsPlumb.overlays) {
this._jsPlumb.overlays[i][hover ? "addClass" : "removeClass"](this._jsPlumb.instance.hoverClass);
}
}
},
addOverlay: function (overlay, doNotRepaint) {
var o = _processOverlay(this, overlay);
if (!doNotRepaint) {
this.repaint();
}
return o;
},
getOverlay: function (id) {
return this._jsPlumb.overlays[id];
},
getOverlays: function () {
return this._jsPlumb.overlays;
},
hideOverlay: function (id) {
var o = this.getOverlay(id);
if (o) {
o.hide();
}
},
hideOverlays: function () {
for (var i in this._jsPlumb.overlays) {
this._jsPlumb.overlays[i].hide();
}
},
showOverlay: function (id) {
var o = this.getOverlay(id);
if (o) {
o.show();
}
},
showOverlays: function () {
for (var i in this._jsPlumb.overlays) {
this._jsPlumb.overlays[i].show();
}
},
removeAllOverlays: function (doNotRepaint) {
for (var i in this._jsPlumb.overlays) {
if (this._jsPlumb.overlays[i].cleanup) {
this._jsPlumb.overlays[i].cleanup();
}
}
this._jsPlumb.overlays = {};
this._jsPlumb.overlayPositions = null;
this._jsPlumb.overlayPlacements= {};
if (!doNotRepaint) {
this.repaint();
}
},
removeOverlay: function (overlayId, dontCleanup) {
var o = this._jsPlumb.overlays[overlayId];
if (o) {
o.setVisible(false);
if (!dontCleanup && o.cleanup) {
o.cleanup();
}
delete this._jsPlumb.overlays[overlayId];
if (this._jsPlumb.overlayPositions) {
delete this._jsPlumb.overlayPositions[overlayId];
}
if (this._jsPlumb.overlayPlacements) {
delete this._jsPlumb.overlayPlacements[overlayId];
}
}
},
removeOverlays: function () {
for (var i = 0, j = arguments.length; i < j; i++) {
this.removeOverlay(arguments[i]);
}
},
moveParent: function (newParent) {
if (this.bgCanvas) {
this.bgCanvas.parentNode.removeChild(this.bgCanvas);
newParent.appendChild(this.bgCanvas);
}
if (this.canvas && this.canvas.parentNode) {
this.canvas.parentNode.removeChild(this.canvas);
newParent.appendChild(this.canvas);
for (var i in this._jsPlumb.overlays) {
if (this._jsPlumb.overlays[i].isAppendedAtTopLevel) {
var el = this._jsPlumb.overlays[i].getElement();
el.parentNode.removeChild(el);
newParent.appendChild(el);
}
}
}
},
getLabel: function () {
var lo = this.getOverlay(_internalLabelOverlayId);
return lo != null ? lo.getLabel() : null;
},
getLabelOverlay: function () {
return this.getOverlay(_internalLabelOverlayId);
},
setLabel: function (l) {
var lo = this.getOverlay(_internalLabelOverlayId);
if (!lo) {
var params = l.constructor === String || l.constructor === Function ? { label: l } : l;
lo = _makeLabelOverlay(this, params);
this._jsPlumb.overlays[_internalLabelOverlayId] = lo;
}
else {
if (l.constructor === String || l.constructor === Function) {
lo.setLabel(l);
}
else {
if (l.label) {
lo.setLabel(l.label);
}
if (l.location) {
lo.setLocation(l.location);
}
}
}
if (!this._jsPlumb.instance.isSuspendDrawing()) {
this.repaint();
}
},
cleanup: function (force) {
for (var i in this._jsPlumb.overlays) {
this._jsPlumb.overlays[i].cleanup(force);
this._jsPlumb.overlays[i].destroy(force);
}
if (force) {
this._jsPlumb.overlays = {};
this._jsPlumb.overlayPositions = null;
}
},
setVisible: function (v) {
this[v ? "showOverlays" : "hideOverlays"]();
},
setAbsoluteOverlayPosition: function (overlay, xy) {
this._jsPlumb.overlayPositions[overlay.id] = xy;
},
getAbsoluteOverlayPosition: function (overlay) {
return this._jsPlumb.overlayPositions ? this._jsPlumb.overlayPositions[overlay.id] : null;
},
_clazzManip:function(action, clazz, dontUpdateOverlays) {
if (!dontUpdateOverlays) {
for (var i in this._jsPlumb.overlays) {
this._jsPlumb.overlays[i][action + "Class"](clazz);
}
}
},
addClass:function(clazz, dontUpdateOverlays) {
this._clazzManip("add", clazz, dontUpdateOverlays);
},
removeClass:function(clazz, dontUpdateOverlays) {
this._clazzManip("remove", clazz, dontUpdateOverlays);
}
});
// ------------------------------ END OverlayCapablejsPlumbUIComponent --------------------------------------------
}).call(typeof window !== 'undefined' ? window : this);
/*
* This file contains the code for Endpoints.
*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function () {
"use strict";
var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
// create the drag handler for a connection
var _makeConnectionDragHandler = function (endpoint, placeholder, _jsPlumb) {
var stopped = false;
return {
drag: function () {
if (stopped) {
stopped = false;
return true;
}
if (placeholder.element) {
var _ui = _jsPlumb.getUIPosition(arguments, _jsPlumb.getZoom());
if (_ui != null) {
_jsPlumb.setPosition(placeholder.element, _ui);
}
_jsPlumb.repaint(placeholder.element, _ui);
// always repaint the source endpoint, because only continuous/dynamic anchors cause the endpoint
// to be repainted, so static anchors need to be told (or the endpoint gets dragged around)
endpoint.paint({anchorPoint:endpoint.anchor.getCurrentLocation({element:endpoint})});
}
},
stopDrag: function () {
stopped = true;
}
};
};
// creates a placeholder div for dragging purposes, adds it, and pre-computes its offset.
var _makeDraggablePlaceholder = function (placeholder, _jsPlumb, ipco, ips) {
var n = _jsPlumb.createElement("div", { position : "absolute" });
_jsPlumb.appendElement(n);
var id = _jsPlumb.getId(n);
_jsPlumb.setPosition(n, ipco);
n.style.width = ips[0] + "px";
n.style.height = ips[1] + "px";
_jsPlumb.manage(id, n, true); // TRANSIENT MANAGE
// create and assign an id, and initialize the offset.
placeholder.id = id;
placeholder.element = n;
};
// create a floating endpoint (for drag connections)
var _makeFloatingEndpoint = function (paintStyle, referenceAnchor, endpoint, referenceCanvas, sourceElement, _jsPlumb, _newEndpoint, scope) {
var floatingAnchor = new _jp.FloatingAnchor({ reference: referenceAnchor, referenceCanvas: referenceCanvas, jsPlumbInstance: _jsPlumb });
//setting the scope here should not be the way to fix that mootools issue. it should be fixed by not
// adding the floating endpoint as a droppable. that makes more sense anyway!
// TRANSIENT MANAGE
return _newEndpoint({
paintStyle: paintStyle,
endpoint: endpoint,
anchor: floatingAnchor,
source: sourceElement,
scope: scope
});
};
var typeParameters = [ "connectorStyle", "connectorHoverStyle", "connectorOverlays",
"connector", "connectionType", "connectorClass", "connectorHoverClass" ];
// a helper function that tries to find a connection to the given element, and returns it if so. if elementWithPrecedence is null,
// or no connection to it is found, we return the first connection in our list.
var findConnectionToUseForDynamicAnchor = function (ep, elementWithPrecedence) {
var idx = 0;
if (elementWithPrecedence != null) {
for (var i = 0; i < ep.connections.length; i++) {
if (ep.connections[i].sourceId === elementWithPrecedence || ep.connections[i].targetId === elementWithPrecedence) {
idx = i;
break;
}
}
}
return ep.connections[idx];
};
_jp.Endpoint = function (params) {
var _jsPlumb = params._jsPlumb,
_newConnection = params.newConnection,
_newEndpoint = params.newEndpoint;
this.idPrefix = "_jsplumb_e_";
this.defaultLabelLocation = [ 0.5, 0.5 ];
this.defaultOverlayKeys = ["Overlays", "EndpointOverlays"];
_jp.OverlayCapableJsPlumbUIComponent.apply(this, arguments);
// TYPE
this.appendToDefaultType({
connectionType:params.connectionType,
maxConnections: params.maxConnections == null ? this._jsPlumb.instance.Defaults.MaxConnections : params.maxConnections, // maximum number of connections this endpoint can be the source of.,
paintStyle: params.endpointStyle || params.paintStyle || params.style || this._jsPlumb.instance.Defaults.EndpointStyle || _jp.Defaults.EndpointStyle,
hoverPaintStyle: params.endpointHoverStyle || params.hoverPaintStyle || this._jsPlumb.instance.Defaults.EndpointHoverStyle || _jp.Defaults.EndpointHoverStyle,
connectorStyle: params.connectorStyle,
connectorHoverStyle: params.connectorHoverStyle,
connectorClass: params.connectorClass,
connectorHoverClass: params.connectorHoverClass,
connectorOverlays: params.connectorOverlays,
connector: params.connector,
connectorTooltip: params.connectorTooltip
});
// END TYPE
this._jsPlumb.enabled = !(params.enabled === false);
this._jsPlumb.visible = true;
this.element = _jp.getElement(params.source);
this._jsPlumb.uuid = params.uuid;
this._jsPlumb.floatingEndpoint = null;
var inPlaceCopy = null;
if (this._jsPlumb.uuid) {
params.endpointsByUUID[this._jsPlumb.uuid] = this;
}
this.elementId = params.elementId;
this.dragProxy = params.dragProxy;
this._jsPlumb.connectionCost = params.connectionCost;
this._jsPlumb.connectionsDirected = params.connectionsDirected;
this._jsPlumb.currentAnchorClass = "";
this._jsPlumb.events = {};
var deleteOnEmpty = params.deleteOnEmpty === true;
this.setDeleteOnEmpty = function(d) {
deleteOnEmpty = d;
};
var _updateAnchorClass = function () {
// stash old, get new
var oldAnchorClass = _jsPlumb.endpointAnchorClassPrefix + "-" + this._jsPlumb.currentAnchorClass;
this._jsPlumb.currentAnchorClass = this.anchor.getCssClass();
var anchorClass = _jsPlumb.endpointAnchorClassPrefix + (this._jsPlumb.currentAnchorClass ? "-" + this._jsPlumb.currentAnchorClass : "");
this.removeClass(oldAnchorClass);
this.addClass(anchorClass);
// add and remove at the same time to reduce the number of reflows.
_jp.updateClasses(this.element, anchorClass, oldAnchorClass);
}.bind(this);
this.prepareAnchor = function(anchorParams) {
var a = this._jsPlumb.instance.makeAnchor(anchorParams, this.elementId, _jsPlumb);
a.bind("anchorChanged", function (currentAnchor) {
this.fire("anchorChanged", {endpoint: this, anchor: currentAnchor});
_updateAnchorClass();
}.bind(this));
return a;
};
this.setPreparedAnchor = function(anchor, doNotRepaint) {
this._jsPlumb.instance.continuousAnchorFactory.clear(this.elementId);
this.anchor = anchor;
_updateAnchorClass();
if (!doNotRepaint) {
this._jsPlumb.instance.repaint(this.elementId);
}
return this;
};
this.setAnchor = function (anchorParams, doNotRepaint) {
var a = this.prepareAnchor(anchorParams);
this.setPreparedAnchor(a, doNotRepaint);
return this;
};
var internalHover = function (state) {
if (this.connections.length > 0) {
for (var i = 0; i < this.connections.length; i++) {
this.connections[i].setHover(state, false);
}
}
else {
this.setHover(state);
}
}.bind(this);
this.bind("mouseover", function () {
internalHover(true);
});
this.bind("mouseout", function () {
internalHover(false);
});
// ANCHOR MANAGER
if (!params._transient) { // in place copies, for example, are transient. they will never need to be retrieved during a paint cycle, because they dont move, and then they are deleted.
this._jsPlumb.instance.anchorManager.add(this, this.elementId);
}
this.prepareEndpoint = function(ep, typeId) {
var _e = function (t, p) {
var rm = _jsPlumb.getRenderMode();
if (_jp.Endpoints[rm][t]) {
return new _jp.Endpoints[rm][t](p);
}
if (!_jsPlumb.Defaults.DoNotThrowErrors) {
throw { msg: "jsPlumb: unknown endpoint type '" + t + "'" };
}
};
var endpointArgs = {
_jsPlumb: this._jsPlumb.instance,
cssClass: params.cssClass,
container: params.container,
tooltip: params.tooltip,
connectorTooltip: params.connectorTooltip,
endpoint: this
};
var endpoint;
if (_ju.isString(ep)) {
endpoint = _e(ep, endpointArgs);
}
else if (_ju.isArray(ep)) {
endpointArgs = _ju.merge(ep[1], endpointArgs);
endpoint = _e(ep[0], endpointArgs);
}
else {
endpoint = ep.clone();
}
// assign a clone function using a copy of endpointArgs. this is used when a drag starts: the endpoint that was dragged is cloned,
// and the clone is left in its place while the original one goes off on a magical journey.
// the copy is to get around a closure problem, in which endpointArgs ends up getting shared by
// the whole world.
//var argsForClone = jsPlumb.extend({}, endpointArgs);
endpoint.clone = function () {
// TODO this, and the code above, can be refactored to be more dry.
if (_ju.isString(ep)) {
return _e(ep, endpointArgs);
}
else if (_ju.isArray(ep)) {
endpointArgs = _ju.merge(ep[1], endpointArgs);
return _e(ep[0], endpointArgs);
}
}.bind(this);
endpoint.typeId = typeId;
return endpoint;
};
this.setEndpoint = function(ep, doNotRepaint) {
var _ep = this.prepareEndpoint(ep);
this.setPreparedEndpoint(_ep, true);
};
this.setPreparedEndpoint = function (ep, doNotRepaint) {
if (this.endpoint != null) {
this.endpoint.cleanup();
this.endpoint.destroy();
}
this.endpoint = ep;
this.type = this.endpoint.type;
this.canvas = this.endpoint.canvas;
};
_jp.extend(this, params, typeParameters);
this.isSource = params.isSource || false;
this.isTemporarySource = params.isTemporarySource || false;
this.isTarget = params.isTarget || false;
this.connections = params.connections || [];
this.connectorPointerEvents = params["connector-pointer-events"];
this.scope = params.scope || _jsPlumb.getDefaultScope();
this.timestamp = null;
this.reattachConnections = params.reattach || _jsPlumb.Defaults.ReattachConnections;
this.connectionsDetachable = _jsPlumb.Defaults.ConnectionsDetachable;
if (params.connectionsDetachable === false || params.detachable === false) {
this.connectionsDetachable = false;
}
this.dragAllowedWhenFull = params.dragAllowedWhenFull !== false;
if (params.onMaxConnections) {
this.bind("maxConnections", params.onMaxConnections);
}
//
// add a connection. not part of public API.
//
this.addConnection = function (connection) {
this.connections.push(connection);
this[(this.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass);
this[(this.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass);
};
this.detachFromConnection = function (connection, idx, doNotCleanup) {
idx = idx == null ? this.connections.indexOf(connection) : idx;
if (idx >= 0) {
this.connections.splice(idx, 1);
this[(this.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass);
this[(this.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass);
}
if (!doNotCleanup && deleteOnEmpty && this.connections.length === 0) {
_jsPlumb.deleteObject({
endpoint: this,
fireEvent: false,
deleteAttachedObjects: doNotCleanup !== true
});
}
};
this.deleteEveryConnection = function(params) {
var c = this.connections.length;
for (var i = 0; i < c; i++) {
_jsPlumb.deleteConnection(this.connections[0], params);
}
};
this.detachFrom = function (targetEndpoint, fireEvent, originalEvent) {
var c = [];
for (var i = 0; i < this.connections.length; i++) {
if (this.connections[i].endpoints[1] === targetEndpoint || this.connections[i].endpoints[0] === targetEndpoint) {
c.push(this.connections[i]);
}
}
for (var j = 0, count = c.length; j < count; j++) {
_jsPlumb.deleteConnection(c[0]);
}
return this;
};
this.getElement = function () {
return this.element;
};
this.setElement = function (el) {
var parentId = this._jsPlumb.instance.getId(el),
curId = this.elementId;
// remove the endpoint from the list for the current endpoint's element
_ju.removeWithFunction(params.endpointsByElement[this.elementId], function (e) {
return e.id === this.id;
}.bind(this));
this.element = _jp.getElement(el);
this.elementId = _jsPlumb.getId(this.element);
_jsPlumb.anchorManager.rehomeEndpoint(this, curId, this.element);
_jsPlumb.dragManager.endpointAdded(this.element);
_ju.addToList(params.endpointsByElement, parentId, this);
return this;
};
/**
* private but must be exposed.
*/
this.makeInPlaceCopy = function () {
var loc = this.anchor.getCurrentLocation({element: this}),
o = this.anchor.getOrientation(this),
acc = this.anchor.getCssClass(),
inPlaceAnchor = {
bind: function () {
},
compute: function () {
return [ loc[0], loc[1] ];
},
getCurrentLocation: function () {
return [ loc[0], loc[1] ];
},
getOrientation: function () {
return o;
},
getCssClass: function () {
return acc;
}
};
return _newEndpoint({
dropOptions: params.dropOptions,
anchor: inPlaceAnchor,
source: this.element,
paintStyle: this.getPaintStyle(),
endpoint: params.hideOnDrag ? "Blank" : this.endpoint,
_transient: true,
scope: this.scope,
reference:this
});
};
/**
* returns a connection from the pool; used when dragging starts. just gets the head of the array if it can.
*/
this.connectorSelector = function () {
return this.connections[0];
};
this.setStyle = this.setPaintStyle;
this.paint = function (params) {
params = params || {};
var timestamp = params.timestamp, recalc = !(params.recalc === false);
if (!timestamp || this.timestamp !== timestamp) {
var info = _jsPlumb.updateOffset({ elId: this.elementId, timestamp: timestamp });
var xy = params.offset ? params.offset.o : info.o;
if (xy != null) {
var ap = params.anchorPoint, connectorPaintStyle = params.connectorPaintStyle;
if (ap == null) {
var wh = params.dimensions || info.s,
anchorParams = { xy: [ xy.left, xy.top ], wh: wh, element: this, timestamp: timestamp };
if (recalc && this.anchor.isDynamic && this.connections.length > 0) {
var c = findConnectionToUseForDynamicAnchor(this, params.elementWithPrecedence),
oIdx = c.endpoints[0] === this ? 1 : 0,
oId = oIdx === 0 ? c.sourceId : c.targetId,
oInfo = _jsPlumb.getCachedData(oId),
oOffset = oInfo.o, oWH = oInfo.s;
anchorParams.index = oIdx === 0 ? 1 : 0;
anchorParams.connection = c;
anchorParams.txy = [ oOffset.left, oOffset.top ];
anchorParams.twh = oWH;
anchorParams.tElement = c.endpoints[oIdx];
} else if (this.connections.length > 0) {
anchorParams.connection = this.connections[0];
}
ap = this.anchor.compute(anchorParams);
}
this.endpoint.compute(ap, this.anchor.getOrientation(this), this._jsPlumb.paintStyleInUse, connectorPaintStyle || this.paintStyleInUse);
this.endpoint.paint(this._jsPlumb.paintStyleInUse, this.anchor);
this.timestamp = timestamp;
// paint overlays
for (var i in this._jsPlumb.overlays) {
if (this._jsPlumb.overlays.hasOwnProperty(i)) {
var o = this._jsPlumb.overlays[i];
if (o.isVisible()) {
this._jsPlumb.overlayPlacements[i] = o.draw(this.endpoint, this._jsPlumb.paintStyleInUse);
o.paint(this._jsPlumb.overlayPlacements[i]);
}
}
}
}
}
};
this.getTypeDescriptor = function () {
return "endpoint";
};
this.isVisible = function () {
return this._jsPlumb.visible;
};
this.repaint = this.paint;
var draggingInitialised = false;
this.initDraggable = function () {
// is this a connection source? we make it draggable and have the
// drag listener maintain a connection with a floating endpoint.
if (!draggingInitialised && _jp.isDragSupported(this.element)) {
var placeholderInfo = { id: null, element: null },
jpc = null,
existingJpc = false,
existingJpcParams = null,
_dragHandler = _makeConnectionDragHandler(this, placeholderInfo, _jsPlumb),
dragOptions = params.dragOptions || {},
defaultOpts = {},
startEvent = _jp.dragEvents.start,
stopEvent = _jp.dragEvents.stop,
dragEvent = _jp.dragEvents.drag,
beforeStartEvent = _jp.dragEvents.beforeStart,
payload;
// respond to beforeStart from katavorio; this will have, optionally, a payload of attribute values
// that were placed there by the makeSource mousedown listener.
var beforeStart = function(beforeStartParams) {
payload = beforeStartParams.e.payload || {};
};
var start = function (startParams) {
// ------------- first, get a connection to drag. this may be null, in which case we are dragging a new one.
jpc = this.connectorSelector();
// -------------------------------- now a bunch of tests about whether or not to proceed -------------------------
var _continue = true;
// if not enabled, return
if (!this.isEnabled()) {
_continue = false;
}
// if no connection and we're not a source - or temporarily a source, as is the case with makeSource - return.
if (jpc == null && !this.isSource && !this.isTemporarySource) {
_continue = false;
}
// otherwise if we're full and not allowed to drag, also return false.
if (this.isSource && this.isFull() && !(jpc != null && this.dragAllowedWhenFull)) {
_continue = false;
}
// if the connection was setup as not detachable or one of its endpoints
// was setup as connectionsDetachable = false, or Defaults.ConnectionsDetachable
// is set to false...
if (jpc != null && !jpc.isDetachable(this)) {
// .. and the endpoint is full
if (this.isFull()) {
_continue = false;
} else {
// otherwise, if not full, set the connection to null, and we will now proceed
// to drag a new connection.
jpc = null;
}
}
var beforeDrag = _jsPlumb.checkCondition(jpc == null ? "beforeDrag" : "beforeStartDetach", {
endpoint:this,
source:this.element,
sourceId:this.elementId,
connection:jpc
});
if (beforeDrag === false) {
_continue = false;
}
// else we might have been given some data. we'll pass it in to a new connection as 'data'.
// here we also merge in the optional payload we were given on mousedown.
else if (typeof beforeDrag === "object") {
_jp.extend(beforeDrag, payload || {});
}
else {
// or if no beforeDrag data, maybe use the payload on its own.
beforeDrag = payload || {};
}
if (_continue === false) {
// this is for mootools and yui. returning false from this causes jquery to stop drag.
// the events are wrapped in both mootools and yui anyway, but i don't think returning
// false from the start callback would stop a drag.
if (_jsPlumb.stopDrag) {
_jsPlumb.stopDrag(this.canvas);
}
_dragHandler.stopDrag();
return false;
}
// ---------------------------------------------------------------------------------------------------------------------
// ok to proceed.
// clear hover for all connections for this endpoint before continuing.
for (var i = 0; i < this.connections.length; i++) {
this.connections[i].setHover(false);
}
this.addClass("endpointDrag");
_jsPlumb.setConnectionBeingDragged(true);
// if we're not full but there was a connection, make it null. we'll create a new one.
if (jpc && !this.isFull() && this.isSource) {
jpc = null;
}
_jsPlumb.updateOffset({ elId: this.elementId });
// ---------------- make the element we will drag around, and position it -----------------------------
var ipco = this._jsPlumb.instance.getOffset(this.canvas),
canvasElement = this.canvas,
ips = this._jsPlumb.instance.getSize(this.canvas);
_makeDraggablePlaceholder(placeholderInfo, _jsPlumb, ipco, ips);
// store the id of the dragging div and the source element. the drop function will pick these up.
_jsPlumb.setAttributes(this.canvas, {
"dragId": placeholderInfo.id,
"elId": this.elementId
});
// ------------------- create an endpoint that will be our floating endpoint ------------------------------------
var endpointToFloat = this.dragProxy || this.endpoint;
if (this.dragProxy == null && this.connectionType != null) {
var aae = this._jsPlumb.instance.deriveEndpointAndAnchorSpec(this.connectionType);
if (aae.endpoints[1]) {
endpointToFloat = aae.endpoints[1];
}
}
var centerAnchor = this._jsPlumb.instance.makeAnchor("Center");
centerAnchor.isFloating = true;
this._jsPlumb.floatingEndpoint = _makeFloatingEndpoint(this.getPaintStyle(), centerAnchor, endpointToFloat, this.canvas, placeholderInfo.element, _jsPlumb, _newEndpoint, this.scope);
var _savedAnchor = this._jsPlumb.floatingEndpoint.anchor;
if (jpc == null) {
this.setHover(false, false);
// create a connection. one end is this endpoint, the other is a floating endpoint.
jpc = _newConnection({
sourceEndpoint: this,
targetEndpoint: this._jsPlumb.floatingEndpoint,
source: this.element, // for makeSource with parent option. ensure source element is represented correctly.
target: placeholderInfo.element,
anchors: [ this.anchor, this._jsPlumb.floatingEndpoint.anchor ],
paintStyle: params.connectorStyle, // this can be null. Connection will use the default.
hoverPaintStyle: params.connectorHoverStyle,
connector: params.connector, // this can also be null. Connection will use the default.
overlays: params.connectorOverlays,
type: this.connectionType,
cssClass: this.connectorClass,
hoverClass: this.connectorHoverClass,
scope:params.scope,
data:beforeDrag
});
jpc.pending = true;
jpc.addClass(_jsPlumb.draggingClass);
this._jsPlumb.floatingEndpoint.addClass(_jsPlumb.draggingClass);
this._jsPlumb.floatingEndpoint.anchor = _savedAnchor;
// fire an event that informs that a connection is being dragged
_jsPlumb.fire("connectionDrag", jpc);
// register the new connection on the drag manager. This connection, at this point, is 'pending',
// and has as its target a temporary element (the 'placeholder'). If the connection subsequently
// becomes established, the anchor manager is informed that the target of the connection has
// changed.
_jsPlumb.anchorManager.newConnection(jpc);
} else {
existingJpc = true;
jpc.setHover(false);
// new anchor idx
var anchorIdx = jpc.endpoints[0].id === this.id ? 0 : 1;
this.detachFromConnection(jpc, null, true); // detach from the connection while dragging is occurring. but dont cleanup automatically.
// store the original scope (issue 57)
var dragScope = _jsPlumb.getDragScope(canvasElement);
_jsPlumb.setAttribute(this.canvas, "originalScope", dragScope);
// fire an event that informs that a connection is being dragged. we do this before
// replacing the original target with the floating element info.
_jsPlumb.fire("connectionDrag", jpc);
// now we replace ourselves with the temporary div we created above:
if (anchorIdx === 0) {
existingJpcParams = [ jpc.source, jpc.sourceId, canvasElement, dragScope ];
_jsPlumb.anchorManager.sourceChanged(jpc.endpoints[anchorIdx].elementId, placeholderInfo.id, jpc, placeholderInfo.element);
} else {
existingJpcParams = [ jpc.target, jpc.targetId, canvasElement, dragScope ];
jpc.target = placeholderInfo.element;
jpc.targetId = placeholderInfo.id;
_jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.endpoints[anchorIdx].elementId, jpc.targetId, jpc);
}
// store the original endpoint and assign the new floating endpoint for the drag.
jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
// PROVIDE THE SUSPENDED ELEMENT, BE IT A SOURCE OR TARGET (ISSUE 39)
jpc.suspendedElement = jpc.endpoints[anchorIdx].getElement();
jpc.suspendedElementId = jpc.endpoints[anchorIdx].elementId;
jpc.suspendedElementType = anchorIdx === 0 ? "source" : "target";
jpc.suspendedEndpoint.setHover(false);
this._jsPlumb.floatingEndpoint.referenceEndpoint = jpc.suspendedEndpoint;
jpc.endpoints[anchorIdx] = this._jsPlumb.floatingEndpoint;
jpc.addClass(_jsPlumb.draggingClass);
this._jsPlumb.floatingEndpoint.addClass(_jsPlumb.draggingClass);
}
_jsPlumb.registerFloatingConnection(placeholderInfo, jpc, this._jsPlumb.floatingEndpoint);
// // register it and register connection on it.
// _jsPlumb.floatingConnections[placeholderInfo.id] = jpc;
//
// // only register for the target endpoint; we will not be dragging the source at any time
// // before this connection is either discarded or made into a permanent connection.
// _ju.addToList(params.endpointsByElement, placeholderInfo.id, this._jsPlumb.floatingEndpoint);
// tell jsplumb about it
_jsPlumb.currentlyDragging = true;
}.bind(this);
var stop = function () {
_jsPlumb.setConnectionBeingDragged(false);
if (jpc && jpc.endpoints != null) {
// get the actual drop event (decode from library args to stop function)
var originalEvent = _jsPlumb.getDropEvent(arguments);
// unlock the other endpoint (if it is dynamic, it would have been locked at drag start)
var idx = _jsPlumb.getFloatingAnchorIndex(jpc);
jpc.endpoints[idx === 0 ? 1 : 0].anchor.unlock();
// TODO: Dont want to know about css classes inside jsplumb, ideally.
jpc.removeClass(_jsPlumb.draggingClass);
// if we have the floating endpoint then the connection has not been dropped
// on another endpoint. If it is a new connection we throw it away. If it is an
// existing connection we check to see if we should reattach it, throwing it away
// if not.
if (this._jsPlumb && (jpc.deleteConnectionNow || jpc.endpoints[idx] === this._jsPlumb.floatingEndpoint)) {
// 6a. if the connection was an existing one...
if (existingJpc && jpc.suspendedEndpoint) {
// fix for issue35, thanks Sylvain Gizard: when firing the detach event make sure the
// floating endpoint has been replaced.
if (idx === 0) {
jpc.floatingElement = jpc.source;
jpc.floatingId = jpc.sourceId;
jpc.floatingEndpoint = jpc.endpoints[0];
jpc.floatingIndex = 0;
jpc.source = existingJpcParams[0];
jpc.sourceId = existingJpcParams[1];
} else {
// keep a copy of the floating element; the anchor manager will want to clean up.
jpc.floatingElement = jpc.target;
jpc.floatingId = jpc.targetId;
jpc.floatingEndpoint = jpc.endpoints[1];
jpc.floatingIndex = 1;
jpc.target = existingJpcParams[0];
jpc.targetId = existingJpcParams[1];
}
var fe = this._jsPlumb.floatingEndpoint; // store for later removal.
// restore the original scope (issue 57)
_jsPlumb.setDragScope(existingJpcParams[2], existingJpcParams[3]);
jpc.endpoints[idx] = jpc.suspendedEndpoint;
// if the connection should be reattached, or the other endpoint refuses detach, then
// reset the connection to its original state
if (jpc.isReattach() || jpc._forceReattach || jpc._forceDetach || !_jsPlumb.deleteConnection(jpc, {originalEvent: originalEvent})) {
jpc.setHover(false);
jpc._forceDetach = null;
jpc._forceReattach = null;
this._jsPlumb.floatingEndpoint.detachFromConnection(jpc);
jpc.suspendedEndpoint.addConnection(jpc);
// TODO this code is duplicated in lots of places...and there is nothing external
// in the code; it all refers to the connection itself. we could add a
// `checkSanity(connection)` method to anchorManager that did this.
if (idx === 1) {
_jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc);
}
else {
_jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source);
}
_jsPlumb.repaint(existingJpcParams[1]);
}
else {
_jsPlumb.deleteObject({endpoint: fe});
}
}
}
// makeTargets sets this flag, to tell us we have been replaced and should delete this object.
if (this.deleteAfterDragStop) {
_jsPlumb.deleteObject({endpoint: this});
}
else {
if (this._jsPlumb) {
this.paint({recalc: false});
}
}
// although the connection is no longer valid, there are use cases where this is useful.
_jsPlumb.fire("connectionDragStop", jpc, originalEvent);
// fire this event to give people more fine-grained control (connectionDragStop fires a lot)
if (jpc.pending) {
_jsPlumb.fire("connectionAborted", jpc, originalEvent);
}
// tell jsplumb that dragging is finished.
_jsPlumb.currentlyDragging = false;
jpc.suspendedElement = null;
jpc.suspendedEndpoint = null;
jpc = null;
}
// if no endpoints, jpc already cleaned up. but still we want to ensure we're reset properly.
// remove the element associated with the floating endpoint
// (and its associated floating endpoint and visual artefacts)
if (placeholderInfo && placeholderInfo.element) {
_jsPlumb.remove(placeholderInfo.element, false, false);
}
// remove the inplace copy
if (inPlaceCopy) {
_jsPlumb.deleteObject({endpoint: inPlaceCopy});
}
if (this._jsPlumb) {
// make our canvas visible (TODO: hand off to library; we should not know about DOM)
this.canvas.style.visibility = "visible";
// unlock our anchor
this.anchor.unlock();
// clear floating anchor.
this._jsPlumb.floatingEndpoint = null;
}
}.bind(this);
dragOptions = _jp.extend(defaultOpts, dragOptions);
dragOptions.scope = this.scope || dragOptions.scope;
dragOptions[beforeStartEvent] = _ju.wrap(dragOptions[beforeStartEvent], beforeStart, false);
dragOptions[startEvent] = _ju.wrap(dragOptions[startEvent], start, false);
// extracted drag handler function so can be used by makeSource
dragOptions[dragEvent] = _ju.wrap(dragOptions[dragEvent], _dragHandler.drag);
dragOptions[stopEvent] = _ju.wrap(dragOptions[stopEvent], stop);
dragOptions.multipleDrop = false;
dragOptions.canDrag = function () {
return this.isSource || this.isTemporarySource || (this.connections.length > 0 && this.connectionsDetachable !== false);
}.bind(this);
_jsPlumb.initDraggable(this.canvas, dragOptions, "internal");
this.canvas._jsPlumbRelatedElement = this.element;
draggingInitialised = true;
}
};
var ep = params.endpoint || this._jsPlumb.instance.Defaults.Endpoint || _jp.Defaults.Endpoint;
this.setEndpoint(ep, true);
var anchorParamsToUse = params.anchor ? params.anchor : params.anchors ? params.anchors : (_jsPlumb.Defaults.Anchor || "Top");
this.setAnchor(anchorParamsToUse, true);
// finally, set type if it was provided
var type = [ "default", (params.type || "")].join(" ");
this.addType(type, params.data, true);
this.canvas = this.endpoint.canvas;
this.canvas._jsPlumb = this;
this.initDraggable();
// pulled this out into a function so we can reuse it for the inPlaceCopy canvas; you can now drop detached connections
// back onto the endpoint you detached it from.
var _initDropTarget = function (canvas, isTransient, endpoint, referenceEndpoint) {
if (_jp.isDropSupported(this.element)) {
var dropOptions = params.dropOptions || _jsPlumb.Defaults.DropOptions || _jp.Defaults.DropOptions;
dropOptions = _jp.extend({}, dropOptions);
dropOptions.scope = dropOptions.scope || this.scope;
var dropEvent = _jp.dragEvents.drop,
overEvent = _jp.dragEvents.over,
outEvent = _jp.dragEvents.out,
_ep = this,
drop = _jsPlumb.EndpointDropHandler({
getEndpoint: function () {
return _ep;
},
jsPlumb: _jsPlumb,
enabled: function () {
return endpoint != null ? endpoint.isEnabled() : true;
},
isFull: function () {
return endpoint.isFull();
},
element: this.element,
elementId: this.elementId,
isSource: this.isSource,
isTarget: this.isTarget,
addClass: function (clazz) {
_ep.addClass(clazz);
},
removeClass: function (clazz) {
_ep.removeClass(clazz);
},
isDropAllowed: function () {
return _ep.isDropAllowed.apply(_ep, arguments);
},
reference:referenceEndpoint,
isRedrop:function(jpc, dhParams) {
return jpc.suspendedEndpoint && dhParams.reference && (jpc.suspendedEndpoint.id === dhParams.reference.id);
}
});
dropOptions[dropEvent] = _ju.wrap(dropOptions[dropEvent], drop, true);
dropOptions[overEvent] = _ju.wrap(dropOptions[overEvent], function () {
var draggable = _jp.getDragObject(arguments),
id = _jsPlumb.getAttribute(_jp.getElement(draggable), "dragId"),
_jpc = _jsPlumb.getFloatingConnectionFor(id);//_jsPlumb.floatingConnections[id];
if (_jpc != null) {
var idx = _jsPlumb.getFloatingAnchorIndex(_jpc);
// here we should fire the 'over' event if we are a target and this is a new connection,
// or we are the same as the floating endpoint.
var _cont = (this.isTarget && idx !== 0) || (_jpc.suspendedEndpoint && this.referenceEndpoint && this.referenceEndpoint.id === _jpc.suspendedEndpoint.id);
if (_cont) {
var bb = _jsPlumb.checkCondition("checkDropAllowed", {
sourceEndpoint: _jpc.endpoints[idx],
targetEndpoint: this,
connection: _jpc
});
this[(bb ? "add" : "remove") + "Class"](_jsPlumb.endpointDropAllowedClass);
this[(bb ? "remove" : "add") + "Class"](_jsPlumb.endpointDropForbiddenClass);
_jpc.endpoints[idx].anchor.over(this.anchor, this);
}
}
}.bind(this));
dropOptions[outEvent] = _ju.wrap(dropOptions[outEvent], function () {
var draggable = _jp.getDragObject(arguments),
id = draggable == null ? null : _jsPlumb.getAttribute(_jp.getElement(draggable), "dragId"),
_jpc = id ? _jsPlumb.getFloatingConnectionFor(id) : null;
if (_jpc != null) {
var idx = _jsPlumb.getFloatingAnchorIndex(_jpc);
var _cont = (this.isTarget && idx !== 0) || (_jpc.suspendedEndpoint && this.referenceEndpoint && this.referenceEndpoint.id === _jpc.suspendedEndpoint.id);
if (_cont) {
this.removeClass(_jsPlumb.endpointDropAllowedClass);
this.removeClass(_jsPlumb.endpointDropForbiddenClass);
_jpc.endpoints[idx].anchor.out();
}
}
}.bind(this));
_jsPlumb.initDroppable(canvas, dropOptions, "internal", isTransient);
}
}.bind(this);
// Initialise the endpoint's canvas as a drop target. The drop handler will take care of the logic of whether
// something can actually be dropped.
if (!this.anchor.isFloating) {
_initDropTarget(this.canvas, !(params._transient || this.anchor.isFloating), this, params.reference);
}
return this;
};
_ju.extend(_jp.Endpoint, _jp.OverlayCapableJsPlumbUIComponent, {
setVisible: function (v, doNotChangeConnections, doNotNotifyOtherEndpoint) {
this._jsPlumb.visible = v;
if (this.canvas) {
this.canvas.style.display = v ? "block" : "none";
}
this[v ? "showOverlays" : "hideOverlays"]();
if (!doNotChangeConnections) {
for (var i = 0; i < this.connections.length; i++) {
this.connections[i].setVisible(v);
if (!doNotNotifyOtherEndpoint) {
var oIdx = this === this.connections[i].endpoints[0] ? 1 : 0;
// only change the other endpoint if this is its only connection.
if (this.connections[i].endpoints[oIdx].connections.length === 1) {
this.connections[i].endpoints[oIdx].setVisible(v, true, true);
}
}
}
}
},
getAttachedElements: function () {
return this.connections;
},
applyType: function (t, doNotRepaint) {
this.setPaintStyle(t.endpointStyle || t.paintStyle, doNotRepaint);
this.setHoverPaintStyle(t.endpointHoverStyle || t.hoverPaintStyle, doNotRepaint);
if (t.maxConnections != null) {
this._jsPlumb.maxConnections = t.maxConnections;
}
if (t.scope) {
this.scope = t.scope;
}
_jp.extend(this, t, typeParameters);
if (t.cssClass != null && this.canvas) {
this._jsPlumb.instance.addClass(this.canvas, t.cssClass);
}
_jp.OverlayCapableJsPlumbUIComponent.applyType(this, t);
},
isEnabled: function () {
return this._jsPlumb.enabled;
},
setEnabled: function (e) {
this._jsPlumb.enabled = e;
},
cleanup: function () {
var anchorClass = this._jsPlumb.instance.endpointAnchorClassPrefix + (this._jsPlumb.currentAnchorClass ? "-" + this._jsPlumb.currentAnchorClass : "");
_jp.removeClass(this.element, anchorClass);
this.anchor = null;
this.endpoint.cleanup(true);
this.endpoint.destroy();
this.endpoint = null;
// drag/drop
this._jsPlumb.instance.destroyDraggable(this.canvas, "internal");
this._jsPlumb.instance.destroyDroppable(this.canvas, "internal");
},
setHover: function (h) {
if (this.endpoint && this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) {
this.endpoint.setHover(h);
}
},
isFull: function () {
return this._jsPlumb.maxConnections === 0 ? true : !(this.isFloating() || this._jsPlumb.maxConnections < 0 || this.connections.length < this._jsPlumb.maxConnections);
},
/**
* private but needs to be exposed.
*/
isFloating: function () {
return this.anchor != null && this.anchor.isFloating;
},
isConnectedTo: function (endpoint) {
var found = false;
if (endpoint) {
for (var i = 0; i < this.connections.length; i++) {
if (this.connections[i].endpoints[1] === endpoint || this.connections[i].endpoints[0] === endpoint) {
found = true;
break;
}
}
}
return found;
},
getConnectionCost: function () {
return this._jsPlumb.connectionCost;
},
setConnectionCost: function (c) {
this._jsPlumb.connectionCost = c;
},
areConnectionsDirected: function () {
return this._jsPlumb.connectionsDirected;
},
setConnectionsDirected: function (b) {
this._jsPlumb.connectionsDirected = b;
},
setElementId: function (_elId) {
this.elementId = _elId;
this.anchor.elementId = _elId;
},
setReferenceElement: function (_el) {
this.element = _jp.getElement(_el);
},
setDragAllowedWhenFull: function (allowed) {
this.dragAllowedWhenFull = allowed;
},
equals: function (endpoint) {
return this.anchor.equals(endpoint.anchor);
},
getUuid: function () {
return this._jsPlumb.uuid;
},
computeAnchor: function (params) {
return this.anchor.compute(params);
}
});
root.jsPlumbInstance.prototype.EndpointDropHandler = function (dhParams) {
return function (e) {
var _jsPlumb = dhParams.jsPlumb;
// remove the classes that are added dynamically. drop is neither forbidden nor allowed now that
// the drop is finishing.
dhParams.removeClass(_jsPlumb.endpointDropAllowedClass);
dhParams.removeClass(_jsPlumb.endpointDropForbiddenClass);
var originalEvent = _jsPlumb.getDropEvent(arguments),
draggable = _jsPlumb.getDragObject(arguments),
id = _jsPlumb.getAttribute(draggable, "dragId"),
elId = _jsPlumb.getAttribute(draggable, "elId"),
scope = _jsPlumb.getAttribute(draggable, "originalScope"),
jpc = _jsPlumb.getFloatingConnectionFor(id);
// if no active connection, bail.
if (jpc == null) {
return;
}
// calculate if this is an existing connection.
var existingConnection = jpc.suspendedEndpoint != null;
// if suspended endpoint exists but has been cleaned up, bail. This means it's an existing connection
// that has been detached and will shortly be discarded.
if (existingConnection && jpc.suspendedEndpoint._jsPlumb == null) {
return;
}
// get the drop endpoint. for a normal connection this is just the one that would replace the currently
// floating endpoint. for a makeTarget this is a new endpoint that is created on drop. But we leave that to
// the handler to figure out.
var _ep = dhParams.getEndpoint(jpc);
// If we're not given an endpoint to use, bail.
if (_ep == null) {
return;
}
// if this is a drop back where the connection came from, mark it force reattach and
// return; the stop handler will reattach. without firing an event.
if (dhParams.isRedrop(jpc, dhParams)) {
jpc._forceReattach = true;
jpc.setHover(false);
if (dhParams.maybeCleanup) {
dhParams.maybeCleanup(_ep);
}
return;
}
// ensure we dont bother trying to drop sources on non-source eps, and same for target.
var idx = _jsPlumb.getFloatingAnchorIndex(jpc);
if ((idx === 0 && !dhParams.isSource)|| (idx === 1 && !dhParams.isTarget)){
if (dhParams.maybeCleanup) {
dhParams.maybeCleanup(_ep);
}
return;
}
if (dhParams.onDrop) {
dhParams.onDrop(jpc);
}
// restore the original scope if necessary (issue 57)
if (scope) {
_jsPlumb.setDragScope(draggable, scope);
}
// if the target of the drop is full, fire an event (we abort below)
// makeTarget: keep.
var isFull = dhParams.isFull(e);
if (isFull) {
_ep.fire("maxConnections", {
endpoint: this,
connection: jpc,
maxConnections: _ep._jsPlumb.maxConnections
}, originalEvent);
}
//
// if endpoint enabled, not full, and matches the index of the floating endpoint...
if (!isFull && dhParams.enabled()) {
var _doContinue = true;
// before testing for beforeDrop, reset the connection's source/target to be the actual DOM elements
// involved (that is, stash any temporary stuff used for dragging. but we need to keep it around in
// order that the anchor manager can clean things up properly).
if (idx === 0) {
jpc.floatingElement = jpc.source;
jpc.floatingId = jpc.sourceId;
jpc.floatingEndpoint = jpc.endpoints[0];
jpc.floatingIndex = 0;
jpc.source = dhParams.element;
jpc.sourceId = dhParams.elementId;
} else {
jpc.floatingElement = jpc.target;
jpc.floatingId = jpc.targetId;
jpc.floatingEndpoint = jpc.endpoints[1];
jpc.floatingIndex = 1;
jpc.target = dhParams.element;
jpc.targetId = dhParams.elementId;
}
// if this is an existing connection and detach is not allowed we won't continue. The connection's
// endpoints have been reinstated; everything is back to how it was.
if (existingConnection && jpc.suspendedEndpoint.id !== _ep.id) {
if (!jpc.isDetachAllowed(jpc) || !jpc.endpoints[idx].isDetachAllowed(jpc) || !jpc.suspendedEndpoint.isDetachAllowed(jpc) || !_jsPlumb.checkCondition("beforeDetach", jpc)) {
_doContinue = false;
}
}
// ------------ wrap the execution path in a function so we can support asynchronous beforeDrop
var continueFunction = function (optionalData) {
// remove this jpc from the current endpoint, which is a floating endpoint that we will
// subsequently discard.
jpc.endpoints[idx].detachFromConnection(jpc);
// if there's a suspended endpoint, detach it from the connection.
if (jpc.suspendedEndpoint) {
jpc.suspendedEndpoint.detachFromConnection(jpc);
}
jpc.endpoints[idx] = _ep;
_ep.addConnection(jpc);
// copy our parameters in to the connection:
var params = _ep.getParameters();
for (var aParam in params) {
jpc.setParameter(aParam, params[aParam]);
}
if (!existingConnection) {
// if not an existing connection and
if (params.draggable) {
_jsPlumb.initDraggable(this.element, dhParams.dragOptions, "internal", _jsPlumb);
}
}
else {
var suspendedElementId = jpc.suspendedEndpoint.elementId;
_jsPlumb.fireMoveEvent({
index: idx,
originalSourceId: idx === 0 ? suspendedElementId : jpc.sourceId,
newSourceId: idx === 0 ? _ep.elementId : jpc.sourceId,
originalTargetId: idx === 1 ? suspendedElementId : jpc.targetId,
newTargetId: idx === 1 ? _ep.elementId : jpc.targetId,
originalSourceEndpoint: idx === 0 ? jpc.suspendedEndpoint : jpc.endpoints[0],
newSourceEndpoint: idx === 0 ? _ep : jpc.endpoints[0],
originalTargetEndpoint: idx === 1 ? jpc.suspendedEndpoint : jpc.endpoints[1],
newTargetEndpoint: idx === 1 ? _ep : jpc.endpoints[1],
connection: jpc
}, originalEvent);
}
if (idx === 1) {
_jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc);
}
else {
_jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source);
}
// when makeSource has uniqueEndpoint:true, we want to create connections with new endpoints
// that are subsequently deleted. So makeSource sets `finalEndpoint`, which is the Endpoint to
// which the connection should be attached. The `detachFromConnection` call below results in the
// temporary endpoint being cleaned up.
if (jpc.endpoints[0].finalEndpoint) {
var _toDelete = jpc.endpoints[0];
_toDelete.detachFromConnection(jpc);
jpc.endpoints[0] = jpc.endpoints[0].finalEndpoint;
jpc.endpoints[0].addConnection(jpc);
}
// if optionalData was given, merge it onto the connection's data.
if (_ju.isObject(optionalData)) {
jpc.mergeData(optionalData);
}
// finalise will inform the anchor manager and also add to
// connectionsByScope if necessary.
_jsPlumb.finaliseConnection(jpc, null, originalEvent, false);
jpc.setHover(false);
// SP continuous anchor flush
_jsPlumb.revalidate(jpc.endpoints[0].element);
}.bind(this);
var dontContinueFunction = function () {
// otherwise just put it back on the endpoint it was on before the drag.
if (jpc.suspendedEndpoint) {
jpc.endpoints[idx] = jpc.suspendedEndpoint;
jpc.setHover(false);
jpc._forceDetach = true;
if (idx === 0) {
jpc.source = jpc.suspendedEndpoint.element;
jpc.sourceId = jpc.suspendedEndpoint.elementId;
} else {
jpc.target = jpc.suspendedEndpoint.element;
jpc.targetId = jpc.suspendedEndpoint.elementId;
}
jpc.suspendedEndpoint.addConnection(jpc);
// TODO checkSanity
if (idx === 1) {
_jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc);
}
else {
_jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source);
}
_jsPlumb.repaint(jpc.sourceId);
jpc._forceDetach = false;
}
};
// --------------------------------------
// now check beforeDrop. this will be available only on Endpoints that are setup to
// have a beforeDrop condition (although, secretly, under the hood all Endpoints and
// the Connection have them, because they are on jsPlumbUIComponent. shhh!), because
// it only makes sense to have it on a target endpoint.
_doContinue = _doContinue && dhParams.isDropAllowed(jpc.sourceId, jpc.targetId, jpc.scope, jpc, _ep);// && jpc.pending;
if (_doContinue) {
continueFunction(_doContinue);
return true;
}
else {
dontContinueFunction();
}
}
if (dhParams.maybeCleanup) {
dhParams.maybeCleanup(_ep);
}
_jsPlumb.currentlyDragging = false;
};
};
}).call(typeof window !== 'undefined' ? window : this);
/*
* This file contains the code for Connections.
*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;
(function () {
"use strict";
var root = this,
_jp = root.jsPlumb,
_ju = root.jsPlumbUtil;
var makeConnector = function (_jsPlumb, renderMode, connectorName, connectorArgs, forComponent) {
// first make sure we have a cache for the specified renderer
_jp.Connectors[renderMode] = _jp.Connectors[renderMode] || {};
// now see if the one we want exists; if not we will try to make it
if (_jp.Connectors[renderMode][connectorName] == null) {
if (_jp.Connectors[connectorName] == null) {
if (!_jsPlumb.Defaults.DoNotThrowErrors) {
throw new TypeError("jsPlumb: unknown connector type '" + connectorName + "'");
} else {
return null;
}
}
_jp.Connectors[renderMode][connectorName] = function() {
_jp.Connectors[connectorName].apply(this, arguments);
_jp.ConnectorRenderers[renderMode].apply(this, arguments);
};
_ju.extend(_jp.Connectors[renderMode][connectorName], [ _jp.Connectors[connectorName], _jp.ConnectorRenderers[renderMode]]);
}
return new _jp.Connectors[renderMode][connectorName](connectorArgs, forComponent);
},
_makeAnchor = function (anchorParams, elementId, _jsPlumb) {
return (anchorParams) ? _jsPlumb.makeAnchor(anchorParams, elementId, _jsPlumb) : null;
},
_updateConnectedClass = function (conn, element, _jsPlumb, remove) {
if (element != null) {
element._jsPlumbConnections = element._jsPlumbConnections || {};
if (remove) {
delete element._jsPlumbConnections[conn.id];
}
else {
element._jsPlumbConnections[conn.id] = true;
}
if (_ju.isEmpty(element._jsPlumbConnections)) {
_jsPlumb.removeClass(element, _jsPlumb.connectedClass);
}
else {
_jsPlumb.addClass(element, _jsPlumb.connectedClass);
}
}
};
_jp.Connection = function (params) {
var _newEndpoint = params.newEndpoint;
this.id = params.id;
this.connector = null;
this.idPrefix = "_jsplumb_c_";
this.defaultLabelLocation = 0.5;
this.defaultOverlayKeys = ["Overlays", "ConnectionOverlays"];
// if a new connection is the result of moving some existing connection, params.previousConnection
// will have that Connection in it. listeners for the jsPlumbConnection event can look for that
// member and take action if they need to.
this.previousConnection = params.previousConnection;
this.source = _jp.getElement(params.source);
this.target = _jp.getElement(params.target);
_jp.OverlayCapableJsPlumbUIComponent.apply(this, arguments);
// sourceEndpoint and targetEndpoint override source/target, if they are present. but
// source is not overridden if the Endpoint has declared it is not the final target of a connection;
// instead we use the source that the Endpoint declares will be the final source element.
if (params.sourceEndpoint) {
this.source = params.sourceEndpoint.getElement();
this.sourceId = params.sourceEndpoint.elementId;
} else {
this.sourceId = this._jsPlumb.instance.getId(this.source);
}
if (params.targetEndpoint) {
this.target = params.targetEndpoint.getElement();
this.targetId = params.targetEndpoint.elementId;
} else {
this.targetId = this._jsPlumb.instance.getId(this.target);
}
this.scope = params.scope; // scope may have been passed in to the connect call. if it wasn't, we will pull it from the source endpoint, after having initialised the endpoints.
this.endpoints = [];
this.endpointStyles = [];
var _jsPlumb = this._jsPlumb.instance;
_jsPlumb.manage(this.sourceId, this.source);
_jsPlumb.manage(this.targetId, this.target);
this._jsPlumb.visible = true;
this._jsPlumb.params = {
cssClass: params.cssClass,
container: params.container,
"pointer-events": params["pointer-events"],
editorParams: params.editorParams,
overlays: params.overlays
};
this._jsPlumb.lastPaintedAt = null;
// listen to mouseover and mouseout events passed from the container delegate.
this.bind("mouseover", function () {
this.setHover(true);
}.bind(this));
this.bind("mouseout", function () {
this.setHover(false);
}.bind(this));
// INITIALISATION CODE
this.makeEndpoint = function (isSource, el, elId, ep) {
elId = elId || this._jsPlumb.instance.getId(el);
return this.prepareEndpoint(_jsPlumb, _newEndpoint, this, ep, isSource ? 0 : 1, params, el, elId);
};
// if type given, get the endpoint definitions mapping to that type from the jsplumb instance, and use those.
// we apply types at the end of this constructor but endpoints are only honoured in a type definition at
// create time.
if (params.type) {
params.endpoints = params.endpoints || this._jsPlumb.instance.deriveEndpointAndAnchorSpec(params.type).endpoints;
}
var eS = this.makeEndpoint(true, this.source, this.sourceId, params.sourceEndpoint),
eT = this.makeEndpoint(false, this.target, this.targetId, params.targetEndpoint);
if (eS) {
_ju.addToList(params.endpointsByElement, this.sourceId, eS);
}
if (eT) {
_ju.addToList(params.endpointsByElement, this.targetId, eT);
}
// if scope not set, set it to be the scope for the source endpoint.
if (!this.scope) {
this.scope = this.endpoints[0].scope;
}
// if explicitly told to (or not to) delete endpoints when empty, override endpoint's preferences
if (params.deleteEndpointsOnEmpty != null) {
this.endpoints[0].setDeleteOnEmpty(params.deleteEndpointsOnEmpty);
this.endpoints[1].setDeleteOnEmpty(params.deleteEndpointsOnEmpty);
}
// -------------------------- DEFAULT TYPE ---------------------------------------------
// DETACHABLE
var _detachable = _jsPlumb.Defaults.ConnectionsDetachable;
if (params.detachable === false) {
_detachable = false;
}
if (this.endpoints[0].connectionsDetachable === false) {
_detachable = false;
}
if (this.endpoints[1].connectionsDetachable === false) {
_detachable = false;
}
// REATTACH
var _reattach = params.reattach || this.endpoints[0].reattachConnections || this.endpoints[1].reattachConnections || _jsPlumb.Defaults.ReattachConnections;
this.appendToDefaultType({
detachable: _detachable,
reattach: _reattach,
paintStyle:this.endpoints[0].connectorStyle || this.endpoints[1].connectorStyle || params.paintStyle || _jsPlumb.Defaults.PaintStyle || _jp.Defaults.PaintStyle,
hoverPaintStyle:this.endpoints[0].connectorHoverStyle || this.endpoints[1].connectorHoverStyle || params.hoverPaintStyle || _jsPlumb.Defaults.HoverPaintStyle || _jp.Defaults.HoverPaintStyle
});
var _suspendedAt = _jsPlumb.getSuspendedAt();
if (!_jsPlumb.isSuspendDrawing()) {
// paint the endpoints
var myInfo = _jsPlumb.getCachedData(this.sourceId),
myOffset = myInfo.o, myWH = myInfo.s,
otherInfo = _jsPlumb.getCachedData(this.targetId),
otherOffset = otherInfo.o,
otherWH = otherInfo.s,
initialTimestamp = _suspendedAt || _jsPlumb.timestamp(),
anchorLoc = this.endpoints[0].anchor.compute({
xy: [ myOffset.left, myOffset.top ], wh: myWH, element: this.endpoints[0],
elementId: this.endpoints[0].elementId,
txy: [ otherOffset.left, otherOffset.top ], twh: otherWH, tElement: this.endpoints[1],
timestamp: initialTimestamp
});
this.endpoints[0].paint({ anchorLoc: anchorLoc, timestamp: initialTimestamp });
anchorLoc = this.endpoints[1].anchor.compute({
xy: [ otherOffset.left, otherOffset.top ], wh: otherWH, element: this.endpoints[1],
elementId: this.endpoints[1].elementId,
txy: [ myOffset.left, myOffset.top ], twh: myWH, tElement: this.endpoints[0],
timestamp: initialTimestamp
});
this.endpoints[1].paint({ anchorLoc: anchorLoc, timestamp: initialTimestamp });
}
this.getTypeDescriptor = function () {
return "connection";
};
this.getAttachedElements = function () {
return this.endpoints;
};
this.isDetachable = function (ep) {
return ep != null ? ep.connectionsDetachable === true : this._jsPlumb.detachable === true;
};
this.setDetachable = function (detachable) {
this._jsPlumb.detachable = detachable === true;
};
this.isReattach = function () {
return this._jsPlumb.reattach === true || this.endpoints[0].reattachConnections === true || this.endpoints[1].reattachConnections === true;
};
this.setReattach = function (reattach) {
this._jsPlumb.reattach = reattach === true;
};
// END INITIALISATION CODE
// COST + DIRECTIONALITY
// if cost not supplied, try to inherit from source endpoint
this._jsPlumb.cost = params.cost || this.endpoints[0].getConnectionCost();
this._jsPlumb.directed = params.directed;
// inherit directed flag if set no source endpoint
if (params.directed == null) {
this._jsPlumb.directed = this.endpoints[0].areConnectionsDirected();
}
// END COST + DIRECTIONALITY
// PARAMETERS
// merge all the parameters objects into the connection. parameters set
// on the connection take precedence; then source endpoint params, then
// finally target endpoint params.
var _p = _jp.extend({}, this.endpoints[1].getParameters());
_jp.extend(_p, this.endpoints[0].getParameters());
_jp.extend(_p, this.getParameters());
this.setParameters(_p);
// END PARAMETERS
// PAINTING
this.setConnector(this.endpoints[0].connector || this.endpoints[1].connector || params.connector || _jsPlumb.Defaults.Connector || _jp.Defaults.Connector, true);
var data = params.data == null || !_ju.isObject(params.data) ? {} : params.data;
this.getData = function() { return data; };
this.setData = function(d) { data = d || {}; };
this.mergeData = function(d) { data = _jp.extend(data, d); };
// the very last thing we do is apply types, if there are any.
var _types = [ "default", this.endpoints[0].connectionType, this.endpoints[1].connectionType, params.type ].join(" ");
if (/[^\s]/.test(_types)) {
this.addType(_types, params.data, true);
}
this.updateConnectedClass();
// END PAINTING
};
_ju.extend(_jp.Connection, _jp.OverlayCapableJsPlumbUIComponent, {
applyType: function (t, doNotRepaint, typeMap) {
var _connector = null;
if (t.connector != null) {
_connector = this.getCachedTypeItem("connector", typeMap.connector);
if (_connector == null) {
_connector = this.prepareConnector(t.connector, typeMap.connector);
this.cacheTypeItem("connector", _connector, typeMap.connector);
}
this.setPreparedConnector(_connector);
}
// none of these things result in the creation of objects so can be ignored.
if (t.detachable != null) {
this.setDetachable(t.detachable);
}
if (t.reattach != null) {
this.setReattach(t.reattach);
}
if (t.scope) {
this.scope = t.scope;
}
if (t.cssClass != null && this.canvas) {
this._jsPlumb.instance.addClass(this.canvas, t.cssClass);
}
var _anchors = null;
// this also results in the creation of objects.
if (t.anchor) {
// note that even if the param was anchor, we store `anchors`.
_anchors = this.getCachedTypeItem("anchors", typeMap.anchor);
if (_anchors == null) {
_anchors = [ this._jsPlumb.instance.makeAnchor(t.anchor), this._jsPlumb.instance.makeAnchor(t.anchor) ];
this.cacheTypeItem("anchors", _anchors, typeMap.anchor);
}
}
else if (t.anchors) {
_anchors = this.getCachedTypeItem("anchors", typeMap.anchors);
if (_anchors == null) {
_anchors = [
this._jsPlumb.instance.makeAnchor(t.anchors[0]),
this._jsPlumb.instance.makeAnchor(t.anchors[1])
];
this.cacheTypeItem("anchors", _anchors, typeMap.anchors);
}
}
if (_anchors != null) {
this.endpoints[0].anchor = _anchors[0];
this.endpoints[1].anchor = _anchors[1];
if (this.endpoints[1].anchor.isDynamic) {
this._jsPlumb.instance.repaint(this.endpoints[1].elementId);
}
}
_jp.OverlayCapableJsPlumbUIComponent.applyType(this, t);
},
addClass: function (c, informEndpoints) {
if (informEndpoints) {
this.endpoints[0].addClass(c);
this.endpoints[1].addClass(c);
if (this.suspendedEndpoint) {
this.suspendedEndpoint.addClass(c);
}
}
if (this.connector) {
this.connector.addClass(c);
}
},
removeClass: function (c, informEndpoints) {
if (informEndpoints) {
this.endpoints[0].removeClass(c);
this.endpoints[1].removeClass(c);
if (this.suspendedEndpoint) {
this.suspendedEndpoint.removeClass(c);
}
}
if (this.connector) {
this.connector.removeClass(c);
}
},
isVisible: function () {
return this._jsPlumb.visible;
},
setVisible: function (v) {
this._jsPlumb.visible = v;
if (this.connector) {
this.connector.setVisible(v);
}
this.repaint();
},
cleanup: function () {
this.updateConnectedClass(true);
this.endpoints = null;
this.source = null;
this.target = null;
if (this.connector != null) {
this.connector.cleanup(true);
this.connector.destroy(true);
}
this.connector = null;
},
updateConnectedClass:function(remove) {
if (this._jsPlumb) {
_updateConnectedClass(this, this.source, this._jsPlumb.instance, remove);
_updateConnectedClass(this, this.target, this._jsPlumb.instance, remove);
}
},
setHover: function (state) {
if (this.connector && this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) {
this.connector.setHover(state);
root.jsPlumb[state ? "addClass" : "removeClass"](this.source, this._jsPlumb.instance.hoverSourceClass);
root.jsPlumb[state ? "addClass" : "removeClass"](this.target, this._jsPlumb.instance.hoverTargetClass);
}
},
getUuids:function() {
return [ this.endpoints[0].getUuid(), this.endpoints[1].getUuid() ];
},
getCost: function () {
return this._jsPlumb ? this._jsPlumb.cost : -Infinity;
},
setCost: function (c) {
this._jsPlumb.cost = c;
},
isDirected: function () {
return this._jsPlumb.directed;
},
getConnector: function () {
return this.connector;
},
prepareConnector:function(connectorSpec, typeId) {
var connectorArgs = {
_jsPlumb: this._jsPlumb.instance,
cssClass: this._jsPlumb.params.cssClass,
container: this._jsPlumb.params.container,
"pointer-events": this._jsPlumb.params["pointer-events"]
},
renderMode = this._jsPlumb.instance.getRenderMode(),
connector;
if (_ju.isString(connectorSpec)) {
connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec, connectorArgs, this);
} // lets you use a string as shorthand.
else if (_ju.isArray(connectorSpec)) {
if (connectorSpec.length === 1) {
connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec[0], connectorArgs, this);
}
else {
connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec[0], _ju.merge(connectorSpec[1], connectorArgs), this);
}
}
if (typeId != null) {
connector.typeId = typeId;
}
return connector;
},
setPreparedConnector: function(connector, doNotRepaint, doNotChangeListenerComponent, typeId) {
if (this.connector !== connector) {
var previous, previousClasses = "";
// the connector will not be cleaned up if it was set as part of a type, because `typeId` will be set on it
// and we havent passed in `true` for "force" here.
if (this.connector != null) {
previous = this.connector;
previousClasses = previous.getClass();
this.connector.cleanup();
this.connector.destroy();
}
this.connector = connector;
if (typeId) {
this.cacheTypeItem("connector", connector, typeId);
}
this.canvas = this.connector.canvas;
this.bgCanvas = this.connector.bgCanvas;
// put classes from prior connector onto the canvas
this.addClass(previousClasses);
// new: instead of binding listeners per connector, we now just have one delegate on the container.
// so for that handler we set the connection as the '_jsPlumb' member of the canvas element, and
// bgCanvas, if it exists, which it does right now in the VML renderer, so it won't from v 2.0.0 onwards.
if (this.canvas) {
this.canvas._jsPlumb = this;
}
if (this.bgCanvas) {
this.bgCanvas._jsPlumb = this;
}
if (previous != null) {
var o = this.getOverlays();
for (var i = 0; i < o.length; i++) {
if (o[i].transfer) {
o[i].transfer(this.connector);
}
}
}
if (!doNotChangeListenerComponent) {
this.setListenerComponent(this.connector);
}
if (!doNotRepaint) {
this.repaint();
}
}
},
setConnector: function (connectorSpec, doNotRepaint, doNotChangeListenerComponent, typeId) {
var connector = this.prepareConnector(connectorSpec, typeId);
this.setPreparedConnector(connector, doNotRepaint, doNotChangeListenerComponent, typeId);
},
paint: function (params) {
if (!this._jsPlumb.instance.isSuspendDrawing() && this._jsPlumb.visible) {
params = params || {};
var timestamp = params.timestamp,
// if the moving object is not the source we must transpose the two references.
swap = false,
tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId,
tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
if (timestamp == null || timestamp !== this._jsPlumb.lastPaintedAt) {
var sourceInfo = this._jsPlumb.instance.updateOffset({elId:sId}).o,
targetInfo = this._jsPlumb.instance.updateOffset({elId:tId}).o,
sE = this.endpoints[sIdx], tE = this.endpoints[tIdx];
var sAnchorP = sE.anchor.getCurrentLocation({xy: [sourceInfo.left, sourceInfo.top], wh: [sourceInfo.width, sourceInfo.height], element: sE, timestamp: timestamp}),
tAnchorP = tE.anchor.getCurrentLocation({xy: [targetInfo.left, targetInfo.top], wh: [targetInfo.width, targetInfo.height], element: tE, timestamp: timestamp});
this.connector.resetBounds();
this.connector.compute({
sourcePos: sAnchorP,
targetPos: tAnchorP,
sourceOrientation:sE.anchor.getOrientation(sE),
targetOrientation:tE.anchor.getOrientation(tE),
sourceEndpoint: this.endpoints[sIdx],
targetEndpoint: this.endpoints[tIdx],
"stroke-width": this._jsPlumb.paintStyleInUse.strokeWidth,
sourceInfo: sourceInfo,
targetInfo: targetInfo
});
var overlayExtents = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
// compute overlays. we do this first so we can get their placements, and adjust the
// container if needs be (if an overlay would be clipped)
for (var i in this._jsPlumb.overlays) {
if (this._jsPlumb.overlays.hasOwnProperty(i)) {
var o = this._jsPlumb.overlays[i];
if (o.isVisible()) {
this._jsPlumb.overlayPlacements[i] = o.draw(this.connector, this._jsPlumb.paintStyleInUse, this.getAbsoluteOverlayPosition(o));
overlayExtents.minX = Math.min(overlayExtents.minX, this._jsPlumb.overlayPlacements[i].minX);
overlayExtents.maxX = Math.max(overlayExtents.maxX, this._jsPlumb.overlayPlacements[i].maxX);
overlayExtents.minY = Math.min(overlayExtents.minY, this._jsPlumb.overlayPlacements[i].minY);
overlayExtents.maxY = Math.max(overlayExtents.maxY, this._jsPlumb.overlayPlacements[i].maxY);
}
}
}
var lineWidth = parseFloat(this._jsPlumb.paintStyleInUse.strokeWidth || 1) / 2,
outlineWidth = parseFloat(this._jsPlumb.paintStyleInUse.strokeWidth || 0),
extents = {
xmin: Math.min(this.connector.bounds.minX - (lineWidth + outlineWidth), overlayExtents.minX),
ymin: Math.min(this.connector.bounds.minY - (lineWidth + outlineWidth), overlayExtents.minY),
xmax: Math.max(this.connector.bounds.maxX + (lineWidth + outlineWidth), overlayExtents.maxX),
ymax: Math.max(this.connector.bounds.maxY + (lineWidth + outlineWidth), overlayExtents.maxY)
};
// paint the connector.
this.connector.paint(this._jsPlumb.paintStyleInUse, null, extents);
// and then the overlays
for (var j in this._jsPlumb.overlays) {
if (this._jsPlumb.overlays.hasOwnProperty(j)) {
var p = this._jsPlumb.overlays[j];
if (p.isVisible()) {
p.paint(this._jsPlumb.overlayPlacements[j], extents);
}
}
}
}
this._jsPlumb.lastPaintedAt = timestamp;
}
},
repaint: function (params) {
var p = jsPlumb.extend(params || {}, {});
p.elId = this.sourceId;
this.paint(p);
},
prepareEndpoint: function (_jsPlumb, _newEndpoint, conn, existing, index, params, element, elementId) {
var e;
if (existing) {
conn.endpoints[index] = existing;
existing.addConnection(conn);
} else {
if (!params.endpoints) {
params.endpoints = [ null, null ];
}
var ep = params.endpoints[index] || params.endpoint || _jsPlumb.Defaults.Endpoints[index] || _jp.Defaults.Endpoints[index] || _jsPlumb.Defaults.Endpoint || _jp.Defaults.Endpoint;
if (!params.endpointStyles) {
params.endpointStyles = [ null, null ];
}
if (!params.endpointHoverStyles) {
params.endpointHoverStyles = [ null, null ];
}
var es = params.endpointStyles[index] || params.endpointStyle || _jsPlumb.Defaults.EndpointStyles[index] || _jp.Defaults.EndpointStyles[index] || _jsPlumb.Defaults.EndpointStyle || _jp.Defaults.EndpointStyle;
// Endpoints derive their fill from the connector's stroke, if no fill was specified.
if (es.fill == null && params.paintStyle != null) {
es.fill = params.paintStyle.stroke;
}
if (es.outlineStroke == null && params.paintStyle != null) {
es.outlineStroke = params.paintStyle.outlineStroke;
}
if (es.outlineWidth == null && params.paintStyle != null) {
es.outlineWidth = params.paintStyle.outlineWidth;
}
var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _jsPlumb.Defaults.EndpointHoverStyles[index] || _jp.Defaults.EndpointHoverStyles[index] || _jsPlumb.Defaults.EndpointHoverStyle || _jp.Defaults.EndpointHoverStyle;
// endpoint hover fill style is derived from connector's hover stroke style
if (params.hoverPaintStyle != null) {
if (ehs == null) {
ehs = {};
}
if (ehs.fill == null) {
ehs.fill = params.hoverPaintStyle.stroke;
}
}
var a = params.anchors ? params.anchors[index] :
params.anchor ? params.anchor :
_makeAnchor(_jsPlumb.Defaults.Anchors[index], elementId, _jsPlumb) ||
_makeAnchor(_jp.Defaults.Anchors[index], elementId, _jsPlumb) ||
_makeAnchor(_jsPlumb.Defaults.Anchor, elementId, _jsPlumb) ||
_makeAnchor(_jp.Defaults.Anchor, elementId, _jsPlumb),
u = params.uuids ? params.uuids[index] : null;
e = _newEndpoint({
paintStyle: es, hoverPaintStyle: ehs, endpoint: ep, connections: [ conn ],
uuid: u, anchor: a, source: element, scope: params.scope,
reattach: params.reattach || _jsPlumb.Defaults.ReattachConnections,
detachable: params.detachable || _jsPlumb.Defaults.ConnectionsDetachable
});
if (existing == null) {
e.setDeleteOnEmpty(true);
}
conn.endpoints[index] = e;
if (params.drawEndpoints === false) {
e.setVisible(false, true, true);
}
}
return e;
}
}); // END Connection class
}).call(typeof window !== 'undefined' ? window : this);
/*
* This file contains the code for creating and manipulating anchors.
*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;
(function () {
"use strict";
var root = this,
_ju = root.jsPlumbUtil,
_jp = root.jsPlumb;
//
// manages anchors for all elements.
//
_jp.AnchorManager = function (params) {
var _amEndpoints = {},
continuousAnchorLocations = {},
continuousAnchorOrientations = {},
connectionsByElementId = {},
self = this,
anchorLists = {},
jsPlumbInstance = params.jsPlumbInstance,
floatingConnections = {},
// used by placeAnchors function
placeAnchorsOnLine = function (desc, elementDimensions, elementPosition, connections, horizontal, otherMultiplier, reverse) {
var a = [], step = elementDimensions[horizontal ? 0 : 1] / (connections.length + 1);
for (var i = 0; i < connections.length; i++) {
var val = (i + 1) * step, other = otherMultiplier * elementDimensions[horizontal ? 1 : 0];
if (reverse) {
val = elementDimensions[horizontal ? 0 : 1] - val;
}
var dx = (horizontal ? val : other), x = elementPosition[0] + dx, xp = dx / elementDimensions[0],
dy = (horizontal ? other : val), y = elementPosition[1] + dy, yp = dy / elementDimensions[1];
a.push([ x, y, xp, yp, connections[i][1], connections[i][2] ]);
}
return a;
},
// used by edgeSortFunctions
currySort = function (reverseAngles) {
return function (a, b) {
var r = true;
if (reverseAngles) {
r = a[0][0] < b[0][0];
}
else {
r = a[0][0] > b[0][0];
}
return r === false ? -1 : 1;
};
},
// used by edgeSortFunctions
leftSort = function (a, b) {
// first get adjusted values
var p1 = a[0][0] < 0 ? -Math.PI - a[0][0] : Math.PI - a[0][0],
p2 = b[0][0] < 0 ? -Math.PI - b[0][0] : Math.PI - b[0][0];
if (p1 > p2) {
return 1;
}
else {
return -1;
}
},
// used by placeAnchors
edgeSortFunctions = {
"top": function (a, b) {
return a[0] > b[0] ? 1 : -1;
},
"right": currySort(true),
"bottom": currySort(true),
"left": leftSort
},
// used by placeAnchors
_sortHelper = function (_array, _fn) {
return _array.sort(_fn);
},
// used by AnchorManager.redraw
placeAnchors = function (elementId, _anchorLists) {
var cd = jsPlumbInstance.getCachedData(elementId), sS = cd.s, sO = cd.o,
placeSomeAnchors = function (desc, elementDimensions, elementPosition, unsortedConnections, isHorizontal, otherMultiplier, orientation) {
if (unsortedConnections.length > 0) {
var sc = _sortHelper(unsortedConnections, edgeSortFunctions[desc]), // puts them in order based on the target element's pos on screen
reverse = desc === "right" || desc === "top",
anchors = placeAnchorsOnLine(desc, elementDimensions,
elementPosition, sc,
isHorizontal, otherMultiplier, reverse);
// takes a computed anchor position and adjusts it for parent offset and scroll, then stores it.
var _setAnchorLocation = function (endpoint, anchorPos) {
continuousAnchorLocations[endpoint.id] = [ anchorPos[0], anchorPos[1], anchorPos[2], anchorPos[3] ];
continuousAnchorOrientations[endpoint.id] = orientation;
};
for (var i = 0; i < anchors.length; i++) {
var c = anchors[i][4], weAreSource = c.endpoints[0].elementId === elementId, weAreTarget = c.endpoints[1].elementId === elementId;
if (weAreSource) {
_setAnchorLocation(c.endpoints[0], anchors[i]);
}
if (weAreTarget) {
_setAnchorLocation(c.endpoints[1], anchors[i]);
}
}
}
};
placeSomeAnchors("bottom", sS, [sO.left, sO.top], _anchorLists.bottom, true, 1, [0, 1]);
placeSomeAnchors("top", sS, [sO.left, sO.top], _anchorLists.top, true, 0, [0, -1]);
placeSomeAnchors("left", sS, [sO.left, sO.top], _anchorLists.left, false, 0, [-1, 0]);
placeSomeAnchors("right", sS, [sO.left, sO.top], _anchorLists.right, false, 1, [1, 0]);
};
this.reset = function () {
_amEndpoints = {};
connectionsByElementId = {};
anchorLists = {};
};
this.addFloatingConnection = function (key, conn) {
floatingConnections[key] = conn;
};
this.removeFloatingConnection = function (key) {
delete floatingConnections[key];
};
this.newConnection = function (conn) {
var sourceId = conn.sourceId, targetId = conn.targetId,
ep = conn.endpoints,
doRegisterTarget = true,
registerConnection = function (otherIndex, otherEndpoint, otherAnchor, elId, c) {
if ((sourceId === targetId) && otherAnchor.isContinuous) {
// remove the target endpoint's canvas. we dont need it.
conn._jsPlumb.instance.removeElement(ep[1].canvas);
doRegisterTarget = false;
}
_ju.addToList(connectionsByElementId, elId, [c, otherEndpoint, otherAnchor.constructor === _jp.DynamicAnchor]);
};
registerConnection(0, ep[0], ep[0].anchor, targetId, conn);
if (doRegisterTarget) {
registerConnection(1, ep[1], ep[1].anchor, sourceId, conn);
}
};
var removeEndpointFromAnchorLists = function (endpoint) {
(function (list, eId) {
if (list) { // transient anchors dont get entries in this list.
var f = function (e) {
return e[4] === eId;
};
_ju.removeWithFunction(list.top, f);
_ju.removeWithFunction(list.left, f);
_ju.removeWithFunction(list.bottom, f);
_ju.removeWithFunction(list.right, f);
}
})(anchorLists[endpoint.elementId], endpoint.id);
};
this.connectionDetached = function (connInfo, doNotRedraw) {
var connection = connInfo.connection || connInfo,
sourceId = connInfo.sourceId,
targetId = connInfo.targetId,
ep = connection.endpoints,
removeConnection = function (otherIndex, otherEndpoint, otherAnchor, elId, c) {
_ju.removeWithFunction(connectionsByElementId[elId], function (_c) {
return _c[0].id === c.id;
});
};
removeConnection(1, ep[1], ep[1].anchor, sourceId, connection);
removeConnection(0, ep[0], ep[0].anchor, targetId, connection);
if (connection.floatingId) {
removeConnection(connection.floatingIndex, connection.floatingEndpoint, connection.floatingEndpoint.anchor, connection.floatingId, connection);
removeEndpointFromAnchorLists(connection.floatingEndpoint);
}
// remove from anchorLists
removeEndpointFromAnchorLists(connection.endpoints[0]);
removeEndpointFromAnchorLists(connection.endpoints[1]);
if (!doNotRedraw) {
self.redraw(connection.sourceId);
if (connection.targetId !== connection.sourceId) {
self.redraw(connection.targetId);
}
}
};
this.add = function (endpoint, elementId) {
_ju.addToList(_amEndpoints, elementId, endpoint);
};
this.changeId = function (oldId, newId) {
connectionsByElementId[newId] = connectionsByElementId[oldId];
_amEndpoints[newId] = _amEndpoints[oldId];
delete connectionsByElementId[oldId];
delete _amEndpoints[oldId];
};
this.getConnectionsFor = function (elementId) {
return connectionsByElementId[elementId] || [];
};
this.getEndpointsFor = function (elementId) {
return _amEndpoints[elementId] || [];
};
this.deleteEndpoint = function (endpoint) {
_ju.removeWithFunction(_amEndpoints[endpoint.elementId], function (e) {
return e.id === endpoint.id;
});
removeEndpointFromAnchorLists(endpoint);
};
this.clearFor = function (elementId) {
delete _amEndpoints[elementId];
_amEndpoints[elementId] = [];
};
// updates the given anchor list by either updating an existing anchor's info, or adding it. this function
// also removes the anchor from its previous list, if the edge it is on has changed.
// all connections found along the way (those that are connected to one of the faces this function
// operates on) are added to the connsToPaint list, as are their endpoints. in this way we know to repaint
// them wthout having to calculate anything else about them.
var _updateAnchorList = function (lists, theta, order, conn, aBoolean, otherElId, idx, reverse, edgeId, elId, connsToPaint, endpointsToPaint) {
// first try to find the exact match, but keep track of the first index of a matching element id along the way.s
var exactIdx = -1,
firstMatchingElIdx = -1,
endpoint = conn.endpoints[idx],
endpointId = endpoint.id,
oIdx = [1, 0][idx],
values = [
[ theta, order ],
conn,
aBoolean,
otherElId,
endpointId
],
listToAddTo = lists[edgeId],
listToRemoveFrom = endpoint._continuousAnchorEdge ? lists[endpoint._continuousAnchorEdge] : null,
i,
candidate;
if (listToRemoveFrom) {
var rIdx = _ju.findWithFunction(listToRemoveFrom, function (e) {
return e[4] === endpointId;
});
if (rIdx !== -1) {
listToRemoveFrom.splice(rIdx, 1);
// get all connections from this list
for (i = 0; i < listToRemoveFrom.length; i++) {
candidate = listToRemoveFrom[i][1];
_ju.addWithFunction(connsToPaint, candidate, function (c) {
return c.id === candidate.id;
});
_ju.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[idx], function (e) {
return e.id === candidate.endpoints[idx].id;
});
_ju.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[oIdx], function (e) {
return e.id === candidate.endpoints[oIdx].id;
});
}
}
}
for (i = 0; i < listToAddTo.length; i++) {
candidate = listToAddTo[i][1];
if (params.idx === 1 && listToAddTo[i][3] === otherElId && firstMatchingElIdx === -1) {
firstMatchingElIdx = i;
}
_ju.addWithFunction(connsToPaint, candidate, function (c) {
return c.id === candidate.id;
});
_ju.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[idx], function (e) {
return e.id === candidate.endpoints[idx].id;
});
_ju.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[oIdx], function (e) {
return e.id === candidate.endpoints[oIdx].id;
});
}
if (exactIdx !== -1) {
listToAddTo[exactIdx] = values;
}
else {
var insertIdx = reverse ? firstMatchingElIdx !== -1 ? firstMatchingElIdx : 0 : listToAddTo.length; // of course we will get this from having looked through the array shortly.
listToAddTo.splice(insertIdx, 0, values);
}
// store this for next time.
endpoint._continuousAnchorEdge = edgeId;
};
//
// find the entry in an endpoint's list for this connection and update its target endpoint
// with the current target in the connection.
// This method and sourceChanged need to be folder into one.
//
this.updateOtherEndpoint = function (sourceElId, oldTargetId, newTargetId, connection) {
var sIndex = _ju.findWithFunction(connectionsByElementId[sourceElId], function (i) {
return i[0].id === connection.id;
}),
tIndex = _ju.findWithFunction(connectionsByElementId[oldTargetId], function (i) {
return i[0].id === connection.id;
});
// update or add data for source
if (sIndex !== -1) {
connectionsByElementId[sourceElId][sIndex][0] = connection;
connectionsByElementId[sourceElId][sIndex][1] = connection.endpoints[1];
connectionsByElementId[sourceElId][sIndex][2] = connection.endpoints[1].anchor.constructor === _jp.DynamicAnchor;
}
// remove entry for previous target (if there)
if (tIndex > -1) {
connectionsByElementId[oldTargetId].splice(tIndex, 1);
// add entry for new target
_ju.addToList(connectionsByElementId, newTargetId, [connection, connection.endpoints[0], connection.endpoints[0].anchor.constructor === _jp.DynamicAnchor]);
}
connection.updateConnectedClass();
};
//
// notification that the connection given has changed source from the originalId to the newId.
// This involves:
// 1. removing the connection from the list of connections stored for the originalId
// 2. updating the source information for the target of the connection
// 3. re-registering the connection in connectionsByElementId with the newId
//
this.sourceChanged = function (originalId, newId, connection, newElement) {
if (originalId !== newId) {
connection.sourceId = newId;
connection.source = newElement;
// remove the entry that points from the old source to the target
_ju.removeWithFunction(connectionsByElementId[originalId], function (info) {
return info[0].id === connection.id;
});
// find entry for target and update it
var tIdx = _ju.findWithFunction(connectionsByElementId[connection.targetId], function (i) {
return i[0].id === connection.id;
});
if (tIdx > -1) {
connectionsByElementId[connection.targetId][tIdx][0] = connection;
connectionsByElementId[connection.targetId][tIdx][1] = connection.endpoints[0];
connectionsByElementId[connection.targetId][tIdx][2] = connection.endpoints[0].anchor.constructor === _jp.DynamicAnchor;
}
// add entry for new source
_ju.addToList(connectionsByElementId, newId, [connection, connection.endpoints[1], connection.endpoints[1].anchor.constructor === _jp.DynamicAnchor]);
// TODO SP not final on this yet. when a user drags an existing connection and it turns into a self
// loop, then this code hides the target endpoint (by removing it from the DOM) But I think this should
// occur only if the anchor is Continuous
if (connection.endpoints[1].anchor.isContinuous) {
if (connection.source === connection.target) {
connection._jsPlumb.instance.removeElement(connection.endpoints[1].canvas);
}
else {
if (connection.endpoints[1].canvas.parentNode == null) {
connection._jsPlumb.instance.appendElement(connection.endpoints[1].canvas);
}
}
}
connection.updateConnectedClass();
}
};
//
// moves the given endpoint from `currentId` to `element`.
// This involves:
//
// 1. changing the key in _amEndpoints under which the endpoint is stored
// 2. changing the source or target values in all of the endpoint's connections
// 3. changing the array in connectionsByElementId in which the endpoint's connections
// are stored (done by either sourceChanged or updateOtherEndpoint)
//
this.rehomeEndpoint = function (ep, currentId, element) {
var eps = _amEndpoints[currentId] || [],
elementId = jsPlumbInstance.getId(element);
if (elementId !== currentId) {
var idx = eps.indexOf(ep);
if (idx > -1) {
var _ep = eps.splice(idx, 1)[0];
self.add(_ep, elementId);
}
}
for (var i = 0; i < ep.connections.length; i++) {
if (ep.connections[i].sourceId === currentId) {
self.sourceChanged(currentId, ep.elementId, ep.connections[i], ep.element);
}
else if (ep.connections[i].targetId === currentId) {
ep.connections[i].targetId = ep.elementId;
ep.connections[i].target = ep.element;
self.updateOtherEndpoint(ep.connections[i].sourceId, currentId, ep.elementId, ep.connections[i]);
}
}
};
this.redraw = function (elementId, ui, timestamp, offsetToUI, clearEdits, doNotRecalcEndpoint) {
if (!jsPlumbInstance.isSuspendDrawing()) {
// get all the endpoints for this element
var ep = _amEndpoints[elementId] || [],
endpointConnections = connectionsByElementId[elementId] || [],
connectionsToPaint = [],
endpointsToPaint = [],
anchorsToUpdate = [];
timestamp = timestamp || jsPlumbInstance.timestamp();
// offsetToUI are values that would have been calculated in the dragManager when registering
// an endpoint for an element that had a parent (somewhere in the hierarchy) that had been
// registered as draggable.
offsetToUI = offsetToUI || {left: 0, top: 0};
if (ui) {
ui = {
left: ui.left + offsetToUI.left,
top: ui.top + offsetToUI.top
};
}
// valid for one paint cycle.
var myOffset = jsPlumbInstance.updateOffset({ elId: elementId, offset: ui, recalc: false, timestamp: timestamp }),
orientationCache = {};
// actually, first we should compute the orientation of this element to all other elements to which
// this element is connected with a continuous anchor (whether both ends of the connection have
// a continuous anchor or just one)
for (var i = 0; i < endpointConnections.length; i++) {
var conn = endpointConnections[i][0],
sourceId = conn.sourceId,
targetId = conn.targetId,
sourceContinuous = conn.endpoints[0].anchor.isContinuous,
targetContinuous = conn.endpoints[1].anchor.isContinuous;
if (sourceContinuous || targetContinuous) {
var oKey = sourceId + "_" + targetId,
o = orientationCache[oKey],
oIdx = conn.sourceId === elementId ? 1 : 0;
if (sourceContinuous && !anchorLists[sourceId]) {
anchorLists[sourceId] = { top: [], right: [], bottom: [], left: [] };
}
if (targetContinuous && !anchorLists[targetId]) {
anchorLists[targetId] = { top: [], right: [], bottom: [], left: [] };
}
if (elementId !== targetId) {
jsPlumbInstance.updateOffset({ elId: targetId, timestamp: timestamp });
}
if (elementId !== sourceId) {
jsPlumbInstance.updateOffset({ elId: sourceId, timestamp: timestamp });
}
var td = jsPlumbInstance.getCachedData(targetId),
sd = jsPlumbInstance.getCachedData(sourceId);
if (targetId === sourceId && (sourceContinuous || targetContinuous)) {
// here we may want to improve this by somehow determining the face we'd like
// to put the connector on. ideally, when drawing, the face should be calculated
// by determining which face is closest to the point at which the mouse button
// was released. for now, we're putting it on the top face.
_updateAnchorList( anchorLists[sourceId], -Math.PI / 2, 0, conn, false, targetId, 0, false, "top", sourceId, connectionsToPaint, endpointsToPaint);
_updateAnchorList( anchorLists[targetId], -Math.PI / 2, 0, conn, false, sourceId, 1, false, "top", targetId, connectionsToPaint, endpointsToPaint);
}
else {
if (!o) {
o = this.calculateOrientation(sourceId, targetId, sd.o, td.o, conn.endpoints[0].anchor, conn.endpoints[1].anchor, conn);
orientationCache[oKey] = o;
// this would be a performance enhancement, but the computed angles need to be clamped to
//the (-PI/2 -> PI/2) range in order for the sorting to work properly.
/* orientationCache[oKey2] = {
orientation:o.orientation,
a:[o.a[1], o.a[0]],
theta:o.theta + Math.PI,
theta2:o.theta2 + Math.PI
};*/
}
if (sourceContinuous) {
_updateAnchorList(anchorLists[sourceId], o.theta, 0, conn, false, targetId, 0, false, o.a[0], sourceId, connectionsToPaint, endpointsToPaint);
}
if (targetContinuous) {
_updateAnchorList(anchorLists[targetId], o.theta2, -1, conn, true, sourceId, 1, true, o.a[1], targetId, connectionsToPaint, endpointsToPaint);
}
}
if (sourceContinuous) {
_ju.addWithFunction(anchorsToUpdate, sourceId, function (a) {
return a === sourceId;
});
}
if (targetContinuous) {
_ju.addWithFunction(anchorsToUpdate, targetId, function (a) {
return a === targetId;
});
}
_ju.addWithFunction(connectionsToPaint, conn, function (c) {
return c.id === conn.id;
});
if ((sourceContinuous && oIdx === 0) || (targetContinuous && oIdx === 1)) {
_ju.addWithFunction(endpointsToPaint, conn.endpoints[oIdx], function (e) {
return e.id === conn.endpoints[oIdx].id;
});
}
}
}
// place Endpoints whose anchors are continuous but have no Connections
for (i = 0; i < ep.length; i++) {
if (ep[i].connections.length === 0 && ep[i].anchor.isContinuous) {
if (!anchorLists[elementId]) {
anchorLists[elementId] = { top: [], right: [], bottom: [], left: [] };
}
_updateAnchorList(anchorLists[elementId], -Math.PI / 2, 0, {endpoints: [ep[i], ep[i]], paint: function () {
}}, false, elementId, 0, false, ep[i].anchor.getDefaultFace(), elementId, connectionsToPaint, endpointsToPaint);
_ju.addWithFunction(anchorsToUpdate, elementId, function (a) {
return a === elementId;
});
}
}
// now place all the continuous anchors we need to;
for (i = 0; i < anchorsToUpdate.length; i++) {
placeAnchors(anchorsToUpdate[i], anchorLists[anchorsToUpdate[i]]);
}
// now that continuous anchors have been placed, paint all the endpoints for this element
for (i = 0; i < ep.length; i++) {
ep[i].paint({ timestamp: timestamp, offset: myOffset, dimensions: myOffset.s, recalc: doNotRecalcEndpoint !== true });
}
// ... and any other endpoints we came across as a result of the continuous anchors.
for (i = 0; i < endpointsToPaint.length; i++) {
var cd = jsPlumbInstance.getCachedData(endpointsToPaint[i].elementId);
//endpointsToPaint[i].paint({ timestamp: timestamp, offset: cd, dimensions: cd.s });
endpointsToPaint[i].paint({ timestamp: null, offset: cd, dimensions: cd.s });
}
// paint all the standard and "dynamic connections", which are connections whose other anchor is
// static and therefore does need to be recomputed; we make sure that happens only one time.
// TODO we could have compiled a list of these in the first pass through connections; might save some time.
for (i = 0; i < endpointConnections.length; i++) {
var otherEndpoint = endpointConnections[i][1];
if (otherEndpoint.anchor.constructor === _jp.DynamicAnchor) {
otherEndpoint.paint({ elementWithPrecedence: elementId, timestamp: timestamp });
_ju.addWithFunction(connectionsToPaint, endpointConnections[i][0], function (c) {
return c.id === endpointConnections[i][0].id;
});
// all the connections for the other endpoint now need to be repainted
for (var k = 0; k < otherEndpoint.connections.length; k++) {
if (otherEndpoint.connections[k] !== endpointConnections[i][0]) {
_ju.addWithFunction(connectionsToPaint, otherEndpoint.connections[k], function (c) {
return c.id === otherEndpoint.connections[k].id;
});
}
}
} else {
_ju.addWithFunction(connectionsToPaint, endpointConnections[i][0], function (c) {
return c.id === endpointConnections[i][0].id;
});
}
}
// paint current floating connection for this element, if there is one.
var fc = floatingConnections[elementId];
if (fc) {
fc.paint({timestamp: timestamp, recalc: false, elId: elementId});
}
// paint all the connections
for (i = 0; i < connectionsToPaint.length; i++) {
connectionsToPaint[i].paint({elId: elementId, timestamp: null, recalc: false, clearEdits: clearEdits});
}
}
};
var ContinuousAnchor = function (anchorParams) {
_ju.EventGenerator.apply(this);
this.type = "Continuous";
this.isDynamic = true;
this.isContinuous = true;
var faces = anchorParams.faces || ["top", "right", "bottom", "left"],
clockwise = !(anchorParams.clockwise === false),
availableFaces = { },
opposites = { "top": "bottom", "right": "left", "left": "right", "bottom": "top" },
clockwiseOptions = { "top": "right", "right": "bottom", "left": "top", "bottom": "left" },
antiClockwiseOptions = { "top": "left", "right": "top", "left": "bottom", "bottom": "right" },
secondBest = clockwise ? clockwiseOptions : antiClockwiseOptions,
lastChoice = clockwise ? antiClockwiseOptions : clockwiseOptions,
cssClass = anchorParams.cssClass || "",
_currentFace = null, _lockedFace = null, X_AXIS_FACES = ["left", "right"], Y_AXIS_FACES = ["top", "bottom"],
_lockedAxis = null;
for (var i = 0; i < faces.length; i++) {
availableFaces[faces[i]] = true;
}
this.getDefaultFace = function () {
return faces.length === 0 ? "top" : faces[0];
};
this.isRelocatable = function() { return true; };
this.isSnapOnRelocate = function() { return true; };
// if the given edge is supported, returns it. otherwise looks for a substitute that _is_
// supported. if none supported we also return the request edge.
this.verifyEdge = function (edge) {
if (availableFaces[edge]) {
return edge;
}
else if (availableFaces[opposites[edge]]) {
return opposites[edge];
}
else if (availableFaces[secondBest[edge]]) {
return secondBest[edge];
}
else if (availableFaces[lastChoice[edge]]) {
return lastChoice[edge];
}
return edge; // we have to give them something.
};
this.isEdgeSupported = function (edge) {
return _lockedAxis == null ?
(_lockedFace == null ? availableFaces[edge] === true : _lockedFace === edge)
: _lockedAxis.indexOf(edge) !== -1;
};
this.setCurrentFace = function(face, overrideLock) {
_currentFace = face;
// if currently locked, and the user wants to override, do that.
if (overrideLock && _lockedFace != null) {
_lockedFace = _currentFace;
}
};
this.getCurrentFace = function() { return _currentFace; };
this.getSupportedFaces = function() {
var af = [];
for (var k in availableFaces) {
if (availableFaces[k]) {
af.push(k);
}
}
return af;
};
this.lock = function() {
_lockedFace = _currentFace;
};
this.unlock = function() {
_lockedFace = null;
};
this.isLocked = function() {
return _lockedFace != null;
};
this.lockCurrentAxis = function() {
if (_currentFace != null) {
_lockedAxis = (_currentFace === "left" || _currentFace === "right") ? X_AXIS_FACES : Y_AXIS_FACES;
}
};
this.unlockCurrentAxis = function() {
_lockedAxis = null;
};
this.compute = function (params) {
return continuousAnchorLocations[params.element.id] || [0, 0];
};
this.getCurrentLocation = function (params) {
return continuousAnchorLocations[params.element.id] || [0, 0];
};
this.getOrientation = function (endpoint) {
return continuousAnchorOrientations[endpoint.id] || [0, 0];
};
this.getCssClass = function () {
return cssClass;
};
};
// continuous anchors
jsPlumbInstance.continuousAnchorFactory = {
get: function (params) {
return new ContinuousAnchor(params);
},
clear: function (elementId) {
delete continuousAnchorLocations[elementId];
}
};
};
_jp.AnchorManager.prototype.calculateOrientation = function (sourceId, targetId, sd, td, sourceAnchor, targetAnchor) {
var Orientation = { HORIZONTAL: "horizontal", VERTICAL: "vertical", DIAGONAL: "diagonal", IDENTITY: "identity" },
axes = ["left", "top", "right", "bottom"];
if (sourceId === targetId) {
return {
orientation: Orientation.IDENTITY,
a: ["top", "top"]
};
}
var theta = Math.atan2((td.centery - sd.centery), (td.centerx - sd.centerx)),
theta2 = Math.atan2((sd.centery - td.centery), (sd.centerx - td.centerx));
// --------------------------------------------------------------------------------------
// improved face calculation. get midpoints of each face for source and target, then put in an array with all combinations of
// source/target faces. sort this array by distance between midpoints. the entry at index 0 is our preferred option. we can
// go through the array one by one until we find an entry in which each requested face is supported.
var candidates = [], midpoints = { };
(function (types, dim) {
for (var i = 0; i < types.length; i++) {
midpoints[types[i]] = {
"left": [ dim[i].left, dim[i].centery ],
"right": [ dim[i].right, dim[i].centery ],
"top": [ dim[i].centerx, dim[i].top ],
"bottom": [ dim[i].centerx , dim[i].bottom]
};
}
})([ "source", "target" ], [ sd, td ]);
for (var sf = 0; sf < axes.length; sf++) {
for (var tf = 0; tf < axes.length; tf++) {
candidates.push({
source: axes[sf],
target: axes[tf],
dist: Biltong.lineLength(midpoints.source[axes[sf]], midpoints.target[axes[tf]])
});
}
}
candidates.sort(function (a, b) {
return a.dist < b.dist ? -1 : a.dist > b.dist ? 1 : 0;
});
// now go through this list and try to get an entry that satisfies both (there will be one, unless one of the anchors
// declares no available faces)
var sourceEdge = candidates[0].source, targetEdge = candidates[0].target;
for (var i = 0; i < candidates.length; i++) {
if (!sourceAnchor.isContinuous || sourceAnchor.isEdgeSupported(candidates[i].source)) {
sourceEdge = candidates[i].source;
}
else {
sourceEdge = null;
}
if (!targetAnchor.isContinuous || targetAnchor.isEdgeSupported(candidates[i].target)) {
targetEdge = candidates[i].target;
}
else {
targetEdge = null;
}
if (sourceEdge != null && targetEdge != null) {
break;
}
}
if (sourceAnchor.isContinuous) {
sourceAnchor.setCurrentFace(sourceEdge);
}
if (targetAnchor.isContinuous) {
targetAnchor.setCurrentFace(targetEdge);
}
// --------------------------------------------------------------------------------------
return {
a: [ sourceEdge, targetEdge ],
theta: theta,
theta2: theta2
};
};
/**
* Anchors model a position on some element at which an Endpoint may be located. They began as a first class citizen of jsPlumb, ie. a user
* was required to create these themselves, but over time this has been replaced by the concept of referring to them either by name (eg. "TopMiddle"),
* or by an array describing their coordinates (eg. [ 0, 0.5, 0, -1 ], which is the same as "TopMiddle"). jsPlumb now handles all of the
* creation of Anchors without user intervention.
*/
_jp.Anchor = function (params) {
this.x = params.x || 0;
this.y = params.y || 0;
this.elementId = params.elementId;
this.cssClass = params.cssClass || "";
this.userDefinedLocation = null;
this.orientation = params.orientation || [ 0, 0 ];
this.lastReturnValue = null;
this.offsets = params.offsets || [ 0, 0 ];
this.timestamp = null;
var relocatable = params.relocatable !== false;
this.isRelocatable = function() { return relocatable; };
this.setRelocatable = function(_relocatable) { relocatable = _relocatable; };
var snapOnRelocate = params.snapOnRelocate !== false;
this.isSnapOnRelocate = function() { return snapOnRelocate; };
var locked = false;
this.lock = function() { locked = true; };
this.unlock = function() { locked = false; };
this.isLocked = function() { return locked; };
_ju.EventGenerator.apply(this);
this.compute = function (params) {
var xy = params.xy, wh = params.wh, timestamp = params.timestamp;
if (params.clearUserDefinedLocation) {
this.userDefinedLocation = null;
}
if (timestamp && timestamp === this.timestamp) {
return this.lastReturnValue;
}
if (this.userDefinedLocation != null) {
this.lastReturnValue = this.userDefinedLocation;
}
else {
this.lastReturnValue = [ xy[0] + (this.x * wh[0]) + this.offsets[0], xy[1] + (this.y * wh[1]) + this.offsets[1], this.x, this.y ];
}
this.timestamp = timestamp;
return this.lastReturnValue;
};
this.getCurrentLocation = function (params) {
params = params || {};
return (this.lastReturnValue == null || (params.timestamp != null && this.timestamp !== params.timestamp)) ? this.compute(params) : this.lastReturnValue;
};
this.setPosition = function(x, y, ox, oy, overrideLock) {
if (!locked || overrideLock) {
this.x = x;
this.y = y;
this.orientation = [ ox, oy ];
this.lastReturnValue = null;
}
};
};
_ju.extend(_jp.Anchor, _ju.EventGenerator, {
equals: function (anchor) {
if (!anchor) {
return false;
}
var ao = anchor.getOrientation(),
o = this.getOrientation();
return this.x === anchor.x && this.y === anchor.y && this.offsets[0] === anchor.offsets[0] && this.offsets[1] === anchor.offsets[1] && o[0] === ao[0] && o[1] === ao[1];
},
getUserDefinedLocation: function () {
return this.userDefinedLocation;
},
setUserDefinedLocation: function (l) {
this.userDefinedLocation = l;
},
clearUserDefinedLocation: function () {
this.userDefinedLocation = null;
},
getOrientation: function () {
return this.orientation;
},
getCssClass: function () {
return this.cssClass;
}
});
/**
* An Anchor that floats. its orientation is computed dynamically from
* its position relative to the anchor it is floating relative to. It is used when creating
* a connection through drag and drop.
*
* TODO FloatingAnchor could totally be refactored to extend Anchor just slightly.
*/
_jp.FloatingAnchor = function (params) {
_jp.Anchor.apply(this, arguments);
// this is the anchor that this floating anchor is referenced to for
// purposes of calculating the orientation.
var ref = params.reference,
// the canvas this refers to.
refCanvas = params.referenceCanvas,
size = _jp.getSize(refCanvas),
// these are used to store the current relative position of our
// anchor wrt the reference anchor. they only indicate
// direction, so have a value of 1 or -1 (or, very rarely, 0). these
// values are written by the compute method, and read
// by the getOrientation method.
xDir = 0, yDir = 0,
// temporary member used to store an orientation when the floating
// anchor is hovering over another anchor.
orientation = null,
_lastResult = null;
// clear from parent. we want floating anchor orientation to always be computed.
this.orientation = null;
// set these to 0 each; they are used by certain types of connectors in the loopback case,
// when the connector is trying to clear the element it is on. but for floating anchor it's not
// very important.
this.x = 0;
this.y = 0;
this.isFloating = true;
this.compute = function (params) {
var xy = params.xy,
result = [ xy[0] + (size[0] / 2), xy[1] + (size[1] / 2) ]; // return origin of the element. we may wish to improve this so that any object can be the drag proxy.
_lastResult = result;
return result;
};
this.getOrientation = function (_endpoint) {
if (orientation) {
return orientation;
}
else {
var o = ref.getOrientation(_endpoint);
// here we take into account the orientation of the other
// anchor: if it declares zero for some direction, we declare zero too. this might not be the most awesome. perhaps we can come
// up with a better way. it's just so that the line we draw looks like it makes sense. maybe this wont make sense.
return [ Math.abs(o[0]) * xDir * -1,
Math.abs(o[1]) * yDir * -1 ];
}
};
/**
* notification the endpoint associated with this anchor is hovering
* over another anchor; we want to assume that anchor's orientation
* for the duration of the hover.
*/
this.over = function (anchor, endpoint) {
orientation = anchor.getOrientation(endpoint);
};
/**
* notification the endpoint associated with this anchor is no
* longer hovering over another anchor; we should resume calculating
* orientation as we normally do.
*/
this.out = function () {
orientation = null;
};
this.getCurrentLocation = function (params) {
return _lastResult == null ? this.compute(params) : _lastResult;
};
};
_ju.extend(_jp.FloatingAnchor, _jp.Anchor);
var _convertAnchor = function (anchor, jsPlumbInstance, elementId) {
return anchor.constructor === _jp.Anchor ? anchor : jsPlumbInstance.makeAnchor(anchor, elementId, jsPlumbInstance);
};
/*
* A DynamicAnchor is an Anchor that contains a list of other Anchors, which it cycles
* through at compute time to find the one that is located closest to
* the center of the target element, and returns that Anchor's compute
* method result. this causes endpoints to follow each other with
* respect to the orientation of their target elements, which is a useful
* feature for some applications.
*
*/
_jp.DynamicAnchor = function (params) {
_jp.Anchor.apply(this, arguments);
this.isDynamic = true;
this.anchors = [];
this.elementId = params.elementId;
this.jsPlumbInstance = params.jsPlumbInstance;
for (var i = 0; i < params.anchors.length; i++) {
this.anchors[i] = _convertAnchor(params.anchors[i], this.jsPlumbInstance, this.elementId);
}
this.getAnchors = function () {
return this.anchors;
};
var _curAnchor = this.anchors.length > 0 ? this.anchors[0] : null,
_lastAnchor = _curAnchor,
self = this,
// helper method to calculate the distance between the centers of the two elements.
_distance = function (anchor, cx, cy, xy, wh) {
var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]),
acx = xy[0] + (wh[0] / 2), acy = xy[1] + (wh[1] / 2);
return (Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2)) +
Math.sqrt(Math.pow(acx - ax, 2) + Math.pow(acy - ay, 2)));
},
// default method uses distance between element centers. you can provide your own method in the dynamic anchor
// constructor (and also to jsPlumb.makeDynamicAnchor). the arguments to it are four arrays:
// xy - xy loc of the anchor's element
// wh - anchor's element's dimensions
// txy - xy loc of the element of the other anchor in the connection
// twh - dimensions of the element of the other anchor in the connection.
// anchors - the list of selectable anchors
_anchorSelector = params.selector || function (xy, wh, txy, twh, anchors) {
var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2);
var minIdx = -1, minDist = Infinity;
for (var i = 0; i < anchors.length; i++) {
var d = _distance(anchors[i], cx, cy, xy, wh);
if (d < minDist) {
minIdx = i + 0;
minDist = d;
}
}
return anchors[minIdx];
};
this.compute = function (params) {
var xy = params.xy, wh = params.wh, txy = params.txy, twh = params.twh;
this.timestamp = params.timestamp;
var udl = self.getUserDefinedLocation();
if (udl != null) {
return udl;
}
// if anchor is locked or an opposite element was not given, we
// maintain our state. anchor will be locked
// if it is the source of a drag and drop.
if (this.isLocked() || txy == null || twh == null) {
return _curAnchor.compute(params);
}
else {
params.timestamp = null; // otherwise clear this, i think. we want the anchor to compute.
}
_curAnchor = _anchorSelector(xy, wh, txy, twh, this.anchors);
this.x = _curAnchor.x;
this.y = _curAnchor.y;
if (_curAnchor !== _lastAnchor) {
this.fire("anchorChanged", _curAnchor);
}
_lastAnchor = _curAnchor;
return _curAnchor.compute(params);
};
this.getCurrentLocation = function (params) {
return this.getUserDefinedLocation() || (_curAnchor != null ? _curAnchor.getCurrentLocation(params) : null);
};
this.getOrientation = function (_endpoint) {
return _curAnchor != null ? _curAnchor.getOrientation(_endpoint) : [ 0, 0 ];
};
this.over = function (anchor, endpoint) {
if (_curAnchor != null) {
_curAnchor.over(anchor, endpoint);
}
};
this.out = function () {
if (_curAnchor != null) {
_curAnchor.out();
}
};
this.setAnchor = function(a) {
_curAnchor = a;
};
this.getCssClass = function () {
return (_curAnchor && _curAnchor.getCssClass()) || "";
};
/**
* Attempt to match an anchor with the given coordinates and then set it.
* @param coords
* @returns true if matching anchor found, false otherwise.
*/
this.setAnchorCoordinates = function(coords) {
var idx = jsPlumbUtil.findWithFunction(this.anchors, function(a) {
return a.x === coords[0] && a.y === coords[1];
});
if (idx !== -1) {
this.setAnchor(this.anchors[idx]);
return true;
} else {
return false;
}
};
};
_ju.extend(_jp.DynamicAnchor, _jp.Anchor);
// -------- basic anchors ------------------
var _curryAnchor = function (x, y, ox, oy, type, fnInit) {
_jp.Anchors[type] = function (params) {
var a = params.jsPlumbInstance.makeAnchor([ x, y, ox, oy, 0, 0 ], params.elementId, params.jsPlumbInstance);
a.type = type;
if (fnInit) {
fnInit(a, params);
}
return a;
};
};
_curryAnchor(0.5, 0, 0, -1, "TopCenter");
_curryAnchor(0.5, 1, 0, 1, "BottomCenter");
_curryAnchor(0, 0.5, -1, 0, "LeftMiddle");
_curryAnchor(1, 0.5, 1, 0, "RightMiddle");
_curryAnchor(0.5, 0, 0, -1, "Top");
_curryAnchor(0.5, 1, 0, 1, "Bottom");
_curryAnchor(0, 0.5, -1, 0, "Left");
_curryAnchor(1, 0.5, 1, 0, "Right");
_curryAnchor(0.5, 0.5, 0, 0, "Center");
_curryAnchor(1, 0, 0, -1, "TopRight");
_curryAnchor(1, 1, 0, 1, "BottomRight");
_curryAnchor(0, 0, 0, -1, "TopLeft");
_curryAnchor(0, 1, 0, 1, "BottomLeft");
// ------- dynamic anchors -------------------
// default dynamic anchors chooses from Top, Right, Bottom, Left
_jp.Defaults.DynamicAnchors = function (params) {
return params.jsPlumbInstance.makeAnchors(["TopCenter", "RightMiddle", "BottomCenter", "LeftMiddle"], params.elementId, params.jsPlumbInstance);
};
// default dynamic anchors bound to name 'AutoDefault'
_jp.Anchors.AutoDefault = function (params) {
var a = params.jsPlumbInstance.makeDynamicAnchor(_jp.Defaults.DynamicAnchors(params));
a.type = "AutoDefault";
return a;
};
// ------- continuous anchors -------------------
var _curryContinuousAnchor = function (type, faces) {
_jp.Anchors[type] = function (params) {
var a = params.jsPlumbInstance.makeAnchor(["Continuous", { faces: faces }], params.elementId, params.jsPlumbInstance);
a.type = type;
return a;
};
};
_jp.Anchors.Continuous = function (params) {
return params.jsPlumbInstance.continuousAnchorFactory.get(params);
};
_curryContinuousAnchor("ContinuousLeft", ["left"]);
_curryContinuousAnchor("ContinuousTop", ["top"]);
_curryContinuousAnchor("ContinuousBottom", ["bottom"]);
_curryContinuousAnchor("ContinuousRight", ["right"]);
// ------- position assign anchors -------------------
// this anchor type lets you assign the position at connection time.
_curryAnchor(0, 0, 0, 0, "Assign", function (anchor, params) {
// find what to use as the "position finder". the user may have supplied a String which represents
// the id of a position finder in jsPlumb.AnchorPositionFinders, or the user may have supplied the
// position finder as a function. we find out what to use and then set it on the anchor.
var pf = params.position || "Fixed";
anchor.positionFinder = pf.constructor === String ? params.jsPlumbInstance.AnchorPositionFinders[pf] : pf;
// always set the constructor params; the position finder might need them later (the Grid one does,
// for example)
anchor.constructorParams = params;
});
// these are the default anchor positions finders, which are used by the makeTarget function. supplying
// a position finder argument to that function allows you to specify where the resulting anchor will
// be located
root.jsPlumbInstance.prototype.AnchorPositionFinders = {
"Fixed": function (dp, ep, es) {
return [ (dp.left - ep.left) / es[0], (dp.top - ep.top) / es[1] ];
},
"Grid": function (dp, ep, es, params) {
var dx = dp.left - ep.left, dy = dp.top - ep.top,
gx = es[0] / (params.grid[0]), gy = es[1] / (params.grid[1]),
mx = Math.floor(dx / gx), my = Math.floor(dy / gy);
return [ ((mx * gx) + (gx / 2)) / es[0], ((my * gy) + (gy / 2)) / es[1] ];
}
};
// ------- perimeter anchors -------------------
_jp.Anchors.Perimeter = function (params) {
params = params || {};
var anchorCount = params.anchorCount || 60,
shape = params.shape;
if (!shape) {
throw new Error("no shape supplied to Perimeter Anchor type");
}
var _circle = function () {
var r = 0.5, step = Math.PI * 2 / anchorCount, current = 0, a = [];
for (var i = 0; i < anchorCount; i++) {
var x = r + (r * Math.sin(current)),
y = r + (r * Math.cos(current));
a.push([ x, y, 0, 0 ]);
current += step;
}
return a;
},
_path = function (segments) {
var anchorsPerFace = anchorCount / segments.length, a = [],
_computeFace = function (x1, y1, x2, y2, fractionalLength) {
anchorsPerFace = anchorCount * fractionalLength;
var dx = (x2 - x1) / anchorsPerFace, dy = (y2 - y1) / anchorsPerFace;
for (var i = 0; i < anchorsPerFace; i++) {
a.push([
x1 + (dx * i),
y1 + (dy * i),
0,
0
]);
}
};
for (var i = 0; i < segments.length; i++) {
_computeFace.apply(null, segments[i]);
}
return a;
},
_shape = function (faces) {
var s = [];
for (var i = 0; i < faces.length; i++) {
s.push([faces[i][0], faces[i][1], faces[i][2], faces[i][3], 1 / faces.length]);
}
return _path(s);
},
_rectangle = function () {
return _shape([
[ 0, 0, 1, 0 ],
[ 1, 0, 1, 1 ],
[ 1, 1, 0, 1 ],
[ 0, 1, 0, 0 ]
]);
};
var _shapes = {
"Circle": _circle,
"Ellipse": _circle,
"Diamond": function () {
return _shape([
[ 0.5, 0, 1, 0.5 ],
[ 1, 0.5, 0.5, 1 ],
[ 0.5, 1, 0, 0.5 ],
[ 0, 0.5, 0.5, 0 ]
]);
},
"Rectangle": _rectangle,
"Square": _rectangle,
"Triangle": function () {
return _shape([
[ 0.5, 0, 1, 1 ],
[ 1, 1, 0, 1 ],
[ 0, 1, 0.5, 0]
]);
},
"Path": function (params) {
var points = params.points, p = [], tl = 0;
for (var i = 0; i < points.length - 1; i++) {
var l = Math.sqrt(Math.pow(points[i][2] - points[i][0]) + Math.pow(points[i][3] - points[i][1]));
tl += l;
p.push([points[i][0], points[i][1], points[i + 1][0], points[i + 1][1], l]);
}
for (var j = 0; j < p.length; j++) {
p[j][4] = p[j][4] / tl;
}
return _path(p);
}
},
_rotate = function (points, amountInDegrees) {
var o = [], theta = amountInDegrees / 180 * Math.PI;
for (var i = 0; i < points.length; i++) {
var _x = points[i][0] - 0.5,
_y = points[i][1] - 0.5;
o.push([
0.5 + ((_x * Math.cos(theta)) - (_y * Math.sin(theta))),
0.5 + ((_x * Math.sin(theta)) + (_y * Math.cos(theta))),
points[i][2],
points[i][3]
]);
}
return o;
};
if (!_shapes[shape]) {
throw new Error("Shape [" + shape + "] is unknown by Perimeter Anchor type");
}
var da = _shapes[shape](params);
if (params.rotation) {
da = _rotate(da, params.rotation);
}
var a = params.jsPlumbInstance.makeDynamicAnchor(da);
a.type = "Perimeter";
return a;
};
}).call(typeof window !== 'undefined' ? window : this);
/*
* This file contains the default Connectors, Endpoint and Overlay definitions.
*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;
(function () {
"use strict";
var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil, _jg = root.Biltong;
_jp.Segments = {
/*
* Class: AbstractSegment
* A Connector is made up of 1..N Segments, each of which has a Type, such as 'Straight', 'Arc',
* 'Bezier'. This is new from 1.4.2, and gives us a lot more flexibility when drawing connections: things such
* as rounded corners for flowchart connectors, for example, or a straight line stub for Bezier connections, are
* much easier to do now.
*
* A Segment is responsible for providing coordinates for painting it, and also must be able to report its length.
*
*/
AbstractSegment: function (params) {
this.params = params;
/**
* Function: findClosestPointOnPath
* Finds the closest point on this segment to the given [x, y],
* returning both the x and y of the point plus its distance from
* the supplied point, and its location along the length of the
* path inscribed by the segment. This implementation returns
* Infinity for distance and null values for everything else;
* subclasses are expected to override.
*/
this.findClosestPointOnPath = function (x, y) {
return {
d: Infinity,
x: null,
y: null,
l: null
};
};
this.getBounds = function () {
return {
minX: Math.min(params.x1, params.x2),
minY: Math.min(params.y1, params.y2),
maxX: Math.max(params.x1, params.x2),
maxY: Math.max(params.y1, params.y2)
};
};
/**
* Computes the list of points on the segment that intersect the given line.
* @method lineIntersection
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @returns {Array<[number, number]>}
*/
this.lineIntersection = function(x1, y1, x2, y2) {
return [];
};
/**
* Computes the list of points on the segment that intersect the box with the given origin and size.
* @method boxIntersection
* @param {number} x1
* @param {number} y1
* @param {number} w
* @param {number} h
* @returns {Array<[number, number]>}
*/
this.boxIntersection = function(x, y, w, h) {
var a = [];
a.push.apply(a, this.lineIntersection(x, y, x + w, y));
a.push.apply(a, this.lineIntersection(x + w, y, x + w, y + h));
a.push.apply(a, this.lineIntersection(x + w, y + h, x, y + h));
a.push.apply(a, this.lineIntersection(x, y + h, x, y));
return a;
};
/**
* Computes the list of points on the segment that intersect the given bounding box, which is an object of the form { x:.., y:.., w:.., h:.. }.
* @method lineIntersection
* @param {BoundingRectangle} box
* @returns {Array<[number, number]>}
*/
this.boundingBoxIntersection = function(box) {
return this.boxIntersection(box.x, box.y, box.w, box.y);
};
},
Straight: function (params) {
var _super = _jp.Segments.AbstractSegment.apply(this, arguments),
length, m, m2, x1, x2, y1, y2,
_recalc = function () {
length = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
m = _jg.gradient({x: x1, y: y1}, {x: x2, y: y2});
m2 = -1 / m;
};
this.type = "Straight";
this.getLength = function () {
return length;
};
this.getGradient = function () {
return m;
};
this.getCoordinates = function () {
return { x1: x1, y1: y1, x2: x2, y2: y2 };
};
this.setCoordinates = function (coords) {
x1 = coords.x1;
y1 = coords.y1;
x2 = coords.x2;
y2 = coords.y2;
_recalc();
};
this.setCoordinates({x1: params.x1, y1: params.y1, x2: params.x2, y2: params.y2});
this.getBounds = function () {
return {
minX: Math.min(x1, x2),
minY: Math.min(y1, y2),
maxX: Math.max(x1, x2),
maxY: Math.max(y1, y2)
};
};
/**
* returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
* 0 to 1 inclusive. for the straight line segment this is simple maths.
*/
this.pointOnPath = function (location, absolute) {
if (location === 0 && !absolute) {
return { x: x1, y: y1 };
}
else if (location === 1 && !absolute) {
return { x: x2, y: y2 };
}
else {
var l = absolute ? location > 0 ? location : length + location : location * length;
return _jg.pointOnLine({x: x1, y: y1}, {x: x2, y: y2}, l);
}
};
/**
* returns the gradient of the segment at the given point - which for us is constant.
*/
this.gradientAtPoint = function (_) {
return m;
};
/**
* returns the point on the segment's path that is 'distance' along the length of the path from 'location', where
* 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels.
* this hands off to jsPlumbUtil to do the maths, supplying two points and the distance.
*/
this.pointAlongPathFrom = function (location, distance, absolute) {
var p = this.pointOnPath(location, absolute),
farAwayPoint = distance <= 0 ? {x: x1, y: y1} : {x: x2, y: y2 };
/*
location == 1 ? {
x:x1 + ((x2 - x1) * 10),
y:y1 + ((y1 - y2) * 10)
} :
*/
if (distance <= 0 && Math.abs(distance) > 1) {
distance *= -1;
}
return _jg.pointOnLine(p, farAwayPoint, distance);
};
// is c between a and b?
var within = function (a, b, c) {
return c >= Math.min(a, b) && c <= Math.max(a, b);
};
// find which of a and b is closest to c
var closest = function (a, b, c) {
return Math.abs(c - a) < Math.abs(c - b) ? a : b;
};
/**
Function: findClosestPointOnPath
Finds the closest point on this segment to [x,y]. See
notes on this method in AbstractSegment.
*/
this.findClosestPointOnPath = function (x, y) {
var out = {
d: Infinity,
x: null,
y: null,
l: null,
x1: x1,
x2: x2,
y1: y1,
y2: y2
};
if (m === 0) {
out.y = y1;
out.x = within(x1, x2, x) ? x : closest(x1, x2, x);
}
else if (m === Infinity || m === -Infinity) {
out.x = x1;
out.y = within(y1, y2, y) ? y : closest(y1, y2, y);
}
else {
// closest point lies on normal from given point to this line.
var b = y1 - (m * x1),
b2 = y - (m2 * x),
// y1 = m.x1 + b and y1 = m2.x1 + b2
// so m.x1 + b = m2.x1 + b2
// x1(m - m2) = b2 - b
// x1 = (b2 - b) / (m - m2)
_x1 = (b2 - b) / (m - m2),
_y1 = (m * _x1) + b;
out.x = within(x1, x2, _x1) ? _x1 : closest(x1, x2, _x1);//_x1;
out.y = within(y1, y2, _y1) ? _y1 : closest(y1, y2, _y1);//_y1;
}
var fractionInSegment = _jg.lineLength([ out.x, out.y ], [ x1, y1 ]);
out.d = _jg.lineLength([x, y], [out.x, out.y]);
out.l = fractionInSegment / length;
return out;
};
var _pointLiesBetween = function(q, p1, p2) {
return (p2 > p1) ? (p1 <= q && q <= p2) : (p1 >= q && q >= p2);
}, _plb = _pointLiesBetween;
/**
* Calculates all intersections of the given line with this segment.
* @param _x1
* @param _y1
* @param _x2
* @param _y2
* @returns {Array}
*/
this.lineIntersection = function(_x1, _y1, _x2, _y2) {
var m2 = Math.abs(_jg.gradient({x: _x1, y: _y1}, {x: _x2, y: _y2})),
m1 = Math.abs(m),
b = m1 === Infinity ? x1 : y1 - (m1 * x1),
out = [],
b2 = m2 === Infinity ? _x1 : _y1 - (m2 * _x1);
// if lines parallel, no intersection
if (m2 !== m1) {
// perpendicular, segment horizontal
if(m2 === Infinity && m1 === 0) {
if (_plb(_x1, x1, x2) && _plb(y1, _y1, _y2)) {
out = [ _x1, y1 ]; // we return X on the incident line and Y from the segment
}
} else if(m2 === 0 && m1 === Infinity) {
// perpendicular, segment vertical
if(_plb(_y1, y1, y2) && _plb(x1, _x1, _x2)) {
out = [x1, _y1]; // we return X on the segment and Y from the incident line
}
} else {
var X, Y;
if (m2 === Infinity) {
// test line is a vertical line. where does it cross the segment?
X = _x1;
if (_plb(X, x1, x2)) {
Y = (m1 * _x1) + b;
if (_plb(Y, _y1, _y2)) {
out = [ X, Y ];
}
}
} else if (m2 === 0) {
Y = _y1;
// test line is a horizontal line. where does it cross the segment?
if (_plb(Y, y1, y2)) {
X = (_y1 - b) / m1;
if (_plb(X, _x1, _x2)) {
out = [ X, Y ];
}
}
} else {
// mX + b = m2X + b2
// mX - m2X = b2 - b
// X(m - m2) = b2 - b
// X = (b2 - b) / (m - m2)
// Y = mX + b
X = (b2 - b) / (m1 - m2);
Y = (m1 * X) + b;
if(_plb(X, x1, x2) && _plb(Y, y1, y2)) {
out = [ X, Y];
}
}
}
}
return out;
};
/**
* Calculates all intersections of the given box with this segment. By default this method simply calls `lineIntersection` with each of the four
* faces of the box; subclasses can override this if they think there's a faster way to compute the entire box at once.
* @param x X position of top left corner of box
* @param y Y position of top left corner of box
* @param w width of box
* @param h height of box
* @returns {Array}
*/
this.boxIntersection = function(x, y, w, h) {
var a = [];
a.push.apply(a, this.lineIntersection(x, y, x + w, y));
a.push.apply(a, this.lineIntersection(x + w, y, x + w, y + h));
a.push.apply(a, this.lineIntersection(x + w, y + h, x, y + h));
a.push.apply(a, this.lineIntersection(x, y + h, x, y));
return a;
};
/**
* Calculates all intersections of the given bounding box with this segment. By default this method simply calls `lineIntersection` with each of the four
* faces of the box; subclasses can override this if they think there's a faster way to compute the entire box at once.
* @param box Bounding box, in { x:.., y:..., w:..., h:... } format.
* @returns {Array}
*/
this.boundingBoxIntersection = function(box) {
return this.boxIntersection(box.x, box.y, box.w, box.h);
};
},
/*
Arc Segment. You need to supply:
r - radius
cx - center x for the arc
cy - center y for the arc
ac - whether the arc is anticlockwise or not. default is clockwise.
and then either:
startAngle - startAngle for the arc.
endAngle - endAngle for the arc.
or:
x1 - x for start point
y1 - y for start point
x2 - x for end point
y2 - y for end point
*/
Arc: function (params) {
var _super = _jp.Segments.AbstractSegment.apply(this, arguments),
_calcAngle = function (_x, _y) {
return _jg.theta([params.cx, params.cy], [_x, _y]);
},
_calcAngleForLocation = function (segment, location) {
if (segment.anticlockwise) {
var sa = segment.startAngle < segment.endAngle ? segment.startAngle + TWO_PI : segment.startAngle,
s = Math.abs(sa - segment.endAngle);
return sa - (s * location);
}
else {
var ea = segment.endAngle < segment.startAngle ? segment.endAngle + TWO_PI : segment.endAngle,
ss = Math.abs(ea - segment.startAngle);
return segment.startAngle + (ss * location);
}
},
TWO_PI = 2 * Math.PI;
this.radius = params.r;
this.anticlockwise = params.ac;
this.type = "Arc";
if (params.startAngle && params.endAngle) {
this.startAngle = params.startAngle;
this.endAngle = params.endAngle;
this.x1 = params.cx + (this.radius * Math.cos(params.startAngle));
this.y1 = params.cy + (this.radius * Math.sin(params.startAngle));
this.x2 = params.cx + (this.radius * Math.cos(params.endAngle));
this.y2 = params.cy + (this.radius * Math.sin(params.endAngle));
}
else {
this.startAngle = _calcAngle(params.x1, params.y1);
this.endAngle = _calcAngle(params.x2, params.y2);
this.x1 = params.x1;
this.y1 = params.y1;
this.x2 = params.x2;
this.y2 = params.y2;
}
if (this.endAngle < 0) {
this.endAngle += TWO_PI;
}
if (this.startAngle < 0) {
this.startAngle += TWO_PI;
}
// segment is used by vml
//this.segment = _jg.quadrant([this.x1, this.y1], [this.x2, this.y2]);
// we now have startAngle and endAngle as positive numbers, meaning the
// absolute difference (|d|) between them is the sweep (s) of this arc, unless the
// arc is 'anticlockwise' in which case 's' is given by 2PI - |d|.
var ea = this.endAngle < this.startAngle ? this.endAngle + TWO_PI : this.endAngle;
this.sweep = Math.abs(ea - this.startAngle);
if (this.anticlockwise) {
this.sweep = TWO_PI - this.sweep;
}
var circumference = 2 * Math.PI * this.radius,
frac = this.sweep / TWO_PI,
length = circumference * frac;
this.getLength = function () {
return length;
};
this.getBounds = function () {
return {
minX: params.cx - params.r,
maxX: params.cx + params.r,
minY: params.cy - params.r,
maxY: params.cy + params.r
};
};
var VERY_SMALL_VALUE = 0.0000000001,
gentleRound = function (n) {
var f = Math.floor(n), r = Math.ceil(n);
if (n - f < VERY_SMALL_VALUE) {
return f;
}
else if (r - n < VERY_SMALL_VALUE) {
return r;
}
return n;
};
/**
* returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
* 0 to 1 inclusive.
*/
this.pointOnPath = function (location, absolute) {
if (location === 0) {
return { x: this.x1, y: this.y1, theta: this.startAngle };
}
else if (location === 1) {
return { x: this.x2, y: this.y2, theta: this.endAngle };
}
if (absolute) {
location = location / length;
}
var angle = _calcAngleForLocation(this, location),
_x = params.cx + (params.r * Math.cos(angle)),
_y = params.cy + (params.r * Math.sin(angle));
return { x: gentleRound(_x), y: gentleRound(_y), theta: angle };
};
/**
* returns the gradient of the segment at the given point.
*/
this.gradientAtPoint = function (location, absolute) {
var p = this.pointOnPath(location, absolute);
var m = _jg.normal([ params.cx, params.cy ], [p.x, p.y ]);
if (!this.anticlockwise && (m === Infinity || m === -Infinity)) {
m *= -1;
}
return m;
};
this.pointAlongPathFrom = function (location, distance, absolute) {
var p = this.pointOnPath(location, absolute),
arcSpan = distance / circumference * 2 * Math.PI,
dir = this.anticlockwise ? -1 : 1,
startAngle = p.theta + (dir * arcSpan),
startX = params.cx + (this.radius * Math.cos(startAngle)),
startY = params.cy + (this.radius * Math.sin(startAngle));
return {x: startX, y: startY};
};
// TODO: lineIntersection
},
Bezier: function (params) {
this.curve = [
{ x: params.x1, y: params.y1},
{ x: params.cp1x, y: params.cp1y },
{ x: params.cp2x, y: params.cp2y },
{ x: params.x2, y: params.y2 }
];
var _super = _jp.Segments.AbstractSegment.apply(this, arguments);
// although this is not a strictly rigorous determination of bounds
// of a bezier curve, it works for the types of curves that this segment
// type produces.
this.bounds = {
minX: Math.min(params.x1, params.x2, params.cp1x, params.cp2x),
minY: Math.min(params.y1, params.y2, params.cp1y, params.cp2y),
maxX: Math.max(params.x1, params.x2, params.cp1x, params.cp2x),
maxY: Math.max(params.y1, params.y2, params.cp1y, params.cp2y)
};
this.type = "Bezier";
var _translateLocation = function (_curve, location, absolute) {
if (absolute) {
location = root.jsBezier.locationAlongCurveFrom(_curve, location > 0 ? 0 : 1, location);
}
return location;
};
/**
* returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
* 0 to 1 inclusive.
*/
this.pointOnPath = function (location, absolute) {
location = _translateLocation(this.curve, location, absolute);
return root.jsBezier.pointOnCurve(this.curve, location);
};
/**
* returns the gradient of the segment at the given point.
*/
this.gradientAtPoint = function (location, absolute) {
location = _translateLocation(this.curve, location, absolute);
return root.jsBezier.gradientAtPoint(this.curve, location);
};
this.pointAlongPathFrom = function (location, distance, absolute) {
location = _translateLocation(this.curve, location, absolute);
return root.jsBezier.pointAlongCurveFrom(this.curve, location, distance);
};
this.getLength = function () {
return root.jsBezier.getLength(this.curve);
};
this.getBounds = function () {
return this.bounds;
};
this.findClosestPointOnPath = function (x, y) {
var p = root.jsBezier.nearestPointOnCurve({x:x,y:y}, this.curve);
return {
d:Math.sqrt(Math.pow(p.point.x - x, 2) + Math.pow(p.point.y - y, 2)),
x:p.point.x,
y:p.point.y,
l:p.location,
s:this
};
};
this.lineIntersection = function(x1, y1, x2, y2) {
return root.jsBezier.lineIntersection(x1, y1, x2, y2, this.curve);
};
}
};
_jp.SegmentRenderer = {
getPath: function (segment, isFirstSegment) {
return ({
"Straight": function (isFirstSegment) {
var d = segment.getCoordinates();
return (isFirstSegment ? "M " + d.x1 + " " + d.y1 + " " : "") + "L " + d.x2 + " " + d.y2;
},
"Bezier": function (isFirstSegment) {
var d = segment.params;
return (isFirstSegment ? "M " + d.x2 + " " + d.y2 + " " : "") +
"C " + d.cp2x + " " + d.cp2y + " " + d.cp1x + " " + d.cp1y + " " + d.x1 + " " + d.y1;
},
"Arc": function (isFirstSegment) {
var d = segment.params,
laf = segment.sweep > Math.PI ? 1 : 0,
sf = segment.anticlockwise ? 0 : 1;
return (isFirstSegment ? "M" + segment.x1 + " " + segment.y1 + " " : "") + "A " + segment.radius + " " + d.r + " 0 " + laf + "," + sf + " " + segment.x2 + " " + segment.y2;
}
})[segment.type](isFirstSegment);
}
};
/*
Class: UIComponent
Superclass for Connector and AbstractEndpoint.
*/
var AbstractComponent = function () {
this.resetBounds = function () {
this.bounds = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
};
this.resetBounds();
};
/*
* Class: Connector
* Superclass for all Connectors; here is where Segments are managed. This is exposed on jsPlumb just so it
* can be accessed from other files. You should not try to instantiate one of these directly.
*
* When this class is asked for a pointOnPath, or gradient etc, it must first figure out which segment to dispatch
* that request to. This is done by keeping track of the total connector length as segments are added, and also
* their cumulative ratios to the total length. Then when the right segment is found it is a simple case of dispatching
* the request to it (and adjusting 'location' so that it is relative to the beginning of that segment.)
*/
_jp.Connectors.AbstractConnector = function (params) {
AbstractComponent.apply(this, arguments);
var segments = [],
totalLength = 0,
segmentProportions = [],
segmentProportionalLengths = [],
stub = params.stub || 0,
sourceStub = _ju.isArray(stub) ? stub[0] : stub,
targetStub = _ju.isArray(stub) ? stub[1] : stub,
gap = params.gap || 0,
sourceGap = _ju.isArray(gap) ? gap[0] : gap,
targetGap = _ju.isArray(gap) ? gap[1] : gap,
userProvidedSegments = null,
paintInfo = null;
this.getPathData = function() {
var p = "";
for (var i = 0; i < segments.length; i++) {
p += _jp.SegmentRenderer.getPath(segments[i], i === 0);
p += " ";
}
return p;
};
/**
* Function: findSegmentForPoint
* Returns the segment that is closest to the given [x,y],
* null if nothing found. This function returns a JS
* object with:
*
* d - distance from segment
* l - proportional location in segment
* x - x point on the segment
* y - y point on the segment
* s - the segment itself.
*/
this.findSegmentForPoint = function (x, y) {
var out = { d: Infinity, s: null, x: null, y: null, l: null };
for (var i = 0; i < segments.length; i++) {
var _s = segments[i].findClosestPointOnPath(x, y);
if (_s.d < out.d) {
out.d = _s.d;
out.l = _s.l;
out.x = _s.x;
out.y = _s.y;
out.s = segments[i];
out.x1 = _s.x1;
out.x2 = _s.x2;
out.y1 = _s.y1;
out.y2 = _s.y2;
out.index = i;
}
}
return out;
};
this.lineIntersection = function(x1, y1, x2, y2) {
var out = [];
for (var i = 0; i < segments.length; i++) {
out.push.apply(out, segments[i].lineIntersection(x1, y1, x2, y2));
}
return out;
};
this.boxIntersection = function(x, y, w, h) {
var out = [];
for (var i = 0; i < segments.length; i++) {
out.push.apply(out, segments[i].boxIntersection(x, y, w, h));
}
return out;
};
this.boundingBoxIntersection = function(box) {
var out = [];
for (var i = 0; i < segments.length; i++) {
out.push.apply(out, segments[i].boundingBoxIntersection(box));
}
return out;
};
var _updateSegmentProportions = function () {
var curLoc = 0;
for (var i = 0; i < segments.length; i++) {
var sl = segments[i].getLength();
segmentProportionalLengths[i] = sl / totalLength;
segmentProportions[i] = [curLoc, (curLoc += (sl / totalLength)) ];
}
},
/**
* returns [segment, proportion of travel in segment, segment index] for the segment
* that contains the point which is 'location' distance along the entire path, where
* 'location' is a decimal between 0 and 1 inclusive. in this connector type, paths
* are made up of a list of segments, each of which contributes some fraction to
* the total length.
* From 1.3.10 this also supports the 'absolute' property, which lets us specify a location
* as the absolute distance in pixels, rather than a proportion of the total path.
*/
_findSegmentForLocation = function (location, absolute) {
if (absolute) {
location = location > 0 ? location / totalLength : (totalLength + location) / totalLength;
}
var idx = segmentProportions.length - 1, inSegmentProportion = 1;
for (var i = 0; i < segmentProportions.length; i++) {
if (segmentProportions[i][1] >= location) {
idx = i;
// todo is this correct for all connector path types?
inSegmentProportion = location === 1 ? 1 : location === 0 ? 0 : (location - segmentProportions[i][0]) / segmentProportionalLengths[i];
break;
}
}
return { segment: segments[idx], proportion: inSegmentProportion, index: idx };
},
_addSegment = function (conn, type, params) {
if (params.x1 === params.x2 && params.y1 === params.y2) {
return;
}
var s = new _jp.Segments[type](params);
segments.push(s);
totalLength += s.getLength();
conn.updateBounds(s);
},
_clearSegments = function () {
totalLength = segments.length = segmentProportions.length = segmentProportionalLengths.length = 0;
};
this.setSegments = function (_segs) {
userProvidedSegments = [];
totalLength = 0;
for (var i = 0; i < _segs.length; i++) {
userProvidedSegments.push(_segs[i]);
totalLength += _segs[i].getLength();
}
};
this.getLength = function() {
return totalLength;
};
var _prepareCompute = function (params) {
this.strokeWidth = params.strokeWidth;
var segment = _jg.quadrant(params.sourcePos, params.targetPos),
swapX = params.targetPos[0] < params.sourcePos[0],
swapY = params.targetPos[1] < params.sourcePos[1],
lw = params.strokeWidth || 1,
so = params.sourceEndpoint.anchor.getOrientation(params.sourceEndpoint),
to = params.targetEndpoint.anchor.getOrientation(params.targetEndpoint),
x = swapX ? params.targetPos[0] : params.sourcePos[0],
y = swapY ? params.targetPos[1] : params.sourcePos[1],
w = Math.abs(params.targetPos[0] - params.sourcePos[0]),
h = Math.abs(params.targetPos[1] - params.sourcePos[1]);
// if either anchor does not have an orientation set, we derive one from their relative
// positions. we fix the axis to be the one in which the two elements are further apart, and
// point each anchor at the other element. this is also used when dragging a new connection.
if (so[0] === 0 && so[1] === 0 || to[0] === 0 && to[1] === 0) {
var index = w > h ? 0 : 1, oIndex = [1, 0][index];
so = [];
to = [];
so[index] = params.sourcePos[index] > params.targetPos[index] ? -1 : 1;
to[index] = params.sourcePos[index] > params.targetPos[index] ? 1 : -1;
so[oIndex] = 0;
to[oIndex] = 0;
}
var sx = swapX ? w + (sourceGap * so[0]) : sourceGap * so[0],
sy = swapY ? h + (sourceGap * so[1]) : sourceGap * so[1],
tx = swapX ? targetGap * to[0] : w + (targetGap * to[0]),
ty = swapY ? targetGap * to[1] : h + (targetGap * to[1]),
oProduct = ((so[0] * to[0]) + (so[1] * to[1]));
var result = {
sx: sx, sy: sy, tx: tx, ty: ty, lw: lw,
xSpan: Math.abs(tx - sx),
ySpan: Math.abs(ty - sy),
mx: (sx + tx) / 2,
my: (sy + ty) / 2,
so: so, to: to, x: x, y: y, w: w, h: h,
segment: segment,
startStubX: sx + (so[0] * sourceStub),
startStubY: sy + (so[1] * sourceStub),
endStubX: tx + (to[0] * targetStub),
endStubY: ty + (to[1] * targetStub),
isXGreaterThanStubTimes2: Math.abs(sx - tx) > (sourceStub + targetStub),
isYGreaterThanStubTimes2: Math.abs(sy - ty) > (sourceStub + targetStub),
opposite: oProduct === -1,
perpendicular: oProduct === 0,
orthogonal: oProduct === 1,
sourceAxis: so[0] === 0 ? "y" : "x",
points: [x, y, w, h, sx, sy, tx, ty ],
stubs:[sourceStub, targetStub]
};
result.anchorOrientation = result.opposite ? "opposite" : result.orthogonal ? "orthogonal" : "perpendicular";
return result;
};
this.getSegments = function () {
return segments;
};
this.updateBounds = function (segment) {
var segBounds = segment.getBounds();
this.bounds.minX = Math.min(this.bounds.minX, segBounds.minX);
this.bounds.maxX = Math.max(this.bounds.maxX, segBounds.maxX);
this.bounds.minY = Math.min(this.bounds.minY, segBounds.minY);
this.bounds.maxY = Math.max(this.bounds.maxY, segBounds.maxY);
};
var dumpSegmentsToConsole = function () {
console.log("SEGMENTS:");
for (var i = 0; i < segments.length; i++) {
console.log(segments[i].type, segments[i].getLength(), segmentProportions[i]);
}
};
this.pointOnPath = function (location, absolute) {
var seg = _findSegmentForLocation(location, absolute);
return seg.segment && seg.segment.pointOnPath(seg.proportion, false) || [0, 0];
};
this.gradientAtPoint = function (location, absolute) {
var seg = _findSegmentForLocation(location, absolute);
return seg.segment && seg.segment.gradientAtPoint(seg.proportion, false) || 0;
};
this.pointAlongPathFrom = function (location, distance, absolute) {
var seg = _findSegmentForLocation(location, absolute);
// TODO what happens if this crosses to the next segment?
return seg.segment && seg.segment.pointAlongPathFrom(seg.proportion, distance, false) || [0, 0];
};
this.compute = function (params) {
paintInfo = _prepareCompute.call(this, params);
_clearSegments();
this._compute(paintInfo, params);
this.x = paintInfo.points[0];
this.y = paintInfo.points[1];
this.w = paintInfo.points[2];
this.h = paintInfo.points[3];
this.segment = paintInfo.segment;
_updateSegmentProportions();
};
return {
addSegment: _addSegment,
prepareCompute: _prepareCompute,
sourceStub: sourceStub,
targetStub: targetStub,
maxStub: Math.max(sourceStub, targetStub),
sourceGap: sourceGap,
targetGap: targetGap,
maxGap: Math.max(sourceGap, targetGap)
};
};
_ju.extend(_jp.Connectors.AbstractConnector, AbstractComponent);
// ********************************* END OF CONNECTOR TYPES *******************************************************************
// ********************************* ENDPOINT TYPES *******************************************************************
_jp.Endpoints.AbstractEndpoint = function (params) {
AbstractComponent.apply(this, arguments);
var compute = this.compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
var out = this._compute.apply(this, arguments);
this.x = out[0];
this.y = out[1];
this.w = out[2];
this.h = out[3];
this.bounds.minX = this.x;
this.bounds.minY = this.y;
this.bounds.maxX = this.x + this.w;
this.bounds.maxY = this.y + this.h;
return out;
};
return {
compute: compute,
cssClass: params.cssClass
};
};
_ju.extend(_jp.Endpoints.AbstractEndpoint, AbstractComponent);
/**
* Class: Endpoints.Dot
* A round endpoint, with default radius 10 pixels.
*/
/**
* Function: Constructor
*
* Parameters:
*
* radius - radius of the endpoint. defaults to 10 pixels.
*/
_jp.Endpoints.Dot = function (params) {
this.type = "Dot";
var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
params = params || {};
this.radius = params.radius || 10;
this.defaultOffset = 0.5 * this.radius;
this.defaultInnerRadius = this.radius / 3;
this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
this.radius = endpointStyle.radius || this.radius;
var x = anchorPoint[0] - this.radius,
y = anchorPoint[1] - this.radius,
w = this.radius * 2,
h = this.radius * 2;
if (endpointStyle.stroke) {
var lw = endpointStyle.strokeWidth || 1;
x -= lw;
y -= lw;
w += (lw * 2);
h += (lw * 2);
}
return [ x, y, w, h, this.radius ];
};
};
_ju.extend(_jp.Endpoints.Dot, _jp.Endpoints.AbstractEndpoint);
_jp.Endpoints.Rectangle = function (params) {
this.type = "Rectangle";
var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
params = params || {};
this.width = params.width || 20;
this.height = params.height || 20;
this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
var width = endpointStyle.width || this.width,
height = endpointStyle.height || this.height,
x = anchorPoint[0] - (width / 2),
y = anchorPoint[1] - (height / 2);
return [ x, y, width, height];
};
};
_ju.extend(_jp.Endpoints.Rectangle, _jp.Endpoints.AbstractEndpoint);
var DOMElementEndpoint = function (params) {
_jp.jsPlumbUIComponent.apply(this, arguments);
this._jsPlumb.displayElements = [];
};
_ju.extend(DOMElementEndpoint, _jp.jsPlumbUIComponent, {
getDisplayElements: function () {
return this._jsPlumb.displayElements;
},
appendDisplayElement: function (el) {
this._jsPlumb.displayElements.push(el);
}
});
/**
* Class: Endpoints.Image
* Draws an image as the Endpoint.
*/
/**
* Function: Constructor
*
* Parameters:
*
* src - location of the image to use.
TODO: multiple references to self. not sure quite how to get rid of them entirely. perhaps self = null in the cleanup
function will suffice
TODO this class still might leak memory.
*/
_jp.Endpoints.Image = function (params) {
this.type = "Image";
DOMElementEndpoint.apply(this, arguments);
_jp.Endpoints.AbstractEndpoint.apply(this, arguments);
var _onload = params.onload,
src = params.src || params.url,
clazz = params.cssClass ? " " + params.cssClass : "";
this._jsPlumb.img = new Image();
this._jsPlumb.ready = false;
this._jsPlumb.initialized = false;
this._jsPlumb.deleted = false;
this._jsPlumb.widthToUse = params.width;
this._jsPlumb.heightToUse = params.height;
this._jsPlumb.endpoint = params.endpoint;
this._jsPlumb.img.onload = function () {
if (this._jsPlumb != null) {
this._jsPlumb.ready = true;
this._jsPlumb.widthToUse = this._jsPlumb.widthToUse || this._jsPlumb.img.width;
this._jsPlumb.heightToUse = this._jsPlumb.heightToUse || this._jsPlumb.img.height;
if (_onload) {
_onload(this);
}
}
}.bind(this);
/*
Function: setImage
Sets the Image to use in this Endpoint.
Parameters:
img - may be a URL or an Image object
onload - optional; a callback to execute once the image has loaded.
*/
this._jsPlumb.endpoint.setImage = function (_img, onload) {
var s = _img.constructor === String ? _img : _img.src;
_onload = onload;
this._jsPlumb.img.src = s;
if (this.canvas != null) {
this.canvas.setAttribute("src", this._jsPlumb.img.src);
}
}.bind(this);
this._jsPlumb.endpoint.setImage(src, _onload);
this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
this.anchorPoint = anchorPoint;
if (this._jsPlumb.ready) {
return [anchorPoint[0] - this._jsPlumb.widthToUse / 2, anchorPoint[1] - this._jsPlumb.heightToUse / 2,
this._jsPlumb.widthToUse, this._jsPlumb.heightToUse];
}
else {
return [0, 0, 0, 0];
}
};
this.canvas = _jp.createElement("img", {
position:"absolute",
margin:0,
padding:0,
outline:0
}, this._jsPlumb.instance.endpointClass + clazz);
if (this._jsPlumb.widthToUse) {
this.canvas.setAttribute("width", this._jsPlumb.widthToUse);
}
if (this._jsPlumb.heightToUse) {
this.canvas.setAttribute("height", this._jsPlumb.heightToUse);
}
this._jsPlumb.instance.appendElement(this.canvas);
this.actuallyPaint = function (d, style, anchor) {
if (!this._jsPlumb.deleted) {
if (!this._jsPlumb.initialized) {
this.canvas.setAttribute("src", this._jsPlumb.img.src);
this.appendDisplayElement(this.canvas);
this._jsPlumb.initialized = true;
}
var x = this.anchorPoint[0] - (this._jsPlumb.widthToUse / 2),
y = this.anchorPoint[1] - (this._jsPlumb.heightToUse / 2);
_ju.sizeElement(this.canvas, x, y, this._jsPlumb.widthToUse, this._jsPlumb.heightToUse);
}
};
this.paint = function (style, anchor) {
if (this._jsPlumb != null) { // may have been deleted
if (this._jsPlumb.ready) {
this.actuallyPaint(style, anchor);
}
else {
root.setTimeout(function () {
this.paint(style, anchor);
}.bind(this), 200);
}
}
};
};
_ju.extend(_jp.Endpoints.Image, [ DOMElementEndpoint, _jp.Endpoints.AbstractEndpoint ], {
cleanup: function (force) {
if (force) {
this._jsPlumb.deleted = true;
if (this.canvas) {
this.canvas.parentNode.removeChild(this.canvas);
}
this.canvas = null;
}
}
});
/*
* Class: Endpoints.Blank
* An Endpoint that paints nothing (visible) on the screen. Supports cssClass and hoverClass parameters like all Endpoints.
*/
_jp.Endpoints.Blank = function (params) {
var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
this.type = "Blank";
DOMElementEndpoint.apply(this, arguments);
this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
return [anchorPoint[0], anchorPoint[1], 10, 0];
};
var clazz = params.cssClass ? " " + params.cssClass : "";
this.canvas = _jp.createElement("div", {
display: "block",
width: "1px",
height: "1px",
background: "transparent",
position: "absolute"
}, this._jsPlumb.instance.endpointClass + clazz);
this._jsPlumb.instance.appendElement(this.canvas);
this.paint = function (style, anchor) {
_ju.sizeElement(this.canvas, this.x, this.y, this.w, this.h);
};
};
_ju.extend(_jp.Endpoints.Blank, [_jp.Endpoints.AbstractEndpoint, DOMElementEndpoint], {
cleanup: function () {
if (this.canvas && this.canvas.parentNode) {
this.canvas.parentNode.removeChild(this.canvas);
}
}
});
/*
* Class: Endpoints.Triangle
* A triangular Endpoint.
*/
/*
* Function: Constructor
*
* Parameters:
*
* width width of the triangle's base. defaults to 55 pixels.
* height height of the triangle from base to apex. defaults to 55 pixels.
*/
_jp.Endpoints.Triangle = function (params) {
this.type = "Triangle";
_jp.Endpoints.AbstractEndpoint.apply(this, arguments);
var self = this;
params = params || { };
params.width = params.width || 55;
params.height = params.height || 55;
this.width = params.width;
this.height = params.height;
this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
var width = endpointStyle.width || self.width,
height = endpointStyle.height || self.height,
x = anchorPoint[0] - (width / 2),
y = anchorPoint[1] - (height / 2);
return [ x, y, width, height ];
};
};
// ********************************* END OF ENDPOINT TYPES *******************************************************************
// ********************************* OVERLAY DEFINITIONS ***********************************************************************
var AbstractOverlay = _jp.Overlays.AbstractOverlay = function (params) {
this.visible = true;
this.isAppendedAtTopLevel = true;
this.component = params.component;
this.loc = params.location == null ? 0.5 : params.location;
this.endpointLoc = params.endpointLocation == null ? [ 0.5, 0.5] : params.endpointLocation;
this.visible = params.visible !== false;
};
AbstractOverlay.prototype = {
cleanup: function (force) {
if (force) {
this.component = null;
this.canvas = null;
this.endpointLoc = null;
}
},
reattach:function(instance, component) { },
setVisible: function (val) {
this.visible = val;
this.component.repaint();
},
isVisible: function () {
return this.visible;
},
hide: function () {
this.setVisible(false);
},
show: function () {
this.setVisible(true);
},
incrementLocation: function (amount) {
this.loc += amount;
this.component.repaint();
},
setLocation: function (l) {
this.loc = l;
this.component.repaint();
},
getLocation: function () {
return this.loc;
},
updateFrom:function() { }
};
/*
* Class: Overlays.Arrow
*
* An arrow overlay, defined by four points: the head, the two sides of the tail, and a 'foldback' point at some distance along the length
* of the arrow that lines from each tail point converge into. The foldback point is defined using a decimal that indicates some fraction
* of the length of the arrow and has a default value of 0.623. A foldback point value of 1 would mean that the arrow had a straight line
* across the tail.
*/
/*
* @constructor
*
* @param {Object} params Constructor params.
* @param {Number} [params.length] Distance in pixels from head to tail baseline. default 20.
* @param {Number} [params.width] Width in pixels of the tail baseline. default 20.
* @param {String} [params.fill] Style to use when filling the arrow. defaults to "black".
* @param {String} [params.stroke] Style to use when stroking the arrow. defaults to null, which means the arrow is not stroked.
* @param {Number} [params.stroke-width] Line width to use when stroking the arrow. defaults to 1, but only used if stroke is not null.
* @param {Number} [params.foldback] Distance (as a decimal from 0 to 1 inclusive) along the length of the arrow marking the point the tail points should fold back to. defaults to 0.623.
* @param {Number} [params.location] Distance (as a decimal from 0 to 1 inclusive) marking where the arrow should sit on the connector. defaults to 0.5.
* @param {NUmber} [params.direction] Indicates the direction the arrow points in. valid values are -1 and 1; 1 is default.
*/
_jp.Overlays.Arrow = function (params) {
this.type = "Arrow";
AbstractOverlay.apply(this, arguments);
this.isAppendedAtTopLevel = false;
params = params || {};
var self = this;
this.length = params.length || 20;
this.width = params.width || 20;
this.id = params.id;
var direction = (params.direction || 1) < 0 ? -1 : 1,
paintStyle = params.paintStyle || { "stroke-width": 1 },
// how far along the arrow the lines folding back in come to. default is 62.3%.
foldback = params.foldback || 0.623;
this.computeMaxSize = function () {
return self.width * 1.5;
};
this.elementCreated = function(p, component) {
this.path = p;
if (params.events) {
for (var i in params.events) {
_jp.on(p, i, params.events[i]);
}
}
};
this.draw = function (component, currentConnectionPaintStyle) {
var hxy, mid, txy, tail, cxy;
if (component.pointAlongPathFrom) {
if (_ju.isString(this.loc) || this.loc > 1 || this.loc < 0) {
var l = parseInt(this.loc, 10),
fromLoc = this.loc < 0 ? 1 : 0;
hxy = component.pointAlongPathFrom(fromLoc, l, false);
mid = component.pointAlongPathFrom(fromLoc, l - (direction * this.length / 2), false);
txy = _jg.pointOnLine(hxy, mid, this.length);
}
else if (this.loc === 1) {
hxy = component.pointOnPath(this.loc);
mid = component.pointAlongPathFrom(this.loc, -(this.length));
txy = _jg.pointOnLine(hxy, mid, this.length);
if (direction === -1) {
var _ = txy;
txy = hxy;
hxy = _;
}
}
else if (this.loc === 0) {
txy = component.pointOnPath(this.loc);
mid = component.pointAlongPathFrom(this.loc, this.length);
hxy = _jg.pointOnLine(txy, mid, this.length);
if (direction === -1) {
var __ = txy;
txy = hxy;
hxy = __;
}
}
else {
hxy = component.pointAlongPathFrom(this.loc, direction * this.length / 2);
mid = component.pointOnPath(this.loc);
txy = _jg.pointOnLine(hxy, mid, this.length);
}
tail = _jg.perpendicularLineTo(hxy, txy, this.width);
cxy = _jg.pointOnLine(hxy, txy, foldback * this.length);
var d = { hxy: hxy, tail: tail, cxy: cxy },
stroke = paintStyle.stroke || currentConnectionPaintStyle.stroke,
fill = paintStyle.fill || currentConnectionPaintStyle.stroke,
lineWidth = paintStyle.strokeWidth || currentConnectionPaintStyle.strokeWidth;
return {
component: component,
d: d,
"stroke-width": lineWidth,
stroke: stroke,
fill: fill,
minX: Math.min(hxy.x, tail[0].x, tail[1].x),
maxX: Math.max(hxy.x, tail[0].x, tail[1].x),
minY: Math.min(hxy.y, tail[0].y, tail[1].y),
maxY: Math.max(hxy.y, tail[0].y, tail[1].y)
};
}
else {
return {component: component, minX: 0, maxX: 0, minY: 0, maxY: 0};
}
};
};
_ju.extend(_jp.Overlays.Arrow, AbstractOverlay, {
updateFrom:function(d) {
this.length = d.length || this.length;
this.width = d.width|| this.width;
this.direction = d.direction != null ? d.direction : this.direction;
this.foldback = d.foldback|| this.foldback;
},
cleanup:function() {
if (this.path && this.canvas) {
this.canvas.removeChild(this.path);
}
}
});
/*
* Class: Overlays.PlainArrow
*
* A basic arrow. This is in fact just one instance of the more generic case in which the tail folds back on itself to some
* point along the length of the arrow: in this case, that foldback point is the full length of the arrow. so it just does
* a 'call' to Arrow with foldback set appropriately.
*/
/*
* Function: Constructor
* See <Overlays.Arrow> for allowed parameters for this overlay.
*/
_jp.Overlays.PlainArrow = function (params) {
params = params || {};
var p = _jp.extend(params, {foldback: 1});
_jp.Overlays.Arrow.call(this, p);
this.type = "PlainArrow";
};
_ju.extend(_jp.Overlays.PlainArrow, _jp.Overlays.Arrow);
/*
* Class: Overlays.Diamond
*
* A diamond. Like PlainArrow, this is a concrete case of the more generic case of the tail points converging on some point...it just
* happens that in this case, that point is greater than the length of the the arrow.
*
* this could probably do with some help with positioning...due to the way it reuses the Arrow paint code, what Arrow thinks is the
* center is actually 1/4 of the way along for this guy. but we don't have any knowledge of pixels at this point, so we're kind of
* stuck when it comes to helping out the Arrow class. possibly we could pass in a 'transpose' parameter or something. the value
* would be -l/4 in this case - move along one quarter of the total length.
*/
/*
* Function: Constructor
* See <Overlays.Arrow> for allowed parameters for this overlay.
*/
_jp.Overlays.Diamond = function (params) {
params = params || {};
var l = params.length || 40,
p = _jp.extend(params, {length: l / 2, foldback: 2});
_jp.Overlays.Arrow.call(this, p);
this.type = "Diamond";
};
_ju.extend(_jp.Overlays.Diamond, _jp.Overlays.Arrow);
var _getDimensions = function (component, forceRefresh) {
if (component._jsPlumb.cachedDimensions == null || forceRefresh) {
component._jsPlumb.cachedDimensions = component.getDimensions();
}
return component._jsPlumb.cachedDimensions;
};
// abstract superclass for overlays that add an element to the DOM.
var AbstractDOMOverlay = function (params) {
_jp.jsPlumbUIComponent.apply(this, arguments);
AbstractOverlay.apply(this, arguments);
// hand off fired events to associated component.
var _f = this.fire;
this.fire = function () {
_f.apply(this, arguments);
if (this.component) {
this.component.fire.apply(this.component, arguments);
}
};
this.detached=false;
this.id = params.id;
this._jsPlumb.div = null;
this._jsPlumb.initialised = false;
this._jsPlumb.component = params.component;
this._jsPlumb.cachedDimensions = null;
this._jsPlumb.create = params.create;
this._jsPlumb.initiallyInvisible = params.visible === false;
this.getElement = function () {
if (this._jsPlumb.div == null) {
var div = this._jsPlumb.div = _jp.getElement(this._jsPlumb.create(this._jsPlumb.component));
div.style.position = "absolute";
jsPlumb.addClass(div, this._jsPlumb.instance.overlayClass + " " +
(this.cssClass ? this.cssClass :
params.cssClass ? params.cssClass : ""));
this._jsPlumb.instance.appendElement(div);
this._jsPlumb.instance.getId(div);
this.canvas = div;
// in IE the top left corner is what it placed at the desired location. This will not
// be fixed. IE8 is not going to be supported for much longer.
var ts = "translate(-50%, -50%)";
div.style.webkitTransform = ts;
div.style.mozTransform = ts;
div.style.msTransform = ts;
div.style.oTransform = ts;
div.style.transform = ts;
// write the related component into the created element
div._jsPlumb = this;
if (params.visible === false) {
div.style.display = "none";
}
}
return this._jsPlumb.div;
};
this.draw = function (component, currentConnectionPaintStyle, absolutePosition) {
var td = _getDimensions(this);
if (td != null && td.length === 2) {
var cxy = { x: 0, y: 0 };
// absolutePosition would have been set by a call to connection.setAbsoluteOverlayPosition.
if (absolutePosition) {
cxy = { x: absolutePosition[0], y: absolutePosition[1] };
}
else if (component.pointOnPath) {
var loc = this.loc, absolute = false;
if (_ju.isString(this.loc) || this.loc < 0 || this.loc > 1) {
loc = parseInt(this.loc, 10);
absolute = true;
}
cxy = component.pointOnPath(loc, absolute); // a connection
}
else {
var locToUse = this.loc.constructor === Array ? this.loc : this.endpointLoc;
cxy = { x: locToUse[0] * component.w,
y: locToUse[1] * component.h };
}
var minx = cxy.x - (td[0] / 2),
miny = cxy.y - (td[1] / 2);
return {
component: component,
d: { minx: minx, miny: miny, td: td, cxy: cxy },
minX: minx,
maxX: minx + td[0],
minY: miny,
maxY: miny + td[1]
};
}
else {
return {minX: 0, maxX: 0, minY: 0, maxY: 0};
}
};
};
_ju.extend(AbstractDOMOverlay, [_jp.jsPlumbUIComponent, AbstractOverlay], {
getDimensions: function () {
return [1,1];
},
setVisible: function (state) {
if (this._jsPlumb.div) {
this._jsPlumb.div.style.display = state ? "block" : "none";
// if initially invisible, dimensions are 0,0 and never get updated
if (state && this._jsPlumb.initiallyInvisible) {
_getDimensions(this, true);
this.component.repaint();
this._jsPlumb.initiallyInvisible = false;
}
}
},
/*
* Function: clearCachedDimensions
* Clears the cached dimensions for the label. As a performance enhancement, label dimensions are
* cached from 1.3.12 onwards. The cache is cleared when you change the label text, of course, but
* there are other reasons why the text dimensions might change - if you make a change through CSS, for
* example, you might change the font size. in that case you should explicitly call this method.
*/
clearCachedDimensions: function () {
this._jsPlumb.cachedDimensions = null;
},
cleanup: function (force) {
if (force) {
if (this._jsPlumb.div != null) {
this._jsPlumb.div._jsPlumb = null;
this._jsPlumb.instance.removeElement(this._jsPlumb.div);
}
}
else {
// if not a forced cleanup, just detach child from parent for now.
if (this._jsPlumb && this._jsPlumb.div && this._jsPlumb.div.parentNode) {
this._jsPlumb.div.parentNode.removeChild(this._jsPlumb.div);
}
this.detached = true;
}
},
reattach:function(instance, component) {
if (this._jsPlumb.div != null) {
instance.getContainer().appendChild(this._jsPlumb.div);
}
this.detached = false;
},
computeMaxSize: function () {
var td = _getDimensions(this);
return Math.max(td[0], td[1]);
},
paint: function (p, containerExtents) {
if (!this._jsPlumb.initialised) {
this.getElement();
p.component.appendDisplayElement(this._jsPlumb.div);
this._jsPlumb.initialised = true;
if (this.detached) {
this._jsPlumb.div.parentNode.removeChild(this._jsPlumb.div);
}
}
this._jsPlumb.div.style.left = (p.component.x + p.d.minx) + "px";
this._jsPlumb.div.style.top = (p.component.y + p.d.miny) + "px";
}
});
/*
* Class: Overlays.Custom
* A Custom overlay. You supply a 'create' function which returns some DOM element, and jsPlumb positions it.
* The 'create' function is passed a Connection or Endpoint.
*/
/*
* Function: Constructor
*
* Parameters:
* create - function for jsPlumb to call that returns a DOM element.
* location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
* id - optional id to use for later retrieval of this overlay.
*
*/
_jp.Overlays.Custom = function (params) {
this.type = "Custom";
AbstractDOMOverlay.apply(this, arguments);
};
_ju.extend(_jp.Overlays.Custom, AbstractDOMOverlay);
_jp.Overlays.GuideLines = function () {
var self = this;
self.length = 50;
self.strokeWidth = 5;
this.type = "GuideLines";
AbstractOverlay.apply(this, arguments);
_jp.jsPlumbUIComponent.apply(this, arguments);
this.draw = function (connector, currentConnectionPaintStyle) {
var head = connector.pointAlongPathFrom(self.loc, self.length / 2),
mid = connector.pointOnPath(self.loc),
tail = _jg.pointOnLine(head, mid, self.length),
tailLine = _jg.perpendicularLineTo(head, tail, 40),
headLine = _jg.perpendicularLineTo(tail, head, 20);
return {
connector: connector,
head: head,
tail: tail,
headLine: headLine,
tailLine: tailLine,
minX: Math.min(head.x, tail.x, headLine[0].x, headLine[1].x),
minY: Math.min(head.y, tail.y, headLine[0].y, headLine[1].y),
maxX: Math.max(head.x, tail.x, headLine[0].x, headLine[1].x),
maxY: Math.max(head.y, tail.y, headLine[0].y, headLine[1].y)
};
};
// this.cleanup = function() { }; // nothing to clean up for GuideLines
};
/*
* Class: Overlays.Label
*/
/*
* Function: Constructor
*
* Parameters:
* cssClass - optional css class string to append to css class. This string is appended "as-is", so you can of course have multiple classes
* defined. This parameter is preferred to using labelStyle, borderWidth and borderStyle.
* label - the label to paint. May be a string or a function that returns a string. Nothing will be painted if your label is null or your
* label function returns null. empty strings _will_ be painted.
* location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
* id - optional id to use for later retrieval of this overlay.
*
*
*/
_jp.Overlays.Label = function (params) {
this.labelStyle = params.labelStyle;
var labelWidth = null, labelHeight = null, labelText = null, labelPadding = null;
this.cssClass = this.labelStyle != null ? this.labelStyle.cssClass : null;
var p = _jp.extend({
create: function () {
return _jp.createElement("div");
}}, params);
_jp.Overlays.Custom.call(this, p);
this.type = "Label";
this.label = params.label || "";
this.labelText = null;
if (this.labelStyle) {
var el = this.getElement();
this.labelStyle.font = this.labelStyle.font || "12px sans-serif";
el.style.font = this.labelStyle.font;
el.style.color = this.labelStyle.color || "black";
if (this.labelStyle.fill) {
el.style.background = this.labelStyle.fill;
}
if (this.labelStyle.borderWidth > 0) {
var dStyle = this.labelStyle.borderStyle ? this.labelStyle.borderStyle : "black";
el.style.border = this.labelStyle.borderWidth + "px solid " + dStyle;
}
if (this.labelStyle.padding) {
el.style.padding = this.labelStyle.padding;
}
}
};
_ju.extend(_jp.Overlays.Label, _jp.Overlays.Custom, {
cleanup: function (force) {
if (force) {
this.div = null;
this.label = null;
this.labelText = null;
this.cssClass = null;
this.labelStyle = null;
}
},
getLabel: function () {
return this.label;
},
/*
* Function: setLabel
* sets the label's, um, label. you would think i'd call this function
* 'setText', but you can pass either a Function or a String to this, so
* it makes more sense as 'setLabel'. This uses innerHTML on the label div, so keep
* that in mind if you need escaped HTML.
*/
setLabel: function (l) {
this.label = l;
this.labelText = null;
this.clearCachedDimensions();
this.update();
this.component.repaint();
},
getDimensions: function () {
this.update();
return AbstractDOMOverlay.prototype.getDimensions.apply(this, arguments);
},
update: function () {
if (typeof this.label === "function") {
var lt = this.label(this);
this.getElement().innerHTML = lt.replace(/\r\n/g, "<br/>");
}
else {
if (this.labelText == null) {
this.labelText = this.label;
this.getElement().innerHTML = this.labelText.replace(/\r\n/g, "<br/>");
}
}
},
updateFrom:function(d) {
if(d.label != null){
this.setLabel(d.label);
}
}
});
// ********************************* END OF OVERLAY DEFINITIONS ***********************************************************************
}).call(typeof window !== 'undefined' ? window : this);
/*
* This file contains the base class for library adapters.
*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
"use strict";
var root = this,
_jp = root.jsPlumb;
var _getEventManager = function(instance) {
var e = instance._mottle;
if (!e) {
e = instance._mottle = new root.Mottle();
}
return e;
};
_jp.extend(root.jsPlumbInstance.prototype, {
getEventManager:function() {
return _getEventManager(this);
},
on : function(el, event, callback) {
// TODO: here we would like to map the tap event if we know its
// an internal bind to a click. we have to know its internal because only
// then can we be sure that the UP event wont be consumed (tap is a synthesized
// event from a mousedown followed by a mouseup).
//event = { "click":"tap", "dblclick":"dbltap"}[event] || event;
this.getEventManager().on.apply(this, arguments);
return this;
},
off : function(el, event, callback) {
this.getEventManager().off.apply(this, arguments);
return this;
}
});
}).call(typeof window !== 'undefined' ? window : this);
/*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
"use strict";
var root = this,
_ju = root.jsPlumbUtil,
_jpi = root.jsPlumbInstance;
var GROUP_COLLAPSED_CLASS = "jtk-group-collapsed";
var GROUP_EXPANDED_CLASS = "jtk-group-expanded";
var GROUP_CONTAINER_SELECTOR = "[jtk-group-content]";
var ELEMENT_DRAGGABLE_EVENT = "elementDraggable";
var STOP = "stop";
var REVERT = "revert";
var GROUP_MANAGER = "_groupManager";
var GROUP = "_jsPlumbGroup";
var GROUP_DRAG_SCOPE = "_jsPlumbGroupDrag";
var EVT_CHILD_ADDED = "group:addMember";
var EVT_CHILD_REMOVED = "group:removeMember";
var EVT_GROUP_ADDED = "group:add";
var EVT_GROUP_REMOVED = "group:remove";
var EVT_EXPAND = "group:expand";
var EVT_COLLAPSE = "group:collapse";
var EVT_GROUP_DRAG_STOP = "groupDragStop";
var EVT_CONNECTION_MOVED = "connectionMoved";
var EVT_INTERNAL_CONNECTION_DETACHED = "internal.connectionDetached";
var CMD_REMOVE_ALL = "removeAll";
var CMD_ORPHAN_ALL = "orphanAll";
var CMD_SHOW = "show";
var CMD_HIDE = "hide";
var GroupManager = function(_jsPlumb) {
var _managedGroups = {}, _connectionSourceMap = {}, _connectionTargetMap = {}, self = this;
_jsPlumb.bind("connection", function(p) {
if (p.source[GROUP] != null && p.target[GROUP] != null && p.source[GROUP] === p.target[GROUP]) {
_connectionSourceMap[p.connection.id] = p.source[GROUP];
_connectionTargetMap[p.connection.id] = p.source[GROUP];
}
else {
if (p.source[GROUP] != null) {
_ju.suggest(p.source[GROUP].connections.source, p.connection);
_connectionSourceMap[p.connection.id] = p.source[GROUP];
}
if (p.target[GROUP] != null) {
_ju.suggest(p.target[GROUP].connections.target, p.connection);
_connectionTargetMap[p.connection.id] = p.target[GROUP];
}
}
});
function _cleanupDetachedConnection(conn) {
delete conn.proxies;
var group = _connectionSourceMap[conn.id], f;
if (group != null) {
f = function(c) { return c.id === conn.id; };
_ju.removeWithFunction(group.connections.source, f);
_ju.removeWithFunction(group.connections.target, f);
delete _connectionSourceMap[conn.id];
}
group = _connectionTargetMap[conn.id];
if (group != null) {
f = function(c) { return c.id === conn.id; };
_ju.removeWithFunction(group.connections.source, f);
_ju.removeWithFunction(group.connections.target, f);
delete _connectionTargetMap[conn.id];
}
}
_jsPlumb.bind(EVT_INTERNAL_CONNECTION_DETACHED, function(p) {
_cleanupDetachedConnection(p.connection);
});
_jsPlumb.bind(EVT_CONNECTION_MOVED, function(p) {
var connMap = p.index === 0 ? _connectionSourceMap : _connectionTargetMap;
var group = connMap[p.connection.id];
if (group) {
var list = group.connections[p.index === 0 ? "source" : "target"];
var idx = list.indexOf(p.connection);
if (idx !== -1) {
list.splice(idx, 1);
}
}
});
this.addGroup = function(group) {
_jsPlumb.addClass(group.getEl(), GROUP_EXPANDED_CLASS);
_managedGroups[group.id] = group;
group.manager = this;
_updateConnectionsForGroup(group);
_jsPlumb.fire(EVT_GROUP_ADDED, { group:group });
};
this.addToGroup = function(group, el, doNotFireEvent) {
group = this.getGroup(group);
if (group) {
var groupEl = group.getEl();
if (el._isJsPlumbGroup) {
return;
}
var currentGroup = el._jsPlumbGroup;
// if already a member of this group, do nothing
if (currentGroup !== group) {
var elpos = _jsPlumb.getOffset(el, true);
var cpos = group.collapsed ? _jsPlumb.getOffset(groupEl, true) : _jsPlumb.getOffset(group.getDragArea(), true);
// otherwise, transfer to this group.
if (currentGroup != null) {
currentGroup.remove(el, false, doNotFireEvent, false, group);
self.updateConnectionsForGroup(currentGroup);
}
group.add(el, doNotFireEvent/*, currentGroup*/);
var handleDroppedConnections = function (list, index) {
var oidx = index === 0 ? 1 : 0;
list.each(function (c) {
c.setVisible(false);
if (c.endpoints[oidx].element._jsPlumbGroup === group) {
c.endpoints[oidx].setVisible(false);
self.expandConnection(c, oidx, group);
}
else {
c.endpoints[index].setVisible(false);
self.collapseConnection(c, index, group);
}
});
};
if (group.collapsed) {
handleDroppedConnections(_jsPlumb.select({source: el}), 0);
handleDroppedConnections(_jsPlumb.select({target: el}), 1);
}
var elId = _jsPlumb.getId(el);
_jsPlumb.dragManager.setParent(el, elId, groupEl, _jsPlumb.getId(groupEl), elpos);
var newPosition = { left: elpos.left - cpos.left, top: elpos.top - cpos.top };
_jsPlumb.setPosition(el, newPosition);
_jsPlumb.dragManager.revalidateParent(el, elId, elpos);
self.updateConnectionsForGroup(group);
_jsPlumb.revalidate(elId);
if (!doNotFireEvent) {
var p = {group: group, el: el};
if (currentGroup) {
p.sourceGroup = currentGroup;
}
_jsPlumb.fire(EVT_CHILD_ADDED, p);
}
}
}
};
this.removeFromGroup = function(group, el, doNotFireEvent) {
group = this.getGroup(group);
if (group) {
group.remove(el, null, doNotFireEvent);
}
};
this.getGroup = function(groupId) {
var group = groupId;
if (_ju.isString(groupId)) {
group = _managedGroups[groupId];
if (group == null) {
throw new TypeError("No such group [" + groupId + "]");
}
}
return group;
};
this.getGroups = function() {
var o = [];
for (var g in _managedGroups) {
o.push(_managedGroups[g]);
}
return o;
};
this.removeGroup = function(group, deleteMembers, manipulateDOM, doNotFireEvent) {
group = this.getGroup(group);
this.expandGroup(group, true); // this reinstates any original connections and removes all proxies, but does not fire an event.
var newPositions = group[deleteMembers ? CMD_REMOVE_ALL : CMD_ORPHAN_ALL](manipulateDOM, doNotFireEvent);
_jsPlumb.remove(group.getEl());
delete _managedGroups[group.id];
delete _jsPlumb._groups[group.id];
_jsPlumb.fire(EVT_GROUP_REMOVED, { group:group });
return newPositions; // this will be null in the case or remove, but be a map of {id->[x,y]} in the case of orphan
};
this.removeAllGroups = function(deleteMembers, manipulateDOM, doNotFireEvent) {
for (var g in _managedGroups) {
this.removeGroup(_managedGroups[g], deleteMembers, manipulateDOM, doNotFireEvent);
}
};
function _setVisible(group, state) {
var m = group.getMembers();
for (var i = 0; i < m.length; i++) {
_jsPlumb[state ? CMD_SHOW : CMD_HIDE](m[i], true);
}
}
var _collapseConnection = this.collapseConnection = function(c, index, group) {
var proxyEp, groupEl = group.getEl(), groupElId = _jsPlumb.getId(groupEl),
originalElementId = c.endpoints[index].elementId;
var otherEl = c.endpoints[index === 0 ? 1 : 0].element;
if (otherEl[GROUP] && (!otherEl[GROUP].shouldProxy() && otherEl[GROUP].collapsed)) {
return;
}
c.proxies = c.proxies || [];
if(c.proxies[index]) {
proxyEp = c.proxies[index].ep;
}else {
proxyEp = _jsPlumb.addEndpoint(groupEl, {
endpoint:group.getEndpoint(c, index),
anchor:group.getAnchor(c, index),
parameters:{
isProxyEndpoint:true
}
});
}
proxyEp.setDeleteOnEmpty(true);
// for this index, stash proxy info: the new EP, the original EP.
c.proxies[index] = { ep:proxyEp, originalEp: c.endpoints[index] };
// and advise the anchor manager
if (index === 0) {
// TODO why are there two differently named methods? Why is there not one method that says "some end of this
// connection changed (you give the index), and here's the new element and element id."
_jsPlumb.anchorManager.sourceChanged(originalElementId, groupElId, c, groupEl);
}
else {
_jsPlumb.anchorManager.updateOtherEndpoint(c.endpoints[0].elementId, originalElementId, groupElId, c);
c.target = groupEl;
c.targetId = groupElId;
}
// detach the original EP from the connection.
c.proxies[index].originalEp.detachFromConnection(c, null, true);
// set the proxy as the new ep
proxyEp.connections = [ c ];
c.endpoints[index] = proxyEp;
c.setVisible(true);
};
this.collapseGroup = function(group) {
group = this.getGroup(group);
if (group == null || group.collapsed) {
return;
}
var groupEl = group.getEl();
// todo remove old proxy endpoints first, just in case?
//group.proxies.length = 0;
// hide all connections
_setVisible(group, false);
if (group.shouldProxy()) {
// collapses all connections in a group.
var _collapseSet = function (conns, index) {
for (var i = 0; i < conns.length; i++) {
var c = conns[i];
_collapseConnection(c, index, group);
}
};
// setup proxies for sources and targets
_collapseSet(group.connections.source, 0);
_collapseSet(group.connections.target, 1);
}
group.collapsed = true;
_jsPlumb.removeClass(groupEl, GROUP_EXPANDED_CLASS);
_jsPlumb.addClass(groupEl, GROUP_COLLAPSED_CLASS);
_jsPlumb.revalidate(groupEl);
_jsPlumb.fire(EVT_COLLAPSE, { group:group });
};
var _expandConnection = this.expandConnection = function(c, index, group) {
// if no proxies or none for this end of the connection, abort.
if (c.proxies == null || c.proxies[index] == null) {
return;
}
var groupElId = _jsPlumb.getId(group.getEl()),
originalElement = c.proxies[index].originalEp.element,
originalElementId = c.proxies[index].originalEp.elementId;
c.endpoints[index] = c.proxies[index].originalEp;
// and advise the anchor manager
if (index === 0) {
// TODO why are there two differently named methods? Why is there not one method that says "some end of this
// connection changed (you give the index), and here's the new element and element id."
_jsPlumb.anchorManager.sourceChanged(groupElId, originalElementId, c, originalElement);
}
else {
_jsPlumb.anchorManager.updateOtherEndpoint(c.endpoints[0].elementId, groupElId, originalElementId, c);
c.target = originalElement;
c.targetId = originalElementId;
}
// detach the proxy EP from the connection (which will cause it to be removed as we no longer need it)
c.proxies[index].ep.detachFromConnection(c, null);
c.proxies[index].originalEp.addConnection(c);
// cleanup
delete c.proxies[index];
};
this.expandGroup = function(group, doNotFireEvent) {
group = this.getGroup(group);
if (group == null || !group.collapsed) {
return;
}
var groupEl = group.getEl();
_setVisible(group, true);
if (group.shouldProxy()) {
// collapses all connections in a group.
var _expandSet = function (conns, index) {
for (var i = 0; i < conns.length; i++) {
var c = conns[i];
_expandConnection(c, index, group);
}
};
// setup proxies for sources and targets
_expandSet(group.connections.source, 0);
_expandSet(group.connections.target, 1);
}
group.collapsed = false;
_jsPlumb.addClass(groupEl, GROUP_EXPANDED_CLASS);
_jsPlumb.removeClass(groupEl, GROUP_COLLAPSED_CLASS);
_jsPlumb.revalidate(groupEl);
this.repaintGroup(group);
if (!doNotFireEvent) {
_jsPlumb.fire(EVT_EXPAND, { group: group});
}
};
this.repaintGroup = function(group) {
group = this.getGroup(group);
var m = group.getMembers();
for (var i = 0; i < m.length; i++) {
_jsPlumb.revalidate(m[i]);
}
};
// TODO refactor this with the code that responds to `connection` events.
function _updateConnectionsForGroup(group) {
var members = group.getMembers();
var c1 = _jsPlumb.getConnections({source:members, scope:"*"}, true);
var c2 = _jsPlumb.getConnections({target:members, scope:"*"}, true);
var processed = {};
group.connections.source.length = 0;
group.connections.target.length = 0;
var oneSet = function(c) {
for (var i = 0; i < c.length; i++) {
if (processed[c[i].id]) {
continue;
}
processed[c[i].id] = true;
if (c[i].source._jsPlumbGroup === group) {
if (c[i].target._jsPlumbGroup !== group) {
group.connections.source.push(c[i]);
}
_connectionSourceMap[c[i].id] = group;
}
else if (c[i].target._jsPlumbGroup === group) {
group.connections.target.push(c[i]);
_connectionTargetMap[c[i].id] = group;
}
}
};
oneSet(c1); oneSet(c2);
}
this.updateConnectionsForGroup = _updateConnectionsForGroup;
this.refreshAllGroups = function() {
for (var g in _managedGroups) {
_updateConnectionsForGroup(_managedGroups[g]);
_jsPlumb.dragManager.updateOffsets(_jsPlumb.getId(_managedGroups[g].getEl()));
}
};
};
/**
*
* @param {jsPlumbInstance} _jsPlumb Associated jsPlumb instance.
* @param {Object} params
* @param {Element} params.el The DOM element representing the Group.
* @param {String} [params.id] Optional ID for the Group. A UUID will be assigned as the Group's ID if you do not provide one.
* @param {Boolean} [params.constrain=false] If true, child elements will not be able to be dragged outside of the Group container.
* @param {Boolean} [params.revert=true] By default, child elements revert to the container if dragged outside. You can change this by setting `revert:false`. This behaviour is also overridden if you set `orphan` or `prune`.
* @param {Boolean} [params.orphan=false] If true, child elements dropped outside of the Group container will be removed from the Group (but not from the DOM).
* @param {Boolean} [params.prune=false] If true, child elements dropped outside of the Group container will be removed from the Group and also from the DOM.
* @param {Boolean} [params.dropOverride=false] If true, a child element that has been dropped onto some other Group will not be subject to the controls imposed by `prune`, `revert` or `orphan`.
* @constructor
*/
var Group = function(_jsPlumb, params) {
var self = this;
var el = params.el;
this.getEl = function() { return el; };
this.id = params.id || _ju.uuid();
el._isJsPlumbGroup = true;
var getDragArea = this.getDragArea = function() {
var da = _jsPlumb.getSelector(el, GROUP_CONTAINER_SELECTOR);
return da && da.length > 0 ? da[0] : el;
};
var ghost = params.ghost === true;
var constrain = ghost || (params.constrain === true);
var revert = params.revert !== false;
var orphan = params.orphan === true;
var prune = params.prune === true;
var dropOverride = params.dropOverride === true;
var proxied = params.proxied !== false;
var elements = [];
this.connections = { source:[], target:[], internal:[] };
// this function, and getEndpoint below, are stubs for a future setup in which we can choose endpoint
// and anchor based upon the connection and the index (source/target) of the endpoint to be proxied.
this.getAnchor = function(conn, endpointIndex) {
return params.anchor || "Continuous";
};
this.getEndpoint = function(conn, endpointIndex) {
return params.endpoint || [ "Dot", { radius:10 }];
};
this.collapsed = false;
if (params.draggable !== false) {
var opts = {
stop:function(params) {
_jsPlumb.fire(EVT_GROUP_DRAG_STOP, jsPlumb.extend(params, {group:self}));
},
scope:GROUP_DRAG_SCOPE
};
if (params.dragOptions) {
root.jsPlumb.extend(opts, params.dragOptions);
}
_jsPlumb.draggable(params.el, opts);
}
if (params.droppable !== false) {
_jsPlumb.droppable(params.el, {
drop:function(p) {
var el = p.drag.el;
if (el._isJsPlumbGroup) {
return;
}
var currentGroup = el._jsPlumbGroup;
if (currentGroup !== self) {
if (currentGroup != null) {
if (currentGroup.overrideDrop(el, self)) {
return;
}
}
_jsPlumb.getGroupManager().addToGroup(self, el, false);
}
}
});
}
var _each = function(_el, fn) {
var els = _el.nodeType == null ? _el : [ _el ];
for (var i = 0; i < els.length; i++) {
fn(els[i]);
}
};
this.overrideDrop = function(_el, targetGroup) {
return dropOverride && (revert || prune || orphan);
};
this.add = function(_el, doNotFireEvent/*, sourceGroup*/) {
var dragArea = getDragArea();
_each(_el, function(__el) {
if (__el._jsPlumbGroup != null) {
if (__el._jsPlumbGroup === self) {
return;
} else {
__el._jsPlumbGroup.remove(__el, true, doNotFireEvent, false);
}
}
__el._jsPlumbGroup = self;
elements.push(__el);
// test if draggable and add handlers if so.
if (_jsPlumb.isAlreadyDraggable(__el)) {
_bindDragHandlers(__el);
}
if (__el.parentNode !== dragArea) {
dragArea.appendChild(__el);
}
// if (!doNotFireEvent) {
// var p = {group: self, el: __el};
// if (sourceGroup) {
// p.sourceGroup = sourceGroup;
// }
// //_jsPlumb.fire(EVT_CHILD_ADDED, p);
// }
});
_jsPlumb.getGroupManager().updateConnectionsForGroup(self);
};
this.remove = function(el, manipulateDOM, doNotFireEvent, doNotUpdateConnections, targetGroup) {
_each(el, function(__el) {
delete __el._jsPlumbGroup;
_ju.removeWithFunction(elements, function(e) {
return e === __el;
});
if (manipulateDOM) {
try { self.getDragArea().removeChild(__el); }
catch (e) {
jsPlumbUtil.log("Could not remove element from Group " + e);
}
}
_unbindDragHandlers(__el);
if (!doNotFireEvent) {
var p = {group: self, el: __el};
if (targetGroup) {
p.targetGroup = targetGroup;
}
_jsPlumb.fire(EVT_CHILD_REMOVED, p);
}
});
if (!doNotUpdateConnections) {
_jsPlumb.getGroupManager().updateConnectionsForGroup(self);
}
};
this.removeAll = function(manipulateDOM, doNotFireEvent) {
for (var i = 0, l = elements.length; i < l; i++) {
var el = elements[0];
self.remove(el, manipulateDOM, doNotFireEvent, true);
_jsPlumb.remove(el, true);
}
elements.length = 0;
_jsPlumb.getGroupManager().updateConnectionsForGroup(self);
};
this.orphanAll = function() {
var orphanedPositions = {};
for (var i = 0; i < elements.length; i++) {
var newPosition = _orphan(elements[i]);
orphanedPositions[newPosition[0]] = newPosition[1];
}
elements.length = 0;
return orphanedPositions;
};
this.getMembers = function() { return elements; };
el[GROUP] = this;
_jsPlumb.bind(ELEMENT_DRAGGABLE_EVENT, function(dragParams) {
// if its for the current group,
if (dragParams.el._jsPlumbGroup === this) {
_bindDragHandlers(dragParams.el);
}
}.bind(this));
function _findParent(_el) {
return _el.offsetParent;
}
function _isInsideParent(_el, pos) {
var p = _findParent(_el),
s = _jsPlumb.getSize(p),
ss = _jsPlumb.getSize(_el),
leftEdge = pos[0],
rightEdge = leftEdge + ss[0],
topEdge = pos[1],
bottomEdge = topEdge + ss[1];
return rightEdge > 0 && leftEdge < s[0] && bottomEdge > 0 && topEdge < s[1];
}
//
// orphaning an element means taking it out of the group and adding it to the main jsplumb container.
// we return the new calculated position from this method and the element's id.
//
function _orphan(_el) {
var id = _jsPlumb.getId(_el);
var pos = _jsPlumb.getOffset(_el);
_el.parentNode.removeChild(_el);
_jsPlumb.getContainer().appendChild(_el);
_jsPlumb.setPosition(_el, pos);
delete _el._jsPlumbGroup;
_unbindDragHandlers(_el);
_jsPlumb.dragManager.clearParent(_el, id);
return [id, pos];
}
//
// remove an element from the group, then either prune it from the jsplumb instance, or just orphan it.
//
function _pruneOrOrphan(p) {
var orphanedPosition = null;
if (!_isInsideParent(p.el, p.pos)) {
var group = p.el._jsPlumbGroup;
if (prune) {
_jsPlumb.remove(p.el);
} else {
orphanedPosition = _orphan(p.el);
}
group.remove(p.el);
}
return orphanedPosition;
}
//
// redraws the element
//
function _revalidate(_el) {
var id = _jsPlumb.getId(_el);
_jsPlumb.revalidate(_el);
_jsPlumb.dragManager.revalidateParent(_el, id);
}
//
// unbind the group specific drag/revert handlers.
//
function _unbindDragHandlers(_el) {
if (!_el._katavorioDrag) {
return;
}
if (prune || orphan) {
_el._katavorioDrag.off(STOP, _pruneOrOrphan);
}
if (!prune && !orphan && revert) {
_el._katavorioDrag.off(REVERT, _revalidate);
_el._katavorioDrag.setRevert(null);
}
}
function _bindDragHandlers(_el) {
if (!_el._katavorioDrag) {
return;
}
if (prune || orphan) {
_el._katavorioDrag.on(STOP, _pruneOrOrphan);
}
if (constrain) {
_el._katavorioDrag.setConstrain(true);
}
if (ghost) {
_el._katavorioDrag.setUseGhostProxy(true);
}
if (!prune && !orphan && revert) {
_el._katavorioDrag.on(REVERT, _revalidate);
_el._katavorioDrag.setRevert(function(__el, pos) {
return !_isInsideParent(__el, pos);
});
}
}
this.shouldProxy = function() {
return proxied;
};
_jsPlumb.getGroupManager().addGroup(this);
};
/**
* Adds a group to the jsPlumb instance.
* @method addGroup
* @param {Object} params
* @return {Group} The newly created Group.
*/
_jpi.prototype.addGroup = function(params) {
var j = this;
j._groups = j._groups || {};
if (j._groups[params.id] != null) {
throw new TypeError("cannot create Group [" + params.id + "]; a Group with that ID exists");
}
if (params.el[GROUP] != null) {
throw new TypeError("cannot create Group [" + params.id + "]; the given element is already a Group");
}
var group = new Group(j, params);
j._groups[group.id] = group;
if (params.collapsed) {
this.collapseGroup(group);
}
return group;
};
/**
* Add an element to a group.
* @method addToGroup
* @param {String} group Group, or ID of the group, to add the element to.
* @param {Element} el Element to add to the group.
*/
_jpi.prototype.addToGroup = function(group, el, doNotFireEvent) {
var _one = function(_el) {
var id = this.getId(_el);
this.manage(id, _el);
this.getGroupManager().addToGroup(group, _el, doNotFireEvent);
}.bind(this);
if (Array.isArray(el)) {
for (var i = 0; i < el.length; i++) {
_one(el[i]);
}
} else {
_one(el);
}
};
/**
* Remove an element from a group.
* @method removeFromGroup
* @param {String} group Group, or ID of the group, to remove the element from.
* @param {Element} el Element to add to the group.
*/
_jpi.prototype.removeFromGroup = function(group, el, doNotFireEvent) {
this.getGroupManager().removeFromGroup(group, el, doNotFireEvent);
};
/**
* Remove a group, and optionally remove its members from the jsPlumb instance.
* @method removeGroup
* @param {String|Group} group Group to delete, or ID of Group to delete.
* @param {Boolean} [deleteMembers=false] If true, group members will be removed along with the group. Otherwise they will
* just be 'orphaned' (returned to the main container).
* @returns {Map[String, Position}} When deleteMembers is false, this method returns a map of {id->position}
*/
_jpi.prototype.removeGroup = function(group, deleteMembers, manipulateDOM, doNotFireEvent) {
return this.getGroupManager().removeGroup(group, deleteMembers, manipulateDOM, doNotFireEvent);
};
/**
* Remove all groups, and optionally remove their members from the jsPlumb instance.
* @method removeAllGroup
* @param {Boolean} [deleteMembers=false] If true, group members will be removed along with the groups. Otherwise they will
* just be 'orphaned' (returned to the main container).
*/
_jpi.prototype.removeAllGroups = function(deleteMembers, manipulateDOM, doNotFireEvent) {
this.getGroupManager().removeAllGroups(deleteMembers, manipulateDOM, doNotFireEvent);
};
/**
* Get a Group
* @method getGroup
* @param {String} groupId ID of the group to get
* @return {Group} Group with the given ID, null if not found.
*/
_jpi.prototype.getGroup = function(groupId) {
return this.getGroupManager().getGroup(groupId);
};
/**
* Gets all the Groups managed by the jsPlumb instance.
* @returns {Group[]} List of Groups. Empty if none.
*/
_jpi.prototype.getGroups = function() {
return this.getGroupManager().getGroups();
};
/**
* Expands a group element. jsPlumb doesn't do "everything" for you here, because what it means to expand a Group
* will vary from application to application. jsPlumb does these things:
*
* - Hides any connections that are internal to the group (connections between members, and connections from member of
* the group to the group itself)
* - Proxies all connections for which the source or target is a member of the group.
* - Hides the proxied connections.
* - Adds the jtk-group-expanded class to the group's element
* - Removes the jtk-group-collapsed class from the group's element.
*
* @method expandGroup
* @param {String|Group} group Group to expand, or ID of Group to expand.
*/
_jpi.prototype.expandGroup = function(group) {
this.getGroupManager().expandGroup(group);
};
/**
* Collapses a group element. jsPlumb doesn't do "everything" for you here, because what it means to collapse a Group
* will vary from application to application. jsPlumb does these things:
*
* - Shows any connections that are internal to the group (connections between members, and connections from member of
* the group to the group itself)
* - Removes proxies for all connections for which the source or target is a member of the group.
* - Shows the previously proxied connections.
* - Adds the jtk-group-collapsed class to the group's element
* - Removes the jtk-group-expanded class from the group's element.
*
* @method expandGroup
* @param {String|Group} group Group to expand, or ID of Group to expand.
*/
_jpi.prototype.collapseGroup = function(groupId) {
this.getGroupManager().collapseGroup(groupId);
};
_jpi.prototype.repaintGroup = function(group) {
this.getGroupManager().repaintGroup(group);
};
/**
* Collapses or expands a group element depending on its current state. See notes in the collapseGroup and expandGroup method.
*
* @method toggleGroup
* @param {String|Group} group Group to expand/collapse, or ID of Group to expand/collapse.
*/
_jpi.prototype.toggleGroup = function(group) {
group = this.getGroupManager().getGroup(group);
if (group != null) {
this.getGroupManager()[group.collapsed ? "expandGroup" : "collapseGroup"](group);
}
};
//
// lazy init a group manager for the given jsplumb instance.
//
_jpi.prototype.getGroupManager = function() {
var mgr = this[GROUP_MANAGER];
if (mgr == null) {
mgr = this[GROUP_MANAGER] = new GroupManager(this);
}
return mgr;
};
_jpi.prototype.removeGroupManager = function() {
delete this[GROUP_MANAGER];
};
/**
* Gets the Group that the given element belongs to, null if none.
* @method getGroupFor
* @param {String|Element} el Element, or element ID.
* @returns {Group} A Group, if found, or null.
*/
_jpi.prototype.getGroupFor = function(el) {
el = this.getElement(el);
if (el) {
return el[GROUP];
}
};
}).call(typeof window !== 'undefined' ? window : this);
/*
* This file contains the 'flowchart' connectors, consisting of vertical and horizontal line segments.
*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;
(function () {
"use strict";
var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
var STRAIGHT = "Straight";
var ARC = "Arc";
var Flowchart = function (params) {
this.type = "Flowchart";
params = params || {};
params.stub = params.stub == null ? 30 : params.stub;
var segments,
_super = _jp.Connectors.AbstractConnector.apply(this, arguments),
midpoint = params.midpoint == null ? 0.5 : params.midpoint,
alwaysRespectStubs = params.alwaysRespectStubs === true,
lastx = null, lasty = null, lastOrientation,
cornerRadius = params.cornerRadius != null ? params.cornerRadius : 0,
// TODO now common between this and AbstractBezierEditor; refactor into superclass?
loopbackRadius = params.loopbackRadius || 25,
isLoopbackCurrently = false,
sgn = function (n) {
return n < 0 ? -1 : n === 0 ? 0 : 1;
},
segmentDirections = function(segment) {
return [
sgn( segment[2] - segment[0] ),
sgn( segment[3] - segment[1] )
];
},
/**
* helper method to add a segment.
*/
addSegment = function (segments, x, y, paintInfo) {
if (lastx === x && lasty === y) {
return;
}
var lx = lastx == null ? paintInfo.sx : lastx,
ly = lasty == null ? paintInfo.sy : lasty,
o = lx === x ? "v" : "h";
lastx = x;
lasty = y;
segments.push([ lx, ly, x, y, o ]);
},
segLength = function (s) {
return Math.sqrt(Math.pow(s[0] - s[2], 2) + Math.pow(s[1] - s[3], 2));
},
_cloneArray = function (a) {
var _a = [];
_a.push.apply(_a, a);
return _a;
},
writeSegments = function (conn, segments, paintInfo) {
var current = null, next, currentDirection, nextDirection;
for (var i = 0; i < segments.length - 1; i++) {
current = current || _cloneArray(segments[i]);
next = _cloneArray(segments[i + 1]);
currentDirection = segmentDirections(current);
nextDirection = segmentDirections(next);
if (cornerRadius > 0 && current[4] !== next[4]) {
var minSegLength = Math.min(segLength(current), segLength(next));
var radiusToUse = Math.min(cornerRadius, minSegLength / 2);
current[2] -= currentDirection[0] * radiusToUse;
current[3] -= currentDirection[1] * radiusToUse;
next[0] += nextDirection[0] * radiusToUse;
next[1] += nextDirection[1] * radiusToUse;
var ac = (currentDirection[1] === nextDirection[0] && nextDirection[0] === 1) ||
((currentDirection[1] === nextDirection[0] && nextDirection[0] === 0) && currentDirection[0] !== nextDirection[1]) ||
(currentDirection[1] === nextDirection[0] && nextDirection[0] === -1),
sgny = next[1] > current[3] ? 1 : -1,
sgnx = next[0] > current[2] ? 1 : -1,
sgnEqual = sgny === sgnx,
cx = (sgnEqual && ac || (!sgnEqual && !ac)) ? next[0] : current[2],
cy = (sgnEqual && ac || (!sgnEqual && !ac)) ? current[3] : next[1];
_super.addSegment(conn, STRAIGHT, {
x1: current[0], y1: current[1], x2: current[2], y2: current[3]
});
_super.addSegment(conn, ARC, {
r: radiusToUse,
x1: current[2],
y1: current[3],
x2: next[0],
y2: next[1],
cx: cx,
cy: cy,
ac: ac
});
}
else {
// dx + dy are used to adjust for line width.
var dx = (current[2] === current[0]) ? 0 : (current[2] > current[0]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2),
dy = (current[3] === current[1]) ? 0 : (current[3] > current[1]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2);
_super.addSegment(conn, STRAIGHT, {
x1: current[0] - dx, y1: current[1] - dy, x2: current[2] + dx, y2: current[3] + dy
});
}
current = next;
}
if (next != null) {
// last segment
_super.addSegment(conn, STRAIGHT, {
x1: next[0], y1: next[1], x2: next[2], y2: next[3]
});
}
};
this._compute = function (paintInfo, params) {
segments = [];
lastx = null;
lasty = null;
lastOrientation = null;
var commonStubCalculator = function () {
return [paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY];
},
stubCalculators = {
perpendicular: commonStubCalculator,
orthogonal: commonStubCalculator,
opposite: function (axis) {
var pi = paintInfo,
idx = axis === "x" ? 0 : 1,
areInProximity = {
"x": function () {
return ( (pi.so[idx] === 1 && (
( (pi.startStubX > pi.endStubX) && (pi.tx > pi.startStubX) ) ||
( (pi.sx > pi.endStubX) && (pi.tx > pi.sx))))) ||
( (pi.so[idx] === -1 && (
( (pi.startStubX < pi.endStubX) && (pi.tx < pi.startStubX) ) ||
( (pi.sx < pi.endStubX) && (pi.tx < pi.sx)))));
},
"y": function () {
return ( (pi.so[idx] === 1 && (
( (pi.startStubY > pi.endStubY) && (pi.ty > pi.startStubY) ) ||
( (pi.sy > pi.endStubY) && (pi.ty > pi.sy))))) ||
( (pi.so[idx] === -1 && (
( (pi.startStubY < pi.endStubY) && (pi.ty < pi.startStubY) ) ||
( (pi.sy < pi.endStubY) && (pi.ty < pi.sy)))));
}
};
if (!alwaysRespectStubs && areInProximity[axis]()) {
return {
"x": [(paintInfo.sx + paintInfo.tx) / 2, paintInfo.startStubY, (paintInfo.sx + paintInfo.tx) / 2, paintInfo.endStubY],
"y": [paintInfo.startStubX, (paintInfo.sy + paintInfo.ty) / 2, paintInfo.endStubX, (paintInfo.sy + paintInfo.ty) / 2]
}[axis];
}
else {
return [paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY];
}
}
};
// calculate Stubs.
var stubs = stubCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis),
idx = paintInfo.sourceAxis === "x" ? 0 : 1,
oidx = paintInfo.sourceAxis === "x" ? 1 : 0,
ss = stubs[idx],
oss = stubs[oidx],
es = stubs[idx + 2],
oes = stubs[oidx + 2];
// add the start stub segment. use stubs for loopback as it will look better, with the loop spaced
// away from the element.
addSegment(segments, stubs[0], stubs[1], paintInfo);
// if its a loopback and we should treat it differently.
// if (false && params.sourcePos[0] === params.targetPos[0] && params.sourcePos[1] === params.targetPos[1]) {
//
// // we use loopbackRadius here, as statemachine connectors do.
// // so we go radius to the left from stubs[0], then upwards by 2*radius, to the right by 2*radius,
// // down by 2*radius, left by radius.
// addSegment(segments, stubs[0] - loopbackRadius, stubs[1], paintInfo);
// addSegment(segments, stubs[0] - loopbackRadius, stubs[1] - (2 * loopbackRadius), paintInfo);
// addSegment(segments, stubs[0] + loopbackRadius, stubs[1] - (2 * loopbackRadius), paintInfo);
// addSegment(segments, stubs[0] + loopbackRadius, stubs[1], paintInfo);
// addSegment(segments, stubs[0], stubs[1], paintInfo);
//
// }
// else {
var midx = paintInfo.startStubX + ((paintInfo.endStubX - paintInfo.startStubX) * midpoint),
midy = paintInfo.startStubY + ((paintInfo.endStubY - paintInfo.startStubY) * midpoint);
var orientations = {x: [0, 1], y: [1, 0]},
lineCalculators = {
perpendicular: function (axis) {
var pi = paintInfo,
sis = {
x: [
[[1, 2, 3, 4], null, [2, 1, 4, 3]],
null,
[[4, 3, 2, 1], null, [3, 4, 1, 2]]
],
y: [
[[3, 2, 1, 4], null, [2, 3, 4, 1]],
null,
[[4, 1, 2, 3], null, [1, 4, 3, 2]]
]
},
stubs = {
x: [[pi.startStubX, pi.endStubX], null, [pi.endStubX, pi.startStubX]],
y: [[pi.startStubY, pi.endStubY], null, [pi.endStubY, pi.startStubY]]
},
midLines = {
x: [[midx, pi.startStubY], [midx, pi.endStubY]],
y: [[pi.startStubX, midy], [pi.endStubX, midy]]
},
linesToEnd = {
x: [[pi.endStubX, pi.startStubY]],
y: [[pi.startStubX, pi.endStubY]]
},
startToEnd = {
x: [[pi.startStubX, pi.endStubY], [pi.endStubX, pi.endStubY]],
y: [[pi.endStubX, pi.startStubY], [pi.endStubX, pi.endStubY]]
},
startToMidToEnd = {
x: [[pi.startStubX, midy], [pi.endStubX, midy], [pi.endStubX, pi.endStubY]],
y: [[midx, pi.startStubY], [midx, pi.endStubY], [pi.endStubX, pi.endStubY]]
},
otherStubs = {
x: [pi.startStubY, pi.endStubY],
y: [pi.startStubX, pi.endStubX]
},
soIdx = orientations[axis][0], toIdx = orientations[axis][1],
_so = pi.so[soIdx] + 1,
_to = pi.to[toIdx] + 1,
otherFlipped = (pi.to[toIdx] === -1 && (otherStubs[axis][1] < otherStubs[axis][0])) || (pi.to[toIdx] === 1 && (otherStubs[axis][1] > otherStubs[axis][0])),
stub1 = stubs[axis][_so][0],
stub2 = stubs[axis][_so][1],
segmentIndexes = sis[axis][_so][_to];
if (pi.segment === segmentIndexes[3] || (pi.segment === segmentIndexes[2] && otherFlipped)) {
return midLines[axis];
}
else if (pi.segment === segmentIndexes[2] && stub2 < stub1) {
return linesToEnd[axis];
}
else if ((pi.segment === segmentIndexes[2] && stub2 >= stub1) || (pi.segment === segmentIndexes[1] && !otherFlipped)) {
return startToMidToEnd[axis];
}
else if (pi.segment === segmentIndexes[0] || (pi.segment === segmentIndexes[1] && otherFlipped)) {
return startToEnd[axis];
}
},
orthogonal: function (axis, startStub, otherStartStub, endStub, otherEndStub) {
var pi = paintInfo,
extent = {
"x": pi.so[0] === -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub),
"y": pi.so[1] === -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub)
}[axis];
return {
"x": [
[extent, otherStartStub],
[extent, otherEndStub],
[endStub, otherEndStub]
],
"y": [
[otherStartStub, extent],
[otherEndStub, extent],
[otherEndStub, endStub]
]
}[axis];
},
opposite: function (axis, ss, oss, es) {
var pi = paintInfo,
otherAxis = {"x": "y", "y": "x"}[axis],
dim = {"x": "height", "y": "width"}[axis],
comparator = pi["is" + axis.toUpperCase() + "GreaterThanStubTimes2"];
if (params.sourceEndpoint.elementId === params.targetEndpoint.elementId) {
var _val = oss + ((1 - params.sourceEndpoint.anchor[otherAxis]) * params.sourceInfo[dim]) + _super.maxStub;
return {
"x": [
[ss, _val],
[es, _val]
],
"y": [
[_val, ss],
[_val, es]
]
}[axis];
}
else if (!comparator || (pi.so[idx] === 1 && ss > es) || (pi.so[idx] === -1 && ss < es)) {
return {
"x": [
[ss, midy],
[es, midy]
],
"y": [
[midx, ss],
[midx, es]
]
}[axis];
}
else if ((pi.so[idx] === 1 && ss < es) || (pi.so[idx] === -1 && ss > es)) {
return {
"x": [
[midx, pi.sy],
[midx, pi.ty]
],
"y": [
[pi.sx, midy],
[pi.tx, midy]
]
}[axis];
}
}
};
// compute the rest of the line
var p = lineCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis, ss, oss, es, oes);
if (p) {
for (var i = 0; i < p.length; i++) {
addSegment(segments, p[i][0], p[i][1], paintInfo);
}
}
// line to end stub
addSegment(segments, stubs[2], stubs[3], paintInfo);
//}
// end stub to end (common)
addSegment(segments, paintInfo.tx, paintInfo.ty, paintInfo);
// write out the segments.
writeSegments(this, segments, paintInfo);
};
};
_jp.Connectors.Flowchart = Flowchart;
_ju.extend(_jp.Connectors.Flowchart, _jp.Connectors.AbstractConnector);
}).call(typeof window !== 'undefined' ? window : this);
/*
* This file contains the code for the Bezier connector type.
*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;
(function () {
"use strict";
var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
_jp.Connectors.AbstractBezierConnector = function(params) {
params = params || {};
var showLoopback = params.showLoopback !== false,
curviness = params.curviness || 10,
margin = params.margin || 5,
proximityLimit = params.proximityLimit || 80,
clockwise = params.orientation && params.orientation === "clockwise",
loopbackRadius = params.loopbackRadius || 25,
isLoopbackCurrently = false,
_super;
this._compute = function (paintInfo, p) {
var sp = p.sourcePos,
tp = p.targetPos,
_w = Math.abs(sp[0] - tp[0]),
_h = Math.abs(sp[1] - tp[1]);
if (!showLoopback || (p.sourceEndpoint.elementId !== p.targetEndpoint.elementId)) {
isLoopbackCurrently = false;
this._computeBezier(paintInfo, p, sp, tp, _w, _h);
} else {
isLoopbackCurrently = true;
// a loopback connector. draw an arc from one anchor to the other.
var x1 = p.sourcePos[0], y1 = p.sourcePos[1] - margin,
cx = x1, cy = y1 - loopbackRadius,
// canvas sizing stuff, to ensure the whole painted area is visible.
_x = cx - loopbackRadius,
_y = cy - loopbackRadius;
_w = 2 * loopbackRadius;
_h = 2 * loopbackRadius;
paintInfo.points[0] = _x;
paintInfo.points[1] = _y;
paintInfo.points[2] = _w;
paintInfo.points[3] = _h;
// ADD AN ARC SEGMENT.
_super.addSegment(this, "Arc", {
loopback: true,
x1: (x1 - _x) + 4,
y1: y1 - _y,
startAngle: 0,
endAngle: 2 * Math.PI,
r: loopbackRadius,
ac: !clockwise,
x2: (x1 - _x) - 4,
y2: y1 - _y,
cx: cx - _x,
cy: cy - _y
});
}
};
_super = _jp.Connectors.AbstractConnector.apply(this, arguments);
return _super;
};
_ju.extend(_jp.Connectors.AbstractBezierConnector, _jp.Connectors.AbstractConnector);
var Bezier = function (params) {
params = params || {};
this.type = "Bezier";
var _super = _jp.Connectors.AbstractBezierConnector.apply(this, arguments),
majorAnchor = params.curviness || 150,
minorAnchor = 10;
this.getCurviness = function () {
return majorAnchor;
};
this._findControlPoint = function (point, sourceAnchorPosition, targetAnchorPosition, sourceEndpoint, targetEndpoint, soo, too) {
// determine if the two anchors are perpendicular to each other in their orientation. we swap the control
// points around if so (code could be tightened up)
var perpendicular = soo[0] !== too[0] || soo[1] === too[1],
p = [];
if (!perpendicular) {
if (soo[0] === 0) {
p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor);
}
else {
p.push(point[0] - (majorAnchor * soo[0]));
}
if (soo[1] === 0) {
p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor);
}
else {
p.push(point[1] + (majorAnchor * too[1]));
}
}
else {
if (too[0] === 0) {
p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor);
}
else {
p.push(point[0] + (majorAnchor * too[0]));
}
if (too[1] === 0) {
p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor);
}
else {
p.push(point[1] + (majorAnchor * soo[1]));
}
}
return p;
};
this._computeBezier = function (paintInfo, p, sp, tp, _w, _h) {
var _CP, _CP2,
_sx = sp[0] < tp[0] ? _w : 0,
_sy = sp[1] < tp[1] ? _h : 0,
_tx = sp[0] < tp[0] ? 0 : _w,
_ty = sp[1] < tp[1] ? 0 : _h;
_CP = this._findControlPoint([_sx, _sy], sp, tp, p.sourceEndpoint, p.targetEndpoint, paintInfo.so, paintInfo.to);
_CP2 = this._findControlPoint([_tx, _ty], tp, sp, p.targetEndpoint, p.sourceEndpoint, paintInfo.to, paintInfo.so);
_super.addSegment(this, "Bezier", {
x1: _sx, y1: _sy, x2: _tx, y2: _ty,
cp1x: _CP[0], cp1y: _CP[1], cp2x: _CP2[0], cp2y: _CP2[1]
});
};
};
_jp.Connectors.Bezier = Bezier;
_ju.extend(Bezier, _jp.Connectors.AbstractBezierConnector);
}).call(typeof window !== 'undefined' ? window : this);
/*
* This file contains the state machine connectors, which extend AbstractBezierConnector.
*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;
(function () {
"use strict";
var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
var _segment = function (x1, y1, x2, y2) {
if (x1 <= x2 && y2 <= y1) {
return 1;
}
else if (x1 <= x2 && y1 <= y2) {
return 2;
}
else if (x2 <= x1 && y2 >= y1) {
return 3;
}
return 4;
},
// the control point we will use depends on the faces to which each end of the connection is assigned, specifically whether or not the
// two faces are parallel or perpendicular. if they are parallel then the control point lies on the midpoint of the axis in which they
// are parellel and varies only in the other axis; this variation is proportional to the distance that the anchor points lie from the
// center of that face. if the two faces are perpendicular then the control point is at some distance from both the midpoints; the amount and
// direction are dependent on the orientation of the two elements. 'seg', passed in to this method, tells you which segment the target element
// lies in with respect to the source: 1 is top right, 2 is bottom right, 3 is bottom left, 4 is top left.
//
// sourcePos and targetPos are arrays of info about where on the source and target each anchor is located. their contents are:
//
// 0 - absolute x
// 1 - absolute y
// 2 - proportional x in element (0 is left edge, 1 is right edge)
// 3 - proportional y in element (0 is top edge, 1 is bottom edge)
//
_findControlPoint = function (midx, midy, segment, sourceEdge, targetEdge, dx, dy, distance, proximityLimit) {
// TODO (maybe)
// - if anchor pos is 0.5, make the control point take into account the relative position of the elements.
if (distance <= proximityLimit) {
return [midx, midy];
}
if (segment === 1) {
if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) {
return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
}
else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) {
return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
}
else {
return [ midx + (-1 * dx) , midy + (-1 * dy) ];
}
}
else if (segment === 2) {
if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) {
return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
}
else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) {
return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
}
else {
return [ midx + dx, midy + (-1 * dy) ];
}
}
else if (segment === 3) {
if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) {
return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
}
else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) {
return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
}
else {
return [ midx + (-1 * dx) , midy + (-1 * dy) ];
}
}
else if (segment === 4) {
if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) {
return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
}
else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) {
return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
}
else {
return [ midx + dx , midy + (-1 * dy) ];
}
}
};
var StateMachine = function (params) {
params = params || {};
this.type = "StateMachine";
var _super = _jp.Connectors.AbstractBezierConnector.apply(this, arguments),
curviness = params.curviness || 10,
margin = params.margin || 5,
proximityLimit = params.proximityLimit || 80,
clockwise = params.orientation && params.orientation === "clockwise",
_controlPoint;
this._computeBezier = function(paintInfo, params, sp, tp, w, h) {
var _sx = params.sourcePos[0] < params.targetPos[0] ? 0 : w,
_sy = params.sourcePos[1] < params.targetPos[1] ? 0 : h,
_tx = params.sourcePos[0] < params.targetPos[0] ? w : 0,
_ty = params.sourcePos[1] < params.targetPos[1] ? h : 0;
// now adjust for the margin
if (params.sourcePos[2] === 0) {
_sx -= margin;
}
if (params.sourcePos[2] === 1) {
_sx += margin;
}
if (params.sourcePos[3] === 0) {
_sy -= margin;
}
if (params.sourcePos[3] === 1) {
_sy += margin;
}
if (params.targetPos[2] === 0) {
_tx -= margin;
}
if (params.targetPos[2] === 1) {
_tx += margin;
}
if (params.targetPos[3] === 0) {
_ty -= margin;
}
if (params.targetPos[3] === 1) {
_ty += margin;
}
//
// these connectors are quadratic bezier curves, having a single control point. if both anchors
// are located at 0.5 on their respective faces, the control point is set to the midpoint and you
// get a straight line. this is also the case if the two anchors are within 'proximityLimit', since
// it seems to make good aesthetic sense to do that. outside of that, the control point is positioned
// at 'curviness' pixels away along the normal to the straight line connecting the two anchors.
//
// there may be two improvements to this. firstly, we might actually support the notion of avoiding nodes
// in the UI, or at least making a good effort at doing so. if a connection would pass underneath some node,
// for example, we might increase the distance the control point is away from the midpoint in a bid to
// steer it around that node. this will work within limits, but i think those limits would also be the likely
// limits for, once again, aesthetic good sense in the layout of a chart using these connectors.
//
// the second possible change is actually two possible changes: firstly, it is possible we should gradually
// decrease the 'curviness' as the distance between the anchors decreases; start tailing it off to 0 at some
// point (which should be configurable). secondly, we might slightly increase the 'curviness' for connectors
// with respect to how far their anchor is from the center of its respective face. this could either look cool,
// or stupid, and may indeed work only in a way that is so subtle as to have been a waste of time.
//
var _midx = (_sx + _tx) / 2,
_midy = (_sy + _ty) / 2,
segment = _segment(_sx, _sy, _tx, _ty),
distance = Math.sqrt(Math.pow(_tx - _sx, 2) + Math.pow(_ty - _sy, 2)),
cp1x, cp2x, cp1y, cp2y;
// calculate the control point. this code will be where we'll put in a rudimentary element avoidance scheme; it
// will work by extending the control point to force the curve to be, um, curvier.
_controlPoint = _findControlPoint(_midx,
_midy,
segment,
params.sourcePos,
params.targetPos,
curviness, curviness,
distance,
proximityLimit);
cp1x = _controlPoint[0];
cp2x = _controlPoint[0];
cp1y = _controlPoint[1];
cp2y = _controlPoint[1];
_super.addSegment(this, "Bezier", {
x1: _tx, y1: _ty, x2: _sx, y2: _sy,
cp1x: cp1x, cp1y: cp1y,
cp2x: cp2x, cp2y: cp2y
});
};
};
_jp.Connectors.StateMachine = StateMachine;
_ju.extend(StateMachine, _jp.Connectors.AbstractBezierConnector);
}).call(typeof window !== 'undefined' ? window : this);
/*
* This file contains the 'flowchart' connectors, consisting of vertical and horizontal line segments.
*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;
(function () {
"use strict";
var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
var STRAIGHT = "Straight";
var Straight = function (params) {
this.type = STRAIGHT;
var _super = _jp.Connectors.AbstractConnector.apply(this, arguments);
this._compute = function (paintInfo, _) {
_super.addSegment(this, STRAIGHT, {x1: paintInfo.sx, y1: paintInfo.sy, x2: paintInfo.startStubX, y2: paintInfo.startStubY});
_super.addSegment(this, STRAIGHT, {x1: paintInfo.startStubX, y1: paintInfo.startStubY, x2: paintInfo.endStubX, y2: paintInfo.endStubY});
_super.addSegment(this, STRAIGHT, {x1: paintInfo.endStubX, y1: paintInfo.endStubY, x2: paintInfo.tx, y2: paintInfo.ty});
};
};
_jp.Connectors.Straight = Straight;
_ju.extend(Straight, _jp.Connectors.AbstractConnector);
}).call(typeof window !== 'undefined' ? window : this);
/*
* This file contains the SVG renderers.
*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;
(function () {
// ************************** SVG utility methods ********************************************
"use strict";
var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
var svgAttributeMap = {
"stroke-linejoin": "stroke-linejoin",
"stroke-dashoffset": "stroke-dashoffset",
"stroke-linecap": "stroke-linecap"
},
STROKE_DASHARRAY = "stroke-dasharray",
DASHSTYLE = "dashstyle",
LINEAR_GRADIENT = "linearGradient",
RADIAL_GRADIENT = "radialGradient",
DEFS = "defs",
FILL = "fill",
STOP = "stop",
STROKE = "stroke",
STROKE_WIDTH = "stroke-width",
STYLE = "style",
NONE = "none",
JSPLUMB_GRADIENT = "jsplumb_gradient_",
LINE_WIDTH = "strokeWidth",
ns = {
svg: "http://www.w3.org/2000/svg"
},
_attr = function (node, attributes) {
for (var i in attributes) {
node.setAttribute(i, "" + attributes[i]);
}
},
_node = function (name, attributes) {
attributes = attributes || {};
attributes.version = "1.1";
attributes.xmlns = ns.svg;
return _jp.createElementNS(ns.svg, name, null, null, attributes);
},
_pos = function (d) {
return "position:absolute;left:" + d[0] + "px;top:" + d[1] + "px";
},
_clearGradient = function (parent) {
var els = parent.querySelectorAll(" defs,linearGradient,radialGradient");
for (var i = 0; i < els.length; i++) {
els[i].parentNode.removeChild(els[i]);
}
},
_updateGradient = function (parent, node, style, dimensions, uiComponent) {
var id = JSPLUMB_GRADIENT + uiComponent._jsPlumb.instance.idstamp();
// first clear out any existing gradient
_clearGradient(parent);
// this checks for an 'offset' property in the gradient, and in the absence of it, assumes
// we want a linear gradient. if it's there, we create a radial gradient.
// it is possible that a more explicit means of defining the gradient type would be
// better. relying on 'offset' means that we can never have a radial gradient that uses
// some default offset, for instance.
// issue 244 suggested the 'gradientUnits' attribute; without this, straight/flowchart connectors with gradients would
// not show gradients when the line was perfectly horizontal or vertical.
var g;
if (!style.gradient.offset) {
g = _node(LINEAR_GRADIENT, {id: id, gradientUnits: "userSpaceOnUse"});
}
else {
g = _node(RADIAL_GRADIENT, { id: id });
}
var defs = _node(DEFS);
parent.appendChild(defs);
defs.appendChild(g);
// the svg radial gradient seems to treat stops in the reverse
// order to how canvas does it. so we want to keep all the maths the same, but
// iterate the actual style declarations in reverse order, if the x indexes are not in order.
for (var i = 0; i < style.gradient.stops.length; i++) {
var styleToUse = uiComponent.segment === 1 || uiComponent.segment === 2 ? i : style.gradient.stops.length - 1 - i,
stopColor = style.gradient.stops[styleToUse][1],
s = _node(STOP, {"offset": Math.floor(style.gradient.stops[i][0] * 100) + "%", "stop-color": stopColor});
g.appendChild(s);
}
var applyGradientTo = style.stroke ? STROKE : FILL;
node.setAttribute(applyGradientTo, "url(#" + id + ")");
},
_applyStyles = function (parent, node, style, dimensions, uiComponent) {
node.setAttribute(FILL, style.fill ? style.fill : NONE);
node.setAttribute(STROKE, style.stroke ? style.stroke : NONE);
if (style.gradient) {
_updateGradient(parent, node, style, dimensions, uiComponent);
}
else {
// make sure we clear any existing gradient
_clearGradient(parent);
node.setAttribute(STYLE, "");
}
if (style.strokeWidth) {
node.setAttribute(STROKE_WIDTH, style.strokeWidth);
}
// in SVG there is a stroke-dasharray attribute we can set, and its syntax looks like
// the syntax in VML but is actually kind of nasty: values are given in the pixel
// coordinate space, whereas in VML they are multiples of the width of the stroked
// line, which makes a lot more sense. for that reason, jsPlumb is supporting both
// the native svg 'stroke-dasharray' attribute, and also the 'dashstyle' concept from
// VML, which will be the preferred method. the code below this converts a dashstyle
// attribute given in terms of stroke width into a pixel representation, by using the
// stroke's lineWidth.
if (style[DASHSTYLE] && style[LINE_WIDTH] && !style[STROKE_DASHARRAY]) {
var sep = style[DASHSTYLE].indexOf(",") === -1 ? " " : ",",
parts = style[DASHSTYLE].split(sep),
styleToUse = "";
parts.forEach(function (p) {
styleToUse += (Math.floor(p * style.strokeWidth) + sep);
});
node.setAttribute(STROKE_DASHARRAY, styleToUse);
}
else if (style[STROKE_DASHARRAY]) {
node.setAttribute(STROKE_DASHARRAY, style[STROKE_DASHARRAY]);
}
// extra attributes such as join type, dash offset.
for (var i in svgAttributeMap) {
if (style[i]) {
node.setAttribute(svgAttributeMap[i], style[i]);
}
}
},
_appendAtIndex = function (svg, path, idx) {
if (svg.childNodes.length > idx) {
svg.insertBefore(path, svg.childNodes[idx]);
}
else {
svg.appendChild(path);
}
};
/**
utility methods for other objects to use.
*/
_ju.svg = {
node: _node,
attr: _attr,
pos: _pos
};
// ************************** / SVG utility methods ********************************************
/*
* Base class for SVG components.
*/
var SvgComponent = function (params) {
var pointerEventsSpec = params.pointerEventsSpec || "all", renderer = {};
_jp.jsPlumbUIComponent.apply(this, params.originalArgs);
this.canvas = null;
this.path = null;
this.svg = null;
this.bgCanvas = null;
var clazz = params.cssClass + " " + (params.originalArgs[0].cssClass || ""),
svgParams = {
"style": "",
"width": 0,
"height": 0,
"pointer-events": pointerEventsSpec,
"position": "absolute"
};
this.svg = _node("svg", svgParams);
if (params.useDivWrapper) {
this.canvas = _jp.createElement("div", { position : "absolute" });
_ju.sizeElement(this.canvas, 0, 0, 1, 1);
this.canvas.className = clazz;
}
else {
_attr(this.svg, { "class": clazz });
this.canvas = this.svg;
}
params._jsPlumb.appendElement(this.canvas, params.originalArgs[0].parent);
if (params.useDivWrapper) {
this.canvas.appendChild(this.svg);
}
var displayElements = [ this.canvas ];
this.getDisplayElements = function () {
return displayElements;
};
this.appendDisplayElement = function (el) {
displayElements.push(el);
};
this.paint = function (style, anchor, extents) {
if (style != null) {
var xy = [ this.x, this.y ], wh = [ this.w, this.h ], p;
if (extents != null) {
if (extents.xmin < 0) {
xy[0] += extents.xmin;
}
if (extents.ymin < 0) {
xy[1] += extents.ymin;
}
wh[0] = extents.xmax + ((extents.xmin < 0) ? -extents.xmin : 0);
wh[1] = extents.ymax + ((extents.ymin < 0) ? -extents.ymin : 0);
}
if (params.useDivWrapper) {
_ju.sizeElement(this.canvas, xy[0], xy[1], wh[0], wh[1]);
xy[0] = 0;
xy[1] = 0;
p = _pos([ 0, 0 ]);
}
else {
p = _pos([ xy[0], xy[1] ]);
}
renderer.paint.apply(this, arguments);
_attr(this.svg, {
"style": p,
"width": wh[0] || 0,
"height": wh[1] || 0
});
}
};
return {
renderer: renderer
};
};
_ju.extend(SvgComponent, _jp.jsPlumbUIComponent, {
cleanup: function (force) {
if (force || this.typeId == null) {
if (this.canvas) {
this.canvas._jsPlumb = null;
}
if (this.svg) {
this.svg._jsPlumb = null;
}
if (this.bgCanvas) {
this.bgCanvas._jsPlumb = null;
}
if (this.canvas && this.canvas.parentNode) {
this.canvas.parentNode.removeChild(this.canvas);
}
if (this.bgCanvas && this.bgCanvas.parentNode) {
this.canvas.parentNode.removeChild(this.canvas);
}
this.svg = null;
this.canvas = null;
this.path = null;
this.group = null;
}
else {
// if not a forced cleanup, just detach from DOM for now.
if (this.canvas && this.canvas.parentNode) {
this.canvas.parentNode.removeChild(this.canvas);
}
if (this.bgCanvas && this.bgCanvas.parentNode) {
this.bgCanvas.parentNode.removeChild(this.bgCanvas);
}
}
},
reattach:function(instance) {
var c = instance.getContainer();
if (this.canvas && this.canvas.parentNode == null) {
c.appendChild(this.canvas);
}
if (this.bgCanvas && this.bgCanvas.parentNode == null) {
c.appendChild(this.bgCanvas);
}
},
setVisible: function (v) {
if (this.canvas) {
this.canvas.style.display = v ? "block" : "none";
}
}
});
/*
* Base class for SVG connectors.
*/
_jp.ConnectorRenderers.svg = function (params) {
var self = this,
_super = SvgComponent.apply(this, [
{
cssClass: params._jsPlumb.connectorClass,
originalArgs: arguments,
pointerEventsSpec: "none",
_jsPlumb: params._jsPlumb
}
]);
_super.renderer.paint = function (style, anchor, extents) {
var segments = self.getSegments(), p = "", offset = [0, 0];
if (extents.xmin < 0) {
offset[0] = -extents.xmin;
}
if (extents.ymin < 0) {
offset[1] = -extents.ymin;
}
if (segments.length > 0) {
p = self.getPathData();
var a = {
d: p,
transform: "translate(" + offset[0] + "," + offset[1] + ")",
"pointer-events": params["pointer-events"] || "visibleStroke"
},
outlineStyle = null,
d = [self.x, self.y, self.w, self.h];
// outline style. actually means drawing an svg object underneath the main one.
if (style.outlineStroke) {
var outlineWidth = style.outlineWidth || 1,
outlineStrokeWidth = style.strokeWidth + (2 * outlineWidth);
outlineStyle = _jp.extend({}, style);
delete outlineStyle.gradient;
outlineStyle.stroke = style.outlineStroke;
outlineStyle.strokeWidth = outlineStrokeWidth;
if (self.bgPath == null) {
self.bgPath = _node("path", a);
_jp.addClass(self.bgPath, _jp.connectorOutlineClass);
_appendAtIndex(self.svg, self.bgPath, 0);
}
else {
_attr(self.bgPath, a);
}
_applyStyles(self.svg, self.bgPath, outlineStyle, d, self);
}
if (self.path == null) {
self.path = _node("path", a);
_appendAtIndex(self.svg, self.path, style.outlineStroke ? 1 : 0);
}
else {
_attr(self.path, a);
}
_applyStyles(self.svg, self.path, style, d, self);
}
};
};
_ju.extend(_jp.ConnectorRenderers.svg, SvgComponent);
// ******************************* svg segment renderer *****************************************************
// ******************************* /svg segments *****************************************************
/*
* Base class for SVG endpoints.
*/
var SvgEndpoint = _jp.SvgEndpoint = function (params) {
var _super = SvgComponent.apply(this, [
{
cssClass: params._jsPlumb.endpointClass,
originalArgs: arguments,
pointerEventsSpec: "all",
useDivWrapper: true,
_jsPlumb: params._jsPlumb
}
]);
_super.renderer.paint = function (style) {
var s = _jp.extend({}, style);
if (s.outlineStroke) {
s.stroke = s.outlineStroke;
}
if (this.node == null) {
this.node = this.makeNode(s);
this.svg.appendChild(this.node);
}
else if (this.updateNode != null) {
this.updateNode(this.node);
}
_applyStyles(this.svg, this.node, s, [ this.x, this.y, this.w, this.h ], this);
_pos(this.node, [ this.x, this.y ]);
}.bind(this);
};
_ju.extend(SvgEndpoint, SvgComponent);
/*
* SVG Dot Endpoint
*/
_jp.Endpoints.svg.Dot = function () {
_jp.Endpoints.Dot.apply(this, arguments);
SvgEndpoint.apply(this, arguments);
this.makeNode = function (style) {
return _node("circle", {
"cx": this.w / 2,
"cy": this.h / 2,
"r": this.radius
});
};
this.updateNode = function (node) {
_attr(node, {
"cx": this.w / 2,
"cy": this.h / 2,
"r": this.radius
});
};
};
_ju.extend(_jp.Endpoints.svg.Dot, [_jp.Endpoints.Dot, SvgEndpoint]);
/*
* SVG Rectangle Endpoint
*/
_jp.Endpoints.svg.Rectangle = function () {
_jp.Endpoints.Rectangle.apply(this, arguments);
SvgEndpoint.apply(this, arguments);
this.makeNode = function (style) {
return _node("rect", {
"width": this.w,
"height": this.h
});
};
this.updateNode = function (node) {
_attr(node, {
"width": this.w,
"height": this.h
});
};
};
_ju.extend(_jp.Endpoints.svg.Rectangle, [_jp.Endpoints.Rectangle, SvgEndpoint]);
/*
* SVG Image Endpoint is the default image endpoint.
*/
_jp.Endpoints.svg.Image = _jp.Endpoints.Image;
/*
* Blank endpoint in svg renderer is the default Blank endpoint.
*/
_jp.Endpoints.svg.Blank = _jp.Endpoints.Blank;
/*
* Label overlay in svg renderer is the default Label overlay.
*/
_jp.Overlays.svg.Label = _jp.Overlays.Label;
/*
* Custom overlay in svg renderer is the default Custom overlay.
*/
_jp.Overlays.svg.Custom = _jp.Overlays.Custom;
var AbstractSvgArrowOverlay = function (superclass, originalArgs) {
superclass.apply(this, originalArgs);
_jp.jsPlumbUIComponent.apply(this, originalArgs);
this.isAppendedAtTopLevel = false;
var self = this;
this.path = null;
this.paint = function (params, containerExtents) {
// only draws on connections, not endpoints.
if (params.component.svg && containerExtents) {
if (this.path == null) {
this.path = _node("path", {
"pointer-events": "all"
});
params.component.svg.appendChild(this.path);
if (this.elementCreated) {
this.elementCreated(this.path, params.component);
}
this.canvas = params.component.svg; // for the sake of completeness; this behaves the same as other overlays
}
var clazz = originalArgs && (originalArgs.length === 1) ? (originalArgs[0].cssClass || "") : "",
offset = [0, 0];
if (containerExtents.xmin < 0) {
offset[0] = -containerExtents.xmin;
}
if (containerExtents.ymin < 0) {
offset[1] = -containerExtents.ymin;
}
_attr(this.path, {
"d": makePath(params.d),
"class": clazz,
stroke: params.stroke ? params.stroke : null,
fill: params.fill ? params.fill : null,
transform: "translate(" + offset[0] + "," + offset[1] + ")"
});
}
};
var makePath = function (d) {
return (isNaN(d.cxy.x) || isNaN(d.cxy.y)) ? "" : "M" + d.hxy.x + "," + d.hxy.y +
" L" + d.tail[0].x + "," + d.tail[0].y +
" L" + d.cxy.x + "," + d.cxy.y +
" L" + d.tail[1].x + "," + d.tail[1].y +
" L" + d.hxy.x + "," + d.hxy.y;
};
this.transfer = function(target) {
if (target.canvas && this.path && this.path.parentNode) {
this.path.parentNode.removeChild(this.path);
target.canvas.appendChild(this.path);
}
};
};
_ju.extend(AbstractSvgArrowOverlay, [_jp.jsPlumbUIComponent, _jp.Overlays.AbstractOverlay], {
cleanup: function (force) {
if (this.path != null) {
if (force) {
this._jsPlumb.instance.removeElement(this.path);
}
else {
if (this.path.parentNode) {
this.path.parentNode.removeChild(this.path);
}
}
}
},
reattach:function(instance, component) {
if (this.path && component.canvas) {
component.canvas.appendChild(this.path);
}
},
setVisible: function (v) {
if (this.path != null) {
(this.path.style.display = (v ? "block" : "none"));
}
}
});
_jp.Overlays.svg.Arrow = function () {
AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.Arrow, arguments]);
};
_ju.extend(_jp.Overlays.svg.Arrow, [ _jp.Overlays.Arrow, AbstractSvgArrowOverlay ]);
_jp.Overlays.svg.PlainArrow = function () {
AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.PlainArrow, arguments]);
};
_ju.extend(_jp.Overlays.svg.PlainArrow, [ _jp.Overlays.PlainArrow, AbstractSvgArrowOverlay ]);
_jp.Overlays.svg.Diamond = function () {
AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.Diamond, arguments]);
};
_ju.extend(_jp.Overlays.svg.Diamond, [ _jp.Overlays.Diamond, AbstractSvgArrowOverlay ]);
// a test
_jp.Overlays.svg.GuideLines = function () {
var path = null, self = this, p1_1, p1_2;
_jp.Overlays.GuideLines.apply(this, arguments);
this.paint = function (params, containerExtents) {
if (path == null) {
path = _node("path");
params.connector.svg.appendChild(path);
self.attachListeners(path, params.connector);
self.attachListeners(path, self);
p1_1 = _node("path");
params.connector.svg.appendChild(p1_1);
self.attachListeners(p1_1, params.connector);
self.attachListeners(p1_1, self);
p1_2 = _node("path");
params.connector.svg.appendChild(p1_2);
self.attachListeners(p1_2, params.connector);
self.attachListeners(p1_2, self);
}
var offset = [0, 0];
if (containerExtents.xmin < 0) {
offset[0] = -containerExtents.xmin;
}
if (containerExtents.ymin < 0) {
offset[1] = -containerExtents.ymin;
}
_attr(path, {
"d": makePath(params.head, params.tail),
stroke: "red",
fill: null,
transform: "translate(" + offset[0] + "," + offset[1] + ")"
});
_attr(p1_1, {
"d": makePath(params.tailLine[0], params.tailLine[1]),
stroke: "blue",
fill: null,
transform: "translate(" + offset[0] + "," + offset[1] + ")"
});
_attr(p1_2, {
"d": makePath(params.headLine[0], params.headLine[1]),
stroke: "green",
fill: null,
transform: "translate(" + offset[0] + "," + offset[1] + ")"
});
};
var makePath = function (d1, d2) {
return "M " + d1.x + "," + d1.y +
" L" + d2.x + "," + d2.y;
};
};
_ju.extend(_jp.Overlays.svg.GuideLines, _jp.Overlays.GuideLines);
}).call(typeof window !== 'undefined' ? window : this);
/*
* This file contains the 'vanilla' adapter - having no external dependencies other than bundled libs.
*
* Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
*
* https://jsplumbtoolkit.com
* https://github.com/jsplumb/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;
(function () {
"use strict";
var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil,
_jk = root.Katavorio, _jg = root.Biltong;
var _getDragManager = function (instance, category) {
category = category || "main";
var key = "_katavorio_" + category;
var k = instance[key],
e = instance.getEventManager();
if (!k) {
k = new _jk({
bind: e.on,
unbind: e.off,
getSize: _jp.getSize,
getConstrainingRectangle:function(el) {
return [ el.parentNode.scrollWidth, el.parentNode.scrollHeight ];
},
getPosition: function (el, relativeToRoot) {
// if this is a nested draggable then compute the offset against its own offsetParent, otherwise
// compute against the Container's origin. see also the getUIPosition method below.
var o = instance.getOffset(el, relativeToRoot, el._katavorioDrag ? el.offsetParent : null);
return [o.left, o.top];
},
setPosition: function (el, xy) {
el.style.left = xy[0] + "px";
el.style.top = xy[1] + "px";
},
addClass: _jp.addClass,
removeClass: _jp.removeClass,
intersects: _jg.intersects,
indexOf: function(l, i) { return l.indexOf(i); },
scope:instance.getDefaultScope(),
css: {
noSelect: instance.dragSelectClass,
droppable: "jtk-droppable",
draggable: "jtk-draggable",
drag: "jtk-drag",
selected: "jtk-drag-selected",
active: "jtk-drag-active",
hover: "jtk-drag-hover",
ghostProxy:"jtk-ghost-proxy"
}
});
k.setZoom(instance.getZoom());
instance[key] = k;
instance.bind("zoom", k.setZoom);
}
return k;
};
var _animProps = function (o, p) {
var _one = function (pName) {
if (p[pName] != null) {
if (_ju.isString(p[pName])) {
var m = p[pName].match(/-=/) ? -1 : 1,
v = p[pName].substring(2);
return o[pName] + (m * v);
}
else {
return p[pName];
}
}
else {
return o[pName];
}
};
return [ _one("left"), _one("top") ];
};
_jp.extend(root.jsPlumbInstance.prototype, {
animationSupported:true,
getElement: function (el) {
if (el == null) {
return null;
}
// here we pluck the first entry if el was a list of entries.
// this is not my favourite thing to do, but previous versions of
// jsplumb supported jquery selectors, and it is possible a selector
// will be passed in here.
el = typeof el === "string" ? el : el.length != null && el.enctype == null ? el[0] : el;
return typeof el === "string" ? document.getElementById(el) : el;
},
removeElement: function (element) {
_getDragManager(this).elementRemoved(element);
this.getEventManager().remove(element);
},
//
// this adapter supports a rudimentary animation function. no easing is supported. only
// left/top properties are supported. property delta args are expected to be in the form
//
// +=x.xxxx
//
// or
//
// -=x.xxxx
//
doAnimate: function (el, properties, options) {
options = options || {};
var o = this.getOffset(el),
ap = _animProps(o, properties),
ldist = ap[0] - o.left,
tdist = ap[1] - o.top,
d = options.duration || 250,
step = 15, steps = d / step,
linc = (step / d) * ldist,
tinc = (step / d) * tdist,
idx = 0,
_int = setInterval(function () {
_jp.setPosition(el, {
left: o.left + (linc * (idx + 1)),
top: o.top + (tinc * (idx + 1))
});
if (options.step != null) {
options.step(idx, Math.ceil(steps));
}
idx++;
if (idx >= steps) {
window.clearInterval(_int);
if (options.complete != null) {
options.complete();
}
}
}, step);
},
// DRAG/DROP
destroyDraggable: function (el, category) {
_getDragManager(this, category).destroyDraggable(el);
},
unbindDraggable: function (el, evt, fn, category) {
_getDragManager(this, category).destroyDraggable(el, evt, fn);
},
destroyDroppable: function (el, category) {
_getDragManager(this, category).destroyDroppable(el);
},
unbindDroppable: function (el, evt, fn, category) {
_getDragManager(this, category).destroyDroppable(el, evt, fn);
},
initDraggable: function (el, options, category) {
_getDragManager(this, category).draggable(el, options);
},
initDroppable: function (el, options, category) {
_getDragManager(this, category).droppable(el, options);
},
isAlreadyDraggable: function (el) {
return el._katavorioDrag != null;
},
isDragSupported: function (el, options) {
return true;
},
isDropSupported: function (el, options) {
return true;
},
isElementDraggable: function (el) {
el = _jp.getElement(el);
return el._katavorioDrag && el._katavorioDrag.isEnabled();
},
getDragObject: function (eventArgs) {
return eventArgs[0].drag.getDragElement();
},
getDragScope: function (el) {
return el._katavorioDrag && el._katavorioDrag.scopes.join(" ") || "";
},
getDropEvent: function (args) {
return args[0].e;
},
getUIPosition: function (eventArgs, zoom) {
// here the position reported to us by Katavorio is relative to the element's offsetParent. For top
// level nodes that is fine, but if we have a nested draggable then its offsetParent is actually
// not going to be the jsplumb container; it's going to be some child of that element. In that case
// we want to adjust the UI position to account for the offsetParent's position relative to the Container
// origin.
var el = eventArgs[0].el;
if (el.offsetParent == null) {
return null;
}
var finalPos = eventArgs[0].finalPos || eventArgs[0].pos;
var p = { left:finalPos[0], top:finalPos[1] };
if (el._katavorioDrag && el.offsetParent !== this.getContainer()) {
var oc = this.getOffset(el.offsetParent);
p.left += oc.left;
p.top += oc.top;
}
return p;
},
setDragFilter: function (el, filter, _exclude) {
if (el._katavorioDrag) {
el._katavorioDrag.setFilter(filter, _exclude);
}
},
setElementDraggable: function (el, draggable) {
el = _jp.getElement(el);
if (el._katavorioDrag) {
el._katavorioDrag.setEnabled(draggable);
}
},
setDragScope: function (el, scope) {
if (el._katavorioDrag) {
el._katavorioDrag.k.setDragScope(el, scope);
}
},
setDropScope:function(el, scope) {
if (el._katavorioDrop && el._katavorioDrop.length > 0) {
el._katavorioDrop[0].k.setDropScope(el, scope);
}
},
addToPosse:function(el, spec) {
var specs = Array.prototype.slice.call(arguments, 1);
var dm = _getDragManager(this);
_jp.each(el, function(_el) {
_el = [ _jp.getElement(_el) ];
_el.push.apply(_el, specs );
dm.addToPosse.apply(dm, _el);
});
},
setPosse:function(el, spec) {
var specs = Array.prototype.slice.call(arguments, 1);
var dm = _getDragManager(this);
_jp.each(el, function(_el) {
_el = [ _jp.getElement(_el) ];
_el.push.apply(_el, specs );
dm.setPosse.apply(dm, _el);
});
},
removeFromPosse:function(el, posseId) {
var specs = Array.prototype.slice.call(arguments, 1);
var dm = _getDragManager(this);
_jp.each(el, function(_el) {
_el = [ _jp.getElement(_el) ];
_el.push.apply(_el, specs );
dm.removeFromPosse.apply(dm, _el);
});
},
removeFromAllPosses:function(el) {
var dm = _getDragManager(this);
_jp.each(el, function(_el) { dm.removeFromAllPosses(_jp.getElement(_el)); });
},
setPosseState:function(el, posseId, state) {
var dm = _getDragManager(this);
_jp.each(el, function(_el) { dm.setPosseState(_jp.getElement(_el), posseId, state); });
},
dragEvents: {
'start': 'start', 'stop': 'stop', 'drag': 'drag', 'step': 'step',
'over': 'over', 'out': 'out', 'drop': 'drop', 'complete': 'complete',
'beforeStart':'beforeStart'
},
animEvents: {
'step': "step", 'complete': 'complete'
},
stopDrag: function (el) {
if (el._katavorioDrag) {
el._katavorioDrag.abort();
}
},
addToDragSelection: function (spec) {
_getDragManager(this).select(spec);
},
removeFromDragSelection: function (spec) {
_getDragManager(this).deselect(spec);
},
clearDragSelection: function () {
_getDragManager(this).deselectAll();
},
trigger: function (el, event, originalEvent, payload) {
this.getEventManager().trigger(el, event, originalEvent, payload);
},
doReset:function() {
// look for katavorio instances and reset each one if found.
for (var key in this) {
if (key.indexOf("_katavorio_") === 0) {
this[key].reset();
}
}
}
});
var ready = function (f) {
var _do = function () {
if (/complete|loaded|interactive/.test(document.readyState) && typeof(document.body) !== "undefined" && document.body != null) {
f();
}
else {
setTimeout(_do, 9);
}
};
_do();
};
ready(_jp.init);
}).call(typeof window !== 'undefined' ? window : this);
| mit |
unaio/una | modules/boonex/decorous/updates/11.0.3_12.0.0/source/classes/BxDecorousStudioPage.php | 2515 | <?php defined('BX_DOL') or die('hack attempt');
/**
* Copyright (c) UNA, Inc - https://una.io
* MIT License - https://opensource.org/licenses/MIT
*
* @defgroup Decorous Decorous template
* @ingroup UnaModules
*
* @{
*/
define('BX_DECOROUS_STUDIO_TEMPL_TYPE_STYLES', 'styles');
class BxDecorousStudioPage extends BxTemplStudioDesign
{
function __construct($sModule, $mixedPageName, $sPage = "")
{
$this->MODULE = 'bx_decorous';
parent::__construct($sModule, $mixedPageName, $sPage);
$this->aMenuItems[BX_DECOROUS_STUDIO_TEMPL_TYPE_STYLES] = array('title' => '_bx_decorous_lmi_cpt_styles', 'icon' => 'paint-brush');
unset($this->aMenuItems[BX_DOL_STUDIO_TEMPL_TYPE_LOGO]);
}
protected function getSettings($mixedCategory = '', $sMix = '')
{
return parent::getSettings('bx_decorous_system', $sMix);
}
protected function getStyles($sMix = '')
{
$oTemplate = BxDolStudioTemplate::getInstance();
$sPrefix = $this->MODULE;
$aCategories = array(
$sPrefix . '_styles_general',
$sPrefix . '_styles_header',
$sPrefix . '_styles_footer',
$sPrefix . '_styles_body',
$sPrefix . '_styles_cover',
$sPrefix . '_styles_block',
$sPrefix . '_styles_card',
$sPrefix . '_styles_popup',
$sPrefix . '_styles_menu_main',
$sPrefix . '_styles_menu_account',
$sPrefix . '_styles_menu_add',
$sPrefix . '_styles_menu_page',
$sPrefix . '_styles_menu_slide',
$sPrefix . '_styles_form',
$sPrefix . '_styles_large_button',
$sPrefix . '_styles_small_button',
$sPrefix . '_styles_font',
$sPrefix . '_styles_custom',
$sPrefix . '_viewport_tablet',
$sPrefix . '_viewport_mobile'
);
$oPage = new BxTemplStudioSettings($this->sModule, $aCategories, $sMix);
$oPage->enableReadOnly(true);
$oPage->enableMixes(true);
$oTemplate->addJs(array('codemirror/codemirror.min.js'));
$oTemplate->addCss(BX_DIRECTORY_PATH_PLUGINS_PUBLIC . 'codemirror/|codemirror.css');
return BxDolStudioTemplate::getInstance()->parseHtmlByName('design.html', array(
'content' => $oPage->getFormCode(),
'js_content' => $this->getPageJsCode(array(
'sCodeMirror' => "textarea[name='" . $sPrefix . "_styles_custom']"
))
));
}
}
/** @} */
| mit |
ar13101085/senso_web | CI_phpStorm.php | 8894 | <?php die('This file is not really here!');
/**
* ------------- DO NOT UPLOAD THIS FILE TO LIVE SERVER ---------------------
*
* Implements code completion for CodeIgniter in phpStorm
* phpStorm indexes all class constructs, so if this file is in the project it will be loaded.
*
*
* This property values were borrowed from another site on the internet
* This is just a better way to implement it, rather than editing core CI files
*
* PHP version 5
*
* LICENSE: GPL http://www.gnu.org/copyleft/gpl.html
*
* Created 1/28/12, 11:06 PM
*
* @category
* @package CodeIgniter CI_phpStorm.php
* @author Jeff Behnke
* @copyright 2009-11 Valid-Webs.com
* @license GPL http://www.gnu.org/copyleft/gpl.html
* @version 2012.02.03
*/
/**
* @property CI_DB_active_record $db This is the platform-independent base Active Record implementation class.
* @property CI_DB_forge $dbforge Database Utility Class
* @property CI_Benchmark $benchmark This class enables you to mark points and calculate the time difference between them.<br /> Memory consumption can also be displayed.
* @property CI_Calendar $calendar This class enables the creation of calendars
* @property CI_Cart $cart Shopping Cart Class
* @property CI_Config $config This class contains functions that enable config files to be managed
* @property CI_Controller $controller This class object is the super class that every library in.<br />CodeIgniter will be assigned to.
* @property CI_Email $email Permits email to be sent using Mail, Sendmail, or SMTP.
* @property CI_Encrypt $encrypt Provides two-way keyed encoding using XOR Hashing and Mcrypt
* @property CI_Exceptions $exceptions Exceptions Class
* @property CI_Form_validation $form_validation Form Validation Class
* @property CI_Ftp $ftp FTP Class
* @property CI_Hooks $hooks //dead
* @property CI_Image_lib $image_lib Image Manipulation class
* @property CI_Input $input Pre-processes global input data for security
* @property CI_Lang $lang Language Class
* @property CI_Loader $load Loads views and files
* @property CI_Log $log Logging Class
* @property CI_Model $model CodeIgniter Model Class
* @property CI_Output $output Responsible for sending final output to browser
* @property CI_Pagination $pagination Pagination Class
* @property CI_Parser $parser Parses pseudo-variables contained in the specified template view,<br />replacing them with the data in the second param
* @property CI_Profiler $profiler This class enables you to display benchmark, query, and other data<br />in order to help with debugging and optimization.
* @property CI_Router $router Parses URIs and determines routing
* @property CI_Session $session Session Class
* @property CI_Sha1 $sha1 Provides 160 bit hashing using The Secure Hash Algorithm
* @property CI_Table $table HTML table generation<br />Lets you create tables manually or from database result objects, or arrays.
* @property CI_Trackback $trackback Trackback Sending/Receiving Class
* @property CI_Typography $typography Typography Class
* @property CI_Unit_test $unit_test Simple testing class
* @property CI_Upload $upload File Uploading Class
* @property CI_URI $uri Parses URIs and determines routing
* @property CI_User_agent $user_agent Identifies the platform, browser, robot, or mobile devise of the browsing agent
* @property CI_Validation $validation //dead
* @property CI_Xmlrpc $xmlrpc XML-RPC request handler class
* @property CI_Xmlrpcs $xmlrpcs XML-RPC server class
* @property CI_Zip $zip Zip Compression Class
* @property CI_Javascript $javascript Javascript Class
* @property CI_Jquery $jquery Jquery Class
* @property CI_Utf8 $utf8 Provides support for UTF-8 environments
* @property CI_Security $security Security Class, xss, csrf, etc...
* @property CI_Driver_Library $driver CodeIgniter Driver Library Class
* @property CI_Cache $cache CodeIgniter Caching Class
* @method static CI_Controller get_instance() CodeIgniter CI_Controller instance class
*/
class CI_Controller extends my_models
{
public function __construct() {} //This default return construct as set
}
/**
* @property CI_DB_active_record $db This is the platform-independent base Active Record implementation class.
* @property CI_DB_forge $dbforge Database Utility Class
* @property CI_Benchmark $benchmark This class enables you to mark points and calculate the time difference between them.<br /> Memory consumption can also be displayed.
* @property CI_Calendar $calendar This class enables the creation of calendars
* @property CI_Cart $cart Shopping Cart Class
* @property CI_Config $config This class contains functions that enable config files to be managed
* @property CI_Controller $controller This class object is the super class that every library in.<br />CodeIgniter will be assigned to.
* @property CI_Email $email Permits email to be sent using Mail, Sendmail, or SMTP.
* @property CI_Encrypt $encrypt Provides two-way keyed encoding using XOR Hashing and Mcrypt
* @property CI_Exceptions $exceptions Exceptions Class
* @property CI_Form_validation $form_validation Form Validation Class
* @property CI_Ftp $ftp FTP Class
* @property CI_Hooks $hooks //dead
* @property CI_Image_lib $image_lib Image Manipulation class
* @property CI_Input $input Pre-processes global input data for security
* @property CI_Lang $lang Language Class
* @property CI_Loader $load Loads views and files
* @property CI_Log $log Logging Class
* @property CI_Model $model CodeIgniter Model Class
* @property CI_Output $output Responsible for sending final output to browser
* @property CI_Pagination $pagination Pagination Class
* @property CI_Parser $parser Parses pseudo-variables contained in the specified template view,<br />replacing them with the data in the second param
* @property CI_Profiler $profiler This class enables you to display benchmark, query, and other data<br />in order to help with debugging and optimization.
* @property CI_Router $router Parses URIs and determines routing
* @property CI_Session $session Session Class
* @property CI_Sha1 $sha1 Provides 160 bit hashing using The Secure Hash Algorithm
* @property CI_Table $table HTML table generation<br />Lets you create tables manually or from database result objects, or arrays.
* @property CI_Trackback $trackback Trackback Sending/Receiving Class
* @property CI_Typography $typography Typography Class
* @property CI_Unit_test $unit_test Simple testing class
* @property CI_Upload $upload File Uploading Class
* @property CI_URI $uri Parses URIs and determines routing
* @property CI_User_agent $user_agent Identifies the platform, browser, robot, or mobile devise of the browsing agent
* @property CI_Validation $validation //dead
* @property CI_Xmlrpc $xmlrpc XML-RPC request handler class
* @property CI_Xmlrpcs $xmlrpcs XML-RPC server class
* @property CI_Zip $zip Zip Compression Class
* @property CI_Javascript $javascript Javascript Class
* @property CI_Jquery $jquery Jquery Class
* @property CI_Utf8 $utf8 Provides support for UTF-8 environments
* @property CI_Security $security Security Class, xss, csrf, etc...
* @property CI_Driver_Library $driver CodeIgniter Driver Library Class
* @property CI_Cache $cache CodeIgniter Caching Class
*/
class CI_Model extends my_models
{
public function __construct() {} //This default return construct as set
}
| mit |
extend1994/cdnjs | ajax/libs/highcharts/7.0.2/es-modules/modules/oldie.src.js | 51352 | /* *
* (c) 2010-2019 Torstein Honsi
*
* Support for old IE browsers (6, 7 and 8) in Highcharts v6+.
*
* License: www.highcharts.com/license
*/
'use strict';
import H from '../parts/Globals.js';
import '../parts/Utilities.js';
import '../parts/SvgRenderer.js';
var VMLRenderer,
VMLRendererExtension,
VMLElement,
Chart = H.Chart,
createElement = H.createElement,
css = H.css,
defined = H.defined,
deg2rad = H.deg2rad,
discardElement = H.discardElement,
doc = H.doc,
erase = H.erase,
extend = H.extend,
extendClass = H.extendClass,
isArray = H.isArray,
isNumber = H.isNumber,
isObject = H.isObject,
merge = H.merge,
noop = H.noop,
pick = H.pick,
pInt = H.pInt,
svg = H.svg,
SVGElement = H.SVGElement,
SVGRenderer = H.SVGRenderer,
win = H.win;
/**
* Path to the pattern image required by VML browsers in order to
* draw radial gradients.
*
* @type {string}
* @default http://code.highcharts.com/{version}/gfx/vml-radial-gradient.png
* @since 2.3.0
* @apioption global.VMLRadialGradientURL
*/
H.getOptions().global.VMLRadialGradientURL =
'http://code.highcharts.com/@product.version@/gfx/vml-radial-gradient.png';
// Utilites
if (doc && !doc.defaultView) {
H.getStyle = function (el, prop) {
var val,
alias = { width: 'clientWidth', height: 'clientHeight' }[prop];
if (el.style[prop]) {
return H.pInt(el.style[prop]);
}
if (prop === 'opacity') {
prop = 'filter';
}
// Getting the rendered width and height
if (alias) {
el.style.zoom = 1;
return Math.max(el[alias] - 2 * H.getStyle(el, 'padding'), 0);
}
val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b) {
return b.toUpperCase();
})];
if (prop === 'filter') {
val = val.replace(
/alpha\(opacity=([0-9]+)\)/,
function (a, b) {
return b / 100;
}
);
}
return val === '' ? 1 : H.pInt(val);
};
}
if (!svg) {
// Prevent wrapping from creating false offsetWidths in export in legacy IE.
// This applies only to charts for export, where IE runs the SVGRenderer
// instead of the VMLRenderer
// (#1079, #1063)
H.addEvent(SVGElement, 'afterInit', function () {
if (this.element.nodeName === 'text') {
this.css({
position: 'absolute'
});
}
});
/**
* Old IE override for pointer normalize, adds chartX and chartY to event
* arguments.
*
* @ignore
* @function Highcharts.Pointer#normalize
*
* @param {global.Event} e
*
* @param {boolean} [chartPosition=false]
*/
H.Pointer.prototype.normalize = function (e, chartPosition) {
e = e || win.event;
if (!e.target) {
e.target = e.srcElement;
}
// Get mouse position
if (!chartPosition) {
this.chartPosition = chartPosition = H.offset(this.chart.container);
}
return H.extend(e, {
// #2005, #2129: the second case is for IE10 quirks mode within
// framesets
chartX: Math.round(Math.max(e.x, e.clientX - chartPosition.left)),
chartY: Math.round(e.y)
});
};
/**
* Further sanitize the mock-SVG that is generated when exporting charts in
* oldIE.
*
* @private
* @function Highcharts.Chart#ieSanitizeSVG
*/
Chart.prototype.ieSanitizeSVG = function (svg) {
svg = svg
.replace(/<IMG /g, '<image ')
.replace(/<(\/?)TITLE>/g, '<$1title>')
.replace(/height=([^" ]+)/g, 'height="$1"')
.replace(/width=([^" ]+)/g, 'width="$1"')
.replace(/hc-svg-href="([^"]+)">/g, 'xlink:href="$1"/>')
.replace(/ id=([^" >]+)/g, ' id="$1"') // #4003
.replace(/class=([^" >]+)/g, 'class="$1"')
.replace(/ transform /g, ' ')
.replace(/:(path|rect)/g, '$1')
.replace(/style="([^"]+)"/g, function (s) {
return s.toLowerCase();
});
return svg;
};
/**
* VML namespaces can't be added until after complete. Listening
* for Perini's doScroll hack is not enough.
*
* @private
* @function Highcharts.Chart#isReadyToRender
*/
Chart.prototype.isReadyToRender = function () {
var chart = this;
// Note: win == win.top is required
if (
!svg &&
(
win == win.top && // eslint-disable-line eqeqeq
doc.readyState !== 'complete'
)
) {
doc.attachEvent('onreadystatechange', function () {
doc.detachEvent('onreadystatechange', chart.firstRender);
if (doc.readyState === 'complete') {
chart.firstRender();
}
});
return false;
}
return true;
};
// IE compatibility hack for generating SVG content that it doesn't really
// understand. Used by the exporting module.
if (!doc.createElementNS) {
doc.createElementNS = function (ns, tagName) {
return doc.createElement(tagName);
};
}
/**
* Old IE polyfill for addEventListener, called from inside the addEvent
* function.
*
* @private
* @function Highcharts.addEventListenerPolyfill
*
* @param {string} type
*
* @param {Function} fn
*/
H.addEventListenerPolyfill = function (type, fn) {
var el = this;
function wrappedFn(e) {
e.target = e.srcElement || win; // #2820
fn.call(el, e);
}
if (el.attachEvent) {
if (!el.hcEventsIE) {
el.hcEventsIE = {};
}
// unique function string (#6746)
if (!fn.hcKey) {
fn.hcKey = H.uniqueKey();
}
// Link wrapped fn with original fn, so we can get this in
// removeEvent
el.hcEventsIE[fn.hcKey] = wrappedFn;
el.attachEvent('on' + type, wrappedFn);
}
};
/**
* @private
* @function Highcharts.removeEventListenerPolyfill
*
* @param {string} type
*
* @param {Function} fn
*/
H.removeEventListenerPolyfill = function (type, fn) {
if (this.detachEvent) {
fn = this.hcEventsIE[fn.hcKey];
this.detachEvent('on' + type, fn);
}
};
/**
* The VML element wrapper.
*
* @private
* @class
* @name Highcharts.VMLElement
*
* @augments Highcharts.SVGElement
*/
VMLElement = {
docMode8: doc && doc.documentMode === 8,
/**
* Initialize a new VML element wrapper. It builds the markup as a
* string to minimize DOM traffic.
*
* @function Highcharts.VMLElement#init
*
* @param {object} renderer
*
* @param {object} nodeName
*/
init: function (renderer, nodeName) {
var wrapper = this,
markup = ['<', nodeName, ' filled="f" stroked="f"'],
style = ['position: ', 'absolute', ';'],
isDiv = nodeName === 'div';
// divs and shapes need size
if (nodeName === 'shape' || isDiv) {
style.push('left:0;top:0;width:1px;height:1px;');
}
style.push('visibility: ', isDiv ? 'hidden' : 'visible');
markup.push(' style="', style.join(''), '"/>');
// create element with default attributes and style
if (nodeName) {
markup = isDiv || nodeName === 'span' || nodeName === 'img' ?
markup.join('') :
renderer.prepVML(markup);
wrapper.element = createElement(markup);
}
wrapper.renderer = renderer;
},
/**
* Add the node to the given parent
*
* @function Highcharts.VMLElement
*
* @param {object} parent
*/
add: function (parent) {
var wrapper = this,
renderer = wrapper.renderer,
element = wrapper.element,
box = renderer.box,
inverted = parent && parent.inverted,
// get the parent node
parentNode = parent ?
parent.element || parent :
box;
if (parent) {
this.parentGroup = parent;
}
// if the parent group is inverted, apply inversion on all children
if (inverted) { // only on groups
renderer.invertChild(element, parentNode);
}
// append it
parentNode.appendChild(element);
// align text after adding to be able to read offset
wrapper.added = true;
if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) {
wrapper.updateTransform();
}
// fire an event for internal hooks
if (wrapper.onAdd) {
wrapper.onAdd();
}
// IE8 Standards can't set the class name before the element is
// appended
if (this.className) {
this.attr('class', this.className);
}
return wrapper;
},
/**
* VML always uses htmlUpdateTransform
*
* @function Highcharts.VMLElement#updateTransform
*/
updateTransform: SVGElement.prototype.htmlUpdateTransform,
/**
* Set the rotation of a span with oldIE's filter
*
* @function Highcharts.VMLElement#setSpanRotation
*/
setSpanRotation: function () {
// Adjust for alignment and rotation. Rotation of useHTML content is
// not yet implemented but it can probably be implemented for
// Firefox 3.5+ on user request. FF3.5+ has support for CSS3
// transform. The getBBox method also needs to be updated to
// compensate for the rotation, like it currently does for SVG.
// Test case: https://jsfiddle.net/highcharts/Ybt44/
var rotation = this.rotation,
costheta = Math.cos(rotation * deg2rad),
sintheta = Math.sin(rotation * deg2rad);
css(this.element, {
filter: rotation ? [
'progid:DXImageTransform.Microsoft.Matrix(M11=', costheta,
', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta,
', sizingMethod=\'auto expand\')'
].join('') : 'none'
});
},
/**
* Get the positioning correction for the span after rotating.
*
* @function Highcharts.VMLElement#getSpanCorrection
*/
getSpanCorrection: function (
width,
baseline,
alignCorrection,
rotation,
align
) {
var costheta = rotation ? Math.cos(rotation * deg2rad) : 1,
sintheta = rotation ? Math.sin(rotation * deg2rad) : 0,
height = pick(this.elemHeight, this.element.offsetHeight),
quad,
nonLeft = align && align !== 'left';
// correct x and y
this.xCorr = costheta < 0 && -width;
this.yCorr = sintheta < 0 && -height;
// correct for baseline and corners spilling out after rotation
quad = costheta * sintheta < 0;
this.xCorr += (
sintheta *
baseline *
(quad ? 1 - alignCorrection : alignCorrection)
);
this.yCorr -= (
costheta *
baseline *
(rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1)
);
// correct for the length/height of the text
if (nonLeft) {
this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1);
if (rotation) {
this.yCorr -= (
height *
alignCorrection *
(sintheta < 0 ? -1 : 1)
);
}
css(this.element, {
textAlign: align
});
}
},
/**
* Converts a subset of an SVG path definition to its VML counterpart.
* Takes an array as the parameter and returns a string.
*
* @function Highcharts.VMLElement#pathToVML
*/
pathToVML: function (value) {
// convert paths
var i = value.length,
path = [];
while (i--) {
// Multiply by 10 to allow subpixel precision.
// Substracting half a pixel seems to make the coordinates
// align with SVG, but this hasn't been tested thoroughly
if (isNumber(value[i])) {
path[i] = Math.round(value[i] * 10) - 5;
} else if (value[i] === 'Z') { // close the path
path[i] = 'x';
} else {
path[i] = value[i];
// When the start X and end X coordinates of an arc are too
// close, they are rounded to the same value above. In this
// case, substract or add 1 from the end X and Y positions.
// #186, #760, #1371, #1410.
if (
value.isArc &&
(value[i] === 'wa' || value[i] === 'at')
) {
// Start and end X
if (path[i + 5] === path[i + 7]) {
path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1;
}
// Start and end Y
if (path[i + 6] === path[i + 8]) {
path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1;
}
}
}
}
return path.join(' ') || 'x';
},
/**
* Set the element's clipping to a predefined rectangle
*
* @function Highcharts.VMLElement#clip
*
* @param {object} clipRect
*/
clip: function (clipRect) {
var wrapper = this,
clipMembers,
cssRet;
if (clipRect) {
clipMembers = clipRect.members;
// Ensure unique list of elements (#1258)
erase(clipMembers, wrapper);
clipMembers.push(wrapper);
wrapper.destroyClip = function () {
erase(clipMembers, wrapper);
};
cssRet = clipRect.getCSS(wrapper);
} else {
if (wrapper.destroyClip) {
wrapper.destroyClip();
}
cssRet = {
clip: wrapper.docMode8 ? 'inherit' : 'rect(auto)'
}; // #1214
}
return wrapper.css(cssRet);
},
/**
* Set styles for the element
*
* @function Highcharts.VMLElement#css
*
* @param {Highcharts.SVGAttributes} styles
*/
css: SVGElement.prototype.htmlCss,
/**
* Removes a child either by removeChild or move to garbageBin.
* Issue 490; in VML removeChild results in Orphaned nodes according to
* sIEve, discardElement does not.
*
* @function Highcharts.VMLElement#safeRemoveChild
*/
safeRemoveChild: function (element) {
// discardElement will detach the node from its parent before
// attaching it to the garbage bin. Therefore it is important that
// the node is attached and have parent.
if (element.parentNode) {
discardElement(element);
}
},
/**
* Extend element.destroy by removing it from the clip members array
*
* @function Highcharts.VMLElement#destroy
*/
destroy: function () {
if (this.destroyClip) {
this.destroyClip();
}
return SVGElement.prototype.destroy.apply(this);
},
/**
* Add an event listener. VML override for normalizing event parameters.
*
* @function Highcharts.VMLElement#on
*
* @param {string} eventType
*
* @param {Function} handler
*/
on: function (eventType, handler) {
// simplest possible event model for internal use
this.element['on' + eventType] = function () {
var evt = win.event;
evt.target = evt.srcElement;
handler(evt);
};
return this;
},
/**
* In stacked columns, cut off the shadows so that they don't overlap
*
* @function Highcharts.VMLElement#cutOffPath
*/
cutOffPath: function (path, length) {
var len;
// The extra comma tricks the trailing comma remover in
// "gulp scripts" task
path = path.split(/[ ,]/);
len = path.length;
if (len === 9 || len === 11) {
path[len - 4] = path[len - 2] =
pInt(path[len - 2]) - 10 * length;
}
return path.join(' ');
},
/**
* Apply a drop shadow by copying elements and giving them different
* strokes.
*
* @function Highcharts.VMLElement#shadow
*
* @param {boolean|Highcharts.ShadowOptionsObject} shadowOptions
*
* @param {boolean} group
*
* @param {boolean} cutOff
*/
shadow: function (shadowOptions, group, cutOff) {
var shadows = [],
i,
element = this.element,
renderer = this.renderer,
shadow,
elemStyle = element.style,
markup,
path = element.path,
strokeWidth,
modifiedPath,
shadowWidth,
shadowElementOpacity;
// some times empty paths are not strings
if (path && typeof path.value !== 'string') {
path = 'x';
}
modifiedPath = path;
if (shadowOptions) {
shadowWidth = pick(shadowOptions.width, 3);
shadowElementOpacity =
(shadowOptions.opacity || 0.15) / shadowWidth;
for (i = 1; i <= 3; i++) {
strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
// Cut off shadows for stacked column items
if (cutOff) {
modifiedPath = this.cutOffPath(
path.value,
strokeWidth + 0.5
);
}
markup = [
'<shape isShadow="true" strokeweight="', strokeWidth,
'" filled="false" path="', modifiedPath,
'" coordsize="10 10" style="', element.style.cssText,
'" />'
];
shadow = createElement(
renderer.prepVML(markup),
null, {
left: pInt(elemStyle.left) +
pick(shadowOptions.offsetX, 1),
top: pInt(elemStyle.top) +
pick(shadowOptions.offsetY, 1)
}
);
if (cutOff) {
shadow.cutOff = strokeWidth + 1;
}
// apply the opacity
markup = [
'<stroke color="',
shadowOptions.color || '#000000',
'" opacity="', shadowElementOpacity * i, '"/>'];
createElement(renderer.prepVML(markup), null, null, shadow);
// insert it
if (group) {
group.element.appendChild(shadow);
} else {
element.parentNode.insertBefore(shadow, element);
}
// record it
shadows.push(shadow);
}
this.shadows = shadows;
}
return this;
},
updateShadows: noop, // Used in SVG only
setAttr: function (key, value) {
if (this.docMode8) { // IE8 setAttribute bug
this.element[key] = value;
} else {
this.element.setAttribute(key, value);
}
},
getAttr: function (key) {
if (this.docMode8) { // IE8 setAttribute bug
return this.element[key];
}
return this.element.getAttribute(key);
},
classSetter: function (value) {
// IE8 Standards mode has problems retrieving the className unless
// set like this. IE8 Standards can't set the class name before the
// element is appended.
(this.added ? this.element : this).className = value;
},
dashstyleSetter: function (value, key, element) {
var strokeElem = element.getElementsByTagName('stroke')[0] ||
createElement(
this.renderer.prepVML(['<stroke/>']),
null,
null,
element
);
strokeElem[key] = value || 'solid';
// Because changing stroke-width will change the dash length and
// cause an epileptic effect
this[key] = value;
},
dSetter: function (value, key, element) {
var i,
shadows = this.shadows;
value = value || [];
// Used in getter for animation
this.d = value.join && value.join(' ');
element.path = value = this.pathToVML(value);
// update shadows
if (shadows) {
i = shadows.length;
while (i--) {
shadows[i].path = shadows[i].cutOff ?
this.cutOffPath(value, shadows[i].cutOff) :
value;
}
}
this.setAttr(key, value);
},
fillSetter: function (value, key, element) {
var nodeName = element.nodeName;
if (nodeName === 'SPAN') { // text color
element.style.color = value;
} else if (nodeName !== 'IMG') { // #1336
element.filled = value !== 'none';
this.setAttr(
'fillcolor',
this.renderer.color(value, element, key, this)
);
}
},
'fill-opacitySetter': function (value, key, element) {
createElement(
this.renderer.prepVML(
['<', key.split('-')[0], ' opacity="', value, '"/>']
),
null,
null,
element
);
},
// Don't bother - animation is too slow and filters introduce artifacts
opacitySetter: noop,
rotationSetter: function (value, key, element) {
var style = element.style;
this[key] = style[key] = value; // style is for #1873
// Correction for the 1x1 size of the shape container. Used in gauge
// needles.
style.left = -Math.round(Math.sin(value * deg2rad) + 1) + 'px';
style.top = Math.round(Math.cos(value * deg2rad)) + 'px';
},
strokeSetter: function (value, key, element) {
this.setAttr(
'strokecolor',
this.renderer.color(value, element, key, this)
);
},
'stroke-widthSetter': function (value, key, element) {
element.stroked = !!value; // VML "stroked" attribute
this[key] = value; // used in getter, issue #113
if (isNumber(value)) {
value += 'px';
}
this.setAttr('strokeweight', value);
},
titleSetter: function (value, key) {
this.setAttr(key, value);
},
visibilitySetter: function (value, key, element) {
// Handle inherited visibility
if (value === 'inherit') {
value = 'visible';
}
// Let the shadow follow the main element
if (this.shadows) {
this.shadows.forEach(function (shadow) {
shadow.style[key] = value;
});
}
// Instead of toggling the visibility CSS property, move the div out
// of the viewport. This works around #61 and #586
if (element.nodeName === 'DIV') {
value = value === 'hidden' ? '-999em' : 0;
// In order to redraw, IE7 needs the div to be visible when
// tucked away outside the viewport. So the visibility is
// actually opposite of the expected value. This applies to the
// tooltip only.
if (!this.docMode8) {
element.style[key] = value ? 'visible' : 'hidden';
}
key = 'top';
}
element.style[key] = value;
},
xSetter: function (value, key, element) {
this[key] = value; // used in getter
if (key === 'x') {
key = 'left';
} else if (key === 'y') {
key = 'top';
}
// clipping rectangle special
if (this.updateClipping) {
// the key is now 'left' or 'top' for 'x' and 'y'
this[key] = value;
this.updateClipping();
} else {
// normal
element.style[key] = value;
}
},
zIndexSetter: function (value, key, element) {
element.style[key] = value;
},
fillGetter: function () {
return this.getAttr('fillcolor') || '';
},
strokeGetter: function () {
return this.getAttr('strokecolor') || '';
},
// #7850
classGetter: function () {
return this.getAttr('className') || '';
}
};
VMLElement['stroke-opacitySetter'] = VMLElement['fill-opacitySetter'];
H.VMLElement = VMLElement = extendClass(SVGElement, VMLElement);
// Some shared setters
VMLElement.prototype.ySetter =
VMLElement.prototype.widthSetter =
VMLElement.prototype.heightSetter =
VMLElement.prototype.xSetter;
/**
* The VML renderer
*
* @private
* @class
* @name Highcharts.VMLRenderer
*
* @augments Highcharts.SVGRenderer
*/
VMLRendererExtension = { // inherit SVGRenderer
Element: VMLElement,
isIE8: win.navigator.userAgent.indexOf('MSIE 8.0') > -1,
/**
* Initialize the VMLRenderer.
*
* @function Highcharts.VMLRenderer#init
*
* @param {object} container
*
* @param {number} width
*
* @param {number} height
*/
init: function (container, width, height) {
var renderer = this,
boxWrapper,
box,
css;
renderer.alignedObjects = [];
boxWrapper = renderer.createElement('div')
.css({ position: 'relative' });
box = boxWrapper.element;
container.appendChild(boxWrapper.element);
// generate the containing box
renderer.isVML = true;
renderer.box = box;
renderer.boxWrapper = boxWrapper;
renderer.gradients = {};
renderer.cache = {}; // Cache for numerical bounding boxes
renderer.cacheKeys = [];
renderer.imgCount = 0;
renderer.setSize(width, height, false);
// The only way to make IE6 and IE7 print is to use a global
// namespace. However, with IE8 the only way to make the dynamic
// shapes visible in screen and print mode seems to be to add the
// xmlns attribute and the behaviour style inline.
if (!doc.namespaces.hcv) {
doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml');
// Setup default CSS (#2153, #2368, #2384)
css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' +
'{ behavior:url(#default#VML); display: inline-block; } ';
try {
doc.createStyleSheet().cssText = css;
} catch (e) {
doc.styleSheets[0].cssText += css;
}
}
},
/**
* Detect whether the renderer is hidden. This happens when one of the
* parent elements has display: none
*
* @function Highcharts.VMLRenderer#isHidden
*/
isHidden: function () {
return !this.box.offsetWidth;
},
/**
* Define a clipping rectangle. In VML it is accomplished by storing the
* values for setting the CSS style to all associated members.
*
* @function Highcharts.VMLRenderer#clipRect
*
* @param {number} x
*
* @param {number} y
*
* @param {number} width
*
* @param {number} height
*/
clipRect: function (x, y, width, height) {
// create a dummy element
var clipRect = this.createElement(),
isObj = isObject(x);
// mimic a rectangle with its style object for automatic updating in
// attr
return extend(clipRect, {
members: [],
count: 0,
left: (isObj ? x.x : x) + 1,
top: (isObj ? x.y : y) + 1,
width: (isObj ? x.width : width) - 1,
height: (isObj ? x.height : height) - 1,
getCSS: function (wrapper) {
var element = wrapper.element,
nodeName = element.nodeName,
isShape = nodeName === 'shape',
inverted = wrapper.inverted,
rect = this,
top = rect.top - (isShape ? element.offsetTop : 0),
left = rect.left,
right = left + rect.width,
bottom = top + rect.height,
ret = {
clip: 'rect(' +
Math.round(inverted ? left : top) + 'px,' +
Math.round(inverted ? bottom : right) + 'px,' +
Math.round(inverted ? right : bottom) + 'px,' +
Math.round(inverted ? top : left) + 'px)'
};
// issue 74 workaround
if (!inverted && wrapper.docMode8 && nodeName === 'DIV') {
extend(ret, {
width: right + 'px',
height: bottom + 'px'
});
}
return ret;
},
// used in attr and animation to update the clipping of all
// members
updateClipping: function () {
clipRect.members.forEach(function (member) {
// Member.element is falsy on deleted series, like in
// stock/members/series-remove demo. Should be removed
// from members, but this will do.
if (member.element) {
member.css(clipRect.getCSS(member));
}
});
}
});
},
/**
* Take a color and return it if it's a string, make it a gradient if
* it's a gradient configuration object, and apply opacity.
*
* @function Highcharts.VMLRenderer#color
*
* @param {object} color
* The color or config object
*/
color: function (color, elem, prop, wrapper) {
var renderer = this,
colorObject,
regexRgba = /^rgba/,
markup,
fillType,
ret = 'none';
// Check for linear or radial gradient
if (color && color.linearGradient) {
fillType = 'gradient';
} else if (color && color.radialGradient) {
fillType = 'pattern';
}
if (fillType) {
var stopColor,
stopOpacity,
gradient = color.linearGradient || color.radialGradient,
x1,
y1,
x2,
y2,
opacity1,
opacity2,
color1,
color2,
fillAttr = '',
stops = color.stops,
firstStop,
lastStop,
colors = [],
addFillNode = function () {
// Add the fill subnode. When colors attribute is used,
// the meanings of opacity and o:opacity2 are reversed.
markup = ['<fill colors="' + colors.join(',') +
'" opacity="', opacity2, '" o:opacity2="',
opacity1, '" type="', fillType, '" ', fillAttr,
'focus="100%" method="any" />'];
createElement(
renderer.prepVML(markup),
null,
null,
elem
);
};
// Extend from 0 to 1
firstStop = stops[0];
lastStop = stops[stops.length - 1];
if (firstStop[0] > 0) {
stops.unshift([
0,
firstStop[1]
]);
}
if (lastStop[0] < 1) {
stops.push([
1,
lastStop[1]
]);
}
// Compute the stops
stops.forEach(function (stop, i) {
if (regexRgba.test(stop[1])) {
colorObject = H.color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
// Build the color attribute
colors.push((stop[0] * 100) + '% ' + stopColor);
// Only start and end opacities are allowed, so we use the
// first and the last
if (!i) {
opacity1 = stopOpacity;
color2 = stopColor;
} else {
opacity2 = stopOpacity;
color1 = stopColor;
}
});
// Apply the gradient to fills only.
if (prop === 'fill') {
// Handle linear gradient angle
if (fillType === 'gradient') {
x1 = gradient.x1 || gradient[0] || 0;
y1 = gradient.y1 || gradient[1] || 0;
x2 = gradient.x2 || gradient[2] || 0;
y2 = gradient.y2 || gradient[3] || 0;
fillAttr = 'angle="' + (90 - Math.atan(
(y2 - y1) / // y vector
(x2 - x1) // x vector
) * 180 / Math.PI) + '"';
addFillNode();
// Radial (circular) gradient
} else {
var r = gradient.r,
sizex = r * 2,
sizey = r * 2,
cx = gradient.cx,
cy = gradient.cy,
radialReference = elem.radialReference,
bBox,
applyRadialGradient = function () {
if (radialReference) {
bBox = wrapper.getBBox();
cx += (radialReference[0] - bBox.x) /
bBox.width - 0.5;
cy += (radialReference[1] - bBox.y) /
bBox.height - 0.5;
sizex *= radialReference[2] / bBox.width;
sizey *= radialReference[2] / bBox.height;
}
fillAttr = 'src="' +
H.getOptions().global.VMLRadialGradientURL +
'" ' +
'size="' + sizex + ',' + sizey + '" ' +
'origin="0.5,0.5" ' +
'position="' + cx + ',' + cy + '" ' +
'color2="' + color2 + '" ';
addFillNode();
};
// Apply radial gradient
if (wrapper.added) {
applyRadialGradient();
} else {
// We need to know the bounding box to get the size
// and position right
wrapper.onAdd = applyRadialGradient;
}
// The fill element's color attribute is broken in IE8
// standards mode, so we need to set the parent shape's
// fillcolor attribute instead.
ret = color1;
}
// Gradients are not supported for VML stroke, return the first
// color. #722.
} else {
ret = stopColor;
}
// If the color is an rgba color, split it and add a fill node
// to hold the opacity component
} else if (regexRgba.test(color) && elem.tagName !== 'IMG') {
colorObject = H.color(color);
wrapper[prop + '-opacitySetter'](
colorObject.get('a'),
prop,
elem
);
ret = colorObject.get('rgb');
} else {
// 'stroke' or 'fill' node
var propNodes = elem.getElementsByTagName(prop);
if (propNodes.length) {
propNodes[0].opacity = 1;
propNodes[0].type = 'solid';
}
ret = color;
}
return ret;
},
/**
* Take a VML string and prepare it for either IE8 or IE6/IE7.
*
* @function Highcharts.VMLRenderer#prepVML
*
* @param {Array<*>} markup
* A string array of the VML markup to prepare
*/
prepVML: function (markup) {
var vmlStyle = 'display:inline-block;behavior:url(#default#VML);',
isIE8 = this.isIE8;
markup = markup.join('');
if (isIE8) { // add xmlns and style inline
markup = markup.replace(
'/>',
' xmlns="urn:schemas-microsoft-com:vml" />'
);
if (markup.indexOf('style="') === -1) {
markup = markup.replace(
'/>',
' style="' + vmlStyle + '" />'
);
} else {
markup = markup.replace('style="', 'style="' + vmlStyle);
}
} else { // add namespace
markup = markup.replace('<', '<hcv:');
}
return markup;
},
/**
* Create rotated and aligned text
*
* @function Highcharts.VMLRenderer#text
*
* @param {string} str
*
* @param {number} x
*
* @param {number} y
*/
text: SVGRenderer.prototype.html,
/**
* Create and return a path element
*
* @function Highcharts.VMLRenderer#path
*
* @param {Highcharts.SVGPathArray} path
*/
path: function (path) {
var attr = {
// subpixel precision down to 0.1 (width and height = 1px)
coordsize: '10 10'
};
if (isArray(path)) {
attr.d = path;
} else if (isObject(path)) { // attributes
extend(attr, path);
}
// create the shape
return this.createElement('shape').attr(attr);
},
/**
* Create and return a circle element. In VML circles are implemented as
* shapes, which is faster than v:oval
*
* @function Highcharts.VMLRenderer#circle
*
* @param {number} x
*
* @param {number} y
*
* @param {number} r
*/
circle: function (x, y, r) {
var circle = this.symbol('circle');
if (isObject(x)) {
r = x.r;
y = x.y;
x = x.x;
}
circle.isCircle = true; // Causes x and y to mean center (#1682)
circle.r = r;
return circle.attr({ x: x, y: y });
},
/**
* Create a group using an outer div and an inner v:group to allow
* rotating and flipping. A simple v:group would have problems with
* positioning child HTML elements and CSS clip.
*
* @function Highcharts.VMLRenderer#g
*
* @param {string} name
* The name of the group
*/
g: function (name) {
var wrapper,
attribs;
// set the class name
if (name) {
attribs = {
'className': 'highcharts-' + name,
'class': 'highcharts-' + name
};
}
// the div to hold HTML and clipping
wrapper = this.createElement('div').attr(attribs);
return wrapper;
},
/**
* VML override to create a regular HTML image.
*
* @function Highcharts.VMLRenderer#image
*
* @param {string} src
*
* @param {number} x
*
* @param {number} y
*
* @param {number} width
*
* @param {number} height
*/
image: function (src, x, y, width, height) {
var obj = this.createElement('img')
.attr({ src: src });
if (arguments.length > 1) {
obj.attr({
x: x,
y: y,
width: width,
height: height
});
}
return obj;
},
/**
* For rectangles, VML uses a shape for rect to overcome bugs and
* rotation problems
*
* @function Highcharts.VMLRenderer#createElement
*
* @param {string} nodeName
*/
createElement: function (nodeName) {
return nodeName === 'rect' ?
this.symbol(nodeName) :
SVGRenderer.prototype.createElement.call(this, nodeName);
},
/**
* In the VML renderer, each child of an inverted div (group) is
* inverted
*
* @function Highcharts.VMLRenderer#invertChild
*
* @param {object} element
*
* @param {object} parentNode
*/
invertChild: function (element, parentNode) {
var ren = this,
parentStyle = parentNode.style,
imgStyle = element.tagName === 'IMG' && element.style; // #1111
css(element, {
flip: 'x',
left: pInt(parentStyle.width) -
(imgStyle ? pInt(imgStyle.top) : 1),
top: pInt(parentStyle.height) -
(imgStyle ? pInt(imgStyle.left) : 1),
rotation: -90
});
// Recursively invert child elements, needed for nested composite
// shapes like box plots and error bars. #1680, #1806.
element.childNodes.forEach(function (child) {
ren.invertChild(child, element);
});
},
/**
* Symbol definitions that override the parent SVG renderer's symbols
*
* @name Highcharts.VMLRenderer#symbols
* @type {Highcharts.Dictionary<Function>}
*/
symbols: {
// VML specific arc function
arc: function (x, y, w, h, options) {
var start = options.start,
end = options.end,
radius = options.r || w || h,
innerRadius = options.innerR,
cosStart = Math.cos(start),
sinStart = Math.sin(start),
cosEnd = Math.cos(end),
sinEnd = Math.sin(end),
ret;
if (end - start === 0) { // no angle, don't show it.
return ['x'];
}
ret = [
'wa', // clockwise arc to
x - radius, // left
y - radius, // top
x + radius, // right
y + radius, // bottom
x + radius * cosStart, // start x
y + radius * sinStart, // start y
x + radius * cosEnd, // end x
y + radius * sinEnd // end y
];
if (options.open && !innerRadius) {
ret.push(
'e',
'M',
x, // - innerRadius,
y // - innerRadius
);
}
ret.push(
'at', // anti clockwise arc to
x - innerRadius, // left
y - innerRadius, // top
x + innerRadius, // right
y + innerRadius, // bottom
x + innerRadius * cosEnd, // start x
y + innerRadius * sinEnd, // start y
x + innerRadius * cosStart, // end x
y + innerRadius * sinStart, // end y
'x', // finish path
'e' // close
);
ret.isArc = true;
return ret;
},
// Add circle symbol path. This performs significantly faster than
// v:oval.
circle: function (x, y, w, h, wrapper) {
if (wrapper && defined(wrapper.r)) {
w = h = 2 * wrapper.r;
}
// Center correction, #1682
if (wrapper && wrapper.isCircle) {
x -= w / 2;
y -= h / 2;
}
// Return the path
return [
'wa', // clockwisearcto
x, // left
y, // top
x + w, // right
y + h, // bottom
x + w, // start x
y + h / 2, // start y
x + w, // end x
y + h / 2, // end y
'e' // close
];
},
/**
* Add rectangle symbol path which eases rotation and omits arcsize
* problems compared to the built-in VML roundrect shape. When
* borders are not rounded, use the simpler square path, else use
* the callout path without the arrow.
*/
rect: function (x, y, w, h, options) {
return SVGRenderer.prototype.symbols[
!defined(options) || !options.r ? 'square' : 'callout'
].call(0, x, y, w, h, options);
}
}
};
H.VMLRenderer = VMLRenderer = function () {
this.init.apply(this, arguments);
};
VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension);
// general renderer
H.Renderer = VMLRenderer;
}
SVGRenderer.prototype.getSpanWidth = function (wrapper, tspan) {
var renderer = this,
bBox = wrapper.getBBox(true),
actualWidth = bBox.width;
// Old IE cannot measure the actualWidth for SVG elements (#2314)
if (!svg && renderer.forExport) {
actualWidth = renderer.measureSpanWidth(
tspan.firstChild.data,
wrapper.styles
);
}
return actualWidth;
};
// This method is used with exporting in old IE, when emulating SVG (see #2314)
SVGRenderer.prototype.measureSpanWidth = function (text, styles) {
var measuringSpan = doc.createElement('span'),
offsetWidth,
textNode = doc.createTextNode(text);
measuringSpan.appendChild(textNode);
css(measuringSpan, styles);
this.box.appendChild(measuringSpan);
offsetWidth = measuringSpan.offsetWidth;
discardElement(measuringSpan); // #2463
return offsetWidth;
};
| mit |
cpojer/react | packages/react-noop-renderer/src/ReactNoopFlightServer.js | 2113 | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
/**
* This is a renderer of React that doesn't have a render target output.
* It is useful to demonstrate the internals of the reconciler in isolation
* and for testing semantics of reconciliation separate from the host
* environment.
*/
import type {ReactModel} from 'react-server/src/ReactFlightServer';
import {saveModule} from 'react-noop-renderer/flight-modules';
import ReactFlightServer from 'react-server/flight';
type Destination = Array<string>;
const ReactNoopFlightServer = ReactFlightServer({
scheduleWork(callback: () => void) {
callback();
},
beginWriting(destination: Destination): void {},
writeChunk(destination: Destination, buffer: Uint8Array): void {
destination.push(Buffer.from((buffer: any)).toString('utf8'));
},
completeWriting(destination: Destination): void {},
close(destination: Destination): void {},
flushBuffered(destination: Destination): void {},
convertStringToBuffer(content: string): Uint8Array {
return Buffer.from(content, 'utf8');
},
formatChunkAsString(type: string, props: Object): string {
return JSON.stringify({type, props});
},
formatChunk(type: string, props: Object): Uint8Array {
return Buffer.from(JSON.stringify({type, props}), 'utf8');
},
isModuleReference(reference: Object): boolean {
return reference.$$typeof === Symbol.for('react.module.reference');
},
getModuleKey(reference: Object): Object {
return reference;
},
resolveModuleMetaData(
config: void,
reference: {$$typeof: Symbol, value: any},
) {
return saveModule(reference.value);
},
});
function render(model: ReactModel): Destination {
const destination: Destination = [];
const bundlerConfig = undefined;
const request = ReactNoopFlightServer.createRequest(
model,
destination,
bundlerConfig,
);
ReactNoopFlightServer.startWork(request);
return destination;
}
export {render};
| mit |
chales-whitepages/twilio-whitepages-callerIDApp | twilio-ruby/lib/twilio-ruby/rest/api/v2010/account/usage/record/last_month.rb | 11098 | ##
# This code was generated by
# \ / _ _ _| _ _
# | (_)\/(_)(_|\/| |(/_ v1.0.0
# / /
module Twilio
module REST
class Api < Domain
class V2010 < Version
class AccountContext < InstanceContext
class UsageList < ListResource
class RecordList < ListResource
class LastMonthList < ListResource
##
# Initialize the LastMonthList
# @param [Version] version Version that contains the resource
# @param [String] account_sid A 34 character string that uniquely identifies this
# resource.
# @return [LastMonthList] LastMonthList
def initialize(version, account_sid: nil)
super(version)
# Path Solution
@solution = {
account_sid: account_sid
}
@uri = "/Accounts/#{@solution[:account_sid]}/Usage/Records/LastMonth.json"
end
##
# Lists LastMonthInstance records from the API as a list.
# Unlike stream(), this operation is eager and will load `limit` records into
# memory before returning.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit
# @param [Integer] page_size Number of records to fetch per request, when not set will use
# the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the
# limit with the most efficient page size, i.e. min(limit, 1000)
# @return [Array] Array of up to limit results
def list(limit: nil, page_size: nil)
self.stream(
limit: limit,
page_size: page_size
).entries
end
##
# Streams LastMonthInstance records from the API as an Enumerable.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit
# @param [Integer] page_size Number of records to fetch per request, when not set will use
# the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the
# limit with the most efficient page size, i.e. min(limit, 1000)
# @return [Enumerable] Enumerable that will yield up to limit results
def stream(limit: nil, page_size: nil)
limits = @version.read_limits(limit, page_size)
page = self.page(
page_size: limits['page_size'],
)
@version.stream(page, limit: limits['limit'], page_limit: limits['page_limit'])
end
##
# When passed a block, yields LastMonthInstance records from the API.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit
# @param [Integer] page_size Number of records to fetch per request, when not set will use
# the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the
# limit with the most efficient page size, i.e. min(limit, 1000)
def each
limits = @version.read_limits
page = self.page(
page_size: limits['page_size'],
)
@version.stream(page,
limit: limits['limit'],
page_limit: limits['page_limit']).each {|x| yield x}
end
##
# Retrieve a single page of LastMonthInstance records from the API.
# Request is executed immediately.
# @param [String] page_token PageToken provided by the API
# @param [Integer] page_number Page Number, this value is simply for client state
# @param [Integer] page_size Number of records to return, defaults to 50
# @return [Page] Page of LastMonthInstance
def page(page_token: nil, page_number: nil, page_size: nil)
params = {
'PageToken' => page_token,
'Page' => page_number,
'PageSize' => page_size,
}
response = @version.page(
'GET',
@uri,
params
)
return LastMonthPage.new(@version, response, @solution)
end
##
# Provide a user friendly representation
def to_s
'#<Twilio.Api.V2010.LastMonthList>'
end
end
class LastMonthPage < Page
##
# Initialize the LastMonthPage
# @param [Version] version Version that contains the resource
# @param [Response] response Response from the API
# @param [Hash] solution Path solution for the resource
# @param [String] account_sid A 34 character string that uniquely identifies this
# resource.
# @return [LastMonthPage] LastMonthPage
def initialize(version, response, solution)
super(version, response)
# Path Solution
@solution = solution
end
##
# Build an instance of LastMonthInstance
# @param [Hash] payload Payload response from the API
# @return [LastMonthInstance] LastMonthInstance
def get_instance(payload)
return LastMonthInstance.new(
@version,
payload,
account_sid: @solution['account_sid'],
)
end
##
# Provide a user friendly representation
def to_s
'<Twilio.Api.V2010.LastMonthPage>'
end
end
class LastMonthInstance < InstanceResource
##
# Initialize the LastMonthInstance
# @param [Version] version Version that contains the resource
# @param [Hash] payload payload that contains response from Twilio
# @param [String] account_sid A 34 character string that uniquely identifies this
# resource.
# @return [LastMonthInstance] LastMonthInstance
def initialize(version, payload, account_sid: nil)
super(version)
# Marshaled Properties
@properties = {
'account_sid' => payload['account_sid'],
'api_version' => payload['api_version'],
'category' => payload['category'],
'count' => payload['count'],
'count_unit' => payload['count_unit'],
'description' => payload['description'],
'end_date' => Twilio.deserialize_iso8601(payload['end_date']),
'price' => payload['price'].to_f,
'price_unit' => payload['price_unit'],
'start_date' => Twilio.deserialize_iso8601(payload['start_date']),
'subresource_uris' => payload['subresource_uris'],
'uri' => payload['uri'],
'usage' => payload['usage'],
'usage_unit' => payload['usage_unit'],
}
end
def account_sid
@properties['account_sid']
end
def api_version
@properties['api_version']
end
def category
@properties['category']
end
def count
@properties['count']
end
def count_unit
@properties['count_unit']
end
def description
@properties['description']
end
def end_date
@properties['end_date']
end
def price
@properties['price']
end
def price_unit
@properties['price_unit']
end
def start_date
@properties['start_date']
end
def subresource_uris
@properties['subresource_uris']
end
def uri
@properties['uri']
end
def usage
@properties['usage']
end
def usage_unit
@properties['usage_unit']
end
##
# Provide a user friendly representation
def to_s
"<Twilio.Api.V2010.LastMonthInstance>"
end
end
end
end
end
end
end
end
end | mit |
kayoubi/mongoid | lib/mongoid/criterion/optional.rb | 5194 | # encoding: utf-8
module Mongoid #:nodoc:
module Criterion #:nodoc:
module Optional
# Adds fields to be sorted in ascending order. Will add them in the order
# they were passed into the method.
#
# Example:
#
# <tt>criteria.ascending(:title, :dob)</tt>
def ascending(*fields)
@options[:sort] = [] unless @options[:sort] || fields.first.nil?
fields.flatten.each { |field| @options[:sort] << [ field, :asc ] }
self
end
alias :asc :ascending
# Tells the criteria that the cursor that gets returned needs to be
# cached. This is so multiple iterations don't hit the database multiple
# times, however this is not advisable when working with large data sets
# as the entire results will get stored in memory.
#
# Example:
#
# <tt>criteria.cache</tt>
def cache
@options.merge!(:cache => true); self
end
# Will return true if the cache option has been set.
#
# Example:
#
# <tt>criteria.cached?</tt>
def cached?
@options[:cache] == true
end
# Adds fields to be sorted in descending order. Will add them in the order
# they were passed into the method.
#
# Example:
#
# <tt>criteria.descending(:title, :dob)</tt>
def descending(*fields)
@options[:sort] = [] unless @options[:sort] || fields.first.nil?
fields.flatten.each { |field| @options[:sort] << [ field, :desc ] }
self
end
alias :desc :descending
# Flags the criteria to execute against a read-only slave in the pool
# instead of master.
#
# Example:
#
# <tt>criteria.enslave</tt>
def enslave
@options.merge!(:enslave => true); self
end
# Will return true if the criteria is enslaved.
#
# Example:
#
# <tt>criteria.enslaved?</tt>
def enslaved?
@options[:enslave] == true
end
# Adds a criterion to the +Criteria+ that specifies additional options
# to be passed to the Ruby driver, in the exact format for the driver.
#
# Options:
#
# extras: A +Hash+ that gets set to the driver options.
#
# Example:
#
# <tt>criteria.extras(:limit => 20, :skip => 40)</tt>
#
# Returns: <tt>self</tt>
def extras(extras)
@options.merge!(extras); filter_options; self
end
# Adds a criterion to the +Criteria+ that specifies an id that must be matched.
#
# Options:
#
# object_id: A +String+ representation of a <tt>BSON::ObjectID</tt>
#
# Example:
#
# <tt>criteria.id("4ab2bc4b8ad548971900005c")</tt>
#
# Returns: <tt>self</tt>
def id(*args)
(args.flatten.size > 1) ? self.in(:_id => args.flatten) : (@selector[:_id] = args.first)
self
end
# Adds a criterion to the +Criteria+ that specifies the maximum number of
# results to return. This is mostly used in conjunction with <tt>skip()</tt>
# to handle paginated results.
#
# Options:
#
# value: An +Integer+ specifying the max number of results. Defaults to 20.
#
# Example:
#
# <tt>criteria.limit(100)</tt>
#
# Returns: <tt>self</tt>
def limit(value = 20)
@options[:limit] = value; self
end
# Returns the offset option. If a per_page option is in the list then it
# will replace it with a skip parameter and return the same value. Defaults
# to 20 if nothing was provided.
def offset(*args)
args.size > 0 ? skip(args.first) : @options[:skip]
end
# Adds a criterion to the +Criteria+ that specifies the sort order of
# the returned documents in the database. Similar to a SQL "ORDER BY".
#
# Options:
#
# params: An +Array+ of [field, direction] sorting pairs.
#
# Example:
#
# <tt>criteria.order_by([[:field1, :asc], [:field2, :desc]])</tt>
#
# Returns: <tt>self</tt>
def order_by(*args)
@options[:sort] = [] unless @options[:sort] || args.first.nil?
arguments = args.first
case arguments
when Hash then arguments.each { |field, direction| @options[:sort] << [ field, direction ] }
when Array then @options[:sort].concat(arguments)
when Complex
args.flatten.each { |complex| @options[:sort] << [ complex.key, complex.operator.to_sym ] }
end; self
end
# Adds a criterion to the +Criteria+ that specifies how many results to skip
# when returning Documents. This is mostly used in conjunction with
# <tt>limit()</tt> to handle paginated results, and is similar to the
# traditional "offset" parameter.
#
# Options:
#
# value: An +Integer+ specifying the number of results to skip. Defaults to 0.
#
# Example:
#
# <tt>criteria.skip(20)</tt>
#
# Returns: <tt>self</tt>
def skip(value = 0)
@options[:skip] = value; self
end
end
end
end
| mit |
feyeleanor/slices | uintptr_test.go | 24150 | package slices
import "testing"
func TestASliceString(t *testing.T) {
ConfirmString := func(s ASlice, r string) {
if x := s.String(); x != r {
t.Fatalf("%v erroneously serialised as '%v'", r, x)
}
}
ConfirmString(ASlice{}, "()")
ConfirmString(ASlice{0}, "(0)")
ConfirmString(ASlice{0, 1}, "(0 1)")
}
func TestASliceLen(t *testing.T) {
ConfirmLength := func(s ASlice, i int) {
if x := s.Len(); x != i {
t.Fatalf("%v.Len() should be %v but is %v", s, i, x)
}
}
ConfirmLength(ASlice{0}, 1)
ConfirmLength(ASlice{0, 1}, 2)
}
func TestASliceSwap(t *testing.T) {
ConfirmSwap := func(s ASlice, i, j int, r ASlice) {
if s.Swap(i, j); !r.Equal(s) {
t.Fatalf("Swap(%v, %v) should be %v but is %v", i, j, r, s)
}
}
ConfirmSwap(ASlice{0, 1, 2}, 0, 1, ASlice{1, 0, 2})
ConfirmSwap(ASlice{0, 1, 2}, 0, 2, ASlice{2, 1, 0})
}
func TestASliceCompare(t *testing.T) {
ConfirmCompare := func(s ASlice, i, j, r int) {
if x := s.Compare(i, j); x != r {
t.Fatalf("Compare(%v, %v) should be %v but is %v", i, j, r, x)
}
}
ConfirmCompare(ASlice{0, 1}, 0, 0, IS_SAME_AS)
ConfirmCompare(ASlice{0, 1}, 0, 1, IS_LESS_THAN)
ConfirmCompare(ASlice{0, 1}, 1, 0, IS_GREATER_THAN)
}
func TestASliceZeroCompare(t *testing.T) {
ConfirmCompare := func(s ASlice, i, r int) {
if x := s.ZeroCompare(i); x != r {
t.Fatalf("ZeroCompare(%v) should be %v but is %v", i, r, x)
}
}
ConfirmCompare(ASlice{1, 0, 2}, 0, IS_LESS_THAN)
ConfirmCompare(ASlice{1, 0, 2}, 1, IS_SAME_AS)
ConfirmCompare(ASlice{1, 0, 3}, 2, IS_LESS_THAN)
}
func TestASliceCut(t *testing.T) {
ConfirmCut := func(s ASlice, start, end int, r ASlice) {
if s.Cut(start, end); !r.Equal(s) {
t.Fatalf("Cut(%v, %v) should be %v but is %v", start, end, r, s)
}
}
ConfirmCut(ASlice{0, 1, 2, 3, 4, 5}, 0, 1, ASlice{1, 2, 3, 4, 5})
ConfirmCut(ASlice{0, 1, 2, 3, 4, 5}, 1, 2, ASlice{0, 2, 3, 4, 5})
ConfirmCut(ASlice{0, 1, 2, 3, 4, 5}, 2, 3, ASlice{0, 1, 3, 4, 5})
ConfirmCut(ASlice{0, 1, 2, 3, 4, 5}, 3, 4, ASlice{0, 1, 2, 4, 5})
ConfirmCut(ASlice{0, 1, 2, 3, 4, 5}, 4, 5, ASlice{0, 1, 2, 3, 5})
ConfirmCut(ASlice{0, 1, 2, 3, 4, 5}, 5, 6, ASlice{0, 1, 2, 3, 4})
ConfirmCut(ASlice{0, 1, 2, 3, 4, 5}, -1, 1, ASlice{1, 2, 3, 4, 5})
ConfirmCut(ASlice{0, 1, 2, 3, 4, 5}, 0, 2, ASlice{2, 3, 4, 5})
ConfirmCut(ASlice{0, 1, 2, 3, 4, 5}, 1, 3, ASlice{0, 3, 4, 5})
ConfirmCut(ASlice{0, 1, 2, 3, 4, 5}, 2, 4, ASlice{0, 1, 4, 5})
ConfirmCut(ASlice{0, 1, 2, 3, 4, 5}, 3, 5, ASlice{0, 1, 2, 5})
ConfirmCut(ASlice{0, 1, 2, 3, 4, 5}, 4, 6, ASlice{0, 1, 2, 3})
ConfirmCut(ASlice{0, 1, 2, 3, 4, 5}, 5, 7, ASlice{0, 1, 2, 3, 4})
}
func TestASliceTrim(t *testing.T) {
ConfirmTrim := func(s ASlice, start, end int, r ASlice) {
if s.Trim(start, end); !r.Equal(s) {
t.Fatalf("Trim(%v, %v) should be %v but is %v", start, end, r, s)
}
}
ConfirmTrim(ASlice{0, 1, 2, 3, 4, 5}, 0, 1, ASlice{0})
ConfirmTrim(ASlice{0, 1, 2, 3, 4, 5}, 1, 2, ASlice{1})
ConfirmTrim(ASlice{0, 1, 2, 3, 4, 5}, 2, 3, ASlice{2})
ConfirmTrim(ASlice{0, 1, 2, 3, 4, 5}, 3, 4, ASlice{3})
ConfirmTrim(ASlice{0, 1, 2, 3, 4, 5}, 4, 5, ASlice{4})
ConfirmTrim(ASlice{0, 1, 2, 3, 4, 5}, 5, 6, ASlice{5})
ConfirmTrim(ASlice{0, 1, 2, 3, 4, 5}, -1, 1, ASlice{0})
ConfirmTrim(ASlice{0, 1, 2, 3, 4, 5}, 0, 2, ASlice{0, 1})
ConfirmTrim(ASlice{0, 1, 2, 3, 4, 5}, 1, 3, ASlice{1, 2})
ConfirmTrim(ASlice{0, 1, 2, 3, 4, 5}, 2, 4, ASlice{2, 3})
ConfirmTrim(ASlice{0, 1, 2, 3, 4, 5}, 3, 5, ASlice{3, 4})
ConfirmTrim(ASlice{0, 1, 2, 3, 4, 5}, 4, 6, ASlice{4, 5})
ConfirmTrim(ASlice{0, 1, 2, 3, 4, 5}, 5, 7, ASlice{5})
}
func TestASliceDelete(t *testing.T) {
ConfirmDelete := func(s ASlice, index int, r ASlice) {
if s.Delete(index); !r.Equal(s) {
t.Fatalf("Delete(%v) should be %v but is %v", index, r, s)
}
}
ConfirmDelete(ASlice{0, 1, 2, 3, 4, 5}, -1, ASlice{0, 1, 2, 3, 4, 5})
ConfirmDelete(ASlice{0, 1, 2, 3, 4, 5}, 0, ASlice{1, 2, 3, 4, 5})
ConfirmDelete(ASlice{0, 1, 2, 3, 4, 5}, 1, ASlice{0, 2, 3, 4, 5})
ConfirmDelete(ASlice{0, 1, 2, 3, 4, 5}, 2, ASlice{0, 1, 3, 4, 5})
ConfirmDelete(ASlice{0, 1, 2, 3, 4, 5}, 3, ASlice{0, 1, 2, 4, 5})
ConfirmDelete(ASlice{0, 1, 2, 3, 4, 5}, 4, ASlice{0, 1, 2, 3, 5})
ConfirmDelete(ASlice{0, 1, 2, 3, 4, 5}, 5, ASlice{0, 1, 2, 3, 4})
ConfirmDelete(ASlice{0, 1, 2, 3, 4, 5}, 6, ASlice{0, 1, 2, 3, 4, 5})
}
func TestASliceDeleteIf(t *testing.T) {
ConfirmDeleteIf := func(s ASlice, f interface{}, r ASlice) {
if s.DeleteIf(f); !r.Equal(s) {
t.Fatalf("DeleteIf(%v) should be %v but is %v", f, r, s)
}
}
ConfirmDeleteIf(ASlice{0, 1, 0, 3, 0, 5}, uintptr(0), ASlice{1, 3, 5})
ConfirmDeleteIf(ASlice{0, 1, 0, 3, 0, 5}, uintptr(1), ASlice{0, 0, 3, 0, 5})
ConfirmDeleteIf(ASlice{0, 1, 0, 3, 0, 5}, uintptr(6), ASlice{0, 1, 0, 3, 0, 5})
ConfirmDeleteIf(ASlice{0, 1, 0, 3, 0, 5}, func(x interface{}) bool { return x == uintptr(0) }, ASlice{1, 3, 5})
ConfirmDeleteIf(ASlice{0, 1, 0, 3, 0, 5}, func(x interface{}) bool { return x == uintptr(1) }, ASlice{0, 0, 3, 0, 5})
ConfirmDeleteIf(ASlice{0, 1, 0, 3, 0, 5}, func(x interface{}) bool { return x == uintptr(6) }, ASlice{0, 1, 0, 3, 0, 5})
ConfirmDeleteIf(ASlice{0, 1, 0, 3, 0, 5}, func(x uintptr) bool { return x == uintptr(0) }, ASlice{1, 3, 5})
ConfirmDeleteIf(ASlice{0, 1, 0, 3, 0, 5}, func(x uintptr) bool { return x == uintptr(1) }, ASlice{0, 0, 3, 0, 5})
ConfirmDeleteIf(ASlice{0, 1, 0, 3, 0, 5}, func(x uintptr) bool { return x == uintptr(6) }, ASlice{0, 1, 0, 3, 0, 5})
}
func TestASliceEach(t *testing.T) {
var count uintptr
ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.Each(func(i interface{}) {
if i != uintptr(count) {
t.Fatalf("element %v erroneously reported as %v", count, i)
}
count++
})
ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.Each(func(index int, i interface{}) {
if i != uintptr(index) {
t.Fatalf("element %v erroneously reported as %v", index, i)
}
})
ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.Each(func(key, i interface{}) {
if i != uintptr(key.(int)) {
t.Fatalf("element %v erroneously reported as %v", key, i)
}
})
count = 0
ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.Each(func(i uintptr) {
if i != count {
t.Fatalf("element %v erroneously reported as %v", count, i)
}
count++
})
ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.Each(func(index int, i uintptr) {
if i != uintptr(index) {
t.Fatalf("element %v erroneously reported as %v", index, i)
}
})
ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.Each(func(key interface{}, i uintptr) {
if i != uintptr(key.(int)) {
t.Fatalf("element %v erroneously reported as %v", key, i)
}
})
}
func TestUASliceWhile(t *testing.T) {
ConfirmLimit := func(s ASlice, l int, f interface{}) {
if count := s.While(f); count != l {
t.Fatalf("%v.While() should have iterated %v times not %v times", s, l, count)
}
}
s := ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
count := 0
limit := 5
ConfirmLimit(s, limit, func(i interface{}) bool {
if count == limit {
return false
}
count++
return true
})
ConfirmLimit(s, limit, func(index int, i interface{}) bool {
return index != limit
})
ConfirmLimit(s, limit, func(key, i interface{}) bool {
return key.(int) != limit
})
count = 0
ConfirmLimit(s, limit, func(i uintptr) bool {
if count == limit {
return false
}
count++
return true
})
ConfirmLimit(s, limit, func(index int, i uintptr) bool {
return index != limit
})
ConfirmLimit(s, limit, func(key interface{}, i uintptr) bool {
return key.(int) != limit
})
}
func TestUASliceUntil(t *testing.T) {
ConfirmLimit := func(s ASlice, l int, f interface{}) {
if count := s.Until(f); count != l {
t.Fatalf("%v.Until() should have iterated %v times not %v times", s, l, count)
}
}
s := ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
count := 0
limit := 5
ConfirmLimit(s, limit, func(i interface{}) bool {
if count == limit {
return true
}
count++
return false
})
ConfirmLimit(s, limit, func(index int, i interface{}) bool {
return index == limit
})
ConfirmLimit(s, limit, func(key, i interface{}) bool {
return key.(int) == limit
})
count = 0
ConfirmLimit(s, limit, func(i uintptr) bool {
if count == limit {
return true
}
count++
return false
})
ConfirmLimit(s, limit, func(index int, i uintptr) bool {
return index == limit
})
ConfirmLimit(s, limit, func(key interface{}, i uintptr) bool {
return key.(int) == limit
})
}
func TestASliceBlockCopy(t *testing.T) {
ConfirmBlockCopy := func(s ASlice, destination, source, count int, r ASlice) {
s.BlockCopy(destination, source, count)
if !r.Equal(s) {
t.Fatalf("BlockCopy(%v, %v, %v) should be %v but is %v", destination, source, count, r, s)
}
}
ConfirmBlockCopy(ASlice{}, 0, 0, 1, ASlice{})
ConfirmBlockCopy(ASlice{}, 1, 0, 1, ASlice{})
ConfirmBlockCopy(ASlice{}, 0, 1, 1, ASlice{})
ConfirmBlockCopy(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 0, 0, 4, ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
ConfirmBlockCopy(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 9, 9, 4, ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
ConfirmBlockCopy(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 9, 0, 4, ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 0})
ConfirmBlockCopy(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 10, 0, 4, ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
ConfirmBlockCopy(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 10, 10, 4, ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
ConfirmBlockCopy(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 5, 2, 4, ASlice{0, 1, 2, 3, 4, 2, 3, 4, 5, 9})
ConfirmBlockCopy(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 2, 5, 4, ASlice{0, 1, 5, 6, 7, 8, 6, 7, 8, 9})
}
func TestASliceBlockClear(t *testing.T) {
ConfirmBlockClear := func(s ASlice, start, count int, r ASlice) {
s.BlockClear(start, count)
if !r.Equal(s) {
t.Fatalf("BlockClear(%v, %v) should be %v but is %v", start, count, r, s)
}
}
ConfirmBlockClear(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 0, 4, ASlice{0, 0, 0, 0, 4, 5, 6, 7, 8, 9})
ConfirmBlockClear(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 10, 4, ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
ConfirmBlockClear(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 5, 4, ASlice{0, 1, 2, 3, 4, 0, 0, 0, 0, 9})
}
func TestASliceOverwrite(t *testing.T) {
ConfirmOverwrite := func(s ASlice, offset int, v, r ASlice) {
s.Overwrite(offset, v)
if !r.Equal(s) {
t.Fatalf("Overwrite(%v, %v) should be %v but is %v", offset, v, r, s)
}
}
ConfirmOverwrite(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 0, ASlice{10, 9, 8, 7}, ASlice{10, 9, 8, 7, 4, 5, 6, 7, 8, 9})
ConfirmOverwrite(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 10, ASlice{10, 9, 8, 7}, ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
ConfirmOverwrite(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 5, ASlice{11, 12, 13, 14}, ASlice{0, 1, 2, 3, 4, 11, 12, 13, 14, 9})
}
func TestASliceReallocate(t *testing.T) {
ConfirmReallocate := func(s ASlice, l, c int, r ASlice) {
o := s.String()
el := l
if el > c {
el = c
}
switch s.Reallocate(l, c); {
case s == nil: t.Fatalf("%v.Reallocate(%v, %v) created a nil value for Slice", o, l, c)
case s.Cap() != c: t.Fatalf("%v.Reallocate(%v, %v) capacity should be %v but is %v", o, l, c, c, s.Cap())
case s.Len() != el: t.Fatalf("%v.Reallocate(%v, %v) length should be %v but is %v", o, l, c, el, s.Len())
case !r.Equal(s): t.Fatalf("%v.Reallocate(%v, %v) should be %v but is %v", o, l, c, r, s)
}
}
ConfirmReallocate(ASlice{}, 0, 10, make(ASlice, 0, 10))
ConfirmReallocate(ASlice{0, 1, 2, 3, 4}, 3, 10, ASlice{0, 1, 2})
ConfirmReallocate(ASlice{0, 1, 2, 3, 4}, 5, 10, ASlice{0, 1, 2, 3, 4})
ConfirmReallocate(ASlice{0, 1, 2, 3, 4}, 10, 10, ASlice{0, 1, 2, 3, 4, 0, 0, 0, 0, 0})
ConfirmReallocate(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 1, 5, ASlice{0})
ConfirmReallocate(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 5, 5, ASlice{0, 1, 2, 3, 4})
ConfirmReallocate(ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 10, 5, ASlice{0, 1, 2, 3, 4})
}
func TestASliceExtend(t *testing.T) {
ConfirmExtend := func(s ASlice, n int, r ASlice) {
c := s.Cap()
s.Extend(n)
switch {
case s.Len() != r.Len(): t.Fatalf("Extend(%v) len should be %v but is %v", n, r.Len(), s.Len())
case s.Cap() != c + n: t.Fatalf("Extend(%v) cap should be %v but is %v", n, c + n, s.Cap())
case !r.Equal(s): t.Fatalf("Extend(%v) should be %v but is %v", n, r, s)
}
}
ConfirmExtend(ASlice{}, 1, ASlice{0})
ConfirmExtend(ASlice{}, 2, ASlice{0, 0})
}
func TestASliceExpand(t *testing.T) {
ConfirmExpand := func(s ASlice, i, n int, r ASlice) {
c := s.Cap()
s.Expand(i, n)
switch {
case s.Len() != r.Len(): t.Fatalf("Expand(%v, %v) len should be %v but is %v", i, n, r.Len(), s.Len())
case s.Cap() != c + n: t.Fatalf("Expand(%v, %v) cap should be %v but is %v", i, n, c + n, s.Cap())
case !r.Equal(s): t.Fatalf("Expand(%v, %v) should be %v but is %v", i, n, r, s)
}
}
ConfirmExpand(ASlice{}, -1, 1, ASlice{0})
ConfirmExpand(ASlice{}, 0, 1, ASlice{0})
ConfirmExpand(ASlice{}, 1, 1, ASlice{0})
ConfirmExpand(ASlice{}, 0, 2, ASlice{0, 0})
ConfirmExpand(ASlice{0, 1, 2}, -1, 2, ASlice{0, 0, 0, 1, 2})
ConfirmExpand(ASlice{0, 1, 2}, 0, 2, ASlice{0, 0, 0, 1, 2})
ConfirmExpand(ASlice{0, 1, 2}, 1, 2, ASlice{0, 0, 0, 1, 2})
ConfirmExpand(ASlice{0, 1, 2}, 2, 2, ASlice{0, 1, 0, 0, 2})
ConfirmExpand(ASlice{0, 1, 2}, 3, 2, ASlice{0, 1, 2, 0, 0})
ConfirmExpand(ASlice{0, 1, 2}, 4, 2, ASlice{0, 1, 2, 0, 0})
}
func TestASliceDepth(t *testing.T) {
ConfirmDepth := func(s ASlice, i int) {
if x := s.Depth(); x != i {
t.Fatalf("%v.Depth() should be %v but is %v", s, i, x)
}
}
ConfirmDepth(ASlice{0, 1}, 0)
}
func TestASliceReverse(t *testing.T) {
ConfirmReverse := func(s, r ASlice) {
if s.Reverse(); !Equal(s, r) {
t.Fatalf("Reverse() should be %v but is %v", r, s)
}
}
ConfirmReverse(ASlice{}, ASlice{})
ConfirmReverse(ASlice{1}, ASlice{1})
ConfirmReverse(ASlice{1, 2}, ASlice{2, 1})
ConfirmReverse(ASlice{1, 2, 3}, ASlice{3, 2, 1})
ConfirmReverse(ASlice{1, 2, 3, 4}, ASlice{4, 3, 2, 1})
}
func TestASliceAppend(t *testing.T) {
ConfirmAppend := func(s ASlice, v interface{}, r ASlice) {
s.Append(v)
if !r.Equal(s) {
t.Fatalf("Append(%v) should be %v but is %v", v, r, s)
}
}
ConfirmAppend(ASlice{}, uintptr(0), ASlice{0})
ConfirmAppend(ASlice{}, ASlice{0}, ASlice{0})
ConfirmAppend(ASlice{}, ASlice{0, 1}, ASlice{0, 1})
ConfirmAppend(ASlice{0, 1, 2}, ASlice{3, 4}, ASlice{0, 1, 2, 3, 4})
}
func TestASlicePrepend(t *testing.T) {
ConfirmPrepend := func(s ASlice, v interface{}, r ASlice) {
if s.Prepend(v); !r.Equal(s) {
t.Fatalf("Prepend(%v) should be %v but is %v", v, r, s)
}
}
ConfirmPrepend(ASlice{}, uintptr(0), ASlice{0})
ConfirmPrepend(ASlice{0}, uintptr(1), ASlice{1, 0})
ConfirmPrepend(ASlice{}, ASlice{0}, ASlice{0})
ConfirmPrepend(ASlice{}, ASlice{0, 1}, ASlice{0, 1})
ConfirmPrepend(ASlice{0, 1, 2}, ASlice{3, 4}, ASlice{3, 4, 0, 1, 2})
}
func TestASliceRepeat(t *testing.T) {
ConfirmRepeat := func(s ASlice, count int, r ASlice) {
if x := s.Repeat(count); !x.Equal(r) {
t.Fatalf("%v.Repeat(%v) should be %v but is %v", s, count, r, x)
}
}
ConfirmRepeat(ASlice{}, 5, ASlice{})
ConfirmRepeat(ASlice{0}, 1, ASlice{0})
ConfirmRepeat(ASlice{0}, 2, ASlice{0, 0})
ConfirmRepeat(ASlice{0}, 3, ASlice{0, 0, 0})
ConfirmRepeat(ASlice{0}, 4, ASlice{0, 0, 0, 0})
ConfirmRepeat(ASlice{0}, 5, ASlice{0, 0, 0, 0, 0})
}
func TestASliceCar(t *testing.T) {
ConfirmCar := func(s ASlice, r uintptr) {
n := s.Car()
if ok := n == r; !ok {
t.Fatalf("head should be '%v' but is '%v'", r, n)
}
}
ConfirmCar(ASlice{1, 2, 3}, 1)
}
func TestASliceCdr(t *testing.T) {
ConfirmCdr := func(s, r ASlice) {
if n := s.Cdr(); !n.Equal(r) {
t.Fatalf("tail should be '%v' but is '%v'", r, n)
}
}
ConfirmCdr(ASlice{1, 2, 3}, ASlice{2, 3})
}
func TestASliceRplaca(t *testing.T) {
ConfirmRplaca := func(s ASlice, v interface{}, r ASlice) {
if s.Rplaca(v); !s.Equal(r) {
t.Fatalf("slice should be '%v' but is '%v'", r, s)
}
}
ConfirmRplaca(ASlice{1, 2, 3, 4, 5}, uintptr(0), ASlice{0, 2, 3, 4, 5})
}
func TestASliceRplacd(t *testing.T) {
ConfirmRplacd := func(s ASlice, v interface{}, r ASlice) {
if s.Rplacd(v); !s.Equal(r) {
t.Fatalf("slice should be '%v' but is '%v'", r, s)
}
}
ConfirmRplacd(ASlice{1, 2, 3, 4, 5}, nil, ASlice{1})
ConfirmRplacd(ASlice{1, 2, 3, 4, 5}, uintptr(10), ASlice{1, 10})
ConfirmRplacd(ASlice{1, 2, 3, 4, 5}, ASlice{5, 4, 3, 2}, ASlice{1, 5, 4, 3, 2})
ConfirmRplacd(ASlice{1, 2, 3, 4, 5, 6}, ASlice{2, 4, 8, 16}, ASlice{1, 2, 4, 8, 16})
}
func TestASliceFind(t *testing.T) {
ConfirmFind := func(s ASlice, v uintptr, i int) {
if x, ok := s.Find(v); !ok || x != i {
t.Fatalf("%v.Find(%v) should be %v but is %v", s, v, i, x)
}
}
ConfirmFind(ASlice{0, 1, 2, 3, 4}, 0, 0)
ConfirmFind(ASlice{0, 1, 2, 3, 4}, 1, 1)
ConfirmFind(ASlice{0, 1, 2, 4, 3}, 2, 2)
ConfirmFind(ASlice{0, 1, 2, 4, 3}, 3, 4)
ConfirmFind(ASlice{0, 1, 2, 4, 3}, 4, 3)
}
func TestASliceFindN(t *testing.T) {
ConfirmFindN := func(s ASlice, v uintptr, n int, i ISlice) {
if x := s.FindN(v, n); !x.Equal(i) {
t.Fatalf("%v.Find(%v, %v) should be %v but is %v", s, v, n, i, x)
}
}
ConfirmFindN(ASlice{1, 0, 1, 0, 1}, 2, 3, ISlice{})
ConfirmFindN(ASlice{1, 0, 1, 0, 1}, 1, 0, ISlice{0, 2, 4})
ConfirmFindN(ASlice{1, 0, 1, 0, 1}, 1, 1, ISlice{0})
ConfirmFindN(ASlice{1, 0, 1, 0, 1}, 1, 2, ISlice{0, 2})
ConfirmFindN(ASlice{1, 0, 1, 0, 1}, 1, 3, ISlice{0, 2, 4})
ConfirmFindN(ASlice{1, 0, 1, 0, 1}, 1, 4, ISlice{0, 2, 4})
}
func TestASliceKeepIf(t *testing.T) {
ConfirmKeepIf := func(s ASlice, f interface{}, r ASlice) {
if s.KeepIf(f); !r.Equal(s) {
t.Fatalf("KeepIf(%v) should be %v but is %v", f, r, s)
}
}
ConfirmKeepIf(ASlice{0, 1, 0, 3, 0, 5}, uintptr(0), ASlice{0, 0, 0})
ConfirmKeepIf(ASlice{0, 1, 0, 3, 0, 5}, uintptr(1), ASlice{1})
ConfirmKeepIf(ASlice{0, 1, 0, 3, 0, 5}, uintptr(6), ASlice{})
ConfirmKeepIf(ASlice{0, 1, 0, 3, 0, 5}, func(x interface{}) bool { return x == uintptr(0) }, ASlice{0, 0, 0})
ConfirmKeepIf(ASlice{0, 1, 0, 3, 0, 5}, func(x interface{}) bool { return x == uintptr(1) }, ASlice{1})
ConfirmKeepIf(ASlice{0, 1, 0, 3, 0, 5}, func(x interface{}) bool { return x == uintptr(6) }, ASlice{})
ConfirmKeepIf(ASlice{0, 1, 0, 3, 0, 5}, func(x uintptr) bool { return x == uintptr(0) }, ASlice{0, 0, 0})
ConfirmKeepIf(ASlice{0, 1, 0, 3, 0, 5}, func(x uintptr) bool { return x == uintptr(1) }, ASlice{1})
ConfirmKeepIf(ASlice{0, 1, 0, 3, 0, 5}, func(x uintptr) bool { return x == uintptr(6) }, ASlice{})
}
func TestASliceReverseEach(t *testing.T) {
var count uintptr
count = 9
ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.ReverseEach(func(i interface{}) {
if i != count {
t.Fatalf("0: element %v erroneously reported as %v", count, i)
}
count--
})
ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.ReverseEach(func(index int, i interface{}) {
if index != int(i.(uintptr)) {
t.Fatalf("1: element %v erroneously reported as %v", index, i)
}
})
ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.ReverseEach(func(key, i interface{}) {
if uintptr(key.(int)) != i {
t.Fatalf("2: element %v erroneously reported as %v", key, i)
}
})
count = 9
ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.ReverseEach(func(i uintptr) {
if i != count {
t.Fatalf("3: element %v erroneously reported as %v", count, i)
}
count--
})
ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.ReverseEach(func(index int, i uintptr) {
if int(i) != index {
t.Fatalf("4: element %v erroneously reported as %v", index, i)
}
})
ASlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.ReverseEach(func(key interface{}, i uintptr) {
if key.(int) != int(i) {
t.Fatalf("5: element %v erroneously reported as %v", key, i)
}
})
}
func TestASliceReplaceIf(t *testing.T) {
ConfirmReplaceIf := func(s ASlice, f, v interface{}, r ASlice) {
if s.ReplaceIf(f, v); !r.Equal(s) {
t.Fatalf("ReplaceIf(%v, %v) should be %v but is %v", f, v, r, s)
}
}
ConfirmReplaceIf(ASlice{0, 1, 0, 3, 0, 5}, uintptr(0), uintptr(1), ASlice{1, 1, 1, 3, 1, 5})
ConfirmReplaceIf(ASlice{0, 1, 0, 3, 0, 5}, uintptr(1), uintptr(0), ASlice{0, 0, 0, 3, 0, 5})
ConfirmReplaceIf(ASlice{0, 1, 0, 3, 0, 5}, uintptr(6), uintptr(0), ASlice{0, 1, 0, 3, 0, 5})
ConfirmReplaceIf(ASlice{0, 1, 0, 3, 0, 5}, func(x interface{}) bool { return x == uintptr(0) }, uintptr(1), ASlice{1, 1, 1, 3, 1, 5})
ConfirmReplaceIf(ASlice{0, 1, 0, 3, 0, 5}, func(x interface{}) bool { return x == uintptr(1) }, uintptr(0), ASlice{0, 0, 0, 3, 0, 5})
ConfirmReplaceIf(ASlice{0, 1, 0, 3, 0, 5}, func(x interface{}) bool { return x == uintptr(6) }, uintptr(0), ASlice{0, 1, 0, 3, 0, 5})
ConfirmReplaceIf(ASlice{0, 1, 0, 3, 0, 5}, func(x uintptr) bool { return x == uintptr(0) }, uintptr(1), ASlice{1, 1, 1, 3, 1, 5})
ConfirmReplaceIf(ASlice{0, 1, 0, 3, 0, 5}, func(x uintptr) bool { return x == uintptr(1) }, uintptr(0), ASlice{0, 0, 0, 3, 0, 5})
ConfirmReplaceIf(ASlice{0, 1, 0, 3, 0, 5}, func(x uintptr) bool { return x == uintptr(6) }, uintptr(0), ASlice{0, 1, 0, 3, 0, 5})
}
func TestASliceReplace(t *testing.T) {
ConfirmReplace := func(s ASlice, v interface{}) {
if s.Replace(v); !s.Equal(v) {
t.Fatalf("Replace() should be %v but is %v", s, v)
}
}
ConfirmReplace(ASlice{0, 1, 2, 3, 4, 5}, ASlice{ 9, 8, 7, 6, 5 })
ConfirmReplace(ASlice{0, 1, 2, 3, 4, 5}, []uintptr{ 9, 8, 7, 6, 5 })
}
func TestASliceSelect(t *testing.T) {
ConfirmSelect := func(s ASlice, f interface{}, r ASlice) {
if x := s.Select(f); !r.Equal(x) {
t.Fatalf("Select(%v) should be %v but is %v", f, r, s)
}
}
ConfirmSelect(ASlice{0, 1, 0, 3, 0, 5}, uintptr(0), ASlice{0, 0, 0})
ConfirmSelect(ASlice{0, 1, 0, 3, 0, 5}, uintptr(1), ASlice{1})
ConfirmSelect(ASlice{0, 1, 0, 3, 0, 5}, uintptr(6), ASlice{})
ConfirmSelect(ASlice{0, 1, 0, 3, 0, 5}, func(x interface{}) bool { return x == uintptr(0) }, ASlice{0, 0, 0})
ConfirmSelect(ASlice{0, 1, 0, 3, 0, 5}, func(x interface{}) bool { return x == uintptr(1) }, ASlice{1})
ConfirmSelect(ASlice{0, 1, 0, 3, 0, 5}, func(x interface{}) bool { return x == uintptr(6) }, ASlice{})
ConfirmSelect(ASlice{0, 1, 0, 3, 0, 5}, func(x uintptr) bool { return x == uintptr(0) }, ASlice{0, 0, 0})
ConfirmSelect(ASlice{0, 1, 0, 3, 0, 5}, func(x uintptr) bool { return x == uintptr(1) }, ASlice{1})
ConfirmSelect(ASlice{0, 1, 0, 3, 0, 5}, func(x uintptr) bool { return x == uintptr(6) }, ASlice{})
}
func TestASliceUniq(t *testing.T) {
ConfirmUniq := func(s, r ASlice) {
if s.Uniq(); !r.Equal(s) {
t.Fatalf("Uniq() should be %v but is %v", r, s)
}
}
ConfirmUniq(ASlice{0, 0, 0, 0, 0, 0}, ASlice{0})
ConfirmUniq(ASlice{0, 1, 0, 3, 0, 5}, ASlice{0, 1, 3, 5})
}
func TestASlicePick(t *testing.T) {
ConfirmPick := func(s ASlice, i []int, r ASlice) {
if x := s.Pick(i...); !r.Equal(x) {
t.Fatalf("%v.Pick(%v) should be %v but is %v", s, i, r, x)
}
}
ConfirmPick(ASlice{0, 1, 2, 3, 4, 5}, []int{}, ASlice{})
ConfirmPick(ASlice{0, 1, 2, 3, 4, 5}, []int{ 0, 1 }, ASlice{0, 1})
ConfirmPick(ASlice{0, 1, 2, 3, 4, 5}, []int{ 0, 3 }, ASlice{0, 3})
ConfirmPick(ASlice{0, 1, 2, 3, 4, 5}, []int{ 0, 3, 4, 3 }, ASlice{0, 3, 4, 3})
}
func TestASliceInsert(t *testing.T) {
ConfirmInsert := func(s ASlice, n int, v interface{}, r ASlice) {
if s.Insert(n, v); !r.Equal(s) {
t.Fatalf("Insert(%v, %v) should be %v but is %v", n, v, r, s)
}
}
ConfirmInsert(ASlice{}, 0, uintptr(0), ASlice{0})
ConfirmInsert(ASlice{}, 0, ASlice{0}, ASlice{0})
ConfirmInsert(ASlice{}, 0, ASlice{0, 1}, ASlice{0, 1})
ConfirmInsert(ASlice{0}, 0, uintptr(1), ASlice{1, 0})
ConfirmInsert(ASlice{0}, 0, ASlice{1}, ASlice{1, 0})
ConfirmInsert(ASlice{0}, 1, uintptr(1), ASlice{0, 1})
ConfirmInsert(ASlice{0}, 1, ASlice{1}, ASlice{0, 1})
ConfirmInsert(ASlice{0, 1, 2}, 0, uintptr(3), ASlice{3, 0, 1, 2})
ConfirmInsert(ASlice{0, 1, 2}, 1, uintptr(3), ASlice{0, 3, 1, 2})
ConfirmInsert(ASlice{0, 1, 2}, 2, uintptr(3), ASlice{0, 1, 3, 2})
ConfirmInsert(ASlice{0, 1, 2}, 3, uintptr(3), ASlice{0, 1, 2, 3})
ConfirmInsert(ASlice{0, 1, 2}, 0, ASlice{3, 4}, ASlice{3, 4, 0, 1, 2})
ConfirmInsert(ASlice{0, 1, 2}, 1, ASlice{3, 4}, ASlice{0, 3, 4, 1, 2})
ConfirmInsert(ASlice{0, 1, 2}, 2, ASlice{3, 4}, ASlice{0, 1, 3, 4, 2})
ConfirmInsert(ASlice{0, 1, 2}, 3, ASlice{3, 4}, ASlice{0, 1, 2, 3, 4})
} | mit |
cdnjs/cdnjs | ajax/libs/material-ui/5.0.0-beta.1/legacy/Select/Select.js | 9829 | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
var _Input, _FilledInput;
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { deepmerge } from '@material-ui/utils';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import SelectInput from './SelectInput';
import formControlState from '../FormControl/formControlState';
import useFormControl from '../FormControl/useFormControl';
import ArrowDropDownIcon from '../internal/svg-icons/ArrowDropDown';
import Input from '../Input';
import NativeSelectInput from '../NativeSelect/NativeSelectInput';
import FilledInput from '../FilledInput';
import OutlinedInput from '../OutlinedInput';
import useThemeProps from '../styles/useThemeProps';
import { getSelectUtilityClasses } from './selectClasses';
import { jsx as _jsx } from "react/jsx-runtime";
var useUtilityClasses = function useUtilityClasses(styleProps) {
var classes = styleProps.classes;
var slots = {
root: ['root']
};
return composeClasses(slots, getSelectUtilityClasses, classes);
};
var Select = /*#__PURE__*/React.forwardRef(function Select(inProps, ref) {
var props = useThemeProps({
name: 'MuiSelect',
props: inProps
});
var _props$autoWidth = props.autoWidth,
autoWidth = _props$autoWidth === void 0 ? false : _props$autoWidth,
children = props.children,
_props$classes = props.classes,
classesProp = _props$classes === void 0 ? {} : _props$classes,
className = props.className,
_props$displayEmpty = props.displayEmpty,
displayEmpty = _props$displayEmpty === void 0 ? false : _props$displayEmpty,
_props$IconComponent = props.IconComponent,
IconComponent = _props$IconComponent === void 0 ? ArrowDropDownIcon : _props$IconComponent,
id = props.id,
input = props.input,
inputProps = props.inputProps,
label = props.label,
labelId = props.labelId,
MenuProps = props.MenuProps,
_props$multiple = props.multiple,
multiple = _props$multiple === void 0 ? false : _props$multiple,
_props$native = props.native,
native = _props$native === void 0 ? false : _props$native,
onClose = props.onClose,
onOpen = props.onOpen,
open = props.open,
renderValue = props.renderValue,
SelectDisplayProps = props.SelectDisplayProps,
_props$variant = props.variant,
variantProps = _props$variant === void 0 ? 'outlined' : _props$variant,
other = _objectWithoutProperties(props, ["autoWidth", "children", "classes", "className", "displayEmpty", "IconComponent", "id", "input", "inputProps", "label", "labelId", "MenuProps", "multiple", "native", "onClose", "onOpen", "open", "renderValue", "SelectDisplayProps", "variant"]);
var inputComponent = native ? NativeSelectInput : SelectInput;
var muiFormControl = useFormControl();
var fcs = formControlState({
props: props,
muiFormControl: muiFormControl,
states: ['variant']
});
var variant = fcs.variant || variantProps;
var InputComponent = input || {
standard: _Input || (_Input = /*#__PURE__*/_jsx(Input, {})),
outlined: /*#__PURE__*/_jsx(OutlinedInput, {
label: label
}),
filled: _FilledInput || (_FilledInput = /*#__PURE__*/_jsx(FilledInput, {}))
}[variant];
var styleProps = _extends({}, props, {
classes: classesProp
});
var classes = useUtilityClasses(styleProps);
var root = classesProp.root,
otherClasses = _objectWithoutProperties(classesProp, ["root"]);
return /*#__PURE__*/React.cloneElement(InputComponent, _extends({
// Most of the logic is implemented in `SelectInput`.
// The `Select` component is a simple API wrapper to expose something better to play with.
inputComponent: inputComponent,
inputProps: _extends({
children: children,
IconComponent: IconComponent,
variant: variant,
type: undefined,
// We render a select. We can ignore the type provided by the `Input`.
multiple: multiple
}, native ? {
id: id
} : {
autoWidth: autoWidth,
displayEmpty: displayEmpty,
labelId: labelId,
MenuProps: MenuProps,
onClose: onClose,
onOpen: onOpen,
open: open,
renderValue: renderValue,
SelectDisplayProps: _extends({
id: id
}, SelectDisplayProps)
}, inputProps, {
classes: inputProps ? deepmerge(otherClasses, inputProps.classes) : otherClasses
}, input ? input.props.inputProps : {})
}, multiple && native && variant === 'outlined' ? {
notched: true
} : {}, {
ref: ref,
className: clsx(classes.root, InputComponent.props.className, className)
}, other));
});
process.env.NODE_ENV !== "production" ? Select.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, the width of the popover will automatically be set according to the items inside the
* menu, otherwise it will be at least the width of the select input.
* @default false
*/
autoWidth: PropTypes.bool,
/**
* The option elements to populate the select with.
* Can be some `MenuItem` when `native` is false and `option` when `native` is true.
*
* ⚠️The `MenuItem` elements **must** be direct descendants when `native` is false.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* @default {}
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, a value is displayed even if no items are selected.
*
* In order to display a meaningful value, a function can be passed to the `renderValue` prop which
* returns the value to be displayed when no items are selected.
*
* ⚠️ When using this prop, make sure the label doesn't overlap with the empty displayed value.
* The label should either be hidden or forced to a shrunk state.
* @default false
*/
displayEmpty: PropTypes.bool,
/**
* The icon that displays the arrow.
* @default ArrowDropDownIcon
*/
IconComponent: PropTypes.elementType,
/**
* The `id` of the wrapper element or the `select` element when `native`.
*/
id: PropTypes.string,
/**
* An `Input` element; does not have to be a material-ui specific `Input`.
*/
input: PropTypes.element,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
* When `native` is `true`, the attributes are applied on the `select` element.
*/
inputProps: PropTypes.object,
/**
* See [OutlinedInput#label](/api/outlined-input/#props)
*/
label: PropTypes.node,
/**
* The ID of an element that acts as an additional label. The Select will
* be labelled by the additional label and the selected value.
*/
labelId: PropTypes.string,
/**
* Props applied to the [`Menu`](/api/menu/) element.
*/
MenuProps: PropTypes.object,
/**
* If `true`, `value` must be an array and the menu will support multiple selections.
* @default false
*/
multiple: PropTypes.bool,
/**
* If `true`, the component uses a native `select` element.
* @default false
*/
native: PropTypes.bool,
/**
* Callback fired when a menu item is selected.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* **Warning**: This is a generic event not a change event.
* @param {object} [child] The react element that was selected when `native` is `false` (default).
*/
onChange: PropTypes.func,
/**
* Callback fired when the component requests to be closed.
* Use in controlled mode (see open).
*
* @param {object} event The event source of the callback.
*/
onClose: PropTypes.func,
/**
* Callback fired when the component requests to be opened.
* Use in controlled mode (see open).
*
* @param {object} event The event source of the callback.
*/
onOpen: PropTypes.func,
/**
* If `true`, the component is shown.
* You can only use it when the `native` prop is `false` (default).
*/
open: PropTypes.bool,
/**
* Render the selected value.
* You can only use it when the `native` prop is `false` (default).
*
* @param {any} value The `value` provided to the component.
* @returns {ReactNode}
*/
renderValue: PropTypes.func,
/**
* Props applied to the clickable div element.
*/
SelectDisplayProps: PropTypes.object,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object,
/**
* The `input` value. Providing an empty string will select no options.
* Set to an empty string `''` if you don't want any of the available options to be selected.
*
* If the value is an object it must have reference equality with the option in order to be selected.
* If the value is not an object, the string representation must match with the string representation of the option in order to be selected.
*/
value: PropTypes.any,
/**
* The variant to use.
* @default 'outlined'
*/
variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])
} : void 0;
Select.muiName = 'Select';
export default Select; | mit |
cdnjs/cdnjs | ajax/libs/simple-icons/1.9.11/adobepremiere.js | 988 | module.exports={"title":"Adobe Premiere","hex":"EA77FF","source":"https://helpx.adobe.com/content/dam/help/mnemonics/pr_cc_app_RGB.svg","svg":"<svg aria-labelledby=\"simpleicons-adobepremiere-icon\" role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><title id=\"simpleicons-adobepremiere-icon\">Adobe Premiere icon</title><path d=\"M0 .3v23.4h24V.3zm1 1h22v21.4H1z\"/><path d=\"M6.297 5.778c0-.066.017-.116.1-.116.643-.033 1.583-.05 2.573-.05 2.772 0 3.977 1.519 3.977 3.466 0 2.54-1.839 3.63-4.099 3.63-.38 0-.512-.017-.776-.017v3.843c0 .083-.033.116-.115.116H6.413c-.083 0-.116-.033-.116-.116zm1.775 5.313c.231.016.413.016.809.016 1.171 0 2.267-.412 2.267-1.996 0-1.27-.782-1.914-2.119-1.914-.396 0-.775.016-.957.033zm6.4-.908c0-.115 0-.412-.049-.973 0-.083.011-.1.077-.132a10.42 10.42 0 0 1 3.657-.693c.082 0 .115.016.115.099v1.452c0 .082-.026.099-.109.099a5.725 5.725 0 0 0-1.89.198v6.301c0 .083-.034.116-.116.116h-1.57c-.082 0-.115-.033-.115-.116z\"/></svg>\n"}; | mit |
sudaraka94/che | core/che-core-db/src/test/java/org/eclipse/che/core/db/schema/impl/flyway/FlywaySchemaInitializerTest.java | 11784 | /*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.core.db.schema.impl.flyway;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import java.io.IOException;
import java.io.StringReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import javax.sql.DataSource;
import org.eclipse.che.commons.lang.IoUtil;
import org.eclipse.che.core.db.schema.SchemaInitializationException;
import org.eclipse.che.core.db.schema.SchemaInitializer;
import org.flywaydb.core.internal.util.PlaceholderReplacer;
import org.h2.jdbcx.JdbcDataSource;
import org.h2.tools.RunScript;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* Tests {@link FlywaySchemaInitializer}.
*
* @author Yevhenii Voevodin
*/
public class FlywaySchemaInitializerTest {
private static final String SCRIPTS_ROOT = "flyway/sql";
private JdbcDataSource dataSource;
@BeforeMethod
public void setUp() throws URISyntaxException {
dataSource = new JdbcDataSource();
dataSource.setUrl("jdbc:h2:mem:flyway_test;DB_CLOSE_DELAY=-1");
}
@AfterMethod
public void cleanup() throws SQLException, URISyntaxException {
try (Connection conn = dataSource.getConnection()) {
RunScript.execute(conn, new StringReader("SHUTDOWN"));
}
IoUtil.deleteRecursive(targetDir().resolve(Paths.get(SCRIPTS_ROOT)).toFile());
}
@Test
public void initializesSchemaWhenDatabaseIsEmpty() throws Exception {
createScript("1.0/1__init.sql", "CREATE TABLE test (id INT, text TEXT, PRIMARY KEY (id));");
createScript(
"1.0/2__add_data.sql",
"INSERT INTO test VALUES(1, 'test1');"
+ "INSERT INTO test VALUES(2, 'test2');"
+ "INSERT INTO test VALUES(3, 'test3');");
createScript("2.0/1__add_more_data.sql", "INSERT INTO test VALUES(4, 'test4');");
createScript(
"2.0/postgresql/1__add_more_data.sql", "INSERT INTO test VALUES(4, 'postgresql-data');");
final SchemaInitializer initializer = FlywayInitializerBuilder.from(dataSource).build();
initializer.init();
assertEquals(
queryEntities(),
Sets.newHashSet(
new TestEntity(1, "test1"),
new TestEntity(2, "test2"),
new TestEntity(3, "test3"),
new TestEntity(4, "test4")));
// second init must do nothing, so there are no conflicts
initializer.init();
}
@Test(expectedExceptions = SchemaInitializationException.class)
public void failsIfBaseLineIsNotConfiguredProperly() throws Exception {
execQuery(
"CREATE TABLE test (id INT, text TEXT, PRIMARY KEY (id));"
+ "INSERT INTO test VALUES(1, 'test1');"
+ "INSERT INTO test VALUES(2, 'test2');"
+ "INSERT INTO test VALUES(3, 'test3');");
createScript("1.0/1__init.sql", "CREATE TABLE test (id INT, text TEXT, PRIMARY KEY (id));");
FlywayInitializerBuilder.from(dataSource)
.setBaselineOnMigrate(true)
.setBaselineVersion("1.0")
.build()
.init();
}
@Test
public void executesOnlyThoseMigrationsWhichGoAfterBaseline() throws Exception {
execQuery("CREATE TABLE test (id INT, text TEXT, PRIMARY KEY (id));");
createScript("1.0/1__init.sql", "CREATE TABLE test (id INT, text TEXT, PRIMARY KEY (id));");
createScript(
"2.0/1__add_data.sql",
"INSERT INTO test VALUES(1, 'test1');"
+ "INSERT INTO test VALUES(2, 'test2');"
+ "INSERT INTO test VALUES(3, 'test3');");
final FlywaySchemaInitializer initializer =
FlywayInitializerBuilder.from(dataSource)
.setBaselineOnMigrate(true)
.setBaselineVersion("1.0.1")
.build();
initializer.init();
assertEquals(
queryEntities(),
Sets.newHashSet(
new TestEntity(1, "test1"), new TestEntity(2, "test2"), new TestEntity(3, "test3")));
// second init must do nothing, so there are no conflicts
initializer.init();
}
@Test
public void initializesSchemaWhenDatabaseIsEmptyAndBaselineIsConfigured() throws Exception {
createScript("1.0/1__init.sql", "CREATE TABLE test (id INT, text TEXT, PRIMARY KEY (id));");
createScript(
"2.0/1__add_data.sql",
"INSERT INTO test VALUES(1, 'test1');"
+ "INSERT INTO test VALUES(2, 'test2');"
+ "INSERT INTO test VALUES(3, 'test3');");
final FlywaySchemaInitializer initializer =
FlywayInitializerBuilder.from(dataSource)
.setBaselineOnMigrate(true)
.setBaselineVersion("1.0.1")
.build();
initializer.init();
assertEquals(
queryEntities(),
Sets.newHashSet(
new TestEntity(1, "test1"), new TestEntity(2, "test2"), new TestEntity(3, "test3")));
// second init must do nothing, so there are no conflicts
initializer.init();
}
@Test
public void selectsProviderSpecificScriptsInPreferenceToDefaultOnes() throws Exception {
createScript("1.0/1__init.sql", "CREATE TABLE test (id INT, text TEXT, PRIMARY KEY (id));");
createScript("2.0/1__add_data.sql", "INSERT INTO test VALUES(1, 'default data');");
createScript("2.0/h2/1__add_data.sql", "INSERT INTO test VALUES(1, 'h2 data');");
final FlywaySchemaInitializer initializer = FlywayInitializerBuilder.from(dataSource).build();
initializer.init();
assertEquals(queryEntities(), Sets.newHashSet(new TestEntity(1, "h2 data")));
// second init must do nothing, so there are no conflicts
initializer.init();
}
@Test
public void replacesVariablesWhenPlaceholderReplacerIsConfigured() throws Exception {
createScript(
"1.0/1__init.sql",
"CREATE TABLE test (id INT, text TEXT, PRIMARY KEY (id));"
+ "INSERT INTO test VALUES(1, '${variable}');");
FlywayInitializerBuilder.from(dataSource)
.setReplacer(new PlaceholderReplacer(ImmutableMap.of("variable", "test"), "${", "}"))
.build()
.init();
assertEquals(queryEntities(), Sets.newHashSet(new TestEntity(1, "test")));
}
private Set<TestEntity> queryEntities() throws SQLException {
final Set<TestEntity> entities = new HashSet<>();
try (Connection conn = dataSource.getConnection()) {
final ResultSet result = RunScript.execute(conn, new StringReader("SELECT * FROM test"));
while (result.next()) {
entities.add(new TestEntity(result.getLong("id"), result.getString("text")));
}
}
return entities;
}
private ResultSet execQuery(String query) throws SQLException {
try (Connection conn = dataSource.getConnection()) {
return RunScript.execute(conn, new StringReader(query));
}
}
private static Path createScript(String relativePath, String content)
throws URISyntaxException, IOException {
return createFile(
targetDir().resolve(Paths.get(SCRIPTS_ROOT)).resolve(relativePath).toString(), content);
}
private static Path createFile(String filepath, String content)
throws URISyntaxException, IOException {
final Path path = targetDir().resolve(Paths.get(filepath));
if (!Files.exists(path.getParent())) {
Files.createDirectories(path.getParent());
}
Files.write(path, content.getBytes(StandardCharsets.UTF_8));
return path;
}
private static Path targetDir() throws URISyntaxException {
final URL url = Thread.currentThread().getContextClassLoader().getResource(".");
assertNotNull(url);
return Paths.get(url.toURI()).getParent();
}
private static class TestEntity {
final long id;
final String text;
private TestEntity(long id, String text) {
this.id = id;
this.text = text;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof TestEntity)) {
return false;
}
final TestEntity that = (TestEntity) obj;
return id == that.id && Objects.equals(text, that.text);
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + Long.hashCode(id);
hash = 31 * hash + Objects.hashCode(text);
return hash;
}
@Override
public String toString() {
return "TestEntity{" + "id=" + id + ", text='" + text + '\'' + '}';
}
}
private static class FlywayInitializerBuilder {
public static FlywayInitializerBuilder from(DataSource dataSource) {
try {
final String scriptsRoot = targetDir().resolve(Paths.get(SCRIPTS_ROOT)).toString();
return new FlywayInitializerBuilder()
.setDataSource(dataSource)
.setScriptsPrefix("")
.setScriptsSuffix(".sql")
.setVersionSeparator("__")
.setReplacer(PlaceholderReplacer.NO_PLACEHOLDERS)
.setBaselineOnMigrate(false)
.addLocation("filesystem:" + scriptsRoot);
} catch (Exception x) {
throw new RuntimeException(x.getMessage(), x);
}
}
private DataSource dataSource;
private List<String> locations;
private String scriptsPrefix;
private String scriptsSuffix;
private String versionSeparator;
private boolean baselineOnMigrate;
private String baselineVersion;
private PlaceholderReplacer replacer;
public FlywayInitializerBuilder setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
return this;
}
public FlywayInitializerBuilder setReplacer(PlaceholderReplacer replacer) {
this.replacer = replacer;
return this;
}
public FlywayInitializerBuilder addLocation(String location) {
if (locations == null) {
locations = new ArrayList<>();
}
locations.add(location);
return this;
}
public FlywayInitializerBuilder setScriptsPrefix(String scriptsPrefix) {
this.scriptsPrefix = scriptsPrefix;
return this;
}
public FlywayInitializerBuilder setScriptsSuffix(String scriptsSuffix) {
this.scriptsSuffix = scriptsSuffix;
return this;
}
public FlywayInitializerBuilder setVersionSeparator(String versionSeparator) {
this.versionSeparator = versionSeparator;
return this;
}
public FlywayInitializerBuilder setBaselineOnMigrate(boolean baselineOnMigrate) {
this.baselineOnMigrate = baselineOnMigrate;
return this;
}
public FlywayInitializerBuilder setBaselineVersion(String baselineVersion) {
this.baselineVersion = baselineVersion;
return this;
}
public FlywaySchemaInitializer build() {
if (locations == null) {
throw new IllegalStateException("locations required");
}
return new FlywaySchemaInitializer(
locations.toArray(new String[locations.size()]),
scriptsPrefix,
scriptsSuffix,
versionSeparator,
baselineOnMigrate,
baselineVersion,
dataSource,
replacer);
}
}
}
| epl-1.0 |
sudaraka94/che | ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/part/widgets/panemenu/PaneMenuTabItemWidget.java | 2754 | /*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.ide.part.widgets.panemenu;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import javax.validation.constraints.NotNull;
import org.eclipse.che.ide.api.parts.PartStackView.TabItem;
/**
* Implementation of {@link EditorPaneMenuItem} to displaying editor tab item in {@link
* EditorPaneMenu}
*
* @author Dmitry Shnurenko
* @author Vitaliy Guliy
*/
public class PaneMenuTabItemWidget extends Composite implements EditorPaneMenuItem<TabItem> {
interface PaneMenuTabItemWidgetUiBinder extends UiBinder<Widget, PaneMenuTabItemWidget> {}
private static final PaneMenuTabItemWidgetUiBinder UI_BINDER =
GWT.create(PaneMenuTabItemWidgetUiBinder.class);
private TabItem tabItem;
@UiField FlowPanel iconPanel;
@UiField Label title;
@UiField FlowPanel closeButton;
private ActionDelegate<TabItem> delegate;
public PaneMenuTabItemWidget(@NotNull TabItem tabItem) {
initWidget(UI_BINDER.createAndBindUi(this));
this.tabItem = tabItem;
Widget icon = tabItem.getIcon();
if (icon != null) {
iconPanel.add(icon);
}
title.setText(tabItem.getTitle());
addDomHandler(
new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if (delegate != null) {
delegate.onItemClicked(PaneMenuTabItemWidget.this);
}
}
},
ClickEvent.getType());
closeButton.addDomHandler(
new ClickHandler() {
@Override
public void onClick(ClickEvent clickEvent) {
clickEvent.stopPropagation();
clickEvent.preventDefault();
if (delegate != null) {
delegate.onCloseButtonClicked(PaneMenuTabItemWidget.this);
}
}
},
ClickEvent.getType());
}
/** {@inheritDoc} */
@Override
public void setDelegate(ActionDelegate<TabItem> delegate) {
this.delegate = delegate;
}
@Override
public TabItem getData() {
return tabItem;
}
}
| epl-1.0 |
sudaraka94/che | wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/vfs/search/Searcher.java | 2276 | /*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.api.vfs.search;
import org.eclipse.che.api.core.ServerException;
import org.eclipse.che.api.vfs.VirtualFile;
import org.eclipse.che.api.vfs.VirtualFileFilter;
/**
* @deprecated VFS components are now considered deprecated and will be replaced by standard JDK
* routines.
*/
@Deprecated
public interface Searcher {
/**
* Return paths of matched items on virtual filesystem.
*
* @param query query expression
* @return results of search
* @throws ServerException if an error occurs
*/
SearchResult search(QueryExpression query) throws ServerException;
/**
* Add VirtualFile to index.
*
* @param virtualFile VirtualFile to add
* @throws ServerException if an error occurs
*/
void add(VirtualFile virtualFile) throws ServerException;
/**
* Delete VirtualFile from index.
*
* @param path path of VirtualFile
* @throws ServerException if an error occurs
*/
void delete(String path, boolean isFile) throws ServerException;
/**
* Updated indexed VirtualFile.
*
* @param virtualFile VirtualFile to add
* @throws ServerException if an error occurs
*/
void update(VirtualFile virtualFile) throws ServerException;
/** Close Searcher. */
void close();
boolean isClosed();
/**
* Add filter to prevent adding files in index.
*
* @param indexFilter file filter
* @return {@code true} if filter accepted and {@code false} otherwise, e.g. if filter already
* added
*/
boolean addIndexFilter(VirtualFileFilter indexFilter);
/**
* Remove filter to prevent adding files in index.
*
* @param indexFilter file filter
* @return {@code true} if filter successfully removed and {@code false} otherwise, e.g. if filter
* was not added before with method {@link #addIndexFilter(VirtualFileFilter)}
*/
boolean removeIndexFilter(VirtualFileFilter indexFilter);
}
| epl-1.0 |
echoes-tech/eclipse.jsdt.core | org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/IErrorHandlingPolicy.java | 1133 | /*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.jsdt.internal.compiler;
/*
* Handler policy is responsible to answer the 2 following
* questions:
* 1. should the handler stop on first problem which appears
* to be a real error (that is, not a warning),
* 2. should it proceed once it has gathered all problems
*
* The intent is that one can supply its own policy to implement
* some interactive error handling strategy where some UI would
* display problems and ask user if he wants to proceed or not.
*/
public interface IErrorHandlingPolicy {
boolean proceedOnErrors();
boolean stopOnFirstError();
}
| epl-1.0 |
sarpkayanehta/mdht | hl7/plugins/org.openhealthtools.mdht.emf.hl7.mif2/src/org/openhealthtools/mdht/emf/hl7/mif2/internal/impl/ArtifactCrossReferenceImpl.java | 9313 | /*******************************************************************************
* Copyright (c) 2006, 2009 David A Carlson
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David A Carlson (XMLmodeling.com) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.emf.hl7.mif2.internal.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.openhealthtools.mdht.emf.hl7.mif2.ArtifactCrossReference;
import org.openhealthtools.mdht.emf.hl7.mif2.ElementDerivation;
import org.openhealthtools.mdht.emf.hl7.mif2.Mif2Package;
import org.openhealthtools.mdht.emf.hl7.mif2.PackageOrArtifactRef;
import org.openhealthtools.mdht.emf.hl7.mif2.PackageRef;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Artifact Cross Reference</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.internal.impl.ArtifactCrossReferenceImpl#getDerivedFrom <em>Derived From</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.internal.impl.ArtifactCrossReferenceImpl#getImportedPackage <em>Imported Package</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.internal.impl.ArtifactCrossReferenceImpl#getDependentOnElement <em>Dependent On Element</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.hl7.mif2.internal.impl.ArtifactCrossReferenceImpl#getContainedElements <em>Contained Elements</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ArtifactCrossReferenceImpl extends PackageArtifactImpl implements ArtifactCrossReference {
/**
* The cached value of the '{@link #getDerivedFrom() <em>Derived From</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDerivedFrom()
* @generated
* @ordered
*/
protected EList<ElementDerivation> derivedFrom;
/**
* The cached value of the '{@link #getImportedPackage() <em>Imported Package</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getImportedPackage()
* @generated
* @ordered
*/
protected EList<PackageRef> importedPackage;
/**
* The cached value of the '{@link #getDependentOnElement() <em>Dependent On Element</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDependentOnElement()
* @generated
* @ordered
*/
protected EList<PackageOrArtifactRef> dependentOnElement;
/**
* The cached value of the '{@link #getContainedElements() <em>Contained Elements</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getContainedElements()
* @generated
* @ordered
*/
protected EList<ArtifactCrossReference> containedElements;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ArtifactCrossReferenceImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Mif2Package.Literals.ARTIFACT_CROSS_REFERENCE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ElementDerivation> getDerivedFrom() {
if (derivedFrom == null) {
derivedFrom = new EObjectContainmentEList<ElementDerivation>(
ElementDerivation.class, this, Mif2Package.ARTIFACT_CROSS_REFERENCE__DERIVED_FROM);
}
return derivedFrom;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<PackageRef> getImportedPackage() {
if (importedPackage == null) {
importedPackage = new EObjectContainmentEList<PackageRef>(
PackageRef.class, this, Mif2Package.ARTIFACT_CROSS_REFERENCE__IMPORTED_PACKAGE);
}
return importedPackage;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<PackageOrArtifactRef> getDependentOnElement() {
if (dependentOnElement == null) {
dependentOnElement = new EObjectContainmentEList<PackageOrArtifactRef>(
PackageOrArtifactRef.class, this, Mif2Package.ARTIFACT_CROSS_REFERENCE__DEPENDENT_ON_ELEMENT);
}
return dependentOnElement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ArtifactCrossReference> getContainedElements() {
if (containedElements == null) {
containedElements = new EObjectContainmentEList<ArtifactCrossReference>(
ArtifactCrossReference.class, this, Mif2Package.ARTIFACT_CROSS_REFERENCE__CONTAINED_ELEMENTS);
}
return containedElements;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Mif2Package.ARTIFACT_CROSS_REFERENCE__DERIVED_FROM:
return ((InternalEList<?>) getDerivedFrom()).basicRemove(otherEnd, msgs);
case Mif2Package.ARTIFACT_CROSS_REFERENCE__IMPORTED_PACKAGE:
return ((InternalEList<?>) getImportedPackage()).basicRemove(otherEnd, msgs);
case Mif2Package.ARTIFACT_CROSS_REFERENCE__DEPENDENT_ON_ELEMENT:
return ((InternalEList<?>) getDependentOnElement()).basicRemove(otherEnd, msgs);
case Mif2Package.ARTIFACT_CROSS_REFERENCE__CONTAINED_ELEMENTS:
return ((InternalEList<?>) getContainedElements()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Mif2Package.ARTIFACT_CROSS_REFERENCE__DERIVED_FROM:
return getDerivedFrom();
case Mif2Package.ARTIFACT_CROSS_REFERENCE__IMPORTED_PACKAGE:
return getImportedPackage();
case Mif2Package.ARTIFACT_CROSS_REFERENCE__DEPENDENT_ON_ELEMENT:
return getDependentOnElement();
case Mif2Package.ARTIFACT_CROSS_REFERENCE__CONTAINED_ELEMENTS:
return getContainedElements();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Mif2Package.ARTIFACT_CROSS_REFERENCE__DERIVED_FROM:
getDerivedFrom().clear();
getDerivedFrom().addAll((Collection<? extends ElementDerivation>) newValue);
return;
case Mif2Package.ARTIFACT_CROSS_REFERENCE__IMPORTED_PACKAGE:
getImportedPackage().clear();
getImportedPackage().addAll((Collection<? extends PackageRef>) newValue);
return;
case Mif2Package.ARTIFACT_CROSS_REFERENCE__DEPENDENT_ON_ELEMENT:
getDependentOnElement().clear();
getDependentOnElement().addAll((Collection<? extends PackageOrArtifactRef>) newValue);
return;
case Mif2Package.ARTIFACT_CROSS_REFERENCE__CONTAINED_ELEMENTS:
getContainedElements().clear();
getContainedElements().addAll((Collection<? extends ArtifactCrossReference>) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Mif2Package.ARTIFACT_CROSS_REFERENCE__DERIVED_FROM:
getDerivedFrom().clear();
return;
case Mif2Package.ARTIFACT_CROSS_REFERENCE__IMPORTED_PACKAGE:
getImportedPackage().clear();
return;
case Mif2Package.ARTIFACT_CROSS_REFERENCE__DEPENDENT_ON_ELEMENT:
getDependentOnElement().clear();
return;
case Mif2Package.ARTIFACT_CROSS_REFERENCE__CONTAINED_ELEMENTS:
getContainedElements().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Mif2Package.ARTIFACT_CROSS_REFERENCE__DERIVED_FROM:
return derivedFrom != null && !derivedFrom.isEmpty();
case Mif2Package.ARTIFACT_CROSS_REFERENCE__IMPORTED_PACKAGE:
return importedPackage != null && !importedPackage.isEmpty();
case Mif2Package.ARTIFACT_CROSS_REFERENCE__DEPENDENT_ON_ELEMENT:
return dependentOnElement != null && !dependentOnElement.isEmpty();
case Mif2Package.ARTIFACT_CROSS_REFERENCE__CONTAINED_ELEMENTS:
return containedElements != null && !containedElements.isEmpty();
}
return super.eIsSet(featureID);
}
} // ArtifactCrossReferenceImpl
| epl-1.0 |
lbchen/odl-mod | opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ConfigurationObject.java | 400 |
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.sal.utils;
public interface ConfigurationObject {
}
| epl-1.0 |
sudaraka94/che | plugins/plugin-debugger/che-plugin-debugger-ide/src/main/java/org/eclipse/che/plugin/debugger/ide/debug/expression/EvaluateExpressionView.java | 2004 | /*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.plugin.debugger.ide.debug.expression;
import javax.validation.constraints.NotNull;
import org.eclipse.che.ide.api.mvp.View;
/**
* The view of {@link EvaluateExpressionPresenter}.
*
* @author <a href="mailto:aplotnikov@codenvy.com">Andrey Plotnikov</a>
*/
public interface EvaluateExpressionView extends View<EvaluateExpressionView.ActionDelegate> {
/** Needs for delegate some function into EvaluateExpression view. */
public interface ActionDelegate {
/** Performs any actions appropriate in response to the user having pressed the Close button. */
void onCloseClicked();
/**
* Performs any actions appropriate in response to the user having pressed the Evaluate button.
*/
void onEvaluateClicked();
/** Performs any actions appropriate in response to the user having changed expression. */
void onExpressionValueChanged();
}
/**
* Get expression field value.
*
* @return {@link String}
*/
@NotNull
String getExpression();
/**
* Set expression field value.
*
* @param expression
*/
void setExpression(@NotNull String expression);
/**
* Set result field value.
*
* @param value result field value
*/
void setResult(@NotNull String value);
/**
* Change the enable state of the evaluate button.
*
* @param enabled <code>true</code> to enable the button, <code>false</code> to disable it
*/
void setEnableEvaluateButton(boolean enabled);
/** Give focus to expression field. */
void focusInExpressionField();
/** Close dialog. */
void close();
/** Show dialog. */
void showDialog();
}
| epl-1.0 |
sleshchenko/che | plugins/plugin-java/che-plugin-java-ext-lang-server/src/test/resources/RenamePackage/testFail7/in/p1/A.java | 90 | package p1;
class B{
void m(AA fred){
r.A.length();
}
}
class AA{
static String A;
}
| epl-1.0 |
jarlebh/openhab2-addons | addons/io/org.openhab.io.neeo/src/main/java/org/openhab/io/neeo/internal/serialization/NeeoDeviceSerializer.java | 9046 | /**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.io.neeo.internal.serialization;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.type.ThingType;
import org.openhab.io.neeo.NeeoService;
import org.openhab.io.neeo.internal.NeeoBrainServlet;
import org.openhab.io.neeo.internal.NeeoConstants;
import org.openhab.io.neeo.internal.NeeoDeviceKeys;
import org.openhab.io.neeo.internal.NeeoUtil;
import org.openhab.io.neeo.internal.ServiceContext;
import org.openhab.io.neeo.internal.models.NeeoDevice;
import org.openhab.io.neeo.internal.models.NeeoDeviceChannel;
import org.openhab.io.neeo.internal.models.NeeoDeviceTiming;
import org.openhab.io.neeo.internal.models.NeeoDeviceType;
import org.openhab.io.neeo.internal.models.NeeoThingUID;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
/**
* Implementation of {@link JsonSerializer} and {@link JsonDeserializer} to serialize/deserial
* {@link NeeoDevice}. This implementation should NOT be used in communications with the NEEO brain (use
* {@link NeeoBrainDeviceSerializer} instead)
*
* @author Tim Roberts - Initial Contribution
*/
@NonNullByDefault
public class NeeoDeviceSerializer implements JsonSerializer<NeeoDevice>, JsonDeserializer<NeeoDevice> {
/** The service */
@Nullable
private final NeeoService service;
/** The service context */
@Nullable
private final ServiceContext context;
/**
* Constructs the object with no service or context
*/
public NeeoDeviceSerializer() {
this(null, null);
}
/**
* Constructs the object from the service and context. A null service or context will suppress certain values on the
* returned json object
*
* @param service the possibly null service
* @param context the possibly null context
*/
public NeeoDeviceSerializer(@Nullable NeeoService service, @Nullable ServiceContext context) {
this.service = service;
this.context = context;
}
@Override
public NeeoDevice deserialize(@Nullable JsonElement elm, @Nullable Type type,
@Nullable JsonDeserializationContext jsonContext) throws JsonParseException {
Objects.requireNonNull(elm, "elm cannot be null");
Objects.requireNonNull(type, "type cannot be null");
Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
if (!(elm instanceof JsonObject)) {
throw new JsonParseException("Element not an instance of JsonObject: " + elm);
}
final JsonObject jo = (JsonObject) elm;
final NeeoThingUID uid = jsonContext.deserialize(jo.get("uid"), NeeoThingUID.class);
final NeeoDeviceType devType = jsonContext.deserialize(jo.get("type"), NeeoDeviceType.class);
final String manufacturer = NeeoUtil.getString(jo, "manufacturer");
final String name = NeeoUtil.getString(jo, "name");
final NeeoDeviceChannel[] channels = jsonContext.deserialize(jo.get("channels"), NeeoDeviceChannel[].class);
final NeeoDeviceTiming timing = jo.has("timing")
? jsonContext.deserialize(jo.get("timing"), NeeoDeviceTiming.class)
: null;
final String[] deviceCapabilities = jo.has("deviceCapabilities")
? jsonContext.deserialize(jo.get("deviceCapabilities"), String[].class)
: null;
final String specificName = jo.has("specificName") ? jo.get("specificName").getAsString() : null;
final String iconName = jo.has("iconName") ? jo.get("iconName").getAsString() : null;
try {
return new NeeoDevice(uid, devType,
manufacturer == null || StringUtils.isEmpty(manufacturer) ? NeeoUtil.NOTAVAILABLE : manufacturer,
name, Arrays.asList(channels), timing,
deviceCapabilities == null ? null : Arrays.asList(deviceCapabilities), specificName, iconName);
} catch (NullPointerException | IllegalArgumentException e) {
throw new JsonParseException(e);
}
}
@Override
public JsonElement serialize(NeeoDevice device, @Nullable Type deviceType,
@Nullable JsonSerializationContext jsonContext) {
Objects.requireNonNull(device, "device cannot be null");
Objects.requireNonNull(deviceType, "deviceType cannot be null");
Objects.requireNonNull(jsonContext, "jsonContext cannot be null");
final JsonObject jsonObject = new JsonObject();
final NeeoThingUID uid = device.getUid();
jsonObject.add("uid", jsonContext.serialize(uid));
jsonObject.add("type", jsonContext.serialize(device.getType()));
jsonObject.addProperty("manufacturer", device.getManufacturer());
jsonObject.addProperty("name", device.getName());
jsonObject.addProperty("specificName", device.getSpecificName());
jsonObject.addProperty("iconName", device.getIconName());
final JsonArray channels = (JsonArray) jsonContext.serialize(device.getChannels());
final NeeoDeviceTiming timing = device.getDeviceTiming();
jsonObject.add("timing", jsonContext.serialize(timing == null ? new NeeoDeviceTiming() : timing));
jsonObject.add("deviceCapabilities", jsonContext.serialize(device.getDeviceCapabilities()));
jsonObject.addProperty("thingType", uid.getThingType());
if (StringUtils.equalsIgnoreCase(NeeoConstants.NEEOIO_BINDING_ID, uid.getBindingId())) {
jsonObject.addProperty("thingStatus", uid.getThingType().toUpperCase());
}
final ServiceContext localContext = context;
if (localContext != null) {
if (!StringUtils.equalsIgnoreCase(NeeoConstants.NEEOIO_BINDING_ID, uid.getBindingId())) {
final Thing thing = localContext.getThingRegistry().get(device.getUid().asThingUID());
jsonObject.addProperty("thingStatus",
thing == null ? ThingStatus.UNKNOWN.name() : thing.getStatus().name());
if (thing != null) {
final ThingType thingType = localContext.getThingTypeRegistry()
.getThingType(thing.getThingTypeUID());
if (thingType != null) {
for (JsonElement chnl : channels) {
JsonObject jo = (JsonObject) chnl;
if (jo.has("groupId") && jo.has("itemLabel")) {
final String groupId = jo.get("groupId").getAsString();
final String groupLabel = NeeoUtil.getGroupLabel(thingType, groupId);
if (StringUtils.isNotEmpty(groupLabel)) {
final JsonElement itemLabel = jo.remove("itemLabel");
jo.addProperty("itemLabel", groupLabel + "#" + itemLabel.getAsString());
} else if (StringUtils.isNotEmpty("groupId")) {
// have a groupid but no group definition found (usually error on binding)
// just default to "Others" like the Paperui does.
final JsonElement itemLabel = jo.remove("itemLabel");
jo.addProperty("itemLabel", "Others#" + itemLabel.getAsString());
}
}
}
}
}
}
}
jsonObject.add("channels", channels);
final NeeoService localService = service;
if (localService != null) {
List<String> foundKeys = new ArrayList<>();
for (final NeeoBrainServlet servlet : localService.getServlets()) {
final NeeoDeviceKeys servletKeys = servlet.getDeviceKeys();
final Set<String> keys = servletKeys.get(device.getUid());
foundKeys.addAll(keys);
}
jsonObject.add("keys", jsonContext.serialize(foundKeys));
}
return jsonObject;
}
}
| epl-1.0 |
sudaraka94/che | plugins/plugin-maven/che-plugin-maven-server/src/main/java/org/eclipse/che/plugin/maven/server/inject/MavenModule.java | 4302 | /*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.plugin.maven.server.inject;
import static com.google.inject.multibindings.Multibinder.newSetBinder;
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import com.google.inject.multibindings.Multibinder;
import java.util.Collections;
import org.eclipse.che.api.languageserver.launcher.LanguageServerLauncher;
import org.eclipse.che.api.languageserver.shared.model.LanguageDescription;
import org.eclipse.che.api.project.server.handlers.ProjectHandler;
import org.eclipse.che.api.project.server.type.ProjectTypeDef;
import org.eclipse.che.api.project.server.type.ValueProviderFactory;
import org.eclipse.che.inject.DynaModule;
import org.eclipse.che.maven.server.MavenTerminal;
import org.eclipse.che.plugin.maven.generator.archetype.MavenArchetypeJsonRpcMessenger;
import org.eclipse.che.plugin.maven.lsp.MavenLanguageServerLauncher;
import org.eclipse.che.plugin.maven.server.PomModificationDetector;
import org.eclipse.che.plugin.maven.server.core.MavenJsonRpcCommunication;
import org.eclipse.che.plugin.maven.server.core.MavenProgressNotifier;
import org.eclipse.che.plugin.maven.server.core.MavenServerNotifier;
import org.eclipse.che.plugin.maven.server.core.MavenTerminalImpl;
import org.eclipse.che.plugin.maven.server.core.project.PomChangeListener;
import org.eclipse.che.plugin.maven.server.projecttype.MavenProjectType;
import org.eclipse.che.plugin.maven.server.projecttype.MavenValueProviderFactory;
import org.eclipse.che.plugin.maven.server.projecttype.handler.ArchetypeGenerationStrategy;
import org.eclipse.che.plugin.maven.server.projecttype.handler.GeneratorStrategy;
import org.eclipse.che.plugin.maven.server.projecttype.handler.MavenProjectGenerator;
import org.eclipse.che.plugin.maven.server.projecttype.handler.MavenProjectInitHandler;
import org.eclipse.che.plugin.maven.server.projecttype.handler.SimpleGeneratorStrategy;
import org.eclipse.che.plugin.maven.server.rest.MavenServerService;
/** @author Artem Zatsarynnyi */
@DynaModule
public class MavenModule extends AbstractModule {
@Override
protected void configure() {
newSetBinder(binder(), ValueProviderFactory.class)
.addBinding()
.to(MavenValueProviderFactory.class);
//bind maven project type only if maven installed on dev machine
if (System.getenv("M2_HOME") != null) {
newSetBinder(binder(), ProjectTypeDef.class).addBinding().to(MavenProjectType.class);
}
Multibinder<ProjectHandler> projectHandlerMultibinder =
newSetBinder(binder(), ProjectHandler.class);
projectHandlerMultibinder.addBinding().to(MavenProjectGenerator.class);
projectHandlerMultibinder.addBinding().to(MavenProjectInitHandler.class);
Multibinder<GeneratorStrategy> generatorStrategyMultibinder =
newSetBinder(binder(), GeneratorStrategy.class);
generatorStrategyMultibinder.addBinding().to(SimpleGeneratorStrategy.class);
generatorStrategyMultibinder.addBinding().to(ArchetypeGenerationStrategy.class);
bind(MavenTerminal.class).to(MavenTerminalImpl.class).in(Singleton.class);
bind(MavenProgressNotifier.class).to(MavenServerNotifier.class).in(Singleton.class);
bind(MavenServerService.class);
bind(MavenJsonRpcCommunication.class);
bind(MavenArchetypeJsonRpcMessenger.class);
bind(PomChangeListener.class).asEagerSingleton();
bind(PomModificationDetector.class).asEagerSingleton();
Multibinder.newSetBinder(binder(), LanguageServerLauncher.class)
.addBinding()
.to(MavenLanguageServerLauncher.class)
.asEagerSingleton();
;
LanguageDescription description = new LanguageDescription();
description.setLanguageId("pom");
description.setMimeType("application/pom");
description.setFileNames(Collections.singletonList("pom.xml"));
Multibinder.newSetBinder(binder(), LanguageDescription.class)
.addBinding()
.toInstance(description);
}
}
| epl-1.0 |
rarguello/ironjacamar | core/src/main/java/org/ironjacamar/core/bootstrapcontext/BootstrapContextImpl.java | 3991 | /*
* IronJacamar, a Java EE Connector Architecture implementation
* Copyright 2015, Red Hat Inc, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the Eclipse Public License 1.0 as
* published by the Free Software Foundation.
*
* This software 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 Eclipse
* Public License for more details.
*
* You should have received a copy of the Eclipse Public License
* along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.ironjacamar.core.bootstrapcontext;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import javax.resource.spi.BootstrapContext;
import javax.resource.spi.XATerminator;
import javax.resource.spi.work.HintsContext;
import javax.resource.spi.work.SecurityContext;
import javax.resource.spi.work.TransactionContext;
import javax.resource.spi.work.WorkContext;
import javax.resource.spi.work.WorkManager;
import javax.transaction.TransactionSynchronizationRegistry;
/**
* Basic BootstrapContext implementation
* @author <a href="mailto:jesper.pedersen@ironjacamar.org">Jesper Pedersen</a>
*/
public class BootstrapContextImpl implements BootstrapContext
{
/** Work Manager */
private WorkManager workManager;
/** Transaction synchronization registry */
private TransactionSynchronizationRegistry transactionSynchronizationRegistry;
/** XATerminator */
private XATerminator xaTerminator;
/** Supported contexts */
private Set<Class> supportedContexts;
/** Timers */
private List<Timer> timers;
/**
* Constructor
* @param wm The WorkManager
* @param tsr The TransactionSynchronizationRegistry
* @param terminator The XATerminator
*/
public BootstrapContextImpl(WorkManager wm,
TransactionSynchronizationRegistry tsr,
XATerminator terminator)
{
this.workManager = wm;
this.transactionSynchronizationRegistry = tsr;
this.xaTerminator = terminator;
this.supportedContexts = new HashSet<Class>(3);
this.supportedContexts.add(HintsContext.class);
this.supportedContexts.add(SecurityContext.class);
this.supportedContexts.add(TransactionContext.class);
this.timers = null;
}
/**
* {@inheritDoc}
*/
public TransactionSynchronizationRegistry getTransactionSynchronizationRegistry()
{
return transactionSynchronizationRegistry;
}
/**
* {@inheritDoc}
*/
public WorkManager getWorkManager()
{
return workManager;
}
/**
* {@inheritDoc}
*/
public XATerminator getXATerminator()
{
return xaTerminator;
}
/**
* Create a timer
* @return The timer
*/
public Timer createTimer()
{
Timer t = new Timer(true);
if (timers == null)
timers = new ArrayList<Timer>();
timers.add(t);
return t;
}
/**
* Is the work context supported ?
* @param workContextClass The work context class
* @return True if supported; otherwise false
*/
public boolean isContextSupported(Class<? extends WorkContext> workContextClass)
{
if (workContextClass == null)
return false;
return supportedContexts.contains(workContextClass);
}
/**
* Shutdown
*/
public void shutdown()
{
if (timers != null)
{
for (Timer t : timers)
{
t.cancel();
t.purge();
}
}
}
}
| epl-1.0 |
alexVengrovsk/che-core | platform-api-client-gwt/che-core-client-gwt-user/src/main/java/org/eclipse/che/api/user/gwt/client/UserProfileServiceClientImpl.java | 4837 | /*******************************************************************************
* Copyright (c) 2012-2015 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.user.gwt.client;
import com.google.inject.Inject;
import org.eclipse.che.api.user.shared.dto.ProfileDescriptor;
import org.eclipse.che.ide.json.JsonHelper;
import org.eclipse.che.ide.rest.AsyncRequestCallback;
import org.eclipse.che.ide.rest.AsyncRequestFactory;
import org.eclipse.che.ide.rest.AsyncRequestLoader;
import org.eclipse.che.ide.rest.RestContext;
import javax.validation.constraints.NotNull;
import java.util.Map;
import static org.eclipse.che.ide.MimeType.APPLICATION_JSON;
import static org.eclipse.che.ide.rest.HTTPHeader.ACCEPT;
import static org.eclipse.che.ide.rest.HTTPHeader.CONTENT_TYPE;
/**
* Implementation for {@link UserProfileServiceClient}.
*
* @author Ann Shumilova
*/
public class UserProfileServiceClientImpl implements UserProfileServiceClient {
private final String PROFILE;
private final String PREFS;
private final AsyncRequestLoader loader;
private final AsyncRequestFactory asyncRequestFactory;
@Inject
protected UserProfileServiceClientImpl(@RestContext String restContext,
AsyncRequestLoader loader,
AsyncRequestFactory asyncRequestFactory) {
this.loader = loader;
this.asyncRequestFactory = asyncRequestFactory;
PROFILE = restContext + "/profile/";
PREFS = PROFILE + "prefs";
}
/** {@inheritDoc} */
@Override
public void getCurrentProfile(AsyncRequestCallback<ProfileDescriptor> callback) {
asyncRequestFactory.createGetRequest(PROFILE)
.header(ACCEPT, APPLICATION_JSON)
.loader(loader, "Retrieving current user's profile...")
.send(callback);
}
/** {@inheritDoc} */
@Override
public void updateCurrentProfile(@NotNull Map<String, String> updates, AsyncRequestCallback<ProfileDescriptor> callback) {
asyncRequestFactory.createPostRequest(PROFILE, null)
.header(ACCEPT, APPLICATION_JSON)
.header(CONTENT_TYPE, APPLICATION_JSON)
.data(JsonHelper.toJson(updates))
.loader(loader, "Updating current user's profile...")
.send(callback);
}
/** {@inheritDoc} */
@Override
public void getProfileById(@NotNull String id, AsyncRequestCallback<ProfileDescriptor> callback) {
String requestUrl = PROFILE + id;
asyncRequestFactory.createGetRequest(requestUrl)
.header(ACCEPT, APPLICATION_JSON)
.loader(loader, "Getting user's profile...")
.send(callback);
}
@Override
public void getPreferences(AsyncRequestCallback<Map<String, String>> callback) {
asyncRequestFactory.createGetRequest(PREFS)
.header(ACCEPT, APPLICATION_JSON)
.header(CONTENT_TYPE, APPLICATION_JSON)
.loader(loader, "Getting user's preferences...")
.send(callback);
}
/** {@inheritDoc} */
@Override
public void updateProfile(@NotNull String id, Map<String, String> updates, AsyncRequestCallback<ProfileDescriptor> callback) {
String requestUrl = PROFILE + id;
asyncRequestFactory.createPostRequest(requestUrl, null)
.header(ACCEPT, APPLICATION_JSON)
.header(CONTENT_TYPE, APPLICATION_JSON)
.data(JsonHelper.toJson(updates))
.loader(loader, "Updating user's profile...")
.send(callback);
}
/** {@inheritDoc} */
@Override
public void updatePreferences(@NotNull Map<String, String> update, AsyncRequestCallback<Map<String, String>> callback) {
final String data = JsonHelper.toJson(update);
asyncRequestFactory.createPostRequest(PREFS, null)
.header(ACCEPT, APPLICATION_JSON)
.header(CONTENT_TYPE, APPLICATION_JSON)
.data(data)
.loader(loader)
.send(callback);
}
}
| epl-1.0 |
wojwal/msiext | src/Common/Lsa/ProcessTokenUnitTests.cpp | 723 | #include "StdAfxUnitTests.h"
#include "ProcessTokenUnitTests.h"
#include "ProcessToken.h"
using namespace AppSecInc::LSA;
using namespace AppSecInc::UnitTests::LSA;
CPPUNIT_TEST_SUITE_REGISTRATION(ProcessTokenUnitTests);
void ProcessTokenUnitTests::testConstructorDestructor()
{
{
ProcessToken ptoken;
CPPUNIT_ASSERT(! ptoken.IsOpen());
}
}
void ProcessTokenUnitTests::testOpenClose()
{
ProcessToken ptoken;
ptoken.Open(::GetCurrentProcess(), TOKEN_ALL_ACCESS);
CPPUNIT_ASSERT(ptoken.IsOpen());
ptoken.Close();
CPPUNIT_ASSERT(! ptoken.IsOpen());
ptoken.Open(::GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES);
CPPUNIT_ASSERT(ptoken.IsOpen());
} | epl-1.0 |
ctron/package-drone | bundles/org.eclipse.packagedrone.web/src/org/eclipse/packagedrone/web/controller/ControllerBinderParametersAware.java | 703 | /*******************************************************************************
* Copyright (c) 2015 IBH SYSTEMS GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBH SYSTEMS GmbH - initial API and implementation
*******************************************************************************/
package org.eclipse.packagedrone.web.controller;
public interface ControllerBinderParametersAware
{
public void setParameters ( ControllerBinderParameter[] parameters );
}
| epl-1.0 |
google-code/bh-v1-jl | libraries/openid/Auth/OpenID/BigMath.php | 12571 | <?php
/**
* BigMath: A math library wrapper that abstracts out the underlying
* long integer library.
*
* PHP versions 4 and 5
*
* LICENSE: See the COPYING file included in this distribution.
*
* @access private
* @package OpenID
* @author JanRain, Inc. <openid@janrain.com>
* @copyright 2005-2008 Janrain, Inc.
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache
*/
// Do not allow direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
/**
* Needed for random number generation
*/
require_once 'Auth/OpenID/CryptUtil.php';
/**
* Need Auth_OpenID::bytes().
*/
require_once 'Auth/OpenID.php';
/**
* The superclass of all big-integer math implementations
* @access private
* @package OpenID
*/
class Auth_OpenID_MathLibrary {
/**
* Given a long integer, returns the number converted to a binary
* string. This function accepts long integer values of arbitrary
* magnitude and uses the local large-number math library when
* available.
*
* @param integer $long The long number (can be a normal PHP
* integer or a number created by one of the available long number
* libraries)
* @return string $binary The binary version of $long
*/
function longToBinary($long)
{
$cmp = $this->cmp($long, 0);
if ($cmp < 0) {
$msg = __FUNCTION__ . " takes only positive integers.";
trigger_error($msg, E_USER_ERROR);
return null;
}
if ($cmp == 0) {
return "\x00";
}
$bytes = array();
while ($this->cmp($long, 0) > 0) {
array_unshift($bytes, $this->mod($long, 256));
$long = $this->div($long, pow(2, 8));
}
if ($bytes && ($bytes[0] > 127)) {
array_unshift($bytes, 0);
}
$string = '';
foreach ($bytes as $byte) {
$string .= pack('C', $byte);
}
return $string;
}
/**
* Given a binary string, returns the binary string converted to a
* long number.
*
* @param string $binary The binary version of a long number,
* probably as a result of calling longToBinary
* @return integer $long The long number equivalent of the binary
* string $str
*/
function binaryToLong($str)
{
if ($str === null) {
return null;
}
// Use array_merge to return a zero-indexed array instead of a
// one-indexed array.
$bytes = array_merge(unpack('C*', $str));
$n = $this->init(0);
if ($bytes && ($bytes[0] > 127)) {
trigger_error("bytesToNum works only for positive integers.",
E_USER_WARNING);
return null;
}
foreach ($bytes as $byte) {
$n = $this->mul($n, pow(2, 8));
$n = $this->add($n, $byte);
}
return $n;
}
function base64ToLong($str)
{
$b64 = base64_decode($str);
if ($b64 === false) {
return false;
}
return $this->binaryToLong($b64);
}
function longToBase64($str)
{
return base64_encode($this->longToBinary($str));
}
/**
* Returns a random number in the specified range. This function
* accepts $start, $stop, and $step values of arbitrary magnitude
* and will utilize the local large-number math library when
* available.
*
* @param integer $start The start of the range, or the minimum
* random number to return
* @param integer $stop The end of the range, or the maximum
* random number to return
* @param integer $step The step size, such that $result - ($step
* * N) = $start for some N
* @return integer $result The resulting randomly-generated number
*/
function rand($stop)
{
static $duplicate_cache = array();
// Used as the key for the duplicate cache
$rbytes = $this->longToBinary($stop);
if (array_key_exists($rbytes, $duplicate_cache)) {
list($duplicate, $nbytes) = $duplicate_cache[$rbytes];
} else {
if ($rbytes[0] == "\x00") {
$nbytes = Auth_OpenID::bytes($rbytes) - 1;
} else {
$nbytes = Auth_OpenID::bytes($rbytes);
}
$mxrand = $this->pow(256, $nbytes);
// If we get a number less than this, then it is in the
// duplicated range.
$duplicate = $this->mod($mxrand, $stop);
if (count($duplicate_cache) > 10) {
$duplicate_cache = array();
}
$duplicate_cache[$rbytes] = array($duplicate, $nbytes);
}
do {
$bytes = "\x00" . Auth_OpenID_CryptUtil::getBytes($nbytes);
$n = $this->binaryToLong($bytes);
// Keep looping if this value is in the low duplicated range
} while ($this->cmp($n, $duplicate) < 0);
return $this->mod($n, $stop);
}
}
/**
* Exposes BCmath math library functionality.
*
* {@link Auth_OpenID_BcMathWrapper} wraps the functionality provided
* by the BCMath extension.
*
* @access private
* @package OpenID
*/
class Auth_OpenID_BcMathWrapper extends Auth_OpenID_MathLibrary{
var $type = 'bcmath';
function add($x, $y)
{
return bcadd($x, $y);
}
function sub($x, $y)
{
return bcsub($x, $y);
}
function pow($base, $exponent)
{
return bcpow($base, $exponent);
}
function cmp($x, $y)
{
return bccomp($x, $y);
}
function init($number, $base = 10)
{
return $number;
}
function mod($base, $modulus)
{
return bcmod($base, $modulus);
}
function mul($x, $y)
{
return bcmul($x, $y);
}
function div($x, $y)
{
return bcdiv($x, $y);
}
/**
* Same as bcpowmod when bcpowmod is missing
*
* @access private
*/
function _powmod($base, $exponent, $modulus)
{
$square = $this->mod($base, $modulus);
$result = 1;
while($this->cmp($exponent, 0) > 0) {
if ($this->mod($exponent, 2)) {
$result = $this->mod($this->mul($result, $square), $modulus);
}
$square = $this->mod($this->mul($square, $square), $modulus);
$exponent = $this->div($exponent, 2);
}
return $result;
}
function powmod($base, $exponent, $modulus)
{
if (function_exists('bcpowmod')) {
return bcpowmod($base, $exponent, $modulus);
} else {
return $this->_powmod($base, $exponent, $modulus);
}
}
function toString($num)
{
return $num;
}
}
/**
* Exposes GMP math library functionality.
*
* {@link Auth_OpenID_GmpMathWrapper} wraps the functionality provided
* by the GMP extension.
*
* @access private
* @package OpenID
*/
class Auth_OpenID_GmpMathWrapper extends Auth_OpenID_MathLibrary{
var $type = 'gmp';
function add($x, $y)
{
return gmp_add($x, $y);
}
function sub($x, $y)
{
return gmp_sub($x, $y);
}
function pow($base, $exponent)
{
return gmp_pow($base, $exponent);
}
function cmp($x, $y)
{
return gmp_cmp($x, $y);
}
function init($number, $base = 10)
{
return gmp_init($number, $base);
}
function mod($base, $modulus)
{
return gmp_mod($base, $modulus);
}
function mul($x, $y)
{
return gmp_mul($x, $y);
}
function div($x, $y)
{
return gmp_div_q($x, $y);
}
function powmod($base, $exponent, $modulus)
{
return gmp_powm($base, $exponent, $modulus);
}
function toString($num)
{
return gmp_strval($num);
}
}
/**
* Define the supported extensions. An extension array has keys
* 'modules', 'extension', and 'class'. 'modules' is an array of PHP
* module names which the loading code will attempt to load. These
* values will be suffixed with a library file extension (e.g. ".so").
* 'extension' is the name of a PHP extension which will be tested
* before 'modules' are loaded. 'class' is the string name of a
* {@link Auth_OpenID_MathWrapper} subclass which should be
* instantiated if a given extension is present.
*
* You can define new math library implementations and add them to
* this array.
*/
function Auth_OpenID_math_extensions()
{
$result = array();
if (!defined('Auth_OpenID_BUGGY_GMP')) {
$result[] =
array('modules' => array('gmp', 'php_gmp'),
'extension' => 'gmp',
'class' => 'Auth_OpenID_GmpMathWrapper');
}
$result[] = array(
'modules' => array('bcmath', 'php_bcmath'),
'extension' => 'bcmath',
'class' => 'Auth_OpenID_BcMathWrapper');
return $result;
}
/**
* Detect which (if any) math library is available
*/
function Auth_OpenID_detectMathLibrary($exts)
{
$loaded = false;
foreach ($exts as $extension) {
// See if the extension specified is already loaded.
if ($extension['extension'] &&
extension_loaded($extension['extension'])) {
$loaded = true;
}
// Try to load dynamic modules.
if (!$loaded) {
foreach ($extension['modules'] as $module) {
if (@dl($module . "." . PHP_SHLIB_SUFFIX)) {
$loaded = true;
break;
}
}
}
// If the load succeeded, supply an instance of
// Auth_OpenID_MathWrapper which wraps the specified
// module's functionality.
if ($loaded) {
return $extension;
}
}
return false;
}
/**
* {@link Auth_OpenID_getMathLib} checks for the presence of long
* number extension modules and returns an instance of
* {@link Auth_OpenID_MathWrapper} which exposes the module's
* functionality.
*
* Checks for the existence of an extension module described by the
* result of {@link Auth_OpenID_math_extensions()} and returns an
* instance of a wrapper for that extension module. If no extension
* module is found, an instance of {@link Auth_OpenID_MathWrapper} is
* returned, which wraps the native PHP integer implementation. The
* proper calling convention for this method is $lib =&
* Auth_OpenID_getMathLib().
*
* This function checks for the existence of specific long number
* implementations in the following order: GMP followed by BCmath.
*
* @return Auth_OpenID_MathWrapper $instance An instance of
* {@link Auth_OpenID_MathWrapper} or one of its subclasses
*
* @package OpenID
*/
function &Auth_OpenID_getMathLib()
{
// The instance of Auth_OpenID_MathWrapper that we choose to
// supply will be stored here, so that subseqent calls to this
// method will return a reference to the same object.
static $lib = null;
if (isset($lib)) {
return $lib;
}
if (Auth_OpenID_noMathSupport()) {
$null = null;
return $null;
}
// If this method has not been called before, look at
// Auth_OpenID_math_extensions and try to find an extension that
// works.
$ext = Auth_OpenID_detectMathLibrary(Auth_OpenID_math_extensions());
if ($ext === false) {
$tried = array();
foreach (Auth_OpenID_math_extensions() as $extinfo) {
$tried[] = $extinfo['extension'];
}
$triedstr = implode(", ", $tried);
Auth_OpenID_setNoMathSupport();
$result = null;
return $result;
}
// Instantiate a new wrapper
$class = $ext['class'];
$lib = new $class();
return $lib;
}
function Auth_OpenID_setNoMathSupport()
{
if (!defined('Auth_OpenID_NO_MATH_SUPPORT')) {
define('Auth_OpenID_NO_MATH_SUPPORT', true);
}
}
function Auth_OpenID_noMathSupport()
{
return defined('Auth_OpenID_NO_MATH_SUPPORT');
}
?>
| gpl-2.0 |
tmhorne/simplewiki | zim/gui/customtools.py | 6157 | # -*- coding: utf-8 -*-
# Copyright 2010 Jaap Karssenberg <jaap.karssenberg@gmail.com>
'''This module contains code for defining and managing custom
commands.
'''
import gtk
import logging
from zim.gui.applications import CustomToolManager
from zim.gui.widgets import Dialog, IconButton, IconChooserButton
from zim.fs import File
logger = logging.getLogger('zim.gui')
class CustomToolManagerDialog(Dialog):
def __init__(self, ui):
Dialog.__init__(self, ui, _('Custom Tools'), buttons=gtk.BUTTONS_CLOSE) # T: Dialog title
self.set_help(':Help:Custom Tools')
self.manager = CustomToolManager()
self.add_help_text(_(
'You can configure custom tools that will appear\n'
'in the tool menu and in the tool bar or context menus.'
) ) # T: help text in "Custom Tools" dialog
hbox = gtk.HBox(spacing=5)
self.vbox.add(hbox)
self.listview = CustomToolList(self.manager)
hbox.add(self.listview)
vbox = gtk.VBox(spacing=5)
hbox.pack_start(vbox, False)
for stock, handler, data in (
(gtk.STOCK_ADD, self.__class__.on_add, None),
(gtk.STOCK_EDIT, self.__class__.on_edit, None),
(gtk.STOCK_DELETE, self.__class__.on_delete, None),
(gtk.STOCK_GO_UP, self.__class__.on_move, -1),
(gtk.STOCK_GO_DOWN, self.__class__.on_move, 1),
):
button = IconButton(stock) # TODO tooltips for icon button
if data:
button.connect_object('clicked', handler, self, data)
else:
button.connect_object('clicked', handler, self)
vbox.pack_start(button, False)
def on_add(self):
properties = EditCustomToolDialog(self).run()
if properties:
self.manager.create(**properties)
self.listview.refresh()
def on_edit(self):
name = self.listview.get_selected()
if name:
tool = self.manager.get_tool(name)
properties = EditCustomToolDialog(self, tool=tool).run()
if properties:
tool.update(**properties)
tool.write()
self.listview.refresh()
def on_delete(self):
name = self.listview.get_selected()
if name:
self.manager.delete(name)
self.listview.refresh()
def on_move(self, step):
name = self.listview.get_selected()
if name:
i = self.manager.index(name)
self.manager.reorder(name, i + step)
self.listview.refresh()
self.listview.select(i+step)
class CustomToolList(gtk.TreeView):
PIXBUF_COL = 0
TEXT_COL = 1
NAME_COL = 2
def __init__(self, manager):
self.manager = manager
model = gtk.ListStore(gtk.gdk.Pixbuf, str, str)
# PIXBUF_COL, TEXT_COL, NAME_COL
gtk.TreeView.__init__(self, model)
self.get_selection().set_mode(gtk.SELECTION_BROWSE)
self.set_headers_visible(False)
cr = gtk.CellRendererPixbuf()
column = gtk.TreeViewColumn('_pixbuf_', cr, pixbuf=self.PIXBUF_COL)
self.append_column(column)
cr = gtk.CellRendererText()
column = gtk.TreeViewColumn('_text_', cr, markup=self.TEXT_COL)
self.append_column(column)
self.refresh()
def get_selected(self):
model, iter = self.get_selection().get_selected()
if model and iter:
return model[iter][self.NAME_COL]
else:
return None
def select(self, i):
path = (i, )
self.get_selection().select_path(path)
def refresh(self):
from zim.gui.widgets import encode_markup_text
model = self.get_model()
model.clear()
for tool in self.manager:
pixbuf = tool.get_pixbuf(gtk.ICON_SIZE_MENU)
text = '<b>%s</b>\n%s' % (encode_markup_text(tool.name), encode_markup_text(tool.comment))
model.append((pixbuf, text, tool.key))
class EditCustomToolDialog(Dialog):
def __init__(self, ui, tool=None):
Dialog.__init__(self, ui, _('Edit Custom Tool')) # T: Dialog title
self.set_help(':Help:Custom Tools')
self.vbox.set_spacing(12)
if tool:
name = tool.name
comment = tool.comment
execcmd = tool.execcmd
readonly = tool.isreadonly
toolbar = tool.showintoolbar
replaceselection = tool.replaceselection
else:
name = ''
comment = ''
execcmd = ''
readonly = False
toolbar = False
replaceselection = False
self.add_form((
('Name', 'string', _('Name')), # T: Input in "Edit Custom Tool" dialog
('Comment', 'string', _('Description')), # T: Input in "Edit Custom Tool" dialog
('X-Zim-ExecTool', 'string', _('Command')), # T: Input in "Edit Custom Tool" dialog
), {
'Name': name,
'Comment': comment,
'X-Zim-ExecTool': execcmd,
}, trigger_response=False)
# FIXME need ui builder to take care of this as well
self.iconbutton = IconChooserButton(stock=gtk.STOCK_EXECUTE)
if tool and tool.icon and tool.icon != gtk.STOCK_EXECUTE:
try:
self.iconbutton.set_file(File(tool.icon))
except Exception, error:
logger.exception('Could not load: %s', tool.icon)
label = gtk.Label(_('Icon')+':') # T: Input in "Edit Custom Tool" dialog
label.set_alignment(0.0, 0.5)
hbox = gtk.HBox()
i = self.form.get_property('n-rows')
self.form.attach(label, 0,1, i,i+1, xoptions=0)
self.form.attach(hbox, 1,2, i,i+1)
hbox.pack_start(self.iconbutton, False)
self.form.add_inputs((
('X-Zim-ReadOnly', 'bool', _('Command does not modify data')), # T: Input in "Edit Custom Tool" dialog
('X-Zim-ReplaceSelection', 'bool', _('Output should replace current selection')), # T: Input in "Edit Custom Tool" dialog
('X-Zim-ShowInToolBar', 'bool', _('Show in the toolbar')), # T: Input in "Edit Custom Tool" dialog
))
self.form.update({
'X-Zim-ReadOnly': readonly,
'X-Zim-ReplaceSelection': replaceselection,
'X-Zim-ShowInToolBar': toolbar,
})
self.add_help_text(_('''\
The following parameters will be substituted
in the command when it is executed:
<tt>
<b>%f</b> the page source as a temporary file
<b>%d</b> the attachment directory of the current page
<b>%s</b> the real page source file (if any)
<b>%n</b> the notebook location (file or folder)
<b>%D</b> the document root (if any)
<b>%t</b> the selected text or word under cursor
<b>%T</b> the selected text including wiki formatting
</tt>
''') ) # T: Short help text in "Edit Custom Tool" dialog. The "%" is literal - please include the html formatting
def do_response_ok(self):
fields = self.form.copy()
fields['Icon'] = self.iconbutton.get_file() or None
self.result = fields
return True
| gpl-2.0 |
alekxeyuk/trinityzero | src/game/CreatureAISelector.cpp | 5390 | /*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2009 Trinity <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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Creature.h"
#include "CreatureAISelector.h"
#include "PassiveAI.h"
#include "Policies/SingletonImp.h"
#include "MovementGenerator.h"
#include "ScriptCalls.h"
#include "Pet.h"
#include "TemporarySummon.h"
#include "CreatureAIFactory.h"
INSTANTIATE_SINGLETON_1(CreatureAIRegistry);
INSTANTIATE_SINGLETON_1(MovementGeneratorRegistry);
namespace FactorySelector
{
CreatureAI* selectAI(Creature *creature)
{
const CreatureAICreator *ai_factory = NULL;
CreatureAIRegistry &ai_registry(CreatureAIRepository::Instance());
if(creature->isPet())
ai_factory = ai_registry.GetRegistryItem("PetAI");
//scriptname in db
if(!ai_factory)
if(CreatureAI* scriptedAI = Script->GetAI(creature))
return scriptedAI;
// AIname in db
std::string ainame=creature->GetAIName();
if(!ai_factory && !ainame.empty())
ai_factory = ai_registry.GetRegistryItem( ainame.c_str() );
// select by NPC flags
if(!ai_factory)
{
if(creature->isGuard() && creature->GetOwner() && creature->GetOwner()->GetTypeId() == TYPEID_PLAYER)
ai_factory = ai_registry.GetRegistryItem("PetAI");
else if(creature->isGuard())
ai_factory = ai_registry.GetRegistryItem("GuardAI");
else if(creature->isPet() || (creature->isCharmed() && !creature->isPossessed()))
ai_factory = ai_registry.GetRegistryItem("PetAI");
else if(creature->isTotem())
ai_factory = ai_registry.GetRegistryItem("TotemAI");
else if(creature->isTrigger())
{
if(creature->m_spells[0])
ai_factory = ai_registry.GetRegistryItem("TriggerAI");
else
ai_factory = ai_registry.GetRegistryItem("NullCreatureAI");
}
else if(creature->GetCreatureType() == CREATURE_TYPE_CRITTER)
ai_factory = ai_registry.GetRegistryItem("CritterAI");
}
if(!ai_factory)
{
for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
{
if(creature->m_spells[i])
{
ai_factory = ai_registry.GetRegistryItem("CombatAI");
break;
}
}
}
// select by permit check
if(!ai_factory)
{
int best_val = -1;
typedef CreatureAIRegistry::RegistryMapType RMT;
RMT const &l = ai_registry.GetRegisteredItems();
for( RMT::const_iterator iter = l.begin(); iter != l.end(); ++iter)
{
const CreatureAICreator *factory = iter->second;
const SelectableAI *p = dynamic_cast<const SelectableAI *>(factory);
assert( p != NULL );
int val = p->Permit(creature);
if( val > best_val )
{
best_val = val;
ai_factory = p;
}
}
}
// select NullCreatureAI if not another cases
ainame = (ai_factory == NULL) ? "NullCreatureAI" : ai_factory->key();
DEBUG_LOG("Creature %u used AI is %s.", creature->GetGUIDLow(), ainame.c_str() );
return ( ai_factory == NULL ? new NullCreatureAI(creature) : ai_factory->Create(creature) );
}
MovementGenerator* selectMovementGenerator(Creature *creature)
{
MovementGeneratorRegistry &mv_registry(MovementGeneratorRepository::Instance());
assert( creature->GetCreatureInfo() != NULL );
const MovementGeneratorCreator *mv_factory = mv_registry.GetRegistryItem( creature->GetDefaultMovementType());
/* if( mv_factory == NULL )
{
int best_val = -1;
std::vector<std::string> l;
mv_registry.GetRegisteredItems(l);
for( std::vector<std::string>::iterator iter = l.begin(); iter != l.end(); ++iter)
{
const MovementGeneratorCreator *factory = mv_registry.GetRegistryItem((*iter).c_str());
const SelectableMovement *p = dynamic_cast<const SelectableMovement *>(factory);
assert( p != NULL );
int val = p->Permit(creature);
if( val > best_val )
{
best_val = val;
mv_factory = p;
}
}
}*/
return ( mv_factory == NULL ? NULL : mv_factory->Create(creature) );
}
}
| gpl-2.0 |
vvanherk/oscar_emr | src/main/java/org/oscarehr/common/model/FlowSheetUserCreated.java | 3454 | /**
* Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved.
* This software is published under the GPL GNU General Public License.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* This software was written for the
* Department of Family Medicine
* McMaster University
* Hamilton
* Ontario, Canada
*/
package org.oscarehr.common.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@Entity
public class FlowSheetUserCreated extends AbstractModel<Integer> implements Serializable {
/*
create table FlowSheetUserCreated(
id int(10) auto_increment primary key,
name varchar(4),
dxcodeTriggers varchar(255),
displayName varchar(255),
warningColour varchar(20),
recommendationColour varchar(20),
topHTML text,
archived tinyint(1),
createdDate date
);
<indicator key="HIGH 1" colour="#E00000" />
<indicator key="HIGH" colour="orange" />
<indicator key="LOW" colour="#9999FF" />
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
String name ;
String dxcodeTriggers ;
String displayName ;
String warningColour ;
String recommendationColour ;
String topHTML ;
Boolean archived;
@Temporal(TemporalType.DATE)
private Date createdDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDxcodeTriggers() {
return dxcodeTriggers;
}
public void setDxcodeTriggers(String dxcodeTriggers) {
this.dxcodeTriggers = dxcodeTriggers;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getWarningColour() {
return warningColour;
}
public void setWarningColour(String warningColour) {
this.warningColour = warningColour;
}
public String getRecommendationColour() {
return recommendationColour;
}
public void setRecommendationColour(String recommendationColour) {
this.recommendationColour = recommendationColour;
}
public String getTopHTML() {
return topHTML;
}
public void setTopHTML(String topHTML) {
this.topHTML = topHTML;
}
public Boolean getArchived() {
return archived;
}
public void setArchived(Boolean archived) {
this.archived = archived;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Integer getId() {
return id;
}
}
| gpl-2.0 |
dkgndec/fabulist | core/modules/system/src/Tests/Image/ToolkitGdTest.php | 18679 | <?php
/**
* @file
* Contains \Drupal\system\Tests\Image\ToolkitGdTest.
*/
namespace Drupal\system\Tests\Image;
use Drupal\Core\Image\ImageInterface;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\simpletest\KernelTestBase;
/**
* Tests that core image manipulations work properly: scale, resize, rotate,
* crop, scale and crop, and desaturate.
*
* @group Image
*/
class ToolkitGdTest extends KernelTestBase {
/**
* The image factory service.
*
* @var \Drupal\Core\Image\ImageFactory
*/
protected $imageFactory;
// Colors that are used in testing.
protected $black = array(0, 0, 0, 0);
protected $red = array(255, 0, 0, 0);
protected $green = array(0, 255, 0, 0);
protected $blue = array(0, 0, 255, 0);
protected $yellow = array(255, 255, 0, 0);
protected $white = array(255, 255, 255, 0);
protected $transparent = array(0, 0, 0, 127);
// Used as rotate background colors.
protected $fuchsia = array(255, 0, 255, 0);
protected $rotateTransparent = array(255, 255, 255, 127);
protected $width = 40;
protected $height = 20;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('system', 'simpletest');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Set the image factory service.
$this->imageFactory = $this->container->get('image.factory');
}
protected function checkRequirements() {
// GD2 support is available.
if (!function_exists('imagegd2')) {
return array(
'Image manipulations for the GD toolkit cannot run because the GD toolkit is not available.',
);
}
return parent::checkRequirements();
}
/**
* Function to compare two colors by RGBa.
*/
function colorsAreEqual($color_a, $color_b) {
// Fully transparent pixels are equal, regardless of RGB.
if ($color_a[3] == 127 && $color_b[3] == 127) {
return TRUE;
}
foreach ($color_a as $key => $value) {
if ($color_b[$key] != $value) {
return FALSE;
}
}
return TRUE;
}
/**
* Function for finding a pixel's RGBa values.
*/
function getPixelColor(ImageInterface $image, $x, $y) {
$toolkit = $image->getToolkit();
$color_index = imagecolorat($toolkit->getResource(), $x, $y);
$transparent_index = imagecolortransparent($toolkit->getResource());
if ($color_index == $transparent_index) {
return array(0, 0, 0, 127);
}
return array_values(imagecolorsforindex($toolkit->getResource(), $color_index));
}
/**
* Since PHP can't visually check that our images have been manipulated
* properly, build a list of expected color values for each of the corners and
* the expected height and widths for the final images.
*/
function testManipulations() {
// Test that the image factory is set to use the GD toolkit.
$this->assertEqual($this->imageFactory->getToolkitId(), 'gd', 'The image factory is set to use the \'gd\' image toolkit.');
// Typically the corner colors will be unchanged. These colors are in the
// order of top-left, top-right, bottom-right, bottom-left.
$default_corners = array($this->red, $this->green, $this->blue, $this->transparent);
// A list of files that will be tested.
$files = array(
'image-test.png',
'image-test.gif',
'image-test-no-transparency.gif',
'image-test.jpg',
);
// Setup a list of tests to perform on each type.
$operations = array(
'resize' => array(
'function' => 'resize',
'arguments' => array('width' => 20, 'height' => 10),
'width' => 20,
'height' => 10,
'corners' => $default_corners,
),
'scale_x' => array(
'function' => 'scale',
'arguments' => array('width' => 20),
'width' => 20,
'height' => 10,
'corners' => $default_corners,
),
'scale_y' => array(
'function' => 'scale',
'arguments' => array('height' => 10),
'width' => 20,
'height' => 10,
'corners' => $default_corners,
),
'upscale_x' => array(
'function' => 'scale',
'arguments' => array('width' => 80, 'upscale' => TRUE),
'width' => 80,
'height' => 40,
'corners' => $default_corners,
),
'upscale_y' => array(
'function' => 'scale',
'arguments' => array('height' => 40, 'upscale' => TRUE),
'width' => 80,
'height' => 40,
'corners' => $default_corners,
),
'crop' => array(
'function' => 'crop',
'arguments' => array('x' => 12, 'y' => 4, 'width' => 16, 'height' => 12),
'width' => 16,
'height' => 12,
'corners' => array_fill(0, 4, $this->white),
),
'scale_and_crop' => array(
'function' => 'scale_and_crop',
'arguments' => array('width' => 10, 'height' => 8),
'width' => 10,
'height' => 8,
'corners' => array_fill(0, 4, $this->black),
),
'convert_jpg' => array(
'function' => 'convert',
'width' => 40,
'height' => 20,
'arguments' => array('extension' => 'jpeg'),
'corners' => $default_corners,
),
'convert_gif' => array(
'function' => 'convert',
'width' => 40,
'height' => 20,
'arguments' => array('extension' => 'gif'),
'corners' => $default_corners,
),
'convert_png' => array(
'function' => 'convert',
'width' => 40,
'height' => 20,
'arguments' => array('extension' => 'png'),
'corners' => $default_corners,
),
);
// Systems using non-bundled GD2 don't have imagerotate. Test if available.
if (function_exists('imagerotate')) {
$operations += array(
'rotate_5' => array(
'function' => 'rotate',
'arguments' => array('degrees' => 5, 'background' => '#FF00FF'), // Fuchsia background.
'width' => 42,
'height' => 24,
'corners' => array_fill(0, 4, $this->fuchsia),
),
'rotate_90' => array(
'function' => 'rotate',
'arguments' => array('degrees' => 90, 'background' => '#FF00FF'), // Fuchsia background.
'width' => 20,
'height' => 40,
'corners' => array($this->transparent, $this->red, $this->green, $this->blue),
),
'rotate_transparent_5' => array(
'function' => 'rotate',
'arguments' => array('degrees' => 5),
'width' => 42,
'height' => 24,
'corners' => array_fill(0, 4, $this->rotateTransparent),
),
'rotate_transparent_90' => array(
'function' => 'rotate',
'arguments' => array('degrees' => 90),
'width' => 20,
'height' => 40,
'corners' => array($this->transparent, $this->red, $this->green, $this->blue),
),
);
}
// Systems using non-bundled GD2 don't have imagefilter. Test if available.
if (function_exists('imagefilter')) {
$operations += array(
'desaturate' => array(
'function' => 'desaturate',
'arguments' => array(),
'height' => 20,
'width' => 40,
// Grayscale corners are a bit funky. Each of the corners are a shade of
// gray. The values of these were determined simply by looking at the
// final image to see what desaturated colors end up being.
'corners' => array(
array_fill(0, 3, 76) + array(3 => 0),
array_fill(0, 3, 149) + array(3 => 0),
array_fill(0, 3, 29) + array(3 => 0),
array_fill(0, 3, 225) + array(3 => 127)
),
),
);
}
// Prepare a directory for test file results.
$directory = $this->publicFilesDirectory .'/imagetest';
file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
foreach ($files as $file) {
foreach ($operations as $op => $values) {
// Load up a fresh image.
$image = $this->imageFactory->get(drupal_get_path('module', 'simpletest') . '/files/' . $file);
$toolkit = $image->getToolkit();
if (!$image->isValid()) {
$this->fail(SafeMarkup::format('Could not load image %file.', array('%file' => $file)));
continue 2;
}
$image_original_type = $image->getToolkit()->getType();
// All images should be converted to truecolor when loaded.
$image_truecolor = imageistruecolor($toolkit->getResource());
$this->assertTrue($image_truecolor, SafeMarkup::format('Image %file after load is a truecolor image.', array('%file' => $file)));
if ($image->getToolkit()->getType() == IMAGETYPE_GIF) {
if ($op == 'desaturate') {
// Transparent GIFs and the imagefilter function don't work together.
$values['corners'][3][3] = 0;
}
}
// Perform our operation.
$image->apply($values['function'], $values['arguments']);
// To keep from flooding the test with assert values, make a general
// value for whether each group of values fail.
$correct_dimensions_real = TRUE;
$correct_dimensions_object = TRUE;
// PHP 5.5 GD bug: https://bugs.php.net/bug.php?id=65148. PHP 5.5 GD
// rotates differently then it did in PHP 5.4 resulting in different
// dimensions then what math teaches us. For the test images, the
// dimensions will be 1 pixel smaller in both dimensions (though other
// tests have shown a difference of 0 to 3 pixels in both dimensions.
// @todo: if and when the PHP bug gets solved, add an upper limit
// version check.
// @todo: in [#1551686] the dimension calculations for rotation are
// reworked. That issue should also check if these tests can be made
// more robust.
if (version_compare(PHP_VERSION, '5.5', '>=') && $values['function'] === 'rotate' && $values['arguments']['degrees'] % 90 != 0) {
$values['height']--;
$values['width']--;
}
if (imagesy($toolkit->getResource()) != $values['height'] || imagesx($toolkit->getResource()) != $values['width']) {
$correct_dimensions_real = FALSE;
}
// Check that the image object has an accurate record of the dimensions.
if ($image->getWidth() != $values['width'] || $image->getHeight() != $values['height']) {
$correct_dimensions_object = FALSE;
}
$file_path = $directory . '/' . $op . image_type_to_extension($image->getToolkit()->getType());
$image->save($file_path);
$this->assertTrue($correct_dimensions_real, SafeMarkup::format('Image %file after %action action has proper dimensions.', array('%file' => $file, '%action' => $op)));
$this->assertTrue($correct_dimensions_object, SafeMarkup::format('Image %file object after %action action is reporting the proper height and width values.', array('%file' => $file, '%action' => $op)));
// JPEG colors will always be messed up due to compression. So we skip
// these tests if the original or the result is in jpeg format.
if ($image->getToolkit()->getType() != IMAGETYPE_JPEG && $image_original_type != IMAGETYPE_JPEG) {
// Now check each of the corners to ensure color correctness.
foreach ($values['corners'] as $key => $corner) {
// The test gif that does not have transparency has yellow where the
// others have transparent.
if ($file === 'image-test-no-transparency.gif' && $corner === $this->transparent) {
$corner = $this->yellow;
}
// Get the location of the corner.
switch ($key) {
case 0:
$x = 0;
$y = 0;
break;
case 1:
$x = $image->getWidth() - 1;
$y = 0;
break;
case 2:
$x = $image->getWidth() - 1;
$y = $image->getHeight() - 1;
break;
case 3:
$x = 0;
$y = $image->getHeight() - 1;
break;
}
$color = $this->getPixelColor($image, $x, $y);
// We also skip the color test for transparency for gif <-> png
// conversion. The convert operation cannot handle that correctly.
if ($image->getToolkit()->getType() == $image_original_type || $corner != $this->transparent) {
$correct_colors = $this->colorsAreEqual($color, $corner);
$this->assertTrue($correct_colors, SafeMarkup::format('Image %file object after %action action has the correct color placement at corner %corner.',
array('%file' => $file, '%action' => $op, '%corner' => $key)));
}
}
}
// Check that saved image reloads without raising PHP errors.
$image_reloaded = $this->imageFactory->get($file_path);
$resource = $image_reloaded->getToolkit()->getResource();
}
}
// Test creation of image from scratch, and saving to storage.
foreach (array(IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_JPEG) as $type) {
$image = $this->imageFactory->get();
$image->createNew(50, 20, image_type_to_extension($type, FALSE), '#ffff00');
$file = 'from_null' . image_type_to_extension($type);
$file_path = $directory . '/' . $file ;
$this->assertEqual(50, $image->getWidth(), SafeMarkup::format('Image file %file has the correct width.', array('%file' => $file)));
$this->assertEqual(20, $image->getHeight(), SafeMarkup::format('Image file %file has the correct height.', array('%file' => $file)));
$this->assertEqual(image_type_to_mime_type($type), $image->getMimeType(), SafeMarkup::format('Image file %file has the correct MIME type.', array('%file' => $file)));
$this->assertTrue($image->save($file_path), SafeMarkup::format('Image %file created anew from a null image was saved.', array('%file' => $file)));
// Reload saved image.
$image_reloaded = $this->imageFactory->get($file_path);
if (!$image_reloaded->isValid()) {
$this->fail(SafeMarkup::format('Could not load image %file.', array('%file' => $file)));
continue;
}
$this->assertEqual(50, $image_reloaded->getWidth(), SafeMarkup::format('Image file %file has the correct width.', array('%file' => $file)));
$this->assertEqual(20, $image_reloaded->getHeight(), SafeMarkup::format('Image file %file has the correct height.', array('%file' => $file)));
$this->assertEqual(image_type_to_mime_type($type), $image_reloaded->getMimeType(), SafeMarkup::format('Image file %file has the correct MIME type.', array('%file' => $file)));
if ($image_reloaded->getToolkit()->getType() == IMAGETYPE_GIF) {
$this->assertEqual('#ffff00', $image_reloaded->getToolkit()->getTransparentColor(), SafeMarkup::format('Image file %file has the correct transparent color channel set.', array('%file' => $file)));
}
else {
$this->assertEqual(NULL, $image_reloaded->getToolkit()->getTransparentColor(), SafeMarkup::format('Image file %file has no color channel set.', array('%file' => $file)));
}
}
// Test failures of CreateNew.
$image = $this->imageFactory->get();
$image->createNew(-50, 20);
$this->assertFalse($image->isValid(), 'CreateNew with negative width fails.');
$image->createNew(50, 20, 'foo');
$this->assertFalse($image->isValid(), 'CreateNew with invalid extension fails.');
$image->createNew(50, 20, 'gif', '#foo');
$this->assertFalse($image->isValid(), 'CreateNew with invalid color hex string fails.');
$image->createNew(50, 20, 'gif', '#ff0000');
$this->assertTrue($image->isValid(), 'CreateNew with valid arguments validates the Image.');
}
/**
* Tests that GD resources are freed from memory.
*/
public function testResourceDestruction() {
$image = $this->imageFactory->get(drupal_get_path('module', 'simpletest') . '/files/image-test.png');
$res = $image->getToolkit()->getResource();
$this->assertTrue(is_resource($res), 'Successfully loaded image resource.');
// Force the toolkit to go out of scope.
$image = NULL;
$this->assertFalse(is_resource($res), 'Image resource was destroyed after losing scope.');
}
/**
* Tests loading an image whose transparent color index is out of range.
*/
function testTransparentColorOutOfRange() {
// This image was generated by taking an initial image with a palette size
// of 6 colors, and setting the transparent color index to 6 (one higher
// than the largest allowed index), as follows:
// @code
// $image = imagecreatefromgif('core/modules/simpletest/files/image-test.gif');
// imagecolortransparent($image, 6);
// imagegif($image, 'core/modules/simpletest/files/image-test-transparent-out-of-range.gif');
// @endcode
// This allows us to test that an image with an out-of-range color index
// can be loaded correctly.
$file = 'image-test-transparent-out-of-range.gif';
$image = $this->imageFactory->get(drupal_get_path('module', 'simpletest') . '/files/' . $file);
$toolkit = $image->getToolkit();
if (!$image->isValid()) {
$this->fail(SafeMarkup::format('Could not load image %file.', array('%file' => $file)));
}
else {
// All images should be converted to truecolor when loaded.
$image_truecolor = imageistruecolor($toolkit->getResource());
$this->assertTrue($image_truecolor, SafeMarkup::format('Image %file after load is a truecolor image.', array('%file' => $file)));
}
}
/**
* Tests calling a missing image operation plugin.
*/
function testMissingOperation() {
// Test that the image factory is set to use the GD toolkit.
$this->assertEqual($this->imageFactory->getToolkitId(), 'gd', 'The image factory is set to use the \'gd\' image toolkit.');
// An image file that will be tested.
$file = 'image-test.png';
// Load up a fresh image.
$image = $this->imageFactory->get(drupal_get_path('module', 'simpletest') . '/files/' . $file);
if (!$image->isValid()) {
$this->fail(SafeMarkup::format('Could not load image %file.', array('%file' => $file)));
}
// Try perform a missing toolkit operation.
$this->assertFalse($image->apply('missing_op', array()), 'Calling a missing image toolkit operation plugin fails.');
}
}
| gpl-2.0 |
AntumDeluge/arianne-stendhal | src/games/stendhal/server/maps/magic/city/HealerNPC.java | 3091 | /* $Id$ */
/***************************************************************************
* (C) Copyright 2003-2010 - Stendhal *
***************************************************************************
***************************************************************************
* *
* 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. *
* *
***************************************************************************/
package games.stendhal.server.maps.magic.city;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import games.stendhal.server.core.config.ZoneConfigurator;
import games.stendhal.server.core.engine.StendhalRPZone;
import games.stendhal.server.core.pathfinder.FixedPath;
import games.stendhal.server.core.pathfinder.Node;
import games.stendhal.server.entity.npc.SpeakerNPC;
import games.stendhal.server.entity.npc.behaviour.adder.HealerAdder;
/**
* Builds a Healer NPC for the magic city.
*
* @author kymara
*/
public class HealerNPC implements ZoneConfigurator {
/**
* Configure a zone.
*
* @param zone The zone to be configured.
* @param attributes Configuration attributes.
*/
@Override
public void configureZone(final StendhalRPZone zone, final Map<String, String> attributes) {
buildNPC(zone);
}
private void buildNPC(final StendhalRPZone zone) {
final SpeakerNPC npc = new SpeakerNPC("Salva Mattori") {
@Override
protected void createPath() {
final List<Node> nodes = new LinkedList<Node>();
// walks along the aqueduct path, roughly
nodes.add(new Node(5, 25));
nodes.add(new Node(5, 51));
nodes.add(new Node(18, 51));
nodes.add(new Node(18, 78));
nodes.add(new Node(20, 78));
nodes.add(new Node(20, 109));
// and back again
nodes.add(new Node(20, 78));
nodes.add(new Node(18, 78));
nodes.add(new Node(18, 51));
nodes.add(new Node(5, 51));
setPath(new FixedPath(nodes, true));
}
@Override
protected void createDialog() {
addGreeting("Greetings. Can I #help you?");
addJob("I practise alchemy and have the ability to #heal others.");
new HealerAdder().addHealer(this, 500);
addReply("magical", "We're all capable of magic here. There are different kinds, of course. My favourite is the Sunlight Spell to keep grass and flowers growing underground.");
addHelp("I have #magical powers to #heal your ailments.");
addQuest("I need nothing, thank you.");
addGoodbye("Fare thee well.");
}
};
npc.setDescription("You see a quiet woman with a benign face.");
npc.setEntityClass("cloakedwomannpc");
npc.setPosition(5, 25);
npc.initHP(100);
zone.add(npc);
}
}
| gpl-2.0 |
BrunoChauvet/phpmyadmin | libraries/select_server.lib.php | 3512 | <?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Code for displaying server selection
*
* @package PhpMyAdmin
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* Renders the server selection in list or selectbox form, or option tags only
*
* @param boolean $not_only_options whether to include form tags or not
* @param boolean $omit_fieldset whether to omit fieldset tag or not
*
* @return string
*/
function PMA_selectServer($not_only_options, $omit_fieldset)
{
$retval = '';
// Show as list?
if ($not_only_options) {
$list = $GLOBALS['cfg']['DisplayServersList'];
$not_only_options =! $list;
} else {
$list = false;
}
if ($not_only_options) {
$retval .= '<form method="post" action="'
. PMA_Util::getScriptNameForOption(
$GLOBALS['cfg']['DefaultTabServer'], 'server'
)
. '" class="disableAjax">';
if (! $omit_fieldset) {
$retval .= '<fieldset>';
}
$retval .= '<label for="select_server">'
. __('Current Server:') . '</label> ';
$retval .= '<select name="server" id="select_server" class="autosubmit">';
$retval .= '<option value="">(' . __('Servers') . ') ...</option>' . "\n";
} elseif ($list) {
$retval .= __('Current Server:') . '<br />';
$retval .= '<ul id="list_server">';
}
foreach ($GLOBALS['cfg']['Servers'] as $key => $server) {
if (empty($server['host'])) {
continue;
}
if (!empty($GLOBALS['server']) && (int) $GLOBALS['server'] === (int) $key) {
$selected = 1;
} else {
$selected = 0;
}
if (!empty($server['verbose'])) {
$label = $server['verbose'];
} else {
$label = $server['host'];
if (!empty($server['port'])) {
$label .= ':' . $server['port'];
}
}
if (! empty($server['only_db'])) {
if (! is_array($server['only_db'])) {
$label .= ' - ' . $server['only_db'];
// try to avoid displaying a too wide selector
} elseif (count($server['only_db']) < 4) {
$label .= ' - ' . implode(', ', $server['only_db']);
}
}
if (!empty($server['user']) && $server['auth_type'] == 'config') {
$label .= ' (' . $server['user'] . ')';
}
if ($list) {
$retval .= '<li>';
if ($selected) {
$retval .= '<strong>' . htmlspecialchars($label) . '</strong>';
} else {
$retval .= '<a class="disableAjax item" href="'
. PMA_Util::getScriptNameForOption(
$GLOBALS['cfg']['DefaultTabServer'], 'server'
)
. PMA_URL_getCommon(array('server' => $key))
. '" >' . htmlspecialchars($label) . '</a>';
}
$retval .= '</li>';
} else {
$retval .= '<option value="' . $key . '" '
. ($selected ? ' selected="selected"' : '') . '>'
. htmlspecialchars($label) . '</option>' . "\n";
}
} // end while
if ($not_only_options) {
$retval .= '</select>';
if (! $omit_fieldset) {
$retval .= '</fieldset>';
}
$retval .= '</form>';
} elseif ($list) {
$retval .= '</ul>';
}
return $retval;
}
?>
| gpl-2.0 |
shchiu/openjdk | hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsGCAdaptivePolicyCounters.cpp | 11532 | /*
* Copyright (c) 2004, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
# include "incls/_precompiled.incl"
# include "incls/_cmsGCAdaptivePolicyCounters.cpp.incl"
CMSGCAdaptivePolicyCounters::CMSGCAdaptivePolicyCounters(const char* name_arg,
int collectors,
int generations,
AdaptiveSizePolicy* size_policy_arg)
: GCAdaptivePolicyCounters(name_arg,
collectors,
generations,
size_policy_arg) {
if (UsePerfData) {
EXCEPTION_MARK;
ResourceMark rm;
const char* cname =
PerfDataManager::counter_name(name_space(), "cmsCapacity");
_cms_capacity_counter = PerfDataManager::create_variable(SUN_GC, cname,
PerfData::U_Bytes, (jlong) OldSize, CHECK);
#ifdef NOT_PRODUCT
cname =
PerfDataManager::counter_name(name_space(), "initialPause");
_initial_pause_counter = PerfDataManager::create_variable(SUN_GC, cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_initial_pause()->last_sample(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "remarkPause");
_remark_pause_counter = PerfDataManager::create_variable(SUN_GC, cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_remark_pause()->last_sample(),
CHECK);
#endif
cname =
PerfDataManager::counter_name(name_space(), "avgInitialPause");
_avg_initial_pause_counter = PerfDataManager::create_variable(SUN_GC, cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_initial_pause()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgRemarkPause");
_avg_remark_pause_counter = PerfDataManager::create_variable(SUN_GC, cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_remark_pause()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgSTWGcCost");
_avg_cms_STW_gc_cost_counter = PerfDataManager::create_variable(SUN_GC,
cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_cms_STW_gc_cost()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgSTWTime");
_avg_cms_STW_time_counter = PerfDataManager::create_variable(SUN_GC,
cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_cms_STW_time()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgConcurrentTime");
_avg_concurrent_time_counter = PerfDataManager::create_variable(SUN_GC,
cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_concurrent_time()->average(),
CHECK);
cname =
PerfDataManager::counter_name(name_space(), "avgConcurrentInterval");
_avg_concurrent_interval_counter = PerfDataManager::create_variable(SUN_GC,
cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_concurrent_interval()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgConcurrentGcCost");
_avg_concurrent_gc_cost_counter = PerfDataManager::create_variable(SUN_GC,
cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_concurrent_gc_cost()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgCMSFreeAtSweep");
_avg_cms_free_at_sweep_counter = PerfDataManager::create_variable(SUN_GC,
cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_cms_free_at_sweep()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgCMSFree");
_avg_cms_free_counter = PerfDataManager::create_variable(SUN_GC,
cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_cms_free()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgCMSPromo");
_avg_cms_promo_counter = PerfDataManager::create_variable(SUN_GC,
cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_cms_promo()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgMscPause");
_avg_msc_pause_counter = PerfDataManager::create_variable(SUN_GC,
cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_msc_pause()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgMscInterval");
_avg_msc_interval_counter = PerfDataManager::create_variable(SUN_GC,
cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_msc_interval()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "mscGcCost");
_msc_gc_cost_counter = PerfDataManager::create_variable(SUN_GC,
cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_msc_gc_cost()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgMsPause");
_avg_ms_pause_counter = PerfDataManager::create_variable(SUN_GC,
cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_ms_pause()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgMsInterval");
_avg_ms_interval_counter = PerfDataManager::create_variable(SUN_GC,
cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_ms_interval()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "msGcCost");
_ms_gc_cost_counter = PerfDataManager::create_variable(SUN_GC,
cname,
PerfData::U_Ticks,
(jlong) cms_size_policy()->avg_ms_gc_cost()->average(),
CHECK);
cname = PerfDataManager::counter_name(name_space(), "majorGcCost");
_major_gc_cost_counter = PerfDataManager::create_variable(SUN_GC, cname,
PerfData::U_Ticks, (jlong) cms_size_policy()->cms_gc_cost(), CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgPromotedAvg");
_promoted_avg_counter =
PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
cms_size_policy()->calculated_promo_size_in_bytes(), CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgPromotedDev");
_promoted_avg_dev_counter =
PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
(jlong) 0 , CHECK);
cname = PerfDataManager::counter_name(name_space(), "avgPromotedPaddedAvg");
_promoted_padded_avg_counter =
PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
cms_size_policy()->calculated_promo_size_in_bytes(), CHECK);
cname = PerfDataManager::counter_name(name_space(),
"changeYoungGenForMajPauses");
_change_young_gen_for_maj_pauses_counter =
PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Events,
(jlong)0, CHECK);
cname = PerfDataManager::counter_name(name_space(), "remarkPauseOldSlope");
_remark_pause_old_slope_counter =
PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
(jlong) cms_size_policy()->remark_pause_old_slope(), CHECK);
cname = PerfDataManager::counter_name(name_space(), "initialPauseOldSlope");
_initial_pause_old_slope_counter =
PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
(jlong) cms_size_policy()->initial_pause_old_slope(), CHECK);
cname =
PerfDataManager::counter_name(name_space(), "remarkPauseYoungSlope") ;
_remark_pause_young_slope_counter =
PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
(jlong) cms_size_policy()->remark_pause_young_slope(), CHECK);
cname =
PerfDataManager::counter_name(name_space(), "initialPauseYoungSlope");
_initial_pause_young_slope_counter =
PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
(jlong) cms_size_policy()->initial_pause_young_slope(), CHECK);
}
assert(size_policy()->is_gc_cms_adaptive_size_policy(),
"Wrong type of size policy");
}
void CMSGCAdaptivePolicyCounters::update_counters() {
if (UsePerfData) {
GCAdaptivePolicyCounters::update_counters_from_policy();
update_counters_from_policy();
}
}
void CMSGCAdaptivePolicyCounters::update_counters(CMSGCStats* gc_stats) {
if (UsePerfData) {
update_counters();
update_promoted((size_t) gc_stats->avg_promoted()->last_sample());
update_avg_promoted_avg(gc_stats);
update_avg_promoted_dev(gc_stats);
update_avg_promoted_padded_avg(gc_stats);
}
}
void CMSGCAdaptivePolicyCounters::update_counters_from_policy() {
if (UsePerfData && (cms_size_policy() != NULL)) {
GCAdaptivePolicyCounters::update_counters_from_policy();
update_major_gc_cost_counter();
update_mutator_cost_counter();
update_eden_size();
update_promo_size();
// If these updates from the last_sample() work,
// revise the update methods for these counters
// (both here and in PS).
update_survived((size_t) cms_size_policy()->avg_survived()->last_sample());
update_avg_concurrent_time_counter();
update_avg_concurrent_interval_counter();
update_avg_concurrent_gc_cost_counter();
#ifdef NOT_PRODUCT
update_initial_pause_counter();
update_remark_pause_counter();
#endif
update_avg_initial_pause_counter();
update_avg_remark_pause_counter();
update_avg_cms_STW_time_counter();
update_avg_cms_STW_gc_cost_counter();
update_avg_cms_free_counter();
update_avg_cms_free_at_sweep_counter();
update_avg_cms_promo_counter();
update_avg_msc_pause_counter();
update_avg_msc_interval_counter();
update_msc_gc_cost_counter();
update_avg_ms_pause_counter();
update_avg_ms_interval_counter();
update_ms_gc_cost_counter();
update_avg_old_live_counter();
update_survivor_size_counters();
update_avg_survived_avg_counters();
update_avg_survived_dev_counters();
update_decrement_tenuring_threshold_for_gc_cost();
update_increment_tenuring_threshold_for_gc_cost();
update_decrement_tenuring_threshold_for_survivor_limit();
update_change_young_gen_for_maj_pauses();
update_major_collection_slope_counter();
update_remark_pause_old_slope_counter();
update_initial_pause_old_slope_counter();
update_remark_pause_young_slope_counter();
update_initial_pause_young_slope_counter();
update_decide_at_full_gc_counter();
}
}
| gpl-2.0 |
motoschifo/mame | src/devices/cpu/patinhofeio/patinho_feio_dasm.cpp | 7063 | // license:GPL-2.0+
// copyright-holders:Felipe Sanches
#include "emu.h"
#include "cpu/patinhofeio/patinho_feio.h"
CPU_DISASSEMBLE( patinho_feio )
{
int addr, value, n, f;
switch (oprom[0] & 0xF0)
{
case 0x00:
//PLA = "Pula": Unconditionally JUMP to effective address
addr = (oprom[0] & 0x0F) << 8 | oprom[1];
sprintf (buffer, "PLA /%03X", addr);
return 2;
case 0x10:
//PLAX = "Pulo indexado": Unconditionally JUMP to indexed address
addr = (oprom[0] & 0x0F) << 8 | oprom[1];
sprintf (buffer, "PLAX (IDX) + /%03X", addr);
return 2;
case 0x20:
//ARM = "Armazena": Stores the contents of the
// accumulator in the given 12bit address
addr = (oprom[0] & 0x0F) << 8 | oprom[1];
if (addr==0){
sprintf (buffer, "ARM (IDX)");
}else{
sprintf (buffer, "ARM /%03X", addr);
}
return 2;
case 0x30:
//ARMX = "Armazenamento indexado": Stores the contents of the accumulator in the
// given 12bit address (indexed by IDX)
addr = (oprom[0] & 0x0F) << 8 | oprom[1];
sprintf (buffer, "ARMX (IDX) + /%03X", addr);
return 2;
case 0x40:
//CAR = "Carrega": Loads the contents of the given 12bit address
// into the accumulator
addr = (oprom[0] & 0x0F) << 8 | oprom[1];
if (addr==0){
sprintf (buffer, "CAR (IDX)");
}else{
sprintf (buffer, "CAR /%03X", addr);
}
return 2;
case 0x50:
//CARX = "Carga indexada": Loads the contents of the given 12bit address
// (indexed by IDX) into the accumulator
addr = (oprom[0] & 0x0F) << 8 | oprom[1];
sprintf (buffer, "CARX (IDX) + /%03X", addr);
return 2;
case 0x60:
//SOM = "Soma": Adds the contents of the given 12bit address
// into the accumulator
addr = (oprom[0] & 0x0F) << 8 | oprom[1];
sprintf (buffer, "SOM /%03X", addr);
return 2;
case 0x70:
//SOMX = "Soma indexada": Adds the contents of the given 12bit address
// (indexed by IDX) into the accumulator
addr = (oprom[0] & 0x0F) << 8 | oprom[1];
sprintf (buffer, "SOMX (IDX) + /%03X", addr);
return 2;
case 0xA0:
//PLAN = "Pula se ACC for negativo": Jumps to the 12bit address
// if the accumulator is negative
addr = (oprom[0] & 0x0F) << 8 | oprom[1];
sprintf (buffer, "PLAN /%03X", addr);
return 2;
case 0xB0:
//PLAZ = "Pula se ACC for zero": Jumps to the 12bit address
// if the accumulator is zero
addr = (oprom[0] & 0x0F) << 8 | oprom[1];
sprintf (buffer, "PLAZ /%03X", addr);
return 2;
case 0xC0:
n = (oprom[0] & 0x0F);
f = (oprom[1] & 0x0F);
n+= (n < 10) ? '0' : 'A'-10;
f+= (f < 10) ? '0' : 'A'-10;
switch(oprom[1] & 0xF0)
{
case 0x10: sprintf (buffer, "FNC /%c%c", n, f); return 2;
case 0x20: sprintf (buffer, "SAL /%c%c", n, f); return 2;
case 0x40: sprintf (buffer, "ENTR /%c0", n); return 2;
case 0x80: sprintf (buffer, "SAI /%c0", n); return 2;
}
break;
case 0xD0:
value = oprom[1] & 0x0F;
switch (oprom[0] & 0x0F)
{
case 0x01:
switch (oprom[1] & 0xF0)
{
case 0x00: sprintf (buffer, "DD /%01X", value); return 2; //DD = "Deslocamento para a direita": Shift right
case 0x10: sprintf (buffer, "DDV /%01X", value); return 2; //DDV = "Deslocamento para a direita c/ V": Shift right with carry
case 0x20: sprintf (buffer, "GD /%01X", value); return 2; //GD = "Giro para a direita": Rotate right
case 0x30: sprintf (buffer, "GDV /%01X", value); return 2; //GDV = "Giro para a direita c/ V": Rotate right with carry
case 0x40: sprintf (buffer, "DE /%01X", value); return 2; //DE = "Deslocamento para a esquerda": Shift right
case 0x50: sprintf (buffer, "DEV /%01X", value); return 2; //DEV = "Deslocamento para a esquerda c/ V": Shift right with carry
case 0x60: sprintf (buffer, "GE /%01X", value); return 2; //GE = "Giro para a esquerda": Rotate right
case 0x70: sprintf (buffer, "GEV /%01X", value); return 2; //GEV = "Giro para a esquerda c/ V": Rotate right with carry
case 0x80: sprintf (buffer, "DDS /%01X", value); return 2; //DDS = "Deslocamento para a direita com duplicacao de sinal": Shift right with sign duplication
}
break;
case 0x02: sprintf (buffer, "XOR /%02X", oprom[1]); return 2; //Logical XOR
case 0x04: sprintf (buffer, "NAND /%02X", oprom[1]); return 2; //Logical NAND
case 0x08: sprintf (buffer, "SOMI /%02X", oprom[1]); return 2; //SOMI = "Soma imediata": Add immediate value into accumulator
case 0x0A: sprintf (buffer, "CARI /%02X", oprom[1]); return 2; //CARI = "Carrega imediato": Loads an immediate value into the accumulator
}
break;
case 0xE0:
//SUS = "Subtrai um ou salta"
addr = (oprom[0] & 0x0F) << 8 | oprom[1];
sprintf (buffer, "SUS /%03X", addr);
return 2;
case 0xF0:
//PUG = "Pula e guarda"
addr = (oprom[0] & 0x0F) << 8 | oprom[1];
sprintf (buffer, "PUG /%03X", addr);
return 2;
}
switch (oprom[0])
{
case 0x80: sprintf (buffer, "LIMPO"); return 1;
case 0x81: sprintf (buffer, "UM"); return 1;
case 0x82: sprintf (buffer, "CMP1"); return 1;
case 0x83: sprintf (buffer, "CMP2"); return 1;
case 0x84: sprintf (buffer, "LIN"); return 1;
case 0x85: sprintf (buffer, "INC"); return 1;
case 0x86: sprintf (buffer, "UNEG"); return 1;
case 0x87: sprintf (buffer, "LIMP1"); return 1;
case 0x88: sprintf (buffer, "PNL 0"); return 1;
case 0x89: sprintf (buffer, "PNL 1"); return 1;
case 0x8A: sprintf (buffer, "PNL 2"); return 1;
case 0x8B: sprintf (buffer, "PNL 3"); return 1;
case 0x8C: sprintf (buffer, "PNL 4"); return 1;
case 0x8D: sprintf (buffer, "PNL 5"); return 1;
case 0x8E: sprintf (buffer, "PNL 6"); return 1;
case 0x8F: sprintf (buffer, "PNL 7"); return 1;
case 0x90: sprintf (buffer, "ST 0"); return 1;
case 0x91: sprintf (buffer, "STM 0"); return 1;
case 0x92: sprintf (buffer, "ST 1"); return 1;
case 0x93: sprintf (buffer, "STM 1"); return 1;
case 0x94: sprintf (buffer, "SV 0"); return 1;
case 0x95: sprintf (buffer, "SVM 0"); return 1;
case 0x96: sprintf (buffer, "SV 1"); return 1;
case 0x97: sprintf (buffer, "SVM 1"); return 1;
case 0x98: sprintf (buffer, "PUL"); return 1;
case 0x99: sprintf (buffer, "TRE"); return 1;
case 0x9A: sprintf (buffer, "INIB"); return 1;
case 0x9B: sprintf (buffer, "PERM"); return 1;
case 0x9C: sprintf (buffer, "ESP"); return 1;
case 0x9D: sprintf (buffer, "PARE"); return 1;
case 0x9E: sprintf (buffer, "TRI"); return 1;
case 0x9F: sprintf (buffer, "IND"); return 1;
}
sprintf (buffer, "illegal instruction");
return 1;
}
| gpl-2.0 |
quanghung0404/it2tech | media/com_easysocial/apps/event/news/hooks/notification.comments.php | 2411 | <?php
/**
* @package EasySocial
* @copyright Copyright (C) 2010 - 2014 Stack Ideas Sdn Bhd. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* EasySocial 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('Unauthorized Access');
class SocialEventAppNewsHookNotificationComments
{
/**
* Processes likes notifications
*
* @since 1.2
* @access public
* @param string
* @return
*/
public function execute(&$item)
{
// Get comment participants
$model = FD::model('Comments');
$users = $model->getParticipants($item->uid, $item->context_type);
// Merge to include actor, diff to exclude self, unique to remove dups, and values to reset the index
$users = array_values(array_unique(array_diff(array_merge($users, array($item->actor_id)), array(FD::user()->id))));
// Convert the names to stream-ish
$names = FD::string()->namesToNotifications($users);
// When someone likes on the photo that you have uploaded in a event
if ($item->context_type == 'news.event.create') {
// Get the news object
$news = FD::table('EventNews');
$news->load($item->uid);
// Get the event from the stream
$event = FD::event($news->cluster_id);
// Set the content
if ($event) {
$item->image = $event->getAvatar();
}
// We need to generate the notification message differently for the author of the item and the recipients of the item.
if ($news->created_by == $item->target_id && $item->target_type == SOCIAL_TYPE_USER) {
$item->title = JText::sprintf('APP_EVENT_NEWS_USER_COMMENTED_ON_YOUR_ANNOUNCEMENT', $names, $event->getName());
return $item;
}
// This is for 3rd party viewers
$item->title = JText::sprintf('APP_EVENT_NEWS_USER_COMMENTED_ON_USERS_ANNOUNCEMENT', $names, FD::user($news->created_by)->getName(), $event->getName());
return;
}
return;
}
}
| gpl-2.0 |
C4AProjects/Zuvaa | wp-content/languages/plugins/usernoise/admin/editor-page.php | 3705 | <?php
class UN_Admin_Editor_Page{
public function __construct(){
add_action('admin_print_styles-post.php', array($this, 'action_print_styles'));
add_action('add_meta_boxes_un_feedback', array($this, 'action_add_meta_boxes'));
add_action('post_updated_messages', array($this, 'filter_post_updated_messages'));
add_action('admin_enqueue_scripts', array($this, 'action_admin_enqueue_scripts'));
add_filter('redirect_post_location', array($this, '_redirect_post_location'), 10, 2);
}
public function _redirect_post_location($location, $post_id){
$post = get_post($post_id);
if ($post->post_type != FEEDBACK) return $location;
if (isset($_REQUEST['un_redirect_back']) && $_REQUEST['un_redirect_backp'])
$location = $_REQUEST['un_redirect_back'];
else
$location = admin_url('edit.php?order=desc&post_type=un_feedback&post_status=pending');
return $location;
}
public function action_add_meta_boxes($post){
global $post_new_file;
if (isset($post_new_file)){
$post_new_file = null;
}
remove_meta_box('submitdiv', FEEDBACK, 'side');
add_meta_box('submitdiv', __('Publish'), array($this, 'post_submit_meta_box'),
FEEDBACK, 'side', 'default');
$title = un_get_feedback_type_span($post->ID);
add_meta_box('un-feedback-body',
$title . ($title ? ": " : '') . esc_html($post->post_title),
array($this, 'description_meta_box'),
FEEDBACK);
add_meta_box('stub-http-headers', __('HTTP Headers', 'usernoise'),
array($this, '_stub_pro_block'), FEEDBACK, 'side', 'default');
add_meta_box('stub-discussion', __('Discussion'), array($this, '_stub_pro_block'), FEEDBACK);
add_meta_box('stub-debug-info', __('WordPress Debug Info', 'usernoise'),
array($this, '_stub_pro_block'), FEEDBACK);
}
public function _stub_pro_block($post){?>
Please <strong><a href="http://codecanyon.net/item/usernoise-pro-advanced-modal-feedback-debug/1420436" class="un-upgrade">Upgrade to Pro</a></strong> to enable this block.
<?php
}
public function action_admin_enqueue_scripts($hook){
global $post_type;
if (!($post_type == FEEDBACK && $hook == 'post.php'))
return;
wp_enqueue_script('quicktags');
wp_enqueue_script('un-editor-page', usernoise_url('/js/editor-page.js'));
}
public function filter_post_updated_messages($messages){
$messages[FEEDBACK][6] = __('Feedback was marked as reviewed', 'usernoise');
return $messages;
}
public function action_print_styles(){
global $post_type;
if ($post_type == FEEDBACK) {
wp_enqueue_style('un-admin', usernoise_url('/css/admin.css'));
wp_enqueue_style('un-admin-font-awesome', usernoise_url('/vendor/font-awesome/css/font-awesome.min.css' . "?version=" . UN_VERSION));
}
}
public function reply_meta_box($post){
global $un_h;
require(usernoise_path('/html/reply-meta-box.php'));
}
public function description_meta_box($post){
do_action('description_meta_box_top', $post);
if (un_feedback_has_author($post->ID)){
echo '<div class="un-admin-section un-admin-section-first"><strong>' . __('Author') . ': ';
un_feedback_author_link($post->ID);
echo "</strong></div>";
}
do_action('description_meta_box_before_content', $post);
echo '<div class="un-admin-section un-admin-section-last">';
echo nl2br(esc_html($post->post_content));
echo '</div>';
do_action('description_meta_box_bottom', $post);
}
public function post_submit_meta_box($post) {
global $action;
$post_type = $post->post_type;
$post_type_object = get_post_type_object($post_type);
$can_publish = current_user_can($post_type_object->cap->publish_posts);
require(usernoise_path('/html/publish-meta-box.php'));
}
}
$un_admin_editor_page = new UN_Admin_Editor_Page; | gpl-2.0 |
bruderstein/PythonScript | PythonLib/full/idlelib/idle_test/test_iomenu.py | 1278 | "Test , coverage 17%."
from idlelib import iomenu
import unittest
from test.support import requires
from tkinter import Tk
from idlelib.editor import EditorWindow
class IOBindingTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
requires('gui')
cls.root = Tk()
cls.root.withdraw()
cls.editwin = EditorWindow(root=cls.root)
cls.io = iomenu.IOBinding(cls.editwin)
@classmethod
def tearDownClass(cls):
cls.io.close()
cls.editwin._close()
del cls.editwin
cls.root.update_idletasks()
for id in cls.root.tk.call('after', 'info'):
cls.root.after_cancel(id) # Need for EditorWindow.
cls.root.destroy()
del cls.root
def test_init(self):
self.assertIs(self.io.editwin, self.editwin)
def test_fixnewlines_end(self):
eq = self.assertEqual
io = self.io
fix = io.fixnewlines
text = io.editwin.text
self.editwin.interp = None
eq(fix(), '')
del self.editwin.interp
text.insert(1.0, 'a')
eq(fix(), 'a'+io.eol_convention)
eq(text.get('1.0', 'end-1c'), 'a\n')
eq(fix(), 'a'+io.eol_convention)
if __name__ == '__main__':
unittest.main(verbosity=2)
| gpl-2.0 |
1nv4d3r5/joomla-cms | libraries/cms/module/helper.php | 14245 | <?php
/**
* @package Joomla.Libraries
* @subpackage Module
*
* @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
use Joomla\Registry\Registry;
/**
* Module helper class
*
* @since 1.5
*/
abstract class JModuleHelper
{
/**
* Get module by name (real, eg 'Breadcrumbs' or folder, eg 'mod_breadcrumbs')
*
* @param string $name The name of the module
* @param string $title The title of the module, optional
*
* @return object The Module object
*
* @since 1.5
*/
public static function &getModule($name, $title = null)
{
$result = null;
$modules =& static::load();
$total = count($modules);
for ($i = 0; $i < $total; $i++)
{
// Match the name of the module
if ($modules[$i]->name == $name || $modules[$i]->module == $name)
{
// Match the title if we're looking for a specific instance of the module
if (!$title || $modules[$i]->title == $title)
{
// Found it
$result = &$modules[$i];
break;
}
}
}
// If we didn't find it, and the name is mod_something, create a dummy object
if (is_null($result) && substr($name, 0, 4) == 'mod_')
{
$result = new stdClass;
$result->id = 0;
$result->title = '';
$result->module = $name;
$result->position = '';
$result->content = '';
$result->showtitle = 0;
$result->control = '';
$result->params = '';
}
return $result;
}
/**
* Get modules by position
*
* @param string $position The position of the module
*
* @return array An array of module objects
*
* @since 1.5
*/
public static function &getModules($position)
{
$position = strtolower($position);
$result = array();
$input = JFactory::getApplication()->input;
$modules =& static::load();
$total = count($modules);
for ($i = 0; $i < $total; $i++)
{
if ($modules[$i]->position == $position)
{
$result[] = &$modules[$i];
}
}
if (count($result) == 0)
{
if ($input->getBool('tp') && JComponentHelper::getParams('com_templates')->get('template_positions_display'))
{
$result[0] = static::getModule('mod_' . $position);
$result[0]->title = $position;
$result[0]->content = $position;
$result[0]->position = $position;
}
}
return $result;
}
/**
* Checks if a module is enabled. A given module will only be returned
* if it meets the following criteria: it is enabled, it is assigned to
* the current menu item or all items, and the user meets the access level
* requirements.
*
* @param string $module The module name
*
* @return boolean See description for conditions.
*
* @since 1.5
*/
public static function isEnabled($module)
{
$result = static::getModule($module);
return (!is_null($result) && $result->id !== 0);
}
/**
* Render the module.
*
* @param object $module A module object.
* @param array $attribs An array of attributes for the module (probably from the XML).
*
* @return string The HTML content of the module output.
*
* @since 1.5
*/
public static function renderModule($module, $attribs = array())
{
static $chrome;
// Check that $module is a valid module object
if (!is_object($module) || !isset($module->module) || !isset($module->params))
{
if (defined('JDEBUG') && JDEBUG)
{
JLog::addLogger(array('text_file' => 'jmodulehelper.log.php'), JLog::ALL, array('modulehelper'));
JLog::add('JModuleHelper::renderModule($module) expects a module object', JLog::DEBUG, 'modulehelper');
}
return;
}
if (defined('JDEBUG'))
{
JProfiler::getInstance('Application')->mark('beforeRenderModule ' . $module->module . ' (' . $module->title . ')');
}
$app = JFactory::getApplication();
// Record the scope.
$scope = $app->scope;
// Set scope to component name
$app->scope = $module->module;
// Get module parameters
$params = new Registry;
$params->loadString($module->params);
// Get the template
$template = $app->getTemplate();
// Get module path
$module->module = preg_replace('/[^A-Z0-9_\.-]/i', '', $module->module);
$path = JPATH_BASE . '/modules/' . $module->module . '/' . $module->module . '.php';
// Load the module
if (file_exists($path))
{
$lang = JFactory::getLanguage();
// 1.5 or Core then 1.6 3PD
$lang->load($module->module, JPATH_BASE, null, false, true) ||
$lang->load($module->module, dirname($path), null, false, true);
$content = '';
ob_start();
include $path;
$module->content = ob_get_contents() . $content;
ob_end_clean();
}
// Load the module chrome functions
if (!$chrome)
{
$chrome = array();
}
include_once JPATH_THEMES . '/system/html/modules.php';
$chromePath = JPATH_THEMES . '/' . $template . '/html/modules.php';
if (!isset($chrome[$chromePath]))
{
if (file_exists($chromePath))
{
include_once $chromePath;
}
$chrome[$chromePath] = true;
}
// Check if the current module has a style param to override template module style
$paramsChromeStyle = $params->get('style');
if ($paramsChromeStyle)
{
$attribs['style'] = preg_replace('/^(system|' . $template . ')\-/i', '', $paramsChromeStyle);
}
// Make sure a style is set
if (!isset($attribs['style']))
{
$attribs['style'] = 'none';
}
// Dynamically add outline style
if ($app->input->getBool('tp') && JComponentHelper::getParams('com_templates')->get('template_positions_display'))
{
$attribs['style'] .= ' outline';
}
foreach (explode(' ', $attribs['style']) as $style)
{
$chromeMethod = 'modChrome_' . $style;
// Apply chrome and render module
if (function_exists($chromeMethod))
{
$module->style = $attribs['style'];
ob_start();
$chromeMethod($module, $params, $attribs);
$module->content = ob_get_contents();
ob_end_clean();
}
}
// Revert the scope
$app->scope = $scope;
if (defined('JDEBUG'))
{
JProfiler::getInstance('Application')->mark('afterRenderModule ' . $module->module . ' (' . $module->title . ')');
}
return $module->content;
}
/**
* Get the path to a layout for a module
*
* @param string $module The name of the module
* @param string $layout The name of the module layout. If alternative layout, in the form template:filename.
*
* @return string The path to the module layout
*
* @since 1.5
*/
public static function getLayoutPath($module, $layout = 'default')
{
$template = JFactory::getApplication()->getTemplate();
$defaultLayout = $layout;
if (strpos($layout, ':') !== false)
{
// Get the template and file name from the string
$temp = explode(':', $layout);
$template = ($temp[0] == '_') ? $template : $temp[0];
$layout = $temp[1];
$defaultLayout = ($temp[1]) ? $temp[1] : 'default';
}
// Build the template and base path for the layout
$tPath = JPATH_THEMES . '/' . $template . '/html/' . $module . '/' . $layout . '.php';
$bPath = JPATH_BASE . '/modules/' . $module . '/tmpl/' . $defaultLayout . '.php';
$dPath = JPATH_BASE . '/modules/' . $module . '/tmpl/default.php';
// If the template has a layout override use it
if (file_exists($tPath))
{
return $tPath;
}
elseif (file_exists($bPath))
{
return $bPath;
}
else
{
return $dPath;
}
}
/**
* Load published modules.
*
* @return array
*
* @since 1.5
* @deprecated 4.0 Use JModuleHelper::load() instead
*/
protected static function &_load()
{
return static::load();
}
/**
* Load published modules.
*
* @return array
*
* @since 3.2
*/
protected static function &load()
{
static $clean;
if (isset($clean))
{
return $clean;
}
$app = JFactory::getApplication();
$Itemid = $app->input->getInt('Itemid');
$user = JFactory::getUser();
$groups = implode(',', $user->getAuthorisedViewLevels());
$lang = JFactory::getLanguage()->getTag();
$clientId = (int) $app->getClientId();
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select('m.id, m.title, m.module, m.position, m.content, m.showtitle, m.params, mm.menuid')
->from('#__modules AS m')
->join('LEFT', '#__modules_menu AS mm ON mm.moduleid = m.id')
->where('m.published = 1')
->join('LEFT', '#__extensions AS e ON e.element = m.module AND e.client_id = m.client_id')
->where('e.enabled = 1');
$date = JFactory::getDate();
$now = $date->toSql();
$nullDate = $db->getNullDate();
$query->where('(m.publish_up = ' . $db->quote($nullDate) . ' OR m.publish_up <= ' . $db->quote($now) . ')')
->where('(m.publish_down = ' . $db->quote($nullDate) . ' OR m.publish_down >= ' . $db->quote($now) . ')')
->where('m.access IN (' . $groups . ')')
->where('m.client_id = ' . $clientId)
->where('(mm.menuid = ' . (int) $Itemid . ' OR mm.menuid <= 0)');
// Filter by language
if ($app->isSite() && $app->getLanguageFilter())
{
$query->where('m.language IN (' . $db->quote($lang) . ',' . $db->quote('*') . ')');
}
$query->order('m.position, m.ordering');
// Set the query
$db->setQuery($query);
$clean = array();
try
{
$modules = $db->loadObjectList();
}
catch (RuntimeException $e)
{
JLog::add(JText::sprintf('JLIB_APPLICATION_ERROR_MODULE_LOAD', $e->getMessage()), JLog::WARNING, 'jerror');
return $clean;
}
// Apply negative selections and eliminate duplicates
$negId = $Itemid ? -(int) $Itemid : false;
$dupes = array();
for ($i = 0, $n = count($modules); $i < $n; $i++)
{
$module = &$modules[$i];
// The module is excluded if there is an explicit prohibition
$negHit = ($negId === (int) $module->menuid);
if (isset($dupes[$module->id]))
{
// If this item has been excluded, keep the duplicate flag set,
// but remove any item from the cleaned array.
if ($negHit)
{
unset($clean[$module->id]);
}
continue;
}
$dupes[$module->id] = true;
// Only accept modules without explicit exclusions.
if (!$negHit)
{
$module->name = substr($module->module, 4);
$module->style = null;
$module->position = strtolower($module->position);
$clean[$module->id] = $module;
}
}
unset($dupes);
// Return to simple indexing that matches the query order.
$clean = array_values($clean);
return $clean;
}
/**
* Module cache helper
*
* Caching modes:
* To be set in XML:
* 'static' One cache file for all pages with the same module parameters
* 'oldstatic' 1.5 definition of module caching, one cache file for all pages
* with the same module id and user aid,
* 'itemid' Changes on itemid change, to be called from inside the module:
* 'safeuri' Id created from $cacheparams->modeparams array,
* 'id' Module sets own cache id's
*
* @param object $module Module object
* @param object $moduleparams Module parameters
* @param object $cacheparams Module cache parameters - id or url parameters, depending on the module cache mode
*
* @return string
*
* @see JFilterInput::clean()
* @since 1.6
*/
public static function moduleCache($module, $moduleparams, $cacheparams)
{
if (!isset($cacheparams->modeparams))
{
$cacheparams->modeparams = null;
}
if (!isset($cacheparams->cachegroup))
{
$cacheparams->cachegroup = $module->module;
}
$user = JFactory::getUser();
$cache = JFactory::getCache($cacheparams->cachegroup, 'callback');
$conf = JFactory::getConfig();
// Turn cache off for internal callers if parameters are set to off and for all logged in users
if ($moduleparams->get('owncache', null) === '0' || $conf->get('caching') == 0 || $user->get('id'))
{
$cache->setCaching(false);
}
// Module cache is set in seconds, global cache in minutes, setLifeTime works in minutes
$cache->setLifeTime($moduleparams->get('cache_time', $conf->get('cachetime') * 60) / 60);
$wrkaroundoptions = array('nopathway' => 1, 'nohead' => 0, 'nomodules' => 1, 'modulemode' => 1, 'mergehead' => 1);
$wrkarounds = true;
$view_levels = md5(serialize($user->getAuthorisedViewLevels()));
switch ($cacheparams->cachemode)
{
case 'id':
$ret = $cache->get(
array($cacheparams->class, $cacheparams->method),
$cacheparams->methodparams,
$cacheparams->modeparams,
$wrkarounds,
$wrkaroundoptions
);
break;
case 'safeuri':
$secureid = null;
if (is_array($cacheparams->modeparams))
{
$input = JFactory::getApplication()->input;
$uri = $input->getArray();
$safeuri = new stdClass;
foreach ($cacheparams->modeparams as $key => $value)
{
// Use int filter for id/catid to clean out spamy slugs
if (isset($uri[$key]))
{
$noHtmlFilter = JFilterInput::getInstance();
$safeuri->$key = $noHtmlFilter->clean($uri[$key], $value);
}
}
}
$secureid = md5(serialize(array($safeuri, $cacheparams->method, $moduleparams)));
$ret = $cache->get(
array($cacheparams->class, $cacheparams->method),
$cacheparams->methodparams,
$module->id . $view_levels . $secureid,
$wrkarounds,
$wrkaroundoptions
);
break;
case 'static':
$ret = $cache->get(
array($cacheparams->class,
$cacheparams->method),
$cacheparams->methodparams,
$module->module . md5(serialize($cacheparams->methodparams)),
$wrkarounds,
$wrkaroundoptions
);
break;
// Provided for backward compatibility, not really useful.
case 'oldstatic':
$ret = $cache->get(
array($cacheparams->class, $cacheparams->method),
$cacheparams->methodparams,
$module->id . $view_levels,
$wrkarounds,
$wrkaroundoptions
);
break;
case 'itemid':
default:
$ret = $cache->get(
array($cacheparams->class, $cacheparams->method),
$cacheparams->methodparams,
$module->id . $view_levels . JFactory::getApplication()->input->getInt('Itemid', null),
$wrkarounds,
$wrkaroundoptions
);
break;
}
return $ret;
}
}
| gpl-2.0 |
mirror/vbox | src/VBox/Runtime/testcase/tstLdr-4.cpp | 9073 | /* $Id$ */
/** @file
* IPRT - Testcase for RTLdrOpen using ldrLdrObjR0.r0.
*/
/*
* Copyright (C) 2006-2012 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include <iprt/ldr.h>
#include <iprt/alloc.h>
#include <iprt/log.h>
#include <iprt/stream.h>
#include <iprt/assert.h>
#include <iprt/param.h>
#include <iprt/path.h>
#include <iprt/initterm.h>
#include <iprt/err.h>
#include <iprt/string.h>
extern "C" DECLEXPORT(int) DisasmTest1(void);
/**
* Resolve an external symbol during RTLdrGetBits().
*
* @returns iprt status code.
* @param hLdrMod The loader module handle.
* @param pszModule Module name.
* @param pszSymbol Symbol name, NULL if uSymbol should be used.
* @param uSymbol Symbol ordinal, ~0 if pszSymbol should be used.
* @param pValue Where to store the symbol value (address).
* @param pvUser User argument.
*/
static DECLCALLBACK(int) testGetImport(RTLDRMOD hLdrMod, const char *pszModule, const char *pszSymbol, unsigned uSymbol, RTUINTPTR *pValue, void *pvUser)
{
if ( !strcmp(pszSymbol, "RTAssertMsg1Weak") || !strcmp(pszSymbol, "_RTAssertMsg1Weak"))
*pValue = (uintptr_t)RTAssertMsg1Weak;
else if (!strcmp(pszSymbol, "RTAssertMsg2Weak") || !strcmp(pszSymbol, "_RTAssertMsg2Weak"))
*pValue = (uintptr_t)RTAssertMsg1Weak;
else if (!strcmp(pszSymbol, "RTAssertMsg1") || !strcmp(pszSymbol, "_RTAssertMsg1"))
*pValue = (uintptr_t)RTAssertMsg1;
else if (!strcmp(pszSymbol, "RTAssertMsg2") || !strcmp(pszSymbol, "_RTAssertMsg2"))
*pValue = (uintptr_t)RTAssertMsg2;
else if (!strcmp(pszSymbol, "RTAssertMsg2V") || !strcmp(pszSymbol, "_RTAssertMsg2V"))
*pValue = (uintptr_t)RTAssertMsg2V;
else if (!strcmp(pszSymbol, "RTAssertMayPanic") || !strcmp(pszSymbol, "_RTAssertMayPanic"))
*pValue = (uintptr_t)RTAssertMayPanic;
else if (!strcmp(pszSymbol, "RTLogDefaultInstance") || !strcmp(pszSymbol, "_RTLogDefaultInstance"))
*pValue = (uintptr_t)RTLogDefaultInstance;
else if (!strcmp(pszSymbol, "RTLogLoggerExV") || !strcmp(pszSymbol, "_RTLogLoggerExV"))
*pValue = (uintptr_t)RTLogLoggerExV;
else if (!strcmp(pszSymbol, "RTLogPrintfV") || !strcmp(pszSymbol, "_RTLogPrintfV"))
*pValue = (uintptr_t)RTLogPrintfV;
else if (!strcmp(pszSymbol, "RTR0AssertPanicSystem")|| !strcmp(pszSymbol, "_RTR0AssertPanicSystem"))
*pValue = (uintptr_t)0;
else if (!strcmp(pszSymbol, "MyPrintf") || !strcmp(pszSymbol, "_MyPrintf"))
*pValue = (uintptr_t)RTPrintf;
else
{
RTPrintf("tstLdr-4: Unexpected import '%s'!\n", pszSymbol);
return VERR_SYMBOL_NOT_FOUND;
}
return VINF_SUCCESS;
}
/**
* One test iteration with one file.
*
* The test is very simple, we load the file three times
* into two different regions. The first two into each of the
* regions the for compare usage. The third is loaded into one
* and then relocated between the two and other locations a few times.
*
* @returns number of errors.
* @param pszFilename The file to load the mess with.
*/
static int testLdrOne(const char *pszFilename)
{
int cErrors = 0;
size_t cbImage = 0;
struct Load
{
RTLDRMOD hLdrMod;
void *pvBits;
size_t cbBits;
const char *pszName;
} aLoads[6] =
{
{ NULL, NULL, 0, "foo" },
{ NULL, NULL, 0, "bar" },
{ NULL, NULL, 0, "foobar" },
{ NULL, NULL, 0, "kLdr-foo" },
{ NULL, NULL, 0, "kLdr-bar" },
{ NULL, NULL, 0, "kLdr-foobar" }
};
unsigned i;
int rc;
/*
* Load them.
*/
for (i = 0; i < RT_ELEMENTS(aLoads); i++)
{
if (!strncmp(aLoads[i].pszName, RT_STR_TUPLE("kLdr-")))
rc = RTLdrOpenkLdr(pszFilename, 0, RTLDRARCH_WHATEVER, &aLoads[i].hLdrMod);
else
rc = RTLdrOpen(pszFilename, 0, RTLDRARCH_WHATEVER, &aLoads[i].hLdrMod);
if (RT_FAILURE(rc))
{
RTPrintf("tstLdr-4: Failed to open '%s'/%d, rc=%Rrc. aborting test.\n", pszFilename, i, rc);
Assert(aLoads[i].hLdrMod == NIL_RTLDRMOD);
cErrors++;
break;
}
/* size it */
size_t cb = RTLdrSize(aLoads[i].hLdrMod);
if (cbImage && cb != cbImage)
{
RTPrintf("tstLdr-4: Size mismatch '%s'/%d. aborting test.\n", pszFilename, i);
cErrors++;
break;
}
aLoads[i].cbBits = cbImage = cb;
/* Allocate bits. */
aLoads[i].pvBits = RTMemExecAlloc(cb);
if (!aLoads[i].pvBits)
{
RTPrintf("tstLdr-4: Out of memory '%s'/%d cbImage=%d. aborting test.\n", pszFilename, i, cbImage);
cErrors++;
break;
}
/* Get the bits. */
rc = RTLdrGetBits(aLoads[i].hLdrMod, aLoads[i].pvBits, (uintptr_t)aLoads[i].pvBits, testGetImport, NULL);
if (RT_FAILURE(rc))
{
RTPrintf("tstLdr-4: Failed to get bits for '%s'/%d, rc=%Rrc. aborting test\n", pszFilename, i, rc);
cErrors++;
break;
}
}
/*
* Execute the code.
*/
if (!cErrors)
{
for (i = 0; i < RT_ELEMENTS(aLoads); i += 1)
{
/* get the pointer. */
RTUINTPTR Value;
rc = RTLdrGetSymbolEx(aLoads[i].hLdrMod, aLoads[i].pvBits, (uintptr_t)aLoads[i].pvBits,
UINT32_MAX, "DisasmTest1", &Value);
if (rc == VERR_SYMBOL_NOT_FOUND)
rc = RTLdrGetSymbolEx(aLoads[i].hLdrMod, aLoads[i].pvBits, (uintptr_t)aLoads[i].pvBits,
UINT32_MAX, "_DisasmTest1", &Value);
if (RT_FAILURE(rc))
{
RTPrintf("tstLdr-4: Failed to get symbol \"DisasmTest1\" from load #%d: %Rrc\n", i, rc);
cErrors++;
break;
}
DECLCALLBACKPTR(int, pfnDisasmTest1)(void) = (DECLCALLBACKPTR(int, RT_NOTHING)(void))(uintptr_t)Value; /* eeeh. */
RTPrintf("tstLdr-4: pfnDisasmTest1=%p / add-symbol-file %s %#x\n", pfnDisasmTest1, pszFilename, aLoads[i].pvBits);
/* call the test function. */
rc = pfnDisasmTest1();
if (rc)
{
RTPrintf("tstLdr-4: load #%d Test1 -> %#x\n", i, rc);
cErrors++;
}
}
}
/*
* Clean up.
*/
for (i = 0; i < RT_ELEMENTS(aLoads); i++)
{
if (aLoads[i].pvBits)
RTMemExecFree(aLoads[i].pvBits, aLoads[i].cbBits);
if (aLoads[i].hLdrMod)
{
rc = RTLdrClose(aLoads[i].hLdrMod);
if (RT_FAILURE(rc))
{
RTPrintf("tstLdr-4: Failed to close '%s' i=%d, rc=%Rrc.\n", pszFilename, i, rc);
cErrors++;
}
}
}
return cErrors;
}
int main(int argc, char **argv)
{
int cErrors = 0;
RTR3InitExe(argc, &argv, 0);
/*
* Sanity check.
*/
int rc = DisasmTest1();
if (rc)
{
RTPrintf("tstLdr-4: FATAL ERROR - DisasmTest1 is buggy: rc=%#x\n", rc);
return 1;
}
/*
* Execute the test.
*/
char szPath[RTPATH_MAX];
rc = RTPathExecDir(szPath, sizeof(szPath) - sizeof("/tstLdrObjR0.r0"));
if (RT_SUCCESS(rc))
{
strcat(szPath, "/tstLdrObjR0.r0");
RTPrintf("tstLdr-4: TESTING '%s'...\n", szPath);
cErrors += testLdrOne(szPath);
}
else
{
RTPrintf("tstLdr-4: RTPathExecDir -> %Rrc\n", rc);
cErrors++;
}
/*
* Test result summary.
*/
if (!cErrors)
RTPrintf("tstLdr-4: SUCCESS\n");
else
RTPrintf("tstLdr-4: FAILURE - %d errors\n", cErrors);
return !!cErrors;
}
| gpl-2.0 |
haiweiosu/Angular2.0-Simple-Project-Demo | node_modules/angular2/es6/prod/src/core/metadata.js | 28616 | /**
* This indirection is needed to free up Component, etc symbols in the public API
* to be used by the decorator versions of these annotations.
*/
export { QueryMetadata, ContentChildrenMetadata, ContentChildMetadata, ViewChildrenMetadata, ViewQueryMetadata, ViewChildMetadata, AttributeMetadata } from './metadata/di';
export { ComponentMetadata, DirectiveMetadata, PipeMetadata, InputMetadata, OutputMetadata, HostBindingMetadata, HostListenerMetadata } from './metadata/directives';
export { ViewMetadata, ViewEncapsulation } from './metadata/view';
import { QueryMetadata, ContentChildrenMetadata, ContentChildMetadata, ViewChildrenMetadata, ViewChildMetadata, ViewQueryMetadata, AttributeMetadata } from './metadata/di';
import { ComponentMetadata, DirectiveMetadata, PipeMetadata, InputMetadata, OutputMetadata, HostBindingMetadata, HostListenerMetadata } from './metadata/directives';
import { ViewMetadata } from './metadata/view';
import { makeDecorator, makeParamDecorator, makePropDecorator } from './util/decorators';
// TODO(alexeagle): remove the duplication of this doc. It is copied from ComponentMetadata.
/**
* Declare reusable UI building blocks for an application.
*
* Each Angular component requires a single `@Component` and at least one `@View` annotation. The
* `@Component`
* annotation specifies when a component is instantiated, and which properties and hostListeners it
* binds to.
*
* When a component is instantiated, Angular
* - creates a shadow DOM for the component.
* - loads the selected template into the shadow DOM.
* - creates all the injectable objects configured with `providers` and `viewProviders`.
*
* All template expressions and statements are then evaluated against the component instance.
*
* For details on the `@View` annotation, see {@link ViewMetadata}.
*
* ## Lifecycle hooks
*
* When the component class implements some {@link angular2/lifecycle_hooks} the callbacks are
* called by the change detection at defined points in time during the life of the component.
*
* ## Example
*
* ```
* @Component({
* selector: 'greet',
* template: 'Hello {{name}}!'
* })
* class Greet {
* name: string;
*
* constructor() {
* this.name = 'World';
* }
* }
* ```
*
*/
export var Component = makeDecorator(ComponentMetadata, (fn) => fn.View = View);
// TODO(alexeagle): remove the duplication of this doc. It is copied from DirectiveMetadata.
/**
* Directives allow you to attach behavior to elements in the DOM.
*
* {@link DirectiveMetadata}s with an embedded view are called {@link ComponentMetadata}s.
*
* A directive consists of a single directive annotation and a controller class. When the
* directive's `selector` matches
* elements in the DOM, the following steps occur:
*
* 1. For each directive, the `ElementInjector` attempts to resolve the directive's constructor
* arguments.
* 2. Angular instantiates directives for each matched element using `ElementInjector` in a
* depth-first order,
* as declared in the HTML.
*
* ## Understanding How Injection Works
*
* There are three stages of injection resolution.
* - *Pre-existing Injectors*:
* - The terminal {@link Injector} cannot resolve dependencies. It either throws an error or, if
* the dependency was
* specified as `@Optional`, returns `null`.
* - The platform injector resolves browser singleton resources, such as: cookies, title,
* location, and others.
* - *Component Injectors*: Each component instance has its own {@link Injector}, and they follow
* the same parent-child hierarchy
* as the component instances in the DOM.
* - *Element Injectors*: Each component instance has a Shadow DOM. Within the Shadow DOM each
* element has an `ElementInjector`
* which follow the same parent-child hierarchy as the DOM elements themselves.
*
* When a template is instantiated, it also must instantiate the corresponding directives in a
* depth-first order. The
* current `ElementInjector` resolves the constructor dependencies for each directive.
*
* Angular then resolves dependencies as follows, according to the order in which they appear in the
* {@link ViewMetadata}:
*
* 1. Dependencies on the current element
* 2. Dependencies on element injectors and their parents until it encounters a Shadow DOM boundary
* 3. Dependencies on component injectors and their parents until it encounters the root component
* 4. Dependencies on pre-existing injectors
*
*
* The `ElementInjector` can inject other directives, element-specific special objects, or it can
* delegate to the parent
* injector.
*
* To inject other directives, declare the constructor parameter as:
* - `directive:DirectiveType`: a directive on the current element only
* - `@Host() directive:DirectiveType`: any directive that matches the type between the current
* element and the
* Shadow DOM root.
* - `@Query(DirectiveType) query:QueryList<DirectiveType>`: A live collection of direct child
* directives.
* - `@QueryDescendants(DirectiveType) query:QueryList<DirectiveType>`: A live collection of any
* child directives.
*
* To inject element-specific special objects, declare the constructor parameter as:
* - `element: ElementRef` to obtain a reference to logical element in the view.
* - `viewContainer: ViewContainerRef` to control child template instantiation, for
* {@link DirectiveMetadata} directives only
* - `bindingPropagation: BindingPropagation` to control change detection in a more granular way.
*
* ## Example
*
* The following example demonstrates how dependency injection resolves constructor arguments in
* practice.
*
*
* Assume this HTML template:
*
* ```
* <div dependency="1">
* <div dependency="2">
* <div dependency="3" my-directive>
* <div dependency="4">
* <div dependency="5"></div>
* </div>
* <div dependency="6"></div>
* </div>
* </div>
* </div>
* ```
*
* With the following `dependency` decorator and `SomeService` injectable class.
*
* ```
* @Injectable()
* class SomeService {
* }
*
* @Directive({
* selector: '[dependency]',
* inputs: [
* 'id: dependency'
* ]
* })
* class Dependency {
* id:string;
* }
* ```
*
* Let's step through the different ways in which `MyDirective` could be declared...
*
*
* ### No injection
*
* Here the constructor is declared with no arguments, therefore nothing is injected into
* `MyDirective`.
*
* ```
* @Directive({ selector: '[my-directive]' })
* class MyDirective {
* constructor() {
* }
* }
* ```
*
* This directive would be instantiated with no dependencies.
*
*
* ### Component-level injection
*
* Directives can inject any injectable instance from the closest component injector or any of its
* parents.
*
* Here, the constructor declares a parameter, `someService`, and injects the `SomeService` type
* from the parent
* component's injector.
* ```
* @Directive({ selector: '[my-directive]' })
* class MyDirective {
* constructor(someService: SomeService) {
* }
* }
* ```
*
* This directive would be instantiated with a dependency on `SomeService`.
*
*
* ### Injecting a directive from the current element
*
* Directives can inject other directives declared on the current element.
*
* ```
* @Directive({ selector: '[my-directive]' })
* class MyDirective {
* constructor(dependency: Dependency) {
* expect(dependency.id).toEqual(3);
* }
* }
* ```
* This directive would be instantiated with `Dependency` declared at the same element, in this case
* `dependency="3"`.
*
* ### Injecting a directive from any ancestor elements
*
* Directives can inject other directives declared on any ancestor element (in the current Shadow
* DOM), i.e. on the current element, the
* parent element, or its parents.
* ```
* @Directive({ selector: '[my-directive]' })
* class MyDirective {
* constructor(@Host() dependency: Dependency) {
* expect(dependency.id).toEqual(2);
* }
* }
* ```
*
* `@Host` checks the current element, the parent, as well as its parents recursively. If
* `dependency="2"` didn't
* exist on the direct parent, this injection would
* have returned
* `dependency="1"`.
*
*
* ### Injecting a live collection of direct child directives
*
*
* A directive can also query for other child directives. Since parent directives are instantiated
* before child directives, a directive can't simply inject the list of child directives. Instead,
* the directive injects a {@link QueryList}, which updates its contents as children are added,
* removed, or moved by a directive that uses a {@link ViewContainerRef} such as a `ng-for`, an
* `ng-if`, or an `ng-switch`.
*
* ```
* @Directive({ selector: '[my-directive]' })
* class MyDirective {
* constructor(@Query(Dependency) dependencies:QueryList<Dependency>) {
* }
* }
* ```
*
* This directive would be instantiated with a {@link QueryList} which contains `Dependency` 4 and
* 6. Here, `Dependency` 5 would not be included, because it is not a direct child.
*
* ### Injecting a live collection of descendant directives
*
* By passing the descendant flag to `@Query` above, we can include the children of the child
* elements.
*
* ```
* @Directive({ selector: '[my-directive]' })
* class MyDirective {
* constructor(@Query(Dependency, {descendants: true}) dependencies:QueryList<Dependency>) {
* }
* }
* ```
*
* This directive would be instantiated with a Query which would contain `Dependency` 4, 5 and 6.
*
* ### Optional injection
*
* The normal behavior of directives is to return an error when a specified dependency cannot be
* resolved. If you
* would like to inject `null` on unresolved dependency instead, you can annotate that dependency
* with `@Optional()`.
* This explicitly permits the author of a template to treat some of the surrounding directives as
* optional.
*
* ```
* @Directive({ selector: '[my-directive]' })
* class MyDirective {
* constructor(@Optional() dependency:Dependency) {
* }
* }
* ```
*
* This directive would be instantiated with a `Dependency` directive found on the current element.
* If none can be
* found, the injector supplies `null` instead of throwing an error.
*
* ## Example
*
* Here we use a decorator directive to simply define basic tool-tip behavior.
*
* ```
* @Directive({
* selector: '[tooltip]',
* inputs: [
* 'text: tooltip'
* ],
* host: {
* '(mouseenter)': 'onMouseEnter()',
* '(mouseleave)': 'onMouseLeave()'
* }
* })
* class Tooltip{
* text:string;
* overlay:Overlay; // NOT YET IMPLEMENTED
* overlayManager:OverlayManager; // NOT YET IMPLEMENTED
*
* constructor(overlayManager:OverlayManager) {
* this.overlay = overlay;
* }
*
* onMouseEnter() {
* // exact signature to be determined
* this.overlay = this.overlayManager.open(text, ...);
* }
*
* onMouseLeave() {
* this.overlay.close();
* this.overlay = null;
* }
* }
* ```
* In our HTML template, we can then add this behavior to a `<div>` or any other element with the
* `tooltip` selector,
* like so:
*
* ```
* <div tooltip="some text here"></div>
* ```
*
* Directives can also control the instantiation, destruction, and positioning of inline template
* elements:
*
* A directive uses a {@link ViewContainerRef} to instantiate, insert, move, and destroy views at
* runtime.
* The {@link ViewContainerRef} is created as a result of `<template>` element, and represents a
* location in the current view
* where these actions are performed.
*
* Views are always created as children of the current {@link ViewMetadata}, and as siblings of the
* `<template>` element. Thus a
* directive in a child view cannot inject the directive that created it.
*
* Since directives that create views via ViewContainers are common in Angular, and using the full
* `<template>` element syntax is wordy, Angular
* also supports a shorthand notation: `<li *foo="bar">` and `<li template="foo: bar">` are
* equivalent.
*
* Thus,
*
* ```
* <ul>
* <li *foo="bar" title="text"></li>
* </ul>
* ```
*
* Expands in use to:
*
* ```
* <ul>
* <template [foo]="bar">
* <li title="text"></li>
* </template>
* </ul>
* ```
*
* Notice that although the shorthand places `*foo="bar"` within the `<li>` element, the binding for
* the directive
* controller is correctly instantiated on the `<template>` element rather than the `<li>` element.
*
* ## Lifecycle hooks
*
* When the directive class implements some {@link angular2/lifecycle_hooks} the callbacks are
* called by the change detection at defined points in time during the life of the directive.
*
* ## Example
*
* Let's suppose we want to implement the `unless` behavior, to conditionally include a template.
*
* Here is a simple directive that triggers on an `unless` selector:
*
* ```
* @Directive({
* selector: '[unless]',
* inputs: ['unless']
* })
* export class Unless {
* viewContainer: ViewContainerRef;
* templateRef: TemplateRef;
* prevCondition: boolean;
*
* constructor(viewContainer: ViewContainerRef, templateRef: TemplateRef) {
* this.viewContainer = viewContainer;
* this.templateRef = templateRef;
* this.prevCondition = null;
* }
*
* set unless(newCondition) {
* if (newCondition && (isBlank(this.prevCondition) || !this.prevCondition)) {
* this.prevCondition = true;
* this.viewContainer.clear();
* } else if (!newCondition && (isBlank(this.prevCondition) || this.prevCondition)) {
* this.prevCondition = false;
* this.viewContainer.create(this.templateRef);
* }
* }
* }
* ```
*
* We can then use this `unless` selector in a template:
* ```
* <ul>
* <li *unless="expr"></li>
* </ul>
* ```
*
* Once the directive instantiates the child view, the shorthand notation for the template expands
* and the result is:
*
* ```
* <ul>
* <template [unless]="exp">
* <li></li>
* </template>
* <li></li>
* </ul>
* ```
*
* Note also that although the `<li></li>` template still exists inside the `<template></template>`,
* the instantiated
* view occurs on the second `<li></li>` which is a sibling to the `<template>` element.
*/
export var Directive = makeDecorator(DirectiveMetadata);
// TODO(alexeagle): remove the duplication of this doc. It is copied from ViewMetadata.
/**
* Metadata properties available for configuring Views.
*
* Each Angular component requires a single `@Component` and at least one `@View` annotation. The
* `@View` annotation specifies the HTML template to use, and lists the directives that are active
* within the template.
*
* When a component is instantiated, the template is loaded into the component's shadow root, and
* the expressions and statements in the template are evaluated against the component.
*
* For details on the `@Component` annotation, see {@link ComponentMetadata}.
*
* ## Example
*
* ```
* @Component({
* selector: 'greet',
* template: 'Hello {{name}}!',
* directives: [GreetUser, Bold]
* })
* class Greet {
* name: string;
*
* constructor() {
* this.name = 'World';
* }
* }
* ```
*/
export var View = makeDecorator(ViewMetadata, (fn) => fn.View = View);
// TODO(alexeagle): remove the duplication of this doc. It is copied from AttributeMetadata.
/**
* Metadata properties available for configuring Views.
*
* Each Angular component requires a single `@Component` and at least one `@View` annotation. The
* `@View` annotation specifies the HTML template to use, and lists the directives that are active
* within the template.
*
* When a component is instantiated, the template is loaded into the component's shadow root, and
* the expressions and statements in the template are evaluated against the component.
*
* For details on the `@Component` annotation, see {@link ComponentMetadata}.
*
* ## Example
*
* ```
* @Component({
* selector: 'greet',
* template: 'Hello {{name}}!',
* directives: [GreetUser, Bold]
* })
* class Greet {
* name: string;
*
* constructor() {
* this.name = 'World';
* }
* }
* ```
*/
export var Attribute = makeParamDecorator(AttributeMetadata);
// TODO(alexeagle): remove the duplication of this doc. It is copied from QueryMetadata.
/**
* Declares an injectable parameter to be a live list of directives or variable
* bindings from the content children of a directive.
*
* ### Example ([live demo](http://plnkr.co/edit/lY9m8HLy7z06vDoUaSN2?p=preview))
*
* Assume that `<tabs>` component would like to get a list its children `<pane>`
* components as shown in this example:
*
* ```html
* <tabs>
* <pane title="Overview">...</pane>
* <pane *ng-for="#o of objects" [title]="o.title">{{o.text}}</pane>
* </tabs>
* ```
*
* The preferred solution is to query for `Pane` directives using this decorator.
*
* ```javascript
* @Component({
* selector: 'pane',
* inputs: ['title']
* })
* class Pane {
* title:string;
* }
*
* @Component({
* selector: 'tabs',
* template: `
* <ul>
* <li *ng-for="#pane of panes">{{pane.title}}</li>
* </ul>
* <content></content>
* `
* })
* class Tabs {
* panes: QueryList<Pane>;
* constructor(@Query(Pane) panes:QueryList<Pane>) {
* this.panes = panes;
* }
* }
* ```
*
* A query can look for variable bindings by passing in a string with desired binding symbol.
*
* ### Example ([live demo](http://plnkr.co/edit/sT2j25cH1dURAyBRCKx1?p=preview))
* ```html
* <seeker>
* <div #findme>...</div>
* </seeker>
*
* @Component({ selector: 'foo' })
* class seeker {
* constructor(@Query('findme') elList: QueryList<ElementRef>) {...}
* }
* ```
*
* In this case the object that is injected depend on the type of the variable
* binding. It can be an ElementRef, a directive or a component.
*
* Passing in a comma separated list of variable bindings will query for all of them.
*
* ```html
* <seeker>
* <div #find-me>...</div>
* <div #find-me-too>...</div>
* </seeker>
*
* @Component({
* selector: 'foo'
* })
* class Seeker {
* constructor(@Query('findMe, findMeToo') elList: QueryList<ElementRef>) {...}
* }
* ```
*
* Configure whether query looks for direct children or all descendants
* of the querying element, by using the `descendants` parameter.
* It is set to `false` by default.
*
* ### Example ([live demo](http://plnkr.co/edit/wtGeB977bv7qvA5FTYl9?p=preview))
* ```html
* <container #first>
* <item>a</item>
* <item>b</item>
* <container #second>
* <item>c</item>
* </container>
* </container>
* ```
*
* When querying for items, the first container will see only `a` and `b` by default,
* but with `Query(TextDirective, {descendants: true})` it will see `c` too.
*
* The queried directives are kept in a depth-first pre-order with respect to their
* positions in the DOM.
*
* Query does not look deep into any subcomponent views.
*
* Query is updated as part of the change-detection cycle. Since change detection
* happens after construction of a directive, QueryList will always be empty when observed in the
* constructor.
*
* The injected object is an unmodifiable live list.
* See {@link QueryList} for more details.
*/
export var Query = makeParamDecorator(QueryMetadata);
// TODO(alexeagle): remove the duplication of this doc. It is copied from ContentChildrenMetadata.
/**
* Configures a content query.
*
* Content queries are set before the `afterContentInit` callback is called.
*
* ### Example
*
* ```
* @Directive({
* selector: 'someDir'
* })
* class SomeDir {
* @ContentChildren(ChildDirective) contentChildren: QueryList<ChildDirective>;
*
* afterContentInit() {
* // contentChildren is set
* }
* }
* ```
*/
export var ContentChildren = makePropDecorator(ContentChildrenMetadata);
// TODO(alexeagle): remove the duplication of this doc. It is copied from ContentChildMetadata.
/**
* Configures a content query.
*
* Content queries are set before the `afterContentInit` callback is called.
*
* ### Example
*
* ```
* @Directive({
* selector: 'someDir'
* })
* class SomeDir {
* @ContentChild(ChildDirective) contentChild;
*
* afterContentInit() {
* // contentChild is set
* }
* }
* ```
*/
export var ContentChild = makePropDecorator(ContentChildMetadata);
// TODO(alexeagle): remove the duplication of this doc. It is copied from ViewChildrenMetadata.
/**
* Configures a view query.
*
* View queries are set before the `afterViewInit` callback is called.
*
* ### Example
*
* ```
* @Component({
* selector: 'someDir',
* templateUrl: 'someTemplate',
* directives: [ItemDirective]
* })
* class SomeDir {
* @ViewChildren(ItemDirective) viewChildren: QueryList<ItemDirective>;
*
* afterViewInit() {
* // viewChildren is set
* }
* }
* ```
*/
export var ViewChildren = makePropDecorator(ViewChildrenMetadata);
// TODO(alexeagle): remove the duplication of this doc. It is copied from ViewChildMetadata.
/**
* Configures a view query.
*
* View queries are set before the `afterViewInit` callback is called.
*
* ### Example
*
* ```
* @Component({
* selector: 'someDir',
* templateUrl: 'someTemplate',
* directives: [ItemDirective]
* })
* class SomeDir {
* @ViewChild(ItemDirective) viewChild:ItemDirective;
*
* afterViewInit() {
* // viewChild is set
* }
* }
* ```
*/
export var ViewChild = makePropDecorator(ViewChildMetadata);
// TODO(alexeagle): remove the duplication of this doc. It is copied from ViewQueryMetadata.
/**
* Similar to {@link QueryMetadata}, but querying the component view, instead of
* the content children.
*
* ### Example ([live demo](http://plnkr.co/edit/eNsFHDf7YjyM6IzKxM1j?p=preview))
*
* ```javascript
* @Component({...})
* @View({
* template: `
* <item> a </item>
* <item> b </item>
* <item> c </item>
* `
* })
* class MyComponent {
* shown: boolean;
*
* constructor(private @Query(Item) items:QueryList<Item>) {
* items.onChange(() => console.log(items.length));
* }
* }
* ```
*
* Supports the same querying parameters as {@link QueryMetadata}, except
* `descendants`. This always queries the whole view.
*
* As `shown` is flipped between true and false, items will contain zero of one
* items.
*
* Specifies that a {@link QueryList} should be injected.
*
* The injected object is an iterable and observable live list.
* See {@link QueryList} for more details.
*/
export var ViewQuery = makeParamDecorator(ViewQueryMetadata);
// TODO(alexeagle): remove the duplication of this doc. It is copied from PipeMetadata.
/**
* Declare reusable pipe function.
*
* ## Example
*
* ```
* @Pipe({
* name: 'lowercase'
* })
* class Lowercase {
* transform(v, args) { return v.toLowerCase(); }
* }
* ```
*/
export var Pipe = makeDecorator(PipeMetadata);
// TODO(alexeagle): remove the duplication of this doc. It is copied from InputMetadata.
/**
* Declares a data-bound input property.
*
* Angular automatically updates data-bound properties during change detection.
*
* `InputMetadata` takes an optional parameter that specifies the name
* used when instantiating a component in the template. When not provided,
* the name of the decorated property is used.
*
* ### Example
*
* The following example creates a component with two input properties.
*
* ```typescript
* @Component({
* selector: 'bank-account',
* template: `
* Bank Name: {{bankName}}
* Account Id: {{id}}
* `
* })
* class BankAccount {
* @Input() bankName: string;
* @Input('account-id') id: string;
*
* // this property is not bound, and won't be automatically updated by Angular
* normalizedBankName: string;
* }
*
* @Component({
* selector: 'app',
* template: `
* <bank-account bank-name="RBC" account-id="4747"></bank-account>
* `,
* directives: [BankAccount]
* })
* class App {}
*
* bootstrap(App);
* ```
*/
export var Input = makePropDecorator(InputMetadata);
// TODO(alexeagle): remove the duplication of this doc. It is copied from OutputMetadata.
/**
* Declares an event-bound output property.
*
* When an output property emits an event, an event handler attached to that event
* the template is invoked.
*
* `OutputMetadata` takes an optional parameter that specifies the name
* used when instantiating a component in the template. When not provided,
* the name of the decorated property is used.
*
* ### Example
*
* ```typescript
* @Directive({
* selector: 'interval-dir',
* })
* class IntervalDir {
* @Output() everySecond = new EventEmitter();
* @Output('everyFiveSeconds') five5Secs = new EventEmitter();
*
* constructor() {
* setInterval(() => this.everySecond.next("event"), 1000);
* setInterval(() => this.five5Secs.next("event"), 5000);
* }
* }
*
* @Component({
* selector: 'app',
* template: `
* <interval-dir (every-second)="everySecond()" (every-five-seconds)="everyFiveSeconds()">
* </interval-dir>
* `,
* directives: [IntervalDir]
* })
* class App {
* everySecond() { console.log('second'); }
* everyFiveSeconds() { console.log('five seconds'); }
* }
* bootstrap(App);
* ```
*/
export var Output = makePropDecorator(OutputMetadata);
// TODO(alexeagle): remove the duplication of this doc. It is copied from HostBindingMetadata.
/**
* Declares a host property binding.
*
* Angular automatically checks host property bindings during change detection.
* If a binding changes, it will update the host element of the directive.
*
* `HostBindingMetadata` takes an optional parameter that specifies the property
* name of the host element that will be updated. When not provided,
* the class property name is used.
*
* ### Example
*
* The following example creates a directive that sets the `valid` and `invalid` classes
* on the DOM element that has ng-model directive on it.
*
* ```typescript
* @Directive({selector: '[ng-model]'})
* class NgModelStatus {
* constructor(public control:NgModel) {}
* @HostBinding('[class.valid]') get valid { return this.control.valid; }
* @HostBinding('[class.invalid]') get invalid { return this.control.invalid; }
* }
*
* @Component({
* selector: 'app',
* template: `<input [(ng-model)]="prop">`,
* directives: [FORM_DIRECTIVES, NgModelStatus]
* })
* class App {
* prop;
* }
*
* bootstrap(App);
* ```
*/
export var HostBinding = makePropDecorator(HostBindingMetadata);
// TODO(alexeagle): remove the duplication of this doc. It is copied from HostListenerMetadata.
/**
* Declares a host listener.
*
* Angular will invoke the decorated method when the host element emits the specified event.
*
* If the decorated method returns `false`, then `preventDefault` is applied on the DOM
* event.
*
* ### Example
*
* The following example declares a directive that attaches a click listener to the button and
* counts clicks.
*
* ```typescript
* @Directive({selector: 'button[counting]'})
* class CountClicks {
* numberOfClicks = 0;
*
* @HostListener('click', ['$event.target'])
* onClick(btn) {
* console.log("button", btn, "number of clicks:", this.numberOfClicks++);
* }
* }
*
* @Component({
* selector: 'app',
* template: `<button counting>Increment</button>`,
* directives: [CountClicks]
* })
* class App {}
*
* bootstrap(App);
* ```
*/
export var HostListener = makePropDecorator(HostListenerMetadata);
//# sourceMappingURL=metadata.js.map | gpl-2.0 |
tempesta-tech/mariadb | plugin/auth_gssapi/gssapi_errmsg.cc | 2492 | /* Copyright (c) 2015, Shuang Qiu, Robbie Harwood,
Vladislav Vaintroub & MariaDB Corporation
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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(__FreeBSD__) || defined(SOLARIS) || defined(__sun)
#include <gssapi/gssapi.h>
#else
#include <gssapi.h>
#endif
#include <string.h>
void gssapi_errmsg(OM_uint32 major, OM_uint32 minor, char *buf, size_t size)
{
OM_uint32 message_context;
OM_uint32 status_code;
OM_uint32 maj_status;
OM_uint32 min_status;
gss_buffer_desc status_string;
char *p= buf;
char *end= buf + size - 1;
int types[] = {GSS_C_GSS_CODE,GSS_C_MECH_CODE};
for(int i= 0; i < 2;i++)
{
message_context= 0;
status_code= types[i] == GSS_C_GSS_CODE?major:minor;
if(!status_code)
continue;
do
{
maj_status = gss_display_status(
&min_status,
status_code,
types[i],
GSS_C_NO_OID,
&message_context,
&status_string);
if(maj_status)
break;
if(p + status_string.length + 2 < end)
{
memcpy(p,status_string.value, status_string.length);
p += status_string.length;
*p++ = '.';
*p++ = ' ';
}
gss_release_buffer(&min_status, &status_string);
}
while (message_context != 0);
}
*p= 0;
}
| gpl-2.0 |
rk34cj/qt-extend-4.4.3 | qtopiacore/qt/tools/designer/src/components/signalsloteditor/signalsloteditor_instance.cpp | 1929 | /****************************************************************************
**
** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License versions 2.0 or 3.0 as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information
** to ensure GNU General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html. In addition, as a special
** exception, Nokia gives you certain additional rights. These rights
** are described in the Nokia Qt GPL Exception version 1.3, included in
** the file GPL_EXCEPTION.txt in this package.
**
** Qt for Windows(R) Licensees
** As a special exception, Nokia, as the sole copyright holder for Qt
** Designer, grants users of the Qt/Eclipse Integration plug-in the
** right for the Qt/Eclipse Integration to link to functionality
** provided by Qt Designer and its related libraries.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
****************************************************************************/
#include <QtCore/qplugin.h>
#include "signalsloteditor_plugin.h"
QT_USE_NAMESPACE
using namespace qdesigner_internal;
Q_EXPORT_PLUGIN(SignalSlotEditorPlugin)
| gpl-2.0 |
epgmedia/beveragedynamics | wp-content/themes/reporter/admin/functions/functions.mediauploader.php | 6243 | <?php
/**
* WooThemes Media Library-driven AJAX File Uploader Module (2010-11-05)
*
* Slightly modified for use in the Options Framework.
*
* @since 1.0.0
*/
/**
* Sets up a custom post type to attach image to. This allows us to have
* individual galleries for different uploaders.
*/
if ( ! function_exists( 'optionsframework_mlu_init' ) ) {
function optionsframework_mlu_init () {
register_post_type( 'options', array(
'labels' => array(
'name' => 'Options',
),
'public' => true,
'show_ui' => false,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => false,
'supports' => array( 'title', 'editor' ),
'query_var' => false,
'can_export' => true,
'show_in_nav_menus' => false
) );
}
}
/**
* Forces insert into post
*/
add_filter( 'get_media_item_args', 'force_send' );
function force_send($args){
$args['send'] = true;
return $args;
}
/**
* Adds the Thickbox CSS file and specific loading and button images to the header
* on the pages where this function is called.
*/
if ( ! function_exists( 'optionsframework_mlu_css' ) ) {
function optionsframework_mlu_css () {
$_html = '';
$_html .= '<link rel="stylesheet" href="' . get_option('siteurl') . '/' . WPINC . '/js/thickbox/thickbox.css" type="text/css" media="screen" />' . "\n";
$_html .= '<script type="text/javascript">
var tb_pathToImage = "' . get_option('siteurl') . '/' . WPINC . '/js/thickbox/loadingAnimation.gif";
var tb_closeImage = "' . get_option('siteurl') . '/' . WPINC . '/js/thickbox/tb-close.png";
</script>' . "\n";
echo $_html;
}
}
/**
* Registers and enqueues (loads) the necessary JavaScript file for working with the
* Media Library-driven AJAX File Uploader Module.
*/
if ( ! function_exists( 'optionsframework_mlu_js' ) ) {
function optionsframework_mlu_js () {
// Registers custom scripts for the Media Library AJAX uploader.
wp_register_script( 'of-medialibrary-uploader', ADMIN_DIR .'assets/js/of-medialibrary-uploader.js', array( 'jquery', 'thickbox' ) );
wp_enqueue_script( 'of-medialibrary-uploader' );
wp_enqueue_script( 'media-upload' );
}
}
/**
* Uses "silent" posts in the database to store relationships for images.
* This also creates the facility to collect galleries of, for example, logo images.
*
* Return: $_postid.
*
* If no "silent" post is present, one will be created with the type "optionsframework"
* and the post_name of "of-$_token".
*
* Example Usage:
* optionsframework_mlu_get_silentpost ( 'of_logo' );
*/
if ( ! function_exists( 'optionsframework_mlu_get_silentpost' ) ) {
function optionsframework_mlu_get_silentpost ( $_token ) {
global $wpdb;
$_id = 0;
// Check if the token is valid against a whitelist.
// $_whitelist = array( 'of_logo', 'of_custom_favicon', 'of_ad_top_image' );
// Sanitise the token.
$_token = strtolower( str_replace( ' ', '_', $_token ) );
// if ( in_array( $_token, $_whitelist ) ) {
if ( $_token ) {
// Tell the function what to look for in a post.
$_args = array( 'post_type' => 'options', 'post_name' => 'of-' . $_token, 'post_status' => 'draft', 'comment_status' => 'closed', 'ping_status' => 'closed' );
// Look in the database for a "silent" post that meets our criteria.
$query = 'SELECT ID FROM ' . $wpdb->posts . ' WHERE post_parent = 0';
foreach ( $_args as $k => $v ) {
$query .= ' AND ' . $k . ' = "' . $v . '"';
} // End FOREACH Loop
$query .= ' LIMIT 1';
$_posts = $wpdb->get_row( $query );
// If we've got a post, loop through and get it's ID.
if ( count( $_posts ) ) {
$_id = $_posts->ID;
} else {
// If no post is present, insert one.
// Prepare some additional data to go with the post insertion.
$_words = explode( '_', $_token );
$_title = join( ' ', $_words );
$_title = ucwords( $_title );
$_post_data = array( 'post_title' => $_title );
$_post_data = array_merge( $_post_data, $_args );
$_id = wp_insert_post( $_post_data );
}
}
return $_id;
}
}
/**
* Trigger code inside the Media Library popup.
*/
if ( ! function_exists( 'optionsframework_mlu_insidepopup' ) ) {
function optionsframework_mlu_insidepopup () {
if ( isset( $_REQUEST['is_optionsframework'] ) && $_REQUEST['is_optionsframework'] == 'yes' ) {
add_action( 'admin_head', 'optionsframework_mlu_js_popup' );
add_filter( 'media_upload_tabs', 'optionsframework_mlu_modify_tabs' );
}
}
}
if ( ! function_exists( 'optionsframework_mlu_js_popup' ) ) {
function optionsframework_mlu_js_popup () {
$_of_title = $_REQUEST['of_title'];
if ( ! $_of_title ) { $_of_title = 'file'; } // End IF Statement
?>
<script type="text/javascript">
jQuery(function($) {
jQuery.noConflict();
// Change the title of each tab to use the custom title text instead of "Media File".
$( 'h3.media-title' ).each ( function () {
var current_title = $( this ).html();
var new_title = current_title.replace( 'media file', '<?php echo $_of_title; ?>' );
$( this ).html( new_title );
} );
// Change the text of the "Insert into Post" buttons to read "Use this File".
$( '.savesend input.button[value*="Insert into Post"], .media-item #go_button' ).attr( 'value', 'Use this File' );
// Hide the "Insert Gallery" settings box on the "Gallery" tab.
$( 'div#gallery-settings' ).hide();
// Preserve the "is_optionsframework" parameter on the "delete" confirmation button.
$( '.savesend a.del-link' ).click ( function () {
var continueButton = $( this ).next( '.del-attachment' ).children( 'a.button[id*="del"]' );
var continueHref = continueButton.attr( 'href' );
continueHref = continueHref + '&is_optionsframework=yes';
continueButton.attr( 'href', continueHref );
} );
});
</script>
<?php
}
}
/**
* Triggered inside the Media Library popup to modify the title of the "Gallery" tab.
*/
if ( ! function_exists( 'optionsframework_mlu_modify_tabs' ) ) {
function optionsframework_mlu_modify_tabs ( $tabs ) {
$tabs['gallery'] = str_replace( __( 'Gallery', 'optionsframework' ), __( 'Previously Uploaded', 'optionsframework' ), $tabs['gallery'] );
return $tabs;
}
} | gpl-2.0 |
ehazell/AWPF | sites/all/libraries/yui/tests/common/tests/functional/yui/yui/src/test/java/com/yahoo/test/SelNG/YUI/tests/DragAndDropTestBasic.java | 755 | package com.yahoo.test.SelNG.YUI.tests;
import static org.testng.Assert.fail;
import org.apache.log4j.Logger;
import org.testng.annotations.Test;
import com.yahoo.test.SelNG.YUI.library.DragAndDropBasic;
import com.yahoo.test.SelNG.framework.util.SelNGRetryAnalyzer;
public class DragAndDropTestBasic extends CommonTest{
public static Logger logger = Logger.getLogger(DragAndDropTestBasic.class.getName());
@Test(groups = {"demo"}, retryAnalyzer = SelNGRetryAnalyzer.class)
public void DragAndDropBasic() {
logger.info("Invoked Tabview Method");
try {
DragAndDropBasic.ddTest();
} catch (Throwable t) {
t.printStackTrace(System.out);
logger.error(t);
fail();
}
}
} | gpl-2.0 |
teamfx/openjfx-8u-dev-rt | modules/graphics/src/main/java/com/sun/scenario/effect/impl/prism/PrImage.java | 3115 | /*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.scenario.effect.impl.prism;
import com.sun.prism.Image;
import com.sun.scenario.effect.Filterable;
/**
* This is a special class that is only used for the purposes of converting
* a Prism image (from Image.platformImage) into a Filterable (see
* PrismToolkit.toFilterable()) that can then be passed to
* PrRenderer.createImageData(). All of this is only used by the Identity
* effect; eventually we should figure out a more straightforward solution.
*/
public class PrImage implements Filterable {
private final Image image;
private PrImage(Image image) {
this.image = image;
}
public static PrImage create(Image image) {
return new PrImage(image);
}
public Image getImage() {
return image;
}
public Object getData() {
throw new UnsupportedOperationException("Not supported yet.");
}
public int getContentWidth() {
return image.getWidth();
}
public int getContentHeight() {
return image.getHeight();
}
public int getPhysicalWidth() {
return image.getWidth();
}
public int getPhysicalHeight() {
return image.getHeight();
}
public float getPixelScale() {
return image.getPixelScale();
}
public int getMaxContentWidth() {
return image.getWidth();
}
public int getMaxContentHeight() {
return image.getHeight();
}
public void setContentWidth(int contentW) {
throw new UnsupportedOperationException("Not supported.");
}
public void setContentHeight(int contentH) {
throw new UnsupportedOperationException("Not supported");
}
public void lock() {
}
public void unlock() {
}
public boolean isLost() {
return false;
}
public void flush() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| gpl-2.0 |
andrijdavid/MyTheme | resources/views/pages/year.scout.php | 208 | @extends('layouts.default')
@section('content')
<div class="container">
@include('partials.timeline.timeline')
@include('partials.pagination')
</div>
@stop
@section('script')
<script></script>
@stop | gpl-2.0 |
gajop/Zero-K | units/chicken_blimpy.lua | 6362 | unitDef = {
unitname = [[chicken_blimpy]],
name = [[Blimpy]],
description = [[Dodo Bomber]],
airHoverFactor = 0,
amphibious = true,
buildCostEnergy = 0,
buildCostMetal = 0,
builder = false,
buildPic = [[chicken_blimpy.png]],
buildTime = 750,
canAttack = true,
canFly = true,
canGuard = true,
canLand = true,
canMove = true,
canPatrol = true,
canSubmerge = false,
category = [[FIXEDWING]],
collide = false,
cruiseAlt = 250,
customParams = {
description_fr = [[Bombardier ? Dodos]],
description_de = [[Dodo Bomber]],
description_pl = [[Bombowiec Dodo]],
helptext = [[Blimpy drops a Dodo on unsuspecting armies and bases.]],
helptext_fr = [[Le Blimpy est une unit? a?rienne ressemblant ? un bourdon dont apparemment la seule vocation soit de l?cher sur l'adversaire le Dodo qu'elle transporte sous son ventre. D?vastateur contre les bases.]],
helptext_de = [[Blimpy wirft Dodos auf ahnungslose Heere und Basen ab.]],
helptext_pl = [[Blimpy zrzuca Dodo w charakterze bomb.]],
},
explodeAs = [[NOWEAPON]],
floater = true,
footprintX = 4,
footprintZ = 4,
iconType = [[bomberassault]],
idleAutoHeal = 20,
idleTime = 300,
leaveTracks = true,
maneuverleashlength = [[64000]],
mass = 258,
maxDamage = 1850,
maxSlope = 18,
maxVelocity = 5,
minCloakDistance = 75,
moverate1 = [[32]],
noAutoFire = false,
noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE GUNSHIP STUPIDTARGET]],
objectName = [[chicken_blimpy.s3o]],
power = 750,
seismicSignature = 0,
selfDestructAs = [[NOWEAPON]],
separation = [[0.2]],
sfxtypes = {
explosiongenerators = {
[[custom:blood_spray]],
[[custom:blood_explode]],
[[custom:dirt]],
},
},
side = [[THUNDERBIRDS]],
sightDistance = 512,
smoothAnim = true,
turnRate = 6000,
workerTime = 0,
weapons = {
{
def = [[BOGUS_BOMB]],
badTargetCategory = [[SWIM LAND SHIP HOVER]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER]],
},
{
def = [[BOMBTRIGGER]],
mainDir = [[0 -1 0]],
maxAngleDif = 70,
onlyTargetCategory = [[LAND SINK TURRET SHIP SWIM FLOAT HOVER SUB]],
},
{
def = [[DODOBOMB]],
mainDir = [[0 -1 0]],
maxAngleDif = 90,
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER SUB]],
},
},
weaponDefs = {
BOGUS_BOMB = {
name = [[BogusBomb]],
areaOfEffect = 80,
commandfire = true,
craterBoost = 0,
craterMult = 0,
damage = {
default = 0,
},
edgeEffectiveness = 0,
explosionGenerator = [[custom:NONE]],
impulseBoost = 0,
impulseFactor = 0,
interceptedByShieldType = 1,
model = [[wep_b_fabby.s3o]],
myGravity = 1000,
noSelfDamage = true,
range = 300,
reloadtime = 0.5,
weaponType = [[AircraftBomb]],
},
BOMBTRIGGER = {
name = [[Bogus BOMBTRIGGER]],
accuracy = 12000,
areaOfEffect = 1,
beamTime = 0.1,
canattackground = true,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
damage = {
default = 1,
planes = 1,
subs = 1,
},
explosionGenerator = [[custom:none]],
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0,
interceptedByShieldType = 0,
lodDistance = 10000,
minIntensity = 1,
noSelfDamage = true,
range = 900,
reloadtime = 14,
rgbColor = [[0 0 0]],
thickness = 0,
tolerance = 10000,
turret = true,
weaponType = [[BeamLaser]],
weaponVelocity = 100,
},
DODOBOMB = {
name = [[Dodo Bomb]],
accuracy = 60000,
areaOfEffect = 1,
avoidFeature = false,
avoidFriendly = false,
burnblow = true,
burst = 1,
burstrate = 0.1,
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
customparams = {
spawns_name = "chicken_dodo",
spawns_expire = 30,
},
damage = {
default = 1,
planes = 1,
subs = 1,
},
explosionGenerator = [[custom:none]],
fireStarter = 70,
flightTime = 0,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 0,
model = [[chicken_dodobomb.s3o]],
noSelfDamage = true,
range = 900,
reloadtime = 10,
smokeTrail = false,
startVelocity = 200,
tolerance = 8000,
tracks = false,
turnRate = 4000,
turret = true,
waterweapon = true,
weaponAcceleration = 200,
weaponTimer = 0.1,
weaponType = [[AircraftBomb]],
weaponVelocity = 200,
},
},
}
return lowerkeys({ chicken_blimpy = unitDef })
| gpl-2.0 |
FFMG/myoddweb.piger | myodd/boost/libs/hana/example/misc/printf.cpp | 2380 | // Copyright Louis Dionne 2013-2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
#include <boost/hana/adjust_if.hpp>
#include <boost/hana/at_key.hpp>
#include <boost/hana/core/to.hpp>
#include <boost/hana/core/is_a.hpp>
#include <boost/hana/filter.hpp>
#include <boost/hana/fold_left.hpp>
#include <boost/hana/functional/compose.hpp>
#include <boost/hana/functional/partial.hpp>
#include <boost/hana/map.hpp>
#include <boost/hana/not.hpp>
#include <boost/hana/pair.hpp>
#include <boost/hana/prepend.hpp>
#include <boost/hana/string.hpp>
#include <boost/hana/tuple.hpp>
#include <boost/hana/type.hpp>
#include <boost/hana/unpack.hpp>
#include <cstdio>
namespace hana = boost::hana;
constexpr auto formats = hana::make_map(
hana::make_pair(hana::type_c<int>, hana::string_c<'%', 'd'>),
hana::make_pair(hana::type_c<float>, hana::string_c<'%', 'f'>),
hana::make_pair(hana::type_c<char const*>, hana::string_c<'%', 's'>)
);
struct concat_strings {
template <char ...s1, char ...s2>
constexpr auto operator()(hana::string<s1...>, hana::string<s2...>) const
{ return hana::string_c<s1..., s2...>; }
};
template <typename ...Tokens>
constexpr auto format(Tokens ...tokens_) {
auto tokens = hana::make_tuple(tokens_...);
// If you don't care about constexpr-ness of `format`, you can use
// this lambda instead of `compose(partial(...), typeid_)`:
//
// [](auto token) {
// return formats[typeid_(token)];
// }
auto format_string_tokens = hana::adjust_if(tokens,
hana::compose(hana::not_, hana::is_a<hana::string_tag>),
hana::compose(hana::partial(hana::at_key, formats), hana::typeid_)
);
auto format_string = hana::fold_left(format_string_tokens, hana::string_c<>, concat_strings{});
auto variables = hana::filter(tokens, hana::compose(hana::not_, hana::is_a<hana::string_tag>));
return hana::prepend(variables, format_string);
}
int main() {
int a = 1;
float b = 1.3;
char const* c = "abcdef";
auto args = format(
BOOST_HANA_STRING("first="), a
, BOOST_HANA_STRING(" second="), b
, BOOST_HANA_STRING(" third="), c
);
hana::unpack(args, [](auto fmt, auto ...args) {
std::printf(hana::to<char const*>(fmt), args...);
});
}
| gpl-2.0 |
krullgor/portalclassic | src/game/Level0.cpp | 9202 | /*
* This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Common.h"
#include "Database/DatabaseEnv.h"
#include "World.h"
#include "Player.h"
#include "Opcodes.h"
#include "Chat.h"
#include "ObjectAccessor.h"
#include "Language.h"
#include "AccountMgr.h"
#include "ScriptMgr.h"
#include "SystemConfig.h"
#include "revision.h"
#include "revision_nr.h"
#include "Util.h"
bool ChatHandler::HandleHelpCommand(char* args)
{
if (!*args)
{
ShowHelpForCommand(getCommandTable(), "help");
ShowHelpForCommand(getCommandTable(), "");
}
else
{
if (!ShowHelpForCommand(getCommandTable(), args))
SendSysMessage(LANG_NO_CMD);
}
return true;
}
bool ChatHandler::HandleCommandsCommand(char* /*args*/)
{
ShowHelpForCommand(getCommandTable(), "");
return true;
}
bool ChatHandler::HandleAccountCommand(char* args)
{
// let show subcommands at unexpected data in args
if (*args)
return false;
AccountTypes gmlevel = GetAccessLevel();
PSendSysMessage(LANG_ACCOUNT_LEVEL, uint32(gmlevel));
return true;
}
bool ChatHandler::HandleStartCommand(char* /*args*/)
{
Player* chr = m_session->GetPlayer();
if (chr->IsTaxiFlying())
{
SendSysMessage(LANG_YOU_IN_FLIGHT);
SetSentErrorMessage(true);
return false;
}
if (chr->isInCombat())
{
SendSysMessage(LANG_YOU_IN_COMBAT);
SetSentErrorMessage(true);
return false;
}
// cast spell Stuck
chr->CastSpell(chr, 7355, false);
return true;
}
bool ChatHandler::HandleServerInfoCommand(char* /*args*/)
{
uint32 activeClientsNum = sWorld.GetActiveSessionCount();
uint32 queuedClientsNum = sWorld.GetQueuedSessionCount();
uint32 maxActiveClientsNum = sWorld.GetMaxActiveSessionCount();
uint32 maxQueuedClientsNum = sWorld.GetMaxQueuedSessionCount();
std::string str = secsToTimeString(sWorld.GetUptime());
char const* full;
if (m_session)
full = _FULLVERSION(REVISION_DATE, REVISION_TIME, REVISION_NR, "|cffffffff|Hurl:" REVISION_ID "|h" REVISION_ID "|h|r");
else
full = _FULLVERSION(REVISION_DATE, REVISION_TIME, REVISION_NR, REVISION_ID);
SendSysMessage(full);
if (sScriptMgr.IsScriptLibraryLoaded())
{
char const* ver = sScriptMgr.GetScriptLibraryVersion();
if (ver && *ver)
PSendSysMessage(LANG_USING_SCRIPT_LIB, ver);
else
SendSysMessage(LANG_USING_SCRIPT_LIB_UNKNOWN);
}
else
SendSysMessage(LANG_USING_SCRIPT_LIB_NONE);
PSendSysMessage(LANG_USING_WORLD_DB, sWorld.GetDBVersion());
PSendSysMessage(LANG_USING_EVENT_AI, sWorld.GetCreatureEventAIVersion());
PSendSysMessage(LANG_CONNECTED_USERS, activeClientsNum, maxActiveClientsNum, queuedClientsNum, maxQueuedClientsNum);
PSendSysMessage(LANG_UPTIME, str.c_str());
return true;
}
bool ChatHandler::HandleDismountCommand(char* /*args*/)
{
Player* player = m_session->GetPlayer();
// If player is not mounted, so go out :)
if (!player->IsMounted())
{
SendSysMessage(LANG_CHAR_NON_MOUNTED);
SetSentErrorMessage(true);
return false;
}
if (player->IsTaxiFlying())
{
SendSysMessage(LANG_YOU_IN_FLIGHT);
SetSentErrorMessage(true);
return false;
}
player->Unmount();
player->RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
return true;
}
bool ChatHandler::HandleSaveCommand(char* /*args*/)
{
Player* player = m_session->GetPlayer();
// save GM account without delay and output message (testing, etc)
if (GetAccessLevel() > SEC_PLAYER)
{
player->SaveToDB();
SendSysMessage(LANG_PLAYER_SAVED);
return true;
}
// save or plan save after 20 sec (logout delay) if current next save time more this value and _not_ output any messages to prevent cheat planning
uint32 save_interval = sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE);
if (save_interval == 0 || (save_interval > 20 * IN_MILLISECONDS && player->GetSaveTimer() <= save_interval - 20 * IN_MILLISECONDS))
player->SaveToDB();
return true;
}
bool ChatHandler::HandleGMListIngameCommand(char* /*args*/)
{
std::list< std::pair<std::string, bool> > names;
{
HashMapHolder<Player>::ReadGuard g(HashMapHolder<Player>::GetLock());
HashMapHolder<Player>::MapType& m = sObjectAccessor.GetPlayers();
for (HashMapHolder<Player>::MapType::const_iterator itr = m.begin(); itr != m.end(); ++itr)
{
Player* player = itr->second;
AccountTypes security = player->GetSession()->GetSecurity();
if ((player->isGameMaster() || (security > SEC_PLAYER && security <= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_GM_LEVEL_IN_GM_LIST))) &&
(!m_session || player->IsVisibleGloballyFor(m_session->GetPlayer())))
names.push_back(std::make_pair<std::string, bool>(GetNameLink(player), player->isAcceptWhispers()));
}
}
if (!names.empty())
{
SendSysMessage(LANG_GMS_ON_SRV);
char const* accepts = GetMangosString(LANG_GM_ACCEPTS_WHISPER);
char const* not_accept = GetMangosString(LANG_GM_NO_WHISPER);
for (std::list<std::pair< std::string, bool> >::const_iterator iter = names.begin(); iter != names.end(); ++iter)
PSendSysMessage("%s - %s", iter->first.c_str(), iter->second ? accepts : not_accept);
}
else
SendSysMessage(LANG_GMS_NOT_LOGGED);
return true;
}
bool ChatHandler::HandleAccountPasswordCommand(char* args)
{
// allow use from RA, but not from console (not have associated account id)
if (!GetAccountId())
{
SendSysMessage(LANG_RA_ONLY_COMMAND);
SetSentErrorMessage(true);
return false;
}
// allow or quoted string with possible spaces or literal without spaces
char* old_pass = ExtractQuotedOrLiteralArg(&args);
char* new_pass = ExtractQuotedOrLiteralArg(&args);
char* new_pass_c = ExtractQuotedOrLiteralArg(&args);
if (!old_pass || !new_pass || !new_pass_c)
return false;
std::string password_old = old_pass;
std::string password_new = new_pass;
std::string password_new_c = new_pass_c;
if (password_new != password_new_c)
{
SendSysMessage(LANG_NEW_PASSWORDS_NOT_MATCH);
SetSentErrorMessage(true);
return false;
}
if (!sAccountMgr.CheckPassword(GetAccountId(), password_old))
{
SendSysMessage(LANG_COMMAND_WRONGOLDPASSWORD);
SetSentErrorMessage(true);
return false;
}
AccountOpResult result = sAccountMgr.ChangePassword(GetAccountId(), password_new);
switch (result)
{
case AOR_OK:
SendSysMessage(LANG_COMMAND_PASSWORD);
break;
case AOR_PASS_TOO_LONG:
SendSysMessage(LANG_PASSWORD_TOO_LONG);
SetSentErrorMessage(true);
return false;
case AOR_NAME_NOT_EXIST: // not possible case, don't want get account name for output
default:
SendSysMessage(LANG_COMMAND_NOTCHANGEPASSWORD);
SetSentErrorMessage(true);
return false;
}
// OK, but avoid normal report for hide passwords, but log use command for anyone
LogCommand(".account password *** *** ***");
SetSentErrorMessage(true);
return false;
}
bool ChatHandler::HandleAccountLockCommand(char* args)
{
// allow use from RA, but not from console (not have associated account id)
if (!GetAccountId())
{
SendSysMessage(LANG_RA_ONLY_COMMAND);
SetSentErrorMessage(true);
return false;
}
bool value;
if (!ExtractOnOff(&args, value))
{
SendSysMessage(LANG_USE_BOL);
SetSentErrorMessage(true);
return false;
}
if (value)
{
LoginDatabase.PExecute("UPDATE account SET locked = '1' WHERE id = '%u'", GetAccountId());
PSendSysMessage(LANG_COMMAND_ACCLOCKLOCKED);
}
else
{
LoginDatabase.PExecute("UPDATE account SET locked = '0' WHERE id = '%u'", GetAccountId());
PSendSysMessage(LANG_COMMAND_ACCLOCKUNLOCKED);
}
return true;
}
/// Display the 'Message of the day' for the realm
bool ChatHandler::HandleServerMotdCommand(char* /*args*/)
{
PSendSysMessage(LANG_MOTD_CURRENT, sWorld.GetMotd());
return true;
}
| gpl-2.0 |
webvangvn/nukeviet41 | modules/contact/admin.menu.php | 599 | <?php
/**
* @Project NUKEVIET 4.x
* @Author VINADES.,JSC (contact@vinades.vn)
* @Copyright (C) 2014 VINADES.,JSC. All rights reserved
* @License GNU/GPL version 2 or any later version
* @Createdate 07/30/2013 10:27
*/
if( ! defined( 'NV_ADMIN' ) ) die( 'Stop!!!' );
if( defined( 'NV_IS_GODADMIN' ) )
{
$submenu['list_row'] = $lang_module['list_row_title'];
$submenu['content'] = $lang_module['content'];
$allow_func = array( 'main', 'reply', 'del', 'list_row', 'row', 'del_row', 'content', 'view', 'change_status' );
}
else
{
$allow_func = array( 'main', 'reply', 'del', 'view' );
}
?> | gpl-2.0 |
AlexOreshkevich/velomode.by | world/Specs/Scene/SkyAtmosphereSpec.js | 4503 | /*global defineSuite*/
defineSuite([
'Scene/SkyAtmosphere',
'Core/Cartesian3',
'Core/Ellipsoid',
'Renderer/ClearCommand',
'Scene/SceneMode',
'Specs/createCamera',
'Specs/createContext',
'Specs/createFrameState'
], function(
SkyAtmosphere,
Cartesian3,
Ellipsoid,
ClearCommand,
SceneMode,
createCamera,
createContext,
createFrameState) {
"use strict";
/*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn*/
var context;
beforeAll(function() {
context = createContext();
});
afterAll(function() {
context.destroyForSpecs();
});
it('draws sky with camera in atmosphere', function() {
var s = new SkyAtmosphere();
ClearCommand.ALL.execute(context);
expect(context.readPixels()).toEqual([0, 0, 0, 0]);
var us = context.uniformState;
var radii = Ellipsoid.WGS84.radii;
var frameState = createFrameState(createCamera({
offset : new Cartesian3(radii.x * 0.1, 0.0, 0.0),
target : new Cartesian3(0.0, 0.0, radii.z * 1.005),
near : 1.0,
far : 20000000.0
}));
us.update(context, frameState);
var command = s.update(context, frameState);
expect(command).toBeDefined();
command.execute(context); // Not reliable enough across browsers to test pixels
s.destroy();
});
it('draws sky with camera in space', function() {
var s = new SkyAtmosphere();
ClearCommand.ALL.execute(context);
expect(context.readPixels()).toEqual([0, 0, 0, 0]);
var us = context.uniformState;
var radii = Ellipsoid.WGS84.radii;
var frameState = createFrameState(createCamera({
offset : new Cartesian3(radii.x * 0.1, 0.0, 0.0),
target : new Cartesian3(0.0, 0.0, radii.z * 1.005),
near : 1.0,
far : 20000000.0
}));
us.update(context, frameState);
var command = s.update(context, frameState);
expect(command).toBeDefined();
command.execute(context); // Not reliable enough across browsers to test pixels
s.destroy();
});
it('does not render when show is false', function() {
var s = new SkyAtmosphere();
s.show = false;
var us = context.uniformState;
var radii = Ellipsoid.WGS84.radii;
var frameState = createFrameState(createCamera({
offset : new Cartesian3(radii.x * 0.1, 0.0, 0.0),
target : new Cartesian3(0.0, 0.0, radii.z * 1.005),
near : 1.0,
far : 20000000.0
}));
us.update(context, frameState);
var command = s.update(context, frameState);
expect(command).not.toBeDefined();
});
it('does not render in 2D', function() {
var s = new SkyAtmosphere();
var us = context.uniformState;
var radii = Ellipsoid.WGS84.radii;
var frameState = createFrameState(createCamera({
offset : new Cartesian3(radii.x * 0.1, 0.0, 0.0),
target : new Cartesian3(0.0, 0.0, radii.z * 1.005),
near : 1.0,
far : 20000000.0
}));
frameState.mode = SceneMode.SCENE2D;
us.update(context, frameState);
var command = s.update(context, frameState);
expect(command).not.toBeDefined();
});
it('does not render without a color pass', function() {
var s = new SkyAtmosphere();
var us = context.uniformState;
var radii = Ellipsoid.WGS84.radii;
var frameState = createFrameState(createCamera({
offset : new Cartesian3(radii.x * 0.1, 0.0, 0.0),
target : new Cartesian3(0.0, 0.0, radii.z * 1.005),
near : 1.0,
far : 20000000.0
}));
frameState.passes.render = false;
us.update(context, frameState);
var command = s.update(context, frameState);
expect(command).not.toBeDefined();
});
it('gets ellipsoid', function() {
var s = new SkyAtmosphere(Ellipsoid.UNIT_SPHERE);
expect(s.ellipsoid).toEqual(Ellipsoid.UNIT_SPHERE);
});
it('isDestroyed', function() {
var s = new SkyAtmosphere();
expect(s.isDestroyed()).toEqual(false);
s.destroy();
expect(s.isDestroyed()).toEqual(true);
});
}, 'WebGL'); | gpl-2.0 |
xinran505982/videolan_vlc | modules/gui/qt4/input_manager.hpp | 9082 | /*****************************************************************************
* input_manager.hpp : Manage an input and interact with its GUI elements
****************************************************************************
* Copyright (C) 2006-2008 the VideoLAN team
* $Id$
*
* Authors: Clément Stenac <zorglub@videolan.org>
* Jean-Baptiste <jb@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifndef QVLC_INPUT_MANAGER_H_
#define QVLC_INPUT_MANAGER_H_
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <vlc_input.h>
#include "qt4.hpp"
#include "util/singleton.hpp"
#include "adapters/variables.hpp"
#include <QObject>
#include <QEvent>
class QSignalMapper;
enum { NORMAL, /* loop: 0, repeat: 0 */
REPEAT_ONE,/* loop: 0, repeat: 1 */
REPEAT_ALL,/* loop: 1, repeat: 0 */
};
class IMEvent : public QEvent
{
public:
enum event_types {
PositionUpdate = QEvent::User + IMEventTypeOffset + 1,
ItemChanged,
ItemStateChanged,
ItemTitleChanged,
ItemRateChanged,
ItemEsChanged,
ItemTeletextChanged,
InterfaceVoutUpdate,
StatisticsUpdate, /*10*/
InterfaceAoutUpdate,
MetaChanged,
NameChanged,
InfoChanged,
SynchroChanged,
CachingEvent,
BookmarksChanged,
RecordingEvent,
ProgramChanged,
RandomChanged,
LoopOrRepeatChanged,
EPGEvent,
/* SignalChanged, */
FullscreenControlToggle = QEvent::User + IMEventTypeOffset + 20,
FullscreenControlShow,
FullscreenControlHide,
FullscreenControlPlanHide,
};
IMEvent( event_types type, input_item_t *p_input = NULL )
: QEvent( (QEvent::Type)(type) )
{
if( (p_item = p_input) != NULL )
vlc_gc_incref( p_item );
}
virtual ~IMEvent()
{
if( p_item )
vlc_gc_decref( p_item );
}
input_item_t *item() const { return p_item; };
private:
input_item_t *p_item;
};
class PLEvent : public QEvent
{
public:
enum PLEventTypes
{
PLItemAppended = QEvent::User + PLEventTypeOffset + 1,
PLItemRemoved,
LeafToParent,
PLEmpty
};
PLEvent( PLEventTypes t, int i, int p = 0 )
: QEvent( (QEvent::Type)(t) ), i_item(i), i_parent(p) {}
int getItemId() const { return i_item; };
int getParentId() const { return i_parent; };
private:
/* Needed for "playlist-item*" and "leaf-to-parent" callbacks
* !! Can be a input_item_t->i_id or a playlist_item_t->i_id */
int i_item;
// Needed for "playlist-item-append" callback, notably
int i_parent;
};
class InputManager : public QObject
{
Q_OBJECT
friend class MainInputManager;
public:
InputManager( QObject *, intf_thread_t * );
virtual ~InputManager();
void delInput();
bool hasInput()
{
return p_input /* We have an input */
&& !p_input->b_dead /* not dead yet, */
&& !p_input->b_eof /* not EOF either */;
}
int playingStatus();
bool hasAudio();
bool hasVideo() { return hasInput() && b_video; }
bool hasVisualisation();
void requestArtUpdate( input_item_t *p_item, bool b_forced );
void setArt( input_item_t *p_item, QString fileUrl );
QString getName() { return oldName; }
static const QString decodeArtURL( input_item_t *p_item );
private:
intf_thread_t *p_intf;
input_thread_t *p_input;
vlc_object_t *p_input_vbi;
input_item_t *p_item;
int i_old_playing_status;
QString oldName;
QString lastURI;
QString artUrl;
float f_rate;
float f_cache;
bool b_video;
mtime_t timeA, timeB;
void customEvent( QEvent * );
void addCallbacks();
void delCallbacks();
void UpdateRate();
void UpdateName();
void UpdateStatus();
void UpdateNavigation();
void UpdatePosition();
void UpdateTeletext();
void UpdateArt();
void UpdateInfo();
void UpdateMeta();
void UpdateMeta(input_item_t *);
void UpdateVout();
void UpdateAout();
void UpdateStats();
void UpdateCaching();
void UpdateRecord();
void UpdateProgramEvent();
void UpdateEPG();
void setInput( input_thread_t * );
public slots:
void inputChangedHandler(); ///< Our controlled input changed
void sliderUpdate( float ); ///< User dragged the slider. We get new pos
/* SpeedRate Rate Management */
void reverse();
void slower();
void faster();
void littlefaster();
void littleslower();
void normalRate();
void setRate( int );
/* Jumping */
void jumpFwd();
void jumpBwd();
/* Menus */
void sectionNext();
void sectionPrev();
void sectionMenu();
/* Teletext */
void telexSetPage( int ); ///< Goto teletext page
void telexSetTransparency( bool ); ///< Transparency on teletext background
void activateTeletext( bool ); ///< Toggle buttons after click
/* A to B Loop */
void setAtoB();
private slots:
void AtoBLoop( float, int64_t, int );
signals:
/// Send new position, new time and new length
void positionUpdated( float , int64_t, int );
void seekRequested( float pos );
void rateChanged( float );
void nameChanged( const QString& );
/// Used to signal whether we should show navigation buttons
void titleChanged( bool );
void chapterChanged( bool );
void inputCanSeek( bool );
/// You can resume playback
void resumePlayback( int64_t );
/// Statistics are updated
void statisticsUpdated( input_item_t* );
void infoChanged( input_item_t* );
void currentMetaChanged( input_item_t* );
void metaChanged( input_item_t *);
void artChanged( QString ); /* current item art ( same as item == NULL ) */
void artChanged( input_item_t * );
/// Play/pause status
void playingStatusChanged( int );
void recordingStateChanged( bool );
/// Teletext
void teletextPossible( bool );
void teletextActivated( bool );
void teletextTransparencyActivated( bool );
void newTelexPageSet( int );
/// Advanced buttons
void AtoBchanged( bool, bool );
/// Vout
void voutChanged( bool );
void voutListChanged( vout_thread_t **pp_vout, int i_vout );
/// Other
void synchroChanged();
void bookmarksChanged();
void cachingChanged( float );
/// Program Event changes
void encryptionChanged( bool );
void epgChanged();
};
class MainInputManager : public QObject, public Singleton<MainInputManager>
{
Q_OBJECT
friend class Singleton<MainInputManager>;
friend class VLCMenuBar;
public:
input_thread_t *getInput() { return p_input; }
InputManager *getIM() { return im; }
inline input_item_t *currentInputItem()
{
return ( p_input ? input_GetItem( p_input ) : NULL );
}
vout_thread_t* getVout();
audio_output_t *getAout();
bool getPlayExitState();
bool hasEmptyPlaylist();
void requestVoutUpdate() { return im->UpdateVout(); }
protected:
QSignalMapper *menusAudioMapper;
private:
MainInputManager( intf_thread_t * );
virtual ~MainInputManager();
void customEvent( QEvent * );
InputManager *im;
input_thread_t *p_input;
intf_thread_t *p_intf;
QVLCBool random, repeat, loop;
QVLCFloat volume;
QVLCBool mute;
public slots:
void togglePlayPause();
void play();
void pause();
void toggleRandom();
void stop();
void next();
void prev();
void prevOrReset();
void activatePlayQuit( bool );
void loopRepeatLoopStatus();
private slots:
void notifyRandom( bool );
void notifyRepeatLoop( bool );
void notifyVolume( float );
void notifyMute( bool );
void menusUpdateAudio( const QString& );
signals:
void inputChanged( input_thread_t * );
void volumeChanged( float );
void soundMuteChanged( bool );
void playlistItemAppended( int itemId, int parentId );
void playlistItemRemoved( int itemId );
void playlistNotEmpty( bool );
void randomChanged( bool );
void repeatLoopChanged( int );
void leafBecameParent( int );
};
#endif
| gpl-2.0 |
gfgtdf/wesnoth-old | src/tests/utils/fake_display.cpp | 2186 | /*
Copyright (C) 2008 - 2018 by Pauli Nieminen <paniemin@cc.hut.fi>
Part of the Battle for Wesnoth Project https://www.wesnoth.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.
See the COPYING file for more details.
*/
#define GETTEXT_DOMAIN "wesnoth-test"
#include "tests/utils/fake_display.hpp"
#include "game_board.hpp"
#include "game_config_view.hpp"
#include "game_display.hpp"
#include "terrain/type_data.hpp"
#include "reports.hpp"
namespace wb {
class manager;
}
namespace test_utils {
class fake_display_manager {
static fake_display_manager* manager_;
CVideo video_;
config dummy_cfg_;
game_config_view dummy_cfg_view_;
config dummy_cfg2_;
game_board dummy_board_;
reports dummy_reports;
const events::event_context main_event_context_;
game_display disp_;
public:
static fake_display_manager* get_manager();
game_display& get_display();
fake_display_manager();
// ~fake_display_manager();
};
fake_display_manager* fake_display_manager::manager_ = 0;
fake_display_manager* fake_display_manager::get_manager()
{
if (!manager_)
{
manager_ = new fake_display_manager();
}
return manager_;
}
fake_display_manager::fake_display_manager() :
video_(CVideo::FAKE_TEST),
dummy_cfg_(),
dummy_cfg_view_(game_config_view::wrap(dummy_cfg_)),
dummy_cfg2_(),
dummy_board_(std::make_shared<terrain_type_data>(dummy_cfg_view_), dummy_cfg2_),
main_event_context_(),
disp_(dummy_board_, std::shared_ptr<wb::manager> (), dummy_reports, dummy_cfg_, dummy_cfg_)
{
}
game_display& fake_display_manager::get_display()
{
return disp_;
}
game_display& get_fake_display(const int width, const int height)
{
game_display& display =
fake_display_manager::get_manager()->get_display();
if(width >= 0 && height >= 0) {
display.video().make_test_fake(width, height);
}
return display;
}
}
| gpl-2.0 |
superwow/foton.core | dep/recastnavigation/Recast/RecastLayers.cpp | 16459 | //
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#include <float.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "Recast.h"
#include "RecastAlloc.h"
#include "RecastAssert.h"
static const int RC_MAX_LAYERS = RC_NOT_CONNECTED;
static const int RC_MAX_NEIS = 16;
struct rcLayerRegion
{
unsigned char layers[RC_MAX_LAYERS];
unsigned char neis[RC_MAX_NEIS];
unsigned short ymin, ymax;
unsigned char layerId; // Layer ID
unsigned char nlayers; // Layer count
unsigned char nneis; // Neighbour count
unsigned char base; // Flag indicating if the region is the base of merged regions.
};
static void addUnique(unsigned char* a, unsigned char& an, unsigned char v)
{
const int n = (int)an;
for (int i = 0; i < n; ++i)
if (a[i] == v)
return;
a[an] = v;
an++;
}
static bool contains(const unsigned char* a, const unsigned char an, const unsigned char v)
{
const int n = (int)an;
for (int i = 0; i < n; ++i)
if (a[i] == v)
return true;
return false;
}
inline bool overlapRange(const unsigned short amin, const unsigned short amax,
const unsigned short bmin, const unsigned short bmax)
{
return (amin > bmax || amax < bmin) ? false : true;
}
struct rcLayerSweepSpan
{
unsigned short ns; // number samples
unsigned char id; // region id
unsigned char nei; // neighbour id
};
/// @par
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// @see rcAllocHeightfieldLayerSet, rcCompactHeightfield, rcHeightfieldLayerSet, rcConfig
bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
const int borderSize, const int walkableHeight,
rcHeightfieldLayerSet& lset)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_BUILD_LAYERS);
const int w = chf.width;
const int h = chf.height;
rcScopedDelete<unsigned char> srcReg = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
if (!srcReg)
{
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'srcReg' (%d).", chf.spanCount);
return false;
}
memset(srcReg,0xff,sizeof(unsigned char)*chf.spanCount);
const int nsweeps = chf.width;
rcScopedDelete<rcLayerSweepSpan> sweeps = (rcLayerSweepSpan*)rcAlloc(sizeof(rcLayerSweepSpan)*nsweeps, RC_ALLOC_TEMP);
if (!sweeps)
{
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'sweeps' (%d).", nsweeps);
return false;
}
// Partition walkable area into monotone regions.
int prevCount[256];
unsigned char regId = 0;
for (int y = borderSize; y < h-borderSize; ++y)
{
memset(prevCount,0,sizeof(int)*regId);
unsigned char sweepId = 0;
for (int x = borderSize; x < w-borderSize; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
const rcCompactSpan& s = chf.spans[i];
if (chf.areas[i] == RC_NULL_AREA) continue;
unsigned char sid = 0xff;
// -x
if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(0);
const int ay = y + rcGetDirOffsetY(0);
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0);
if (chf.areas[ai] != RC_NULL_AREA && srcReg[ai] != 0xff)
sid = srcReg[ai];
}
if (sid == 0xff)
{
sid = sweepId++;
sweeps[sid].nei = 0xff;
sweeps[sid].ns = 0;
}
// -y
if (rcGetCon(s,3) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(3);
const int ay = y + rcGetDirOffsetY(3);
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3);
const unsigned char nr = srcReg[ai];
if (nr != 0xff)
{
// Set neighbour when first valid neighbour is encoutered.
if (sweeps[sid].ns == 0)
sweeps[sid].nei = nr;
if (sweeps[sid].nei == nr)
{
// Update existing neighbour
sweeps[sid].ns++;
prevCount[nr]++;
}
else
{
// This is hit if there is nore than one neighbour.
// Invalidate the neighbour.
sweeps[sid].nei = 0xff;
}
}
}
srcReg[i] = sid;
}
}
// Create unique ID.
for (int i = 0; i < sweepId; ++i)
{
// If the neighbour is set and there is only one continuous connection to it,
// the sweep will be merged with the previous one, else new region is created.
if (sweeps[i].nei != 0xff && prevCount[sweeps[i].nei] == (int)sweeps[i].ns)
{
sweeps[i].id = sweeps[i].nei;
}
else
{
if (regId == 255)
{
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Region ID overflow.");
return false;
}
sweeps[i].id = regId++;
}
}
// Remap local sweep ids to region ids.
for (int x = borderSize; x < w-borderSize; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
if (srcReg[i] != 0xff)
srcReg[i] = sweeps[srcReg[i]].id;
}
}
}
// Allocate and init layer regions.
const int nregs = (int)regId;
rcScopedDelete<rcLayerRegion> regs = (rcLayerRegion*)rcAlloc(sizeof(rcLayerRegion)*nregs, RC_ALLOC_TEMP);
if (!regs)
{
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'regs' (%d).", nregs);
return false;
}
memset(regs, 0, sizeof(rcLayerRegion)*nregs);
for (int i = 0; i < nregs; ++i)
{
regs[i].layerId = 0xff;
regs[i].ymin = 0xffff;
regs[i].ymax = 0;
}
// Find region neighbours and overlapping regions.
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
unsigned char lregs[RC_MAX_LAYERS];
int nlregs = 0;
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
const rcCompactSpan& s = chf.spans[i];
const unsigned char ri = srcReg[i];
if (ri == 0xff) continue;
regs[ri].ymin = rcMin(regs[ri].ymin, s.y);
regs[ri].ymax = rcMax(regs[ri].ymax, s.y);
// Collect all region layers.
if (nlregs < RC_MAX_LAYERS)
lregs[nlregs++] = ri;
// Update neighbours
for (int dir = 0; dir < 4; ++dir)
{
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(dir);
const int ay = y + rcGetDirOffsetY(dir);
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
const unsigned char rai = srcReg[ai];
if (rai != 0xff && rai != ri)
addUnique(regs[ri].neis, regs[ri].nneis, rai);
}
}
}
// Update overlapping regions.
for (int i = 0; i < nlregs-1; ++i)
{
for (int j = i+1; j < nlregs; ++j)
{
if (lregs[i] != lregs[j])
{
rcLayerRegion& ri = regs[lregs[i]];
rcLayerRegion& rj = regs[lregs[j]];
addUnique(ri.layers, ri.nlayers, lregs[j]);
addUnique(rj.layers, rj.nlayers, lregs[i]);
}
}
}
}
}
// Create 2D layers from regions.
unsigned char layerId = 0;
static const int MAX_STACK = 64;
unsigned char stack[MAX_STACK];
int nstack = 0;
for (int i = 0; i < nregs; ++i)
{
rcLayerRegion& root = regs[i];
// Skip already visited.
if (root.layerId != 0xff)
continue;
// Start search.
root.layerId = layerId;
root.base = 1;
nstack = 0;
stack[nstack++] = (unsigned char)i;
while (nstack)
{
// Pop front
rcLayerRegion& reg = regs[stack[0]];
nstack--;
for (int j = 0; j < nstack; ++j)
stack[j] = stack[j+1];
const int nneis = (int)reg.nneis;
for (int j = 0; j < nneis; ++j)
{
const unsigned char nei = reg.neis[j];
rcLayerRegion& regn = regs[nei];
// Skip already visited.
if (regn.layerId != 0xff)
continue;
// Skip if the neighbour is overlapping root region.
if (contains(root.layers, root.nlayers, nei))
continue;
// Skip if the height range would become too large.
const int ymin = rcMin(root.ymin, regn.ymin);
const int ymax = rcMax(root.ymax, regn.ymax);
if ((ymax - ymin) >= 255)
continue;
if (nstack < MAX_STACK)
{
// Deepen
stack[nstack++] = (unsigned char)nei;
// Mark layer id
regn.layerId = layerId;
// Merge current layers to root.
for (int k = 0; k < regn.nlayers; ++k)
addUnique(root.layers, root.nlayers, regn.layers[k]);
root.ymin = rcMin(root.ymin, regn.ymin);
root.ymax = rcMax(root.ymax, regn.ymax);
}
}
}
layerId++;
}
// Merge non-overlapping regions that are close in height.
const unsigned short mergeHeight = (unsigned short)walkableHeight * 4;
for (int i = 0; i < nregs; ++i)
{
rcLayerRegion& ri = regs[i];
if (!ri.base) continue;
unsigned char newId = ri.layerId;
for (;;)
{
unsigned char oldId = 0xff;
for (int j = 0; j < nregs; ++j)
{
if (i == j) continue;
rcLayerRegion& rj = regs[j];
if (!rj.base) continue;
// Skip if the regions are not close to each other.
if (!overlapRange(ri.ymin,ri.ymax+mergeHeight, rj.ymin,rj.ymax+mergeHeight))
continue;
// Skip if the height range would become too large.
const int ymin = rcMin(ri.ymin, rj.ymin);
const int ymax = rcMax(ri.ymax, rj.ymax);
if ((ymax - ymin) >= 255)
continue;
// Make sure that there is no overlap when merging 'ri' and 'rj'.
bool overlap = false;
// Iterate over all regions which have the same layerId as 'rj'
for (int k = 0; k < nregs; ++k)
{
if (regs[k].layerId != rj.layerId)
continue;
// Check if region 'k' is overlapping region 'ri'
// Index to 'regs' is the same as region id.
if (contains(ri.layers,ri.nlayers, (unsigned char)k))
{
overlap = true;
break;
}
}
// Cannot merge of regions overlap.
if (overlap)
continue;
// Can merge i and j.
oldId = rj.layerId;
break;
}
// Could not find anything to merge with, stop.
if (oldId == 0xff)
break;
// Merge
for (int j = 0; j < nregs; ++j)
{
rcLayerRegion& rj = regs[j];
if (rj.layerId == oldId)
{
rj.base = 0;
// Remap layerIds.
rj.layerId = newId;
// Add overlaid layers from 'rj' to 'ri'.
for (int k = 0; k < rj.nlayers; ++k)
addUnique(ri.layers, ri.nlayers, rj.layers[k]);
// Update height bounds.
ri.ymin = rcMin(ri.ymin, rj.ymin);
ri.ymax = rcMax(ri.ymax, rj.ymax);
}
}
}
}
// Compact layerIds
unsigned char remap[256];
memset(remap, 0, 256);
// Find number of unique layers.
layerId = 0;
for (int i = 0; i < nregs; ++i)
remap[regs[i].layerId] = 1;
for (int i = 0; i < 256; ++i)
{
if (remap[i])
remap[i] = layerId++;
else
remap[i] = 0xff;
}
// Remap ids.
for (int i = 0; i < nregs; ++i)
regs[i].layerId = remap[regs[i].layerId];
// No layers, return empty.
if (layerId == 0)
{
ctx->stopTimer(RC_TIMER_BUILD_LAYERS);
return true;
}
// Create layers.
rcAssert(lset.layers == 0);
const int lw = w - borderSize*2;
const int lh = h - borderSize*2;
// Build contracted bbox for layers.
float bmin[3], bmax[3];
rcVcopy(bmin, chf.bmin);
rcVcopy(bmax, chf.bmax);
bmin[0] += borderSize*chf.cs;
bmin[2] += borderSize*chf.cs;
bmax[0] -= borderSize*chf.cs;
bmax[2] -= borderSize*chf.cs;
lset.nlayers = (int)layerId;
lset.layers = (rcHeightfieldLayer*)rcAlloc(sizeof(rcHeightfieldLayer)*lset.nlayers, RC_ALLOC_PERM);
if (!lset.layers)
{
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'layers' (%d).", lset.nlayers);
return false;
}
memset(lset.layers, 0, sizeof(rcHeightfieldLayer)*lset.nlayers);
// Store layers.
for (int i = 0; i < lset.nlayers; ++i)
{
unsigned char curId = (unsigned char)i;
rcHeightfieldLayer* layer = &lset.layers[i];
const int gridSize = sizeof(unsigned char)*lw*lh;
layer->heights = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);
if (!layer->heights)
{
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'heights' (%d).", gridSize);
return false;
}
memset(layer->heights, 0xff, gridSize);
layer->areas = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);
if (!layer->areas)
{
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'areas' (%d).", gridSize);
return false;
}
memset(layer->areas, 0, gridSize);
layer->cons = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);
if (!layer->cons)
{
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'cons' (%d).", gridSize);
return false;
}
memset(layer->cons, 0, gridSize);
// Find layer height bounds.
int hmin = 0, hmax = 0;
for (int j = 0; j < nregs; ++j)
{
if (regs[j].base && regs[j].layerId == curId)
{
hmin = (int)regs[j].ymin;
hmax = (int)regs[j].ymax;
}
}
layer->width = lw;
layer->height = lh;
layer->cs = chf.cs;
layer->ch = chf.ch;
// Adjust the bbox to fit the heightfield.
rcVcopy(layer->bmin, bmin);
rcVcopy(layer->bmax, bmax);
layer->bmin[1] = bmin[1] + hmin*chf.ch;
layer->bmax[1] = bmin[1] + hmax*chf.ch;
layer->hmin = hmin;
layer->hmax = hmax;
// Update usable data region.
layer->minx = layer->width;
layer->maxx = 0;
layer->miny = layer->height;
layer->maxy = 0;
// Copy height and area from compact heightfield.
for (int y = 0; y < lh; ++y)
{
for (int x = 0; x < lw; ++x)
{
const int cx = borderSize+x;
const int cy = borderSize+y;
const rcCompactCell& c = chf.cells[cx+cy*w];
for (int j = (int)c.index, nj = (int)(c.index+c.count); j < nj; ++j)
{
const rcCompactSpan& s = chf.spans[j];
// Skip unassigned regions.
if (srcReg[j] == 0xff)
continue;
// Skip of does nto belong to current layer.
unsigned char lid = regs[srcReg[j]].layerId;
if (lid != curId)
continue;
// Update data bounds.
layer->minx = rcMin(layer->minx, x);
layer->maxx = rcMax(layer->maxx, x);
layer->miny = rcMin(layer->miny, y);
layer->maxy = rcMax(layer->maxy, y);
// Store height and area type.
const int idx = x+y*lw;
layer->heights[idx] = (unsigned char)(s.y - hmin);
layer->areas[idx] = chf.areas[j];
// Check connection.
unsigned char portal = 0;
unsigned char con = 0;
for (int dir = 0; dir < 4; ++dir)
{
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
{
const int ax = cx + rcGetDirOffsetX(dir);
const int ay = cy + rcGetDirOffsetY(dir);
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
unsigned char alid = srcReg[ai] != 0xff ? regs[srcReg[ai]].layerId : 0xff;
// Portal mask
if (chf.areas[ai] != RC_NULL_AREA && lid != alid)
{
portal |= (unsigned char)(1<<dir);
// Update height so that it matches on both sides of the portal.
const rcCompactSpan& as = chf.spans[ai];
if (as.y > hmin)
layer->heights[idx] = rcMax(layer->heights[idx], (unsigned char)(as.y - hmin));
}
// Valid connection mask
if (chf.areas[ai] != RC_NULL_AREA && lid == alid)
{
const int nx = ax - borderSize;
const int ny = ay - borderSize;
if (nx >= 0 && ny >= 0 && nx < lw && ny < lh)
con |= (unsigned char)(1<<dir);
}
}
}
layer->cons[idx] = (portal << 4) | con;
}
}
}
if (layer->minx > layer->maxx)
layer->minx = layer->maxx = 0;
if (layer->miny > layer->maxy)
layer->miny = layer->maxy = 0;
}
ctx->stopTimer(RC_TIMER_BUILD_LAYERS);
return true;
}
| gpl-2.0 |
infoalex/huayra | cxp/sigesp_cxp_r_relacionndnc.php | 13496 | <?php
session_start();
////////////////////////////////////////////// SEGURIDAD /////////////////////////////////////////////
if(!array_key_exists("la_logusr",$_SESSION))
{
print "<script language=JavaScript>";
print "location.href='../sigesp_inicio_sesion.php'";
print "</script>";
}
$ls_logusr=$_SESSION["la_logusr"];
require_once("class_folder/class_funciones_cxp.php");
$io_fun_cxp=new class_funciones_cxp();
$io_fun_cxp->uf_load_seguridad("CXP","sigesp_cxp_r_relacionndnc.php",$ls_permisos,$la_seguridad,$la_permisos);
////////////////////////////////////////////// SEGURIDAD /////////////////////////////////////////////
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Reporte de Relación de Notas de Debito/Crédito </title>
<meta http-equiv="" content="text/html; charset=iso-8859-1">
<meta http-equiv="" content="text/html; charset=iso-8859-1">
<script type="text/javascript" language="JavaScript1.2" src="js/stm31.js"></script>
<script type="text/javascript" language="JavaScript1.2" src="js/funcion_cxp.js"></script>
<meta http-equiv="" content="text/html; charset=iso-8859-1"><meta http-equiv="" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Type" content="text/html; charset=">
<link href="../shared/css/cabecera.css" rel="stylesheet" type="text/css">
<link href="../shared/css/general.css" rel="stylesheet" type="text/css">
<link href="../shared/css/tablas.css" rel="stylesheet" type="text/css">
<link href="../shared/css/ventanas.css" rel="stylesheet" type="text/css">
<link href="../shared/js/css_intra/datepickercontrol.css" rel="stylesheet" type="text/css">
<link href="css/cxp.css" rel="stylesheet" type="text/css">
<script type="text/javascript" language="JavaScript1.2" src="../shared/js/disabled_keys.js"></script>
<script language="javascript">
if(document.all)
{ //ie
document.onkeydown = function(){
if(window.event && (window.event.keyCode == 122 || window.event.keyCode == 116 || window.event.ctrlKey))
{
window.event.keyCode = 505;
}
if(window.event.keyCode == 505){ return false;}
}
}
</script>
<style type="text/css">
<!--
a:link {
color: #006699;
}
a:visited {
color: #006699;
}
a:hover {
color: #006699;
}
a:active {
color: #006699;
}
-->
</style></head>
<body>
<table width="762" border="0" align="center" cellpadding="0" cellspacing="0" class="contorno">
<tr>
<td width="780" height="30" colspan="11" class="cd-logo"><img src="../shared/imagebank/header.jpg" width="804" height="40"></td>
</tr>
<tr>
<td width="432" height="20" colspan="11" bgcolor="#E7E7E7">
<table width="774" border="0" align="center" cellpadding="0" cellspacing="0">
<td width="423" height="20" bgcolor="#E7E7E7" class="descripcion_sistema">Cuentas por Pagar </td>
<td width="351" bgcolor="#E7E7E7"><div align="right"><span class="letras-pequenas"><b><?PHP print date("j/n/Y")." - ".date("h:i a");?></b></span></div></td>
<tr>
<td height="20" bgcolor="#E7E7E7" class="descripcion_sistema"> </td>
<td bgcolor="#E7E7E7"><div align="right" class="letras-pequenas"><b><?php print $_SESSION["la_nomusu"]." ".$_SESSION["la_apeusu"];?></b></div></td>
</table> </td>
</tr>
<tr>
<td height="20" colspan="11" bgcolor="#E7E7E7" class="cd-menu"><script type="text/javascript" language="JavaScript1.2" src="js/menu.js"></script></td>
</tr>
<tr>
<td width="780" height="13" colspan="11" class="toolbar"></td>
</tr>
<tr>
<td height="20" width="25" class="toolbar"><div align="center"><a href="javascript: uf_imprimir();"><img src="../shared/imagebank/tools20/imprimir.gif" alt="Imprimir" width="20" height="20" border="0" title="Imprimir"></a></div></td>
<td class="toolbar" width="25"><div align="center"><a href="javascript: ue_cerrar();"><img src="../shared/imagebank/tools20/salir.gif" alt="Salir" width="20" height="20" border="0" title="Salir"></a></div></td>
<td class="toolbar" width="25"><div align="center"><a href="javascript: ue_ayuda();"><img src="../shared/imagebank/tools20/ayuda.gif" alt="Ayuda" width="20" height="20" border="0" title="Ayuda"></a></div></td>
<td class="toolbar" width="25"><div align="center"></div></td>
<td class="toolbar" width="25"> </td>
<td class="toolbar" width="25"><div align="center"></div></td>
<td class="toolbar" width="25"><div align="center"></div></td>
<td class="toolbar" width="25"><div align="center"></div></td>
<td class="toolbar" width="25"><div align="center"></div></td>
<td class="toolbar" width="25"><div align="center"></div></td>
<td class="toolbar" width="530"> </td>
</tr>
</table>
</div>
<p> </p>
<form name="formulario" method="post" action="">
<?php
////////////////////////////////////////////// SEGURIDAD /////////////////////////////////////////////
$io_fun_cxp->uf_print_permisos($ls_permisos,$la_permisos,$ls_logusr,"location.href='sigespwindow_blank.php'");
unset($io_fun_cxp);
////////////////////////////////////////////// SEGURIDAD /////////////////////////////////////////////
?>
<table width="599" height="18" border="0" align="center" cellpadding="1" cellspacing="1">
<tr>
<td width="595" colspan="2" class="titulo-ventana">Reporte de Relación de Notas de Debito/Crédito </td>
</tr>
</table>
<table width="600" border="0" align="center" cellpadding="0" cellspacing="0" class="formato-blanco">
<tr>
<td width="598"></td>
</tr>
<tr style="visibility:hidden">
<td height="22" colspan="3" align="center"><div align="left">Reporte en
<select name="cmbbsf" id="cmbbsf">
<option value="0" selected>Bs.</option>
<option value="1">Bs.F.</option>
</select>
</div></td>
</tr>
<tr>
<td height="22" colspan="3" align="center"><table width="511" border="0" cellspacing="0" class="formato-blanco">
<tr>
<td width="199" height="22"><div align="left"><strong>Solicitudes de Pago </strong></div></td>
<td width="89" height="22"><div align="center"></div></td>
<td width="215" height="22"><div align="left"></div></td>
</tr>
<tr>
<td height="22"><div align="right">Desde
<input name="txtnumsoldes" type="text" id="txtnumsoldes" size="20" readonly>
<a href="javascript: ue_catalogo_solicitudes('REPDES');"><img src="../shared/imagebank/tools15/buscar.gif" width="15" height="15" border="0"></a></div></td>
<td><div align="right">Hasta</div></td>
<td><input name="txtnumsolhas" type="text" id="txtnumsolhas" size="20" readonly>
<a href="javascript: ue_catalogo_solicitudes('REPHAS');"><img src="../shared/imagebank/tools15/buscar.gif" width="15" height="15" border="0"></a></td>
</tr>
</table></td>
</tr>
<tr>
<td height="22" colspan="3" align="center"> </td>
</tr>
<tr>
<td height="22" colspan="3" align="center"><table width="511" border="0" cellspacing="0" class="formato-blanco">
<tr>
<td width="199" height="22"><div align="left"><strong>Notas de Debito/Credito </strong></div></td>
<td width="89" height="22"><div align="center"></div></td>
<td width="215" height="22"><div align="left"></div></td>
</tr>
<tr>
<td height="22"><div align="right">
<input name="rdndnc" type="radio" class="sin-borde" value="radiobutton" checked>
Todas</div></td>
<td><input name="rdndnc" type="radio" class="sin-borde" value="radiobutton">
Debito</td>
<td><input name="rdndnc" type="radio" class="sin-borde" value="radiobutton">
Credito</td>
</tr>
<tr>
<td height="22"><div align="right">Desde
<input name="txtnumdcdes" type="text" id="txtnumdcdes" size="20" readonly>
<a href="javascript: ue_catalogo_notas('REPDES');"><img src="../shared/imagebank/tools15/buscar.gif" width="15" height="15" border="0"></a></div></td>
<td><div align="right">Hasta</div></td>
<td><input name="txtnumdchas" type="text" id="txtnumdchas" size="20" readonly>
<a href="javascript: ue_catalogo_notas('REPHAS');"><img src="../shared/imagebank/tools15/buscar.gif" width="15" height="15" border="0"></a></td>
</tr>
</table></td>
</tr>
<tr>
<td height="22" colspan="3" align="center"> </td>
</tr>
<tr>
<td height="33" colspan="3" align="center"> <div align="left">
<table width="511" border="0" align="center" cellpadding="0" cellspacing="0" class="formato-blanco">
<tr>
<td height="22" colspan="5"><strong>Fecha de Registro </strong></td>
</tr>
<tr>
<td width="136"><div align="right">Desde</div></td>
<td width="101"><input name="txtfecregdes" type="text" id="txtfecregdes" onKeyDown="javascript:ue_formato_fecha(this,'/',patron,true,event);" onBlur="javascript: ue_validar_formatofecha(this);" size="15" maxlength="10" datepicker="true"></td>
<td width="42"><div align="right">Hasta</div></td>
<td width="129"><div align="left">
<input name="txtfecreghas" type="text" id="txtfecreghas" onKeyDown="javascript:ue_formato_fecha(this,'/',patron,true,event);" onBlur="javascript: ue_validar_formatofecha(this);" size="15" maxlength="10" datepicker="true">
</div></td>
<td width="101"> </td>
</tr>
</table>
</div></td>
</tr>
<tr>
<td height="22" colspan="3" align="center"><div align="left" class="style14"></div></td>
</tr>
<tr>
<td height="22" colspan="3" align="center"><table width="511" border="0" align="center" cellpadding="0" cellspacing="0" class="formato-blanco">
<tr>
<td height="22" colspan="3"><strong>Estatus</strong></td>
</tr>
<tr>
<td width="183" height="22"><div align="right">
<input name="chkemitida" type="checkbox" class="sin-borde" id="chkemitida" value="checkbox">
Emitida</div></td>
<td width="132" height="22">
<div align="center">
<input name="chkcontab" type="checkbox" class="sin-borde" id="chkcontab" value="checkbox">
Contabilizada</div>
<div align="left"></div></td>
<td width="194" height="22"> <input name="chkanulada" type="checkbox" class="sin-borde" id="chkanulada" value="checkbox">
Anulada </td>
</tr>
</table></td>
</tr>
<tr>
<td height="22" colspan="3" align="center"> </td>
</tr>
</table>
<p align="center">
<input name="total" type="hidden" id="total" value="<?php print $totrow;?>">
</p>
</form>
<p> </p>
<p> </p>
<p> </p>
</body>
<script language="JavaScript">
var patron = new Array(2,2,4)
var patron2 = new Array(1,3,3,3,3)
function ue_catalogo_solicitudes(ls_tipo)
{
ls_catalogo="sigesp_cxp_cat_solicitudpago.php?tipo="+ls_tipo+"";
window.open(ls_catalogo,"_blank","menubar=no,toolbar=no,scrollbars=yes,width=550,height=400,left=50,top=50,location=no,resizable=yes");
}
function ue_catalogo_notas(ls_tipo)
{
ls_catalogo="sigesp_cxp_cat_notas.php?tipo="+ls_tipo+"";
window.open(ls_catalogo,"_blank","menubar=no,toolbar=no,scrollbars=yes,width=600,height=400,left=50,top=50,location=no,resizable=yes");
}
function uf_imprimir()
{
f=document.formulario;
li_imprimir=f.imprimir.value;
emitida=0;
contabilizada=0;
anulada=0;
if(li_imprimir==1)
{
if(f.rdndnc[0].checked)
{
tipndnc="";
}
else
{
if(f.rdndnc[1].checked)
{
tipndnc="D";
}
else
{
tipndnc="C";
}
}
if(f.chkemitida.checked==true)
emitida=1;
if(f.chkcontab.checked==true)
contabilizada=1;
if(f.chkanulada.checked==true)
anulada=1;
numsoldes=f.txtnumsoldes.value;
numsolhas=f.txtnumsolhas.value;
ndncdes=f.txtnumdcdes.value;
ndnchas=f.txtnumdchas.value;
fecregdes=f.txtfecregdes.value;
fecreghas=f.txtfecreghas.value;
tiporeporte=f.cmbbsf.value;
pantalla="reportes/sigesp_cxp_rpp_relacionndnc.php?tipndnc="+tipndnc+"&numsoldes="+numsoldes+"&numsolhas="+numsolhas+
"&ndncdes="+ndncdes+"&ndnchas="+ndnchas+"&fecregdes="+fecregdes+"&fecreghas="+fecreghas+"&emitida="+emitida+
"&contabilizada="+contabilizada+"&anulada="+anulada+"&tiporeporte="+tiporeporte+"";
window.open(pantalla,"catalogo","menubar=no,toolbar=no,scrollbars=yes,width=800,height=600,left=0,top=0,location=no,resizable=yes");
}
else
{alert("No tiene permiso para realizar esta operación");}
}
function ue_cerrar()
{
window.location.href="sigespwindow_blank.php";
}
</script>
<script language="javascript" src="../shared/js/js_intra/datepickercontrol.js"></script>
<script type="text/javascript" language="JavaScript1.2" src="../shared/js/validaciones.js"></script>
</html> | gpl-2.0 |
marciomlopes/cmaga | wp-content/plugins/types/wpcf.php | 8960 | <?php
/*
Plugin Name: Types - Complete Solution for Custom Fields and Types
Plugin URI: http://wordpress.org/extend/plugins/types/
Description: Define custom post types, custom taxonomy and custom fields.
Author: OnTheGoSystems
Author URI: http://www.onthegosystems.com
Version: 1.6.6.1
*/
/**
*
* $HeadURL: http://plugins.svn.wordpress.org/types/tags/1.6.6.1/wpcf.php $
* $LastChangedDate: 2015-04-03 12:05:28 +0000 (Fri, 03 Apr 2015) $
* $LastChangedRevision: 1126995 $
* $LastChangedBy: iworks $
*
*/
// Added check because of activation hook and theme embedded code
if ( !defined( 'WPCF_VERSION' ) ) {
/**
* make sure that WPCF_VERSION in embedded/bootstrap.php is the same!
*/
define( 'WPCF_VERSION', '1.6.6.1' );
}
define( 'WPCF_REPOSITORY', 'http://api.wp-types.com/' );
define( 'WPCF_ABSPATH', dirname( __FILE__ ) );
define( 'WPCF_RELPATH', plugins_url() . '/' . basename( WPCF_ABSPATH ) );
define( 'WPCF_INC_ABSPATH', WPCF_ABSPATH . '/includes' );
define( 'WPCF_INC_RELPATH', WPCF_RELPATH . '/includes' );
define( 'WPCF_RES_ABSPATH', WPCF_ABSPATH . '/resources' );
define( 'WPCF_RES_RELPATH', WPCF_RELPATH . '/resources' );
// Add installer
$installer = dirname( __FILE__ ) . '/plus/installer/loader.php';
if ( file_exists($installer) ) {
include_once $installer;
if ( class_exists('WP_Installer_Setup') ) {
WP_Installer_Setup(
$wp_installer_instance,
array(
'plugins_install_tab' => '1',
'repositories_include' => array('toolset', 'wpml')
)
);
}
}
require_once WPCF_INC_ABSPATH . '/constants.php';
/*
* Since Types 1.2 we load all embedded code without conflicts
*/
require_once WPCF_ABSPATH . '/embedded/types.php';
require_once WPCF_ABSPATH . '/embedded/onthego-resources/loader.php';
onthego_initialize(WPCF_ABSPATH . '/embedded/onthego-resources/',
WPCF_RELPATH . '/embedded/onthego-resources/' );
// Plugin mode only hooks
add_action( 'plugins_loaded', 'wpcf_init' );
// init hook for module manager
add_action( 'init', 'wpcf_wp_init' );
register_deactivation_hook( __FILE__, 'wpcf_deactivation_hook' );
register_activation_hook( __FILE__, 'wpcf_activation_hook' );
/**
* Deactivation hook.
*
* Reset some of data.
*/
function wpcf_deactivation_hook()
{
// Delete messages
delete_option( 'wpcf-messages' );
delete_option( 'WPCF_VERSION' );
/**
* check site kind and if do not exist, delete types_show_on_activate
*/
if ( !get_option('types-site-kind') ) {
delete_option('types_show_on_activate');
}
}
/**
* Activation hook.
*
* Reset some of data.
*/
function wpcf_activation_hook()
{
$version = get_option('WPCF_VERSION');
if ( empty($version) ) {
$version = 0;
add_option('WPCF_VERSION', 0, null, 'no');
}
if ( version_compare($version, WPCF_VERSION) < 0 ) {
update_option('WPCF_VERSION', WPCF_VERSION);
}
if( 0 == version_compare(WPCF_VERSION, '1.6.5')) {
add_option('types_show_on_activate', 'show', null, 'no');
if ( get_option('types-site-kind') ) {
update_option('types_show_on_activate', 'hide');
}
}
}
/**
* Main init hook.
*/
function wpcf_init()
{
if ( !defined( 'EDITOR_ADDON_RELPATH' ) ) {
define( 'EDITOR_ADDON_RELPATH', WPCF_RELPATH . '/embedded/common/visual-editor' );
}
if ( is_admin() ) {
require_once WPCF_ABSPATH . '/admin.php';
}
/**
* remove unused option
*/
$version_from_db = get_option('wpcf-version', 0);
if ( version_compare(WPCF_VERSION, $version_from_db) > 0 ) {
delete_option('wpcf-survey-2014-09');
update_option('wpcf-version', WPCF_VERSION);
}
}
//Render Installer packages
function installer_content()
{
echo '<div class="wrap">';
$config['repository'] = array(); // required
WP_Installer_Show_Products($config);
echo "</div>";
}
/**
* WP Main init hook.
*/
function wpcf_wp_init()
{
if ( is_admin() ) {
require_once WPCF_ABSPATH . '/admin.php';
add_action('wpcf_menu_plus', 'setup_installer');
//Add submenu Installer to Types
function setup_installer()
{
wpcf_admin_add_submenu_page(
array(
'page_title' => __('Installer', 'wpcf'),
'menu_title' => __('Installer', 'wpcf'),
'menu_slug' => 'installer',
'function' => 'installer_content'
)
);
}
}
}
/**
* Checks if name is reserved.
*
* @param type $name
* @return type
*/
function wpcf_is_reserved_name($name, $context, $check_pages = true)
{
$name = strval( $name );
/*
*
* If name is empty string skip page cause there might be some pages without name
*/
if ( $check_pages && !empty( $name ) ) {
global $wpdb;
$page = $wpdb->get_var(
$wpdb->prepare(
"SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type='page'",
sanitize_title( $name )
)
);
if ( !empty( $page ) ) {
return new WP_Error( 'wpcf_reserved_name', __( 'You cannot use this slug because there is already a page by that name. Please choose a different slug.',
'wpcf' ) );
}
}
// Add custom types
$custom_types = (array) get_option( 'wpcf-custom-types', array() );
$post_types = get_post_types();
if ( !empty( $custom_types ) ) {
$custom_types = array_keys( $custom_types );
$post_types = array_merge( array_combine( $custom_types, $custom_types ),
$post_types );
}
// Unset to avoid checking itself
if ( $context == 'post_type' && isset( $post_types[$name] ) ) {
unset( $post_types[$name] );
}
// Add taxonomies
$custom_taxonomies = (array) get_option( 'wpcf-custom-taxonomies', array() );
$taxonomies = get_taxonomies();
if ( !empty( $custom_taxonomies ) ) {
$custom_taxonomies = array_keys( $custom_taxonomies );
$taxonomies = array_merge( array_combine( $custom_taxonomies,
$custom_taxonomies ), $taxonomies );
}
// Unset to avoid checking itself
if ( $context == 'taxonomy' && isset( $taxonomies[$name] ) ) {
unset( $taxonomies[$name] );
}
$reserved_names = wpcf_reserved_names();
$reserved = array_merge( array_combine( $reserved_names, $reserved_names ),
array_merge( $post_types, $taxonomies ) );
return in_array( $name, $reserved ) ? new WP_Error( 'wpcf_reserved_name', __( 'You cannot use this slug because it is a reserved word, used by WordPress. Please choose a different slug.',
'wpcf' ) ) : false;
}
/**
* Reserved names.
*
* @return type
*/
function wpcf_reserved_names()
{
$reserved = array(
'attachment',
'attachment_id',
'author',
'author_name',
'calendar',
'cat',
'category',
'category__and',
'category__in',
'category__not_in',
'category_name',
'comments_per_page',
'comments_popup',
'cpage',
'day',
'debug',
'error',
'exact',
'feed',
'format',
'hour',
'link_category',
'm',
'minute',
'monthnum',
'more',
'name',
'nav_menu',
'nopaging',
'offset',
'order',
'orderby',
'p',
'page',
'page_id',
'paged',
'pagename',
'pb',
'perm',
'post',
'post__in',
'post__not_in',
'post_format',
'post_mime_type',
'post_status',
'post_tag',
'post_type',
'posts',
'posts_per_archive_page',
'posts_per_page',
'preview',
'robots',
's',
'search',
'second',
'sentence',
'showposts',
'static',
'subpost',
'subpost_id',
'tag',
'tag__and',
'tag__in',
'tag__not_in',
'tag_id',
'tag_slug__and',
'tag_slug__in',
'taxonomy',
'tb',
'term',
'type',
'w',
'withcomments',
'withoutcomments',
'year',
'lang',
// 'comments',
// 'blog',
// 'files'
);
return apply_filters( 'wpcf_reserved_names', $reserved );
}
add_action( 'icl_pro_translation_saved', 'wpcf_fix_translated_post_relationships' );
function wpcf_fix_translated_post_relationships($post_id)
{
require_once WPCF_EMBEDDED_ABSPATH . '/includes/post-relationship.php';
wpcf_post_relationship_set_translated_parent( $post_id );
wpcf_post_relationship_set_translated_children( $post_id );
}
| gpl-2.0 |
YJSGframework/yjsg | includes/yjsgcore/classes/extend/38/component/view.php | 4038 | <?php
/**
* @package Joomla.Platform
* @subpackage Application
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Base class for a Joomla View
*
* Class holding methods for displaying presentation data.
*
* @package Joomla.Platform
* @subpackage Application
* @since 11.1
*/
class JViewLegacy extends YjsgJViewLegacyDefault
{
/**
* Load a template file -- first look in the templates folder for an override
*
* @param string $tpl The name of the template source file; automatically searches the template paths and compiles as needed.
*
* @return string The output of the the template script.
*
* @since 12.2
* @throws Exception
*/
public function loadTemplate($tpl = null)
{
// Clear prior output
$this->_output = null;
$template = JFactory::getApplication()->getTemplate();
// Yjsg instance
$yjsg = Yjsg::getInstance();
$layout = $this->getLayout();
$layoutTemplate = $this->getLayoutTemplate();
// Create the template file name based on the layout
$file = isset($tpl) ? $layout . '_' . $tpl : $layout;
// Clean the file name
$file = preg_replace('/[^A-Z0-9_\.-]/i', '', $file);
$tpl = isset($tpl) ? preg_replace('/[^A-Z0-9_\.-]/i', '', $tpl) : $tpl;
// Load the language file for the template
$lang = JFactory::getLanguage();
$lang->load('tpl_' . $template, JPATH_BASE, null, false, false)
|| $lang->load('tpl_' . $template, JPATH_THEMES . "/$template", null, false, false)
|| $lang->load('tpl_' . $template, JPATH_BASE, $lang->getDefault(), false, false)
|| $lang->load('tpl_' . $template, JPATH_THEMES . "/$template", $lang->getDefault(), false, false);
// Change the template folder if alternative layout is in different template
if (isset($layoutTemplate) && $layoutTemplate != '_' && $layoutTemplate != $template)
{
$this->_path['template'] = str_replace($template, $layoutTemplate, $this->_path['template']);
}
//yjsg start
$option = JFactory::getApplication()->input->getCmd('option');
$folderName = $this->getName();
if($yjsg->preplugin() && JFactory::getApplication()->isSite()){
$yjsg_path = array(YJSGTEMPLATEPATH . 'html' . YJDS . $option . YJDS . $folderName, YJSGPATH . 'legacy' . YJDS . 'html' . YJDS . $option . YJDS . $folderName);
}else{
$yjsg_path = array(YJSGTEMPLATEPATH . 'html' . YJDS . $option . YJDS . $folderName, YJSGPATH . 'includes' . YJDS . 'html' . YJDS . $option . YJDS . $folderName);
}
foreach($this->_path['template'] as $jpath){
if(!in_array($jpath,$yjsg_path)){
$yjsg_path[] = $jpath;
}
}
$this->_path['template'] = $yjsg_path;
//yjsg end
// Load the template script
jimport('joomla.filesystem.path');
$filetofind = $this->_createFileName('template', array('name' => $file));
$this->_template = JPath::find($this->_path['template'], $filetofind);
// If alternate layout can't be found, fall back to default layout
if ($this->_template == false)
{
$filetofind = $this->_createFileName('', array('name' => 'default' . (isset($tpl) ? '_' . $tpl : $tpl)));
$this->_template = JPath::find($this->_path['template'], $filetofind);
}
if ($this->_template != false)
{
// Unset so as not to introduce into template scope
unset($tpl);
unset($file);
// Never allow a 'this' property
if (isset($this->this))
{
unset($this->this);
}
// Start capturing output into a buffer
ob_start();
// Include the requested template filename in the local scope
// (this will execute the view logic).
include $this->_template;
// Done with the requested template; get the buffer and
// clear it.
$this->_output = ob_get_contents();
ob_end_clean();
return $this->_output;
}
else
{
throw new Exception(JText::sprintf('JLIB_APPLICATION_ERROR_LAYOUTFILE_NOT_FOUND', $file), 500);
}
}
}
| gpl-2.0 |
donniexyz/calligra | krita/image/commands_new/kis_update_command.cpp | 1661 | /*
* Copyright (c) 2011 Dmitry Kazakov <dimula73@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 "kis_update_command.h"
#include "kis_image_interfaces.h"
#include "kis_node.h"
KisUpdateCommand::KisUpdateCommand(KisNodeSP node, QRect dirtyRect,
KisUpdatesFacade *updatesFacade,
bool needsFullRefresh)
: KUndo2Command(kundo2_noi18n("UPDATE_COMMAND")),
m_node(node),
m_dirtyRect(dirtyRect),
m_updatesFacade(updatesFacade),
m_needsFullRefresh(needsFullRefresh)
{
}
KisUpdateCommand::~KisUpdateCommand()
{
}
void KisUpdateCommand::undo()
{
KUndo2Command::undo();
update();
}
void KisUpdateCommand::redo()
{
KUndo2Command::redo();
update();
}
void KisUpdateCommand::update()
{
if(m_needsFullRefresh) {
m_updatesFacade->refreshGraphAsync(m_node, m_dirtyRect);
}
else {
m_node->setDirty(m_dirtyRect);
}
}
| gpl-2.0 |
rofl0r/exult | audio/midi_drivers/mt32emu/mt32_file.cpp | 2888 | /* Copyright (c) 2003-2004 Various contributors
*
* 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 "pent_include.h"
#include <stdio.h>
#include "mt32emu.h"
namespace Pentagram {
bool ANSIFile::open(const char *filename, OpenMode mode) {
const char *fmode;
if (mode == OpenMode_read) {
fmode = "rb";
} else {
fmode = "wb";
}
fp = fopen(filename, fmode);
return (fp != NULL);
}
void ANSIFile::close() {
fclose(fp);
}
size_t ANSIFile::read(void *in, size_t size) {
return fread(in, 1, size, fp);
}
bool ANSIFile::readLine(char *in, size_t size) {
return fgets(in, (int)size, fp) != NULL;
}
bool ANSIFile::readBit8u(Bit8u *in) {
int c = fgetc(fp);
if (c == EOF)
return false;
*in = (Bit8u)c;
return true;
}
bool File::readBit16u(Bit16u *in) {
Bit8u b[2];
if (read(&b[0], 2) != 2)
return false;
*in = ((b[0] << 8) | b[1]);
return true;
}
bool File::readBit32u(Bit32u *in) {
Bit8u b[4];
if (read(&b[0], 4) != 4)
return false;
*in = ((b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]);
return true;
}
size_t ANSIFile::write(const void *out, size_t size) {
return fwrite(out, 1, size, fp);
}
bool ANSIFile::writeBit8u(Bit8u out) {
return fputc(out, fp) != EOF;
}
bool File::writeBit16u(Bit16u out) {
if (!writeBit8u((Bit8u)((out & 0xFF00) >> 8))) {
return false;
}
if (!writeBit8u((Bit8u)(out & 0x00FF))) {
return false;
}
return true;
}
bool File::writeBit32u(Bit32u out) {
if (!writeBit8u((Bit8u)((out & 0xFF000000) >> 24))) {
return false;
}
if (!writeBit8u((Bit8u)((out & 0x00FF0000) >> 16))) {
return false;
}
if (!writeBit8u((Bit8u)((out & 0x0000FF00) >> 8))) {
return false;
}
if (!writeBit8u((Bit8u)(out & 0x000000FF))) {
return false;
}
return true;
}
bool ANSIFile::isEOF() {
return feof(fp) != 0;
}
}
| gpl-2.0 |
universsky/openjdk | jdk/test/javax/management/notification/BroadcasterSupportDeadlockTest.java | 6412 | /*
* Copyright (c) 2004, 2015, 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.
*/
/*
* @test
* @bug 5093922 2120055
* @summary Test that NotificationBroadcasterSupport can be subclassed
* and used with synchronized(this) without causing deadlock
* @author Eamonn McManus
* @modules java.management
* @run clean BroadcasterSupportDeadlockTest
* @run build BroadcasterSupportDeadlockTest
* @run main BroadcasterSupportDeadlockTest
*/
import java.lang.management.*;
import java.util.concurrent.*;
import javax.management.*;
public class BroadcasterSupportDeadlockTest {
public static void main(String[] args) throws Exception {
try {
Class.forName(ManagementFactory.class.getName());
} catch (Throwable t) {
System.out.println("TEST CANNOT RUN: needs JDK 5 at least");
return;
}
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
final BroadcasterMBean mbean = new Broadcaster();
final ObjectName name = new ObjectName("test:type=Broadcaster");
mbs.registerMBean(mbean, name);
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
threads.setThreadContentionMonitoringEnabled(true);
final Semaphore semaphore = new Semaphore(0);
// Thread 1 - block the Broadcaster
Thread t1 = new Thread() {
public void run() {
try {
mbs.invoke(name, "block",
new Object[] {semaphore},
new String[] {Semaphore.class.getName()});
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
System.out.println("TEST INCORRECT: block returned");
System.exit(1);
}
}
};
t1.setDaemon(true);
t1.start();
/* Wait for Thread 1 to be doing Object.wait(). It's very
difficult to synchronize properly here so we wait for the
semaphore, then wait a little longer for the mbs.invoke to
run, then just in case that isn't enough, we wait for the
thread to be in WAITING state. This isn't foolproof,
because the machine could be very slow and the
Thread.getState() could find the thread in WAITING state
due to some operation it does on its way to the one we're
interested in. */
semaphore.acquire();
Thread.sleep(100);
while (t1.getState() != Thread.State.WAITING)
Thread.sleep(1);
// Thread 2 - try to add a listener
final NotificationListener listener = new NotificationListener() {
public void handleNotification(Notification n, Object h) {}
};
Thread t2 = new Thread() {
public void run() {
try {
mbs.addNotificationListener(name, listener, null, null);
} catch (Exception e) {
System.out.println("TEST INCORRECT: addNL failed:");
e.printStackTrace(System.out);
}
}
};
t2.setDaemon(true);
t2.start();
/* Wait for Thread 2 to be blocked on the monitor or to
succeed. */
Thread.sleep(100);
for (int i = 0; i < 1000/*ms*/; i++) {
t2.join(1/*ms*/);
switch (t2.getState()) {
case TERMINATED:
System.out.println("TEST PASSED");
return;
case BLOCKED:
java.util.Map<Thread,StackTraceElement[]> traces =
Thread.getAllStackTraces();
showStackTrace("Thread 1", traces.get(t1));
showStackTrace("Thread 2", traces.get(t2));
System.out.println("TEST FAILED: deadlock");
System.exit(1);
break;
default:
break;
}
}
System.out.println("TEST FAILED BUT DID NOT NOTICE DEADLOCK");
Thread.sleep(10000);
System.exit(1);
}
private static void showStackTrace(String title,
StackTraceElement[] stack) {
System.out.println("---" + title + "---");
if (stack == null)
System.out.println("<no stack trace???>");
else {
for (StackTraceElement elmt : stack)
System.out.println(" " + elmt);
}
System.out.println();
}
public static interface BroadcasterMBean {
public void block(Semaphore semaphore);
}
public static class Broadcaster
extends NotificationBroadcasterSupport
implements BroadcasterMBean {
public synchronized void block(Semaphore semaphore) {
Object lock = new Object();
synchronized (lock) {
try {
// Let the caller know that it can now wait for us to
// hit the WAITING state
semaphore.release();
lock.wait(); // block forever
} catch (InterruptedException e) {
System.out.println("TEST INCORRECT: lock interrupted:");
e.printStackTrace(System.out);
System.exit(1);
}
}
}
}
}
| gpl-2.0 |
mixerp6/mixerp | src/FrontEnd/MixERP.Net.FrontEnd/Modules/Inventory/Setup/Shippers.ascx.cs | 3069 | /********************************************************************************
Copyright (C) MixERP Inc. (http://mixof.org).
This file is part of MixERP.
MixERP is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2 of the License.
MixERP 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 MixERP. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************************/
using MixERP.Net.ApplicationState.Cache;
using MixERP.Net.Common.Helpers;
using MixERP.Net.FrontEnd.Base;
using MixERP.Net.FrontEnd.Controls;
using MixERP.Net.i18n.Resources;
using System;
using System.Collections.Generic;
namespace MixERP.Net.Core.Modules.Inventory.Setup
{
public partial class Shippers : MixERPUserControl
{
public override void OnControlLoad(object sender, EventArgs e)
{
using (Scrud scrud = new Scrud())
{
scrud.KeyColumn = "shipper_id";
scrud.TableSchema = "core";
scrud.Table = "shippers";
scrud.ViewSchema = "core";
scrud.View = "shipper_scrud_view";
//The following fields will be automatically generated on the database server.
scrud.Exclude = "shipper_code, shipper_name";
scrud.DisplayFields = GetDisplayFields();
scrud.DisplayViews = GetDisplayViews();
scrud.SelectedValues = GetSelectedValues();
scrud.Text = Titles.Shippers;
this.ScrudPlaceholder.Controls.Add(scrud);
}
}
private static string GetDisplayFields()
{
List<string> displayFields = new List<string>();
ScrudHelper.AddDisplayField(displayFields, "core.accounts.account_id",
DbConfig.GetDbParameter(AppUsers.GetCurrentUserDB(), "AccountDisplayField"));
return string.Join(",", displayFields);
}
private static string GetDisplayViews()
{
List<string> displayViews = new List<string>();
ScrudHelper.AddDisplayView(displayViews, "core.accounts.account_id", "core.account_selector_view");
return string.Join(",", displayViews);
}
private static string GetSelectedValues()
{
List<string> selectedValues = new List<string>();
//Todo:
//The default selected value of shipping payable account
//should be done via GL Mapping.
ScrudHelper.AddSelectedValue(selectedValues, "core.accounts.account_id", "'20110 (Shipping Charge Payable)'");
return string.Join(",", selectedValues);
}
}
} | gpl-2.0 |
vaseidong/hudbt | invite.php | 7095 | <?php
require "include/bittorrent.php";
dbconn();
require_once(get_langfile_path());
loggedinorreturn();
parked();
$id = 0 + $_REQUEST["id"];
$type = unesc($_REQUEST["type"]);
if (!$id) {
$id = $CURUSER['id'];
}
registration_check('invitesystem',true,false);
if (($CURUSER['id'] != $id && get_user_class() < $viewinvite_class) || !is_valid_id($id)) {
header("HTTP/1.1 403 Forbidden");
stderr($lang_invite['std_sorry'],$lang_invite['std_permission_denied']);
}
if (get_user_class() < $sendinvite_class) {
header("HTTP/1.1 403 Forbidden");
stderr($lang_invite['std_sorry'],$lang_invite['std_only'].get_user_class_name($sendinvite_class,false,true,true).$lang_invite['std_or_above_can_invite'],false);
}
stdhead($lang_invite['head_invites']);
print("<h1 align=center><a href=\"invite.php?id=".$id."\">".get_user_row($id)['username'].$lang_invite['text_invite_system']."</a></h1>");
$sent = htmlspecialchars($_GET['sent']);
if ($sent == 1){
$msg = $lang_invite['text_invite_code_sent'];
print("<p align=center><font color=red>".$msg."</font></p>");
}
$res = sql_query("SELECT invites FROM users WHERE id = ?", [$id]);
$inv = _mysql_fetch_assoc($res);
//for one or more. "invite"/"invites"
if ($inv["invites"] != 1){
$_s = $lang_invite['text_s'];
} else {
$_s = "";
}
if ($type == 'recover'){
if (($CURUSER['id'] != $id && get_user_class() < $viewinvite_class) || !is_valid_id($id))
stderr($lang_invite['std_sorry'],$lang_invite['std_permission_denied']);
$recinv =$_POST["invitee"];
$rechash=$_POST["hash"];
sql_query("DELETE FROM invites WHERE invitee = '".$recinv."'and hash='".$rechash."'");
if(_mysql_affected_rows()) {
update_user($id, 'invites = invites+1');
stdmsg($lang_invite['std_recover'], $lang_invite['std_recoversentto'].$recinv.$lang_invite['std_s_invite']);
}
}
if ($type == 'new'){
if ($CURUSER['invites'] <= 0) {
stdmsg($lang_invite['std_sorry'],$lang_invite['std_no_invites_left'].
"<a class=altlink href=invite.php?id=$CURUSER[id]>".$lang_invite['here_to_go_back'],false);
print("</td></tr></table>");
stdfoot();
die;
}
$invitation_body = $lang_invite['text_invitation_body'].$CURUSER['username'];
//$invitation_body_insite = str_replace("<br />","\n",$invitation_body);
echo "<h2 class=\"center\">".$lang_invite['text_invite_someone']."$SITENAME ($inv[invites]".$lang_invite['text_invitation'].$_s.$lang_invite['text_left'] .")</h2>";
print("<form method=post action=takeinvite.php?id=".htmlspecialchars($id)." id=\"sendInviteRequest\">".
"<table border=1 width=737 cellpadding=5>".
"<tr><td class=\"nowrap\" valign=\"top\" align=\"right\">".$lang_invite['text_email_address']."</td><td align=left><input type=\"email\" size=40 name=\"email\"><br />".$lang_invite['text_email_address_note'].($restrictemaildomain == 'yes' ? "<br />".$lang_invite['text_email_restriction_note'].allowedemails() : "")."</td></tr>".
"<tr><td class=\"nowrap\" valign=\"top\" align=\"right\">".$lang_invite['text_message']."</td><td><textarea name=body rows=8 cols=120>" .$invitation_body.
"</textarea></td></tr>".
"<tr><td class=\"center\" colspan=2><input type=\"submit\" value='".$lang_invite['submit_invite']."' onclick=\"document.getElementById('sendInviteRequest').submit(); this.disabled = true\"></td></tr>".
"</form></table></td></tr></table>");
} else {
$rel = sql_query("SELECT COUNT(*) FROM users WHERE invited_by = ?", [$id]);
$arro = _mysql_fetch_row($rel);
$number = $arro[0];
$ret = sql_query("SELECT id, username, email, uploaded, downloaded, status, warned, enabled, donor, email FROM users WHERE invited_by = ?", [$id]);
$num = _mysql_num_rows($ret);
print("<h2 align=center>".$lang_invite['text_invite_status']." ($number)</h2>");
echo "<form method=post action=takeconfirm.php?id=".htmlspecialchars($id).">";
echo "<table class=\"invites\" border=1 width=737 cellpadding=5>";
if(!$num){
print("<tbody><tr><td colspan=7 align=center>".$lang_invite['text_no_invites']."</tr>");
} else {
print("<thead><tr><th><b>".$lang_invite['text_username']."</b></th><th><b>".$lang_invite['text_email']."</b></th><th><b>".$lang_invite['text_uploaded']."</b></th><th><b>".$lang_invite['text_downloaded']."</b></th><th><b>".$lang_invite['text_ratio']."</b></th><th><b>".$lang_invite['text_status']."</b></th>");
print("</tr></thead><tbody>");
for ($i = 0; $i < $num; ++$i)
{
$arr = _mysql_fetch_assoc($ret);
$user = "<td class=rowfollow>" . get_username($arr['id']) . "</td>";
if ($arr["downloaded"] > 0) {
$ratio = number_format($arr["uploaded"] / $arr["downloaded"], 3);
$ratio = "<font color=" . get_ratio_color($ratio) . ">$ratio</font>";
} else {
if ($arr["uploaded"] > 0) {
$ratio = "Inf.";
}
else {
$ratio = "---";
}
}
if ($arr["status"] == 'confirmed')
$status = "<a href=userdetails.php?id=$arr[id]><span class=\"confirmed\">".$lang_invite['text_confirmed']."</font></a>";
else
$status = "<span class=\"pending\">".$lang_invite['text_pending']."</span>";
print("<tr>$user<td>$arr[email]</td><td class=rowfollow>" . mksize($arr['uploaded']) . "</td><td class=rowfollow>" . mksize($arr['downloaded']) . "</td><td class=rowfollow>$ratio</td><td class=rowfollow>$status</td></tr>");
}
}
if ($CURUSER['id'] == $id) {
print("<tr><td colspan=7 align=center>");
if ($CURUSER['invites'] <= 0) {
echo '<span class="disabled">' . $lang_invite['text_unable_to_invite'] . '</span>';
}
else {
echo '<a class="index" href="' . htmlspecialchars('invite.php?id=' . $id . '&type=new') . '">' . $lang_invite['sumbit_invite_someone'] . '</a>';
}
echo '</td></tr>';
}
print("</tbody></table>");
print("</form>");
$number1 = get_row_count('invites', "WHERE inviter = ?", [$id]);
echo "<h2 class=\"center\">".$lang_invite['text_sent_invites_status']." ($number1)</h2>";
print("<table border=1 width=737 cellpadding=5>");
if(!$number1){
print("<tr align=center><td colspan=6>".$lang_invite['text_no_invitation_sent']."</tr>");
} else {
$res = sql_query("SELECT id, hash, invitee, time_invited FROM invites WHERE inviter = ?", [$id]);
print("<thead><tr><th>".$lang_invite['text_email']."</th><th>".$lang_invite['text_send_date']."</th>");
if ($CURUSER['id'] == $id) {
echo "<th>".$lang_invite['text_action']."</th>";
}
echo "</tr></thead><tbody>";
foreach ($res as $arr1) {
print("<tr><td>$arr1[invitee]</td><td>$arr1[time_invited]</td>");
if ($CURUSER['id'] == $id) {
print("<td><form class='a' method='post' action='invite.php'><input type='hidden' name='type' value='recover'><input type='hidden' name='id' value=$id><input type='hidden' name='invitee' value=".$arr1['invitee']."><input type='hidden' name='hash' value=".$arr1['hash']."><input type='submit' value=\"".$lang_invite['text_recover']."\"></form><form class='a' method='post' action='takeinvite.php?action=resend-mail&id=" . $arr1['id'] . "'><input type='submit' value=\"".$lang_invite['text_resend_mail']."\"></form></td>");
}
print("</tr>");
}
}
print("</tbody></table>");
}
stdfoot();
die;
| gpl-2.0 |
CTSATLAS/wordpress | wp-content/plugins/constant-contact-api/vendor/constantcontact/constantcontact/src/Ctct/Services/ContactService.php | 5172 | <?php
namespace Ctct\Services;
use Ctct\Util\Config;
use Ctct\Components\Contacts\Contact;
use Ctct\Components\ResultSet;
/**
* Performs all actions pertaining to Constant Contact Contacts
*
* @package Services
* @author ContactContact
*/
class ContactService extends BaseService
{
/**
* Get a ResultSet of contacts
* @param string $accessToken - Constant Contact OAuth2 access token
* @param array $params - array of query parameters to be appended to the url
* @return ResultSet
*/
public function getContacts($accessToken, array $params = array())
{
$baseUrl = Config::get('endpoints.base_url') . Config::get('endpoints.contacts');
$url = $this->buildUrl($baseUrl, $params);
$response = parent::getRestClient()->get($url, parent::getHeaders($accessToken));
$body = json_decode($response->body, true);
$contacts = array();
foreach ($body['results'] as $contact) {
$contacts[] = Contact::create($contact);
}
return new ResultSet($contacts, $body['meta']);
}
/**
* Get contact details for a specific contact
* @param string $accessToken - Constant Contact OAuth2 access token
* @param int $contactId - Unique contact id
* @return Contact
*/
public function getContact($accessToken, $contactId)
{
$baseUrl = Config::get('endpoints.base_url') . sprintf(Config::get('endpoints.contact'), $contactId);
$url = $this->buildUrl($baseUrl);
$response = parent::getRestClient()->get($url, parent::getHeaders($accessToken));
return Contact::create(json_decode($response->body, true));
}
/**
* Add a new contact to the Constant Contact account
* @param string $accessToken - Constant Contact OAuth2 access token
* @param Contact $contact - Contact to add
* @param array $params - query params to be appended to the request
* @return Contact
*/
public function addContact($accessToken, Contact $contact, array $params = array())
{
$baseUrl = Config::get('endpoints.base_url') . Config::get('endpoints.contacts');
$url = $this->buildUrl($baseUrl, $params);
$response = parent::getRestClient()->post($url, parent::getHeaders($accessToken), $contact->toJson());
$response_body = empty( $response->body ) ? false : json_decode($response->body, true);
return $response_body ? Contact::create($response_body) : false;
}
/**
* Delete contact details for a specific contact
* @param string $accessToken - Constant Contact OAuth2 access token
* @param int $contactId - Unique contact id
* @return boolean
*/
public function deleteContact($accessToken, $contactId)
{
$baseUrl = Config::get('endpoints.base_url') . sprintf(Config::get('endpoints.contact'), $contactId);
$url = $this->buildUrl($baseUrl);
$response = parent::getRestClient()->delete($url, parent::getHeaders($accessToken));
return ($response->info['http_code'] == 204) ? true : false;
}
/**
* Delete a contact from all contact lists
* @param string $accessToken - Constant Contact OAuth2 access token
* @param int $contactId - Contact id to be removed from lists
* @return boolean
*/
public function deleteContactFromLists($accessToken, $contactId)
{
$baseUrl = Config::get('endpoints.base_url') . sprintf(Config::get('endpoints.contact_lists'), $contactId);
$url = $this->buildUrl($baseUrl);
$response = parent::getRestClient()->delete($url, parent::getHeaders($accessToken));
return ($response->info['http_code'] == 204) ? true : false;
}
/**
* Delete a contact from a specific contact list
* @param string $accessToken - Constant Contact OAuth2 access token
* @param int $contactId - Contact id to be removed
* @param int $listId - ContactList to remove the contact from
* @return boolean
*/
public function deleteContactFromList($accessToken, $contactId, $listId)
{
$baseUrl = Config::get('endpoints.base_url') .
sprintf(Config::get('endpoints.contact_list'), $contactId, $listId);
$url = $this->buildUrl($baseUrl);
$response = parent::getRestClient()->delete($url, parent::getHeaders($accessToken));
return ($response->info['http_code'] == 204) ? true : false;
}
/**
* Update contact details for a specific contact
* @param string $accessToken - Constant Contact OAuth2 access token
* @param Contact $contact - Contact to be updated
* @param array $params - query params to be appended to the request
* @return Contact
*/
public function updateContact($accessToken, Contact $contact, array $params = array())
{
$baseUrl = Config::get('endpoints.base_url') . sprintf(Config::get('endpoints.contact'), $contact->id);
$url = $this->buildUrl($baseUrl, $params);
$response = parent::getRestClient()->put($url, parent::getHeaders($accessToken), $contact->toJson());
return Contact::create(json_decode($response->body, true));
}
}
| gpl-2.0 |
XOOPS/XoopsCore25 | htdocs/class/xoopseditor/sampleform.inc.php | 2655 | <?php
/**
* XOOPS Editor usage guide
*
* You may not change or alter any portion of this comment or credits
* of supporting developers from this source code or any supporting source code
* which is considered copyrighted (c) material of the original comment or credit authors.
* 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.
*
* @copyright (c) 2000-2016 XOOPS Project (www.xoops.org)
* @license GNU GPL 2 (https://www.gnu.org/licenses/gpl-2.0.html)
* @package class
* @subpackage editor
* @since 2.3.0
* @author Taiwen Jiang <phppp@users.sourceforge.net>
*/
defined('XOOPS_ROOT_PATH') || exit('Restricted access');
/**
* Edit form with selected editor
*/
$sample_form = new XoopsThemeForm('', 'sample_form', 'action.php');
$sample_form->setExtra('enctype="multipart/form-data"');
// Not required but for user-friendly concern
$editor = !empty($_REQUEST['editor']) ? $_REQUEST['editor'] : '';
if (!empty($editor)) {
setcookie('editor', $editor); // save to cookie
} else {
// Or use user pre-selected editor through profile
if (is_object($xoopsUser)) {
$editor = @ $xoopsUser->getVar('editor'); // Need set through user profile
}
// Add the editor selection box
// If dohtml is disabled, set $noHtml = true
$sample_form->addElement(new XoopsFormSelectEditor($sample_form, 'editor', $editor, $noHtml = false));
// options for the editor
// required configs
$options['editor'] = $editor;
$options['name'] = 'required_element';
$options['value'] = empty($_REQUEST['message']) ? '' : $_REQUEST['message'];
// optional configs
$options['rows'] = 25; // default value = 5
$options['cols'] = 60; // default value = 50
$options['width'] = '100%'; // default value = 100%
$options['height'] = '400px'; // default value = 400px
// "textarea": if the selected editor with name of $editor can not be created, the editor "textarea" will be used
// if no $onFailure is set, then the first available editor will be used
// If dohtml is disabled, set $noHtml to true
$sample_form->addElement(new XoopsFormEditor(_MD_MESSAGEC, $options['name'], $options, $nohtml = false, $onfailure = 'textarea'), true);
$sample_form->addElement(new XoopsFormText('SOME REQUIRED ELEMENTS', 'required_element2', 50, 255, $required_element2), true);
$sample_form->addElement(new XoopsFormButton('', 'save', _SUBMIT, 'submit'));
$sample_form->display();
}
| gpl-2.0 |
aesptux/aesptux.com-blog | output/theme/js/libs/instagram.js | 3070 | /*
UI functions dedicated to the Instagram modal panel
*/
var instagram_api_user = 'https://api.instagram.com/v1/users/';
var instagram_api_media = '/media/recent';
var instagram_api_token = '/?access_token=';
var url = null;
var spinner = (new Spinner(spin_opts)).spin();
var template = null;
var instagram_data = {};
$('a[id^="Instagram-link"]').click(function (e)
{
var url = prepare_link(e, this);
adjustSelection("Instagram-link");
remove_modal();
showInstagram(url, this);
});
function showInstagram(e, t) {
url = t.href;
var instagram_profile = $("#instagram-profile");
if (instagram_profile.length > 0) {
instagram_profile.modal('show');
}
else {
$("#Instagram-link").append(spinner.el);
$.get('/theme/templates/instagram-view.html', function(data) {
// Request succeeded, data contains HTML template, we can load data
template = Handlebars.compile(data);
var user_url = instagram_api_user+instagram_username+instagram_api_token+instagram_accesskey;
try {
$.ajax({
url: user_url,
dataType: "jsonp",
jsonpCallback: "readInstagramData",
error: function(s, statusCode, errorThrown) {
window.location.href = url;
spinner.stop();
}
});
}
catch (err) {
window.location.href = url;
spinner.stop();
}
})
.error(function() {
window.location.href = url;
spinner.stop();
});
}
}
function readInstagramData(result) {
try {
var user = result.data;
user.media = numberWithCommas( user.counts.media );
user.followed_by = numberWithCommas( user.counts.followed_by );
user.follows = numberWithCommas( user.counts.follows );
user.url = url;
instagram_data['user'] = user
var posts_url = instagram_api_user+instagram_username+instagram_api_media+instagram_api_token+instagram_accesskey;
$.ajax({
url: posts_url,
dataType: "jsonp",
jsonpCallback: "readPictures",
error: function(s, statusCode, errorThrown) {
window.location.href = url;
spinner.stop();
}
});
}
catch (err) {
window.location.href = url;
spinner.stop();
}
}
function readPictures(result) {
try {
var posts = result.data;
for(var index = 0; index < posts.length; index++) {
var post = posts[index];
post.formated_date = moment.unix( parseInt( post.created_time ) ).fromNow();
}
instagram_data['media'] = posts
var html = template(instagram_data);
$('body').append(html);
$("#instagram-profile").modal();
spinner.stop();
}
catch (err) {
window.location.href = url;
spinner.stop();
}
}
| gpl-2.0 |
valib/UniversalMediaServer | src/main/java/net/pms/formats/ISO.java | 1114 | /*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.formats;
public class ISO extends MPG {
/**
* {@inheritDoc}
*/
@Override
public Identifier getIdentifier() {
return Identifier.ISO;
}
public ISO() {
type = ISO;
}
/**
* {@inheritDoc}
*/
@Override
public String[] getSupportedExtensions() {
return new String[] {
"img",
"iso"
};
}
}
| gpl-2.0 |
BaerMitUmlaut/CBA_A3 | addons/jam/magwells_8x50mmR_Mannlicher.hpp | 72 | class CBA_8x50mmR_Mannlicher_M1895 {}; // Mannlicher M1895
| gpl-2.0 |
infoalex/huayra | spi/reportes/sigesp_spi_rpp_listado_apertura.php | 35937 | <?php
session_start();
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
if(!array_key_exists("la_logusr",$_SESSION))
{
print "<script language=JavaScript>";
print "close();";
print "</script>";
}
//--------------------------------------------------------------------------------------------------------------------------------
function uf_print_encabezado_pagina($as_titulo,&$io_pdf)
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_encabezadopagina
// Acess: private
// Arguments: as_titulo // Título del Reporte
// as_periodo_comp // Descripción del periodo del comprobante
// as_fecha_comp // Descripción del período de la fecha del comprobante
// io_pdf // Instancia de objeto pdf
// Description: función que imprime los encabezados por página
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 21/04/2006
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_encabezado=$io_pdf->openObject();
$io_pdf->saveState();
$io_pdf->line(10,40,578,40);
$io_pdf->addJpegFromFile('../../shared/imagebank/'.$_SESSION["ls_logo"],38,730,$_SESSION["ls_width"],$_SESSION["ls_height"]); // Agregar Logo
$li_tm=$io_pdf->getTextWidth(11,$as_titulo);
$tm=306-($li_tm/2);
$io_pdf->addText($tm,730,11,$as_titulo); // Agregar el título
$io_pdf->addText(500,730,9,date("d/m/Y")); // Agregar la Fecha
$io_pdf->addText(500,720,9,date("h:i a")); // Agregar la Fecha
$io_pdf->restoreState();
$io_pdf->closeObject();
$io_pdf->addObject($io_encabezado,'all');
}// end function uf_print_encabezadopagina
//--------------------------------------------------------------------------------------------------------------------------------
function uf_print_encabezado_pagina2($as_titulo,$as_titulo1,&$io_pdf)
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_encabezadopagina2
// Acess: private
// Arguments: as_titulo // Título del Reporte
// as_periodo_comp // Descripción del periodo del comprobante
// as_fecha_comp // Descripción del período de la fecha del comprobante
// io_pdf // Instancia de objeto pdf
// Description: función que imprime los encabezados por página
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 21/04/2006
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_encabezado=$io_pdf->openObject();
$io_pdf->saveState();
$io_pdf->line(10,40,578,40);
$io_pdf->addJpegFromFile('../../shared/imagebank/'.$_SESSION["ls_logo"],38,730,$_SESSION["ls_width"],$_SESSION["ls_height"]); // Agregar Logo
$li_tm=$io_pdf->getTextWidth(11,$as_titulo);
$tm=306-($li_tm/2);
$io_pdf->addText($tm,730,11,$as_titulo); // Agregar el título
$li_tm=$io_pdf->getTextWidth(10,$as_titulo1);
$tm=300-($li_tm/2);
$io_pdf->addText($tm,715,10,$as_titulo1); // Agregar el título
$io_pdf->addText(500,760,9,date("d/m/Y")); // Agregar la Fecha
$io_pdf->addText(500,750,9,date("h:i a")); // Agregar la Fecha
$io_pdf->restoreState();
$io_pdf->closeObject();
$io_pdf->addObject($io_encabezado,'all');
}// end function uf_print_encabezadopagina2
//--------------------------------------------------------------------------------------------------------------------------------
function uf_print_cabecera_detalle($io_encabezado,&$io_pdf)
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_cabecera_detalle
// Acess: private
// Arguments: la_data // arreglo de información
// io_pdf // Objeto PDF
// Description: función que imprime el detalle
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 21/04/2006
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_pdf->saveState();
//$io_pdf->ezSetDy(-0.5);
$la_data=array(array('cuenta'=>'<b>Cuenta</b>','denominacion'=>'<b>Denominación</b>','descripcion'=>'<b>Descripción</b>',
'documento'=>'<b>Documento</b>','monto'=>'<b>Monto</b>'));
$la_columnas=array('cuenta'=>'','denominacion'=>'','descripcion'=>'','documento'=>'','monto'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 8, // Tamaño de Letras
'titleFontSize' => 8, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'colGap'=>1, // separacion entre tablas
'width'=>530, // Ancho de la tabla
'maxWidth'=>530, // Ancho Máximo de la tabla
'xPos'=>302, // Orientación de la tabla
'cols'=>array('cuenta'=>array('justification'=>'center','width'=>70), // Justificación y ancho
'denominacion'=>array('justification'=>'center','width'=>140), // Justificación y ancho
'descripcion'=>array('justification'=>'center','width'=>115), // Justificación y ancho
'documento'=>array('justification'=>'center','width'=>90), // Justificación y ancho
'monto'=>array('justification'=>'center','width'=>115))); // Justificación y ancho
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
$io_pdf->restoreState();
$io_pdf->closeObject();
$io_pdf->addObject($io_encabezado,'all');
}// end function uf_print_cabecera_detalle
//--------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------------------
function uf_print_detalle($la_data,&$io_pdf)
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle
// Acess: private
// Arguments: la_data // arreglo de información
// io_pdf // Objeto PDF
// Description: función que imprime el detalle
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 21/04/2006
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
global $ls_tiporeporte;
if($ls_tiporeporte==1)
{
$ls_titulo="Monto Bs.F.";
}
else
{
$ls_titulo="Monto Bs.";
}
//print_r($la_data);
$la_config=array('showHeadings'=>1, // Mostrar encabezados
'fontSize' => 8, // Tamaño de Letras
'titleFontSize' => 8, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'colGap'=>1, // separacion entre tablas
'width'=>530, // Ancho de la tabla
'maxWidth'=>530, // Ancho Máximo de la tabla
'xPos'=>302, // Orientación de la tabla
'cols'=>array('cuenta'=>array('justification'=>'center','width'=>70), // Justificación y ancho de la
'denominacion'=>array('justification'=>'left','width'=>140), // Justificación y ancho de la
'descripcion'=>array('justification'=>'center','width'=>115), // Justificación y ancho de la
'documento'=>array('justification'=>'center','width'=>90), // Justificación y ancho de la
'monto'=>array('justification'=>'right','width'=>115))); // Justificación y ancho de la
$la_columnas=array('cuenta'=>'<b>Cuenta</b>',
'denominacion'=>'<b>Denominación</b>',
'descripcion'=>'<b>Descripción</b>',
'documento'=>'<b>Documento</b>',
'monto'=>'<b>Monto</b>');
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
}// end function uf_print_detalle
//--------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------------------
function uf_print_pie_cabecera($ad_total,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function : uf_print_pie_cabecera
// Acess : private
// Arguments : ad_total // Total General
// Description : función que imprime el fin de la cabecera de cada página
// Creado Por : Ing. Yesenia Moreno
// Fecha Creación : 18/02/2006
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$la_data=array(array('total'=>'<b>Total</b>','monto'=>$ad_total));
$la_columna=array('total'=>'','monto'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'showLines'=>1, // Mostrar Líneas
'fontSize' => 9, // Tamaño de Letras
'shaded'=>0, // Sombra entre líneas
'colGap'=>1, // separacion entre tablas
'width'=>530, // Ancho de la tabla
'maxWidth'=>530, // Ancho Máximo de la tabla
'xPos'=>302, // Orientación de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'cols'=>array('total'=>array('justification'=>'right','width'=>415), // Justificación y ancho de la columna
'monto'=>array('justification'=>'right','width'=>115))); // Justificación y ancho de la
$io_pdf->ezTable($la_data,$la_columna,'',$la_config);
}// end function uf_print_pie_cabecera
//--------------------------------------------------------------------------------------------------------------------------------------
function uf_print_cabecera_estructura( $ls_codestpro1,$ls_codestpro2,$ls_codestpro3,$ls_codestpro4,$ls_codestpro5,
$ls_denestpro1,$ls_denestpro2,$ls_denestpro3,$ls_denestpro4,$ls_denestpro5,$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_cabecera
// Access: private
// Arguments: as_programatica // programatica del comprobante
// as_denestpro5 // denominacion de la programatica del comprobante
// io_pdf // Objeto PDF
// Description: función que imprime la cabecera de cada página
// Creado Por: Ing. Jennifer Rivero
// Fecha Creación: 17/11/2008
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$ls_estmodest = $_SESSION["la_empresa"]["estmodest"];
$li_nomestpro1 = $_SESSION["la_empresa"]["nomestpro1"];
$li_nomestpro2 = $_SESSION["la_empresa"]["nomestpro2"];
$li_nomestpro3 = $_SESSION["la_empresa"]["nomestpro3"];
$li_nomestpro4 = $_SESSION["la_empresa"]["nomestpro4"];
$li_nomestpro5 = $_SESSION["la_empresa"]["nomestpro5"];
$li_loncodestpro1 = $_SESSION["la_empresa"]["loncodestpro1"];
$li_loncodestpro2 = $_SESSION["la_empresa"]["loncodestpro2"];
$li_loncodestpro3 = $_SESSION["la_empresa"]["loncodestpro3"];
$li_loncodestpro4 = $_SESSION["la_empresa"]["loncodestpro4"];
$li_loncodestpro5 = $_SESSION["la_empresa"]["loncodestpro5"];
$ls_codestpro1 = trim(substr($ls_codestpro1,-$li_loncodestpro1));
$ls_codestpro2 = trim(substr($ls_codestpro2,-$li_loncodestpro2));
$ls_codestpro3 = trim(substr($ls_codestpro3,-$li_loncodestpro3));
$ls_codestpro4 = trim(substr($ls_codestpro4,-$li_loncodestpro4));
$ls_codestpro5 = trim(substr($ls_codestpro5,-$li_loncodestpro5));
if ($ls_estmodest==1)
{
$ls_datat1[1]=array('nombre'=>'<b>'.$li_nomestpro1.":</b> ",'codestpro'=>$ls_codestpro1,'denom'=>$ls_denestpro1);
$ls_datat1[2]=array('nombre'=>'<b>'.$li_nomestpro2.":</b> ",'codestpro'=>$ls_codestpro2,'denom'=>$ls_denestpro2);
$ls_datat1[3]=array('nombre'=>'<b>'.$li_nomestpro3.":</b> ",'codestpro'=>$ls_codestpro3,'denom'=>$ls_denestpro3);
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 6, // Tamaño de Letras
'titleFontSize' => 7, // Tamaño de Letras de los títulos
'showLines'=>0, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'colGap'=>1, // separacion entre tablas
'width'=>990, // Ancho de la tabla
'maxWidth'=>990, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'xPos'=>302, // Orientación de la tabla
'cols'=>array('nombre'=>array('justification'=>'left','width'=>150),
'codestpro'=>array('justification'=>'right','width'=>60),
'denom'=>array('justification'=>'left','width'=>320)));
$io_pdf->ezTable($ls_datat1,'','',$la_config);
}
else
{
$ls_datat1[1]=array('nombre'=>'<b>'.$li_nomestpro1.":</b> ",'codestpro'=>$ls_codestpro1,'denom'=>$ls_denestpro1);
$ls_datat1[2]=array('nombre'=>'<b>'.$li_nomestpro2.":</b> ",'codestpro'=>$ls_codestpro2,'denom'=>$ls_denestpro2);
$ls_datat1[3]=array('nombre'=>'<b>'.$li_nomestpro3.":</b> ",'codestpro'=>$ls_codestpro3,'denom'=>$ls_denestpro3);
$ls_datat1[4]=array('nombre'=>'<b>'.$li_nomestpro4.":</b> ",'codestpro'=>$ls_codestpro4,'denom'=>$ls_denestpro4);
$ls_datat1[5]=array('nombre'=>'<b>'.$li_nomestpro5.":</b> ",'codestpro'=>$ls_codestpro5,'denom'=>$ls_denestpro5);
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 6, // Tamaño de Letras
'titleFontSize' => 7, // Tamaño de Letras de los títulos
'showLines'=>0, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'colGap'=>1, // separacion entre tablas
'width'=>990, // Ancho de la tabla
'maxWidth'=>990, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'xPos'=>302, // Orientación de la tabla
'cols'=>array('nombre'=>array('justification'=>'left','width'=>150),
'codestpro'=>array('justification'=>'right','width'=>60),
'denom'=>array('justification'=>'left','width'=>320)));
$io_pdf->ezTable($ls_datat1,'','',$la_config);
}
unset($ls_datat1);
unset($la_config);
}// end function uf_print_cabecera
//--------------------------------------------------------------------------------------------------------------------------------------
require_once("../../shared/ezpdf/class.ezpdf.php");
require_once("sigesp_spi_reporte.php");
$io_report = new sigesp_spi_reporte();
require_once("sigesp_spi_funciones_reportes.php");
$io_function_report = new sigesp_spi_funciones_reportes();
require_once("../../shared/class_folder/class_funciones.php");
$io_funciones=new class_funciones();
require_once("../class_funciones_ingreso.php");
$io_fun_ingreso=new class_funciones_ingreso();
require_once("../../shared/class_folder/class_fecha.php");
$io_fecha = new class_fecha();
//-------------------------------------------------- Parámetros para Filtar el Reporte -------------------------------------
$ldt_periodo=$_SESSION["la_empresa"]["periodo"];
$li_ano=substr($ldt_periodo,0,4);
$ls_cmbmesdes = "01";
$ldt_fecini=$li_ano."-".$ls_cmbmesdes."-01";
$ls_cmbmeshas = "12";
$ls_mes=$ls_cmbmeshas;
$ls_ano=$li_ano;
$fecfin=$io_fecha->uf_last_day($ls_mes,$ls_ano);
$ldt_fecfin=$io_funciones->uf_convertirdatetobd($fecfin);
$ls_modalidad=$_SESSION["la_empresa"]["estmodest"];
$ls_estpreing=$_SESSION["la_empresa"]["estpreing"];
if($ls_estpreing==1)
{
$ls_codestpro1_min = $_GET["codestpro1"];
$ls_codestpro2_min = $_GET["codestpro2"];
$ls_codestpro3_min = $_GET["codestpro3"];
$ls_codestpro1h_max = $_GET["codestpro1h"];
$ls_codestpro2h_max = $_GET["codestpro2h"];
$ls_codestpro3h_max = $_GET["codestpro3h"];
$ls_estclades = $_GET["estclades"];
$ls_estclahas = $_GET["estclahas"];
$ls_loncodestpro1 = $_SESSION["la_empresa"]["loncodestpro1"];
$ls_loncodestpro2 = $_SESSION["la_empresa"]["loncodestpro2"];
$ls_loncodestpro3 = $_SESSION["la_empresa"]["loncodestpro3"];
$ls_loncodestpro4 = $_SESSION["la_empresa"]["loncodestpro4"];
$ls_loncodestpro5 = $_SESSION["la_empresa"]["loncodestpro5"];
if($ls_modalidad==1)
{
$ls_codestpro4_min = "0000000000000000000000000";
$ls_codestpro5_min = "0000000000000000000000000";
$ls_codestpro4h_max = "0000000000000000000000000";
$ls_codestpro5h_max = "0000000000000000000000000";
if(($ls_codestpro1_min=="")&&($ls_codestpro2_min=="")&&($ls_codestpro3_min==""))
{
if($io_function_report->uf_spi_reporte_select_min_programatica($ls_codestpro1_min,$ls_codestpro2_min,
$ls_codestpro3_min,$ls_codestpro4_min,
$ls_codestpro5_min,$ls_estclades))
{
$ls_codestpro1 = $ls_codestpro1_min;
$ls_codestpro2 = $ls_codestpro2_min;
$ls_codestpro3 = $ls_codestpro3_min;
$ls_codestpro4 = $ls_codestpro4_min;
$ls_codestpro5 = $ls_codestpro5_min;
}
}
else
{
$ls_codestpro1 = $ls_codestpro1_min;
$ls_codestpro2 = $ls_codestpro2_min;
$ls_codestpro3 = $ls_codestpro3_min;
$ls_codestpro4 = $ls_codestpro4_min;
$ls_codestpro5 = $ls_codestpro5_min;
}
if(($ls_codestpro1h_max=="")&&($ls_codestpro2h_max=="")&&($ls_codestpro3h_max==""))
{
if($io_function_report->uf_spi_reporte_select_max_programatica($ls_codestpro1h_max,$ls_codestpro2h_max,
$ls_codestpro3h_max,$ls_codestpro4h_max,
$ls_codestpro5h_max,$ls_estclahas))
{
$ls_codestpro1h = $ls_codestpro1h_max;
$ls_codestpro2h = $ls_codestpro2h_max;
$ls_codestpro3h = $ls_codestpro3h_max;
$ls_codestpro4h = $ls_codestpro4h_max;
$ls_codestpro5h = $ls_codestpro5h_max;
}
}
else
{
$ls_codestpro1h = $ls_codestpro1h_max;
$ls_codestpro2h = $ls_codestpro2h_max;
$ls_codestpro3h = $ls_codestpro3h_max;
$ls_codestpro4h = $ls_codestpro4h_max;
$ls_codestpro5h = $ls_codestpro5h_max;
}
}
elseif($ls_modalidad==2)
{
$ls_codestpro4_min = $_GET["codestpro4"];
$ls_codestpro5_min = $_GET["codestpro5"];
$ls_codestpro4h_max = $_GET["codestpro4h"];
$ls_codestpro5h_max = $_GET["codestpro5h"];
if(($ls_codestpro1_min=='**') ||($ls_codestpro1_min==''))
{
$ls_codestpro1_min='';
}
else
{
$ls_codestpro1_min = $io_funciones->uf_cerosizquierda($ls_codestpro1_min,25);
}
if(($ls_codestpro2_min=='**') ||($ls_codestpro2_min==''))
{
$ls_codestpro2_min='';
}
else
{
$ls_codestpro2_min = $io_funciones->uf_cerosizquierda($ls_codestpro2_min,25);
}
if(($ls_codestpro3_min=='**')||($ls_codestpro3_min==''))
{
$ls_codestpro3_min='';
}
else
{
$ls_codestpro3_min = $io_funciones->uf_cerosizquierda($ls_codestpro3_min,25);
}
if(($ls_codestpro4_min=='**') ||($ls_codestpro4_min==''))
{
$ls_codestpro4_min='';
}
else
{
$ls_codestpro4_min = $io_funciones->uf_cerosizquierda($ls_codestpro4_min,25);
}
if(($ls_codestpro5_min=='**') ||($ls_codestpro5_min==''))
{
$ls_codestpro5_min='';
}
else
{
$ls_codestpro5_min = $io_funciones->uf_cerosizquierda($ls_codestpro5_min,25);
}
if(($ls_codestpro1h_max=='**')||($ls_codestpro1h_max==''))
{
$ls_codestpro1h_max='';
}
else
{
$ls_codestpro1h_max = $io_funciones->uf_cerosizquierda($ls_codestpro1h_max,25);
}
if(($ls_codestpro2h_max=='**') ||($ls_codestpro2h_max==''))
{
$ls_codestpro2h_max='';
}else
{
$ls_codestpro2h_max = $io_funciones->uf_cerosizquierda($ls_codestpro2h_max,25);
}
if(($ls_codestpro3h_max=='**') ||($ls_codestpro3h_max==''))
{
$ls_codestpro3h_max='';
}else
{
$ls_codestpro3h_max = $io_funciones->uf_cerosizquierda($ls_codestpro3h_max,25);
}
if(($ls_codestpro4h_max=='**') ||($ls_codestpro4h_max==''))
{
$ls_codestpro4h_max='';
}else
{
$ls_codestpro4h_max = $io_funciones->uf_cerosizquierda($ls_codestpro4h_max,25);
}
if(($ls_codestpro5h_max=='**') || ($ls_codestpro5h_max==''))
{
$ls_codestpro5h_max='';
}else
{
$ls_codestpro5h_max = $io_funciones->uf_cerosizquierda($ls_codestpro5h_max,25);
}
if(($ls_codestpro1_min=="")||($ls_codestpro2_min=="")||($ls_codestpro3_min=="")||($ls_codestpro4_min=="")||($ls_codestpro5_min==""))
{
if($io_function_report->uf_spi_reporte_select_min_programatica($ls_codestpro1_min,$ls_codestpro2_min,
$ls_codestpro3_min,$ls_codestpro4_min,
$ls_codestpro5_min,$ls_estclades))
{
$ls_codestpro1 = $ls_codestpro1_min;
$ls_codestpro2 = $ls_codestpro2_min;
$ls_codestpro3 = $ls_codestpro3_min;
$ls_codestpro4 = $ls_codestpro4_min;
$ls_codestpro5 = $ls_codestpro5_min;
}
}
else
{
$ls_codestpro1 = $ls_codestpro1_min;
$ls_codestpro2 = $ls_codestpro2_min;
$ls_codestpro3 = $ls_codestpro3_min;
$ls_codestpro4 = $ls_codestpro4_min;
$ls_codestpro5 = $ls_codestpro5_min;
}
if(($ls_codestpro1h_max=="")||($ls_codestpro2h_max=="")||($ls_codestpro3h_max=="")||($ls_codestpro4h_max=="")||($ls_codestpro5h_max==""))
{
if($io_function_report->uf_spi_reporte_select_max_programatica($ls_codestpro1h_max,$ls_codestpro2h_max,
$ls_codestpro3h_max,$ls_codestpro4h_max,
$ls_codestpro5h_max,$ls_estclahas))
{
$ls_codestpro1h = $ls_codestpro1h_max;
$ls_codestpro2h = $ls_codestpro2h_max;
$ls_codestpro3h = $ls_codestpro3h_max;
$ls_codestpro4h = $ls_codestpro4h_max;
$ls_codestpro5h = $ls_codestpro5h_max;
}
}
else
{
$ls_codestpro1h = $ls_codestpro1h_max;
$ls_codestpro2h = $ls_codestpro2h_max;
$ls_codestpro3h = $ls_codestpro3h_max;
$ls_codestpro4h = $ls_codestpro4h_max;
$ls_codestpro5h = $ls_codestpro5h_max;
}
}
$ls_programatica_desde=$ls_codestpro1.$ls_codestpro2.$ls_codestpro3.$ls_codestpro4.$ls_codestpro5;
$ls_programatica_hasta=$ls_codestpro1h.$ls_codestpro2h.$ls_codestpro3h.$ls_codestpro4h.$ls_codestpro5h;
if($ls_modalidad==1)
{
if (($ls_codestpro1<>"")&&($ls_codestpro2=="")&&($ls_codestpro3==""))
{
$ls_programatica_desde1=substr($ls_codestpro1,-$ls_loncodestpro1);
$ls_programatica_hasta1=substr($ls_codestpro1h,-$ls_loncodestpro1);
}
elseif(($ls_codestpro1<>"")&&($ls_codestpro2<>"")&&($ls_codestpro3==""))
{
$ls_programatica_desde1=substr($ls_codestpro1,-$ls_loncodestpro1)."-".substr($ls_codestpro2,-$ls_loncodestpro2);
$ls_programatica_hasta1=substr($ls_codestpro1h,-$ls_loncodestpro1)."-".substr($ls_codestpro2h,-$ls_loncodestpro2);
}
elseif(($ls_codestpro1<>"")&&($ls_codestpro2<>"")&&($ls_codestpro3<>""))
{
$ls_programatica_desde1=substr($ls_codestpro1,-$ls_loncodestpro1)."-".substr($ls_codestpro2,-$ls_loncodestpro2)."-".substr($ls_codestpro3,-$ls_loncodestpro3);
$ls_programatica_hasta1=substr($ls_codestpro1h,-$ls_loncodestpro1)."-".substr($ls_codestpro2h,-$ls_loncodestpro2)."-".substr($ls_codestpro3h,-$ls_loncodestpro3);
}
else
{
$ls_programatica_desde1="";
$ls_programatica_hasta1="";
}
}
else
{
$ls_programatica_desde1=substr($ls_codestpro1,-$ls_loncodestpro1)."-".substr($ls_codestpro2,-$ls_loncodestpro2)."-".substr($ls_codestpro3,-$ls_loncodestpro3)."-".substr($ls_codestpro4,-$ls_loncodestpro4)."-".substr($ls_codestpro5,-$ls_loncodestpro5)."-".$ls_estclades;
$ls_programatica_hasta1=substr($ls_codestpro1h,-$ls_loncodestpro1)."-".substr($ls_codestpro2h,-$ls_loncodestpro2)."-".substr($ls_codestpro3h,-$ls_loncodestpro3)."-".substr($ls_codestpro4h,-$ls_loncodestpro4)."-".substr($ls_codestpro5h,-$ls_loncodestpro5)."-".$ls_estclahas;
}
}
$ls_cuentades_min=$_GET["txtcuentades"];
$ls_cuentahas_max=$_GET["txtcuentahas"];
if($ls_cuentades_min=="")
{
if($io_function_report->uf_spi_reporte_select_min_cuenta($ls_cuentades_min))
{
$ls_cuentades=$ls_cuentades_min;
}
else
{
print("<script language=JavaScript>");
print(" alert('No hay cuentas presupuestraias');");
print(" close();");
print("</script>");
}
}
else
{
$ls_cuentades=$ls_cuentades_min;
}
if($ls_cuentahas_max=="")
{
if($io_function_report->uf_spi_reporte_select_max_cuenta($ls_cuentahas_max))
{
$ls_cuentahas=$ls_cuentahas_max;
}
else
{
print("<script language=JavaScript>");
print(" alert('No hay cuentas presupuestraias');");
print(" close();");
print("</script>");
}
}
else
{
$ls_cuentahas=$ls_cuentahas_max;
}
///////////////////////////////// SEGURIDAD ////////////////////////////////////////////////////
$ls_desc_event="Solicitud de Reporte Listado de Apertura desde la Cuenta ".$ls_cuentades." hasta ".$ls_cuentahas;
$io_fun_ingreso->uf_load_seguridad_reporte("SPI","sigesp_spi_r_listado_apertura.php",$ls_desc_event);
//////////////////////////////// SEGURIDAD /////////////////////////////////////////////////////
//---------------------------------------------------- Parámetros del encabezado --------------------------------------------
$ls_titulo=" <b>LISTADO DE APERTURAS</b> ";
if($ls_estpreing==1)
{
$ls_titulo1="<b>DESDE LA PROGRAMATICA ".$ls_programatica_desde1." HASTA ".$ls_programatica_hasta1." </b>";
}
$ls_tiporeporte=$_GET["tiporeporte"];
global $ls_tiporeporte;
require_once("../../shared/ezpdf/class.ezpdf.php");
if($ls_tiporeporte==1)
{
require_once("sigesp_spi_reportebsf.php");
$io_report=new sigesp_spi_reportebsf();
}
//--------------------------------------------------------------------------------------------------------------------------------
// Cargar el dts_cab con los datos de la cabecera del reporte( Selecciono todos comprobantes )
if($ls_estpreing==1)
{
$ls_codestpro1 = $io_funciones->uf_cerosizquierda($ls_codestpro1_min,25);
$ls_codestpro2 = $io_funciones->uf_cerosizquierda($ls_codestpro2_min,25);
$ls_codestpro3 = $io_funciones->uf_cerosizquierda($ls_codestpro3_min,25);
$ls_codestpro4 = $io_funciones->uf_cerosizquierda($ls_codestpro4_min,25);
$ls_codestpro5 = $io_funciones->uf_cerosizquierda($ls_codestpro5_min,25);
$ls_codestpro1h = $io_funciones->uf_cerosizquierda($ls_codestpro1h_max,25);
$ls_codestpro2h = $io_funciones->uf_cerosizquierda($ls_codestpro2h_max,25);
$ls_codestpro3h = $io_funciones->uf_cerosizquierda($ls_codestpro3h_max,25);
$ls_codestpro4h = $io_funciones->uf_cerosizquierda($ls_codestpro4h_max,25);
$ls_codestpro5h = $io_funciones->uf_cerosizquierda($ls_codestpro5h_max,25);
$ls_modalidad=$_SESSION["la_empresa"]["estmodest"];
$ls_estpreing=$_SESSION["la_empresa"]["estpreing"];
$li_loncodestpro1 = $_SESSION["la_empresa"]["loncodestpro1"];
$li_loncodestpro2 = $_SESSION["la_empresa"]["loncodestpro2"];
$li_loncodestpro3 = $_SESSION["la_empresa"]["loncodestpro3"];
$li_loncodestpro4 = $_SESSION["la_empresa"]["loncodestpro4"];
$li_loncodestpro5 = $_SESSION["la_empresa"]["loncodestpro5"];
$ls_denestpro4="";
$ls_denestpro5="";
}
error_reporting(E_ALL);
set_time_limit(1800);
$io_pdf=new Cezpdf('LETTER','portrait'); // Instancia de la clase PDF
$io_pdf->selectFont('../../shared/ezpdf/fonts/Helvetica.afm'); // Seleccionamos el tipo de letra
$io_pdf->ezSetCmMargins(3,3,3,3); // Configuración de los margenes en centímetros
if ($ls_estpreing==1)
{
uf_print_encabezado_pagina2($ls_titulo,$ls_titulo1,$io_pdf); // Imprimimos el encabezado de la página
}
else
{
uf_print_encabezado_pagina($ls_titulo,$io_pdf); // Imprimimos el encabezado de la página
}
$io_pdf->ezStartPageNumbers(550,50,10,'','',1); // Insertar el número de página
if ($ls_estpreing==1)
{
$lb_valido=$io_report->select_estructuras($ls_codestpro1,$ls_codestpro2,$ls_codestpro3,$ls_codestpro4,
$ls_codestpro5,$ls_codestpro1h,$ls_codestpro2h,$ls_codestpro3h,
$ls_codestpro4h,$ls_codestpro5h,$ls_estclades,$ls_estclahas);
$li_totfila=$io_report->data_est->getRowCount("programatica");
for ($j=1;$j<=$li_totfila;$j++)
{
$ls_codestpro1=trim($io_report->data_est->data["codestpro1"][$j]);
$ls_codestpro2=trim($io_report->data_est->data["codestpro2"][$j]);
$ls_codestpro3=trim($io_report->data_est->data["codestpro3"][$j]);
$ls_codestpro4=trim($io_report->data_est->data["codestpro4"][$j]);
$ls_codestpro5=trim($io_report->data_est->data["codestpro5"][$j]);
$ls_estcla=trim($io_report->data_est->data["estcla"][$j]);
$ls_estclades=trim($io_report->data_est->data["estcla"][$j]);
$ls_codestpro1h=trim($io_report->data_est->data["codestpro1"][$j]);
$ls_codestpro2h=trim($io_report->data_est->data["codestpro2"][$j]);
$ls_codestpro3h=trim($io_report->data_est->data["codestpro3"][$j]);
$ls_codestpro4h=trim($io_report->data_est->data["codestpro4"][$j]);
$ls_codestpro5h=trim($io_report->data_est->data["codestpro5"][$j]);
$ls_estclahas=trim($io_report->data_est->data["estcla"][$j]);
$lb_valido=$io_report->uf_spi_reporte_apertura2($ldt_fecini,$ldt_fecfin,$ls_cuentades,$ls_cuentahas,
$ls_codestpro1,$ls_codestpro2,$ls_codestpro3,$ls_codestpro4,
$ls_codestpro5,$ls_codestpro1h,$ls_codestpro2h,$ls_codestpro3h,
$ls_codestpro4h,$ls_codestpro5h,$ls_estclades,$ls_estclahas);
$li_totrow_det=$io_report->dts_reporte->getRowCount("spi_cuenta");
$ld_total=0;
for($li_s=1;$li_s<=$li_totrow_det;$li_s++)
{
$ls_spi_cuenta=$io_report->dts_reporte->data["spi_cuenta"][$li_s];
$ls_denominacion=$io_report->dts_reporte->data["denominacion"][$li_s];
$ls_descripcion=$io_report->dts_reporte->data["descripcion"][$li_s];
$ls_documento=$io_report->dts_reporte->data["documento"][$li_s];
$ld_monto=$io_report->dts_reporte->data["monto"][$li_s];
$ld_total=$ld_total+$ld_monto;
$ld_monto=number_format($ld_monto,2,",",".");
$la_data1[$li_s]=array('cuenta'=>$ls_spi_cuenta,'denominacion'=>$ls_denominacion,
'descripcion'=>$ls_descripcion,'documento'=>$ls_documento,'monto'=>$ld_monto);
$ld_monto=str_replace('.','',$ld_monto);
$ld_monto=str_replace(',','.',$ld_monto);
} //fin del for
$lb_valido=$io_report->uf_spg_reporte_select_denestpro1($ls_codestpro1,$ls_denestpro1,$ls_estcla);
if($lb_valido)
{
$ls_denestpro1=$ls_denestpro1;
}
if($lb_valido)
{
$ls_denestpro2="";
$lb_valido=$io_report->uf_spg_reporte_select_denestpro2($ls_codestpro1,$ls_codestpro2,
$ls_denestpro2,$ls_estcla);
$ls_denestpro2=$ls_denestpro2;
}
if($lb_valido)
{
$ls_denestpro3="";
$lb_valido=$io_report->uf_spg_reporte_select_denestpro3($ls_codestpro1,$ls_codestpro2,$ls_codestpro3,
$ls_denestpro3,$ls_estcla);
$ls_denestpro3=$ls_denestpro3;
}
if($ls_modalidad==2)
{
$ls_codestpro4=substr($ls_programatica,75,25);
if($lb_valido)
{
$ls_denestpro4="";
$lb_valido=$io_report->uf_spg_reporte_select_denestpro4($ls_codestpro1,$ls_codestpro2,$ls_codestpro3,
$ls_codestpro4,$ls_denestpro4,$ls_estcla);
$ls_denestpro4=$ls_denestpro4;
}
$ls_codestpro5=substr($ls_programatica,100,25);
if($lb_valido)
{
$ls_denestpro5="";
$lb_valido=$io_report->uf_spg_reporte_select_denestpro5($ls_codestpro1,$ls_codestpro2,$ls_codestpro3,
$ls_codestpro4,$ls_codestpro5,$ls_denestpro5,
$ls_estcla);
$ls_denestpro5=$ls_denestpro5;
}
}
if ($li_totrow_det>0)
{
$io_pdf->ezSetDy(-10);
uf_print_cabecera_estructura($ls_codestpro1,$ls_codestpro2,$ls_codestpro3,$ls_codestpro4,$ls_codestpro5,
$ls_denestpro1,$ls_denestpro2,$ls_denestpro3,$ls_denestpro4,$ls_denestpro5,$io_pdf);
uf_print_detalle($la_data1,$io_pdf); // Imprimimos el detalle
$ld_total=number_format($ld_total,2,",",".");
uf_print_pie_cabecera($ld_total,$io_pdf); // Imprimimos el total programatica
}
unset($la_data1);
unset($la_data);
}// fin del for
$io_pdf->ezStopPageNumbers(1,1);
if (isset($d) && $d)
{
$ls_pdfcode = $io_pdf->ezOutput(1);
$ls_pdfcode = str_replace("\n","\n<br>",htmlspecialchars($ls_pdfcode));
echo '<html><body>';
echo trim($ls_pdfcode);
echo '</body></html>';
}
else
{
$io_pdf->ezStream();
}
unset($io_pdf);
}
else
{
$lb_valido=$io_report->uf_spi_reporte_apertura($ldt_fecini,$ldt_fecfin,$ls_cuentades,$ls_cuentahas);
if($lb_valido==false) // Existe algún error ó no hay registros
{
print("<script language=JavaScript>");
print(" alert('No hay nada que Reportar');");
print(" close();");
print("</script>");
}
else // Imprimimos el reporte
{
$li_totrow_det=$io_report->dts_reporte->getRowCount("spi_cuenta");
$ld_total=0;
for($li_s=1;$li_s<=$li_totrow_det;$li_s++)
{
$ls_spi_cuenta=$io_report->dts_reporte->data["spi_cuenta"][$li_s];
$ls_denominacion=$io_report->dts_reporte->data["denominacion"][$li_s];
$ls_descripcion=$io_report->dts_reporte->data["descripcion"][$li_s];
$ls_documento=$io_report->dts_reporte->data["documento"][$li_s];
$ld_monto=$io_report->dts_reporte->data["monto"][$li_s];
$ld_total=$ld_total+$ld_monto;
$ld_monto=number_format($ld_monto,2,",",".");
$la_data[$li_s]=array('cuenta'=>$ls_spi_cuenta,'denominacion'=>$ls_denominacion,
'descripcion'=>$ls_descripcion,'documento'=>$ls_documento,'monto'=>$ld_monto);
$ld_monto=str_replace('.','',$ld_monto);
$ld_monto=str_replace(',','.',$ld_monto);
}
uf_print_detalle($la_data,$io_pdf); // Imprimimos el detalle
$ld_total=number_format($ld_total,2,",",".");
uf_print_pie_cabecera($ld_total,$io_pdf); // Imprimimos el total programatica
unset($la_data);
$io_pdf->ezStopPageNumbers(1,1);
if (isset($d) && $d)
{
$ls_pdfcode = $io_pdf->ezOutput(1);
$ls_pdfcode = str_replace("\n","\n<br>",htmlspecialchars($ls_pdfcode));
echo '<html><body>';
echo trim($ls_pdfcode);
echo '</body></html>';
}
else
{
$io_pdf->ezStream();
}
unset($io_pdf);
}
unset($io_report);
unset($io_funciones);
unset($io_function_report);
}//fin del eslede no usa estrutcuras
?> | gpl-2.0 |
laurynas-biveinis/webscalesql-5.6 | client/mysqlbinlog.cc | 100987 | /*
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
TODO: print the catalog (some USE catalog.db ????).
Standalone program to read a MySQL binary log (or relay log).
Should be able to read any file of these categories, even with
--start-position.
An important fact: the Format_desc event of the log is at most the 3rd event
of the log; if it is the 3rd then there is this combination:
Format_desc_of_slave, Rotate_of_master, Format_desc_of_master.
*/
#define MYSQL_CLIENT
#undef MYSQL_SERVER
#include "client_priv.h"
#include "my_default.h"
#include <my_time.h>
/* That one is necessary for defines of OPTION_NO_FOREIGN_KEY_CHECKS etc */
#include "sql_priv.h"
#include <signal.h>
#include <my_dir.h>
/*
error() is used in macro BINLOG_ERROR which is invoked in
rpl_gtid.h, hence the early forward declaration.
*/
static void error(const char *format, ...) ATTRIBUTE_FORMAT(printf, 1, 2);
static void warning(const char *format, ...) ATTRIBUTE_FORMAT(printf, 1, 2);
#include "rpl_gtid.h"
#include "log_event.h"
#include "log_event_old.h"
#include "sql_common.h"
#include "my_dir.h"
#include <welcome_copyright_notice.h> // ORACLE_WELCOME_COPYRIGHT_NOTICE
#include "sql_string.h"
#include "my_decimal.h"
#include "rpl_constants.h"
#include <algorithm>
using std::min;
using std::max;
#define BIN_LOG_HEADER_SIZE 4U
#define PROBE_HEADER_LEN (EVENT_LEN_OFFSET+4)
#define INTVAR_DYNAMIC_INIT 16
#define INTVAR_DYNAMIC_INCR 1
#define CLIENT_CAPABILITIES (CLIENT_LONG_PASSWORD | CLIENT_LONG_FLAG | CLIENT_LOCAL_FILES)
char server_version[SERVER_VERSION_LENGTH];
ulong filter_server_id = 0;
/*
One statement can result in a sequence of several events: Intvar_log_events,
User_var_log_events, and Rand_log_events, followed by one
Query_log_event. If statements are filtered out, the filter has to be
checked for the Query_log_event. So we have to buffer the Intvar,
User_var, and Rand events and their corresponding log postions until we see
the Query_log_event. This dynamic array buff_ev is used to buffer a structure
which stores such an event and the corresponding log position.
*/
DYNAMIC_ARRAY buff_ev;
// needed by net_serv.c
ulong bytes_sent = 0L, bytes_received = 0L;
ulong mysqld_net_retry_count = 10L;
ulong open_files_limit;
ulong opt_binlog_rows_event_max_size;
uint test_flags = 0;
static uint opt_protocol= 0;
static FILE *result_file;
#ifndef DBUG_OFF
static const char* default_dbug_option = "d:t:o,/tmp/mysqlbinlog.trace";
#endif
static const char *load_default_groups[]= { "mysqlbinlog","client",0 };
static my_bool one_database=0, disable_log_bin= 0;
static my_bool opt_hexdump= 0;
const char *base64_output_mode_names[]=
{"NEVER", "AUTO", "UNSPEC", "DECODE-ROWS", NullS};
TYPELIB base64_output_mode_typelib=
{ array_elements(base64_output_mode_names) - 1, "",
base64_output_mode_names, NULL };
static enum_base64_output_mode opt_base64_output_mode= BASE64_OUTPUT_UNSPEC;
static char *opt_base64_output_mode_str= 0;
static my_bool opt_remote_alias= 0;
const char *remote_proto_names[]=
{"BINLOG-DUMP-NON-GTIDS", "BINLOG-DUMP-GTIDS", NullS};
TYPELIB remote_proto_typelib=
{ array_elements(remote_proto_names) - 1, "",
remote_proto_names, NULL };
static enum enum_remote_proto {
BINLOG_DUMP_NON_GTID= 0,
BINLOG_DUMP_GTID= 1,
BINLOG_LOCAL= 2
} opt_remote_proto= BINLOG_LOCAL;
static char *opt_remote_proto_str= 0;
static char *database= 0;
static char *output_file= 0;
static my_bool force_opt= 0, short_form= 0;
static my_bool debug_info_flag, debug_check_flag;
static my_bool force_if_open_opt= 1, raw_mode= 0;
static my_bool to_last_remote_log= 0, stop_never= 0;
static my_bool opt_verify_binlog_checksum= 1;
static ulonglong offset = 0;
static int64 stop_never_slave_server_id= -1;
#ifndef DBUG_OFF
static int64 connection_server_id= -1;
#endif //DBUG_OFF
static char* host = 0;
static int port= 0;
static uint my_end_arg;
static const char* sock= 0;
static char *opt_plugin_dir= 0, *opt_default_auth= 0;
static my_bool opt_secure_auth= TRUE;
#ifdef HAVE_SMEM
static char *shared_memory_base_name= 0;
#endif
static char* user = 0;
static char* pass = 0;
static char *opt_bind_addr = NULL;
static char *charset= 0;
static uint verbose= 0;
static ulonglong start_position, stop_position;
#define start_position_mot ((my_off_t)start_position)
#define stop_position_mot ((my_off_t)stop_position)
static char *start_datetime_str, *stop_datetime_str;
static my_time_t start_datetime= 0, stop_datetime= MY_TIME_T_MAX;
static ulonglong rec_count= 0;
static MYSQL* mysql = NULL;
static char* dirname_for_local_load= 0;
static uint opt_server_id_bits = 0;
static ulong opt_server_id_mask = 0;
Sid_map *global_sid_map= NULL;
Checkable_rwlock *global_sid_lock= NULL;
Gtid_set *gtid_set_included= NULL;
Gtid_set *gtid_set_excluded= NULL;
/**
Pointer to the Format_description_log_event of the currently active binlog.
This will be changed each time a new Format_description_log_event is
found in the binlog. It is finally destroyed at program termination.
*/
static Format_description_log_event* glob_description_event= NULL;
/**
Exit status for functions in this file.
*/
enum Exit_status {
/** No error occurred and execution should continue. */
OK_CONTINUE= 0,
/** An error occurred and execution should stop. */
ERROR_STOP,
/** No error occurred but execution should stop. */
OK_STOP
};
/*
Options that will be used to filter out events.
*/
static char *opt_include_gtids_str= NULL,
*opt_exclude_gtids_str= NULL;
static my_bool opt_skip_gtids= 0;
static bool filter_based_on_gtids= false;
static bool in_transaction= false;
static bool seen_gtids= false;
static Exit_status dump_local_log_entries(PRINT_EVENT_INFO *print_event_info,
const char* logname);
static Exit_status dump_remote_log_entries(PRINT_EVENT_INFO *print_event_info,
const char* logname);
static Exit_status dump_single_log(PRINT_EVENT_INFO *print_event_info,
const char* logname);
static Exit_status dump_multiple_logs(int argc, char **argv);
static Exit_status safe_connect();
/*
This strucure is used to store the event and the log postion of the events
which is later used to print the event details from correct log postions.
The Log_event *event is used to store the pointer to the current event and
the event_pos is used to store the current event log postion.
*/
struct buff_event_info
{
Log_event *event;
my_off_t event_pos;
};
struct buff_event_info buff_event;
class Load_log_processor
{
char target_dir_name[FN_REFLEN];
size_t target_dir_name_len;
/*
When we see first event corresponding to some LOAD DATA statement in
binlog, we create temporary file to store data to be loaded.
We add name of this file to file_names array using its file_id as index.
If we have Create_file event (i.e. we have binary log in pre-5.0.3
format) we also store save event object to be able which is needed to
emit LOAD DATA statement when we will meet Exec_load_data event.
If we have Begin_load_query event we simply store 0 in
File_name_record::event field.
*/
struct File_name_record
{
char *fname;
Create_file_log_event *event;
};
/*
@todo Should be a map (e.g., a hash map), not an array. With the
present implementation, the number of elements in this array is
about the number of files loaded since the server started, which
may be big after a few years. We should be able to use existing
library data structures for this. /Sven
*/
DYNAMIC_ARRAY file_names;
/**
Looks for a non-existing filename by adding a numerical suffix to
the given base name, creates the generated file, and returns the
filename by modifying the filename argument.
@param[in,out] filename Base filename
@param[in,out] file_name_end Pointer to last character of
filename. The numerical suffix will be written to this position.
Note that there must be a least five bytes of allocated memory
after file_name_end.
@retval -1 Error (can't find new filename).
@retval >=0 Found file.
*/
File create_unique_file(char *filename, char *file_name_end)
{
File res;
/* If we have to try more than 1000 times, something is seriously wrong */
for (uint version= 0; version<1000; version++)
{
sprintf(file_name_end,"-%x",version);
if ((res= my_create(filename,0,
O_CREAT|O_EXCL|O_BINARY|O_WRONLY,MYF(0)))!=-1)
return res;
}
return -1;
}
public:
Load_log_processor() {}
~Load_log_processor() {}
int init()
{
return init_dynamic_array(&file_names, sizeof(File_name_record),
100, 100);
}
void init_by_dir_name(const char *dir)
{
target_dir_name_len= (convert_dirname(target_dir_name, dir, NullS) -
target_dir_name);
}
void init_by_cur_dir()
{
if (my_getwd(target_dir_name,sizeof(target_dir_name),MYF(MY_WME)))
exit(1);
target_dir_name_len= strlen(target_dir_name);
}
void destroy()
{
File_name_record *ptr= (File_name_record *)file_names.buffer;
File_name_record *end= ptr + file_names.elements;
for (; ptr < end; ptr++)
{
if (ptr->fname)
{
my_free(ptr->fname);
delete ptr->event;
memset(ptr, 0, sizeof(File_name_record));
}
}
delete_dynamic(&file_names);
}
/**
Obtain Create_file event for LOAD DATA statement by its file_id
and remove it from this Load_log_processor's list of events.
Checks whether we have already seen a Create_file_log_event with
the given file_id. If yes, returns a pointer to the event and
removes the event from array describing active temporary files.
From this moment, the caller is responsible for freeing the memory
occupied by the event.
@param[in] file_id File id identifying LOAD DATA statement.
@return Pointer to Create_file_log_event, or NULL if we have not
seen any Create_file_log_event with this file_id.
*/
Create_file_log_event *grab_event(uint file_id)
{
File_name_record *ptr;
Create_file_log_event *res;
if (file_id >= file_names.elements)
return 0;
ptr= dynamic_element(&file_names, file_id, File_name_record*);
if ((res= ptr->event))
memset(ptr, 0, sizeof(File_name_record));
return res;
}
/**
Obtain file name of temporary file for LOAD DATA statement by its
file_id and remove it from this Load_log_processor's list of events.
@param[in] file_id Identifier for the LOAD DATA statement.
Checks whether we have already seen Begin_load_query event for
this file_id. If yes, returns the file name of the corresponding
temporary file and removes the filename from the array of active
temporary files. From this moment, the caller is responsible for
freeing the memory occupied by this name.
@return String with the name of the temporary file, or NULL if we
have not seen any Begin_load_query_event with this file_id.
*/
char *grab_fname(uint file_id)
{
File_name_record *ptr;
char *res= 0;
if (file_id >= file_names.elements)
return 0;
ptr= dynamic_element(&file_names, file_id, File_name_record*);
if (!ptr->event)
{
res= ptr->fname;
memset(ptr, 0, sizeof(File_name_record));
}
return res;
}
Exit_status process(Create_file_log_event *ce);
Exit_status process(Begin_load_query_log_event *ce);
Exit_status process(Append_block_log_event *ae);
File prepare_new_file_for_old_format(Load_log_event *le, char *filename);
Exit_status load_old_format_file(NET* net, const char *server_fname,
uint server_fname_len, File file);
Exit_status process_first_event(const char *bname, size_t blen,
const uchar *block,
size_t block_len, uint file_id,
Create_file_log_event *ce);
};
/**
Creates and opens a new temporary file in the directory specified by previous call to init_by_dir_name() or init_by_cur_dir().
@param[in] le The basename of the created file will start with the
basename of the file pointed to by this Load_log_event.
@param[out] filename Buffer to save the filename in.
@return File handle >= 0 on success, -1 on error.
*/
File Load_log_processor::prepare_new_file_for_old_format(Load_log_event *le,
char *filename)
{
size_t len;
char *tail;
File file;
fn_format(filename, le->fname, target_dir_name, "", MY_REPLACE_DIR);
len= strlen(filename);
tail= filename + len;
if ((file= create_unique_file(filename,tail)) < 0)
{
error("Could not construct local filename %s.",filename);
return -1;
}
le->set_fname_outside_temp_buf(filename,len+(uint) strlen(tail));
return file;
}
/**
Reads a file from a server and saves it locally.
@param[in,out] net The server to read from.
@param[in] server_fname The name of the file that the server should
read.
@param[in] server_fname_len The length of server_fname.
@param[in,out] file The file to write to.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
*/
Exit_status Load_log_processor::load_old_format_file(NET* net,
const char*server_fname,
uint server_fname_len,
File file)
{
uchar buf[FN_REFLEN+1];
buf[0] = 0;
memcpy(buf + 1, server_fname, server_fname_len + 1);
if (my_net_write(net, buf, server_fname_len +2) || net_flush(net))
{
error("Failed requesting the remote dump of %s.", server_fname);
return ERROR_STOP;
}
for (;;)
{
ulong packet_len = my_net_read(net);
if (packet_len == 0)
{
if (my_net_write(net, (uchar*) "", 0) || net_flush(net))
{
error("Failed sending the ack packet.");
return ERROR_STOP;
}
/*
we just need to send something, as the server will read but
not examine the packet - this is because mysql_load() sends
an OK when it is done
*/
break;
}
else if (packet_len == packet_error)
{
error("Failed reading a packet during the dump of %s.", server_fname);
return ERROR_STOP;
}
if (packet_len > UINT_MAX)
{
error("Illegal length of packet read from net.");
return ERROR_STOP;
}
if (my_write(file, (uchar*) net->read_pos,
(uint) packet_len, MYF(MY_WME|MY_NABP)))
return ERROR_STOP;
}
return OK_CONTINUE;
}
/**
Process the first event in the sequence of events representing a
LOAD DATA statement.
Creates a temporary file to be used in LOAD DATA and writes first
block of data to it. Registers its file name (and optional
Create_file event) in the array of active temporary files.
@param bname Base name for temporary file to be created.
@param blen Base name length.
@param block First block of data to be loaded.
@param block_len First block length.
@param file_id Identifies the LOAD DATA statement.
@param ce Pointer to Create_file event object if we are processing
this type of event.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
*/
Exit_status Load_log_processor::process_first_event(const char *bname,
size_t blen,
const uchar *block,
size_t block_len,
uint file_id,
Create_file_log_event *ce)
{
uint full_len= target_dir_name_len + blen + 9 + 9 + 1;
Exit_status retval= OK_CONTINUE;
char *fname, *ptr;
File file;
File_name_record rec;
DBUG_ENTER("Load_log_processor::process_first_event");
if (!(fname= (char*) my_malloc(full_len,MYF(MY_WME))))
{
error("Out of memory.");
delete ce;
DBUG_RETURN(ERROR_STOP);
}
memcpy(fname, target_dir_name, target_dir_name_len);
ptr= fname + target_dir_name_len;
memcpy(ptr,bname,blen);
ptr+= blen;
ptr+= sprintf(ptr, "-%x", file_id);
if ((file= create_unique_file(fname,ptr)) < 0)
{
error("Could not construct local filename %s%s.",
target_dir_name,bname);
my_free(fname);
delete ce;
DBUG_RETURN(ERROR_STOP);
}
rec.fname= fname;
rec.event= ce;
/*
fname is freed in process_event()
after Execute_load_query_log_event or Execute_load_log_event
will have been processed, otherwise in Load_log_processor::destroy()
*/
if (set_dynamic(&file_names, &rec, file_id))
{
error("Out of memory.");
my_free(fname);
delete ce;
DBUG_RETURN(ERROR_STOP);
}
if (ce)
ce->set_fname_outside_temp_buf(fname, (uint) strlen(fname));
if (my_write(file, (uchar*)block, block_len, MYF(MY_WME|MY_NABP)))
{
error("Failed writing to file.");
retval= ERROR_STOP;
}
if (my_close(file, MYF(MY_WME)))
{
error("Failed closing file.");
retval= ERROR_STOP;
}
DBUG_RETURN(retval);
}
/**
Process the given Create_file_log_event.
@see Load_log_processor::process_first_event(const char*,uint,const char*,uint,uint,Create_file_log_event*)
@param ce Create_file_log_event to process.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
*/
Exit_status Load_log_processor::process(Create_file_log_event *ce)
{
const char *bname= ce->fname + dirname_length(ce->fname);
uint blen= ce->fname_len - (bname-ce->fname);
return process_first_event(bname, blen, ce->block, ce->block_len,
ce->file_id, ce);
}
/**
Process the given Begin_load_query_log_event.
@see Load_log_processor::process_first_event(const char*,uint,const char*,uint,uint,Create_file_log_event*)
@param ce Begin_load_query_log_event to process.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
*/
Exit_status Load_log_processor::process(Begin_load_query_log_event *blqe)
{
return process_first_event("SQL_LOAD_MB", 11, blqe->block, blqe->block_len,
blqe->file_id, 0);
}
/**
Process the given Append_block_log_event.
Appends the chunk of the file contents specified by the event to the
file created by a previous Begin_load_query_log_event or
Create_file_log_event.
If the file_id for the event does not correspond to any file
previously registered through a Begin_load_query_log_event or
Create_file_log_event, this member function will print a warning and
return OK_CONTINUE. It is safe to return OK_CONTINUE, because no
query will be written for this event. We should not print an error
and fail, since the missing file_id could be because a (valid)
--start-position has been specified after the Begin/Create event but
before this Append event.
@param ae Append_block_log_event to process.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
*/
Exit_status Load_log_processor::process(Append_block_log_event *ae)
{
DBUG_ENTER("Load_log_processor::process");
const char* fname= ((ae->file_id < file_names.elements) ?
dynamic_element(&file_names, ae->file_id,
File_name_record*)->fname : 0);
if (fname)
{
File file;
Exit_status retval= OK_CONTINUE;
if (((file= my_open(fname,
O_APPEND|O_BINARY|O_WRONLY,MYF(MY_WME))) < 0))
{
error("Failed opening file %s", fname);
DBUG_RETURN(ERROR_STOP);
}
if (my_write(file,(uchar*)ae->block,ae->block_len,MYF(MY_WME|MY_NABP)))
{
error("Failed writing to file %s", fname);
retval= ERROR_STOP;
}
if (my_close(file,MYF(MY_WME)))
{
error("Failed closing file %s", fname);
retval= ERROR_STOP;
}
DBUG_RETURN(retval);
}
/*
There is no Create_file event (a bad binlog or a big
--start-position). Assuming it's a big --start-position, we just do
nothing and print a warning.
*/
warning("Ignoring Append_block as there is no "
"Create_file event for file_id: %u", ae->file_id);
DBUG_RETURN(OK_CONTINUE);
}
static Load_log_processor load_processor;
/**
Replace windows-style backslashes by forward slashes so it can be
consumed by the mysql client, which requires Unix path.
@todo This is only useful under windows, so may be ifdef'ed out on
other systems. /Sven
@todo If a Create_file_log_event contains a filename with a
backslash (valid under unix), then we have problems under windows.
/Sven
@param[in,out] fname Filename to modify. The filename is modified
in-place.
*/
static void convert_path_to_forward_slashes(char *fname)
{
while (*fname)
{
if (*fname == '\\')
*fname= '/';
fname++;
}
}
/**
Indicates whether the given database should be filtered out,
according to the --database=X option.
@param log_dbname Name of database.
@return nonzero if the database with the given name should be
filtered out, 0 otherwise.
*/
static bool shall_skip_database(const char *log_dbname)
{
return one_database &&
(log_dbname != NULL) &&
strcmp(log_dbname, database);
}
/**
Checks whether the given event should be filtered out,
according to the include-gtids, exclude-gtids and
skip-gtids options.
@param ev Pointer to the event to be checked.
@return true if the event should be filtered out,
false, otherwise.
*/
static bool shall_skip_gtids(Log_event* ev)
{
bool filtered= false;
switch (ev->get_type_code())
{
case GTID_LOG_EVENT:
case ANONYMOUS_GTID_LOG_EVENT:
{
Gtid_log_event *gtid= (Gtid_log_event *) ev;
if (opt_include_gtids_str != NULL)
{
filtered= filtered ||
!gtid_set_included->contains_gtid(gtid->get_sidno(true),
gtid->get_gno());
}
if (opt_exclude_gtids_str != NULL)
{
filtered= filtered ||
gtid_set_excluded->contains_gtid(gtid->get_sidno(true),
gtid->get_gno());
}
filter_based_on_gtids= filtered;
filtered= filtered || opt_skip_gtids;
}
break;
/* Skip previous gtids if --skip-gtids is set. */
case PREVIOUS_GTIDS_LOG_EVENT:
filtered= opt_skip_gtids;
break;
/*
Transaction boundaries reset the global filtering flag.
Since in the relay log a transaction can span multiple
log files, we do not reset filter_based_on_gtids flag when
processing control events (they can appear in the middle
of a transaction). But then, if:
FILE1: ... GTID BEGIN QUERY QUERY COMMIT ROTATE
FILE2: FD BEGIN QUERY QUERY COMMIT
Events on the second file would not be outputted, even
though they should.
*/
case XID_EVENT:
filtered= filter_based_on_gtids;
filter_based_on_gtids= false;
break;
case QUERY_EVENT:
filtered= filter_based_on_gtids;
if (((Query_log_event *)ev)->ends_group())
filter_based_on_gtids= false;
break;
/*
Never skip STOP, FD, ROTATE, IGNORABLE or INCIDENT events.
SLAVE_EVENT and START_EVENT_V3 are there for completion.
Although in the binlog transactions do not span multiple
log files, in the relay-log, that can happen. As such,
we need to explicitly state that we do not filter these
events, because there is a chance that they appear in the
middle of a filtered transaction, e.g.:
FILE1: ... GTID BEGIN QUERY QUERY ROTATE
FILE2: FD QUERY QUERY COMMIT GTID BEGIN ...
In this case, ROTATE and FD events should be processed and
outputted.
*/
case START_EVENT_V3: /* for completion */
case SLAVE_EVENT: /* for completion */
case STOP_EVENT:
case FORMAT_DESCRIPTION_EVENT:
case ROTATE_EVENT:
case IGNORABLE_LOG_EVENT:
case INCIDENT_EVENT:
filtered= false;
break;
default:
filtered= filter_based_on_gtids;
break;
}
return filtered;
}
/**
Print the given event, and either delete it or delegate the deletion
to someone else.
The deletion may be delegated in two cases: (1) the event is a
Format_description_log_event, and is saved in
glob_description_event; (2) the event is a Create_file_log_event,
and is saved in load_processor.
@param[in,out] print_event_info Parameters and context state
determining how to print.
@param[in] ev Log_event to process.
@param[in] pos Offset from beginning of binlog file.
@param[in] logname Name of input binlog.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
@retval OK_STOP No error, but the end of the specified range of
events to process has been reached and the program should terminate.
*/
Exit_status process_event(PRINT_EVENT_INFO *print_event_info, Log_event *ev,
my_off_t pos, const char *logname)
{
char ll_buff[21];
Log_event_type ev_type= ev->get_type_code();
my_bool destroy_evt= TRUE;
DBUG_ENTER("process_event");
print_event_info->short_form= short_form;
Exit_status retval= OK_CONTINUE;
IO_CACHE *const head= &print_event_info->head_cache;
/*
Format events are not concerned by --offset and such, we always need to
read them to be able to process the wanted events.
*/
if (((rec_count >= offset) &&
((my_time_t) (ev->when.tv_sec) >= start_datetime)) ||
(ev_type == FORMAT_DESCRIPTION_EVENT))
{
if (ev_type != FORMAT_DESCRIPTION_EVENT)
{
/*
We have found an event after start_datetime, from now on print
everything (in case the binlog has timestamps increasing and
decreasing, we do this to avoid cutting the middle).
*/
start_datetime= 0;
offset= 0; // print everything and protect against cycling rec_count
/*
Skip events according to the --server-id flag. However, don't
skip format_description or rotate events, because they they
are really "global" events that are relevant for the entire
binlog, even if they have a server_id. Also, we have to read
the format_description event so that we can parse subsequent
events.
*/
if (ev_type != ROTATE_EVENT &&
filter_server_id && (filter_server_id != ev->server_id))
goto end;
}
if (((my_time_t) (ev->when.tv_sec) >= stop_datetime)
|| (pos >= stop_position_mot))
{
/* end the program */
retval= OK_STOP;
goto end;
}
if (!short_form)
my_b_printf(&print_event_info->head_cache,
"# at %s\n",llstr(pos,ll_buff));
if (!opt_hexdump)
print_event_info->hexdump_from= 0; /* Disabled */
else
print_event_info->hexdump_from= pos;
print_event_info->base64_output_mode= opt_base64_output_mode;
DBUG_PRINT("debug", ("event_type: %s", ev->get_type_str()));
if (shall_skip_gtids(ev))
goto end;
switch (ev_type) {
case QUERY_EVENT:
{
bool parent_query_skips=
!((Query_log_event*) ev)->is_trans_keyword() &&
shall_skip_database(((Query_log_event*) ev)->db);
bool ends_group= ((Query_log_event*) ev)->ends_group();
bool starts_group= ((Query_log_event*) ev)->starts_group();
for (uint i= 0; i < buff_ev.elements; i++)
{
buff_event_info pop_event_array= *dynamic_element(&buff_ev, i, buff_event_info *);
Log_event *temp_event= pop_event_array.event;
my_off_t temp_log_pos= pop_event_array.event_pos;
print_event_info->hexdump_from= (opt_hexdump ? temp_log_pos : 0);
if (!parent_query_skips)
temp_event->print(result_file, print_event_info);
delete temp_event;
}
print_event_info->hexdump_from= (opt_hexdump ? pos : 0);
reset_dynamic(&buff_ev);
if (parent_query_skips)
{
/*
Even though there would be no need to set the flag here,
since parent_query_skips is never true when handling "COMMIT"
statements in the Query_log_event, we still need to handle DDL,
which causes a commit itself.
*/
if (seen_gtids && !in_transaction && !starts_group && !ends_group)
{
/*
For DDLs, print the COMMIT right away.
*/
fprintf(result_file, "COMMIT /* added by mysqlbinlog */%s\n", print_event_info->delimiter);
print_event_info->skipped_event_in_transaction= false;
in_transaction= false;
}
else
print_event_info->skipped_event_in_transaction= true;
goto end;
}
if (ends_group)
{
in_transaction= false;
print_event_info->skipped_event_in_transaction= false;
if (print_event_info->is_gtid_next_set)
print_event_info->is_gtid_next_valid= false;
}
else if (starts_group)
in_transaction= true;
else
{
/*
We are not in a transaction and are not seeing a BEGIN or
COMMIT. So this is an implicitly committing DDL.
*/
if (print_event_info->is_gtid_next_set && !in_transaction)
print_event_info->is_gtid_next_valid= false;
}
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
break;
destroy_evt= TRUE;
}
case INTVAR_EVENT:
{
destroy_evt= FALSE;
buff_event.event= ev;
buff_event.event_pos= pos;
insert_dynamic(&buff_ev, (uchar*) &buff_event);
break;
}
case RAND_EVENT:
{
destroy_evt= FALSE;
buff_event.event= ev;
buff_event.event_pos= pos;
insert_dynamic(&buff_ev, (uchar*) &buff_event);
break;
}
case USER_VAR_EVENT:
{
destroy_evt= FALSE;
buff_event.event= ev;
buff_event.event_pos= pos;
insert_dynamic(&buff_ev, (uchar*) &buff_event);
break;
}
case CREATE_FILE_EVENT:
{
Create_file_log_event* ce= (Create_file_log_event*)ev;
/*
We test if this event has to be ignored. If yes, we don't save
this event; this will have the good side-effect of ignoring all
related Append_block and Exec_load.
Note that Load event from 3.23 is not tested.
*/
if (shall_skip_database(ce->db))
{
print_event_info->skipped_event_in_transaction= true;
goto end; // Next event
}
/*
We print the event, but with a leading '#': this is just to inform
the user of the original command; the command we want to execute
will be a derivation of this original command (we will change the
filename and use LOCAL), prepared in the 'case EXEC_LOAD_EVENT'
below.
*/
{
ce->print(result_file, print_event_info, TRUE);
if (head->error == -1)
goto err;
}
// If this binlog is not 3.23 ; why this test??
if (glob_description_event->binlog_version >= 3)
{
/*
transfer the responsibility for destroying the event to
load_processor
*/
ev= NULL;
if ((retval= load_processor.process(ce)) != OK_CONTINUE)
goto end;
}
break;
}
case APPEND_BLOCK_EVENT:
/*
Append_block_log_events can safely print themselves even if
the subsequent call load_processor.process fails, because the
output of Append_block_log_event::print is only a comment.
*/
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
if ((retval= load_processor.process((Append_block_log_event*) ev)) !=
OK_CONTINUE)
goto end;
break;
case EXEC_LOAD_EVENT:
{
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
Execute_load_log_event *exv= (Execute_load_log_event*)ev;
Create_file_log_event *ce= load_processor.grab_event(exv->file_id);
/*
if ce is 0, it probably means that we have not seen the Create_file
event (a bad binlog, or most probably --start-position is after the
Create_file event). Print a warning comment.
*/
if (ce)
{
/*
We must not convert earlier, since the file is used by
my_open() in Load_log_processor::append().
*/
convert_path_to_forward_slashes((char*) ce->fname);
ce->print(result_file, print_event_info, TRUE);
my_free((void*)ce->fname);
delete ce;
if (head->error == -1)
goto err;
}
else
warning("Ignoring Execute_load_log_event as there is no "
"Create_file event for file_id: %u", exv->file_id);
break;
}
case FORMAT_DESCRIPTION_EVENT:
delete glob_description_event;
glob_description_event= (Format_description_log_event*) ev;
print_event_info->common_header_len=
glob_description_event->common_header_len;
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
if (opt_remote_proto == BINLOG_LOCAL)
{
ev->free_temp_buf(); // free memory allocated in dump_local_log_entries
}
else
{
/*
disassociate but not free dump_remote_log_entries time memory
*/
ev->temp_buf= 0;
}
/*
We don't want this event to be deleted now, so let's hide it (I
(Guilhem) should later see if this triggers a non-serious Valgrind
error). Not serious error, because we will free description_event
later.
*/
ev= 0;
if (!force_if_open_opt &&
(glob_description_event->flags & LOG_EVENT_BINLOG_IN_USE_F))
{
error("Attempting to dump binlog '%s', which was not closed properly. "
"Most probably, mysqld is still writing it, or it crashed. "
"Rerun with --force-if-open to ignore this problem.", logname);
DBUG_RETURN(ERROR_STOP);
}
break;
case BEGIN_LOAD_QUERY_EVENT:
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
if ((retval= load_processor.process((Begin_load_query_log_event*) ev)) !=
OK_CONTINUE)
goto end;
break;
case EXECUTE_LOAD_QUERY_EVENT:
{
Execute_load_query_log_event *exlq= (Execute_load_query_log_event*)ev;
char *fname= load_processor.grab_fname(exlq->file_id);
if (shall_skip_database(exlq->db))
print_event_info->skipped_event_in_transaction= true;
else
{
if (fname)
{
convert_path_to_forward_slashes(fname);
exlq->print(result_file, print_event_info, fname);
if (head->error == -1)
{
if (fname)
my_free(fname);
goto err;
}
}
else
warning("Ignoring Execute_load_query since there is no "
"Begin_load_query event for file_id: %u", exlq->file_id);
}
if (fname)
my_free(fname);
break;
}
case TABLE_MAP_EVENT:
{
Table_map_log_event *map= ((Table_map_log_event *)ev);
if (shall_skip_database(map->get_db_name()))
{
print_event_info->skipped_event_in_transaction= true;
print_event_info->m_table_map_ignored.set_table(map->get_table_id(), map);
destroy_evt= FALSE;
goto end;
}
}
case ROWS_QUERY_LOG_EVENT:
case WRITE_ROWS_EVENT:
case DELETE_ROWS_EVENT:
case UPDATE_ROWS_EVENT:
case WRITE_ROWS_EVENT_V1:
case UPDATE_ROWS_EVENT_V1:
case DELETE_ROWS_EVENT_V1:
case PRE_GA_WRITE_ROWS_EVENT:
case PRE_GA_DELETE_ROWS_EVENT:
case PRE_GA_UPDATE_ROWS_EVENT:
{
bool stmt_end= FALSE;
Table_map_log_event *ignored_map= NULL;
if (ev_type == WRITE_ROWS_EVENT ||
ev_type == DELETE_ROWS_EVENT ||
ev_type == UPDATE_ROWS_EVENT ||
ev_type == WRITE_ROWS_EVENT_V1 ||
ev_type == DELETE_ROWS_EVENT_V1 ||
ev_type == UPDATE_ROWS_EVENT_V1)
{
Rows_log_event *new_ev= (Rows_log_event*) ev;
if (new_ev->get_flags(Rows_log_event::STMT_END_F))
stmt_end= TRUE;
ignored_map= print_event_info->m_table_map_ignored.get_table(new_ev->get_table_id());
}
else if (ev_type == PRE_GA_WRITE_ROWS_EVENT ||
ev_type == PRE_GA_DELETE_ROWS_EVENT ||
ev_type == PRE_GA_UPDATE_ROWS_EVENT)
{
Old_rows_log_event *old_ev= (Old_rows_log_event*) ev;
if (old_ev->get_flags(Rows_log_event::STMT_END_F))
stmt_end= TRUE;
ignored_map= print_event_info->m_table_map_ignored.get_table(old_ev->get_table_id());
}
bool skip_event= (ignored_map != NULL);
/*
end of statement check:
i) destroy/free ignored maps
ii) if skip event
a) set the unflushed_events flag to false
b) since we are skipping the last event,
append END-MARKER(') to body cache (if required)
c) flush cache now
*/
if (stmt_end)
{
/*
Now is safe to clear ignored map (clear_tables will also
delete original table map events stored in the map).
*/
if (print_event_info->m_table_map_ignored.count() > 0)
print_event_info->m_table_map_ignored.clear_tables();
/*
One needs to take into account an event that gets
filtered but was last event in the statement. If this is
the case, previous rows events that were written into
IO_CACHEs still need to be copied from cache to
result_file (as it would happen in ev->print(...) if
event was not skipped).
*/
if (skip_event)
{
// set the unflushed_events flag to false
print_event_info->have_unflushed_events= FALSE;
// append END-MARKER(') with delimiter
IO_CACHE *const body_cache= &print_event_info->body_cache;
if (my_b_tell(body_cache))
my_b_printf(body_cache, "'%s\n", print_event_info->delimiter);
// flush cache
if ((copy_event_cache_to_file_and_reinit(&print_event_info->head_cache,
result_file, stop_never /* flush result_file */) ||
copy_event_cache_to_file_and_reinit(&print_event_info->body_cache,
result_file, stop_never /* flush result_file */)))
goto err;
}
}
/* skip the event check */
if (skip_event)
{
print_event_info->skipped_event_in_transaction= true;
goto end;
}
/*
These events must be printed in base64 format, if printed.
base64 format requires a FD event to be safe, so if no FD
event has been printed, we give an error. Except if user
passed --short-form, because --short-form disables printing
row events.
*/
if (!print_event_info->printed_fd_event && !short_form &&
ev_type != TABLE_MAP_EVENT && ev_type != ROWS_QUERY_LOG_EVENT &&
opt_base64_output_mode != BASE64_OUTPUT_DECODE_ROWS)
{
const char* type_str= ev->get_type_str();
if (opt_base64_output_mode == BASE64_OUTPUT_NEVER)
error("--base64-output=never specified, but binlog contains a "
"%s event which must be printed in base64.",
type_str);
else
error("malformed binlog: it does not contain any "
"Format_description_log_event. I now found a %s event, which "
"is not safe to process without a "
"Format_description_log_event.",
type_str);
goto err;
}
ev->print(result_file, print_event_info);
print_event_info->have_unflushed_events= TRUE;
/* Flush head and body cache to result_file */
if (stmt_end)
{
print_event_info->have_unflushed_events= FALSE;
if (copy_event_cache_to_file_and_reinit(&print_event_info->head_cache,
result_file, stop_never /* flush result file */) ||
copy_event_cache_to_file_and_reinit(&print_event_info->body_cache,
result_file, stop_never /* flush result file */))
goto err;
goto end;
}
break;
}
case ANONYMOUS_GTID_LOG_EVENT:
case GTID_LOG_EVENT:
{
seen_gtids= true;
print_event_info->is_gtid_next_set= true;
print_event_info->is_gtid_next_valid= true;
if (print_event_info->skipped_event_in_transaction == true)
fprintf(result_file, "COMMIT /* added by mysqlbinlog */%s\n", print_event_info->delimiter);
print_event_info->skipped_event_in_transaction= false;
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
break;
}
case XID_EVENT:
{
in_transaction= false;
print_event_info->skipped_event_in_transaction= false;
if (print_event_info->is_gtid_next_set)
print_event_info->is_gtid_next_valid= false;
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
break;
}
case ROTATE_EVENT:
{
Rotate_log_event *rev= (Rotate_log_event *) ev;
/* no transaction context, gtids seen and not a fake rotate */
if (seen_gtids)
{
/*
Fake rotate events have 'when' set to zero. @c fake_rotate_event(...).
*/
bool is_fake= (rev->when.tv_sec == 0);
if (!in_transaction && !is_fake)
{
/*
If processing multiple files, we must reset this flag,
since there may be no gtids on the next one.
*/
seen_gtids= false;
fprintf(result_file, "%sAUTOMATIC' /* added by mysqlbinlog */ %s\n",
Gtid_log_event::SET_STRING_PREFIX,
print_event_info->delimiter);
print_event_info->is_gtid_next_set= false;
print_event_info->is_gtid_next_valid= true;
}
}
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
break;
}
case PREVIOUS_GTIDS_LOG_EVENT:
if (one_database && !opt_skip_gtids)
warning("The option --database has been used. It may filter "
"parts of transactions, but will include the GTIDs in "
"any case. If you want to exclude or include transactions, "
"you should use the options --exclude-gtids or "
"--include-gtids, respectively, instead.");
/* fall through */
default:
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
}
/* Flush head cache to result_file for every event */
if (copy_event_cache_to_file_and_reinit(&print_event_info->head_cache,
result_file, stop_never /* flush result_file */))
goto err;
}
goto end;
err:
retval= ERROR_STOP;
end:
rec_count++;
/*
Destroy the log_event object. If reading from a remote host,
set the temp_buf to NULL so that memory isn't freed twice.
*/
if (ev)
{
if (opt_remote_proto != BINLOG_LOCAL)
ev->temp_buf= 0;
if (destroy_evt) /* destroy it later if not set (ignored table map) */
delete ev;
}
DBUG_RETURN(retval);
}
static struct my_option my_long_options[] =
{
{"help", '?', "Display this help and exit.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"base64-output", OPT_BASE64_OUTPUT_MODE,
/* 'unspec' is not mentioned because it is just a placeholder. */
"Determine when the output statements should be base64-encoded BINLOG "
"statements: 'never' disables it and works only for binlogs without "
"row-based events; 'decode-rows' decodes row events into commented pseudo-SQL "
"statements if the --verbose option is also given; 'auto' prints base64 "
"only when necessary (i.e., for row-based events and format description "
"events). If no --base64-output[=name] option is given at all, the "
"default is 'auto'.",
&opt_base64_output_mode_str, &opt_base64_output_mode_str,
0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"bind-address", 0, "IP address to bind to.",
(uchar**) &opt_bind_addr, (uchar**) &opt_bind_addr, 0, GET_STR,
REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
/*
mysqlbinlog needs charsets knowledge, to be able to convert a charset
number found in binlog to a charset name (to be able to print things
like this:
SET @`a`:=_cp850 0x4DFC6C6C6572 COLLATE `cp850_general_ci`;
*/
{"character-sets-dir", OPT_CHARSETS_DIR,
"Directory for character set files.", &charsets_dir,
&charsets_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"database", 'd', "List entries for just this database (local log only).",
&database, &database, 0, GET_STR_ALLOC, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
#ifndef DBUG_OFF
{"debug", '#', "Output debug log.", &default_dbug_option,
&default_dbug_option, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
#endif
{"debug-check", OPT_DEBUG_CHECK, "Check memory and open file usage at exit .",
&debug_check_flag, &debug_check_flag, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"debug-info", OPT_DEBUG_INFO, "Print some debug info at exit.",
&debug_info_flag, &debug_info_flag,
0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"default_auth", OPT_DEFAULT_AUTH,
"Default authentication client-side plugin to use.",
&opt_default_auth, &opt_default_auth, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"disable-log-bin", 'D', "Disable binary log. This is useful, if you "
"enabled --to-last-log and are sending the output to the same MySQL server. "
"This way you could avoid an endless loop. You would also like to use it "
"when restoring after a crash to avoid duplication of the statements you "
"already have. NOTE: you will need a SUPER privilege to use this option.",
&disable_log_bin, &disable_log_bin, 0, GET_BOOL,
NO_ARG, 0, 0, 0, 0, 0, 0},
{"force-if-open", 'F', "Force if binlog was not closed properly.",
&force_if_open_opt, &force_if_open_opt, 0, GET_BOOL, NO_ARG,
1, 0, 0, 0, 0, 0},
{"force-read", 'f', "Force reading unknown binlog events.",
&force_opt, &force_opt, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0,
0, 0},
{"hexdump", 'H', "Augment output with hexadecimal and ASCII event dump.",
&opt_hexdump, &opt_hexdump, 0, GET_BOOL, NO_ARG,
0, 0, 0, 0, 0, 0},
{"host", 'h', "Get the binlog from server.", &host, &host,
0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"local-load", 'l', "Prepare local temporary files for LOAD DATA INFILE in the specified directory.",
&dirname_for_local_load, &dirname_for_local_load, 0,
GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"offset", 'o', "Skip the first N entries.", &offset, &offset,
0, GET_ULL, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"password", 'p', "Password to connect to remote server.",
0, 0, 0, GET_PASSWORD, OPT_ARG, 0, 0, 0, 0, 0, 0},
{"plugin_dir", OPT_PLUGIN_DIR, "Directory for client-side plugins.",
&opt_plugin_dir, &opt_plugin_dir, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"port", 'P', "Port number to use for connection or 0 for default to, in "
"order of preference, my.cnf, $MYSQL_TCP_PORT, "
#if MYSQL_PORT_DEFAULT == 0
"/etc/services, "
#endif
"built-in default (" STRINGIFY_ARG(MYSQL_PORT) ").",
&port, &port, 0, GET_INT, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"protocol", OPT_MYSQL_PROTOCOL,
"The protocol to use for connection (tcp, socket, pipe, memory).",
0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"read-from-remote-server", 'R', "Read binary logs from a MySQL server. "
"This is an alias for read-from-remote-master=BINLOG-DUMP-NON-GTIDS.",
&opt_remote_alias, &opt_remote_alias, 0, GET_BOOL, NO_ARG,
0, 0, 0, 0, 0, 0},
{"read-from-remote-master", OPT_REMOTE_PROTO,
"Read binary logs from a MySQL server through the COM_BINLOG_DUMP or "
"COM_BINLOG_DUMP_GTID commands by setting the option to either "
"BINLOG-DUMP-NON-GTIDS or BINLOG-DUMP-GTIDS, respectively. If "
"--read-from-remote-master=BINLOG-DUMP-GTIDS is combined with "
"--exclude-gtids, transactions can be filtered out on the master "
"avoiding unnecessary network traffic.",
&opt_remote_proto_str, &opt_remote_proto_str, 0, GET_STR, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"raw", OPT_RAW_OUTPUT, "Requires -R. Output raw binlog data instead of SQL "
"statements, output is to log files.",
&raw_mode, &raw_mode, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0,
0, 0},
{"result-file", 'r', "Direct output to a given file. With --raw this is a "
"prefix for the file names.",
&output_file, &output_file, 0, GET_STR, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"secure-auth", OPT_SECURE_AUTH, "Refuse client connecting to server if it"
" uses old (pre-4.1.1) protocol.", &opt_secure_auth,
&opt_secure_auth, 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0},
{"server-id", OPT_SERVER_ID,
"Extract only binlog entries created by the server having the given id.",
&filter_server_id, &filter_server_id, 0, GET_ULONG,
REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"server-id-bits", 0,
"Set number of significant bits in server-id",
&opt_server_id_bits, &opt_server_id_bits,
/* Default + Max 32 bits, minimum 7 bits */
0, GET_UINT, REQUIRED_ARG, 32, 7, 32, 0, 0, 0},
{"set-charset", OPT_SET_CHARSET,
"Add 'SET NAMES character_set' to the output.", &charset,
&charset, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#ifdef HAVE_SMEM
{"shared-memory-base-name", OPT_SHARED_MEMORY_BASE_NAME,
"Base name of shared memory.", &shared_memory_base_name,
&shared_memory_base_name,
0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#endif
{"short-form", 's', "Just show regular queries: no extra info and no "
"row-based events. This is for testing only, and should not be used in "
"production systems. If you want to suppress base64-output, consider "
"using --base64-output=never instead.",
&short_form, &short_form, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0,
0, 0},
{"socket", 'S', "The socket file to use for connection.",
&sock, &sock, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0,
0, 0},
{"start-datetime", OPT_START_DATETIME,
"Start reading the binlog at first event having a datetime equal or "
"posterior to the argument; the argument must be a date and time "
"in the local time zone, in any format accepted by the MySQL server "
"for DATETIME and TIMESTAMP types, for example: 2004-12-25 11:25:56 "
"(you should probably use quotes for your shell to set it properly).",
&start_datetime_str, &start_datetime_str,
0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"start-position", 'j',
"Start reading the binlog at position N. Applies to the first binlog "
"passed on the command line.",
&start_position, &start_position, 0, GET_ULL,
REQUIRED_ARG, BIN_LOG_HEADER_SIZE, BIN_LOG_HEADER_SIZE,
/* COM_BINLOG_DUMP accepts only 4 bytes for the position */
(ulonglong)(~(uint32)0), 0, 0, 0},
{"stop-datetime", OPT_STOP_DATETIME,
"Stop reading the binlog at first event having a datetime equal or "
"posterior to the argument; the argument must be a date and time "
"in the local time zone, in any format accepted by the MySQL server "
"for DATETIME and TIMESTAMP types, for example: 2004-12-25 11:25:56 "
"(you should probably use quotes for your shell to set it properly).",
&stop_datetime_str, &stop_datetime_str,
0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"stop-never", OPT_STOP_NEVER, "Wait for more data from the server "
"instead of stopping at the end of the last log. Implicitly sets "
"--to-last-log but instead of stopping at the end of the last log "
"it continues to wait till the server disconnects.",
&stop_never, &stop_never, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"stop-never-slave-server-id", OPT_WAIT_SERVER_ID,
"The slave server_id used for --read-from-remote-server --stop-never.",
&stop_never_slave_server_id, &stop_never_slave_server_id, 0,
GET_LL, REQUIRED_ARG, -1, -1, 0xFFFFFFFFLL, 0, 0, 0},
#ifndef DBUG_OFF
{"connection-server-id", OPT_CONNECTION_SERVER_ID,
"The slave server_id used for --read-from-remote-server.",
&connection_server_id, &connection_server_id, 0,
GET_LL, REQUIRED_ARG, -1, -1, 0xFFFFFFFFLL, 0, 0, 0},
#endif
{"stop-position", OPT_STOP_POSITION,
"Stop reading the binlog at position N. Applies to the last binlog "
"passed on the command line.",
&stop_position, &stop_position, 0, GET_ULL,
REQUIRED_ARG, (longlong)(~(my_off_t)0), BIN_LOG_HEADER_SIZE,
(ulonglong)(~(my_off_t)0), 0, 0, 0},
{"to-last-log", 't', "Requires -R. Will not stop at the end of the "
"requested binlog but rather continue printing until the end of the last "
"binlog of the MySQL server. If you send the output to the same MySQL "
"server, that may lead to an endless loop.",
&to_last_remote_log, &to_last_remote_log, 0, GET_BOOL,
NO_ARG, 0, 0, 0, 0, 0, 0},
{"user", 'u', "Connect to the remote server as username.",
&user, &user, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0,
0, 0},
{"verbose", 'v', "Reconstruct pseudo-SQL statements out of row events. "
"-v -v adds comments on column data types.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"version", 'V', "Print version and exit.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0,
0, 0, 0, 0, 0},
{"open_files_limit", OPT_OPEN_FILES_LIMIT,
"Used to reserve file descriptors for use by this program.",
&open_files_limit, &open_files_limit, 0, GET_ULONG,
REQUIRED_ARG, MY_NFILE, 8, OS_FILE_LIMIT, 0, 1, 0},
{"verify-binlog-checksum", 'c', "Verify checksum binlog events.",
(uchar**) &opt_verify_binlog_checksum, (uchar**) &opt_verify_binlog_checksum,
0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"binlog-row-event-max-size", OPT_BINLOG_ROWS_EVENT_MAX_SIZE,
"The maximum size of a row-based binary log event in bytes. Rows will be "
"grouped into events smaller than this size if possible. "
"This value must be a multiple of 256.",
&opt_binlog_rows_event_max_size,
&opt_binlog_rows_event_max_size, 0,
GET_ULONG, REQUIRED_ARG,
/* def_value 4GB */ UINT_MAX, /* min_value */ 256,
/* max_value */ ULONG_MAX, /* sub_size */ 0,
/* block_size */ 256, /* app_type */ 0},
{"skip-gtids", OPT_MYSQLBINLOG_SKIP_GTIDS,
"Do not print Global Transaction Identifier information "
"(SET GTID_NEXT=... etc).",
&opt_skip_gtids, &opt_skip_gtids, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"include-gtids", OPT_MYSQLBINLOG_INCLUDE_GTIDS,
"Print events whose Global Transaction Identifiers "
"were provided.",
&opt_include_gtids_str, &opt_include_gtids_str, 0,
GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"exclude-gtids", OPT_MYSQLBINLOG_EXCLUDE_GTIDS,
"Print all events but those whose Global Transaction "
"Identifiers were provided.",
&opt_exclude_gtids_str, &opt_exclude_gtids_str, 0,
GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
};
/**
Auxiliary function used by error() and warning().
Prints the given text (normally "WARNING: " or "ERROR: "), followed
by the given vprintf-style string, followed by a newline.
@param format Printf-style format string.
@param args List of arguments for the format string.
@param msg Text to print before the string.
*/
static void error_or_warning(const char *format, va_list args, const char *msg)
{
fprintf(stderr, "%s: ", msg);
vfprintf(stderr, format, args);
fprintf(stderr, "\n");
}
/**
Prints a message to stderr, prefixed with the text "ERROR: " and
suffixed with a newline.
@param format Printf-style format string, followed by printf
varargs.
*/
static void error(const char *format,...)
{
va_list args;
va_start(args, format);
error_or_warning(format, args, "ERROR");
va_end(args);
}
/**
This function is used in log_event.cc to report errors.
@param format Printf-style format string, followed by printf
varargs.
*/
static void sql_print_error(const char *format,...)
{
va_list args;
va_start(args, format);
error_or_warning(format, args, "ERROR");
va_end(args);
}
/**
Prints a message to stderr, prefixed with the text "WARNING: " and
suffixed with a newline.
@param format Printf-style format string, followed by printf
varargs.
*/
static void warning(const char *format,...)
{
va_list args;
va_start(args, format);
error_or_warning(format, args, "WARNING");
va_end(args);
}
/**
Frees memory for global variables in this file.
*/
static void cleanup()
{
my_free(pass);
my_free(database);
my_free(host);
my_free(user);
my_free(dirname_for_local_load);
for (uint i= 0; i < buff_ev.elements; i++)
{
buff_event_info pop_event_array= *dynamic_element(&buff_ev, i, buff_event_info *);
delete (pop_event_array.event);
}
delete_dynamic(&buff_ev);
delete glob_description_event;
if (mysql)
mysql_close(mysql);
}
static void print_version()
{
printf("%s Ver 3.4 for %s at %s\n", my_progname, SYSTEM_TYPE, MACHINE_TYPE);
}
static void usage()
{
print_version();
puts(ORACLE_WELCOME_COPYRIGHT_NOTICE("2000"));
printf("\
Dumps a MySQL binary log in a format usable for viewing or for piping to\n\
the mysql command line client.\n\n");
printf("Usage: %s [options] log-files\n", my_progname);
my_print_help(my_long_options);
my_print_variables(my_long_options);
}
static my_time_t convert_str_to_timestamp(const char* str)
{
MYSQL_TIME_STATUS status;
MYSQL_TIME l_time;
long dummy_my_timezone;
my_bool dummy_in_dst_time_gap;
/* We require a total specification (date AND time) */
if (str_to_datetime(str, (uint) strlen(str), &l_time, 0, &status) ||
l_time.time_type != MYSQL_TIMESTAMP_DATETIME || status.warnings)
{
error("Incorrect date and time argument: %s", str);
exit(1);
}
/*
Note that Feb 30th, Apr 31st cause no error messages and are mapped to
the next existing day, like in mysqld. Maybe this could be changed when
mysqld is changed too (with its "strict" mode?).
*/
return
my_system_gmt_sec(&l_time, &dummy_my_timezone, &dummy_in_dst_time_gap);
}
extern "C" my_bool
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
char *argument)
{
bool tty_password=0;
switch (optid) {
#ifndef DBUG_OFF
case '#':
DBUG_PUSH(argument ? argument : default_dbug_option);
break;
#endif
case 'd':
one_database = 1;
break;
case 'p':
if (argument == disabled_my_option)
argument= (char*) ""; // Don't require password
if (argument)
{
my_free(pass);
char *start=argument;
pass= my_strdup(argument,MYF(MY_FAE));
while (*argument) *argument++= 'x'; /* Destroy argument */
if (*start)
start[1]=0; /* Cut length of argument */
}
else
tty_password=1;
break;
case 'R':
opt_remote_alias= 1;
opt_remote_proto= BINLOG_DUMP_NON_GTID;
break;
case OPT_REMOTE_PROTO:
opt_remote_proto= (enum_remote_proto)
(find_type_or_exit(argument, &remote_proto_typelib, opt->name) - 1);
break;
case OPT_MYSQL_PROTOCOL:
opt_protocol= find_type_or_exit(argument, &sql_protocol_typelib,
opt->name);
break;
case OPT_START_DATETIME:
start_datetime= convert_str_to_timestamp(start_datetime_str);
break;
case OPT_STOP_DATETIME:
stop_datetime= convert_str_to_timestamp(stop_datetime_str);
break;
case OPT_BASE64_OUTPUT_MODE:
opt_base64_output_mode= (enum_base64_output_mode)
(find_type_or_exit(argument, &base64_output_mode_typelib, opt->name)-1);
break;
case 'v':
if (argument == disabled_my_option)
verbose= 0;
else
verbose++;
break;
case 'V':
print_version();
exit(0);
case OPT_STOP_NEVER:
/* wait-for-data implicitly sets to-last-log */
to_last_remote_log= 1;
break;
case '?':
usage();
exit(0);
}
if (tty_password)
pass= get_tty_password(NullS);
return 0;
}
static int parse_args(int *argc, char*** argv)
{
int ho_error;
result_file = stdout;
if ((ho_error=handle_options(argc, argv, my_long_options, get_one_option)))
exit(ho_error);
if (debug_info_flag)
my_end_arg= MY_CHECK_ERROR | MY_GIVE_INFO;
if (debug_check_flag)
my_end_arg= MY_CHECK_ERROR;
return 0;
}
/**
Create and initialize the global mysql object, and connect to the
server.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
*/
static Exit_status safe_connect()
{
mysql= mysql_init(NULL);
if (!mysql)
{
error("Failed on mysql_init.");
return ERROR_STOP;
}
if (opt_plugin_dir && *opt_plugin_dir)
mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);
if (opt_default_auth && *opt_default_auth)
mysql_options(mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);
if (opt_protocol)
mysql_options(mysql, MYSQL_OPT_PROTOCOL, (char*) &opt_protocol);
if (opt_bind_addr)
mysql_options(mysql, MYSQL_OPT_BIND, opt_bind_addr);
if (!opt_secure_auth)
mysql_options(mysql, MYSQL_SECURE_AUTH,(char*)&opt_secure_auth);
#ifdef HAVE_SMEM
if (shared_memory_base_name)
mysql_options(mysql, MYSQL_SHARED_MEMORY_BASE_NAME,
shared_memory_base_name);
#endif
mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0);
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD,
"program_name", "mysqlbinlog");
if (!mysql_real_connect(mysql, host, user, pass, 0, port, sock, 0))
{
error("Failed on connect: %s", mysql_error(mysql));
return ERROR_STOP;
}
mysql->reconnect= 1;
return OK_CONTINUE;
}
/**
High-level function for dumping a named binlog.
This function calls dump_remote_log_entries() or
dump_local_log_entries() to do the job.
@param[in] logname Name of input binlog.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
@retval OK_STOP No error, but the end of the specified range of
events to process has been reached and the program should terminate.
*/
static Exit_status dump_single_log(PRINT_EVENT_INFO *print_event_info,
const char* logname)
{
DBUG_ENTER("dump_single_log");
Exit_status rc= OK_CONTINUE;
switch (opt_remote_proto)
{
case BINLOG_LOCAL:
rc= dump_local_log_entries(print_event_info, logname);
break;
case BINLOG_DUMP_NON_GTID:
case BINLOG_DUMP_GTID:
rc= dump_remote_log_entries(print_event_info, logname);
break;
default:
DBUG_ASSERT(0);
break;
}
DBUG_RETURN(rc);
}
static Exit_status dump_multiple_logs(int argc, char **argv)
{
DBUG_ENTER("dump_multiple_logs");
Exit_status rc= OK_CONTINUE;
PRINT_EVENT_INFO print_event_info;
if (!print_event_info.init_ok())
DBUG_RETURN(ERROR_STOP);
/*
Set safe delimiter, to dump things
like CREATE PROCEDURE safely
*/
if (!raw_mode)
{
fprintf(result_file, "DELIMITER /*!*/;\n");
}
strmov(print_event_info.delimiter, "/*!*/;");
print_event_info.verbose= short_form ? 0 : verbose;
// Dump all logs.
my_off_t save_stop_position= stop_position;
stop_position= ~(my_off_t)0;
for (int i= 0; i < argc; i++)
{
if (i == argc - 1) // last log, --stop-position applies
stop_position= save_stop_position;
if ((rc= dump_single_log(&print_event_info, argv[i])) != OK_CONTINUE)
break;
// For next log, --start-position does not apply
start_position= BIN_LOG_HEADER_SIZE;
}
if (buff_ev.elements > 0)
warning("The range of printed events ends with an Intvar_event, "
"Rand_event or User_var_event with no matching Query_log_event. "
"This might be because the last statement was not fully written "
"to the log, or because you are using a --stop-position or "
"--stop-datetime that refers to an event in the middle of a "
"statement. The event(s) from the partial statement have not been "
"written to output. ");
else if (print_event_info.have_unflushed_events)
warning("The range of printed events ends with a row event or "
"a table map event that does not have the STMT_END_F "
"flag set. This might be because the last statement "
"was not fully written to the log, or because you are "
"using a --stop-position or --stop-datetime that refers "
"to an event in the middle of a statement. The event(s) "
"from the partial statement have not been written to output.");
/* Set delimiter back to semicolon */
if (!raw_mode)
{
if (print_event_info.skipped_event_in_transaction)
fprintf(result_file, "COMMIT /* added by mysqlbinlog */%s\n", print_event_info.delimiter);
if (!print_event_info.is_gtid_next_valid)
{
fprintf(result_file, "%sAUTOMATIC' /* added by mysqlbinlog */%s\n",
Gtid_log_event::SET_STRING_PREFIX,
print_event_info.delimiter);
print_event_info.is_gtid_next_set= false;
print_event_info.is_gtid_next_valid= true;
}
fprintf(result_file, "DELIMITER ;\n");
strmov(print_event_info.delimiter, ";");
}
DBUG_RETURN(rc);
}
/**
When reading a remote binlog, this function is used to grab the
Format_description_log_event in the beginning of the stream.
This is not as smart as check_header() (used for local log); it will
not work for a binlog which mixes format. TODO: fix this.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
*/
static Exit_status check_master_version()
{
DBUG_ENTER("check_master_version");
MYSQL_RES* res = 0;
MYSQL_ROW row;
const char* version;
if (mysql_query(mysql, "SELECT VERSION()") ||
!(res = mysql_store_result(mysql)))
{
error("Could not find server version: "
"Query failed when checking master version: %s", mysql_error(mysql));
DBUG_RETURN(ERROR_STOP);
}
if (!(row = mysql_fetch_row(res)))
{
error("Could not find server version: "
"Master returned no rows for SELECT VERSION().");
goto err;
}
if (!(version = row[0]))
{
error("Could not find server version: "
"Master reported NULL for the version.");
goto err;
}
/*
Make a notice to the server that this client
is checksum-aware. It does not need the first fake Rotate
necessary checksummed.
That preference is specified below.
*/
if (mysql_query(mysql, "SET @master_binlog_checksum='NONE'"))
{
error("Could not notify master about checksum awareness."
"Master returned '%s'", mysql_error(mysql));
goto err;
}
delete glob_description_event;
switch (*version) {
case '3':
glob_description_event= new Format_description_log_event(1);
break;
case '4':
glob_description_event= new Format_description_log_event(3);
break;
case '5':
/*
The server is soon going to send us its Format_description log
event, unless it is a 5.0 server with 3.23 or 4.0 binlogs.
So we first assume that this is 4.0 (which is enough to read the
Format_desc event if one comes).
*/
glob_description_event= new Format_description_log_event(3);
break;
default:
glob_description_event= NULL;
error("Could not find server version: "
"Master reported unrecognized MySQL version '%s'.", version);
goto err;
}
if (!glob_description_event || !glob_description_event->is_valid())
{
error("Failed creating Format_description_log_event; out of memory?");
goto err;
}
mysql_free_result(res);
DBUG_RETURN(OK_CONTINUE);
err:
mysql_free_result(res);
DBUG_RETURN(ERROR_STOP);
}
static int get_dump_flags()
{
return stop_never ? 0 : BINLOG_DUMP_NON_BLOCK;
}
/**
Requests binlog dump from a remote server and prints the events it
receives.
@param[in,out] print_event_info Parameters and context state
determining how to print.
@param[in] logname Name of input binlog.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
@retval OK_STOP No error, but the end of the specified range of
events to process has been reached and the program should terminate.
*/
static Exit_status dump_remote_log_entries(PRINT_EVENT_INFO *print_event_info,
const char* logname)
{
uchar *command_buffer= NULL;
size_t command_size= 0;
ulong len= 0;
uint logname_len= 0;
uint server_id= 0;
NET* net= NULL;
my_off_t old_off= start_position_mot;
char fname[FN_REFLEN + 1];
char log_file_name[FN_REFLEN + 1];
Exit_status retval= OK_CONTINUE;
enum enum_server_command command= COM_END;
DBUG_ENTER("dump_remote_log_entries");
fname[0]= log_file_name[0]= 0;
/*
Even if we already read one binlog (case of >=2 binlogs on command line),
we cannot re-use the same connection as before, because it is now dead
(COM_BINLOG_DUMP kills the thread when it finishes).
*/
if ((retval= safe_connect()) != OK_CONTINUE)
DBUG_RETURN(retval);
net= &mysql->net;
if ((retval= check_master_version()) != OK_CONTINUE)
DBUG_RETURN(retval);
/*
Fake a server ID to log continously. This will show as a
slave on the mysql server.
*/
if (to_last_remote_log && stop_never)
{
if (stop_never_slave_server_id == -1)
server_id= 1;
else
server_id= stop_never_slave_server_id;
}
else
server_id= 0;
#ifndef DBUG_OFF
if (connection_server_id != -1)
server_id= connection_server_id;
#endif
size_t tlen = strlen(logname);
if (tlen > UINT_MAX)
{
error("Log name too long.");
DBUG_RETURN(ERROR_STOP);
}
const uint BINLOG_NAME_INFO_SIZE= logname_len= tlen;
if (opt_remote_proto == BINLOG_DUMP_NON_GTID)
{
command= COM_BINLOG_DUMP;
size_t allocation_size= ::BINLOG_POS_OLD_INFO_SIZE +
BINLOG_NAME_INFO_SIZE + ::BINLOG_FLAGS_INFO_SIZE +
::BINLOG_SERVER_ID_INFO_SIZE + 1;
if (!(command_buffer= (uchar *) my_malloc(allocation_size, MYF(MY_WME))))
{
error("Got fatal error allocating memory.");
DBUG_RETURN(ERROR_STOP);
}
uchar* ptr_buffer= command_buffer;
/*
COM_BINLOG_DUMP accepts only 4 bytes for the position, so
we are forced to cast to uint32.
*/
int4store(ptr_buffer, (uint32) start_position);
ptr_buffer+= ::BINLOG_POS_OLD_INFO_SIZE;
int2store(ptr_buffer, get_dump_flags());
ptr_buffer+= ::BINLOG_FLAGS_INFO_SIZE;
int4store(ptr_buffer, server_id);
ptr_buffer+= ::BINLOG_SERVER_ID_INFO_SIZE;
memcpy(ptr_buffer, logname, BINLOG_NAME_INFO_SIZE);
ptr_buffer+= BINLOG_NAME_INFO_SIZE;
command_size= ptr_buffer - command_buffer;
DBUG_ASSERT(command_size == (allocation_size - 1));
}
else
{
command= COM_BINLOG_DUMP_GTID;
global_sid_lock->rdlock();
// allocate buffer
size_t encoded_data_size= gtid_set_excluded->get_encoded_length();
size_t allocation_size=
::BINLOG_FLAGS_INFO_SIZE + ::BINLOG_SERVER_ID_INFO_SIZE +
::BINLOG_NAME_SIZE_INFO_SIZE + BINLOG_NAME_INFO_SIZE +
::BINLOG_POS_INFO_SIZE + ::BINLOG_DATA_SIZE_INFO_SIZE +
encoded_data_size + 1;
if (!(command_buffer= (uchar *) my_malloc(allocation_size, MYF(MY_WME))))
{
error("Got fatal error allocating memory.");
global_sid_lock->unlock();
DBUG_RETURN(ERROR_STOP);
}
uchar* ptr_buffer= command_buffer;
int2store(ptr_buffer, get_dump_flags());
ptr_buffer+= ::BINLOG_FLAGS_INFO_SIZE;
int4store(ptr_buffer, server_id);
ptr_buffer+= ::BINLOG_SERVER_ID_INFO_SIZE;
int4store(ptr_buffer, BINLOG_NAME_INFO_SIZE);
ptr_buffer+= ::BINLOG_NAME_SIZE_INFO_SIZE;
memcpy(ptr_buffer, logname, BINLOG_NAME_INFO_SIZE);
ptr_buffer+= BINLOG_NAME_INFO_SIZE;
int8store(ptr_buffer, start_position);
ptr_buffer+= ::BINLOG_POS_INFO_SIZE;
int4store(ptr_buffer, encoded_data_size);
ptr_buffer+= ::BINLOG_DATA_SIZE_INFO_SIZE;
gtid_set_excluded->encode(ptr_buffer);
ptr_buffer+= encoded_data_size;
global_sid_lock->unlock();
command_size= ptr_buffer - command_buffer;
DBUG_ASSERT(command_size == (allocation_size - 1));
}
if (simple_command(mysql, command, command_buffer, command_size, 1))
{
error("Got fatal error sending the log dump command.");
my_free(command_buffer);
DBUG_RETURN(ERROR_STOP);
}
my_free(command_buffer);
for (;;)
{
const char *error_msg= NULL;
Log_event *ev= NULL;
Log_event_type type= UNKNOWN_EVENT;
len= cli_safe_read(mysql);
if (len == packet_error)
{
error("Got error reading packet from server: %s", mysql_error(mysql));
DBUG_RETURN(ERROR_STOP);
}
if (len < 8 && net->read_pos[0] == 254)
break; // end of data
DBUG_PRINT("info",( "len: %lu net->read_pos[5]: %d\n",
len, net->read_pos[5]));
/*
In raw mode We only need the full event details if it is a
ROTATE_EVENT or FORMAT_DESCRIPTION_EVENT
*/
type= (Log_event_type) net->read_pos[1 + EVENT_TYPE_OFFSET];
/*
Ignore HEARBEAT events. They can show up if mysqlbinlog is
running with:
--read-from-remote-server
--read-from-remote-master=BINLOG-DUMP-GTIDS'
--stop-never
--stop-never-slave-server-id
i.e., acting as a fake slave.
*/
if (type == HEARTBEAT_LOG_EVENT)
continue;
if (!raw_mode || (type == ROTATE_EVENT) || (type == FORMAT_DESCRIPTION_EVENT))
{
if (!(ev= Log_event::read_log_event((const char*) net->read_pos + 1 ,
len - 1, &error_msg,
glob_description_event,
opt_verify_binlog_checksum)))
{
error("Could not construct log event object: %s", error_msg);
DBUG_RETURN(ERROR_STOP);
}
/*
If reading from a remote host, ensure the temp_buf for the
Log_event class is pointing to the incoming stream.
*/
ev->register_temp_buf((char *) net->read_pos + 1);
}
if (raw_mode || (type != LOAD_EVENT))
{
/*
If this is a Rotate event, maybe it's the end of the requested binlog;
in this case we are done (stop transfer).
This is suitable for binlogs, not relay logs (but for now we don't read
relay logs remotely because the server is not able to do that). If one
day we read relay logs remotely, then we will have a problem with the
detection below: relay logs contain Rotate events which are about the
binlogs, so which would trigger the end-detection below.
*/
if (type == ROTATE_EVENT)
{
Rotate_log_event *rev= (Rotate_log_event *)ev;
/*
If this is a fake Rotate event, and not about our log, we can stop
transfer. If this a real Rotate event (so it's not about our log,
it's in our log describing the next log), we print it (because it's
part of our log) and then we will stop when we receive the fake one
soon.
*/
if (raw_mode)
{
if (output_file != 0)
{
my_snprintf(log_file_name, sizeof(log_file_name), "%s%s",
output_file, rev->new_log_ident);
}
else
{
strmov(log_file_name, rev->new_log_ident);
}
}
if (rev->when.tv_sec == 0)
{
if (!to_last_remote_log)
{
if ((rev->ident_len != logname_len) ||
memcmp(rev->new_log_ident, logname, logname_len))
{
DBUG_RETURN(OK_CONTINUE);
}
/*
Otherwise, this is a fake Rotate for our log, at the very
beginning for sure. Skip it, because it was not in the original
log. If we are running with to_last_remote_log, we print it,
because it serves as a useful marker between binlogs then.
*/
continue;
}
/*
Reset the value of '# at pos' field shown against first event of
next binlog file (fake rotate) picked by mysqlbinlog --to-last-log
*/
old_off= start_position_mot;
len= 1; // fake Rotate, so don't increment old_off
}
}
else if (type == FORMAT_DESCRIPTION_EVENT)
{
/*
This could be an fake Format_description_log_event that server
(5.0+) automatically sends to a slave on connect, before sending
a first event at the requested position. If this is the case,
don't increment old_off. Real Format_description_log_event always
starts from BIN_LOG_HEADER_SIZE position.
*/
// fake event when not in raw mode, don't increment old_off
if ((old_off != BIN_LOG_HEADER_SIZE) && (!raw_mode))
len= 1;
if (raw_mode)
{
if (result_file && (result_file != stdout))
my_fclose(result_file, MYF(0));
if (!(result_file = my_fopen(log_file_name, O_WRONLY | O_BINARY,
MYF(MY_WME))))
{
error("Could not create log file '%s'", log_file_name);
DBUG_RETURN(ERROR_STOP);
}
DBUG_EXECUTE_IF("simulate_result_file_write_error_for_FD_event",
DBUG_SET("+d,simulate_fwrite_error"););
if (my_fwrite(result_file, (const uchar*) BINLOG_MAGIC,
BIN_LOG_HEADER_SIZE, MYF(MY_NABP)))
{
error("Could not write into log file '%s'", log_file_name);
DBUG_RETURN(ERROR_STOP);
}
/*
Need to handle these events correctly in raw mode too
or this could get messy
*/
delete glob_description_event;
glob_description_event= (Format_description_log_event*) ev;
print_event_info->common_header_len= glob_description_event->common_header_len;
ev->temp_buf= 0;
ev= 0;
}
}
if (type == LOAD_EVENT)
{
DBUG_ASSERT(raw_mode);
warning("Attempting to load a remote pre-4.0 binary log that contains "
"LOAD DATA INFILE statements. The file will not be copied from "
"the remote server. ");
}
if (raw_mode)
{
DBUG_EXECUTE_IF("simulate_result_file_write_error",
DBUG_SET("+d,simulate_fwrite_error"););
if (my_fwrite(result_file, net->read_pos + 1 , len - 1, MYF(MY_NABP)))
{
error("Could not write into log file '%s'", log_file_name);
retval= ERROR_STOP;
}
if (ev)
{
ev->temp_buf=0;
delete ev;
}
}
else
{
retval= process_event(print_event_info, ev, old_off, logname);
}
if (retval != OK_CONTINUE)
DBUG_RETURN(retval);
}
else
{
Load_log_event *le= (Load_log_event*)ev;
const char *old_fname= le->fname;
uint old_len= le->fname_len;
File file;
if ((file= load_processor.prepare_new_file_for_old_format(le,fname)) < 0)
DBUG_RETURN(ERROR_STOP);
retval= process_event(print_event_info, ev, old_off, logname);
if (retval != OK_CONTINUE)
{
my_close(file,MYF(MY_WME));
DBUG_RETURN(retval);
}
retval= load_processor.load_old_format_file(net,old_fname,old_len,file);
my_close(file,MYF(MY_WME));
if (retval != OK_CONTINUE)
DBUG_RETURN(retval);
}
/*
Let's adjust offset for remote log as for local log to produce
similar text and to have --stop-position to work identically.
*/
old_off+= len-1;
}
DBUG_RETURN(OK_CONTINUE);
}
/**
Reads the @c Format_description_log_event from the beginning of a
local input file.
The @c Format_description_log_event is only read if it is outside
the range specified with @c --start-position; otherwise, it will be
seen later. If this is an old binlog, a fake @c
Format_description_event is created. This also prints a @c
Format_description_log_event to the output, unless we reach the
--start-position range. In this case, it is assumed that a @c
Format_description_log_event will be found when reading events the
usual way.
@param file The file to which a @c Format_description_log_event will
be printed.
@param[in,out] print_event_info Parameters and context state
determining how to print.
@param[in] logname Name of input binlog.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
@retval OK_STOP No error, but the end of the specified range of
events to process has been reached and the program should terminate.
*/
static Exit_status check_header(IO_CACHE* file,
PRINT_EVENT_INFO *print_event_info,
const char* logname)
{
DBUG_ENTER("check_header");
uchar header[BIN_LOG_HEADER_SIZE];
uchar buf[PROBE_HEADER_LEN];
my_off_t tmp_pos, pos;
MY_STAT my_file_stat;
delete glob_description_event;
if (!(glob_description_event= new Format_description_log_event(3)))
{
error("Failed creating Format_description_log_event; out of memory?");
DBUG_RETURN(ERROR_STOP);
}
pos= my_b_tell(file);
/* fstat the file to check if the file is a regular file. */
if (my_fstat(file->file, &my_file_stat, MYF(0)) == -1)
{
error("Unable to stat the file.");
DBUG_RETURN(ERROR_STOP);
}
if ((my_file_stat.st_mode & S_IFMT) == S_IFREG)
my_b_seek(file, (my_off_t)0);
if (my_b_read(file, header, sizeof(header)))
{
error("Failed reading header; probably an empty file.");
DBUG_RETURN(ERROR_STOP);
}
if (memcmp(header, BINLOG_MAGIC, sizeof(header)))
{
error("File is not a binary log file.");
DBUG_RETURN(ERROR_STOP);
}
/*
Imagine we are running with --start-position=1000. We still need
to know the binlog format's. So we still need to find, if there is
one, the Format_desc event, or to know if this is a 3.23
binlog. So we need to first read the first events of the log,
those around offset 4. Even if we are reading a 3.23 binlog from
the start (no --start-position): we need to know the header length
(which is 13 in 3.23, 19 in 4.x) to be able to successfully print
the first event (Start_log_event_v3). So even in this case, we
need to "probe" the first bytes of the log *before* we do a real
read_log_event(). Because read_log_event() needs to know the
header's length to work fine.
*/
for(;;)
{
tmp_pos= my_b_tell(file); /* should be 4 the first time */
if (my_b_read(file, buf, sizeof(buf)))
{
if (file->error)
{
error("Could not read entry at offset %llu: "
"Error in log format or read error.", (ulonglong)tmp_pos);
DBUG_RETURN(ERROR_STOP);
}
/*
Otherwise this is just EOF : this log currently contains 0-2
events. Maybe it's going to be filled in the next
milliseconds; then we are going to have a problem if this a
3.23 log (imagine we are locally reading a 3.23 binlog which
is being written presently): we won't know it in
read_log_event() and will fail(). Similar problems could
happen with hot relay logs if --start-position is used (but a
--start-position which is posterior to the current size of the log).
These are rare problems anyway (reading a hot log + when we
read the first events there are not all there yet + when we
read a bit later there are more events + using a strange
--start-position).
*/
break;
}
else
{
DBUG_PRINT("info",("buf[EVENT_TYPE_OFFSET=%d]=%d",
EVENT_TYPE_OFFSET, buf[EVENT_TYPE_OFFSET]));
/* always test for a Start_v3, even if no --start-position */
if (buf[EVENT_TYPE_OFFSET] == START_EVENT_V3)
{
/* This is 3.23 or 4.x */
if (uint4korr(buf + EVENT_LEN_OFFSET) <
(LOG_EVENT_MINIMAL_HEADER_LEN + START_V3_HEADER_LEN))
{
/* This is 3.23 (format 1) */
delete glob_description_event;
if (!(glob_description_event= new Format_description_log_event(1)))
{
error("Failed creating Format_description_log_event; "
"out of memory?");
DBUG_RETURN(ERROR_STOP);
}
}
break;
}
else if (tmp_pos >= start_position)
break;
else if (buf[EVENT_TYPE_OFFSET] == FORMAT_DESCRIPTION_EVENT)
{
/* This is 5.0 */
Format_description_log_event *new_description_event;
my_b_seek(file, tmp_pos); /* seek back to event's start */
if (!(new_description_event= (Format_description_log_event*)
Log_event::read_log_event(file, glob_description_event,
opt_verify_binlog_checksum)))
/* EOF can't be hit here normally, so it's a real error */
{
error("Could not read a Format_description_log_event event at "
"offset %llu; this could be a log format error or read error.",
(ulonglong)tmp_pos);
DBUG_RETURN(ERROR_STOP);
}
if (opt_base64_output_mode == BASE64_OUTPUT_AUTO)
{
/*
process_event will delete *description_event and set it to
the new one, so we should not do it ourselves in this
case.
*/
Exit_status retval= process_event(print_event_info,
new_description_event, tmp_pos,
logname);
if (retval != OK_CONTINUE)
DBUG_RETURN(retval);
}
else
{
delete glob_description_event;
glob_description_event= new_description_event;
}
DBUG_PRINT("info",("Setting description_event"));
}
else if (buf[EVENT_TYPE_OFFSET] == ROTATE_EVENT)
{
Log_event *ev;
my_b_seek(file, tmp_pos); /* seek back to event's start */
if (!(ev= Log_event::read_log_event(file, glob_description_event,
opt_verify_binlog_checksum)))
{
/* EOF can't be hit here normally, so it's a real error */
error("Could not read a Rotate_log_event event at offset %llu;"
" this could be a log format error or read error.",
(ulonglong)tmp_pos);
DBUG_RETURN(ERROR_STOP);
}
delete ev;
}
else
break;
}
}
my_b_seek(file, pos);
DBUG_RETURN(OK_CONTINUE);
}
/**
Reads a local binlog and prints the events it sees.
@param[in] logname Name of input binlog.
@param[in,out] print_event_info Parameters and context state
determining how to print.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
@retval OK_STOP No error, but the end of the specified range of
events to process has been reached and the program should terminate.
*/
static Exit_status dump_local_log_entries(PRINT_EVENT_INFO *print_event_info,
const char* logname)
{
File fd = -1;
IO_CACHE cache,*file= &cache;
uchar tmp_buff[BIN_LOG_HEADER_SIZE];
Exit_status retval= OK_CONTINUE;
if (logname && strcmp(logname, "-") != 0)
{
/* read from normal file */
if ((fd = my_open(logname, O_RDONLY | O_BINARY, MYF(MY_WME))) < 0)
return ERROR_STOP;
if (init_io_cache(file, fd, 0, READ_CACHE, start_position_mot, 0,
MYF(MY_WME | MY_NABP)))
{
my_close(fd, MYF(MY_WME));
return ERROR_STOP;
}
if ((retval= check_header(file, print_event_info, logname)) != OK_CONTINUE)
goto end;
}
else
{
/* read from stdin */
/*
Windows opens stdin in text mode by default. Certain characters
such as CTRL-Z are interpeted as events and the read() method
will stop. CTRL-Z is the EOF marker in Windows. to get past this
you have to open stdin in binary mode. Setmode() is used to set
stdin in binary mode. Errors on setting this mode result in
halting the function and printing an error message to stderr.
*/
#if defined (__WIN__) || (_WIN64)
if (_setmode(fileno(stdin), O_BINARY) == -1)
{
error("Could not set binary mode on stdin.");
return ERROR_STOP;
}
#endif
if (init_io_cache(file, my_fileno(stdin), 0, READ_CACHE, (my_off_t) 0,
0, MYF(MY_WME | MY_NABP | MY_DONT_CHECK_FILESIZE)))
{
error("Failed to init IO cache.");
return ERROR_STOP;
}
if ((retval= check_header(file, print_event_info, logname)) != OK_CONTINUE)
goto end;
if (start_position)
{
/* skip 'start_position' characters from stdin */
uchar buff[IO_SIZE];
my_off_t length,tmp;
for (length= start_position_mot ; length > 0 ; length-=tmp)
{
tmp= min<size_t>(length, sizeof(buff));
if (my_b_read(file, buff, (uint) tmp))
{
error("Failed reading from file.");
goto err;
}
}
}
}
if (!glob_description_event || !glob_description_event->is_valid())
{
error("Invalid Format_description log event; could be out of memory.");
goto err;
}
if (!start_position && my_b_read(file, tmp_buff, BIN_LOG_HEADER_SIZE))
{
error("Failed reading from file.");
goto err;
}
for (;;)
{
char llbuff[21];
my_off_t old_off = my_b_tell(file);
Log_event* ev = Log_event::read_log_event(file, glob_description_event,
opt_verify_binlog_checksum);
if (!ev)
{
/*
if binlog wasn't closed properly ("in use" flag is set) don't complain
about a corruption, but treat it as EOF and move to the next binlog.
*/
if (glob_description_event->flags & LOG_EVENT_BINLOG_IN_USE_F)
file->error= 0;
else if (file->error)
{
error("Could not read entry at offset %s: "
"Error in log format or read error.",
llstr(old_off,llbuff));
goto err;
}
// file->error == 0 means EOF, that's OK, we break in this case
goto end;
}
if ((retval= process_event(print_event_info, ev, old_off, logname)) !=
OK_CONTINUE)
goto end;
}
/* NOTREACHED */
err:
retval= ERROR_STOP;
end:
if (fd >= 0)
my_close(fd, MYF(MY_WME));
/*
Since the end_io_cache() writes to the
file errors may happen.
*/
if (end_io_cache(file))
retval= ERROR_STOP;
return retval;
}
/* Post processing of arguments to check for conflicts and other setups */
static int args_post_process(void)
{
DBUG_ENTER("args_post_process");
if (opt_remote_alias && opt_remote_proto != BINLOG_DUMP_NON_GTID)
{
error("The option read-from-remote-server cannot be used when "
"read-from-remote-master is defined and is not equal to "
"BINLOG-DUMP-NON-GTIDS");
DBUG_RETURN(ERROR_STOP);
}
if (raw_mode)
{
if (one_database)
warning("The --database option is ignored with --raw mode");
if (opt_remote_proto == BINLOG_LOCAL)
{
error("You need to set --read-from-remote-master={BINLOG_DUMP_NON_GTID, "
"BINLOG_DUMP_GTID} for --raw mode");
DBUG_RETURN(ERROR_STOP);
}
if (opt_remote_proto == BINLOG_DUMP_NON_GTID &&
(opt_exclude_gtids_str != NULL || opt_include_gtids_str != NULL))
{
error("You cannot set --exclude-gtids or --include-gtids for --raw-mode "
"when --read-from-remote-master=BINLOG_DUMP_NON_GTID");
DBUG_RETURN(ERROR_STOP);
}
if (opt_remote_proto == BINLOG_DUMP_GTID && opt_include_gtids_str != NULL)
{
error("You cannot set --include-gtids for --raw-mode "
"when --read-from-remote-master=BINLOG_DUMP_GTID for");
DBUG_RETURN(ERROR_STOP);
}
if (stop_position != (ulonglong)(~(my_off_t)0))
warning("The --stop-position option is ignored in raw mode");
if (stop_datetime != MY_TIME_T_MAX)
warning("The --stop-datetime option is ignored in raw mode");
}
else if (output_file)
{
if (!(result_file = my_fopen(output_file, O_WRONLY | O_BINARY, MYF(MY_WME))))
{
error("Could not create log file '%s'", output_file);
DBUG_RETURN(ERROR_STOP);
}
}
global_sid_lock->rdlock();
if (opt_include_gtids_str != NULL)
{
if (gtid_set_included->add_gtid_text(opt_include_gtids_str) !=
RETURN_STATUS_OK)
{
error("Could not configure --include-gtids '%s'", opt_include_gtids_str);
global_sid_lock->unlock();
DBUG_RETURN(ERROR_STOP);
}
}
if (opt_exclude_gtids_str != NULL)
{
if (gtid_set_excluded->add_gtid_text(opt_exclude_gtids_str) !=
RETURN_STATUS_OK)
{
error("Could not configure --exclude-gtids '%s'", opt_exclude_gtids_str);
global_sid_lock->unlock();
DBUG_RETURN(ERROR_STOP);
}
}
global_sid_lock->unlock();
#ifndef DBUG_OFF
if (connection_server_id == 0 && stop_never)
error("Cannot set --server-id=0 when --stop-never is specified.");
if (connection_server_id != -1 && stop_never_slave_server_id != -1)
error("Cannot set --connection-server-id= %lld and "
"--stop-never-slave-server-id= %lld. ", connection_server_id,
stop_never_slave_server_id);
#endif
DBUG_RETURN(OK_CONTINUE);
}
/**
GTID cleanup destroys objects and reset their pointer.
Function is reentrant.
*/
inline void gtid_client_cleanup()
{
delete global_sid_lock;
delete global_sid_map;
delete gtid_set_excluded;
delete gtid_set_included;
global_sid_lock= NULL;
global_sid_map= NULL;
gtid_set_excluded= NULL;
gtid_set_included= NULL;
}
/**
GTID initialization.
@return true if allocation does not succeed
false if OK
*/
inline bool gtid_client_init()
{
bool res=
(!(global_sid_lock= new Checkable_rwlock) ||
!(global_sid_map= new Sid_map(global_sid_lock)) ||
!(gtid_set_excluded= new Gtid_set(global_sid_map)) ||
!(gtid_set_included= new Gtid_set(global_sid_map)));
if (res)
{
gtid_client_cleanup();
}
return res;
}
int main(int argc, char** argv)
{
char **defaults_argv;
Exit_status retval= OK_CONTINUE;
MY_INIT(argv[0]);
DBUG_ENTER("main");
DBUG_PROCESS(argv[0]);
my_init_time(); // for time functions
/*
A pointer of type Log_event can point to
INTVAR
USER_VAR
RANDOM
events, when we allocate a element of sizeof(Log_event*)
for the DYNAMIC_ARRAY.
*/
if((my_init_dynamic_array(&buff_ev, sizeof(buff_event_info),
INTVAR_DYNAMIC_INIT, INTVAR_DYNAMIC_INCR)))
exit(1);
my_getopt_use_args_separator= TRUE;
if (load_defaults("my", load_default_groups, &argc, &argv))
exit(1);
my_getopt_use_args_separator= FALSE;
defaults_argv= argv;
parse_args(&argc, &argv);
if (!argc)
{
usage();
free_defaults(defaults_argv);
my_end(my_end_arg);
exit(1);
}
if (gtid_client_init())
{
error("Could not initialize GTID structuress.");
exit(1);
}
/* Check for argument conflicts and do any post-processing */
if (args_post_process() == ERROR_STOP)
exit(1);
if (opt_base64_output_mode == BASE64_OUTPUT_UNSPEC)
opt_base64_output_mode= BASE64_OUTPUT_AUTO;
opt_server_id_mask = (opt_server_id_bits == 32)?
~ ulong(0) : (1 << opt_server_id_bits) -1;
my_set_max_open_files(open_files_limit);
MY_TMPDIR tmpdir;
tmpdir.list= 0;
if (!dirname_for_local_load)
{
if (init_tmpdir(&tmpdir, 0))
exit(1);
dirname_for_local_load= my_strdup(my_tmpdir(&tmpdir), MY_WME);
}
if (load_processor.init())
exit(1);
if (dirname_for_local_load)
load_processor.init_by_dir_name(dirname_for_local_load);
else
load_processor.init_by_cur_dir();
if (!raw_mode)
{
fprintf(result_file, "/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;\n");
fprintf(result_file,
"/*!40019 SET @@session.max_insert_delayed_threads=0*/;\n");
if (disable_log_bin)
fprintf(result_file,
"/*!32316 SET @OLD_SQL_LOG_BIN=@@SQL_LOG_BIN, SQL_LOG_BIN=0*/;\n");
/*
In mysqlbinlog|mysql, don't want mysql to be disconnected after each
transaction (which would be the case with GLOBAL.COMPLETION_TYPE==2).
*/
fprintf(result_file,
"/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,"
"COMPLETION_TYPE=0*/;\n");
if (charset)
fprintf(result_file,
"\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;"
"\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;"
"\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;"
"\n/*!40101 SET NAMES %s */;\n", charset);
}
retval= dump_multiple_logs(argc, argv);
if (!raw_mode)
{
/*
Issue a ROLLBACK in case the last printed binlog was crashed and had half
of transaction.
*/
fprintf(result_file,
"# End of log file\nROLLBACK /* added by mysqlbinlog */;\n"
"/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;\n");
if (disable_log_bin)
fprintf(result_file, "/*!32316 SET SQL_LOG_BIN=@OLD_SQL_LOG_BIN*/;\n");
if (charset)
fprintf(result_file,
"/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n"
"/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n"
"/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n");
fprintf(result_file, "/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;\n");
}
if (tmpdir.list)
free_tmpdir(&tmpdir);
if (result_file && (result_file != stdout))
my_fclose(result_file, MYF(0));
cleanup();
if (defaults_argv)
free_defaults(defaults_argv);
my_free_open_file_info();
load_processor.destroy();
/* We cannot free DBUG, it is used in global destructors after exit(). */
my_end(my_end_arg | MY_DONT_FREE_DBUG);
gtid_client_cleanup();
exit(retval == ERROR_STOP ? 1 : 0);
/* Keep compilers happy. */
DBUG_RETURN(retval == ERROR_STOP ? 1 : 0);
}
/*
We must include this here as it's compiled with different options for
the server
*/
#include "decimal.c"
#include "my_decimal.cc"
#include "log_event.cc"
#include "log_event_old.cc"
#include "rpl_utility.cc"
#include "rpl_gtid_sid_map.cc"
#include "rpl_gtid_misc.cc"
#include "uuid.cc"
#include "rpl_gtid_set.cc"
#include "rpl_gtid_specification.cc"
#include "rpl_tblmap.cc"
| gpl-2.0 |
liuyanghejerry/qtextended | qtopiacore/qt/src/3rdparty/webkit/WebCore/generated/JSSVGRenderingIntent.cpp | 7026 | /*
This file is part of the WebKit open source project.
This file has been generated by generate-bindings.pl. DO NOT MODIFY!
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG)
#include "Document.h"
#include "Frame.h"
#include "SVGDocumentExtensions.h"
#include "SVGElement.h"
#include "SVGAnimatedTemplate.h"
#include "JSSVGRenderingIntent.h"
#include <wtf/GetPtr.h>
#include "SVGRenderingIntent.h"
using namespace KJS;
namespace WebCore {
/* Hash table */
static const HashEntry JSSVGRenderingIntentTableEntries[] =
{
{ "constructor", JSSVGRenderingIntent::ConstructorAttrNum, DontDelete|DontEnum|ReadOnly, 0, 0 }
};
static const HashTable JSSVGRenderingIntentTable =
{
2, 1, JSSVGRenderingIntentTableEntries, 1
};
/* Hash table for constructor */
static const HashEntry JSSVGRenderingIntentConstructorTableEntries[] =
{
{ 0, 0, 0, 0, 0 },
{ "RENDERING_INTENT_UNKNOWN", SVGRenderingIntent::RENDERING_INTENT_UNKNOWN, DontDelete|ReadOnly, 0, 0 },
{ 0, 0, 0, 0, 0 },
{ "RENDERING_INTENT_SATURATION", SVGRenderingIntent::RENDERING_INTENT_SATURATION, DontDelete|ReadOnly, 0, 0 },
{ "RENDERING_INTENT_AUTO", SVGRenderingIntent::RENDERING_INTENT_AUTO, DontDelete|ReadOnly, 0, &JSSVGRenderingIntentConstructorTableEntries[6] },
{ "RENDERING_INTENT_PERCEPTUAL", SVGRenderingIntent::RENDERING_INTENT_PERCEPTUAL, DontDelete|ReadOnly, 0, &JSSVGRenderingIntentConstructorTableEntries[7] },
{ "RENDERING_INTENT_RELATIVE_COLORIMETRIC", SVGRenderingIntent::RENDERING_INTENT_RELATIVE_COLORIMETRIC, DontDelete|ReadOnly, 0, 0 },
{ "RENDERING_INTENT_ABSOLUTE_COLORIMETRIC", SVGRenderingIntent::RENDERING_INTENT_ABSOLUTE_COLORIMETRIC, DontDelete|ReadOnly, 0, 0 }
};
static const HashTable JSSVGRenderingIntentConstructorTable =
{
2, 8, JSSVGRenderingIntentConstructorTableEntries, 6
};
class JSSVGRenderingIntentConstructor : public DOMObject {
public:
JSSVGRenderingIntentConstructor(ExecState* exec)
{
setPrototype(exec->lexicalInterpreter()->builtinObjectPrototype());
putDirect(exec->propertyNames().prototype, JSSVGRenderingIntentPrototype::self(exec), None);
}
virtual bool getOwnPropertySlot(ExecState*, const Identifier&, PropertySlot&);
JSValue* getValueProperty(ExecState*, int token) const;
virtual const ClassInfo* classInfo() const { return &info; }
static const ClassInfo info;
virtual bool implementsHasInstance() const { return true; }
};
const ClassInfo JSSVGRenderingIntentConstructor::info = { "SVGRenderingIntentConstructor", 0, &JSSVGRenderingIntentConstructorTable, 0 };
bool JSSVGRenderingIntentConstructor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSSVGRenderingIntentConstructor, DOMObject>(exec, &JSSVGRenderingIntentConstructorTable, this, propertyName, slot);
}
JSValue* JSSVGRenderingIntentConstructor::getValueProperty(ExecState*, int token) const
{
// The token is the numeric value of its associated constant
return jsNumber(token);
}
/* Hash table for prototype */
static const HashEntry JSSVGRenderingIntentPrototypeTableEntries[] =
{
{ 0, 0, 0, 0, 0 },
{ "RENDERING_INTENT_UNKNOWN", SVGRenderingIntent::RENDERING_INTENT_UNKNOWN, DontDelete|ReadOnly, 0, 0 },
{ 0, 0, 0, 0, 0 },
{ "RENDERING_INTENT_SATURATION", SVGRenderingIntent::RENDERING_INTENT_SATURATION, DontDelete|ReadOnly, 0, 0 },
{ "RENDERING_INTENT_AUTO", SVGRenderingIntent::RENDERING_INTENT_AUTO, DontDelete|ReadOnly, 0, &JSSVGRenderingIntentPrototypeTableEntries[6] },
{ "RENDERING_INTENT_PERCEPTUAL", SVGRenderingIntent::RENDERING_INTENT_PERCEPTUAL, DontDelete|ReadOnly, 0, &JSSVGRenderingIntentPrototypeTableEntries[7] },
{ "RENDERING_INTENT_RELATIVE_COLORIMETRIC", SVGRenderingIntent::RENDERING_INTENT_RELATIVE_COLORIMETRIC, DontDelete|ReadOnly, 0, 0 },
{ "RENDERING_INTENT_ABSOLUTE_COLORIMETRIC", SVGRenderingIntent::RENDERING_INTENT_ABSOLUTE_COLORIMETRIC, DontDelete|ReadOnly, 0, 0 }
};
static const HashTable JSSVGRenderingIntentPrototypeTable =
{
2, 8, JSSVGRenderingIntentPrototypeTableEntries, 6
};
const ClassInfo JSSVGRenderingIntentPrototype::info = { "SVGRenderingIntentPrototype", 0, &JSSVGRenderingIntentPrototypeTable, 0 };
JSObject* JSSVGRenderingIntentPrototype::self(ExecState* exec)
{
return KJS::cacheGlobalObject<JSSVGRenderingIntentPrototype>(exec, "[[JSSVGRenderingIntent.prototype]]");
}
bool JSSVGRenderingIntentPrototype::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSSVGRenderingIntentPrototype, JSObject>(exec, &JSSVGRenderingIntentPrototypeTable, this, propertyName, slot);
}
JSValue* JSSVGRenderingIntentPrototype::getValueProperty(ExecState*, int token) const
{
// The token is the numeric value of its associated constant
return jsNumber(token);
}
const ClassInfo JSSVGRenderingIntent::info = { "SVGRenderingIntent", 0, &JSSVGRenderingIntentTable, 0 };
JSSVGRenderingIntent::JSSVGRenderingIntent(ExecState* exec, SVGRenderingIntent* impl)
: m_impl(impl)
{
setPrototype(JSSVGRenderingIntentPrototype::self(exec));
}
JSSVGRenderingIntent::~JSSVGRenderingIntent()
{
ScriptInterpreter::forgetDOMObject(m_impl.get());
}
bool JSSVGRenderingIntent::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSSVGRenderingIntent, KJS::DOMObject>(exec, &JSSVGRenderingIntentTable, this, propertyName, slot);
}
JSValue* JSSVGRenderingIntent::getValueProperty(ExecState* exec, int token) const
{
switch (token) {
case ConstructorAttrNum:
return getConstructor(exec);
}
return 0;
}
JSValue* JSSVGRenderingIntent::getConstructor(ExecState* exec)
{
return KJS::cacheGlobalObject<JSSVGRenderingIntentConstructor>(exec, "[[SVGRenderingIntent.constructor]]");
}
KJS::JSValue* toJS(KJS::ExecState* exec, SVGRenderingIntent* obj)
{
return KJS::cacheDOMObject<SVGRenderingIntent, JSSVGRenderingIntent>(exec, obj);
}
SVGRenderingIntent* toSVGRenderingIntent(KJS::JSValue* val)
{
return val->isObject(&JSSVGRenderingIntent::info) ? static_cast<JSSVGRenderingIntent*>(val)->impl() : 0;
}
}
#endif // ENABLE(SVG)
| gpl-2.0 |
monkivn92/benhanonline | libraries/CBLib/CBLib/Database/DatabaseDriverInterface.php | 15872 | <?php
/**
* CBLib, Community Builder Library(TM)
*
* @version $Id: 4/27/14 2:26 AM $
* @package ${NAMESPACE}
* @copyright (C) 2004-2016 www.joomlapolis.com / Lightning MultiCom SA - and its licensors, all rights reserved
* @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU/GPL version 2
*/
namespace CBLib\Database;
/**
* CBLib\Database\Driver\CmsDatabaseDriver Class implementation
*
*/
interface DatabaseDriverInterface
{
/**
* This method loads the first field of the first row returned by the query.
*
* @return string|null The value returned in the query or null if the query failed.
*
* @throws \RuntimeException
*/
public function loadResult();
/**
* Load an array of single field results into an array
*
* @param int $offset The row offset to use to build the result array
* @return array The array with the result (empty in case of error)
*
* @throws \RuntimeException
*/
public function loadResultArray( $offset = 0 );
/**
* @return \stdClass The first row of the query.
*
* @throws \RuntimeException
*/
public function loadRow();
/**
* Load a list of database rows (numeric column indexing)
* If <var>key</var> is not empty then the returned array is indexed by the value
* the database key. Returns <var>null</var> if the query fails.
*
* @param string $key The field name of a primary key
* @return array If <var>key</var> is empty as sequential list of returned records.
*
* @throws \RuntimeException
*/
public function loadRowList( $key = null );
/**
* Fetch a result row as an associative array
*
* @return array
*
* @throws \RuntimeException
*/
public function loadAssoc();
/**
* Load a associative array of associative database rows or column values.
*
* @param string $key The name of a field on which to key the result array
* @param string $column [optional] column name. If not null: Instead of the whole row, only this column value will be in the result array
* @return array If $key is null: Sequential array of returned records/values, Otherwise: Keyed array
*
* @throws \RuntimeException
*/
public function loadAssocList( $key = null, $column = null );
/**
* This global function loads the first row of a query into an object
*
* If an object is passed to this function, the returned row is bound to the existing elements of <var>object</var>.
* If <var>object</var> has a value of null, then all of the returned query fields returned in the object.
*
* @param object|\stdClass $object
* @return boolean Success
*
* @throws \RuntimeException
*/
public function loadObject( &$object );
/**
* Load a list of database objects
* If $key is not empty then the returned array is indexed by the value
* the database key. Returns NULL if the query fails.
*
* @param string|array $key The field name of a primary key, if array contains keys for sub-arrays: e.g. array( 'a', 'b' ) will store into $array[$row->a][$row->b]
* @param string|null $className The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned
* @param array|null $ctor_params An optional array of parameters to pass to the constructor for class_name objects
* @param boolean $lowerCaseIndex default: FALSE: keep case, TRUE: lowercase array indexes (only valid if $key is string and not array)
* @return array If $key is empty as sequential list of returned records.
*
* @throws \RuntimeException
*/
public function loadObjectList( $key = null, $className = null, $ctor_params = null, $lowerCaseIndex = false );
/**
* Get the database driver SQL statement log.
*
* @return array SQL statements executed by the database driver.
*/
public function getLog();
/**
* Returns the status of all tables, with the prefix changed if needed.
*
* @param string $tableName Name of table (SQL LIKE pattern), null: all tables
* @param string $prefix Prefix to change back
* @return array A list of all the table statuses in the database
*
* @throws \RuntimeException
*/
public function getTableStatus( $tableName = null, $prefix = '#__' );
/**
* Method to initialize a transaction.
*
* @param boolean $asSavepoint If true and a transaction is already active, a savepoint will be created.
* @return self Returns this object to support chaining.
*
* @throws \RuntimeException
*/
public function transactionStart( $asSavepoint = false );
/**
* Method to commit a transaction.
*
* @param boolean $toSavepoint If true, commit to the last savepoint.
* @return self Returns this object to support chaining.
*
* @throws \RuntimeException
*/
public function transactionCommit( $toSavepoint = false );
/**
* Method to roll back a transaction.
*
* @param boolean $toSavepoint If true, rollback to the last savepoint.
* @return self Returns this object to support chaining.
*
* @throws \RuntimeException
*/
public function transactionRollback( $toSavepoint = false );
/**
* Was setting error message
*
* @deprecated 2.0 (no effect)
*
* @param string $errorMsg The error message for the most recent query
*/
public function setErrorMsg( $errorMsg );
/**
* Gets error message
*
* @return string The error message for the most recent query
*/
public function getErrorMsg();
/**
* Returns a PHP date() function compliant date format for the database driver.
*
* @param string $dateTime 'datetime', 'date', 'time'
* @return string The format string.
*/
public function getDateFormat( $dateTime = 'datetime' );
/**
* Returns the zero date/time
*
* @param string $dateTime 'datetime', 'date', 'time'
* @return string Unquoted null/zero date string
*/
public function getNullDate( $dateTime = 'datetime' );
/**
* Returns the database-formatted (not quoted) date/time in UTC timezone format
*
* @param int $time NULL: Now of script start time
* @param string $dateTime 'datetime', 'date', 'time'
* @return string Unquoted date string
*/
public function getUtcDateTime( $time = null, $dateTime = 'datetime' );
/**
* Gets the fields as in DESCRIBE of MySQL
*
* @param array|string $tables A (list of) table names
* @param boolean $onlyType TRUE: only type without size, FALSE: full DESCRIBE MySql
* @return array EITHER: array( tablename => array( fieldname => fieldtype ) ) or of => fieldDESCRIBE
*
* @throws \RuntimeException
*/
public function getTableFields( $tables, $onlyType = true );
/**
* Replace $prefix with $this->getPrefix() in $sql
*
* @param string $sql SQL query
* @param string $prefix Common table prefix
* @return string
*/
public function replacePrefix( $sql, $prefix = '#__' );
/**
* @param array $tables A list of valid (and safe!) table names
* @return array A list the create SQL for the tables
*
* @throws \RuntimeException
*/
public function getTableCreate( $tables );
/**
* @return int The number of affected rows in the previous operation
*/
public function getAffectedRows();
/**
* Locks a table in the database.
*
* @param string $tableName The name of the table to unlock.
*
* @return self Returns this object to support chaining.
*
* @throws \RuntimeException
*/
public function lockTable( $tableName );
/**
* Unlocks tables in the database.
*
* @return self Returns this object to support chaining.
*
* @throws \RuntimeException
*/
public function unlockTables();
/**
* @return string The current value of the internal SQL vairable
*/
public function getQuery();
/**
* Gets error number
*
* @return int The error number for the most recent query
*/
public function getErrorNum();
/**
* Checks if database's collation is case-INsensitive
* WARNING: individual table's fields might have a different collation
*
* @return boolean TRUE if case INsensitive
*
* @throws \RuntimeException
*/
public function isDbCollationCaseInsensitive();
/**
* Method to truncate a table.
*
* @param string $tableName The table to truncate
* @return self Returns this object to support chaining.
*
* @throws \RuntimeException
*/
public function truncateTable( $tableName );
/**
* Returns the version of MySQL
*
* @return string
*/
public function getVersion();
/**
* Get the total number of SQL statements executed by the database driver.
*
* @return integer
*/
public function getCount();
/**
* Returns a list of tables, with the prefix changed if needed.
*
* @param string $tableName Name of table (SQL LIKE pattern), null: all tables
* @param string $prefix Prefix to change back
* @return array A list of all the tables in the database
*
* @throws \RuntimeException
*/
public function getTableList( $tableName = null, $prefix = '#__' );
/**
* Returns the number of rows returned from the most recent query.
*
* @param \mysqli_result|\resource $cursor
* @return int
*/
public function getNumRows( $cursor = null );
/**
* Get tables prefix (so that '#__' can be replaced by this
*
* @since 1.7
*
* @return string Database table prefix.
*
*/
public function getPrefix();
/**
* Returns the insert_id() from Mysql
*
* @return int
*/
public function insertid();
/**
* Get a database escaped string. For LIKE statemends: $db->Quote( $db->getEscaped( $text, true ) . '%', false )
*
* @param string $text
* @param boolean $escapeForLike : escape also % and _ wildcards for LIKE statements with % or _ in search strings (since CB 1.2.3)
* @return string
*/
public function getEscaped( $text, $escapeForLike = false );
/**
* Get a quoted database escaped string (or array of strings)
*
* @param string|array $text
* @param boolean $escape
* @return string
*/
public function Quote( $text, $escape = true );
/**
* Quote an identifier name (field, table, etc)
*
* @param string|array $name The name (supports arrays and .-notations)
* @param string|array $as The AS query part (supports arrays too)
* @return string The quoted name
*/
public function NameQuote( $name, $as = null );
/**
* Sanitizes an array of (int) as REFERENCE
*
* @param array $array Array to sanitize out
* @return string ' ( 1, 2, 3 ) '
*/
public function safeArrayOfIntegers( $array );
/**
* Sanitizes an array of (int) as REFERENCE
*
* @param array $array Array to sanitize out
* @return string ' ( "a", "b", "c" ) '
*/
public function safeArrayOfStrings( $array );
/**
* Sets the SQL query string for later execution.
*
* This function replaces a string identifier $prefix with the
* string held is the $this->getPrefix() class variable.
*
* @param string $sql The SQL query (casted to (string) )
* @param int $offset The offset to start selection
* @param int $limit The number of results to return
* @return self For chaining
*/
public function setQuery( $sql, $offset = 0, $limit = 0 );
/**
* Compares MySQL version with version_compare( MySQLversion, $minimumVersionCompare, '>=' )
*
* @param string $minimumVersionCompare Version to compare to
* @return int Result of version_compare( $version, $minimumVersionCompare, '>=' )
*/
public function versionCompare( $minimumVersionCompare );
/**
* Sets debug level
*
* @param int $level New level
* @return int Previous level
*/
public function debug( $level );
/**
* Returns the formatted standard error message of SQL
*
* @deprecated 2.0
*
* @param boolean $showSQL If TRUE, displays the last SQL statement sent to the database
* @return string A standised error message
*/
public function stderr( $showSQL = false );
/**
* Renames a table in the database.
*
* @param string $oldTable The name of the table to be renamed
* @param string $newTable The new name for the table.
* @param string $backup Non-MySQL: Table prefix
* @param string $prefix Non-MySQL: For the table - used to rename constraints in non-mysql databases
*
* @return self Returns this object to support chaining.
*
* @throws \RuntimeException
*/
public function renameTable( $oldTable, $newTable, $backup = null, $prefix = null );
/**
* Drops a table from the database.
*
* @param string $tableName The name of the database table to drop.
* @param boolean $ifExists Optionally specify that the table must exist before it is dropped.
* @return self Returns this object to support chaining.
*
* @throws \RuntimeException
*/
public function dropTable( $tableName, $ifExists = true );
/**
* Renames a column of table in the database.
*
* @param string $table The table of the field to rename
* @param string $oldColumn The name of the field to be renamed
* @param string $newColumn The new name for the field.
*
* @return self Returns this object to support chaining.
*
* @throws \RuntimeException
*/
public function renameColumn( $table, $oldColumn, $newColumn );
/**
* Drops a column of table in the database.
*
* @param string $table The table of the field to rename
* @param string $column The name of the field to be dropped
* @param boolean $ifExists Optionally specify that the column must exist before it is dropped.
*
* @return self Returns this object to support chaining.
*
* @throws \RuntimeException
*/
public function dropColumn( $table, $column, $ifExists = true );
/**
* Insert an object into database
*
* @param string $table This is expected to be a valid (and safe!) table name
* @param object &$object A reference to an object whose public properties match the table fields.
* @param string $keyName The name of the primary key. If provided the object property is updated.
* @return boolean TRUE if insert succeeded, FALSE when error
*
* @throws \RuntimeException
*/
public function insertObject( $table, &$object, $keyName = null );
/**
* Updates an object into a database
*
* @param string $table This is expected to be a valid (and safe!) table name
* @param object $object
* @param string|array|object $keysNames
* @param boolean $updateNulls
* @return mixed A database resource if successful, FALSE if not.
*
* @throws \RuntimeException
*/
public function updateObject( $table, &$object, $keysNames, $updateNulls = true );
/**
* Execute the query
*
* @param string $sql The query (optional, it will use the setQuery one otherwise)
* @return \mysqli_result|\resource|boolean A database resource if successful, FALSE if not.
*
* @throws \RuntimeException
*/
public function query( $sql = null );
/**
* Was setting error number
*
* @deprecated 2.0 (no effect)
*
* @param int $errorNum The error number for the most recent query
*/
public function setErrorNum( $errorNum );
/**
* Gets the index of the table
*
* @param string $table param array|string $tables A (list of) table names
* @param string $prefix
* @return array Indexes
*
* @throws \RuntimeException
*/
public function getTableIndex( $table, $prefix = '#__' );
} | gpl-2.0 |
tracyapps/chad | node_modules/grunt-contrib-imagemin/node_modules/imagemin/node_modules/imagemin-gifsicle/node_modules/gifsicle/node_modules/bin-build/node_modules/decompress/node_modules/vinyl-fs/node_modules/glob-stream/node_modules/unique-stream/node_modules/es6-set/node_modules/es5-ext/test/date/valid-date.js | 250 | 'use strict';
module.exports = function( t, a ) {
var d = new Date();
a( t( d ), d, "Date" );
a.throws( function() {
t( {} );
}, "Object" );
a.throws( function() {
t( { valueOf: function() {
return 20;
} } );
}, "Number object" );
};
| gpl-2.0 |
smalyshev/blazegraph | dsi-utils/src/java/it/unimi/dsi/compression/HuffmanCodec.java | 14921 | package it.unimi.dsi.compression;
/*
* DSI utilities
*
* Copyright (C) 2005-2009 Sebastiano Vigna
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
import it.unimi.dsi.bits.BitVector;
import it.unimi.dsi.bits.LongArrayBitVector;
import java.io.Serializable;
import java.util.Arrays;
import cern.colt.Sorting;
import cern.colt.function.IntComparator;
/** An implementation of Huffman optimal prefix-free coding.
*
* <p>A Huffman coder is built starting from an array of frequencies corresponding to each
* symbol. Frequency 0 symbols are allowed, but they will degrade the resulting code.
*
* <p>Instances of this class compute a <em>canonical</em> Huffman code
* (Eugene S. Schwartz and Bruce Kallick, “Generating a Canonical Prefix Encoding”, <i>Commun. ACM</i> 7(3), pages 166−169, 1964), which can
* by {@linkplain CanonicalFast64CodeWordDecoder quickly decoded using table lookups}.
* The construction uses the most efficient one-pass in-place codelength computation procedure
* described by Alistair Moffat and Jyrki Katajainen in “In-Place Calculation of Minimum-Redundancy Codes”,
* <i>Algorithms and Data Structures, 4th International Workshop</i>,
* number 955 in Lecture Notes in Computer Science, pages 393−402, Springer-Verlag, 1995.
*
* <p>We note by passing that this coded uses a {@link CanonicalFast64CodeWordDecoder}, which does not support codelengths above 64.
* However, since the worst case for codelengths is given by Fibonacci numbers, and frequencies are to be provided as integers,
* no codeword longer than the base-[(5<sup>1/2</sup> + 1)/2] logarithm of 5<sup>1/2</sup> · 2<sup>31</sup> (less than 47) will ever be generated.
* <p>
* <h3>Modifications</h3>
* <ol><li>
* This class has been modified to define an alternative ctor which exposes the
* symbol[] in correlated order with the codeWord bitLength[] and the shortest
* code word in the generated canonical.</li>
* <li>
* A method has been added to recreate the {@link PrefixCoder} from the
* shortest code word, the code word length[], and the symbol[].
* </li>
* </ol>
* */
public class HuffmanCodec implements PrefixCodec, Serializable {
private static final boolean DEBUG = false;
private static final boolean ASSERTS = false;
private static final long serialVersionUID = 2L;
/** The number of symbols of this coder. */
public final int size;
/** The codewords for this coder. */
private final BitVector[] codeWord;
/** A cached singleton instance of the coder of this codec. */
private final Fast64CodeWordCoder coder;
/** A cached singleton instance of the decoder of this codec. */
private final CanonicalFast64CodeWordDecoder decoder;
/**
* Class encapsulates the data necessary to reconstruct a
* {@link CanonicalFast64CodeWordDecoder} or recreate the code.
*
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan
* Thompson</a>
* @version $Id: HuffmanCodec.java 2265 2009-10-26 12:51:06Z thompsonbry $
*/
public static class DecoderInputs {
private BitVector shortestCodeWord;
private int symbol[];
private int length[];
/**
* Ctor may be passed to {@link HuffmanCodec} to obtain the assigned
* length[] and symbol[] data and the shortest code word.
*/
public DecoderInputs() {
}
/**
* Ctor may be used to explicitly populate an instance with the caller's
* data.
*
* @param shortestCodeWord
* @param length
* @param symbol
*/
public DecoderInputs(final BitVector shortestCodeWord,
final int[] length, final int[] symbol) {
assert shortestCodeWord!=null;
assert length!=null;
assert symbol!=null;
assert length.length==symbol.length;
assert shortestCodeWord.size()==length[0];
this.shortestCodeWord = shortestCodeWord;
this.length = length;
this.symbol = symbol;
}
/**
* The shortest code word. Note that canonical huffman codes can be
* recreated from just length[0] and the shortest code word.
*/
public BitVector getShortestCodeWord() {
return shortestCodeWord;
}
/**
* Return the symbol[] in the permuted order used to construct the
* {@link CanonicalFast64CodeWordDecoder}. This information is
* <em>transient</em>.
*/
public int[] getSymbols() {
return symbol;
}
/**
* Return the codeWord bit lengths in the non-decreasing order used to
* construct the {@link CanonicalFast64CodeWordDecoder}. This information is
* <em>transient</em>.
*/
public int[] getLengths() {
return length;
}
}
/** Creates a new Huffman codec using the given vector of frequencies.
*
* @param frequency a vector of nonnnegative frequencies.
*/
public HuffmanCodec( final int[] frequency ) {
this(frequency, new DecoderInputs());
}
/**
* Creates a new Huffman codec using the given vector of frequencies.
*
* @param frequency
* a vector of non-negative frequencies.
* @param decoderInputs
* The inputs necessary to reconstruct a
* {@link CanonicalFast64CodeWordDecoder} will be set on this
* object.
*/
public HuffmanCodec( final int[] frequency, final DecoderInputs decoderInputs ) {
if(decoderInputs==null)
throw new IllegalArgumentException();
size = frequency.length;
if ( size == 0 || size == 1 ) {
codeWord = new BitVector[ size ];
if ( size == 1 ) codeWord[ 0 ] = LongArrayBitVector.getInstance();
coder = new Fast64CodeWordCoder( codeWord, new long[ size ] );
// Modified BBT 8/11/2009
// decoder = new CanonicalFast64CodeWordDecoder( new int[ size ], new int[ size ] );
decoderInputs.shortestCodeWord = LongArrayBitVector.getInstance().length( 0 );
decoderInputs.length = new int[size];
decoderInputs.symbol = new int[size];
decoder = new CanonicalFast64CodeWordDecoder( decoderInputs.length, decoderInputs.symbol );
return;
}
final long[] a = new long[ size ];
for( int i = size; i-- != 0; ) a[ i ] = frequency[ i ];
// Sort frequencies (this is the only n log n step).
Arrays.sort( a );
// The following lines are from Moffat & Katajainen sample code. Please refer to their paper.
// First pass, left to right, setting parent pointers.
a[ 0 ] += a[ 1 ];
int root = 0;
int leaf = 2;
for ( int next = 1; next < size - 1; next++ ) {
// Select first item for a pairing.
if ( leaf >= size || a[ root ] < a[ leaf ] ) {
a[ next ] = a[ root ];
a[ root++ ] = next;
}
else a[ next ] = a[ leaf++ ];
// Add on the second item.
if ( leaf >= size || ( root < next && a[ root ] < a[ leaf ] ) ) {
a[ next ] += a[ root ];
a[ root++ ] = next;
}
else a[ next ] += a[ leaf++ ];
}
// Second pass, right to left, setting internal depths.
a[ size - 2 ] = 0;
for ( int next = size - 3; next >= 0; next-- ) a[ next ] = a[ (int)a[ next ] ] + 1;
// Third pass, right to left, setting leaf depths.
int available = 1, used = 0, depth = 0;
root = size - 2;
int next = size - 1;
while ( available > 0 ) {
while ( root >= 0 && a[ root ] == depth ) {
used++;
root--;
}
while ( available > used ) {
a[ next-- ] = depth;
available--;
}
available = 2 * used;
depth++;
used = 0;
}
// Reverse the order of symbol lengths, and store them into an int array.
final int[] length = new int[ size ];
for( int i = size; i-- != 0; ) length[ i ] = (int)a[ size - 1 - i ];
// Sort symbols indices by decreasing frequencies (so symbols correspond to lengths).
final int[] symbol = new int[ size ];
for( int i = size; i-- != 0; ) symbol[ i ] = i;
Sorting.quickSort( symbol, 0, size, new IntComparator() {
public int compare( int x, int y ) {
return frequency[ y ] - frequency[ x ];
}
});
// Assign codewords (just for the coder--the decoder needs just the lengths).
int s = symbol[ 0 ];
int l = length[ 0 ];
long value = 0;
BitVector v;
codeWord = new BitVector[ size ];
final long[] longCodeWord = new long[ size ];
codeWord[ s ] = LongArrayBitVector.getInstance().length( l );
for( int i = 1; i < size; i++ ) {
s = symbol[ i ];
if ( length[ i ] == l ) value++;
else {
value++;
value <<= length[ i ] - l;
if ( ASSERTS ) assert length[ i ] > l;
l = length[ i ];
}
v = LongArrayBitVector.getInstance().length( l );
for( int j = l; j-- != 0; ) if ( ( 1L << j & value ) != 0 ) v.set( l - 1 - j );
codeWord[ s ] = v;
longCodeWord[ s ] = value;
}
coder = new Fast64CodeWordCoder( codeWord, longCodeWord );
// Modified BBT 8/11/2009
// decoder = new CanonicalFast64CodeWordDecoder( length, symbol );
decoderInputs.shortestCodeWord = codeWord[symbol[0]];
decoderInputs.length = length;
decoderInputs.symbol = symbol;
assert decoderInputs.shortestCodeWord.size() == length[0] : "shortestCodeWord="
+ decoderInputs.shortestCodeWord
+ ", but length[0]="
+ length[0];
decoder = new CanonicalFast64CodeWordDecoder( decoderInputs.length, decoderInputs.symbol);
if ( DEBUG ) {
final BitVector[] codeWord = codeWords();
System.err.println( "Codes: " );
for( int i = 0; i < size; i++ )
System.err.println( i + " (" + codeWord[ i ].size() + " bits): " + codeWord[ i ] );
long totFreq = 0;
for( int i = size; i-- != 0; ) totFreq += frequency[ i ];
long totBits = 0;
for( int i = size; i-- != 0; ) totBits += frequency[ i ] * codeWord[ i ].size();
System.err.println( "Compression: " + totBits + " / " + totFreq * Character.SIZE + " = " + (double)totBits/(totFreq * Character.SIZE) );
}
}
public CodeWordCoder coder() {
return coder;
}
public Decoder decoder() {
return decoder;
}
public int size() {
return size;
}
public BitVector[] codeWords() {
return coder.codeWords();
}
/**
* (Re-)constructs the canonical huffman code from the shortest code word,
* the non-decreasing bit lengths of each code word, and the permutation of
* the symbols corresponding to those bit lengths. This information is
* necessary and sufficient to reconstruct a canonical huffman code.
*
* @param decoderInputs
* This contains the necessary and sufficient information to
* recreate the {@link PrefixCoder}.
*
* @return A new {@link PrefixCoder} instance for the corresponding
* canonical huffman code.
*/
static public PrefixCoder newCoder(final DecoderInputs decoderInputs) {
return newCoder(decoderInputs.getShortestCodeWord(), decoderInputs
.getLengths(), decoderInputs.getSymbols());
}
/**
* (Re-)constructs the canonical huffman code from the shortest code word,
* the non-decreasing bit lengths of each code word, and the permutation of
* the symbols corresponding to those bit lengths. This information is
* necessary and sufficient to reconstruct a canonical huffman code.
*
* @param shortestCodeWord
* The code word with the shortest bit length.
* @param length
* The bit length of each code word in the non-decreasing order
* assigned when the code was generated. The length of this array
* is the #of symbols in the code.
* @param symbol
* The permutation of the symbols in the assigned when the
* canonical huffman code was generated. The length of this array
* is the #of symbols in the code.
*
* @return A new {@link PrefixCoder} instance for the corresponding
* canonical huffman code.
*
* @see DecoderInputs
*/
static public PrefixCoder newCoder(final BitVector shortestCodeWord,
final int[] length, final int[] symbol) {
if (shortestCodeWord == null)
throw new IllegalArgumentException();
if (shortestCodeWord.size() == 0)
throw new IllegalArgumentException();
if (length == null)
throw new IllegalArgumentException();
if (length.length == 0)
throw new IllegalArgumentException();
if (symbol == null)
throw new IllegalArgumentException();
if (symbol.length == 0)
throw new IllegalArgumentException();
final int size = length.length;
int s = symbol[ 0 ];
int l = length[ 0 ];
long value = 0;
BitVector v;
final BitVector[] codeWord = new BitVector[ size ];
final long[] longCodeWord = new long[ size ];
codeWord[ s ] = LongArrayBitVector.getInstance().length( l );
for( int i = 1; i < size; i++ ) {
s = symbol[ i ];
if ( length[ i ] == l ) value++;
else {
value++;
value <<= length[ i ] - l;
if ( ASSERTS ) assert length[ i ] > l;
l = length[ i ];
}
v = LongArrayBitVector.getInstance().length( l );
for( int j = l; j-- != 0; ) if ( ( 1L << j & value ) != 0 ) v.set( l - 1 - j );
codeWord[ s ] = v;
longCodeWord[ s ] = value;
}
return new Fast64CodeWordCoder(codeWord, longCodeWord);
}
}
| gpl-2.0 |
olek1984/dremboard | wp-content/plugins/buddypress/bp-forums/bbpress/bb-includes/backpress/functions.plugin-api.php | 27489 | <?php
// Last sync [WP14924]
/**
* The plugin API is located in this file, which allows for creating actions
* and filters and hooking functions, and methods. The functions or methods will
* then be run when the action or filter is called.
*
* The API callback examples reference functions, but can be methods of classes.
* To hook methods, you'll need to pass an array one of two ways.
*
* Any of the syntaxes explained in the PHP documentation for the
* {@link http://us2.php.net/manual/en/language.pseudo-types.php#language.types.callback 'callback'}
* type are valid.
*
* Also see the {@link http://codex.wordpress.org/Plugin_API Plugin API} for
* more information and examples on how to use a lot of these functions.
*
* @package WordPress
* @subpackage Plugin
* @since 1.5
*/
/**
* Hooks a function or method to a specific filter action.
*
* Filters are the hooks that WordPress launches to modify text of various types
* before adding it to the database or sending it to the browser screen. Plugins
* can specify that one or more of its PHP functions is executed to
* modify specific types of text at these times, using the Filter API.
*
* To use the API, the following code should be used to bind a callback to the
* filter.
*
* <code>
* function example_hook($example) { echo $example; }
* add_filter('example_filter', 'example_hook');
* </code>
*
* In WordPress 1.5.1+, hooked functions can take extra arguments that are set
* when the matching do_action() or apply_filters() call is run. The
* $accepted_args allow for calling functions only when the number of args
* match. Hooked functions can take extra arguments that are set when the
* matching do_action() or apply_filters() call is run. For example, the action
* comment_id_not_found will pass any functions that hook onto it the ID of the
* requested comment.
*
* <strong>Note:</strong> the function will return true no matter if the
* function was hooked fails or not. There are no checks for whether the
* function exists beforehand and no checks to whether the <tt>$function_to_add
* is even a string. It is up to you to take care and this is done for
* optimization purposes, so everything is as quick as possible.
*
* @package WordPress
* @subpackage Plugin
* @since 0.71
* @global array $wp_filter Stores all of the filters added in the form of
* wp_filter['tag']['array of priorities']['array of functions serialized']['array of ['array (functions, accepted_args)']']
* @global array $merged_filters Tracks the tags that need to be merged for later. If the hook is added, it doesn't need to run through that process.
*
* @param string $tag The name of the filter to hook the $function_to_add to.
* @param callback $function_to_add The name of the function to be called when the filter is applied.
* @param int $priority optional. Used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
* @param int $accepted_args optional. The number of arguments the function accept (default 1).
* @return boolean true
*/
function add_filter($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
global $wp_filter, $merged_filters;
$idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority);
$wp_filter[$tag][$priority][$idx] = array('function' => $function_to_add, 'accepted_args' => $accepted_args);
unset( $merged_filters[ $tag ] );
return true;
}
/**
* Check if any filter has been registered for a hook.
*
* @package WordPress
* @subpackage Plugin
* @since 2.5
* @global array $wp_filter Stores all of the filters
*
* @param string $tag The name of the filter hook.
* @param callback $function_to_check optional. If specified, return the priority of that function on this hook or false if not attached.
* @return int|boolean Optionally returns the priority on that hook for the specified function.
*/
function has_filter($tag, $function_to_check = false) {
global $wp_filter;
$has = !empty($wp_filter[$tag]);
if ( false === $function_to_check || false == $has )
return $has;
if ( !$idx = _wp_filter_build_unique_id($tag, $function_to_check, false) )
return false;
foreach ( (array) array_keys($wp_filter[$tag]) as $priority ) {
if ( isset($wp_filter[$tag][$priority][$idx]) )
return $priority;
}
return false;
}
/**
* Call the functions added to a filter hook.
*
* The callback functions attached to filter hook $tag are invoked by calling
* this function. This function can be used to create a new filter hook by
* simply calling this function with the name of the new hook specified using
* the $tag parameter.
*
* The function allows for additional arguments to be added and passed to hooks.
* <code>
* function example_hook($string, $arg1, $arg2)
* {
* //Do stuff
* return $string;
* }
* $value = apply_filters('example_filter', 'filter me', 'arg1', 'arg2');
* </code>
*
* @package WordPress
* @subpackage Plugin
* @since 0.71
* @global array $wp_filter Stores all of the filters
* @global array $merged_filters Merges the filter hooks using this function.
* @global array $wp_current_filter stores the list of current filters with the current one last
*
* @param string $tag The name of the filter hook.
* @param mixed $value The value on which the filters hooked to <tt>$tag</tt> are applied on.
* @param mixed $var,... Additional variables passed to the functions hooked to <tt>$tag</tt>.
* @return mixed The filtered value after all hooked functions are applied to it.
*/
function apply_filters($tag, $value) {
global $wp_filter, $merged_filters, $wp_current_filter;
$args = array();
$wp_current_filter[] = $tag;
// Do 'all' actions first
if ( isset($wp_filter['all']) ) {
$args = func_get_args();
_wp_call_all_hook($args);
}
if ( !isset($wp_filter[$tag]) ) {
array_pop($wp_current_filter);
return $value;
}
// Sort
if ( !isset( $merged_filters[ $tag ] ) ) {
ksort($wp_filter[$tag]);
$merged_filters[ $tag ] = true;
}
reset( $wp_filter[ $tag ] );
if ( empty($args) )
$args = func_get_args();
do {
foreach( (array) current($wp_filter[$tag]) as $the_ )
if ( !is_null($the_['function']) ){
$args[1] = $value;
$value = call_user_func_array($the_['function'], array_slice($args, 1, (int) $the_['accepted_args']));
}
} while ( next($wp_filter[$tag]) !== false );
array_pop( $wp_current_filter );
return $value;
}
/**
* Execute functions hooked on a specific filter hook, specifying arguments in an array.
*
* @see apply_filters() This function is identical, but the arguments passed to the
* functions hooked to <tt>$tag</tt> are supplied using an array.
*
* @package WordPress
* @subpackage Plugin
* @since 3.0.0
* @global array $wp_filter Stores all of the filters
* @global array $merged_filters Merges the filter hooks using this function.
* @global array $wp_current_filter stores the list of current filters with the current one last
*
* @param string $tag The name of the filter hook.
* @param array $args The arguments supplied to the functions hooked to <tt>$tag</tt>
* @return mixed The filtered value after all hooked functions are applied to it.
*/
function apply_filters_ref_array($tag, $args) {
global $wp_filter, $merged_filters, $wp_current_filter;
$wp_current_filter[] = $tag;
// Do 'all' actions first
if ( isset($wp_filter['all']) ) {
$all_args = func_get_args();
_wp_call_all_hook($all_args);
}
if ( !isset($wp_filter[$tag]) ) {
array_pop($wp_current_filter);
return $args[0];
}
// Sort
if ( !isset( $merged_filters[ $tag ] ) ) {
ksort($wp_filter[$tag]);
$merged_filters[ $tag ] = true;
}
reset( $wp_filter[ $tag ] );
do {
foreach( (array) current($wp_filter[$tag]) as $the_ )
if ( !is_null($the_['function']) )
$args[0] = call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args']));
} while ( next($wp_filter[$tag]) !== false );
array_pop( $wp_current_filter );
return $args[0];
}
/**
* Removes a function from a specified filter hook.
*
* This function removes a function attached to a specified filter hook. This
* method can be used to remove default functions attached to a specific filter
* hook and possibly replace them with a substitute.
*
* To remove a hook, the $function_to_remove and $priority arguments must match
* when the hook was added. This goes for both filters and actions. No warning
* will be given on removal failure.
*
* @package WordPress
* @subpackage Plugin
* @since 1.2
*
* @param string $tag The filter hook to which the function to be removed is hooked.
* @param callback $function_to_remove The name of the function which should be removed.
* @param int $priority optional. The priority of the function (default: 10).
* @param int $accepted_args optional. The number of arguments the function accpets (default: 1).
* @return boolean Whether the function existed before it was removed.
*/
function remove_filter($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
$function_to_remove = _wp_filter_build_unique_id($tag, $function_to_remove, $priority);
$r = isset($GLOBALS['wp_filter'][$tag][$priority][$function_to_remove]);
if ( true === $r) {
unset($GLOBALS['wp_filter'][$tag][$priority][$function_to_remove]);
if ( empty($GLOBALS['wp_filter'][$tag][$priority]) )
unset($GLOBALS['wp_filter'][$tag][$priority]);
unset($GLOBALS['merged_filters'][$tag]);
}
return $r;
}
/**
* Remove all of the hooks from a filter.
*
* @since 2.7
*
* @param string $tag The filter to remove hooks from.
* @param int $priority The priority number to remove.
* @return bool True when finished.
*/
function remove_all_filters($tag, $priority = false) {
global $wp_filter, $merged_filters;
if( isset($wp_filter[$tag]) ) {
if( false !== $priority && isset($wp_filter[$tag][$priority]) )
unset($wp_filter[$tag][$priority]);
else
unset($wp_filter[$tag]);
}
if( isset($merged_filters[$tag]) )
unset($merged_filters[$tag]);
return true;
}
/**
* Retrieve the name of the current filter or action.
*
* @package WordPress
* @subpackage Plugin
* @since 2.5
*
* @return string Hook name of the current filter or action.
*/
function current_filter() {
global $wp_current_filter;
return end( $wp_current_filter );
}
/**
* Hooks a function on to a specific action.
*
* Actions are the hooks that the WordPress core launches at specific points
* during execution, or when specific events occur. Plugins can specify that
* one or more of its PHP functions are executed at these points, using the
* Action API.
*
* @uses add_filter() Adds an action. Parameter list and functionality are the same.
*
* @package WordPress
* @subpackage Plugin
* @since 1.2
*
* @param string $tag The name of the action to which the $function_to_add is hooked.
* @param callback $function_to_add The name of the function you wish to be called.
* @param int $priority optional. Used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
* @param int $accepted_args optional. The number of arguments the function accept (default 1).
*/
function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
return add_filter($tag, $function_to_add, $priority, $accepted_args);
}
/**
* Execute functions hooked on a specific action hook.
*
* This function invokes all functions attached to action hook $tag. It is
* possible to create new action hooks by simply calling this function,
* specifying the name of the new hook using the <tt>$tag</tt> parameter.
*
* You can pass extra arguments to the hooks, much like you can with
* apply_filters().
*
* @see apply_filters() This function works similar with the exception that
* nothing is returned and only the functions or methods are called.
*
* @package WordPress
* @subpackage Plugin
* @since 1.2
* @global array $wp_filter Stores all of the filters
* @global array $wp_actions Increments the amount of times action was triggered.
*
* @param string $tag The name of the action to be executed.
* @param mixed $arg,... Optional additional arguments which are passed on to the functions hooked to the action.
* @return null Will return null if $tag does not exist in $wp_filter array
*/
function do_action($tag, $arg = '') {
global $wp_filter, $wp_actions, $merged_filters, $wp_current_filter;
if ( ! isset($wp_actions) )
$wp_actions = array();
if ( ! isset($wp_actions[$tag]) )
$wp_actions[$tag] = 1;
else
++$wp_actions[$tag];
$wp_current_filter[] = $tag;
// Do 'all' actions first
if ( isset($wp_filter['all']) ) {
$all_args = func_get_args();
_wp_call_all_hook($all_args);
}
if ( !isset($wp_filter[$tag]) ) {
array_pop($wp_current_filter);
return;
}
$args = array();
if ( is_array($arg) && 1 == count($arg) && isset($arg[0]) && is_object($arg[0]) ) // array(&$this)
$args[] =& $arg[0];
else
$args[] = $arg;
for ( $a = 2; $a < func_num_args(); $a++ )
$args[] = func_get_arg($a);
// Sort
if ( !isset( $merged_filters[ $tag ] ) ) {
ksort($wp_filter[$tag]);
$merged_filters[ $tag ] = true;
}
reset( $wp_filter[ $tag ] );
do {
foreach ( (array) current($wp_filter[$tag]) as $the_ )
if ( !is_null($the_['function']) )
call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args']));
} while ( next($wp_filter[$tag]) !== false );
array_pop($wp_current_filter);
}
/**
* Retrieve the number times an action is fired.
*
* @package WordPress
* @subpackage Plugin
* @since 2.1
* @global array $wp_actions Increments the amount of times action was triggered.
*
* @param string $tag The name of the action hook.
* @return int The number of times action hook <tt>$tag</tt> is fired
*/
function did_action($tag) {
global $wp_actions;
if ( ! isset( $wp_actions ) || ! isset( $wp_actions[$tag] ) )
return 0;
return $wp_actions[$tag];
}
/**
* Execute functions hooked on a specific action hook, specifying arguments in an array.
*
* @see do_action() This function is identical, but the arguments passed to the
* functions hooked to <tt>$tag</tt> are supplied using an array.
*
* @package WordPress
* @subpackage Plugin
* @since 2.1
* @global array $wp_filter Stores all of the filters
* @global array $wp_actions Increments the amount of times action was triggered.
*
* @param string $tag The name of the action to be executed.
* @param array $args The arguments supplied to the functions hooked to <tt>$tag</tt>
* @return null Will return null if $tag does not exist in $wp_filter array
*/
function do_action_ref_array($tag, $args) {
global $wp_filter, $wp_actions, $merged_filters, $wp_current_filter;
if ( ! isset($wp_actions) )
$wp_actions = array();
if ( ! isset($wp_actions[$tag]) )
$wp_actions[$tag] = 1;
else
++$wp_actions[$tag];
$wp_current_filter[] = $tag;
// Do 'all' actions first
if ( isset($wp_filter['all']) ) {
$all_args = func_get_args();
_wp_call_all_hook($all_args);
}
if ( !isset($wp_filter[$tag]) ) {
array_pop($wp_current_filter);
return;
}
// Sort
if ( !isset( $merged_filters[ $tag ] ) ) {
ksort($wp_filter[$tag]);
$merged_filters[ $tag ] = true;
}
reset( $wp_filter[ $tag ] );
do {
foreach( (array) current($wp_filter[$tag]) as $the_ )
if ( !is_null($the_['function']) )
call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args']));
} while ( next($wp_filter[$tag]) !== false );
array_pop($wp_current_filter);
}
/**
* Check if any action has been registered for a hook.
*
* @package WordPress
* @subpackage Plugin
* @since 2.5
* @see has_filter() has_action() is an alias of has_filter().
*
* @param string $tag The name of the action hook.
* @param callback $function_to_check optional. If specified, return the priority of that function on this hook or false if not attached.
* @return int|boolean Optionally returns the priority on that hook for the specified function.
*/
function has_action($tag, $function_to_check = false) {
return has_filter($tag, $function_to_check);
}
/**
* Removes a function from a specified action hook.
*
* This function removes a function attached to a specified action hook. This
* method can be used to remove default functions attached to a specific filter
* hook and possibly replace them with a substitute.
*
* @package WordPress
* @subpackage Plugin
* @since 1.2
*
* @param string $tag The action hook to which the function to be removed is hooked.
* @param callback $function_to_remove The name of the function which should be removed.
* @param int $priority optional The priority of the function (default: 10).
* @param int $accepted_args optional. The number of arguments the function accpets (default: 1).
* @return boolean Whether the function is removed.
*/
function remove_action($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
return remove_filter($tag, $function_to_remove, $priority, $accepted_args);
}
/**
* Remove all of the hooks from an action.
*
* @since 2.7
*
* @param string $tag The action to remove hooks from.
* @param int $priority The priority number to remove them from.
* @return bool True when finished.
*/
function remove_all_actions($tag, $priority = false) {
return remove_all_filters($tag, $priority);
}
//
// Functions for handling plugins.
//
/**
* Gets the basename of a plugin.
*
* This method extracts the name of a plugin from its filename.
*
* @package WordPress
* @subpackage Plugin
* @since 1.5
*
* @access private
*
* @param string $file The filename of plugin.
* @return string The name of a plugin.
* @uses WP_PLUGIN_DIR
*/
function plugin_basename($file) {
$file = str_replace('\\','/',$file); // sanitize for Win32 installs
$file = preg_replace('|/+|','/', $file); // remove any duplicate slash
$plugin_dir = str_replace('\\','/',WP_PLUGIN_DIR); // sanitize for Win32 installs
$plugin_dir = preg_replace('|/+|','/', $plugin_dir); // remove any duplicate slash
$mu_plugin_dir = str_replace('\\','/',WPMU_PLUGIN_DIR); // sanitize for Win32 installs
$mu_plugin_dir = preg_replace('|/+|','/', $mu_plugin_dir); // remove any duplicate slash
$file = preg_replace('#^' . preg_quote($plugin_dir, '#') . '/|^' . preg_quote($mu_plugin_dir, '#') . '/#','',$file); // get relative path from plugins dir
$file = trim($file, '/');
return $file;
}
/**
* Gets the filesystem directory path (with trailing slash) for the plugin __FILE__ passed in
* @package WordPress
* @subpackage Plugin
* @since 2.8
*
* @param string $file The filename of the plugin (__FILE__)
* @return string the filesystem path of the directory that contains the plugin
*/
function plugin_dir_path( $file ) {
return trailingslashit( dirname( $file ) );
}
/**
* Gets the URL directory path (with trailing slash) for the plugin __FILE__ passed in
* @package WordPress
* @subpackage Plugin
* @since 2.8
*
* @param string $file The filename of the plugin (__FILE__)
* @return string the URL path of the directory that contains the plugin
*/
function plugin_dir_url( $file ) {
return trailingslashit( plugins_url( '', $file ) );
}
/**
* Set the activation hook for a plugin.
*
* When a plugin is activated, the action 'activate_PLUGINNAME' hook is
* activated. In the name of this hook, PLUGINNAME is replaced with the name of
* the plugin, including the optional subdirectory. For example, when the plugin
* is located in wp-content/plugin/sampleplugin/sample.php, then the name of
* this hook will become 'activate_sampleplugin/sample.php'. When the plugin
* consists of only one file and is (as by default) located at
* wp-content/plugin/sample.php the name of this hook will be
* 'activate_sample.php'.
*
* @package WordPress
* @subpackage Plugin
* @since 2.0
*
* @param string $file The filename of the plugin including the path.
* @param callback $function the function hooked to the 'activate_PLUGIN' action.
*/
function register_activation_hook($file, $function) {
$file = plugin_basename($file);
add_action('activate_' . $file, $function);
}
/**
* Set the deactivation hook for a plugin.
*
* When a plugin is deactivated, the action 'deactivate_PLUGINNAME' hook is
* deactivated. In the name of this hook, PLUGINNAME is replaced with the name
* of the plugin, including the optional subdirectory. For example, when the
* plugin is located in wp-content/plugin/sampleplugin/sample.php, then
* the name of this hook will become 'activate_sampleplugin/sample.php'.
*
* When the plugin consists of only one file and is (as by default) located at
* wp-content/plugin/sample.php the name of this hook will be
* 'activate_sample.php'.
*
* @package WordPress
* @subpackage Plugin
* @since 2.0
*
* @param string $file The filename of the plugin including the path.
* @param callback $function the function hooked to the 'activate_PLUGIN' action.
*/
function register_deactivation_hook($file, $function) {
$file = plugin_basename($file);
add_action('deactivate_' . $file, $function);
}
/**
* Set the uninstallation hook for a plugin.
*
* Registers the uninstall hook that will be called when the user clicks on the
* uninstall link that calls for the plugin to uninstall itself. The link won't
* be active unless the plugin hooks into the action.
*
* The plugin should not run arbitrary code outside of functions, when
* registering the uninstall hook. In order to run using the hook, the plugin
* will have to be included, which means that any code laying outside of a
* function will be run during the uninstall process. The plugin should not
* hinder the uninstall process.
*
* If the plugin can not be written without running code within the plugin, then
* the plugin should create a file named 'uninstall.php' in the base plugin
* folder. This file will be called, if it exists, during the uninstall process
* bypassing the uninstall hook. The plugin, when using the 'uninstall.php'
* should always check for the 'WP_UNINSTALL_PLUGIN' constant, before
* executing.
*
* @since 2.7
*
* @param string $file
* @param callback $callback The callback to run when the hook is called.
*/
function register_uninstall_hook($file, $callback) {
// The option should not be autoloaded, because it is not needed in most
// cases. Emphasis should be put on using the 'uninstall.php' way of
// uninstalling the plugin.
$uninstallable_plugins = (array) backpress_get_option('uninstall_plugins');
$uninstallable_plugins[plugin_basename($file)] = $callback;
backpress_update_option('uninstall_plugins', $uninstallable_plugins);
}
/**
* Calls the 'all' hook, which will process the functions hooked into it.
*
* The 'all' hook passes all of the arguments or parameters that were used for
* the hook, which this function was called for.
*
* This function is used internally for apply_filters(), do_action(), and
* do_action_ref_array() and is not meant to be used from outside those
* functions. This function does not check for the existence of the all hook, so
* it will fail unless the all hook exists prior to this function call.
*
* @package WordPress
* @subpackage Plugin
* @since 2.5
* @access private
*
* @uses $wp_filter Used to process all of the functions in the 'all' hook
*
* @param array $args The collected parameters from the hook that was called.
* @param string $hook Optional. The hook name that was used to call the 'all' hook.
*/
function _wp_call_all_hook($args) {
global $wp_filter;
reset( $wp_filter['all'] );
do {
foreach( (array) current($wp_filter['all']) as $the_ )
if ( !is_null($the_['function']) )
call_user_func_array($the_['function'], $args);
} while ( next($wp_filter['all']) !== false );
}
/**
* Build Unique ID for storage and retrieval.
*
* The old way to serialize the callback caused issues and this function is the
* solution. It works by checking for objects and creating an a new property in
* the class to keep track of the object and new objects of the same class that
* need to be added.
*
* It also allows for the removal of actions and filters for objects after they
* change class properties. It is possible to include the property $wp_filter_id
* in your class and set it to "null" or a number to bypass the workaround.
* However this will prevent you from adding new classes and any new classes
* will overwrite the previous hook by the same class.
*
* Functions and static method callbacks are just returned as strings and
* shouldn't have any speed penalty.
*
* @package WordPress
* @subpackage Plugin
* @access private
* @since 2.2.3
* @link http://trac.wordpress.org/ticket/3875
*
* @global array $wp_filter Storage for all of the filters and actions
* @param string $tag Used in counting how many hooks were applied
* @param callback $function Used for creating unique id
* @param int|bool $priority Used in counting how many hooks were applied. If === false and $function is an object reference, we return the unique id only if it already has one, false otherwise.
* @param string $type filter or action
* @return string|bool Unique ID for usage as array key or false if $priority === false and $function is an object reference, and it does not already have a uniqe id.
*/
function _wp_filter_build_unique_id($tag, $function, $priority) {
global $wp_filter;
static $filter_id_count = 0;
if ( is_string($function) )
return $function;
if ( is_object($function) ) {
// Closures are currently implemented as objects
$function = array( $function, '' );
} else {
$function = (array) $function;
}
if (is_object($function[0]) ) {
// Object Class Calling
if ( function_exists('spl_object_hash') ) {
return spl_object_hash($function[0]) . $function[1];
} else {
$obj_idx = get_class($function[0]).$function[1];
if ( !isset($function[0]->wp_filter_id) ) {
if ( false === $priority )
return false;
$obj_idx .= isset($wp_filter[$tag][$priority]) ? count((array)$wp_filter[$tag][$priority]) : $filter_id_count;
$function[0]->wp_filter_id = $filter_id_count;
++$filter_id_count;
} else {
$obj_idx .= $function[0]->wp_filter_id;
}
return $obj_idx;
}
} else if ( is_string($function[0]) ) {
// Static Calling
return $function[0].$function[1];
}
}
| gpl-2.0 |
gidbot/treble | wp-content/plugins/fresh-framework/framework/themes/layouts/optionsHolders/class.ffOptionsHolder_Layout_Placement.php | 1836 | <?php
class ffOptionsHolder_Layout_Placement extends ffOptionsHolder {
public function getOptions() {
$s = $this->_getOnestructurefactory()->createOneStructure('layout');
$s->startSection('placement');
$s->addElement( ffOneElement::TYPE_HTML,'', '<div id="post-formats-select" class="ff-custom-code-placement">');
$s->addOption(ffOneOption::TYPE_CHECKBOX, 'active', 'Layout is Active', 1);
$s->addElement( ffOneElement::TYPE_NEW_LINE );
$s->addOption(ffOneOption::TYPE_RADIO, 'placement', '', 'content')
->addParam('break-line-at-end', true)
->addSelectValue('Header', 'header')
->addSelectValue('Before Content', 'before-content')
->addSelectValue('Content', 'content')
->addSelectValue('After Content', 'after-content')
->addSelectValue('Footer', 'footer');
$s->addOption(ffOneOption::TYPE_SELECT, 'priority', 'Priority ', '5')
->addSelectValue('1 (highest)', '1')
->addSelectValue('2', '2')
->addSelectValue('3', '3')
->addSelectValue('4', '4')
->addSelectValue('5 (default)', '5')
->addSelectValue('6', '6')
->addSelectValue('7', '7')
->addSelectValue('8', '8')
->addSelectValue('9', '9')
->addSelectValue('10 (lowest)', '10');
$s->addElement( ffOneElement::TYPE_NEW_LINE );
$s->addOption( ffOneOption::TYPE_CHECKBOX, 'default', 'Default (show when nothing else found AND the conditional logic passes)', 0);
$s->addElement( ffOneElement::TYPE_HTML,'', '</div>');
$s->endSection();
return $s;
}
} | gpl-2.0 |
Gurgel100/gcc | libstdc++-v3/testsuite/22_locale/time_put/put/wchar_t/wrapped_locale.cc | 2083 | // { dg-require-namedlocale "de_DE.ISO8859-15" }
// { dg-require-namedlocale "en_HK.ISO8859-1" }
// { dg-require-namedlocale "es_ES.ISO8859-15" }
// { dg-require-namedlocale "fr_FR.ISO8859-15" }
// { dg-require-namedlocale "ja_JP.eucJP" }
// 2001-08-15 Benjamin Kosnik <bkoz@redhat.com>
// Copyright (C) 2001-2021 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 22.2.4.1.1 collate members
#include <testsuite_hooks.h>
#define main discard_main_1
#include "1.cc"
#undef main
#define main discard_main_2
#include "2.cc"
#undef main
#define main discard_main_3
#include "3.cc"
#undef main
#define main discard_main_4
#include "4.cc"
#undef main
#define main discard_main_5
#include "5.cc"
#undef main
#define main discard_main_6
#include "6.cc"
#undef main
#define main discard_main_7
#include "7.cc"
#undef main
#define main discard_main_8
#include "8.cc"
#undef main
#define main discard_main_9
#include "9.cc"
#undef main
#define main discard_main_10
#include "10.cc"
#undef main
int main()
{
using namespace __gnu_test;
func_callback two;
two.push_back(&test01);
two.push_back(&test02);
two.push_back(&test03);
two.push_back(&test04);
two.push_back(&test05);
two.push_back(&test06);
two.push_back(&test07);
two.push_back(&test08);
two.push_back(&test09);
two.push_back(&test10);
run_tests_wrapped_locale("ja_JP.eucJP", two);
return 0;
}
| gpl-2.0 |
google-code/bh-v1-jl | administrator/components/com_modules/toolbar.modules.html.php | 2389 | <?php
/**
* @version $Id: toolbar.modules.html.php 14401 2010-01-26 14:10:00Z louis $
* @package Joomla
* @subpackage Modules
* @copyright Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
/**
* @package Joomla
* @subpackage Modules
*/
class TOOLBAR_modules {
/**
* Draws the menu for a New module
*/
function _NEW($client)
{
JToolBarHelper::title( JText::_( 'Module' ) . ': <small><small>[ '. JText::_( 'New' ) .' ]</small></small>', 'module.png' );
JToolBarHelper::customX( 'edit', 'forward.png', 'forward_f2.png', 'Next', true );
JToolBarHelper::cancel();
if ($client->name == 'site') {
JToolBarHelper::help( 'screen.modulessite.edit' );
}
else {
JToolBarHelper::help( 'screen.modulesadministrator.edit');
}
}
/**
* Draws the menu for Editing an existing module
*/
function _EDIT( $client )
{
$moduleType = JRequest::getCmd( 'module' );
$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
JArrayHelper::toInteger($cid, array(0));
JToolBarHelper::title( JText::_( 'Module' ) . ': <small><small>[ '. JText::_( 'Edit' ) .' ]</small></small>', 'module.png' );
if($moduleType == 'custom') {
JToolBarHelper::Preview('index.php?option=com_modules&tmpl=component&client='.$client->id.'&pollid='.$cid[0]);
}
JToolBarHelper::save();
JToolBarHelper::apply();
if ( $cid[0] ) {
// for existing items the button is renamed `close`
JToolBarHelper::cancel( 'cancel', 'Close' );
} else {
JToolBarHelper::cancel();
}
JToolBarHelper::help( 'screen.modules.edit' );
}
function _DEFAULT($client)
{
JToolBarHelper::title( JText::_( 'Module Manager' ), 'module.png' );
JToolBarHelper::publishList();
JToolBarHelper::unpublishList();
JToolBarHelper::custom( 'copy', 'copy.png', 'copy_f2.png', 'Copy', true );
JToolBarHelper::deleteList();
JToolBarHelper::editListX();
JToolBarHelper::addNewX();
JToolBarHelper::help( 'screen.modules' );
}
}
| gpl-2.0 |
webian/TYPO3.CMS | typo3/sysext/core/Classes/Cache/Frontend/StringFrontend.php | 3475 | <?php
namespace TYPO3\CMS\Core\Cache\Frontend;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Core\Cache\Exception\InvalidDataException;
/**
* A cache frontend for strings. Nothing else.
*
* This file is a backport from FLOW3
* @api
*/
class StringFrontend extends AbstractFrontend
{
/**
* Saves the value of a PHP variable in the cache.
*
* @param string $entryIdentifier An identifier used for this cache entry
* @param string $string The variable to cache
* @param array $tags Tags to associate with this cache entry
* @param int $lifetime Lifetime of this cache entry in seconds. If NULL is specified, the default lifetime is used. "0" means unlimited liftime.
* @return void
* @throws \InvalidArgumentException if the identifier or tag is not valid
* @throws InvalidDataException if the variable to cache is not of type string
* @api
*/
public function set($entryIdentifier, $string, array $tags = [], $lifetime = null)
{
if (!$this->isValidEntryIdentifier($entryIdentifier)) {
throw new \InvalidArgumentException('"' . $entryIdentifier . '" is not a valid cache entry identifier.', 1233057566);
}
if (!is_string($string)) {
throw new InvalidDataException('Given data is of type "' . gettype($string) . '", but a string is expected for string cache.', 1222808333);
}
foreach ($tags as $tag) {
if (!$this->isValidTag($tag)) {
throw new \InvalidArgumentException('"' . $tag . '" is not a valid tag for a cache entry.', 1233057512);
}
}
$this->backend->set($entryIdentifier, $string, $tags, $lifetime);
}
/**
* Finds and returns a variable value from the cache.
*
* @param string $entryIdentifier Identifier of the cache entry to fetch
* @return string The value
* @throws \InvalidArgumentException if the cache identifier is not valid
* @api
*/
public function get($entryIdentifier)
{
if (!$this->isValidEntryIdentifier($entryIdentifier)) {
throw new \InvalidArgumentException('"' . $entryIdentifier . '" is not a valid cache entry identifier.', 1233057752);
}
return $this->backend->get($entryIdentifier);
}
/**
* Finds and returns all cache entries which are tagged by the specified tag.
*
* @param string $tag The tag to search for
* @return array An array with the content of all matching entries. An empty array if no entries matched
* @throws \InvalidArgumentException if the tag is not valid
* @api
*/
public function getByTag($tag)
{
if (!$this->isValidTag($tag)) {
throw new \InvalidArgumentException('"' . $tag . '" is not a valid tag for a cache entry.', 1233057772);
}
$entries = [];
$identifiers = $this->backend->findIdentifiersByTag($tag);
foreach ($identifiers as $identifier) {
$entries[] = $this->backend->get($identifier);
}
return $entries;
}
}
| gpl-2.0 |
aplocher/mRemoteNG | mRemoteNGTests/Connection/ConnectionInfoComparerTests.cs | 1178 | using System.ComponentModel;
using mRemoteNG.Connection;
using NUnit.Framework;
namespace mRemoteNGTests.Connection
{
public class ConnectionInfoComparerTests
{
private ConnectionInfo _con1;
private ConnectionInfo _con2;
[OneTimeSetUp]
public void OnetimeSetup()
{
_con1 = new ConnectionInfo { Name = "a" };
_con2 = new ConnectionInfo { Name = "b" };
}
[Test]
public void SortAscendingOnName()
{
var comparer = new ConnectionInfoComparer<string>(node => node.Name)
{
SortDirection = ListSortDirection.Ascending
};
var compareReturn = comparer.Compare(_con1, _con2);
Assert.That(compareReturn, Is.Negative);
}
[Test]
public void SortDescendingOnName()
{
var comparer = new ConnectionInfoComparer<string>(node => node.Name)
{
SortDirection = ListSortDirection.Descending
};
var compareReturn = comparer.Compare(_con1, _con2);
Assert.That(compareReturn, Is.Positive);
}
}
} | gpl-2.0 |
ghtmtt/QGIS | tests/src/python/test_qgscolorramplegendnode.py | 21371 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsColorRampLegendNode.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Nyall Dawson'
__date__ = '2015-08'
__copyright__ = 'Copyright 2015, The QGIS Project'
import qgis # NOQA
from qgis.PyQt.QtCore import QSize, QDir, Qt, QSizeF
from qgis.PyQt.QtGui import QColor, QImage, QPainter
from qgis.PyQt.QtXml import QDomDocument, QDomElement
from qgis.core import (QgsGradientColorRamp,
QgsRectangle,
QgsColorRampLegendNode,
QgsLayerTreeLayer,
QgsVectorLayer,
QgsMultiRenderChecker,
QgsFontUtils,
QgsLegendSettings,
QgsLegendStyle,
QgsLayerTreeModelLegendNode,
QgsRenderContext,
QgsMapSettings,
QgsColorRampLegendNodeSettings,
QgsBearingNumericFormat,
QgsReadWriteContext,
QgsBasicNumericFormat,
QgsTextFormat)
from qgis.testing import start_app, unittest
start_app()
class TestColorRampLegend(QgsColorRampLegendNode):
"""
Override font role to use standard qgis test font
"""
def data(self, role):
if role == Qt.FontRole:
return QgsFontUtils.getStandardTestFont('Bold', 18)
else:
return super().data(role)
class TestQgsColorRampLegendNode(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = "<h1>Python QgsColorRampLegendNode Tests</h1>\n"
@classmethod
def tearDownClass(cls):
report_file_path = "%s/qgistest.html" % QDir.tempPath()
with open(report_file_path, 'a') as report_file:
report_file.write(cls.report)
def test_settings(self):
settings = QgsColorRampLegendNodeSettings()
settings.setDirection(QgsColorRampLegendNodeSettings.MaximumToMinimum)
self.assertEqual(settings.direction(), QgsColorRampLegendNodeSettings.MaximumToMinimum)
settings.setMinimumLabel('min')
self.assertEqual(settings.minimumLabel(), 'min')
settings.setMaximumLabel('max')
self.assertEqual(settings.maximumLabel(), 'max')
settings.setPrefix('pref')
self.assertEqual(settings.prefix(), 'pref')
settings.setSuffix('suff')
self.assertEqual(settings.suffix(), 'suff')
self.assertEqual(settings.orientation(), Qt.Vertical)
settings.setOrientation(Qt.Horizontal)
self.assertEqual(settings.orientation(), Qt.Horizontal)
self.assertFalse(settings.textFormat().isValid())
tf = QgsTextFormat()
tf.setSize(13)
settings.setTextFormat(tf)
self.assertEqual(settings.textFormat().size(), 13)
self.assertIsNotNone(settings.numericFormat())
settings.setNumericFormat(QgsBearingNumericFormat())
self.assertIsInstance(settings.numericFormat(), QgsBearingNumericFormat)
settings2 = QgsColorRampLegendNodeSettings(settings)
self.assertEqual(settings2.direction(), QgsColorRampLegendNodeSettings.MaximumToMinimum)
self.assertEqual(settings2.minimumLabel(), 'min')
self.assertEqual(settings2.maximumLabel(), 'max')
self.assertIsInstance(settings2.numericFormat(), QgsBearingNumericFormat)
self.assertEqual(settings2.prefix(), 'pref')
self.assertEqual(settings2.suffix(), 'suff')
self.assertEqual(settings2.textFormat().size(), 13)
self.assertEqual(settings2.orientation(), Qt.Horizontal)
settings2.setTextFormat(QgsTextFormat())
settings2a = QgsColorRampLegendNodeSettings(settings2)
self.assertFalse(settings2a.textFormat().isValid())
doc = QDomDocument("testdoc")
elem = doc.createElement('test')
settings.writeXml(doc, elem, QgsReadWriteContext())
settings3 = QgsColorRampLegendNodeSettings()
settings3.readXml(elem, QgsReadWriteContext())
self.assertEqual(settings3.direction(), QgsColorRampLegendNodeSettings.MaximumToMinimum)
self.assertEqual(settings3.minimumLabel(), 'min')
self.assertEqual(settings3.maximumLabel(), 'max')
self.assertIsInstance(settings3.numericFormat(), QgsBearingNumericFormat)
self.assertEqual(settings3.prefix(), 'pref')
self.assertEqual(settings3.suffix(), 'suff')
self.assertEqual(settings3.textFormat().size(), 13)
self.assertEqual(settings3.orientation(), Qt.Horizontal)
# no text format
elem = doc.createElement('test2')
settings2.writeXml(doc, elem, QgsReadWriteContext())
settings3a = QgsColorRampLegendNodeSettings()
settings3a.readXml(elem, QgsReadWriteContext())
self.assertFalse(settings3a.textFormat().isValid())
def test_basic(self):
r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200))
# need a layer in order to make legend nodes
layer = QgsVectorLayer('dummy', 'test', 'memory')
layer_tree_layer = QgsLayerTreeLayer(layer)
node = QgsColorRampLegendNode(layer_tree_layer, r, 'min_label', 'max_label')
self.assertEqual(node.ramp().color1().name(), '#c80000')
self.assertEqual(node.ramp().color2().name(), '#00c800')
node.setIconSize(QSize(11, 12))
self.assertEqual(node.iconSize(), QSize(11, 12))
self.assertEqual(node.data(QgsLayerTreeModelLegendNode.NodeTypeRole),
QgsLayerTreeModelLegendNode.ColorRampLegend)
def test_icon(self):
r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200))
# need a layer in order to make legend nodes
layer = QgsVectorLayer('dummy', 'test', 'memory')
layer_tree_layer = QgsLayerTreeLayer(layer)
node = TestColorRampLegend(layer_tree_layer, r, 'min_label', 'max_label')
pixmap = node.data(Qt.DecorationRole)
im = QImage(pixmap.size(), QImage.Format_ARGB32)
im.fill(QColor(255, 255, 255))
p = QPainter(im)
p.drawPixmap(0, 0, pixmap)
p.end()
self.assertTrue(self.imageCheck('color_ramp_legend_node_icon', 'color_ramp_legend_node_icon', im, 10))
def test_icon_with_settings(self):
r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200))
# need a layer in order to make legend nodes
layer = QgsVectorLayer('dummy', 'test', 'memory')
layer_tree_layer = QgsLayerTreeLayer(layer)
settings = QgsColorRampLegendNodeSettings()
format = QgsBasicNumericFormat()
format.setShowTrailingZeros(True)
format.setNumberDecimalPlaces(3)
settings.setNumericFormat(format)
settings.setDirection(QgsColorRampLegendNodeSettings.MaximumToMinimum)
node = TestColorRampLegend(layer_tree_layer, r, settings, 5, 10)
pixmap = node.data(Qt.DecorationRole)
im = QImage(pixmap.size(), QImage.Format_ARGB32)
im.fill(QColor(255, 255, 255))
p = QPainter(im)
p.drawPixmap(0, 0, pixmap)
p.end()
self.assertTrue(self.imageCheck('color_ramp_legend_node_settings_icon', 'color_ramp_legend_node_settings_icon', im, 10))
def test_icon_prefix_suffix(self):
r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200))
# need a layer in order to make legend nodes
layer = QgsVectorLayer('dummy', 'test', 'memory')
layer_tree_layer = QgsLayerTreeLayer(layer)
settings = QgsColorRampLegendNodeSettings()
settings.setPrefix('pref ')
settings.setSuffix(' suff')
node = TestColorRampLegend(layer_tree_layer, r, settings, 5, 10)
pixmap = node.data(Qt.DecorationRole)
im = QImage(pixmap.size(), QImage.Format_ARGB32)
im.fill(QColor(255, 255, 255))
p = QPainter(im)
p.drawPixmap(0, 0, pixmap)
p.end()
self.assertTrue(self.imageCheck('color_ramp_legend_node_prefix_suffix_icon', 'color_ramp_legend_node_prefix_suffix_icon', im, 10))
def test_icon_horizontal(self):
r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200))
# need a layer in order to make legend nodes
layer = QgsVectorLayer('dummy', 'test', 'memory')
layer_tree_layer = QgsLayerTreeLayer(layer)
settings = QgsColorRampLegendNodeSettings()
settings.setOrientation(Qt.Horizontal)
node = TestColorRampLegend(layer_tree_layer, r, settings, 5, 10)
pixmap = node.data(Qt.DecorationRole)
im = QImage(pixmap.size(), QImage.Format_ARGB32)
im.fill(QColor(255, 255, 255))
p = QPainter(im)
p.drawPixmap(0, 0, pixmap)
p.end()
self.assertTrue(self.imageCheck('color_ramp_legend_node_horizontal_icon', 'color_ramp_legend_node_horizontal_icon', im, 10))
def test_icon_horizontal_flipped(self):
r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200))
# need a layer in order to make legend nodes
layer = QgsVectorLayer('dummy', 'test', 'memory')
layer_tree_layer = QgsLayerTreeLayer(layer)
settings = QgsColorRampLegendNodeSettings()
settings.setDirection(QgsColorRampLegendNodeSettings.MaximumToMinimum)
settings.setOrientation(Qt.Horizontal)
node = TestColorRampLegend(layer_tree_layer, r, settings, 5, 10)
pixmap = node.data(Qt.DecorationRole)
im = QImage(pixmap.size(), QImage.Format_ARGB32)
im.fill(QColor(255, 255, 255))
p = QPainter(im)
p.drawPixmap(0, 0, pixmap)
p.end()
self.assertTrue(self.imageCheck('color_ramp_legend_node_flipped_horizontal_icon', 'color_ramp_legend_node_flipped_horizontal_icon', im, 10))
def test_draw(self):
r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200))
# need a layer in order to make legend nodes
layer = QgsVectorLayer('dummy', 'test', 'memory')
layer_tree_layer = QgsLayerTreeLayer(layer)
node = QgsColorRampLegendNode(layer_tree_layer, r, 'min_label', 'max_label')
ls = QgsLegendSettings()
item_style = ls.style(QgsLegendStyle.SymbolLabel)
item_style.setFont(QgsFontUtils.getStandardTestFont('Bold', 18))
ls.setStyle(QgsLegendStyle.SymbolLabel, item_style)
item_context = QgsLayerTreeModelLegendNode.ItemContext()
image = QImage(400, 250, QImage.Format_ARGB32)
image.fill(QColor(255, 255, 255))
p = QPainter(image)
ms = QgsMapSettings()
ms.setExtent(QgsRectangle(1, 10, 1, 10))
ms.setOutputSize(image.size())
context = QgsRenderContext.fromMapSettings(ms)
context.setPainter(p)
context.setScaleFactor(150 / 25.4) # 150 DPI
p.scale(context.scaleFactor(), context.scaleFactor())
item_context.context = context
item_context.painter = p
item_context.top = 1
item_context.columnLeft = 3
item_context.columnRight = 30
item_context.patchSize = QSizeF(12, 40)
symbol_size = node.drawSymbol(ls, item_context, 0)
node.drawSymbolText(ls, item_context, symbol_size)
p.end()
self.assertTrue(self.imageCheck('color_ramp_legend_node_draw', 'color_ramp_legend_node_draw', image))
def test_draw_settings(self):
r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200))
# need a layer in order to make legend nodes
layer = QgsVectorLayer('dummy', 'test', 'memory')
layer_tree_layer = QgsLayerTreeLayer(layer)
settings = QgsColorRampLegendNodeSettings()
format = QgsBasicNumericFormat()
format.setShowTrailingZeros(True)
format.setNumberDecimalPlaces(3)
settings.setNumericFormat(format)
settings.setDirection(QgsColorRampLegendNodeSettings.MaximumToMinimum)
node = QgsColorRampLegendNode(layer_tree_layer, r, settings, 5, 10)
ls = QgsLegendSettings()
item_style = ls.style(QgsLegendStyle.SymbolLabel)
item_style.setFont(QgsFontUtils.getStandardTestFont('Bold', 18))
ls.setStyle(QgsLegendStyle.SymbolLabel, item_style)
item_context = QgsLayerTreeModelLegendNode.ItemContext()
image = QImage(400, 250, QImage.Format_ARGB32)
image.fill(QColor(255, 255, 255))
p = QPainter(image)
ms = QgsMapSettings()
ms.setExtent(QgsRectangle(1, 10, 1, 10))
ms.setOutputSize(image.size())
context = QgsRenderContext.fromMapSettings(ms)
context.setPainter(p)
context.setScaleFactor(150 / 25.4) # 150 DPI
p.scale(context.scaleFactor(), context.scaleFactor())
item_context.context = context
item_context.painter = p
item_context.top = 1
item_context.columnLeft = 3
item_context.columnRight = 30
item_context.patchSize = QSizeF(12, 40)
symbol_size = node.drawSymbol(ls, item_context, 0)
node.drawSymbolText(ls, item_context, symbol_size)
p.end()
self.assertTrue(self.imageCheck('color_ramp_legend_node_settings_draw', 'color_ramp_legend_node_settings_draw', image))
def test_draw_prefix_suffix(self):
r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200))
# need a layer in order to make legend nodes
layer = QgsVectorLayer('dummy', 'test', 'memory')
layer_tree_layer = QgsLayerTreeLayer(layer)
settings = QgsColorRampLegendNodeSettings()
settings.setPrefix('pref ')
settings.setSuffix(' suff')
node = QgsColorRampLegendNode(layer_tree_layer, r, settings, 5, 10)
ls = QgsLegendSettings()
item_style = ls.style(QgsLegendStyle.SymbolLabel)
item_style.setFont(QgsFontUtils.getStandardTestFont('Bold', 18))
ls.setStyle(QgsLegendStyle.SymbolLabel, item_style)
item_context = QgsLayerTreeModelLegendNode.ItemContext()
image = QImage(400, 250, QImage.Format_ARGB32)
image.fill(QColor(255, 255, 255))
p = QPainter(image)
ms = QgsMapSettings()
ms.setExtent(QgsRectangle(1, 10, 1, 10))
ms.setOutputSize(image.size())
context = QgsRenderContext.fromMapSettings(ms)
context.setPainter(p)
context.setScaleFactor(150 / 25.4) # 150 DPI
p.scale(context.scaleFactor(), context.scaleFactor())
item_context.context = context
item_context.painter = p
item_context.top = 1
item_context.columnLeft = 3
item_context.columnRight = 30
item_context.patchSize = QSizeF(12, 40)
symbol_size = node.drawSymbol(ls, item_context, 0)
node.drawSymbolText(ls, item_context, symbol_size)
p.end()
self.assertTrue(self.imageCheck('color_ramp_legend_node_prefix_suffix_draw', 'color_ramp_legend_node_prefix_suffix_draw', image))
def test_draw_text_format(self):
r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200))
# need a layer in order to make legend nodes
layer = QgsVectorLayer('dummy', 'test', 'memory')
layer_tree_layer = QgsLayerTreeLayer(layer)
settings = QgsColorRampLegendNodeSettings()
tf = QgsTextFormat()
tf.setFont(QgsFontUtils.getStandardTestFont('Bold', 18))
tf.setSize(30)
tf.setColor(QColor(200, 100, 50))
settings.setTextFormat(tf)
node = QgsColorRampLegendNode(layer_tree_layer, r, settings, 5, 10)
ls = QgsLegendSettings()
item_style = ls.style(QgsLegendStyle.SymbolLabel)
item_style.setFont(QgsFontUtils.getStandardTestFont('Bold', 18))
ls.setStyle(QgsLegendStyle.SymbolLabel, item_style)
item_context = QgsLayerTreeModelLegendNode.ItemContext()
image = QImage(400, 250, QImage.Format_ARGB32)
image.fill(QColor(255, 255, 255))
p = QPainter(image)
ms = QgsMapSettings()
ms.setExtent(QgsRectangle(1, 10, 1, 10))
ms.setOutputSize(image.size())
context = QgsRenderContext.fromMapSettings(ms)
context.setPainter(p)
context.setScaleFactor(150 / 25.4) # 150 DPI
p.scale(context.scaleFactor(), context.scaleFactor())
item_context.context = context
item_context.painter = p
item_context.top = 1
item_context.columnLeft = 3
item_context.columnRight = 30
item_context.patchSize = QSizeF(12, 40)
symbol_size = node.drawSymbol(ls, item_context, 0)
node.drawSymbolText(ls, item_context, symbol_size)
p.end()
self.assertTrue(self.imageCheck('color_ramp_legend_node_text_format_draw', 'color_ramp_legend_node_text_format_draw', image))
def test_draw_horizontal(self):
r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200))
# need a layer in order to make legend nodes
layer = QgsVectorLayer('dummy', 'test', 'memory')
layer_tree_layer = QgsLayerTreeLayer(layer)
settings = QgsColorRampLegendNodeSettings()
settings.setOrientation(Qt.Horizontal)
node = QgsColorRampLegendNode(layer_tree_layer, r, settings, 5, 10)
ls = QgsLegendSettings()
item_style = ls.style(QgsLegendStyle.SymbolLabel)
item_style.setFont(QgsFontUtils.getStandardTestFont('Bold', 18))
ls.setStyle(QgsLegendStyle.SymbolLabel, item_style)
item_context = QgsLayerTreeModelLegendNode.ItemContext()
image = QImage(400, 250, QImage.Format_ARGB32)
image.fill(QColor(255, 255, 255))
p = QPainter(image)
ms = QgsMapSettings()
ms.setExtent(QgsRectangle(1, 10, 1, 10))
ms.setOutputSize(image.size())
context = QgsRenderContext.fromMapSettings(ms)
context.setPainter(p)
context.setScaleFactor(150 / 25.4) # 150 DPI
p.scale(context.scaleFactor(), context.scaleFactor())
item_context.context = context
item_context.painter = p
item_context.top = 1
item_context.columnLeft = 3
item_context.columnRight = 50
item_context.patchSize = QSizeF(40, 12)
symbol_size = node.drawSymbol(ls, item_context, 0)
node.drawSymbolText(ls, item_context, symbol_size)
p.end()
self.assertTrue(self.imageCheck('color_ramp_legend_node_horizontal_draw', 'color_ramp_legend_node_horizontal_draw', image))
def test_draw_horizontal_reversed(self):
r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200))
# need a layer in order to make legend nodes
layer = QgsVectorLayer('dummy', 'test', 'memory')
layer_tree_layer = QgsLayerTreeLayer(layer)
settings = QgsColorRampLegendNodeSettings()
settings.setOrientation(Qt.Horizontal)
settings.setDirection(QgsColorRampLegendNodeSettings.MaximumToMinimum)
node = QgsColorRampLegendNode(layer_tree_layer, r, settings, 5, 10)
ls = QgsLegendSettings()
item_style = ls.style(QgsLegendStyle.SymbolLabel)
item_style.setFont(QgsFontUtils.getStandardTestFont('Bold', 18))
ls.setStyle(QgsLegendStyle.SymbolLabel, item_style)
item_context = QgsLayerTreeModelLegendNode.ItemContext()
image = QImage(400, 250, QImage.Format_ARGB32)
image.fill(QColor(255, 255, 255))
p = QPainter(image)
ms = QgsMapSettings()
ms.setExtent(QgsRectangle(1, 10, 1, 10))
ms.setOutputSize(image.size())
context = QgsRenderContext.fromMapSettings(ms)
context.setPainter(p)
context.setScaleFactor(150 / 25.4) # 150 DPI
p.scale(context.scaleFactor(), context.scaleFactor())
item_context.context = context
item_context.painter = p
item_context.top = 1
item_context.columnLeft = 3
item_context.columnRight = 50
item_context.patchSize = QSizeF(40, 12)
symbol_size = node.drawSymbol(ls, item_context, 0)
node.drawSymbolText(ls, item_context, symbol_size)
p.end()
self.assertTrue(self.imageCheck('color_ramp_legend_node_flipped_horizontal_draw', 'color_ramp_legend_node_flipped_horizontal_draw', image))
def imageCheck(self, name, reference_image, image, size_tolerance=0):
TestQgsColorRampLegendNode.report += "<h2>Render {}</h2>\n".format(name)
temp_dir = QDir.tempPath() + '/'
file_name = temp_dir + name + ".png"
image.save(file_name, "PNG")
checker = QgsMultiRenderChecker()
checker.setControlPathPrefix("color_ramp_legend_node")
checker.setControlName("expected_" + reference_image)
checker.setRenderedImage(file_name)
checker.setColorTolerance(2)
checker.setSizeTolerance(size_tolerance, size_tolerance)
result = checker.runTest(name, 20)
TestQgsColorRampLegendNode.report += checker.report()
return result
if __name__ == '__main__':
unittest.main()
| gpl-2.0 |
parsonsc/H2only | wp-content/plugins/justgiving/lib/ApiClients/Model/CreateAccountRequest.php | 301 | <?php
include_once 'Address.php';
class CreateAccountRequest
{
public $reference;
public $title;
public $firstName;
public $lastName;
public $address;
public $email;
public $password;
public $acceptTermsAndConditions;
public function __construct()
{
$this->address = new Address();
}
} | gpl-2.0 |
lostdj/Jaklin-OpenJFX | apps/scenebuilder/SceneBuilderKit/src/com/oracle/javafx/scenebuilder/kit/editor/panel/content/guides/SegmentIndex.java | 3070 | /*
* Copyright (c) 2012, 2014, Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
* - Neither the name of Oracle Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.oracle.javafx.scenebuilder.kit.editor.panel.content.guides;
import com.oracle.javafx.scenebuilder.kit.util.MathUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
*
*/
public class SegmentIndex {
private final List<AbstractSegment> segments = new ArrayList<>();
private boolean sorted;
public void addSegment(AbstractSegment s) {
segments.add(s);
sorted = false;
}
public void clear() {
segments.clear();
}
public List<AbstractSegment> match(double targetLength, double threshold) {
assert targetLength >= 0;
assert threshold >= 0;
if (sorted == false) {
Collections.sort(segments);
}
double bestDelta = Double.MAX_VALUE;
final List<AbstractSegment> result = new ArrayList<>();
for (AbstractSegment s : segments) {
final double delta = Math.abs(s.getLength() - targetLength);
if (delta < threshold) {
if (MathUtils.equals(delta, bestDelta)) {
result.add(s);
} else if (delta < bestDelta) {
bestDelta = delta;
result.clear();
result.add(s);
}
}
}
return result;
}
}
| gpl-2.0 |
GlidingShadow/Applied-Energistics-2 | src/main/java/appeng/parts/layers/LayerISidedInventory.java | 5855 | /*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.parts.layers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.util.ForgeDirection;
import appeng.api.parts.IPart;
import appeng.api.parts.IPartHost;
import appeng.api.parts.LayerBase;
/**
* Inventory wrapper for parts,
*
* this is considerably more complicated then the other wrappers as it requires creating a "unified inventory".
*
* You must use {@link ISidedInventory} instead of {@link IInventory}.
*
* If your inventory changes in between placement and removal, you must trigger a PartChange on the {@link IPartHost} so
* it can recalculate the inventory wrapper.
*/
public class LayerISidedInventory extends LayerBase implements ISidedInventory
{
// a simple empty array for empty stuff..
private static final int[] NULL_SIDES = new int[] {};
InvLayerData invLayer = null;
/**
* Recalculate inventory wrapper cache.
*/
@Override
public void notifyNeighbors()
{
// cache of inventory state.
int[][] sideData = null;
List<ISidedInventory> inventories = null;
List<InvSot> slots = null;
inventories = new ArrayList<ISidedInventory>();
int slotCount = 0;
for( ForgeDirection side : ForgeDirection.VALID_DIRECTIONS )
{
IPart bp = this.getPart( side );
if( bp instanceof ISidedInventory )
{
ISidedInventory part = (ISidedInventory) bp;
slotCount += part.getSizeInventory();
inventories.add( part );
}
}
if( inventories.isEmpty() || slotCount == 0 )
{
inventories = null;
}
else
{
sideData = new int[][] { NULL_SIDES, NULL_SIDES, NULL_SIDES, NULL_SIDES, NULL_SIDES, NULL_SIDES };
slots = new ArrayList<InvSot>( Collections.nCopies( slotCount, (InvSot) null ) );
int offsetForLayer = 0;
int offsetForPart = 0;
for( ISidedInventory sides : inventories )
{
offsetForPart = 0;
slotCount = sides.getSizeInventory();
ForgeDirection currentSide = ForgeDirection.UNKNOWN;
for( ForgeDirection side : ForgeDirection.VALID_DIRECTIONS )
{
if( this.getPart( side ) == sides )
{
currentSide = side;
break;
}
}
int[] cSidesList = sideData[currentSide.ordinal()] = new int[slotCount];
for( int cSlot = 0; cSlot < slotCount; cSlot++ )
{
cSidesList[cSlot] = offsetForLayer;
slots.set( offsetForLayer, new InvSot( sides, offsetForPart ) );
offsetForLayer++;
offsetForPart++;
}
}
}
if( sideData == null || slots == null )
{
this.invLayer = null;
}
else
{
this.invLayer = new InvLayerData( sideData, inventories, slots );
}
// make sure inventory is updated before we call FMP.
super.notifyNeighbors();
}
@Override
public int getSizeInventory()
{
if( this.invLayer == null )
{
return 0;
}
return this.invLayer.getSizeInventory();
}
@Override
public ItemStack getStackInSlot( int slot )
{
if( this.invLayer == null )
{
return null;
}
return this.invLayer.getStackInSlot( slot );
}
@Override
public ItemStack decrStackSize( int slot, int amount )
{
if( this.invLayer == null )
{
return null;
}
return this.invLayer.decreaseStackSize( slot, amount );
}
@Override
public ItemStack getStackInSlotOnClosing( int slot )
{
return null;
}
@Override
public void setInventorySlotContents( int slot, ItemStack itemstack )
{
if( this.invLayer == null )
{
return;
}
this.invLayer.setInventorySlotContents( slot, itemstack );
}
@Override
public String getInventoryName()
{
return "AEMultiPart";
}
@Override
public boolean hasCustomInventoryName()
{
return false;
}
@Override
public int getInventoryStackLimit()
{
return 64; // no options here.
}
@Override
public boolean isUseableByPlayer( EntityPlayer entityplayer )
{
return false;
}
@Override
public void openInventory()
{
}
@Override
public void closeInventory()
{
}
@Override
public boolean isItemValidForSlot( int slot, ItemStack itemstack )
{
if( this.invLayer == null )
{
return false;
}
return this.invLayer.isItemValidForSlot( slot, itemstack );
}
@Override
public void markDirty()
{
if( this.invLayer != null )
{
this.invLayer.markDirty();
}
super.markForSave();
}
@Override
public int[] getAccessibleSlotsFromSide( int side )
{
if( this.invLayer != null )
{
return this.invLayer.getAccessibleSlotsFromSide( side );
}
return NULL_SIDES;
}
@Override
public boolean canInsertItem( int slot, ItemStack itemstack, int side )
{
if( this.invLayer == null )
{
return false;
}
return this.invLayer.canInsertItem( slot, itemstack, side );
}
@Override
public boolean canExtractItem( int slot, ItemStack itemstack, int side )
{
if( this.invLayer == null )
{
return false;
}
return this.invLayer.canExtractItem( slot, itemstack, side );
}
}
| gpl-3.0 |
Progressive-Learning-Platform/progressive-learning-platform | reference/sw/PLPTool/src/plptool/mods/VGACanvas.java | 1186 | /*
Copyright 2010 David Fritz, Brian Gordon, Wira Mulia
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package plptool.mods;
import java.awt.image.BufferedImage;
import java.awt.Graphics;
import java.awt.Color;
/**
*
* @author CAESAR
*/
public class VGACanvas extends javax.swing.JPanel {
private BufferedImage I;
public VGACanvas(BufferedImage I) {
this.I = I;
}
public void setImage(BufferedImage I) {
this.I = I;
}
@Override
public void paint(Graphics g) {
g.drawImage(I, 0, 0, Color.BLACK, null);
}
}
| gpl-3.0 |
gratefulfrog/SPI | RPI/Python/serialApp/SerialSlave2560_wire/board.cpp | 655 | #include "board.h"
Board::Board(uint8_t numberADCs, const uint8_t nbChannelVec[]) : nbADCs(numberADCs){
adcMgrVec = new ADCMgr*[nbADCs];
for (uint8_t i=0;i<nbADCs;i++){
if (nbChannelVec[i]>0){
adcMgrVec[i] = new YADCMgr(i+1,nbChannelVec[i]); // init adcMgr vec if there are channels, if not, skip
}
else{
adcMgrVec[i] = NULL;
}
}
}
boardID Board::getGUID() const{
return AA025UID().getGuidID();
}
float Board::getValue(uint8_t adcID, uint8_t channelID) const{
return adcMgrVec[adcID]->getValue(channelID);
}
uint8_t Board::getMgrNbChannels(uint8_t mgrId) const{
return adcMgrVec[mgrId]->nbChannels;
}
| gpl-3.0 |
FarhadF/mautic | app/bundles/UserBundle/Model/UserModel.php | 9148 | <?php
/*
* @copyright 2014 Mautic Contributors. All rights reserved
* @author Mautic
*
* @link http://mautic.org
*
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
namespace Mautic\UserBundle\Model;
use Mautic\CoreBundle\Model\FormModel;
use Mautic\EmailBundle\Helper\MailHelper;
use Mautic\UserBundle\Entity\User;
use Mautic\UserBundle\Event\StatusChangeEvent;
use Mautic\UserBundle\Event\UserEvent;
use Mautic\UserBundle\UserEvents;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
/**
* Class UserModel.
*/
class UserModel extends FormModel
{
/**
* @var MailHelper
*/
protected $mailHelper;
public function __construct(MailHelper $mailHelper)
{
$this->mailHelper = $mailHelper;
}
/**
* Define statuses that are supported.
*
* @var array
*/
private $supportedOnlineStatuses = [
'online',
'idle',
'away',
'manualaway',
'dnd',
'offline',
];
/**
* {@inheritdoc}
*/
public function getRepository()
{
return $this->em->getRepository('MauticUserBundle:User');
}
/**
* {@inheritdoc}
*/
public function getPermissionBase()
{
return 'user:users';
}
/**
* {@inheritdoc}
*
* @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
*/
public function saveEntity($entity, $unlock = true)
{
if (!$entity instanceof User) {
throw new MethodNotAllowedHttpException(['User'], 'Entity must be of class User()');
}
parent::saveEntity($entity, $unlock);
}
/**
* Checks for a new password and rehashes if necessary.
*
* @param User $entity
* @param PasswordEncoderInterface $encoder
* @param string $submittedPassword
*
* @return string
*/
public function checkNewPassword(User $entity, PasswordEncoderInterface $encoder, $submittedPassword)
{
if (!empty($submittedPassword)) {
//hash the clear password submitted via the form
return $encoder->encodePassword($submittedPassword, $entity->getSalt());
}
return $entity->getPassword();
}
/**
* {@inheritdoc}
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function createForm($entity, $formFactory, $action = null, $options = [])
{
if (!$entity instanceof User) {
throw new MethodNotAllowedHttpException(['User'], 'Entity must be of class User()');
}
if (!empty($action)) {
$options['action'] = $action;
}
return $formFactory->create('user', $entity, $options);
}
/**
* {@inheritdoc}
*/
public function getEntity($id = null)
{
if ($id === null) {
return new User();
}
$entity = parent::getEntity($id);
if ($entity) {
//add user's permissions
$entity->setActivePermissions(
$this->em->getRepository('MauticUserBundle:Permission')->getPermissionsByRole($entity->getRole())
);
}
return $entity;
}
/**
* {@inheritdoc}
*
* @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
*/
protected function dispatchEvent($action, &$entity, $isNew = false, Event $event = null)
{
if (!$entity instanceof User) {
throw new MethodNotAllowedHttpException(['User'], 'Entity must be of class User()');
}
switch ($action) {
case 'pre_save':
$name = UserEvents::USER_PRE_SAVE;
break;
case 'post_save':
$name = UserEvents::USER_POST_SAVE;
break;
case 'pre_delete':
$name = UserEvents::USER_PRE_DELETE;
break;
case 'post_delete':
$name = UserEvents::USER_POST_DELETE;
break;
default:
return null;
}
if ($this->dispatcher->hasListeners($name)) {
if (empty($event)) {
$event = new UserEvent($entity, $isNew);
$event->setEntityManager($this->em);
}
$this->dispatcher->dispatch($name, $event);
return $event;
}
return null;
}
/**
* Get list of entities for autopopulate fields.
*
* @param string $type
* @param string $filter
* @param int $limit
*
* @return array
*/
public function getLookupResults($type, $filter = '', $limit = 10)
{
$results = [];
switch ($type) {
case 'role':
$results = $this->em->getRepository('MauticUserBundle:Role')->getRoleList($filter, $limit);
break;
case 'user':
$results = $this->em->getRepository('MauticUserBundle:User')->getUserList($filter, $limit);
break;
case 'position':
$results = $this->em->getRepository('MauticUserBundle:User')->getPositionList($filter, $limit);
break;
}
return $results;
}
/**
* Resets the user password and emails it.
*
* @param User $user
* @param PasswordEncoderInterface $encoder
* @param string $newPassword
*/
public function resetPassword(User $user, PasswordEncoderInterface $encoder, $newPassword)
{
$encodedPassword = $this->checkNewPassword($user, $encoder, $newPassword);
$user->setPassword($encodedPassword);
$this->saveEntity($user);
}
/**
* @param User $user
*
* @return string
*/
protected function getResetToken(User $user)
{
/** @var \DateTime $lastLogin */
$lastLogin = $user->getLastLogin();
$dateTime = ($lastLogin instanceof \DateTime) ? $lastLogin->format('Y-m-d H:i:s') : null;
return hash('sha256', $user->getUsername().$user->getEmail().$dateTime);
}
/**
* @param User $user
* @param string $token
*
* @return bool
*/
public function confirmResetToken(User $user, $token)
{
$resetToken = $this->getResetToken($user);
return hash_equals($token, $resetToken);
}
/**
* @param User $user
*/
public function sendResetEmail(User $user)
{
$mailer = $this->mailHelper->getMailer();
$resetToken = $this->getResetToken($user);
$resetLink = $this->router->generate('mautic_user_passwordresetconfirm', ['token' => $resetToken], true);
$mailer->setTo([$user->getEmail() => $user->getName()]);
$mailer->setSubject($this->translator->trans('mautic.user.user.passwordreset.subject'));
$text = $this->translator->trans(
'mautic.user.user.passwordreset.email.body',
['%name%' => $user->getFirstName(), '%resetlink%' => '<a href="'.$resetLink.'">'.$resetLink.'</a>']
);
$text = str_replace('\\n', "\n", $text);
$html = nl2br($text);
$mailer->setBody($html);
$mailer->setPlainText(strip_tags($text));
$mailer->send();
}
/**
* Set user preference.
*
* @param $key
* @param null $value
* @param User $user
*/
public function setPreference($key, $value = null, User $user = null)
{
if ($user == null) {
$user = $this->userHelper->getUser();
}
$preferences = $user->getPreferences();
$preferences[$key] = $value;
$user->setPreferences($preferences);
$this->getRepository()->saveEntity($user);
}
/**
* Get user preference.
*
* @param $key
* @param null $default
* @param User $user
*/
public function getPreference($key, $default = null, User $user = null)
{
if ($user == null) {
$user = $this->userHelper->getUser();
}
$preferences = $user->getPreferences();
return (isset($preferences[$key])) ? $preferences[$key] : $default;
}
/**
* @param $status
*/
public function setOnlineStatus($status)
{
$status = strtolower($status);
if (in_array($status, $this->supportedOnlineStatuses)) {
if ($this->userHelper->getUser()->getId()) {
$this->userHelper->getUser()->setOnlineStatus($status);
$this->getRepository()->saveEntity($this->userHelper->getUser());
if ($this->dispatcher->hasListeners(UserEvents::STATUS_CHANGE)) {
$event = new StatusChangeEvent($this->userHelper->getUser());
$this->dispatcher->dispatch(UserEvents::STATUS_CHANGE, $event);
}
}
}
}
}
| gpl-3.0 |