code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
using Machine.Specifications; using PlainElastic.Net.IndexSettings; using PlainElastic.Net.Utils; namespace PlainElastic.Net.Tests.Builders.IndexSettings { [Subject(typeof(NGramTokenFilter))] class When_complete_NGramTokenFilter_built { Because of = () => result = new NGramTokenFilter() .Name("name") .Version("3.6") .MinGram(2) .MaxGram(3) .CustomPart("{ Custom }") .ToString(); It should_start_with_name = () => result.ShouldStartWith("'name': {".AltQuote()); It should_contain_type_part = () => result.ShouldContain("'type': 'nGram'".AltQuote()); It should_contain_version_part = () => result.ShouldContain("'version': '3.6'".AltQuote()); It should_contain_min_gram_part = () => result.ShouldContain("'min_gram': 2".AltQuote()); It should_contain_max_gram_part = () => result.ShouldContain("'max_gram': 3".AltQuote()); It should_contain_custom_part = () => result.ShouldContain("{ Custom }".AltQuote()); It should_return_correct_result = () => result.ShouldEqual(("'name': { " + "'type': 'nGram'," + "'version': '3.6'," + "'min_gram': 2," + "'max_gram': 3," + "{ Custom } }").AltQuote()); private static string result; } }
yonglehou/PlainElastic.Net
src/PlainElastic.Net.Tests/Builders/Analysis/TokenFilters/NGram/When_complete_NGramTokenFilter_built.cs
C#
mit
1,835
# frozen_string_literal: true require 'spec_helper' RSpec.describe DeleteUserWorker do let!(:user) { create(:user) } let!(:current_user) { create(:user) } it "calls the DeleteUserWorker with the params it was given" do expect_next_instance_of(Users::DestroyService) do |service| expect(service).to receive(:execute).with(user, {}) end described_class.new.perform(current_user.id, user.id) end it "uses symbolized keys" do expect_next_instance_of(Users::DestroyService) do |service| expect(service).to receive(:execute).with(user, test: "test") end described_class.new.perform(current_user.id, user.id, "test" => "test") end end
mmkassem/gitlabhq
spec/workers/delete_user_worker_spec.rb
Ruby
mit
690
// Copyright (c) Umbraco. // See LICENSE for more details. using Microsoft.Extensions.Logging; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Serialization; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; namespace Umbraco.Cms.Core.PropertyEditors { /// <summary> /// Represents a slider editor. /// </summary> [DataEditor( Constants.PropertyEditors.Aliases.Slider, "Slider", "slider", Icon = "icon-navigation-horizontal")] public class SliderPropertyEditor : DataEditor { private readonly IIOHelper _ioHelper; /// <summary> /// Initializes a new instance of the <see cref="SliderPropertyEditor"/> class. /// </summary> public SliderPropertyEditor( IDataValueEditorFactory dataValueEditorFactory, IIOHelper ioHelper) : base(dataValueEditorFactory) { _ioHelper = ioHelper; } /// <inheritdoc /> protected override IConfigurationEditor CreateConfigurationEditor() { return new SliderConfigurationEditor(_ioHelper); } } }
umbraco/Umbraco-CMS
src/Umbraco.Infrastructure/PropertyEditors/SliderPropertyEditor.cs
C#
mit
1,153
using Umbraco.Cms.Core.DependencyInjection; namespace Umbraco.Cms.Core.Composing { /// <summary> /// Provides a base class for composers which compose a component. /// </summary> /// <typeparam name="TComponent">The type of the component</typeparam> public abstract class ComponentComposer<TComponent> : IComposer where TComponent : IComponent { /// <inheritdoc /> public virtual void Compose(IUmbracoBuilder builder) { builder.Components().Append<TComponent>(); } // note: thanks to this class, a component that does not compose anything can be // registered with one line: // public class MyComponentComposer : ComponentComposer<MyComponent> { } } }
umbraco/Umbraco-CMS
src/Umbraco.Core/Composing/ComponentComposer.cs
C#
mit
761
'use strict'; var dynamoose = require('../'); dynamoose.AWS.config.update({ accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-east-1' }); dynamoose.local(); var should = require('should'); var Cat, Cat2; describe('Model', function (){ this.timeout(5000); before(function(done) { this.timeout(12000); dynamoose.setDefaults({ prefix: 'test-' }); Cat = dynamoose.model('Cat', { id: Number, name: String, owner: String, age: { type: Number }, vet:{ name: String, address: String }, ears:[{ name: String }], legs: [String], more: Object, array: Array }, {useDocumentTypes: true}); // Create a model with a range key Cat2 = dynamoose.model('Cat2', { ownerId: { type: Number, hashKey: true }, name: { type: String, rangeKey: true } }); done(); }); after(function (done) { delete dynamoose.models['test-Cat']; done(); }); it('Create simple model', function (done) { this.timeout(12000); Cat.should.have.property('$__'); Cat.$__.name.should.eql('test-Cat'); Cat.$__.options.should.have.property('create', true); var schema = Cat.$__.schema; should.exist(schema); schema.attributes.id.type.name.should.eql('number'); should(schema.attributes.id.isSet).not.be.ok; should.not.exist(schema.attributes.id.default); should.not.exist(schema.attributes.id.validator); should(schema.attributes.id.required).not.be.ok; schema.attributes.name.type.name.should.eql('string'); schema.attributes.name.isSet.should.not.be.ok; should.not.exist(schema.attributes.name.default); should.not.exist(schema.attributes.name.validator); should(schema.attributes.name.required).not.be.ok; schema.hashKey.should.equal(schema.attributes.id); // should be same object should.not.exist(schema.rangeKey); var kitten = new Cat( { id: 1, name: 'Fluffy', vet:{name:'theVet', address:'12 somewhere'}, ears:[{name:'left'}, {name:'right'}], legs: ['front right', 'front left', 'back right', 'back left'], more: {fovorites: {food: 'fish'}}, array: [{one: '1'}] } ); kitten.id.should.eql(1); kitten.name.should.eql('Fluffy'); var dynamoObj = schema.toDynamo(kitten); dynamoObj.should.eql( { ears: { L: [ { M: { name: { S: 'left' } } }, { M: { name: { S: 'right' } } } ] }, id: { N: '1' }, name: { S: 'Fluffy' }, vet: { M: { address: { S: '12 somewhere' }, name: { S: 'theVet' } } }, legs: { SS: ['front right', 'front left', 'back right', 'back left']}, more: { S: '{"fovorites":{"food":"fish"}}' }, array: { S: '[{"one":"1"}]' } }); kitten.save(done); }); it('Create simple model with range key', function () { Cat2.should.have.property('$__'); Cat2.$__.name.should.eql('test-Cat2'); Cat2.$__.options.should.have.property('create', true); var schema = Cat2.$__.schema; should.exist(schema); schema.attributes.ownerId.type.name.should.eql('number'); should(schema.attributes.ownerId.isSet).not.be.ok; should.not.exist(schema.attributes.ownerId.default); should.not.exist(schema.attributes.ownerId.validator); should(schema.attributes.ownerId.required).not.be.ok; schema.attributes.name.type.name.should.eql('string'); schema.attributes.name.isSet.should.not.be.ok; should.not.exist(schema.attributes.name.default); should.not.exist(schema.attributes.name.validator); should(schema.attributes.name.required).not.be.ok; schema.hashKey.should.equal(schema.attributes.ownerId); // should be same object schema.rangeKey.should.equal(schema.attributes.name); }); it('Get item for model', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.should.have.property('id', 1); model.should.have.property('name', 'Fluffy'); model.should.have.property('vet', { address: '12 somewhere', name: 'theVet' }); model.should.have.property('$__'); done(); }); }); it('Save existing item', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.name.should.eql('Fluffy'); model.name = 'Bad Cat'; model.vet.name = 'Tough Vet'; model.ears[0].name = 'right'; model.save(function (err) { should.not.exist(err); Cat.get({id: 1}, {consistent: true}, function(err, badCat) { should.not.exist(err); badCat.name.should.eql('Bad Cat'); badCat.vet.name.should.eql('Tough Vet'); badCat.ears[0].name.should.eql('right'); badCat.ears[1].name.should.eql('right'); done(); }); }); }); }); it('Save existing item with a false condition', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.name.should.eql('Bad Cat'); model.name = 'Whiskers'; model.save({ condition: '#name = :name', conditionNames: { name: 'name' }, conditionValues: { name: 'Muffin' } }, function (err) { should.exist(err); err.code.should.eql('ConditionalCheckFailedException'); Cat.get({id: 1}, {consistent: true}, function(err, badCat) { should.not.exist(err); badCat.name.should.eql('Bad Cat'); done(); }); }); }); }); it('Save existing item with a true condition', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.name.should.eql('Bad Cat'); model.name = 'Whiskers'; model.save({ condition: '#name = :name', conditionNames: { name: 'name' }, conditionValues: { name: 'Bad Cat' } }, function (err) { should.not.exist(err); Cat.get({id: 1}, {consistent: true}, function(err, whiskers) { should.not.exist(err); whiskers.name.should.eql('Whiskers'); done(); }); }); }); }); it('Save with a pre hook', function (done) { var flag = false; Cat.pre('save', function (next) { flag = true; next(); }); Cat.get(1, function(err, model) { should.not.exist(err); should.exist(model); model.name.should.eql('Whiskers'); model.name = 'Fluffy'; model.vet.name = 'Nice Guy'; model.save(function (err) { should.not.exist(err); Cat.get({id: 1}, {consistent: true}, function(err, badCat) { should.not.exist(err); badCat.name.should.eql('Fluffy'); badCat.vet.name.should.eql('Nice Guy'); flag.should.be.true; Cat.removePre('save'); done(); }); }); }); }); it('Deletes item', function (done) { var cat = new Cat({id: 1}); cat.delete(done); }); it('Get missing item', function (done) { Cat.get(1, function(err, model) { should.not.exist(err); should.not.exist(model); done(); }); }); it('Static Creates new item', function (done) { Cat.create({id: 666, name: 'Garfield'}, function (err, garfield) { should.not.exist(err); should.exist(garfield); garfield.id.should.eql(666); done(); }); }); it('Static Creates new item with range key', function (done) { Cat2.create({ownerId: 666, name: 'Garfield'}, function (err, garfield) { should.not.exist(err); should.exist(garfield); garfield.ownerId.should.eql(666); done(); }); }); it('Prevent duplicate create', function (done) { Cat.create({id: 666, name: 'Garfield'}, function (err, garfield) { should.exist(err); should.not.exist(garfield); done(); }); }); it('Prevent duplicate create with range key', function (done) { Cat2.create({ownerId: 666, name: 'Garfield'}, function (err, garfield) { should.exist(err); should.not.exist(garfield); done(); }); }); it('Static Creates second item', function (done) { Cat.create({id: 777, name: 'Catbert'}, function (err, catbert) { should.not.exist(err); should.exist(catbert); catbert.id.should.eql(777); done(); }); }); it('BatchGet items', function (done) { Cat.batchGet([{id: 666}, {id: 777}], function (err, cats) { cats.length.should.eql(2); done(); }); }); it('Static Delete', function (done) { Cat.delete(666, function (err) { should.not.exist(err); Cat.get(666, function (err, delCat) { should.not.exist(err); should.not.exist(delCat); Cat.delete(777, done); }); }); }); it('Static Delete with range key', function (done) { Cat2.delete({ ownerId: 666, name: 'Garfield' }, function (err) { should.not.exist(err); Cat2.get({ ownerId: 666, name: 'Garfield' }, function (err, delCat) { should.not.exist(err); should.not.exist(delCat); done(); }); }); }); it('Static Creates new item', function (done) { Cat.create({id: 666, name: 'Garfield'}, function (err, garfield) { should.not.exist(err); should.exist(garfield); garfield.id.should.eql(666); done(); }); }); it('Static Delete with update', function (done) { Cat.delete(666, { update: true }, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(666); data.name.should.eql('Garfield'); Cat.get(666, function (err, delCat) { should.not.exist(err); should.not.exist(delCat); done(); }); }); }); it('Static Delete with update failure', function (done) { Cat.delete(666, { update: true }, function (err) { should.exist(err); err.statusCode.should.eql(400); err.code.should.eql('ConditionalCheckFailedException'); done(); }); }); describe('Model.update', function (){ before(function (done) { var stray = new Cat({id: 999, name: 'Tom'}); stray.save(done); }); it('False condition', function (done) { Cat.update({id: 999}, {name: 'Oliver'}, { condition: '#name = :name', conditionNames: { name: 'name' }, conditionValues: { name: 'Muffin' } }, function (err) { should.exist(err); Cat.get(999, function (err, tomcat) { should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); should.not.exist(tomcat.owner); should.not.exist(tomcat.age); done(); }); }); }); it('True condition', function (done) { Cat.update({id: 999}, {name: 'Oliver'}, { condition: '#name = :name', conditionNames: { name: 'name' }, conditionValues: { name: 'Tom' } }, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.name.should.equal('Oliver'); Cat.get(999, function (err, oliver) { should.not.exist(err); should.exist(oliver); oliver.id.should.eql(999); oliver.name.should.eql('Oliver'); should.not.exist(oliver.owner); should.not.exist(oliver.age); done(); }); }); }); it('Default puts attribute', function (done) { Cat.update({id: 999}, {name: 'Tom'}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.name.should.equal('Tom'); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); should.not.exist(tomcat.owner); should.not.exist(tomcat.age); done(); }); }); }); it('Manual puts attribute with removal', function (done) { Cat.update({id: 999}, {$PUT: {name: null}}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); should.not.exist(data.name); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); should.not.exist(tomcat.name); done(); }); }); }); it('Manual puts attribute', function (done) { Cat.update({id: 999}, {$PUT: {name: 'Tom', owner: 'Jerry', age: 3}}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.owner.should.equal('Jerry'); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); tomcat.owner.should.eql('Jerry'); tomcat.age.should.eql(3); done(); }); }); }); it('Add attribute', function (done) { Cat.update({id: 999}, {$ADD: {age: 1}}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); data.age.should.equal(4); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); tomcat.owner.should.eql('Jerry'); tomcat.age.should.eql(4); done(); }); }); }); it('Delete attribute', function (done) { Cat.update({id: 999}, {$DELETE: {owner: null}}, function (err, data) { should.not.exist(err); should.exist(data); data.id.should.eql(999); should.not.exist(data.owner); Cat.get(999, function (err, tomcat){ should.not.exist(err); should.exist(tomcat); tomcat.id.should.eql(999); tomcat.name.should.eql('Tom'); should.not.exist(tomcat.owner); tomcat.age.should.eql(4); done(); }); }); }); }); describe('Model.batchPut', function (){ it('Put new', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat({id: 10+i, name: 'Tom_'+i})); } Cat.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Object.getOwnPropertyNames(result.UnprocessedItems).length.should.eql(0); for (var i=0 ; i<10 ; ++i) { delete cats[i].name; } Cat.batchGet(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); result2.length.should.eql(cats.length); done(); }); }); }); it('Put lots of new items', function (done) { var cats = []; for (var i=0 ; i<100 ; ++i) { cats.push(new Cat({id: 100+i, name: 'Tom_'+i})); } Cat.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Object.getOwnPropertyNames(result.UnprocessedItems).length.should.eql(0); for (var i=0 ; i<100 ; ++i) { delete cats[i].name; } Cat.batchGet(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); result2.length.should.eql(cats.length); done(); }); }); }); it('Put new with range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 10+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Object.getOwnPropertyNames(result.UnprocessedItems).length.should.eql(0); Cat2.batchGet(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); result2.length.should.eql(cats.length); done(); }); }); }); it('Put new without range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 10+i})); } Cat2.batchPut(cats, function (err, result) { should.exist(err); should.not.exist(result); done(); }); }); it('Update items', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat({id: 20+i, name: 'Tom_'+i})); } Cat.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); for (var i=0 ; i<10 ; ++i) { var cat = cats[i]; cat.name = 'John_' + (cat.id + 100); } Cat.batchPut(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); for (var i=0 ; i<10 ; ++i) { delete cats[i].name; } Cat.batchGet(cats, function (err3, result3) { should.not.exist(err3); should.exist(result3); result3.length.should.eql(cats.length); done(); }); }); }); }); it('Update with range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 20+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); for (var i=0 ; i<10 ; ++i) { var cat = cats[i]; cat.name = 'John_' + (cat.ownerId + 100); } Cat2.batchPut(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); Cat2.batchGet(cats, function (err3, result3) { should.not.exist(err3); should.exist(result3); result3.length.should.eql(cats.length); done(); }); }); }); }); it('Update without range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 20+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); for (var i=0 ; i<10 ; ++i) { cats[i].name = null; } Cat2.batchPut(cats, function (err2, result2) { should.exist(err2); should.not.exist(result2); done(); }); }); }); }); describe('Model.batchDelete', function (){ it('Simple delete', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat({id: 30+i, name: 'Tom_'+i})); } Cat.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Cat.batchDelete(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); Cat.batchGet(cats, function (err3, result3) { should.not.exist(err3); should.exist(result3); result3.length.should.eql(0); done(); }); }); }); }); it('Delete with range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 30+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); Cat2.batchDelete(cats, function (err2, result2) { should.not.exist(err2); should.exist(result2); Object.getOwnPropertyNames(result2.UnprocessedItems).length.should.eql(0); Cat2.batchGet(cats, function (err3, result3) { should.not.exist(err3); should.exist(result3); result3.length.should.eql(0); done(); }); }); }); }); it('Delete without range key', function (done) { var cats = []; for (var i=0 ; i<10 ; ++i) { cats.push(new Cat2({ownerId: 30+i, name: 'Tom_'+i})); } Cat2.batchPut(cats, function (err, result) { should.not.exist(err); should.exist(result); for (var i=0 ; i<10 ; ++i) { delete cats[i].name; } Cat2.batchDelete(cats, function (err2, result2) { should.exist(err2); should.not.exist(result2); done(); }); }); }); }); });
benjcooley/dynamoose
test/Model.js
JavaScript
mit
21,235
# -*- coding: utf-8 -*- import os import sys try: from gluon import current except ImportError: print >> sys.stderr, """ The installed version of Web2py is too old -- it does not define current. Please upgrade Web2py to a more recent version. """ # Version of 000_config.py # Increment this if the user should update their running instance VERSION = 1 #def update_check(environment, template="default"): def update_check(settings): """ Check whether the dependencies are sufficient to run Eden @ToDo: Load deployment_settings so that we can configure the update_check - need to rework so that 000_config.py is parsed 1st @param settings: the deployment_settings """ # Get Web2py environment into our globals. #globals().update(**environment) request = current.request # Fatal errors errors = [] # Non-fatal warnings warnings = [] # ------------------------------------------------------------------------- # Check Python libraries # Get mandatory global dependencies app_path = request.folder gr_path = os.path.join(app_path, "requirements.txt") or_path = os.path.join(app_path, "optional_requirements.txt") global_dep = parse_requirements({}, gr_path) optional_dep = parse_requirements({}, or_path) templates = settings.get_template() location = settings.get_template_location() if not isinstance(templates, (tuple, list)): templates = (templates,) template_dep = {} template_optional_dep = {} for template in templates: tr_path = os.path.join(app_path, location, "templates", template, "requirements.txt") tor_path = os.path.join(app_path, location, "templates", template, "optional_requirements.txt") parse_requirements(template_dep, tr_path) parse_requirements(template_optional_dep, tor_path) # Remove optional dependencies which are already accounted for in template dependencies unique = set(optional_dep.keys()).difference(set(template_dep.keys())) for dependency in optional_dep.keys(): if dependency not in unique: del optional_dep[dependency] # Override optional dependency messages from template unique = set(optional_dep.keys()).difference(set(template_optional_dep.keys())) for dependency in optional_dep.keys(): if dependency not in unique: del optional_dep[dependency] errors, warnings = s3_check_python_lib(global_dep, template_dep, template_optional_dep, optional_dep) # @ToDo: Move these to Template # for now this is done in s3db.climate_first_run() if settings.has_module("climate"): if settings.get_database_type() != "postgres": errors.append("Climate unresolved dependency: PostgreSQL required") try: import rpy2 except ImportError: errors.append("Climate unresolved dependency: RPy2 required") try: from Scientific.IO import NetCDF except ImportError: warnings.append("Climate unresolved dependency: NetCDF required if you want to import readings") try: from scipy import stats except ImportError: warnings.append("Climate unresolved dependency: SciPy required if you want to generate graphs on the map") # ------------------------------------------------------------------------- # Check Web2Py version # # Currently, the minimum usable Web2py is determined by whether the # Scheduler is available web2py_minimum_version = "Version 2.4.7-stable+timestamp.2013.05.27.11.49.44" # Offset of datetime in return value of parse_version. datetime_index = 4 web2py_version_ok = True try: from gluon.fileutils import parse_version except ImportError: web2py_version_ok = False if web2py_version_ok: try: web2py_minimum_parsed = parse_version(web2py_minimum_version) web2py_minimum_datetime = web2py_minimum_parsed[datetime_index] web2py_installed_version = request.global_settings.web2py_version if isinstance(web2py_installed_version, str): # Post 2.4.2, request.global_settings.web2py_version is unparsed web2py_installed_parsed = parse_version(web2py_installed_version) web2py_installed_datetime = web2py_installed_parsed[datetime_index] else: # 2.4.2 & earlier style web2py_installed_datetime = web2py_installed_version[datetime_index] web2py_version_ok = web2py_installed_datetime >= web2py_minimum_datetime except: # Will get AttributeError if Web2py's parse_version is too old for # its current version format, which changed in 2.3.2. web2py_version_ok = False if not web2py_version_ok: warnings.append( "The installed version of Web2py is too old to support the current version of Sahana Eden." "\nPlease upgrade Web2py to at least version: %s" % \ web2py_minimum_version) # ------------------------------------------------------------------------- # Create required directories if needed databases_dir = os.path.join(app_path, "databases") try: os.stat(databases_dir) except OSError: # not found, create it os.mkdir(databases_dir) # ------------------------------------------------------------------------- # Copy in Templates # - 000_config.py (machine-specific settings) # - rest are run in-place # template_folder = os.path.join(app_path, "modules", "templates") template_files = { # source : destination "000_config.py" : os.path.join("models", "000_config.py"), } copied_from_template = [] for t in template_files: src_path = os.path.join(template_folder, t) dst_path = os.path.join(app_path, template_files[t]) try: os.stat(dst_path) except OSError: # Not found, copy from template if t == "000_config.py": input = open(src_path) output = open(dst_path, "w") for line in input: if "akeytochange" in line: # Generate a random hmac_key to secure the passwords in case # the database is compromised import uuid hmac_key = uuid.uuid4() line = 'settings.auth.hmac_key = "%s"' % hmac_key output.write(line) output.close() input.close() else: import shutil shutil.copy(src_path, dst_path) copied_from_template.append(template_files[t]) # @ToDo: WebSetup # http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/WebSetup #if not os.path.exists("%s/applications/websetup" % os.getcwd()): # # @ToDo: Check Permissions # # Copy files into this folder (@ToDo: Pythonise) # cp -r private/websetup "%s/applications" % os.getcwd() # Launch WebSetup #redirect(URL(a="websetup", c="default", f="index", # vars=dict(appname=request.application, # firstTime="True"))) else: # Found the file in the destination # Check if it has been edited import re edited_pattern = r"FINISHED_EDITING_\w*\s*=\s*(True|False)" edited_matcher = re.compile(edited_pattern).match has_edited = False with open(dst_path) as f: for line in f: edited_result = edited_matcher(line) if edited_result: has_edited = True edited = edited_result.group(1) break if has_edited and (edited != "True"): errors.append("Please edit %s before starting the system." % t) # Check if it's up to date (i.e. a critical update requirement) version_pattern = r"VERSION =\s*([0-9]+)" version_matcher = re.compile(version_pattern).match has_version = False with open(dst_path) as f: for line in f: version_result = version_matcher(line) if version_result: has_version = True version = version_result.group(1) break if not has_version: error = "Your %s is using settings from the old templates system. Please switch to the new templates system: http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/Templates" % t errors.append(error) elif int(version) != VERSION: error = "Your %s is using settings from template version %s. Please update with new settings from template version %s before starting the system." % \ (t, version, VERSION) errors.append(error) if copied_from_template: errors.append( "The following files were copied from templates and should be edited: %s" % ", ".join(copied_from_template)) return {"error_messages": errors, "warning_messages": warnings} # ------------------------------------------------------------------------- def parse_requirements(output, filepath): """ """ try: with open(filepath) as filehandle: dependencies = filehandle.read().splitlines() msg = "" for dependency in dependencies: if dependency[0] == "#": # either a normal comment or custom message if dependency[:9] == "# Warning" or dependency[7] == "# Error:": msg = dependency.split(":", 1)[1] else: import re # Check if the module name is different from the package name if "#" in dependency: dep = dependency.split("#", 1)[1] output[dep] = msg else: pattern = re.compile(r'([A-Za-z0-9_-]+)') try: dep = pattern.match(dependency).group(1) output[dep] = msg except AttributeError: # Invalid dependency syntax pass msg = "" except IOError: # No override for Template pass return output # ------------------------------------------------------------------------- def s3_check_python_lib(global_mandatory, template_mandatory, template_optional, global_optional): """ checks for optional as well as mandatory python libraries """ errors = [] warnings = [] for dependency, err in global_mandatory.iteritems(): try: if "from" in dependency: exec dependency else: exec "import %s" % dependency except ImportError: if err: errors.append(err) else: errors.append("S3 unresolved dependency: %s required for Sahana to run" % dependency) for dependency, err in template_mandatory.iteritems(): try: if "from" in dependency: exec dependency else: exec "import %s" % dependency except ImportError: if err: errors.append(err) else: errors.append("Unresolved template dependency: %s required" % dependency) for dependency, warn in template_optional.iteritems(): try: if "from" in dependency: exec dependency else: exec "import %s" % dependency except ImportError: if warn: warnings.append(warn) else: warnings.append("Unresolved optional dependency: %s required" % dependency) for dependency, warn in global_optional.iteritems(): try: if "from" in dependency: exec dependency else: exec "import %s" % dependency except ImportError: if warn: warnings.append(warn) else: warnings.append("Unresolved optional dependency: %s required" % dependency) return errors, warnings # END =========================================================================
sahana/Turkey
modules/s3_update_check.py
Python
mit
13,160
import _curry3 from './internal/_curry3.js'; /** * Move an item, at index `from`, to index `to`, in a list of elements. * A new list will be created containing the new elements order. * * @func * @memberOf R * @since v0.27.1 * @category List * @sig Number -> Number -> [a] -> [a] * @param {Number} from The source index * @param {Number} to The destination index * @param {Array} list The list which will serve to realise the move * @return {Array} The new list reordered * @example * * R.move(0, 2, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['b', 'c', 'a', 'd', 'e', 'f'] * R.move(-1, 0, ['a', 'b', 'c', 'd', 'e', 'f']); //=> ['f', 'a', 'b', 'c', 'd', 'e'] list rotation */ var move = _curry3(function(from, to, list) { var length = list.length; var result = list.slice(); var positiveFrom = from < 0 ? length + from : from; var positiveTo = to < 0 ? length + to : to; var item = result.splice(positiveFrom, 1); return positiveFrom < 0 || positiveFrom >= list.length || positiveTo < 0 || positiveTo >= list.length ? list : [] .concat(result.slice(0, positiveTo)) .concat(item) .concat(result.slice(positiveTo, list.length)); }); export default move;
CrossEye/ramda
source/move.js
JavaScript
mit
1,225
<?php /* The MIT License (MIT) Copyright (c) 2015 Twitter Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Twitter\Tests\Cards; /** * @coversDefaultClass \Twitter\Cards\SummaryLargeImage */ final class SummaryLargeImage extends \Twitter\Tests\TestWithPrivateAccess { /** * Test converting the card into an array * * @since 1.0.0 * * @covers ::toArray() * @small * * @return void */ public function testToArray() { $card = new \Twitter\Cards\SummaryLargeImage(); // generate the array $properties = $card->toArray(); $this->assertEquals($properties['card'], 'summary_large_image', 'Summary large image card type not set'); } }
josafafilho/wordpress-1
tests/phpunit/Cards/SummaryLargeImage.php
PHP
mit
1,718
/** @type {import("../../../../").Configuration} */ module.exports = { entry: { a: "./a", b: "./b" }, output: { filename: "[name].js", libraryTarget: "commonjs2" }, optimization: { chunkIds: "named", splitChunks: { cacheGroups: { shared: { chunks: "all", test: /shared/, filename: "shared-[name].js", enforce: true }, common: { chunks: "all", test: /common/, enforce: true } } } } };
webpack/webpack
test/configCases/split-chunks/custom-filename/webpack.config.js
JavaScript
mit
461
package net.jsunit; import java.io.IOException; public class MockProcessStarter implements ProcessStarter { public String[] commandPassed; public Process execute(String[] command) throws IOException { this.commandPassed = command; return null; } }
wesmaldonado/test-driven-javascript-example-application
public/js-common/jsunit/java/tests_server/net/jsunit/MockProcessStarter.java
Java
mit
295
using System; using System.Reactive.Threading.Tasks; using Octokit.Reactive.Internal; namespace Octokit.Reactive { public class ObservableCommitStatusClient : IObservableCommitStatusClient { readonly ICommitStatusClient _client; readonly IConnection _connection; public ObservableCommitStatusClient(IGitHubClient client) { Ensure.ArgumentNotNull(client, "client"); _client = client.Repository.CommitStatus; _connection = client.Connection; } /// <summary> /// Retrieves commit statuses for the specified reference. A reference can be a commit SHA, a branch name, or /// a tag name. /// </summary> /// <remarks>Only users with pull access can see this.</remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="reference">The reference (SHA, branch name, or tag name) to list commits for</param> /// <returns></returns> public IObservable<CommitStatus> GetAll(string owner, string name, string reference) { return _connection.GetAndFlattenAllPages<CommitStatus>(ApiUrls.CommitStatus(owner, name, reference)); } /// <summary> /// Creates a commit status for the specified ref. /// </summary> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="reference">The reference (SHA, branch name, or tag name) to list commits for</param> /// <param name="commitStatus">The commit status to create</param> /// <returns></returns> public IObservable<CommitStatus> Create(string owner, string name, string reference, NewCommitStatus commitStatus) { return _client.Create(owner, name, reference, commitStatus).ToObservable(); } } }
senlinsky/octokit.net
Octokit.Reactive/Clients/ObservableCommitStatusClient.cs
C#
mit
1,991
//----------------------------------------------------------------------- // <copyright file="DataPortalHookArgs.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary></summary> // <remarks>Generated file.</remarks> //----------------------------------------------------------------------- using System.Data; using System.Data.Common; using Csla.Data; namespace ActionExtenderSample.Business { /// <summary> /// Event arguments for the DataPortalHook.<br/> /// This class holds the arguments for events that happen during DataPortal operations. /// </summary> public class DataPortalHookArgs { #region Properties /// <summary> /// Gets or sets the criteria argument. /// </summary> /// <value>The criteria object.</value> public object CriteriaArg { get; private set; } /// <summary> /// Gets or sets the connection argument. /// </summary> /// <value>The connection.</value> public DbConnection ConnectionArg { get; private set; } /// <summary> /// Gets or sets the command argument. /// </summary> /// <value>The command.</value> public DbCommand CommandArg { get; private set; } /// <summary> /// Gets or sets the ADO transaction argument. /// </summary> /// <value>The ADO transaction.</value> public DbTransaction TransactionArg { get; private set; } /// <summary> /// Gets or sets the data reader argument. /// </summary> /// <value>The data reader.</value> public SafeDataReader DataReaderArg { get; private set; } /// <summary> /// Gets or sets the data row argument. /// </summary> /// <value>The data row.</value> public DataRow DataRowArg { get; private set; } /// <summary> /// Gets or sets the data set argument. /// </summary> /// <value>The data set.</value> public DataSet DataSetArg { get; private set; } #endregion #region Constructor /// <summary> /// Initializes a new empty instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> public DataPortalHookArgs() { } /// <summary> /// Initializes a new instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> /// <param name="crit">The criteria object argument.</param> public DataPortalHookArgs(object crit) { CriteriaArg = crit; } /// <summary> /// Initializes a new instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> /// <param name="cmd">The command argument.</param> /// <remarks>The connection and ADO transaction arguments are set automatically, based on the command argument.</remarks> public DataPortalHookArgs(DbCommand cmd) { CommandArg = cmd; ConnectionArg = cmd.Connection; TransactionArg = cmd.Transaction; } /// <summary> /// Initializes a new instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> /// <param name="cmd">The command argument.</param> /// <param name="crit">The criteria argument.</param> /// <remarks>The connection and ADO transaction arguments are set automatically, based on the command argument.</remarks> public DataPortalHookArgs(DbCommand cmd, object crit) : this(cmd) { CriteriaArg = crit; } /// <summary> /// Initializes a new instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> /// <param name="dr">The SafeDataReader argument.</param> public DataPortalHookArgs(SafeDataReader dr) { DataReaderArg = dr; } /// <summary> /// Initializes a new instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> /// <param name="cmd">The command argument.</param> /// <param name="dr">The SafeDataReader argument.</param> /// <remarks>The connection and ADO transaction arguments are set automatically, based on the command argument.</remarks> public DataPortalHookArgs(DbCommand cmd, SafeDataReader dr) : this(cmd) { DataReaderArg = dr; } /// <summary> /// Initializes a new instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> /// <param name="cmd">The command argument.</param> /// <param name="ds">The DataSet argument.</param> /// <remarks>The connection and ADO transaction arguments are set automatically, based on the command argument.</remarks> public DataPortalHookArgs(DbCommand cmd, DataSet ds) : this(cmd) { DataSetArg = ds; } /// <summary> /// Initializes a new instance of the <see cref="DataPortalHookArgs"/> class. /// </summary> /// <param name="dr">The data row argument.</param> public DataPortalHookArgs(DataRow dr) { DataRowArg = dr; } #endregion } }
MarimerLLC/cslacontrib
trunk/samples/ActionExtenderSample/ActionExtenderSample.Business/DataPortalHookArgs.cs
C#
mit
4,899
(function () { 'use strict'; angular.module('mPlatform.directives') .directive('ngTextChange', function () { return { restrict: 'A', replace: 'ngModel', link: function (scope, element, attr) { element.on('change', function () { scope.$apply(function () { scope.$eval(attr.ngTextChange); }); }); } }; }); })();
michaelmarriott/LabyrinthRipper.Mobile
www/scripts/ang/directives.js
JavaScript
mit
540
Astro.createValidator = function(validatorDefinition) { var definition = new ValidatorDefinition(validatorDefinition); var validatorGenerator = function(options, userMessage) { var validator = function(fieldValue, fieldName) { return validator.definition.validate.call( this, fieldValue, fieldName, options, // Validator options passed by user. validator // Parent validator. ); }; _.extend(validator, { definition: definition, options: options, message: userMessage }); return validator; }; // Validator is just a function with the "definition" property where all the // validator definition is stored. Validators[definition.name] = validatorGenerator; // We also return created validator if someone would like not to use long // default namespace which is e.g. `Validators.isString`. return validatorGenerator; };
ribbedcrown/meteor-astronomy-validators
lib/module/validator.js
JavaScript
mit
929
import _Object$getOwnPropertySymbols from "../../core-js/object/get-own-property-symbols"; import _Object$keys from "../../core-js/object/keys"; export default function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = _Object$keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } if (_Object$getOwnPropertySymbols) { var sourceSymbolKeys = _Object$getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
Skillupco/babel
packages/babel-runtime/helpers/es6/objectWithoutProperties.js
JavaScript
mit
854
/* * Power BI Visualizations * * Copyright (c) Microsoft Corporation * All rights reserved. * MIT License * * 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. */ module powerbi.data { export interface CompiledDataViewMapping { metadata: CompiledDataViewMappingMetadata; categorical?: CompiledDataViewCategoricalMapping; table?: CompiledDataViewTableMapping; single?: CompiledDataViewSingleMapping; tree?: CompiledDataViewTreeMapping; matrix?: CompiledDataViewMatrixMapping; } export interface CompiledDataViewMappingMetadata { /** The metadata repetition objects. */ objects?: DataViewObjects; } export interface CompiledDataViewCategoricalMapping { categories?: CompiledDataViewRoleMappingWithReduction; values?: CompiledDataViewRoleMapping | CompiledDataViewGroupedRoleMapping | CompiledDataViewListRoleMapping; } export interface CompiledDataViewGroupingRoleMapping { role: CompiledDataViewRole } export interface CompiledDataViewSingleMapping { role: CompiledDataViewRole; } export interface CompiledDataViewValuesRoleMapping { roles: CompiledDataViewRole[]; } export interface CompiledDataViewTableMapping { rows: CompiledDataViewRoleMappingWithReduction | CompiledDataViewListRoleMappingWithReduction; } export interface CompiledDataViewTreeMapping { nodes?: CompiledDataViewGroupingRoleMapping values?: CompiledDataViewValuesRoleMapping } export interface CompiledDataViewMatrixMapping { rows?: CompiledDataViewRoleForMappingWithReduction; columns?: CompiledDataViewRoleForMappingWithReduction; values?: CompiledDataViewRoleForMapping; } export type CompiledDataViewRoleMapping = CompiledDataViewRoleBindMapping | CompiledDataViewRoleForMapping; export interface CompiledDataViewRoleBindMapping { bind: { to: CompiledDataViewRole; }; } export interface CompiledDataViewRoleForMapping { for: { in: CompiledDataViewRole; }; } export type CompiledDataViewRoleMappingWithReduction = CompiledDataViewRoleBindMappingWithReduction | CompiledDataViewRoleForMappingWithReduction; export interface CompiledDataViewRoleBindMappingWithReduction extends CompiledDataViewRoleBindMapping, HasReductionAlgorithm { } export interface CompiledDataViewRoleForMappingWithReduction extends CompiledDataViewRoleForMapping, HasReductionAlgorithm { } export interface CompiledDataViewGroupedRoleMapping { group: { by: CompiledDataViewRole; select: CompiledDataViewRoleMapping[]; dataReductionAlgorithm?: ReductionAlgorithm; }; } export interface CompiledDataViewListRoleMapping { select: CompiledDataViewRoleMapping[]; } export interface CompiledDataViewListRoleMappingWithReduction extends CompiledDataViewListRoleMapping, HasReductionAlgorithm { } export enum CompiledSubtotalType { None = 0, Before = 1, After = 2 } export interface CompiledDataViewRole { role: string; items: CompiledDataViewRoleItem[]; subtotalType?: CompiledSubtotalType; } export interface CompiledDataViewRoleItem { type?: ValueType; } }
sgrebnov/PowerBI-visuals
src/Clients/Data/dataView/compiledDataViewMapping.ts
TypeScript
mit
4,466
import test from 'ava'; import fn from './'; test('title', t => { t.is(fn('unicorns'), 'unicorns & rainbows'); });
kokujin/sails-nedb
test.js
JavaScript
mit
117
<?php namespace Bolt\Tests\Nut; use Bolt\Nut\ExtensionsUninstall; use Bolt\Tests\BoltUnitTest; use Symfony\Component\Console\Tester\CommandTester; /** * Class to test src/Nut/ExtensionsDisable. * * @author Ross Riley <riley.ross@gmail.com> * @author Gawain Lynch <gawain.lynch@gmail.com> */ class ExtensionsUninstallTest extends BoltUnitTest { public function testRun() { $app = $this->getApp(); $runner = $this->getMock('Bolt\Composer\PackageManager', ['removePackage'], [$app]); $runner->expects($this->any()) ->method('removePackage') ->will($this->returnValue(0)); $app['extend.manager'] = $runner; $command = new ExtensionsUninstall($app); $tester = new CommandTester($command); $tester->execute(['name' => 'test']); $result = $tester->getDisplay(); $this->assertRegExp('/Starting uninstall of test… \[DONE\]/', trim($result)); } public function testFailed() { $app = $this->getApp(); $runner = $this->getMock('Bolt\Composer\PackageManager', ['removePackage'], [$app]); $runner->expects($this->any()) ->method('removePackage') ->will($this->returnValue(1)); $app['extend.manager'] = $runner; $command = new ExtensionsUninstall($app); $tester = new CommandTester($command); $tester->execute(['name' => 'test']); $result = $tester->getDisplay(); $this->assertRegExp('/Starting uninstall of test… \[FAILED\]/', trim($result)); } }
Intendit/bolt
tests/phpunit/unit/Nut/ExtensionsUninstallTest.php
PHP
mit
1,569
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) 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. */ package org.spongepowered.common.mixin.core.block.tiles; import net.minecraft.tileentity.TileEntityDaylightDetector; import org.spongepowered.api.block.tileentity.DaylightDetector; import org.spongepowered.asm.mixin.Mixin; @Mixin(TileEntityDaylightDetector.class) public abstract class MixinTileEntityDaylightDetector extends MixinTileEntity implements DaylightDetector { }
kashike/SpongeCommon
src/main/java/org/spongepowered/common/mixin/core/block/tiles/MixinTileEntityDaylightDetector.java
Java
mit
1,625
'use strict'; import $ from 'jquery'; import { Keyboard } from './foundation.util.keyboard'; import { GetYoDigits } from './foundation.util.core'; import { Positionable } from './foundation.positionable'; import { Triggers } from './foundation.util.triggers'; /** * Dropdown module. * @module foundation.dropdown * @requires foundation.util.keyboard * @requires foundation.util.box * @requires foundation.util.triggers */ class Dropdown extends Positionable { /** * Creates a new instance of a dropdown. * @class * @name Dropdown * @param {jQuery} element - jQuery object to make into a dropdown. * Object should be of the dropdown panel, rather than its anchor. * @param {Object} options - Overrides to the default plugin settings. */ _setup(element, options) { this.$element = element; this.options = $.extend({}, Dropdown.defaults, this.$element.data(), options); this.className = 'Dropdown'; // ie9 back compat // Triggers init is idempotent, just need to make sure it is initialized Triggers.init($); this._init(); Keyboard.register('Dropdown', { 'ENTER': 'open', 'SPACE': 'open', 'ESCAPE': 'close' }); } /** * Initializes the plugin by setting/checking options and attributes, adding helper variables, and saving the anchor. * @function * @private */ _init() { var $id = this.$element.attr('id'); this.$anchors = $(`[data-toggle="${$id}"]`).length ? $(`[data-toggle="${$id}"]`) : $(`[data-open="${$id}"]`); this.$anchors.attr({ 'aria-controls': $id, 'data-is-focus': false, 'data-yeti-box': $id, 'aria-haspopup': true, 'aria-expanded': false }); this._setCurrentAnchor(this.$anchors.first()); if(this.options.parentClass){ this.$parent = this.$element.parents('.' + this.options.parentClass); }else{ this.$parent = null; } this.$element.attr({ 'aria-hidden': 'true', 'data-yeti-box': $id, 'data-resize': $id, 'aria-labelledby': this.$currentAnchor.id || GetYoDigits(6, 'dd-anchor') }); super._init(); this._events(); } _getDefaultPosition() { // handle legacy classnames var position = this.$element[0].className.match(/(top|left|right|bottom)/g); if(position) { return position[0]; } else { return 'bottom' } } _getDefaultAlignment() { // handle legacy float approach var horizontalPosition = /float-(\S+)/.exec(this.$currentAnchor.className); if(horizontalPosition) { return horizontalPosition[1]; } return super._getDefaultAlignment(); } /** * Sets the position and orientation of the dropdown pane, checks for collisions if allow-overlap is not true. * Recursively calls itself if a collision is detected, with a new position class. * @function * @private */ _setPosition() { this.$element.removeClass(`has-position-${this.position} has-alignment-${this.alignment}`); super._setPosition(this.$currentAnchor, this.$element, this.$parent); this.$element.addClass(`has-position-${this.position} has-alignment-${this.alignment}`); } /** * Make it a current anchor. * Current anchor as the reference for the position of Dropdown panes. * @param {HTML} el - DOM element of the anchor. * @function * @private */ _setCurrentAnchor(el) { this.$currentAnchor = $(el); } /** * Adds event listeners to the element utilizing the triggers utility library. * @function * @private */ _events() { var _this = this; this.$element.on({ 'open.zf.trigger': this.open.bind(this), 'close.zf.trigger': this.close.bind(this), 'toggle.zf.trigger': this.toggle.bind(this), 'resizeme.zf.trigger': this._setPosition.bind(this) }); this.$anchors.off('click.zf.trigger') .on('click.zf.trigger', function() { _this._setCurrentAnchor(this); }); if(this.options.hover){ this.$anchors.off('mouseenter.zf.dropdown mouseleave.zf.dropdown') .on('mouseenter.zf.dropdown', function(){ _this._setCurrentAnchor(this); var bodyData = $('body').data(); if(typeof(bodyData.whatinput) === 'undefined' || bodyData.whatinput === 'mouse') { clearTimeout(_this.timeout); _this.timeout = setTimeout(function(){ _this.open(); _this.$anchors.data('hover', true); }, _this.options.hoverDelay); } }).on('mouseleave.zf.dropdown', function(){ clearTimeout(_this.timeout); _this.timeout = setTimeout(function(){ _this.close(); _this.$anchors.data('hover', false); }, _this.options.hoverDelay); }); if(this.options.hoverPane){ this.$element.off('mouseenter.zf.dropdown mouseleave.zf.dropdown') .on('mouseenter.zf.dropdown', function(){ clearTimeout(_this.timeout); }).on('mouseleave.zf.dropdown', function(){ clearTimeout(_this.timeout); _this.timeout = setTimeout(function(){ _this.close(); _this.$anchors.data('hover', false); }, _this.options.hoverDelay); }); } } this.$anchors.add(this.$element).on('keydown.zf.dropdown', function(e) { var $target = $(this), visibleFocusableElements = Keyboard.findFocusable(_this.$element); Keyboard.handleKey(e, 'Dropdown', { open: function() { if ($target.is(_this.$anchors)) { _this.open(); _this.$element.attr('tabindex', -1).focus(); e.preventDefault(); } }, close: function() { _this.close(); _this.$anchors.focus(); } }); }); } /** * Adds an event handler to the body to close any dropdowns on a click. * @function * @private */ _addBodyHandler() { var $body = $(document.body).not(this.$element), _this = this; $body.off('click.zf.dropdown') .on('click.zf.dropdown', function(e){ if(_this.$anchors.is(e.target) || _this.$anchors.find(e.target).length) { return; } if(_this.$element.is(e.target) || _this.$element.find(e.target).length) { return; } _this.close(); $body.off('click.zf.dropdown'); }); } /** * Opens the dropdown pane, and fires a bubbling event to close other dropdowns. * @function * @fires Dropdown#closeme * @fires Dropdown#show */ open() { // var _this = this; /** * Fires to close other open dropdowns, typically when dropdown is opening * @event Dropdown#closeme */ this.$element.trigger('closeme.zf.dropdown', this.$element.attr('id')); this.$anchors.addClass('hover') .attr({'aria-expanded': true}); // this.$element/*.show()*/; this.$element.addClass('is-opening'); this._setPosition(); this.$element.removeClass('is-opening').addClass('is-open') .attr({'aria-hidden': false}); if(this.options.autoFocus){ var $focusable = Keyboard.findFocusable(this.$element); if($focusable.length){ $focusable.eq(0).focus(); } } if(this.options.closeOnClick){ this._addBodyHandler(); } if (this.options.trapFocus) { Keyboard.trapFocus(this.$element); } /** * Fires once the dropdown is visible. * @event Dropdown#show */ this.$element.trigger('show.zf.dropdown', [this.$element]); } /** * Closes the open dropdown pane. * @function * @fires Dropdown#hide */ close() { if(!this.$element.hasClass('is-open')){ return false; } this.$element.removeClass('is-open') .attr({'aria-hidden': true}); this.$anchors.removeClass('hover') .attr('aria-expanded', false); /** * Fires once the dropdown is no longer visible. * @event Dropdown#hide */ this.$element.trigger('hide.zf.dropdown', [this.$element]); if (this.options.trapFocus) { Keyboard.releaseFocus(this.$element); } } /** * Toggles the dropdown pane's visibility. * @function */ toggle() { if(this.$element.hasClass('is-open')){ if(this.$anchors.data('hover')) return; this.close(); }else{ this.open(); } } /** * Destroys the dropdown. * @function */ _destroy() { this.$element.off('.zf.trigger').hide(); this.$anchors.off('.zf.dropdown'); $(document.body).off('click.zf.dropdown'); } } Dropdown.defaults = { /** * Class that designates bounding container of Dropdown (default: window) * @option * @type {?string} * @default null */ parentClass: null, /** * Amount of time to delay opening a submenu on hover event. * @option * @type {number} * @default 250 */ hoverDelay: 250, /** * Allow submenus to open on hover events * @option * @type {boolean} * @default false */ hover: false, /** * Don't close dropdown when hovering over dropdown pane * @option * @type {boolean} * @default false */ hoverPane: false, /** * Number of pixels between the dropdown pane and the triggering element on open. * @option * @type {number} * @default 0 */ vOffset: 0, /** * Number of pixels between the dropdown pane and the triggering element on open. * @option * @type {number} * @default 0 */ hOffset: 0, /** * DEPRECATED: Class applied to adjust open position. * @option * @type {string} * @default '' */ positionClass: '', /** * Position of dropdown. Can be left, right, bottom, top, or auto. * @option * @type {string} * @default 'auto' */ position: 'auto', /** * Alignment of dropdown relative to anchor. Can be left, right, bottom, top, center, or auto. * @option * @type {string} * @default 'auto' */ alignment: 'auto', /** * Allow overlap of container/window. If false, dropdown will first try to position as defined by data-position and data-alignment, but reposition if it would cause an overflow. * @option * @type {boolean} * @default false */ allowOverlap: false, /** * Allow overlap of only the bottom of the container. This is the most common * behavior for dropdowns, allowing the dropdown to extend the bottom of the * screen but not otherwise influence or break out of the container. * @option * @type {boolean} * @default true */ allowBottomOverlap: true, /** * Allow the plugin to trap focus to the dropdown pane if opened with keyboard commands. * @option * @type {boolean} * @default false */ trapFocus: false, /** * Allow the plugin to set focus to the first focusable element within the pane, regardless of method of opening. * @option * @type {boolean} * @default false */ autoFocus: false, /** * Allows a click on the body to close the dropdown. * @option * @type {boolean} * @default false */ closeOnClick: false } export {Dropdown};
robertgraleigh/supreme-journey
node_modules/foundation-sites/js/foundation.dropdown.js
JavaScript
mit
11,158
<?php namespace Elastica\Filter; /** * Type Filter * * @category Xodoa * @package Elastica * @author James Wilson <jwilson556@gmail.com> * @link http://www.elasticsearch.org/guide/reference/query-dsl/type-filter.html */ class Type extends AbstractFilter { /** * Type name * * @var string */ protected $_type = null; /** * Construct Type Filter * * @param string $typeName Type name * @return \Elastica\Filter\Type */ public function __construct($typeName = null) { if ($typeName) { $this->setType($typeName); } } /** * Ads a field with arguments to the range query * * @param string $typeName Type name * @return \Elastica\Filter\Type current object */ public function setType($typeName) { $this->_type = $typeName; return $this; } /** * Convert object to array * * @see \Elastica\Filter\AbstractFilter::toArray() * @return array Filter array */ public function toArray() { return array( 'type' => array('value' => $this->_type), ); } }
didix16/snackhelper
vendor/ruflin/elastica/lib/Elastica/Filter/Type.php
PHP
mit
1,205
__title__ = 'pif.exceptions' __author__ = 'Artur Barseghyan' __copyright__ = 'Copyright (c) 2013 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('InvalidRegistryItemType',) class InvalidRegistryItemType(ValueError): """ Raised when an attempt is made to register an item in the registry which does not have a proper type. """
djabber/Dashboard
bottle/dash/local/lib/pif-0.7/src/pif/exceptions.py
Python
mit
352
import {EntitySubscriberInterface} from "../../../../src/subscriber/EntitySubscriberInterface"; import {EventSubscriber} from "../../../../src/decorator/listeners/EventSubscriber"; import {InsertEvent} from "../../../../src/subscriber/event/InsertEvent"; @EventSubscriber() export class FirstConnectionSubscriber implements EntitySubscriberInterface<any> { /** * Called after entity insertion. */ beforeInsert(event: InsertEvent<any>) { console.log(`BEFORE ENTITY INSERTED: `, event.entity); } }
ReaxDev/typeorm
test/functional/connection/subscriber/FirstConnectionSubscriber.ts
TypeScript
mit
532
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceBus.Messaging; using Nimbus.Extensions; namespace Nimbus.Infrastructure.MessageSendersAndReceivers { internal abstract class BatchingMessageSender : INimbusMessageSender { private const int _maxConcurrentFlushTasks = 10; private const int _maximumBatchSize = 100; private readonly List<BrokeredMessage> _outboundQueue = new List<BrokeredMessage>(); private bool _disposed; private readonly object _mutex = new object(); private readonly SemaphoreSlim _sendingSemaphore = new SemaphoreSlim(_maxConcurrentFlushTasks, _maxConcurrentFlushTasks); private Task _lazyFlushTask; protected abstract Task SendBatch(BrokeredMessage[] messages); public Task Send(BrokeredMessage message) { lock (_mutex) { _outboundQueue.Add(message); if (_outboundQueue.Count >= _maximumBatchSize) { return DoBatchSendNow(); } if (_lazyFlushTask == null) { _lazyFlushTask = FlushMessagesLazily(); } return _lazyFlushTask; } } private async Task FlushMessagesLazily() { if (_disposed) return; await Task.Delay(TimeSpan.FromMilliseconds(100)); // sleep *after* we grab a semaphore to allow messages to be batched _lazyFlushTask = null; await DoBatchSendNow(); } private async Task DoBatchSendNow() { await _sendingSemaphore.WaitAsync(); try { BrokeredMessage[] toSend; lock (_mutex) { toSend = _outboundQueue.Take(_maximumBatchSize).ToArray(); _outboundQueue.RemoveRange(0, toSend.Length); } if (toSend.None()) return; await SendBatch(toSend); GlobalMessageCounters.IncrementSentMessageCount(toSend.Length); } finally { _sendingSemaphore.Release(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { _disposed = true; } } }
rebase42/Anubus
src/Nimbus/Infrastructure/MessageSendersAndReceivers/BatchingMessageSender.cs
C#
mit
2,558
// REACHABILITY,CODE_GENERATION public class J1_whiletrue1 { public J1_whiletrue1() { } public static int test() { return 123; } public static void foo() { while(true); } }
gregwym/joos-compiler-java
testcases/a5/J1_whiletrue1.java
Java
mit
184
// import { createAction } from 'redux-actions'; //Actions: //Simulate loading
dgilroy77/Car.ly
src/actions/loadActions.js
JavaScript
mit
80
#include "render/action_renderer.h" #include "engine/cloak_system.h" #include "platform/auto_id.h" #include "platform/id_storage.h" #include "core/i_renderable_component.h" namespace render { ActionRenderer::~ActionRenderer() { } ActionRenderer::ActionRenderer( int32_t Id, int32_t ActionId ) : mId( Id ) , mActionId( ActionId == -1 ? AutoId( "idle" ) : ActionId ) , mSecsToEnd( 1.0 ) , mState( 0 ) , mRenderableRepo( RenderableRepo::Get() ) , mOrder( 0 ) { } void ActionRenderer::Init( const Actor& actor ) { int32_t actorId = actor.GetId(); auto renderableC( actor.Get<IRenderableComponent>() ); actorId = GetSpriteId( renderableC->GetSpriteIndex(), actorId ); SpriteCollection const& Sprites = mRenderableRepo( actorId ); Sprite const& Spr = Sprites( mActionId ); if( Spr.IsValid() ) { mSpr = &Spr; mSecsToEnd = Spr.GetSecsToEnd(); } mCompanionSprites = GetCompanionSprites( actorId, mActionId ); } glm::vec4 ActionRenderer::GetRenderableColor( Actor const& actor ) const { auto const& col = GetCloakColor( actor ) * GetColor( actor ); return col; } void ActionRenderer::FillRenderableSprites( const Actor& actor, IRenderableComponent const& renderableC, RenderableSprites_t& renderableSprites ) { if( nullptr == mSpr ) { return; } int32_t st( GetState() ); auto const& Phase = (*mSpr)( st ); auto const& col = GetRenderableColor( actor ); RenderableSprite rs( &actor, &renderableC, mActionId, mSpr, &Phase, col ); FillRenderableSprite( rs, mCompanionSprites, st ); renderableSprites.push_back( rs ); } void FillRenderableSprite( RenderableSprite& rs, CompanionSprites const& data, int32_t st ) { for( auto const& spr : data.AdditionalSprs ) { rs.AdditionalSprs.push_back( &(*spr)( st ) ); } if( nullptr != data.MaskSpr ) { rs.MaskSpr = &(*data.MaskSpr)( st ); } if( nullptr != data.NormalSpr ) { rs.NormalSpr = &(*data.NormalSpr)( st ); } } void ActionRenderer::Update( double DeltaTime ) { double nextState = mSecsToEnd == 0 ? 100 : ( mState + DeltaTime / mSecsToEnd * 100. ); if( nextState >= 100 ) { nextState = fmod( nextState, 100. ); } mState = nextState; } double ActionRenderer::GetState() const { return mState; } void ActionRenderer::SetState( double S ) { mState = S; } int32_t ActionRenderer::GetId() const { return mId; } int32_t ActionRenderer::GetOrder() const { return mOrder; } void ActionRenderer::SetOrder( int32_t order ) { mOrder = order; } bool ActionRenderer::operator<( const render::ActionRenderer& r ) const { return mOrder < r.GetOrder(); } DefaultActionRenderer::DefaultActionRenderer( int32_t Id ) : ActionRenderer( Id ) { } glm::vec4 GetCloakColor( const Actor& actor ) { glm::vec4 r = glm::vec4( 1.0 ); engine::CloakSystem::CloakState cloakState = engine::CloakSystem::GetCloakState( actor ); if ( cloakState == engine::CloakSystem::Cloaked ) { r = glm::vec4( 1.0, 1.0, 1.0, 0.5 ); } else if ( cloakState == engine::CloakSystem::Invisible ) { r = glm::vec4( 0.0 ); } return r; } glm::vec4 GetColor( const Actor& actor ) { auto renderableC = actor.Get<IRenderableComponent>(); if (renderableC.IsValid()) { return renderableC->GetColor(); } return glm::vec4( 1.0 ); } CompanionSprites GetCompanionSprites( int32_t actorId, int32_t actionId ) { CompanionSprites rv; static auto& renderableRepo( RenderableRepo::Get() ); SpriteCollection const& Sprites = renderableRepo( actorId ); SpriteCollection const& Joint = renderableRepo( Sprites.JointId() ); std::string actorName; platform::IdStorage::Get().GetName( actorId, actorName ); SpriteCollection const& Mask = renderableRepo( AutoId( actorName + "_mask" ) ); SpriteCollection const& Normal = renderableRepo( AutoId( actorName + "_normal" ) ); Sprite const& JointSpr = Joint( actionId ); Sprite const& MaskSpr = Mask( actionId ); Sprite const& NormalSpr = Normal( actionId ); if( JointSpr.IsValid() ) { rv.AdditionalSprs.push_back( &JointSpr ); } if( MaskSpr.IsValid() ) { rv.MaskSpr = &MaskSpr; } if( NormalSpr.IsValid() ) { rv.NormalSpr = &NormalSpr; } return rv; } int32_t GetSpriteId( int32_t spriteIndex, int32_t actorId ) { if (spriteIndex > 0) { static auto& idStorage = IdStorage::Get(); std::string actorName; bool const gotId = idStorage.GetName( actorId, actorName ); BOOST_ASSERT( gotId ); actorName = actorName + "_" + std::to_string( spriteIndex ); actorId = idStorage.GetId( actorName ); } return actorId; } void DefaultActionRendererLoader::BindValues() { } } // namespace render
HalalUr/Reaping2
src/render/action_renderer.cpp
C++
mit
4,908
<?php namespace Checkout\tests\Helpers; class Notifications { public static function generateID() { return 'ntf_' . substr(md5(rand()), 0, 26); } }
checkout/checkout-woocommerce-plugin
woocommerce-gateway-checkout-com/includes/lib/checkout-sdk-php/tests/Helpers/Notifications.php
PHP
mit
170
'use strict'; const common = require('../common'); if (!common.hasIPv6) common.skip('no IPv6 support'); const assert = require('assert'); const cluster = require('cluster'); const net = require('net'); // This test ensures that the `ipv6Only` option in `net.Server.listen()` // works as expected when we use cluster with `SCHED_RR` schedulingPolicy. cluster.schedulingPolicy = cluster.SCHED_RR; const host = '::'; const WORKER_ACCOUNT = 3; if (cluster.isMaster) { const workers = []; let address; for (let i = 0; i < WORKER_ACCOUNT; i += 1) { const myWorker = new Promise((resolve) => { const worker = cluster.fork().on('exit', common.mustCall((statusCode) => { assert.strictEqual(statusCode, 0); })).on('listening', common.mustCall((workerAddress) => { if (!address) { address = workerAddress; } else { assert.deepStrictEqual(workerAddress, address); } resolve(worker); })); }); workers.push(myWorker); } Promise.all(workers).then(common.mustCall((resolvedWorkers) => { // Make sure the `ipv6Only` option works. Should be able to use the port on // IPv4. const server = net.createServer().listen({ host: '0.0.0.0', port: address.port, }, common.mustCall(() => { // Exit. server.close(); resolvedWorkers.forEach((resolvedWorker) => { resolvedWorker.disconnect(); }); })); })); } else { // As the cluster member has the potential to grab any port // from the environment, this can cause collision when master // obtains the port from cluster member and tries to listen on. // So move this to sequential, and provide a static port. // Refs: https://github.com/nodejs/node/issues/25813 net.createServer().listen({ host: host, port: common.PORT, ipv6Only: true, }, common.mustCall()); }
enclose-io/compiler
lts/test/sequential/test-cluster-net-listen-ipv6only-rr.js
JavaScript
mit
1,884
import Vue from 'vue'; import closedComponent from '~/vue_merge_request_widget/components/states/mr_widget_closed.vue'; import mountComponent from 'spec/helpers/vue_mount_component_helper'; describe('MRWidgetClosed', () => { let vm; beforeEach(() => { const Component = Vue.extend(closedComponent); vm = mountComponent(Component, { mr: { metrics: { mergedBy: {}, closedBy: { name: 'Administrator', username: 'root', webUrl: 'http://localhost:3000/root', avatarUrl: 'http://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80&d=identicon', }, mergedAt: 'Jan 24, 2018 1:02pm GMT+0000', closedAt: 'Jan 24, 2018 1:02pm GMT+0000', readableMergedAt: '', readableClosedAt: 'less than a minute ago', }, targetBranchPath: '/twitter/flight/commits/so_long_jquery', targetBranch: 'so_long_jquery', }, }); }); afterEach(() => { vm.$destroy(); }); it('renders warning icon', () => { expect(vm.$el.querySelector('.js-ci-status-icon-warning')).not.toBeNull(); }); it('renders closed by information with author and time', () => { expect( vm.$el .querySelector('.js-mr-widget-author') .textContent.trim() .replace(/\s\s+/g, ' '), ).toContain('Closed by Administrator less than a minute ago'); }); it('links to the user that closed the MR', () => { expect(vm.$el.querySelector('.author-link').getAttribute('href')).toEqual( 'http://localhost:3000/root', ); }); it('renders information about the changes not being merged', () => { expect( vm.$el .querySelector('.mr-info-list') .textContent.trim() .replace(/\s\s+/g, ' '), ).toContain('The changes were not merged into so_long_jquery'); }); it('renders link for target branch', () => { expect(vm.$el.querySelector('.label-branch').getAttribute('href')).toEqual( '/twitter/flight/commits/so_long_jquery', ); }); });
stoplightio/gitlabhq
spec/javascripts/vue_mr_widget/components/states/mr_widget_closed_spec.js
JavaScript
mit
2,094
using System.Linq; using System.Runtime.InteropServices; using Diadoc.Api.Com; namespace Diadoc.Api.Proto { [ComVisible(true)] [Guid("6D52D398-C4C9-4ED0-B9A1-38D074C045C7")] public interface ICounteragentList { int TotalCount { get; } ReadonlyList CounteragentsList { get; } } [ComVisible(true)] [Guid("0165E953-29A3-40DA-9FCC-786ED727DA6A")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (ICounteragentList))] public partial class CounteragentList : SafeComObject, ICounteragentList { public ReadonlyList CounteragentsList { get { return new ReadonlyList(Counteragents); } } public override string ToString() { return string.Join("\r\n", Counteragents.Select(c => c.ToString()).ToArray()); } } [ComVisible(true)] [Guid("92320D36-B9E7-44A5-9F63-D799D42EAAF8")] public interface ICounteragent { string IndexKey { get; } Organization Organization { get; } long LastEventTimestampTicks { get; } string MessageFromCounteragent { get; } string MessageToCounteragent { get; } Com.CounteragentStatus CurrentCounteragentStatus { get; } } [ComVisible(true)] [Guid("839DA27C-80F7-45AB-A554-22C3DE3D624B")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof (ICounteragent))] public partial class Counteragent : SafeComObject, ICounteragent { public override string ToString() { return string.Format("IndexKey: {0}, Organization: {1}, CurrentStatus: {2}, LastEventTimestampTicks: {3}", IndexKey, Organization, CurrentStatus, LastEventTimestampTicks); } public Com.CounteragentStatus CurrentCounteragentStatus { get { return (Com.CounteragentStatus) CurrentStatus; } } } [ComVisible(true)] [Guid("0C809297-EFC6-4BBD-B952-678F55D3F2D2")] public interface ICounteragentCertificateList { ReadonlyList CertificatesList { get; } } [ComVisible(true)] [Guid("C5BCC37D-E415-4232-81F6-ED0B351EED81")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(ICounteragentCertificateList))] public partial class CounteragentCertificateList : SafeComObject, ICounteragentCertificateList { public ReadonlyList CertificatesList { get { return new ReadonlyList(Certificates); } } public override string ToString() { return string.Join("\r\n", Certificates.Select(c => c.ToString()).ToArray()); } } [ComVisible(true)] [Guid("6550D3C1-1BB0-4043-B24B-1D98B529C363")] public interface ICertificate { byte[] RawCertificateData { get; } } [ComVisible(true)] [Guid("243319AA-3232-483A-BE8A-913747A971C7")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(ICertificate))] public partial class Certificate : SafeComObject, ICertificate { } }
s-rogonov/diadocsdk-csharp
src/Proto/Counteragent.cs
C#
mit
2,719
'use strict'; import React from 'react'; import PlaylistHeader from './PlaylistHeader'; import PlaylistVideos from './PlaylistVideos'; const PureRenderMixin = React.addons.PureRenderMixin; export default React.createClass({ propTypes: { playlist: React.PropTypes.array.isRequired, }, mixins: [PureRenderMixin], renderPlaylists(playlist){ return ( <div key={playlist.get('id')} className="playlist-items"> <PlaylistHeader title={playlist.get('title')} playlist={playlist.get('id')} /> <PlaylistVideos videos={playlist.get('videos')} /> </div> ); }, render() { let nodes = this.props.playlist.map(this.renderPlaylists); return ( <div className="playlist-items-container"> {nodes} </div> ); } });
whoisandie/yoda
src/scripts/Playlist.js
JavaScript
mit
785
'use strict'; /* global google */ function cdDojoDetailCtrl($scope, $state, $location, cdDojoService, cdUsersService, alertService, usSpinnerService, auth, dojo, gmap, $translate, currentUser) { $scope.dojo = dojo; $scope.model = {}; $scope.markers = []; $scope.requestInvite = {}; $scope.userMemberCheckComplete = false; currentUser = currentUser.data; var approvalRequired = ['mentor', 'champion']; var latitude, longitude; if(!_.isEmpty(currentUser)) { if(!dojo || !dojo.id){ return $state.go('error-404-no-headers'); } if(!dojo.verified && dojo.creator !== currentUser.id && !_.contains(currentUser.roles, 'cdf-admin')){ return $state.go('error-404-no-headers'); } //Check if user is a member of this Dojo var query = {dojoId:dojo.id, userId: currentUser.id}; cdDojoService.getUsersDojos(query, function (response) { $scope.dojoMember = !_.isEmpty(response); $scope.dojoOwner = false; if($scope.dojoMember) $scope.dojoOwner = (response[0].owner === 1) ? true : false; $scope.userMemberCheckComplete = true; }); } else { if(!dojo || !dojo.id || !dojo.verified) return $state.go('error-404-no-headers'); $scope.userMemberCheckComplete = true; } cdUsersService.getInitUserTypes(function (response) { var userTypes = _.filter(response, function(type) { return type.name.indexOf('u13') === -1; }); $scope.initUserTypes = userTypes; }); cdDojoService.getDojoConfig(function(json){ $scope.dojoStages = _.map(json.dojoStages, function(item){ return { value: item.value, label: $translate.instant(item.label) }; }); $scope.dojo.stage = _.find($scope.dojoStages, function(obj) { return obj.value === $scope.dojo.stage }) }); $scope.$watch('model.map', function(map){ if(map) { if(latitude && longitude) { var marker = new google.maps.Marker({ map: $scope.model.map, position: new google.maps.LatLng(latitude, longitude) }); $scope.markers.push(marker); } } }); if(gmap) { if($scope.dojo.coordinates) { var coordinates = $scope.dojo.coordinates.split(','); latitude = coordinates[0]; longitude = coordinates[1]; $scope.mapOptions = { center: new google.maps.LatLng(latitude, longitude), zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP }; $scope.mapLoaded = true; } else { var countryCoordinates; cdDojoService.loadCountriesLatLongData(function (response) { countryCoordinates = response[$scope.dojo.alpha2]; $scope.mapOptions = { center: new google.maps.LatLng(countryCoordinates[0], countryCoordinates[1]), zoom: 5, mapTypeId: google.maps.MapTypeId.ROADMAP }; $scope.mapLoaded = true; }); } } $scope.userTypeSelected = function ($item) { if(_.contains(approvalRequired, $item)) return $scope.approvalRequired = true; return $scope.approvalRequired = false; }; $scope.requestToJoin = function (requestInvite) { if(!$scope.requestInvite.userType) { $scope.requestInvite.validate="false"; return } else { var userType = requestInvite.userType.name; auth.get_loggedin_user(function (user) { usSpinnerService.spin('dojo-detail-spinner'); var data = {user:user, dojoId:dojo.id, userType:userType, emailSubject: $translate.instant('New Request to join your Dojo')}; if(_.contains(approvalRequired, userType)) { cdDojoService.requestInvite(data, function (response) { usSpinnerService.stop('dojo-detail-spinner'); if(!response.error) { alertService.showAlert($translate.instant('Join Request Sent!')); } else { alertService.showError($translate.instant(response.error)); } }); } else { //Check if user is already a member of this Dojo var query = {userId:user.id, dojoId:dojo.id}; var userDojo = {}; cdDojoService.getUsersDojos(query, function (response) { if(_.isEmpty(response)) { //Save userDojo.owner = 0; userDojo.userId = user.id; userDojo.dojoId = dojo.id; userDojo.userTypes = [userType]; cdDojoService.saveUsersDojos(userDojo, function (response) { usSpinnerService.stop('dojo-detail-spinner'); $state.go($state.current, {}, {reload: true}); alertService.showAlert($translate.instant('Successfully Joined Dojo')); }); } else { //Update userDojo = response[0]; if(!userDojo.userTypes) userDojo.userTypes = []; userDojo.userTypes.push(userType); cdDojoService.saveUsersDojos(userDojo, function (response) { usSpinnerService.stop('dojo-detail-spinner'); $state.go($state.current, {}, {reload: true}); alertService.showAlert($translate.instant('Successfully Joined Dojo')); }); } }); } }, function () { //Not logged in $state.go('register-account', {referer:$location.url()}); }); } }; $scope.leaveDojo = function () { usSpinnerService.spin('dojo-detail-spinner'); cdDojoService.removeUsersDojosLink({userId: currentUser.id, dojoId: dojo.id, emailSubject: $translate.instant('A user has left your Dojo')}, function (response) { usSpinnerService.stop('dojo-detail-spinner'); $state.go($state.current, {}, {reload: true}); }, function (err) { alertService.showError($translate.instant('Error leaving Dojo')); }); } } angular.module('cpZenPlatform') .controller('dojo-detail-controller', ['$scope', '$state', '$location', 'cdDojoService', 'cdUsersService', 'alertService', 'usSpinnerService', 'auth', 'dojo', 'gmap', '$translate', 'currentUser', cdDojoDetailCtrl]);
Aryess/cp-zen-platform
web/public/js/controllers/dojo-detail-controller.js
JavaScript
mit
6,054
#!/usr/bin/env node const os = require('os') const {spawn} = require('child_process') if (os.platform() === 'win32' || os.platform() === 'windows') console.log('skipping on windows') else spawn('yarn bats test/integration/*.bats', {stdio: 'inherit', shell: true})
heroku/heroku-cli
packages/run/bin/bats-test-runner.js
JavaScript
mit
266
var searchData= [ ['label',['Label',['../classLabel.html',1,'']]], ['labeliterator',['LabelIterator',['../classLabelIterator.html',1,'']]], ['labelsegment',['LabelSegment',['../structLabelSegment.html',1,'']]] ];
chabbimilind/cctlib
docs/html/search/classes_6c.js
JavaScript
mit
219
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.ha.backend; import java.net.InetAddress; /* * This class represents a front-end httpd server. * */ public class Proxy { protected enum State { OK, ERROR, DOWN }; public InetAddress address = null; public int port = 80; public State state = State.OK; }
plumer/codana
tomcat_files/7.0.0/Proxy.java
Java
mit
1,102
<?php /* * This file is part of the Alice package. * * (c) Nelmio <hello@nelm.io> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Nelmio\Alice\Throwable\Exception\Generator\Resolver; class NoSuchPropertyException extends UnresolvableValueException { }
furtadodiegos/projeto_cv
vendor/nelmio/alice/src/Throwable/Exception/Generator/Resolver/NoSuchPropertyException.php
PHP
mit
380
class AddIsRefundToDrawerTransactions < ActiveRecord::Migration def self.up add_column :drawer_transactions, :is_refund, :boolean, :default => false end def self.down remove_column :drawer_transactions, :is_refund end end
a0ali0taha/pos
vendor/db/migrate/20110627192451_add_is_refund_to_drawer_transactions.rb
Ruby
mit
239
# This migration will create one row of NotificationSetting for each Member row # It can take long time on big instances. # # This migration can be done online but with following effects: # - during migration some users will receive notifications based on their global settings (project/group settings will be ignored) # - its possible to get duplicate records for notification settings since we don't create uniq index yet # class MigrateNewNotificationSetting < ActiveRecord::Migration def up timestamp = Time.now.strftime('%F %T') execute "INSERT INTO notification_settings ( user_id, source_id, source_type, level, created_at, updated_at ) SELECT user_id, source_id, source_type, notification_level, '#{timestamp}', '#{timestamp}' FROM members WHERE user_id IS NOT NULL" end def down execute "DELETE FROM notification_settings" end end
larryli/gitlabhq
db/migrate/20160328115649_migrate_new_notification_setting.rb
Ruby
mit
861
/**! * Sortable * @author RubaXa <trash@rubaxa.org> * @author owenm <owen23355@gmail.com> * @license MIT */ (function sortableModule(factory) { "use strict"; if (typeof define === "function" && define.amd) { define(factory); } else if (typeof module != "undefined" && typeof module.exports != "undefined") { module.exports = factory(); } else { /* jshint sub:true */ window["Sortable"] = factory(); } })(function sortableFactory() { "use strict"; if (typeof window === "undefined" || !window.document) { return function sortableError() { throw new Error("Sortable.js requires a window with a document"); }; } var dragEl, parentEl, ghostEl, cloneEl, rootEl, nextEl, lastDownEl, scrollEl, scrollParentEl, scrollCustomFn, oldIndex, newIndex, activeGroup, putSortable, autoScrolls = [], scrolling = false, pointerElemChangedInterval, lastPointerElemX, lastPointerElemY, tapEvt, touchEvt, moved, lastTarget, lastDirection, pastFirstInvertThresh = false, isCircumstantialInvert = false, forRepaintDummy, realDragElRect, // dragEl rect after current animation /** @const */ R_SPACE = /\s+/g, expando = 'Sortable' + (new Date).getTime(), win = window, document = win.document, parseInt = win.parseInt, setTimeout = win.setTimeout, $ = win.jQuery || win.Zepto, Polymer = win.Polymer, captureMode = { capture: false, passive: false }, supportDraggable = ('draggable' in document.createElement('div')), supportCssPointerEvents = (function (el) { // false when IE11 if (!!navigator.userAgent.match(/(?:Trident.*rv[ :]?11\.|msie)/i)) { return false; } el = document.createElement('x'); el.style.cssText = 'pointer-events:auto'; return el.style.pointerEvents === 'auto'; })(), _silent = false, _alignedSilent = false, abs = Math.abs, min = Math.min, savedInputChecked = [], touchDragOverListeners = [], alwaysFalse = function () { return false; }, _detectDirection = function(el, options) { var elCSS = _css(el), elWidth = parseInt(elCSS.width), child1 = _getChild(el, 0, options), child2 = _getChild(el, 1, options), firstChildCSS = child1 && _css(child1), secondChildCSS = child2 && _css(child2), firstChildWidth = firstChildCSS && parseInt(firstChildCSS.marginLeft) + parseInt(firstChildCSS.marginRight) + child1.getBoundingClientRect().width, secondChildWidth = secondChildCSS && parseInt(secondChildCSS.marginLeft) + parseInt(secondChildCSS.marginRight) + child2.getBoundingClientRect().width ; if (elCSS.display === 'flex') { return elCSS.flexDirection === 'column' || elCSS.flexDirection === 'column-reverse' ? 'vertical' : 'horizontal'; } return (child1 && ( firstChildCSS.display === 'block' || firstChildCSS.display === 'grid' || firstChildWidth >= elWidth && elCSS.float === 'none' || child2 && elCSS.float === 'none' && firstChildWidth + secondChildWidth > elWidth ) ? 'vertical' : 'horizontal' ); }, _isInRowColumn = function(x, y, el, axis, options) { var targetRect = realDragElRect || dragEl.getBoundingClientRect(), targetS1Opp = axis === 'vertical' ? targetRect.left : targetRect.top, targetS2Opp = axis === 'vertical' ? targetRect.right : targetRect.bottom, mouseOnOppAxis = axis === 'vertical' ? x : y ; return targetS1Opp < mouseOnOppAxis && mouseOnOppAxis < targetS2Opp; }, _getParentAutoScrollElement = function(el, includeSelf) { // skip to window if (!el || !el.getBoundingClientRect) return win; var elem = el; var gotSelf = false; do { // we don't need to get elem css if it isn't even overflowing in the first place (performance) if (elem.clientWidth < elem.scrollWidth || elem.clientHeight < elem.scrollHeight) { var elemCSS = _css(elem); if ( elem.clientWidth < elem.scrollWidth && (elemCSS.overflowX == 'auto' || elemCSS.overflowX == 'scroll') || elem.clientHeight < elem.scrollHeight && (elemCSS.overflowY == 'auto' || elemCSS.overflowY == 'scroll') ) { if (!elem || !elem.getBoundingClientRect || elem === document.body) return win; if (gotSelf || includeSelf) return elem; gotSelf = true; } } /* jshint boss:true */ } while (elem = elem.parentNode); return win; }, _autoScroll = _throttle(function (/**Event*/evt, /**Object*/options, /**HTMLElement*/rootEl, /**Boolean*/isFallback) { // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521 if (options.scroll) { var _this = rootEl ? rootEl[expando] : window, rect, css, sens = options.scrollSensitivity, speed = options.scrollSpeed, x = evt.clientX, y = evt.clientY, winWidth = window.innerWidth, winHeight = window.innerHeight, vx, vy, scrollThisInstance = false ; // Detect scrollEl if (scrollParentEl !== rootEl) { _clearAutoScrolls(); scrollEl = options.scroll; scrollCustomFn = options.scrollFn; if (scrollEl === true) { scrollEl = _getParentAutoScrollElement(rootEl, true); scrollParentEl = scrollEl; } } var layersOut = 0; var currentParent = scrollEl; do { var el; if (currentParent && currentParent !== win) { el = currentParent; css = _css(el); rect = currentParent.getBoundingClientRect(); vx = el.clientWidth < el.scrollWidth && (css.overflowX == 'auto' || css.overflowX == 'scroll') && ((abs(rect.right - x) <= sens) - (abs(rect.left - x) <= sens)); vy = el.clientHeight < el.scrollHeight && (css.overflowY == 'auto' || css.overflowY == 'scroll') && ((abs(rect.bottom - y) <= sens) - (abs(rect.top - y) <= sens)); } else if (currentParent === win) { el = win; vx = (winWidth - x <= sens) - (x <= sens); vy = (winHeight - y <= sens) - (y <= sens); } if (!autoScrolls[layersOut]) { for (var i = 0; i <= layersOut; i++) { if (!autoScrolls[i]) { autoScrolls[i] = {}; } } } if (autoScrolls[layersOut].vx != vx || autoScrolls[layersOut].vy != vy || autoScrolls[layersOut].el !== el) { autoScrolls[layersOut].el = el; autoScrolls[layersOut].vx = vx; autoScrolls[layersOut].vy = vy; clearInterval(autoScrolls[layersOut].pid); if (el && (vx != 0 || vy != 0)) { scrollThisInstance = true; /* jshint loopfunc:true */ autoScrolls[layersOut].pid = setInterval((function () { // emulate drag over during autoscroll (fallback), emulating native DnD behaviour if (isFallback && this.layer === 0) { Sortable.active._emulateDragOver(true); } var scrollOffsetY = autoScrolls[this.layer].vy ? autoScrolls[this.layer].vy * speed : 0; var scrollOffsetX = autoScrolls[this.layer].vx ? autoScrolls[this.layer].vx * speed : 0; if ('function' === typeof(scrollCustomFn)) { if (scrollCustomFn.call(_this, scrollOffsetX, scrollOffsetY, evt, touchEvt, autoScrolls[this.layer].el) !== 'continue') { return; } } if (autoScrolls[this.layer].el === win) { win.scrollTo(win.pageXOffset + scrollOffsetX, win.pageYOffset + scrollOffsetY); } else { autoScrolls[this.layer].el.scrollTop += scrollOffsetY; autoScrolls[this.layer].el.scrollLeft += scrollOffsetX; } }).bind({layer: layersOut}), 24); } } layersOut++; } while (options.bubbleScroll && currentParent !== win && (currentParent = _getParentAutoScrollElement(currentParent, false))); scrolling = scrollThisInstance; // in case another function catches scrolling as false in between when it is not } }, 30), _clearAutoScrolls = function () { autoScrolls.forEach(function(autoScroll) { clearInterval(autoScroll.pid); }); autoScrolls = []; }, _prepareGroup = function (options) { function toFn(value, pull) { return function(to, from, dragEl, evt) { var ret; if (value == null && pull) { ret = true; // default pull value: true (backwards compatibility) } else if (value == null || value === false) { ret = false; } else if (pull && value === 'clone') { ret = value; } else if (typeof value === 'function') { ret = value(to, from, dragEl, evt); } else { var otherGroup = (pull ? to : from).options.group.name; ret = (value === true || (typeof value === 'string' && value === otherGroup) || (value.join && value.indexOf(otherGroup) > -1)); } return ret || (to.options.group.name && from.options.group.name && to.options.group.name === from.options.group.name); }; } var group = {}; var originalGroup = options.group; if (!originalGroup || typeof originalGroup != 'object') { originalGroup = {name: originalGroup}; } group.name = originalGroup.name; group.checkPull = toFn(originalGroup.pull, true); group.checkPut = toFn(originalGroup.put); group.revertClone = originalGroup.revertClone; options.group = group; }, _checkAlignment = function(evt) { if (!dragEl) return; dragEl.parentNode[expando] && dragEl.parentNode[expando]._computeIsAligned(evt); } ; /** * @class Sortable * @param {HTMLElement} el * @param {Object} [options] */ function Sortable(el, options) { if (!(el && el.nodeType && el.nodeType === 1)) { throw 'Sortable: `el` must be HTMLElement, and not ' + {}.toString.call(el); } this.el = el; // root element this.options = options = _extend({}, options); // Export instance el[expando] = this; // Default options var defaults = { group: null, sort: true, disabled: false, store: null, handle: null, scroll: true, scrollSensitivity: 30, scrollSpeed: 10, bubbleScroll: true, draggable: /[uo]l/i.test(el.nodeName) ? 'li' : '>*', swapThreshold: 1, // percentage; 0 <= x <= 1 invertSwap: false, // invert always invertedSwapThreshold: null, // will be set to same as swapThreshold if default ghostClass: 'sortable-ghost', chosenClass: 'sortable-chosen', dragClass: 'sortable-drag', ignore: 'a, img', filter: null, preventOnFilter: true, animation: 0, setData: function (dataTransfer, dragEl) { dataTransfer.setData('Text', dragEl.textContent); }, dropBubble: false, dragoverBubble: false, dataIdAttr: 'data-id', delay: 0, touchStartThreshold: parseInt(window.devicePixelRatio, 10) || 1, forceFallback: false, fallbackClass: 'sortable-fallback', fallbackOnBody: false, fallbackTolerance: 0, fallbackOffset: {x: 0, y: 0}, supportPointer: Sortable.supportPointer !== false && ( ('PointerEvent' in window) || window.navigator && ('msPointerEnabled' in window.navigator) // microsoft ) }; // Set default options for (var name in defaults) { !(name in options) && (options[name] = defaults[name]); } if (!('direction' in options)) { options.direction = function() { return _detectDirection(el, options); }; } _prepareGroup(options); options.invertedSwapThreshold == null && (options.invertedSwapThreshold = options.swapThreshold); // Bind all private methods for (var fn in this) { if (fn.charAt(0) === '_' && typeof this[fn] === 'function') { this[fn] = this[fn].bind(this); } } // Setup drag mode this.nativeDraggable = options.forceFallback ? false : supportDraggable; // Bind events _on(el, 'mousedown', this._onTapStart); _on(el, 'touchstart', this._onTapStart); options.supportPointer && _on(el, 'pointerdown', this._onTapStart); if (this.nativeDraggable) { _on(el, 'dragover', this); _on(el, 'dragenter', this); } touchDragOverListeners.push(this._onDragOver); // Restore sorting options.store && options.store.get && this.sort(options.store.get(this) || []); } Sortable.prototype = /** @lends Sortable.prototype */ { constructor: Sortable, // is mouse aligned with dragEl? _isAligned: true, _computeIsAligned: function(evt, isDragEl) { if (_alignedSilent) return; if (!dragEl || dragEl.parentNode !== this.el) return; if (isDragEl !== true && isDragEl !== false) { isDragEl = !!_closest(evt.target, null, dragEl, true); } this._isAligned = !scrolling && (isDragEl || this._isAligned && _isInRowColumn(evt.clientX, evt.clientY, this.el, this._getDirection(evt, null), this.options)); _alignedSilent = true; setTimeout(function() { _alignedSilent = false; }, 30); }, _getDirection: function(evt, target) { return (typeof this.options.direction === 'function') ? this.options.direction.call(this, evt, target, dragEl) : this.options.direction; }, _onTapStart: function (/** Event|TouchEvent */evt) { var _this = this, el = this.el, options = this.options, preventOnFilter = options.preventOnFilter, type = evt.type, touch = evt.touches && evt.touches[0], target = (touch || evt).target, originalTarget = evt.target.shadowRoot && ((evt.path && evt.path[0]) || (evt.composedPath && evt.composedPath()[0])) || target, filter = options.filter, startIndex; _saveInputCheckedState(el); // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group. if (dragEl) { return; } if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) { return; // only left button or enabled } // cancel dnd if original target is content editable if (originalTarget.isContentEditable) { return; } target = _closest(target, options.draggable, el, true); if (!target) { return; } if (lastDownEl === target) { // Ignoring duplicate `down` return; } // Get the index of the dragged element within its parent startIndex = _index(target, options.draggable); // Check filter if (typeof filter === 'function') { if (filter.call(this, evt, target, this)) { _dispatchEvent(_this, originalTarget, 'filter', target, el, el, startIndex); preventOnFilter && evt.cancelable && evt.preventDefault(); return; // cancel dnd } } else if (filter) { filter = filter.split(',').some(function (criteria) { criteria = _closest(originalTarget, criteria.trim(), el, false); if (criteria) { _dispatchEvent(_this, criteria, 'filter', target, el, el, startIndex); return true; } }); if (filter) { preventOnFilter && evt.cancelable && evt.preventDefault(); return; // cancel dnd } } if (options.handle && !_closest(originalTarget, options.handle, el, false)) { return; } // Prepare `dragstart` this._prepareDragStart(evt, touch, target, startIndex); }, _handleAutoScroll: function(evt, fallback) { if (!dragEl || !this.options.scroll) return; var x = evt.clientX, y = evt.clientY, elem = document.elementFromPoint(x, y), _this = this ; // firefox does not have native autoscroll if (fallback || (window.navigator && window.navigator.userAgent.toLowerCase().indexOf('firefox') > -1)) { _autoScroll(evt, _this.options, elem, true); // Listener for pointer element change var ogElemScroller = _getParentAutoScrollElement(elem, true); if ( scrolling && ( !pointerElemChangedInterval || x !== lastPointerElemX || y !== lastPointerElemY ) ) { pointerElemChangedInterval && clearInterval(pointerElemChangedInterval); // Detect for pointer elem change, emulating native DnD behaviour pointerElemChangedInterval = setInterval(function() { if (!dragEl) return; // could also check if scroll direction on newElem changes due to parent autoscrolling var newElem = _getParentAutoScrollElement(document.elementFromPoint(x, y), true); if (newElem !== ogElemScroller) { ogElemScroller = newElem; _clearAutoScrolls(); _autoScroll(evt, _this.options, ogElemScroller, true); } }, 10); lastPointerElemX = x; lastPointerElemY = y; } } else { // if DnD is enabled (not on firefox), first autoscroll will already scroll, so get parent autoscroll of first autoscroll if (!_this.options.bubbleScroll || _getParentAutoScrollElement(elem, true) === window) { _clearAutoScrolls(); return; } _autoScroll(evt, _this.options, _getParentAutoScrollElement(elem, false)); } }, _prepareDragStart: function (/** Event */evt, /** Touch */touch, /** HTMLElement */target, /** Number */startIndex) { var _this = this, el = _this.el, options = _this.options, ownerDocument = el.ownerDocument, dragStartFn; if (target && !dragEl && (target.parentNode === el)) { tapEvt = evt; rootEl = el; dragEl = target; parentEl = dragEl.parentNode; nextEl = dragEl.nextSibling; lastDownEl = target; activeGroup = options.group; oldIndex = startIndex; this._lastX = (touch || evt).clientX; this._lastY = (touch || evt).clientY; dragEl.style['will-change'] = 'all'; dragStartFn = function () { // Delayed drag has been triggered // we can re-enable the events: touchmove/mousemove _this._disableDelayedDrag(); // Make the element draggable dragEl.draggable = _this.nativeDraggable; // Bind the events: dragstart/dragend _this._triggerDragStart(evt, touch); // Drag start event _dispatchEvent(_this, rootEl, 'choose', dragEl, rootEl, rootEl, oldIndex); // Chosen item _toggleClass(dragEl, options.chosenClass, true); }; // Disable "draggable" options.ignore.split(',').forEach(function (criteria) { _find(dragEl, criteria.trim(), _disableDraggable); }); _on(ownerDocument, 'mouseup', _this._onDrop); _on(ownerDocument, 'touchend', _this._onDrop); _on(ownerDocument, 'touchcancel', _this._onDrop); options.supportPointer && _on(ownerDocument, 'pointercancel', _this._onDrop); if (options.delay) { // If the user moves the pointer or let go the click or touch // before the delay has been reached: // disable the delayed drag _on(ownerDocument, 'mouseup', _this._disableDelayedDrag); _on(ownerDocument, 'touchend', _this._disableDelayedDrag); _on(ownerDocument, 'touchcancel', _this._disableDelayedDrag); _on(ownerDocument, 'mousemove', _this._delayedDragTouchMoveHandler); _on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler); options.supportPointer && _on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler); _this._dragStartTimer = setTimeout(dragStartFn.bind(_this), options.delay); } else { dragStartFn(); } } }, _delayedDragTouchMoveHandler: function (/** TouchEvent|PointerEvent **/e) { var touch = e.touches ? e.touches[0] : e; if (min(abs(touch.clientX - this._lastX), abs(touch.clientY - this._lastY)) >= this.options.touchStartThreshold ) { this._disableDelayedDrag(); } }, _disableDelayedDrag: function () { var ownerDocument = this.el.ownerDocument; clearTimeout(this._dragStartTimer); _off(ownerDocument, 'mouseup', this._disableDelayedDrag); _off(ownerDocument, 'touchend', this._disableDelayedDrag); _off(ownerDocument, 'touchcancel', this._disableDelayedDrag); _off(ownerDocument, 'mousemove', this._delayedDragTouchMoveHandler); _off(ownerDocument, 'touchmove', this._delayedDragTouchMoveHandler); _off(ownerDocument, 'pointermove', this._delayedDragTouchMoveHandler); }, _triggerDragStart: function (/** Event */evt, /** Touch */touch) { touch = touch || (evt.pointerType == 'touch' ? evt : null); if (touch) { // Touch device support tapEvt = { target: dragEl, clientX: touch.clientX, clientY: touch.clientY }; this._onDragStart(tapEvt, 'touch'); } else if (!this.nativeDraggable) { this._onDragStart(tapEvt, true); } else { _on(dragEl, 'dragend', this); _on(rootEl, 'dragstart', this._onDragStart); } try { if (document.selection) { // Timeout neccessary for IE9 _nextTick(function () { document.selection.empty(); }); } else { window.getSelection().removeAllRanges(); } } catch (err) { } }, _dragStarted: function () { if (rootEl && dragEl) { if (this.nativeDraggable) { _on(document, 'dragover', this._handleAutoScroll); _on(document, 'dragover', _checkAlignment); } var options = this.options; // Apply effect _toggleClass(dragEl, options.dragClass, false); _toggleClass(dragEl, options.ghostClass, true); _css(dragEl, 'transform', ''); Sortable.active = this; this._isAligned = true; // Drag start event _dispatchEvent(this, rootEl, 'start', dragEl, rootEl, rootEl, oldIndex); } else { this._nulling(); } }, _emulateDragOver: function (bypassLastTouchCheck) { if (touchEvt) { if (this._lastX === touchEvt.clientX && this._lastY === touchEvt.clientY && !bypassLastTouchCheck) { return; } this._lastX = touchEvt.clientX; this._lastY = touchEvt.clientY; if (!supportCssPointerEvents) { _css(ghostEl, 'display', 'none'); } var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY); var parent = target; var isDragEl = !!_closest(target, null, dragEl, true); while (target && target.shadowRoot) { target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY); parent = target; } if (parent) { do { if (parent[expando]) { var i = touchDragOverListeners.length; while (i--) { touchDragOverListeners[i]({ clientX: touchEvt.clientX, clientY: touchEvt.clientY, target: target, rootEl: parent }); } if (!this.options.dragoverBubble) { break; } } target = parent; // store last element } /* jshint boss:true */ while (parent = parent.parentNode); } dragEl.parentNode[expando]._computeIsAligned(touchEvt, isDragEl); if (!supportCssPointerEvents) { _css(ghostEl, 'display', ''); } } }, _onTouchMove: function (/**TouchEvent*/evt) { if (tapEvt) { var options = this.options, fallbackTolerance = options.fallbackTolerance, fallbackOffset = options.fallbackOffset, touch = evt.touches ? evt.touches[0] : evt, dx = (touch.clientX - tapEvt.clientX) + fallbackOffset.x, dy = (touch.clientY - tapEvt.clientY) + fallbackOffset.y, translate3d = evt.touches ? 'translate3d(' + dx + 'px,' + dy + 'px,0)' : 'translate(' + dx + 'px,' + dy + 'px)'; // prevent duplicate event firing if (this.options.supportPointer && evt.type === 'touchmove') return; // only set the status to dragging, when we are actually dragging if (!Sortable.active) { if (fallbackTolerance && min(abs(touch.clientX - this._lastX), abs(touch.clientY - this._lastY)) < fallbackTolerance ) { return; } this._dragStarted(); } // as well as creating the ghost element on the document body this._appendGhost(); this._handleAutoScroll(touch, true); moved = true; touchEvt = touch; _css(ghostEl, 'webkitTransform', translate3d); _css(ghostEl, 'mozTransform', translate3d); _css(ghostEl, 'msTransform', translate3d); _css(ghostEl, 'transform', translate3d); evt.cancelable && evt.preventDefault(); } }, _appendGhost: function () { if (!ghostEl) { var rect = dragEl.getBoundingClientRect(), css = _css(dragEl), options = this.options, ghostRect; ghostEl = dragEl.cloneNode(true); _toggleClass(ghostEl, options.ghostClass, false); _toggleClass(ghostEl, options.fallbackClass, true); _toggleClass(ghostEl, options.dragClass, true); _css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10)); _css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10)); _css(ghostEl, 'width', rect.width); _css(ghostEl, 'height', rect.height); _css(ghostEl, 'opacity', '0.8'); _css(ghostEl, 'position', 'fixed'); _css(ghostEl, 'zIndex', '100000'); _css(ghostEl, 'pointerEvents', 'none'); options.fallbackOnBody && document.body.appendChild(ghostEl) || rootEl.appendChild(ghostEl); // Fixing dimensions. ghostRect = ghostEl.getBoundingClientRect(); _css(ghostEl, 'width', rect.width * 2 - ghostRect.width); _css(ghostEl, 'height', rect.height * 2 - ghostRect.height); } }, _onDragStart: function (/**Event*/evt, /**boolean*/useFallback) { var _this = this; var dataTransfer = evt.dataTransfer; var options = _this.options; _this._offUpEvents(); if (activeGroup.checkPull(_this, _this, dragEl, evt)) { cloneEl = _clone(dragEl); cloneEl.draggable = false; cloneEl.style['will-change'] = ''; this._hideClone(); _toggleClass(cloneEl, _this.options.chosenClass, false); // #1143: IFrame support workaround _this._cloneId = _nextTick(function () { rootEl.insertBefore(cloneEl, dragEl); _dispatchEvent(_this, rootEl, 'clone', dragEl); }); } _toggleClass(dragEl, options.dragClass, true); if (useFallback) { if (useFallback === 'touch') { // Fixed #973: _on(document, 'touchmove', _preventScroll); // Bind touch events _on(document, 'touchmove', _this._onTouchMove); _on(document, 'touchend', _this._onDrop); _on(document, 'touchcancel', _this._onDrop); if (options.supportPointer) { _on(document, 'pointermove', _this._onTouchMove); _on(document, 'pointerup', _this._onDrop); } } else { // Old brwoser _on(document, 'mousemove', _this._onTouchMove); _on(document, 'mouseup', _this._onDrop); } _this._loopId = setInterval(_this._emulateDragOver, 50); _toggleClass(dragEl, options.dragClass, false); } else { if (dataTransfer) { dataTransfer.effectAllowed = 'move'; options.setData && options.setData.call(_this, dataTransfer, dragEl); } _on(document, 'drop', _this); // #1276 fix: _css(dragEl, 'transform', 'translateZ(0)'); _this._dragStartId = _nextTick(_this._dragStarted); } _on(document, 'selectstart', _this); }, _onDragOver: function (/**Event*/evt) { var el = this.el, target, dragRect, targetRect, revert, options = this.options, group = options.group, activeSortable = Sortable.active, isOwner = (activeGroup === group), isMovingBetweenSortable = false, canSort = options.sort ; if (evt.rootEl !== void 0 && evt.rootEl !== this.el) return; // touch fallback // no bubbling and not fallback if (!options.dragoverBubble && !evt.rootEl) { this._handleAutoScroll(evt); dragEl.parentNode[expando]._computeIsAligned(evt); } if (evt.preventDefault !== void 0) { evt.cancelable && evt.preventDefault(); !options.dragoverBubble && evt.stopPropagation(); } moved = true; target = _closest(evt.target, options.draggable, el, true); if (dragEl.animated && target === dragEl || target.animated || _silent) { return; } if (target !== lastTarget) { isCircumstantialInvert = false; pastFirstInvertThresh = false; lastTarget = null; } if (activeSortable && !options.disabled && (isOwner ? canSort || (revert = !rootEl.contains(dragEl)) // Reverting item into the original list : ( putSortable === this || ( (this.lastPutMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) && group.checkPut(this, activeSortable, dragEl, evt) ) ) ) ) { var direction; var axis = this._getDirection(evt, target); dragRect = dragEl.getBoundingClientRect(); if (putSortable !== this && this !== Sortable.active) { putSortable = this; isMovingBetweenSortable = true; } else if (this === Sortable.active) { isMovingBetweenSortable = false; putSortable = null; } if (revert) { this._hideClone(); parentEl = rootEl; // actualization if (cloneEl || nextEl) { rootEl.insertBefore(dragEl, cloneEl || nextEl); } else if (!canSort) { rootEl.appendChild(dragEl); } return; } if ((el.children.length === 0) || (el.children[0] === ghostEl) || (el === evt.target) && _ghostIsLast(evt, axis, el) ) { //assign target only if condition is true if (el.children.length !== 0 && el.children[0] !== ghostEl && el === evt.target) { target = _lastChild(el); } if (target) { if (target.animated) { return; } targetRect = target.getBoundingClientRect(); } if (isOwner) { activeSortable._hideClone(); } else { activeSortable._showClone(this); } if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) { if (!dragEl.contains(el)) { el.appendChild(dragEl); parentEl = el; // actualization this._isAligned = true; // must be for _ghostIsLast to pass realDragElRect = null; } this._animate(dragRect, dragEl); target && this._animate(targetRect, target); } } else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0) && target !== el) { isCircumstantialInvert = isCircumstantialInvert || options.invertSwap || dragEl.parentNode !== el || !this._isAligned; direction = _getSwapDirection(evt, target, axis, options.swapThreshold, options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target); if (direction === 0) return; realDragElRect = null; this._isAligned = true; if (!lastTarget || lastTarget !== target && (!target || !target.animated)) { pastFirstInvertThresh = false; lastTarget = target; } lastDirection = direction; targetRect = target.getBoundingClientRect(); var nextSibling = target.nextElementSibling, after = false ; after = direction === 1; var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after); if (moveVector !== false) { if (moveVector === 1 || moveVector === -1) { after = (moveVector === 1); } _silent = true; setTimeout(_unsilent, 30); if (isOwner) { activeSortable._hideClone(); } else { activeSortable._showClone(this); } if (!dragEl.contains(el)) { if (after && !nextSibling) { el.appendChild(dragEl); } else { target.parentNode.insertBefore(dragEl, after ? nextSibling : target); } } parentEl = dragEl.parentNode; // actualization this._animate(dragRect, dragEl); this._animate(targetRect, target); } } } }, _animate: function (prevRect, target) { var ms = this.options.animation; if (ms) { var currentRect = target.getBoundingClientRect(); if (target === dragEl) { realDragElRect = currentRect; } if (prevRect.nodeType === 1) { prevRect = prevRect.getBoundingClientRect(); } // Check if actually moving position if ((prevRect.left + prevRect.width / 2) === (currentRect.left + currentRect.width / 2) && (prevRect.top + prevRect.height / 2) === (currentRect.top + currentRect.height / 2) ) return; _css(target, 'transition', 'none'); _css(target, 'transform', 'translate3d(' + (prevRect.left - currentRect.left) + 'px,' + (prevRect.top - currentRect.top) + 'px,0)' ); forRepaintDummy = target.offsetWidth; // repaint _css(target, 'transition', 'all ' + ms + 'ms'); _css(target, 'transform', 'translate3d(0,0,0)'); clearTimeout(target.animated); target.animated = setTimeout(function () { _css(target, 'transition', ''); _css(target, 'transform', ''); target.animated = false; }, ms); } }, _offUpEvents: function () { var ownerDocument = this.el.ownerDocument; _off(document, 'touchmove', _preventScroll); _off(document, 'touchmove', this._onTouchMove); _off(document, 'pointermove', this._onTouchMove); _off(ownerDocument, 'mouseup', this._onDrop); _off(ownerDocument, 'touchend', this._onDrop); _off(ownerDocument, 'pointerup', this._onDrop); _off(ownerDocument, 'touchcancel', this._onDrop); _off(ownerDocument, 'pointercancel', this._onDrop); _off(document, 'selectstart', this); }, _onDrop: function (/**Event*/evt) { var el = this.el, options = this.options; scrolling = false; isCircumstantialInvert = false; pastFirstInvertThresh = false; clearInterval(this._loopId); clearInterval(pointerElemChangedInterval); _clearAutoScrolls(); _cancelThrottle(); clearTimeout(this._dragStartTimer); _cancelNextTick(this._cloneId); _cancelNextTick(this._dragStartId); // Unbind events _off(document, 'mousemove', this._onTouchMove); if (this.nativeDraggable) { _off(document, 'drop', this); _off(el, 'dragstart', this._onDragStart); _off(document, 'dragover', this._handleAutoScroll); _off(document, 'dragover', _checkAlignment); } this._offUpEvents(); if (evt) { if (moved) { evt.cancelable && evt.preventDefault(); !options.dropBubble && evt.stopPropagation(); } ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl); if (rootEl === parentEl || (putSortable && putSortable.lastPutMode !== 'clone')) { // Remove clone cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl); } if (dragEl) { if (this.nativeDraggable) { _off(dragEl, 'dragend', this); } _disableDraggable(dragEl); dragEl.style['will-change'] = ''; // Remove class's _toggleClass(dragEl, this.options.ghostClass, false); _toggleClass(dragEl, this.options.chosenClass, false); // Drag stop event _dispatchEvent(this, rootEl, 'unchoose', dragEl, parentEl, rootEl, oldIndex, null, evt); if (rootEl !== parentEl) { newIndex = _index(dragEl, options.draggable); if (newIndex >= 0) { // Add event _dispatchEvent(null, parentEl, 'add', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); // Remove event _dispatchEvent(this, rootEl, 'remove', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); // drag from one list and drop into another _dispatchEvent(null, parentEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); _dispatchEvent(this, rootEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); } putSortable && putSortable.save(); } else { if (dragEl.nextSibling !== nextEl) { // Get the index of the dragged element within its parent newIndex = _index(dragEl, options.draggable); if (newIndex >= 0) { // drag & drop within the same list _dispatchEvent(this, rootEl, 'update', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); _dispatchEvent(this, rootEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); } } } if (Sortable.active) { /* jshint eqnull:true */ if (newIndex == null || newIndex === -1) { newIndex = oldIndex; } _dispatchEvent(this, rootEl, 'end', dragEl, parentEl, rootEl, oldIndex, newIndex, evt); // Save sorting this.save(); } } } this._nulling(); }, _nulling: function() { rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = scrollEl = scrollParentEl = autoScrolls.length = pointerElemChangedInterval = lastPointerElemX = lastPointerElemY = tapEvt = touchEvt = moved = newIndex = oldIndex = lastTarget = lastDirection = forRepaintDummy = realDragElRect = putSortable = activeGroup = Sortable.active = null; savedInputChecked.forEach(function (el) { el.checked = true; }); savedInputChecked.length = 0; }, handleEvent: function (/**Event*/evt) { switch (evt.type) { case 'drop': case 'dragend': this._onDrop(evt); break; case 'dragenter': case 'dragover': if (dragEl) { this._onDragOver(evt); _globalDragOver(evt); } break; case 'selectstart': evt.preventDefault(); break; } }, /** * Serializes the item into an array of string. * @returns {String[]} */ toArray: function () { var order = [], el, children = this.el.children, i = 0, n = children.length, options = this.options; for (; i < n; i++) { el = children[i]; if (_closest(el, options.draggable, this.el, false)) { order.push(el.getAttribute(options.dataIdAttr) || _generateId(el)); } } return order; }, /** * Sorts the elements according to the array. * @param {String[]} order order of the items */ sort: function (order) { var items = {}, rootEl = this.el; this.toArray().forEach(function (id, i) { var el = rootEl.children[i]; if (_closest(el, this.options.draggable, rootEl, false)) { items[id] = el; } }, this); order.forEach(function (id) { if (items[id]) { rootEl.removeChild(items[id]); rootEl.appendChild(items[id]); } }); }, /** * Save the current sorting */ save: function () { var store = this.options.store; store && store.set && store.set(this); }, /** * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. * @param {HTMLElement} el * @param {String} [selector] default: `options.draggable` * @returns {HTMLElement|null} */ closest: function (el, selector) { return _closest(el, selector || this.options.draggable, this.el, false); }, /** * Set/get option * @param {string} name * @param {*} [value] * @returns {*} */ option: function (name, value) { var options = this.options; if (value === void 0) { return options[name]; } else { options[name] = value; if (name === 'group') { _prepareGroup(options); } } }, /** * Destroy */ destroy: function () { var el = this.el; el[expando] = null; _off(el, 'mousedown', this._onTapStart); _off(el, 'touchstart', this._onTapStart); _off(el, 'pointerdown', this._onTapStart); if (this.nativeDraggable) { _off(el, 'dragover', this); _off(el, 'dragenter', this); } // Remove draggable attributes Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) { el.removeAttribute('draggable'); }); touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1); this._onDrop(); this.el = el = null; }, _hideClone: function() { if (!cloneEl.cloneHidden) { _css(cloneEl, 'display', 'none'); cloneEl.cloneHidden = true; } }, _showClone: function(putSortable) { if (putSortable.lastPutMode !== 'clone') { this._hideClone(); return; } if (cloneEl.cloneHidden) { // show clone at dragEl or original position if (rootEl.contains(dragEl) && !this.options.group.revertClone) { rootEl.insertBefore(cloneEl, dragEl); } else if (nextEl) { rootEl.insertBefore(cloneEl, nextEl); } else { rootEl.appendChild(cloneEl); } if (this.options.group.revertClone) { this._animate(dragEl, cloneEl); } _css(cloneEl, 'display', ''); cloneEl.cloneHidden = false; } } }; function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx, includeCTX) { if (el) { ctx = ctx || document; do { if ((selector === '>*' && el.parentNode === ctx) || _matches(el, selector) || (includeCTX && el === ctx)) { return el; } if (el === ctx) break; /* jshint boss:true */ } while (el = _getParentOrHost(el)); } return null; } function _getParentOrHost(el) { return (el.host && el !== document && el.host.nodeType) ? el.host : el.parentNode; } function _globalDragOver(/**Event*/evt) { if (evt.dataTransfer) { evt.dataTransfer.dropEffect = 'move'; } evt.cancelable && evt.preventDefault(); } function _on(el, event, fn) { el.addEventListener(event, fn, captureMode); } function _off(el, event, fn) { el.removeEventListener(event, fn, captureMode); } function _toggleClass(el, name, state) { if (el && name) { if (el.classList) { el.classList[state ? 'add' : 'remove'](name); } else { var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' '); el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' '); } } } function _css(el, prop, val) { var style = el && el.style; if (style) { if (val === void 0) { if (document.defaultView && document.defaultView.getComputedStyle) { val = document.defaultView.getComputedStyle(el, ''); } else if (el.currentStyle) { val = el.currentStyle; } return prop === void 0 ? val : val[prop]; } else { if (!(prop in style)) { prop = '-webkit-' + prop; } style[prop] = val + (typeof val === 'string' ? '' : 'px'); } } } function _find(ctx, tagName, iterator) { if (ctx) { var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length; if (iterator) { for (; i < n; i++) { iterator(list[i], i); } } return list; } return []; } function _dispatchEvent(sortable, rootEl, name, targetEl, toEl, fromEl, startIndex, newIndex, originalEvt) { sortable = (sortable || rootEl[expando]); var evt, options = sortable.options, onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1); // Support for new CustomEvent feature if (window.CustomEvent) { evt = new CustomEvent(name, { bubbles: true, cancelable: true }); } else { evt = document.createEvent('Event'); evt.initEvent(name, true, true); } evt.to = toEl || rootEl; evt.from = fromEl || rootEl; evt.item = targetEl || rootEl; evt.clone = cloneEl; evt.oldIndex = startIndex; evt.newIndex = newIndex; evt.originalEvent = originalEvt; rootEl.dispatchEvent(evt); if (options[onName]) { options[onName].call(sortable, evt); } } function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvt, willInsertAfter) { var evt, sortable = fromEl[expando], onMoveFn = sortable.options.onMove, retVal; // Support for new CustomEvent feature if (window.CustomEvent) { evt = new CustomEvent('move', { bubbles: true, cancelable: true }); } else { evt = document.createEvent('Event'); evt.initEvent('move', true, true); } evt.to = toEl; evt.from = fromEl; evt.dragged = dragEl; evt.draggedRect = dragRect; evt.related = targetEl || toEl; evt.relatedRect = targetRect || toEl.getBoundingClientRect(); evt.willInsertAfter = willInsertAfter; evt.originalEvent = originalEvt; fromEl.dispatchEvent(evt); if (onMoveFn) { retVal = onMoveFn.call(sortable, evt, originalEvt); } return retVal; } function _disableDraggable(el) { el.draggable = false; } function _unsilent() { _silent = false; } function _getChild(el, childNum, options) { var currentChild = 0, i = 0, children = el.children ; while (i < children.length) { if ( children[i].style.display !== 'none' && children[i] !== ghostEl && children[i] !== dragEl && _closest(children[i], options.draggable, el, false) ) { if (currentChild === childNum) { return children[i]; } currentChild++; } i++; } return null; } function _lastChild(el) { var last = el.lastElementChild; if (last === ghostEl) { last = el.children[el.childElementCount - 2]; } return last || null; } function _ghostIsLast(evt, axis, el) { var elRect = _lastChild(el).getBoundingClientRect(), mouseOnAxis = axis === 'vertical' ? evt.clientY : evt.clientX, mouseOnOppAxis = axis === 'vertical' ? evt.clientX : evt.clientY, targetS2 = axis === 'vertical' ? elRect.bottom : elRect.right, targetS1Opp = axis === 'vertical' ? elRect.left : elRect.top, targetS2Opp = axis === 'vertical' ? elRect.right : elRect.bottom ; return ( mouseOnOppAxis > targetS1Opp && mouseOnOppAxis < targetS2Opp && mouseOnAxis > targetS2 ); } function _getSwapDirection(evt, target, axis, swapThreshold, invertedSwapThreshold, invertSwap, inside) { var targetRect = target.getBoundingClientRect(), mouseOnAxis = axis === 'vertical' ? evt.clientY : evt.clientX, targetLength = axis === 'vertical' ? targetRect.height : targetRect.width, targetS1 = axis === 'vertical' ? targetRect.top : targetRect.left, targetS2 = axis === 'vertical' ? targetRect.bottom : targetRect.right, dragRect = dragEl.getBoundingClientRect(), dragLength = axis === 'vertical' ? dragRect.height : dragRect.width, invert = false ; var dragStyle = _css(dragEl); dragLength += parseInt(dragStyle.marginLeft) + parseInt(dragStyle.marginRight); if (!invertSwap) { // Never invert or create dragEl shadow when width causes mouse to move past the end of regular swapThreshold if (inside && dragLength < targetLength * swapThreshold) { // multiplied only by swapThreshold because mouse will already be inside target by (1 - threshold) * targetLength / 2 // check if past first invert threshold on side opposite of lastDirection if (!pastFirstInvertThresh && (lastDirection === 1 ? ( mouseOnAxis > targetS1 + targetLength * invertedSwapThreshold / 2 ) : ( mouseOnAxis < targetS2 - targetLength * invertedSwapThreshold / 2 ) ) ) { // past first invert threshold, do not restrict inverted threshold to dragEl shadow pastFirstInvertThresh = true; } if (!pastFirstInvertThresh) { var dragS1 = axis === 'vertical' ? dragRect.top : dragRect.left, dragS2 = axis === 'vertical' ? dragRect.bottom : dragRect.right ; // dragEl shadow if ( lastDirection === 1 ? ( mouseOnAxis < targetS1 + dragLength // over dragEl shadow ) : ( mouseOnAxis > targetS2 - dragLength ) ) { return lastDirection * -1; } } else { invert = true; } } else { // Regular if ( mouseOnAxis > targetS1 + (targetLength * (1 - swapThreshold) / 2) && mouseOnAxis < targetS2 - (targetLength * (1 - swapThreshold) / 2) ) { return ((mouseOnAxis > targetS1 + targetLength / 2) ? -1 : 1); } } } invert = invert || invertSwap; if (invert) { // Invert of regular if ( mouseOnAxis < targetS1 + (targetLength * invertedSwapThreshold / 2) || mouseOnAxis > targetS2 - (targetLength * invertedSwapThreshold / 2) ) { return ((mouseOnAxis > targetS1 + targetLength / 2) ? 1 : -1); } } return 0; } /** * Generate id * @param {HTMLElement} el * @returns {String} * @private */ function _generateId(el) { var str = el.tagName + el.className + el.src + el.href + el.textContent, i = str.length, sum = 0; while (i--) { sum += str.charCodeAt(i); } return sum.toString(36); } /** * Returns the index of an element within its parent for a selected set of * elements * @param {HTMLElement} el * @param {selector} selector * @return {number} */ function _index(el, selector) { var index = 0; if (!el || !el.parentNode) { return -1; } while (el && (el = el.previousElementSibling)) { if ((el.nodeName.toUpperCase() !== 'TEMPLATE') && (selector === '>*' || _matches(el, selector))) { index++; } } return index; } function _matches(/**HTMLElement*/el, /**String*/selector) { if (el) { try { if (el.matches) { return el.matches(selector); } else if (el.msMatchesSelector) { return el.msMatchesSelector(selector); } } catch(_) { return false; } } return false; } var _throttleTimeout; function _throttle(callback, ms) { return function () { if (!_throttleTimeout) { var args = arguments, _this = this ; _throttleTimeout = setTimeout(function () { if (args.length === 1) { callback.call(_this, args[0]); } else { callback.apply(_this, args); } _throttleTimeout = void 0; }, ms); } }; } function _cancelThrottle() { clearTimeout(_throttleTimeout); _throttleTimeout = void 0; } function _extend(dst, src) { if (dst && src) { for (var key in src) { if (src.hasOwnProperty(key)) { dst[key] = src[key]; } } } return dst; } function _clone(el) { if (Polymer && Polymer.dom) { return Polymer.dom(el).cloneNode(true); } else if ($) { return $(el).clone(true)[0]; } else { return el.cloneNode(true); } } function _saveInputCheckedState(root) { savedInputChecked.length = 0; var inputs = root.getElementsByTagName('input'); var idx = inputs.length; while (idx--) { var el = inputs[idx]; el.checked && savedInputChecked.push(el); } } function _nextTick(fn) { return setTimeout(fn, 0); } function _cancelNextTick(id) { return clearTimeout(id); } function _preventScroll(evt) { if (Sortable.active && evt.cancelable) { evt.preventDefault(); } } // Export utils Sortable.utils = { on: _on, off: _off, css: _css, find: _find, is: function (el, selector) { return !!_closest(el, selector, el, false); }, extend: _extend, throttle: _throttle, closest: _closest, toggleClass: _toggleClass, clone: _clone, index: _index, nextTick: _nextTick, cancelNextTick: _cancelNextTick, detectDirection: _detectDirection, getChild: _getChild }; /** * Create sortable instance * @param {HTMLElement} el * @param {Object} [options] */ Sortable.create = function (el, options) { return new Sortable(el, options); }; // Export Sortable.version = '1.8.0-rc1'; return Sortable; });
extend1994/cdnjs
ajax/libs/Sortable/1.8.0-rc1/Sortable.js
JavaScript
mit
50,600
import { isElement, isValidElementType, ForwardRef } from 'react-is'; import unitless from '@emotion/unitless'; import validAttr from '@emotion/is-prop-valid'; import React, { useContext, useMemo, createElement, useState, useDebugValue, useEffect } from 'react'; import Stylis from 'stylis/stylis.min'; import _insertRulePlugin from 'stylis-rule-sheet'; import PropTypes from 'prop-types'; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } // var interleave = (function (strings, interpolations) { var result = [strings[0]]; for (var i = 0, len = interpolations.length; i < len; i += 1) { result.push(interpolations[i], strings[i + 1]); } return result; }); // var isPlainObject = (function (x) { return typeof x === 'object' && x.constructor === Object; }); // var EMPTY_ARRAY = Object.freeze([]); var EMPTY_OBJECT = Object.freeze({}); // function isFunction(test) { return typeof test === 'function'; } // function getComponentName(target) { return (process.env.NODE_ENV !== 'production' ? typeof target === 'string' && target : false) || // $FlowFixMe target.displayName || // $FlowFixMe target.name || 'Component'; } // function isStatelessFunction(test) { return typeof test === 'function' && !(test.prototype && test.prototype.isReactComponent); } // function isStyledComponent(target) { return target && typeof target.styledComponentId === 'string'; } // var SC_ATTR = typeof process !== 'undefined' && process.env.SC_ATTR || 'data-styled'; var SC_ATTR_ACTIVE = 'active'; var SC_VERSION_ATTR = 'data-styled-version'; var SC_VERSION = "5.0.0-4.canary-sheet"; var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window; var DISABLE_SPEEDY = typeof SC_DISABLE_SPEEDY === 'boolean' && SC_DISABLE_SPEEDY || process.env.NODE_ENV !== 'production'; // Shared empty execution context when generating static styles var STATIC_EXECUTION_CONTEXT = {}; // var ELEMENT_TYPE = 1; /* Node.ELEMENT_TYPE */ /** Find last style element if any inside target */ var findLastStyleTag = function findLastStyleTag(target) { var childNodes = target.childNodes; for (var i = childNodes.length; i >= 0; i--) { var child = childNodes[i]; if (child && child.nodeType === ELEMENT_TYPE && child.hasAttribute(SC_ATTR)) { return child; } } return undefined; }; /** Create a style element inside `target` or <head> after the last */ var makeStyleTag = function makeStyleTag(target) { var head = document.head; var parent = target || head; var style = document.createElement('style'); var prevStyle = findLastStyleTag(parent); var nextSibling = prevStyle !== undefined ? prevStyle.nextSibling : null; style.setAttribute(SC_ATTR, SC_ATTR_ACTIVE); style.setAttribute(SC_VERSION_ATTR, SC_VERSION); parent.insertBefore(style, nextSibling); return style; }; /** Get the CSSStyleSheet instance for a given style element */ var getSheet = function getSheet(tag) { if (tag.sheet) { return tag.sheet; } // Avoid Firefox quirk where the style element might not have a sheet property var _document = document, styleSheets = _document.styleSheets; for (var i = 0, l = styleSheets.length; i < l; i++) { var sheet = styleSheets[i]; if (sheet.ownerNode === tag) { return sheet; } } throw new TypeError("CSSStyleSheet could not be found on HTMLStyleElement"); }; // /** CSSStyleSheet-like Tag abstraction for CSS rules */ /** Create a CSSStyleSheet-like tag depending on the environment */ var makeTag = function makeTag(isServer, target) { if (!IS_BROWSER) { return new VirtualTag(target); } else if (DISABLE_SPEEDY) { return new TextTag(target); } else { return new SpeedyTag(target); } }; /** A Tag that wraps CSSOM's CSSStyleSheet API directly */ var SpeedyTag = /*#__PURE__*/ function () { function SpeedyTag(target) { var element = this.element = makeStyleTag(target); // Avoid Edge bug where empty style elements don't create sheets element.appendChild(document.createTextNode('')); this.sheet = getSheet(element); this.length = 0; } var _proto = SpeedyTag.prototype; _proto.insertRule = function insertRule(index, rule) { try { this.sheet.insertRule(rule, index); this.length++; return true; } catch (_error) { return false; } }; _proto.deleteRule = function deleteRule(index) { this.sheet.deleteRule(index); this.length--; }; _proto.getRule = function getRule(index) { if (index < this.length) { return this.sheet.cssRules[index].cssText; } else { return ''; } }; return SpeedyTag; }(); /** A Tag that emulates the CSSStyleSheet API but uses text nodes */ var TextTag = /*#__PURE__*/ function () { function TextTag(target) { var element = this.element = makeStyleTag(target); this.nodes = element.childNodes; this.length = 0; } var _proto2 = TextTag.prototype; _proto2.insertRule = function insertRule(index, rule) { if (index <= this.length && index >= 0) { var node = document.createTextNode(rule); var refNode = this.nodes[index]; this.element.insertBefore(node, refNode || null); this.length++; return true; } else { return false; } }; _proto2.deleteRule = function deleteRule(index) { this.element.removeChild(this.nodes[index]); this.length--; }; _proto2.getRule = function getRule(index) { if (index < this.length) { return this.nodes[index].textContent; } else { return ''; } }; return TextTag; }(); /** A completely virtual (server-side) Tag that doesn't manipulate the DOM */ var VirtualTag = /*#__PURE__*/ function () { function VirtualTag(_target) { this.rules = []; this.length = 0; } var _proto3 = VirtualTag.prototype; _proto3.insertRule = function insertRule(index, rule) { if (index <= this.length) { this.rules.splice(index, 0, rule); this.length++; return true; } else { return false; } }; _proto3.deleteRule = function deleteRule(index) { this.rules.splice(index, 1); this.length--; }; _proto3.getRule = function getRule(index) { if (index < this.length) { return this.rules[index]; } else { return ''; } }; return VirtualTag; }(); // /* eslint-disable no-use-before-define */ /** Group-aware Tag that sorts rules by indices */ /** Create a GroupedTag with an underlying Tag implementation */ var makeGroupedTag = function makeGroupedTag(tag) { return new DefaultGroupedTag(tag); }; var BASE_SIZE = 1 << 8; var DefaultGroupedTag = /*#__PURE__*/ function () { function DefaultGroupedTag(tag) { this.groupSizes = new Uint32Array(BASE_SIZE); this.length = BASE_SIZE; this.tag = tag; } var _proto = DefaultGroupedTag.prototype; _proto.indexOfGroup = function indexOfGroup(group) { var index = 0; for (var i = 0; i < group; i++) { index += this.groupSizes[i]; } return index; }; _proto.insertRules = function insertRules(group, rules) { if (group >= this.groupSizes.length) { var oldBuffer = this.groupSizes; var oldSize = oldBuffer.length; var newSize = BASE_SIZE << (group / BASE_SIZE | 0); this.groupSizes = new Uint32Array(newSize); this.groupSizes.set(oldBuffer); this.length = newSize; for (var i = oldSize; i < newSize; i++) { this.groupSizes[i] = 0; } } var startIndex = this.indexOfGroup(group + 1); for (var _i = 0, l = rules.length; _i < l; _i++) { if (this.tag.insertRule(startIndex + _i, rules[_i])) { this.groupSizes[group]++; } } }; _proto.clearGroup = function clearGroup(group) { if (group < this.length) { var length = this.groupSizes[group]; var startIndex = this.indexOfGroup(group); var endIndex = startIndex + length; this.groupSizes[group] = 0; for (var i = startIndex; i < endIndex; i++) { this.tag.deleteRule(startIndex); } } }; _proto.getGroup = function getGroup(group) { var css = ''; if (group >= this.length || this.groupSizes[group] === 0) { return css; } var length = this.groupSizes[group]; var startIndex = this.indexOfGroup(group); var endIndex = startIndex + length; for (var i = startIndex; i < endIndex; i++) { css += this.tag.getRule(i) + "\n"; } return css; }; return DefaultGroupedTag; }(); // var groupIDRegister = new Map(); var reverseRegister = new Map(); var nextFreeGroup = 1; var getGroupForId = function getGroupForId(id) { if (groupIDRegister.has(id)) { return groupIDRegister.get(id); } var group = nextFreeGroup++; groupIDRegister.set(id, group); reverseRegister.set(group, id); return group; }; var getIdForGroup = function getIdForGroup(group) { return reverseRegister.get(group); }; var setGroupForId = function setGroupForId(id, group) { if (group >= nextFreeGroup) { nextFreeGroup = group + 1; } groupIDRegister.set(id, group); reverseRegister.set(group, id); }; // var PLAIN_RULE_TYPE = 1; var SELECTOR = "style[" + SC_ATTR + "][" + SC_VERSION_ATTR + "=\"" + SC_VERSION + "\"]"; var MARKER_RE = new RegExp("^" + SC_ATTR + "\\.g(\\d+)\\[id=\"([\\w\\d-]+)\"\\]"); var outputSheet = function outputSheet(sheet) { var tag = sheet.getTag(); var length = tag.length; var css = ''; for (var group = 0; group < length; group++) { var id = getIdForGroup(group); if (id === undefined) continue; var names = sheet.names.get(id); var rules = tag.getGroup(group); if (names === undefined || rules.length === 0) continue; var selector = SC_ATTR + ".g" + group + "[id=\"" + id + "\"]"; var content = ''; if (names !== undefined) { names.forEach(function (name) { if (name.length > 0) { content += name + ","; } }); } // NOTE: It's easier to collect rules and have the marker // after the actual rules to simplify the rehydration css += rules + selector; if (content.length > 0) { css += "{content:\"" + content + "\"}\n"; } else { css += '{}\n'; } } return css; }; var rehydrateNamesFromContent = function rehydrateNamesFromContent(sheet, id, content) { var names = content.slice(1, -1).split(','); for (var i = 0, l = names.length; i < l; i++) { var name = names[i]; if (name.length > 0) { sheet.registerName(id, name); } } }; var rehydrateSheetFromTag = function rehydrateSheetFromTag(sheet, style) { var _getSheet = getSheet(style), cssRules = _getSheet.cssRules; var rules = []; for (var i = 0, l = cssRules.length; i < l; i++) { var cssRule = cssRules[i]; if (cssRule.type !== PLAIN_RULE_TYPE) { rules.push(cssRule.cssText); } else { var marker = cssRule.selectorText.match(MARKER_RE); if (marker !== null) { var group = parseInt(marker[1], 10) | 0; var id = marker[2]; var content = cssRule.style.content; if (group !== 0) { // Rehydrate componentId to group index mapping setGroupForId(id, group); // Rehydrate names and rules rehydrateNamesFromContent(sheet, id, content); sheet.getTag().insertRules(group, rules); } rules.length = 0; } else { rules.push(cssRule.cssText); } } } }; var rehydrateSheet = function rehydrateSheet(sheet) { var nodes = document.querySelectorAll(SELECTOR); for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i]; if (node && node.getAttribute(SC_ATTR) !== SC_ATTR_ACTIVE) { rehydrateSheetFromTag(sheet, node); if (node.parentNode) { node.parentNode.removeChild(node); } } } }; // var SHOULD_REHYDRATE = IS_BROWSER; /** Contains the main stylesheet logic for stringification and caching */ var StyleSheet = /*#__PURE__*/ function () { /** Register a group ID to give it an index */ StyleSheet.registerId = function registerId(id) { return getGroupForId(id); }; function StyleSheet(isServer, target) { this.names = new Map(); this.isServer = isServer; this.target = target; // We rehydrate only once and use the sheet that is // created first if (!isServer && IS_BROWSER && SHOULD_REHYDRATE) { SHOULD_REHYDRATE = false; rehydrateSheet(this); } } /** Lazily initialises a GroupedTag for when it's actually needed */ var _proto = StyleSheet.prototype; _proto.getTag = function getTag() { if (this.tag === undefined) { var tag = makeTag(this.isServer, this.target); this.tag = makeGroupedTag(tag); } return this.tag; } /** Check whether a name is known for caching */ ; _proto.hasNameForId = function hasNameForId(id, name) { return this.names.has(id) && this.names.get(id).has(name); } /** Mark a group's name as known for caching */ ; _proto.registerName = function registerName(id, name) { getGroupForId(id); if (!this.names.has(id)) { var groupNames = new Set(); groupNames.add(name); this.names.set(id, groupNames); } else { this.names.get(id).add(name); } } /** Insert new rules which also marks the name as known */ ; _proto.insertRules = function insertRules(id, name, rules) { this.registerName(id, name); this.getTag().insertRules(getGroupForId(id), rules); } /** Clears all cached names for a given group ID */ ; _proto.clearNames = function clearNames(id) { if (this.names.has(id)) { this.names.get(id).clear(); } } /** Clears all rules for a given group ID */ ; _proto.clearRules = function clearRules(id) { this.getTag().clearGroup(getGroupForId(id)); this.clearNames(id); } /** Clears the entire tag which deletes all rules but not its names */ ; _proto.clearTag = function clearTag() { // NOTE: This does not clear the names, since it's only used during SSR // so that we can continuously output only new rules this.tag = undefined; } /** Outputs the current sheet as a CSS string with markers for SSR */ ; _proto.toString = function toString() { return outputSheet(this); }; return StyleSheet; }(); // // /** * Parse errors.md and turn it into a simple hash of code: message */ var ERRORS = process.env.NODE_ENV !== 'production' ? { "1": "Cannot create styled-component for component: %s.\n\n", "2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n", "3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n", "4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n", "5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n", "6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n", "7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n", "8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n", "9": "Missing document `<head>`\n\n", "10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n", "11": "_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n", "12": "It seems you are interpolating a keyframe declaration (%s) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\`\\` helper (see https://www.styled-components.com/docs/api#css), which ensures the styles are injected correctly.\n\n", "13": "%s is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.\n" } : {}; /** * super basic version of sprintf */ function format() { var a = arguments.length <= 0 ? undefined : arguments[0]; var b = []; for (var c = 1, len = arguments.length; c < len; c += 1) { b.push(c < 0 || arguments.length <= c ? undefined : arguments[c]); } b.forEach(function (d) { a = a.replace(/%[a-z]/, d); }); return a; } /** * Create an error file out of errors.md for development and a simple web link to the full errors * in production mode. */ var StyledComponentsError = /*#__PURE__*/ function (_Error) { _inheritsLoose(StyledComponentsError, _Error); function StyledComponentsError(code) { var _this; for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (process.env.NODE_ENV === 'production') { _this = _Error.call(this, "An error occurred. See https://github.com/styled-components/styled-components/blob/master/packages/styled-components/src/utils/errors.md#" + code + " for more information. " + (interpolations ? "Additional arguments: " + interpolations.join(', ') : '')) || this; } else { _this = _Error.call(this, format.apply(void 0, [ERRORS[code]].concat(interpolations)).trim()) || this; } return _assertThisInitialized(_this); } return StyledComponentsError; }(_wrapNativeSuper(Error)); // var Keyframes = /*#__PURE__*/ function () { function Keyframes(name, rules) { var _this = this; this.inject = function (styleSheet) { if (!styleSheet.hasNameForId(_this.id, _this.name)) { styleSheet.insertRules(_this.id, _this.name, _this.rules); } }; this.toString = function () { throw new StyledComponentsError(12, String(_this.name)); }; this.name = name; this.rules = rules; this.id = "sc-keyframes-" + name; } var _proto = Keyframes.prototype; _proto.getName = function getName() { return this.name; }; return Keyframes; }(); // /** * inlined version of * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js */ var uppercasePattern = /([A-Z])/g; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-'); } // function addUnitIfNeeded(name, value) { // https://github.com/amilajack/eslint-plugin-flowtype-errors/issues/133 // $FlowFixMe if (value == null || typeof value === 'boolean' || value === '') { return ''; } if (typeof value === 'number' && value !== 0 && !(name in unitless)) { return value + "px"; // Presumes implicit 'px' suffix for unitless numbers } return String(value).trim(); } // /** * It's falsish not falsy because 0 is allowed. */ var isFalsish = function isFalsish(chunk) { return chunk === undefined || chunk === null || chunk === false || chunk === ''; }; var objToCss = function objToCss(obj, prevKey) { var css = Object.keys(obj).filter(function (key) { return !isFalsish(obj[key]); }).map(function (key) { if (isPlainObject(obj[key])) return objToCss(obj[key], key); return hyphenateStyleName(key) + ": " + addUnitIfNeeded(key, obj[key]) + ";"; }).join(' '); return prevKey ? prevKey + " {\n " + css + "\n}" : css; }; function flatten(chunk, executionContext, styleSheet) { if (Array.isArray(chunk)) { var ruleSet = []; for (var i = 0, len = chunk.length, result; i < len; i += 1) { result = flatten(chunk[i], executionContext, styleSheet); if (result === '') continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result); } return ruleSet; } if (isFalsish(chunk)) { return ''; } /* Handle other components */ if (isStyledComponent(chunk)) { return "." + chunk.styledComponentId; } /* Either execute or defer the function */ if (isFunction(chunk)) { if (isStatelessFunction(chunk) && executionContext) { var _result = chunk(executionContext); if (process.env.NODE_ENV !== 'production' && isElement(_result)) { // eslint-disable-next-line no-console console.warn(getComponentName(chunk) + " is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details."); } return flatten(_result, executionContext, styleSheet); } else return chunk; } if (chunk instanceof Keyframes) { if (styleSheet) { chunk.inject(styleSheet); return chunk.getName(); } else return chunk; } /* Handle objects */ return isPlainObject(chunk) ? objToCss(chunk) : chunk.toString(); } // function css(styles) { for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (isFunction(styles) || isPlainObject(styles)) { // $FlowFixMe return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations))); } // $FlowFixMe return flatten(interleave(styles, interpolations)); } function constructWithOptions(componentConstructor, tag, options) { if (options === void 0) { options = EMPTY_OBJECT; } if (!isValidElementType(tag)) { throw new StyledComponentsError(1, String(tag)); } /* This is callable directly as a template function */ // $FlowFixMe: Not typed to avoid destructuring arguments var templateFunction = function templateFunction() { return componentConstructor(tag, options, css.apply(void 0, arguments)); }; /* If config methods are called, wrap up a new template function and merge options */ templateFunction.withConfig = function (config) { return constructWithOptions(componentConstructor, tag, _extends({}, options, config)); }; /* Modify/inject new props at runtime */ templateFunction.attrs = function (attrs) { return constructWithOptions(componentConstructor, tag, _extends({}, options, { attrs: Array.prototype.concat(options.attrs, attrs).filter(Boolean) })); }; return templateFunction; } // /* eslint-disable no-bitwise */ /* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised * counterparts */ var charsLength = 52; /* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */ var getAlphabeticChar = function getAlphabeticChar(code) { return String.fromCharCode(code + (code > 25 ? 39 : 97)); }; /* input a number, usually a hash and convert it to base-52 */ function generateAlphabeticName(code) { var name = ''; var x; /* get a char and divide by alphabet-length */ for (x = Math.abs(code); x > charsLength; x = x / charsLength | 0) { name = getAlphabeticChar(x % charsLength) + name; } return getAlphabeticChar(x % charsLength) + name; } // // version of djb2 where we pretend that we're still looping over // the same string var phash = function phash(h, x) { h = h | 0; for (var i = 0, l = x.length | 0; i < l; i++) { h = (h << 5) + h + x.charCodeAt(i); } return h; }; // This is a djb2 hashing function var hash = function hash(x) { return phash(5381 | 0, x) >>> 0; }; var hasher = function hasher(str) { return generateAlphabeticName(hash(str)); }; // var stylis = new Stylis({ global: false, cascade: true, keyframe: false, prefix: true, compress: false, semicolon: false // NOTE: This means "autocomplete missing semicolons" }); // Wrap `insertRulePlugin to build a list of rules, // and then make our own plugin to return the rules. This // makes it easier to hook into the existing SSR architecture var parsingRules = []; // eslint-disable-next-line consistent-return var returnRulesPlugin = function returnRulesPlugin(context) { if (context === -2) { var parsedRules = parsingRules; parsingRules = []; return parsedRules; } }; var parseRulesPlugin = _insertRulePlugin(function (rule) { parsingRules.push(rule); }); var _componentId; var _selector; var _selectorRegexp; var selfReferenceReplacer = function selfReferenceReplacer(match, offset, string) { if ( // the first self-ref is always untouched offset > 0 && // there should be at least two self-refs to do a replacement (.b > .b) string.slice(0, offset).indexOf(_selector) !== -1 && // no consecutive self refs (.b.b); that is a precedence boost and treated differently string.slice(offset - _selector.length, offset) !== _selector) { return "." + _componentId; } return match; }; /** * When writing a style like * * & + & { * color: red; * } * * The second ampersand should be a reference to the static component class. stylis * has no knowledge of static class so we have to intelligently replace the base selector. */ var selfReferenceReplacementPlugin = function selfReferenceReplacementPlugin(context, _, selectors) { if (context === 2 && selectors.length && selectors[0].lastIndexOf(_selector) > 0) { // eslint-disable-next-line no-param-reassign selectors[0] = selectors[0].replace(_selectorRegexp, selfReferenceReplacer); } }; stylis.use([selfReferenceReplacementPlugin, parseRulesPlugin, returnRulesPlugin]); var COMMENT_REGEX = /^\s*\/\/.*$/gm; function stringifyRules(css, selector, prefix, componentId) { if (componentId === void 0) { componentId = '&'; } var flatCSS = css.replace(COMMENT_REGEX, ''); var cssStr = selector && prefix ? prefix + " " + selector + " { " + flatCSS + " }" : flatCSS; // stylis has no concept of state to be passed to plugins // but since JS is single=threaded, we can rely on that to ensure // these properties stay in sync with the current stylis run _componentId = componentId; _selector = selector; _selectorRegexp = new RegExp("\\" + _selector + "\\b", 'g'); return stylis(prefix || !selector ? '' : selector, cssStr); } // function hasFunctionObjectKey(obj) { // eslint-disable-next-line guard-for-in, no-restricted-syntax for (var key in obj) { if (isFunction(obj[key])) { return true; } } return false; } function isStaticRules(rules, attrs) { for (var i = 0; i < rules.length; i += 1) { var rule = rules[i]; // recursive case if (Array.isArray(rule) && !isStaticRules(rule, attrs)) { return false; } else if (isFunction(rule) && !isStyledComponent(rule)) { // functions are allowed to be static if they're just being // used to get the classname of a nested styled component return false; } } if (attrs.some(function (x) { return isFunction(x) || hasFunctionObjectKey(x); })) return false; return true; } // var isHMREnabled = process.env.NODE_ENV !== 'production' && typeof module !== 'undefined' && module.hot; /* ComponentStyle is all the CSS-specific stuff, not the React-specific stuff. */ var ComponentStyle = /*#__PURE__*/ function () { function ComponentStyle(rules, attrs, componentId) { this.rules = rules; this.isStatic = !isHMREnabled && IS_BROWSER && isStaticRules(rules, attrs); this.componentId = componentId; this.baseHash = hash(componentId); // NOTE: This registers the componentId, which ensures a consistent order // for this component's styles compared to others StyleSheet.registerId(componentId); } /* * Flattens a rule set into valid CSS * Hashes it, wraps the whole chunk in a .hash1234 {} * Returns the hash to be injected on render() * */ var _proto = ComponentStyle.prototype; _proto.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) { var componentId = this.componentId; if (this.isStatic) { if (!styleSheet.hasNameForId(componentId, componentId)) { var cssStatic = flatten(this.rules, executionContext, styleSheet).join(''); var cssStaticFormatted = stringifyRules(cssStatic, "." + componentId, undefined, componentId); styleSheet.insertRules(componentId, componentId, cssStaticFormatted); } return componentId; } else { var length = this.rules.length; var i = 0; var dynamicHash = this.baseHash; var css = ''; for (i = 0; i < length; i++) { var partRule = this.rules[i]; if (typeof partRule === 'string') { css += partRule; } else { var partChunk = flatten(partRule, executionContext, styleSheet); var partString = Array.isArray(partChunk) ? partChunk.join('') : partChunk; dynamicHash = phash(dynamicHash, partString + i); css += partString; } } var name = generateAlphabeticName(dynamicHash >>> 0); if (!styleSheet.hasNameForId(componentId, name)) { var cssFormatted = stringifyRules(css, "." + name, undefined, componentId); styleSheet.insertRules(componentId, name, cssFormatted); } return name; } }; return ComponentStyle; }(); // var LIMIT = 200; var createWarnTooManyClasses = (function (displayName) { var generatedClasses = {}; var warningSeen = false; return function (className) { if (!warningSeen) { generatedClasses[className] = true; if (Object.keys(generatedClasses).length >= LIMIT) { // Unable to find latestRule in test environment. /* eslint-disable no-console, prefer-template */ console.warn("Over " + LIMIT + " classes were generated for component " + displayName + ". \n" + 'Consider using the attrs method, together with a style object for frequently changed styles.\n' + 'Example:\n' + ' const Component = styled.div.attrs({\n' + ' style: ({ background }) => ({\n' + ' background,\n' + ' }),\n' + ' })`width: 100%;`\n\n' + ' <Component />'); warningSeen = true; generatedClasses = {}; } } }; }); // var determineTheme = (function (props, fallbackTheme, defaultProps) { if (defaultProps === void 0) { defaultProps = EMPTY_OBJECT; } // Props should take precedence over ThemeProvider, which should take precedence over // defaultProps, but React automatically puts defaultProps on props. /* eslint-disable react/prop-types, flowtype-errors/show-errors */ var isDefaultTheme = defaultProps ? props.theme === defaultProps.theme : false; var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme || defaultProps.theme; /* eslint-enable */ return theme; }); // var escapeRegex = /[[\].#*$><+~=|^:(),"'`-]+/g; var dashesAtEnds = /(^-|-$)/g; /** * TODO: Explore using CSS.escape when it becomes more available * in evergreen browsers. */ function escape(str) { return str // Replace all possible CSS selectors .replace(escapeRegex, '-') // Remove extraneous hyphens at the start and end .replace(dashesAtEnds, ''); } // function isTag(target) { return typeof target === 'string' && (process.env.NODE_ENV !== 'production' ? target.charAt(0) === target.charAt(0).toLowerCase() : true); } // function generateDisplayName(target) { // $FlowFixMe return isTag(target) ? "styled." + target : "Styled(" + getComponentName(target) + ")"; } var _TYPE_STATICS; var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDerivedStateFromProps: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var TYPE_STATICS = (_TYPE_STATICS = {}, _TYPE_STATICS[ForwardRef] = { $$typeof: true, render: true }, _TYPE_STATICS); var defineProperty = Object.defineProperty, getOwnPropertyNames = Object.getOwnPropertyNames, _Object$getOwnPropert = Object.getOwnPropertySymbols, getOwnPropertySymbols = _Object$getOwnPropert === void 0 ? function () { return []; } : _Object$getOwnPropert, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getPrototypeOf = Object.getPrototypeOf, objectPrototype = Object.prototype; var arrayPrototype = Array.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } var keys = arrayPrototype.concat(getOwnPropertyNames(sourceComponent), // $FlowFixMe getOwnPropertySymbols(sourceComponent)); var targetStatics = TYPE_STATICS[targetComponent.$$typeof] || REACT_STATICS; var sourceStatics = TYPE_STATICS[sourceComponent.$$typeof] || REACT_STATICS; var i = keys.length; var descriptor; var key; // eslint-disable-next-line no-plusplus while (i--) { key = keys[i]; if ( // $FlowFixMe !KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && // $FlowFixMe !(targetStatics && targetStatics[key])) { descriptor = getOwnPropertyDescriptor(sourceComponent, key); if (descriptor) { try { // Avoid failures from read-only properties defineProperty(targetComponent, key, descriptor); } catch (e) { /* fail silently */ } } } } return targetComponent; } return targetComponent; } // function isDerivedReactComponent(fn) { return !!(fn && fn.prototype && fn.prototype.isReactComponent); } // // Helper to call a given function, only once var once = (function (cb) { var called = false; // $FlowFixMe this works if F is "(...any[]) => any" but that would imply the return value si forwarded return function () { if (!called) { called = true; cb.apply(void 0, arguments); } }; }); var ThemeContext = React.createContext(); var ThemeConsumer = ThemeContext.Consumer; function useMergedTheme(theme, outerTheme) { if (isFunction(theme)) { var mergedTheme = theme(outerTheme); if (process.env.NODE_ENV !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || typeof mergedTheme !== 'object')) { throw new StyledComponentsError(7); } return mergedTheme; } if (theme === null || Array.isArray(theme) || typeof theme !== 'object') { throw new StyledComponentsError(8); } return outerTheme ? _extends({}, outerTheme, theme) : theme; } /** * Provide a theme to an entire react component tree via context */ function ThemeProvider(props) { var outerTheme = useContext(ThemeContext); // NOTE: can't really memoize with props.theme as that'd cause incorrect memoization when it's a function var themeContext = useMergedTheme(props.theme, outerTheme); if (!props.children) { return null; } return React.createElement(ThemeContext.Provider, { value: themeContext }, React.Children.only(props.children)); } // var StyleSheetContext = React.createContext(); var StyleSheetConsumer = StyleSheetContext.Consumer; var masterSheet = new StyleSheet(false); function useStyleSheet() { var fromContext = useContext(StyleSheetContext); return fromContext !== undefined ? fromContext : masterSheet; } function useStyleSheetProvider(sheet, target) { return useMemo(function () { if (sheet) { return sheet; } else if (target) { return new StyleSheet(false, target); } else { throw new StyledComponentsError(4); } }, [sheet, target]); } function StyleSheetManager(props) { var sheet = useStyleSheetProvider(props.sheet, props.target); return React.createElement(StyleSheetContext.Provider, { value: sheet }, process.env.NODE_ENV !== 'production' ? React.Children.only(props.children) : props.children); } process.env.NODE_ENV !== "production" ? StyleSheetManager.propTypes = { sheet: PropTypes.instanceOf(StyleSheet), target: PropTypes.shape({ appendChild: PropTypes.func.isRequired }) } : void 0; /* global $Call */ var identifiers = {}; /* We depend on components having unique IDs */ function generateId(displayName, parentComponentId) { var name = typeof displayName !== 'string' ? 'sc' : escape(displayName); // Ensure that no displayName can lead to duplicate componentIds var nr = (identifiers[name] || 0) + 1; identifiers[name] = nr; var componentId = name + "-" + hasher(name + nr); return parentComponentId ? parentComponentId + "-" + componentId : componentId; } function useResolvedAttrs(theme, props, attrs, utils) { if (theme === void 0) { theme = EMPTY_OBJECT; } // NOTE: can't memoize this // returns [context, resolvedAttrs] // where resolvedAttrs is only the things injected by the attrs themselves var context = _extends({}, props, { theme: theme }); var resolvedAttrs = {}; attrs.forEach(function (attrDef) { var resolvedAttrDef = attrDef; var attrDefWasFn = false; var attr; var key; if (isFunction(resolvedAttrDef)) { resolvedAttrDef = resolvedAttrDef(context); attrDefWasFn = true; } /* eslint-disable guard-for-in */ for (key in resolvedAttrDef) { attr = resolvedAttrDef[key]; if (!attrDefWasFn) { if (isFunction(attr) && !isDerivedReactComponent(attr) && !isStyledComponent(attr)) { if (process.env.NODE_ENV !== 'production') { utils.warnAttrsFnObjectKeyDeprecated(key); } attr = attr(context); if (process.env.NODE_ENV !== 'production' && React.isValidElement(attr)) { utils.warnNonStyledComponentAttrsObjectKey(key); } } } resolvedAttrs[key] = attr; context[key] = attr; } /* eslint-enable */ }); return [context, resolvedAttrs]; } function useInjectedStyle(componentStyle, hasAttrs, resolvedAttrs, utils, warnTooManyClasses) { var styleSheet = useStyleSheet(); // statically styled-components don't need to build an execution context object, // and shouldn't be increasing the number of class names var isStatic = componentStyle.isStatic && !hasAttrs; var className = isStatic ? componentStyle.generateAndInjectStyles(EMPTY_OBJECT, styleSheet) : componentStyle.generateAndInjectStyles(resolvedAttrs, styleSheet); if (process.env.NODE_ENV !== 'production' && !isStatic && warnTooManyClasses) { warnTooManyClasses(className); } useDebugValue(className); return className; } // TODO: convert these all to individual hooks, if possible function developmentDeprecationWarningsFactory(displayNameArg) { var displayName = displayNameArg || 'Unknown'; return { warnInnerRef: once(function () { return (// eslint-disable-next-line no-console console.warn("The \"innerRef\" API has been removed in styled-components v4 in favor of React 16 ref forwarding, use \"ref\" instead like a typical component. \"innerRef\" was detected on component \"" + displayName + "\".") ); }), warnAttrsFnObjectKeyDeprecated: once(function (key) { return (// eslint-disable-next-line no-console console.warn("Functions as object-form attrs({}) keys are now deprecated and will be removed in a future version of styled-components. Switch to the new attrs(props => ({})) syntax instead for easier and more powerful composition. The attrs key in question is \"" + key + "\" on component \"" + displayName + "\".") ); }), warnNonStyledComponentAttrsObjectKey: once(function (key) { return (// eslint-disable-next-line no-console console.warn("It looks like you've used a non styled-component as the value for the \"" + key + "\" prop in an object-form attrs constructor of \"" + displayName + "\".\n" + 'You should use the new function-form attrs constructor which avoids this issue: attrs(props => ({ yourStuff }))\n' + "To continue using the deprecated object syntax, you'll need to wrap your component prop in a function to make it available inside the styled component (you'll still get the deprecation warning though.)\n" + ("For example, { " + key + ": () => InnerComponent } instead of { " + key + ": InnerComponent }")) ); }) }; } function useDevelopmentDeprecationWarnings(displayName) { return useState(function () { return developmentDeprecationWarningsFactory(displayName); })[0]; } var useDeprecationWarnings = process.env.NODE_ENV !== 'production' ? useDevelopmentDeprecationWarnings : // NOTE: return value must only be accessed in non-production, of course // $FlowFixMe function () {}; function useStyledComponentImpl(forwardedComponent, props, forwardedRef) { var componentAttrs = forwardedComponent.attrs, componentStyle = forwardedComponent.componentStyle, defaultProps = forwardedComponent.defaultProps, displayName = forwardedComponent.displayName, foldedComponentIds = forwardedComponent.foldedComponentIds, styledComponentId = forwardedComponent.styledComponentId, target = forwardedComponent.target; // NOTE: the non-hooks version only subscribes to this when !componentStyle.isStatic, // but that'd be against the rules-of-hooks. We could be naughty and do it anyway as it // should be an immutable value, but behave for now. var theme = determineTheme(props, useContext(ThemeContext), defaultProps); var utils = useDeprecationWarnings(displayName); var _useResolvedAttrs = useResolvedAttrs(theme, props, componentAttrs, utils), context = _useResolvedAttrs[0], attrs = _useResolvedAttrs[1]; var generatedClassName = useInjectedStyle(componentStyle, componentAttrs.length > 0, context, utils, process.env.NODE_ENV !== 'production' ? forwardedComponent.warnTooManyClasses : undefined); // NOTE: this has to be called unconditionally due to the rules of hooks // it will just do nothing if it's not an in-browser development build // NOTE2: there is no (supported) way to know if the wrapped component actually can // receive refs -- just passing refs will trigger warnings on any function component child :( // -- this also means we can't keep doing this check unless StyledComponent is itself a class. // // const refToForward = useCheckClassNameUsage( // forwardedRef, // target, // generatedClassName, // attrs.suppressClassNameWarning // ); var refToForward = forwardedRef; var elementToBeCreated = // $FlowFixMe props.as || // eslint-disable-line react/prop-types attrs.as || target; var isTargetTag = isTag(elementToBeCreated); var computedProps = attrs !== props ? _extends({}, attrs, props) : props; var shouldFilterProps = 'as' in computedProps || isTargetTag; var propsForElement = shouldFilterProps ? {} : _extends({}, computedProps); if (process.env.NODE_ENV !== 'production' && 'innerRef' in computedProps && isTargetTag) { utils.warnInnerRef(); } if (shouldFilterProps) { // eslint-disable-next-line guard-for-in for (var key in computedProps) { if (key !== 'as' && (!isTargetTag || validAttr(key))) { // Don't pass through non HTML tags through to HTML elements propsForElement[key] = computedProps[key]; } } } if ( // $FlowFixMe props.style && // eslint-disable-line react/prop-types attrs.style !== props.style // eslint-disable-line react/prop-types ) { // $FlowFixMe propsForElement.style = _extends({}, attrs.style, props.style); // eslint-disable-line react/prop-types } // $FlowFixMe propsForElement.className = Array.prototype.concat(foldedComponentIds, // $FlowFixMe props.className, // eslint-disable-line react/prop-types styledComponentId, attrs.className, generatedClassName).filter(Boolean).join(' '); // $FlowFixMe propsForElement.ref = refToForward; useDebugValue(styledComponentId); return createElement(elementToBeCreated, propsForElement); } function createStyledComponent(target, options, rules) { var isTargetStyledComp = isStyledComponent(target); var isCompositeComponent = !isTag(target); var _options$displayName = options.displayName, displayName = _options$displayName === void 0 ? generateDisplayName(target) : _options$displayName, _options$componentId = options.componentId, componentId = _options$componentId === void 0 ? generateId(options.displayName, options.parentComponentId) : _options$componentId, _options$attrs = options.attrs, attrs = _options$attrs === void 0 ? EMPTY_ARRAY : _options$attrs; var styledComponentId = options.displayName && options.componentId ? escape(options.displayName) + "-" + options.componentId : options.componentId || componentId; // fold the underlying StyledComponent attrs up (implicit extend) var finalAttrs = // $FlowFixMe isTargetStyledComp && target.attrs ? Array.prototype.concat(target.attrs, attrs).filter(Boolean) : attrs; var componentStyle = new ComponentStyle(isTargetStyledComp ? // fold the underlying StyledComponent rules up (implicit extend) // $FlowFixMe target.componentStyle.rules.concat(rules) : rules, finalAttrs, styledComponentId); /** * forwardRef creates a new interim component, which we'll take advantage of * instead of extending ParentComponent to create _another_ interim class */ // $FlowFixMe this is a forced cast to merge it StyledComponentWrapperProperties var WrappedStyledComponent = React.forwardRef(function (props, ref) { return useStyledComponentImpl(WrappedStyledComponent, props, ref); }); WrappedStyledComponent.attrs = finalAttrs; WrappedStyledComponent.componentStyle = componentStyle; WrappedStyledComponent.displayName = displayName; WrappedStyledComponent.foldedComponentIds = isTargetStyledComp ? // $FlowFixMe Array.prototype.concat(target.foldedComponentIds, target.styledComponentId) : EMPTY_ARRAY; WrappedStyledComponent.styledComponentId = styledComponentId; // fold the underlying StyledComponent target up since we folded the styles WrappedStyledComponent.target = isTargetStyledComp ? // $FlowFixMe target.target : target; // $FlowFixMe WrappedStyledComponent.withComponent = function withComponent(tag) { var previousComponentId = options.componentId, optionsToCopy = _objectWithoutPropertiesLoose(options, ["componentId"]); var newComponentId = previousComponentId && previousComponentId + "-" + (isTag(tag) ? tag : escape(getComponentName(tag))); var newOptions = _extends({}, optionsToCopy, { attrs: finalAttrs, componentId: newComponentId }); return createStyledComponent(tag, newOptions, rules); }; if (process.env.NODE_ENV !== 'production') { WrappedStyledComponent.warnTooManyClasses = createWarnTooManyClasses(displayName); } // $FlowFixMe WrappedStyledComponent.toString = function () { return "." + WrappedStyledComponent.styledComponentId; }; if (isCompositeComponent) { hoistNonReactStatics(WrappedStyledComponent, target, { // all SC-specific things should not be hoisted attrs: true, componentStyle: true, displayName: true, foldedComponentIds: true, styledComponentId: true, target: true, withComponent: true }); } return WrappedStyledComponent; } // // Thanks to ReactDOMFactories for this handy list! var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG 'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'marker', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan']; // var styled = function styled(tag) { return constructWithOptions(createStyledComponent, tag); }; // Shorthands for all valid HTML Elements domElements.forEach(function (domElement) { styled[domElement] = styled(domElement); }); // var GlobalStyle = /*#__PURE__*/ function () { function GlobalStyle(rules, componentId) { this.rules = rules; this.componentId = componentId; this.isStatic = isStaticRules(rules, EMPTY_ARRAY); StyleSheet.registerId(componentId); } var _proto = GlobalStyle.prototype; _proto.createStyles = function createStyles(executionContext, styleSheet) { var flatCSS = flatten(this.rules, executionContext, styleSheet); var css = stringifyRules(flatCSS.join(''), ''); var id = this.componentId; // NOTE: We use the id as a name as well, since these rules never change styleSheet.insertRules(id, id, css); }; _proto.removeStyles = function removeStyles(styleSheet) { styleSheet.clearRules(this.componentId); }; _proto.renderStyles = function renderStyles(executionContext, styleSheet) { // NOTE: Remove old styles, then inject the new ones this.removeStyles(styleSheet); this.createStyles(executionContext, styleSheet); }; return GlobalStyle; }(); if (IS_BROWSER) { window.scCGSHMRCache = {}; } function createGlobalStyle(strings) { for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(void 0, [strings].concat(interpolations)); var styledComponentId = "sc-global-" + hasher(JSON.stringify(rules)); var globalStyle = new GlobalStyle(rules, styledComponentId); function GlobalStyleComponent(props) { var styleSheet = useStyleSheet(); var theme = useContext(ThemeContext); if (process.env.NODE_ENV !== 'production' && React.Children.count(props.children)) { // eslint-disable-next-line no-console console.warn("The global style component " + styledComponentId + " was given child JSX. createGlobalStyle does not render children."); } if (globalStyle.isStatic) { globalStyle.renderStyles(STATIC_EXECUTION_CONTEXT, styleSheet); } else { var context = _extends({}, props); if (typeof theme !== 'undefined') { context.theme = determineTheme(props, theme); } globalStyle.renderStyles(context, styleSheet); } useEffect(function () { if (IS_BROWSER) { window.scCGSHMRCache[styledComponentId] = (window.scCGSHMRCache[styledComponentId] || 0) + 1; return function () { if (window.scCGSHMRCache[styledComponentId]) { window.scCGSHMRCache[styledComponentId] -= 1; } /** * Depending on the order "render" is called this can cause the styles to be lost * until the next render pass of the remaining instance, which may * not be immediate. */ if (window.scCGSHMRCache[styledComponentId] === 0) { globalStyle.removeStyles(styleSheet); } }; } return undefined; }, []); return null; } return GlobalStyleComponent; } // function keyframes(strings) { /* Warning if you've used keyframes on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { // eslint-disable-next-line no-console console.warn('`keyframes` cannot be used on ReactNative, only on the web. To do animation in ReactNative please use Animated.'); } for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(void 0, [strings].concat(interpolations)).join(''); var name = hasher(rules); return new Keyframes(name, stringifyRules(rules, name, '@keyframes')); } // /* eslint-disable camelcase, no-undef */ var getNonce = function getNonce() { return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null; }; // var CLOSING_TAG_R = /^\s*<\/[a-z]/i; var ServerStyleSheet = /*#__PURE__*/ function () { function ServerStyleSheet() { var _this = this; this.getStyleTags = function () { var css = _this.sheet.toString(); var nonce = getNonce(); var attrs = [nonce && "nonce=\"" + nonce + "\"", SC_ATTR, SC_VERSION_ATTR + "=\"" + SC_VERSION + "\""]; var htmlAttr = attrs.filter(Boolean).join(' '); return "<style " + htmlAttr + ">" + css + "</style>"; }; this.getStyleElement = function () { var _props; var props = (_props = {}, _props[SC_ATTR] = '', _props[SC_VERSION_ATTR] = SC_VERSION, _props.dangerouslySetInnerHTML = { __html: _this.sheet.toString() }, _props); var nonce = getNonce(); if (nonce) { props.nonce = nonce; } return React.createElement("style", props); }; this.sheet = new StyleSheet(true); this.sealed = false; } var _proto = ServerStyleSheet.prototype; _proto.collectStyles = function collectStyles(children) { if (this.sealed) { throw new StyledComponentsError(2); } this.sealed = true; return React.createElement(StyleSheetManager, { sheet: this.sheet }, children); }; _proto.interleaveWithNodeStream = function interleaveWithNodeStream(input) { { throw new StyledComponentsError(3); } // eslint-disable-next-line global-require var _require = require('stream'), Readable = _require.Readable, Transform = _require.Transform; var readableStream = input; var sheet = this.sheet, getStyleTags = this.getStyleTags; var transformer = new Transform({ transform: function appendStyleChunks(chunk, /* encoding */ _, callback) { // Get the chunk and retrieve the sheet's CSS as an HTML chunk, // then reset its rules so we get only new ones for the next chunk var renderedHtml = chunk.toString(); var html = getStyleTags(); sheet.clearTag(); // prepend style html to chunk, unless the start of the chunk is a // closing tag in which case append right after that if (CLOSING_TAG_R.test(renderedHtml)) { var endOfClosingTag = renderedHtml.indexOf('>') + 1; var before = renderedHtml.slice(0, endOfClosingTag); var after = renderedHtml.slice(endOfClosingTag); this.push(before + html + after); } else { this.push(html + renderedHtml); } callback(); } }); readableStream.on('error', function (err) { // forward the error to the transform stream transformer.emit('error', err); }); return readableStream.pipe(transformer); }; return ServerStyleSheet; }(); // export default <Config: { theme?: any }, Instance>( // Component: AbstractComponent<Config, Instance> // ): AbstractComponent<$Diff<Config, { theme?: any }> & { theme?: any }, Instance> // // but the old build system tooling doesn't support the syntax var withTheme = (function (Component) { // $FlowFixMe This should be React.forwardRef<Config, Instance> var WithTheme = React.forwardRef(function (props, ref) { var theme = useContext(ThemeContext); // $FlowFixMe defaultProps isn't declared so it can be inferrable var defaultProps = Component.defaultProps; var themeProp = determineTheme(props, theme, defaultProps); if (process.env.NODE_ENV !== 'production' && themeProp === undefined) { // eslint-disable-next-line no-console console.warn("[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class \"" + getComponentName(Component) + "\""); } return React.createElement(Component, _extends({}, props, { theme: themeProp, ref: ref })); }); hoistNonReactStatics(WithTheme, Component); WithTheme.displayName = "WithTheme(" + getComponentName(Component) + ")"; return WithTheme; }); // var __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS = { StyleSheet: StyleSheet, masterSheet: masterSheet }; // /* Warning if you've imported this file on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { // eslint-disable-next-line no-console console.warn("It looks like you've imported 'styled-components' on React Native.\n" + "Perhaps you're looking to import 'styled-components/native'?\n" + 'Read more about this at https://www.styled-components.com/docs/basics#react-native'); } /* Warning if there are several instances of styled-components */ if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test' && typeof window !== 'undefined' && typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Node.js') === -1 && navigator.userAgent.indexOf('jsdom') === -1) { window['__styled-components-init__'] = window['__styled-components-init__'] || 0; if (window['__styled-components-init__'] === 1) { // eslint-disable-next-line no-console console.warn("It looks like there are several instances of 'styled-components' initialized in this application. " + 'This may cause dynamic styles not rendering properly, errors happening during rehydration process ' + 'and makes your application bigger without a good reason.\n\n' + 'See https://s-c.sh/2BAXzed for more info.'); } window['__styled-components-init__'] += 1; } // export default styled; export { ServerStyleSheet, StyleSheetConsumer, StyleSheetContext, StyleSheetManager, ThemeConsumer, ThemeContext, ThemeProvider, __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS, createGlobalStyle, css, isStyledComponent, keyframes, withTheme }; //# sourceMappingURL=styled-components.browser.esm.js.map
sufuf3/cdnjs
ajax/libs/styled-components/5.0.0-4.canary-sheet/styled-components.browser.esm.js
JavaScript
mit
63,129
require 'test_helper' class RemoteHpsTest < Test::Unit::TestCase def setup @gateway = HpsGateway.new(fixtures(:hps)) @amount = 100 @declined_amount = 1034 @credit_card = credit_card('4000100011112224') @options = { order_id: '1', billing_address: address, description: 'Store Purchase' } end def test_successful_purchase response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_equal 'Success', response.message end def test_successful_purchase_without_cardholder response = @gateway.purchase(@amount, @credit_card) assert_success response assert_equal 'Success', response.message end def test_successful_purchase_with_details @options[:description] = 'Description' @options[:order_id] = '12345' @options[:customer_id] = '654321' response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_equal 'Success', response.message end def test_successful_purchase_with_descriptor response = @gateway.purchase(@amount, @credit_card, @options.merge(descriptor_name: 'Location Name')) assert_success response assert_equal 'Success', response.message end def test_successful_purchase_no_address options = { order_id: '1', description: 'Store Purchase' } response = @gateway.purchase(@amount, @credit_card, options) assert_instance_of Response, response assert_success response assert_equal 'Success', response.message end def test_failed_purchase response = @gateway.purchase(@declined_amount, @credit_card, @options) assert_failure response assert_equal 'The card was declined.', response.message end def test_successful_authorize_with_details @options[:description] = 'Description' @options[:order_id] = '12345' @options[:customer_id] = '654321' auth = @gateway.authorize(@amount, @credit_card, @options) assert_success auth end def test_successful_authorize_and_capture auth = @gateway.authorize(@amount, @credit_card, @options) assert_success auth assert capture = @gateway.capture(nil, auth.authorization) assert_success capture end def test_successful_authorize_no_address options = { order_id: '1', description: 'Store Authorize' } response = @gateway.authorize(@amount, @credit_card, options) assert_instance_of Response, response assert_success response assert_equal 'Success', response.message end def test_failed_authorize response = @gateway.authorize(@declined_amount, @credit_card, @options) assert_failure response end def test_partial_capture auth = @gateway.authorize(@amount, @credit_card, @options) assert_success auth assert capture = @gateway.capture(@amount-1, auth.authorization) assert_success capture end def test_failed_capture response = @gateway.capture(nil, '') assert_failure response end def test_successful_refund purchase = @gateway.purchase(@amount, @credit_card, @options) assert_success purchase assert refund = @gateway.refund(@amount, purchase.authorization) assert_success refund assert_equal 'Success', refund.params['GatewayRspMsg'] assert_equal '0', refund.params['GatewayRspCode'] end def test_partial_refund purchase = @gateway.purchase(@amount, @credit_card, @options) assert_success purchase assert refund = @gateway.refund(@amount-1, purchase.authorization) assert_success refund assert_equal 'Success', refund.params['GatewayRspMsg'] assert_equal '0', refund.params['GatewayRspCode'] end def test_failed_refund response = @gateway.refund(nil, '') assert_failure response end def test_successful_void auth = @gateway.authorize(@amount, @credit_card, @options) assert_success auth assert void = @gateway.void(auth.authorization) assert_success void assert_equal 'Success', void.params['GatewayRspMsg'] end def test_failed_void response = @gateway.void('123') assert_failure response assert_match %r{rejected}i, response.message end def test_empty_login gateway = HpsGateway.new(secret_api_key: '') response = gateway.purchase(@amount, @credit_card, @options) assert_failure response assert_equal 'Authentication error. Please double check your service configuration.', response.message end def test_nil_login gateway = HpsGateway.new(secret_api_key: nil) response = gateway.purchase(@amount, @credit_card, @options) assert_failure response assert_equal 'Authentication error. Please double check your service configuration.', response.message end def test_invalid_login gateway = HpsGateway.new(secret_api_key: 'Bad_API_KEY') response = gateway.purchase(@amount, @credit_card, @options) assert_failure response assert_equal 'Authentication error. Please double check your service configuration.', response.message end def test_successful_get_token_from_auth response = @gateway.authorize(@amount, @credit_card, @options.merge(store: true)) assert_success response assert_equal 'Visa', response.params['CardType'] assert_equal 'Success', response.params['TokenRspMsg'] assert_not_nil response.params['TokenValue'] end def test_successful_get_token_from_purchase response = @gateway.purchase(@amount, @credit_card, @options.merge(store: true)) assert_success response assert_equal 'Visa', response.params['CardType'] assert_equal 'Success', response.params['TokenRspMsg'] assert_not_nil response.params['TokenValue'] end def test_successful_purchase_with_token_from_auth response = @gateway.authorize(@amount, @credit_card, @options.merge(store: true)) assert_success response assert_equal 'Visa', response.params['CardType'] assert_equal 'Success', response.params['TokenRspMsg'] assert_not_nil response.params['TokenValue'] token = response.params['TokenValue'] purchase = @gateway.purchase(@amount, token, @options) assert_success purchase assert_equal 'Success', purchase.message end def test_successful_purchase_with_swipe_no_encryption @credit_card.track_data = '%B547888879888877776?;5473500000000014=25121019999888877776?' response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_equal 'Success', response.message end def test_failed_purchase_with_swipe_bad_track_data @credit_card.track_data = '%B547888879888877776?;?' response = @gateway.purchase(@amount, @credit_card, @options) assert_failure response assert_equal 'Transaction was rejected because the track data could not be read.', response.message end def test_successful_purchase_with_swipe_encryption_type_01 @options[:encryption_type] = '01' @credit_card.track_data = '&lt;E1052711%B5473501000000014^MC TEST CARD^251200000000000000000000000000000000?|GVEY/MKaKXuqqjKRRueIdCHPPoj1gMccgNOtHC41ymz7bIvyJJVdD3LW8BbwvwoenI+|+++++++C4cI2zjMp|11;5473501000000014=25120000000000000000?|8XqYkQGMdGeiIsgM0pzdCbEGUDP|+++++++C4cI2zjMp|00|||/wECAQECAoFGAgEH2wYcShV78RZwb3NAc2VjdXJlZXhjaGFuZ2UubmV0PX50qfj4dt0lu9oFBESQQNkpoxEVpCW3ZKmoIV3T93zphPS3XKP4+DiVlM8VIOOmAuRrpzxNi0TN/DWXWSjUC8m/PI2dACGdl/hVJ/imfqIs68wYDnp8j0ZfgvM26MlnDbTVRrSx68Nzj2QAgpBCHcaBb/FZm9T7pfMr2Mlh2YcAt6gGG1i2bJgiEJn8IiSDX5M2ybzqRT86PCbKle/XCTwFFe1X|&gt;' response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_equal 'Success', response.message end def test_successful_purchase_with_swipe_encryption_type_02 @options[:encryption_type] = '02' @options[:encrypted_track_number] = 2 @options[:ktb] = '/wECAQECAoFGAgEH3QgVTDT6jRZwb3NAc2VjdXJlZXhjaGFuZ2UubmV0Nkt08KRSPigRYcr1HVgjRFEvtUBy+VcCKlOGA3871r3SOkqDvH2+30insdLHmhTLCc4sC2IhlobvWnutAfylKk2GLspH/pfEnVKPvBv0hBnF4413+QIRlAuGX6+qZjna2aMl0kIsjEY4N6qoVq2j5/e5I+41+a2pbm61blv2PEMAmyuCcAbN3/At/1kRZNwN6LSUg9VmJO83kOglWBe1CbdFtncq' @credit_card.track_data = '7SV2BK6ESQPrq01iig27E74SxMg' response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_equal 'Success', response.message end def tests_successful_verify response = @gateway.verify(@credit_card, @options) assert_success response assert_equal 'Success', response.message end def tests_failed_verify @credit_card.number = 12345 response = @gateway.verify(@credit_card, @options) assert_failure response assert_equal 'The card number is not a valid credit card number.', response.message end def test_transcript_scrubbing transcript = capture_transcript(@gateway) do @gateway.purchase(@amount, @credit_card, @options) end transcript = @gateway.scrub(transcript) assert_scrubbed(@credit_card.number, transcript) assert_scrubbed(@credit_card.verification_value, transcript) assert_scrubbed(@gateway.options[:secret_api_key], transcript) end end
reinteractive/active_merchant
test/remote/gateways/remote_hps_test.rb
Ruby
mit
9,060
// Flags: --unhandled-rejections=none 'use strict'; const common = require('../common'); common.disableCrashOnUnhandledRejection(); // Verify that ignoring unhandled rejection works fine and that no warning is // logged. new Promise(() => { throw new Error('One'); }); Promise.reject('test'); process.on('warning', common.mustNotCall('warning')); process.on('uncaughtException', common.mustNotCall('uncaughtException')); process.on('rejectionHandled', common.mustNotCall('rejectionHandled')); process.on('unhandledRejection', common.mustCall(2)); setTimeout(common.mustCall(), 2);
enclose-io/compiler
lts/test/parallel/test-promise-unhandled-silent.js
JavaScript
mit
591
/** * Copyright (c) UNA, Inc - https://una.io * MIT License - https://opensource.org/licenses/MIT * * @defgroup UnaStudio UNA Studio * @{ */ function BxDolStudioNavigationMenus(oOptions) { this.sActionsUrl = oOptions.sActionUrl; this.sPageUrl = oOptions.sPageUrl; this.sObjNameGrid = oOptions.sObjNameGrid; this.sObjName = oOptions.sObjName == undefined ? 'oBxDolStudioNavigationMenus' : oOptions.sObjName; this.sAnimationEffect = oOptions.sAnimationEffect == undefined ? 'fade' : oOptions.sAnimationEffect; this.iAnimationSpeed = oOptions.iAnimationSpeed == undefined ? 'slow' : oOptions.iAnimationSpeed; this.sParamsDivider = oOptions.sParamsDivider == undefined ? '#-#' : oOptions.sParamsDivider; this.sTextSearchInput = oOptions.sTextSearchInput == undefined ? '' : oOptions.sTextSearchInput; } BxDolStudioNavigationMenus.prototype.onChangeFilter = function() { var sValueModule = $('#bx-grid-module-' + this.sObjNameGrid).val(); var sValueSearch = $('#bx-grid-search-' + this.sObjNameGrid).val(); if(sValueSearch == this.sTextSearchInput) sValueSearch = ''; glGrids[this.sObjNameGrid].setFilter(sValueModule + this.sParamsDivider + sValueSearch, true); }; BxDolStudioNavigationMenus.prototype.onSelectSet = function(oSelect) { var sSet = $(oSelect).val(); if(sSet == 'sys_create_new') $('#bx-form-element-set_title').show(); else $('#bx-form-element-set_title').hide(); }; /** @} */
camperjz/trident
upgrade/files/9.0.0.B2-9.0.0.B3/files/studio/js/navigation_menus.js
JavaScript
mit
1,476
<?php namespace Buzz\Test\Message; use Buzz\Message\AbstractMessage; class Message extends AbstractMessage { } class AbstractMessageTest extends \PHPUnit_Framework_TestCase { public function testGetHeaderGluesHeadersTogether() { $message = new Message(); $message->addHeader('X-My-Header: foo'); $message->addHeader('X-My-Header: bar'); $this->assertEquals('foo'."\r\n".'bar', $message->getHeader('X-My-Header')); $this->assertEquals('foo,bar', $message->getHeader('X-My-Header', ',')); $this->assertEquals(array('foo', 'bar'), $message->getHeader('X-My-Header', false)); } public function testGetHeaderReturnsNullIfHeaderDoesNotExist() { $message = new Message(); $this->assertNull($message->getHeader('X-Nonexistant')); } public function testGetHeaderIsCaseInsensitive() { $message = new Message(); $message->addHeader('X-zomg: test'); $this->assertEquals('test', $message->getHeader('X-ZOMG')); } public function testToStringFormatsTheMessage() { $message = new Message(); $message->addHeader('Foo: Bar'); $message->setContent('==CONTENT=='); $expected = "Foo: Bar\r\n\r\n==CONTENT==\r\n"; $this->assertEquals($expected, (string) $message); } public function testGetHeaderAttributesReturnsHeaderAttributes() { $message = new Message(); $message->addHeader('Content-Type: text/xml; charset=utf8'); $this->assertEquals('utf8', $message->getHeaderAttribute('Content-Type', 'charset')); } public function testGetNotFoundHeaderAttribute() { $message = new Message(); $this->assertNull($message->getHeaderAttribute('Content-Type', 'charset')); } public function testAddHeaders() { $message = new Message(); $message->addHeaders(array('Content-Type: text/xml; charset=utf8')); $this->assertEquals(1, count($message->getHeaders())); } public function testToDomDocument() { $message = new Message(); $message->setContent('<foo><bar></bar></foo>'); $this->assertInstanceOf('DOMDocument', $message->toDomDocument()); } }
guillaumeduval64/peinture-et-vitres
vendor/kriswallsmith/buzz/test/Buzz/Test/Message/AbstractMessageTest.php
PHP
mit
2,242
// HumanizeDuration.js - https://git.io/j0HgmQ ;(function () { // This has to be defined separately because of a bug: we want to alias // `gr` and `el` for backwards-compatiblity. In a breaking change, we can // remove `gr` entirely. // See https://github.com/EvanHahn/HumanizeDuration.js/issues/143 for more. var greek = { y: function (c) { return c === 1 ? 'χρόνος' : 'χρόνια' }, mo: function (c) { return c === 1 ? 'μήνας' : 'μήνες' }, w: function (c) { return c === 1 ? 'εβδομάδα' : 'εβδομάδες' }, d: function (c) { return c === 1 ? 'μέρα' : 'μέρες' }, h: function (c) { return c === 1 ? 'ώρα' : 'ώρες' }, m: function (c) { return c === 1 ? 'λεπτό' : 'λεπτά' }, s: function (c) { return c === 1 ? 'δευτερόλεπτο' : 'δευτερόλεπτα' }, ms: function (c) { return c === 1 ? 'χιλιοστό του δευτερολέπτου' : 'χιλιοστά του δευτερολέπτου' }, decimal: ',' } var languages = { ar: { y: function (c) { return c === 1 ? 'سنة' : 'سنوات' }, mo: function (c) { return c === 1 ? 'شهر' : 'أشهر' }, w: function (c) { return c === 1 ? 'أسبوع' : 'أسابيع' }, d: function (c) { return c === 1 ? 'يوم' : 'أيام' }, h: function (c) { return c === 1 ? 'ساعة' : 'ساعات' }, m: function (c) { return ['دقيقة', 'دقائق'][getArabicForm(c)] }, s: function (c) { return c === 1 ? 'ثانية' : 'ثواني' }, ms: function (c) { return c === 1 ? 'جزء من الثانية' : 'أجزاء من الثانية' }, decimal: ',' }, bg: { y: function (c) { return ['години', 'година', 'години'][getSlavicForm(c)] }, mo: function (c) { return ['месеца', 'месец', 'месеца'][getSlavicForm(c)] }, w: function (c) { return ['седмици', 'седмица', 'седмици'][getSlavicForm(c)] }, d: function (c) { return ['дни', 'ден', 'дни'][getSlavicForm(c)] }, h: function (c) { return ['часа', 'час', 'часа'][getSlavicForm(c)] }, m: function (c) { return ['минути', 'минута', 'минути'][getSlavicForm(c)] }, s: function (c) { return ['секунди', 'секунда', 'секунди'][getSlavicForm(c)] }, ms: function (c) { return ['милисекунди', 'милисекунда', 'милисекунди'][getSlavicForm(c)] }, decimal: ',' }, ca: { y: function (c) { return 'any' + (c === 1 ? '' : 's') }, mo: function (c) { return 'mes' + (c === 1 ? '' : 'os') }, w: function (c) { return 'setman' + (c === 1 ? 'a' : 'es') }, d: function (c) { return 'di' + (c === 1 ? 'a' : 'es') }, h: function (c) { return 'hor' + (c === 1 ? 'a' : 'es') }, m: function (c) { return 'minut' + (c === 1 ? '' : 's') }, s: function (c) { return 'segon' + (c === 1 ? '' : 's') }, ms: function (c) { return 'milisegon' + (c === 1 ? '' : 's') }, decimal: ',' }, cs: { y: function (c) { return ['rok', 'roku', 'roky', 'let'][getCzechOrSlovakForm(c)] }, mo: function (c) { return ['měsíc', 'měsíce', 'měsíce', 'měsíců'][getCzechOrSlovakForm(c)] }, w: function (c) { return ['týden', 'týdne', 'týdny', 'týdnů'][getCzechOrSlovakForm(c)] }, d: function (c) { return ['den', 'dne', 'dny', 'dní'][getCzechOrSlovakForm(c)] }, h: function (c) { return ['hodina', 'hodiny', 'hodiny', 'hodin'][getCzechOrSlovakForm(c)] }, m: function (c) { return ['minuta', 'minuty', 'minuty', 'minut'][getCzechOrSlovakForm(c)] }, s: function (c) { return ['sekunda', 'sekundy', 'sekundy', 'sekund'][getCzechOrSlovakForm(c)] }, ms: function (c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekund'][getCzechOrSlovakForm(c)] }, decimal: ',' }, da: { y: 'år', mo: function (c) { return 'måned' + (c === 1 ? '' : 'er') }, w: function (c) { return 'uge' + (c === 1 ? '' : 'r') }, d: function (c) { return 'dag' + (c === 1 ? '' : 'e') }, h: function (c) { return 'time' + (c === 1 ? '' : 'r') }, m: function (c) { return 'minut' + (c === 1 ? '' : 'ter') }, s: function (c) { return 'sekund' + (c === 1 ? '' : 'er') }, ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'er') }, decimal: ',' }, de: { y: function (c) { return 'Jahr' + (c === 1 ? '' : 'e') }, mo: function (c) { return 'Monat' + (c === 1 ? '' : 'e') }, w: function (c) { return 'Woche' + (c === 1 ? '' : 'n') }, d: function (c) { return 'Tag' + (c === 1 ? '' : 'e') }, h: function (c) { return 'Stunde' + (c === 1 ? '' : 'n') }, m: function (c) { return 'Minute' + (c === 1 ? '' : 'n') }, s: function (c) { return 'Sekunde' + (c === 1 ? '' : 'n') }, ms: function (c) { return 'Millisekunde' + (c === 1 ? '' : 'n') }, decimal: ',' }, el: greek, en: { y: function (c) { return 'year' + (c === 1 ? '' : 's') }, mo: function (c) { return 'month' + (c === 1 ? '' : 's') }, w: function (c) { return 'week' + (c === 1 ? '' : 's') }, d: function (c) { return 'day' + (c === 1 ? '' : 's') }, h: function (c) { return 'hour' + (c === 1 ? '' : 's') }, m: function (c) { return 'minute' + (c === 1 ? '' : 's') }, s: function (c) { return 'second' + (c === 1 ? '' : 's') }, ms: function (c) { return 'millisecond' + (c === 1 ? '' : 's') }, decimal: '.' }, es: { y: function (c) { return 'año' + (c === 1 ? '' : 's') }, mo: function (c) { return 'mes' + (c === 1 ? '' : 'es') }, w: function (c) { return 'semana' + (c === 1 ? '' : 's') }, d: function (c) { return 'día' + (c === 1 ? '' : 's') }, h: function (c) { return 'hora' + (c === 1 ? '' : 's') }, m: function (c) { return 'minuto' + (c === 1 ? '' : 's') }, s: function (c) { return 'segundo' + (c === 1 ? '' : 's') }, ms: function (c) { return 'milisegundo' + (c === 1 ? '' : 's') }, decimal: ',' }, et: { y: function (c) { return 'aasta' + (c === 1 ? '' : 't') }, mo: function (c) { return 'kuu' + (c === 1 ? '' : 'd') }, w: function (c) { return 'nädal' + (c === 1 ? '' : 'at') }, d: function (c) { return 'päev' + (c === 1 ? '' : 'a') }, h: function (c) { return 'tund' + (c === 1 ? '' : 'i') }, m: function (c) { return 'minut' + (c === 1 ? '' : 'it') }, s: function (c) { return 'sekund' + (c === 1 ? '' : 'it') }, ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'it') }, decimal: ',' }, fa: { y: 'سال', mo: 'ماه', w: 'هفته', d: 'روز', h: 'ساعت', m: 'دقیقه', s: 'ثانیه', ms: 'میلی ثانیه', decimal: '.' }, fi: { y: function (c) { return c === 1 ? 'vuosi' : 'vuotta' }, mo: function (c) { return c === 1 ? 'kuukausi' : 'kuukautta' }, w: function (c) { return 'viikko' + (c === 1 ? '' : 'a') }, d: function (c) { return 'päivä' + (c === 1 ? '' : 'ä') }, h: function (c) { return 'tunti' + (c === 1 ? '' : 'a') }, m: function (c) { return 'minuutti' + (c === 1 ? '' : 'a') }, s: function (c) { return 'sekunti' + (c === 1 ? '' : 'a') }, ms: function (c) { return 'millisekunti' + (c === 1 ? '' : 'a') }, decimal: ',' }, fr: { y: function (c) { return 'an' + (c >= 2 ? 's' : '') }, mo: 'mois', w: function (c) { return 'semaine' + (c >= 2 ? 's' : '') }, d: function (c) { return 'jour' + (c >= 2 ? 's' : '') }, h: function (c) { return 'heure' + (c >= 2 ? 's' : '') }, m: function (c) { return 'minute' + (c >= 2 ? 's' : '') }, s: function (c) { return 'seconde' + (c >= 2 ? 's' : '') }, ms: function (c) { return 'milliseconde' + (c >= 2 ? 's' : '') }, decimal: ',' }, gr: greek, hr: { y: function (c) { if (c % 10 === 2 || c % 10 === 3 || c % 10 === 4) { return 'godine' } return 'godina' }, mo: function (c) { if (c === 1) { return 'mjesec' } else if (c === 2 || c === 3 || c === 4) { return 'mjeseca' } return 'mjeseci' }, w: function (c) { if (c % 10 === 1 && c !== 11) { return 'tjedan' } return 'tjedna' }, d: function (c) { return c === 1 ? 'dan' : 'dana' }, h: function (c) { if (c === 1) { return 'sat' } else if (c === 2 || c === 3 || c === 4) { return 'sata' } return 'sati' }, m: function (c) { var mod10 = c % 10 if ((mod10 === 2 || mod10 === 3 || mod10 === 4) && (c < 10 || c > 14)) { return 'minute' } return 'minuta' }, s: function (c) { if ((c === 10 || c === 11 || c === 12 || c === 13 || c === 14 || c === 16 || c === 17 || c === 18 || c === 19) || (c % 10 === 5)) { return 'sekundi' } else if (c % 10 === 1) { return 'sekunda' } else if (c % 10 === 2 || c % 10 === 3 || c % 10 === 4) { return 'sekunde' } return 'sekundi' }, ms: function (c) { if (c === 1) { return 'milisekunda' } else if (c % 10 === 2 || c % 10 === 3 || c % 10 === 4) { return 'milisekunde' } return 'milisekundi' }, decimal: ',' }, hu: { y: 'év', mo: 'hónap', w: 'hét', d: 'nap', h: 'óra', m: 'perc', s: 'másodperc', ms: 'ezredmásodperc', decimal: ',' }, id: { y: 'tahun', mo: 'bulan', w: 'minggu', d: 'hari', h: 'jam', m: 'menit', s: 'detik', ms: 'milidetik', decimal: '.' }, is: { y: 'ár', mo: function (c) { return 'mánuð' + (c === 1 ? 'ur' : 'ir') }, w: function (c) { return 'vik' + (c === 1 ? 'a' : 'ur') }, d: function (c) { return 'dag' + (c === 1 ? 'ur' : 'ar') }, h: function (c) { return 'klukkutím' + (c === 1 ? 'i' : 'ar') }, m: function (c) { return 'mínút' + (c === 1 ? 'a' : 'ur') }, s: function (c) { return 'sekúnd' + (c === 1 ? 'a' : 'ur') }, ms: function (c) { return 'millisekúnd' + (c === 1 ? 'a' : 'ur') }, decimal: '.' }, it: { y: function (c) { return 'ann' + (c === 1 ? 'o' : 'i') }, mo: function (c) { return 'mes' + (c === 1 ? 'e' : 'i') }, w: function (c) { return 'settiman' + (c === 1 ? 'a' : 'e') }, d: function (c) { return 'giorn' + (c === 1 ? 'o' : 'i') }, h: function (c) { return 'or' + (c === 1 ? 'a' : 'e') }, m: function (c) { return 'minut' + (c === 1 ? 'o' : 'i') }, s: function (c) { return 'second' + (c === 1 ? 'o' : 'i') }, ms: function (c) { return 'millisecond' + (c === 1 ? 'o' : 'i') }, decimal: ',' }, ja: { y: '年', mo: '月', w: '週', d: '日', h: '時間', m: '分', s: '秒', ms: 'ミリ秒', decimal: '.' }, ko: { y: '년', mo: '개월', w: '주일', d: '일', h: '시간', m: '분', s: '초', ms: '밀리 초', decimal: '.' }, lo: { y: 'ປີ', mo: 'ເດືອນ', w: 'ອາທິດ', d: 'ມື້', h: 'ຊົ່ວໂມງ', m: 'ນາທີ', s: 'ວິນາທີ', ms: 'ມິນລິວິນາທີ', decimal: ',' }, lt: { y: function (c) { return ((c % 10 === 0) || (c % 100 >= 10 && c % 100 <= 20)) ? 'metų' : 'metai' }, mo: function (c) { return ['mėnuo', 'mėnesiai', 'mėnesių'][getLithuanianForm(c)] }, w: function (c) { return ['savaitė', 'savaitės', 'savaičių'][getLithuanianForm(c)] }, d: function (c) { return ['diena', 'dienos', 'dienų'][getLithuanianForm(c)] }, h: function (c) { return ['valanda', 'valandos', 'valandų'][getLithuanianForm(c)] }, m: function (c) { return ['minutė', 'minutės', 'minučių'][getLithuanianForm(c)] }, s: function (c) { return ['sekundė', 'sekundės', 'sekundžių'][getLithuanianForm(c)] }, ms: function (c) { return ['milisekundė', 'milisekundės', 'milisekundžių'][getLithuanianForm(c)] }, decimal: ',' }, lv: { y: function (c) { return ['gads', 'gadi'][getLatvianForm(c)] }, mo: function (c) { return ['mēnesis', 'mēneši'][getLatvianForm(c)] }, w: function (c) { return ['nedēļa', 'nedēļas'][getLatvianForm(c)] }, d: function (c) { return ['diena', 'dienas'][getLatvianForm(c)] }, h: function (c) { return ['stunda', 'stundas'][getLatvianForm(c)] }, m: function (c) { return ['minūte', 'minūtes'][getLatvianForm(c)] }, s: function (c) { return ['sekunde', 'sekundes'][getLatvianForm(c)] }, ms: function (c) { return ['milisekunde', 'milisekundes'][getLatvianForm(c)] }, decimal: ',' }, ms: { y: 'tahun', mo: 'bulan', w: 'minggu', d: 'hari', h: 'jam', m: 'minit', s: 'saat', ms: 'milisaat', decimal: '.' }, nl: { y: 'jaar', mo: function (c) { return c === 1 ? 'maand' : 'maanden' }, w: function (c) { return c === 1 ? 'week' : 'weken' }, d: function (c) { return c === 1 ? 'dag' : 'dagen' }, h: 'uur', m: function (c) { return c === 1 ? 'minuut' : 'minuten' }, s: function (c) { return c === 1 ? 'seconde' : 'seconden' }, ms: function (c) { return c === 1 ? 'milliseconde' : 'milliseconden' }, decimal: ',' }, no: { y: 'år', mo: function (c) { return 'måned' + (c === 1 ? '' : 'er') }, w: function (c) { return 'uke' + (c === 1 ? '' : 'r') }, d: function (c) { return 'dag' + (c === 1 ? '' : 'er') }, h: function (c) { return 'time' + (c === 1 ? '' : 'r') }, m: function (c) { return 'minutt' + (c === 1 ? '' : 'er') }, s: function (c) { return 'sekund' + (c === 1 ? '' : 'er') }, ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'er') }, decimal: ',' }, pl: { y: function (c) { return ['rok', 'roku', 'lata', 'lat'][getPolishForm(c)] }, mo: function (c) { return ['miesiąc', 'miesiąca', 'miesiące', 'miesięcy'][getPolishForm(c)] }, w: function (c) { return ['tydzień', 'tygodnia', 'tygodnie', 'tygodni'][getPolishForm(c)] }, d: function (c) { return ['dzień', 'dnia', 'dni', 'dni'][getPolishForm(c)] }, h: function (c) { return ['godzina', 'godziny', 'godziny', 'godzin'][getPolishForm(c)] }, m: function (c) { return ['minuta', 'minuty', 'minuty', 'minut'][getPolishForm(c)] }, s: function (c) { return ['sekunda', 'sekundy', 'sekundy', 'sekund'][getPolishForm(c)] }, ms: function (c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekund'][getPolishForm(c)] }, decimal: ',' }, pt: { y: function (c) { return 'ano' + (c === 1 ? '' : 's') }, mo: function (c) { return c === 1 ? 'mês' : 'meses' }, w: function (c) { return 'semana' + (c === 1 ? '' : 's') }, d: function (c) { return 'dia' + (c === 1 ? '' : 's') }, h: function (c) { return 'hora' + (c === 1 ? '' : 's') }, m: function (c) { return 'minuto' + (c === 1 ? '' : 's') }, s: function (c) { return 'segundo' + (c === 1 ? '' : 's') }, ms: function (c) { return 'milissegundo' + (c === 1 ? '' : 's') }, decimal: ',' }, ro: { y: function (c) { return c === 1 ? 'an' : 'ani' }, mo: function (c) { return c === 1 ? 'lună' : 'luni' }, w: function (c) { return c === 1 ? 'săptămână' : 'săptămâni' }, d: function (c) { return c === 1 ? 'zi' : 'zile' }, h: function (c) { return c === 1 ? 'oră' : 'ore' }, m: function (c) { return c === 1 ? 'minut' : 'minute' }, s: function (c) { return c === 1 ? 'secundă' : 'secunde' }, ms: function (c) { return c === 1 ? 'milisecundă' : 'milisecunde' }, decimal: ',' }, ru: { y: function (c) { return ['лет', 'год', 'года'][getSlavicForm(c)] }, mo: function (c) { return ['месяцев', 'месяц', 'месяца'][getSlavicForm(c)] }, w: function (c) { return ['недель', 'неделя', 'недели'][getSlavicForm(c)] }, d: function (c) { return ['дней', 'день', 'дня'][getSlavicForm(c)] }, h: function (c) { return ['часов', 'час', 'часа'][getSlavicForm(c)] }, m: function (c) { return ['минут', 'минута', 'минуты'][getSlavicForm(c)] }, s: function (c) { return ['секунд', 'секунда', 'секунды'][getSlavicForm(c)] }, ms: function (c) { return ['миллисекунд', 'миллисекунда', 'миллисекунды'][getSlavicForm(c)] }, decimal: ',' }, uk: { y: function (c) { return ['років', 'рік', 'роки'][getSlavicForm(c)] }, mo: function (c) { return ['місяців', 'місяць', 'місяці'][getSlavicForm(c)] }, w: function (c) { return ['тижнів', 'тиждень', 'тижні'][getSlavicForm(c)] }, d: function (c) { return ['днів', 'день', 'дні'][getSlavicForm(c)] }, h: function (c) { return ['годин', 'година', 'години'][getSlavicForm(c)] }, m: function (c) { return ['хвилин', 'хвилина', 'хвилини'][getSlavicForm(c)] }, s: function (c) { return ['секунд', 'секунда', 'секунди'][getSlavicForm(c)] }, ms: function (c) { return ['мілісекунд', 'мілісекунда', 'мілісекунди'][getSlavicForm(c)] }, decimal: ',' }, ur: { y: 'سال', mo: function (c) { return c === 1 ? 'مہینہ' : 'مہینے' }, w: function (c) { return c === 1 ? 'ہفتہ' : 'ہفتے' }, d: 'دن', h: function (c) { return c === 1 ? 'گھنٹہ' : 'گھنٹے' }, m: 'منٹ', s: 'سیکنڈ', ms: 'ملی سیکنڈ', decimal: '.' }, sk: { y: function (c) { return ['rok', 'roky', 'roky', 'rokov'][getCzechOrSlovakForm(c)] }, mo: function (c) { return ['mesiac', 'mesiace', 'mesiace', 'mesiacov'][getCzechOrSlovakForm(c)] }, w: function (c) { return ['týždeň', 'týždne', 'týždne', 'týždňov'][getCzechOrSlovakForm(c)] }, d: function (c) { return ['deň', 'dni', 'dni', 'dní'][getCzechOrSlovakForm(c)] }, h: function (c) { return ['hodina', 'hodiny', 'hodiny', 'hodín'][getCzechOrSlovakForm(c)] }, m: function (c) { return ['minúta', 'minúty', 'minúty', 'minút'][getCzechOrSlovakForm(c)] }, s: function (c) { return ['sekunda', 'sekundy', 'sekundy', 'sekúnd'][getCzechOrSlovakForm(c)] }, ms: function (c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekúnd'][getCzechOrSlovakForm(c)] }, decimal: ',' }, sv: { y: 'år', mo: function (c) { return 'månad' + (c === 1 ? '' : 'er') }, w: function (c) { return 'veck' + (c === 1 ? 'a' : 'or') }, d: function (c) { return 'dag' + (c === 1 ? '' : 'ar') }, h: function (c) { return 'timm' + (c === 1 ? 'e' : 'ar') }, m: function (c) { return 'minut' + (c === 1 ? '' : 'er') }, s: function (c) { return 'sekund' + (c === 1 ? '' : 'er') }, ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'er') }, decimal: ',' }, tr: { y: 'yıl', mo: 'ay', w: 'hafta', d: 'gün', h: 'saat', m: 'dakika', s: 'saniye', ms: 'milisaniye', decimal: ',' }, th: { y: 'ปี', mo: 'เดือน', w: 'อาทิตย์', d: 'วัน', h: 'ชั่วโมง', m: 'นาที', s: 'วินาที', ms: 'มิลลิวินาที', decimal: '.' }, vi: { y: 'năm', mo: 'tháng', w: 'tuần', d: 'ngày', h: 'giờ', m: 'phút', s: 'giây', ms: 'mili giây', decimal: ',' }, zh_CN: { y: '年', mo: '个月', w: '周', d: '天', h: '小时', m: '分钟', s: '秒', ms: '毫秒', decimal: '.' }, zh_TW: { y: '年', mo: '個月', w: '周', d: '天', h: '小時', m: '分鐘', s: '秒', ms: '毫秒', decimal: '.' } } // You can create a humanizer, which returns a function with default // parameters. function humanizer (passedOptions) { var result = function humanizer (ms, humanizerOptions) { var options = extend({}, result, humanizerOptions || {}) return doHumanization(ms, options) } return extend(result, { language: 'en', delimiter: ', ', spacer: ' ', conjunction: '', serialComma: true, units: ['y', 'mo', 'w', 'd', 'h', 'm', 's'], languages: {}, round: false, unitMeasures: { y: 31557600000, mo: 2629800000, w: 604800000, d: 86400000, h: 3600000, m: 60000, s: 1000, ms: 1 } }, passedOptions) } // The main function is just a wrapper around a default humanizer. var humanizeDuration = humanizer({}) // Build dictionary from options function getDictionary (options) { var languagesFromOptions = [options.language] if (has(options, 'fallbacks')) { if (isArray(options.fallbacks) && options.fallbacks.length) { languagesFromOptions = languagesFromOptions.concat(options.fallbacks) } else { throw new Error('fallbacks must be an array with at least one element') } } for (var i = 0; i < languagesFromOptions.length; i++) { var languageToTry = languagesFromOptions[i] if (has(options.languages, languageToTry)) { return options.languages[languageToTry] } else if (has(languages, languageToTry)) { return languages[languageToTry] } } throw new Error('No language found.') } // doHumanization does the bulk of the work. function doHumanization (ms, options) { var i, len, piece // Make sure we have a positive number. // Has the nice sideffect of turning Number objects into primitives. ms = Math.abs(ms) var dictionary = getDictionary(options) var pieces = [] // Start at the top and keep removing units, bit by bit. var unitName, unitMS, unitCount for (i = 0, len = options.units.length; i < len; i++) { unitName = options.units[i] unitMS = options.unitMeasures[unitName] // What's the number of full units we can fit? if (i + 1 === len) { if (has(options, 'maxDecimalPoints')) { // We need to use this expValue to avoid rounding functionality of toFixed call var expValue = Math.pow(10, options.maxDecimalPoints) var unitCountFloat = (ms / unitMS) unitCount = parseFloat((Math.floor(expValue * unitCountFloat) / expValue).toFixed(options.maxDecimalPoints)) } else { unitCount = ms / unitMS } } else { unitCount = Math.floor(ms / unitMS) } // Add the string. pieces.push({ unitCount: unitCount, unitName: unitName }) // Remove what we just figured out. ms -= unitCount * unitMS } var firstOccupiedUnitIndex = 0 for (i = 0; i < pieces.length; i++) { if (pieces[i].unitCount) { firstOccupiedUnitIndex = i break } } if (options.round) { var ratioToLargerUnit, previousPiece for (i = pieces.length - 1; i >= 0; i--) { piece = pieces[i] piece.unitCount = Math.round(piece.unitCount) if (i === 0) { break } previousPiece = pieces[i - 1] ratioToLargerUnit = options.unitMeasures[previousPiece.unitName] / options.unitMeasures[piece.unitName] if ((piece.unitCount % ratioToLargerUnit) === 0 || (options.largest && ((options.largest - 1) < (i - firstOccupiedUnitIndex)))) { previousPiece.unitCount += piece.unitCount / ratioToLargerUnit piece.unitCount = 0 } } } var result = [] for (i = 0, pieces.length; i < len; i++) { piece = pieces[i] if (piece.unitCount) { result.push(render(piece.unitCount, piece.unitName, dictionary, options)) } if (result.length === options.largest) { break } } if (result.length) { if (!options.conjunction || result.length === 1) { return result.join(options.delimiter) } else if (result.length === 2) { return result.join(options.conjunction) } else if (result.length > 2) { return result.slice(0, -1).join(options.delimiter) + (options.serialComma ? ',' : '') + options.conjunction + result.slice(-1) } } else { return render(0, options.units[options.units.length - 1], dictionary, options) } } function render (count, type, dictionary, options) { var decimal if (has(options, 'decimal')) { decimal = options.decimal } else if (has(dictionary, 'decimal')) { decimal = dictionary.decimal } else { decimal = '.' } var countStr = count.toString().replace('.', decimal) var dictionaryValue = dictionary[type] var word if (typeof dictionaryValue === 'function') { word = dictionaryValue(count) } else { word = dictionaryValue } return countStr + options.spacer + word } function extend (destination) { var source for (var i = 1; i < arguments.length; i++) { source = arguments[i] for (var prop in source) { if (has(source, prop)) { destination[prop] = source[prop] } } } return destination } // Internal helper function for Polish language. function getPolishForm (c) { if (c === 1) { return 0 } else if (Math.floor(c) !== c) { return 1 } else if (c % 10 >= 2 && c % 10 <= 4 && !(c % 100 > 10 && c % 100 < 20)) { return 2 } else { return 3 } } // Internal helper function for Russian and Ukranian languages. function getSlavicForm (c) { if (Math.floor(c) !== c) { return 2 } else if ((c % 100 >= 5 && c % 100 <= 20) || (c % 10 >= 5 && c % 10 <= 9) || c % 10 === 0) { return 0 } else if (c % 10 === 1) { return 1 } else if (c > 1) { return 2 } else { return 0 } } // Internal helper function for Slovak language. function getCzechOrSlovakForm (c) { if (c === 1) { return 0 } else if (Math.floor(c) !== c) { return 1 } else if (c % 10 >= 2 && c % 10 <= 4 && c % 100 < 10) { return 2 } else { return 3 } } // Internal helper function for Lithuanian language. function getLithuanianForm (c) { if (c === 1 || (c % 10 === 1 && c % 100 > 20)) { return 0 } else if (Math.floor(c) !== c || (c % 10 >= 2 && c % 100 > 20) || (c % 10 >= 2 && c % 100 < 10)) { return 1 } else { return 2 } } // Internal helper function for Latvian language. function getLatvianForm (c) { if (c === 1 || (c % 10 === 1 && c % 100 !== 11)) { return 0 } else { return 1 } } // Internal helper function for Arabic language. function getArabicForm (c) { if (c <= 2) { return 0 } if (c > 2 && c < 11) { return 1 } return 0 } // We need to make sure we support browsers that don't have // `Array.isArray`, so we define a fallback here. var isArray = Array.isArray || function (arg) { return Object.prototype.toString.call(arg) === '[object Array]' } function has (obj, key) { return Object.prototype.hasOwnProperty.call(obj, key) } humanizeDuration.getSupportedLanguages = function getSupportedLanguages () { var result = [] for (var language in languages) { if (has(languages, language) && language !== 'gr') { result.push(language) } } return result } humanizeDuration.humanizer = humanizer if (typeof define === 'function' && define.amd) { define(function () { return humanizeDuration }) } else if (typeof module !== 'undefined' && module.exports) { module.exports = humanizeDuration } else { this.humanizeDuration = humanizeDuration } })(); // eslint-disable-line semi
extend1994/cdnjs
ajax/libs/humanize-duration/3.20.1/humanize-duration.js
JavaScript
mit
28,768
<?php namespace TYPO3\Flow\Tests\Unit\Session; /* * This file is part of the TYPO3.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ /** * Testcase for the Transient Session implementation * */ class TransientSessionTest extends \TYPO3\Flow\Tests\UnitTestCase { /** * @test */ public function theTransientSessionImplementsTheSessionInterface() { $session = new \TYPO3\Flow\Session\TransientSession(); $this->assertInstanceOf(\TYPO3\Flow\Session\SessionInterface::class, $session); } /** * @test */ public function aSessionIdIsGeneratedOnStartingTheSession() { $session = new \TYPO3\Flow\Session\TransientSession(); $session->start(); $this->assertTrue(strlen($session->getId()) == 13); } /** * @test * @expectedException \TYPO3\Flow\Session\Exception\SessionNotStartedException */ public function tryingToGetTheSessionIdWithoutStartingTheSessionThrowsAnException() { $session = new \TYPO3\Flow\Session\TransientSession(); $session->getId(); } /** * @test */ public function stringsCanBeStoredByCallingPutData() { $session = new \TYPO3\Flow\Session\TransientSession(); $session->start(); $session->putData('theKey', 'some data'); $this->assertEquals('some data', $session->getData('theKey')); } /** * @test */ public function allSessionDataCanBeFlushedByCallingDestroy() { $session = new \TYPO3\Flow\Session\TransientSession(); $session->start(); $session->putData('theKey', 'some data'); $session->destroy(); $session->start(); $this->assertNull($session->getData('theKey')); } /** * @test */ public function hasKeyReturnsTrueOrFalseAccordingToAvailableKeys() { $session = new \TYPO3\Flow\Session\TransientSession(); $session->start(); $session->putData('theKey', 'some data'); $this->assertTrue($session->hasKey('theKey')); $this->assertFalse($session->hasKey('noKey')); } }
chewbakartik/flow-development-collection
TYPO3.Flow/Tests/Unit/Session/TransientSessionTest.php
PHP
mit
2,321
<?php class WP_REST_Posts_Terms_Controller extends WP_REST_Controller { protected $post_type; public function __construct( $post_type, $taxonomy ) { $this->post_type = $post_type; $this->taxonomy = $taxonomy; $this->posts_controller = new WP_REST_Posts_Controller( $post_type ); $this->terms_controller = new WP_REST_Terms_Controller( $taxonomy ); } /** * Register the routes for the objects of the controller. */ public function register_routes() { $base = $this->posts_controller->get_post_type_base( $this->post_type ); $tax_base = $this->terms_controller->get_taxonomy_base( $this->taxonomy ); register_rest_route( 'wp/v2', sprintf( '/%s/(?P<post_id>[\d]+)/%s', $base, $tax_base ), array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => $this->get_collection_params(), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( 'wp/v2', sprintf( '/%s/(?P<post_id>[\d]+)/%s/(?P<term_id>[\d]+)', $base, $tax_base ), array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'create_item' ), 'permission_callback' => array( $this, 'create_item_permissions_check' ), ), array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => array( $this, 'delete_item' ), 'permission_callback' => array( $this, 'create_item_permissions_check' ), 'args' => array( 'force' => array( 'default' => false, ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Get all the terms that are attached to a post * * @param WP_REST_Request $request Full details about the request * @return WP_Error|WP_REST_Response */ public function get_items( $request ) { $post = get_post( absint( $request['post_id'] ) ); $is_request_valid = $this->validate_request( $request ); if ( is_wp_error( $is_request_valid ) ) { return $is_request_valid; } $args = array( 'order' => $request['order'], 'orderby' => $request['orderby'], ); $terms = wp_get_object_terms( $post->ID, $this->taxonomy, $args ); $response = array(); foreach ( $terms as $term ) { $data = $this->terms_controller->prepare_item_for_response( $term, $request ); $response[] = $this->prepare_response_for_collection( $data ); } $response = rest_ensure_response( $response ); return $response; } /** * Get a term that is attached to a post * * @param WP_REST_Request $request Full details about the request * @return WP_Error|WP_REST_Response */ public function get_item( $request ) { $post = get_post( absint( $request['post_id'] ) ); $term_id = absint( $request['term_id'] ); $is_request_valid = $this->validate_request( $request ); if ( is_wp_error( $is_request_valid ) ) { return $is_request_valid; } $terms = wp_get_object_terms( $post->ID, $this->taxonomy ); if ( ! in_array( $term_id, wp_list_pluck( $terms, 'term_id' ) ) ) { return new WP_Error( 'rest_post_not_in_term', __( 'Invalid taxonomy for post id.' ), array( 'status' => 404 ) ); } $term = $this->terms_controller->prepare_item_for_response( get_term( $term_id, $this->taxonomy ), $request ); $response = rest_ensure_response( $term ); return $response; } /** * Add a term to a post * * @param WP_REST_Request $request Full details about the request * @return WP_Error|WP_REST_Response */ public function create_item( $request ) { $post = get_post( $request['post_id'] ); $term_id = absint( $request['term_id'] ); $is_request_valid = $this->validate_request( $request ); if ( is_wp_error( $is_request_valid ) ) { return $is_request_valid; } $term = get_term( $term_id, $this->taxonomy ); $tt_ids = wp_set_object_terms( $post->ID, $term->term_id, $this->taxonomy, true ); if ( is_wp_error( $tt_ids ) ) { return $tt_ids; } $term = $this->terms_controller->prepare_item_for_response( get_term( $term_id, $this->taxonomy ), $request ); $response = rest_ensure_response( $term ); $response->set_status( 201 ); /** * Fires after a term is added to a post via the REST API. * * @param array $term The added term data. * @param WP_Post $post The post the term was added to. * @param WP_REST_Request $request The request sent to the API. */ do_action( 'rest_insert_term', $term, $post, $request ); return $term; } /** * Remove a term from a post. * * @param WP_REST_Request $request Full details about the request * @return WP_Error|null */ public function delete_item( $request ) { $post = get_post( absint( $request['post_id'] ) ); $term_id = absint( $request['term_id'] ); $force = isset( $request['force'] ) ? (bool) $request['force'] : false; // We don't support trashing for this type, error out if ( ! $force ) { return new WP_Error( 'rest_trash_not_supported', __( 'Terms do not support trashing.' ), array( 'status' => 501 ) ); } $is_request_valid = $this->validate_request( $request ); if ( is_wp_error( $is_request_valid ) ) { return $is_request_valid; } $previous_item = $this->get_item( $request ); $remove = wp_remove_object_terms( $post->ID, $term_id, $this->taxonomy ); if ( is_wp_error( $remove ) ) { return $remove; } /** * Fires after a term is removed from a post via the REST API. * * @param array $previous_item The removed term data. * @param WP_Post $post The post the term was removed from. * @param WP_REST_Request $request The request sent to the API. */ do_action( 'rest_remove_term', $previous_item, $post, $request ); return $previous_item; } /** * Get the Term schema, conforming to JSON Schema. * * @return array */ public function get_item_schema() { return $this->terms_controller->get_item_schema(); } /** * Validate the API request for relationship requests. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|true */ protected function validate_request( $request ) { $post = get_post( (int) $request['post_id'] ); if ( empty( $post ) || empty( $post->ID ) || $post->post_type !== $this->post_type ) { return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post id.' ), array( 'status' => 404 ) ); } if ( ! $this->posts_controller->check_read_permission( $post ) ) { return new WP_Error( 'rest_forbidden', __( 'Sorry, you cannot view this post.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( ! empty( $request['term_id'] ) ) { $term_id = absint( $request['term_id'] ); $term = get_term( $term_id, $this->taxonomy ); if ( ! $term || $term->taxonomy !== $this->taxonomy ) { return new WP_Error( 'rest_term_invalid', __( "Term doesn't exist." ), array( 'status' => 404 ) ); } } return true; } /** * Check if a given request has access to read a post's term. * * @param WP_REST_Request $request Full details about the request. * @return bool|WP_Error */ public function get_items_permissions_check( $request ) { $post_request = new WP_REST_Request(); $post_request->set_param( 'id', $request['post_id'] ); $post_check = $this->posts_controller->get_item_permissions_check( $post_request ); if ( ! $post_check || is_wp_error( $post_check ) ) { return $post_check; } $term_request = new WP_REST_Request(); $term_request->set_param( 'id', $request['term_id'] ); $terms_check = $this->terms_controller->get_item_permissions_check( $term_request ); if ( ! $terms_check || is_wp_error( $terms_check ) ) { return $terms_check; } return true; } /** * Check if a given request has access to create a post/term relationship. * * @param WP_REST_Request $request Full details about the request. * @return bool|WP_Error */ public function create_item_permissions_check( $request ) { $post_request = new WP_REST_Request(); $post_request->set_param( 'id', $request['post_id'] ); $post_check = $this->posts_controller->update_item_permissions_check( $post_request ); if ( ! $post_check || is_wp_error( $post_check ) ) { return $post_check; } return true; } /** * Get the query params for collections * * @return array */ public function get_collection_params() { $query_params = array(); $query_params['context'] = $this->get_context_param( array( 'default' => 'view' ) ); $query_params['order'] = array( 'description' => 'Order sort attribute ascending or descending.', 'type' => 'string', 'default' => 'asc', 'enum' => array( 'asc', 'desc' ), ); $query_params['orderby'] = array( 'description' => 'Sort collection by object attribute.', 'type' => 'string', 'default' => 'name', 'enum' => array( 'count', 'name', 'slug', 'term_order', ), ); return $query_params; } }
trungnghia112/AngularJS-and-WordPress
wp-content/plugins/rest-api/lib/endpoints/class-wp-rest-posts-terms-controller.php
PHP
mit
9,539
// Copyright (c) 2013-2015 Titanium I.T. LLC. All rights reserved. See LICENSE.TXT for details. (function() { "use strict"; var arrayToSentence = require("array-to-sentence"); var objectAssign = require("object-assign"); // ponyfill for Object.assign(); check if Node supports it yet exports.check = function(arg, type, options) { var argType = getType(arg); if (!Array.isArray(type)) type = [ type ]; options = options || {}; options.name = options.name || "argument"; for (var i = 0; i < type.length; i++) { if (oneTypeMatches(arg, argType, type[i])) { if (isStructComparison(argType, type[i])) return checkStruct(arg, type[i], options); else return null; } } return describeError(argType, type, options.name); function oneTypeMatches(arg, argType, type) { if (argType === Object) return checkObject(arg, type); else if (Number.isNaN(argType)) return Number.isNaN(type); else return argType === type; function checkObject(arg, type) { if (typeof type === "function") return arg instanceof type; else if (typeof type === "object") return typeof arg === "object"; else throw new Error("unrecognized type: " + type); } } function isStructComparison(argType, type) { return argType === Object && typeof type === "object"; } function checkStruct(arg, type, options) { if (typeof type !== "object") throw new Error("unrecognized type: " + type); var keys = Object.getOwnPropertyNames(type); for (var i = 0; i < keys.length; i++) { var newOptions = objectAssign({}, options); newOptions.name = options.name + "." + keys[i]; var checkResult = exports.check(arg[keys[i]], type[keys[i]], newOptions); if (checkResult !== null) return checkResult; } return null; } function describeError(argType, type, name) { var describe = exports.describe; var articles = { articles: true }; return name + " must be " + describe(type, articles) + ", but it was " + describe(argType, articles); } }; exports.describe = function(type, options) { if (!Array.isArray(type)) type = [ type ]; if (options === undefined) options = {}; var descriptions = type.map(function(oneType) { return describeOneType(oneType); }); if (descriptions.length <= 2) return descriptions.join(" or "); else return arrayToSentence(descriptions, { lastSeparator: ", or " }); // dat Oxford comma function describeOneType(type) { switch(type) { case Boolean: return options.articles ? "a boolean" : "boolean"; case String: return options.articles ? "a string" : "string"; case Number: return options.articles ? "a number" : "number"; case Function: return options.articles ? "a function" : "function"; case Array: return options.articles ? "an array" : "array"; case undefined: return "undefined"; case null: return "null"; default: if (Number.isNaN(type)) return "NaN"; else if (typeof type === "function") return describeObject(type, options); else if (typeof type === "object") return describeStruct(type, options); else throw new Error("unrecognized type: " + type); } } function describeObject(type, options) { var articles = options.articles; if (type === Object) return articles ? "an object" : "object"; else if (type === RegExp) return articles ? "a regular expression" : "regular expression"; var name = type.name; if (name) { if (articles) name = "a " + name; } else { name = articles ? "an <anon>" : "<anon>"; } return name + " instance"; } function describeStruct(type, options) { var properties = Object.getOwnPropertyNames(type).map(function(key) { return key + ": <" + exports.describe(type[key]) + ">"; }); if (properties.length === 0) return options.articles ? "an object" : "object"; var description = " " + properties.join(", ") + " "; return (options.articles ? "an " : "") + "object containing {" + description + "}"; } }; function getType(variable) { if (variable === null) return null; if (Array.isArray(variable)) return Array; if (Number.isNaN(variable)) return NaN; switch (typeof variable) { case "boolean": return Boolean; case "string": return String; case "number": return Number; case "function": return Function; case "object": return Object; case "undefined": return undefined; default: throw new Error("Unreachable code executed. Unknown typeof value: " + typeof variable); } } }());
evrimfeyyaz/ios-calculator
node_modules/simplebuild/lib/type.js
JavaScript
mit
4,496
# encoding: utf-8 # frozen_string_literal: true require 'spec_helper' require 'mail/fields/common_field' describe Mail::CommonField do describe "multi-charset support" do before(:each) do @original = $KCODE if RUBY_VERSION < '1.9' end after(:each) do $KCODE = @original if RUBY_VERSION < '1.9' end it "should return '' on to_s if there is no value" do expect(Mail::SubjectField.new(nil).to_s).to eq '' end it "should leave ascii alone" do field = Mail::SubjectField.new("This is a test") expect(field.encoded).to eq "Subject: This is a test\r\n" expect(field.decoded).to eq "This is a test" end it "should encode a utf-8 string as utf-8 quoted printable" do value = "かきくけこ" if RUBY_VERSION < '1.9' $KCODE = 'u' result = "Subject: =?UTF-8?Q?=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n" else value = value.dup.force_encoding('UTF-8') result = "Subject: =?UTF-8?Q?=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n" end field = Mail::SubjectField.new(value) expect(field.encoded).to eq result expect(field.decoded).to eq value expect(field.value).to eq value end it "should wrap an encoded at 60 characters" do value = "かきくけこ かきくけこ かきくけこ かきくけこ かきくけこ かきくけこ かきくけこ かきくけこ かきくけこ" if RUBY_VERSION < '1.9' $KCODE = 'u' result = "Subject: =?UTF-8?Q?=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n" else value = value.dup.force_encoding('UTF-8') result = "Subject: =?UTF-8?Q?=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n\s=?UTF-8?Q?_=E3=81=8B=E3=81=8D=E3=81=8F=E3=81=91=E3=81=93?=\r\n" end field = Mail::SubjectField.new(value) expect(field.encoded).to eq result expect(field.decoded).to eq value expect(field.value).to eq value end it "should handle charsets in assigned addresses" do value = '"かきくけこ" <mikel@test.lindsaar.net>' if RUBY_VERSION < '1.9' $KCODE = 'u' result = "From: =?UTF-8?B?44GL44GN44GP44GR44GT?= <mikel@test.lindsaar.net>\r\n" else value = value.dup.force_encoding('UTF-8') result = "From: =?UTF-8?B?44GL44GN44GP44GR44GT?= <mikel@test.lindsaar.net>\r\n" end field = Mail::FromField.new(value) expect(field.encoded).to eq result expect(field.decoded).to eq value end end describe "with content that looks like the field name" do it "does not strip from start" do field = Mail::SubjectField.new("Subject: for your approval") expect(field.decoded).to eq("Subject: for your approval") end it "does not strip from middle" do field = Mail::SubjectField.new("for your approval subject: xyz") expect(field.decoded).to eq("for your approval subject: xyz") end end end
planio-gmbh/mail
spec/mail/fields/common_field_spec.rb
Ruby
mit
3,942
""" Logger for the spectroscopic toolkit packge Goal: Use decorators to log each command in full Author: Adam Ginsburg Created: 03/17/2011 """ import os import time class Logger(object): """ Logger object. Should be initiated on import. """ def __init__(self, filename): """ Open a log file for writing """ newfilename = filename ii=0 while os.path.exists(filename): newfilename = filename+".%3i" % ii ii += 1 if newfilename != filename: os.rename(filename,newfilename) self.outfile = open(filename,'w') print >>self.outfile,"Began logging at %s" % (time.strftime("%M/%d/%Y %H:%M:%S",time.localtime())) def __call__(self, function): """ """ def wrapper(*args, **kwargs): modname = function.__module__ fname = function.__name__ print >>self.outfile,"%s.%s" % (modname,fname) +\ "("+"".join([a.__name__ for a in args]) + \ "".join(["%s=%s" % (k,v) for (k,v) in kwargs])+ ")" return function return wrapper def close(self): self.outfile.close()
keflavich/pyspeckit-obsolete
pyspeckit/spectrum/logger.py
Python
mit
1,211
<?php namespace Kunstmaan\AdminBundle\Toolbar; use Doctrine\ORM\EntityManagerInterface; use Kunstmaan\AdminBundle\Entity\Exception; use Kunstmaan\AdminBundle\Helper\Toolbar\AbstractDataCollector; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class ExceptionDataCollector extends AbstractDataCollector { /** * @var EntityManagerInterface $em */ private $em; public function __construct(EntityManagerInterface $em) { $this->em = $em; } /** * @return array */ public function getAccessRoles() { return ['ROLE_ADMIN']; } /** * @return array */ public function collectData() { $model = $this->em->getRepository(Exception::class)->findExceptionStatistics(); if ( isset($model['cp_all'], $model['cp_sum']) ) { return [ 'data' => $model ]; } else { return []; } } /** * @param Request $request * @param Response $response * @param \Exception|null $exception */ public function collect(Request $request, Response $response, \Exception $exception = null) { if ( false === $this->isEnabled() ) { $this->data = false; } else { $this->data = $this->collectData(); } } /** * Gets the data for template * * @return array The request events */ public function getTemplateData() { return $this->data; } /** * @return string */ public function getName() { return 'kuma_exception'; } /** * @return bool */ public function isEnabled() { return true; } public function reset() { $this->data = []; } }
treeleaf/KunstmaanBundlesCMS
src/Kunstmaan/AdminBundle/Toolbar/ExceptionDataCollector.php
PHP
mit
1,851
var searchData= [ ['cache',['cache',['../classglobals.html#a5637b6b2c65cc2b027616212978a0e47',1,'globals']]], ['camera',['camera',['../classglobals.html#af37dc090d333e3a996373643f7c2c31f',1,'globals']]], ['camera_5fdistance',['camera_distance',['../classplayer.html#ae80ee7bccfac6b0b1167e3260db03206',1,'player']]], ['camera_5ffirst_5fperson',['camera_first_person',['../classplayer.html#ac31f384bb1a62333fc79fd1abd6fe4c4',1,'player']]], ['camera_5fpitch',['camera_pitch',['../classplayer.html#abb7b860ec40207dcc5f6e8ab414db5e5',1,'player']]], ['camera_5fyaw',['camera_yaw',['../classplayer.html#af3291faa017eb5a379d18f4efb86f8df',1,'player']]], ['cameranode_5f',['cameraNode_',['../class_u_s_p.html#a7cfd1fc925146d7b7700eaaf843ec5da',1,'USP']]], ['context',['context',['../classglobals.html#a90d6620c5d95436101be5e76b18a9002',1,'globals']]], ['current_5flevel',['current_level',['../classgs__playing.html#ad5484e116fdab7774ccd9e1a3c0c8789',1,'gs_playing']]] ];
gawag/Urho-Sample-Platformer
doxygen/html/search/variables_2.js
JavaScript
mit
980
/*! * OverlayScrollbars * https://github.com/KingSora/OverlayScrollbars * * Version: 1.7.3 * * Copyright KingSora. * https://github.com/KingSora * * Released under the MIT license. * Date: 23.06.2019 */ (function (global, factory) { if (typeof define === 'function' && define.amd) define(function() { return factory(global, global.document, undefined); }); else if (typeof module === 'object' && typeof module.exports === 'object') module.exports = factory(global, global.document, undefined); else factory(global, global.document, undefined); }(typeof window !== 'undefined' ? window : this, function(window, document, undefined) { 'use strict'; var PLUGINNAME = 'OverlayScrollbars'; var TYPES = { o : 'object', f : 'function', a : 'array', s : 'string', b : 'boolean', n : 'number', u : 'undefined', z : 'null' //d : 'date', //e : 'error', //r : 'regexp', //y : 'symbol' }; var LEXICON = { c : 'class', s : 'style', i : 'id', l : 'length', p : 'prototype', oH : 'offsetHeight', cH : 'clientHeight', sH : 'scrollHeight', oW : 'offsetWidth', cW : 'clientWidth', sW : 'scrollWidth' }; var VENDORS = { //https://developer.mozilla.org/en-US/docs/Glossary/Vendor_Prefix _jsCache : { }, _cssCache : { }, _cssPrefixes : ['-webkit-', '-moz-', '-o-', '-ms-'], _jsPrefixes : ['WebKit', 'Moz', 'O', 'MS'], _cssProperty : function(name) { var cache = this._cssCache; if(cache[name]) return cache[name]; var prefixes = this._cssPrefixes; var uppercasedName = this._firstLetterToUpper(name); var elmStyle = document.createElement('div')[LEXICON.s]; var resultPossibilities; var i = 0; var v = 0; var currVendorWithoutDashes; for (; i < prefixes.length; i++) { currVendorWithoutDashes = prefixes[i].replace(/-/g, ''); resultPossibilities = [ name, //transition prefixes[i] + name, //-webkit-transition currVendorWithoutDashes + uppercasedName, //webkitTransition this._firstLetterToUpper(currVendorWithoutDashes) + uppercasedName //WebkitTransition ]; for(v = 0; v < resultPossibilities[LEXICON.l]; v++) { if(elmStyle[resultPossibilities[v]] !== undefined) { cache[name] = resultPossibilities[v]; return resultPossibilities[v]; } } } return null; }, _jsAPI : function(name, isInterface, fallback) { var prefixes = this._jsPrefixes; var cache = this._jsCache; var i = 0; var result = cache[name]; if(!result) { result = window[name]; for(; i < prefixes[LEXICON.l]; i++) result = result || window[(isInterface ? prefixes[i] : prefixes[i].toLowerCase()) + this._firstLetterToUpper(name)]; cache[name] = result; } return result || fallback; }, _firstLetterToUpper : function(str) { return str.charAt(0).toUpperCase() + str.slice(1); } }; var COMPATIBILITY = { /** * Gets the current window width. * @returns {Number|number} The current window width in pixel. */ wW: function() { return window.innerWidth || document.documentElement[LEXICON.cW] || document.body[LEXICON.cW]; }, /** * Gets the current window height. * @returns {Number|number} The current window height in pixel. */ wH: function() { return window.innerHeight || document.documentElement[LEXICON.cH] || document.body[LEXICON.cH]; }, /** * Gets the MutationObserver Object or undefined if not supported. * @returns {MutationObserver|*|undefined} The MutationsObserver Object or undefined. */ mO: function() { return VENDORS._jsAPI('MutationObserver', true); }, /** * Gets the ResizeObserver Object or undefined if not supported. * @returns {MutationObserver|*|undefined} The ResizeObserver Object or undefined. */ rO: function() { return VENDORS._jsAPI('ResizeObserver', true); }, /** * Gets the RequestAnimationFrame method or it's corresponding polyfill. * @returns {*|Function} The RequestAnimationFrame method or it's corresponding polyfill. */ rAF: function() { return VENDORS._jsAPI('requestAnimationFrame', false, function (func) { return window.setTimeout(func, 1000 / 60); }); }, /** * Gets the CancelAnimationFrame method or it's corresponding polyfill. * @returns {*|Function} The CancelAnimationFrame method or it's corresponding polyfill. */ cAF: function() { return VENDORS._jsAPI('cancelAnimationFrame', false, function (id) { return window.clearTimeout(id); }); }, /** * Gets the current time. * @returns {number} The current time. */ now: function() { return Date.now && Date.now() || new Date().getTime(); }, /** * Stops the propagation of the given event. * @param event The event of which the propagation shall be stoped. */ stpP: function(event) { if(event.stopPropagation) event.stopPropagation(); else event.cancelBubble = true; }, /** * Prevents the default action of the given event. * @param event The event of which the default action shall be prevented. */ prvD: function(event) { if(event.preventDefault && event.cancelable) event.preventDefault(); else event.returnValue = false; }, /** * Gets the pageX and pageY values of the given mouse event. * @param event The mouse event of which the pageX and pageX shall be got. * @returns {{x: number, y: number}} x = pageX value, y = pageY value. */ page: function(event) { event = event.originalEvent || event; var strPage = 'page'; var strClient = 'client'; var strX = 'X'; var strY = 'Y'; var target = event.target || event.srcElement || document; var eventDoc = target.ownerDocument || document; var doc = eventDoc.documentElement; var body = eventDoc.body; //if touch event return return pageX/Y of it if(event.touches !== undefined) { var touch = event.touches[0]; return { x : touch[strPage + strX], y : touch[strPage + strY] } } // Calculate pageX/Y if not native supported if (!event[strPage + strX] && event[strClient + strX] && event[strClient + strX] != null) { return { x : event[strClient + strX] + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0), y : event[strClient + strY] + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0) } } return { x : event[strPage + strX], y : event[strPage + strY] }; }, /** * Gets the clicked mouse button of the given mouse event. * @param event The mouse event of which the clicked button shal be got. * @returns {number} The number of the clicked mouse button. (0 : none | 1 : leftButton | 2 : middleButton | 3 : rightButton) */ mBtn: function(event) { var button = event.button; if (!event.which && button !== undefined) return (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0))); else return event.which; }, /** * Checks whether a item is in the given array and returns its index. * @param item The item of which the position in the array shall be determined. * @param arr The array. * @returns {number} The zero based index of the item or -1 if the item isn't in the array. */ inA : function(item, arr) { for (var i = 0; i < arr[LEXICON.l]; i++) //Sometiems in IE a "SCRIPT70" Permission denied error occurs if HTML elements in a iFrame are compared try { if (arr[i] === item) return i; } catch(e) { } return -1; }, /** * Returns true if the given value is a array. * @param arr The potential array. * @returns {boolean} True if the given value is a array, false otherwise. */ isA: function(arr) { var def = Array.isArray; return def ? def(arr) : this.type(arr) == TYPES.a; }, /** * Determine the internal JavaScript [[Class]] of the given object. * @param obj The object of which the type shall be determined. * @returns {string} The type of the given object. */ type: function(obj) { if (obj === undefined) return obj + ""; if (obj === null) return obj + ""; return Object[LEXICON.p].toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase(); }, bind: function(func, thisObj) { if (typeof func != TYPES.f) { throw "Can't bind function!"; // closest thing possible to the ECMAScript 5 // internal IsCallable function //throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var proto = LEXICON.p; var aArgs = Array[proto].slice.call(arguments, 2); var fNOP = function() {}; var fBound = function() { return func.apply(this instanceof fNOP ? this : thisObj, aArgs.concat(Array[proto].slice.call(arguments))); }; if (func[proto]) fNOP[proto] = func[proto]; // Function.prototype doesn't have a prototype property fBound[proto] = new fNOP(); return fBound; } /** * Gets the vendor-prefixed CSS property by the given name. * For example the given name is "transform" and you're using a old Firefox browser then the returned value would be "-moz-transform". * If the browser doesn't need a vendor-prefix, then the returned string is the given name. * If the browser doesn't support the given property name at all (not even with a vendor-prefix) the returned value is null. * @param propName The unprefixed CSS property name. * @returns {string|null} The vendor-prefixed CSS property or null if the browser doesn't support the given CSS property. cssProp : function(propName) { return VENDORS._cssProperty(propName); } */ }; var MATH = Math; var JQUERY = window.jQuery; var EASING = (function() { var _easingsMath = { p : MATH.PI, c : MATH.cos, s : MATH.sin, w : MATH.pow, t : MATH.sqrt, n : MATH.asin, a : MATH.abs, o : 1.70158 }; /* x : current percent (0 - 1), t : current time (duration * percent), b : start value (from), c : end value (to), d : duration easingName : function(x, t, b, c, d) { return easedValue; } */ return { swing: function (x, t, b, c, d) { return 0.5 - _easingsMath.c(x * _easingsMath.p) / 2; }, linear: function(x, t, b, c, d) { return x; }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? c/2*t*t + b : -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? c/2*t*t*t + b : c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? c/2*t*t*t*t + b : -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? c/2*t*t*t*t*t + b : c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * _easingsMath.c(t/d * (_easingsMath.p/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * _easingsMath.s(t/d * (_easingsMath.p/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (_easingsMath.c(_easingsMath.p*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * _easingsMath.w(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-_easingsMath.w(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * _easingsMath.w(2, 10 * (t - 1)) + b; return c/2 * (-_easingsMath.w(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (_easingsMath.t(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * _easingsMath.t(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { return ((t/=d/2) < 1) ? -c/2 * (_easingsMath.t(1 - t*t) - 1) + b : c/2 * (_easingsMath.t(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=_easingsMath.o;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < _easingsMath.a(c)) { a=c; s=p/4; } else s = p/(2*_easingsMath.p) * _easingsMath.n (c/a); return -(a*_easingsMath.w(2,10*(t-=1)) * _easingsMath.s( (t*d-s)*(2*_easingsMath.p)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=_easingsMath.o;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < _easingsMath.a(c)) { a=c; s=p/4; } else s = p/(2*_easingsMath.p) * _easingsMath.n (c/a); return a*_easingsMath.w(2,-10*t) * _easingsMath.s( (t*d-s)*(2*_easingsMath.p)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=_easingsMath.o;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < _easingsMath.a(c)) { a=c; s=p/4; } else s = p/(2*_easingsMath.p) * _easingsMath.n (c/a); if (t < 1) return -.5*(a*_easingsMath.w(2,10*(t-=1)) * _easingsMath.s( (t*d-s)*(2*_easingsMath.p)/p )) + b; return a*_easingsMath.w(2,-10*(t-=1)) * _easingsMath.s( (t*d-s)*(2*_easingsMath.p)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { s = s || _easingsMath.o; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { s = s || _easingsMath.o; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { s = s || _easingsMath.o; return ((t/=d/2) < 1) ? c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b : c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - this.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { var o = 7.5625; if ((t/=d) < (1/2.75)) { return c*(o*t*t) + b; } else if (t < (2/2.75)) { return c*(o*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(o*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(o*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { return (t < d/2) ? this.easeInBounce (x, t*2, 0, c, d) * .5 + b : this.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }; /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of 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. * */ })(); var FRAMEWORK = (function() { var _rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); var _strSpace = ' '; var _strEmpty = ''; var _strScrollLeft = 'scrollLeft'; var _strScrollTop = 'scrollTop'; var _animations = [ ]; var _type = COMPATIBILITY.type; var _cssNumber = { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }; var extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments[LEXICON.l], deep = false; // Handle a deep copy situation if (_type(target) == TYPES.b) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if (_type(target) != TYPES.o && !_type(target) == TYPES.f) { target = {}; } // extend jQuery itself if only one argument is passed if (length === i) { target = FakejQuery; --i; } for (; i < length; i++) { // Only deal with non-null/undefined values if ((options = arguments[i]) != null) { // Extend the base object for (name in options) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target === copy) { continue; } // Recurse if we're merging plain objects or arrays if (deep && copy && (isPlainObject(copy) || (copyIsArray = COMPATIBILITY.isA(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && COMPATIBILITY.isA(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[name] = extend(deep, clone, copy); // Don't bring in undefined values } else if (copy !== undefined) { target[name] = copy; } } } } // Return the modified object return target; }; var inArray = function(item, arr, fromIndex) { for (var i = fromIndex || 0; i < arr[LEXICON.l]; i++) if (arr[i] === item) return i; return -1; } var isFunction = function(obj) { return _type(obj) == TYPES.f; }; var isEmptyObject = function(obj) { for (var name in obj ) return false; return true; }; var isPlainObject = function(obj) { if (!obj || _type(obj) != TYPES.o) return false; var key; var proto = LEXICON.p; var hasOwnProperty = Object[proto].hasOwnProperty; var hasOwnConstructor = hasOwnProperty.call(obj, 'constructor'); var hasIsPrototypeOf = obj.constructor && obj.constructor[proto] && hasOwnProperty.call(obj.constructor[proto], 'isPrototypeOf'); if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { return false; } for (key in obj) { /**/ } return _type(key) == TYPES.u || hasOwnProperty.call(obj, key); }; var each = function(obj, callback) { var i = 0; if (isArrayLike(obj)) { for (; i < obj[LEXICON.l]; i++) { if (callback.call(obj[i], i, obj[i]) === false) break; } } else { for (i in obj) { if (callback.call(obj[i], i, obj[i]) === false) break; } } return obj; }; var FakejQuery = function (selector) { if(arguments[LEXICON.l] === 0) return this; var base = new FakejQuery(); var elements = selector; var i = 0; var elms; var el; if(_type(selector) == TYPES.s) { elements = [ ]; if(selector.charAt(0) === '<') { el = document.createElement('div'); el.innerHTML = selector; elms = el.children; } else { elms = document.querySelectorAll(selector); } for(; i < elms[LEXICON.l]; i++) elements.push(elms[i]); } if(elements) { if(_type(elements) != TYPES.s && (!isArrayLike(elements) || elements === window || elements === elements.self)) elements = [ elements ]; for(i = 0; i < elements[LEXICON.l]; i++) base[i] = elements[i]; base[LEXICON.l] = elements[LEXICON.l]; } return base; }; function isArrayLike(obj) { var length = !!obj && [LEXICON.l] in obj && obj[LEXICON.l]; var t = _type(obj); return isFunction(t) ? false : (t == TYPES.a || length === 0 || _type(length) == TYPES.n && length > 0 && (length - 1) in obj); } function stripAndCollapse(value) { var tokens = value.match(_rnothtmlwhite) || []; return tokens.join(_strSpace); } function matches(elem, selector) { var nodeList = (elem.parentNode || document).querySelectorAll(selector) || []; var i = nodeList[LEXICON.l]; while (i--) if (nodeList[i] == elem) return true; return false; } function insertAdjacentElement(el, strategy, child) { if(_type(child) == TYPES.a) { for(var i = 0; i < child[LEXICON.l]; i++) insertAdjacentElement(el, strategy, child[i]); } else if(_type(child) == TYPES.s) el.insertAdjacentHTML(strategy, child); else el.insertAdjacentElement(strategy, child.nodeType ? child : child[0]); } function setCSSVal(el, prop, val) { try { if(el[LEXICON.s][prop] !== undefined) el[LEXICON.s][prop] = parseCSSVal(prop, val); } catch(e) { } } function parseCSSVal(prop, val) { if(!_cssNumber[prop.toLowerCase()] && _type(val) == TYPES.n) val += 'px'; return val; } function startNextAnimationInQ(animObj, removeFromQ) { var index; var nextAnim; if(removeFromQ !== false) animObj.q.splice(0, 1); if(animObj.q[LEXICON.l] > 0) { nextAnim = animObj.q[0]; animate(animObj.el, nextAnim.props, nextAnim.duration, nextAnim.easing, nextAnim.complete, true); } else { index = inArray(animObj, _animations); if(index > -1) _animations.splice(index, 1); } } function setAnimationValue(el, prop, value) { if(prop === _strScrollLeft || prop === _strScrollTop) el[prop] = value; else setCSSVal(el, prop, value); } function animate(el, props, options, easing, complete, guaranteedNext) { var hasOptions = isPlainObject(options); var from = { }; var to = { }; var i = 0; var key; var animObj; var start; var progress; var step; var specialEasing; var duration; if(hasOptions) { easing = options.easing; start = options.start; progress = options.progress; step = options.step; specialEasing = options.specialEasing; complete = options.complete; duration = options.duration; } else duration = options; specialEasing = specialEasing || { }; duration = duration || 400; easing = easing || 'swing'; guaranteedNext = guaranteedNext || false; for(; i < _animations[LEXICON.l]; i++) { if(_animations[i].el === el) { animObj = _animations[i]; break; } } if(!animObj) { animObj = { el : el, q : [] }; _animations.push(animObj); } for (key in props) { if(key === _strScrollLeft || key === _strScrollTop) from[key] = el[key]; else from[key] = FakejQuery(el).css(key); } for (key in from) { if(from[key] !== props[key] && props[key] !== undefined) to[key] = props[key]; } if(!isEmptyObject(to)) { var timeNow; var end; var percent; var fromVal; var toVal; var easedVal; var timeStart; var frame; var elapsed; var qPos = guaranteedNext ? 0 : inArray(qObj, animObj.q); var qObj = { props : to, duration : hasOptions ? options : duration, easing : easing, complete : complete }; if (qPos === -1) { qPos = animObj.q[LEXICON.l]; animObj.q.push(qObj); } if(qPos === 0) { if(duration > 0) { timeStart = COMPATIBILITY.now(); frame = function() { timeNow = COMPATIBILITY.now(); elapsed = (timeNow - timeStart); end = qObj.stop || elapsed >= duration; percent = 1 - ((MATH.max(0, timeStart + duration - timeNow) / duration) || 0); for(key in to) { fromVal = parseFloat(from[key]); toVal = parseFloat(to[key]); easedVal = (toVal - fromVal) * EASING[specialEasing[key] || easing](percent, percent * duration, 0, 1, duration) + fromVal; setAnimationValue(el, key, easedVal); if(isFunction(step)) { step(easedVal, { elem : el, prop : key, start : fromVal, now : easedVal, end : toVal, pos : percent, options : { easing : easing, speacialEasing : specialEasing, duration : duration, complete : complete, step : step }, startTime : timeStart }); } } if(isFunction(progress)) progress({ }, percent, MATH.max(0, duration - elapsed)); if (end) { startNextAnimationInQ(animObj); if(isFunction(complete)) complete(); } else qObj.frame = COMPATIBILITY.rAF()(frame); }; qObj.frame = COMPATIBILITY.rAF()(frame); } else { for(key in to) setAnimationValue(el, key, to[key]); startNextAnimationInQ(animObj); } } } else if(guaranteedNext) startNextAnimationInQ(animObj); } function stop(el, clearQ, jumpToEnd) { var animObj; var qObj; var key; var i = 0; for(; i < _animations[LEXICON.l]; i++) { animObj = _animations[i]; if(animObj.el === el) { if(animObj.q[LEXICON.l] > 0) { qObj = animObj.q[0]; qObj.stop = true; COMPATIBILITY.cAF()(qObj.frame); animObj.q.splice(0, 1); if(jumpToEnd) for(key in qObj.props) setAnimationValue(el, key, qObj.props[key]); if(clearQ) animObj.q = [ ]; else startNextAnimationInQ(animObj, false); } break; } } } FakejQuery[LEXICON.p] = { //EVENTS: on : function(eventName, handler) { eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty]; var eventNameLength = eventName[LEXICON.l]; var i = 0; var el; return this.each(function() { el = this; try { if (el.addEventListener) { for (; i < eventNameLength; i++) el.addEventListener(eventName[i], handler); } else if(el.detachEvent) { for (; i < eventNameLength; i++) el.attachEvent('on' + eventName[i], handler); } } catch (e) { } }); }, off : function(eventName, handler) { eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty]; var eventNameLength = eventName[LEXICON.l]; var i = 0; var el; return this.each(function() { el = this; try { if (el.removeEventListener) { for (; i < eventNameLength; i++) el.removeEventListener(eventName[i], handler); } else if(el.detachEvent) { for (; i < eventNameLength; i++) el.detachEvent('on' + eventName[i], handler); } } catch (e) { } }); }, one : function (eventName, handler) { eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty]; return this.each(function() { var el = FakejQuery(this); FakejQuery.each(eventName, function(i, oneEventName) { var oneHandler = function(e) { handler.call(this, e); el.off(oneEventName, oneHandler); }; el.on(oneEventName, oneHandler); }); }); }, trigger : function(eventName) { var el; var event; return this.each(function() { el = this; if (document.createEvent) { event = document.createEvent('HTMLEvents'); event.initEvent(eventName, true, false); el.dispatchEvent(event); } else { el.fireEvent("on" + eventName); } }); }, //DOM NODE INSERTING / REMOVING: append : function(child) { return this.each(function() { insertAdjacentElement(this, 'beforeend', child); }); }, prepend : function(child) { return this.each(function() { insertAdjacentElement(this, 'afterbegin', child); }); }, before : function(child) { return this.each(function() { insertAdjacentElement(this, 'beforebegin', child); }); }, after : function(child) { return this.each(function() { insertAdjacentElement(this, 'afterend', child); }); }, remove : function() { return this.each(function() { var el = this; var parentNode = el.parentNode; if(parentNode != null) parentNode.removeChild(el); }); }, unwrap : function() { var parents = [ ]; var i; var el; var parent; this.each(function() { parent = this.parentNode; if(inArray(parent, parents) === - 1) parents.push(parent); }); for(i = 0; i < parents[LEXICON.l]; i++) { el = parents[i]; parent = el.parentNode; while (el.firstChild) parent.insertBefore(el.firstChild, el); parent.removeChild(el); } return this; }, wrapAll : function(wrapperHTML) { var i; var nodes = this; var wrapper = FakejQuery(wrapperHTML)[0]; var deepest = wrapper; var parent = nodes[0].parentNode; var previousSibling = nodes[0].previousSibling; while(deepest.childNodes[LEXICON.l] > 0) deepest = deepest.childNodes[0]; for (i = 0; nodes[LEXICON.l] - i; deepest.firstChild === nodes[0] && i++) deepest.appendChild(nodes[i]); var nextSibling = previousSibling ? previousSibling.nextSibling : parent.firstChild; parent.insertBefore(wrapper, nextSibling); return this; }, wrapInner : function(wrapperHTML) { return this.each(function() { var el = FakejQuery(this); var contents = el.contents(); if (contents[LEXICON.l]) contents.wrapAll(wrapperHTML); else el.append(wrapperHTML); }); }, wrap : function(wrapperHTML) { return this.each(function() { FakejQuery(this).wrapAll(wrapperHTML); }); }, //DOM NODE MANIPULATION / INFORMATION: css : function(styles, val) { var el; var key; var cptStyle; var getCptStyle = window.getComputedStyle; if(_type(styles) == TYPES.s) { if(val === undefined) { el = this[0]; cptStyle = getCptStyle ? getCptStyle(el, null) : el.currentStyle[styles]; //https://bugzilla.mozilla.org/show_bug.cgi?id=548397 can be null sometimes if iframe with display: none (firefox only!) return getCptStyle ? cptStyle != null ? cptStyle.getPropertyValue(styles) : el[LEXICON.s][styles] : cptStyle; } else { return this.each(function() { setCSSVal(this, styles, val); }); } } else { return this.each(function() { for(key in styles) setCSSVal(this, key, styles[key]); }); } }, hasClass : function(className) { var elem, i = 0; var classNamePrepared = _strSpace + className + _strSpace; var classList; while ((elem = this[ i++ ])) { classList = elem.classList; if(classList && classList.contains(className)) return true; else if (elem.nodeType === 1 && (_strSpace + stripAndCollapse(elem.className + _strEmpty) + _strSpace).indexOf(classNamePrepared) > -1) return true; } return false; }, addClass : function(className) { var classes; var elem; var cur; var curValue; var clazz; var finalValue; var supportClassList; var elmClassList; var i = 0; var v = 0; if (className) { classes = className.match( _rnothtmlwhite ) || []; while ((elem = this[i++])) { elmClassList = elem.classList; if(supportClassList === undefined) supportClassList = elmClassList !== undefined; if(supportClassList) { while ((clazz = classes[v++])) elmClassList.add(clazz); } else { curValue = elem.className + _strEmpty; cur = elem.nodeType === 1 && (_strSpace + stripAndCollapse(curValue) + _strSpace); if (cur) { while ((clazz = classes[v++])) if (cur.indexOf(_strSpace + clazz + _strSpace) < 0) cur += clazz + _strSpace; finalValue = stripAndCollapse(cur); if (curValue !== finalValue) elem.className = finalValue; } } } } return this; }, removeClass : function(className) { var classes; var elem; var cur; var curValue; var clazz; var finalValue; var supportClassList; var elmClassList; var i = 0; var v = 0; if (className) { classes = className.match(_rnothtmlwhite) || []; while ((elem = this[i++])) { elmClassList = elem.classList; if(supportClassList === undefined) supportClassList = elmClassList !== undefined; if(supportClassList) { while ((clazz = classes[v++])) elmClassList.remove(clazz); } else { curValue = elem.className + _strEmpty; cur = elem.nodeType === 1 && (_strSpace + stripAndCollapse(curValue) + _strSpace); if (cur) { while ((clazz = classes[v++])) while (cur.indexOf(_strSpace + clazz + _strSpace) > -1) cur = cur.replace(_strSpace + clazz + _strSpace, _strSpace); finalValue = stripAndCollapse(cur); if (curValue !== finalValue) elem.className = finalValue; } } } } return this; }, hide : function() { return this.each(function() { this[LEXICON.s].display = 'none'; }); }, show : function() { return this.each(function() { this[LEXICON.s].display = 'block'; }); }, attr : function(attrName, value) { var i = 0; var el; while (el = this[i++]) { if(value === undefined) return el.getAttribute(attrName); el.setAttribute(attrName, value); } return this; }, removeAttr : function(attrName) { return this.each(function() { this.removeAttribute(attrName); }); }, offset : function() { var el = this[0]; var rect = el.getBoundingClientRect(); var scrollLeft = window.pageXOffset || document.documentElement[_strScrollLeft]; var scrollTop = window.pageYOffset || document.documentElement[_strScrollTop]; return { top: rect.top + scrollTop, left: rect.left + scrollLeft }; }, position : function() { var el = this[0]; return { top: el.offsetTop, left: el.offsetLeft }; }, scrollLeft : function(value) { var i = 0; var el; while (el = this[i++]) { if(value === undefined) return el[_strScrollLeft]; el[_strScrollLeft] = value; } return this; }, scrollTop : function(value) { var i = 0; var el; while (el = this[i++]) { if(value === undefined) return el[_strScrollTop]; el[_strScrollTop] = value; } return this; }, val : function(value) { var el = this[0]; if(!value) return el.value; el.value = value; return this; }, //DOM TRAVERSAL / FILTERING: first : function() { return this.eq(0); }, last : function() { return this.eq(-1); }, eq : function(index) { return FakejQuery(this[index >= 0 ? index : this[LEXICON.l] + index]); }, find : function(selector) { var children = [ ]; var i; this.each(function() { var el = this; var ch = el.querySelectorAll(selector); for(i = 0; i < ch[LEXICON.l]; i++) children.push(ch[i]); }); return FakejQuery(children); }, children : function(selector) { var children = [ ]; var el; var ch; var i; this.each(function() { ch = this.children; for(i = 0; i < ch[LEXICON.l]; i++) { el = ch[i]; if(selector) { if((el.matches && el.matches(selector)) || matches(el, selector)) children.push(el); } else children.push(el); } }); return FakejQuery(children); }, parent : function(selector) { var parents = [ ]; var parent; this.each(function() { parent = this.parentNode; if(selector ? FakejQuery(parent).is(selector) : true) parents.push(parent); }); return FakejQuery(parents); }, is : function(selector) { var el; var i; for(i = 0; i < this[LEXICON.l]; i++) { el = this[i]; if(selector === ":visible") return !!(el[LEXICON.oW] || el[LEXICON.oH] || el.getClientRects()[LEXICON.l]); if(selector === ":hidden") return !!!(el[LEXICON.oW] || el[LEXICON.oH] || el.getClientRects()[LEXICON.l]); if((el.matches && el.matches(selector)) || matches(el, selector)) return true; } return false; }, contents : function() { var contents = [ ]; var childs; var i; this.each(function() { childs = this.childNodes; for(i = 0; i < childs[LEXICON.l]; i++) contents.push(childs[i]); }); return FakejQuery(contents); }, each : function(callback) { return each(this, callback); }, //ANIMATION: animate : function(props, duration, easing, complete) { return this.each(function() { animate(this, props, duration, easing, complete); }); }, stop : function(clearQ, jump) { return this.each(function() { stop(this, clearQ, jump); }); } }; extend(FakejQuery, { extend : extend, inArray : inArray, isEmptyObject : isEmptyObject, isPlainObject : isPlainObject, each : each }); return FakejQuery; })(); var INSTANCES = (function() { var _targets = [ ]; var _instancePropertyString = '__overlayScrollbars__'; /** * Register, unregister or get a certain (or all) instances. * Register: Pass the target and the instance. * Unregister: Pass the target and null. * Get Instance: Pass the target from which the instance shall be got. * Get Targets: Pass no arguments. * @param target The target to which the instance shall be registered / from which the instance shall be unregistered / the instance shall be got * @param instance The instance. * @returns {*|void} Returns the instance from the given target. */ return function (target, instance) { var argLen = arguments[LEXICON.l]; if(argLen < 1) { //return all targets return _targets; } else { if(instance) { //register instance target[_instancePropertyString] = instance; _targets.push(target); } else { var index = COMPATIBILITY.inA(target, _targets); if (index > -1) { if(argLen > 1) { //unregister instance delete target[_instancePropertyString]; _targets.splice(index, 1); } else { //get instance from target return _targets[index][_instancePropertyString]; } } } } } })(); var PLUGIN = (function() { var _pluginsGlobals; var _pluginsAutoUpdateLoop; var _pluginsExtensions = [ ]; var _pluginsOptions = (function() { var possibleTemplateTypes = [ TYPES.b, //boolean TYPES.n, //number TYPES.s, //string TYPES.a, //array TYPES.o, //object TYPES.f, //function TYPES.z //null ]; var restrictedStringsSplit = ' '; var restrictedStringsPossibilitiesSplit = ':'; var classNameAllowedValues = [TYPES.z, TYPES.s]; var numberAllowedValues = TYPES.n; var booleanNullAllowedValues = [TYPES.z, TYPES.b]; var booleanTrueTemplate = [true, TYPES.b]; var booleanFalseTemplate = [false, TYPES.b]; var callbackTemplate = [null, [TYPES.z, TYPES.f]]; var inheritedAttrsTemplate = [['style', 'class'], [TYPES.s, TYPES.a, TYPES.z]]; var resizeAllowedValues = 'n:none b:both h:horizontal v:vertical'; var overflowBehaviorAllowedValues = 'v-h:visible-hidden v-s:visible-scroll s:scroll h:hidden'; var scrollbarsVisibilityAllowedValues = 'v:visible h:hidden a:auto'; var scrollbarsAutoHideAllowedValues = 'n:never s:scroll l:leave m:move'; var optionsDefaultsAndTemplate = { className: ['os-theme-dark', classNameAllowedValues], //null || string resize: ['none', resizeAllowedValues], //none || both || horizontal || vertical || n || b || h || v sizeAutoCapable: booleanTrueTemplate, //true || false clipAlways: booleanTrueTemplate, //true || false normalizeRTL: booleanTrueTemplate, //true || false paddingAbsolute: booleanFalseTemplate, //true || false autoUpdate: [null, booleanNullAllowedValues], //true || false || null autoUpdateInterval: [33, numberAllowedValues], //number nativeScrollbarsOverlaid: { showNativeScrollbars: booleanFalseTemplate, //true || false initialize: booleanTrueTemplate //true || false }, overflowBehavior: { x: ['scroll', overflowBehaviorAllowedValues], //visible-hidden || visible-scroll || hidden || scroll || v-h || v-s || h || s y: ['scroll', overflowBehaviorAllowedValues] //visible-hidden || visible-scroll || hidden || scroll || v-h || v-s || h || s }, scrollbars: { visibility: ['auto', scrollbarsVisibilityAllowedValues], //visible || hidden || auto || v || h || a autoHide: ['never', scrollbarsAutoHideAllowedValues], //never || scroll || leave || move || n || s || l || m autoHideDelay: [800, numberAllowedValues], //number dragScrolling: booleanTrueTemplate, //true || false clickScrolling: booleanFalseTemplate, //true || false touchSupport: booleanTrueTemplate, //true || false snapHandle: booleanFalseTemplate //true || false }, textarea: { dynWidth: booleanFalseTemplate, //true || false dynHeight: booleanFalseTemplate, //true || false inheritedAttrs : inheritedAttrsTemplate //string || array || null }, callbacks: { onInitialized: callbackTemplate, //null || function onInitializationWithdrawn: callbackTemplate, //null || function onDestroyed: callbackTemplate, //null || function onScrollStart: callbackTemplate, //null || function onScroll: callbackTemplate, //null || function onScrollStop: callbackTemplate, //null || function onOverflowChanged: callbackTemplate, //null || function onOverflowAmountChanged: callbackTemplate, //null || function onDirectionChanged: callbackTemplate, //null || function onContentSizeChanged: callbackTemplate, //null || function onHostSizeChanged: callbackTemplate, //null || function onUpdated: callbackTemplate //null || function } }; var convert = function(template) { var recursive = function(obj) { var key; var val; var valType; for(key in obj) { if(!obj.hasOwnProperty(key)) continue; val = obj[key]; valType = COMPATIBILITY.type(val); if(valType == TYPES.a) obj[key] = val[template ? 1 : 0]; else if(valType == TYPES.o) obj[key] = recursive(val); } return obj; }; return recursive(FRAMEWORK.extend(true, { }, optionsDefaultsAndTemplate)); }; return { _defaults : convert(), _template : convert(true), /** * Validates the passed object by the passed template. * @param obj The object which shall be validated. * @param template The template which defines the allowed values and types. * @param writeErrors True if errors shall be logged to the console. * @param usePreparedValues True if the validated main values shall be returned in the validated object, false otherwise. * @param keepForeignProps True if properties which aren't in the template shall be added to the validated object, false otherwise. * @returns {{}} A object which contains only the valid properties of the passed original object. */ _validate : function (obj, template, writeErrors, usePreparedValues, keepForeignProps) { var validatedOptions = { }; var objectCopy = FRAMEWORK.extend(true, { }, obj); var checkObjectProps = function(data, template, validatedOptions, prevPropName) { for (var prop in template) { if (template.hasOwnProperty(prop) && data.hasOwnProperty(prop)) { var isValid = false; var templateValue = template[prop]; var templateValueType = COMPATIBILITY.type(templateValue); var templateIsComplext = templateValueType == TYPES.o; var templateTypes = COMPATIBILITY.type(templateValue) != TYPES.a ? [ templateValue ] : templateValue; var dataValue = data[prop]; var dataValueType = COMPATIBILITY.type(dataValue); var propPrefix = prevPropName ? prevPropName + "." : ""; var error = "The option \"" + propPrefix + prop + "\" wasn't set, because"; var errorPossibleTypes = [ ]; var errorRestrictedStrings = [ ]; var restrictedStringValuesSplit; var restrictedStringValuesPossibilitiesSplit; var isRestrictedValue; var mainPossibility; var currType; var i; var v; var j; //if the template has a object as value, it means that the options are complex (verschachtelt) if(templateIsComplext && dataValueType == TYPES.o) { validatedOptions[prop] = { }; checkObjectProps(dataValue, templateValue, validatedOptions[prop], propPrefix + prop); if(FRAMEWORK.isEmptyObject(dataValue)) delete data[prop]; } else if(!templateIsComplext) { for(i = 0; i < templateTypes.length; i++) { currType = templateTypes[i]; templateValueType = COMPATIBILITY.type(currType); //if currtype is string and starts with restrictedStringPrefix and end with restrictedStringSuffix isRestrictedValue = templateValueType == TYPES.s && FRAMEWORK.inArray(currType, possibleTemplateTypes) === -1; if(isRestrictedValue) { errorPossibleTypes.push(TYPES.s); //split it into a array which contains all possible values for example: ["y:yes", "n:no", "m:maybe"] restrictedStringValuesSplit = currType.split(restrictedStringsSplit); errorRestrictedStrings = errorRestrictedStrings.concat(restrictedStringValuesSplit); for(v = 0; v < restrictedStringValuesSplit.length; v++) { //split the possible values into their possibiliteis for example: ["y", "yes"] -> the first is always the mainPossibility restrictedStringValuesPossibilitiesSplit = restrictedStringValuesSplit[v].split(restrictedStringsPossibilitiesSplit); mainPossibility = restrictedStringValuesPossibilitiesSplit[0]; for(j = 0; j < restrictedStringValuesPossibilitiesSplit.length; j++) { //if any possibility matches with the dataValue, its valid if(dataValue === restrictedStringValuesPossibilitiesSplit[j]) { isValid = true; break; } } if(isValid) break; } } else { errorPossibleTypes.push(currType); if(dataValueType === currType) { isValid = true; break; } } } if(isValid) { validatedOptions[prop] = isRestrictedValue && usePreparedValues ? mainPossibility : dataValue; } else if(writeErrors) { console.warn(error + " it doesn't accept the type [ " + dataValueType.toUpperCase() + " ] with the value of \"" + dataValue + "\".\r\n" + "Accepted types are: [ " + errorPossibleTypes.join(", ").toUpperCase() + " ]." + (errorRestrictedStrings.length > 0 ? "\r\nValid strings are: [ " + errorRestrictedStrings.join(", ").split(restrictedStringsPossibilitiesSplit).join(", ") + " ]." : "")); } delete data[prop]; } } } }; checkObjectProps(objectCopy, template, validatedOptions); //add values which aren't specified in the template to the finished validated object to prevent them from being discarded if(keepForeignProps) FRAMEWORK.extend(true, validatedOptions, objectCopy); else if(!FRAMEWORK.isEmptyObject(objectCopy) && writeErrors) console.warn("The following options are discarded due to invalidity:\r\n" + window.JSON.stringify(objectCopy, null, 2)); return validatedOptions; } } }()); /** * Initializes the object which contains global information about the plugin and each instance of it. */ function initOverlayScrollbarsStatics() { if(!_pluginsGlobals) _pluginsGlobals = new OverlayScrollbarsGlobals(_pluginsOptions._defaults); if(!_pluginsAutoUpdateLoop) _pluginsAutoUpdateLoop = new OverlayScrollbarsAutoUpdateLoop(_pluginsGlobals); } /** * The global object for the OverlayScrollbars objects. It contains resources which every OverlayScrollbars object needs. This object is initialized only once: if the first OverlayScrollbars object gets initialized. * @param defaultOptions * @constructor */ function OverlayScrollbarsGlobals(defaultOptions) { var _base = this; var strOverflow = 'overflow'; var strHidden = 'hidden'; var strScroll = 'scroll'; var bodyElement = FRAMEWORK('body'); var scrollbarDummyElement = FRAMEWORK('<div id="os-dummy-scrollbar-size"><div></div></div>'); var scrollbarDummyElement0 = scrollbarDummyElement[0]; var dummyContainerChild = FRAMEWORK(scrollbarDummyElement.children('div').eq(0)); var getCptStyle = window.getComputedStyle; bodyElement.append(scrollbarDummyElement); scrollbarDummyElement.hide().show(); //fix IE8 bug (incorrect measuring) var nativeScrollbarSize = calcNativeScrollbarSize(scrollbarDummyElement0); var nativeScrollbarIsOverlaid = { x: nativeScrollbarSize.x === 0, y: nativeScrollbarSize.y === 0 }; FRAMEWORK.extend(_base, { defaultOptions : defaultOptions, autoUpdateLoop : false, autoUpdateRecommended : !COMPATIBILITY.mO(), nativeScrollbarSize : nativeScrollbarSize, nativeScrollbarIsOverlaid : nativeScrollbarIsOverlaid, nativeScrollbarStyling : (function() { scrollbarDummyElement.addClass('os-viewport-native-scrollbars-invisible'); //fix opera bug: scrollbar styles will only appear if overflow value is scroll or auto during the activation of the style. //and set overflow to scroll //scrollbarDummyElement.css(strOverflow, strHidden).hide().css(strOverflow, strScroll).show(); //return (scrollbarDummyElement0[LEXICON.oH] - scrollbarDummyElement0[LEXICON.cH]) === 0 && (scrollbarDummyElement0[LEXICON.oW] - scrollbarDummyElement0[LEXICON.cW]) === 0; return scrollbarDummyElement.css('scrollbar-width') === 'none' || (getCptStyle ? getCptStyle(scrollbarDummyElement0, '::-webkit-scrollbar').getPropertyValue('display') === 'none' : false); })(), overlayScrollbarDummySize : { x: 30, y: 30 }, msie : (function() { var ua = window.navigator.userAgent; var strIndexOf = 'indexOf'; var strSubString = 'substring'; var msie = ua[strIndexOf]('MSIE '); var trident = ua[strIndexOf]('Trident/'); var edge = ua[strIndexOf]('Edge/'); var rv = ua[strIndexOf]('rv:'); var result; var parseIntFunc = parseInt; // IE 10 or older => return version number if (msie > 0) result = parseIntFunc(ua[strSubString](msie + 5, ua[strIndexOf]('.', msie)), 10); // IE 11 => return version number else if (trident > 0) result = parseIntFunc(ua[strSubString](rv + 3, ua[strIndexOf]('.', rv)), 10); // Edge (IE 12+) => return version number else if (edge > 0) result = parseIntFunc(ua[strSubString](edge + 5, ua[strIndexOf]('.', edge)), 10); // other browser return result; })(), cssCalc : (function() { var dummyStyle = document.createElement('div')[LEXICON.s]; var strCalc = 'calc'; var i = -1; var prop; for(; i < VENDORS._cssPrefixes[LEXICON.l]; i++) { prop = i < 0 ? strCalc : VENDORS._cssPrefixes[i] + strCalc; dummyStyle.cssText = 'width:' + prop + '(1px);'; if (dummyStyle[LEXICON.l]) return prop; } return null; })(), restrictedMeasuring : (function() { //https://bugzilla.mozilla.org/show_bug.cgi?id=1439305 scrollbarDummyElement.css(strOverflow, strHidden); var scrollSize = { w : scrollbarDummyElement0[LEXICON.sW], h : scrollbarDummyElement0[LEXICON.sH] }; scrollbarDummyElement.css(strOverflow, 'visible'); var scrollSize2 = { w : scrollbarDummyElement0[LEXICON.sW], h : scrollbarDummyElement0[LEXICON.sH] }; return (scrollSize.w - scrollSize2.w) !== 0 || (scrollSize.h - scrollSize2.h) !== 0; })(), rtlScrollBehavior : (function() { scrollbarDummyElement.css({ 'overflow-y' : strHidden, 'overflow-x' : strScroll, 'direction' : 'rtl' }).scrollLeft(0); var dummyContainerOffset = scrollbarDummyElement.offset(); var dummyContainerChildOffset = dummyContainerChild.offset(); scrollbarDummyElement.scrollLeft(999); var dummyContainerScrollOffsetAfterScroll = dummyContainerChild.offset(); return { //origin direction = determines if the zero scroll position is on the left or right side //'i' means 'invert' (i === true means that the axis must be inverted to be correct) //true = on the left side //false = on the right side i : dummyContainerOffset.left === dummyContainerChildOffset.left, //negative = determines if the maximum scroll is positive or negative //'n' means 'negate' (n === true means that the axis must be negated to be correct) //true = negative //false = positive n : dummyContainerChildOffset.left - dummyContainerScrollOffsetAfterScroll.left === 0 }; })(), supportTransform : VENDORS._cssProperty('transform') !== null, supportTransition : VENDORS._cssProperty('transition') !== null, supportPassiveEvents : (function() { var supportsPassive = false; try { window.addEventListener('test', null, Object.defineProperty({ }, 'passive', { get: function() { supportsPassive = true; } })); } catch (e) { } return supportsPassive; })(), supportResizeObserver : !!COMPATIBILITY.rO(), supportMutationObserver : !!COMPATIBILITY.mO() }); scrollbarDummyElement.removeAttr(LEXICON.s).remove(); //Catch zoom event: (function () { if(nativeScrollbarIsOverlaid.x && nativeScrollbarIsOverlaid.y) return; var abs = MATH.abs; var windowWidth = COMPATIBILITY.wW(); var windowHeight = COMPATIBILITY.wH(); var windowDpr = getWindowDPR(); var onResize = function() { if(INSTANCES().length > 0) { var newW = COMPATIBILITY.wW(); var newH = COMPATIBILITY.wH(); var deltaW = newW - windowWidth; var deltaH = newH - windowHeight; if (deltaW === 0 && deltaH === 0) return; var deltaWRatio = MATH.round(newW / (windowWidth / 100.0)); var deltaHRatio = MATH.round(newH / (windowHeight / 100.0)); var absDeltaW = abs(deltaW); var absDeltaH = abs(deltaH); var absDeltaWRatio = abs(deltaWRatio); var absDeltaHRatio = abs(deltaHRatio); var newDPR = getWindowDPR(); var deltaIsBigger = absDeltaW > 2 && absDeltaH > 2; var difference = !differenceIsBiggerThanOne(absDeltaWRatio, absDeltaHRatio); var dprChanged = newDPR !== windowDpr && windowDpr > 0; var isZoom = deltaIsBigger && difference && dprChanged; var oldScrollbarSize = _base.nativeScrollbarSize; var newScrollbarSize; if (isZoom) { bodyElement.append(scrollbarDummyElement); newScrollbarSize = _base.nativeScrollbarSize = calcNativeScrollbarSize(scrollbarDummyElement[0]); scrollbarDummyElement.remove(); if(oldScrollbarSize.x !== newScrollbarSize.x || oldScrollbarSize.y !== newScrollbarSize.y) { FRAMEWORK.each(INSTANCES(), function () { if(INSTANCES(this)) INSTANCES(this).update('zoom'); }); } } windowWidth = newW; windowHeight = newH; windowDpr = newDPR; } }; function differenceIsBiggerThanOne(valOne, valTwo) { var absValOne = abs(valOne); var absValTwo = abs(valTwo); return !(absValOne === absValTwo || absValOne + 1 === absValTwo || absValOne - 1 === absValTwo); } function getWindowDPR() { var dDPI = window.screen.deviceXDPI || 0; var sDPI = window.screen.logicalXDPI || 1; return window.devicePixelRatio || (dDPI / sDPI); } FRAMEWORK(window).on('resize', onResize); })(); function calcNativeScrollbarSize(measureElement) { return { x: measureElement[LEXICON.oH] - measureElement[LEXICON.cH], y: measureElement[LEXICON.oW] - measureElement[LEXICON.cW] }; } } /** * The object which manages the auto update loop for all OverlayScrollbars objects. This object is initialized only once: if the first OverlayScrollbars object gets initialized. * @constructor */ function OverlayScrollbarsAutoUpdateLoop(globals) { var _base = this; var _strAutoUpdate = 'autoUpdate'; var _strAutoUpdateInterval = _strAutoUpdate + 'Interval'; var _strLength = LEXICON.l; var _loopingInstances = [ ]; var _loopingInstancesIntervalCache = [ ]; var _loopIsActive = false; var _loopIntervalDefault = 33; var _loopInterval = _loopIntervalDefault; var _loopTimeOld = COMPATIBILITY.now(); var _loopID; /** * The auto update loop which will run every 50 milliseconds or less if the update interval of a instance is lower than 50 milliseconds. */ var loop = function() { if(_loopingInstances[_strLength] > 0 && _loopIsActive) { _loopID = COMPATIBILITY.rAF()(function () { loop(); }); var timeNew = COMPATIBILITY.now(); var timeDelta = timeNew - _loopTimeOld; var lowestInterval; var instance; var instanceOptions; var instanceAutoUpdateAllowed; var instanceAutoUpdateInterval; var now; if (timeDelta > _loopInterval) { _loopTimeOld = timeNew - (timeDelta % _loopInterval); lowestInterval = _loopIntervalDefault; for(var i = 0; i < _loopingInstances[_strLength]; i++) { instance = _loopingInstances[i]; if (instance !== undefined) { instanceOptions = instance.options(); instanceAutoUpdateAllowed = instanceOptions[_strAutoUpdate]; instanceAutoUpdateInterval = MATH.max(1, instanceOptions[_strAutoUpdateInterval]); now = COMPATIBILITY.now(); if ((instanceAutoUpdateAllowed === true || instanceAutoUpdateAllowed === null) && (now - _loopingInstancesIntervalCache[i]) > instanceAutoUpdateInterval) { instance.update('auto'); _loopingInstancesIntervalCache[i] = new Date(now += instanceAutoUpdateInterval); } lowestInterval = MATH.max(1, MATH.min(lowestInterval, instanceAutoUpdateInterval)); } } _loopInterval = lowestInterval; } } else { _loopInterval = _loopIntervalDefault; } }; /** * Add OverlayScrollbars instance to the auto update loop. Only successful if the instance isn't already added. * @param instance The instance which shall be updated in a loop automatically. */ _base.add = function(instance) { if(FRAMEWORK.inArray(instance, _loopingInstances) === -1) { _loopingInstances.push(instance); _loopingInstancesIntervalCache.push(COMPATIBILITY.now()); if (_loopingInstances[_strLength] > 0 && !_loopIsActive) { _loopIsActive = true; globals.autoUpdateLoop = _loopIsActive; loop(); } } }; /** * Remove OverlayScrollbars instance from the auto update loop. Only successful if the instance was added before. * @param instance The instance which shall be updated in a loop automatically. */ _base.remove = function(instance) { var index = FRAMEWORK.inArray(instance, _loopingInstances); if(index > -1) { //remove from loopingInstances list _loopingInstancesIntervalCache.splice(index, 1); _loopingInstances.splice(index, 1); //correct update loop behavior if (_loopingInstances[_strLength] === 0 && _loopIsActive) { _loopIsActive = false; globals.autoUpdateLoop = _loopIsActive; if(_loopID !== undefined) { COMPATIBILITY.cAF()(_loopID); _loopID = -1; } } } }; } /** * A object which manages the scrollbars visibility of the target element. * @param pluginTargetElement The element from which the scrollbars shall be hidden. * @param options The custom options. * @param extensions The custom extensions. * @param globals * @param autoUpdateLoop * @returns {*} * @constructor */ function OverlayScrollbarsInstance(pluginTargetElement, options, extensions, globals, autoUpdateLoop) { //if passed element is no HTML element: skip and return if(!isHTMLElement(pluginTargetElement)) return; //if passed element is already initialized: set passed options if there are any and return its instance if(INSTANCES(pluginTargetElement)) { var inst = INSTANCES(pluginTargetElement); inst.options(options); return inst; } //make correct instanceof var _base = new window[PLUGINNAME](); var _frameworkProto = FRAMEWORK[LEXICON.p]; //globals: var _nativeScrollbarIsOverlaid; var _overlayScrollbarDummySize; var _rtlScrollBehavior; var _autoUpdateRecommended; var _msieVersion; var _nativeScrollbarStyling; var _cssCalc; var _nativeScrollbarSize; var _supportTransition; var _supportTransform; var _supportPassiveEvents; var _supportResizeObserver; var _supportMutationObserver; var _restrictedMeasuring; //general readonly: var _initialized; var _destroyed; var _isTextarea; var _isBody; var _documentMixed; var _isTextareaHostGenerated; //general: var _isBorderBox; var _sizeAutoObserverAdded; var _paddingX; var _paddingY; var _borderX; var _borderY; var _marginX; var _marginY; var _isRTL; var _isSleeping; var _contentBorderSize = { }; var _scrollHorizontalInfo = { }; var _scrollVerticalInfo = { }; var _viewportSize = { }; var _nativeScrollbarMinSize = { }; //naming: var _strMinusHidden = '-hidden'; var _strMarginMinus = 'margin-'; var _strPaddingMinus = 'padding-'; var _strBorderMinus = 'border-'; var _strTop = 'top'; var _strRight = 'right'; var _strBottom = 'bottom'; var _strLeft = 'left'; var _strMinMinus = 'min-'; var _strMaxMinus = 'max-'; var _strWidth = 'width'; var _strHeight = 'height'; var _strFloat = 'float'; var _strEmpty = ''; var _strAuto = 'auto'; var _strScroll = 'scroll'; var _strHundredPercent = '100%'; var _strX = 'x'; var _strY = 'y'; var _strDot = '.'; var _strSpace = ' '; var _strScrollbar = 'scrollbar'; var _strMinusHorizontal = '-horizontal'; var _strMinusVertical = '-vertical'; var _strScrollLeft = _strScroll + 'Left'; var _strScrollTop = _strScroll + 'Top'; var _strMouseTouchDownEvent = 'mousedown touchstart'; var _strMouseTouchUpEvent = 'mouseup touchend touchcancel'; var _strMouseTouchMoveEvent = 'mousemove touchmove'; var _strMouseTouchEnter = 'mouseenter'; var _strMouseTouchLeave = 'mouseleave'; var _strKeyDownEvent = 'keydown'; var _strKeyUpEvent = 'keyup'; var _strSelectStartEvent = 'selectstart'; var _strTransitionEndEvent = 'transitionend webkitTransitionEnd oTransitionEnd'; var _strResizeObserverProperty = '__overlayScrollbarsRO__'; //class names: var _cassNamesPrefix = 'os-'; var _classNameHTMLElement = _cassNamesPrefix + 'html'; var _classNameHostElement = _cassNamesPrefix + 'host'; var _classNameHostTextareaElement = _classNameHostElement + '-textarea'; var _classNameHostScrollbarHorizontalHidden = _classNameHostElement + '-' + _strScrollbar + _strMinusHorizontal + _strMinusHidden; var _classNameHostScrollbarVerticalHidden = _classNameHostElement + '-' + _strScrollbar + _strMinusVertical + _strMinusHidden; var _classNameHostTransition = _classNameHostElement + '-transition'; var _classNameHostRTL = _classNameHostElement + '-rtl'; var _classNameHostResizeDisabled = _classNameHostElement + '-resize-disabled'; var _classNameHostScrolling = _classNameHostElement + '-scrolling'; var _classNameHostOverflow = _classNameHostElement + '-overflow'; var _classNameHostOverflowX = _classNameHostOverflow + '-x'; var _classNameHostOverflowY = _classNameHostOverflow + '-y'; var _classNameTextareaElement = _cassNamesPrefix + 'textarea'; var _classNameTextareaCoverElement = _classNameTextareaElement + '-cover'; var _classNamePaddingElement = _cassNamesPrefix + 'padding'; var _classNameViewportElement = _cassNamesPrefix + 'viewport'; var _classNameViewportNativeScrollbarsInvisible = _classNameViewportElement + '-native-scrollbars-invisible'; var _classNameViewportNativeScrollbarsOverlaid = _classNameViewportElement + '-native-scrollbars-overlaid'; var _classNameContentElement = _cassNamesPrefix + 'content'; var _classNameContentArrangeElement = _cassNamesPrefix + 'content-arrange'; var _classNameContentGlueElement = _cassNamesPrefix + 'content-glue'; var _classNameSizeAutoObserverElement = _cassNamesPrefix + 'size-auto-observer'; var _classNameResizeObserverElement = _cassNamesPrefix + 'resize-observer'; var _classNameResizeObserverItemElement = _cassNamesPrefix + 'resize-observer-item'; var _classNameResizeObserverItemFinalElement = _classNameResizeObserverItemElement + '-final'; var _classNameTextInherit = _cassNamesPrefix + 'text-inherit'; var _classNameScrollbar = _cassNamesPrefix + _strScrollbar; var _classNameScrollbarTrack = _classNameScrollbar + '-track'; var _classNameScrollbarTrackOff = _classNameScrollbarTrack + '-off'; var _classNameScrollbarHandle = _classNameScrollbar + '-handle'; var _classNameScrollbarHandleOff = _classNameScrollbarHandle + '-off'; var _classNameScrollbarUnusable = _classNameScrollbar + '-unusable'; var _classNameScrollbarAutoHidden = _classNameScrollbar + '-' + _strAuto + _strMinusHidden; var _classNameScrollbarCorner = _classNameScrollbar + '-corner'; var _classNameScrollbarCornerResize = _classNameScrollbarCorner + '-resize'; var _classNameScrollbarCornerResizeB = _classNameScrollbarCornerResize + '-both'; var _classNameScrollbarCornerResizeH = _classNameScrollbarCornerResize + _strMinusHorizontal; var _classNameScrollbarCornerResizeV = _classNameScrollbarCornerResize + _strMinusVertical; var _classNameScrollbarHorizontal = _classNameScrollbar + _strMinusHorizontal; var _classNameScrollbarVertical = _classNameScrollbar + _strMinusVertical; var _classNameDragging = _cassNamesPrefix + 'dragging'; var _classNameThemeNone = _cassNamesPrefix + 'theme-none'; //callbacks: var _callbacksInitQeueue = [ ]; //options: var _defaultOptions; var _currentOptions; var _currentPreparedOptions; //extensions: var _extensions = { }; var _extensionsPrivateMethods = "added removed on contract"; //update var _lastUpdateTime; var _swallowedUpdateParams = { }; var _swallowedUpdateTimeout; var _swallowUpdateLag = 42; var _imgs = [ ]; //DOM elements: var _windowElement; var _documentElement; var _htmlElement; var _bodyElement; var _targetElement; //the target element of this OverlayScrollbars object var _hostElement; //the host element of this OverlayScrollbars object -> may be the same as targetElement var _sizeAutoObserverElement; //observes size auto changes var _sizeObserverElement; //observes size and padding changes var _paddingElement; //manages the padding var _viewportElement; //is the viewport of our scrollbar model var _contentElement; //the element which holds the content var _contentArrangeElement; //is needed for correct sizing of the content element (only if native scrollbars are overlays) var _contentGlueElement; //has always the size of the content element var _textareaCoverElement; //only applied if target is a textarea element. Used for correct size calculation and for prevention of uncontrolled scrolling var _scrollbarCornerElement; var _scrollbarHorizontalElement; var _scrollbarHorizontalTrackElement; var _scrollbarHorizontalHandleElement; var _scrollbarVerticalElement; var _scrollbarVerticalTrackElement; var _scrollbarVerticalHandleElement; var _windowElementNative; var _documentElementNative; var _targetElementNative; var _hostElementNative; var _sizeAutoObserverElementNative; var _sizeObserverElementNative; var _paddingElementNative; var _viewportElementNative; var _contentElementNative; //Cache: var _hostSizeCache; var _contentScrollSizeCache; var _arrangeContentSizeCache; var _hasOverflowCache; var _hideOverflowCache; var _widthAutoCache; var _heightAutoCache; var _cssMaxValueCache; var _cssBoxSizingCache; var _cssPaddingCache; var _cssBorderCache; var _cssMarginCache; var _cssDirectionCache; var _cssDirectionDetectedCache; var _paddingAbsoluteCache; var _clipAlwaysCache; var _contentGlueSizeCache; var _overflowBehaviorCache; var _overflowAmountCache; var _ignoreOverlayScrollbarHidingCache; var _autoUpdateCache; var _sizeAutoCapableCache; var _textareaAutoWrappingCache; var _textareaInfoCache; var _updateAutoHostElementIdCache; var _updateAutoHostElementClassCache; var _updateAutoHostElementStyleCache; var _updateAutoHostElementVisibleCache; var _updateAutoTargetElementRowsCache; var _updateAutoTargetElementColsCache; var _updateAutoTargetElementWrapCache; var _contentElementScrollSizeChangeDetectedCache; var _hostElementSizeChangeDetectedCache; var _scrollbarsVisibilityCache; var _scrollbarsAutoHideCache; var _scrollbarsClickScrollingCache; var _scrollbarsDragScrollingCache; var _resizeCache; var _normalizeRTLCache; var _classNameCache; var _oldClassName; var _textareaDynHeightCache; var _textareaDynWidthCache; var _bodyMinSizeCache; var _viewportScrollSizeCache; var _displayIsHiddenCache; //MutationObserver: var _mutationObserverHost; var _mutationObserverContent; var _mutationObserverHostCallback; var _mutationObserverContentCallback; var _mutationObserversConnected; //textarea: var _textareaEvents; var _textareaHasFocus; //scrollbars: var _scrollbarsAutoHideTimeoutId; var _scrollbarsAutoHideMoveTimeoutId; var _scrollbarsAutoHideDelay; var _scrollbarsAutoHideNever; var _scrollbarsAutoHideScroll; var _scrollbarsAutoHideMove; var _scrollbarsAutoHideLeave; var _scrollbarsHandleHovered; var _scrollbarsHandleAsync; //resize var _resizeReconnectMutationObserver; var _resizeNone; var _resizeBoth; var _resizeHorizontal; var _resizeVertical; var _resizeOnMouseTouchDown; //==== Passive Event Listener ====// /** * Adds a passive event listener to the given element. * @param element The element to which the event listener shall be applied. * @param eventNames The name(s) of the event listener. * @param listener The listener method which shall be called. */ function addPassiveEventListener(element, eventNames, listener) { var events = eventNames.split(_strSpace); for (var i = 0; i < events.length; i++) element[0].addEventListener(events[i], listener, {passive: true}); } /** * Removes a passive event listener to the given element. * @param element The element from which the event listener shall be removed. * @param eventNames The name(s) of the event listener. * @param listener The listener method which shall be removed. */ function removePassiveEventListener(element, eventNames, listener) { var events = eventNames.split(_strSpace); for (var i = 0; i < events.length; i++) element[0].removeEventListener(events[i], listener, {passive: true}); } //==== Resize Observer ====// /** * Adds a resize observer to the given element. * @param targetElement The element to which the resize observer shall be applied. * @param onElementResizedCallback The callback which is fired every time the resize observer registers a size change. */ function addResizeObserver(targetElement, onElementResizedCallback) { var constMaximum = 3333333; var resizeObserver = COMPATIBILITY.rO(); var strAnimationStartEvent = 'animationstart mozAnimationStart webkitAnimationStart MSAnimationStart'; var strChildNodes = 'childNodes'; var callback = function () { targetElement[_strScrollTop](constMaximum)[_strScrollLeft](_isRTL ? _rtlScrollBehavior.n ? -constMaximum : _rtlScrollBehavior.i ? 0 : constMaximum : constMaximum); onElementResizedCallback(); }; if (_supportResizeObserver) { var element = targetElement.append(generateDiv(_classNameResizeObserverElement + ' observed')).contents()[0]; var observer = element[_strResizeObserverProperty] = new resizeObserver(callback); observer.observe(element); } else { if (_msieVersion > 9 || !_autoUpdateRecommended) { targetElement.prepend( generateDiv(_classNameResizeObserverElement, generateDiv({ className : _classNameResizeObserverItemElement, dir : "ltr" }, generateDiv(_classNameResizeObserverItemElement, generateDiv(_classNameResizeObserverItemFinalElement) ) + generateDiv(_classNameResizeObserverItemElement, generateDiv({ className : _classNameResizeObserverItemFinalElement, style : 'width: 200%; height: 200%' }) ) ) ) ); var observerElement = targetElement[0][strChildNodes][0][strChildNodes][0]; var shrinkElement = FRAMEWORK(observerElement[strChildNodes][1]); var expandElement = FRAMEWORK(observerElement[strChildNodes][0]); var expandElementChild = FRAMEWORK(expandElement[0][strChildNodes][0]); var widthCache = observerElement[LEXICON.oW]; var heightCache = observerElement[LEXICON.oH]; var isDirty; var rAFId; var currWidth; var currHeight; var factor = 2; var nativeScrollbarSize = globals.nativeScrollbarSize; //care don't make changes to this object!!! var reset = function () { /* var sizeResetWidth = observerElement[LEXICON.oW] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y; var sizeResetHeight = observerElement[LEXICON.oH] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y; var expandChildCSS = {}; expandChildCSS[_strWidth] = sizeResetWidth; expandChildCSS[_strHeight] = sizeResetHeight; expandElementChild.css(expandChildCSS); expandElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight); shrinkElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight); */ expandElement[_strScrollLeft](constMaximum)[_strScrollTop](constMaximum); shrinkElement[_strScrollLeft](constMaximum)[_strScrollTop](constMaximum); }; var onResized = function () { rAFId = 0; if (!isDirty) return; widthCache = currWidth; heightCache = currHeight; callback(); }; var onScroll = function (event) { currWidth = observerElement[LEXICON.oW]; currHeight = observerElement[LEXICON.oH]; isDirty = currWidth != widthCache || currHeight != heightCache; if (event && isDirty && !rAFId) { COMPATIBILITY.cAF()(rAFId); rAFId = COMPATIBILITY.rAF()(onResized); } else if(!event) onResized(); reset(); if (event) { COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); } return false; }; var expandChildCSS = {}; var observerElementCSS = {}; setTopRightBottomLeft(observerElementCSS, _strEmpty, [ -((nativeScrollbarSize.y + 1) * factor), nativeScrollbarSize.x * -factor, nativeScrollbarSize.y * -factor, -((nativeScrollbarSize.x + 1) * factor) ]); FRAMEWORK(observerElement).css(observerElementCSS); expandElement.on(_strScroll, onScroll); shrinkElement.on(_strScroll, onScroll); targetElement.on(strAnimationStartEvent, function () { onScroll(false); }); //lets assume that the divs will never be that large and a constant value is enough expandChildCSS[_strWidth] = constMaximum; expandChildCSS[_strHeight] = constMaximum; expandElementChild.css(expandChildCSS); reset(); } else { var attachEvent = _documentElementNative.attachEvent; var isIE = _msieVersion !== undefined; if (attachEvent) { targetElement.prepend(generateDiv(_classNameResizeObserverElement)); findFirst(targetElement, _strDot + _classNameResizeObserverElement)[0].attachEvent('onresize', callback); } else { var obj = _documentElementNative.createElement(TYPES.o); obj.setAttribute('tabindex', '-1'); obj.setAttribute(LEXICON.c, _classNameResizeObserverElement); obj.onload = function () { var wnd = this.contentDocument.defaultView; wnd.addEventListener('resize', callback); wnd.document.documentElement.style.display = 'none'; }; obj.type = 'text/html'; if (isIE) targetElement.prepend(obj); obj.data = 'about:blank'; if (!isIE) targetElement.prepend(obj); targetElement.on(strAnimationStartEvent, callback); } } } //direction change detection: if (targetElement[0] === _sizeObserverElementNative) { var directionChanged = function () { var dir = _hostElement.css('direction'); var css = {}; var scrollLeftValue = 0; var result = false; if (dir !== _cssDirectionDetectedCache) { if (dir === 'ltr') { css[_strLeft] = 0; css[_strRight] = _strAuto; scrollLeftValue = constMaximum; } else { css[_strLeft] = _strAuto; css[_strRight] = 0; scrollLeftValue = _rtlScrollBehavior.n ? -constMaximum : _rtlScrollBehavior.i ? 0 : constMaximum; } _sizeObserverElement.children().eq(0).css(css); targetElement[_strScrollLeft](scrollLeftValue)[_strScrollTop](constMaximum); _cssDirectionDetectedCache = dir; result = true; } return result; }; directionChanged(); targetElement.on(_strScroll, function (event) { if (directionChanged()) update(); COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); return false; }); } } /** * Removes a resize observer from the given element. * @param targetElement The element to which the target resize observer is applied. */ function removeResizeObserver(targetElement) { if (_supportResizeObserver) { var element = targetElement.contents()[0]; element[_strResizeObserverProperty].disconnect(); delete element[_strResizeObserverProperty]; } else { remove(targetElement.children(_strDot + _classNameResizeObserverElement).eq(0)); } } /** * Freezes the given resize observer. * @param targetElement The element to which the target resize observer is applied. */ function freezeResizeObserver(targetElement) { if (targetElement !== undefined) { /* if (_supportResizeObserver) { var element = targetElement.contents()[0]; element[_strResizeObserverProperty].unobserve(element); } else { targetElement = targetElement.children(_strDot + _classNameResizeObserverElement).eq(0); var w = targetElement.css(_strWidth); var h = targetElement.css(_strHeight); var css = {}; css[_strWidth] = w; css[_strHeight] = h; targetElement.css(css); } */ } } /** * Unfreezes the given resize observer. * @param targetElement The element to which the target resize observer is applied. */ function unfreezeResizeObserver(targetElement) { if (targetElement !== undefined) { /* if (_supportResizeObserver) { var element = targetElement.contents()[0]; element[_strResizeObserverProperty].observe(element); } else { var css = { }; css[_strHeight] = _strEmpty; css[_strWidth] = _strEmpty; targetElement.children(_strDot + _classNameResizeObserverElement).eq(0).css(css); } */ } } //==== Mutation Observers ====// /** * Creates MutationObservers for the host and content Element if they are supported. */ function createMutationObservers() { if (_supportMutationObserver) { var mutationObserverContentLag = 11; var mutationObserver = COMPATIBILITY.mO(); var contentLastUpdate = COMPATIBILITY.now(); var mutationTarget; var mutationAttrName; var contentTimeout; var now; var sizeAuto; var action; _mutationObserverHostCallback = function(mutations) { var doUpdate = false; var mutation; if (_initialized && !_isSleeping) { FRAMEWORK.each(mutations, function () { mutation = this; mutationTarget = mutation.target; mutationAttrName = mutation.attributeName; if (mutationAttrName === LEXICON.c) doUpdate = hostClassNamesChanged(mutation.oldValue, mutationTarget.className); else if (mutationAttrName === LEXICON.s) doUpdate = mutation.oldValue !== mutationTarget[LEXICON.s].cssText; else doUpdate = true; if (doUpdate) return false; }); if (doUpdate) _base.update(_strAuto); } return doUpdate; }; _mutationObserverContentCallback = function (mutations) { var doUpdate = false; var mutation; if (_initialized && !_isSleeping) { FRAMEWORK.each(mutations, function () { mutation = this; doUpdate = isUnknownMutation(mutation); return !doUpdate; }); if (doUpdate) { now = COMPATIBILITY.now(); sizeAuto = (_heightAutoCache || _widthAutoCache); action = function () { if(!_destroyed) { contentLastUpdate = now; //if cols, rows or wrap attr was changed if (_isTextarea) textareaUpdate(); if (sizeAuto) update(); else _base.update(_strAuto); } }; clearTimeout(contentTimeout); if (mutationObserverContentLag <= 0 || now - contentLastUpdate > mutationObserverContentLag || !sizeAuto) action(); else contentTimeout = setTimeout(action, mutationObserverContentLag); } } return doUpdate; } _mutationObserverHost = new mutationObserver(_mutationObserverHostCallback); _mutationObserverContent = new mutationObserver(_mutationObserverContentCallback); } } /** * Connects the MutationObservers if they are supported. */ function connectMutationObservers() { if (_supportMutationObserver && !_mutationObserversConnected) { _mutationObserverHost.observe(_hostElementNative, { attributes: true, attributeOldValue: true, attributeFilter: [LEXICON.i, LEXICON.c, LEXICON.s] }); _mutationObserverContent.observe(_isTextarea ? _targetElementNative : _contentElementNative, { attributes: true, attributeOldValue: true, subtree: !_isTextarea, childList: !_isTextarea, characterData: !_isTextarea, attributeFilter: _isTextarea ? ['wrap', 'cols', 'rows'] : [LEXICON.i, LEXICON.c, LEXICON.s, 'open'] }); _mutationObserversConnected = true; } } /** * Disconnects the MutationObservers if they are supported. */ function disconnectMutationObservers() { if (_supportMutationObserver && _mutationObserversConnected) { _mutationObserverHost.disconnect(); _mutationObserverContent.disconnect(); _mutationObserversConnected = false; } } /** * Disconnects the MutationObservers if they are supported. * @returns {boolean|undefined} True if the MutationObservers needed to be synchronized, false or undefined otherwise. */ function synchronizeMutationObservers() { if(_mutationObserversConnected) { var mutHost = _mutationObserverHostCallback(_mutationObserverHost.takeRecords()); var mutContent = _mutationObserverContentCallback(_mutationObserverContent.takeRecords()); return mutHost || mutContent; } } //==== Events of elements ====// /** * This method gets called every time the host element gets resized. IMPORTANT: Padding changes are detected too!! * It refreshes the hostResizedEventArgs and the hostSizeResizeCache. * If there are any size changes, the update method gets called. */ function hostOnResized() { if (_isSleeping) return; var changed; var hostSize = { w: _sizeObserverElementNative[LEXICON.sW], h: _sizeObserverElementNative[LEXICON.sH] }; if (_initialized) { changed = checkCacheDouble(hostSize, _hostElementSizeChangeDetectedCache); _hostElementSizeChangeDetectedCache = hostSize; if (changed) update(true, false); } else { _hostElementSizeChangeDetectedCache = hostSize; } } /** * The mouse enter event of the host element. This event is only needed for the autoHide feature. */ function hostOnMouseEnter() { if (_scrollbarsAutoHideLeave) refreshScrollbarsAutoHide(true); } /** * The mouse leave event of the host element. This event is only needed for the autoHide feature. */ function hostOnMouseLeave() { if (_scrollbarsAutoHideLeave && !_bodyElement.hasClass(_classNameDragging)) refreshScrollbarsAutoHide(false); } /** * The mouse move event of the host element. This event is only needed for the autoHide "move" feature. */ function hostOnMouseMove() { if (_scrollbarsAutoHideMove) { refreshScrollbarsAutoHide(true); clearTimeout(_scrollbarsAutoHideMoveTimeoutId); _scrollbarsAutoHideMoveTimeoutId = setTimeout(function () { if (_scrollbarsAutoHideMove && !_destroyed) refreshScrollbarsAutoHide(false); }, 100); } } /** * Adds or removes mouse & touch events of the host element. (for handling auto-hiding of the scrollbars) * @param destroy Indicates whether the events shall be added or removed. */ function setupHostMouseTouchEvents(destroy) { var passiveEvent = destroy ? removePassiveEventListener : addPassiveEventListener; var strOnOff = destroy ? 'off' : 'on'; var setupEvent = function(target, name, listener) { if(_supportPassiveEvents) passiveEvent(target, name, listener); else target[strOnOff](name, listener); }; if(_scrollbarsAutoHideMove && !destroy) setupEvent(_hostElement, _strMouseTouchMoveEvent, hostOnMouseMove); else { if(destroy) setupEvent(_hostElement, _strMouseTouchMoveEvent, hostOnMouseMove); setupEvent(_hostElement, _strMouseTouchEnter, hostOnMouseEnter); setupEvent(_hostElement, _strMouseTouchLeave, hostOnMouseLeave); } //if the plugin is initialized and the mouse is over the host element, make the scrollbars visible if(!_initialized && !destroy) _hostElement.one("mouseover", hostOnMouseEnter); } /** * Prevents text from deselection if attached to the document element on the mousedown event of a DOM element. * @param event The select start event. */ function documentOnSelectStart(event) { COMPATIBILITY.prvD(event); return false; } /** * A callback which will be called after a img element has downloaded its src asynchronous. */ function imgOnLoad() { update(false, true); } //==== Update Detection ====// /** * Measures the min width and min height of the body element and refreshes the related cache. * @returns {boolean} True if the min width or min height has changed, false otherwise. */ function bodyMinSizeChanged() { var bodyMinSize = {}; if (_isBody && _contentArrangeElement) { bodyMinSize.w = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + _strWidth)); bodyMinSize.h = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + _strHeight)); bodyMinSize.c = checkCacheDouble(bodyMinSize, _bodyMinSizeCache); bodyMinSize.f = true; //flag for "measured at least once" } _bodyMinSizeCache = bodyMinSize; return bodyMinSize.c || false; } /** * Returns true if the class names really changed (new class without plugin host prefix) * @param oldCassNames The old ClassName string. * @param newClassNames The new ClassName string. * @returns {boolean} True if the class names has really changed, false otherwise. */ function hostClassNamesChanged(oldCassNames, newClassNames) { var currClasses = (newClassNames !== undefined && newClassNames !== null) ? newClassNames.split(_strSpace) : _strEmpty; var oldClasses = (oldCassNames !== undefined && oldCassNames !== null) ? oldCassNames.split(_strSpace) : _strEmpty; if (currClasses === _strEmpty && oldClasses === _strEmpty) return false; var diff = getArrayDifferences(oldClasses, currClasses); var changed = false; var oldClassNames = _oldClassName !== undefined && _oldClassName !== null ? _oldClassName.split(_strSpace) : [_strEmpty]; var currClassNames = _classNameCache !== undefined && _classNameCache !== null ? _classNameCache.split(_strSpace) : [_strEmpty]; //remove none theme from diff list to prevent update var idx = FRAMEWORK.inArray(_classNameThemeNone, diff); var curr; var i; var v; var o; var c; if (idx > -1) diff.splice(idx, 1); for (i = 0; i < diff.length; i++) { curr = diff[i]; if (curr.indexOf(_classNameHostElement) !== 0) { o = true; c = true; for (v = 0; v < oldClassNames.length; v++) { if (curr === oldClassNames[v]) { o = false; break; } } for (v = 0; v < currClassNames.length; v++) { if (curr === currClassNames[v]) { c = false; break; } } if (o && c) { changed = true; break; } } } return changed; } /** * Returns true if the given mutation is not from a from the plugin generated element. If the target element is a textarea the mutation is always unknown. * @param mutation The mutation which shall be checked. * @returns {boolean} True if the mutation is from a unknown element, false otherwise. */ function isUnknownMutation(mutation) { var attributeName = mutation.attributeName; var mutationTarget = mutation.target; var mutationType = mutation.type; var strClosest = 'closest'; if (mutationTarget === _contentElementNative) return attributeName === null; if (mutationType === 'attributes' && (attributeName === LEXICON.c || attributeName === LEXICON.s) && !_isTextarea) { //ignore className changes by the plugin if (attributeName === LEXICON.c && FRAMEWORK(mutationTarget).hasClass(_classNameHostElement)) return hostClassNamesChanged(mutation.oldValue, mutationTarget.getAttribute(LEXICON.c)); //only do it of browser support it natively if (typeof mutationTarget[strClosest] != TYPES.f) return true; if (mutationTarget[strClosest](_strDot + _classNameResizeObserverElement) !== null || mutationTarget[strClosest](_strDot + _classNameScrollbar) !== null || mutationTarget[strClosest](_strDot + _classNameScrollbarCorner) !== null) return false; } return true; } /** * Returns true if the content size was changed since the last time this method was called. * @returns {boolean} True if the content size was changed, false otherwise. */ function updateAutoContentSizeChanged() { if (_isSleeping) return false; var float; var textareaValueLength = _isTextarea && _widthAutoCache && !_textareaAutoWrappingCache ? _targetElement.val().length : 0; var setCSS = !_mutationObserversConnected && _widthAutoCache && !_isTextarea; var viewportScrollSize = { }; var css = { }; var bodyMinSizeC; var changed; var viewportScrollSizeChanged; //fix for https://bugzilla.mozilla.org/show_bug.cgi?id=1439305, it only works with "clipAlways : true" //it can work with "clipAlways : false" too, but we had to set the overflow of the viewportElement to hidden every time before measuring if(_restrictedMeasuring) { viewportScrollSize = { x : _viewportElementNative[LEXICON.sW], y : _viewportElementNative[LEXICON.sH] } } if (setCSS) { float = _contentElement.css(_strFloat); css[_strFloat] = _isRTL ? _strRight : _strLeft; css[_strWidth] = _strAuto; _contentElement.css(css); } var contentElementScrollSize = { w: getContentMeasureElement()[LEXICON.sW] + textareaValueLength, h: getContentMeasureElement()[LEXICON.sH] + textareaValueLength }; if (setCSS) { css[_strFloat] = float; css[_strWidth] = _strHundredPercent; _contentElement.css(css); } bodyMinSizeC = bodyMinSizeChanged(); changed = checkCacheDouble(contentElementScrollSize, _contentElementScrollSizeChangeDetectedCache); viewportScrollSizeChanged = checkCacheDouble(viewportScrollSize, _viewportScrollSizeCache, _strX, _strY); _contentElementScrollSizeChangeDetectedCache = contentElementScrollSize; _viewportScrollSizeCache = viewportScrollSize; return changed || bodyMinSizeC || viewportScrollSizeChanged; } /** * Returns true if the host element attributes (id, class, style) was changed since the last time this method was called. * @returns {boolean} */ function meaningfulAttrsChanged() { if (_isSleeping || _mutationObserversConnected) return false; var hostElementId = _hostElement.attr(LEXICON.i) || _strEmpty; var hostElementIdChanged = checkCacheSingle(hostElementId, _updateAutoHostElementIdCache); var hostElementClass = _hostElement.attr(LEXICON.c) || _strEmpty; var hostElementClassChanged = checkCacheSingle(hostElementClass, _updateAutoHostElementClassCache); var hostElementStyle = _hostElement.attr(LEXICON.s) || _strEmpty; var hostElementStyleChanged = checkCacheSingle(hostElementStyle, _updateAutoHostElementStyleCache); var hostElementVisible = _hostElement.is(':visible') || _strEmpty; var hostElementVisibleChanged = checkCacheSingle(hostElementVisible, _updateAutoHostElementVisibleCache); var targetElementRows = _isTextarea ? (_targetElement.attr('rows') || _strEmpty) : _strEmpty; var targetElementRowsChanged = checkCacheSingle(targetElementRows, _updateAutoTargetElementRowsCache); var targetElementCols = _isTextarea ? (_targetElement.attr('cols') || _strEmpty) : _strEmpty; var targetElementColsChanged = checkCacheSingle(targetElementCols, _updateAutoTargetElementColsCache); var targetElementWrap = _isTextarea ? (_targetElement.attr('wrap') || _strEmpty) : _strEmpty; var targetElementWrapChanged = checkCacheSingle(targetElementWrap, _updateAutoTargetElementWrapCache); _updateAutoHostElementIdCache = hostElementId; if (hostElementClassChanged) hostElementClassChanged = hostClassNamesChanged(_updateAutoHostElementClassCache, hostElementClass); _updateAutoHostElementClassCache = hostElementClass; _updateAutoHostElementStyleCache = hostElementStyle; _updateAutoHostElementVisibleCache = hostElementVisible; _updateAutoTargetElementRowsCache = targetElementRows; _updateAutoTargetElementColsCache = targetElementCols; _updateAutoTargetElementWrapCache = targetElementWrap; return hostElementIdChanged || hostElementClassChanged || hostElementStyleChanged || hostElementVisibleChanged || targetElementRowsChanged || targetElementColsChanged || targetElementWrapChanged; } /** * Checks is a CSS Property of a child element is affecting the scroll size of the content. * @param propertyName The CSS property name. * @returns {boolean} True if the property is affecting the content scroll size, false otherwise. */ function isSizeAffectingCSSProperty(propertyName) { if (!_initialized) return true; var flexGrow = 'flex-grow'; var flexShrink = 'flex-shrink'; var flexBasis = 'flex-basis'; var affectingPropsX = [ _strWidth, _strMinMinus + _strWidth, _strMaxMinus + _strWidth, _strMarginMinus + _strLeft, _strMarginMinus + _strRight, _strLeft, _strRight, 'font-weight', 'word-spacing', flexGrow, flexShrink, flexBasis ]; var affectingPropsXContentBox = [ _strPaddingMinus + _strLeft, _strPaddingMinus + _strRight, _strBorderMinus + _strLeft + _strWidth, _strBorderMinus + _strRight + _strWidth ]; var affectingPropsY = [ _strHeight, _strMinMinus + _strHeight, _strMaxMinus + _strHeight, _strMarginMinus + _strTop, _strMarginMinus + _strBottom, _strTop, _strBottom, 'line-height', flexGrow, flexShrink, flexBasis ]; var affectingPropsYContentBox = [ _strPaddingMinus + _strTop, _strPaddingMinus + _strBottom, _strBorderMinus + _strTop + _strWidth, _strBorderMinus + _strBottom + _strWidth ]; var _strS = 's'; var _strVS = 'v-s'; var checkX = _overflowBehaviorCache.x === _strS || _overflowBehaviorCache.x === _strVS; var checkY = _overflowBehaviorCache.y === _strS || _overflowBehaviorCache.y === _strVS; var sizeIsAffected = false; var checkPropertyName = function (arr, name) { for (var i = 0; i < arr[LEXICON.l]; i++) { if (arr[i] === name) return true; } return false; }; if (checkY) { sizeIsAffected = checkPropertyName(affectingPropsY, propertyName); if (!sizeIsAffected && !_isBorderBox) sizeIsAffected = checkPropertyName(affectingPropsYContentBox, propertyName); } if (checkX && !sizeIsAffected) { sizeIsAffected = checkPropertyName(affectingPropsX, propertyName); if (!sizeIsAffected && !_isBorderBox) sizeIsAffected = checkPropertyName(affectingPropsXContentBox, propertyName); } return sizeIsAffected; } //==== Update ====// /** * Updates the variables and size of the textarea element, and manages the scroll on new line or new character. */ function textareaUpdate() { if (_isSleeping) return; var wrapAttrOff = !_textareaAutoWrappingCache; var minWidth = _viewportSize.w /* - (!_isBorderBox && !_paddingAbsoluteCache && _widthAutoCache ? _paddingY + _borderY : 0) */; var minHeight = _viewportSize.h /* - (!_isBorderBox && !_paddingAbsoluteCache && _heightAutoCache ? _paddingY + _borderY : 0) */; var css = { }; var doMeasure = _widthAutoCache || wrapAttrOff; var origWidth; var width; var origHeight; var height; //reset min size css[_strMinMinus + _strWidth] = _strEmpty; css[_strMinMinus + _strHeight] = _strEmpty; //set width auto css[_strWidth] = _strAuto; _targetElement.css(css); //measure width origWidth = _targetElementNative[LEXICON.oW]; width = doMeasure ? MATH.max(origWidth, _targetElementNative[LEXICON.sW] - 1) : 1; /*width += (_widthAutoCache ? _marginX + (!_isBorderBox ? wrapAttrOff ? 0 : _paddingX + _borderX : 0) : 0);*/ //set measured width css[_strWidth] = _widthAutoCache ? _strAuto /*width*/ : _strHundredPercent; css[_strMinMinus + _strWidth] = _strHundredPercent; //set height auto css[_strHeight] = _strAuto; _targetElement.css(css); //measure height origHeight = _targetElementNative[LEXICON.oH]; height = MATH.max(origHeight, _targetElementNative[LEXICON.sH] - 1); //append correct size values css[_strWidth] = width; css[_strHeight] = height; _textareaCoverElement.css(css); //apply min width / min height to prevent textarea collapsing css[_strMinMinus + _strWidth] = minWidth /*+ (!_isBorderBox && _widthAutoCache ? _paddingX + _borderX : 0)*/; css[_strMinMinus + _strHeight] = minHeight /*+ (!_isBorderBox && _heightAutoCache ? _paddingY + _borderY : 0)*/; _targetElement.css(css); return { _originalWidth: origWidth, _originalHeight: origHeight, _dynamicWidth: width, _dynamicHeight: height }; } /** * Updates the plugin and DOM to the current options. * This method should only be called if a update is 100% required. * @param hostSizeChanged True if this method was called due to a host size change. * @param contentSizeChanged True if this method was called due to a content size change. * @param force True if every property shall be updated and the cache shall be ignored. * @param preventSwallowing True if this method shall be executed even if it could be swallowed. */ function update(hostSizeChanged, contentSizeChanged, force, preventSwallowing) { var now = COMPATIBILITY.now(); var swallow = _swallowUpdateLag > 0 && _initialized && (now - _lastUpdateTime) < _swallowUpdateLag && (!_heightAutoCache && !_widthAutoCache) && !preventSwallowing; var displayIsHidden = _hostElement.is(':hidden'); var displayIsHiddenChanged = checkCacheSingle(displayIsHidden, _displayIsHiddenCache, force); _displayIsHiddenCache = displayIsHidden; clearTimeout(_swallowedUpdateTimeout); if (swallow) { _swallowedUpdateParams.h = _swallowedUpdateParams.h || hostSizeChanged; _swallowedUpdateParams.c = _swallowedUpdateParams.c || contentSizeChanged; _swallowedUpdateParams.f = _swallowedUpdateParams.f || force; _swallowedUpdateTimeout = setTimeout(update, _swallowUpdateLag); } //abort update due to: //destroyed //swallowing //sleeping //host is hidden or has false display if (_destroyed || swallow || _isSleeping || (_initialized && !force && displayIsHidden) || _hostElement.css('display') === 'inline') return; _lastUpdateTime = now; hostSizeChanged = hostSizeChanged || _swallowedUpdateParams.h; contentSizeChanged = contentSizeChanged || _swallowedUpdateParams.c; force = force || _swallowedUpdateParams.f; _swallowedUpdateParams = {}; hostSizeChanged = hostSizeChanged === undefined ? false : hostSizeChanged; contentSizeChanged = contentSizeChanged === undefined ? false : contentSizeChanged; force = force === undefined ? false : force; //if scrollbar styling is possible and native scrollbars aren't overlaid the scrollbar styling will be applied which hides the native scrollbars completely. if (_nativeScrollbarStyling && !(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)) { //native scrollbars are hidden, so change the values to zero _nativeScrollbarSize.x = 0; _nativeScrollbarSize.y = 0; } else { //refresh native scrollbar size (in case of zoom) _nativeScrollbarSize = extendDeep({}, globals.nativeScrollbarSize); } // Scrollbar padding is needed for firefox, because firefox hides scrollbar automatically if the size of the div is too small. // The calculation: [scrollbar size +3 *3] // (+3 because of possible decoration e.g. borders, margins etc., but only if native scrollbar is NOT a overlaid scrollbar) // (*3 because (1)increase / (2)decrease -button and (3)resize handle) _nativeScrollbarMinSize = { x: (_nativeScrollbarSize.x + (_nativeScrollbarIsOverlaid.x ? 0 : 3)) * 3, y: (_nativeScrollbarSize.y + (_nativeScrollbarIsOverlaid.y ? 0 : 3)) * 3 }; freezeResizeObserver(_sizeObserverElement); freezeResizeObserver(_sizeAutoObserverElement); //save current scroll offset var currScroll = { x: _viewportElement[_strScrollLeft](), y: _viewportElement[_strScrollTop]() }; var currentPreparedOptionsScrollbars = _currentPreparedOptions.scrollbars; var currentPreparedOptionsTextarea = _currentPreparedOptions.textarea; //scrollbars visibility: var scrollbarsVisibility = currentPreparedOptionsScrollbars.visibility; var scrollbarsVisibilityChanged = checkCacheSingle(scrollbarsVisibility, _scrollbarsVisibilityCache, force); //scrollbars autoHide: var scrollbarsAutoHide = currentPreparedOptionsScrollbars.autoHide; var scrollbarsAutoHideChanged = checkCacheSingle(scrollbarsAutoHide, _scrollbarsAutoHideCache, force); //scrollbars click scrolling var scrollbarsClickScrolling = currentPreparedOptionsScrollbars.clickScrolling; var scrollbarsClickScrollingChanged = checkCacheSingle(scrollbarsClickScrolling, _scrollbarsClickScrollingCache, force); //scrollbars drag scrolling var scrollbarsDragScrolling = currentPreparedOptionsScrollbars.dragScrolling; var scrollbarsDragScrollingChanged = checkCacheSingle(scrollbarsDragScrolling, _scrollbarsDragScrollingCache, force); //className var className = _currentPreparedOptions.className; var classNameChanged = checkCacheSingle(className, _classNameCache, force); //resize var resize = _currentPreparedOptions.resize; var resizeChanged = checkCacheSingle(resize, _resizeCache, force) && !_isBody; //body can't be resized since the window itself acts as resize possibility. //textarea AutoWrapping var textareaAutoWrapping = _isTextarea ? _targetElement.attr('wrap') !== 'off' : false; var textareaAutoWrappingChanged = checkCacheSingle(textareaAutoWrapping, _textareaAutoWrappingCache, force); //paddingAbsolute var paddingAbsolute = _currentPreparedOptions.paddingAbsolute; var paddingAbsoluteChanged = checkCacheSingle(paddingAbsolute, _paddingAbsoluteCache, force); //clipAlways var clipAlways = _currentPreparedOptions.clipAlways; var clipAlwaysChanged = checkCacheSingle(clipAlways, _clipAlwaysCache, force); //sizeAutoCapable var sizeAutoCapable = _currentPreparedOptions.sizeAutoCapable && !_isBody; //body can never be size auto, because it shall be always as big as the viewport. var sizeAutoCapableChanged = checkCacheSingle(sizeAutoCapable, _sizeAutoCapableCache, force); //showNativeScrollbars var ignoreOverlayScrollbarHiding = _currentPreparedOptions.nativeScrollbarsOverlaid.showNativeScrollbars; var ignoreOverlayScrollbarHidingChanged = checkCacheSingle(ignoreOverlayScrollbarHiding, _ignoreOverlayScrollbarHidingCache); //autoUpdate var autoUpdate = _currentPreparedOptions.autoUpdate; var autoUpdateChanged = checkCacheSingle(autoUpdate, _autoUpdateCache); //overflowBehavior var overflowBehavior = _currentPreparedOptions.overflowBehavior; var overflowBehaviorChanged = checkCacheDouble(overflowBehavior, _overflowBehaviorCache, _strX, _strY, force); //dynWidth: var textareaDynWidth = currentPreparedOptionsTextarea.dynWidth; var textareaDynWidthChanged = checkCacheSingle(_textareaDynWidthCache, textareaDynWidth); //dynHeight: var textareaDynHeight = currentPreparedOptionsTextarea.dynHeight; var textareaDynHeightChanged = checkCacheSingle(_textareaDynHeightCache, textareaDynHeight); //scrollbars visibility _scrollbarsAutoHideNever = scrollbarsAutoHide === 'n'; _scrollbarsAutoHideScroll = scrollbarsAutoHide === 's'; _scrollbarsAutoHideMove = scrollbarsAutoHide === 'm'; _scrollbarsAutoHideLeave = scrollbarsAutoHide === 'l'; //scrollbars autoHideDelay _scrollbarsAutoHideDelay = currentPreparedOptionsScrollbars.autoHideDelay; //old className _oldClassName = _classNameCache; //resize _resizeNone = resize === 'n'; _resizeBoth = resize === 'b'; _resizeHorizontal = resize === 'h'; _resizeVertical = resize === 'v'; //normalizeRTL _normalizeRTLCache = _currentPreparedOptions.normalizeRTL; //ignore overlay scrollbar hiding ignoreOverlayScrollbarHiding = ignoreOverlayScrollbarHiding && (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y); //refresh options cache _scrollbarsVisibilityCache = scrollbarsVisibility; _scrollbarsAutoHideCache = scrollbarsAutoHide; _scrollbarsClickScrollingCache = scrollbarsClickScrolling; _scrollbarsDragScrollingCache = scrollbarsDragScrolling; _classNameCache = className; _resizeCache = resize; _textareaAutoWrappingCache = textareaAutoWrapping; _paddingAbsoluteCache = paddingAbsolute; _clipAlwaysCache = clipAlways; _sizeAutoCapableCache = sizeAutoCapable; _ignoreOverlayScrollbarHidingCache = ignoreOverlayScrollbarHiding; _autoUpdateCache = autoUpdate; _overflowBehaviorCache = extendDeep({}, overflowBehavior); _textareaDynWidthCache = textareaDynWidth; _textareaDynHeightCache = textareaDynHeight; _hasOverflowCache = _hasOverflowCache || { x: false, y: false }; //set correct class name to the host element if (classNameChanged) { removeClass(_hostElement, _oldClassName + _strSpace + _classNameThemeNone); addClass(_hostElement, className !== undefined && className !== null && className.length > 0 ? className : _classNameThemeNone); } //set correct auto Update if (autoUpdateChanged) { if (autoUpdate === true) { disconnectMutationObservers(); autoUpdateLoop.add(_base); } else if (autoUpdate === null) { if (_autoUpdateRecommended) { disconnectMutationObservers(); autoUpdateLoop.add(_base); } else { autoUpdateLoop.remove(_base); connectMutationObservers(); } } else { autoUpdateLoop.remove(_base); connectMutationObservers(); } } //activate or deactivate size auto capability if (sizeAutoCapableChanged) { if (sizeAutoCapable) { if (!_contentGlueElement) { _contentGlueElement = FRAMEWORK(generateDiv(_classNameContentGlueElement)); _paddingElement.before(_contentGlueElement); } else { _contentGlueElement.show(); } if (_sizeAutoObserverAdded) { _sizeAutoObserverElement.show(); } else { _sizeAutoObserverElement = FRAMEWORK(generateDiv(_classNameSizeAutoObserverElement)); _sizeAutoObserverElementNative = _sizeAutoObserverElement[0]; _contentGlueElement.before(_sizeAutoObserverElement); var oldSize = {w: -1, h: -1}; addResizeObserver(_sizeAutoObserverElement, function () { var newSize = { w: _sizeAutoObserverElementNative[LEXICON.oW], h: _sizeAutoObserverElementNative[LEXICON.oH] }; if (checkCacheDouble(newSize, oldSize)) { if (_initialized && (_heightAutoCache && newSize.h > 0) || (_widthAutoCache && newSize.w > 0)) { update(); } else if (_initialized && (!_heightAutoCache && newSize.h === 0) || (!_widthAutoCache && newSize.w === 0)) { update(); } } oldSize = newSize; }); _sizeAutoObserverAdded = true; //fix heightAuto detector bug if height is fixed but contentHeight is 0. //the probability this bug will ever happen is very very low, thats why its ok if we use calc which isn't supported in IE8. if (_cssCalc !== null) _sizeAutoObserverElement.css(_strHeight, _cssCalc + '(100% + 1px)'); } } else { if (_sizeAutoObserverAdded) _sizeAutoObserverElement.hide(); if (_contentGlueElement) _contentGlueElement.hide(); } } //if force, update all resizeObservers too if (force) { _sizeObserverElement.find('*').trigger(_strScroll); if (_sizeAutoObserverAdded) _sizeAutoObserverElement.find('*').trigger(_strScroll); } //detect direction: var cssDirection = _hostElement.css('direction'); var cssDirectionChanged = checkCacheSingle(cssDirection, _cssDirectionCache, force); //detect box-sizing: var boxSizing = _hostElement.css('box-sizing'); var boxSizingChanged = checkCacheSingle(boxSizing, _cssBoxSizingCache, force); //detect padding: var padding = { c: force, t: parseToZeroOrNumber(_hostElement.css(_strPaddingMinus + _strTop)), r: parseToZeroOrNumber(_hostElement.css(_strPaddingMinus + _strRight)), b: parseToZeroOrNumber(_hostElement.css(_strPaddingMinus + _strBottom)), l: parseToZeroOrNumber(_hostElement.css(_strPaddingMinus + _strLeft)) }; //width + height auto detecting var: var sizeAutoObserverElementBCRect; //exception occurs in IE8 sometimes (unknown exception) try { sizeAutoObserverElementBCRect = _sizeAutoObserverAdded ? _sizeAutoObserverElementNative.getBoundingClientRect() : null; } catch (ex) { return; } _isRTL = cssDirection === 'rtl'; _isBorderBox = (boxSizing === 'border-box'); var isRTLLeft = _isRTL ? _strLeft : _strRight; var isRTLRight = _isRTL ? _strRight : _strLeft; //detect width auto: var widthAutoResizeDetection = false; var widthAutoObserverDetection = (_sizeAutoObserverAdded && (_hostElement.css(_strFloat) !== 'none' /*|| _isTextarea */)) ? (MATH.round(sizeAutoObserverElementBCRect.right - sizeAutoObserverElementBCRect.left) === 0) && (!paddingAbsolute ? (_hostElementNative[LEXICON.cW] - _paddingX) > 0 : true) : false; if (sizeAutoCapable && !widthAutoObserverDetection) { var tmpCurrHostWidth = _hostElementNative[LEXICON.oW]; var tmpCurrContentGlueWidth = _contentGlueElement.css(_strWidth); _contentGlueElement.css(_strWidth, _strAuto); var tmpNewHostWidth = _hostElementNative[LEXICON.oW]; _contentGlueElement.css(_strWidth, tmpCurrContentGlueWidth); widthAutoResizeDetection = tmpCurrHostWidth !== tmpNewHostWidth; if (!widthAutoResizeDetection) { _contentGlueElement.css(_strWidth, tmpCurrHostWidth + 1); tmpNewHostWidth = _hostElementNative[LEXICON.oW]; _contentGlueElement.css(_strWidth, tmpCurrContentGlueWidth); widthAutoResizeDetection = tmpCurrHostWidth !== tmpNewHostWidth; } } var widthAuto = (widthAutoObserverDetection || widthAutoResizeDetection) && sizeAutoCapable && !displayIsHidden; var widthAutoChanged = checkCacheSingle(widthAuto, _widthAutoCache, force); var wasWidthAuto = !widthAuto && _widthAutoCache; //detect height auto: var heightAuto = _sizeAutoObserverAdded && sizeAutoCapable && !displayIsHidden ? (MATH.round(sizeAutoObserverElementBCRect.bottom - sizeAutoObserverElementBCRect.top) === 0) /* && (!paddingAbsolute && (_msieVersion > 9 || !_msieVersion) ? true : true) */ : false; var heightAutoChanged = checkCacheSingle(heightAuto, _heightAutoCache, force); var wasHeightAuto = !heightAuto && _heightAutoCache; //detect border: //we need the border only if border box and auto size var strMinusWidth = '-' + _strWidth; var updateBorderX = (widthAuto && _isBorderBox) || !_isBorderBox; var updateBorderY = (heightAuto && _isBorderBox) || !_isBorderBox; var border = { c: force, t: updateBorderY ? parseToZeroOrNumber(_hostElement.css(_strBorderMinus + _strTop + strMinusWidth), true) : 0, r: updateBorderX ? parseToZeroOrNumber(_hostElement.css(_strBorderMinus + _strRight + strMinusWidth), true) : 0, b: updateBorderY ? parseToZeroOrNumber(_hostElement.css(_strBorderMinus + _strBottom + strMinusWidth), true) : 0, l: updateBorderX ? parseToZeroOrNumber(_hostElement.css(_strBorderMinus + _strLeft + strMinusWidth), true) : 0 }; //detect margin: var margin = { c: force, t: parseToZeroOrNumber(_hostElement.css(_strMarginMinus + _strTop)), r: parseToZeroOrNumber(_hostElement.css(_strMarginMinus + _strRight)), b: parseToZeroOrNumber(_hostElement.css(_strMarginMinus + _strBottom)), l: parseToZeroOrNumber(_hostElement.css(_strMarginMinus + _strLeft)) }; //detect css max width & height: var cssMaxValue = { h: String(_hostElement.css(_strMaxMinus + _strHeight)), w: String(_hostElement.css(_strMaxMinus + _strWidth)) }; //vars to apply correct css var contentElementCSS = { }; var contentGlueElementCSS = { }; //funcs var getHostSize = function() { //has to be clientSize because offsetSize respect borders return { w: _hostElementNative[LEXICON.cW], h: _hostElementNative[LEXICON.cH] }; }; var getViewportSize = function() { //viewport size is padding container because it never has padding, margin and a border //determine zoom rounding error -> sometimes scrollWidth/Height is smaller than clientWidth/Height //if this happens add the difference to the viewportSize to compensate the rounding error return { w: _paddingElementNative[LEXICON.oW] + MATH.max(0, _contentElementNative[LEXICON.cW] - _contentElementNative[LEXICON.sW]), h: _paddingElementNative[LEXICON.oH] + MATH.max(0, _contentElementNative[LEXICON.cH] - _contentElementNative[LEXICON.sH]) }; }; //set info for padding var paddingAbsoluteX = _paddingX = padding.l + padding.r; var paddingAbsoluteY = _paddingY = padding.t + padding.b; paddingAbsoluteX *= paddingAbsolute ? 1 : 0; paddingAbsoluteY *= paddingAbsolute ? 1 : 0; padding.c = checkCacheTRBL(padding, _cssPaddingCache); //set info for border _borderX = border.l + border.r; _borderY = border.t + border.b; border.c = checkCacheTRBL(border, _cssBorderCache); //set info for margin _marginX = margin.l + margin.r; _marginY = margin.t + margin.b; margin.c = checkCacheTRBL(margin, _cssMarginCache); //set info for css max value cssMaxValue.ih = parseToZeroOrNumber(cssMaxValue.h); //ih = integer height cssMaxValue.iw = parseToZeroOrNumber(cssMaxValue.w); //iw = integer width cssMaxValue.ch = cssMaxValue.h.indexOf('px') > -1; //ch = correct height cssMaxValue.cw = cssMaxValue.w.indexOf('px') > -1; //cw = correct width cssMaxValue.c = checkCacheDouble(cssMaxValue, _cssMaxValueCache, force); //refresh cache _cssDirectionCache = cssDirection; _cssBoxSizingCache = boxSizing; _widthAutoCache = widthAuto; _heightAutoCache = heightAuto; _cssPaddingCache = padding; _cssBorderCache = border; _cssMarginCache = margin; _cssMaxValueCache = cssMaxValue; //IEFix direction changed if (cssDirectionChanged && _sizeAutoObserverAdded) _sizeAutoObserverElement.css(_strFloat, isRTLRight); //apply padding: if (padding.c || cssDirectionChanged || paddingAbsoluteChanged || widthAutoChanged || heightAutoChanged || boxSizingChanged || sizeAutoCapableChanged) { var paddingElementCSS = {}; var textareaCSS = {}; setTopRightBottomLeft(contentGlueElementCSS, _strMarginMinus, [-padding.t, -padding.r, -padding.b, -padding.l]); if (paddingAbsolute) { setTopRightBottomLeft(paddingElementCSS, _strEmpty, [padding.t, padding.r, padding.b, padding.l]); if (_isTextarea) setTopRightBottomLeft(textareaCSS, _strPaddingMinus); else setTopRightBottomLeft(contentElementCSS, _strPaddingMinus); } else { setTopRightBottomLeft(paddingElementCSS, _strEmpty); if (_isTextarea) setTopRightBottomLeft(textareaCSS, _strPaddingMinus, [padding.t, padding.r, padding.b, padding.l]); else setTopRightBottomLeft(contentElementCSS, _strPaddingMinus, [padding.t, padding.r, padding.b, padding.l]); } _paddingElement.css(paddingElementCSS); _targetElement.css(textareaCSS); } //viewport size is padding container because it never has padding, margin and a border. _viewportSize = getViewportSize(); //update Textarea var textareaSize = _isTextarea ? textareaUpdate() : false; var textareaDynOrigSize = _isTextarea && textareaSize ? { w : textareaDynWidth ? textareaSize._dynamicWidth : textareaSize._originalWidth, h : textareaDynHeight ? textareaSize._dynamicHeight : textareaSize._originalHeight } : { }; //fix height auto / width auto in cooperation with current padding & boxSizing behavior: if (heightAuto && (heightAutoChanged || paddingAbsoluteChanged || boxSizingChanged || cssMaxValue.c || padding.c || border.c)) { //if (cssMaxValue.ch) contentElementCSS[_strMaxMinus + _strHeight] = (cssMaxValue.ch ? (cssMaxValue.ih - paddingAbsoluteY + (_isBorderBox ? -_borderY : _paddingY)) : _strEmpty); contentElementCSS[_strHeight] = _strAuto; } else if (heightAutoChanged || paddingAbsoluteChanged) { contentElementCSS[_strMaxMinus + _strHeight] = _strEmpty; contentElementCSS[_strHeight] = _strHundredPercent; } if (widthAuto && (widthAutoChanged || paddingAbsoluteChanged || boxSizingChanged || cssMaxValue.c || padding.c || border.c || cssDirectionChanged)) { //if (cssMaxValue.cw) contentElementCSS[_strMaxMinus + _strWidth] = (cssMaxValue.cw ? (cssMaxValue.iw - paddingAbsoluteX + (_isBorderBox ? -_borderX : _paddingX)) + (_nativeScrollbarIsOverlaid.y /*&& _hasOverflowCache.y && widthAuto */ ? _overlayScrollbarDummySize.y : 0) : _strEmpty); contentElementCSS[_strWidth] = _strAuto; contentGlueElementCSS[_strMaxMinus + _strWidth] = _strHundredPercent; //IE Fix } else if (widthAutoChanged || paddingAbsoluteChanged) { contentElementCSS[_strMaxMinus + _strWidth] = _strEmpty; contentElementCSS[_strWidth] = _strHundredPercent; contentElementCSS[_strFloat] = _strEmpty; contentGlueElementCSS[_strMaxMinus + _strWidth] = _strEmpty; //IE Fix } if (widthAuto) { if (!cssMaxValue.cw) contentElementCSS[_strMaxMinus + _strWidth] = _strEmpty; //textareaDynOrigSize.w || _strAuto :: doesnt works because applied margin will shift width contentGlueElementCSS[_strWidth] = _strAuto; contentElementCSS[_strWidth] = _strAuto; contentElementCSS[_strFloat] = isRTLRight; } else { contentGlueElementCSS[_strWidth] = _strEmpty; } if (heightAuto) { if (!cssMaxValue.ch) contentElementCSS[_strMaxMinus + _strHeight] = _strEmpty; //textareaDynOrigSize.h || _contentElementNative[LEXICON.cH] :: use for anti scroll jumping contentGlueElementCSS[_strHeight] = textareaDynOrigSize.h || _contentElementNative[LEXICON.cH]; } else { contentGlueElementCSS[_strHeight] = _strEmpty; } if (sizeAutoCapable) _contentGlueElement.css(contentGlueElementCSS); _contentElement.css(contentElementCSS); //CHECKPOINT HERE ~ contentElementCSS = {}; contentGlueElementCSS = {}; //if [content(host) client / scroll size, or target element direction, or content(host) max-sizes] changed, or force is true if (hostSizeChanged || contentSizeChanged || cssDirectionChanged || boxSizingChanged || paddingAbsoluteChanged || widthAutoChanged || widthAuto || heightAutoChanged || heightAuto || cssMaxValue.c || ignoreOverlayScrollbarHidingChanged || overflowBehaviorChanged || clipAlwaysChanged || resizeChanged || scrollbarsVisibilityChanged || scrollbarsAutoHideChanged || scrollbarsDragScrollingChanged || scrollbarsClickScrollingChanged || textareaDynWidthChanged || textareaDynHeightChanged || textareaAutoWrappingChanged || force) { var strOverflow = 'overflow'; var strOverflowX = strOverflow + '-x'; var strOverflowY = strOverflow + '-y'; var strHidden = 'hidden'; var strVisible = 'visible'; //decide whether the content overflow must get hidden for correct overflow measuring, it !MUST! be always hidden if the height is auto var hideOverflow4CorrectMeasuring = _restrictedMeasuring ? (_nativeScrollbarIsOverlaid.x || _nativeScrollbarIsOverlaid.y) || //it must be hidden if native scrollbars are overlaid (_viewportSize.w < _nativeScrollbarMinSize.y || _viewportSize.h < _nativeScrollbarMinSize.x) || //it must be hidden if host-element is too small heightAuto || displayIsHiddenChanged //it must be hidden if height is auto or display was change : heightAuto; //if there is not the restricted Measuring bug, it must be hidden if the height is auto //Reset the viewport (very important for natively overlaid scrollbars and zoom change //don't change the overflow prop as it is very expensive and affects performance !A LOT! var viewportElementResetCSS = { }; var resetXTmp = _hasOverflowCache.y && _hideOverflowCache.ys && !ignoreOverlayScrollbarHiding ? (_nativeScrollbarIsOverlaid.y ? _viewportElement.css(isRTLLeft) : -_nativeScrollbarSize.y) : 0; var resetBottomTmp = _hasOverflowCache.x && _hideOverflowCache.xs && !ignoreOverlayScrollbarHiding ? (_nativeScrollbarIsOverlaid.x ? _viewportElement.css(_strBottom) : -_nativeScrollbarSize.x) : 0; setTopRightBottomLeft(viewportElementResetCSS, _strEmpty); _viewportElement.css(viewportElementResetCSS); if(hideOverflow4CorrectMeasuring) _contentElement.css(strOverflow, strHidden); //measure several sizes: var contentMeasureElement = getContentMeasureElement(); //in Firefox content element has to have overflow hidden, else element margins aren't calculated properly, this element prevents this bug, but only if scrollbars aren't overlaid var contentMeasureElementGuaranty = _restrictedMeasuring && !hideOverflow4CorrectMeasuring ? _viewportElementNative : contentMeasureElement; var contentSize = { //use clientSize because natively overlaidScrollbars add borders w: textareaDynOrigSize.w || contentMeasureElement[LEXICON.cW], h: textareaDynOrigSize.h || contentMeasureElement[LEXICON.cH] }; var scrollSize = { w: MATH.max(contentMeasureElement[LEXICON.sW], contentMeasureElementGuaranty[LEXICON.sW]), h: MATH.max(contentMeasureElement[LEXICON.sH], contentMeasureElementGuaranty[LEXICON.sH]) }; //apply the correct viewport style and measure viewport size viewportElementResetCSS[_strBottom] = wasHeightAuto ? _strEmpty : resetBottomTmp; viewportElementResetCSS[isRTLLeft] = wasWidthAuto ? _strEmpty : resetXTmp; _viewportElement.css(viewportElementResetCSS); _viewportSize = getViewportSize(); //measure and correct several sizes var hostSize = getHostSize(); var contentGlueSize = { //client/scrollSize + AbsolutePadding -> because padding is only applied to the paddingElement if its absolute, so you have to add it manually //hostSize is clientSize -> so padding should be added manually, right? FALSE! Because content glue is inside hostElement, so we don't have to worry about padding w: MATH.max((widthAuto ? contentSize.w : scrollSize.w) + paddingAbsoluteX, hostSize.w), h: MATH.max((heightAuto ? contentSize.h : scrollSize.h) + paddingAbsoluteY, hostSize.h) }; contentGlueSize.c = checkCacheDouble(contentGlueSize, _contentGlueSizeCache, force); _contentGlueSizeCache = contentGlueSize; //apply correct contentGlue size if (sizeAutoCapable) { //size contentGlue correctly to make sure the element has correct size if the sizing switches to auto if (contentGlueSize.c || (heightAuto || widthAuto)) { contentGlueElementCSS[_strWidth] = contentGlueSize.w; contentGlueElementCSS[_strHeight] = contentGlueSize.h; //textarea-sizes are already calculated correctly at this point if(!_isTextarea) { contentSize = { //use clientSize because natively overlaidScrollbars add borders w: contentMeasureElement[LEXICON.cW], h: contentMeasureElement[LEXICON.cH] }; } } var textareaCoverCSS = {}; var setContentGlueElementCSSfunction = function(horizontal) { var scrollbarVars = getScrollbarVars(horizontal); var wh = scrollbarVars._w_h; var strWH = scrollbarVars._width_height; var autoSize = horizontal ? widthAuto : heightAuto; var borderSize = horizontal ? _borderX : _borderY; var paddingSize = horizontal ? _paddingX : _paddingY; var marginSize = horizontal ? _marginX : _marginY; var maxSize = contentGlueElementCSS[strWH] + (_isBorderBox ? borderSize : -paddingSize); //make contentGlue size -1 if element is not auto sized, to make sure that a resize event happens when the element shrinks if (!autoSize || (!autoSize && border.c)) contentGlueElementCSS[strWH] = hostSize[wh] - (_isBorderBox ? 0 : paddingSize + borderSize) - 1 - marginSize; //if size is auto and host is same size as max size, make content glue size +1 to make sure size changes will be detected if (autoSize && cssMaxValue['c' + wh] && cssMaxValue['i' + wh] === maxSize) contentGlueElementCSS[strWH] = maxSize + (_isBorderBox ? 0 : paddingSize) + 1; //if size is auto and host is smaller than size as min size, make content glue size -1 to make sure size changes will be detected (this is only needed if padding is 0) if (autoSize && (contentSize[wh] < _viewportSize[wh]) && (horizontal ? (_isTextarea ? !textareaAutoWrapping : false) : true)) { if (_isTextarea) textareaCoverCSS[strWH] = parseToZeroOrNumber(_textareaCoverElement.css(strWH)) - 1; contentGlueElementCSS[strWH] -= 1; } //make sure content glue size is at least 1 if (contentSize[wh] > 0) contentGlueElementCSS[strWH] = MATH.max(1, contentGlueElementCSS[strWH]); }; setContentGlueElementCSSfunction(true); setContentGlueElementCSSfunction(false); if (_isTextarea) _textareaCoverElement.css(textareaCoverCSS); _contentGlueElement.css(contentGlueElementCSS); } if (widthAuto) contentElementCSS[_strWidth] = _strHundredPercent; if (widthAuto && !_isBorderBox && !_mutationObserversConnected) contentElementCSS[_strFloat] = 'none'; //apply and reset content style _contentElement.css(contentElementCSS); contentElementCSS = {}; //measure again, but this time all correct sizes: var contentScrollSize = { w: MATH.max(contentMeasureElement[LEXICON.sW], contentMeasureElementGuaranty[LEXICON.sW]), h: MATH.max(contentMeasureElement[LEXICON.sH], contentMeasureElementGuaranty[LEXICON.sH]) }; contentScrollSize.c = contentSizeChanged = checkCacheDouble(contentScrollSize, _contentScrollSizeCache, force); _contentScrollSizeCache = contentScrollSize; //remove overflow hidden to restore overflow if(hideOverflow4CorrectMeasuring) _contentElement.css(strOverflow, _strEmpty); //refresh viewport size after correct measuring _viewportSize = getViewportSize(); hostSize = getHostSize(); hostSizeChanged = checkCacheDouble(hostSize, _hostSizeCache); _hostSizeCache = hostSize; var hideOverflowForceTextarea = _isTextarea && (_viewportSize.w === 0 || _viewportSize.h === 0); var previousOverflow = _overflowAmountCache; var overflowBehaviorIsVS = { }; var overflowBehaviorIsVH = { }; var overflowBehaviorIsS = { }; var overflowAmount = { }; var hasOverflow = { }; var hideOverflow = { }; var canScroll = { }; var viewportRect = _paddingElementNative.getBoundingClientRect(); var setOverflowVariables = function(horizontal) { var scrollbarVars = getScrollbarVars(horizontal); var scrollbarVarsInverted = getScrollbarVars(!horizontal); var xyI = scrollbarVarsInverted._x_y; var xy = scrollbarVars._x_y; var wh = scrollbarVars._w_h; var widthHeight = scrollbarVars._width_height; var scrollMax = _strScroll + scrollbarVars._Left_Top + 'Max'; var fractionalOverflowAmount = viewportRect[widthHeight] ? MATH.abs(viewportRect[widthHeight] - _viewportSize[wh]) : 0; overflowBehaviorIsVS[xy] = overflowBehavior[xy] === 'v-s'; overflowBehaviorIsVH[xy] = overflowBehavior[xy] === 'v-h'; overflowBehaviorIsS[xy] = overflowBehavior[xy] === 's'; overflowAmount[xy] = MATH.max(0, MATH.round((contentScrollSize[wh] - _viewportSize[wh]) * 100) / 100); overflowAmount[xy] *= (hideOverflowForceTextarea || (_viewportElementNative[scrollMax] === 0 && fractionalOverflowAmount > 0 && fractionalOverflowAmount < 1)) ? 0 : 1; hasOverflow[xy] = overflowAmount[xy] > 0; //hideOverflow: //x || y : true === overflow is hidden by "overflow: scroll" OR "overflow: hidden" //xs || ys : true === overflow is hidden by "overflow: scroll" hideOverflow[xy] = overflowBehaviorIsVS[xy] || overflowBehaviorIsVH[xy] ? (hasOverflow[xyI] && !overflowBehaviorIsVS[xyI] && !overflowBehaviorIsVH[xyI]) : hasOverflow[xy]; hideOverflow[xy + 's'] = hideOverflow[xy] ? (overflowBehaviorIsS[xy] || overflowBehaviorIsVS[xy]) : false; canScroll[xy] = hasOverflow[xy] && hideOverflow[xy + 's']; }; setOverflowVariables(true); setOverflowVariables(false); overflowAmount.c = checkCacheDouble(overflowAmount, _overflowAmountCache, _strX, _strY, force); _overflowAmountCache = overflowAmount; hasOverflow.c = checkCacheDouble(hasOverflow, _hasOverflowCache, _strX, _strY, force); _hasOverflowCache = hasOverflow; hideOverflow.c = checkCacheDouble(hideOverflow, _hideOverflowCache, _strX, _strY, force); _hideOverflowCache = hideOverflow; //if native scrollbar is overlay at x OR y axis, prepare DOM if (_nativeScrollbarIsOverlaid.x || _nativeScrollbarIsOverlaid.y) { var borderDesign = 'px solid transparent'; var contentArrangeElementCSS = { }; var arrangeContent = { }; var arrangeChanged = force; var setContentElementCSS; if (hasOverflow.x || hasOverflow.y) { arrangeContent.w = _nativeScrollbarIsOverlaid.y && hasOverflow.y ? contentScrollSize.w + _overlayScrollbarDummySize.y : _strEmpty; arrangeContent.h = _nativeScrollbarIsOverlaid.x && hasOverflow.x ? contentScrollSize.h + _overlayScrollbarDummySize.x : _strEmpty; arrangeChanged = checkCacheSingle(arrangeContent, _arrangeContentSizeCache, force); _arrangeContentSizeCache = arrangeContent; } if (hasOverflow.c || hideOverflow.c || contentScrollSize.c || cssDirectionChanged || widthAutoChanged || heightAutoChanged || widthAuto || heightAuto || ignoreOverlayScrollbarHidingChanged) { contentElementCSS[_strMarginMinus + isRTLRight] = contentElementCSS[_strBorderMinus + isRTLRight] = _strEmpty; setContentElementCSS = function(horizontal) { var scrollbarVars = getScrollbarVars(horizontal); var scrollbarVarsInverted = getScrollbarVars(!horizontal); var xy = scrollbarVars._x_y; var strDirection = horizontal ? _strBottom : isRTLLeft; var invertedAutoSize = horizontal ? heightAuto : widthAuto; if (_nativeScrollbarIsOverlaid[xy] && hasOverflow[xy] && hideOverflow[xy + 's']) { contentElementCSS[_strMarginMinus + strDirection] = invertedAutoSize ? (ignoreOverlayScrollbarHiding ? _strEmpty : _overlayScrollbarDummySize[xy]) : _strEmpty; contentElementCSS[_strBorderMinus + strDirection] = ((horizontal ? !invertedAutoSize : true) && !ignoreOverlayScrollbarHiding) ? (_overlayScrollbarDummySize[xy] + borderDesign) : _strEmpty; } else { arrangeContent[scrollbarVarsInverted._w_h] = contentElementCSS[_strMarginMinus + strDirection] = contentElementCSS[_strBorderMinus + strDirection] = _strEmpty; arrangeChanged = true; } }; if (_nativeScrollbarStyling) { if (ignoreOverlayScrollbarHiding) removeClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible); else addClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible); } else { setContentElementCSS(true); setContentElementCSS(false); } } if (ignoreOverlayScrollbarHiding) { arrangeContent.w = arrangeContent.h = _strEmpty; arrangeChanged = true; } if (arrangeChanged && !_nativeScrollbarStyling) { contentArrangeElementCSS[_strWidth] = hideOverflow.y ? arrangeContent.w : _strEmpty; contentArrangeElementCSS[_strHeight] = hideOverflow.x ? arrangeContent.h : _strEmpty; if (!_contentArrangeElement) { _contentArrangeElement = FRAMEWORK(generateDiv(_classNameContentArrangeElement)); _viewportElement.prepend(_contentArrangeElement); } _contentArrangeElement.css(contentArrangeElementCSS); } _contentElement.css(contentElementCSS); } var viewportElementCSS = {}; var paddingElementCSS = {}; var setViewportCSS; if (hostSizeChanged || hasOverflow.c || hideOverflow.c || contentScrollSize.c || overflowBehaviorChanged || boxSizingChanged || ignoreOverlayScrollbarHidingChanged || cssDirectionChanged || clipAlwaysChanged || heightAutoChanged) { viewportElementCSS[isRTLRight] = _strEmpty; setViewportCSS = function(horizontal) { var scrollbarVars = getScrollbarVars(horizontal); var scrollbarVarsInverted = getScrollbarVars(!horizontal); var xy = scrollbarVars._x_y; var XY = scrollbarVars._X_Y; var strDirection = horizontal ? _strBottom : isRTLLeft; var reset = function () { viewportElementCSS[strDirection] = _strEmpty; _contentBorderSize[scrollbarVarsInverted._w_h] = 0; }; if (hasOverflow[xy] && hideOverflow[xy + 's']) { viewportElementCSS[strOverflow + XY] = _strScroll; if (ignoreOverlayScrollbarHiding || _nativeScrollbarStyling) { reset(); } else { viewportElementCSS[strDirection] = -(_nativeScrollbarIsOverlaid[xy] ? _overlayScrollbarDummySize[xy] : _nativeScrollbarSize[xy]); _contentBorderSize[scrollbarVarsInverted._w_h] = _nativeScrollbarIsOverlaid[xy] ? _overlayScrollbarDummySize[scrollbarVarsInverted._x_y] : 0; } } else { viewportElementCSS[strOverflow + XY] = _strEmpty; reset(); } }; setViewportCSS(true); setViewportCSS(false); // if the scroll container is too small and if there is any overflow with no overlay scrollbar (and scrollbar styling isn't possible), // make viewport element greater in size (Firefox hide Scrollbars fix) // because firefox starts hiding scrollbars on too small elements // with this behavior the overflow calculation may be incorrect or the scrollbars would appear suddenly // https://bugzilla.mozilla.org/show_bug.cgi?id=292284 if (!_nativeScrollbarStyling && (_viewportSize.h < _nativeScrollbarMinSize.x || _viewportSize.w < _nativeScrollbarMinSize.y) && ((hasOverflow.x && hideOverflow.x && !_nativeScrollbarIsOverlaid.x) || (hasOverflow.y && hideOverflow.y && !_nativeScrollbarIsOverlaid.y))) { viewportElementCSS[_strPaddingMinus + _strTop] = _nativeScrollbarMinSize.x; viewportElementCSS[_strMarginMinus + _strTop] = -_nativeScrollbarMinSize.x; viewportElementCSS[_strPaddingMinus + isRTLRight] = _nativeScrollbarMinSize.y; viewportElementCSS[_strMarginMinus + isRTLRight] = -_nativeScrollbarMinSize.y; } else { viewportElementCSS[_strPaddingMinus + _strTop] = viewportElementCSS[_strMarginMinus + _strTop] = viewportElementCSS[_strPaddingMinus + isRTLRight] = viewportElementCSS[_strMarginMinus + isRTLRight] = _strEmpty; } viewportElementCSS[_strPaddingMinus + isRTLLeft] = viewportElementCSS[_strMarginMinus + isRTLLeft] = _strEmpty; //if there is any overflow (x OR y axis) and this overflow shall be hidden, make overflow hidden, else overflow visible if ((hasOverflow.x && hideOverflow.x) || (hasOverflow.y && hideOverflow.y) || hideOverflowForceTextarea) { //only hide if is Textarea if (_isTextarea && hideOverflowForceTextarea) { paddingElementCSS[strOverflowX] = paddingElementCSS[strOverflowY] = strHidden; } } else { if (!clipAlways || (overflowBehaviorIsVH.x || overflowBehaviorIsVS.x || overflowBehaviorIsVH.y || overflowBehaviorIsVS.y)) { //only un-hide if Textarea if (_isTextarea) { paddingElementCSS[strOverflowX] = paddingElementCSS[strOverflowY] = _strEmpty; } viewportElementCSS[strOverflowX] = viewportElementCSS[strOverflowY] = strVisible; } } _paddingElement.css(paddingElementCSS); _viewportElement.css(viewportElementCSS); viewportElementCSS = { }; //force soft redraw in webkit because without the scrollbars will may appear because DOM wont be redrawn under special conditions if ((hasOverflow.c || boxSizingChanged || widthAutoChanged || heightAutoChanged) && !(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)) { var elementStyle = _contentElementNative[LEXICON.s]; var dump; elementStyle.webkitTransform = 'scale(1)'; elementStyle.display = 'run-in'; dump = _contentElementNative[LEXICON.oH]; elementStyle.display = _strEmpty; //|| dump; //use dump to prevent it from deletion if minify elementStyle.webkitTransform = _strEmpty; } /* //force hard redraw in webkit if native overlaid scrollbars shall appear if (ignoreOverlayScrollbarHidingChanged && ignoreOverlayScrollbarHiding) { _hostElement.hide(); var dump = _hostElementNative[LEXICON.oH]; _hostElement.show(); } */ } //change to direction RTL and width auto Bugfix in Webkit //without this fix, the DOM still thinks the scrollbar is LTR and thus the content is shifted to the left contentElementCSS = {}; if (cssDirectionChanged || widthAutoChanged || heightAutoChanged) { if (_isRTL && widthAuto) { var floatTmp = _contentElement.css(_strFloat); var posLeftWithoutFloat = MATH.round(_contentElement.css(_strFloat, _strEmpty).css(_strLeft, _strEmpty).position().left); _contentElement.css(_strFloat, floatTmp); var posLeftWithFloat = MATH.round(_contentElement.position().left); if (posLeftWithoutFloat !== posLeftWithFloat) contentElementCSS[_strLeft] = posLeftWithoutFloat; } else { contentElementCSS[_strLeft] = _strEmpty; } } _contentElement.css(contentElementCSS); //handle scroll position if (_isTextarea && contentSizeChanged) { var textareaInfo = getTextareaInfo(); if (textareaInfo) { var textareaRowsChanged = _textareaInfoCache === undefined ? true : textareaInfo._rows !== _textareaInfoCache._rows; var cursorRow = textareaInfo._cursorRow; var cursorCol = textareaInfo._cursorColumn; var widestRow = textareaInfo._widestRow; var lastRow = textareaInfo._rows; var lastCol = textareaInfo._columns; var cursorPos = textareaInfo._cursorPosition; var cursorMax = textareaInfo._cursorMax; var cursorIsLastPosition = (cursorPos >= cursorMax && _textareaHasFocus); var textareaScrollAmount = { x: (!textareaAutoWrapping && (cursorCol === lastCol && cursorRow === widestRow)) ? _overflowAmountCache.x : -1, y: (textareaAutoWrapping ? cursorIsLastPosition || textareaRowsChanged && (previousOverflow !== undefined ? (currScroll.y === previousOverflow.y) : false) : (cursorIsLastPosition || textareaRowsChanged) && cursorRow === lastRow) ? _overflowAmountCache.y : -1 }; currScroll.x = textareaScrollAmount.x > -1 ? (_isRTL && _normalizeRTLCache && _rtlScrollBehavior.i ? 0 : textareaScrollAmount.x) : currScroll.x; //if inverted, scroll to 0 -> normalized this means to max scroll offset. currScroll.y = textareaScrollAmount.y > -1 ? textareaScrollAmount.y : currScroll.y; } _textareaInfoCache = textareaInfo; } if (_isRTL && _rtlScrollBehavior.i && _nativeScrollbarIsOverlaid.y && hasOverflow.x && _normalizeRTLCache) currScroll.x += _contentBorderSize.w || 0; if(widthAuto) _hostElement[_strScrollLeft](0); if(heightAuto) _hostElement[_strScrollTop](0); _viewportElement[_strScrollLeft](currScroll.x)[_strScrollTop](currScroll.y); //scrollbars management: var scrollbarsVisibilityVisible = scrollbarsVisibility === 'v'; var scrollbarsVisibilityHidden = scrollbarsVisibility === 'h'; var scrollbarsVisibilityAuto = scrollbarsVisibility === 'a'; var showScrollbarH = COMPATIBILITY.bind(refreshScrollbarAppearance, 0, true, true, canScroll.x); var showScrollbarV = COMPATIBILITY.bind(refreshScrollbarAppearance, 0, false, true, canScroll.y); var hideScrollbarH = COMPATIBILITY.bind(refreshScrollbarAppearance, 0, true, false, canScroll.x); var hideScrollbarV = COMPATIBILITY.bind(refreshScrollbarAppearance, 0, false, false, canScroll.y); //manage class name which indicates scrollable overflow if (hideOverflow.x || hideOverflow.y) addClass(_hostElement, _classNameHostOverflow); else removeClass(_hostElement, _classNameHostOverflow); if (hideOverflow.x) addClass(_hostElement, _classNameHostOverflowX); else removeClass(_hostElement, _classNameHostOverflowX); if (hideOverflow.y) addClass(_hostElement, _classNameHostOverflowY); else removeClass(_hostElement, _classNameHostOverflowY); //add or remove rtl class name for styling purposes if (cssDirectionChanged) { if (_isRTL) addClass(_hostElement, _classNameHostRTL); else removeClass(_hostElement, _classNameHostRTL); } //manage the resize feature (CSS3 resize "polyfill" for this plugin) if (_isBody) addClass(_hostElement, _classNameHostResizeDisabled); if (resizeChanged) { var addCornerEvents = function () { _scrollbarCornerElement.on(_strMouseTouchDownEvent, _resizeOnMouseTouchDown); }; var removeCornerEvents = function () { _scrollbarCornerElement.off(_strMouseTouchDownEvent, _resizeOnMouseTouchDown); }; removeClass(_scrollbarCornerElement, [ _classNameHostResizeDisabled, _classNameScrollbarCornerResize, _classNameScrollbarCornerResizeB, _classNameScrollbarCornerResizeH, _classNameScrollbarCornerResizeV].join(_strSpace)); if (_resizeNone) { addClass(_hostElement, _classNameHostResizeDisabled); removeCornerEvents(); } else { addClass(_scrollbarCornerElement, _classNameScrollbarCornerResize); if (_resizeBoth) addClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeB); else if (_resizeHorizontal) addClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeH); else if (_resizeVertical) addClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeV); removeCornerEvents(); addCornerEvents(); } } //manage the scrollbars general visibility + the scrollbar interactivity (unusable class name) if (scrollbarsVisibilityChanged || overflowBehaviorChanged || hideOverflow.c || hasOverflow.c || ignoreOverlayScrollbarHidingChanged) { if (ignoreOverlayScrollbarHiding) { if (ignoreOverlayScrollbarHidingChanged) { removeClass(_hostElement, _classNameHostScrolling); if (ignoreOverlayScrollbarHiding) { hideScrollbarH(); hideScrollbarV(); } } } else if (scrollbarsVisibilityAuto) { if (canScroll.x) showScrollbarH(); else hideScrollbarH(); if (canScroll.y) showScrollbarV(); else hideScrollbarV(); } else if (scrollbarsVisibilityVisible) { showScrollbarH(); showScrollbarV(); } else if (scrollbarsVisibilityHidden) { hideScrollbarH(); hideScrollbarV(); } } //manage the scrollbars auto hide feature (auto hide them after specific actions) if (scrollbarsAutoHideChanged || ignoreOverlayScrollbarHidingChanged) { if (_scrollbarsAutoHideLeave || _scrollbarsAutoHideMove) { setupHostMouseTouchEvents(true); setupHostMouseTouchEvents(); } else { setupHostMouseTouchEvents(true); } if (_scrollbarsAutoHideNever) refreshScrollbarsAutoHide(true); else refreshScrollbarsAutoHide(false, true); } //manage scrollbars handle length & offset - don't remove! if (hostSizeChanged || overflowAmount.c || heightAutoChanged || widthAutoChanged || resizeChanged || boxSizingChanged || paddingAbsoluteChanged || ignoreOverlayScrollbarHidingChanged || cssDirectionChanged) { refreshScrollbarHandleLength(true); refreshScrollbarHandleOffset(true); refreshScrollbarHandleLength(false); refreshScrollbarHandleOffset(false); } //manage interactivity if (scrollbarsClickScrollingChanged) refreshScrollbarsInteractive(true, scrollbarsClickScrolling); if (scrollbarsDragScrollingChanged) refreshScrollbarsInteractive(false, scrollbarsDragScrolling); //callbacks: if (cssDirectionChanged) { dispatchCallback("onDirectionChanged", { isRTL: _isRTL, dir: cssDirection }); } if (hostSizeChanged) { dispatchCallback("onHostSizeChanged", { width: _hostSizeCache.w, height: _hostSizeCache.h }); } if (contentSizeChanged) { dispatchCallback("onContentSizeChanged", { width: _contentScrollSizeCache.w, height: _contentScrollSizeCache.h }); } if (hasOverflow.c || hideOverflow.c) { dispatchCallback("onOverflowChanged", { x: hasOverflow.x, y: hasOverflow.y, xScrollable: hideOverflow.xs, yScrollable: hideOverflow.ys, clipped: hideOverflow.x || hideOverflow.y }); } if (overflowAmount.c) { dispatchCallback("onOverflowAmountChanged", { x: overflowAmount.x, y: overflowAmount.y }); } } //fix body min size if (_isBody && (_hasOverflowCache.c || _bodyMinSizeCache.c)) { //its possible that no min size was measured until now, because the content arrange element was just added now, in this case, measure now the min size. if (!_bodyMinSizeCache.f) bodyMinSizeChanged(); if (_nativeScrollbarIsOverlaid.y && _hasOverflowCache.x) _contentElement.css(_strMinMinus + _strWidth, _bodyMinSizeCache.w + _overlayScrollbarDummySize.y); if (_nativeScrollbarIsOverlaid.x && _hasOverflowCache.y) _contentElement.css(_strMinMinus + _strHeight, _bodyMinSizeCache.h + _overlayScrollbarDummySize.x); _bodyMinSizeCache.c = false; } unfreezeResizeObserver(_sizeObserverElement); unfreezeResizeObserver(_sizeAutoObserverElement); dispatchCallback("onUpdated", { forced: force }); } //==== Options ====// /** * Sets new options but doesn't call the update method. * @param newOptions The object which contains the new options. */ function setOptions(newOptions) { _currentOptions = extendDeep({}, _currentOptions, _pluginsOptions._validate(newOptions, _pluginsOptions._template, true)); _currentPreparedOptions = extendDeep({}, _currentPreparedOptions, _pluginsOptions._validate(newOptions, _pluginsOptions._template, false, true)); } //==== Structure ====// /** * Builds or destroys the wrapper and helper DOM elements. * @param destroy Indicates whether the DOM shall be build or destroyed. */ function setupStructureDOM(destroy) { var adoptAttrs = _currentPreparedOptions.textarea.inheritedAttrs; var adoptAttrsMap = { }; var applyAdoptedAttrs = function() { var applyAdoptedAttrsElm = destroy ? _targetElement : _hostElement; FRAMEWORK.each(adoptAttrsMap, function(k, v) { if(type(v) == TYPES.s) { if(k == LEXICON.c) applyAdoptedAttrsElm.addClass(v); else applyAdoptedAttrsElm.attr(k, v); } }); }; var hostElementClassNames = [ _classNameHostElement, _classNameHostTextareaElement, _classNameHostResizeDisabled, _classNameHostRTL, _classNameHostScrollbarHorizontalHidden, _classNameHostScrollbarVerticalHidden, _classNameHostTransition, _classNameHostScrolling, _classNameHostOverflow, _classNameHostOverflowX, _classNameHostOverflowY, _classNameThemeNone, _classNameTextareaElement, _classNameTextInherit, _classNameCache].join(_strSpace); adoptAttrs = type(adoptAttrs) == TYPES.s ? adoptAttrs.split(' ') : adoptAttrs; if(type(adoptAttrs) == TYPES.a) { FRAMEWORK.each(adoptAttrs, function(i, v) { if(type(v) == TYPES.s) adoptAttrsMap[v] = destroy ? _hostElement.attr(v) : _targetElement.attr(v); }); } if(!destroy) { if (_isTextarea) { var hostElementCSS = {}; var parent = _targetElement.parent(); _isTextareaHostGenerated = !(parent.hasClass(_classNameHostTextareaElement) && parent.children()[LEXICON.l] === 1); if (!_currentPreparedOptions.sizeAutoCapable) { hostElementCSS[_strWidth] = _targetElement.css(_strWidth); hostElementCSS[_strHeight] = _targetElement.css(_strHeight); } if(_isTextareaHostGenerated) _targetElement.wrap(generateDiv(_classNameHostTextareaElement)); _hostElement = _targetElement.parent(); _hostElement.css(hostElementCSS) .wrapInner(generateDiv(_classNameContentElement + _strSpace + _classNameTextInherit)) .wrapInner(generateDiv(_classNameViewportElement + _strSpace + _classNameTextInherit)) .wrapInner(generateDiv(_classNamePaddingElement + _strSpace + _classNameTextInherit)); _contentElement = findFirst(_hostElement, _strDot + _classNameContentElement); _viewportElement = findFirst(_hostElement, _strDot + _classNameViewportElement); _paddingElement = findFirst(_hostElement, _strDot + _classNamePaddingElement); _textareaCoverElement = FRAMEWORK(generateDiv(_classNameTextareaCoverElement)); _contentElement.prepend(_textareaCoverElement); addClass(_targetElement, _classNameTextareaElement + _strSpace + _classNameTextInherit); if(_isTextareaHostGenerated) applyAdoptedAttrs(); } else { _hostElement = _targetElement; _hostElement.wrapInner(generateDiv(_classNameContentElement)) .wrapInner(generateDiv(_classNameViewportElement)) .wrapInner(generateDiv(_classNamePaddingElement)); _contentElement = findFirst(_hostElement, _strDot + _classNameContentElement); _viewportElement = findFirst(_hostElement, _strDot + _classNameViewportElement); _paddingElement = findFirst(_hostElement, _strDot + _classNamePaddingElement); addClass(_targetElement, _classNameHostElement); } if (_nativeScrollbarStyling) addClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible); if(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y) addClass(_viewportElement, _classNameViewportNativeScrollbarsOverlaid); if (_isBody) addClass(_htmlElement, _classNameHTMLElement); _sizeObserverElement = FRAMEWORK(generateDiv('os-resize-observer-host')); _hostElement.prepend(_sizeObserverElement); _sizeObserverElementNative = _sizeObserverElement[0]; _hostElementNative = _hostElement[0]; _paddingElementNative = _paddingElement[0]; _viewportElementNative = _viewportElement[0]; _contentElementNative = _contentElement[0]; } else { _contentElement.contents() .unwrap() .unwrap() .unwrap(); removeClass(_hostElement, hostElementClassNames); if (_isTextarea) { _targetElement.removeAttr(LEXICON.s); if(_isTextareaHostGenerated) applyAdoptedAttrs(); removeClass(_targetElement, hostElementClassNames); remove(_textareaCoverElement); if(_isTextareaHostGenerated) { _targetElement.unwrap(); remove(_hostElement); } else { addClass(_hostElement, _classNameHostTextareaElement); } } else { removeClass(_targetElement, _classNameHostElement); } if (_isBody) removeClass(_htmlElement, _classNameHTMLElement); remove(_sizeObserverElement); } } /** * Adds or removes all wrapper elements interactivity events. * @param destroy Indicates whether the Events shall be added or removed. */ function setupStructureEvents(destroy) { var textareaKeyDownRestrictedKeyCodes = [ 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 123, //F1 to F12 33, 34, //page up, page down 37, 38, 39, 40, //left, up, right, down arrows 16, 17, 18, 19, 20, 144 //Shift, Ctrl, Alt, Pause, CapsLock, NumLock ]; var textareaKeyDownKeyCodesList = [ ]; var textareaUpdateIntervalID; var scrollStopDelay = 175; var scrollStopTimeoutId; var strOnOff = destroy ? 'off' : 'on'; var updateTextarea; var viewportOnScroll; if(!destroy && _isTextarea) { _textareaEvents = { }; updateTextarea = function(doClearInterval) { textareaUpdate(); _base.update(_strAuto); if(doClearInterval) clearInterval(textareaUpdateIntervalID); }; _textareaEvents[_strScroll] = function(event) { _targetElement[_strScrollLeft](_rtlScrollBehavior.i && _normalizeRTLCache ? 9999999 : 0); _targetElement[_strScrollTop](0); COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); return false; }; _textareaEvents['drop'] = function() { setTimeout(function () { if(!_destroyed) updateTextarea(); }, 50); }; _textareaEvents['focus'] = function() { _textareaHasFocus = true; }; _textareaEvents['focusout'] = function() { _textareaHasFocus = false; textareaKeyDownKeyCodesList = [ ]; updateTextarea(true); }; if (_msieVersion > 9 || !_autoUpdateRecommended) { _textareaEvents['input'] = function textareaOnInput() { updateTextarea(); } } else { _textareaEvents[_strKeyDownEvent] = function textareaOnKeyDown(event) { var keyCode = event.keyCode; if (FRAMEWORK.inArray(keyCode, textareaKeyDownRestrictedKeyCodes) > -1) return; if (!textareaKeyDownKeyCodesList.length) { updateTextarea(); textareaUpdateIntervalID = setInterval(updateTextarea, 1000 / 60); } if (FRAMEWORK.inArray(keyCode, textareaKeyDownKeyCodesList) === -1) textareaKeyDownKeyCodesList.push(keyCode); }; _textareaEvents[_strKeyUpEvent] = function(event) { var keyCode = event.keyCode; var index = FRAMEWORK.inArray(keyCode, textareaKeyDownKeyCodesList); if (FRAMEWORK.inArray(keyCode, textareaKeyDownRestrictedKeyCodes) > -1) return; if (index > -1) textareaKeyDownKeyCodesList.splice(index, 1); if (!textareaKeyDownKeyCodesList.length) updateTextarea(true); }; } } if (_isTextarea) { FRAMEWORK.each(_textareaEvents, function(key, value) { _targetElement[strOnOff](key, value); }); } else { _contentElement[strOnOff](_strTransitionEndEvent, function (event) { if (_autoUpdateCache === true) return; event = event.originalEvent || event; if (isSizeAffectingCSSProperty(event.propertyName)) update(_strAuto); }); } if(!destroy) { viewportOnScroll = function(event) { if (_isSleeping) return; if (scrollStopTimeoutId !== undefined) clearTimeout(scrollStopTimeoutId); else { if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(true); if (!nativeOverlayScrollbarsAreActive()) addClass(_hostElement, _classNameHostScrolling); dispatchCallback("onScrollStart", event); } //if a scrollbars handle gets dragged, the mousemove event is responsible for refreshing the handle offset //because if CSS scroll-snap is used, the handle offset gets only refreshed on every snap point //this looks laggy & clunky, it looks much better if the offset refreshes with the mousemove if(!_scrollbarsHandleAsync) { refreshScrollbarHandleOffset(true); refreshScrollbarHandleOffset(false); } dispatchCallback("onScroll", event); scrollStopTimeoutId = setTimeout(function () { if(!_destroyed) { //OnScrollStop: clearTimeout(scrollStopTimeoutId); scrollStopTimeoutId = undefined; if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(false); if (!nativeOverlayScrollbarsAreActive()) removeClass(_hostElement, _classNameHostScrolling); dispatchCallback("onScrollStop", event); } }, scrollStopDelay); }; if (_supportPassiveEvents) addPassiveEventListener(_viewportElement, _strScroll, viewportOnScroll); else _viewportElement.on(_strScroll, viewportOnScroll); } } //==== Scrollbars ====// /** * Builds or destroys all scrollbar DOM elements (scrollbar, track, handle) * @param destroy Indicates whether the DOM shall be build or destroyed. */ function setupScrollbarsDOM(destroy) { if(!destroy) { _scrollbarHorizontalElement = FRAMEWORK(generateDiv(_classNameScrollbar + _strSpace + _classNameScrollbarHorizontal)); _scrollbarHorizontalTrackElement = FRAMEWORK(generateDiv(_classNameScrollbarTrack)); _scrollbarHorizontalHandleElement = FRAMEWORK(generateDiv(_classNameScrollbarHandle)); _scrollbarVerticalElement = FRAMEWORK(generateDiv(_classNameScrollbar + _strSpace + _classNameScrollbarVertical)); _scrollbarVerticalTrackElement = FRAMEWORK(generateDiv(_classNameScrollbarTrack)); _scrollbarVerticalHandleElement = FRAMEWORK(generateDiv(_classNameScrollbarHandle)); _scrollbarHorizontalElement.append(_scrollbarHorizontalTrackElement); _scrollbarHorizontalTrackElement.append(_scrollbarHorizontalHandleElement); _scrollbarVerticalElement.append(_scrollbarVerticalTrackElement); _scrollbarVerticalTrackElement.append(_scrollbarVerticalHandleElement); _paddingElement.after(_scrollbarVerticalElement); _paddingElement.after(_scrollbarHorizontalElement); } else { remove(_scrollbarHorizontalElement); remove(_scrollbarVerticalElement); } } /** * Initializes all scrollbar interactivity events. (track and handle dragging, clicking, scrolling) * @param isHorizontal True if the target scrollbar is the horizontal scrollbar, false if the target scrollbar is the vertical scrollbar. */ function setupScrollbarEvents(isHorizontal) { var scrollbarVars = getScrollbarVars(isHorizontal); var scrollbarVarsInfo = scrollbarVars._info; var insideIFrame = _windowElementNative.top !== _windowElementNative; var xy = scrollbarVars._x_y; var XY = scrollbarVars._X_Y; var scroll = _strScroll + scrollbarVars._Left_Top; var strActive = 'active'; var strSnapHandle = 'snapHandle'; var scrollDurationFactor = 1; var increaseDecreaseScrollAmountKeyCodes = [ 16, 17 ]; //shift, ctrl var trackTimeout; var mouseDownScroll; var mouseDownOffset; var mouseDownInvertedScale; function getPointerPosition(event) { return _msieVersion && insideIFrame ? event['screen' + XY] : COMPATIBILITY.page(event)[xy]; //use screen coordinates in EDGE & IE because the page values are incorrect in frames. } function getPreparedScrollbarsOption(name) { return _currentPreparedOptions.scrollbars[name]; } function increaseTrackScrollAmount() { scrollDurationFactor = 0.5; } function decreaseTrackScrollAmount() { scrollDurationFactor = 1; } function documentKeyDown(event) { if (FRAMEWORK.inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1) increaseTrackScrollAmount(); } function documentKeyUp(event) { if (FRAMEWORK.inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1) decreaseTrackScrollAmount(); } function onMouseTouchDownContinue(event) { var originalEvent = event.originalEvent || event; var isTouchEvent = originalEvent.touches !== undefined; return _isSleeping || _destroyed || nativeOverlayScrollbarsAreActive() || !_scrollbarsDragScrollingCache || (isTouchEvent && !getPreparedScrollbarsOption('touchSupport')) ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent; } function documentDragMove(event) { if(onMouseTouchDownContinue(event)) { var trackLength = scrollbarVarsInfo._trackLength; var handleLength = scrollbarVarsInfo._handleLength; var scrollRange = scrollbarVarsInfo._maxScroll; var scrollRaw = (getPointerPosition(event) - mouseDownOffset) * mouseDownInvertedScale; var scrollDeltaPercent = scrollRaw / (trackLength - handleLength); var scrollDelta = (scrollRange * scrollDeltaPercent); scrollDelta = isFinite(scrollDelta) ? scrollDelta : 0; if (_isRTL && isHorizontal && !_rtlScrollBehavior.i) scrollDelta *= -1; _viewportElement[scroll](MATH.round(mouseDownScroll + scrollDelta)); if(_scrollbarsHandleAsync) refreshScrollbarHandleOffset(isHorizontal, mouseDownScroll + scrollDelta); if (!_supportPassiveEvents) COMPATIBILITY.prvD(event); } else documentMouseTouchUp(event); } function documentMouseTouchUp(event) { event = event || event.originalEvent; _documentElement.off(_strMouseTouchMoveEvent, documentDragMove) .off(_strMouseTouchUpEvent, documentMouseTouchUp) .off(_strKeyDownEvent, documentKeyDown) .off(_strKeyUpEvent, documentKeyUp) .off(_strSelectStartEvent, documentOnSelectStart); if(_scrollbarsHandleAsync) refreshScrollbarHandleOffset(isHorizontal, true); _scrollbarsHandleAsync = false; removeClass(_bodyElement, _classNameDragging); removeClass(scrollbarVars._handle, strActive); removeClass(scrollbarVars._track, strActive); removeClass(scrollbarVars._scrollbar, strActive); mouseDownScroll = undefined; mouseDownOffset = undefined; mouseDownInvertedScale = 1; decreaseTrackScrollAmount(); if (trackTimeout !== undefined) { _base.scrollStop(); clearTimeout(trackTimeout); trackTimeout = undefined; } if(event) { var rect = _hostElementNative.getBoundingClientRect(); var mouseInsideHost = event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom; //if mouse is outside host element if (!mouseInsideHost) hostOnMouseLeave(); if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(false); } } function onHandleMouseTouchDown(event) { mouseDownScroll = _viewportElement[scroll](); mouseDownScroll = isNaN(mouseDownScroll) ? 0 : mouseDownScroll; if (_isRTL && isHorizontal && !_rtlScrollBehavior.n || !_isRTL) mouseDownScroll = mouseDownScroll < 0 ? 0 : mouseDownScroll; mouseDownInvertedScale = getHostElementInvertedScale()[xy]; mouseDownOffset = getPointerPosition(event); _scrollbarsHandleAsync = !getPreparedScrollbarsOption(strSnapHandle); addClass(_bodyElement, _classNameDragging); addClass(scrollbarVars._handle, strActive); addClass(scrollbarVars._scrollbar, strActive); _documentElement.on(_strMouseTouchMoveEvent, documentDragMove) .on(_strMouseTouchUpEvent, documentMouseTouchUp) .on(_strSelectStartEvent, documentOnSelectStart); if(_msieVersion || !_documentMixed) COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); } scrollbarVars._handle.on(_strMouseTouchDownEvent, function(event) { if (onMouseTouchDownContinue(event)) onHandleMouseTouchDown(event); }); scrollbarVars._track.on(_strMouseTouchDownEvent, function(event) { if (onMouseTouchDownContinue(event)) { var scrollDistance = MATH.round(_viewportSize[scrollbarVars._w_h]); var trackOffset = scrollbarVars._track.offset()[scrollbarVars._left_top]; var ctrlKey = event.ctrlKey; var instantScroll = event.shiftKey; var instantScrollTransition = instantScroll && ctrlKey; var isFirstIteration = true; var easing = 'linear'; var decreaseScroll; var finishedCondition; var scrollActionFinsished = function(transition) { if(_scrollbarsHandleAsync) refreshScrollbarHandleOffset(isHorizontal, transition); }; var scrollActionInstantFinished = function() { scrollActionFinsished(); onHandleMouseTouchDown(event); }; var scrollAction = function () { if(!_destroyed) { var mouseOffset = (mouseDownOffset - trackOffset) * mouseDownInvertedScale; var handleOffset = scrollbarVarsInfo._handleOffset; var trackLength = scrollbarVarsInfo._trackLength; var handleLength = scrollbarVarsInfo._handleLength; var scrollRange = scrollbarVarsInfo._maxScroll; var currScroll = scrollbarVarsInfo._currentScroll; var scrollDuration = 270 * scrollDurationFactor; var timeoutDelay = isFirstIteration ? MATH.max(400, scrollDuration) : scrollDuration; var instantScrollPosition = scrollRange * ((mouseOffset - (handleLength / 2)) / (trackLength - handleLength)); // 100% * positionPercent var rtlIsNormal = _isRTL && isHorizontal && ((!_rtlScrollBehavior.i && !_rtlScrollBehavior.n) || _normalizeRTLCache); var decreaseScrollCondition = rtlIsNormal ? handleOffset < mouseOffset : handleOffset > mouseOffset; var scrollObj = { }; var animationObj = { easing : easing, step : function(now) { if(_scrollbarsHandleAsync) { _viewportElement[scroll](now); //https://github.com/jquery/jquery/issues/4340 refreshScrollbarHandleOffset(isHorizontal, now); } } }; instantScrollPosition = isFinite(instantScrollPosition) ? instantScrollPosition : 0; instantScrollPosition = _isRTL && isHorizontal && !_rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition; //_base.scrollStop(); if(instantScroll) { _viewportElement[scroll](instantScrollPosition); //scroll instantly to new position if(instantScrollTransition) { //get the scroll position after instant scroll (in case CSS Snap Points are used) to get the correct snapped scroll position //and the animation stops at the correct point instantScrollPosition = _viewportElement[scroll](); //scroll back to the position before instant scrolling so animation can be performed _viewportElement[scroll](currScroll); instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition; instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.n ? -instantScrollPosition : instantScrollPosition; scrollObj[xy] = instantScrollPosition; _base.scroll(scrollObj, extendDeep(animationObj, { duration : 130, complete : scrollActionInstantFinished })); } else scrollActionInstantFinished(); } else { decreaseScroll = isFirstIteration ? decreaseScrollCondition : decreaseScroll; finishedCondition = rtlIsNormal ? (decreaseScroll ? handleOffset + handleLength >= mouseOffset : handleOffset <= mouseOffset) : (decreaseScroll ? handleOffset <= mouseOffset : handleOffset + handleLength >= mouseOffset); if (finishedCondition) { clearTimeout(trackTimeout); _base.scrollStop(); trackTimeout = undefined; scrollActionFinsished(true); } else { trackTimeout = setTimeout(scrollAction, timeoutDelay); scrollObj[xy] = (decreaseScroll ? '-=' : '+=') + scrollDistance; _base.scroll(scrollObj, extendDeep(animationObj, { duration: scrollDuration })); } isFirstIteration = false; } } }; if (ctrlKey) increaseTrackScrollAmount(); mouseDownInvertedScale = getHostElementInvertedScale()[xy]; mouseDownOffset = COMPATIBILITY.page(event)[xy]; _scrollbarsHandleAsync = !getPreparedScrollbarsOption(strSnapHandle); addClass(_bodyElement, _classNameDragging); addClass(scrollbarVars._track, strActive); addClass(scrollbarVars._scrollbar, strActive); _documentElement.on(_strMouseTouchUpEvent, documentMouseTouchUp) .on(_strKeyDownEvent, documentKeyDown) .on(_strKeyUpEvent, documentKeyUp) .on(_strSelectStartEvent, documentOnSelectStart); scrollAction(); COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); } }).on(_strMouseTouchEnter, function() { //make sure both scrollbars will stay visible if one scrollbar is hovered if autoHide is "scroll" or "move". _scrollbarsHandleHovered = true; if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(true); }).on(_strMouseTouchLeave, function() { _scrollbarsHandleHovered = false; if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove) refreshScrollbarsAutoHide(false); }); scrollbarVars._scrollbar.on(_strMouseTouchDownEvent, function(event) { COMPATIBILITY.stpP(event); }); if (_supportTransition) { scrollbarVars._scrollbar.on(_strTransitionEndEvent, function(event) { if (event.target !== scrollbarVars._scrollbar[0]) return; refreshScrollbarHandleLength(isHorizontal); refreshScrollbarHandleOffset(isHorizontal); }); } } /** * Shows or hides the given scrollbar and applied a class name which indicates if the scrollbar is scrollable or not. * @param isHorizontal True if the horizontal scrollbar is the target, false if the vertical scrollbar is the target. * @param shallBeVisible True if the scrollbar shall be shown, false if hidden. * @param canScroll True if the scrollbar is scrollable, false otherwise. */ function refreshScrollbarAppearance(isHorizontal, shallBeVisible, canScroll) { var scrollbarClassName = isHorizontal ? _classNameHostScrollbarHorizontalHidden : _classNameHostScrollbarVerticalHidden; var scrollbarElement = isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement; if (shallBeVisible) removeClass(_hostElement, scrollbarClassName); else addClass(_hostElement, scrollbarClassName); if (canScroll) removeClass(scrollbarElement, _classNameScrollbarUnusable); else addClass(scrollbarElement, _classNameScrollbarUnusable); } /** * Autoshows / autohides both scrollbars with. * @param shallBeVisible True if the scrollbars shall be autoshown (only the case if they are hidden by a autohide), false if the shall be auto hidden. * @param delayfree True if the scrollbars shall be hidden without a delay, false or undefined otherwise. */ function refreshScrollbarsAutoHide(shallBeVisible, delayfree) { clearTimeout(_scrollbarsAutoHideTimeoutId); if (shallBeVisible) { //if(_hasOverflowCache.x && _hideOverflowCache.xs) removeClass(_scrollbarHorizontalElement, _classNameScrollbarAutoHidden); //if(_hasOverflowCache.y && _hideOverflowCache.ys) removeClass(_scrollbarVerticalElement, _classNameScrollbarAutoHidden); } else { var anyActive; var strActive = 'active'; var hide = function () { if (!_scrollbarsHandleHovered && !_destroyed) { anyActive = _scrollbarHorizontalHandleElement.hasClass(strActive) || _scrollbarVerticalHandleElement.hasClass(strActive); if (!anyActive && (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove || _scrollbarsAutoHideLeave)) addClass(_scrollbarHorizontalElement, _classNameScrollbarAutoHidden); if (!anyActive && (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove || _scrollbarsAutoHideLeave)) addClass(_scrollbarVerticalElement, _classNameScrollbarAutoHidden); } }; if (_scrollbarsAutoHideDelay > 0 && delayfree !== true) _scrollbarsAutoHideTimeoutId = setTimeout(hide, _scrollbarsAutoHideDelay); else hide(); } } /** * Refreshes the handle length of the given scrollbar. * @param isHorizontal True if the horizontal scrollbar handle shall be refreshed, false if the vertical one shall be refreshed. */ function refreshScrollbarHandleLength(isHorizontal) { var handleCSS = {}; var scrollbarVars = getScrollbarVars(isHorizontal); var scrollbarVarsInfo = scrollbarVars._info; var digit = 1000000; //get and apply intended handle length var handleRatio = MATH.min(1, (_hostSizeCache[scrollbarVars._w_h] - (_paddingAbsoluteCache ? (isHorizontal ? _paddingX : _paddingY) : 0)) / _contentScrollSizeCache[scrollbarVars._w_h]); handleCSS[scrollbarVars._width_height] = (MATH.floor(handleRatio * 100 * digit) / digit) + "%"; //the last * digit / digit is for flooring to the 4th digit if (!nativeOverlayScrollbarsAreActive()) scrollbarVars._handle.css(handleCSS); //measure the handle length to respect min & max length scrollbarVarsInfo._handleLength = scrollbarVars._handle[0]['offset' + scrollbarVars._Width_Height]; scrollbarVarsInfo._handleLengthRatio = handleRatio; } /** * Refreshes the handle offset of the given scrollbar. * @param isHorizontal True if the horizontal scrollbar handle shall be refreshed, false if the vertical one shall be refreshed. * @param scrollOrTransition The scroll position of the given scrollbar axis to which the handle shall be moved or a boolean which indicates whether a transition shall be applied. If undefined or boolean if the current scroll-offset is taken. (if isHorizontal ? scrollLeft : scrollTop) */ function refreshScrollbarHandleOffset(isHorizontal, scrollOrTransition) { var transition = type(scrollOrTransition) == TYPES.b; var transitionDuration = 250; var isRTLisHorizontal = _isRTL && isHorizontal; var scrollbarVars = getScrollbarVars(isHorizontal); var scrollbarVarsInfo = scrollbarVars._info; var strTranslateBrace = 'translate('; var strTransform = VENDORS._cssProperty('transform'); var strTransition = VENDORS._cssProperty('transition'); var nativeScroll = isHorizontal ? _viewportElement[_strScrollLeft]() : _viewportElement[_strScrollTop](); var currentScroll = scrollOrTransition === undefined || transition ? nativeScroll : scrollOrTransition; //measure the handle length to respect min & max length var handleLength = scrollbarVarsInfo._handleLength; var trackLength = scrollbarVars._track[0]['offset' + scrollbarVars._Width_Height]; var handleTrackDiff = trackLength - handleLength; var handleCSS = {}; var transformOffset; var translateValue; //DONT use the variable '_contentScrollSizeCache[scrollbarVars._w_h]' instead of '_viewportElement[0]['scroll' + scrollbarVars._Width_Height]' // because its a bit behind during the small delay when content size updates //(delay = mutationObserverContentLag, if its 0 then this var could be used) var maxScroll = (_viewportElementNative[_strScroll + scrollbarVars._Width_Height] - _viewportElementNative['client' + scrollbarVars._Width_Height]) * (_rtlScrollBehavior.n && isRTLisHorizontal ? -1 : 1); //* -1 if rtl scroll max is negative var getScrollRatio = function(base) { return isNaN(base / maxScroll) ? 0 : MATH.max(0, MATH.min(1, base / maxScroll)); }; var getHandleOffset = function(scrollRatio) { var offset = handleTrackDiff * scrollRatio; offset = isNaN(offset) ? 0 : offset; offset = (isRTLisHorizontal && !_rtlScrollBehavior.i) ? (trackLength - handleLength - offset) : offset; offset = MATH.max(0, offset); return offset; }; var scrollRatio = getScrollRatio(nativeScroll); var unsnappedScrollRatio = getScrollRatio(currentScroll); var handleOffset = getHandleOffset(unsnappedScrollRatio); var snappedHandleOffset = getHandleOffset(scrollRatio); scrollbarVarsInfo._maxScroll = maxScroll; scrollbarVarsInfo._currentScroll = nativeScroll; scrollbarVarsInfo._currentScrollRatio = scrollRatio; if (_supportTransform) { transformOffset = isRTLisHorizontal ? -(trackLength - handleLength - handleOffset) : handleOffset; //in px //transformOffset = (transformOffset / trackLength * 100) * (trackLength / handleLength); //in % translateValue = isHorizontal ? strTranslateBrace + transformOffset + 'px, 0)' : strTranslateBrace + '0, ' + transformOffset + 'px)'; handleCSS[strTransform] = translateValue; //apply or clear up transition if(_supportTransition) handleCSS[strTransition] = transition && MATH.abs(handleOffset - scrollbarVarsInfo._handleOffset) > 1 ? getCSSTransitionString(scrollbarVars._handle) + ', ' + (strTransform + _strSpace + transitionDuration + 'ms') : _strEmpty; } else handleCSS[scrollbarVars._left_top] = handleOffset; //only apply css if offset has changed and overflow exists. if (!nativeOverlayScrollbarsAreActive()) { scrollbarVars._handle.css(handleCSS); //clear up transition if(_supportTransform && _supportTransition && transition) { scrollbarVars._handle.one(_strTransitionEndEvent, function() { if(!_destroyed) scrollbarVars._handle.css(strTransition, _strEmpty); }); } } scrollbarVarsInfo._handleOffset = handleOffset; scrollbarVarsInfo._snappedHandleOffset = snappedHandleOffset; scrollbarVarsInfo._trackLength = trackLength; } /** * Refreshes the interactivity of the given scrollbar element. * @param isTrack True if the track element is the target, false if the handle element is the target. * @param value True for interactivity false for no interactivity. */ function refreshScrollbarsInteractive(isTrack, value) { var action = value ? 'removeClass' : 'addClass'; var element1 = isTrack ? _scrollbarHorizontalTrackElement : _scrollbarHorizontalHandleElement; var element2 = isTrack ? _scrollbarVerticalTrackElement : _scrollbarVerticalHandleElement; var className = isTrack ? _classNameScrollbarTrackOff : _classNameScrollbarHandleOff; element1[action](className); element2[action](className); } /** * Returns a object which is used for fast access for specific variables. * @param isHorizontal True if the horizontal scrollbar vars shall be accessed, false if the vertical scrollbar vars shall be accessed. * @returns {{wh: string, WH: string, lt: string, _wh: string, _lt: string, t: *, h: *, c: {}, s: *}} */ function getScrollbarVars(isHorizontal) { return { _width_height: isHorizontal ? _strWidth : _strHeight, _Width_Height: isHorizontal ? 'Width' : 'Height', _left_top: isHorizontal ? _strLeft : _strTop, _Left_Top: isHorizontal ? 'Left' : 'Top', _x_y: isHorizontal ? _strX : _strY, _X_Y: isHorizontal ? 'X' : 'Y', _w_h: isHorizontal ? 'w' : 'h', _l_t: isHorizontal ? 'l' : 't', _track: isHorizontal ? _scrollbarHorizontalTrackElement : _scrollbarVerticalTrackElement, _handle: isHorizontal ? _scrollbarHorizontalHandleElement : _scrollbarVerticalHandleElement, _scrollbar: isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement, _info: isHorizontal ? _scrollHorizontalInfo : _scrollVerticalInfo }; } //==== Scrollbar Corner ====// /** * Builds or destroys the scrollbar corner DOM element. * @param destroy Indicates whether the DOM shall be build or destroyed. */ function setupScrollbarCornerDOM(destroy) { if(!destroy) { _scrollbarCornerElement = FRAMEWORK(generateDiv(_classNameScrollbarCorner)); _hostElement.append(_scrollbarCornerElement); } else { remove(_scrollbarCornerElement); } } /** * Initializes all scrollbar corner interactivity events. */ function setupScrollbarCornerEvents() { var insideIFrame = _windowElementNative.top !== _windowElementNative; var mouseDownPosition = { }; var mouseDownSize = { }; var mouseDownInvertedScale = { }; _resizeOnMouseTouchDown = function(event) { if (onMouseTouchDownContinue(event)) { if (_mutationObserversConnected) { _resizeReconnectMutationObserver = true; disconnectMutationObservers(); } mouseDownPosition = getCoordinates(event); mouseDownSize.w = _hostElementNative[LEXICON.oW] - (!_isBorderBox ? _paddingX : 0); mouseDownSize.h = _hostElementNative[LEXICON.oH] - (!_isBorderBox ? _paddingY : 0); mouseDownInvertedScale = getHostElementInvertedScale(); _documentElement.on(_strSelectStartEvent, documentOnSelectStart) .on(_strMouseTouchMoveEvent, documentDragMove) .on(_strMouseTouchUpEvent, documentMouseTouchUp); addClass(_bodyElement, _classNameDragging); if (_scrollbarCornerElement.setCapture) _scrollbarCornerElement.setCapture(); COMPATIBILITY.prvD(event); COMPATIBILITY.stpP(event); } }; function documentDragMove(event) { if (onMouseTouchDownContinue(event)) { var pageOffset = getCoordinates(event); var hostElementCSS = { }; if (_resizeHorizontal || _resizeBoth) hostElementCSS[_strWidth] = (mouseDownSize.w + (pageOffset.x - mouseDownPosition.x) * mouseDownInvertedScale.x); if (_resizeVertical || _resizeBoth) hostElementCSS[_strHeight] = (mouseDownSize.h + (pageOffset.y - mouseDownPosition.y) * mouseDownInvertedScale.y); _hostElement.css(hostElementCSS); COMPATIBILITY.stpP(event); } else { documentMouseTouchUp(event); } } function documentMouseTouchUp(event) { var eventIsTrusted = event !== undefined; _documentElement.off(_strSelectStartEvent, documentOnSelectStart) .off(_strMouseTouchMoveEvent, documentDragMove) .off(_strMouseTouchUpEvent, documentMouseTouchUp); removeClass(_bodyElement, _classNameDragging); if (_scrollbarCornerElement.releaseCapture) _scrollbarCornerElement.releaseCapture(); if (eventIsTrusted) { if (_resizeReconnectMutationObserver) connectMutationObservers(); _base.update(_strAuto); } _resizeReconnectMutationObserver = false; } function onMouseTouchDownContinue(event) { var originalEvent = event.originalEvent || event; var isTouchEvent = originalEvent.touches !== undefined; return _isSleeping || _destroyed ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent; } function getCoordinates(event) { return _msieVersion && insideIFrame ? { x : event.screenX , y : event.screenY } : COMPATIBILITY.page(event); } } //==== Utils ====// /** * Calls the callback with the given name. The Context of this callback is always _base (this). * @param name The name of the target which shall be called. * @param args The args with which the callback shall be called. */ function dispatchCallback(name, args) { if(_initialized) { var callback = _currentPreparedOptions.callbacks[name]; var extensionOnName = name; var ext; if(extensionOnName.substr(0, 2) === "on") extensionOnName = extensionOnName.substr(2, 1).toLowerCase() + extensionOnName.substr(3); if(type(callback) == TYPES.f) callback.call(_base, args); FRAMEWORK.each(_extensions, function() { ext = this; if(type(ext.on) == TYPES.f) ext.on(extensionOnName, args); }); } else if(!_destroyed) _callbacksInitQeueue.push({ n : name, a : args }); } /** * Sets the "top, right, bottom, left" properties, with a given prefix, of the given css object. * @param targetCSSObject The css object to which the values shall be applied. * @param prefix The prefix of the "top, right, bottom, left" css properties. (example: 'padding-' is a valid prefix) * @param values A array of values which shall be applied to the "top, right, bottom, left" -properties. The array order is [top, right, bottom, left]. * If this argument is undefined the value '' (empty string) will be applied to all properties. */ function setTopRightBottomLeft(targetCSSObject, prefix, values) { if (values === undefined) values = [_strEmpty, _strEmpty, _strEmpty, _strEmpty]; targetCSSObject[prefix + _strTop] = values[0]; targetCSSObject[prefix + _strRight] = values[1]; targetCSSObject[prefix + _strBottom] = values[2]; targetCSSObject[prefix + _strLeft] = values[3]; } /** * Returns the computed CSS transition string from the given element. * @param element The element from which the transition string shall be returned. * @returns {string} The CSS transition string from the given element. */ function getCSSTransitionString(element) { var transitionStr = VENDORS._cssProperty('transition'); var assembledValue = element.css(transitionStr); if(assembledValue) return assembledValue; var regExpString = '\\s*(' + '([^,(]+(\\(.+?\\))?)+' + ')[\\s,]*'; var regExpMain = new RegExp(regExpString); var regExpValidate = new RegExp('^(' + regExpString + ')+$'); var properties = 'property duration timing-function delay'.split(' '); var result = [ ]; var strResult; var valueArray; var i = 0; var j; var splitCssStyleByComma = function(str) { strResult = [ ]; if (!str.match(regExpValidate)) return str; while (str.match(regExpMain)) { strResult.push(RegExp.$1); str = str.replace(regExpMain, _strEmpty); } return strResult; }; for (; i < properties[LEXICON.l]; i++) { valueArray = splitCssStyleByComma(element.css(transitionStr + '-' + properties[i])); for (j = 0; j < valueArray[LEXICON.l]; j++) result[j] = (result[j] ? result[j] + _strSpace : _strEmpty) + valueArray[j]; } return result.join(', '); } /** * Calculates the host-elements inverted scale. (invertedScale = 1 / scale) * @returns {{x: number, y: number}} The scale of the host-element. */ function getHostElementInvertedScale() { var rect = _paddingElementNative.getBoundingClientRect(); return { x : _supportTransform ? 1 / (MATH.round(rect.width) / _paddingElementNative[LEXICON.oW]) || 1 : 1, y : _supportTransform ? 1 / (MATH.round(rect.height) / _paddingElementNative[LEXICON.oH]) || 1 : 1 }; } /** * Checks whether the given object is a HTMLElement. * @param o The object which shall be checked. * @returns {boolean} True the given object is a HTMLElement, false otherwise. */ function isHTMLElement(o) { var strOwnerDocument = 'ownerDocument'; var strHTMLElement = 'HTMLElement'; var wnd = o && o[strOwnerDocument] ? (o[strOwnerDocument].parentWindow || window) : window; return ( typeof wnd[strHTMLElement] == TYPES.o ? o instanceof wnd[strHTMLElement] : //DOM2 o && typeof o == TYPES.o && o !== null && o.nodeType === 1 && typeof o.nodeName == TYPES.s ); } /** * Compares 2 arrays and returns the differences between them as a array. * @param a1 The first array which shall be compared. * @param a2 The second array which shall be compared. * @returns {Array} The differences between the two arrays. */ function getArrayDifferences(a1, a2) { var a = [ ]; var diff = [ ]; var i; var k; for (i = 0; i < a1.length; i++) a[a1[i]] = true; for (i = 0; i < a2.length; i++) { if (a[a2[i]]) delete a[a2[i]]; else a[a2[i]] = true; } for (k in a) diff.push(k); return diff; } /** * Returns Zero or the number to which the value can be parsed. * @param value The value which shall be parsed. * @param toFloat Indicates whether the number shall be parsed to a float. */ function parseToZeroOrNumber(value, toFloat) { var num = toFloat ? parseFloat(value) : parseInt(value, 10); return isNaN(num) ? 0 : num; } /** * Gets several information of the textarea and returns them as a object or undefined if the browser doesn't support it. * @returns {{cursorRow: Number, cursorCol, rows: Number, cols: number, wRow: number, pos: number, max : number}} or undefined if not supported. */ function getTextareaInfo() { //read needed values var textareaCursorPosition = _targetElementNative.selectionStart; if (textareaCursorPosition === undefined) return; var strLength = 'length'; var textareaValue = _targetElement.val(); var textareaLength = textareaValue[strLength]; var textareaRowSplit = textareaValue.split("\n"); var textareaLastRow = textareaRowSplit[strLength]; var textareaCurrentCursorRowSplit = textareaValue.substr(0, textareaCursorPosition).split("\n"); var widestRow = 0; var textareaLastCol = 0; var cursorRow = textareaCurrentCursorRowSplit[strLength]; var cursorCol = textareaCurrentCursorRowSplit[textareaCurrentCursorRowSplit[strLength] - 1][strLength]; var rowCols; var i; //get widest Row and the last column of the textarea for (i = 0; i < textareaRowSplit[strLength]; i++) { rowCols = textareaRowSplit[i][strLength]; if (rowCols > textareaLastCol) { widestRow = i + 1; textareaLastCol = rowCols; } } return { _cursorRow: cursorRow, //cursorRow _cursorColumn: cursorCol, //cursorCol _rows: textareaLastRow, //rows _columns: textareaLastCol, //cols _widestRow: widestRow, //wRow _cursorPosition: textareaCursorPosition, //pos _cursorMax: textareaLength //max }; } /** * Determines whether native overlay scrollbars are active. * @returns {boolean} True if native overlay scrollbars are active, false otherwise. */ function nativeOverlayScrollbarsAreActive() { return (_ignoreOverlayScrollbarHidingCache && (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)); } /** * Gets the element which is used to measure the content size. * @returns {*} TextareaCover if target element is textarea else the ContentElement. */ function getContentMeasureElement() { return _isTextarea ? _textareaCoverElement[0] : _contentElementNative; } /** * Generates a string which represents a HTML div with the given classes or attributes. * @param classesOrAttrs The class of the div as string or a object which represents the attributes of the div. (The class attribute can also be written as "className".) * @param content The content of the div as string. * @returns {string} The concated string which represents a HTML div and its content. */ function generateDiv(classesOrAttrs, content) { return '<div ' + (classesOrAttrs ? type(classesOrAttrs) == TYPES.s ? 'class="' + classesOrAttrs + '"' : (function() { var key; var attrs = ''; if(FRAMEWORK.isPlainObject(classesOrAttrs)) { for (key in classesOrAttrs) attrs += (key === 'className' ? 'class' : key) + '="' + classesOrAttrs[key] + '" '; } return attrs; })() : _strEmpty) + '>' + (content ? content : _strEmpty) + '</div>'; } /** * Gets the value of the given property from the given object. * @param obj The object from which the property value shall be got. * @param path The property of which the value shall be got. * @returns {*} Returns the value of the searched property or undefined of the property wasn't found. */ function getObjectPropVal(obj, path) { var splits = path.split(_strDot); var i = 0; var val; for(; i < splits.length; i++) { if(!obj.hasOwnProperty(splits[i])) return; val = obj[splits[i]]; if(i < splits.length && type(val) == TYPES.o) obj = val; } return val; } /** * Sets the value of the given property from the given object. * @param obj The object from which the property value shall be set. * @param path The property of which the value shall be set. * @param val The value of the property which shall be set. */ function setObjectPropVal(obj, path, val) { var splits = path.split(_strDot); var splitsLength = splits.length; var i = 0; var extendObj = { }; var extendObjRoot = extendObj; for(; i < splitsLength; i++) extendObj = extendObj[splits[i]] = i + 1 < splitsLength ? { } : val; FRAMEWORK.extend(obj, extendObjRoot, true); } //==== Utils Cache ====// /** * Compares two values and returns the result of the comparison as a boolean. * @param current The first value which shall be compared. * @param cache The second value which shall be compared. * @param force If true the returned value is always true. * @returns {boolean} True if both variables aren't equal or some of them is undefined or when the force parameter is true, false otherwise. */ function checkCacheSingle(current, cache, force) { if (force === true) return force; if (cache === undefined) return true; else if (current !== cache) return true; return false; } /** * Compares two objects with two properties and returns the result of the comparison as a boolean. * @param current The first object which shall be compared. * @param cache The second object which shall be compared. * @param prop1 The name of the first property of the objects which shall be compared. * @param prop2 The name of the second property of the objects which shall be compared. * @param force If true the returned value is always true. * @returns {boolean} True if both variables aren't equal or some of them is undefined or when the force parameter is true, false otherwise. */ function checkCacheDouble(current, cache, prop1, prop2, force) { if (force === true) return force; if (prop2 === undefined && force === undefined) { if (prop1 === true) return prop1; else prop1 = undefined; } prop1 = prop1 === undefined ? 'w' : prop1; prop2 = prop2 === undefined ? 'h' : prop2; if (cache === undefined) return true; else if (current[prop1] !== cache[prop1] || current[prop2] !== cache[prop2]) return true; return false; } /** * Compares two objects which have four properties and returns the result of the comparison as a boolean. * @param current The first object with four properties. * @param cache The second object with four properties. * @returns {boolean} True if both objects aren't equal or some of them is undefined, false otherwise. */ function checkCacheTRBL(current, cache) { if (cache === undefined) return true; else if (current.t !== cache.t || current.r !== cache.r || current.b !== cache.b || current.l !== cache.l) return true; return false; } //==== Shortcuts ====// /** * jQuery type method shortcut. */ function type(obj) { return COMPATIBILITY.type(obj); } /** * jQuery extend method shortcut with a appended "true" as first argument. */ function extendDeep() { return FRAMEWORK.extend.apply(this, [ true ].concat([].slice.call(arguments))); } /** * jQuery addClass method shortcut. */ function addClass(el, classes) { return _frameworkProto.addClass.call(el, classes); } /** * jQuery removeClass method shortcut. */ function removeClass(el, classes) { return _frameworkProto.removeClass.call(el, classes); } /** * jQuery remove method shortcut. */ function remove(el) { return _frameworkProto.remove.call(el); } /** * Finds the first child element with the given selector of the given element. * @param el The root element from which the selector shall be valid. * @param selector The selector of the searched element. * @returns {*} The first element which is a child of the given element and matches the givens selector. */ function findFirst(el, selector) { return _frameworkProto.find.call(el, selector).eq(0); } //==== API ====// /** * Puts the instance to sleep. It wont respond to any changes in the DOM and won't update. Scrollbar Interactivity is also disabled as well as the resize handle. * This behavior can be reset by calling the update method. */ _base.sleep = function () { _isSleeping = true; }; /** * Updates the plugin and DOM to the current options. * This method should only be called if a update is 100% required. * @param force True if every property shall be updated and the cache shall be ignored. * !INTERNAL USAGE! : force can be a string "auto", "auto+" or "zoom" too * if this is the case then before a real update the content size and host element attributes gets checked, and if they changed only then the update method will be called. */ _base.update = function (force) { var attrsChanged; var contentSizeC; var isString = type(force) == TYPES.s; var imgElementSelector = 'img'; var imgElementLoadEvent = 'load'; if(isString) { if (force === _strAuto) { attrsChanged = meaningfulAttrsChanged(); contentSizeC = updateAutoContentSizeChanged(); if (attrsChanged || contentSizeC) update(false, contentSizeC, false); } else if (force === 'zoom') update(true, true); } else if(!synchronizeMutationObservers() || force) { force = _isSleeping || force; _isSleeping = false; update(false, false, force, true); } if(!_isTextarea) { _contentElement.find(imgElementSelector).each(function(i, el) { var index = COMPATIBILITY.inA(el, _imgs); if (index === -1) FRAMEWORK(el).off(imgElementLoadEvent, imgOnLoad).on(imgElementLoadEvent, imgOnLoad); }); } }; /** Gets or sets the current options. The update method will be called automatically if new options were set. * @param newOptions If new options are given, then the new options will be set, if new options aren't given (undefined or a not a plain object) then the current options will be returned. * @param value If new options is a property path string, then this value will be used to set the option to which the property path string leads. * @returns {*} */ _base.options = function (newOptions, value) { //return current options if newOptions are undefined or empty if (FRAMEWORK.isEmptyObject(newOptions) || !FRAMEWORK.isPlainObject(newOptions)) { if (type(newOptions) == TYPES.s) { if (arguments.length > 1) { var option = { }; setObjectPropVal(option, newOptions, value); setOptions(option); update(); return; } else return getObjectPropVal(_currentOptions, newOptions); } else return _currentOptions; } setOptions(newOptions); var isSleepingTmp = _isSleeping || false; _isSleeping = false; update(); _isSleeping = isSleepingTmp; }; /** * Restore the DOM, disconnects all observers, remove all resize observers and destroy all methods. */ _base.destroy = function () { _destroyed = true; //remove this instance from auto update loop autoUpdateLoop.remove(_base); //disconnect all mutation observers disconnectMutationObservers(); //remove all resize observers removeResizeObserver(_sizeObserverElement); if (_sizeAutoObserverAdded) removeResizeObserver(_sizeAutoObserverElement); //remove all extensions for(var extName in _extensions) _base.removeExt(extName); //remove all events from host element setupHostMouseTouchEvents(true); //remove all events from structure setupStructureEvents(true); //remove all helper / detection elements if (_contentGlueElement) remove(_contentGlueElement); if (_contentArrangeElement) remove(_contentArrangeElement); if (_sizeAutoObserverAdded) remove(_sizeAutoObserverElement); //remove all generated DOM setupScrollbarsDOM(true); setupScrollbarCornerDOM(true); setupStructureDOM(true); //remove all generated image load events for(var i = 0; i < _imgs[LEXICON.l]; i++) FRAMEWORK(_imgs[i]).off('load', imgOnLoad); _imgs = undefined; //remove this instance from the instances list INSTANCES(pluginTargetElement, 0); dispatchCallback("onDestroyed"); //remove all properties and methods for (var property in _base) delete _base[property]; _base = undefined; }; /** * Scrolls to a given position or element. * @param coordinates * 1. Can be "coordinates" which looks like: * { x : ?, y : ? } OR Object with x and y properties * { left : ?, top : ? } OR Object with left and top properties * { l : ?, t : ? } OR Object with l and t properties * [ ?, ? ] OR Array where the first two element are the coordinates (first is x, second is y) * ? A single value which stays for both axis * A value can be a number, a string or a calculation. * * Operators: * [NONE] The current scroll will be overwritten by the value. * '+=' The value will be added to the current scroll offset * '-=' The value will be subtracted from the current scroll offset * '*=' The current scroll wil be multiplicated by the value. * '/=' The current scroll wil be divided by the value. * * Units: * [NONE] The value is the final scroll amount. final = (value * 1) * 'px' Same as none * '%' The value is dependent on the current scroll value. final = ((currentScrollValue / 100) * value) * 'vw' The value is multiplicated by the viewport width. final = (value * viewportWidth) * 'vh' The value is multiplicated by the viewport height. final = (value * viewportHeight) * * example final values: * 200, '200px', '50%', '1vw', '1vh', '+=200', '/=1vw', '*=2px', '-=5vh', '+=33%', '+= 50% - 2px', '-= 1vw - 50%' * * 2. Can be a HTML or jQuery element: * The final scroll offset is the offset (without margin) of the given HTML / jQuery element. * * 3. Can be a object with a HTML or jQuery element with additional settings: * { * el : [HTMLElement, jQuery element], MUST be specified, else this object isn't valid. * scroll : [string, array, object], Default value is 'always'. * block : [string, array, object], Default value is 'begin'. * margin : [number, boolean, array, object] Default value is false. * } * * Possible scroll settings are: * 'always' Scrolls always. * 'ifneeded' Scrolls only if the element isnt fully in view. * 'never' Scrolls never. * * Possible block settings are: * 'begin' Both axis shall be docked to the "begin" edge. - The element will be docked to the top and left edge of the viewport. * 'end' Both axis shall be docked to the "end" edge. - The element will be docked to the bottom and right edge of the viewport. (If direction is RTL to the bottom and left edge.) * 'center' Both axis shall be docked to "center". - The element will be centered in the viewport. * 'nearest' The element will be docked to the nearest edge(s). * * Possible margin settings are: -- The actual margin of the element wont be affect, this option affects only the final scroll offset. * [BOOLEAN] If true the css margin of the element will be used, if false no margin will be used. * [NUMBER] The margin will be used for all edges. * * @param duration The duration of the scroll animation, OR a jQuery animation configuration object. * @param easing The animation easing. * @param complete The animation complete callback. * @returns {{ * position: {x: number, y: number}, * ratio: {x: number, y: number}, * max: {x: number, y: number}, * handleOffset: {x: number, y: number}, * handleLength: {x: number, y: number}, * handleLengthRatio: {x: number, y: number}, t * rackLength: {x: number, y: number}, * isRTL: boolean, * isRTLNormalized: boolean * }} */ _base.scroll = function (coordinates, duration, easing, complete) { if (arguments.length === 0 || coordinates === undefined) { var infoX = _scrollHorizontalInfo; var infoY = _scrollVerticalInfo; var normalizeInvert = _normalizeRTLCache && _isRTL && _rtlScrollBehavior.i; var normalizeNegate = _normalizeRTLCache && _isRTL && _rtlScrollBehavior.n; var scrollX = infoX._currentScroll; var scrollXRatio = infoX._currentScrollRatio; var maxScrollX = infoX._maxScroll; scrollXRatio = normalizeInvert ? 1 - scrollXRatio : scrollXRatio; scrollX = normalizeInvert ? maxScrollX - scrollX : scrollX; scrollX *= normalizeNegate ? -1 : 1; maxScrollX *= normalizeNegate ? -1 : 1; return { position : { x : scrollX, y : infoY._currentScroll }, ratio : { x : scrollXRatio, y : infoY._currentScrollRatio }, max : { x : maxScrollX, y : infoY._maxScroll }, handleOffset : { x : infoX._handleOffset, y : infoY._handleOffset }, handleLength : { x : infoX._handleLength, y : infoY._handleLength }, handleLengthRatio : { x : infoX._handleLengthRatio, y : infoY._handleLengthRatio }, trackLength : { x : infoX._trackLength, y : infoY._trackLength }, snappedHandleOffset : { x : infoX._snappedHandleOffset, y : infoY._snappedHandleOffset }, isRTL: _isRTL, isRTLNormalized: _normalizeRTLCache }; } synchronizeMutationObservers(); var normalizeRTL = _normalizeRTLCache; var coordinatesXAxisProps = [_strX, _strLeft, 'l']; var coordinatesYAxisProps = [_strY, _strTop, 't']; var coordinatesOperators = ['+=', '-=', '*=', '/=']; var durationIsObject = type(duration) == TYPES.o; var completeCallback = durationIsObject ? duration.complete : complete; var i; var finalScroll = { }; var specialEasing = {}; var doScrollLeft; var doScrollTop; var animationOptions; var strEnd = 'end'; var strBegin = 'begin'; var strCenter = 'center'; var strNearest = 'nearest'; var strAlways = 'always'; var strNever = 'never'; var strIfNeeded = 'ifneeded'; var strLength = LEXICON.l; var settingsAxis; var settingsScroll; var settingsBlock; var settingsMargin; var finalElement; var elementObjSettingsAxisValues = [_strX, _strY, 'xy', 'yx']; var elementObjSettingsBlockValues = [strBegin, strEnd, strCenter, strNearest]; var elementObjSettingsScrollValues = [strAlways, strNever, strIfNeeded]; var coordinatesIsElementObj = coordinates.hasOwnProperty('el'); var possibleElement = coordinatesIsElementObj ? coordinates.el : coordinates; var possibleElementIsJQuery = possibleElement instanceof FRAMEWORK || JQUERY ? possibleElement instanceof JQUERY : false; var possibleElementIsHTMLElement = possibleElementIsJQuery ? false : isHTMLElement(possibleElement); var proxyCompleteCallback = type(completeCallback) != TYPES.f ? undefined : function() { if(doScrollLeft) refreshScrollbarHandleOffset(true); if(doScrollTop) refreshScrollbarHandleOffset(false); completeCallback(); }; var checkSettingsStringValue = function (currValue, allowedValues) { for (i = 0; i < allowedValues[strLength]; i++) { if (currValue === allowedValues[i]) return true; } return false; }; var getRawScroll = function (isX, coordinates) { var coordinateProps = isX ? coordinatesXAxisProps : coordinatesYAxisProps; coordinates = type(coordinates) == TYPES.s || type(coordinates) == TYPES.n ? [ coordinates, coordinates ] : coordinates; if (type(coordinates) == TYPES.a) return isX ? coordinates[0] : coordinates[1]; else if (type(coordinates) == TYPES.o) { //decides RTL normalization "hack" with .n //normalizeRTL = type(coordinates.n) == TYPES.b ? coordinates.n : normalizeRTL; for (i = 0; i < coordinateProps[strLength]; i++) if (coordinateProps[i] in coordinates) return coordinates[coordinateProps[i]]; } }; var getFinalScroll = function (isX, rawScroll) { var isString = type(rawScroll) == TYPES.s; var operator; var amount; var scrollInfo = isX ? _scrollHorizontalInfo : _scrollVerticalInfo; var currScroll = scrollInfo._currentScroll; var maxScroll = scrollInfo._maxScroll; var mult = ' * '; var finalValue; var isRTLisX = _isRTL && isX; var normalizeShortcuts = isRTLisX && _rtlScrollBehavior.n && !normalizeRTL; var strReplace = 'replace'; var evalFunc = eval; var possibleOperator; if (isString) { //check operator if (rawScroll[strLength] > 2) { possibleOperator = rawScroll.substr(0, 2); if(FRAMEWORK.inArray(possibleOperator, coordinatesOperators) > -1) operator = possibleOperator; } //calculate units and shortcuts rawScroll = operator ? rawScroll.substr(2) : rawScroll; rawScroll = rawScroll [strReplace](/min/g, 0) //'min' = 0% [strReplace](/</g, 0) //'<' = 0% [strReplace](/max/g, (normalizeShortcuts ? '-' : _strEmpty) + _strHundredPercent) //'max' = 100% [strReplace](/>/g, (normalizeShortcuts ? '-' : _strEmpty) + _strHundredPercent) //'>' = 100% [strReplace](/px/g, _strEmpty) [strReplace](/%/g, mult + (maxScroll * (isRTLisX && _rtlScrollBehavior.n ? -1 : 1) / 100.0)) [strReplace](/vw/g, mult + _viewportSize.w) [strReplace](/vh/g, mult + _viewportSize.h); amount = parseToZeroOrNumber(isNaN(rawScroll) ? parseToZeroOrNumber(evalFunc(rawScroll), true).toFixed() : rawScroll); } else { amount = rawScroll; } if (amount !== undefined && !isNaN(amount) && type(amount) == TYPES.n) { var normalizeIsRTLisX = normalizeRTL && isRTLisX; var operatorCurrScroll = currScroll * (normalizeIsRTLisX && _rtlScrollBehavior.n ? -1 : 1); var invert = normalizeIsRTLisX && _rtlScrollBehavior.i; var negate = normalizeIsRTLisX && _rtlScrollBehavior.n; operatorCurrScroll = invert ? (maxScroll - operatorCurrScroll) : operatorCurrScroll; switch (operator) { case '+=': finalValue = operatorCurrScroll + amount; break; case '-=': finalValue = operatorCurrScroll - amount; break; case '*=': finalValue = operatorCurrScroll * amount; break; case '/=': finalValue = operatorCurrScroll / amount; break; default: finalValue = amount; break; } finalValue = invert ? maxScroll - finalValue : finalValue; finalValue *= negate ? -1 : 1; finalValue = isRTLisX && _rtlScrollBehavior.n ? MATH.min(0, MATH.max(maxScroll, finalValue)) : MATH.max(0, MATH.min(maxScroll, finalValue)); } return finalValue === currScroll ? undefined : finalValue; }; var getPerAxisValue = function (value, valueInternalType, defaultValue, allowedValues) { var resultDefault = [ defaultValue, defaultValue ]; var valueType = type(value); var valueArrLength; var valueArrItem; //value can be [ string, or array of two strings ] if (valueType == valueInternalType) { value = [value, value]; } else if (valueType == TYPES.a) { valueArrLength = value[strLength]; if (valueArrLength > 2 || valueArrLength < 1) value = resultDefault; else { if (valueArrLength === 1) value[1] = defaultValue; for (i = 0; i < valueArrLength; i++) { valueArrItem = value[i]; if (type(valueArrItem) != valueInternalType || !checkSettingsStringValue(valueArrItem, allowedValues)) { value = resultDefault; break; } } } } else if (valueType == TYPES.o) value = [ value[_strX]|| defaultValue, value[_strY] || defaultValue]; else value = resultDefault; return { x : value[0], y : value[1] }; }; var generateMargin = function (marginTopRightBottomLeftArray) { var result = [ ]; var currValue; var currValueType; var valueDirections = [ _strTop, _strRight, _strBottom, _strLeft ]; for(i = 0; i < marginTopRightBottomLeftArray[strLength]; i++) { if(i === valueDirections[strLength]) break; currValue = marginTopRightBottomLeftArray[i]; currValueType = type(currValue); if(currValueType == TYPES.b) result.push(currValue ? parseToZeroOrNumber(finalElement.css(_strMarginMinus + valueDirections[i])) : 0); else result.push(currValueType == TYPES.n ? currValue : 0); } return result; }; if (possibleElementIsJQuery || possibleElementIsHTMLElement) { //get settings var margin = coordinatesIsElementObj ? coordinates.margin : 0; var axis = coordinatesIsElementObj ? coordinates.axis : 0; var scroll = coordinatesIsElementObj ? coordinates.scroll : 0; var block = coordinatesIsElementObj ? coordinates.block : 0; var marginDefault = [ 0, 0, 0, 0 ]; var marginType = type(margin); var marginLength; finalElement = possibleElementIsJQuery ? possibleElement : FRAMEWORK(possibleElement); if (finalElement[strLength] === 0) return; //margin can be [ boolean, number, array of 2, array of 4, object ] if (marginType == TYPES.n || marginType == TYPES.b) margin = generateMargin([margin, margin, margin, margin]); else if (marginType == TYPES.a) { marginLength = margin[strLength]; if(marginLength === 2) margin = generateMargin([margin[0], margin[1], margin[0], margin[1]]); else if(marginLength >= 4) margin = generateMargin(margin); else margin = marginDefault; } else if (marginType == TYPES.o) margin = generateMargin([margin[_strTop], margin[_strRight], margin[_strBottom], margin[_strLeft]]); else margin = marginDefault; //block = type(block) === TYPES.b ? block ? [ strNearest, strBegin ] : [ strNearest, strEnd ] : block; settingsAxis = checkSettingsStringValue(axis, elementObjSettingsAxisValues) ? axis : 'xy'; settingsScroll = getPerAxisValue(scroll, TYPES.s, strAlways, elementObjSettingsScrollValues); settingsBlock = getPerAxisValue(block, TYPES.s, strBegin, elementObjSettingsBlockValues); settingsMargin = margin; var viewportScroll = { l: _scrollHorizontalInfo._currentScroll, t: _scrollVerticalInfo._currentScroll }; // use padding element instead of viewport element because padding element has never padding, margin or position applied. var viewportOffset = _paddingElement.offset(); //get coordinates var elementOffset = finalElement.offset(); var doNotScroll = { x : settingsScroll.x == strNever || settingsAxis == _strY, y : settingsScroll.y == strNever || settingsAxis == _strX }; elementOffset[_strTop] -= settingsMargin[0]; elementOffset[_strLeft] -= settingsMargin[3]; var elementScrollCoordinates = { x: MATH.round(elementOffset[_strLeft] - viewportOffset[_strLeft] + viewportScroll.l), y: MATH.round(elementOffset[_strTop] - viewportOffset[_strTop] + viewportScroll.t) }; if (_isRTL) { if (!_rtlScrollBehavior.n && !_rtlScrollBehavior.i) elementScrollCoordinates.x = MATH.round(viewportOffset[_strLeft] - elementOffset[_strLeft] + viewportScroll.l); if (_rtlScrollBehavior.n && normalizeRTL) elementScrollCoordinates.x *= -1; if (_rtlScrollBehavior.i && normalizeRTL) elementScrollCoordinates.x = MATH.round(viewportOffset[_strLeft] - elementOffset[_strLeft] + (_scrollHorizontalInfo._maxScroll - viewportScroll.l)); } //measuring is required if (settingsBlock.x != strBegin || settingsBlock.y != strBegin || settingsScroll.x == strIfNeeded || settingsScroll.y == strIfNeeded || _isRTL) { var measuringElm = finalElement[0]; var rawElementSize = _supportTransform ? measuringElm.getBoundingClientRect() : { width : measuringElm[LEXICON.oW], height : measuringElm[LEXICON.oH] }; var elementSize = { w: rawElementSize[_strWidth] + settingsMargin[3] + settingsMargin[1], h: rawElementSize[_strHeight] + settingsMargin[0] + settingsMargin[2] }; var finalizeBlock = function(isX) { var vars = getScrollbarVars(isX); var wh = vars._w_h; var lt = vars._left_top; var xy = vars._x_y; var blockIsEnd = settingsBlock[xy] == (isX ? _isRTL ? strBegin : strEnd : strEnd); var blockIsCenter = settingsBlock[xy] == strCenter; var blockIsNearest = settingsBlock[xy] == strNearest; var scrollNever = settingsScroll[xy] == strNever; var scrollIfNeeded = settingsScroll[xy] == strIfNeeded; var vpSize = _viewportSize[wh]; var vpOffset = viewportOffset[lt]; var elSize = elementSize[wh]; var elOffset = elementOffset[lt]; var divide = blockIsCenter ? 2 : 1; var elementCenterOffset = elOffset + (elSize / 2); var viewportCenterOffset = vpOffset + (vpSize / 2); var isInView = elSize <= vpSize && elOffset >= vpOffset && elOffset + elSize <= vpOffset + vpSize; if(scrollNever) doNotScroll[xy] = true; else if(!doNotScroll[xy]) { if (blockIsNearest || scrollIfNeeded) { doNotScroll[xy] = scrollIfNeeded ? isInView : false; blockIsEnd = elSize < vpSize ? elementCenterOffset > viewportCenterOffset : elementCenterOffset < viewportCenterOffset; } elementScrollCoordinates[xy] -= blockIsEnd || blockIsCenter ? ((vpSize / divide) - (elSize / divide)) * (isX && _isRTL && normalizeRTL ? -1 : 1) : 0; } }; finalizeBlock(true); finalizeBlock(false); } if (doNotScroll.y) delete elementScrollCoordinates.y; if (doNotScroll.x) delete elementScrollCoordinates.x; coordinates = elementScrollCoordinates; } finalScroll[_strScrollLeft] = getFinalScroll(true, getRawScroll(true, coordinates)); finalScroll[_strScrollTop] = getFinalScroll(false, getRawScroll(false, coordinates)); doScrollLeft = finalScroll[_strScrollLeft] !== undefined; doScrollTop = finalScroll[_strScrollTop] !== undefined; if ((doScrollLeft || doScrollTop) && (duration > 0 || durationIsObject)) { if (durationIsObject) { duration.complete = proxyCompleteCallback; _viewportElement.animate(finalScroll, duration); } else { animationOptions = { duration: duration, complete: proxyCompleteCallback }; if (type(easing) == TYPES.a || FRAMEWORK.isPlainObject(easing)) { specialEasing[_strScrollLeft] = easing[0] || easing.x; specialEasing[_strScrollTop] = easing[1] || easing.y; animationOptions.specialEasing = specialEasing; } else { animationOptions.easing = easing; } _viewportElement.animate(finalScroll, animationOptions); } } else { if (doScrollLeft) _viewportElement[_strScrollLeft](finalScroll[_strScrollLeft]); if (doScrollTop) _viewportElement[_strScrollTop](finalScroll[_strScrollTop]); } }; /** * Stops all scroll animations. * @returns {*} The current OverlayScrollbars instance (for chaining). */ _base.scrollStop = function (param1, param2, param3) { _viewportElement.stop(param1, param2, param3); return _base; }; /** * Returns all relevant elements. * @param elementName The name of the element which shall be returned. * @returns {{target: *, host: *, padding: *, viewport: *, content: *, scrollbarHorizontal: {scrollbar: *, track: *, handle: *}, scrollbarVertical: {scrollbar: *, track: *, handle: *}, scrollbarCorner: *} | *} */ _base.getElements = function (elementName) { var obj = { target: _targetElementNative, host: _hostElementNative, padding: _paddingElementNative, viewport: _viewportElementNative, content: _contentElementNative, scrollbarHorizontal: { scrollbar: _scrollbarHorizontalElement[0], track: _scrollbarHorizontalTrackElement[0], handle: _scrollbarHorizontalHandleElement[0] }, scrollbarVertical: { scrollbar: _scrollbarVerticalElement[0], track: _scrollbarVerticalTrackElement[0], handle: _scrollbarVerticalHandleElement[0] }, scrollbarCorner: _scrollbarCornerElement[0] }; return type(elementName) == TYPES.s ? getObjectPropVal(obj, elementName) : obj; }; /** * Returns a object which describes the current state of this instance. * @param stateProperty A specific property from the state object which shall be returned. * @returns {{widthAuto, heightAuto, overflowAmount, hideOverflow, hasOverflow, contentScrollSize, viewportSize, hostSize, autoUpdate} | *} */ _base.getState = function (stateProperty) { var prepare = function (obj) { if (!FRAMEWORK.isPlainObject(obj)) return obj; var extended = extendDeep({}, obj); var changePropertyName = function (from, to) { if (extended.hasOwnProperty(from)) { extended[to] = extended[from]; delete extended[from]; } }; changePropertyName('w', _strWidth); //change w to width changePropertyName('h', _strHeight); //change h to height delete extended.c; //delete c (the 'changed' prop) return extended; }; var obj = { sleeping: prepare(_isSleeping) || false, autoUpdate: prepare(!_mutationObserversConnected), widthAuto: prepare(_widthAutoCache), heightAuto: prepare(_heightAutoCache), padding: prepare(_cssPaddingCache), overflowAmount: prepare(_overflowAmountCache), hideOverflow: prepare(_hideOverflowCache), hasOverflow: prepare(_hasOverflowCache), contentScrollSize: prepare(_contentScrollSizeCache), viewportSize: prepare(_viewportSize), hostSize: prepare(_hostSizeCache), documentMixed : prepare(_documentMixed) }; return type(stateProperty) == TYPES.s ? getObjectPropVal(obj, stateProperty) : obj; }; /** * Gets all or specific extension instance. * @param extName The name of the extension from which the instance shall be got. * @returns {{}} The instance of the extension with the given name or undefined if the instance couldn't be found. */ _base.ext = function(extName) { var result; var privateMethods = _extensionsPrivateMethods.split(' '); var i = 0; if(type(extName) == TYPES.s) { if(_extensions.hasOwnProperty(extName)) { result = extendDeep({}, _extensions[extName]); for (; i < privateMethods.length; i++) delete result[privateMethods[i]]; } } else { result = { }; for(i in _extensions) result[i] = extendDeep({ }, _base.ext(i)); } return result; }; /** * Adds a extension to this instance. * @param extName The name of the extension which shall be added. * @param extensionOptions The extension options which shall be used. * @returns {{}} The instance of the added extension or undefined if the extension couldn't be added properly. */ _base.addExt = function(extName, extensionOptions) { var registeredExtensionObj = window[PLUGINNAME].extension(extName); var instance; var instanceAdded; var instanceContract; var contractResult; var contractFulfilled = true; if(registeredExtensionObj) { if(!_extensions.hasOwnProperty(extName)) { instance = registeredExtensionObj.extensionFactory.call(_base, extendDeep({ }, registeredExtensionObj.defaultOptions), FRAMEWORK, COMPATIBILITY); if (instance) { instanceContract = instance.contract; if (type(instanceContract) == TYPES.f) { contractResult = instanceContract(window); contractFulfilled = type(contractResult) == TYPES.b ? contractResult : contractFulfilled; } if(contractFulfilled) { _extensions[extName] = instance; instanceAdded = instance.added; if(type(instanceAdded) == TYPES.f) instanceAdded(extensionOptions); return _base.ext(extName); } } } else return _base.ext(extName); } else console.warn("A extension with the name \"" + extName + "\" isn't registered."); }; /** * Removes a extension from this instance. * @param extName The name of the extension which shall be removed. * @returns {boolean} True if the extension was removed, false otherwise e.g. if the extension wasn't added before. */ _base.removeExt = function(extName) { var instance = _extensions[extName]; var instanceRemoved; if(instance) { delete _extensions[extName]; instanceRemoved = instance.removed; if(type(instanceRemoved) == TYPES.f) instanceRemoved(); return true; } return false; }; /** * Constructs the plugin. * @param targetElement The element to which the plugin shall be applied. * @param options The initial options of the plugin. * @param extensions The extension(s) which shall be added right after the initialization. * @returns {boolean} True if the plugin was successfully initialized, false otherwise. */ function construct(targetElement, options, extensions) { _defaultOptions = globals.defaultOptions; _nativeScrollbarStyling = globals.nativeScrollbarStyling; _nativeScrollbarSize = extendDeep({}, globals.nativeScrollbarSize); _nativeScrollbarIsOverlaid = extendDeep({}, globals.nativeScrollbarIsOverlaid); _overlayScrollbarDummySize = extendDeep({}, globals.overlayScrollbarDummySize); _rtlScrollBehavior = extendDeep({}, globals.rtlScrollBehavior); //parse & set options but don't update setOptions(extendDeep({ }, _defaultOptions, _pluginsOptions._validate(options, _pluginsOptions._template, true))); //check if the plugin hasn't to be initialized if (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.x && !_currentPreparedOptions.nativeScrollbarsOverlaid.initialize) { dispatchCallback("onInitializationWithdrawn"); return false; } _cssCalc = globals.cssCalc; _msieVersion = globals.msie; _autoUpdateRecommended = globals.autoUpdateRecommended; _supportTransition = globals.supportTransition; _supportTransform = globals.supportTransform; _supportPassiveEvents = globals.supportPassiveEvents; _supportResizeObserver = globals.supportResizeObserver; _supportMutationObserver = globals.supportMutationObserver; _restrictedMeasuring = globals.restrictedMeasuring; _documentElement = FRAMEWORK(targetElement.ownerDocument); _documentElementNative = _documentElement[0]; _windowElement = FRAMEWORK(_documentElementNative.defaultView || _documentElementNative.parentWindow); _windowElementNative = _windowElement[0]; _htmlElement = findFirst(_documentElement, 'html'); _bodyElement = findFirst(_htmlElement, 'body'); _targetElement = FRAMEWORK(targetElement); _targetElementNative = _targetElement[0]; _isTextarea = _targetElement.is('textarea'); _isBody = _targetElement.is('body'); _documentMixed = _documentElementNative !== document; var initBodyScroll; if (_isBody) { initBodyScroll = {}; initBodyScroll.l = MATH.max(_targetElement[_strScrollLeft](), _htmlElement[_strScrollLeft](), _windowElement[_strScrollLeft]()); initBodyScroll.t = MATH.max(_targetElement[_strScrollTop](), _htmlElement[_strScrollTop](), _windowElement[_strScrollTop]()); } //build OverlayScrollbars DOM and Events setupStructureDOM(); setupStructureEvents(); //build Scrollbars DOM and Events setupScrollbarsDOM(); setupScrollbarEvents(true); setupScrollbarEvents(false); //build Scrollbar Corner DOM and Events setupScrollbarCornerDOM(); setupScrollbarCornerEvents(); //create mutation observers createMutationObservers(); if(_isBody) { //apply the body scroll to handle it right in the update method _viewportElement[_strScrollLeft](initBodyScroll.l)[_strScrollTop](initBodyScroll.t); //set the focus on the viewport element so you dont have to click on the page to use keyboard keys (up / down / space) for scrolling if(document.activeElement == targetElement && _viewportElementNative.focus) { //set a tabindex to make the viewportElement focusable _viewportElement.attr('tabindex', '-1'); _viewportElementNative.focus(); /* the tabindex has to be removed due to; * If you set the tabindex attribute on an <div>, then its child content cannot be scrolled with the arrow keys unless you set tabindex on the content, too * https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex */ _viewportElement.one(_strMouseTouchDownEvent, function() { _viewportElement.removeAttr('tabindex'); }); } } //build resize observer for the host element addResizeObserver(_sizeObserverElement, hostOnResized); //update for the first time hostOnResized(); //initialize cache for host size _base.update(_strAuto); //initialize cache for content //the plugin is initialized now! _initialized = true; dispatchCallback("onInitialized"); //call all callbacks which would fire before the initialized was complete FRAMEWORK.each(_callbacksInitQeueue, function(index, value) { dispatchCallback(value.n, value.a); }); _callbacksInitQeueue = [ ]; //add extensions if(type(extensions) == TYPES.s) extensions = [ extensions ]; if(COMPATIBILITY.isA(extensions)) FRAMEWORK.each(extensions, function (index, value) {_base.addExt(value); }); else if(FRAMEWORK.isPlainObject(extensions)) FRAMEWORK.each(extensions, function (key, value) { _base.addExt(key, value); }); //add the transition class for transitions AFTER the first update & AFTER the applied extensions (for preventing unwanted transitions) setTimeout(function () { if (_supportTransition && !_destroyed) addClass(_hostElement, _classNameHostTransition); }, 333); return _initialized; } if (construct(pluginTargetElement, options, extensions)) { INSTANCES(pluginTargetElement, _base); return _base; } _base = undefined; } /** * Initializes a new OverlayScrollbarsInstance object or changes options if already initialized or returns the current instance. * @param pluginTargetElements The elements to which the Plugin shall be initialized. * @param options The custom options with which the plugin shall be initialized. * @param extensions The extension(s) which shall be added right after initialization. * @returns {*} */ window[PLUGINNAME] = function(pluginTargetElements, options, extensions) { if(arguments[LEXICON.l] === 0) return this; var arr = [ ]; var optsIsPlainObj = FRAMEWORK.isPlainObject(options); var inst; var result; //pluginTargetElements is null or undefined if(!pluginTargetElements) return optsIsPlainObj || !options ? result : arr; /* pluginTargetElements will be converted to: 1. A jQueryElement Array 2. A HTMLElement Array 3. A Array with a single HTML Element so pluginTargetElements is always a array. */ pluginTargetElements = pluginTargetElements[LEXICON.l] != undefined ? pluginTargetElements : [ pluginTargetElements[0] || pluginTargetElements ]; initOverlayScrollbarsStatics(); if(pluginTargetElements[LEXICON.l] > 0) { if(optsIsPlainObj) { FRAMEWORK.each(pluginTargetElements, function (i, v) { inst = v; if(inst !== undefined) arr.push(OverlayScrollbarsInstance(inst, options, extensions, _pluginsGlobals, _pluginsAutoUpdateLoop)); }); } else { FRAMEWORK.each(pluginTargetElements, function(i, v) { inst = INSTANCES(v); if((options === '!' && inst instanceof window[PLUGINNAME]) || (COMPATIBILITY.type(options) == TYPES.f && options(v, inst))) arr.push(inst); else if(options === undefined) arr.push(inst); }); } result = arr[LEXICON.l] === 1 ? arr[0] : arr; } return result; }; /** * Returns a object which contains global information about the plugin and each instance of it. * The returned object is just a copy, that means that changes to the returned object won't have any effect to the original object. */ window[PLUGINNAME].globals = function () { initOverlayScrollbarsStatics(); var globals = FRAMEWORK.extend(true, { }, _pluginsGlobals); delete globals['msie']; return globals; }; /** * Gets or Sets the default options for each new plugin initialization. * @param newDefaultOptions The object with which the default options shall be extended. */ window[PLUGINNAME].defaultOptions = function(newDefaultOptions) { initOverlayScrollbarsStatics(); var currDefaultOptions = _pluginsGlobals.defaultOptions; if(newDefaultOptions === undefined) return FRAMEWORK.extend(true, { }, currDefaultOptions); //set the new default options _pluginsGlobals.defaultOptions = FRAMEWORK.extend(true, { }, currDefaultOptions , _pluginsOptions._validate(newDefaultOptions, _pluginsOptions._template, true)); }; /** * Registers, Unregisters or returns a extension. * Register: Pass the name and the extension. (defaultOptions is optional) * Unregister: Pass the name and anything except a function as extension parameter. * Get extension: Pass the name of the extension which shall be got. * Get all extensions: Pass no arguments. * @param extensionName The name of the extension which shall be registered, unregistered or returned. * @param extension A function which generates the instance of the extension or anything other to remove a already registered extension. * @param defaultOptions The default options which shall be used for the registered extension. */ window[PLUGINNAME].extension = function(extensionName, extension, defaultOptions) { var extNameTypeString = COMPATIBILITY.type(extensionName) == TYPES.s; var argLen = arguments[LEXICON.l]; var i = 0; if(argLen < 1 || !extNameTypeString) { //return a copy of all extension objects return FRAMEWORK.extend(true, { length : _pluginsExtensions[LEXICON.l] }, _pluginsExtensions); } else if(extNameTypeString) { if(COMPATIBILITY.type(extension) == TYPES.f) { //register extension _pluginsExtensions.push({ name : extensionName, extensionFactory : extension, defaultOptions : defaultOptions }); } else { for(; i < _pluginsExtensions[LEXICON.l]; i++) { if (_pluginsExtensions[i].name === extensionName) { if(argLen > 1) _pluginsExtensions.splice(i, 1); //remove extension else return FRAMEWORK.extend(true, { }, _pluginsExtensions[i]); //return extension with the given name } } } } }; return window[PLUGINNAME]; })(); if(JQUERY && JQUERY.fn) { /** * The jQuery initialization interface. * @param options The initial options for the construction of the plugin. To initialize the plugin, this option has to be a object! If it isn't a object, the instance(s) are returned and the plugin wont be initialized. * @param extensions The extension(s) which shall be added right after initialization. * @returns {*} After initialization it returns the jQuery element array, else it returns the instance(s) of the elements which are selected. */ JQUERY.fn.overlayScrollbars = function (options, extensions) { var _elements = this; if(JQUERY.isPlainObject(options)) { JQUERY.each(_elements, function() { PLUGIN(this, options, extensions); }); return _elements; } else return PLUGIN(_elements, options); }; } return PLUGIN; } ));
extend1994/cdnjs
ajax/libs/overlayscrollbars/1.7.3/js/OverlayScrollbars.js
JavaScript
mit
348,965
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Component, Directive, InjectionToken, NgModule, Pipe, PlatformRef, SchemaMetadata, Type} from '@angular/core'; import {ComponentFixture} from './component_fixture'; import {MetadataOverride} from './metadata_override'; import {TestBed} from './test_bed'; /** * An abstract class for inserting the root test component element in a platform independent way. * * @publicApi */ export class TestComponentRenderer { insertRootElement(rootElementId: string) {} } /** * @publicApi */ export const ComponentFixtureAutoDetect = new InjectionToken<boolean[]>('ComponentFixtureAutoDetect'); /** * @publicApi */ export const ComponentFixtureNoNgZone = new InjectionToken<boolean[]>('ComponentFixtureNoNgZone'); /** * @publicApi */ export type TestModuleMetadata = { providers?: any[], declarations?: any[], imports?: any[], schemas?: Array<SchemaMetadata|any[]>, aotSummaries?: () => any[], }; /** * Static methods implemented by the `TestBedViewEngine` and `TestBedRender3` * * @publicApi */ export interface TestBedStatic { new (...args: any[]): TestBed; initTestEnvironment( ngModule: Type<any>|Type<any>[], platform: PlatformRef, aotSummaries?: () => any[]): TestBed; /** * Reset the providers for the test injector. */ resetTestEnvironment(): void; resetTestingModule(): TestBedStatic; /** * Allows overriding default compiler providers and settings * which are defined in test_injector.js */ configureCompiler(config: {providers?: any[]; useJit?: boolean;}): TestBedStatic; /** * Allows overriding default providers, directives, pipes, modules of the test injector, * which are defined in test_injector.js */ configureTestingModule(moduleDef: TestModuleMetadata): TestBedStatic; /** * Compile components with a `templateUrl` for the test's NgModule. * It is necessary to call this function * as fetching urls is asynchronous. */ compileComponents(): Promise<any>; overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): TestBedStatic; overrideComponent(component: Type<any>, override: MetadataOverride<Component>): TestBedStatic; overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): TestBedStatic; overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): TestBedStatic; overrideTemplate(component: Type<any>, template: string): TestBedStatic; /** * Overrides the template of the given component, compiling the template * in the context of the TestingModule. * * Note: This works for JIT and AOTed components as well. */ overrideTemplateUsingTestingModule(component: Type<any>, template: string): TestBedStatic; /** * Overwrites all providers for the given token with the given provider definition. * * Note: This works for JIT and AOTed components as well. */ overrideProvider(token: any, provider: { useFactory: Function, deps: any[], }): TestBedStatic; overrideProvider(token: any, provider: {useValue: any;}): TestBedStatic; overrideProvider(token: any, provider: { useFactory?: Function, useValue?: any, deps?: any[], }): TestBedStatic; /** * Overwrites all providers for the given token with the given provider definition. * * @deprecated as it makes all NgModules lazy. Introduced only for migrating off of it. */ deprecatedOverrideProvider(token: any, provider: { useFactory: Function, deps: any[], }): void; deprecatedOverrideProvider(token: any, provider: {useValue: any;}): void; deprecatedOverrideProvider(token: any, provider: { useFactory?: Function, useValue?: any, deps?: any[], }): TestBedStatic; get(token: any, notFoundValue?: any): any; createComponent<T>(component: Type<T>): ComponentFixture<T>; }
ValtoFrameworks/Angular-2
packages/core/testing/src/test_bed_common.ts
TypeScript
mit
4,016
import _curry3 from './internal/_curry3.js'; import prop from './prop.js'; /** * Returns `true` if the specified object property satisfies the given * predicate; `false` otherwise. You can test multiple properties with * [`R.where`](#where). * * @func * @memberOf R * @since v0.16.0 * @category Logic * @sig (a -> Boolean) -> String -> {String: a} -> Boolean * @param {Function} pred * @param {String} name * @param {*} obj * @return {Boolean} * @see R.where, R.propEq, R.propIs * @example * * R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true */ var propSatisfies = _curry3(function propSatisfies(pred, name, obj) { return pred(prop(name, obj)); }); export default propSatisfies;
ramda/ramda
source/propSatisfies.js
JavaScript
mit
715
import * as React from 'react'; /* * A utility for rendering a drag preview image */ export var DragPreviewImage = React.memo(function (_ref) { var connect = _ref.connect, src = _ref.src; React.useEffect(function () { if (typeof Image === 'undefined') return; var connected = false; var img = new Image(); img.src = src; img.onload = function () { connect(img); connected = true; }; return function () { if (connected) { connect(null); } }; }); return null; }); DragPreviewImage.displayName = 'DragPreviewImage';
cdnjs/cdnjs
ajax/libs/react-dnd/11.1.3/esm/common/DragPreviewImage.js
JavaScript
mit
595
import setupStore from 'dummy/tests/helpers/store'; import Ember from 'ember'; import testInDebug from 'dummy/tests/helpers/test-in-debug'; import {module, test} from 'qunit'; import DS from 'ember-data'; const { run } = Ember; const { attr } = DS; const { reject } = Ember.RSVP; let Person, store, env; module("integration/adapter/find - Finding Records", { beforeEach() { Person = DS.Model.extend({ updatedAt: attr('string'), name: attr('string'), firstName: attr('string'), lastName: attr('string') }); env = setupStore({ person: Person }); store = env.store; }, afterEach() { run(store, 'destroy'); } }); testInDebug("It raises an assertion when `undefined` is passed as id (#1705)", (assert) => { assert.expectAssertion(() => { store.find('person', undefined); }, "You cannot pass `undefined` as id to the store's find method"); assert.expectAssertion(() => { store.find('person', null); }, "You cannot pass `null` as id to the store's find method"); }); test("When a single record is requested, the adapter's find method should be called unless it's loaded.", (assert) => { assert.expect(2); var count = 0; env.registry.register('adapter:person', DS.Adapter.extend({ findRecord(_, type) { assert.equal(type, Person, "the find method is called with the correct type"); assert.equal(count, 0, "the find method is only called once"); count++; return { id: 1, name: "Braaaahm Dale" }; } })); run(() => { store.findRecord('person', 1); store.findRecord('person', 1); }); }); test("When a single record is requested multiple times, all .findRecord() calls are resolved after the promise is resolved", (assert) => { var deferred = Ember.RSVP.defer(); env.registry.register('adapter:person', DS.Adapter.extend({ findRecord: () => deferred.promise })); run(() => { store.findRecord('person', 1).then(assert.wait(function(person) { assert.equal(person.get('id'), "1"); assert.equal(person.get('name'), "Braaaahm Dale"); let done = assert.async(); deferred.promise.then(() => { assert.ok(true, 'expected deferred.promise to fulfill'); done(); }, () => { assert.ok(false, 'expected deferred.promise to fulfill, but rejected'); done(); }); })); }); run(() => { store.findRecord('person', 1).then(assert.wait((post) => { assert.equal(post.get('id'), "1"); assert.equal(post.get('name'), "Braaaahm Dale"); let done = assert.async(); deferred.promise.then(() => { assert.ok(true, 'expected deferred.promise to fulfill'); done(); }, () => { assert.ok(false, 'expected deferred.promise to fulfill, but rejected'); done(); }); })); }); run(() => deferred.resolve({ id: 1, name: "Braaaahm Dale" })); }); test("When a single record is requested, and the promise is rejected, .findRecord() is rejected.", (assert) => { env.registry.register('adapter:person', DS.Adapter.extend({ findRecord: () => reject() })); run(() => { store.findRecord('person', 1).then(null, assert.wait(() => { assert.ok(true, "The rejection handler was called"); })); }); }); test("When a single record is requested, and the promise is rejected, the record should be unloaded.", (assert) => { assert.expect(2); env.registry.register('adapter:person', DS.Adapter.extend({ findRecord: () => reject() })); run(() => { store.findRecord('person', 1).then(null, assert.wait((reason) => { assert.ok(true, "The rejection handler was called"); assert.ok(!store.hasRecordForId('person', 1), "The record has been unloaded"); })); }); }); testInDebug('When a single record is requested, and the payload is blank', (assert) => { env.registry.register('adapter:person', DS.Adapter.extend({ findRecord: () => Ember.RSVP.resolve({}) })); assert.expectAssertion(() => { run(() => store.findRecord('person', 'the-id')); }, /You made a `findRecord` request for a person with id the-id, but the adapter's response did not have any data/); }); testInDebug('When multiple records are requested, and the payload is blank', (assert) => { env.registry.register('adapter:person', DS.Adapter.extend({ coalesceFindRequests: true, findMany: () => Ember.RSVP.resolve({}) })); assert.expectAssertion(() => { run(() => { store.findRecord('person', '1'); store.findRecord('person', '2'); }); }, /You made a `findMany` request for person records with ids 1,2, but the adapter's response did not have any data/); }); testInDebug("warns when returned record has different id", function(assert) { env.registry.register('adapter:person', DS.Adapter.extend({ findRecord() { return { id: 1, name: "Braaaahm Dale" }; } })); assert.expectWarning(/You requested a record of type 'person' with id 'me' but the adapter returned a payload with primary data having an id of '1'/); run(function() { env.store.findRecord('person', 'me'); }); });
wecc/data
tests/integration/adapter/find-test.js
JavaScript
mit
5,129
/****************************************************************************** * Copyright (C) 2006-2012 IFS Institute for Software 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 * * Original authors: * Dennis Hunziker * Ueli Kistler * Reto Schuettel * Robin Stocker * Contributors: * Fabio Zadrozny <fabiofz@gmail.com> - initial implementation ******************************************************************************/ /* * Copyright (C) 2006, 2007 Dennis Hunziker, Ueli Kistler * Copyright (C) 2007 Reto Schuettel, Robin Stocker * * IFS Institute for Software, HSR Rapperswil, Switzerland * */ package org.python.pydev.refactoring.ui.core; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.swt.graphics.Image; import org.python.pydev.refactoring.core.model.tree.ITreeNode; public class TreeLabelProvider implements ILabelProvider { private PepticImageCache cache; public TreeLabelProvider() { cache = new PepticImageCache(); } @Override public Image getImage(Object element) { Image image = null; ITreeNode node = (ITreeNode) element; image = cache.get(node.getImageName()); return image; } @Override public String getText(Object element) { if (element instanceof ITreeNode) { return ((ITreeNode) element).getLabel(); } return ""; } @Override public void addListener(ILabelProviderListener listener) { } @Override public void dispose() { cache.dispose(); cache = null; } @Override public boolean isLabelProperty(Object element, String property) { return false; } @Override public void removeListener(ILabelProviderListener listener) { } }
bobwalker99/Pydev
plugins/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ui/core/TreeLabelProvider.java
Java
epl-1.0
2,059
/** * Copyright (c) 2013-2015 by Brainwy Software Ltda, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package org.python.pydev.debug.curr_exception; import java.util.HashMap; import java.util.Map; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.TrayDialog; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.python.pydev.shared_ui.UIConstants; import org.python.pydev.shared_ui.dialogs.DialogMemento; import org.python.pydev.ui.editors.TreeWithAddRemove; /** * @author fabioz */ public class EditIgnoredCaughtExceptionsDialog extends TrayDialog { private Button okButton; private Button cancelButton; private HashMap<String, String> map; private TreeWithAddRemove treeWithAddRemove; private DialogMemento memento; private Map<String, String> finalMap; EditIgnoredCaughtExceptionsDialog(Shell shell, HashMap<String, String> map) { super(shell); this.map = map; setHelpAvailable(false); memento = new DialogMemento(shell, "org.python.pydev.debug.curr_exception.EditIgnoredCaughtExceptionsDialog"); } @Override protected void createButtonsForButtonBar(Composite parent) { okButton = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); cancelButton = createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } @Override public boolean close() { memento.writeSettings(getShell()); return super.close(); } @Override protected Point getInitialSize() { return memento.getInitialSize(super.getInitialSize(), getShell()); } @Override protected Point getInitialLocation(Point initialSize) { return memento.getInitialLocation(initialSize, super.getInitialLocation(initialSize), getShell()); } @Override protected Control createDialogArea(Composite parent) { memento.readSettings(); Composite area = (Composite) super.createDialogArea(parent); treeWithAddRemove = new TreeWithAddRemove(area, 0, map) { @Override protected void handleAddButtonSelected(int nButton) { throw new RuntimeException("not implemented: no add buttons"); } @Override protected String getImageConstant() { return UIConstants.PUBLIC_ATTR_ICON; } @Override protected String getButtonLabel(int i) { throw new RuntimeException("not implemented: no add buttons"); } @Override protected int getNumberOfAddButtons() { return 0; } }; GridData data = new GridData(GridData.FILL_BOTH); data.grabExcessHorizontalSpace = true; data.grabExcessVerticalSpace = true; treeWithAddRemove.setLayoutData(data); treeWithAddRemove.fitToContents(); return area; } @Override protected boolean isResizable() { return true; } @Override protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText("Edit Ignored Thrown Exceptions"); } @Override protected void okPressed() { this.finalMap = treeWithAddRemove.getTreeItemsAsMap(); super.okPressed(); } public Map<String, String> getResult() { return finalMap; } }
bobwalker99/Pydev
plugins/org.python.pydev.debug/src/org/python/pydev/debug/curr_exception/EditIgnoredCaughtExceptionsDialog.java
Java
epl-1.0
3,834
/******************************************************************************* * Copyright (c) 2012, 2014 UT-Battelle, LLC. * 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: * Initial API and implementation and/or initial documentation - Jay Jay Billings, * Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson, * Claire Saunders, Matthew Wang, Anna Wojtowicz *******************************************************************************/ package org.eclipse.ice.datastructures.ICEObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; /** * This class is responsible for reading and writing JAXB-annotated classes into * and out of ICE. * * @author Jay Jay Billings */ public class ICEJAXBHandler { /** * This operation reads an instance of a particular class type from the * input stream into a Java Object. * * @param classList * The class list from which JAXB annotations should be read. * @param inputStream * An InputStream from which the XML should be read by JAXB. * @return An Object that is an instance of the Class that was parsed from * the XML InputStream. * @throws NullPointerException * @throws JAXBException * @throws IOException */ public Object read(ArrayList<Class> classList, InputStream inputStream) throws NullPointerException, JAXBException, IOException { // Initialize local variables JAXBContext context; Class[] clazzArray = {}; // If the input args are null, throw an exception if (classList == null) { throw new NullPointerException("NullPointerException: " + "objectClass argument can not be null"); } if (inputStream == null) { throw new NullPointerException("NullPointerException: " + "inputStream argument can not be null"); } // Create new instance of object from file and then return it. context = JAXBContext.newInstance(classList.toArray(clazzArray)); Unmarshaller unmarshaller = context.createUnmarshaller(); // New object created Object dataFromFile = unmarshaller.unmarshal(inputStream); // Return object return dataFromFile; } /** * This operation writes an instance of a particular class type from the * input stream into a Java Object. This operation requires both the Object * and the specific class type because some classes, such as local classes, * do return the appropriate class type from a call to "this.getClass()." * * @param dataObject * An Object that is an instance of the Class that is parsed to * create the XML InputStream. * @param classList * @param outputStream * An OutputStream to which the XML should be written by JAXB. * @throws NullPointerException * @throws JAXBException * @throws IOException */ public void write(Object dataObject, ArrayList<Class> classList, OutputStream outputStream) throws NullPointerException, JAXBException, IOException { JAXBContext jaxbContext = null; Class[] classArray = {}; // Throw exceptions if input args are null if (dataObject == null) { throw new NullPointerException( "NullPointerException: dataObject can not be null"); } if (outputStream == null) { throw new NullPointerException( "NullPointerException: outputStream can not be null"); } // Create the class list with which to initialize the context. If the // data object is an ListComponent, it is important to give it // both the type of the container and the generic. if (dataObject instanceof ListComponent) { // Cast the object to a generic, type-less list ListComponent list = (ListComponent) dataObject; // Don't pop the container open if it is empty if (list.size() > 0 && !classList.contains(ListComponent.class)) { classList.add(ListComponent.class); classList.add(list.get(0).getClass()); } } else if (!dataObject.getClass().isAnonymousClass()) { // Otherwise just get the class if it is not anonymous classList.add(dataObject.getClass()); } else { // Or get the base class if it is anonymous classList.add(dataObject.getClass().getSuperclass()); } // Create the context and marshal the data if classes were determined if (classList.size() > 0) { jaxbContext = JAXBContext .newInstance(classList.toArray(classArray)); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to file marshaller.marshal(dataObject, outputStream); } return; } }
gorindn/ice
src/org.eclipse.ice.datastructures/src/org/eclipse/ice/datastructures/ICEObject/ICEJAXBHandler.java
Java
epl-1.0
4,963
package org.usfirst.frc.team3952.robot; import java.io.IOException; import edu.wpi.first.wpilibj.CameraServer; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.*; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { DriveTrain dt; DashBoard board; Joystick stick; LinearActuatorWinch lin; //ImageProcess i; int autoLoopCounter; ServoC sc; WindshieldMotor m1; long start; //double speed; //we are using talon motors so need to make new DriveTrain class /** * This function is run when the robot is first started up and should be;ioj;oi * used for any initialization code. */ public void robotInit() { board = new DashBoard(); stick = new Joystick(0); dt=new DriveTrain(stick); lin =new LinearActuatorWinch(stick); sc=new ServoC(stick, new Servo(6)); m1=new WindshieldMotor(4,5,stick); //speed=-0.1; } /** * This function is run once each time the robot enters autonomous mode */ public void autonomousInit() { start=System.currentTimeMillis(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { dt.autonD(start); } /** * This function is called once each time the robot enters tele-operated mode */ public void teleopInit(){ } /** * This function is called periodically during operator control */ public void teleopPeriodic() { dt.drive(); board.updateDashboard(); //lin.goLAW(); sc.pCheck(); //m1.pressCheck(); } /** * This function is called periodically during test mode */ public void testPeriodic() { LiveWindow.run(); } }
Grande14/Team3952desTROYer
v6 3_12_2016 still comments/Robot.java
Java
epl-1.0
2,240
package org.jboss.windup.reporting; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.forge.arquillian.AddonDependencies; import org.jboss.forge.arquillian.AddonDependency; import org.jboss.forge.arquillian.archive.AddonArchive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.windup.config.DefaultEvaluationContext; import org.jboss.windup.config.GraphRewrite; import org.jboss.windup.config.RuleSubset; import org.jboss.windup.config.loader.RuleLoaderContext; import org.jboss.windup.graph.GraphContext; import org.jboss.windup.graph.GraphContextFactory; import org.jboss.windup.reporting.category.IssueCategoryRegistry; import org.jboss.windup.reporting.category.LoadIssueCategoriesRuleProvider; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.ocpsoft.rewrite.config.Configuration; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; /** * @author <a href="mailto:jesse.sightler@gmail.com">Jesse Sightler</a> */ @RunWith(Arquillian.class) public class LoadIssueCategoriesRuleProviderTest { public static final String ISSUE_CATEGORIES_PATH = "src/test/resources/issue-categories"; @Inject private GraphContextFactory factory; @Inject private LoadIssueCategoriesRuleProvider provider; @Deployment @AddonDependencies({ @AddonDependency(name = "org.jboss.windup.config:windup-config"), @AddonDependency(name = "org.jboss.windup.graph:windup-graph"), @AddonDependency(name = "org.jboss.windup.reporting:windup-reporting"), @AddonDependency(name = "org.jboss.forge.furnace.container:cdi") }) public static AddonArchive getDeployment() { return ShrinkWrap .create(AddonArchive.class) .addBeansXML() .addClass(ReportingTestUtil.class) .addAsResource(new File(ISSUE_CATEGORIES_PATH)); } @Test public void testLoadIssueCategories() throws Exception { try (GraphContext context = factory.create(true)) { GraphRewrite event = new GraphRewrite(context); DefaultEvaluationContext evaluationContext = ReportingTestUtil.createEvalContext(event); List<Path> ruleLoaderPaths = new ArrayList<>(); Path testPath = Paths.get(ISSUE_CATEGORIES_PATH); ruleLoaderPaths.add(testPath); RuleLoaderContext ruleLoaderContext = new RuleLoaderContext(event.getRewriteContext(), ruleLoaderPaths, null); Configuration configuration = provider.getConfiguration(ruleLoaderContext); RuleSubset.create(configuration).perform(event, evaluationContext); IssueCategoryRegistry issueCategoryRegistry = IssueCategoryRegistry.instance(event.getRewriteContext()); Assert.assertEquals(1000, (long)issueCategoryRegistry.getByID("mandatory").getPriority()); Assert.assertEquals(2000, (long)issueCategoryRegistry.getByID("optional").getPriority()); Assert.assertEquals(3000, (long)issueCategoryRegistry.getByID("potential").getPriority()); Assert.assertEquals(4000, (long)issueCategoryRegistry.getByID("extra").getPriority()); Assert.assertEquals("extra", issueCategoryRegistry.getByID("extra").getCategoryID()); Assert.assertEquals("Extra", issueCategoryRegistry.getByID("extra").getName()); Assert.assertEquals("Extra Category", issueCategoryRegistry.getByID("extra").getDescription()); Assert.assertNotNull(issueCategoryRegistry.getByID("extra").getOrigin()); Assert.assertTrue(issueCategoryRegistry.getByID("extra").getOrigin().endsWith("test.windup.categories.xml")); } } }
jsight/windup
reporting/tests/src/test/java/org/jboss/windup/reporting/LoadIssueCategoriesRuleProviderTest.java
Java
epl-1.0
3,912
/******************************************************************************* * Copyright (c) 2010, 2011 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.openhealthtools.mdht.uml.cda.hitsp.operations; import java.util.Arrays; import java.util.List; import java.util.Map; import org.eclipse.emf.common.util.BasicDiagnostic; import org.eclipse.emf.ecore.EObject; import org.openhealthtools.mdht.uml.cda.hitsp.EncountersSection; import org.openhealthtools.mdht.uml.cda.hitsp.HITSPFactory; import org.openhealthtools.mdht.uml.cda.ihe.operations.EncounterHistorySectionOperationsTest; /** * This class is a JUnit4 test case. */ @SuppressWarnings("nls") public class EncountersSectionOperationsTest extends EncounterHistorySectionOperationsTest { protected static final String TEMPLATE_ID = "2.16.840.1.113883.3.88.11.83.127"; private static final CDATestCase TEST_CASE_ARRAY[] = { // Template ID // ------------------------------------------------------------- new TemplateIDValidationTest(TEMPLATE_ID) { @Override protected boolean validate(final EObject objectToTest, final BasicDiagnostic diagnostician, final Map<Object, Object> map) { return EncountersSectionOperations.validateHITSPEncountersSectionTemplateId( (EncountersSection) objectToTest, diagnostician, map); } } }; // TEST_CASE_ARRAY @Override protected List<CDATestCase> getTestCases() { // Return a new List because the one returned by Arrays.asList is // unmodifiable so a sub-class can't append their test cases. final List<CDATestCase> retValue = super.getTestCases(); retValue.addAll(Arrays.asList(TEST_CASE_ARRAY)); return retValue; } @Override protected EObject getObjectToTest() { return HITSPFactory.eINSTANCE.createEncountersSection(); } @Override protected EObject getObjectInitToTest() { return HITSPFactory.eINSTANCE.createEncountersSection().init(); } } // EncountersSectionOperationsTest
drbgfc/mdht
cda/deprecated/org.openhealthtools.mdht.uml.cda.hitsp.test/src/org/openhealthtools/mdht/uml/cda/hitsp/operations/EncountersSectionOperationsTest.java
Java
epl-1.0
2,389
require "rjava" # Copyright (c) 2000, 2005 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 module Org::Eclipse::Swt::Widgets module ListenerImports #:nodoc: class_module.module_eval { include ::Java::Lang include ::Org::Eclipse::Swt::Widgets } end # Implementers of <code>Listener</code> provide a simple # <code>handleEvent()</code> method that is used internally # by SWT to dispatch events. # <p> # After creating an instance of a class that implements this interface # it can be added to a widget using the # <code>addListener(int eventType, Listener handler)</code> method and # removed using the # <code>removeListener (int eventType, Listener handler)</code> method. # When the specified event occurs, <code>handleEvent(...)</code> will # be sent to the instance. # </p> # <p> # Classes which implement this interface are described within SWT as # providing the <em>untyped listener</em> API. Typically, widgets will # also provide a higher-level <em>typed listener</em> API, that is based # on the standard <code>java.util.EventListener</code> pattern. # </p> # <p> # Note that, since all internal SWT event dispatching is based on untyped # listeners, it is simple to build subsets of SWT for use on memory # constrained, small footprint devices, by removing the classes and # methods which implement the typed listener API. # </p> # # @see Widget#addListener # @see java.util.EventListener # @see org.eclipse.swt.events module Listener include_class_members ListenerImports typesig { [Event] } # Sent when an event that the receiver has registered for occurs. # # @param event the event which occurred def handle_event(event) raise NotImplementedError end end end
neelance/swt4ruby
swt4ruby/lib/mingw32-x86_32/org/eclipse/swt/widgets/Listener.rb
Ruby
epl-1.0
2,098
/******************************************************************************* * Copyright (c) 2009, 2010 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 * * $Id$ *******************************************************************************/ package org.openhealthtools.mdht.uml.cda.ncr.impl; import java.util.Map; import org.eclipse.emf.common.util.DiagnosticChain; import org.eclipse.emf.ecore.EClass; import org.openhealthtools.mdht.uml.cda.ccd.impl.EncounterLocationImpl; import org.openhealthtools.mdht.uml.cda.ncr.NCRPackage; import org.openhealthtools.mdht.uml.cda.ncr.NeonatalICULocation; import org.openhealthtools.mdht.uml.cda.ncr.operations.NeonatalICULocationOperations; import org.openhealthtools.mdht.uml.cda.util.CDAUtil; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Neonatal ICU Location</b></em>'. * <!-- end-user-doc --> * <p> * </p> * * @generated */ public class NeonatalICULocationImpl extends EncounterLocationImpl implements NeonatalICULocation { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected NeonatalICULocationImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return NCRPackage.Literals.NEONATAL_ICU_LOCATION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean validateNeonatalICULocationTypeCode(DiagnosticChain diagnostics, Map<Object, Object> context) { return NeonatalICULocationOperations.validateNeonatalICULocationTypeCode(this, diagnostics, context); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean validateEncounterLocationTemplateId(DiagnosticChain diagnostics, Map<Object, Object> context) { return NeonatalICULocationOperations.validateEncounterLocationTemplateId(this, diagnostics, context); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NeonatalICULocation init() { CDAUtil.init(this); return this; } } //NeonatalICULocationImpl
drbgfc/mdht
cda/deprecated/org.openhealthtools.mdht.uml.cda.ncr/src/org/openhealthtools/mdht/uml/cda/ncr/impl/NeonatalICULocationImpl.java
Java
epl-1.0
2,533
// Aseprite Base Library // Copyright (c) 2001-2013, 2015 David Capello // // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "base/time.h" #if _WIN32 #include <windows.h> #else #include <ctime> #endif namespace base { Time current_time() { #if _WIN32 SYSTEMTIME st; GetLocalTime(&st); return Time(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); #else std::time_t now = std::time(nullptr); std::tm* t = std::localtime(&now); return Time( t->tm_year+1900, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); #endif } } // namespace base
Fojar/aseprite
src/base/time.cpp
C++
gpl-2.0
704
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/ # # Copyright (c) 2011 - 2014 by Wilbert Berendsen # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # See http://www.gnu.org/licenses/ for more information. """ Utility functions used in the autocomplete package. """ import functools import time import weakref def keep(f): """Returns a decorator that remembers its return value for some time.""" _delay = 5.0 # sec _cache = weakref.WeakKeyDictionary() @functools.wraps(f) def decorator(self, *args): try: result = _cache[self] except KeyError: pass else: t, ret = result if (time.time() - t) < _delay: return ret ret = f(self, *args) _cache[self] = (time.time(), ret) return ret return decorator # helper functions for displaying data from models def command(item): """Prepends '\\' to item.""" return '\\' + item def variable(item): """Appends ' = ' to item.""" return item + " = " def cmd_or_var(item): """Appends ' = ' to item if it does not start with '\\'.""" return item if item.startswith('\\') else item + " = " def make_cmds(words): """Returns generator prepending '\\' to every word.""" return ('\\' + w for w in words)
dliessi/frescobaldi
frescobaldi_app/autocomplete/util.py
Python
gpl-2.0
1,994
<?php /** * PEL: PHP Exif Library. * A library with support for reading and * writing all Exif headers in JPEG and TIFF images using PHP. * * Copyright (C) 2004, 2005, 2006 Martin Geisler. * * 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 in the file COPYING; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ namespace Pel\Test; use lsolesen\pel\PelEntrySShort; class NumberSShortTest extends NumberTestCase { public function setUp(): void { parent::setUp(); $this->num = new PelEntrySShort(42); $this->min = - 32768; $this->max = 32767; } }
maskedjellybean/tee-prop
vendor/lsolesen/pel/test/NumberSShortTest.php
PHP
gpl-2.0
1,216
/* $Id$ */ /** @file * * VBox frontends: Qt4 GUI ("VirtualBox"): * UIWizardImportAppPageBasic1 class implementation */ /* * Copyright (C) 2009-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. */ /* Global includes: */ #include <QFileInfo> #include <QVBoxLayout> /* Local includes: */ #include "UIWizardImportAppPageBasic1.h" #include "UIWizardImportAppPageBasic2.h" #include "UIWizardImportApp.h" #include "VBoxGlobal.h" #include "VBoxFilePathSelectorWidget.h" #include "QIRichTextLabel.h" UIWizardImportAppPage1::UIWizardImportAppPage1() { } UIWizardImportAppPageBasic1::UIWizardImportAppPageBasic1() { /* Create widgets: */ QVBoxLayout *pMainLayout = new QVBoxLayout(this); { m_pLabel = new QIRichTextLabel(this); m_pFileSelector = new VBoxEmptyFileSelector(this); { m_pFileSelector->setMode(VBoxFilePathSelectorWidget::Mode_File_Open); m_pFileSelector->setHomeDir(vboxGlobal().documentsPath()); } pMainLayout->addWidget(m_pLabel); pMainLayout->addWidget(m_pFileSelector); pMainLayout->addStretch(); } /* Setup connections: */ connect(m_pFileSelector, SIGNAL(pathChanged(const QString&)), this, SIGNAL(completeChanged())); } void UIWizardImportAppPageBasic1::retranslateUi() { /* Translate page: */ setTitle(UIWizardImportApp::tr("Appliance to import")); /* Translate widgets: */ m_pLabel->setText(UIWizardImportApp::tr("<p>VirtualBox currently supports importing appliances " "saved in the Open Virtualization Format (OVF). " "To continue, select the file to import below.</p>")); m_pFileSelector->setChooseButtonText(UIWizardImportApp::tr("Open appliance...")); m_pFileSelector->setFileDialogTitle(UIWizardImportApp::tr("Select an appliance to import")); m_pFileSelector->setFileFilters(UIWizardImportApp::tr("Open Virtualization Format (%1)").arg("*.ova *.ovf")); } void UIWizardImportAppPageBasic1::initializePage() { /* Translate page: */ retranslateUi(); } bool UIWizardImportAppPageBasic1::isComplete() const { /* Make sure appliance file has allowed extension and exists: */ return VBoxGlobal::hasAllowedExtension(m_pFileSelector->path().toLower(), OVFFileExts) && QFileInfo(m_pFileSelector->path()).exists(); } bool UIWizardImportAppPageBasic1::validatePage() { /* Get import appliance widget: */ ImportAppliancePointer pImportApplianceWidget = field("applianceWidget").value<ImportAppliancePointer>(); AssertMsg(!pImportApplianceWidget.isNull(), ("Appliance Widget is not set!\n")); /* If file name was changed: */ if (m_pFileSelector->isModified()) { /* Check if set file contains valid appliance: */ if (!pImportApplianceWidget->setFile(m_pFileSelector->path())) return false; /* Reset the modified bit afterwards: */ m_pFileSelector->resetModified(); } /* If we have a valid ovf proceed to the appliance settings page: */ return pImportApplianceWidget->isValid(); }
pombredanne/VirtualBox-OSE
src/VBox/Frontends/VirtualBox/src/wizards/importappliance/UIWizardImportAppPageBasic1.cpp
C++
gpl-2.0
3,589
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2014 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". 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 "Form/Panel.hpp" #include "Look/DialogLook.hpp" PanelControl::PanelControl(ContainerWindow &parent, const DialogLook &look, const PixelRect &rc, const WindowStyle style) { Create(parent, rc, #ifdef HAVE_CLIPPING look.background_color, #endif style); }
CnZoom/XcSoarWork
src/Form/Panel.cpp
C++
gpl-2.0
1,236
/***************************************************************************** Copyright (c) 1994, 2016, Oracle and/or its affiliates. All Rights Reserved. Copyright (c) 2012, Facebook Inc. Copyright (c) 2014, 2016, MariaDB Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; 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 Street, Suite 500, Boston, MA 02110-1335 USA *****************************************************************************/ /**************************************************//** @file btr/btr0btr.cc The B-tree Created 6/2/1994 Heikki Tuuri *******************************************************/ #include "btr0btr.h" #ifdef UNIV_NONINL #include "btr0btr.ic" #endif #include "fsp0fsp.h" #include "page0page.h" #include "page0zip.h" #ifndef UNIV_HOTBACKUP #include "btr0cur.h" #include "btr0sea.h" #include "btr0pcur.h" #include "btr0defragment.h" #include "rem0cmp.h" #include "lock0lock.h" #include "ibuf0ibuf.h" #include "trx0trx.h" #include "srv0mon.h" /**************************************************************//** Checks if the page in the cursor can be merged with given page. If necessary, re-organize the merge_page. @return TRUE if possible to merge. */ UNIV_INTERN ibool btr_can_merge_with_page( /*====================*/ btr_cur_t* cursor, /*!< in: cursor on the page to merge */ ulint page_no, /*!< in: a sibling page */ buf_block_t** merge_block, /*!< out: the merge block */ mtr_t* mtr); /*!< in: mini-transaction */ #endif /* UNIV_HOTBACKUP */ /**************************************************************//** Report that an index page is corrupted. */ UNIV_INTERN void btr_corruption_report( /*==================*/ const buf_block_t* block, /*!< in: corrupted block */ const dict_index_t* index) /*!< in: index tree */ { fprintf(stderr, "InnoDB: flag mismatch in space %u page %u" " index %s of table %s\n", (unsigned) buf_block_get_space(block), (unsigned) buf_block_get_page_no(block), index->name, index->table_name); if (block->page.zip.data) { buf_page_print(block->page.zip.data, buf_block_get_zip_size(block), BUF_PAGE_PRINT_NO_CRASH); } buf_page_print(buf_block_get_frame(block), 0, 0); } #ifndef UNIV_HOTBACKUP #ifdef UNIV_BLOB_DEBUG # include "srv0srv.h" # include "ut0rbt.h" /** TRUE when messages about index->blobs modification are enabled. */ static ibool btr_blob_dbg_msg; /** Issue a message about an operation on index->blobs. @param op operation @param b the entry being subjected to the operation @param ctx the context of the operation */ #define btr_blob_dbg_msg_issue(op, b, ctx) \ fprintf(stderr, op " %u:%u:%u->%u %s(%u,%u,%u)\n", \ (b)->ref_page_no, (b)->ref_heap_no, \ (b)->ref_field_no, (b)->blob_page_no, ctx, \ (b)->owner, (b)->always_owner, (b)->del) /** Insert to index->blobs a reference to an off-page column. @param index the index tree @param b the reference @param ctx context (for logging) */ UNIV_INTERN void btr_blob_dbg_rbt_insert( /*====================*/ dict_index_t* index, /*!< in/out: index tree */ const btr_blob_dbg_t* b, /*!< in: the reference */ const char* ctx) /*!< in: context (for logging) */ { if (btr_blob_dbg_msg) { btr_blob_dbg_msg_issue("insert", b, ctx); } mutex_enter(&index->blobs_mutex); rbt_insert(index->blobs, b, b); mutex_exit(&index->blobs_mutex); } /** Remove from index->blobs a reference to an off-page column. @param index the index tree @param b the reference @param ctx context (for logging) */ UNIV_INTERN void btr_blob_dbg_rbt_delete( /*====================*/ dict_index_t* index, /*!< in/out: index tree */ const btr_blob_dbg_t* b, /*!< in: the reference */ const char* ctx) /*!< in: context (for logging) */ { if (btr_blob_dbg_msg) { btr_blob_dbg_msg_issue("delete", b, ctx); } mutex_enter(&index->blobs_mutex); ut_a(rbt_delete(index->blobs, b)); mutex_exit(&index->blobs_mutex); } /**************************************************************//** Comparator for items (btr_blob_dbg_t) in index->blobs. The key in index->blobs is (ref_page_no, ref_heap_no, ref_field_no). @return negative, 0 or positive if *a<*b, *a=*b, *a>*b */ static int btr_blob_dbg_cmp( /*=============*/ const void* a, /*!< in: first btr_blob_dbg_t to compare */ const void* b) /*!< in: second btr_blob_dbg_t to compare */ { const btr_blob_dbg_t* aa = static_cast<const btr_blob_dbg_t*>(a); const btr_blob_dbg_t* bb = static_cast<const btr_blob_dbg_t*>(b); ut_ad(aa != NULL); ut_ad(bb != NULL); if (aa->ref_page_no != bb->ref_page_no) { return(aa->ref_page_no < bb->ref_page_no ? -1 : 1); } if (aa->ref_heap_no != bb->ref_heap_no) { return(aa->ref_heap_no < bb->ref_heap_no ? -1 : 1); } if (aa->ref_field_no != bb->ref_field_no) { return(aa->ref_field_no < bb->ref_field_no ? -1 : 1); } return(0); } /**************************************************************//** Add a reference to an off-page column to the index->blobs map. */ UNIV_INTERN void btr_blob_dbg_add_blob( /*==================*/ const rec_t* rec, /*!< in: clustered index record */ ulint field_no, /*!< in: off-page column number */ ulint page_no, /*!< in: start page of the column */ dict_index_t* index, /*!< in/out: index tree */ const char* ctx) /*!< in: context (for logging) */ { btr_blob_dbg_t b; const page_t* page = page_align(rec); ut_a(index->blobs); b.blob_page_no = page_no; b.ref_page_no = page_get_page_no(page); b.ref_heap_no = page_rec_get_heap_no(rec); b.ref_field_no = field_no; ut_a(b.ref_field_no >= index->n_uniq); b.always_owner = b.owner = TRUE; b.del = FALSE; ut_a(!rec_get_deleted_flag(rec, page_is_comp(page))); btr_blob_dbg_rbt_insert(index, &b, ctx); } /**************************************************************//** Add to index->blobs any references to off-page columns from a record. @return number of references added */ UNIV_INTERN ulint btr_blob_dbg_add_rec( /*=================*/ const rec_t* rec, /*!< in: record */ dict_index_t* index, /*!< in/out: index */ const ulint* offsets,/*!< in: offsets */ const char* ctx) /*!< in: context (for logging) */ { ulint count = 0; ulint i; btr_blob_dbg_t b; ibool del; ut_ad(rec_offs_validate(rec, index, offsets)); if (!rec_offs_any_extern(offsets)) { return(0); } b.ref_page_no = page_get_page_no(page_align(rec)); b.ref_heap_no = page_rec_get_heap_no(rec); del = (rec_get_deleted_flag(rec, rec_offs_comp(offsets)) != 0); for (i = 0; i < rec_offs_n_fields(offsets); i++) { if (rec_offs_nth_extern(offsets, i)) { ulint len; const byte* field_ref = rec_get_nth_field( rec, offsets, i, &len); ut_a(len != UNIV_SQL_NULL); ut_a(len >= BTR_EXTERN_FIELD_REF_SIZE); field_ref += len - BTR_EXTERN_FIELD_REF_SIZE; if (!memcmp(field_ref, field_ref_zero, BTR_EXTERN_FIELD_REF_SIZE)) { /* the column has not been stored yet */ continue; } b.ref_field_no = i; b.blob_page_no = mach_read_from_4( field_ref + BTR_EXTERN_PAGE_NO); ut_a(b.ref_field_no >= index->n_uniq); b.always_owner = b.owner = !(field_ref[BTR_EXTERN_LEN] & BTR_EXTERN_OWNER_FLAG); b.del = del; btr_blob_dbg_rbt_insert(index, &b, ctx); count++; } } return(count); } /**************************************************************//** Display the references to off-page columns. This function is to be called from a debugger, for example when a breakpoint on ut_dbg_assertion_failed is hit. */ UNIV_INTERN void btr_blob_dbg_print( /*===============*/ const dict_index_t* index) /*!< in: index tree */ { const ib_rbt_node_t* node; if (!index->blobs) { return; } /* We intentionally do not acquire index->blobs_mutex here. This function is to be called from a debugger, and the caller should make sure that the index->blobs_mutex is held. */ for (node = rbt_first(index->blobs); node != NULL; node = rbt_next(index->blobs, node)) { const btr_blob_dbg_t* b = rbt_value(btr_blob_dbg_t, node); fprintf(stderr, "%u:%u:%u->%u%s%s%s\n", b->ref_page_no, b->ref_heap_no, b->ref_field_no, b->blob_page_no, b->owner ? "" : "(disowned)", b->always_owner ? "" : "(has disowned)", b->del ? "(deleted)" : ""); } } /**************************************************************//** Remove from index->blobs any references to off-page columns from a record. @return number of references removed */ UNIV_INTERN ulint btr_blob_dbg_remove_rec( /*====================*/ const rec_t* rec, /*!< in: record */ dict_index_t* index, /*!< in/out: index */ const ulint* offsets,/*!< in: offsets */ const char* ctx) /*!< in: context (for logging) */ { ulint i; ulint count = 0; btr_blob_dbg_t b; ut_ad(rec_offs_validate(rec, index, offsets)); if (!rec_offs_any_extern(offsets)) { return(0); } b.ref_page_no = page_get_page_no(page_align(rec)); b.ref_heap_no = page_rec_get_heap_no(rec); for (i = 0; i < rec_offs_n_fields(offsets); i++) { if (rec_offs_nth_extern(offsets, i)) { ulint len; const byte* field_ref = rec_get_nth_field( rec, offsets, i, &len); ut_a(len != UNIV_SQL_NULL); ut_a(len >= BTR_EXTERN_FIELD_REF_SIZE); field_ref += len - BTR_EXTERN_FIELD_REF_SIZE; b.ref_field_no = i; b.blob_page_no = mach_read_from_4( field_ref + BTR_EXTERN_PAGE_NO); switch (b.blob_page_no) { case 0: /* The column has not been stored yet. The BLOB pointer must be all zero. There cannot be a BLOB starting at page 0, because page 0 is reserved for the tablespace header. */ ut_a(!memcmp(field_ref, field_ref_zero, BTR_EXTERN_FIELD_REF_SIZE)); /* fall through */ case FIL_NULL: /* the column has been freed already */ continue; } btr_blob_dbg_rbt_delete(index, &b, ctx); count++; } } return(count); } /**************************************************************//** Check that there are no references to off-page columns from or to the given page. Invoked when freeing or clearing a page. @return TRUE when no orphan references exist */ UNIV_INTERN ibool btr_blob_dbg_is_empty( /*==================*/ dict_index_t* index, /*!< in: index */ ulint page_no) /*!< in: page number */ { const ib_rbt_node_t* node; ibool success = TRUE; if (!index->blobs) { return(success); } mutex_enter(&index->blobs_mutex); for (node = rbt_first(index->blobs); node != NULL; node = rbt_next(index->blobs, node)) { const btr_blob_dbg_t* b = rbt_value(btr_blob_dbg_t, node); if (b->ref_page_no != page_no && b->blob_page_no != page_no) { continue; } fprintf(stderr, "InnoDB: orphan BLOB ref%s%s%s %u:%u:%u->%u\n", b->owner ? "" : "(disowned)", b->always_owner ? "" : "(has disowned)", b->del ? "(deleted)" : "", b->ref_page_no, b->ref_heap_no, b->ref_field_no, b->blob_page_no); if (b->blob_page_no != page_no || b->owner || !b->del) { success = FALSE; } } mutex_exit(&index->blobs_mutex); return(success); } /**************************************************************//** Count and process all references to off-page columns on a page. @return number of references processed */ UNIV_INTERN ulint btr_blob_dbg_op( /*============*/ const page_t* page, /*!< in: B-tree leaf page */ const rec_t* rec, /*!< in: record to start from (NULL to process the whole page) */ dict_index_t* index, /*!< in/out: index */ const char* ctx, /*!< in: context (for logging) */ const btr_blob_dbg_op_f op) /*!< in: operation on records */ { ulint count = 0; mem_heap_t* heap = NULL; ulint offsets_[REC_OFFS_NORMAL_SIZE]; ulint* offsets = offsets_; rec_offs_init(offsets_); ut_a(fil_page_get_type(page) == FIL_PAGE_INDEX); ut_a(!rec || page_align(rec) == page); if (!index->blobs || !page_is_leaf(page) || !dict_index_is_clust(index)) { return(0); } if (rec == NULL) { rec = page_get_infimum_rec(page); } do { offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); count += op(rec, index, offsets, ctx); rec = page_rec_get_next_const(rec); } while (!page_rec_is_supremum(rec)); if (heap) { mem_heap_free(heap); } return(count); } /**************************************************************//** Count and add to index->blobs any references to off-page columns from records on a page. @return number of references added */ UNIV_INTERN ulint btr_blob_dbg_add( /*=============*/ const page_t* page, /*!< in: rewritten page */ dict_index_t* index, /*!< in/out: index */ const char* ctx) /*!< in: context (for logging) */ { btr_blob_dbg_assert_empty(index, page_get_page_no(page)); return(btr_blob_dbg_op(page, NULL, index, ctx, btr_blob_dbg_add_rec)); } /**************************************************************//** Count and remove from index->blobs any references to off-page columns from records on a page. Used when reorganizing a page, before copying the records. @return number of references removed */ UNIV_INTERN ulint btr_blob_dbg_remove( /*================*/ const page_t* page, /*!< in: b-tree page */ dict_index_t* index, /*!< in/out: index */ const char* ctx) /*!< in: context (for logging) */ { ulint count; count = btr_blob_dbg_op(page, NULL, index, ctx, btr_blob_dbg_remove_rec); /* Check that no references exist. */ btr_blob_dbg_assert_empty(index, page_get_page_no(page)); return(count); } /**************************************************************//** Restore in index->blobs any references to off-page columns Used when page reorganize fails due to compressed page overflow. */ UNIV_INTERN void btr_blob_dbg_restore( /*=================*/ const page_t* npage, /*!< in: page that failed to compress */ const page_t* page, /*!< in: copy of original page */ dict_index_t* index, /*!< in/out: index */ const char* ctx) /*!< in: context (for logging) */ { ulint removed; ulint added; ut_a(page_get_page_no(npage) == page_get_page_no(page)); ut_a(page_get_space_id(npage) == page_get_space_id(page)); removed = btr_blob_dbg_remove(npage, index, ctx); added = btr_blob_dbg_add(page, index, ctx); ut_a(added == removed); } /**************************************************************//** Modify the 'deleted' flag of a record. */ UNIV_INTERN void btr_blob_dbg_set_deleted_flag( /*==========================*/ const rec_t* rec, /*!< in: record */ dict_index_t* index, /*!< in/out: index */ const ulint* offsets,/*!< in: rec_get_offs(rec, index) */ ibool del) /*!< in: TRUE=deleted, FALSE=exists */ { const ib_rbt_node_t* node; btr_blob_dbg_t b; btr_blob_dbg_t* c; ulint i; ut_ad(rec_offs_validate(rec, index, offsets)); ut_a(dict_index_is_clust(index)); ut_a(del == !!del);/* must be FALSE==0 or TRUE==1 */ if (!rec_offs_any_extern(offsets) || !index->blobs) { return; } b.ref_page_no = page_get_page_no(page_align(rec)); b.ref_heap_no = page_rec_get_heap_no(rec); for (i = 0; i < rec_offs_n_fields(offsets); i++) { if (rec_offs_nth_extern(offsets, i)) { ulint len; const byte* field_ref = rec_get_nth_field( rec, offsets, i, &len); ut_a(len != UNIV_SQL_NULL); ut_a(len >= BTR_EXTERN_FIELD_REF_SIZE); field_ref += len - BTR_EXTERN_FIELD_REF_SIZE; b.ref_field_no = i; b.blob_page_no = mach_read_from_4( field_ref + BTR_EXTERN_PAGE_NO); switch (b.blob_page_no) { case 0: ut_a(memcmp(field_ref, field_ref_zero, BTR_EXTERN_FIELD_REF_SIZE)); /* page number 0 is for the page allocation bitmap */ case FIL_NULL: /* the column has been freed already */ ut_error; } mutex_enter(&index->blobs_mutex); node = rbt_lookup(index->blobs, &b); ut_a(node); c = rbt_value(btr_blob_dbg_t, node); /* The flag should be modified. */ c->del = del; if (btr_blob_dbg_msg) { b = *c; mutex_exit(&index->blobs_mutex); btr_blob_dbg_msg_issue("del_mk", &b, ""); } else { mutex_exit(&index->blobs_mutex); } } } } /**************************************************************//** Change the ownership of an off-page column. */ UNIV_INTERN void btr_blob_dbg_owner( /*===============*/ const rec_t* rec, /*!< in: record */ dict_index_t* index, /*!< in/out: index */ const ulint* offsets,/*!< in: rec_get_offs(rec, index) */ ulint i, /*!< in: ith field in rec */ ibool own) /*!< in: TRUE=owned, FALSE=disowned */ { const ib_rbt_node_t* node; btr_blob_dbg_t b; const byte* field_ref; ulint len; ut_ad(rec_offs_validate(rec, index, offsets)); ut_a(rec_offs_nth_extern(offsets, i)); field_ref = rec_get_nth_field(rec, offsets, i, &len); ut_a(len != UNIV_SQL_NULL); ut_a(len >= BTR_EXTERN_FIELD_REF_SIZE); field_ref += len - BTR_EXTERN_FIELD_REF_SIZE; b.ref_page_no = page_get_page_no(page_align(rec)); b.ref_heap_no = page_rec_get_heap_no(rec); b.ref_field_no = i; b.owner = !(field_ref[BTR_EXTERN_LEN] & BTR_EXTERN_OWNER_FLAG); b.blob_page_no = mach_read_from_4(field_ref + BTR_EXTERN_PAGE_NO); ut_a(b.owner == own); mutex_enter(&index->blobs_mutex); node = rbt_lookup(index->blobs, &b); /* row_ins_clust_index_entry_by_modify() invokes btr_cur_unmark_extern_fields() also for the newly inserted references, which are all zero bytes until the columns are stored. The node lookup must fail if and only if that is the case. */ ut_a(!memcmp(field_ref, field_ref_zero, BTR_EXTERN_FIELD_REF_SIZE) == !node); if (node) { btr_blob_dbg_t* c = rbt_value(btr_blob_dbg_t, node); /* Some code sets ownership from TRUE to TRUE. We do not allow changing ownership from FALSE to FALSE. */ ut_a(own || c->owner); c->owner = own; if (!own) { c->always_owner = FALSE; } } mutex_exit(&index->blobs_mutex); } #endif /* UNIV_BLOB_DEBUG */ /* Latching strategy of the InnoDB B-tree -------------------------------------- A tree latch protects all non-leaf nodes of the tree. Each node of a tree also has a latch of its own. A B-tree operation normally first acquires an S-latch on the tree. It searches down the tree and releases the tree latch when it has the leaf node latch. To save CPU time we do not acquire any latch on non-leaf nodes of the tree during a search, those pages are only bufferfixed. If an operation needs to restructure the tree, it acquires an X-latch on the tree before searching to a leaf node. If it needs, for example, to split a leaf, (1) InnoDB decides the split point in the leaf, (2) allocates a new page, (3) inserts the appropriate node pointer to the first non-leaf level, (4) releases the tree X-latch, (5) and then moves records from the leaf to the new allocated page. Node pointers ------------- Leaf pages of a B-tree contain the index records stored in the tree. On levels n > 0 we store 'node pointers' to pages on level n - 1. For each page there is exactly one node pointer stored: thus the our tree is an ordinary B-tree, not a B-link tree. A node pointer contains a prefix P of an index record. The prefix is long enough so that it determines an index record uniquely. The file page number of the child page is added as the last field. To the child page we can store node pointers or index records which are >= P in the alphabetical order, but < P1 if there is a next node pointer on the level, and P1 is its prefix. If a node pointer with a prefix P points to a non-leaf child, then the leftmost record in the child must have the same prefix P. If it points to a leaf node, the child is not required to contain any record with a prefix equal to P. The leaf case is decided this way to allow arbitrary deletions in a leaf node without touching upper levels of the tree. We have predefined a special minimum record which we define as the smallest record in any alphabetical order. A minimum record is denoted by setting a bit in the record header. A minimum record acts as the prefix of a node pointer which points to a leftmost node on any level of the tree. File page allocation -------------------- In the root node of a B-tree there are two file segment headers. The leaf pages of a tree are allocated from one file segment, to make them consecutive on disk if possible. From the other file segment we allocate pages for the non-leaf levels of the tree. */ #ifdef UNIV_BTR_DEBUG /**************************************************************//** Checks a file segment header within a B-tree root page. @return TRUE if valid */ static ibool btr_root_fseg_validate( /*===================*/ const fseg_header_t* seg_header, /*!< in: segment header */ ulint space) /*!< in: tablespace identifier */ { ulint offset = mach_read_from_2(seg_header + FSEG_HDR_OFFSET); ut_a(mach_read_from_4(seg_header + FSEG_HDR_SPACE) == space); ut_a(offset >= FIL_PAGE_DATA); ut_a(offset <= UNIV_PAGE_SIZE - FIL_PAGE_DATA_END); return(TRUE); } #endif /* UNIV_BTR_DEBUG */ /**************************************************************//** Gets the root node of a tree and x- or s-latches it. @return root page, x- or s-latched */ static buf_block_t* btr_root_block_get( /*===============*/ const dict_index_t* index, /*!< in: index tree */ ulint mode, /*!< in: either RW_S_LATCH or RW_X_LATCH */ mtr_t* mtr) /*!< in: mtr */ { ulint space; ulint zip_size; ulint root_page_no; buf_block_t* block; space = dict_index_get_space(index); zip_size = dict_table_zip_size(index->table); root_page_no = dict_index_get_page(index); block = btr_block_get(space, zip_size, root_page_no, mode, (dict_index_t*)index, mtr); if (!block) { if (index && index->table) { index->table->is_encrypted = TRUE; index->table->corrupted = FALSE; ib_push_warning(index->table->thd, DB_DECRYPTION_FAILED, "Table %s in tablespace %lu is encrypted but encryption service or" " used key_id is not available. " " Can't continue reading table.", index->table->name, space); } return NULL; } btr_assert_not_corrupted(block, index); #ifdef UNIV_BTR_DEBUG if (!dict_index_is_ibuf(index)) { const page_t* root = buf_block_get_frame(block); ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF + root, space)); ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP + root, space)); } #endif /* UNIV_BTR_DEBUG */ return(block); } /**************************************************************//** Gets the root node of a tree and x-latches it. @return root page, x-latched */ UNIV_INTERN page_t* btr_root_get( /*=========*/ const dict_index_t* index, /*!< in: index tree */ mtr_t* mtr) /*!< in: mtr */ { buf_block_t* root = btr_root_block_get(index, RW_X_LATCH, mtr); if (root && root->page.encrypted == true) { root = NULL; } return(root ? buf_block_get_frame(root) : NULL); } /**************************************************************//** Gets the height of the B-tree (the level of the root, when the leaf level is assumed to be 0). The caller must hold an S or X latch on the index. @return tree height (level of the root) */ UNIV_INTERN ulint btr_height_get( /*===========*/ dict_index_t* index, /*!< in: index tree */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint height=0; buf_block_t* root_block; ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index), MTR_MEMO_S_LOCK) || mtr_memo_contains(mtr, dict_index_get_lock(index), MTR_MEMO_X_LOCK)); /* S latches the page */ root_block = btr_root_block_get(index, RW_S_LATCH, mtr); if (root_block) { height = btr_page_get_level(buf_block_get_frame(root_block), mtr); /* Release the S latch on the root page. */ mtr_memo_release(mtr, root_block, MTR_MEMO_PAGE_S_FIX); #ifdef UNIV_SYNC_DEBUG sync_thread_reset_level(&root_block->lock); #endif /* UNIV_SYNC_DEBUG */ } return(height); } /**************************************************************//** Checks a file segment header within a B-tree root page and updates the segment header space id. @return TRUE if valid */ static bool btr_root_fseg_adjust_on_import( /*===========================*/ fseg_header_t* seg_header, /*!< in/out: segment header */ page_zip_des_t* page_zip, /*!< in/out: compressed page, or NULL */ ulint space, /*!< in: tablespace identifier */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint offset = mach_read_from_2(seg_header + FSEG_HDR_OFFSET); if (offset < FIL_PAGE_DATA || offset > UNIV_PAGE_SIZE - FIL_PAGE_DATA_END) { return(FALSE); } else if (page_zip) { mach_write_to_4(seg_header + FSEG_HDR_SPACE, space); page_zip_write_header(page_zip, seg_header + FSEG_HDR_SPACE, 4, mtr); } else { mlog_write_ulint(seg_header + FSEG_HDR_SPACE, space, MLOG_4BYTES, mtr); } return(TRUE); } /**************************************************************//** Checks and adjusts the root node of a tree during IMPORT TABLESPACE. @return error code, or DB_SUCCESS */ UNIV_INTERN dberr_t btr_root_adjust_on_import( /*======================*/ const dict_index_t* index) /*!< in: index tree */ { dberr_t err; mtr_t mtr; page_t* page; buf_block_t* block; page_zip_des_t* page_zip; dict_table_t* table = index->table; ulint space_id = dict_index_get_space(index); ulint zip_size = dict_table_zip_size(table); ulint root_page_no = dict_index_get_page(index); mtr_start(&mtr); mtr_set_log_mode(&mtr, MTR_LOG_NO_REDO); DBUG_EXECUTE_IF("ib_import_trigger_corruption_3", return(DB_CORRUPTION);); block = btr_block_get( space_id, zip_size, root_page_no, RW_X_LATCH, (dict_index_t*)index, &mtr); page = buf_block_get_frame(block); page_zip = buf_block_get_page_zip(block); /* Check that this is a B-tree page and both the PREV and NEXT pointers are FIL_NULL, because the root page does not have any siblings. */ if (fil_page_get_type(page) != FIL_PAGE_INDEX || fil_page_get_prev(page) != FIL_NULL || fil_page_get_next(page) != FIL_NULL) { err = DB_CORRUPTION; } else if (dict_index_is_clust(index)) { bool page_is_compact_format; page_is_compact_format = page_is_comp(page) > 0; /* Check if the page format and table format agree. */ if (page_is_compact_format != dict_table_is_comp(table)) { err = DB_CORRUPTION; } else { /* Check that the table flags and the tablespace flags match. */ ulint flags = fil_space_get_flags(table->space); if (flags && flags != dict_tf_to_fsp_flags(table->flags)) { err = DB_CORRUPTION; } else { err = DB_SUCCESS; } } } else { err = DB_SUCCESS; } /* Check and adjust the file segment headers, if all OK so far. */ if (err == DB_SUCCESS && (!btr_root_fseg_adjust_on_import( FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF + page, page_zip, space_id, &mtr) || !btr_root_fseg_adjust_on_import( FIL_PAGE_DATA + PAGE_BTR_SEG_TOP + page, page_zip, space_id, &mtr))) { err = DB_CORRUPTION; } mtr_commit(&mtr); return(err); } /*************************************************************//** Gets pointer to the previous user record in the tree. It is assumed that the caller has appropriate latches on the page and its neighbor. @return previous user record, NULL if there is none */ UNIV_INTERN rec_t* btr_get_prev_user_rec( /*==================*/ rec_t* rec, /*!< in: record on leaf level */ mtr_t* mtr) /*!< in: mtr holding a latch on the page, and if needed, also to the previous page */ { page_t* page; page_t* prev_page; ulint prev_page_no; if (!page_rec_is_infimum(rec)) { rec_t* prev_rec = page_rec_get_prev(rec); if (!page_rec_is_infimum(prev_rec)) { return(prev_rec); } } page = page_align(rec); prev_page_no = btr_page_get_prev(page, mtr); if (prev_page_no != FIL_NULL) { ulint space; ulint zip_size; buf_block_t* prev_block; space = page_get_space_id(page); zip_size = fil_space_get_zip_size(space); prev_block = buf_page_get_with_no_latch(space, zip_size, prev_page_no, mtr); prev_page = buf_block_get_frame(prev_block); /* The caller must already have a latch to the brother */ ut_ad(mtr_memo_contains(mtr, prev_block, MTR_MEMO_PAGE_S_FIX) || mtr_memo_contains(mtr, prev_block, MTR_MEMO_PAGE_X_FIX)); #ifdef UNIV_BTR_DEBUG ut_a(page_is_comp(prev_page) == page_is_comp(page)); ut_a(btr_page_get_next(prev_page, mtr) == page_get_page_no(page)); #endif /* UNIV_BTR_DEBUG */ return(page_rec_get_prev(page_get_supremum_rec(prev_page))); } return(NULL); } /*************************************************************//** Gets pointer to the next user record in the tree. It is assumed that the caller has appropriate latches on the page and its neighbor. @return next user record, NULL if there is none */ UNIV_INTERN rec_t* btr_get_next_user_rec( /*==================*/ rec_t* rec, /*!< in: record on leaf level */ mtr_t* mtr) /*!< in: mtr holding a latch on the page, and if needed, also to the next page */ { page_t* page; page_t* next_page; ulint next_page_no; if (!page_rec_is_supremum(rec)) { rec_t* next_rec = page_rec_get_next(rec); if (!page_rec_is_supremum(next_rec)) { return(next_rec); } } page = page_align(rec); next_page_no = btr_page_get_next(page, mtr); if (next_page_no != FIL_NULL) { ulint space; ulint zip_size; buf_block_t* next_block; space = page_get_space_id(page); zip_size = fil_space_get_zip_size(space); next_block = buf_page_get_with_no_latch(space, zip_size, next_page_no, mtr); next_page = buf_block_get_frame(next_block); /* The caller must already have a latch to the brother */ ut_ad(mtr_memo_contains(mtr, next_block, MTR_MEMO_PAGE_S_FIX) || mtr_memo_contains(mtr, next_block, MTR_MEMO_PAGE_X_FIX)); #ifdef UNIV_BTR_DEBUG ut_a(page_is_comp(next_page) == page_is_comp(page)); ut_a(btr_page_get_prev(next_page, mtr) == page_get_page_no(page)); #endif /* UNIV_BTR_DEBUG */ return(page_rec_get_next(page_get_infimum_rec(next_page))); } return(NULL); } /**************************************************************//** Creates a new index page (not the root, and also not used in page reorganization). @see btr_page_empty(). */ static void btr_page_create( /*============*/ buf_block_t* block, /*!< in/out: page to be created */ page_zip_des_t* page_zip,/*!< in/out: compressed page, or NULL */ dict_index_t* index, /*!< in: index */ ulint level, /*!< in: the B-tree level of the page */ mtr_t* mtr) /*!< in: mtr */ { page_t* page = buf_block_get_frame(block); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); btr_blob_dbg_assert_empty(index, buf_block_get_page_no(block)); if (page_zip) { page_create_zip(block, index, level, 0, mtr); } else { page_create(block, mtr, dict_table_is_comp(index->table)); /* Set the level of the new index page */ btr_page_set_level(page, NULL, level, mtr); } block->check_index_page_at_flush = TRUE; btr_page_set_index_id(page, page_zip, index->id, mtr); } /**************************************************************//** Allocates a new file page to be used in an ibuf tree. Takes the page from the free list of the tree, which must contain pages! @return new allocated block, x-latched */ static buf_block_t* btr_page_alloc_for_ibuf( /*====================*/ dict_index_t* index, /*!< in: index tree */ mtr_t* mtr) /*!< in: mtr */ { fil_addr_t node_addr; page_t* root; page_t* new_page; buf_block_t* new_block; root = btr_root_get(index, mtr); node_addr = flst_get_first(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, mtr); ut_a(node_addr.page != FIL_NULL); new_block = buf_page_get(dict_index_get_space(index), dict_table_zip_size(index->table), node_addr.page, RW_X_LATCH, mtr); new_page = buf_block_get_frame(new_block); buf_block_dbg_add_level(new_block, SYNC_IBUF_TREE_NODE_NEW); flst_remove(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, new_page + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST_NODE, mtr); ut_ad(flst_validate(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, mtr)); return(new_block); } /**************************************************************//** Allocates a new file page to be used in an index tree. NOTE: we assume that the caller has made the reservation for free extents! @retval NULL if no page could be allocated @retval block, rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded (init_mtr == mtr, or the page was not previously freed in mtr) @retval block (not allocated or initialized) otherwise */ static MY_ATTRIBUTE((nonnull, warn_unused_result)) buf_block_t* btr_page_alloc_low( /*===============*/ dict_index_t* index, /*!< in: index */ ulint hint_page_no, /*!< in: hint of a good page */ byte file_direction, /*!< in: direction where a possible page split is made */ ulint level, /*!< in: level where the page is placed in the tree */ mtr_t* mtr, /*!< in/out: mini-transaction for the allocation */ mtr_t* init_mtr) /*!< in/out: mtr or another mini-transaction in which the page should be initialized. If init_mtr!=mtr, but the page is already X-latched in mtr, do not initialize the page. */ { fseg_header_t* seg_header; page_t* root; root = btr_root_get(index, mtr); if (level == 0) { seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_LEAF; } else { seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_TOP; } /* Parameter TRUE below states that the caller has made the reservation for free extents, and thus we know that a page can be allocated: */ buf_block_t* block = fseg_alloc_free_page_general( seg_header, hint_page_no, file_direction, TRUE, mtr, init_mtr); #ifdef UNIV_DEBUG_SCRUBBING if (block != NULL) { fprintf(stderr, "alloc %lu:%lu to index: %lu root: %lu\n", buf_block_get_page_no(block), buf_block_get_space(block), index->id, dict_index_get_page(index)); } else { fprintf(stderr, "failed alloc index: %lu root: %lu\n", index->id, dict_index_get_page(index)); } #endif /* UNIV_DEBUG_SCRUBBING */ return block; } /**************************************************************//** Allocates a new file page to be used in an index tree. NOTE: we assume that the caller has made the reservation for free extents! @retval NULL if no page could be allocated @retval block, rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded (init_mtr == mtr, or the page was not previously freed in mtr) @retval block (not allocated or initialized) otherwise */ UNIV_INTERN buf_block_t* btr_page_alloc( /*===========*/ dict_index_t* index, /*!< in: index */ ulint hint_page_no, /*!< in: hint of a good page */ byte file_direction, /*!< in: direction where a possible page split is made */ ulint level, /*!< in: level where the page is placed in the tree */ mtr_t* mtr, /*!< in/out: mini-transaction for the allocation */ mtr_t* init_mtr) /*!< in/out: mini-transaction for x-latching and initializing the page */ { buf_block_t* new_block; if (dict_index_is_ibuf(index)) { return(btr_page_alloc_for_ibuf(index, mtr)); } new_block = btr_page_alloc_low( index, hint_page_no, file_direction, level, mtr, init_mtr); if (new_block) { buf_block_dbg_add_level(new_block, SYNC_TREE_NODE_NEW); } return(new_block); } /**************************************************************//** Gets the number of pages in a B-tree. @return number of pages, or ULINT_UNDEFINED if the index is unavailable */ UNIV_INTERN ulint btr_get_size( /*=========*/ dict_index_t* index, /*!< in: index */ ulint flag, /*!< in: BTR_N_LEAF_PAGES or BTR_TOTAL_SIZE */ mtr_t* mtr) /*!< in/out: mini-transaction where index is s-latched */ { ulint used; if (flag == BTR_N_LEAF_PAGES) { btr_get_size_and_reserved(index, flag, &used, mtr); return used; } else if (flag == BTR_TOTAL_SIZE) { return btr_get_size_and_reserved(index, flag, &used, mtr); } else { ut_error; } return (ULINT_UNDEFINED); } /**************************************************************//** Gets the number of reserved and used pages in a B-tree. @return number of pages reserved, or ULINT_UNDEFINED if the index is unavailable */ UNIV_INTERN ulint btr_get_size_and_reserved( /*======================*/ dict_index_t* index, /*!< in: index */ ulint flag, /*!< in: BTR_N_LEAF_PAGES or BTR_TOTAL_SIZE */ ulint* used, /*!< out: number of pages used (<= reserved) */ mtr_t* mtr) /*!< in/out: mini-transaction where index is s-latched */ { fseg_header_t* seg_header; page_t* root; ulint n=ULINT_UNDEFINED; ulint dummy; ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index), MTR_MEMO_S_LOCK)); ut_a(flag == BTR_N_LEAF_PAGES || flag == BTR_TOTAL_SIZE); if (index->page == FIL_NULL || dict_index_is_online_ddl(index) || *index->name == TEMP_INDEX_PREFIX) { return(ULINT_UNDEFINED); } root = btr_root_get(index, mtr); *used = 0; if (root) { seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_LEAF; n = fseg_n_reserved_pages(seg_header, used, mtr); if (flag == BTR_TOTAL_SIZE) { seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_TOP; n += fseg_n_reserved_pages(seg_header, &dummy, mtr); *used += dummy; } } return(n); } /**************************************************************//** Frees a page used in an ibuf tree. Puts the page to the free list of the ibuf tree. */ static void btr_page_free_for_ibuf( /*===================*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: block to be freed, x-latched */ mtr_t* mtr) /*!< in: mtr */ { page_t* root; ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); root = btr_root_get(index, mtr); flst_add_first(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, buf_block_get_frame(block) + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST_NODE, mtr); ut_ad(flst_validate(root + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, mtr)); } /**************************************************************//** Frees a file page used in an index tree. Can be used also to (BLOB) external storage pages, because the page level 0 can be given as an argument. */ UNIV_INTERN void btr_page_free_low( /*==============*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: block to be freed, x-latched */ ulint level, /*!< in: page level */ bool blob, /*!< in: blob page */ mtr_t* mtr) /*!< in: mtr */ { fseg_header_t* seg_header; page_t* root; ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); /* The page gets invalid for optimistic searches: increment the frame modify clock */ buf_block_modify_clock_inc(block); btr_blob_dbg_assert_empty(index, buf_block_get_page_no(block)); if (blob) { ut_a(level == 0); } bool scrub = srv_immediate_scrub_data_uncompressed; /* scrub page */ if (scrub && blob) { /* blob page: scrub entire page */ // TODO(jonaso): scrub only what is actually needed page_t* page = buf_block_get_frame(block); memset(page + PAGE_HEADER, 0, UNIV_PAGE_SIZE - PAGE_HEADER); #ifdef UNIV_DEBUG_SCRUBBING fprintf(stderr, "btr_page_free_low: scrub blob page %lu/%lu\n", buf_block_get_space(block), buf_block_get_page_no(block)); #endif /* UNIV_DEBUG_SCRUBBING */ } else if (scrub) { /* scrub records on page */ /* TODO(jonaso): in theory we could clear full page * but, since page still remains in buffer pool, and * gets flushed etc. Lots of routines validates consistency * of it. And in order to remain structurally consistent * we clear each record by it own * * NOTE: The TODO below mentions removing page from buffer pool * and removing redo entries, once that is done, clearing full * pages should be possible */ uint cnt = 0; uint bytes = 0; page_t* page = buf_block_get_frame(block); mem_heap_t* heap = NULL; ulint* offsets = NULL; rec_t* rec = page_rec_get_next(page_get_infimum_rec(page)); while (!page_rec_is_supremum(rec)) { offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); uint size = rec_offs_data_size(offsets); memset(rec, 0, size); rec = page_rec_get_next(rec); cnt++; bytes += size; } #ifdef UNIV_DEBUG_SCRUBBING fprintf(stderr, "btr_page_free_low: scrub %lu/%lu - " "%u records %u bytes\n", buf_block_get_space(block), buf_block_get_page_no(block), cnt, bytes); #endif /* UNIV_DEBUG_SCRUBBING */ if (heap) { mem_heap_free(heap); } } #ifdef UNIV_DEBUG_SCRUBBING if (scrub == false) { fprintf(stderr, "btr_page_free_low %lu/%lu blob: %u\n", buf_block_get_space(block), buf_block_get_page_no(block), blob); } #endif /* UNIV_DEBUG_SCRUBBING */ if (dict_index_is_ibuf(index)) { btr_page_free_for_ibuf(index, block, mtr); return; } root = btr_root_get(index, mtr); if (level == 0) { seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_LEAF; } else { seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_TOP; } if (scrub) { /** * Reset page type so that scrub thread won't try to scrub it */ mlog_write_ulint(buf_block_get_frame(block) + FIL_PAGE_TYPE, FIL_PAGE_TYPE_ALLOCATED, MLOG_2BYTES, mtr); } fseg_free_page(seg_header, buf_block_get_space(block), buf_block_get_page_no(block), mtr); /* The page was marked free in the allocation bitmap, but it should remain buffer-fixed until mtr_commit(mtr) or until it is explicitly freed from the mini-transaction. */ ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); /* TODO: Discard any operations on the page from the redo log and remove the block from the flush list and the buffer pool. This would free up buffer pool earlier and reduce writes to both the tablespace and the redo log. */ } /**************************************************************//** Frees a file page used in an index tree. NOTE: cannot free field external storage pages because the page must contain info on its level. */ UNIV_INTERN void btr_page_free( /*==========*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: block to be freed, x-latched */ mtr_t* mtr) /*!< in: mtr */ { const page_t* page = buf_block_get_frame(block); ulint level = btr_page_get_level(page, mtr); ut_ad(fil_page_get_type(block->frame) == FIL_PAGE_INDEX); btr_page_free_low(index, block, level, false, mtr); } /**************************************************************//** Sets the child node file address in a node pointer. */ UNIV_INLINE void btr_node_ptr_set_child_page_no( /*===========================*/ rec_t* rec, /*!< in: node pointer record */ page_zip_des_t* page_zip,/*!< in/out: compressed page whose uncompressed part will be updated, or NULL */ const ulint* offsets,/*!< in: array returned by rec_get_offsets() */ ulint page_no,/*!< in: child node address */ mtr_t* mtr) /*!< in: mtr */ { byte* field; ulint len; ut_ad(rec_offs_validate(rec, NULL, offsets)); ut_ad(!page_is_leaf(page_align(rec))); ut_ad(!rec_offs_comp(offsets) || rec_get_node_ptr_flag(rec)); /* The child address is in the last field */ field = rec_get_nth_field(rec, offsets, rec_offs_n_fields(offsets) - 1, &len); ut_ad(len == REC_NODE_PTR_SIZE); if (page_zip) { page_zip_write_node_ptr(page_zip, rec, rec_offs_data_size(offsets), page_no, mtr); } else { mlog_write_ulint(field, page_no, MLOG_4BYTES, mtr); } } /************************************************************//** Returns the child page of a node pointer and x-latches it. @return child page, x-latched */ static buf_block_t* btr_node_ptr_get_child( /*===================*/ const rec_t* node_ptr,/*!< in: node pointer */ dict_index_t* index, /*!< in: index */ const ulint* offsets,/*!< in: array returned by rec_get_offsets() */ mtr_t* mtr) /*!< in: mtr */ { ulint page_no; ulint space; ut_ad(rec_offs_validate(node_ptr, index, offsets)); space = page_get_space_id(page_align(node_ptr)); page_no = btr_node_ptr_get_child_page_no(node_ptr, offsets); return(btr_block_get(space, dict_table_zip_size(index->table), page_no, RW_X_LATCH, index, mtr)); } /************************************************************//** Returns the upper level node pointer to a page. It is assumed that mtr holds an x-latch on the tree. @return rec_get_offsets() of the node pointer record */ static ulint* btr_page_get_father_node_ptr_func( /*==============================*/ ulint* offsets,/*!< in: work area for the return value */ mem_heap_t* heap, /*!< in: memory heap to use */ btr_cur_t* cursor, /*!< in: cursor pointing to user record, out: cursor on node pointer record, its page x-latched */ const char* file, /*!< in: file name */ ulint line, /*!< in: line where called */ mtr_t* mtr) /*!< in: mtr */ { dtuple_t* tuple; rec_t* user_rec; rec_t* node_ptr; ulint level; ulint page_no; dict_index_t* index; page_no = buf_block_get_page_no(btr_cur_get_block(cursor)); index = btr_cur_get_index(cursor); ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index), MTR_MEMO_X_LOCK)); ut_ad(dict_index_get_page(index) != page_no); level = btr_page_get_level(btr_cur_get_page(cursor), mtr); user_rec = btr_cur_get_rec(cursor); ut_a(page_rec_is_user_rec(user_rec)); tuple = dict_index_build_node_ptr(index, user_rec, 0, heap, level); btr_cur_search_to_nth_level(index, level + 1, tuple, PAGE_CUR_LE, BTR_CONT_MODIFY_TREE, cursor, 0, file, line, mtr); node_ptr = btr_cur_get_rec(cursor); ut_ad(!page_rec_is_comp(node_ptr) || rec_get_status(node_ptr) == REC_STATUS_NODE_PTR); offsets = rec_get_offsets(node_ptr, index, offsets, ULINT_UNDEFINED, &heap); if (btr_node_ptr_get_child_page_no(node_ptr, offsets) != page_no) { rec_t* print_rec; fputs("InnoDB: Dump of the child page:\n", stderr); buf_page_print(page_align(user_rec), 0, BUF_PAGE_PRINT_NO_CRASH); fputs("InnoDB: Dump of the parent page:\n", stderr); buf_page_print(page_align(node_ptr), 0, BUF_PAGE_PRINT_NO_CRASH); fputs("InnoDB: Corruption of an index tree: table ", stderr); ut_print_name(stderr, NULL, TRUE, index->table_name); fputs(", index ", stderr); ut_print_name(stderr, NULL, FALSE, index->name); fprintf(stderr, ",\n" "InnoDB: father ptr page no %lu, child page no %lu\n", (ulong) btr_node_ptr_get_child_page_no(node_ptr, offsets), (ulong) page_no); print_rec = page_rec_get_next( page_get_infimum_rec(page_align(user_rec))); offsets = rec_get_offsets(print_rec, index, offsets, ULINT_UNDEFINED, &heap); page_rec_print(print_rec, offsets); offsets = rec_get_offsets(node_ptr, index, offsets, ULINT_UNDEFINED, &heap); page_rec_print(node_ptr, offsets); fputs("InnoDB: You should dump + drop + reimport the table" " to fix the\n" "InnoDB: corruption. If the crash happens at " "the database startup, see\n" "InnoDB: " REFMAN "forcing-innodb-recovery.html about\n" "InnoDB: forcing recovery. " "Then dump + drop + reimport.\n", stderr); ut_error; } return(offsets); } #define btr_page_get_father_node_ptr(of,heap,cur,mtr) \ btr_page_get_father_node_ptr_func(of,heap,cur,__FILE__,__LINE__,mtr) /************************************************************//** Returns the upper level node pointer to a page. It is assumed that mtr holds an x-latch on the tree. @return rec_get_offsets() of the node pointer record */ static ulint* btr_page_get_father_block( /*======================*/ ulint* offsets,/*!< in: work area for the return value */ mem_heap_t* heap, /*!< in: memory heap to use */ dict_index_t* index, /*!< in: b-tree index */ buf_block_t* block, /*!< in: child page in the index */ mtr_t* mtr, /*!< in: mtr */ btr_cur_t* cursor) /*!< out: cursor on node pointer record, its page x-latched */ { rec_t* rec = page_rec_get_next(page_get_infimum_rec(buf_block_get_frame( block))); btr_cur_position(index, rec, block, cursor); return(btr_page_get_father_node_ptr(offsets, heap, cursor, mtr)); } /************************************************************//** Seeks to the upper level node pointer to a page. It is assumed that mtr holds an x-latch on the tree. */ static void btr_page_get_father( /*================*/ dict_index_t* index, /*!< in: b-tree index */ buf_block_t* block, /*!< in: child page in the index */ mtr_t* mtr, /*!< in: mtr */ btr_cur_t* cursor) /*!< out: cursor on node pointer record, its page x-latched */ { mem_heap_t* heap; rec_t* rec = page_rec_get_next(page_get_infimum_rec(buf_block_get_frame( block))); btr_cur_position(index, rec, block, cursor); heap = mem_heap_create(100); btr_page_get_father_node_ptr(NULL, heap, cursor, mtr); mem_heap_free(heap); } /************************************************************//** Creates the root node for a new index tree. @return page number of the created root, FIL_NULL if did not succeed */ UNIV_INTERN ulint btr_create( /*=======*/ ulint type, /*!< in: type of the index */ ulint space, /*!< in: space where created */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ index_id_t index_id,/*!< in: index id */ dict_index_t* index, /*!< in: index */ mtr_t* mtr) /*!< in: mini-transaction handle */ { ulint page_no; buf_block_t* block; buf_frame_t* frame; page_t* page; page_zip_des_t* page_zip; /* Create the two new segments (one, in the case of an ibuf tree) for the index tree; the segment headers are put on the allocated root page (for an ibuf tree, not in the root, but on a separate ibuf header page) */ if (type & DICT_IBUF) { /* Allocate first the ibuf header page */ buf_block_t* ibuf_hdr_block = fseg_create( space, 0, IBUF_HEADER + IBUF_TREE_SEG_HEADER, mtr); buf_block_dbg_add_level( ibuf_hdr_block, SYNC_IBUF_TREE_NODE_NEW); ut_ad(buf_block_get_page_no(ibuf_hdr_block) == IBUF_HEADER_PAGE_NO); /* Allocate then the next page to the segment: it will be the tree root page */ block = fseg_alloc_free_page( buf_block_get_frame(ibuf_hdr_block) + IBUF_HEADER + IBUF_TREE_SEG_HEADER, IBUF_TREE_ROOT_PAGE_NO, FSP_UP, mtr); ut_ad(buf_block_get_page_no(block) == IBUF_TREE_ROOT_PAGE_NO); } else { #ifdef UNIV_BLOB_DEBUG if ((type & DICT_CLUSTERED) && !index->blobs) { mutex_create(PFS_NOT_INSTRUMENTED, &index->blobs_mutex, SYNC_ANY_LATCH); index->blobs = rbt_create(sizeof(btr_blob_dbg_t), btr_blob_dbg_cmp); } #endif /* UNIV_BLOB_DEBUG */ block = fseg_create(space, 0, PAGE_HEADER + PAGE_BTR_SEG_TOP, mtr); } if (block == NULL) { return(FIL_NULL); } page_no = buf_block_get_page_no(block); frame = buf_block_get_frame(block); if (type & DICT_IBUF) { /* It is an insert buffer tree: initialize the free list */ buf_block_dbg_add_level(block, SYNC_IBUF_TREE_NODE_NEW); ut_ad(page_no == IBUF_TREE_ROOT_PAGE_NO); flst_init(frame + PAGE_HEADER + PAGE_BTR_IBUF_FREE_LIST, mtr); } else { /* It is a non-ibuf tree: create a file segment for leaf pages */ buf_block_dbg_add_level(block, SYNC_TREE_NODE_NEW); if (!fseg_create(space, page_no, PAGE_HEADER + PAGE_BTR_SEG_LEAF, mtr)) { /* Not enough space for new segment, free root segment before return. */ btr_free_root(space, zip_size, page_no, mtr); return(FIL_NULL); } /* The fseg create acquires a second latch on the page, therefore we must declare it: */ buf_block_dbg_add_level(block, SYNC_TREE_NODE_NEW); } /* Create a new index page on the allocated segment page */ page_zip = buf_block_get_page_zip(block); if (page_zip) { page = page_create_zip(block, index, 0, 0, mtr); } else { page = page_create(block, mtr, dict_table_is_comp(index->table)); /* Set the level of the new index page */ btr_page_set_level(page, NULL, 0, mtr); } block->check_index_page_at_flush = TRUE; /* Set the index id of the page */ btr_page_set_index_id(page, page_zip, index_id, mtr); /* Set the next node and previous node fields */ btr_page_set_next(page, page_zip, FIL_NULL, mtr); btr_page_set_prev(page, page_zip, FIL_NULL, mtr); /* We reset the free bits for the page to allow creation of several trees in the same mtr, otherwise the latch on a bitmap page would prevent it because of the latching order */ if (!(type & DICT_CLUSTERED)) { ibuf_reset_free_bits(block); } /* In the following assertion we test that two records of maximum allowed size fit on the root page: this fact is needed to ensure correctness of split algorithms */ ut_ad(page_get_max_insert_size(page, 2) > 2 * BTR_PAGE_MAX_REC_SIZE); return(page_no); } /************************************************************//** Frees a B-tree except the root page, which MUST be freed after this by calling btr_free_root. */ UNIV_INTERN void btr_free_but_not_root( /*==================*/ ulint space, /*!< in: space where created */ ulint zip_size, /*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint root_page_no) /*!< in: root page number */ { ibool finished; page_t* root; mtr_t mtr; leaf_loop: mtr_start(&mtr); root = btr_page_get(space, zip_size, root_page_no, RW_X_LATCH, NULL, &mtr); if (!root) { mtr_commit(&mtr); return; } #ifdef UNIV_BTR_DEBUG ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF + root, space)); ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP + root, space)); #endif /* UNIV_BTR_DEBUG */ /* NOTE: page hash indexes are dropped when a page is freed inside fsp0fsp. */ finished = fseg_free_step(root + PAGE_HEADER + PAGE_BTR_SEG_LEAF, &mtr); mtr_commit(&mtr); if (!finished) { goto leaf_loop; } top_loop: mtr_start(&mtr); root = btr_page_get(space, zip_size, root_page_no, RW_X_LATCH, NULL, &mtr); #ifdef UNIV_BTR_DEBUG ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP + root, space)); #endif /* UNIV_BTR_DEBUG */ finished = fseg_free_step_not_header( root + PAGE_HEADER + PAGE_BTR_SEG_TOP, &mtr); mtr_commit(&mtr); if (!finished) { goto top_loop; } } /************************************************************//** Frees the B-tree root page. Other tree MUST already have been freed. */ UNIV_INTERN void btr_free_root( /*==========*/ ulint space, /*!< in: space where created */ ulint zip_size, /*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint root_page_no, /*!< in: root page number */ mtr_t* mtr) /*!< in/out: mini-transaction */ { buf_block_t* block; fseg_header_t* header; block = btr_block_get(space, zip_size, root_page_no, RW_X_LATCH, NULL, mtr); if (block) { btr_search_drop_page_hash_index(block); header = buf_block_get_frame(block) + PAGE_HEADER + PAGE_BTR_SEG_TOP; #ifdef UNIV_BTR_DEBUG ut_a(btr_root_fseg_validate(header, space)); #endif /* UNIV_BTR_DEBUG */ while (!fseg_free_step(header, mtr)) { /* Free the entire segment in small steps. */ } } } #endif /* !UNIV_HOTBACKUP */ /*************************************************************//** Reorganizes an index page. IMPORTANT: On success, the caller will have to update IBUF_BITMAP_FREE if this is a compressed leaf page in a secondary index. This has to be done either within the same mini-transaction, or by invoking ibuf_reset_free_bits() before mtr_commit(). On uncompressed pages, IBUF_BITMAP_FREE is unaffected by reorganization. @retval true if the operation was successful @retval false if it is a compressed page, and recompression failed */ UNIV_INTERN bool btr_page_reorganize_low( /*====================*/ bool recovery,/*!< in: true if called in recovery: locks should not be updated, i.e., there cannot exist locks on the page, and a hash index should not be dropped: it cannot exist */ ulint z_level,/*!< in: compression level to be used if dealing with compressed page */ page_cur_t* cursor, /*!< in/out: page cursor */ dict_index_t* index, /*!< in: the index tree of the page */ mtr_t* mtr) /*!< in/out: mini-transaction */ { buf_block_t* block = page_cur_get_block(cursor); #ifndef UNIV_HOTBACKUP buf_pool_t* buf_pool = buf_pool_from_bpage(&block->page); #endif /* !UNIV_HOTBACKUP */ page_t* page = buf_block_get_frame(block); page_zip_des_t* page_zip = buf_block_get_page_zip(block); buf_block_t* temp_block; page_t* temp_page; ulint log_mode; ulint data_size1; ulint data_size2; ulint max_ins_size1; ulint max_ins_size2; bool success = false; ulint pos; bool log_compressed; ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); btr_assert_not_corrupted(block, index); #ifdef UNIV_ZIP_DEBUG ut_a(!page_zip || page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ data_size1 = page_get_data_size(page); max_ins_size1 = page_get_max_insert_size_after_reorganize(page, 1); /* Turn logging off */ log_mode = mtr_set_log_mode(mtr, MTR_LOG_NONE); #ifndef UNIV_HOTBACKUP temp_block = buf_block_alloc(buf_pool); #else /* !UNIV_HOTBACKUP */ ut_ad(block == back_block1); temp_block = back_block2; #endif /* !UNIV_HOTBACKUP */ temp_page = temp_block->frame; MONITOR_INC(MONITOR_INDEX_REORG_ATTEMPTS); /* Copy the old page to temporary space */ buf_frame_copy(temp_page, page); #ifndef UNIV_HOTBACKUP if (!recovery) { btr_search_drop_page_hash_index(block); } block->check_index_page_at_flush = TRUE; #endif /* !UNIV_HOTBACKUP */ btr_blob_dbg_remove(page, index, "btr_page_reorganize"); /* Save the cursor position. */ pos = page_rec_get_n_recs_before(page_cur_get_rec(cursor)); /* Recreate the page: note that global data on page (possible segment headers, next page-field, etc.) is preserved intact */ page_create(block, mtr, dict_table_is_comp(index->table)); /* Copy the records from the temporary space to the recreated page; do not copy the lock bits yet */ page_copy_rec_list_end_no_locks(block, temp_block, page_get_infimum_rec(temp_page), index, mtr); if (dict_index_is_sec_or_ibuf(index) && page_is_leaf(page)) { /* Copy max trx id to recreated page */ trx_id_t max_trx_id = page_get_max_trx_id(temp_page); page_set_max_trx_id(block, NULL, max_trx_id, mtr); /* In crash recovery, dict_index_is_sec_or_ibuf() always holds, even for clustered indexes. max_trx_id is unused in clustered index pages. */ ut_ad(max_trx_id != 0 || recovery); } /* If innodb_log_compressed_pages is ON, page reorganize should log the compressed page image.*/ log_compressed = page_zip && page_zip_log_pages; if (log_compressed) { mtr_set_log_mode(mtr, log_mode); } if (page_zip && !page_zip_compress(page_zip, page, index, z_level, mtr)) { /* Restore the old page and exit. */ btr_blob_dbg_restore(page, temp_page, index, "btr_page_reorganize_compress_fail"); #if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG /* Check that the bytes that we skip are identical. */ ut_a(!memcmp(page, temp_page, PAGE_HEADER)); ut_a(!memcmp(PAGE_HEADER + PAGE_N_RECS + page, PAGE_HEADER + PAGE_N_RECS + temp_page, PAGE_DATA - (PAGE_HEADER + PAGE_N_RECS))); ut_a(!memcmp(UNIV_PAGE_SIZE - FIL_PAGE_DATA_END + page, UNIV_PAGE_SIZE - FIL_PAGE_DATA_END + temp_page, FIL_PAGE_DATA_END)); #endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */ memcpy(PAGE_HEADER + page, PAGE_HEADER + temp_page, PAGE_N_RECS - PAGE_N_DIR_SLOTS); memcpy(PAGE_DATA + page, PAGE_DATA + temp_page, UNIV_PAGE_SIZE - PAGE_DATA - FIL_PAGE_DATA_END); #if defined UNIV_DEBUG || defined UNIV_ZIP_DEBUG ut_a(!memcmp(page, temp_page, UNIV_PAGE_SIZE)); #endif /* UNIV_DEBUG || UNIV_ZIP_DEBUG */ goto func_exit; } #ifndef UNIV_HOTBACKUP if (!recovery) { /* Update the record lock bitmaps */ lock_move_reorganize_page(block, temp_block); } #endif /* !UNIV_HOTBACKUP */ data_size2 = page_get_data_size(page); max_ins_size2 = page_get_max_insert_size_after_reorganize(page, 1); if (data_size1 != data_size2 || max_ins_size1 != max_ins_size2) { buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print(temp_page, 0, BUF_PAGE_PRINT_NO_CRASH); fprintf(stderr, "InnoDB: Error: page old data size %lu" " new data size %lu\n" "InnoDB: Error: page old max ins size %lu" " new max ins size %lu\n" "InnoDB: Submit a detailed bug report" " to http://bugs.mysql.com\n", (unsigned long) data_size1, (unsigned long) data_size2, (unsigned long) max_ins_size1, (unsigned long) max_ins_size2); ut_ad(0); } else { success = true; } /* Restore the cursor position. */ if (pos > 0) { cursor->rec = page_rec_get_nth(page, pos); } else { ut_ad(cursor->rec == page_get_infimum_rec(page)); } func_exit: #ifdef UNIV_ZIP_DEBUG ut_a(!page_zip || page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ #ifndef UNIV_HOTBACKUP buf_block_free(temp_block); #endif /* !UNIV_HOTBACKUP */ /* Restore logging mode */ mtr_set_log_mode(mtr, log_mode); #ifndef UNIV_HOTBACKUP if (success) { byte type; byte* log_ptr; /* Write the log record */ if (page_zip) { ut_ad(page_is_comp(page)); type = MLOG_ZIP_PAGE_REORGANIZE; } else if (page_is_comp(page)) { type = MLOG_COMP_PAGE_REORGANIZE; } else { type = MLOG_PAGE_REORGANIZE; } log_ptr = log_compressed ? NULL : mlog_open_and_write_index( mtr, page, index, type, page_zip ? 1 : 0); /* For compressed pages write the compression level. */ if (log_ptr && page_zip) { mach_write_to_1(log_ptr, z_level); mlog_close(mtr, log_ptr + 1); } MONITOR_INC(MONITOR_INDEX_REORG_SUCCESSFUL); } #endif /* !UNIV_HOTBACKUP */ return(success); } /*************************************************************//** Reorganizes an index page. IMPORTANT: On success, the caller will have to update IBUF_BITMAP_FREE if this is a compressed leaf page in a secondary index. This has to be done either within the same mini-transaction, or by invoking ibuf_reset_free_bits() before mtr_commit(). On uncompressed pages, IBUF_BITMAP_FREE is unaffected by reorganization. @retval true if the operation was successful @retval false if it is a compressed page, and recompression failed */ UNIV_INTERN bool btr_page_reorganize_block( /*======================*/ bool recovery,/*!< in: true if called in recovery: locks should not be updated, i.e., there cannot exist locks on the page, and a hash index should not be dropped: it cannot exist */ ulint z_level,/*!< in: compression level to be used if dealing with compressed page */ buf_block_t* block, /*!< in/out: B-tree page */ dict_index_t* index, /*!< in: the index tree of the page */ mtr_t* mtr) /*!< in/out: mini-transaction */ { page_cur_t cur; page_cur_set_before_first(block, &cur); return(btr_page_reorganize_low(recovery, z_level, &cur, index, mtr)); } #ifndef UNIV_HOTBACKUP /*************************************************************//** Reorganizes an index page. IMPORTANT: On success, the caller will have to update IBUF_BITMAP_FREE if this is a compressed leaf page in a secondary index. This has to be done either within the same mini-transaction, or by invoking ibuf_reset_free_bits() before mtr_commit(). On uncompressed pages, IBUF_BITMAP_FREE is unaffected by reorganization. @retval true if the operation was successful @retval false if it is a compressed page, and recompression failed */ UNIV_INTERN bool btr_page_reorganize( /*================*/ page_cur_t* cursor, /*!< in/out: page cursor */ dict_index_t* index, /*!< in: the index tree of the page */ mtr_t* mtr) /*!< in/out: mini-transaction */ { return(btr_page_reorganize_low(false, page_zip_level, cursor, index, mtr)); } #endif /* !UNIV_HOTBACKUP */ /***********************************************************//** Parses a redo log record of reorganizing a page. @return end of log record or NULL */ UNIV_INTERN byte* btr_parse_page_reorganize( /*======================*/ byte* ptr, /*!< in: buffer */ byte* end_ptr,/*!< in: buffer end */ dict_index_t* index, /*!< in: record descriptor */ bool compressed,/*!< in: true if compressed page */ buf_block_t* block, /*!< in: page to be reorganized, or NULL */ mtr_t* mtr) /*!< in: mtr or NULL */ { ulint level = page_zip_level; ut_ad(ptr != NULL); ut_ad(end_ptr != NULL); /* If dealing with a compressed page the record has the compression level used during original compression written in one byte. Otherwise record is empty. */ if (compressed) { if (ptr == end_ptr) { return(NULL); } level = mach_read_from_1(ptr); ut_a(level <= 9); ++ptr; } else { level = page_zip_level; } if (block != NULL) { btr_page_reorganize_block(true, level, block, index, mtr); } return(ptr); } #ifndef UNIV_HOTBACKUP /*************************************************************//** Empties an index page. @see btr_page_create(). */ static void btr_page_empty( /*===========*/ buf_block_t* block, /*!< in: page to be emptied */ page_zip_des_t* page_zip,/*!< out: compressed page, or NULL */ dict_index_t* index, /*!< in: index of the page */ ulint level, /*!< in: the B-tree level of the page */ mtr_t* mtr) /*!< in: mtr */ { page_t* page = buf_block_get_frame(block); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); ut_ad(page_zip == buf_block_get_page_zip(block)); #ifdef UNIV_ZIP_DEBUG ut_a(!page_zip || page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ btr_search_drop_page_hash_index(block); btr_blob_dbg_remove(page, index, "btr_page_empty"); /* Recreate the page: note that global data on page (possible segment headers, next page-field, etc.) is preserved intact */ if (page_zip) { page_create_zip(block, index, level, 0, mtr); } else { page_create(block, mtr, dict_table_is_comp(index->table)); btr_page_set_level(page, NULL, level, mtr); } block->check_index_page_at_flush = TRUE; } /*************************************************************//** Makes tree one level higher by splitting the root, and inserts the tuple. It is assumed that mtr contains an x-latch on the tree. NOTE that the operation of this function must always succeed, we cannot reverse it: therefore enough free disk space must be guaranteed to be available before this function is called. @return inserted record or NULL if run out of space */ UNIV_INTERN rec_t* btr_root_raise_and_insert( /*======================*/ ulint flags, /*!< in: undo logging and locking flags */ btr_cur_t* cursor, /*!< in: cursor at which to insert: must be on the root page; when the function returns, the cursor is positioned on the predecessor of the inserted record */ ulint** offsets,/*!< out: offsets on inserted record */ mem_heap_t** heap, /*!< in/out: pointer to memory heap, or NULL */ const dtuple_t* tuple, /*!< in: tuple to insert */ ulint n_ext, /*!< in: number of externally stored columns */ mtr_t* mtr) /*!< in: mtr */ { dict_index_t* index; page_t* root; page_t* new_page; ulint new_page_no; rec_t* rec; dtuple_t* node_ptr; ulint level; rec_t* node_ptr_rec; page_cur_t* page_cursor; page_zip_des_t* root_page_zip; page_zip_des_t* new_page_zip; buf_block_t* root_block; buf_block_t* new_block; root = btr_cur_get_page(cursor); root_block = btr_cur_get_block(cursor); root_page_zip = buf_block_get_page_zip(root_block); ut_ad(!page_is_empty(root)); index = btr_cur_get_index(cursor); #ifdef UNIV_ZIP_DEBUG ut_a(!root_page_zip || page_zip_validate(root_page_zip, root, index)); #endif /* UNIV_ZIP_DEBUG */ #ifdef UNIV_BTR_DEBUG if (!dict_index_is_ibuf(index)) { ulint space = dict_index_get_space(index); ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF + root, space)); ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP + root, space)); } ut_a(dict_index_get_page(index) == page_get_page_no(root)); #endif /* UNIV_BTR_DEBUG */ ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index), MTR_MEMO_X_LOCK)); ut_ad(mtr_memo_contains(mtr, root_block, MTR_MEMO_PAGE_X_FIX)); /* Allocate a new page to the tree. Root splitting is done by first moving the root records to the new page, emptying the root, putting a node pointer to the new page, and then splitting the new page. */ level = btr_page_get_level(root, mtr); new_block = btr_page_alloc(index, 0, FSP_NO_DIR, level, mtr, mtr); if (new_block == NULL && os_has_said_disk_full) { return(NULL); } new_page = buf_block_get_frame(new_block); new_page_zip = buf_block_get_page_zip(new_block); ut_a(!new_page_zip == !root_page_zip); ut_a(!new_page_zip || page_zip_get_size(new_page_zip) == page_zip_get_size(root_page_zip)); btr_page_create(new_block, new_page_zip, index, level, mtr); /* Set the next node and previous node fields of new page */ btr_page_set_next(new_page, new_page_zip, FIL_NULL, mtr); btr_page_set_prev(new_page, new_page_zip, FIL_NULL, mtr); /* Copy the records from root to the new page one by one. */ if (0 #ifdef UNIV_ZIP_COPY || new_page_zip #endif /* UNIV_ZIP_COPY */ || !page_copy_rec_list_end(new_block, root_block, page_get_infimum_rec(root), index, mtr)) { ut_a(new_page_zip); /* Copy the page byte for byte. */ page_zip_copy_recs(new_page_zip, new_page, root_page_zip, root, index, mtr); /* Update the lock table and possible hash index. */ lock_move_rec_list_end(new_block, root_block, page_get_infimum_rec(root)); btr_search_move_or_delete_hash_entries(new_block, root_block, index); } /* If this is a pessimistic insert which is actually done to perform a pessimistic update then we have stored the lock information of the record to be inserted on the infimum of the root page: we cannot discard the lock structs on the root page */ lock_update_root_raise(new_block, root_block); /* Create a memory heap where the node pointer is stored */ if (!*heap) { *heap = mem_heap_create(1000); } rec = page_rec_get_next(page_get_infimum_rec(new_page)); new_page_no = buf_block_get_page_no(new_block); /* Build the node pointer (= node key and page address) for the child */ node_ptr = dict_index_build_node_ptr( index, rec, new_page_no, *heap, level); /* The node pointer must be marked as the predefined minimum record, as there is no lower alphabetical limit to records in the leftmost node of a level: */ dtuple_set_info_bits(node_ptr, dtuple_get_info_bits(node_ptr) | REC_INFO_MIN_REC_FLAG); /* Rebuild the root page to get free space */ btr_page_empty(root_block, root_page_zip, index, level + 1, mtr); /* Set the next node and previous node fields, although they should already have been set. The previous node field must be FIL_NULL if root_page_zip != NULL, because the REC_INFO_MIN_REC_FLAG (of the first user record) will be set if and only if btr_page_get_prev() == FIL_NULL. */ btr_page_set_next(root, root_page_zip, FIL_NULL, mtr); btr_page_set_prev(root, root_page_zip, FIL_NULL, mtr); page_cursor = btr_cur_get_page_cur(cursor); /* Insert node pointer to the root */ page_cur_set_before_first(root_block, page_cursor); node_ptr_rec = page_cur_tuple_insert(page_cursor, node_ptr, index, offsets, heap, 0, mtr); /* The root page should only contain the node pointer to new_page at this point. Thus, the data should fit. */ ut_a(node_ptr_rec); /* We play safe and reset the free bits for the new page */ #if 0 fprintf(stderr, "Root raise new page no %lu\n", new_page_no); #endif if (!dict_index_is_clust(index)) { ibuf_reset_free_bits(new_block); } if (tuple != NULL) { /* Reposition the cursor to the child node */ page_cur_search(new_block, index, tuple, PAGE_CUR_LE, page_cursor); } else { /* Set cursor to first record on child node */ page_cur_set_before_first(new_block, page_cursor); } /* Split the child and insert tuple */ return(btr_page_split_and_insert(flags, cursor, offsets, heap, tuple, n_ext, mtr)); } /*************************************************************//** Decides if the page should be split at the convergence point of inserts converging to the left. @return TRUE if split recommended */ UNIV_INTERN ibool btr_page_get_split_rec_to_left( /*===========================*/ btr_cur_t* cursor, /*!< in: cursor at which to insert */ rec_t** split_rec) /*!< out: if split recommended, the first record on upper half page, or NULL if tuple to be inserted should be first */ { page_t* page; rec_t* insert_point; rec_t* infimum; page = btr_cur_get_page(cursor); insert_point = btr_cur_get_rec(cursor); if (page_header_get_ptr(page, PAGE_LAST_INSERT) == page_rec_get_next(insert_point)) { infimum = page_get_infimum_rec(page); /* If the convergence is in the middle of a page, include also the record immediately before the new insert to the upper page. Otherwise, we could repeatedly move from page to page lots of records smaller than the convergence point. */ if (infimum != insert_point && page_rec_get_next(infimum) != insert_point) { *split_rec = insert_point; } else { *split_rec = page_rec_get_next(insert_point); } return(TRUE); } return(FALSE); } /*************************************************************//** Decides if the page should be split at the convergence point of inserts converging to the right. @return TRUE if split recommended */ UNIV_INTERN ibool btr_page_get_split_rec_to_right( /*============================*/ btr_cur_t* cursor, /*!< in: cursor at which to insert */ rec_t** split_rec) /*!< out: if split recommended, the first record on upper half page, or NULL if tuple to be inserted should be first */ { page_t* page; rec_t* insert_point; page = btr_cur_get_page(cursor); insert_point = btr_cur_get_rec(cursor); /* We use eager heuristics: if the new insert would be right after the previous insert on the same page, we assume that there is a pattern of sequential inserts here. */ if (page_header_get_ptr(page, PAGE_LAST_INSERT) == insert_point) { rec_t* next_rec; next_rec = page_rec_get_next(insert_point); if (page_rec_is_supremum(next_rec)) { split_at_new: /* Split at the new record to insert */ *split_rec = NULL; } else { rec_t* next_next_rec = page_rec_get_next(next_rec); if (page_rec_is_supremum(next_next_rec)) { goto split_at_new; } /* If there are >= 2 user records up from the insert point, split all but 1 off. We want to keep one because then sequential inserts can use the adaptive hash index, as they can do the necessary checks of the right search position just by looking at the records on this page. */ *split_rec = next_next_rec; } return(TRUE); } return(FALSE); } /*************************************************************//** Calculates a split record such that the tuple will certainly fit on its half-page when the split is performed. We assume in this function only that the cursor page has at least one user record. @return split record, or NULL if tuple will be the first record on the lower or upper half-page (determined by btr_page_tuple_smaller()) */ static rec_t* btr_page_get_split_rec( /*===================*/ btr_cur_t* cursor, /*!< in: cursor at which insert should be made */ const dtuple_t* tuple, /*!< in: tuple to insert */ ulint n_ext) /*!< in: number of externally stored columns */ { page_t* page; page_zip_des_t* page_zip; ulint insert_size; ulint free_space; ulint total_data; ulint total_n_recs; ulint total_space; ulint incl_data; rec_t* ins_rec; rec_t* rec; rec_t* next_rec; ulint n; mem_heap_t* heap; ulint* offsets; page = btr_cur_get_page(cursor); insert_size = rec_get_converted_size(cursor->index, tuple, n_ext); free_space = page_get_free_space_of_empty(page_is_comp(page)); page_zip = btr_cur_get_page_zip(cursor); if (page_zip) { /* Estimate the free space of an empty compressed page. */ ulint free_space_zip = page_zip_empty_size( cursor->index->n_fields, page_zip_get_size(page_zip)); if (free_space > (ulint) free_space_zip) { free_space = (ulint) free_space_zip; } } /* free_space is now the free space of a created new page */ total_data = page_get_data_size(page) + insert_size; total_n_recs = page_get_n_recs(page) + 1; ut_ad(total_n_recs >= 2); total_space = total_data + page_dir_calc_reserved_space(total_n_recs); n = 0; incl_data = 0; ins_rec = btr_cur_get_rec(cursor); rec = page_get_infimum_rec(page); heap = NULL; offsets = NULL; /* We start to include records to the left half, and when the space reserved by them exceeds half of total_space, then if the included records fit on the left page, they will be put there if something was left over also for the right page, otherwise the last included record will be the first on the right half page */ do { /* Decide the next record to include */ if (rec == ins_rec) { rec = NULL; /* NULL denotes that tuple is now included */ } else if (rec == NULL) { rec = page_rec_get_next(ins_rec); } else { rec = page_rec_get_next(rec); } if (rec == NULL) { /* Include tuple */ incl_data += insert_size; } else { offsets = rec_get_offsets(rec, cursor->index, offsets, ULINT_UNDEFINED, &heap); incl_data += rec_offs_size(offsets); } n++; } while (incl_data + page_dir_calc_reserved_space(n) < total_space / 2); if (incl_data + page_dir_calc_reserved_space(n) <= free_space) { /* The next record will be the first on the right half page if it is not the supremum record of page */ if (rec == ins_rec) { rec = NULL; goto func_exit; } else if (rec == NULL) { next_rec = page_rec_get_next(ins_rec); } else { next_rec = page_rec_get_next(rec); } ut_ad(next_rec); if (!page_rec_is_supremum(next_rec)) { rec = next_rec; } } func_exit: if (heap) { mem_heap_free(heap); } return(rec); } /*************************************************************//** Returns TRUE if the insert fits on the appropriate half-page with the chosen split_rec. @return true if fits */ static MY_ATTRIBUTE((nonnull(1,3,4,6), warn_unused_result)) bool btr_page_insert_fits( /*=================*/ btr_cur_t* cursor, /*!< in: cursor at which insert should be made */ const rec_t* split_rec,/*!< in: suggestion for first record on upper half-page, or NULL if tuple to be inserted should be first */ ulint** offsets,/*!< in: rec_get_offsets( split_rec, cursor->index); out: garbage */ const dtuple_t* tuple, /*!< in: tuple to insert */ ulint n_ext, /*!< in: number of externally stored columns */ mem_heap_t** heap) /*!< in: temporary memory heap */ { page_t* page; ulint insert_size; ulint free_space; ulint total_data; ulint total_n_recs; const rec_t* rec; const rec_t* end_rec; page = btr_cur_get_page(cursor); ut_ad(!split_rec || !page_is_comp(page) == !rec_offs_comp(*offsets)); ut_ad(!split_rec || rec_offs_validate(split_rec, cursor->index, *offsets)); insert_size = rec_get_converted_size(cursor->index, tuple, n_ext); free_space = page_get_free_space_of_empty(page_is_comp(page)); /* free_space is now the free space of a created new page */ total_data = page_get_data_size(page) + insert_size; total_n_recs = page_get_n_recs(page) + 1; /* We determine which records (from rec to end_rec, not including end_rec) will end up on the other half page from tuple when it is inserted. */ if (split_rec == NULL) { rec = page_rec_get_next(page_get_infimum_rec(page)); end_rec = page_rec_get_next(btr_cur_get_rec(cursor)); } else if (cmp_dtuple_rec(tuple, split_rec, *offsets) >= 0) { rec = page_rec_get_next(page_get_infimum_rec(page)); end_rec = split_rec; } else { rec = split_rec; end_rec = page_get_supremum_rec(page); } if (total_data + page_dir_calc_reserved_space(total_n_recs) <= free_space) { /* Ok, there will be enough available space on the half page where the tuple is inserted */ return(true); } while (rec != end_rec) { /* In this loop we calculate the amount of reserved space after rec is removed from page. */ *offsets = rec_get_offsets(rec, cursor->index, *offsets, ULINT_UNDEFINED, heap); total_data -= rec_offs_size(*offsets); total_n_recs--; if (total_data + page_dir_calc_reserved_space(total_n_recs) <= free_space) { /* Ok, there will be enough available space on the half page where the tuple is inserted */ return(true); } rec = page_rec_get_next_const(rec); } return(false); } /*******************************************************//** Inserts a data tuple to a tree on a non-leaf level. It is assumed that mtr holds an x-latch on the tree. */ UNIV_INTERN void btr_insert_on_non_leaf_level_func( /*==============================*/ ulint flags, /*!< in: undo logging and locking flags */ dict_index_t* index, /*!< in: index */ ulint level, /*!< in: level, must be > 0 */ dtuple_t* tuple, /*!< in: the record to be inserted */ const char* file, /*!< in: file name */ ulint line, /*!< in: line where called */ mtr_t* mtr) /*!< in: mtr */ { big_rec_t* dummy_big_rec; btr_cur_t cursor; dberr_t err; rec_t* rec; ulint* offsets = NULL; mem_heap_t* heap = NULL; ut_ad(level > 0); btr_cur_search_to_nth_level(index, level, tuple, PAGE_CUR_LE, BTR_CONT_MODIFY_TREE, &cursor, 0, file, line, mtr); ut_ad(cursor.flag == BTR_CUR_BINARY); err = btr_cur_optimistic_insert( flags | BTR_NO_LOCKING_FLAG | BTR_KEEP_SYS_FLAG | BTR_NO_UNDO_LOG_FLAG, &cursor, &offsets, &heap, tuple, &rec, &dummy_big_rec, 0, NULL, mtr); if (err == DB_FAIL) { err = btr_cur_pessimistic_insert(flags | BTR_NO_LOCKING_FLAG | BTR_KEEP_SYS_FLAG | BTR_NO_UNDO_LOG_FLAG, &cursor, &offsets, &heap, tuple, &rec, &dummy_big_rec, 0, NULL, mtr); ut_a(err == DB_SUCCESS); } mem_heap_free(heap); } /**************************************************************//** Attaches the halves of an index page on the appropriate level in an index tree. */ static MY_ATTRIBUTE((nonnull)) void btr_attach_half_pages( /*==================*/ ulint flags, /*!< in: undo logging and locking flags */ dict_index_t* index, /*!< in: the index tree */ buf_block_t* block, /*!< in/out: page to be split */ const rec_t* split_rec, /*!< in: first record on upper half page */ buf_block_t* new_block, /*!< in/out: the new half page */ ulint direction, /*!< in: FSP_UP or FSP_DOWN */ mtr_t* mtr) /*!< in: mtr */ { ulint space; ulint zip_size; ulint prev_page_no; ulint next_page_no; ulint level; page_t* page = buf_block_get_frame(block); page_t* lower_page; page_t* upper_page; ulint lower_page_no; ulint upper_page_no; page_zip_des_t* lower_page_zip; page_zip_des_t* upper_page_zip; dtuple_t* node_ptr_upper; mem_heap_t* heap; ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); ut_ad(mtr_memo_contains(mtr, new_block, MTR_MEMO_PAGE_X_FIX)); /* Create a memory heap where the data tuple is stored */ heap = mem_heap_create(1024); /* Based on split direction, decide upper and lower pages */ if (direction == FSP_DOWN) { btr_cur_t cursor; ulint* offsets; lower_page = buf_block_get_frame(new_block); lower_page_no = buf_block_get_page_no(new_block); lower_page_zip = buf_block_get_page_zip(new_block); upper_page = buf_block_get_frame(block); upper_page_no = buf_block_get_page_no(block); upper_page_zip = buf_block_get_page_zip(block); /* Look up the index for the node pointer to page */ offsets = btr_page_get_father_block(NULL, heap, index, block, mtr, &cursor); /* Replace the address of the old child node (= page) with the address of the new lower half */ btr_node_ptr_set_child_page_no( btr_cur_get_rec(&cursor), btr_cur_get_page_zip(&cursor), offsets, lower_page_no, mtr); mem_heap_empty(heap); } else { lower_page = buf_block_get_frame(block); lower_page_no = buf_block_get_page_no(block); lower_page_zip = buf_block_get_page_zip(block); upper_page = buf_block_get_frame(new_block); upper_page_no = buf_block_get_page_no(new_block); upper_page_zip = buf_block_get_page_zip(new_block); } /* Get the level of the split pages */ level = btr_page_get_level(buf_block_get_frame(block), mtr); ut_ad(level == btr_page_get_level(buf_block_get_frame(new_block), mtr)); /* Build the node pointer (= node key and page address) for the upper half */ node_ptr_upper = dict_index_build_node_ptr(index, split_rec, upper_page_no, heap, level); /* Insert it next to the pointer to the lower half. Note that this may generate recursion leading to a split on the higher level. */ btr_insert_on_non_leaf_level(flags, index, level + 1, node_ptr_upper, mtr); /* Free the memory heap */ mem_heap_free(heap); /* Get the previous and next pages of page */ prev_page_no = btr_page_get_prev(page, mtr); next_page_no = btr_page_get_next(page, mtr); space = buf_block_get_space(block); zip_size = buf_block_get_zip_size(block); /* Update page links of the level */ if (prev_page_no != FIL_NULL) { buf_block_t* prev_block = btr_block_get( space, zip_size, prev_page_no, RW_X_LATCH, index, mtr); #ifdef UNIV_BTR_DEBUG ut_a(page_is_comp(prev_block->frame) == page_is_comp(page)); ut_a(btr_page_get_next(prev_block->frame, mtr) == buf_block_get_page_no(block)); #endif /* UNIV_BTR_DEBUG */ btr_page_set_next(buf_block_get_frame(prev_block), buf_block_get_page_zip(prev_block), lower_page_no, mtr); } if (next_page_no != FIL_NULL) { buf_block_t* next_block = btr_block_get( space, zip_size, next_page_no, RW_X_LATCH, index, mtr); #ifdef UNIV_BTR_DEBUG ut_a(page_is_comp(next_block->frame) == page_is_comp(page)); ut_a(btr_page_get_prev(next_block->frame, mtr) == page_get_page_no(page)); #endif /* UNIV_BTR_DEBUG */ btr_page_set_prev(buf_block_get_frame(next_block), buf_block_get_page_zip(next_block), upper_page_no, mtr); } btr_page_set_prev(lower_page, lower_page_zip, prev_page_no, mtr); btr_page_set_next(lower_page, lower_page_zip, upper_page_no, mtr); btr_page_set_prev(upper_page, upper_page_zip, lower_page_no, mtr); btr_page_set_next(upper_page, upper_page_zip, next_page_no, mtr); } /*************************************************************//** Determine if a tuple is smaller than any record on the page. @return TRUE if smaller */ static MY_ATTRIBUTE((nonnull, warn_unused_result)) bool btr_page_tuple_smaller( /*===================*/ btr_cur_t* cursor, /*!< in: b-tree cursor */ const dtuple_t* tuple, /*!< in: tuple to consider */ ulint** offsets,/*!< in/out: temporary storage */ ulint n_uniq, /*!< in: number of unique fields in the index page records */ mem_heap_t** heap) /*!< in/out: heap for offsets */ { buf_block_t* block; const rec_t* first_rec; page_cur_t pcur; /* Read the first user record in the page. */ block = btr_cur_get_block(cursor); page_cur_set_before_first(block, &pcur); page_cur_move_to_next(&pcur); first_rec = page_cur_get_rec(&pcur); *offsets = rec_get_offsets( first_rec, cursor->index, *offsets, n_uniq, heap); return(cmp_dtuple_rec(tuple, first_rec, *offsets) < 0); } /** Insert the tuple into the right sibling page, if the cursor is at the end of a page. @param[in] flags undo logging and locking flags @param[in,out] cursor cursor at which to insert; when the function succeeds, the cursor is positioned before the insert point. @param[out] offsets offsets on inserted record @param[in,out] heap memory heap for allocating offsets @param[in] tuple tuple to insert @param[in] n_ext number of externally stored columns @param[in,out] mtr mini-transaction @return inserted record (first record on the right sibling page); the cursor will be positioned on the page infimum @retval NULL if the operation was not performed */ static rec_t* btr_insert_into_right_sibling( ulint flags, btr_cur_t* cursor, ulint** offsets, mem_heap_t* heap, const dtuple_t* tuple, ulint n_ext, mtr_t* mtr) { buf_block_t* block = btr_cur_get_block(cursor); page_t* page = buf_block_get_frame(block); ulint next_page_no = btr_page_get_next(page, mtr); ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(cursor->index), MTR_MEMO_X_LOCK)); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); ut_ad(heap); if (next_page_no == FIL_NULL || !page_rec_is_supremum( page_rec_get_next(btr_cur_get_rec(cursor)))) { return(NULL); } page_cur_t next_page_cursor; buf_block_t* next_block; page_t* next_page; btr_cur_t next_father_cursor; rec_t* rec = NULL; ulint zip_size = buf_block_get_zip_size(block); ulint max_size; next_block = btr_block_get( buf_block_get_space(block), zip_size, next_page_no, RW_X_LATCH, cursor->index, mtr); next_page = buf_block_get_frame(next_block); bool is_leaf = page_is_leaf(next_page); btr_page_get_father( cursor->index, next_block, mtr, &next_father_cursor); page_cur_search( next_block, cursor->index, tuple, PAGE_CUR_LE, &next_page_cursor); max_size = page_get_max_insert_size_after_reorganize(next_page, 1); /* Extends gap lock for the next page */ lock_update_split_left(next_block, block); rec = page_cur_tuple_insert( &next_page_cursor, tuple, cursor->index, offsets, &heap, n_ext, mtr); if (rec == NULL) { if (zip_size && is_leaf && !dict_index_is_clust(cursor->index)) { /* Reset the IBUF_BITMAP_FREE bits, because page_cur_tuple_insert() will have attempted page reorganize before failing. */ ibuf_reset_free_bits(next_block); } return(NULL); } ibool compressed; dberr_t err; ulint level = btr_page_get_level(next_page, mtr); /* adjust cursor position */ *btr_cur_get_page_cur(cursor) = next_page_cursor; ut_ad(btr_cur_get_rec(cursor) == page_get_infimum_rec(next_page)); ut_ad(page_rec_get_next(page_get_infimum_rec(next_page)) == rec); /* We have to change the parent node pointer */ compressed = btr_cur_pessimistic_delete( &err, TRUE, &next_father_cursor, BTR_CREATE_FLAG, RB_NONE, mtr); ut_a(err == DB_SUCCESS); if (!compressed) { btr_cur_compress_if_useful(&next_father_cursor, FALSE, mtr); } dtuple_t* node_ptr = dict_index_build_node_ptr( cursor->index, rec, buf_block_get_page_no(next_block), heap, level); btr_insert_on_non_leaf_level( flags, cursor->index, level + 1, node_ptr, mtr); ut_ad(rec_offs_validate(rec, cursor->index, *offsets)); if (is_leaf && !dict_index_is_clust(cursor->index)) { /* Update the free bits of the B-tree page in the insert buffer bitmap. */ if (zip_size) { ibuf_update_free_bits_zip(next_block, mtr); } else { ibuf_update_free_bits_if_full( next_block, max_size, rec_offs_size(*offsets) + PAGE_DIR_SLOT_SIZE); } } return(rec); } /*************************************************************//** Splits an index page to halves and inserts the tuple. It is assumed that mtr holds an x-latch to the index tree. NOTE: the tree x-latch is released within this function! NOTE that the operation of this function must always succeed, we cannot reverse it: therefore enough free disk space (2 pages) must be guaranteed to be available before this function is called. NOTE: jonaso added support for calling function with tuple == NULL which cause it to only split a page. @return inserted record or NULL if run out of space */ UNIV_INTERN rec_t* btr_page_split_and_insert( /*======================*/ ulint flags, /*!< in: undo logging and locking flags */ btr_cur_t* cursor, /*!< in: cursor at which to insert; when the function returns, the cursor is positioned on the predecessor of the inserted record */ ulint** offsets,/*!< out: offsets on inserted record */ mem_heap_t** heap, /*!< in/out: pointer to memory heap, or NULL */ const dtuple_t* tuple, /*!< in: tuple to insert */ ulint n_ext, /*!< in: number of externally stored columns */ mtr_t* mtr) /*!< in: mtr */ { buf_block_t* block; page_t* page; page_zip_des_t* page_zip; ulint page_no; byte direction; ulint hint_page_no; buf_block_t* new_block; page_t* new_page; page_zip_des_t* new_page_zip; rec_t* split_rec; buf_block_t* left_block; buf_block_t* right_block; buf_block_t* insert_block; page_cur_t* page_cursor; rec_t* first_rec; byte* buf = 0; /* remove warning */ rec_t* move_limit; ibool insert_will_fit; ibool insert_left; ulint n_iterations = 0; rec_t* rec; ulint n_uniq; if (!*heap) { *heap = mem_heap_create(1024); } n_uniq = dict_index_get_n_unique_in_tree(cursor->index); func_start: mem_heap_empty(*heap); *offsets = NULL; ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(cursor->index), MTR_MEMO_X_LOCK)); ut_ad(!dict_index_is_online_ddl(cursor->index) || (flags & BTR_CREATE_FLAG) || dict_index_is_clust(cursor->index)); #ifdef UNIV_SYNC_DEBUG ut_ad(rw_lock_own(dict_index_get_lock(cursor->index), RW_LOCK_EX)); #endif /* UNIV_SYNC_DEBUG */ block = btr_cur_get_block(cursor); page = buf_block_get_frame(block); page_zip = buf_block_get_page_zip(block); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); ut_ad(!page_is_empty(page)); /* try to insert to the next page if possible before split */ rec = btr_insert_into_right_sibling( flags, cursor, offsets, *heap, tuple, n_ext, mtr); if (rec != NULL) { return(rec); } page_no = buf_block_get_page_no(block); /* 1. Decide the split record; split_rec == NULL means that the tuple to be inserted should be the first record on the upper half-page */ insert_left = FALSE; if (tuple != NULL && n_iterations > 0) { direction = FSP_UP; hint_page_no = page_no + 1; split_rec = btr_page_get_split_rec(cursor, tuple, n_ext); if (split_rec == NULL) { insert_left = btr_page_tuple_smaller( cursor, tuple, offsets, n_uniq, heap); } } else if (btr_page_get_split_rec_to_right(cursor, &split_rec)) { direction = FSP_UP; hint_page_no = page_no + 1; } else if (btr_page_get_split_rec_to_left(cursor, &split_rec)) { direction = FSP_DOWN; hint_page_no = page_no - 1; ut_ad(split_rec); } else { direction = FSP_UP; hint_page_no = page_no + 1; /* If there is only one record in the index page, we can't split the node in the middle by default. We need to determine whether the new record will be inserted to the left or right. */ if (page_get_n_recs(page) > 1) { split_rec = page_get_middle_rec(page); } else if (btr_page_tuple_smaller(cursor, tuple, offsets, n_uniq, heap)) { split_rec = page_rec_get_next( page_get_infimum_rec(page)); } else { split_rec = NULL; } } DBUG_EXECUTE_IF("disk_is_full", os_has_said_disk_full = true; return(NULL);); /* 2. Allocate a new page to the index */ new_block = btr_page_alloc(cursor->index, hint_page_no, direction, btr_page_get_level(page, mtr), mtr, mtr); if (new_block == NULL && os_has_said_disk_full) { return(NULL); } new_page = buf_block_get_frame(new_block); new_page_zip = buf_block_get_page_zip(new_block); btr_page_create(new_block, new_page_zip, cursor->index, btr_page_get_level(page, mtr), mtr); /* Only record the leaf level page splits. */ if (btr_page_get_level(page, mtr) == 0) { cursor->index->stat_defrag_n_page_split ++; cursor->index->stat_defrag_modified_counter ++; btr_defragment_save_defrag_stats_if_needed(cursor->index); } /* 3. Calculate the first record on the upper half-page, and the first record (move_limit) on original page which ends up on the upper half */ if (split_rec) { first_rec = move_limit = split_rec; *offsets = rec_get_offsets(split_rec, cursor->index, *offsets, n_uniq, heap); if (tuple != NULL) { insert_left = cmp_dtuple_rec( tuple, split_rec, *offsets) < 0; } else { insert_left = 1; } if (!insert_left && new_page_zip && n_iterations > 0) { /* If a compressed page has already been split, avoid further splits by inserting the record to an empty page. */ split_rec = NULL; goto insert_empty; } } else if (insert_left) { ut_a(n_iterations > 0); first_rec = page_rec_get_next(page_get_infimum_rec(page)); move_limit = page_rec_get_next(btr_cur_get_rec(cursor)); } else { insert_empty: ut_ad(!split_rec); ut_ad(!insert_left); buf = (byte*) mem_alloc(rec_get_converted_size(cursor->index, tuple, n_ext)); first_rec = rec_convert_dtuple_to_rec(buf, cursor->index, tuple, n_ext); move_limit = page_rec_get_next(btr_cur_get_rec(cursor)); } /* 4. Do first the modifications in the tree structure */ btr_attach_half_pages(flags, cursor->index, block, first_rec, new_block, direction, mtr); /* If the split is made on the leaf level and the insert will fit on the appropriate half-page, we may release the tree x-latch. We can then move the records after releasing the tree latch, thus reducing the tree latch contention. */ if (tuple == NULL) { insert_will_fit = 1; } else if (split_rec) { insert_will_fit = !new_page_zip && btr_page_insert_fits(cursor, split_rec, offsets, tuple, n_ext, heap); } else { if (!insert_left) { mem_free(buf); buf = NULL; } insert_will_fit = !new_page_zip && btr_page_insert_fits(cursor, NULL, offsets, tuple, n_ext, heap); } if (insert_will_fit && page_is_leaf(page) && !dict_index_is_online_ddl(cursor->index)) { mtr_memo_release(mtr, dict_index_get_lock(cursor->index), MTR_MEMO_X_LOCK); } /* 5. Move then the records to the new page */ if (direction == FSP_DOWN) { /* fputs("Split left\n", stderr); */ if (0 #ifdef UNIV_ZIP_COPY || page_zip #endif /* UNIV_ZIP_COPY */ || !page_move_rec_list_start(new_block, block, move_limit, cursor->index, mtr)) { /* For some reason, compressing new_page failed, even though it should contain fewer records than the original page. Copy the page byte for byte and then delete the records from both pages as appropriate. Deleting will always succeed. */ ut_a(new_page_zip); page_zip_copy_recs(new_page_zip, new_page, page_zip, page, cursor->index, mtr); page_delete_rec_list_end(move_limit - page + new_page, new_block, cursor->index, ULINT_UNDEFINED, ULINT_UNDEFINED, mtr); /* Update the lock table and possible hash index. */ lock_move_rec_list_start( new_block, block, move_limit, new_page + PAGE_NEW_INFIMUM); btr_search_move_or_delete_hash_entries( new_block, block, cursor->index); /* Delete the records from the source page. */ page_delete_rec_list_start(move_limit, block, cursor->index, mtr); } left_block = new_block; right_block = block; lock_update_split_left(right_block, left_block); } else { /* fputs("Split right\n", stderr); */ if (0 #ifdef UNIV_ZIP_COPY || page_zip #endif /* UNIV_ZIP_COPY */ || !page_move_rec_list_end(new_block, block, move_limit, cursor->index, mtr)) { /* For some reason, compressing new_page failed, even though it should contain fewer records than the original page. Copy the page byte for byte and then delete the records from both pages as appropriate. Deleting will always succeed. */ ut_a(new_page_zip); page_zip_copy_recs(new_page_zip, new_page, page_zip, page, cursor->index, mtr); page_delete_rec_list_start(move_limit - page + new_page, new_block, cursor->index, mtr); /* Update the lock table and possible hash index. */ lock_move_rec_list_end(new_block, block, move_limit); btr_search_move_or_delete_hash_entries( new_block, block, cursor->index); /* Delete the records from the source page. */ page_delete_rec_list_end(move_limit, block, cursor->index, ULINT_UNDEFINED, ULINT_UNDEFINED, mtr); } left_block = block; right_block = new_block; lock_update_split_right(right_block, left_block); } #ifdef UNIV_ZIP_DEBUG if (page_zip) { ut_a(page_zip_validate(page_zip, page, cursor->index)); ut_a(page_zip_validate(new_page_zip, new_page, cursor->index)); } #endif /* UNIV_ZIP_DEBUG */ /* At this point, split_rec, move_limit and first_rec may point to garbage on the old page. */ /* 6. The split and the tree modification is now completed. Decide the page where the tuple should be inserted */ if (tuple == NULL) { rec = NULL; goto func_exit; } if (insert_left) { insert_block = left_block; } else { insert_block = right_block; } /* 7. Reposition the cursor for insert and try insertion */ page_cursor = btr_cur_get_page_cur(cursor); page_cur_search(insert_block, cursor->index, tuple, PAGE_CUR_LE, page_cursor); rec = page_cur_tuple_insert(page_cursor, tuple, cursor->index, offsets, heap, n_ext, mtr); #ifdef UNIV_ZIP_DEBUG { page_t* insert_page = buf_block_get_frame(insert_block); page_zip_des_t* insert_page_zip = buf_block_get_page_zip(insert_block); ut_a(!insert_page_zip || page_zip_validate(insert_page_zip, insert_page, cursor->index)); } #endif /* UNIV_ZIP_DEBUG */ if (rec != NULL) { goto func_exit; } /* 8. If insert did not fit, try page reorganization. For compressed pages, page_cur_tuple_insert() will have attempted this already. */ if (page_cur_get_page_zip(page_cursor) || !btr_page_reorganize(page_cursor, cursor->index, mtr)) { goto insert_failed; } rec = page_cur_tuple_insert(page_cursor, tuple, cursor->index, offsets, heap, n_ext, mtr); if (rec == NULL) { /* The insert did not fit on the page: loop back to the start of the function for a new split */ insert_failed: /* We play safe and reset the free bits */ if (!dict_index_is_clust(cursor->index)) { ibuf_reset_free_bits(new_block); ibuf_reset_free_bits(block); } /* fprintf(stderr, "Split second round %lu\n", page_get_page_no(page)); */ n_iterations++; ut_ad(n_iterations < 2 || buf_block_get_page_zip(insert_block)); ut_ad(!insert_will_fit); goto func_start; } func_exit: /* Insert fit on the page: update the free bits for the left and right pages in the same mtr */ if (!dict_index_is_clust(cursor->index) && page_is_leaf(page)) { ibuf_update_free_bits_for_two_pages_low( buf_block_get_zip_size(left_block), left_block, right_block, mtr); } #if 0 fprintf(stderr, "Split and insert done %lu %lu\n", buf_block_get_page_no(left_block), buf_block_get_page_no(right_block)); #endif MONITOR_INC(MONITOR_INDEX_SPLIT); ut_ad(page_validate(buf_block_get_frame(left_block), cursor->index)); ut_ad(page_validate(buf_block_get_frame(right_block), cursor->index)); if (tuple == NULL) { ut_ad(rec == NULL); } ut_ad(!rec || rec_offs_validate(rec, cursor->index, *offsets)); return(rec); } /*************************************************************//** Removes a page from the level list of pages. */ UNIV_INTERN void btr_level_list_remove_func( /*=======================*/ ulint space, /*!< in: space where removed */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ page_t* page, /*!< in/out: page to remove */ dict_index_t* index, /*!< in: index tree */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint prev_page_no; ulint next_page_no; ut_ad(page != NULL); ut_ad(mtr != NULL); ut_ad(mtr_memo_contains_page(mtr, page, MTR_MEMO_PAGE_X_FIX)); ut_ad(space == page_get_space_id(page)); /* Get the previous and next page numbers of page */ prev_page_no = btr_page_get_prev(page, mtr); next_page_no = btr_page_get_next(page, mtr); /* Update page links of the level */ if (prev_page_no != FIL_NULL) { buf_block_t* prev_block = btr_block_get(space, zip_size, prev_page_no, RW_X_LATCH, index, mtr); page_t* prev_page = buf_block_get_frame(prev_block); #ifdef UNIV_BTR_DEBUG ut_a(page_is_comp(prev_page) == page_is_comp(page)); ut_a(btr_page_get_next(prev_page, mtr) == page_get_page_no(page)); #endif /* UNIV_BTR_DEBUG */ btr_page_set_next(prev_page, buf_block_get_page_zip(prev_block), next_page_no, mtr); } if (next_page_no != FIL_NULL) { buf_block_t* next_block = btr_block_get(space, zip_size, next_page_no, RW_X_LATCH, index, mtr); page_t* next_page = buf_block_get_frame(next_block); #ifdef UNIV_BTR_DEBUG ut_a(page_is_comp(next_page) == page_is_comp(page)); ut_a(btr_page_get_prev(next_page, mtr) == page_get_page_no(page)); #endif /* UNIV_BTR_DEBUG */ btr_page_set_prev(next_page, buf_block_get_page_zip(next_block), prev_page_no, mtr); } } /****************************************************************//** Writes the redo log record for setting an index record as the predefined minimum record. */ UNIV_INLINE void btr_set_min_rec_mark_log( /*=====================*/ rec_t* rec, /*!< in: record */ byte type, /*!< in: MLOG_COMP_REC_MIN_MARK or MLOG_REC_MIN_MARK */ mtr_t* mtr) /*!< in: mtr */ { mlog_write_initial_log_record(rec, type, mtr); /* Write rec offset as a 2-byte ulint */ mlog_catenate_ulint(mtr, page_offset(rec), MLOG_2BYTES); } #else /* !UNIV_HOTBACKUP */ # define btr_set_min_rec_mark_log(rec,comp,mtr) ((void) 0) #endif /* !UNIV_HOTBACKUP */ /****************************************************************//** Parses the redo log record for setting an index record as the predefined minimum record. @return end of log record or NULL */ UNIV_INTERN byte* btr_parse_set_min_rec_mark( /*=======================*/ byte* ptr, /*!< in: buffer */ byte* end_ptr,/*!< in: buffer end */ ulint comp, /*!< in: nonzero=compact page format */ page_t* page, /*!< in: page or NULL */ mtr_t* mtr) /*!< in: mtr or NULL */ { rec_t* rec; if (end_ptr < ptr + 2) { return(NULL); } if (page) { ut_a(!page_is_comp(page) == !comp); rec = page + mach_read_from_2(ptr); btr_set_min_rec_mark(rec, mtr); } return(ptr + 2); } /****************************************************************//** Sets a record as the predefined minimum record. */ UNIV_INTERN void btr_set_min_rec_mark( /*=================*/ rec_t* rec, /*!< in: record */ mtr_t* mtr) /*!< in: mtr */ { ulint info_bits; if (page_rec_is_comp(rec)) { info_bits = rec_get_info_bits(rec, TRUE); rec_set_info_bits_new(rec, info_bits | REC_INFO_MIN_REC_FLAG); btr_set_min_rec_mark_log(rec, MLOG_COMP_REC_MIN_MARK, mtr); } else { info_bits = rec_get_info_bits(rec, FALSE); rec_set_info_bits_old(rec, info_bits | REC_INFO_MIN_REC_FLAG); btr_set_min_rec_mark_log(rec, MLOG_REC_MIN_MARK, mtr); } } #ifndef UNIV_HOTBACKUP /*************************************************************//** Deletes on the upper level the node pointer to a page. */ UNIV_INTERN void btr_node_ptr_delete( /*================*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: page whose node pointer is deleted */ mtr_t* mtr) /*!< in: mtr */ { btr_cur_t cursor; ibool compressed; dberr_t err; ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); /* Delete node pointer on father page */ btr_page_get_father(index, block, mtr, &cursor); compressed = btr_cur_pessimistic_delete(&err, TRUE, &cursor, BTR_CREATE_FLAG, RB_NONE, mtr); ut_a(err == DB_SUCCESS); if (!compressed) { btr_cur_compress_if_useful(&cursor, FALSE, mtr); } } /*************************************************************//** If page is the only on its level, this function moves its records to the father page, thus reducing the tree height. @return father block */ UNIV_INTERN buf_block_t* btr_lift_page_up( /*=============*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: page which is the only on its level; must not be empty: use btr_discard_only_page_on_level if the last record from the page should be removed */ mtr_t* mtr) /*!< in: mtr */ { buf_block_t* father_block; page_t* father_page; ulint page_level; page_zip_des_t* father_page_zip; page_t* page = buf_block_get_frame(block); ulint root_page_no; buf_block_t* blocks[BTR_MAX_LEVELS]; ulint n_blocks; /*!< last used index in blocks[] */ ulint i; bool lift_father_up; buf_block_t* block_orig = block; ut_ad(btr_page_get_prev(page, mtr) == FIL_NULL); ut_ad(btr_page_get_next(page, mtr) == FIL_NULL); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); page_level = btr_page_get_level(page, mtr); root_page_no = dict_index_get_page(index); { btr_cur_t cursor; ulint* offsets = NULL; mem_heap_t* heap = mem_heap_create( sizeof(*offsets) * (REC_OFFS_HEADER_SIZE + 1 + 1 + index->n_fields)); buf_block_t* b; offsets = btr_page_get_father_block(offsets, heap, index, block, mtr, &cursor); father_block = btr_cur_get_block(&cursor); father_page_zip = buf_block_get_page_zip(father_block); father_page = buf_block_get_frame(father_block); n_blocks = 0; /* Store all ancestor pages so we can reset their levels later on. We have to do all the searches on the tree now because later on, after we've replaced the first level, the tree is in an inconsistent state and can not be searched. */ for (b = father_block; buf_block_get_page_no(b) != root_page_no; ) { ut_a(n_blocks < BTR_MAX_LEVELS); offsets = btr_page_get_father_block(offsets, heap, index, b, mtr, &cursor); blocks[n_blocks++] = b = btr_cur_get_block(&cursor); } lift_father_up = (n_blocks && page_level == 0); if (lift_father_up) { /* The father page also should be the only on its level (not root). We should lift up the father page at first. Because the leaf page should be lifted up only for root page. The freeing page is based on page_level (==0 or !=0) to choose segment. If the page_level is changed ==0 from !=0, later freeing of the page doesn't find the page allocation to be freed.*/ block = father_block; page = buf_block_get_frame(block); page_level = btr_page_get_level(page, mtr); ut_ad(btr_page_get_prev(page, mtr) == FIL_NULL); ut_ad(btr_page_get_next(page, mtr) == FIL_NULL); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); father_block = blocks[0]; father_page_zip = buf_block_get_page_zip(father_block); father_page = buf_block_get_frame(father_block); } mem_heap_free(heap); } btr_search_drop_page_hash_index(block); /* Make the father empty */ btr_page_empty(father_block, father_page_zip, index, page_level, mtr); page_level++; /* Copy the records to the father page one by one. */ if (0 #ifdef UNIV_ZIP_COPY || father_page_zip #endif /* UNIV_ZIP_COPY */ || !page_copy_rec_list_end(father_block, block, page_get_infimum_rec(page), index, mtr)) { const page_zip_des_t* page_zip = buf_block_get_page_zip(block); ut_a(father_page_zip); ut_a(page_zip); /* Copy the page byte for byte. */ page_zip_copy_recs(father_page_zip, father_page, page_zip, page, index, mtr); /* Update the lock table and possible hash index. */ lock_move_rec_list_end(father_block, block, page_get_infimum_rec(page)); btr_search_move_or_delete_hash_entries(father_block, block, index); } btr_blob_dbg_remove(page, index, "btr_lift_page_up"); lock_update_copy_and_discard(father_block, block); /* Go upward to root page, decrementing levels by one. */ for (i = lift_father_up ? 1 : 0; i < n_blocks; i++, page_level++) { page_t* page = buf_block_get_frame(blocks[i]); page_zip_des_t* page_zip= buf_block_get_page_zip(blocks[i]); ut_ad(btr_page_get_level(page, mtr) == page_level + 1); btr_page_set_level(page, page_zip, page_level, mtr); #ifdef UNIV_ZIP_DEBUG ut_a(!page_zip || page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ } /* Free the file page */ btr_page_free(index, block, mtr); /* We play it safe and reset the free bits for the father */ if (!dict_index_is_clust(index)) { ibuf_reset_free_bits(father_block); } ut_ad(page_validate(father_page, index)); ut_ad(btr_check_node_ptr(index, father_block, mtr)); return(lift_father_up ? block_orig : father_block); } /*************************************************************//** Tries to merge the page first to the left immediate brother if such a brother exists, and the node pointers to the current page and to the brother reside on the same page. If the left brother does not satisfy these conditions, looks at the right brother. If the page is the only one on that level lifts the records of the page to the father page, thus reducing the tree height. It is assumed that mtr holds an x-latch on the tree and on the page. If cursor is on the leaf level, mtr must also hold x-latches to the brothers, if they exist. @return TRUE on success */ UNIV_INTERN ibool btr_compress( /*=========*/ btr_cur_t* cursor, /*!< in/out: cursor on the page to merge or lift; the page must not be empty: when deleting records, use btr_discard_page() if the page would become empty */ ibool adjust, /*!< in: TRUE if should adjust the cursor position even if compression occurs */ mtr_t* mtr) /*!< in/out: mini-transaction */ { dict_index_t* index; ulint space; ulint zip_size; ulint left_page_no; ulint right_page_no; buf_block_t* merge_block; page_t* merge_page = NULL; page_zip_des_t* merge_page_zip; ibool is_left; buf_block_t* block; page_t* page; btr_cur_t father_cursor; mem_heap_t* heap; ulint* offsets; ulint nth_rec = 0; /* remove bogus warning */ DBUG_ENTER("btr_compress"); block = btr_cur_get_block(cursor); page = btr_cur_get_page(cursor); index = btr_cur_get_index(cursor); btr_assert_not_corrupted(block, index); ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index), MTR_MEMO_X_LOCK)); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); space = dict_index_get_space(index); zip_size = dict_table_zip_size(index->table); MONITOR_INC(MONITOR_INDEX_MERGE_ATTEMPTS); left_page_no = btr_page_get_prev(page, mtr); right_page_no = btr_page_get_next(page, mtr); #ifdef UNIV_DEBUG if (!page_is_leaf(page) && left_page_no == FIL_NULL) { ut_a(REC_INFO_MIN_REC_FLAG & rec_get_info_bits( page_rec_get_next(page_get_infimum_rec(page)), page_is_comp(page))); } #endif /* UNIV_DEBUG */ heap = mem_heap_create(100); offsets = btr_page_get_father_block(NULL, heap, index, block, mtr, &father_cursor); if (adjust) { nth_rec = page_rec_get_n_recs_before(btr_cur_get_rec(cursor)); ut_ad(nth_rec > 0); } if (left_page_no == FIL_NULL && right_page_no == FIL_NULL) { /* The page is the only one on the level, lift the records to the father */ merge_block = btr_lift_page_up(index, block, mtr); goto func_exit; } /* Decide the page to which we try to merge and which will inherit the locks */ is_left = btr_can_merge_with_page(cursor, left_page_no, &merge_block, mtr); DBUG_EXECUTE_IF("ib_always_merge_right", is_left = FALSE;); if(!is_left && !btr_can_merge_with_page(cursor, right_page_no, &merge_block, mtr)) { goto err_exit; } merge_page = buf_block_get_frame(merge_block); #ifdef UNIV_BTR_DEBUG if (is_left) { ut_a(btr_page_get_next(merge_page, mtr) == buf_block_get_page_no(block)); } else { ut_a(btr_page_get_prev(merge_page, mtr) == buf_block_get_page_no(block)); } #endif /* UNIV_BTR_DEBUG */ ut_ad(page_validate(merge_page, index)); merge_page_zip = buf_block_get_page_zip(merge_block); #ifdef UNIV_ZIP_DEBUG if (merge_page_zip) { const page_zip_des_t* page_zip = buf_block_get_page_zip(block); ut_a(page_zip); ut_a(page_zip_validate(merge_page_zip, merge_page, index)); ut_a(page_zip_validate(page_zip, page, index)); } #endif /* UNIV_ZIP_DEBUG */ /* Move records to the merge page */ if (is_left) { rec_t* orig_pred = page_copy_rec_list_start( merge_block, block, page_get_supremum_rec(page), index, mtr); if (!orig_pred) { goto err_exit; } btr_search_drop_page_hash_index(block); /* Remove the page from the level list */ btr_level_list_remove(space, zip_size, page, index, mtr); btr_node_ptr_delete(index, block, mtr); lock_update_merge_left(merge_block, orig_pred, block); if (adjust) { nth_rec += page_rec_get_n_recs_before(orig_pred); } } else { rec_t* orig_succ; ibool compressed; dberr_t err; btr_cur_t cursor2; /* father cursor pointing to node ptr of the right sibling */ #ifdef UNIV_BTR_DEBUG byte fil_page_prev[4]; #endif /* UNIV_BTR_DEBUG */ btr_page_get_father(index, merge_block, mtr, &cursor2); if (merge_page_zip && left_page_no == FIL_NULL) { /* The function page_zip_compress(), which will be invoked by page_copy_rec_list_end() below, requires that FIL_PAGE_PREV be FIL_NULL. Clear the field, but prepare to restore it. */ #ifdef UNIV_BTR_DEBUG memcpy(fil_page_prev, merge_page + FIL_PAGE_PREV, 4); #endif /* UNIV_BTR_DEBUG */ #if FIL_NULL != 0xffffffff # error "FIL_NULL != 0xffffffff" #endif memset(merge_page + FIL_PAGE_PREV, 0xff, 4); } orig_succ = page_copy_rec_list_end(merge_block, block, page_get_infimum_rec(page), cursor->index, mtr); if (!orig_succ) { ut_a(merge_page_zip); #ifdef UNIV_BTR_DEBUG if (left_page_no == FIL_NULL) { /* FIL_PAGE_PREV was restored from merge_page_zip. */ ut_a(!memcmp(fil_page_prev, merge_page + FIL_PAGE_PREV, 4)); } #endif /* UNIV_BTR_DEBUG */ goto err_exit; } btr_search_drop_page_hash_index(block); #ifdef UNIV_BTR_DEBUG if (merge_page_zip && left_page_no == FIL_NULL) { /* Restore FIL_PAGE_PREV in order to avoid an assertion failure in btr_level_list_remove(), which will set the field again to FIL_NULL. Even though this makes merge_page and merge_page_zip inconsistent for a split second, it is harmless, because the pages are X-latched. */ memcpy(merge_page + FIL_PAGE_PREV, fil_page_prev, 4); } #endif /* UNIV_BTR_DEBUG */ /* Remove the page from the level list */ btr_level_list_remove(space, zip_size, page, index, mtr); /* Replace the address of the old child node (= page) with the address of the merge page to the right */ btr_node_ptr_set_child_page_no( btr_cur_get_rec(&father_cursor), btr_cur_get_page_zip(&father_cursor), offsets, right_page_no, mtr); compressed = btr_cur_pessimistic_delete(&err, TRUE, &cursor2, BTR_CREATE_FLAG, RB_NONE, mtr); ut_a(err == DB_SUCCESS); if (!compressed) { btr_cur_compress_if_useful(&cursor2, FALSE, mtr); } lock_update_merge_right(merge_block, orig_succ, block); } btr_blob_dbg_remove(page, index, "btr_compress"); if (!dict_index_is_clust(index) && page_is_leaf(merge_page)) { /* Update the free bits of the B-tree page in the insert buffer bitmap. This has to be done in a separate mini-transaction that is committed before the main mini-transaction. We cannot update the insert buffer bitmap in this mini-transaction, because btr_compress() can be invoked recursively without committing the mini-transaction in between. Since insert buffer bitmap pages have a lower rank than B-tree pages, we must not access other pages in the same mini-transaction after accessing an insert buffer bitmap page. */ /* The free bits in the insert buffer bitmap must never exceed the free space on a page. It is safe to decrement or reset the bits in the bitmap in a mini-transaction that is committed before the mini-transaction that affects the free space. */ /* It is unsafe to increment the bits in a separately committed mini-transaction, because in crash recovery, the free bits could momentarily be set too high. */ if (zip_size) { /* Because the free bits may be incremented and we cannot update the insert buffer bitmap in the same mini-transaction, the only safe thing we can do here is the pessimistic approach: reset the free bits. */ ibuf_reset_free_bits(merge_block); } else { /* On uncompressed pages, the free bits will never increase here. Thus, it is safe to write the bits accurately in a separate mini-transaction. */ ibuf_update_free_bits_if_full(merge_block, UNIV_PAGE_SIZE, ULINT_UNDEFINED); } } ut_ad(page_validate(merge_page, index)); #ifdef UNIV_ZIP_DEBUG ut_a(!merge_page_zip || page_zip_validate(merge_page_zip, merge_page, index)); #endif /* UNIV_ZIP_DEBUG */ /* Free the file page */ btr_page_free(index, block, mtr); ut_ad(btr_check_node_ptr(index, merge_block, mtr)); func_exit: mem_heap_free(heap); if (adjust) { ut_ad(nth_rec > 0); btr_cur_position( index, page_rec_get_nth(merge_block->frame, nth_rec), merge_block, cursor); } MONITOR_INC(MONITOR_INDEX_MERGE_SUCCESSFUL); DBUG_RETURN(TRUE); err_exit: /* We play it safe and reset the free bits. */ if (zip_size && merge_page && page_is_leaf(merge_page) && !dict_index_is_clust(index)) { ibuf_reset_free_bits(merge_block); } mem_heap_free(heap); DBUG_RETURN(FALSE); } /*************************************************************//** Discards a page that is the only page on its level. This will empty the whole B-tree, leaving just an empty root page. This function should never be reached, because btr_compress(), which is invoked in delete operations, calls btr_lift_page_up() to flatten the B-tree. */ static void btr_discard_only_page_on_level( /*===========================*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: page which is the only on its level */ mtr_t* mtr) /*!< in: mtr */ { ulint page_level = 0; trx_id_t max_trx_id; /* Save the PAGE_MAX_TRX_ID from the leaf page. */ max_trx_id = page_get_max_trx_id(buf_block_get_frame(block)); while (buf_block_get_page_no(block) != dict_index_get_page(index)) { btr_cur_t cursor; buf_block_t* father; const page_t* page = buf_block_get_frame(block); ut_a(page_get_n_recs(page) == 1); ut_a(page_level == btr_page_get_level(page, mtr)); ut_a(btr_page_get_prev(page, mtr) == FIL_NULL); ut_a(btr_page_get_next(page, mtr) == FIL_NULL); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); btr_search_drop_page_hash_index(block); btr_page_get_father(index, block, mtr, &cursor); father = btr_cur_get_block(&cursor); lock_update_discard(father, PAGE_HEAP_NO_SUPREMUM, block); /* Free the file page */ btr_page_free(index, block, mtr); block = father; page_level++; } /* block is the root page, which must be empty, except for the node pointer to the (now discarded) block(s). */ #ifdef UNIV_BTR_DEBUG if (!dict_index_is_ibuf(index)) { const page_t* root = buf_block_get_frame(block); const ulint space = dict_index_get_space(index); ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_LEAF + root, space)); ut_a(btr_root_fseg_validate(FIL_PAGE_DATA + PAGE_BTR_SEG_TOP + root, space)); } #endif /* UNIV_BTR_DEBUG */ btr_page_empty(block, buf_block_get_page_zip(block), index, 0, mtr); ut_ad(page_is_leaf(buf_block_get_frame(block))); if (!dict_index_is_clust(index)) { /* We play it safe and reset the free bits for the root */ ibuf_reset_free_bits(block); ut_a(max_trx_id); page_set_max_trx_id(block, buf_block_get_page_zip(block), max_trx_id, mtr); } } /*************************************************************//** Discards a page from a B-tree. This is used to remove the last record from a B-tree page: the whole page must be removed at the same time. This cannot be used for the root page, which is allowed to be empty. */ UNIV_INTERN void btr_discard_page( /*=============*/ btr_cur_t* cursor, /*!< in: cursor on the page to discard: not on the root page */ mtr_t* mtr) /*!< in: mtr */ { dict_index_t* index; ulint space; ulint zip_size; ulint left_page_no; ulint right_page_no; buf_block_t* merge_block; page_t* merge_page; buf_block_t* block; page_t* page; rec_t* node_ptr; block = btr_cur_get_block(cursor); index = btr_cur_get_index(cursor); ut_ad(dict_index_get_page(index) != buf_block_get_page_no(block)); ut_ad(mtr_memo_contains(mtr, dict_index_get_lock(index), MTR_MEMO_X_LOCK)); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); space = dict_index_get_space(index); zip_size = dict_table_zip_size(index->table); MONITOR_INC(MONITOR_INDEX_DISCARD); /* Decide the page which will inherit the locks */ left_page_no = btr_page_get_prev(buf_block_get_frame(block), mtr); right_page_no = btr_page_get_next(buf_block_get_frame(block), mtr); if (left_page_no != FIL_NULL) { merge_block = btr_block_get(space, zip_size, left_page_no, RW_X_LATCH, index, mtr); merge_page = buf_block_get_frame(merge_block); #ifdef UNIV_BTR_DEBUG ut_a(btr_page_get_next(merge_page, mtr) == buf_block_get_page_no(block)); #endif /* UNIV_BTR_DEBUG */ } else if (right_page_no != FIL_NULL) { merge_block = btr_block_get(space, zip_size, right_page_no, RW_X_LATCH, index, mtr); merge_page = buf_block_get_frame(merge_block); #ifdef UNIV_BTR_DEBUG ut_a(btr_page_get_prev(merge_page, mtr) == buf_block_get_page_no(block)); #endif /* UNIV_BTR_DEBUG */ } else { btr_discard_only_page_on_level(index, block, mtr); return; } page = buf_block_get_frame(block); ut_a(page_is_comp(merge_page) == page_is_comp(page)); btr_search_drop_page_hash_index(block); if (left_page_no == FIL_NULL && !page_is_leaf(page)) { /* We have to mark the leftmost node pointer on the right side page as the predefined minimum record */ node_ptr = page_rec_get_next(page_get_infimum_rec(merge_page)); ut_ad(page_rec_is_user_rec(node_ptr)); /* This will make page_zip_validate() fail on merge_page until btr_level_list_remove() completes. This is harmless, because everything will take place within a single mini-transaction and because writing to the redo log is an atomic operation (performed by mtr_commit()). */ btr_set_min_rec_mark(node_ptr, mtr); } btr_node_ptr_delete(index, block, mtr); /* Remove the page from the level list */ btr_level_list_remove(space, zip_size, page, index, mtr); #ifdef UNIV_ZIP_DEBUG { page_zip_des_t* merge_page_zip = buf_block_get_page_zip(merge_block); ut_a(!merge_page_zip || page_zip_validate(merge_page_zip, merge_page, index)); } #endif /* UNIV_ZIP_DEBUG */ if (left_page_no != FIL_NULL) { lock_update_discard(merge_block, PAGE_HEAP_NO_SUPREMUM, block); } else { lock_update_discard(merge_block, lock_get_min_heap_no(merge_block), block); } btr_blob_dbg_remove(page, index, "btr_discard_page"); /* Free the file page */ btr_page_free(index, block, mtr); ut_ad(btr_check_node_ptr(index, merge_block, mtr)); } #ifdef UNIV_BTR_PRINT /*************************************************************//** Prints size info of a B-tree. */ UNIV_INTERN void btr_print_size( /*===========*/ dict_index_t* index) /*!< in: index tree */ { page_t* root; fseg_header_t* seg; mtr_t mtr; if (dict_index_is_ibuf(index)) { fputs("Sorry, cannot print info of an ibuf tree:" " use ibuf functions\n", stderr); return; } mtr_start(&mtr); root = btr_root_get(index, &mtr); seg = root + PAGE_HEADER + PAGE_BTR_SEG_TOP; fputs("INFO OF THE NON-LEAF PAGE SEGMENT\n", stderr); fseg_print(seg, &mtr); if (!dict_index_is_univ(index)) { seg = root + PAGE_HEADER + PAGE_BTR_SEG_LEAF; fputs("INFO OF THE LEAF PAGE SEGMENT\n", stderr); fseg_print(seg, &mtr); } mtr_commit(&mtr); } /************************************************************//** Prints recursively index tree pages. */ static void btr_print_recursive( /*================*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: index page */ ulint width, /*!< in: print this many entries from start and end */ mem_heap_t** heap, /*!< in/out: heap for rec_get_offsets() */ ulint** offsets,/*!< in/out: buffer for rec_get_offsets() */ mtr_t* mtr) /*!< in: mtr */ { const page_t* page = buf_block_get_frame(block); page_cur_t cursor; ulint n_recs; ulint i = 0; mtr_t mtr2; ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); fprintf(stderr, "NODE ON LEVEL %lu page number %lu\n", (ulong) btr_page_get_level(page, mtr), (ulong) buf_block_get_page_no(block)); page_print(block, index, width, width); n_recs = page_get_n_recs(page); page_cur_set_before_first(block, &cursor); page_cur_move_to_next(&cursor); while (!page_cur_is_after_last(&cursor)) { if (page_is_leaf(page)) { /* If this is the leaf level, do nothing */ } else if ((i <= width) || (i >= n_recs - width)) { const rec_t* node_ptr; mtr_start(&mtr2); node_ptr = page_cur_get_rec(&cursor); *offsets = rec_get_offsets(node_ptr, index, *offsets, ULINT_UNDEFINED, heap); btr_print_recursive(index, btr_node_ptr_get_child(node_ptr, index, *offsets, &mtr2), width, heap, offsets, &mtr2); mtr_commit(&mtr2); } page_cur_move_to_next(&cursor); i++; } } /**************************************************************//** Prints directories and other info of all nodes in the tree. */ UNIV_INTERN void btr_print_index( /*============*/ dict_index_t* index, /*!< in: index */ ulint width) /*!< in: print this many entries from start and end */ { mtr_t mtr; buf_block_t* root; mem_heap_t* heap = NULL; ulint offsets_[REC_OFFS_NORMAL_SIZE]; ulint* offsets = offsets_; rec_offs_init(offsets_); fputs("--------------------------\n" "INDEX TREE PRINT\n", stderr); mtr_start(&mtr); root = btr_root_block_get(index, RW_X_LATCH, &mtr); btr_print_recursive(index, root, width, &heap, &offsets, &mtr); if (heap) { mem_heap_free(heap); } mtr_commit(&mtr); btr_validate_index(index, 0); } #endif /* UNIV_BTR_PRINT */ #ifdef UNIV_DEBUG /************************************************************//** Checks that the node pointer to a page is appropriate. @return TRUE */ UNIV_INTERN ibool btr_check_node_ptr( /*===============*/ dict_index_t* index, /*!< in: index tree */ buf_block_t* block, /*!< in: index page */ mtr_t* mtr) /*!< in: mtr */ { mem_heap_t* heap; dtuple_t* tuple; ulint* offsets; btr_cur_t cursor; page_t* page = buf_block_get_frame(block); ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); if (dict_index_get_page(index) == buf_block_get_page_no(block)) { return(TRUE); } heap = mem_heap_create(256); offsets = btr_page_get_father_block(NULL, heap, index, block, mtr, &cursor); if (page_is_leaf(page)) { goto func_exit; } tuple = dict_index_build_node_ptr( index, page_rec_get_next(page_get_infimum_rec(page)), 0, heap, btr_page_get_level(page, mtr)); ut_a(!cmp_dtuple_rec(tuple, btr_cur_get_rec(&cursor), offsets)); func_exit: mem_heap_free(heap); return(TRUE); } #endif /* UNIV_DEBUG */ /************************************************************//** Display identification information for a record. */ static void btr_index_rec_validate_report( /*==========================*/ const page_t* page, /*!< in: index page */ const rec_t* rec, /*!< in: index record */ const dict_index_t* index) /*!< in: index */ { fputs("InnoDB: Record in ", stderr); dict_index_name_print(stderr, NULL, index); fprintf(stderr, ", page %lu, at offset %lu\n", page_get_page_no(page), (ulint) page_offset(rec)); } /************************************************************//** Checks the size and number of fields in a record based on the definition of the index. @return TRUE if ok */ UNIV_INTERN ibool btr_index_rec_validate( /*===================*/ const rec_t* rec, /*!< in: index record */ const dict_index_t* index, /*!< in: index */ ibool dump_on_error) /*!< in: TRUE if the function should print hex dump of record and page on error */ { ulint len; ulint n; ulint i; const page_t* page; mem_heap_t* heap = NULL; ulint offsets_[REC_OFFS_NORMAL_SIZE]; ulint* offsets = offsets_; rec_offs_init(offsets_); page = page_align(rec); if (dict_index_is_univ(index)) { /* The insert buffer index tree can contain records from any other index: we cannot check the number of fields or their length */ return(TRUE); } if ((ibool)!!page_is_comp(page) != dict_table_is_comp(index->table)) { btr_index_rec_validate_report(page, rec, index); fprintf(stderr, "InnoDB: compact flag=%lu, should be %lu\n", (ulong) !!page_is_comp(page), (ulong) dict_table_is_comp(index->table)); return(FALSE); } n = dict_index_get_n_fields(index); if (!page_is_comp(page) && rec_get_n_fields_old(rec) != n) { btr_index_rec_validate_report(page, rec, index); fprintf(stderr, "InnoDB: has %lu fields, should have %lu\n", (ulong) rec_get_n_fields_old(rec), (ulong) n); if (dump_on_error) { buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); fputs("InnoDB: corrupt record ", stderr); rec_print_old(stderr, rec); putc('\n', stderr); } return(FALSE); } offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); for (i = 0; i < n; i++) { ulint fixed_size = dict_col_get_fixed_size( dict_index_get_nth_col(index, i), page_is_comp(page)); rec_get_nth_field_offs(offsets, i, &len); /* Note that if fixed_size != 0, it equals the length of a fixed-size column in the clustered index. A prefix index of the column is of fixed, but different length. When fixed_size == 0, prefix_len is the maximum length of the prefix index column. */ if ((dict_index_get_nth_field(index, i)->prefix_len == 0 && len != UNIV_SQL_NULL && fixed_size && len != fixed_size) || (dict_index_get_nth_field(index, i)->prefix_len > 0 && len != UNIV_SQL_NULL && len > dict_index_get_nth_field(index, i)->prefix_len)) { btr_index_rec_validate_report(page, rec, index); fprintf(stderr, "InnoDB: field %lu len is %lu," " should be %lu\n", (ulong) i, (ulong) len, (ulong) fixed_size); if (dump_on_error) { buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); fputs("InnoDB: corrupt record ", stderr); rec_print_new(stderr, rec, offsets); putc('\n', stderr); } if (heap) { mem_heap_free(heap); } return(FALSE); } } if (heap) { mem_heap_free(heap); } return(TRUE); } /************************************************************//** Checks the size and number of fields in records based on the definition of the index. @return TRUE if ok */ static ibool btr_index_page_validate( /*====================*/ buf_block_t* block, /*!< in: index page */ dict_index_t* index) /*!< in: index */ { page_cur_t cur; ibool ret = TRUE; #ifndef DBUG_OFF ulint nth = 1; #endif /* !DBUG_OFF */ page_cur_set_before_first(block, &cur); /* Directory slot 0 should only contain the infimum record. */ DBUG_EXECUTE_IF("check_table_rec_next", ut_a(page_rec_get_nth_const( page_cur_get_page(&cur), 0) == cur.rec); ut_a(page_dir_slot_get_n_owned( page_dir_get_nth_slot( page_cur_get_page(&cur), 0)) == 1);); page_cur_move_to_next(&cur); for (;;) { if (page_cur_is_after_last(&cur)) { break; } if (!btr_index_rec_validate(cur.rec, index, TRUE)) { return(FALSE); } /* Verify that page_rec_get_nth_const() is correctly retrieving each record. */ DBUG_EXECUTE_IF("check_table_rec_next", ut_a(cur.rec == page_rec_get_nth_const( page_cur_get_page(&cur), page_rec_get_n_recs_before( cur.rec))); ut_a(nth++ == page_rec_get_n_recs_before( cur.rec));); page_cur_move_to_next(&cur); } return(ret); } /************************************************************//** Report an error on one page of an index tree. */ static void btr_validate_report1( /*=================*/ dict_index_t* index, /*!< in: index */ ulint level, /*!< in: B-tree level */ const buf_block_t* block) /*!< in: index page */ { fprintf(stderr, "InnoDB: Error in page %lu of ", buf_block_get_page_no(block)); dict_index_name_print(stderr, NULL, index); if (level) { fprintf(stderr, ", index tree level %lu", level); } putc('\n', stderr); } /************************************************************//** Report an error on two pages of an index tree. */ static void btr_validate_report2( /*=================*/ const dict_index_t* index, /*!< in: index */ ulint level, /*!< in: B-tree level */ const buf_block_t* block1, /*!< in: first index page */ const buf_block_t* block2) /*!< in: second index page */ { fprintf(stderr, "InnoDB: Error in pages %lu and %lu of ", buf_block_get_page_no(block1), buf_block_get_page_no(block2)); dict_index_name_print(stderr, NULL, index); if (level) { fprintf(stderr, ", index tree level %lu", level); } putc('\n', stderr); } /************************************************************//** Validates index tree level. @return TRUE if ok */ static bool btr_validate_level( /*===============*/ dict_index_t* index, /*!< in: index tree */ const trx_t* trx, /*!< in: transaction or NULL */ ulint level) /*!< in: level number */ { ulint space; ulint space_flags; ulint zip_size; buf_block_t* block; page_t* page; buf_block_t* right_block = 0; /* remove warning */ page_t* right_page = 0; /* remove warning */ page_t* father_page; btr_cur_t node_cur; btr_cur_t right_node_cur; rec_t* rec; ulint right_page_no; ulint left_page_no; page_cur_t cursor; dtuple_t* node_ptr_tuple; bool ret = true; mtr_t mtr; mem_heap_t* heap = mem_heap_create(256); fseg_header_t* seg; ulint* offsets = NULL; ulint* offsets2= NULL; #ifdef UNIV_ZIP_DEBUG page_zip_des_t* page_zip; #endif /* UNIV_ZIP_DEBUG */ mtr_start(&mtr); mtr_x_lock(dict_index_get_lock(index), &mtr); block = btr_root_block_get(index, RW_X_LATCH, &mtr); page = buf_block_get_frame(block); seg = page + PAGE_HEADER + PAGE_BTR_SEG_TOP; space = dict_index_get_space(index); zip_size = dict_table_zip_size(index->table); fil_space_get_latch(space, &space_flags); if (zip_size != dict_tf_get_zip_size(space_flags)) { ib_logf(IB_LOG_LEVEL_WARN, "Flags mismatch: table=%lu, tablespace=%lu", (ulint) index->table->flags, (ulint) space_flags); mtr_commit(&mtr); return(false); } while (level != btr_page_get_level(page, &mtr)) { const rec_t* node_ptr; if (fseg_page_is_free(seg, block->page.space, block->page.offset)) { btr_validate_report1(index, level, block); ib_logf(IB_LOG_LEVEL_WARN, "page is free"); ret = false; } ut_a(space == buf_block_get_space(block)); ut_a(space == page_get_space_id(page)); #ifdef UNIV_ZIP_DEBUG page_zip = buf_block_get_page_zip(block); ut_a(!page_zip || page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ ut_a(!page_is_leaf(page)); page_cur_set_before_first(block, &cursor); page_cur_move_to_next(&cursor); node_ptr = page_cur_get_rec(&cursor); offsets = rec_get_offsets(node_ptr, index, offsets, ULINT_UNDEFINED, &heap); block = btr_node_ptr_get_child(node_ptr, index, offsets, &mtr); page = buf_block_get_frame(block); } /* Now we are on the desired level. Loop through the pages on that level. */ if (level == 0) { /* Leaf pages are managed in their own file segment. */ seg -= PAGE_BTR_SEG_TOP - PAGE_BTR_SEG_LEAF; } loop: mem_heap_empty(heap); offsets = offsets2 = NULL; mtr_x_lock(dict_index_get_lock(index), &mtr); #ifdef UNIV_ZIP_DEBUG page_zip = buf_block_get_page_zip(block); ut_a(!page_zip || page_zip_validate(page_zip, page, index)); #endif /* UNIV_ZIP_DEBUG */ ut_a(block->page.space == space); if (fseg_page_is_free(seg, block->page.space, block->page.offset)) { btr_validate_report1(index, level, block); ib_logf(IB_LOG_LEVEL_WARN, "Page is marked as free"); ret = false; } else if (btr_page_get_index_id(page) != index->id) { ib_logf(IB_LOG_LEVEL_ERROR, "Page index id " IB_ID_FMT " != data dictionary " "index id " IB_ID_FMT, btr_page_get_index_id(page), index->id); ret = false; } else if (!page_validate(page, index)) { btr_validate_report1(index, level, block); ret = false; } else if (level == 0 && !btr_index_page_validate(block, index)) { /* We are on level 0. Check that the records have the right number of fields, and field lengths are right. */ ret = false; } ut_a(btr_page_get_level(page, &mtr) == level); right_page_no = btr_page_get_next(page, &mtr); left_page_no = btr_page_get_prev(page, &mtr); ut_a(!page_is_empty(page) || (level == 0 && page_get_page_no(page) == dict_index_get_page(index))); if (right_page_no != FIL_NULL) { const rec_t* right_rec; right_block = btr_block_get(space, zip_size, right_page_no, RW_X_LATCH, index, &mtr); right_page = buf_block_get_frame(right_block); if (btr_page_get_prev(right_page, &mtr) != page_get_page_no(page)) { btr_validate_report2(index, level, block, right_block); fputs("InnoDB: broken FIL_PAGE_NEXT" " or FIL_PAGE_PREV links\n", stderr); buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print(right_page, 0, BUF_PAGE_PRINT_NO_CRASH); ret = false; } if (page_is_comp(right_page) != page_is_comp(page)) { btr_validate_report2(index, level, block, right_block); fputs("InnoDB: 'compact' flag mismatch\n", stderr); buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print(right_page, 0, BUF_PAGE_PRINT_NO_CRASH); ret = false; goto node_ptr_fails; } rec = page_rec_get_prev(page_get_supremum_rec(page)); right_rec = page_rec_get_next(page_get_infimum_rec( right_page)); offsets = rec_get_offsets(rec, index, offsets, ULINT_UNDEFINED, &heap); offsets2 = rec_get_offsets(right_rec, index, offsets2, ULINT_UNDEFINED, &heap); if (cmp_rec_rec(rec, right_rec, offsets, offsets2, index) >= 0) { btr_validate_report2(index, level, block, right_block); fputs("InnoDB: records in wrong order" " on adjacent pages\n", stderr); buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print(right_page, 0, BUF_PAGE_PRINT_NO_CRASH); fputs("InnoDB: record ", stderr); rec = page_rec_get_prev(page_get_supremum_rec(page)); rec_print(stderr, rec, index); putc('\n', stderr); fputs("InnoDB: record ", stderr); rec = page_rec_get_next( page_get_infimum_rec(right_page)); rec_print(stderr, rec, index); putc('\n', stderr); ret = false; } } if (level > 0 && left_page_no == FIL_NULL) { ut_a(REC_INFO_MIN_REC_FLAG & rec_get_info_bits( page_rec_get_next(page_get_infimum_rec(page)), page_is_comp(page))); } if (buf_block_get_page_no(block) != dict_index_get_page(index)) { /* Check father node pointers */ rec_t* node_ptr; offsets = btr_page_get_father_block(offsets, heap, index, block, &mtr, &node_cur); father_page = btr_cur_get_page(&node_cur); node_ptr = btr_cur_get_rec(&node_cur); btr_cur_position( index, page_rec_get_prev(page_get_supremum_rec(page)), block, &node_cur); offsets = btr_page_get_father_node_ptr(offsets, heap, &node_cur, &mtr); if (node_ptr != btr_cur_get_rec(&node_cur) || btr_node_ptr_get_child_page_no(node_ptr, offsets) != buf_block_get_page_no(block)) { btr_validate_report1(index, level, block); fputs("InnoDB: node pointer to the page is wrong\n", stderr); buf_page_print(father_page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); fputs("InnoDB: node ptr ", stderr); rec_print(stderr, node_ptr, index); rec = btr_cur_get_rec(&node_cur); fprintf(stderr, "\n" "InnoDB: node ptr child page n:o %lu\n", (ulong) btr_node_ptr_get_child_page_no( rec, offsets)); fputs("InnoDB: record on page ", stderr); rec_print_new(stderr, rec, offsets); putc('\n', stderr); ret = false; goto node_ptr_fails; } if (!page_is_leaf(page)) { node_ptr_tuple = dict_index_build_node_ptr( index, page_rec_get_next(page_get_infimum_rec(page)), 0, heap, btr_page_get_level(page, &mtr)); if (cmp_dtuple_rec(node_ptr_tuple, node_ptr, offsets)) { const rec_t* first_rec = page_rec_get_next( page_get_infimum_rec(page)); btr_validate_report1(index, level, block); buf_page_print(father_page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print(page, 0, BUF_PAGE_PRINT_NO_CRASH); fputs("InnoDB: Error: node ptrs differ" " on levels > 0\n" "InnoDB: node ptr ", stderr); rec_print_new(stderr, node_ptr, offsets); fputs("InnoDB: first rec ", stderr); rec_print(stderr, first_rec, index); putc('\n', stderr); ret = false; goto node_ptr_fails; } } if (left_page_no == FIL_NULL) { ut_a(node_ptr == page_rec_get_next( page_get_infimum_rec(father_page))); ut_a(btr_page_get_prev(father_page, &mtr) == FIL_NULL); } if (right_page_no == FIL_NULL) { ut_a(node_ptr == page_rec_get_prev( page_get_supremum_rec(father_page))); ut_a(btr_page_get_next(father_page, &mtr) == FIL_NULL); } else { const rec_t* right_node_ptr = page_rec_get_next(node_ptr); offsets = btr_page_get_father_block( offsets, heap, index, right_block, &mtr, &right_node_cur); if (right_node_ptr != page_get_supremum_rec(father_page)) { if (btr_cur_get_rec(&right_node_cur) != right_node_ptr) { ret = false; fputs("InnoDB: node pointer to" " the right page is wrong\n", stderr); btr_validate_report1(index, level, block); buf_page_print( father_page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( right_page, 0, BUF_PAGE_PRINT_NO_CRASH); } } else { page_t* right_father_page = btr_cur_get_page(&right_node_cur); if (btr_cur_get_rec(&right_node_cur) != page_rec_get_next( page_get_infimum_rec( right_father_page))) { ret = false; fputs("InnoDB: node pointer 2 to" " the right page is wrong\n", stderr); btr_validate_report1(index, level, block); buf_page_print( father_page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( right_father_page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( right_page, 0, BUF_PAGE_PRINT_NO_CRASH); } if (page_get_page_no(right_father_page) != btr_page_get_next(father_page, &mtr)) { ret = false; fputs("InnoDB: node pointer 3 to" " the right page is wrong\n", stderr); btr_validate_report1(index, level, block); buf_page_print( father_page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( right_father_page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( page, 0, BUF_PAGE_PRINT_NO_CRASH); buf_page_print( right_page, 0, BUF_PAGE_PRINT_NO_CRASH); } } } } node_ptr_fails: /* Commit the mini-transaction to release the latch on 'page'. Re-acquire the latch on right_page, which will become 'page' on the next loop. The page has already been checked. */ mtr_commit(&mtr); if (trx_is_interrupted(trx)) { /* On interrupt, return the current status. */ } else if (right_page_no != FIL_NULL) { mtr_start(&mtr); block = btr_block_get( space, zip_size, right_page_no, RW_X_LATCH, index, &mtr); page = buf_block_get_frame(block); goto loop; } mem_heap_free(heap); return(ret); } /**************************************************************//** Checks the consistency of an index tree. @return DB_SUCCESS if ok, error code if not */ UNIV_INTERN dberr_t btr_validate_index( /*===============*/ dict_index_t* index, /*!< in: index */ const trx_t* trx) /*!< in: transaction or NULL */ { dberr_t err = DB_SUCCESS; /* Full Text index are implemented by auxiliary tables, not the B-tree */ if (dict_index_is_online_ddl(index) || (index->type & DICT_FTS)) { return(err); } mtr_t mtr; mtr_start(&mtr); mtr_x_lock(dict_index_get_lock(index), &mtr); page_t* root = btr_root_get(index, &mtr); if (root == NULL && index->table->is_encrypted) { err = DB_DECRYPTION_FAILED; mtr_commit(&mtr); return err; } ulint n = btr_page_get_level(root, &mtr); for (ulint i = 0; i <= n; ++i) { if (!btr_validate_level(index, trx, n - i)) { err = DB_CORRUPTION; break; } } mtr_commit(&mtr); return(err); } /**************************************************************//** Checks if the page in the cursor can be merged with given page. If necessary, re-organize the merge_page. @return TRUE if possible to merge. */ UNIV_INTERN ibool btr_can_merge_with_page( /*====================*/ btr_cur_t* cursor, /*!< in: cursor on the page to merge */ ulint page_no, /*!< in: a sibling page */ buf_block_t** merge_block, /*!< out: the merge block */ mtr_t* mtr) /*!< in: mini-transaction */ { dict_index_t* index; page_t* page; ulint space; ulint zip_size; ulint n_recs; ulint data_size; ulint max_ins_size_reorg; ulint max_ins_size; buf_block_t* mblock; page_t* mpage; DBUG_ENTER("btr_can_merge_with_page"); if (page_no == FIL_NULL) { goto error; } index = btr_cur_get_index(cursor); page = btr_cur_get_page(cursor); space = dict_index_get_space(index); zip_size = dict_table_zip_size(index->table); mblock = btr_block_get(space, zip_size, page_no, RW_X_LATCH, index, mtr); mpage = buf_block_get_frame(mblock); n_recs = page_get_n_recs(page); data_size = page_get_data_size(page); max_ins_size_reorg = page_get_max_insert_size_after_reorganize( mpage, n_recs); if (data_size > max_ins_size_reorg) { goto error; } /* If compression padding tells us that merging will result in too packed up page i.e.: which is likely to cause compression failure then don't merge the pages. */ if (zip_size && page_is_leaf(mpage) && (page_get_data_size(mpage) + data_size >= dict_index_zip_pad_optimal_page_size(index))) { goto error; } max_ins_size = page_get_max_insert_size(mpage, n_recs); if (data_size > max_ins_size) { /* We have to reorganize mpage */ if (!btr_page_reorganize_block( false, page_zip_level, mblock, index, mtr)) { goto error; } max_ins_size = page_get_max_insert_size(mpage, n_recs); ut_ad(page_validate(mpage, index)); ut_ad(max_ins_size == max_ins_size_reorg); if (data_size > max_ins_size) { /* Add fault tolerance, though this should never happen */ goto error; } } *merge_block = mblock; DBUG_RETURN(TRUE); error: *merge_block = NULL; DBUG_RETURN(FALSE); } #endif /* !UNIV_HOTBACKUP */
prohaska7/mariadb-server
storage/innobase/btr/btr0btr.cc
C++
gpl-2.0
151,788
// ========================================================== // fipImage class implementation // // Design and implementation by // - Hervé Drolon (drolon@infonie.fr) // // This file is part of FreeImage 3 // // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // Use at your own risk! // ========================================================== #include "FreeImagePlus.h" /////////////////////////////////////////////////////////////////// // Protected functions BOOL fipImage::replace(FIBITMAP *new_dib) { if(new_dib == NULL) return FALSE; if(_dib) FreeImage_Unload(_dib); _dib = new_dib; _bHasChanged = TRUE; return TRUE; } /////////////////////////////////////////////////////////////////// // Creation & Destruction fipImage::fipImage(FREE_IMAGE_TYPE image_type, WORD width, WORD height, WORD bpp) { _dib = NULL; _bHasChanged = FALSE; if(width && height && bpp) setSize(image_type, width, height, bpp); } fipImage::~fipImage() { if(_dib) { FreeImage_Unload(_dib); _dib = NULL; } } BOOL fipImage::setSize(FREE_IMAGE_TYPE image_type, WORD width, WORD height, WORD bpp, unsigned red_mask, unsigned green_mask, unsigned blue_mask) { if(_dib) { FreeImage_Unload(_dib); } if((_dib = FreeImage_AllocateT(image_type, width, height, bpp, red_mask, green_mask, blue_mask)) == NULL) return FALSE; if(image_type == FIT_BITMAP) { // Create palette if needed switch(bpp) { case 1: case 4: case 8: RGBQUAD *pal = FreeImage_GetPalette(_dib); for(unsigned i = 0; i < FreeImage_GetColorsUsed(_dib); i++) { pal[i].rgbRed = i; pal[i].rgbGreen = i; pal[i].rgbBlue = i; } break; } } _bHasChanged = TRUE; return TRUE; } void fipImage::clear() { if(_dib) { FreeImage_Unload(_dib); _dib = NULL; } _bHasChanged = TRUE; } /////////////////////////////////////////////////////////////////// // Copying fipImage::fipImage(const fipImage& Image) { _dib = NULL; _fif = FIF_UNKNOWN; FIBITMAP *clone = FreeImage_Clone((FIBITMAP*)Image._dib); replace(clone); } fipImage& fipImage::operator=(const fipImage& Image) { if(this != &Image) { FIBITMAP *clone = FreeImage_Clone((FIBITMAP*)Image._dib); replace(clone); } return *this; } fipImage& fipImage::operator=(FIBITMAP *dib) { if(_dib != dib) { replace(dib); } return *this; } BOOL fipImage::copySubImage(fipImage& dst, int left, int top, int right, int bottom) const { if(_dib) { dst = FreeImage_Copy(_dib, left, top, right, bottom); return dst.isValid(); } return FALSE; } BOOL fipImage::pasteSubImage(fipImage& src, int left, int top, int alpha) { if(_dib) { BOOL bResult = FreeImage_Paste(_dib, src._dib, left, top, alpha); _bHasChanged = TRUE; return bResult; } return FALSE; } BOOL fipImage::crop(int left, int top, int right, int bottom) { if(_dib) { FIBITMAP *dst = FreeImage_Copy(_dib, left, top, right, bottom); return replace(dst); } return FALSE; } /////////////////////////////////////////////////////////////////// // Information functions FREE_IMAGE_TYPE fipImage::getImageType() const { return FreeImage_GetImageType(_dib); } WORD fipImage::getWidth() const { return FreeImage_GetWidth(_dib); } WORD fipImage::getHeight() const { return FreeImage_GetHeight(_dib); } WORD fipImage::getScanWidth() const { return FreeImage_GetPitch(_dib); } BOOL fipImage::isValid() const { return (_dib != NULL) ? TRUE:FALSE; } BITMAPINFO* fipImage::getInfo() const { return FreeImage_GetInfo(_dib); } BITMAPINFOHEADER* fipImage::getInfoHeader() const { return FreeImage_GetInfoHeader(_dib); } LONG fipImage::getImageSize() const { return FreeImage_GetDIBSize(_dib); } WORD fipImage::getBitsPerPixel() const { return FreeImage_GetBPP(_dib); } WORD fipImage::getLine() const { return FreeImage_GetLine(_dib); } double fipImage::getHorizontalResolution() const { return (FreeImage_GetDotsPerMeterX(_dib) / (double)100); } double fipImage::getVerticalResolution() const { return (FreeImage_GetDotsPerMeterY(_dib) / (double)100); } void fipImage::setHorizontalResolution(double value) { FreeImage_SetDotsPerMeterX(_dib, (unsigned)(value * 100 + 0.5)); } void fipImage::setVerticalResolution(double value) { FreeImage_SetDotsPerMeterY(_dib, (unsigned)(value * 100 + 0.5)); } /////////////////////////////////////////////////////////////////// // Palette operations RGBQUAD* fipImage::getPalette() const { return FreeImage_GetPalette(_dib); } WORD fipImage::getPaletteSize() const { return FreeImage_GetColorsUsed(_dib) * sizeof(RGBQUAD); } WORD fipImage::getColorsUsed() const { return FreeImage_GetColorsUsed(_dib); } FREE_IMAGE_COLOR_TYPE fipImage::getColorType() const { return FreeImage_GetColorType(_dib); } BOOL fipImage::isGrayscale() const { return ((FreeImage_GetBPP(_dib) == 8) && (FreeImage_GetColorType(_dib) != FIC_PALETTE)); } /////////////////////////////////////////////////////////////////// // Pixel access BYTE* fipImage::accessPixels() const { return FreeImage_GetBits(_dib); } BYTE* fipImage::getScanLine(WORD scanline) const { if(scanline < FreeImage_GetHeight(_dib)) { return FreeImage_GetScanLine(_dib, scanline); } return NULL; } BOOL fipImage::getPixelIndex(unsigned x, unsigned y, BYTE *value) const { return FreeImage_GetPixelIndex(_dib, x, y, value); } BOOL fipImage::getPixelColor(unsigned x, unsigned y, RGBQUAD *value) const { return FreeImage_GetPixelColor(_dib, x, y, value); } BOOL fipImage::setPixelIndex(unsigned x, unsigned y, BYTE *value) { _bHasChanged = TRUE; return FreeImage_SetPixelIndex(_dib, x, y, value); } BOOL fipImage::setPixelColor(unsigned x, unsigned y, RGBQUAD *value) { _bHasChanged = TRUE; return FreeImage_SetPixelColor(_dib, x, y, value); } /////////////////////////////////////////////////////////////////// // File type identification FREE_IMAGE_FORMAT fipImage::identifyFIF(const char* lpszPathName) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // check the file signature and get its format // (the second argument is currently not used by FreeImage) fif = FreeImage_GetFileType(lpszPathName, 0); if(fif == FIF_UNKNOWN) { // no signature ? // try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilename(lpszPathName); } return fif; } FREE_IMAGE_FORMAT fipImage::identifyFIFU(const wchar_t* lpszPathName) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // check the file signature and get its format // (the second argument is currently not used by FreeImage) fif = FreeImage_GetFileTypeU(lpszPathName, 0); if(fif == FIF_UNKNOWN) { // no signature ? // try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilenameU(lpszPathName); } return fif; } FREE_IMAGE_FORMAT fipImage::identifyFIFFromHandle(FreeImageIO *io, fi_handle handle) { if(io && handle) { // check the file signature and get its format return FreeImage_GetFileTypeFromHandle(io, handle, 16); } return FIF_UNKNOWN; } FREE_IMAGE_FORMAT fipImage::identifyFIFFromMemory(FIMEMORY *hmem) { if(hmem != NULL) { return FreeImage_GetFileTypeFromMemory(hmem, 0); } return FIF_UNKNOWN; } /////////////////////////////////////////////////////////////////// // Loading & Saving BOOL fipImage::load(const char* lpszPathName, int flag) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // check the file signature and get its format // (the second argument is currently not used by FreeImage) fif = FreeImage_GetFileType(lpszPathName, 0); if(fif == FIF_UNKNOWN) { // no signature ? // try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilename(lpszPathName); } // check that the plugin has reading capabilities ... if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) { // Free the previous dib if(_dib) { FreeImage_Unload(_dib); } // Load the file _dib = FreeImage_Load(fif, lpszPathName, flag); _bHasChanged = TRUE; if(_dib == NULL) return FALSE; return TRUE; } return FALSE; } BOOL fipImage::loadU(const wchar_t* lpszPathName, int flag) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // check the file signature and get its format // (the second argument is currently not used by FreeImage) fif = FreeImage_GetFileTypeU(lpszPathName, 0); if(fif == FIF_UNKNOWN) { // no signature ? // try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilenameU(lpszPathName); } // check that the plugin has reading capabilities ... if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) { // Free the previous dib if(_dib) { FreeImage_Unload(_dib); } // Load the file _dib = FreeImage_LoadU(fif, lpszPathName, flag); _bHasChanged = TRUE; if(_dib == NULL) return FALSE; return TRUE; } return FALSE; } BOOL fipImage::loadFromHandle(FreeImageIO *io, fi_handle handle, int flag) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // check the file signature and get its format fif = FreeImage_GetFileTypeFromHandle(io, handle, 16); if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) { // Free the previous dib if(_dib) { FreeImage_Unload(_dib); } // Load the file _dib = FreeImage_LoadFromHandle(fif, io, handle, flag); _bHasChanged = TRUE; if(_dib == NULL) return FALSE; return TRUE; } return FALSE; } BOOL fipImage::loadFromMemory(fipMemoryIO& memIO, int flag) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // check the file signature and get its format fif = memIO.getFileType(); if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) { // Free the previous dib if(_dib) { FreeImage_Unload(_dib); } // Load the file _dib = memIO.load(fif, flag); _bHasChanged = TRUE; if(_dib == NULL) return FALSE; return TRUE; } return FALSE; } BOOL fipImage::save(const char* lpszPathName, int flag) const { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; BOOL bSuccess = FALSE; // Try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilename(lpszPathName); if(fif != FIF_UNKNOWN ) { // Check that the dib can be saved in this format BOOL bCanSave; FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(_dib); if(image_type == FIT_BITMAP) { // standard bitmap type WORD bpp = FreeImage_GetBPP(_dib); bCanSave = (FreeImage_FIFSupportsWriting(fif) && FreeImage_FIFSupportsExportBPP(fif, bpp)); } else { // special bitmap type bCanSave = FreeImage_FIFSupportsExportType(fif, image_type); } if(bCanSave) { bSuccess = FreeImage_Save(fif, _dib, lpszPathName, flag); return bSuccess; } } return bSuccess; } BOOL fipImage::saveU(const wchar_t* lpszPathName, int flag) const { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; BOOL bSuccess = FALSE; // Try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilenameU(lpszPathName); if(fif != FIF_UNKNOWN ) { // Check that the dib can be saved in this format BOOL bCanSave; FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(_dib); if(image_type == FIT_BITMAP) { // standard bitmap type WORD bpp = FreeImage_GetBPP(_dib); bCanSave = (FreeImage_FIFSupportsWriting(fif) && FreeImage_FIFSupportsExportBPP(fif, bpp)); } else { // special bitmap type bCanSave = FreeImage_FIFSupportsExportType(fif, image_type); } if(bCanSave) { bSuccess = FreeImage_SaveU(fif, _dib, lpszPathName, flag); return bSuccess; } } return bSuccess; } BOOL fipImage::saveToHandle(FREE_IMAGE_FORMAT fif, FreeImageIO *io, fi_handle handle, int flag) const { BOOL bSuccess = FALSE; if(fif != FIF_UNKNOWN ) { // Check that the dib can be saved in this format BOOL bCanSave; FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(_dib); if(image_type == FIT_BITMAP) { // standard bitmap type WORD bpp = FreeImage_GetBPP(_dib); bCanSave = (FreeImage_FIFSupportsWriting(fif) && FreeImage_FIFSupportsExportBPP(fif, bpp)); } else { // special bitmap type bCanSave = FreeImage_FIFSupportsExportType(fif, image_type); } if(bCanSave) { bSuccess = FreeImage_SaveToHandle(fif, _dib, io, handle, flag); return bSuccess; } } return bSuccess; } BOOL fipImage::saveToMemory(FREE_IMAGE_FORMAT fif, fipMemoryIO& memIO, int flag) const { BOOL bSuccess = FALSE; if(fif != FIF_UNKNOWN ) { // Check that the dib can be saved in this format BOOL bCanSave; FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(_dib); if(image_type == FIT_BITMAP) { // standard bitmap type WORD bpp = FreeImage_GetBPP(_dib); bCanSave = (FreeImage_FIFSupportsWriting(fif) && FreeImage_FIFSupportsExportBPP(fif, bpp)); } else { // special bitmap type bCanSave = FreeImage_FIFSupportsExportType(fif, image_type); } if(bCanSave) { bSuccess = memIO.save(fif, _dib, flag); return bSuccess; } } return bSuccess; } /////////////////////////////////////////////////////////////////// // Conversion routines BOOL fipImage::convertToType(FREE_IMAGE_TYPE image_type, BOOL scale_linear) { if(_dib) { FIBITMAP *dib = FreeImage_ConvertToType(_dib, image_type, scale_linear); return replace(dib); } return FALSE; } BOOL fipImage::threshold(BYTE T) { if(_dib) { FIBITMAP *dib1 = FreeImage_Threshold(_dib, T); return replace(dib1); } return FALSE; } BOOL fipImage::convertTo4Bits() { if(_dib) { FIBITMAP *dib4 = FreeImage_ConvertTo4Bits(_dib); return replace(dib4); } return FALSE; } BOOL fipImage::convertTo8Bits() { if(_dib) { FIBITMAP *dib8 = FreeImage_ConvertTo8Bits(_dib); return replace(dib8); } return FALSE; } BOOL fipImage::convertTo16Bits555() { if(_dib) { FIBITMAP *dib16_555 = FreeImage_ConvertTo16Bits555(_dib); return replace(dib16_555); } return FALSE; } BOOL fipImage::convertTo16Bits565() { if(_dib) { FIBITMAP *dib16_565 = FreeImage_ConvertTo16Bits565(_dib); return replace(dib16_565); } return FALSE; } BOOL fipImage::convertTo24Bits() { if(_dib) { FIBITMAP *dibRGB = FreeImage_ConvertTo24Bits(_dib); return replace(dibRGB); } return FALSE; } BOOL fipImage::convertTo32Bits() { if(_dib) { FIBITMAP *dib32 = FreeImage_ConvertTo32Bits(_dib); return replace(dib32); } return FALSE; } BOOL fipImage::convertToGrayscale() { if(_dib) { FIBITMAP *dib8 = FreeImage_ConvertToGreyscale(_dib); return replace(dib8); } return FALSE; } BOOL fipImage::colorQuantize(FREE_IMAGE_QUANTIZE algorithm) { if(_dib) { FIBITMAP *dib8 = FreeImage_ColorQuantize(_dib, algorithm); return replace(dib8); } return FALSE; } BOOL fipImage::dither(FREE_IMAGE_DITHER algorithm) { if(_dib) { FIBITMAP *dib = FreeImage_Dither(_dib, algorithm); return replace(dib); } return FALSE; } BOOL fipImage::convertToRGBF() { if(_dib) { FIBITMAP *dib = FreeImage_ConvertToRGBF(_dib); return replace(dib); } return FALSE; } BOOL fipImage::toneMapping(FREE_IMAGE_TMO tmo, double first_param, double second_param, double third_param, double fourth_param) { if(_dib) { FIBITMAP *dst = NULL; // Apply a tone mapping algorithm and convert to 24-bit switch(tmo) { case FITMO_REINHARD05: dst = FreeImage_TmoReinhard05Ex(_dib, first_param, second_param, third_param, fourth_param); break; default: dst = FreeImage_ToneMapping(_dib, tmo, first_param, second_param); break; } return replace(dst); } return FALSE; } /////////////////////////////////////////////////////////////////// // Transparency support: background colour and alpha channel BOOL fipImage::isTransparent() const { return FreeImage_IsTransparent(_dib); } unsigned fipImage::getTransparencyCount() const { return FreeImage_GetTransparencyCount(_dib); } BYTE* fipImage::getTransparencyTable() const { return FreeImage_GetTransparencyTable(_dib); } void fipImage::setTransparencyTable(BYTE *table, int count) { FreeImage_SetTransparencyTable(_dib, table, count); _bHasChanged = TRUE; } BOOL fipImage::hasFileBkColor() const { return FreeImage_HasBackgroundColor(_dib); } BOOL fipImage::getFileBkColor(RGBQUAD *bkcolor) const { return FreeImage_GetBackgroundColor(_dib, bkcolor); } BOOL fipImage::setFileBkColor(RGBQUAD *bkcolor) { _bHasChanged = TRUE; return FreeImage_SetBackgroundColor(_dib, bkcolor); } /////////////////////////////////////////////////////////////////// // Channel processing support BOOL fipImage::getChannel(fipImage& image, FREE_IMAGE_COLOR_CHANNEL channel) const { if(_dib) { image = FreeImage_GetChannel(_dib, channel); return image.isValid(); } return FALSE; } BOOL fipImage::setChannel(fipImage& image, FREE_IMAGE_COLOR_CHANNEL channel) { if(_dib) { _bHasChanged = TRUE; return FreeImage_SetChannel(_dib, image._dib, channel); } return FALSE; } BOOL fipImage::splitChannels(fipImage& RedChannel, fipImage& GreenChannel, fipImage& BlueChannel) { if(_dib) { RedChannel = FreeImage_GetChannel(_dib, FICC_RED); GreenChannel = FreeImage_GetChannel(_dib, FICC_GREEN); BlueChannel = FreeImage_GetChannel(_dib, FICC_BLUE); return (RedChannel.isValid() && GreenChannel.isValid() && BlueChannel.isValid()); } return FALSE; } BOOL fipImage::combineChannels(fipImage& red, fipImage& green, fipImage& blue) { if(!_dib) { int width = red.getWidth(); int height = red.getHeight(); _dib = FreeImage_Allocate(width, height, 24, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK); } if(_dib) { BOOL bResult = TRUE; bResult &= FreeImage_SetChannel(_dib, red._dib, FICC_RED); bResult &= FreeImage_SetChannel(_dib, green._dib, FICC_GREEN); bResult &= FreeImage_SetChannel(_dib, blue._dib, FICC_BLUE); _bHasChanged = TRUE; return bResult; } return FALSE; } /////////////////////////////////////////////////////////////////// // Rotation and flipping BOOL fipImage::rotateEx(double angle, double x_shift, double y_shift, double x_origin, double y_origin, BOOL use_mask) { if(_dib) { if(FreeImage_GetBPP(_dib) >= 8) { FIBITMAP *rotated = FreeImage_RotateEx(_dib, angle, x_shift, y_shift, x_origin, y_origin, use_mask); return replace(rotated); } } return FALSE; } BOOL fipImage::rotate(double angle, const void *bkcolor) { if(_dib) { switch(FreeImage_GetImageType(_dib)) { case FIT_BITMAP: switch(FreeImage_GetBPP(_dib)) { case 1: case 8: case 24: case 32: break; default: return FALSE; } break; case FIT_UINT16: case FIT_RGB16: case FIT_RGBA16: case FIT_FLOAT: case FIT_RGBF: case FIT_RGBAF: break; default: return FALSE; break; } FIBITMAP *rotated = FreeImage_Rotate(_dib, angle, bkcolor); return replace(rotated); } return FALSE; } BOOL fipImage::flipVertical() { if(_dib) { _bHasChanged = TRUE; return FreeImage_FlipVertical(_dib); } return FALSE; } BOOL fipImage::flipHorizontal() { if(_dib) { _bHasChanged = TRUE; return FreeImage_FlipHorizontal(_dib); } return FALSE; } /////////////////////////////////////////////////////////////////// // Color manipulation routines BOOL fipImage::invert() { if(_dib) { _bHasChanged = TRUE; return FreeImage_Invert(_dib); } return FALSE; } BOOL fipImage::adjustCurve(BYTE *LUT, FREE_IMAGE_COLOR_CHANNEL channel) { if(_dib) { _bHasChanged = TRUE; return FreeImage_AdjustCurve(_dib, LUT, channel); } return FALSE; } BOOL fipImage::adjustGamma(double gamma) { if(_dib) { _bHasChanged = TRUE; return FreeImage_AdjustGamma(_dib, gamma); } return FALSE; } BOOL fipImage::adjustBrightness(double percentage) { if(_dib) { _bHasChanged = TRUE; return FreeImage_AdjustBrightness(_dib, percentage); } return FALSE; } BOOL fipImage::adjustContrast(double percentage) { if(_dib) { _bHasChanged = TRUE; return FreeImage_AdjustContrast(_dib, percentage); } return FALSE; } BOOL fipImage::adjustBrightnessContrastGamma(double brightness, double contrast, double gamma) { if(_dib) { _bHasChanged = TRUE; return FreeImage_AdjustColors(_dib, brightness, contrast, gamma, FALSE); } return FALSE; } BOOL fipImage::getHistogram(DWORD *histo, FREE_IMAGE_COLOR_CHANNEL channel) const { if(_dib) { return FreeImage_GetHistogram(_dib, histo, channel); } return FALSE; } /////////////////////////////////////////////////////////////////// // Upsampling / downsampling routine BOOL fipImage::rescale(WORD new_width, WORD new_height, FREE_IMAGE_FILTER filter) { if(_dib) { switch(FreeImage_GetImageType(_dib)) { case FIT_BITMAP: case FIT_UINT16: case FIT_RGB16: case FIT_RGBA16: case FIT_FLOAT: case FIT_RGBF: case FIT_RGBAF: break; default: return FALSE; break; } // Perform upsampling / downsampling FIBITMAP *dst = FreeImage_Rescale(_dib, new_width, new_height, filter); return replace(dst); } return FALSE; } BOOL fipImage::makeThumbnail(WORD max_size, BOOL convert) { if(_dib) { switch(FreeImage_GetImageType(_dib)) { case FIT_BITMAP: case FIT_UINT16: case FIT_RGB16: case FIT_RGBA16: case FIT_FLOAT: case FIT_RGBF: case FIT_RGBAF: break; default: return FALSE; break; } // Perform downsampling FIBITMAP *dst = FreeImage_MakeThumbnail(_dib, max_size, convert); return replace(dst); } return FALSE; } /////////////////////////////////////////////////////////////////// // Metadata unsigned fipImage::getMetadataCount(FREE_IMAGE_MDMODEL model) const { return FreeImage_GetMetadataCount(model, _dib); } BOOL fipImage::getMetadata(FREE_IMAGE_MDMODEL model, const char *key, fipTag& tag) const { FITAG *searchedTag = NULL; FreeImage_GetMetadata(model, _dib, key, &searchedTag); if(searchedTag != NULL) { tag = FreeImage_CloneTag(searchedTag); return TRUE; } else { // clear the tag tag = (FITAG*)NULL; } return FALSE; } BOOL fipImage::setMetadata(FREE_IMAGE_MDMODEL model, const char *key, fipTag& tag) { return FreeImage_SetMetadata(model, _dib, key, tag); }
bhargavkumar040/android-source-browsing.platform--external--free-image
Wrapper/FreeImagePlus/src/fipImage.cpp
C++
gpl-2.0
22,480
from django.db import models import useraccounts from librehatti.catalog.models import Product from librehatti.catalog.models import ModeOfPayment from librehatti.catalog.models import Surcharge from django.contrib.auth.models import User from librehatti.config import _BUYER from librehatti.config import _DELIVERY_ADDRESS from librehatti.config import _IS_DEBIT from librehatti.config import _PURCHASED_ITEMS from librehatti.config import _QTY from librehatti.config import _REFERENCE from librehatti.config import _REFERENCE_DATE from librehatti.voucher.models import FinancialSession from django.core.urlresolvers import reverse class NoteLine(models.Model): note = models.CharField(max_length=400) is_permanent = models.BooleanField(default=False) def __unicode__(self): return '%s' % (self.note) class Meta: verbose_name_plural = "Quoted Order Note" class QuotedOrder(models.Model): buyer = models.ForeignKey(User,verbose_name=_BUYER) is_debit = models.BooleanField(default=False, verbose_name=_IS_DEBIT) reference = models.CharField(max_length=200, verbose_name=_REFERENCE) reference_date = models.DateField(verbose_name=_REFERENCE_DATE) delivery_address = models.CharField(max_length=500, blank=True,\ null=True, verbose_name=_DELIVERY_ADDRESS) organisation = models.ForeignKey('useraccounts.AdminOrganisations',default=1) date_time = models.DateField(auto_now_add=True) total_discount = models.IntegerField(default=0) cheque_dd_number = models.CharField(max_length=50, blank=True) cheque_dd_date = models.DateField(max_length=50, blank=True, null=True) is_active = models.BooleanField(default=True) def __unicode__(self): return '%s' % (self.id) class QuotedItem(models.Model): quoted_order = models.ForeignKey(QuotedOrder) price_per_unit = models.IntegerField() qty = models.IntegerField(verbose_name=_QTY) price = models.IntegerField() item = models.ForeignKey(Product) def save(self, *args, **kwargs): if self.quoted_order: self.price = self.price_per_unit * self.qty super(QuotedItem,self).save(*args, **kwargs) def __unicode__(self): return '%s' % (self.item) + ' - ' '%s' % (self.quoted_order) class QuotedOrderofSession(models.Model): quoted_order = models.ForeignKey(QuotedOrder) quoted_order_session = models.IntegerField() session = models.ForeignKey(FinancialSession) class QuotedTaxesApplied(models.Model): quoted_order = models.ForeignKey(QuotedOrder) surcharge = models.ForeignKey(Surcharge) tax = models.IntegerField() def __unicode__(self): return "%s" % (self.surcharge) class QuotedBill(models.Model): quoted_order = models.ForeignKey(QuotedOrder) delivery_charges = models.IntegerField() total_cost = models.IntegerField() totalplusdelivery = models.IntegerField() total_tax = models.IntegerField() grand_total = models.IntegerField() amount_received = models.IntegerField() class QuotedOrderNote(models.Model): quoted_order = models.ForeignKey(QuotedOrder) note = models.CharField(max_length=400)
sofathitesh/TCCReports
src/librehatti/bills/models.py
Python
gpl-2.0
3,184
#!/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python import pkg_resources pkg_resources.require("TurboGears") from turbogears import update_config, start_server import cherrypy, os, time cherrypy.lowercase_api = True from os.path import * import sys import datetime from datetime import timedelta import os, glob, time LOCAL_DIR = os.path.dirname(os.path.join(os.getcwd(),"uploads/")) SESSION_PREFIX = 'session-' LOCK = 'Store' def Delete_dirs(data): sessionfiles = [fname for fname in os.listdir(LOCAL_DIR) if (fname.startswith(SESSION_PREFIX) and not fname.endswith(LOCK))] now = datetime.datetime.now() now.timetuple() for sfile in sessionfiles: for file in glob.glob(LOCAL_DIR+"/"+sfile): stats = os.stat(file) dtfile = datetime.datetime.fromtimestamp(stats[8]) t = now-timedelta(days=2) if t > dtfile: os.remove(os.path.join((LOCAL_DIR), sfile)) for fname in os.listdir(LOCAL_DIR): if (not fname.startswith(SESSION_PREFIX) and not fname.endswith(LOCK)): for sname in sessionfiles: if not fname.endswith(sname.split('-')[1]): for aname in os.listdir(LOCAL_DIR+'/'+fname): os.remove(os.path.join((LOCAL_DIR+'/'+fname), aname)) os.rmdir(os.path.join(LOCAL_DIR, fname)) # first look on the command line for a desired config file, # if it's not on the command line, then # look for setup.py in this directory. If it's not there, this script is # probably installed if len(sys.argv) > 1: update_config(configfile=sys.argv[1], modulename="validator.config") elif exists(join(dirname(__file__), "setup.py")): update_config(configfile="dev.cfg",modulename="validator.config") else: update_config(configfile="prod.cfg",modulename="validator.config") if not os.path.isdir(LOCAL_DIR): try: os.mkdir(LOCAL_DIR) except IOError: print "IOError: %s could not be created" % LOCAL_DIR from validator.controllers import Root from cherrypy.filters import sessionfilter cherrypy.root = Root() cherrypy.config.update({ 'server.log_to_screen': True, 'server.environment': 'production', 'session_filter.on': True, 'session_filter.storage_type' : 'file', 'session_filter.storage_path' : LOCAL_DIR, 'session_filter.timeout': 60, 'session_filter.clean_up_delay': 60, 'session_filter.on_create_session': Delete_dirs, }) start_server(Root())
joshmoore/openmicroscopy
components/validator/WebApp/start-validator.py
Python
gpl-2.0
2,476
<?php /** * @package Warp Theme Framework * @author YOOtheme http://www.yootheme.com * @copyright Copyright (C) YOOtheme GmbH * @license http://www.gnu.org/licenses/gpl.html GNU/GPL */ defined('_JEXEC') or die; JHtml::_('behavior.framework'); JHtml::addIncludePath(JPATH_COMPONENT . '/helpers/html'); JHtml::stylesheet('com_finder/finder.css', false, true, false); ?> <div id="system"> <?php if ($this->params->get('show_page_heading', 1)) : ?> <h1 class="title"> <?php if ($this->escape($this->params->get('page_heading'))) : ?> <?php echo $this->escape($this->params->get('page_heading')); ?> <?php else : ?> <?php echo $this->escape($this->params->get('page_title')); ?> <?php endif; ?> </h1> <?php endif; ?> <?php if ($this->params->get('show_search_form', 1)) { echo $this->loadTemplate('form'); } ?> <?php if ($this->query->search === true) { echo $this->loadTemplate('results'); } ?> </div>
valodya-street/workroom
templates/yoo_sphere/warp/systems/joomla/layouts/com_finder/search/default.php
PHP
gpl-2.0
947
# # Copyright (c) 2008--2015 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 # along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. # # Red Hat trademarks are not licensed under GPLv2. No permission is # granted to use or replicate Red Hat trademarks that are incorporated # in this software or its documentation. # import rhnpush_config import utils import sys import os class ConfManager: def __init__(self, optionparser, store_true_list): sysdir = '/etc/sysconfig/rhn' homedir = utils.get_home_dir() default = 'rhnpushrc' regular = '.rhnpushrc' deffile = os.path.join(sysdir, default) regfile = os.path.join(homedir, regular) cwdfile = os.path.join(os.getcwd(), regular) self.cfgFileList = [deffile, regfile, cwdfile] self.defaultconfig = rhnpush_config.rhnpushConfigParser(ensure_consistency=True) # Get a reference to the object containing command-line options self.cmdconfig = optionparser self.store_true_list = store_true_list # Change the files options of the self.userconfig # Change the exclude options of the self.userconfig def _files_to_list(self): # Change the files options to lists. if (self.defaultconfig.__dict__.has_key('files') and not isinstance(self.defaultconfig.files, type([]))): self.defaultconfig.files = [x.strip() for x in self.defaultconfig.files.split(',')] # Change the exclude options to list. if (self.defaultconfig.__dict__.has_key('exclude') and not isinstance(self.defaultconfig.__dict__['exclude'], type([]))): self.defaultconfig.exclude = [x.strip() for x in self.defaultconfig.exclude.split(',')] def get_config(self): for f in self.cfgFileList: if os.access(f, os.F_OK): if not os.access(f, os.R_OK): print "rhnpush does not have read permission on %s" % f sys.exit(1) config2 = rhnpush_config.rhnpushConfigParser(f) self.defaultconfig, config2 = utils.make_common_attr_equal(self.defaultconfig, config2) self._files_to_list() # Change the channel string into a list of strings. # pylint: disable=E1103 if not self.defaultconfig.channel: # if no channel then make it null array instead of # an empty string array from of size 1 [''] . self.defaultconfig.channel = [] else: self.defaultconfig.channel = [x.strip() for x in self.defaultconfig.channel.split(',')] # Get the command line arguments. These take precedence over the other settings argoptions, files = self.cmdconfig.parse_args() # Makes self.defaultconfig compatible with argoptions by changing all '0' value attributes to None. _zero_to_none(self.defaultconfig, self.store_true_list) # If verbose isn't set at the command-line, it automatically gets set to zero. If it's at zero, change it to # None so the settings in the config files take precedence. if argoptions.verbose == 0: argoptions.verbose = None # Orgid, count, cache_lifetime, and verbose all need to be integers, just like in argoptions. if self.defaultconfig.orgid: self.defaultconfig.orgid = int(self.defaultconfig.orgid) if self.defaultconfig.count: self.defaultconfig.count = int(self.defaultconfig.count) if self.defaultconfig.cache_lifetime: self.defaultconfig.cache_lifetime = int(self.defaultconfig.cache_lifetime) if self.defaultconfig.verbose: self.defaultconfig.verbose = int(self.defaultconfig.verbose) if self.defaultconfig.timeout: self.defaultconfig.timeout = int(self.defaultconfig.timeout) # Copy the settings in argoptions into self.defaultconfig. self.defaultconfig, argoptions = utils.make_common_attr_equal(self.defaultconfig, argoptions) # Make sure files is in the correct format. if self.defaultconfig.files != files: self.defaultconfig.files = files return self.defaultconfig # Changes every option in config that is also in store_true_list that is set to '0' to None def _zero_to_none(config, store_true_list): for opt in config.keys(): for cmd in store_true_list: if str(opt) == cmd and config.__dict__[opt] == '0': config.__dict__[opt] = None
xkollar/spacewalk
client/tools/rhnpush/rhnpush_confmanager.py
Python
gpl-2.0
4,950
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Bundle * @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /* @var $installer Mage_Catalog_Model_Resource_Eav_Mysql4_Setup */ $installer = $this; $installer->run(" CREATE TABLE {$this->getTable('bundle/selection_price')} ( `selection_id` int(10) unsigned NOT NULL, `website_id` smallint(5) unsigned NOT NULL, `selection_price_type` tinyint(1) unsigned NOT NULL default '0', `selection_price_value` decimal(12,4) NOT NULL default '0.0000', PRIMARY KEY (`selection_id`, `website_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; "); $installer->getConnection()->addConstraint( 'FK_BUNDLE_PRICE_SELECTION_ID', $this->getTable('bundle/selection_price'), 'selection_id', $this->getTable('bundle/selection'), 'selection_id' ); $installer->getConnection()->addConstraint( 'FK_BUNDLE_PRICE_SELECTION_WEBSITE', $this->getTable('bundle/selection_price'), 'website_id', $this->getTable('core_website'), 'website_id' );
T0MM0R/magento
web/app/code/core/Mage/Bundle/sql/bundle_setup/mysql4-upgrade-0.1.12-0.1.13.php
PHP
gpl-2.0
1,852
/* * Copyright (C) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if UNITY_ANDROID using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using GooglePlayGames.BasicApi; using GooglePlayGames.OurUtils; using GooglePlayGames.BasicApi.Multiplayer; namespace GooglePlayGames.Android { internal class AndroidRtmpClient : IRealTimeMultiplayerClient { AndroidClient mClient = null; AndroidJavaObject mRoom = null; RealTimeMultiplayerListener mRtmpListener = null; // whether rtmp is currently active (this becomes true when we begin setup, and // remains true while the room is active; when we leave the room, this goes back to // false. bool mRtmpActive = false; // whether we are invoking an external UI (which might cause us to get stopped) // we must know this because we will know to keep the reference to the Rtmp Listener // so that when we come back from that UI, we can continue the room setup bool mLaunchedExternalActivity = false; // whether we delivered OnRoomConnected callback; amongst other things, this // means that we also have to deliver the OnLeftRoom callback when leaving the room bool mDeliveredRoomConnected = false; // whether we have a pending request to leave the room (this will happen if the // developer calls LeaveRoom() when we are in a state where we can't service that // request immediately) bool mLeaveRoomRequested = false; // variant requested, 0 for ANY int mVariant = 0; // we use this lock when we access the lists of participants, or mSelf, // from either the UI thread or the game thread. object mParticipantListsLock = new object(); List<Participant> mConnectedParticipants = new List<Participant>(); List<Participant> mAllParticipants = new List<Participant>(); Participant mSelf = null; // accumulated "approximate progress" of the room setup process float mAccumulatedProgress = 0.0f; float mLastReportedProgress = 0.0f; public AndroidRtmpClient(AndroidClient client) { mClient = client; } // called from game thread public void CreateQuickGame(int minOpponents, int maxOpponents, int variant, RealTimeMultiplayerListener listener) { Logger.d(string.Format("AndroidRtmpClient.CreateQuickGame, opponents={0}-{1}, " + "variant={2}", minOpponents, maxOpponents, variant)); if (!PrepareToCreateRoom("CreateQuickGame", listener)) { return; } mRtmpListener = listener; mVariant = variant; mClient.CallClientApi("rtmp create quick game", () => { AndroidJavaClass rtmpUtil = JavaUtil.GetClass(JavaConsts.SupportRtmpUtilsClass); rtmpUtil.CallStatic("createQuickGame", mClient.GHManager.GetApiClient(), minOpponents, maxOpponents, variant, new RoomUpdateProxy(this), new RoomStatusUpdateProxy(this), new RealTimeMessageReceivedProxy(this)); }, (bool success) => { if (!success) { FailRoomSetup("Failed to create game because GoogleApiClient was disconnected"); } }); } // called from game thread public void CreateWithInvitationScreen(int minOpponents, int maxOpponents, int variant, RealTimeMultiplayerListener listener) { Logger.d(string.Format("AndroidRtmpClient.CreateWithInvitationScreen, " + "opponents={0}-{1}, variant={2}", minOpponents, maxOpponents, variant)); if (!PrepareToCreateRoom("CreateWithInvitationScreen", listener)) { return; } mRtmpListener = listener; mVariant = variant; mClient.CallClientApi("rtmp create with invitation screen", () => { AndroidJavaClass klass = JavaUtil.GetClass( JavaConsts.SupportSelectOpponentsHelperActivity); mLaunchedExternalActivity = true; klass.CallStatic("launch", true, mClient.GetActivity(), new SelectOpponentsProxy(this), Logger.DebugLogEnabled, minOpponents, maxOpponents); }, (bool success) => { if (!success) { FailRoomSetup("Failed to create game because GoogleApiClient was disconnected"); } }); } // called from game thread public void AcceptFromInbox(RealTimeMultiplayerListener listener) { Logger.d("AndroidRtmpClient.AcceptFromInbox."); if (!PrepareToCreateRoom("AcceptFromInbox", listener)) { return; } mRtmpListener = listener; mClient.CallClientApi("rtmp accept with inbox screen", () => { AndroidJavaClass klass = JavaUtil.GetClass( JavaConsts.SupportInvitationInboxHelperActivity); mLaunchedExternalActivity = true; klass.CallStatic("launch", true, mClient.GetActivity(), new InvitationInboxProxy(this), Logger.DebugLogEnabled); }, (bool success) => { if (!success) { FailRoomSetup("Failed to accept from inbox because GoogleApiClient was disconnected"); } }); } // called from the game thread public void AcceptInvitation(string invitationId, RealTimeMultiplayerListener listener) { Logger.d("AndroidRtmpClient.AcceptInvitation " + invitationId); if (!PrepareToCreateRoom("AcceptInvitation", listener)) { return; } mRtmpListener = listener; mClient.ClearInvitationIfFromNotification(invitationId); mClient.CallClientApi("rtmp accept invitation", () => { Logger.d("Accepting invite via support lib."); AndroidJavaClass rtmpUtil = JavaUtil.GetClass(JavaConsts.SupportRtmpUtilsClass); rtmpUtil.CallStatic("accept", mClient.GHManager.GetApiClient(), invitationId, new RoomUpdateProxy(this), new RoomStatusUpdateProxy(this), new RealTimeMessageReceivedProxy(this)); }, (bool success) => { if (!success) { FailRoomSetup("Failed to accept invitation because GoogleApiClient was disconnected"); } }); } // called from game thread public void SendMessage(bool reliable, string participantId, byte[] data) { SendMessage(reliable, participantId, data, 0, data.Length); } // called from game thread public void SendMessageToAll(bool reliable, byte[] data) { SendMessage(reliable, null, data, 0, data.Length); } // called from game thread public void SendMessageToAll(bool reliable, byte[] data, int offset, int length) { SendMessage(reliable, null, data, offset, length); } // called from game thread public void SendMessage(bool reliable, string participantId, byte[] data, int offset, int length) { Logger.d(string.Format("AndroidRtmpClient.SendMessage, reliable={0}, " + "participantId={1}, data[]={2} bytes, offset={3}, length={4}", reliable, participantId, data.Length, offset, length)); if (!CheckConnectedRoom("SendMessage")) { return; } if (mSelf != null && mSelf.ParticipantId.Equals(participantId)) { Logger.d("Ignoring request to send message to self, " + participantId); return; } // Since we don't yet have API support for buffer/offset/length, convert // to a regular byte[] buffer: byte[] dataToSend = Misc.GetSubsetBytes(data, offset, length); if (participantId == null) { // this means "send to all" List<Participant> participants = GetConnectedParticipants(); foreach (Participant p in participants) { if (p.ParticipantId != null && !p.Equals(mSelf)) { SendMessage(reliable, p.ParticipantId, dataToSend, 0, dataToSend.Length); } } return; } mClient.CallClientApi("send message to " + participantId, () => { if (mRoom != null) { string roomId = mRoom.Call<string>("getRoomId"); if (reliable) { mClient.GHManager.CallGmsApi<int>("games.Games", "RealTimeMultiplayer", "sendReliableMessage", null, dataToSend, roomId, participantId); } else { mClient.GHManager.CallGmsApi<int>("games.Games", "RealTimeMultiplayer", "sendUnreliableMessage", dataToSend, roomId, participantId); } } else { Logger.w("Not sending message because real-time room was torn down."); } }, null); } // called from game thread public List<Participant> GetConnectedParticipants() { Logger.d("AndroidRtmpClient.GetConnectedParticipants"); if (!CheckConnectedRoom("GetConnectedParticipants")) { return null; } List<Participant> participants; // lock it because this list is assigned to by the UI thread lock (mParticipantListsLock) { participants = mConnectedParticipants; } // Note: it's fine to return a reference to our internal list, because // we use it as an immutable list. When we get an update, we create a new list to // replace it. So the caller may just as well hold on to our copy. return participants; } // called from game thread public Participant GetParticipant(string id) { Logger.d("AndroidRtmpClient.GetParticipant: " + id); if (!CheckConnectedRoom("GetParticipant")) { return null; } List<Participant> allParticipants; lock (mParticipantListsLock) { allParticipants = mAllParticipants; } if (allParticipants == null) { Logger.e("RtmpGetParticipant called without a valid room!"); return null; } foreach (Participant p in allParticipants) { if (p.ParticipantId.Equals(id)) { return p; } } Logger.e("Participant not found in room! id: " + id); return null; } // called from game thread public Participant GetSelf() { Logger.d("AndroidRtmpClient.GetSelf"); if (!CheckConnectedRoom("GetSelf")) { return null; } Participant self; lock (mParticipantListsLock) { self = mSelf; } if (self == null) { Logger.e("Call to RtmpGetSelf() can only be made when in a room. Returning null."); } return self; } // called from game thread public void LeaveRoom() { Logger.d("AndroidRtmpClient.LeaveRoom"); // if we are setting up a room but haven't got the room yet, we can't // leave the room now, we have to defer it to a later time when we have the room if (mRtmpActive && mRoom == null) { Logger.w("AndroidRtmpClient.LeaveRoom: waiting for room; deferring leave request."); mLeaveRoomRequested = true; } else { mClient.CallClientApi("leave room", () => { Clear("LeaveRoom called"); }, null); } } // called from UI thread, on onStop public void OnStop() { // if we launched an external activity (like the "select opponents" UI) as part of // the process, we should NOT clear our RTMP state on OnStop because we will get // OnStop when that Activity launches. if (mLaunchedExternalActivity) { Logger.d("OnStop: EXTERNAL ACTIVITY is pending, so not clearing RTMP."); } else { Clear("leaving room because game is stopping."); } } // called from the game thread public bool IsRoomConnected() { return mRoom != null && mDeliveredRoomConnected; } // called from the game thread public void DeclineInvitation(string invitationId) { Logger.d("AndroidRtmpClient.DeclineInvitation " + invitationId); mClient.ClearInvitationIfFromNotification(invitationId); mClient.CallClientApi("rtmp decline invitation", () => { mClient.GHManager.CallGmsApi("games.Games", "RealTimeMultiplayer", "declineInvitation", invitationId); }, (bool success) => { if (!success) { Logger.w("Failed to decline invitation. GoogleApiClient was disconnected"); } }); } // prepares to create a room private bool PrepareToCreateRoom(string method, RealTimeMultiplayerListener listener) { if (mRtmpActive) { Logger.e("Cannot call " + method + " while a real-time game is active."); if (listener != null) { Logger.d("Notifying listener of failure to create room."); listener.OnRoomConnected(false); } return false; } mAccumulatedProgress = 0.0f; mLastReportedProgress = 0.0f; mRtmpListener = listener; mRtmpActive = true; return true; } // checks that the room is connected, and warn otherwise private bool CheckConnectedRoom(string method) { if (mRoom == null || !mDeliveredRoomConnected) { Logger.e("Method " + method + " called without a connected room. " + "You must create or join a room AND wait until you get the " + "OnRoomConnected(true) callback."); return false; } return true; } // called from UI thread private void Clear(string reason) { Logger.d("RtmpClear: clearing RTMP (reason: " + reason + ")."); // leave the room, if we have one if (mRoom != null) { Logger.d("RtmpClear: Room still active, so leaving room."); string roomId = mRoom.Call<string>("getRoomId"); Logger.d("RtmpClear: room id to leave is " + roomId); // TODO: we are not specifying the callback from this API call to get // notified of when we *actually* leave the room. Perhaps we should do that, // in order to prevent the case where the developer tries to create a room // too soon after leaving the previous room, resulting in errors. mClient.GHManager.CallGmsApi("games.Games" , "RealTimeMultiplayer", "leave", new NoopProxy(JavaConsts.RoomUpdateListenerClass), roomId); Logger.d("RtmpClear: left room."); mRoom = null; } else { Logger.d("RtmpClear: no room active."); } // call the OnLeftRoom() callback if needed if (mDeliveredRoomConnected) { Logger.d("RtmpClear: looks like we must call the OnLeftRoom() callback."); RealTimeMultiplayerListener listener = mRtmpListener; if (listener != null) { Logger.d("Calling OnLeftRoom() callback."); PlayGamesHelperObject.RunOnGameThread(() => { listener.OnLeftRoom(); }); } } else { Logger.d("RtmpClear: no need to call OnLeftRoom() callback."); } mLeaveRoomRequested = false; mDeliveredRoomConnected = false; mRoom = null; mConnectedParticipants = null; mAllParticipants = null; mSelf = null; mRtmpListener = null; mVariant = 0; mRtmpActive = false; mAccumulatedProgress = 0.0f; mLastReportedProgress = 0.0f; mLaunchedExternalActivity = false; Logger.d("RtmpClear: RTMP cleared."); } private string[] SubtractParticipants(List<Participant> a, List<Participant> b) { List<string> result = new List<string>(); if (a != null) { foreach (Participant p in a) { result.Add(p.ParticipantId); } } if (b != null) { foreach (Participant p in b) { if (result.Contains(p.ParticipantId)) { result.Remove(p.ParticipantId); } } } return result.ToArray(); } // called from UI thread private void UpdateRoom() { List<AndroidJavaObject> toDispose = new List<AndroidJavaObject>(); Logger.d("UpdateRoom: Updating our cached data about the room."); string roomId = mRoom.Call<string>("getRoomId"); Logger.d("UpdateRoom: room id: " + roomId); Logger.d("UpdateRoom: querying for my player ID."); string playerId = mClient.GHManager.CallGmsApi<string>("games.Games", "Players", "getCurrentPlayerId"); Logger.d("UpdateRoom: my player ID is: " + playerId); Logger.d("UpdateRoom: querying for my participant ID in the room."); string myPartId = mRoom.Call<string>("getParticipantId", playerId); Logger.d("UpdateRoom: my participant ID is: " + myPartId); AndroidJavaObject participantIds = mRoom.Call<AndroidJavaObject>("getParticipantIds"); toDispose.Add(participantIds); int participantCount = participantIds.Call<int>("size"); Logger.d("UpdateRoom: # participants: " + participantCount); List<Participant> connectedParticipants = new List<Participant>(); List<Participant> allParticipants = new List<Participant>(); mSelf = null; for (int i = 0; i < participantCount; i++) { Logger.d("UpdateRoom: querying participant #" + i); string thisId = participantIds.Call<string>("get", i); Logger.d("UpdateRoom: participant #" + i + " has id: " + thisId); AndroidJavaObject thisPart = mRoom.Call<AndroidJavaObject>("getParticipant", thisId); toDispose.Add(thisPart); Participant p = JavaUtil.ConvertParticipant(thisPart); allParticipants.Add(p); if (p.ParticipantId.Equals(myPartId)) { Logger.d("Participant is SELF."); mSelf = p; } if (p.IsConnectedToRoom) { connectedParticipants.Add(p); } } if (mSelf == null) { Logger.e("List of room participants did not include self, " + " participant id: " + myPartId + ", player id: " + playerId); // stopgap: mSelf = new Participant("?", myPartId, Participant.ParticipantStatus.Unknown, new Player("?", playerId), false); } connectedParticipants.Sort(); allParticipants.Sort(); string[] newlyConnected; string[] newlyDisconnected; // lock the list because it's read by the game thread lock (mParticipantListsLock) { newlyConnected = SubtractParticipants(connectedParticipants, mConnectedParticipants); newlyDisconnected = SubtractParticipants(mConnectedParticipants, connectedParticipants); // IMPORTANT: we treat mConnectedParticipants as an immutable list; we give // away references to it to the callers of our API, so anyone out there might // be holding a reference to it and reading it from any thread. // This is why, instead of modifying it in place, we assign a NEW list to it. mConnectedParticipants = connectedParticipants; mAllParticipants = allParticipants; Logger.d("UpdateRoom: participant list now has " + mConnectedParticipants.Count + " participants."); } // cleanup Logger.d("UpdateRoom: cleanup."); foreach (AndroidJavaObject obj in toDispose) { obj.Dispose(); } Logger.d("UpdateRoom: newly connected participants: " + newlyConnected.Length); Logger.d("UpdateRoom: newly disconnected participants: " + newlyDisconnected.Length); // only deliver peers connected/disconnected events if have delivered OnRoomConnected if (mDeliveredRoomConnected) { if (newlyConnected.Length > 0 && mRtmpListener != null) { Logger.d("UpdateRoom: calling OnPeersConnected callback"); mRtmpListener.OnPeersConnected(newlyConnected); } if (newlyDisconnected.Length > 0 && mRtmpListener != null) { Logger.d("UpdateRoom: calling OnPeersDisconnected callback"); mRtmpListener.OnPeersDisconnected(newlyDisconnected); } } // did the developer request to leave the room? if (mLeaveRoomRequested) { Clear("deferred leave-room request"); } // is it time to report progress during room setup? if (!mDeliveredRoomConnected) { DeliverRoomSetupProgressUpdate(); } } // called from UI thread private void FailRoomSetup(string reason) { Logger.d("Failing room setup: " + reason); RealTimeMultiplayerListener listener = mRtmpListener; Clear("Room setup failed: " + reason); if (listener != null) { Logger.d("Invoking callback OnRoomConnected(false) to signal failure."); PlayGamesHelperObject.RunOnGameThread(() => { listener.OnRoomConnected(false); }); } } private bool CheckRtmpActive(string method) { if (!mRtmpActive) { Logger.d("Got call to " + method + " with RTMP inactive. Ignoring."); return false; } return true; } private void OnJoinedRoom(int statusCode, AndroidJavaObject room) { Logger.d("AndroidClient.OnJoinedRoom, status " + statusCode); if (!CheckRtmpActive("OnJoinedRoom")) { return; } mRoom = room; mAccumulatedProgress += 20.0f; if (statusCode != 0) { FailRoomSetup("OnJoinedRoom error code " + statusCode); } } private void OnLeftRoom(int statusCode, AndroidJavaObject room) { Logger.d("AndroidClient.OnLeftRoom, status " + statusCode); if (!CheckRtmpActive("OnLeftRoom")) { return; } Clear("Got OnLeftRoom " + statusCode); } private void OnRoomConnected(int statusCode, AndroidJavaObject room) { Logger.d("AndroidClient.OnRoomConnected, status " + statusCode); if (!CheckRtmpActive("OnRoomConnected")) { return; } mRoom = room; UpdateRoom(); if (statusCode != 0) { FailRoomSetup("OnRoomConnected error code " + statusCode); } else { Logger.d("AndroidClient.OnRoomConnected: room setup succeeded!"); RealTimeMultiplayerListener listener = mRtmpListener; if (listener != null) { Logger.d("Invoking callback OnRoomConnected(true) to report success."); PlayGamesHelperObject.RunOnGameThread(() => { mDeliveredRoomConnected = true; listener.OnRoomConnected(true); }); } } } private void OnRoomCreated(int statusCode, AndroidJavaObject room) { Logger.d("AndroidClient.OnRoomCreated, status " + statusCode); if (!CheckRtmpActive("OnRoomCreated")) { return; } mRoom = room; mAccumulatedProgress += 20.0f; if (statusCode != 0) { FailRoomSetup("OnRoomCreated error code " + statusCode); } UpdateRoom(); } private void OnConnectedToRoom(AndroidJavaObject room) { Logger.d("AndroidClient.OnConnectedToRoom"); if (!CheckRtmpActive("OnConnectedToRoom")) { return; } mAccumulatedProgress += 10.0f; mRoom = room; UpdateRoom(); } private void OnDisconnectedFromRoom(AndroidJavaObject room) { Logger.d("AndroidClient.OnDisconnectedFromRoom"); if (!CheckRtmpActive("OnDisconnectedFromRoom")) { return; } Clear("Got OnDisconnectedFromRoom"); } private void OnP2PConnected(string participantId) { Logger.d("AndroidClient.OnP2PConnected: " + participantId); if (!CheckRtmpActive("OnP2PConnected")) { return; } UpdateRoom(); } private void OnP2PDisconnected(string participantId) { Logger.d("AndroidClient.OnP2PDisconnected: " + participantId); if (!CheckRtmpActive("OnP2PDisconnected")) { return; } UpdateRoom(); } private void OnPeerDeclined(AndroidJavaObject room, AndroidJavaObject participantIds) { Logger.d("AndroidClient.OnPeerDeclined"); if (!CheckRtmpActive("OnPeerDeclined")) { return; } mRoom = room; UpdateRoom(); // In the current API implementation, if a peer declines, the room will never // subsequently get an onRoomConnected, so this match is doomed to failure. if (!mDeliveredRoomConnected) { FailRoomSetup("OnPeerDeclined received during setup"); } } private void OnPeerInvitedToRoom(AndroidJavaObject room, AndroidJavaObject participantIds) { Logger.d("AndroidClient.OnPeerInvitedToRoom"); if (!CheckRtmpActive("OnPeerInvitedToRoom")) { return; } mRoom = room; UpdateRoom(); } private void OnPeerJoined(AndroidJavaObject room, AndroidJavaObject participantIds) { Logger.d("AndroidClient.OnPeerJoined"); if (!CheckRtmpActive("OnPeerJoined")) { return; } mRoom = room; UpdateRoom(); } private void OnPeerLeft(AndroidJavaObject room, AndroidJavaObject participantIds) { Logger.d("AndroidClient.OnPeerLeft"); if (!CheckRtmpActive("OnPeerLeft")) { return; } mRoom = room; UpdateRoom(); // In the current API implementation, if a peer leaves, the room will never // subsequently get an onRoomConnected, so this match is doomed to failure. if (!mDeliveredRoomConnected) { FailRoomSetup("OnPeerLeft received during setup"); } } private void OnPeersConnected(AndroidJavaObject room, AndroidJavaObject participantIds) { Logger.d("AndroidClient.OnPeersConnected"); if (!CheckRtmpActive("OnPeersConnected")) { return; } mRoom = room; UpdateRoom(); } private void OnPeersDisconnected(AndroidJavaObject room, AndroidJavaObject participantIds) { Logger.d("AndroidClient.OnPeersDisconnected."); if (!CheckRtmpActive("OnPeersDisconnected")) { return; } mRoom = room; UpdateRoom(); } private void OnRoomAutoMatching(AndroidJavaObject room) { Logger.d("AndroidClient.OnRoomAutoMatching"); if (!CheckRtmpActive("OnRoomAutomatching")) { return; } mRoom = room; UpdateRoom(); } private void OnRoomConnecting(AndroidJavaObject room) { Logger.d("AndroidClient.OnRoomConnecting."); if (!CheckRtmpActive("OnRoomConnecting")) { return; } mRoom = room; UpdateRoom(); } private void OnRealTimeMessageReceived(AndroidJavaObject message) { Logger.d("AndroidClient.OnRealTimeMessageReceived."); if (!CheckRtmpActive("OnRealTimeMessageReceived")) { return; } RealTimeMultiplayerListener listener = mRtmpListener; if (listener != null) { byte[] messageData; using (AndroidJavaObject messageBytes = message.Call<AndroidJavaObject>("getMessageData")) { messageData = JavaUtil.ConvertByteArray(messageBytes); } bool isReliable = message.Call<bool>("isReliable"); string senderId = message.Call<string>("getSenderParticipantId"); PlayGamesHelperObject.RunOnGameThread(() => { listener.OnRealTimeMessageReceived(isReliable, senderId, messageData); }); } message.Dispose(); } private void OnSelectOpponentsResult(bool success, AndroidJavaObject opponents, bool hasAutoMatch, AndroidJavaObject autoMatchCriteria) { Logger.d("AndroidRtmpClient.OnSelectOpponentsResult, success=" + success); if (!CheckRtmpActive("OnSelectOpponentsResult")) { return; } // we now do not have an external Activity that we launched mLaunchedExternalActivity = false; if (!success) { Logger.w("Room setup failed because select-opponents UI failed."); FailRoomSetup("Select opponents UI failed."); return; } // at this point, we have to create the room -- but we have to make sure that // our GoogleApiClient is connected before we do that. It might NOT be connected // right now because we just came back from calling an external Activity. // So we use CallClientApi to make sure we are only doing this at the right time: mClient.CallClientApi("creating room w/ select-opponents result", () => { Logger.d("Creating room via support lib's RtmpUtil."); AndroidJavaClass rtmpUtil = JavaUtil.GetClass(JavaConsts.SupportRtmpUtilsClass); rtmpUtil.CallStatic("create", mClient.GHManager.GetApiClient(), opponents, mVariant, hasAutoMatch ? autoMatchCriteria : null, new RoomUpdateProxy(this), new RoomStatusUpdateProxy(this), new RealTimeMessageReceivedProxy(this)); }, (bool ok) => { if (!ok) { FailRoomSetup("GoogleApiClient lost connection"); } }); } private void OnInvitationInboxResult(bool success, string invitationId) { Logger.d("AndroidRtmpClient.OnInvitationInboxResult, " + "success=" + success + ", invitationId=" + invitationId); if (!CheckRtmpActive("OnInvitationInboxResult")) { return; } // we now do not have an external Activity that we launched mLaunchedExternalActivity = false; if (!success || invitationId == null || invitationId.Length == 0) { Logger.w("Failed to setup room because invitation inbox UI failed."); FailRoomSetup("Invitation inbox UI failed."); return; } mClient.ClearInvitationIfFromNotification(invitationId); // we use CallClientApi instead of calling the API directly because we need // to make sure that we call it when the GoogleApiClient is connected, which is // not necessarily true at this point (we just came back from an external // activity) mClient.CallClientApi("accept invite from inbox", () => { Logger.d("Accepting invite from inbox via support lib."); AndroidJavaClass rtmpUtil = JavaUtil.GetClass(JavaConsts.SupportRtmpUtilsClass); rtmpUtil.CallStatic("accept", mClient.GHManager.GetApiClient(), invitationId, new RoomUpdateProxy(this), new RoomStatusUpdateProxy(this), new RealTimeMessageReceivedProxy(this)); }, (bool ok) => { if (!ok) { FailRoomSetup("GoogleApiClient lost connection."); } }); } private void DeliverRoomSetupProgressUpdate() { Logger.d("AndroidRtmpClient: DeliverRoomSetupProgressUpdate"); if (!mRtmpActive || mRoom == null || mDeliveredRoomConnected) { // no need to deliver progress return; } float progress = CalcRoomSetupPercentage(); if (progress < mLastReportedProgress) { progress = mLastReportedProgress; } else { mLastReportedProgress = progress; } Logger.d("room setup progress: " + progress + "%"); if (mRtmpListener != null) { Logger.d("Delivering progress to callback."); PlayGamesHelperObject.RunOnGameThread(() => { mRtmpListener.OnRoomSetupProgress(progress); }); } } private float CalcRoomSetupPercentage() { if (!mRtmpActive || mRoom == null) { return 0.0f; } if (mDeliveredRoomConnected) { return 100.0f; } float progress = mAccumulatedProgress; if (progress > 50.0f) { progress = 50.0f; } float remaining = 100.0f - progress; int all = mAllParticipants == null ? 0 : mAllParticipants.Count; int connected = mConnectedParticipants == null ? 0 : mConnectedParticipants.Count; if (all == 0) { return progress; } else { return progress + remaining * ((float)connected / all); } } private class RoomUpdateProxy : AndroidJavaProxy { AndroidRtmpClient mOwner; internal RoomUpdateProxy(AndroidRtmpClient owner) : base(JavaConsts.RoomUpdateListenerClass) { mOwner = owner; } public void onJoinedRoom(int statusCode, AndroidJavaObject room) { mOwner.OnJoinedRoom(statusCode, room); } public void onLeftRoom(int statusCode, AndroidJavaObject room) { mOwner.OnLeftRoom(statusCode, room); } public void onRoomConnected(int statusCode, AndroidJavaObject room) { mOwner.OnRoomConnected(statusCode, room); } public void onRoomCreated(int statusCode, AndroidJavaObject room) { mOwner.OnRoomCreated(statusCode, room); } } private class RoomStatusUpdateProxy : AndroidJavaProxy { AndroidRtmpClient mOwner; internal RoomStatusUpdateProxy(AndroidRtmpClient owner) : base(JavaConsts.RoomStatusUpdateListenerClass) { mOwner = owner; } public void onConnectedToRoom(AndroidJavaObject room) { mOwner.OnConnectedToRoom(room); } public void onDisconnectedFromRoom(AndroidJavaObject room) { mOwner.OnDisconnectedFromRoom(room); } public void onP2PConnected(string participantId) { mOwner.OnP2PConnected(participantId); } public void onP2PDisconnected(string participantId) { mOwner.OnP2PDisconnected(participantId); } public void onPeerDeclined(AndroidJavaObject room, AndroidJavaObject participantIds) { mOwner.OnPeerDeclined(room, participantIds); } public void onPeerInvitedToRoom(AndroidJavaObject room, AndroidJavaObject participantIds) { mOwner.OnPeerInvitedToRoom(room, participantIds); } public void onPeerJoined(AndroidJavaObject room, AndroidJavaObject participantIds) { mOwner.OnPeerJoined(room, participantIds); } public void onPeerLeft(AndroidJavaObject room, AndroidJavaObject participantIds) { mOwner.OnPeerLeft(room, participantIds); } public void onPeersConnected(AndroidJavaObject room, AndroidJavaObject participantIds) { mOwner.OnPeersConnected(room, participantIds); } public void onPeersDisconnected(AndroidJavaObject room, AndroidJavaObject participantIds) { mOwner.OnPeersDisconnected(room, participantIds); } public void onRoomAutoMatching(AndroidJavaObject room) { mOwner.OnRoomAutoMatching(room); } public void onRoomConnecting(AndroidJavaObject room) { mOwner.OnRoomConnecting(room); } } private class RealTimeMessageReceivedProxy : AndroidJavaProxy { AndroidRtmpClient mOwner; internal RealTimeMessageReceivedProxy(AndroidRtmpClient owner) : base(JavaConsts.RealTimeMessageReceivedListenerClass) { mOwner = owner; } public void onRealTimeMessageReceived(AndroidJavaObject message) { mOwner.OnRealTimeMessageReceived(message); } } private class SelectOpponentsProxy : AndroidJavaProxy { AndroidRtmpClient mOwner; internal SelectOpponentsProxy(AndroidRtmpClient owner) : base(JavaConsts.SupportSelectOpponentsHelperActivityListener) { mOwner = owner; } public void onSelectOpponentsResult(bool success, AndroidJavaObject opponents, bool hasAutoMatch, AndroidJavaObject autoMatchCriteria) { mOwner.OnSelectOpponentsResult(success, opponents, hasAutoMatch, autoMatchCriteria); } } internal void OnSignInSucceeded() { // nothing for now } private class InvitationInboxProxy : AndroidJavaProxy { AndroidRtmpClient mOwner; internal InvitationInboxProxy(AndroidRtmpClient owner) : base(JavaConsts.SupportInvitationInboxHelperActivityListener) { mOwner = owner; } public void onInvitationInboxResult(bool success, string invitationId) { mOwner.OnInvitationInboxResult(success, invitationId); } public void onTurnBasedMatch(AndroidJavaObject match) { Logger.e("Bug: RTMP proxy got onTurnBasedMatch(). Shouldn't happen. Ignoring."); } } } } #endif
pixelthieves/Paper-Frog
Assets/GooglePlayGames/Platforms/Android/AndroidRtmpClient.cs
C#
gpl-2.0
43,782
# -*- coding: utf-8 -*- """ *************************************************************************** EditScriptAction.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot 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. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'April 2014' __copyright__ = '(C) 201, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from qgis.PyQt.QtWidgets import QFileDialog, QMessageBox from qgis.PyQt.QtGui import QIcon from qgis.PyQt.QtCore import QSettings, QFileInfo from processing.script.ScriptAlgorithm import ScriptAlgorithm from processing.gui.ToolboxAction import ToolboxAction from processing.script.WrongScriptException import WrongScriptException from processing.script.ScriptUtils import ScriptUtils from processing.core.alglist import algList pluginPath = os.path.split(os.path.dirname(__file__))[0] class AddScriptFromFileAction(ToolboxAction): def __init__(self): self.name, self.i18n_name = self.trAction('Add script from file') self.group, self.i18n_group = self.trAction('Tools') def getIcon(self): return QIcon(os.path.join(pluginPath, 'images', 'script.png')) def execute(self): settings = QSettings() lastDir = settings.value('Processing/lastScriptsDir', '') filename, selected_filter = QFileDialog.getOpenFileName(self.toolbox, self.tr('Script files', 'AddScriptFromFileAction'), lastDir, self.tr('Script files (*.py *.PY)', 'AddScriptFromFileAction')) if filename: try: settings.setValue('Processing/lastScriptsDir', QFileInfo(filename).absoluteDir().absolutePath()) script = ScriptAlgorithm(filename) except WrongScriptException: QMessageBox.warning(self.toolbox, self.tr('Error reading script', 'AddScriptFromFileAction'), self.tr('The selected file does not contain a valid script', 'AddScriptFromFileAction')) return destFilename = os.path.join(ScriptUtils.scriptsFolders()[0], os.path.basename(filename)) with open(destFilename, 'w') as f: f.write(script.script) algList.reloadProvider('script')
wonder-sk/QGIS
python/plugins/processing/script/AddScriptFromFileAction.py
Python
gpl-2.0
3,158
/* Copyright 2013 David Axmark Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * Util.cpp * * Created on: Aug 7, 2012 * Author: Spiridon Alexandru */ #include <maapi.h> #include "Util.h" #define BUF_MAX 256 /** * Detects if the current platform is Android. * @return true if the platform is Android, false otherwise. */ bool isAndroid() { char platform[BUF_MAX]; maGetSystemProperty("mosync.device.OS", platform, BUF_MAX); if ( strcmp(platform,"Android") == 0 ) { return true; } return false; } /** * Detects if the current platform is iOS. * @return true if the platform is iOS, false otherwise. */ bool isIOS() { char platform[BUF_MAX]; maGetSystemProperty("mosync.device.OS", platform, BUF_MAX); for (unsigned int i = 0; i < strlen(platform); i++) { platform[i] = tolower(platform[i]); } if (strstr(platform,"iphone") != NULL) { return true; } return false; } /** * Detects if the current platform is Windows Phone. * @return true if the platform is Windows Phone, false otherwise. */ bool isWindowsPhone() { char platform[BUF_MAX]; maGetSystemProperty("mosync.device.OS", platform, BUF_MAX); for (unsigned int i = 0; i < strlen(platform); i++) { platform[i] = tolower(platform[i]); } if (strstr(platform,"microsoft") != NULL && strstr(platform,"windows") != NULL) { return true; } return false; } /** * Get the string associated with a ListViewItemSelectionStyle. * @param style The given style. * @return The string associated with the given style. */ MAUtil::String getSelectionStyleString(NativeUI::ListViewItemSelectionStyle style) { MAUtil::String returnedValue; switch (style) { case NativeUI::LIST_VIEW_ITEM_SELECTION_STYLE_BLUE: returnedValue = "blue"; break; case NativeUI::LIST_VIEW_ITEM_SELECTION_STYLE_GRAY: returnedValue = "gray"; break; case NativeUI::LIST_VIEW_ITEM_SELECTION_STYLE_NONE: default: returnedValue = "none"; break; } return returnedValue; }
MoSync/MoSync
testPrograms/native_ui_lib/AlphabeticalListTest/Util.cpp
C++
gpl-2.0
2,447
<?php // Global profile namespace reference define( 'NS_USER_PROFILE', 202 ); define( 'NS_USER_WIKI', 200 ); // Default setup for displaying sections $wgUserPageChoice = true; $wgUserProfileDisplay['friends'] = false; $wgUserProfileDisplay['foes'] = false; $wgUserProfileDisplay['gifts'] = true; $wgUserProfileDisplay['awards'] = true; $wgUserProfileDisplay['profile'] = true; $wgUserProfileDisplay['board'] = false; $wgUserProfileDisplay['stats'] = false; // Display statistics on user profile pages? $wgUserProfileDisplay['interests'] = true; $wgUserProfileDisplay['custom'] = true; $wgUserProfileDisplay['personal'] = true; $wgUserProfileDisplay['activity'] = false; // Display recent social activity? $wgUserProfileDisplay['userboxes'] = false; // If FanBoxes extension is installed, setting this to true will display the user's fanboxes on their profile page $wgUserProfileDisplay['games'] = false; // Display casual games created by the user on their profile? This requires three separate social extensions: PictureGame, PollNY and QuizGame $wgUpdateProfileInRecentChanges = false; // Show a log entry in recent changes whenever a user updates their profile? $wgUploadAvatarInRecentChanges = false; // Same as above, but for avatar uploading $wgAvailableRights[] = 'avatarremove'; $wgAvailableRights[] = 'editothersprofiles'; $wgGroupPermissions['sysop']['avatarremove'] = true; $wgGroupPermissions['staff']['editothersprofiles'] = true; // ResourceLoader support for MediaWiki 1.17+ // Modules for Special:EditProfile/Special:UpdateProfile $wgResourceModules['ext.userProfile.updateProfile'] = array( 'styles' => 'UserProfile.css', 'scripts' => 'UpdateProfile.js', 'localBasePath' => dirname( __FILE__ ), 'remoteExtPath' => 'SocialProfile/UserProfile', 'position' => 'top' ); # Add new log types for profile edits and avatar uploads global $wgLogTypes, $wgLogNames, $wgLogHeaders, $wgLogActions; $wgLogTypes[] = 'profile'; $wgLogNames['profile'] = 'profilelogpage'; $wgLogHeaders['profile'] = 'profilelogpagetext'; $wgLogActions['profile/profile'] = 'profilelogentry'; $wgLogTypes[] = 'avatar'; $wgLogNames['avatar'] = 'avatarlogpage'; $wgLogHeaders['avatar'] = 'avatarlogpagetext'; $wgLogActions['avatar/avatar'] = 'avatarlogentry'; $wgHooks['ArticleFromTitle'][] = 'wfUserProfileFromTitle'; /** * Called by ArticleFromTitle hook * Calls UserProfilePage instead of standard article * * @param &$title Title object * @param &$article Article object * @return true */ function wfUserProfileFromTitle( &$title, &$article ) { global $wgRequest, $wgOut, $wgHooks, $wgUserPageChoice, $wgUserProfileScripts; if ( strpos( $title->getText(), '/' ) === false && ( NS_USER == $title->getNamespace() || NS_USER_PROFILE == $title->getNamespace() ) ) { $show_user_page = false; if ( $wgUserPageChoice ) { $profile = new UserProfile( $title->getText() ); $profile_data = $profile->getProfile(); // If they want regular page, ignore this hook if ( isset( $profile_data['user_id'] ) && $profile_data['user_id'] && $profile_data['user_page_type'] == 0 ) { $show_user_page = true; } } if ( !$show_user_page ) { // Prevents editing of userpage if ( $wgRequest->getVal( 'action' ) == 'edit' ) { $wgOut->redirect( $title->getFullURL() ); } } else { $wgOut->enableClientCache( false ); $wgHooks['ParserLimitReport'][] = 'wfUserProfileMarkUncacheable'; } $wgOut->addExtensionStyle( $wgUserProfileScripts . '/UserProfile.css' ); $article = new UserProfilePage( $title ); } return true; } /** * Mark page as uncacheable * * @param $parser Parser object * @param &$limitReport String: unused * @return true */ function wfUserProfileMarkUncacheable( $parser, &$limitReport ) { $parser->disableCache(); return true; }
SuriyaaKudoIsc/wikia-app-test
extensions/SocialProfile/UserProfile/UserProfile.php
PHP
gpl-2.0
3,868
<?php /** * @Project NUKEVIET 4.x * @Author VINADES.,JSC (contact@vinades.vn) * @Copyright (C) 2014 VINADES.,JSC. All rights reserved * @License GNU/GPL version 2 or any later version * @Createdate 2-1-2010 22:42 */ define( 'NV_ADMIN', true ); require_once 'mainfile.php'; $file_config_temp = NV_TEMP_DIR . '/config_' . md5( $global_config['sitekey'] ) . '.php'; $dirs = nv_scandir( NV_ROOTDIR . '/includes/language', '/^([a-z]{2})/' ); $languageslist = array(); foreach( $dirs as $file ) { if( is_file( NV_ROOTDIR . '/includes/language/' . $file . '/install.php' ) ) { $languageslist[] = $file; } } require_once NV_ROOTDIR . '/modules/users/language/' . NV_LANG_DATA . '.php'; require_once NV_ROOTDIR . '/includes/language/' . NV_LANG_DATA . '/global.php'; require_once NV_ROOTDIR . '/includes/language/' . NV_LANG_DATA . '/install.php'; require_once NV_ROOTDIR . '/install/template.php'; require_once NV_ROOTDIR . '/includes/core/admin_functions.php'; if( is_file( NV_ROOTDIR . '/install/default.php' ) ) { require_once NV_ROOTDIR . '/install/default.php'; } if( is_file( NV_ROOTDIR . '/' . $file_config_temp ) ) { require_once NV_ROOTDIR . '/' . $file_config_temp; } $contents = ''; $step = $nv_Request->get_int( 'step', 'post,get', 1 ); $maxstep = $nv_Request->get_int( 'maxstep', 'session', 1 ); if( $step <= 0 or $step > 7 ) { Header( 'Location: ' . NV_BASE_SITEURL . 'install/index.php?' . NV_LANG_VARIABLE . '=' . NV_LANG_DATA . '&step=1' ); exit(); } if( $step > $maxstep and $step > 2 ) { $step = $maxstep; Header( 'Location: ' . NV_BASE_SITEURL . 'install/index.php?' . NV_LANG_VARIABLE . '=' . NV_LANG_DATA . '&step=' . $step ); exit(); } if( file_exists( NV_ROOTDIR . '/' . NV_CONFIG_FILENAME ) and $step < 7 ) { Header( 'Location: ' . NV_BASE_SITEURL . 'index.php' ); exit(); } if( empty( $sys_info['supports_rewrite'] ) ) { if( isset( $_COOKIE['supports_rewrite'] ) and $_COOKIE['supports_rewrite'] == md5( $global_config['sitekey'] ) ) { $sys_info['supports_rewrite'] = 'rewrite_mode_apache'; } } if( $step == 1 ) { if( $step < 2 ) { $nv_Request->set_Session( 'maxstep', 2 ); } $title = $lang_module['select_language']; $contents = nv_step_1(); } elseif( $step == 2 ) { // Tu dong nhan dang Remove Path if( $nv_Request->isset_request( 'tetectftp', 'post' ) ) { $ftp_server = nv_unhtmlspecialchars( $nv_Request->get_title( 'ftp_server', 'post', '', 1 ) ); $ftp_port = intval( $nv_Request->get_title( 'ftp_port', 'post', '21', 1 ) ); $ftp_user_name = nv_unhtmlspecialchars( $nv_Request->get_title( 'ftp_user_name', 'post', '', 1 ) ); $ftp_user_pass = nv_unhtmlspecialchars( $nv_Request->get_title( 'ftp_user_pass', 'post', '', 1 ) ); if( ! $ftp_server or ! $ftp_user_name or ! $ftp_user_pass ) { die( 'ERROR|' . $lang_module['ftp_error_empty'] ); } $ftp = new NVftp( $ftp_server, $ftp_user_name, $ftp_user_pass, array( 'timeout' => 10 ), $ftp_port ); if( ! empty( $ftp->error ) ) { $ftp->close(); die( 'ERROR|' . ( string )$ftp->error ); } else { $list_valid = array( NV_CACHEDIR, NV_DATADIR, 'images', 'includes', 'js', 'language', NV_LOGS_DIR, 'modules', 'themes', NV_TEMP_DIR, NV_UPLOADS_DIR ); $ftp_root = $ftp->detectFtpRoot( $list_valid, NV_ROOTDIR ); if( $ftp_root === false ) { $ftp->close(); die( 'ERROR|' . ( empty( $ftp->error ) ? $lang_module['ftp_error_detect_root'] : ( string )$ftp->error ) ); } $ftp->close(); die( 'OK|' . $ftp_root ); } $ftp->close(); die( 'ERROR|' . $lang_module['ftp_error_detect_root'] ); } // Danh sach cac file can kiem tra quyen ghi $array_dir = array( NV_LOGS_DIR, NV_LOGS_DIR . '/data_logs', NV_LOGS_DIR . '/dump_backup', NV_LOGS_DIR . '/error_logs', NV_LOGS_DIR . '/error_logs/errors256', NV_LOGS_DIR . '/error_logs/old', NV_LOGS_DIR . '/error_logs/tmp', NV_LOGS_DIR . '/ip_logs', NV_LOGS_DIR . '/ref_logs', NV_LOGS_DIR . '/voting_logs', NV_CACHEDIR, NV_UPLOADS_DIR, NV_TEMP_DIR, NV_FILES_DIR, NV_DATADIR ); // Them vao cac file trong thu muc data va file cau hinh tam $array_file_data = nv_scandir( NV_ROOTDIR . '/' . NV_DATADIR, '/^([a-zA-Z0-9\-\_\.]+)\.([a-z0-9]{2,6})$/' ); foreach( $array_file_data as $file_i ) { $array_dir[] = NV_DATADIR . '/' . $file_i; } $array_dir[] = $file_config_temp; // Them vao file .htaccess va web.config if( ! empty( $sys_info['supports_rewrite'] ) ) { if( $sys_info['supports_rewrite'] == 'rewrite_mode_apache' ) { $array_dir[] = '.htaccess'; } else { $array_dir[] = 'web.config'; } } // Cau hinh FTP $ftp_check_login = 0; $global_config['ftp_server'] = $nv_Request->get_string( 'ftp_server', 'post', 'localhost' ); $global_config['ftp_port'] = $nv_Request->get_int( 'ftp_port', 'post', 21 ); $global_config['ftp_user_name'] = $nv_Request->get_string( 'ftp_user_name', 'post', '' ); $global_config['ftp_user_pass'] = $nv_Request->get_string( 'ftp_user_pass', 'post', '' ); $global_config['ftp_path'] = $nv_Request->get_string( 'ftp_path', 'post', '/' ); $array_ftp_data = array( 'ftp_server' => $global_config['ftp_server'], 'ftp_port' => $global_config['ftp_port'], 'ftp_user_name' => $global_config['ftp_user_name'], 'ftp_user_pass' => $global_config['ftp_user_pass'], 'ftp_path' => $global_config['ftp_path'], 'error' => '' ); // CHMOD bang FTP $modftp = $nv_Request->get_int( 'modftp', 'post', 0 ); if( $modftp ) { if( ! empty( $global_config['ftp_server'] ) and ! empty( $global_config['ftp_user_name'] ) and ! empty( $global_config['ftp_user_pass'] ) ) { // Set up basic connection $conn_id = ftp_connect( $global_config['ftp_server'], $global_config['ftp_port'], 10 ); // Login with username and password $login_result = ftp_login( $conn_id, $global_config['ftp_user_name'], $global_config['ftp_user_pass'] ); if( ( ! $conn_id ) || ( ! $login_result ) ) { $ftp_check_login = 3; $array_ftp_data['error'] = $lang_module['ftp_error_account']; } elseif( ftp_chdir( $conn_id, $global_config['ftp_path'] ) ) { $check_files = array( NV_CACHEDIR, NV_DATADIR, 'images', 'includes', 'index.php', 'robots.txt', 'js', 'language', NV_LOGS_DIR, 'modules', 'themes', NV_TEMP_DIR ); $list_files = ftp_nlist( $conn_id, '.' ); $a = 0; foreach( $list_files as $filename ) { $filename = basename( $filename ); if( in_array( $filename, $check_files ) ) { ++$a; } } if( $a == sizeof( $check_files ) ) { $ftp_check_login = 1; nv_chmod_dir( $conn_id, NV_DATADIR, true ); nv_chmod_dir( $conn_id, NV_TEMP_DIR, true ); nv_save_file_config(); nv_chmod_dir( $conn_id, NV_TEMP_DIR, true ); } else { $ftp_check_login = 2; $array_ftp_data['error'] = $lang_module['ftp_error_path']; } } else { $ftp_check_login = 2; $array_ftp_data['error'] = $lang_module['ftp_error_path']; } $global_config['ftp_check_login'] = $ftp_check_login; } } // Kiem tra quyen ghi doi voi nhung file tren $nextstep = 1; $array_dir_check = array(); foreach( $array_dir as $dir ) { if( $ftp_check_login == 1 ) { if( ! is_dir( NV_ROOTDIR . '/' . $dir ) and $dir != $file_config_temp ) { ftp_mkdir( $conn_id, $dir ); } if( ! is_writable( NV_ROOTDIR . '/' . $dir ) ) { if( substr( $sys_info['os'], 0, 3 ) != 'WIN' ) ftp_chmod( $conn_id, 0777, $dir ); } } if( $dir == $file_config_temp and ! file_exists( NV_ROOTDIR . '/' . $file_config_temp ) and is_writable( NV_ROOTDIR . '/' . NV_TEMP_DIR ) ) { file_put_contents( NV_ROOTDIR . '/' . $file_config_temp, '', LOCK_EX ); } if( is_file( NV_ROOTDIR . '/' . $dir ) ) { if( is_writable( NV_ROOTDIR . '/' . $dir ) ) { $array_dir_check[$dir] = $lang_module['dir_writable']; } else { $array_dir_check[$dir] = $lang_module['dir_not_writable']; $nextstep = 0; } } elseif( is_dir( NV_ROOTDIR . '/' . $dir ) ) { if( is_writable( NV_ROOTDIR . '/' . $dir ) ) { $array_dir_check[$dir] = $lang_module['dir_writable']; } else { $array_dir_check[$dir] = $lang_module['dir_not_writable']; $nextstep = 0; } } else { $array_dir_check[$dir] = $lang_module['dir_noexit']; $nextstep = 0; } } if( ! nv_save_file_config( $db_config, $global_config ) and $ftp_check_login == 1 ) { ftp_chmod( $conn_id, 0777, $file_config_temp ); } if( $ftp_check_login > 0 ) { ftp_close( $conn_id ); } if( $step < 3 and $nextstep == 1 ) { $nv_Request->set_Session( 'maxstep', 3 ); } $title = $lang_module['check_chmod']; $contents = nv_step_2( $array_dir_check, $array_ftp_data, $nextstep ); } elseif( $step == 3 ) { if( $step < 4 ) { $nv_Request->set_Session( 'maxstep', 4 ); } $title = $lang_module['license']; if( file_exists( NV_ROOTDIR . '/install/licenses_' . NV_LANG_DATA . '.html' ) ) { $license = file_get_contents( NV_ROOTDIR . '/install/licenses_' . NV_LANG_DATA . '.html' ); } else { $license = file_get_contents( NV_ROOTDIR . '/install/licenses.html' ); } $contents = nv_step_3( $license ); } elseif( $step == 4 ) { $nextstep = 0; $title = $lang_module['check_server']; $array_resquest = array(); $array_resquest['pdo_support'] = $lang_module['not_compatible']; $array_resquest['class_pdo_support'] = 'highlight_red'; if ( class_exists( 'PDO', false ) ) { $PDODrivers = PDO::getAvailableDrivers(); foreach($PDODrivers as $_driver) { if( file_exists( NV_ROOTDIR . '/install/action_' . $_driver . '.php' ) ) { $array_resquest['pdo_support'] = $lang_module['compatible']; $array_resquest['class_pdo_support'] = 'highlight_green'; $nextstep = 1; break; } } } $array_resquest['php_required'] = $sys_info['php_required']; $sys_info['php_support'] = ( version_compare( PHP_VERSION, $sys_info['php_required'] ) < 0 ) ? 0 : 1; $array_resquest_key = array( 'php_support', 'opendir_support', 'gd_support', 'mcrypt_support', 'session_support', 'fileuploads_support' ); foreach( $array_resquest_key as $key ) { $array_resquest['class_' . $key] = ( $sys_info[$key] ) ? 'highlight_green' : 'highlight_red'; $array_resquest[$key] = ( $sys_info[$key] ) ? $lang_module['compatible'] : $lang_module['not_compatible']; if( ! $sys_info[$key] ) { $nextstep = 0; } } if( $step < 5 and $nextstep == 1 ) { $nv_Request->set_Session( 'maxstep', 5 ); } $array_suport = array(); $array_support['supports_rewrite'] = ( empty( $sys_info['supports_rewrite'] ) ) ? 0 : 1; $array_support['safe_mode'] = ( $sys_info['safe_mode'] ) ? 0 : 1; $array_support['register_globals'] = ( ini_get( 'register_globals' ) == '1' || strtolower( ini_get( 'register_globals' ) ) == 'on' ) ? 0 : 1; $array_support['magic_quotes_runtime'] = ( ini_get( 'magic_quotes_runtime' ) == '1' || strtolower( ini_get( 'magic_quotes_runtime' ) ) == 'on' ) ? 0 : 1; $array_support['magic_quotes_gpc'] = ( ini_get( 'magic_quotes_gpc' ) == '1' || strtolower( ini_get( 'magic_quotes_gpc' ) ) == 'on' ) ? 0 : 1; $array_support['magic_quotes_sybase'] = ( ini_get( 'magic_quotes_sybase' ) == '1' || strtolower( ini_get( 'magic_quotes_sybase' ) ) == 'on' ) ? 0 : 1; $array_support['output_buffering'] = ( ini_get( 'output_buffering' ) == '1' || strtolower( ini_get( 'output_buffering' ) ) == 'on' ) ? 0 : 1; $array_support['session_auto_start'] = ( ini_get( 'session.auto_start' ) == '1' || strtolower( ini_get( 'session.auto_start' ) ) == 'on' ) ? 0 : 1; $array_support['display_errors'] = ( ini_get( 'display_errors' ) == '1' || strtolower( ini_get( 'display_errors' ) ) == 'on' ) ? 0 : 1; $array_support['allowed_set_time_limit'] = ( $sys_info['allowed_set_time_limit'] ) ? 1 : 0; $array_support['zlib_support'] = ( $sys_info['zlib_support'] ) ? 1 : 0; $array_support['zip_support'] = ( extension_loaded( 'zip' ) ) ? 1 : 0; foreach ($array_support as $_key => $_support ) { $array_support['class_' . $_key] = ( $_support ) ? 'highlight_green' : 'highlight_red'; $array_support[$_key] = ( $_support ) ? $lang_module['compatible'] : $lang_module['not_compatible']; } $contents = nv_step_4( $array_resquest, $array_support, $nextstep ); } elseif( $step == 5 ) { $nextstep = 0; $db_config['error'] = ''; $db_config['dbtype'] = $nv_Request->get_string( 'dbtype', 'post', $db_config['dbtype'] ); $db_config['dbhost'] = $nv_Request->get_string( 'dbhost', 'post', $db_config['dbhost'] ); $db_config['dbname'] = $nv_Request->get_string( 'dbname', 'post', $db_config['dbname'] ); $db_config['dbuname'] = $nv_Request->get_string( 'dbuname', 'post', $db_config['dbuname'] ); $db_config['dbpass'] = $nv_Request->get_string( 'dbpass', 'post', $db_config['dbpass'] ); $db_config['prefix'] = $nv_Request->get_string( 'prefix', 'post', $db_config['prefix'] ); $db_config['dbport'] = $nv_Request->get_string( 'dbport', 'post', $db_config['dbport'] ); $db_config['db_detete'] = $nv_Request->get_int( 'db_detete', 'post', $db_config['dbdetete'] ); $db_config['num_table'] = 0; $db_config['create_db'] = 1; $PDODrivers = PDO::getAvailableDrivers(); // Check dbtype if( $nv_Request->isset_request( 'checkdbtype', 'post' ) ) { $dbtype = $nv_Request->get_title( 'checkdbtype', 'post' ); $respon = array( 'status' => 'error', 'dbtype' => $dbtype, 'message' => '', 'link' => '', 'files' => array() ); if( $dbtype == 'mysql' ) // Not check default dbtype { $respon['status'] = 'success'; } else { if( ! in_array( $dbtype, $PDODrivers ) ) { $respon['message'] = $lang_module['dbcheck_error_driver']; } else { $array_check_files = array( 'install' => 'install/action_' . $dbtype . '.php', 'sys' => 'includes/action_' . $dbtype . '.php' ); include NV_ROOTDIR . '/includes/action_mysql.php'; $array_module_setup = array_map( "trim", explode( ',', NV_MODULE_SETUP_DEFAULT ) ); foreach( $array_module_setup as $module ) { if( file_exists( NV_ROOTDIR . '/modules/' . $module . '/action_mysql.php' ) ) { $array_check_files[] = 'modules/' . $module . '/action_' . $dbtype . '.php'; } } foreach( $array_check_files as $key => $file ) { if( file_exists( NV_ROOTDIR . '/' . $file ) ) { unset( $array_check_files[$key] ); } } if( empty( $array_check_files ) ) { $respon['status'] = 'success'; } else { asort( $array_check_files ); $respon['files'] = $array_check_files; $respon['link'] = 'https://github.com/nukeviet/nukeviet/wiki/NukeViet-database-types'; $respon['message'] = $lang_module['dbcheck_error_files']; } } } echo json_encode( $respon ); die(); } if( in_array( $db_config['dbtype'], $PDODrivers ) and ! empty( $db_config['dbhost'] ) and ! empty( $db_config['dbname'] ) and ! empty( $db_config['dbuname'] ) and ! empty( $db_config['prefix'] ) ) { $db_config['dbuname'] = preg_replace( array( '/[^a-z0-9]/i', '/[\_]+/', '/^[\_]+/', '/[\_]+$/' ), array( '_', '_', '', '' ), $db_config['dbuname'] ); $db_config['dbname'] = preg_replace( array( '/[^a-z0-9]/i', '/[\_]+/', '/^[\_]+/', '/[\_]+$/' ), array( '_', '_', '', '' ), $db_config['dbname'] ); $db_config['prefix'] = preg_replace( array( '/[^a-z0-9]/', '/[\_]+/', '/^[\_]+/', '/[\_]+$/' ), array( '_', '_', '', '' ), strtolower( $db_config['prefix'] ) ); if( substr( $sys_info['os'], 0, 3 ) == 'WIN' and $db_config['dbhost'] == 'localhost' ) { $db_config['dbhost'] = '127.0.0.1'; } if( $db_config['dbtype'] == 'mysql' ) { $db_config['dbsystem'] = $db_config['dbname']; } elseif( $db_config['dbtype'] == 'oci' and empty( $db_config['dbport'] ) ) { $db_config['dbport'] = 1521; $db_config['dbsystem'] = $db_config['dbuname']; } // Bat dau phien lam viec cua MySQL $db = new sql_db( $db_config ); $connect = $db->connect; if( ! $connect ) { $db_config['error'] = 'Could not connect to data server'; if( $db_config['dbtype'] == 'mysql' ) { $db_config['dbname'] = ''; $db = new sql_db( $db_config ); $db_config['dbname'] = $db_config['dbsystem']; if( $db->connect ) { try { $db->query( 'CREATE DATABASE ' . $db_config['dbname'] ); $db->exec( 'USE ' . $db_config['dbname'] ); $db_config['error'] = ''; $connect = 1; } catch( PDOException $e ) { trigger_error( $e->getMessage() ); } } } } if( $connect AND $db_config['dbtype'] == 'mysql' ) { try { $db->exec( 'ALTER DATABASE ' . $db_config['dbname'] . ' DEFAULT CHARACTER SET utf8 COLLATE ' . $db_config['collation'] ); } catch( PDOException $e ) { trigger_error( $e->getMessage() ); } $row = $db->query( 'SELECT @@session.character_set_database AS character_set_database, @@session.collation_database AS collation_database')->fetch(); if( $row['character_set_database'] != 'utf8' or $row['collation_database'] != $db_config['collation'] ) { $db_config['error'] = 'Error character set database'; $connect = 0; } } if( $connect ) { $tables = array(); if( $sys_info['allowed_set_time_limit'] ) { set_time_limit( 0 ); } // Cai dat du lieu cho he thong $db_config['error'] = ''; $sql_create_table = array(); $sql_drop_table = array(); define( 'NV_AUTHORS_GLOBALTABLE', $db_config['prefix'] . '_authors' ); define( 'NV_USERS_GLOBALTABLE', $db_config['prefix'] . '_users' ); define( 'NV_CONFIG_GLOBALTABLE', $db_config['prefix'] . '_config' ); define( 'NV_GROUPS_GLOBALTABLE', $db_config['prefix'] . '_groups' ); define( 'NV_LANGUAGE_GLOBALTABLE', $db_config['prefix'] . '_language' ); define( 'NV_SESSIONS_GLOBALTABLE', $db_config['prefix'] . '_sessions' ); define( 'NV_COOKIES_GLOBALTABLE', $db_config['prefix'] . '_cookies' ); define( 'NV_CRONJOBS_GLOBALTABLE', $db_config['prefix'] . '_cronjobs' ); require_once NV_ROOTDIR . '/install/action_' . $db_config['dbtype'] . '.php'; $num_table = sizeof( $sql_drop_table ); if( $num_table > 0 ) { if( $db_config['db_detete'] == 1 ) { foreach( $sql_drop_table as $_sql ) { try { $db->query( $_sql ); } catch( PDOException $e ) { $nv_Request->set_Session( 'maxstep', 4 ); $db_config['error'] = $e->getMessage(); trigger_error( $e->getMessage() ); break; } } $num_table = 0; } else { $db_config['error'] = $lang_module['db_err_prefix']; } } $db_config['num_table'] = $num_table; if( $num_table == 0 ) { nv_save_file_config(); require_once NV_ROOTDIR . '/install/data.php'; foreach( $sql_create_table as $_sql ) { try { $db->query( $_sql ); } catch( PDOException $e ) { $nv_Request->set_Session( 'maxstep', 4 ); $db_config['error'] = $e->getMessage(); trigger_error( $e->getMessage() ); break; } } // Cai dat du lieu cho cac module if( empty( $db_config['error'] ) ) { define( 'NV_IS_MODADMIN', true ); $module_name = 'modules'; $lang_module['modules'] = ''; $lang_module['vmodule_add'] = ''; $lang_module['autoinstall'] = ''; $lang_global['mod_modules'] = ''; define( 'NV_UPLOAD_GLOBALTABLE', $db_config['prefix'] . '_upload' ); require_once NV_ROOTDIR . '/' . NV_ADMINDIR . '/modules/functions.php'; $module_name = ''; $modules_exit = nv_scandir( NV_ROOTDIR . '/modules', $global_config['check_module'] ); // Cai dat du lieu cho ngon ngu require_once NV_ROOTDIR . '/includes/action_' . $db_config['dbtype'] . '.php'; $sql_create_table = nv_create_table_sys( NV_LANG_DATA ); foreach( $sql_create_table as $_sql ) { try { $db->query( $_sql ); } catch( PDOException $e ) { $nv_Request->set_Session( 'maxstep', 4 ); $db_config['error'] = $e->getMessage(); trigger_error( $e->getMessage() ); break; } } unset( $sql_create_table ); $sql = 'SELECT * FROM ' . $db_config['prefix'] . '_' . NV_LANG_DATA . '_modules ORDER BY weight ASC'; $result = $db->query( $sql ); $modules = $result->fetchAll(); foreach( $modules as $key => $row ) { $setmodule = $row['title']; if( in_array( $row['module_file'], $modules_exit ) ) { $sm = nv_setup_data_module( NV_LANG_DATA, $setmodule ); if( $sm != 'OK_' . $setmodule ) { die( 'error set module: ' . $setmodule ); } } else { unset( $modules[$key] ); $db->query( 'DELETE FROM ' . $db_config['prefix'] . '_' . NV_LANG_DATA . '_modules WHERE title=' . $db->quote( $setmodule ) ); } } // Cai dat du lieu mau he thong $filesavedata = NV_LANG_DATA; $lang_data = NV_LANG_DATA; if( ! file_exists( NV_ROOTDIR . '/install/data_' . $lang_data . '.php' ) ) { $filesavedata = 'en'; } include_once NV_ROOTDIR . '/install/data_' . $filesavedata . '.php' ; try { // Xoa du lieu tai bang nvx_vi_modules $db->query( "DELETE FROM " . $db_config['prefix'] . "_" . $lang_data . "_modules WHERE module_file NOT IN ('" . implode( "', '", $modules_exit ) . "')" ); // Xoa du lieu tai bang nvx_setup_extensions $db->query( "DELETE FROM " . $db_config['prefix'] . "_setup_extensions WHERE basename NOT IN ('" . implode( "', '", $modules_exit ) . "') AND type='module'" ); // Xoa du lieu tai bang nvx_vi_blocks_groups $db->query( "DELETE FROM " . $db_config['prefix'] . "_" . $lang_data . "_blocks_groups WHERE module!='theme' AND module NOT IN (SELECT title FROM " . $db_config['prefix'] . "_" . $lang_data . "_modules)" ); // Xoa du lieu tai bang nvx_vi_blocks $db->query( "DELETE FROM " . $db_config['prefix'] . "_" . $lang_data . "_blocks_weight WHERE bid NOT IN (SELECT bid FROM " . $db_config['prefix'] . "_" . $lang_data . "_blocks_groups)" ); // Xoa du lieu tai bang nvx_vi_modthemes $db->query( "DELETE FROM " . $db_config['prefix'] . "_" . $lang_data . "_modthemes WHERE func_id in (SELECT func_id FROM " . $db_config['prefix'] . "_" . $lang_data . "_modfuncs WHERE in_module NOT IN (SELECT title FROM " . $db_config['prefix'] . "_" . $lang_data . "_modules))" ); // Xoa du lieu tai bang nvx_vi_modfuncs $db->query( "DELETE FROM " . $db_config['prefix'] . "_" . $lang_data . "_modfuncs WHERE in_module NOT IN (SELECT title FROM " . $db_config['prefix'] . "_" . $lang_data . "_modules)" ); // Xoa du lieu tai bang nvx_menu $db->query( "DELETE FROM " . $db_config['prefix'] . "_" . $lang_data . "_menu_rows WHERE module_name NOT IN (SELECT title FROM " . $db_config['prefix'] . "_" . $lang_data . "_modules)" ); } catch( PDOException $e ) { $nv_Request->set_Session( 'maxstep', 4 ); $db_config['error'] = $e->getMessage(); trigger_error( $e->getMessage() ); break; } // Cai dat du lieu mau module $lang = NV_LANG_DATA; foreach( $modules as $key => $row ) { $module_name = $row['title']; $module_file = $row['module_file']; $module_data = $row['module_data']; if( file_exists( NV_ROOTDIR . '/modules/' . $module_file . '/language/data_' . NV_LANG_DATA . '.php' ) ) { include NV_ROOTDIR . '/modules/' . $module_file . '/language/data_' . NV_LANG_DATA . '.php'; } elseif( file_exists( NV_ROOTDIR . '/modules/' . $module_file . '/language/data_en.php' ) ) { include NV_ROOTDIR . '/modules/' . $module_file . '/language/data_en.php'; } if( empty( $array_data['socialbutton'] ) ) { if( $module_file == 'news' ) { $db->query( "UPDATE " . NV_CONFIG_GLOBALTABLE . " SET config_value = '0' WHERE module = '" . $module_name . "' AND config_name = 'socialbutton' AND lang='" . $lang . "'" ); } } } if( empty( $db_config['error'] )) { ++ $step; $nv_Request->set_Session( 'maxstep', $step ); Header( 'Location: ' . NV_BASE_SITEURL . 'install/index.php?' . NV_LANG_VARIABLE . '=' . NV_LANG_DATA . '&step=' . $step ); exit(); } } } } } $title = $lang_module['config_database']; $contents = nv_step_5( $db_config, $nextstep ); } elseif( $step == 6 ) { $nextstep = 0; $error = ''; define( 'NV_USERS_GLOBALTABLE', $db_config['prefix'] . '_users' ); // Bat dau phien lam viec cua MySQL $db = new sql_db( $db_config ); if( ! empty( $db->error ) ) { $error = ( ! empty( $db->error['user_message'] ) ) ? $db->error['user_message'] : $db->error['message']; } $array_data['site_name'] = $nv_Request->get_title( 'site_name', 'post', $array_data['site_name'], 1 ); $array_data['nv_login'] = nv_substr( $nv_Request->get_title( 'nv_login', 'post', $array_data['nv_login'], 1 ), 0, NV_UNICKMAX ); $array_data['nv_email'] = $nv_Request->get_title( 'nv_email', 'post', $array_data['nv_email'] ); $array_data['nv_password'] = $nv_Request->get_title( 'nv_password', 'post', $array_data['nv_password'] ); $array_data['re_password'] = $nv_Request->get_title( 're_password', 'post', $array_data['re_password'] ); $array_data['lang_multi'] = (int) $nv_Request->get_bool( 'lang_multi', 'post', $array_data['lang_multi'] ); $check_login = nv_check_valid_login( $array_data['nv_login'], NV_UNICKMAX, NV_UNICKMIN ); $check_pass = nv_check_valid_pass( $array_data['nv_password'], NV_UPASSMAX, NV_UPASSMIN ); $check_email = nv_check_valid_email( $array_data['nv_email'] ); $array_data['question'] = $nv_Request->get_title( 'question', 'post', $array_data['question'], 1 ); $array_data['answer_question'] = $nv_Request->get_title( 'answer_question', 'post', $array_data['answer_question'], 1 ); $global_config['site_email'] = $array_data['nv_email']; if( $nv_Request->isset_request( 'nv_login,nv_password', 'post' ) ) { if( empty( $array_data['site_name'] ) ) { $error = $lang_module['err_sitename']; } elseif( ! empty( $check_login ) ) { $error = $check_login; } elseif( "'" . $array_data['nv_login'] . "'" != $db->quote( $array_data['nv_login'] ) ) { $error = sprintf( $lang_module['account_deny_name'], '<strong>' . $array_data['nv_login'] . '</strong>' ); } elseif( ! empty( $check_email ) ) { $error = $check_email; } elseif( ! empty( $check_pass ) ) { $error = $check_pass; } elseif( $array_data['nv_password'] != $array_data['re_password'] ) { $error = $lang_global['passwordsincorrect']; } elseif( empty( $array_data['question'] ) ) { $error = $lang_module['your_question_empty']; } elseif( empty( $array_data['answer_question'] ) ) { $error = $lang_module['answer_empty']; } elseif( empty( $error )) { $password = $crypt->hash_password( $array_data['nv_password'], $global_config['hashprefix'] ); define( 'NV_CONFIG_GLOBALTABLE', $db_config['prefix'] . '_config' ); $userid = 1; $db->query( 'TRUNCATE TABLE ' . $db_config['prefix'] . '_users' ); $db->query( 'TRUNCATE TABLE ' . $db_config['prefix'] . '_authors' ); $sth = $db->prepare( "INSERT INTO " . $db_config['prefix'] . "_users (userid, username, md5username, password, email, first_name, last_name, gender, photo, birthday, sig, regdate, question, answer, passlostkey, view_mail, remember, in_groups, active, checknum, last_login, last_ip, last_agent, last_openid, idsite) VALUES(" . $userid . ", :username, :md5username, :password, :email, :first_name, '', '', '', 0, '', " . NV_CURRENTTIME . ", :question, :answer_question, '', 0, 1, '', 1, '', " . NV_CURRENTTIME . ", '', '', '', 0)" ); $sth->bindParam( ':username', $array_data['nv_login'], PDO::PARAM_STR ); $sth->bindValue( ':md5username', nv_md5safe( $array_data['nv_login'] ), PDO::PARAM_STR ); $sth->bindParam( ':password', $password, PDO::PARAM_STR ); $sth->bindParam( ':email', $array_data['nv_email'], PDO::PARAM_STR ); $sth->bindParam( ':first_name', $array_data['nv_login'], PDO::PARAM_STR ); $sth->bindParam( ':question', $array_data['question'], PDO::PARAM_STR ); $sth->bindParam( ':answer_question', $array_data['answer_question'], PDO::PARAM_STR ); $ok1 = $sth->execute(); $ok2 = $db->exec( "INSERT INTO " . $db_config['prefix'] . "_authors (admin_id, editor, lev, files_level, position, addtime, edittime, is_suspend, susp_reason, check_num, last_login, last_ip, last_agent) VALUES(" . $userid . ", 'ckeditor', 1, 'adobe,application,archives,audio,documents,flash,images,real,video|1|1|1', 'Administrator', 0, 0, 0, '', '', 0, '', '')" ); if( $ok1 and $ok2 ) { try { $db->query( 'INSERT INTO ' . $db_config['prefix'] . '_users_info (userid) VALUES (' . $userid . ')' ); $db->query( "INSERT INTO " . $db_config['prefix'] . "_groups_users (group_id, userid, data) VALUES(1, " . $userid . ", '0')" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'site', 'statistics_timezone', " . $db->quote( NV_SITE_TIMEZONE_NAME ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'site', 'site_email', " . $db->quote( $global_config['site_email'] ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'error_set_logs', " . $db->quote( $global_config['error_set_logs'] ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'error_send_email', " . $db->quote( $global_config['site_email'] ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'site_lang', '" . NV_LANG_DATA . "')" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'my_domains', " . $db->quote( NV_SERVER_NAME ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'cookie_prefix', " . $db->quote( $global_config['cookie_prefix'] ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'session_prefix', " . $db->quote( $global_config['session_prefix'] ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'site_timezone', " . $db->quote( $global_config['site_timezone'] ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'proxy_blocker', " . $db->quote( $global_config['proxy_blocker'] ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'str_referer_blocker', " . $db->quote( $global_config['str_referer_blocker'] ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'lang_multi', " . $db->quote( $global_config['lang_multi'] ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'lang_geo', " . $db->quote( $global_config['lang_geo'] ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'ftp_server', " . $db->quote( $global_config['ftp_server'] ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'ftp_port', " . $db->quote( $global_config['ftp_port'] ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'ftp_user_name', " . $db->quote( $global_config['ftp_user_name'] ) . ")" ); $ftp_user_pass = nv_base64_encode( $crypt->aes_encrypt( $global_config['ftp_user_pass'] ) ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'ftp_user_pass', " . $db->quote( $ftp_user_pass ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'ftp_path', " . $db->quote( $global_config['ftp_path'] ) . ")" ); $db->query( "INSERT INTO " . NV_CONFIG_GLOBALTABLE . " (lang, module, config_name, config_value) VALUES ('sys', 'global', 'ftp_check_login', " . $db->quote( $global_config['ftp_check_login'] ) . ")" ); $db->query( "UPDATE " . NV_CONFIG_GLOBALTABLE . " SET config_value = " . $db->quote( $array_data['site_name'] ) . " WHERE module = 'global' AND config_name = 'site_name'" ); $result = $db->query( "SELECT * FROM " . $db_config['prefix'] . "_authors_module ORDER BY weight ASC" ); while( $row = $result->fetch() ) { $checksum = md5( $row['module'] . "#" . $row['act_1'] . "#" . $row['act_2'] . "#" . $row['act_3'] . "#" . $global_config['sitekey'] ); $db->query( "UPDATE " . $db_config['prefix'] . "_authors_module SET checksum = '" . $checksum . "' WHERE mid = " . $row['mid'] ); } if( ! ( nv_function_exists( 'finfo_open' ) or nv_class_exists( 'finfo', false ) or nv_function_exists( 'mime_content_type' ) or ( substr( $sys_info['os'], 0, 3 ) != 'WIN' and ( nv_function_exists( 'system' ) or nv_function_exists( 'exec' ) ) ) ) ) { $db->query( "UPDATE " . NV_CONFIG_GLOBALTABLE . " SET config_value = 'mild' WHERE lang='sys' AND module = 'global' AND config_name = 'upload_checking_mode'" ); } if( empty( $array_data['lang_multi'] ) ) { $global_config['rewrite_optional'] = 1; $global_config['lang_multi'] = 0; $db->query( "UPDATE " . NV_CONFIG_GLOBALTABLE . " SET config_value = '0' WHERE lang='sys' AND module = 'global' AND config_name = 'lang_multi'" ); $db->query( "UPDATE " . NV_CONFIG_GLOBALTABLE . " SET config_value = '1' WHERE lang='sys' AND module = 'global' AND config_name = 'rewrite_optional'" ); $result = $db->query( "SELECT COUNT(*) FROM " . $db_config['prefix'] . "_" . NV_LANG_DATA . "_modules where title='news'" ); if( $result->fetchColumn() ) { $global_config['rewrite_op_mod'] = 'news'; $db->query( "UPDATE " . NV_CONFIG_GLOBALTABLE . " SET config_value = 'news' WHERE lang='sys' AND module = 'global' AND config_name = 'rewrite_op_mod'" ); } } } catch( PDOException $e ) { trigger_error( $e->getMessage() ); die( $e->getMessage() ); } nv_save_file_config(); $array_config_rewrite = array( 'rewrite_optional' => $global_config['rewrite_optional'], 'rewrite_endurl' => $global_config['rewrite_endurl'], 'rewrite_exturl' => $global_config['rewrite_exturl'], 'rewrite_op_mod' => $global_config['rewrite_op_mod'], 'ssl_https' => 0 ); $rewrite = nv_rewrite_change( $array_config_rewrite ); if( empty( $rewrite[0] ) ) { $error .= sprintf( $lang_module['file_not_writable'], $rewrite[1] ); } elseif( nv_save_file_config_global() ) { ++ $step; $nv_Request->set_Session( 'maxstep', $step ); nv_save_file_config(); @rename( NV_ROOTDIR . '/' . $file_config_temp, NV_ROOTDIR . '/' . NV_TEMP_DIR . '/' . NV_CONFIG_FILENAME ); if( is_writable( NV_ROOTDIR . '/robots.txt' ) ) { $contents = file_get_contents( NV_ROOTDIR . '/robots.txt' ); $check_rewrite_file = nv_check_rewrite_file(); if( $check_rewrite_file ) { $content_sitemap = 'Sitemap: ' . NV_MY_DOMAIN . NV_BASE_SITEURL . 'sitemap.xml'; } else { $content_sitemap = 'Sitemap: ' . NV_MY_DOMAIN . NV_BASE_SITEURL . 'index.php/SitemapIndex' . $global_config['rewrite_endurl']; } $contents = str_replace( 'Sitemap: http://yousite.com/?nv=SitemapIndex', $content_sitemap, $contents ); file_put_contents( NV_ROOTDIR . '/robots.txt', $contents, LOCK_EX ); } define( 'NV_IS_MODADMIN', true ); $module_name = 'upload'; $lang_global['mod_upload'] = 'upload'; $global_config['upload_logo'] = ''; define( 'NV_UPLOAD_GLOBALTABLE', $db_config['prefix'] . '_upload' ); define( 'SYSTEM_UPLOADS_DIR', NV_UPLOADS_DIR ); require_once NV_ROOTDIR . '/' . NV_ADMINDIR . '/upload/functions.php'; $real_dirlist = array(); foreach( $allow_upload_dir as $dir ) { $real_dirlist = nv_listUploadDir( $dir, $real_dirlist ); } foreach( $real_dirlist as $dirname ) { try { $array_dirname[$dirname] = $db->insert_id( "INSERT INTO " . NV_UPLOAD_GLOBALTABLE . "_dir (dirname, time, thumb_type, thumb_width, thumb_height, thumb_quality) VALUES ('" . $dirname . "', '0', '0', '0', '0', '0')", "did" ); } catch (PDOException $e) { trigger_error( $e->getMessage() ); } } // Data Counter $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('c_time', 'start', 0, 0, 0)" ); $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('c_time', 'last', 0, 0, 0)" ); $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('total', 'hits', 0, 0, 0)" ); $year = date( 'Y' );; for( $i=0; $i < 9; $i++ ) { $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('year', '" . $year . "', 0, 0, 0)" ); ++$year; } $ar_tmp = explode(',', 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'); foreach( $ar_tmp as $month ) { $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('month', '" . $month . "', 0, 0, 0)" ); } for( $i=1; $i < 32; $i++ ) { $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('day', '" . str_pad( $i, 2, '0', STR_PAD_LEFT ) . "', 0, 0, 0)" ); } $ar_tmp = explode(',', 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'); foreach( $ar_tmp as $dayofweek ) { $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('dayofweek', '" . $dayofweek . "', 0, 0, 0)" ); } for( $i=0; $i < 24; $i++ ) { $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('hour', '" . str_pad( $i, 2, '0', STR_PAD_LEFT ) . "', 0, 0, 0)" ); } $bots = array('googlebot', 'msnbot', 'bingbot', 'yahooslurp', 'w3cvalidator'); foreach( $bots as $_bot ) { $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('bot', " . $db->quote( $_bot ) . ", 0, 0, 0)" ); } $tmp_array = array('opera','operamini','webtv','explorer','edge','pocket','konqueror','icab','omniweb','firebird','firefox','iceweasel','shiretoko','mozilla','amaya','lynx','safari','iphone','ipod','ipad','chrome','android','googlebot','yahooslurp','w3cvalidator','blackberry','icecat','nokias60','nokia','msn','msnbot','bingbot','netscape','galeon','netpositive','phoenix'); foreach( $tmp_array as $_browser ) { $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('browser', " . $db->quote( $_browser ) . ", 0, 0, 0)" ); } $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('browser', 'Mobile', 0, 0, 0)" ); $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('browser', 'bots', 0, 0, 0)" ); $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('browser', 'Unknown', 0, 0, 0)" ); $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('browser', 'Unspecified', 0, 0, 0)" ); $tmp_array = array('unknown', 'win', 'win10', 'win8', 'win7', 'win2003', 'winvista', 'wince', 'winxp', 'win2000', 'apple', 'linux', 'os2', 'beos', 'iphone', 'ipod', 'ipad', 'blackberry', 'nokia', 'freebsd', 'openbsd', 'netbsd', 'sunos', 'opensolaris', 'android', 'irix', 'palm'); foreach( $tmp_array as $_os ) { $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('os', " . $db->quote( $_os ) . ", 0, 0, 0)" ); } $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('os', 'Unspecified', 0, 0, 0)" ); foreach( $countries as $_country => $v ) { $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('country', " . $db->quote( $_country ) . ", 0, 0, 0)" ); } $db->query( "INSERT INTO " . $db_config['prefix'] . "_counter VALUES ('country', 'unkown', 0, 0, 0)" ); Header( 'Location: ' . NV_BASE_SITEURL . 'install/index.php?' . NV_LANG_VARIABLE . '=' . NV_LANG_DATA . '&step=' . $step ); exit(); } else { $error = sprintf( $lang_module['file_not_writable'], NV_DATADIR . '/config_global.php' ); } } else { $error = 'Error add Administrator'; } } } $array_data['error'] = $error; $title = $lang_module['website_info']; $contents = nv_step_6( $array_data, $nextstep ); } elseif( $step == 7 ) { $finish = 0; if( file_exists( NV_ROOTDIR . '/' . NV_TEMP_DIR . '/' . NV_CONFIG_FILENAME ) ) { $ftp_check_login = 0; $ftp_server_array = array( 'ftp_check_login' => 0 ); if( $nv_Request->isset_request( 'ftp_server_array', 'session' ) ) { $ftp_server_array = $nv_Request->get_string( 'ftp_server_array', 'session' ); $ftp_server_array = unserialize( $ftp_server_array ); } if( isset( $ftp_server_array['ftp_check_login'] ) and intval( $ftp_server_array['ftp_check_login'] ) == 1 ) { // Set up basic connection $conn_id = ftp_connect( $ftp_server_array['ftp_server'], $ftp_server_array['ftp_port'], 10 ); // Login with username and password $login_result = ftp_login( $conn_id, $ftp_server_array['ftp_user_name'], $ftp_server_array['ftp_user_pass'] ); if( ( ! $conn_id ) || ( ! $login_result ) ) { $ftp_check_login = 3; } elseif( ftp_chdir( $conn_id, $ftp_server_array['ftp_path'] ) ) { $ftp_check_login = 1; } } if( $ftp_check_login == 1 ) { ftp_rename( $conn_id, NV_TEMP_DIR . '/' . NV_CONFIG_FILENAME, NV_CONFIG_FILENAME ); nv_chmod_dir( $conn_id, NV_UPLOADS_DIR, true ); ftp_chmod( $conn_id, 0644, NV_CONFIG_FILENAME ); ftp_close( $conn_id ); } else { @rename( NV_ROOTDIR . '/' . NV_TEMP_DIR . '/' . NV_CONFIG_FILENAME, NV_ROOTDIR . '/' . NV_CONFIG_FILENAME ); } } if( file_exists( NV_ROOTDIR . '/' . NV_CONFIG_FILENAME ) ) { $finish = 1; } else { $finish = 2; } $title = $lang_module['done']; $contents = nv_step_7( $finish ); } echo nv_site_theme( $step, $title, $contents ); function nv_save_file_config() { global $nv_Request, $file_config_temp, $db_config, $global_config, $step; if( is_writable( NV_ROOTDIR . '/' . $file_config_temp ) or is_writable( NV_ROOTDIR . '/' . NV_TEMP_DIR ) ) { $global_config['cookie_prefix'] = ( empty( $global_config['cookie_prefix'] ) or $global_config['cookie_prefix'] == 'nv4' ) ? 'nv4c_' . nv_genpass( 5 ) : $global_config['cookie_prefix']; $global_config['session_prefix'] = ( empty( $global_config['session_prefix'] ) or $global_config['session_prefix'] == 'nv4' ) ? 'nv4s_' . nv_genpass( 6 ) : $global_config['session_prefix']; $global_config['site_email'] = ( ! isset( $global_config['site_email'] ) ) ? '' : $global_config['site_email']; $db_config['dbhost'] = ( ! isset( $db_config['dbhost'] ) ) ? 'localhost' : $db_config['dbhost']; $db_config['dbport'] = ( ! isset( $db_config['dbport'] ) ) ? '' : $db_config['dbport']; $db_config['dbname'] = ( ! isset( $db_config['dbname'] ) ) ? '' : $db_config['dbname']; $db_config['dbuname'] = ( ! isset( $db_config['dbuname'] ) ) ? '' : $db_config['dbuname']; $db_config['dbsystem'] = ( isset( $db_config['dbsystem'] ) ) ? $db_config['dbsystem'] : $db_config['dbuname']; $db_config['dbpass'] = ( ! isset( $db_config['dbpass'] ) ) ? '' : $db_config['dbpass']; $db_config['prefix'] = ( ! isset( $db_config['prefix'] ) ) ? 'nv4' : $db_config['prefix']; $persistent = ( $db_config['persistent'] ) ? 'true' : 'false'; $content = ''; $content .= "<?php\n\n"; $content .= NV_FILEHEAD . "\n\n"; $content .= "if ( ! defined( 'NV_MAINFILE' ) )\n"; $content .= "{\n"; $content .= "\tdie( 'Stop!!!' );\n"; $content .= "}\n\n"; $content .= "\$db_config['dbhost'] = '" . $db_config['dbhost'] . "';\n"; $content .= "\$db_config['dbport'] = '" . $db_config['dbport'] . "';\n"; $content .= "\$db_config['dbname'] = '" . $db_config['dbname'] . "';\n"; $content .= "\$db_config['dbsystem'] = '" . $db_config['dbsystem'] . "';\n"; $content .= "\$db_config['dbuname'] = '" . $db_config['dbuname'] . "';\n"; $content .= "\$db_config['dbpass'] = '" . $db_config['dbpass'] . "';\n"; $content .= "\$db_config['dbtype'] = '" . $db_config['dbtype'] . "';\n"; $content .= "\$db_config['collation'] = '" . $db_config['collation'] . "';\n"; $content .= "\$db_config['persistent'] = " . $persistent . ";\n"; $content .= "\$db_config['prefix'] = '" . $db_config['prefix'] . "';\n"; $content .= "\n"; $content .= "\$global_config['idsite'] = 0;\n"; $content .= "\$global_config['sitekey'] = '" . $global_config['sitekey'] . "';// Do not change sitekey!\n"; $content .= "\$global_config['hashprefix'] = '" . $global_config['hashprefix'] . "';\n"; if( $step < 7 ) { $content .= "\$global_config['cookie_prefix'] = '" . $global_config['cookie_prefix'] . "';\n"; $content .= "\$global_config['session_prefix'] = '" . $global_config['session_prefix'] . "';\n"; $global_config['ftp_server'] = ( ! isset( $global_config['ftp_server'] ) ) ? "localhost" : $global_config['ftp_server']; $global_config['ftp_port'] = ( ! isset( $global_config['ftp_port'] ) ) ? 21 : $global_config['ftp_port']; $global_config['ftp_user_name'] = ( ! isset( $global_config['ftp_user_name'] ) ) ? "" : $global_config['ftp_user_name']; $global_config['ftp_user_pass'] = ( ! isset( $global_config['ftp_user_pass'] ) ) ? "" : $global_config['ftp_user_pass']; $global_config['ftp_path'] = ( ! isset( $global_config['ftp_path'] ) ) ? "" : $global_config['ftp_path']; $global_config['ftp_check_login'] = ( ! isset( $global_config['ftp_check_login'] ) ) ? 0 : $global_config['ftp_check_login']; if( $global_config['ftp_check_login'] ) { $ftp_server_array = array( "ftp_server" => $global_config['ftp_server'], "ftp_port" => $global_config['ftp_port'], "ftp_user_name" => $global_config['ftp_user_name'], "ftp_user_pass" => $global_config['ftp_user_pass'], "ftp_path" => $global_config['ftp_path'], "ftp_check_login" => $global_config['ftp_check_login'] ); $nv_Request->set_Session( 'ftp_server_array', serialize( $ftp_server_array ) ); } $content .= "\n"; $content .= "\$global_config['ftp_server'] = '" . $global_config['ftp_server'] . "';\n"; $content .= "\$global_config['ftp_port'] = '" . $global_config['ftp_port'] . "';\n"; $content .= "\$global_config['ftp_user_name'] = '" . $global_config['ftp_user_name'] . "';\n"; $content .= "\$global_config['ftp_user_pass'] = '" . $global_config['ftp_user_pass'] . "';\n"; $content .= "\$global_config['ftp_path'] = '" . $global_config['ftp_path'] . "';\n"; $content .= "\$global_config['ftp_check_login'] = '" . $global_config['ftp_check_login'] . "';\n"; } file_put_contents( NV_ROOTDIR . '/' . $file_config_temp, trim( $content ), LOCK_EX ); return true; } else { return false; } }
dounets/HomePage
install/index.php
PHP
gpl-2.0
47,683
// ext3grep -- An ext3 file system investigation and undelete tool // //! @file debug.cc //! @brief This file contains the definitions of debug related objects and functions. // // Copyright (C) 2008, by // // Carlo Wood, Run on IRC <carlo@alinoe.com> // RSA-1024 0x624ACAD5 1997-01-26 Sign & Encrypt // Fingerprint16 = 32 EC A7 B6 AC DB 65 A6 F6 F6 55 DD 1C DC FF 61 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef USE_PCH #include "sys.h" // Needed for platform-specific code #endif #ifdef CWDEBUG #ifndef USE_PCH #include <cctype> // Needed for std::isprint #include <iomanip> // Needed for setfill #include <map> #include <string> #include <sstream> #include <signal.h> #include "debug.h" #ifdef USE_LIBCW #include <libcw/memleak.h> // memleak_filter #endif #endif // USE_PCH namespace debug { namespace channels { // namespace DEBUGCHANNELS namespace dc { #ifndef DOXYGEN #define DDCN(x) (x) #endif // Add new debug channels here. //channel_ct custom DDCN("CUSTOM"); //!< This debug channel is used for ... } // namespace dc } // namespace DEBUGCHANNELS // Anonymous namespace, this map and its initialization functions are private to this file // for Thead-safeness reasons. namespace { /*! @brief The type of rcfile_dc_states. * @internal */ typedef std::map<std::string, bool> rcfile_dc_states_type; /*! @brief Map containing the default debug channel states used at the start of each new thread. * @internal * * The first thread calls main, which calls debug::init which will initialize this * map with all debug channel labels and whether or not they were turned on in the * rcfile or not. */ rcfile_dc_states_type rcfile_dc_states; /*! @brief Set the default state of debug channel \a dc_label. * @internal * * This function is called once for each debug channel. */ void set_state(char const* dc_label, bool is_on) { std::pair<rcfile_dc_states_type::iterator, bool> res = rcfile_dc_states.insert(rcfile_dc_states_type::value_type(std::string(dc_label), is_on)); if (!res.second) Dout(dc::warning, "Calling set_state() more than once for the same label!"); return; } /*! @brief Save debug channel states. * @internal * * One time initialization function of rcfile_dc_state. * This must be called from debug::init after reading the rcfile. */ void save_dc_states(void) { // We may only call this function once: it reflects the states as stored // in the rcfile and that won't change. Therefore it is not needed to // lock `rcfile_dc_states', it is only written to by the first thread // (once, via main -> init) when there are no other threads yet. static bool second_time = false; if (second_time) { Dout(dc::warning, "Calling save_dc_states() more than once!"); return; } second_time = true; ForAllDebugChannels( set_state(debugChannel.get_label(), debugChannel.is_on()) ); } } // anonymous namespace /*! @brief Returns the the original state of a debug channel. * @internal * * For a given \a dc_label, which must be the exact name (<tt>channel_ct::get_label</tt>) of an * existing debug channel, this function returns \c true when the corresponding debug channel was * <em>on</em> at the startup of the application, directly after reading the libcwd runtime * configuration file (.libcwdrc). * * If the label/channel did not exist at the start of the application, it will return \c false * (note that libcwd disallows adding debug channels to modules - so this would probably * a bug). */ bool is_on_in_rcfile(char const* dc_label) { rcfile_dc_states_type::const_iterator iter = rcfile_dc_states.find(std::string(dc_label)); if (iter == rcfile_dc_states.end()) { Dout(dc::warning, "is_on_in_rcfile(\"" << dc_label << "\"): \"" << dc_label << "\" is an unknown label!"); return false; } return iter->second; } /*! @brief Initialize debugging code from new threads. * * This function needs to be called at the start of each new thread, * because a new thread starts in a completely reset state. * * The function turns on all debug channels that were turned on * after reading the rcfile at the start of the application. * Furthermore it initializes the debug ostream, its mutex and the * margin of the default debug object (Dout). */ void init_thread(void) { // Turn on all debug channels that are turned on as per rcfile configuration. ForAllDebugChannels( if (!debugChannel.is_on() && is_on_in_rcfile(debugChannel.get_label())) debugChannel.on(); ); // Turn on debug output. Debug( libcw_do.on() ); #if LIBCWD_THREAD_SAFE Debug( libcw_do.set_ostream(&std::cout, &cout_mutex) ); #else Debug( libcw_do.set_ostream(&std::cout) ); #endif static bool first_thread = true; if (!first_thread) // So far, the application has only one thread. So don't add a thread id. { // Set the thread id in the margin. char margin[12]; sprintf(margin, "%-10lu ", pthread_self()); Debug( libcw_do.margin().assign(margin, 11) ); } } /*! @brief Initialize debugging code from main. * * This function initializes the debug code. */ void init(void) { #if CWDEBUG_ALLOC && defined(USE_LIBCW) // Tell the memory leak detector which parts of the code are // expected to leak so that we won't get an alarm for those. { std::vector<std::pair<std::string, std::string> > hide_list; hide_list.push_back(std::pair<std::string, std::string>("libdl.so.2", "_dlerror_run")); hide_list.push_back(std::pair<std::string, std::string>("libstdc++.so.6", "__cxa_get_globals")); // The following is actually necessary because of a bug in glibc // (see http://sources.redhat.com/bugzilla/show_bug.cgi?id=311). hide_list.push_back(std::pair<std::string, std::string>("libc.so.6", "dl_open_worker")); memleak_filter().hide_functions_matching(hide_list); } { std::vector<std::string> hide_list; // Also because of http://sources.redhat.com/bugzilla/show_bug.cgi?id=311 hide_list.push_back(std::string("ld-linux.so.2")); memleak_filter().hide_objectfiles_matching(hide_list); } memleak_filter().set_flags(libcwd::show_objectfile|libcwd::show_function); #endif // The following call allocated the filebuf's of cin, cout, cerr, wcin, wcout and wcerr. // Because this causes a memory leak being reported, make them invisible. Debug(set_invisible_on()); // You want this, unless you mix streams output with C output. // Read http://gcc.gnu.org/onlinedocs/libstdc++/27_io/howto.html#8 for an explanation. //std::ios::sync_with_stdio(false); // Cancel previous call to set_invisible_on. Debug(set_invisible_off()); // This will warn you when you are using header files that do not belong to the // shared libcwd object that you linked with. Debug( check_configuration() ); Debug( libcw_do.on(); // Show which rcfile we are reading! ForAllDebugChannels( while (debugChannel.is_on()) debugChannel.off() // Print as little as possible though. ); read_rcfile(); // Put 'silent = on' in the rcfile to suppress most of the output here. libcw_do.off() ); save_dc_states(); init_thread(); } #if CWDEBUG_LOCATION /*! @brief Return call location. * * @param return_addr The return address of the call. */ std::string call_location(void const* return_addr) { libcwd::location_ct loc((char*)return_addr + libcwd::builtin_return_address_offset); std::ostringstream convert; convert << loc; return convert.str(); } #endif } // namespace debug #endif // CWDEBUG //----------------------------------------------------------------------------- // // Debug stuff #include "debug.h" // Define our own assert. #ifdef DEBUG #include <iostream> #include "backtrace.h" #include <signal.h> void assert_fail(char const* expr, char const* file, int line, char const* function) { std::cout << file << ':' << line << ": " << function << ": Assertion `" << expr << "' failed." << std::endl; std::cout << "Backtrace:\n"; dump_backtrace_on(std::cout); raise(6); } #endif #if EXTERNAL_BLOCK #if 0 // Ian Jacobi's '\\' file. uint32_t someones_inode_count = std::numeric_limits<uint32_t>::max(); unsigned char someones_block[SOMEONES_BLOCK_SIZE] = { 0x21, 0x47, 0xf1, 0x00, 0x0c, 0x00, 0x01, 0x02, 0x2e, 0x00, 0x00, 0x00, 0x20, 0x47, 0xf1, 0x00, 0x0c, 0x00, 0x02, 0x02, 0x2e, 0x2e, 0x00, 0x00, 0x22, 0x47, 0xf1, 0x00, 0xe8, 0x0f, 0x01, 0x02, 0x5c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0 }; #else // siegelring -- directory, not detected as directory. uint32_t someones_inode_count = 1465920; unsigned char someones_block[SOMEONES_BLOCK_SIZE] = { 0x34, 0xba, 0x08, 0x00, 0x0c, 0x00, 0x01, 0x02, 0x2e, 0x00, 0x00, 0x00, 0x2d, 0xba, 0x08, 0x00, 0x0c, 0x00, 0x02, 0x02, 0x2e, 0x2e, 0x00, 0x00, 0x35, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0d, 0x01, 0x56, 0x65, 0x72, 0x73, 0x75, 0x63, 0x68, 0x30, 0x2e, 0x66, 0x6f, 0x72, 0x6d, 0x00, 0x00, 0x00, 0x36, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0d, 0x01, 0x56, 0x65, 0x72, 0x73, 0x75, 0x63, 0x68, 0x30, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x00, 0x00, 0x00, 0x37, 0xba, 0x08, 0x00, 0x24, 0x00, 0x1b, 0x01, 0x46, 0x61, 0x68, 0x72, 0x74, 0x65, 0x6e, 0x62, 0x75, 0x63, 0x68, 0x2d, 0x61, 0x75, 0x66, 0x72, 0x75, 0x66, 0x2d, 0x6a, 0x61, 0x76, 0x61, 0x2e, 0x74, 0x78, 0x74, 0x00, 0x38, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x46, 0x62, 0x31, 0x24, 0x34, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x39, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0f, 0x01, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x44, 0x65, 0x6d, 0x6f, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x3a, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0e, 0x01, 0x56, 0x65, 0x72, 0x73, 0x75, 0x63, 0x68, 0x30, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x3b, 0xba, 0x08, 0x00, 0x10, 0x00, 0x08, 0x01, 0x2e, 0x6e, 0x62, 0x61, 0x74, 0x74, 0x72, 0x73, 0x3c, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0e, 0x01, 0x4a, 0x61, 0x72, 0x4d, 0x61, 0x6b, 0x65, 0x72, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x3d, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x14, 0x01, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x43, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x54, 0x65, 0x73, 0x74, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x3e, 0xba, 0x08, 0x00, 0x14, 0x00, 0x09, 0x01, 0x46, 0x62, 0x31, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x00, 0x3f, 0xba, 0x08, 0x00, 0x10, 0x00, 0x08, 0x01, 0x46, 0x62, 0x31, 0x2e, 0x66, 0x6f, 0x72, 0x6d, 0x40, 0xba, 0x08, 0x00, 0x10, 0x00, 0x08, 0x01, 0x46, 0x62, 0x31, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x41, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x46, 0x62, 0x31, 0x24, 0x35, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x42, 0xba, 0x08, 0x00, 0x10, 0x00, 0x08, 0x01, 0x46, 0x62, 0x33, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x43, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0e, 0x01, 0x66, 0x62, 0x5f, 0x4f, 0x6b, 0x74, 0x6f, 0x62, 0x65, 0x72, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x00, 0x44, 0xba, 0x08, 0x00, 0x24, 0x00, 0x1a, 0x01, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x24, 0x4d, 0x79, 0x42, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x45, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x12, 0x01, 0x4a, 0x4d, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x4c, 0x6f, 0x61, 0x64, 0x65, 0x72, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x00, 0x00, 0x46, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x46, 0x62, 0x31, 0x24, 0x36, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x47, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0e, 0x01, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x44, 0x65, 0x6d, 0x6f, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x00, 0x00, 0x48, 0xba, 0x08, 0x00, 0x20, 0x00, 0x16, 0x01, 0x46, 0x62, 0x31, 0x24, 0x4d, 0x79, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x4d, 0x6f, 0x64, 0x65, 0x6c, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x49, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0d, 0x01, 0x66, 0x62, 0x5f, 0x41, 0x75, 0x67, 0x75, 0x73, 0x74, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x00, 0x00, 0x4a, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0f, 0x01, 0x66, 0x62, 0x5f, 0x4e, 0x6f, 0x76, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x4b, 0xba, 0x08, 0x00, 0x14, 0x00, 0x09, 0x01, 0x46, 0x62, 0x33, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x00, 0x4c, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x13, 0x01, 0x42, 0x72, 0x6f, 0x77, 0x73, 0x65, 0x72, 0x4d, 0x61, 0x69, 0x6e, 0x54, 0x61, 0x62, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x00, 0x4d, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x13, 0x01, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x24, 0x31, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x4e, 0xba, 0x08, 0x00, 0x14, 0x00, 0x09, 0x01, 0x55, 0x74, 0x69, 0x6c, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x00, 0x00, 0x00, 0x4f, 0xba, 0x08, 0x00, 0x18, 0x00, 0x10, 0x01, 0x56, 0x65, 0x72, 0x73, 0x75, 0x63, 0x68, 0x30, 0x24, 0x31, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x50, 0xba, 0x08, 0x00, 0x18, 0x00, 0x10, 0x01, 0x66, 0x62, 0x5f, 0x53, 0x65, 0x70, 0x74, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x2e, 0x64, 0x61, 0x74, 0x51, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0d, 0x01, 0x66, 0x6f, 0x6e, 0x74, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x66, 0x6f, 0x72, 0x6d, 0x00, 0x00, 0x00, 0x52, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0d, 0x01, 0x66, 0x6f, 0x6e, 0x74, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x00, 0x00, 0x00, 0x53, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x11, 0x01, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x00, 0x54, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x4d, 0x41, 0x4e, 0x49, 0x46, 0x45, 0x53, 0x54, 0x2e, 0x4d, 0x46, 0x00, 0x55, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x46, 0x62, 0x31, 0x24, 0x31, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x56, 0xba, 0x08, 0x00, 0x24, 0x00, 0x1c, 0x01, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x44, 0x65, 0x6d, 0x6f, 0x24, 0x4d, 0x79, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x4d, 0x6f, 0x64, 0x65, 0x6c, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x57, 0xba, 0x08, 0x00, 0x20, 0x00, 0x15, 0x01, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x43, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x54, 0x65, 0x73, 0x74, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x00, 0x58, 0xba, 0x08, 0x00, 0x18, 0x00, 0x10, 0x01, 0x56, 0x65, 0x72, 0x73, 0x75, 0x63, 0x68, 0x30, 0x24, 0x32, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x59, 0xba, 0x08, 0x00, 0x18, 0x00, 0x10, 0x01, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x5a, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0d, 0x01, 0x4a, 0x61, 0x72, 0x4d, 0x61, 0x6b, 0x65, 0x72, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x00, 0x00, 0x00, 0x5b, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0c, 0x01, 0x66, 0x62, 0x5f, 0x41, 0x70, 0x72, 0x69, 0x6c, 0x2e, 0x64, 0x61, 0x74, 0x5c, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0f, 0x01, 0x66, 0x61, 0x68, 0x72, 0x74, 0x65, 0x6e, 0x62, 0x75, 0x63, 0x68, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x5d, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0c, 0x01, 0x66, 0x62, 0x5f, 0x4d, 0x61, 0x65, 0x72, 0x7a, 0x2e, 0x64, 0x61, 0x74, 0x5e, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x46, 0x62, 0x31, 0x24, 0x32, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x5f, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x11, 0x01, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x44, 0x65, 0x6d, 0x6f, 0x24, 0x31, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x00, 0x60, 0xba, 0x08, 0x00, 0x18, 0x00, 0x10, 0x01, 0x56, 0x65, 0x72, 0x73, 0x75, 0x63, 0x68, 0x30, 0x24, 0x33, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x61, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0c, 0x01, 0x46, 0x62, 0x50, 0x72, 0x69, 0x6e, 0x74, 0x2e, 0x6a, 0x61, 0x76, 0x61, 0x62, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x13, 0x01, 0x4a, 0x4d, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x4c, 0x6f, 0x61, 0x64, 0x65, 0x72, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x63, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x13, 0x01, 0x66, 0x62, 0x5f, 0x46, 0x65, 0x62, 0x72, 0x75, 0x61, 0x72, 0x5f, 0x32, 0x30, 0x30, 0x34, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x64, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x13, 0x01, 0x66, 0x62, 0x5f, 0x46, 0x65, 0x62, 0x72, 0x75, 0x61, 0x72, 0x5f, 0x32, 0x30, 0x30, 0x35, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x65, 0xba, 0x08, 0x00, 0x1c, 0x00, 0x12, 0x01, 0x66, 0x62, 0x5f, 0x4a, 0x61, 0x6e, 0x75, 0x61, 0x72, 0x5f, 0x32, 0x30, 0x30, 0x34, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x00, 0x66, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0a, 0x01, 0x55, 0x74, 0x69, 0x6c, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x00, 0x67, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x66, 0x62, 0x5f, 0x4a, 0x75, 0x6c, 0x69, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x68, 0xba, 0x08, 0x00, 0x18, 0x00, 0x0f, 0x01, 0x66, 0x62, 0x5f, 0x44, 0x65, 0x7a, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x69, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x46, 0x62, 0x31, 0x24, 0x33, 0x2e, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x00, 0x6a, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0b, 0x01, 0x66, 0x62, 0x5f, 0x4a, 0x75, 0x6e, 0x69, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x6b, 0xba, 0x08, 0x00, 0x14, 0x00, 0x0a, 0x01, 0x66, 0x62, 0x5f, 0x4d, 0x61, 0x69, 0x2e, 0x64, 0x61, 0x74, 0x00, 0x00, 0x6c, 0xba, 0x08, 0x00, 0xc8, 0x0a, 0x01, 0x01, 0x9b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0 }; #endif #else // !EXTERNAL_BLOCK // Not used, except in compiler check. uint32_t someones_inode_count; unsigned char someones_block[SOMEONES_BLOCK_SIZE]; #endif // !EXTERNAL_BLOCK
gcode-mirror/ext3grep
src/debug.cc
C++
gpl-2.0
18,296
/* * Copyright (c) 2007, 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 6601652 * @summary Test exception when SortedMap or SortedSet has non-null Comparator * @author Eamonn McManus * @modules java.management */ import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; public class ComparatorExceptionTest { public static interface TestMXBean { public SortedSet<String> getSortedSet(); public SortedMap<String, String> getSortedMap(); } public static class TestImpl implements TestMXBean { public SortedSet<String> getSortedSet() { return new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); } public SortedMap<String, String> getSortedMap() { return new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); } } private static String failure; private static void fail(String why) { failure = "FAILED: " + why; System.out.println(failure); } public static void main(String[] args) throws Exception { MBeanServer mbs = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("a:b=c"); mbs.registerMBean(new TestImpl(), name); for (String attr : new String[] {"SortedSet", "SortedMap"}) { try { Object value = mbs.getAttribute(name, attr); fail("get " + attr + " did not throw exception"); } catch (Exception e) { Throwable t = e; while (!(t instanceof IllegalArgumentException)) { if (t == null) break; t = t.getCause(); } if (t != null) System.out.println("Correct exception for " + attr); else { fail("get " + attr + " got wrong exception"); e.printStackTrace(System.out); } } } if (failure != null) throw new Exception(failure); } }
FauxFaux/jdk9-jdk
test/javax/management/mxbean/ComparatorExceptionTest.java
Java
gpl-2.0
3,210
<?php /* ** Zabbix ** Copyright (C) 2000-2011 Zabbix SIA ** ** 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. **/ ?> <?php require_once dirname(__FILE__).'/include/config.inc.php'; require_once dirname(__FILE__).'/include/hosts.inc.php'; require_once dirname(__FILE__).'/include/maintenances.inc.php'; require_once dirname(__FILE__).'/include/forms.inc.php'; $page['title'] = _('Configuration of maintenance'); $page['file'] = 'maintenance.php'; $page['hist_arg'] = array('groupid', 'hostid'); $page['scripts'] = array('class.calendar.js'); require_once dirname(__FILE__).'/include/page_header.php'; // VAR TYPE OPTIONAL FLAGS VALIDATION EXCEPTION $fields = array( 'hosts' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'groups' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'hostids' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'groupids' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'hostid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'groupid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), // maintenance 'maintenanceid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, 'isset({form})&&({form}=="update")'), 'maintenanceids' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'mname' => array(T_ZBX_STR, O_OPT, null, NOT_EMPTY, 'isset({save})'), 'maintenance_type' => array(T_ZBX_INT, O_OPT, null, null, 'isset({save})'), 'description' => array(T_ZBX_STR, O_OPT, null, null, 'isset({save})'), 'active_since' => array(T_ZBX_STR, O_OPT, null, NOT_EMPTY, 'isset({save})'), 'active_till' => array(T_ZBX_STR, O_OPT, null, NOT_EMPTY, 'isset({save})'), 'new_timeperiod' => array(T_ZBX_STR, O_OPT, null, null, 'isset({add_timeperiod})'), 'timeperiods' => array(T_ZBX_STR, O_OPT, null, null, null), 'g_timeperiodid' => array(null, O_OPT, null, null, null), 'edit_timeperiodid' => array(null, O_OPT, P_ACT, DB_ID, null), 'twb_groupid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), // actions 'go' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'add_timeperiod' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'del_timeperiod' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'cancel_new_timeperiod' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'save' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'clone' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'delete' => array(T_ZBX_STR, O_OPT, P_SYS|P_ACT, null, null), 'cancel' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), // form 'form' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), 'form_refresh' => array(T_ZBX_STR, O_OPT, null, null, null) ); check_fields($fields); validate_sort_and_sortorder('name', ZBX_SORT_UP); $_REQUEST['go'] = get_request('go', 'none'); // permissions if (get_request('groupid', 0) > 0) { $groupids = available_groups($_REQUEST['groupid'], 1); if (empty($groupids)) { access_deny(); } } if (get_request('hostid', 0) > 0) { $hostids = available_hosts($_REQUEST['hostid'], 1); if (empty($hostids)) { access_deny(); } } /* * Actions */ if (isset($_REQUEST['clone']) && isset($_REQUEST['maintenanceid'])) { unset($_REQUEST['maintenanceid']); $_REQUEST['form'] = 'clone'; } elseif (isset($_REQUEST['cancel_new_timeperiod'])) { unset($_REQUEST['new_timeperiod']); } elseif (isset($_REQUEST['save'])) { if (!count(get_accessible_nodes_by_user($USER_DETAILS, PERM_READ_WRITE, PERM_RES_IDS_ARRAY))) { access_deny(); } if (isset($_REQUEST['maintenanceid'])) { $msg1 = _('Maintenance updated'); $msg2 = _('Cannot update maintenance'); } else { $msg1 = _('Maintenance added'); $msg2 = _('Cannot add maintenance'); } $active_since = zbxDateToTime(get_request('active_since', date('YmdHi'))); $active_till = zbxDateToTime(get_request('active_till')); $isValid = true; if (empty($active_since)) { error(_s('"%s" must be between 1970.01.01 and 2038.01.18', _('Active since'))); $isValid = false; } if (empty($active_till)) { error(_s('"%s" must be between 1970.01.01 and 2038.01.18', _('Active till'))); $isValid = false; } if ($isValid) { $maintenance = array( 'name' => $_REQUEST['mname'], 'maintenance_type' => $_REQUEST['maintenance_type'], 'description' => $_REQUEST['description'], 'active_since' => $active_since, 'active_till' => $active_till, 'timeperiods' => get_request('timeperiods', array()), 'hostids' => get_request('hostids', array()), 'groupids' => get_request('groupids', array()) ); if (isset($_REQUEST['maintenanceid'])) { $maintenance['maintenanceid'] = $_REQUEST['maintenanceid']; $result = API::Maintenance()->update($maintenance); } else { $result = API::Maintenance()->create($maintenance); } if ($result) { add_audit(!isset($_REQUEST['maintenanceid']) ? AUDIT_ACTION_ADD : AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_MAINTENANCE, _('Name').': '.$_REQUEST['mname']); unset($_REQUEST['form']); } show_messages($result, $msg1, $msg2); } else { show_error_message($msg2); } } elseif (isset($_REQUEST['delete']) || $_REQUEST['go'] == 'delete') { if (!count(get_accessible_nodes_by_user($USER_DETAILS, PERM_READ_WRITE, PERM_RES_IDS_ARRAY))) { access_deny(); } $maintenanceids = get_request('maintenanceid', array()); if (isset($_REQUEST['maintenanceids'])) { $maintenanceids = $_REQUEST['maintenanceids']; } zbx_value2array($maintenanceids); $maintenances = array(); foreach ($maintenanceids as $id => $maintenanceid) { $maintenances[$maintenanceid] = get_maintenance_by_maintenanceid($maintenanceid); } $go_result = API::Maintenance()->delete($maintenanceids); if ($go_result) { foreach ($maintenances as $maintenanceid => $maintenance) { add_audit(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_MAINTENANCE, 'Id ['.$maintenanceid.'] '._('Name').' ['.$maintenance['name'].']'); } unset($_REQUEST['form'], $_REQUEST['maintenanceid']); } show_messages($go_result, _('Maintenance deleted'), _('Cannot delete maintenance')); } elseif (isset($_REQUEST['add_timeperiod']) && isset($_REQUEST['new_timeperiod'])) { $new_timeperiod = $_REQUEST['new_timeperiod']; $new_timeperiod['start_date'] = zbxDateToTime($new_timeperiod['start_date']); // start time $new_timeperiod['start_time'] = ($new_timeperiod['hour'] * SEC_PER_HOUR) + ($new_timeperiod['minute'] * SEC_PER_MIN); // period $new_timeperiod['period'] = ($new_timeperiod['period_days'] * SEC_PER_DAY) + ($new_timeperiod['period_hours'] * SEC_PER_HOUR) + ($new_timeperiod['period_minutes'] * SEC_PER_MIN); // days of week if (!isset($new_timeperiod['dayofweek'])) { $dayofweek = (!isset($new_timeperiod['dayofweek_su'])) ? '0' : '1'; $dayofweek .= (!isset($new_timeperiod['dayofweek_sa'])) ? '0' : '1'; $dayofweek .= (!isset($new_timeperiod['dayofweek_fr'])) ? '0' : '1'; $dayofweek .= (!isset($new_timeperiod['dayofweek_th'])) ? '0' : '1'; $dayofweek .= (!isset($new_timeperiod['dayofweek_we'])) ? '0' : '1'; $dayofweek .= (!isset($new_timeperiod['dayofweek_tu'])) ? '0' : '1'; $dayofweek .= (!isset($new_timeperiod['dayofweek_mo'])) ? '0' : '1'; $new_timeperiod['dayofweek'] = bindec($dayofweek); } // months if (!isset($new_timeperiod['month'])) { $month = (!isset($new_timeperiod['month_dec'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_nov'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_oct'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_sep'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_aug'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_jul'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_jun'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_may'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_apr'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_mar'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_feb'])) ? '0' : '1'; $month .= (!isset($new_timeperiod['month_jan'])) ? '0' : '1'; $new_timeperiod['month'] = bindec($month); } if ($new_timeperiod['timeperiod_type'] == TIMEPERIOD_TYPE_MONTHLY) { if ($new_timeperiod['month_date_type'] > 0) { $new_timeperiod['day'] = 0; } else { $new_timeperiod['every'] = 0; $new_timeperiod['dayofweek'] = 0; } } $_REQUEST['timeperiods'] = get_request('timeperiods', array()); $result = false; if ($new_timeperiod['period'] < 300) { info(_('Incorrect maintenance period (minimum 5 minutes)')); } elseif ($new_timeperiod['hour'] > 23 || $new_timeperiod['minute'] > 59) { info(_('Incorrect maintenance period')); } elseif ($new_timeperiod['timeperiod_type'] == TIMEPERIOD_TYPE_ONETIME && $new_timeperiod['start_date'] < 1) { error(_('Incorrect maintenance - date must be between 1970.01.01 and 2038.01.18')); } elseif ($new_timeperiod['timeperiod_type'] == TIMEPERIOD_TYPE_DAILY && $new_timeperiod['every'] < 1) { info(_('Incorrect maintenance day period')); } elseif ($new_timeperiod['timeperiod_type'] == TIMEPERIOD_TYPE_WEEKLY) { if ($new_timeperiod['every'] < 1) { info(_('Incorrect maintenance week period')); } elseif ($new_timeperiod['dayofweek'] < 1) { info(_('Incorrect maintenance days of week')); } else { $result = true; } } elseif ($new_timeperiod['timeperiod_type'] == TIMEPERIOD_TYPE_MONTHLY) { if ($new_timeperiod['month'] < 1) { info(_('Incorrect maintenance month period')); } elseif ($new_timeperiod['day'] == 0 && $new_timeperiod['dayofweek'] < 1) { info(_('Incorrect maintenance days of week')); } elseif (($new_timeperiod['day'] < 1 || $new_timeperiod['day'] > 31) && $new_timeperiod['dayofweek'] == 0) { info(_('Incorrect maintenance date')); } else { $result = true; } } else { $result = true; } show_messages(); if ($result) { if (!isset($new_timeperiod['id'])) { if (!str_in_array($new_timeperiod, $_REQUEST['timeperiods'])) { array_push($_REQUEST['timeperiods'], $new_timeperiod); } } else { $id = $new_timeperiod['id']; unset($new_timeperiod['id']); $_REQUEST['timeperiods'][$id] = $new_timeperiod; } unset($_REQUEST['new_timeperiod']); } } elseif (isset($_REQUEST['del_timeperiod']) && isset($_REQUEST['g_timeperiodid'])) { $_REQUEST['timeperiods'] = get_request('timeperiods', array()); foreach ($_REQUEST['g_timeperiodid'] as $val) { unset($_REQUEST['timeperiods'][$val]); } } elseif (isset($_REQUEST['edit_timeperiodid'])) { $_REQUEST['edit_timeperiodid'] = array_keys($_REQUEST['edit_timeperiodid']); $edit_timeperiodid = $_REQUEST['edit_timeperiodid'] = array_pop($_REQUEST['edit_timeperiodid']); $_REQUEST['timeperiods'] = get_request('timeperiods', array()); if (isset($_REQUEST['timeperiods'][$edit_timeperiodid])) { $_REQUEST['new_timeperiod'] = $_REQUEST['timeperiods'][$edit_timeperiodid]; $_REQUEST['new_timeperiod']['id'] = $edit_timeperiodid; $_REQUEST['new_timeperiod']['start_date'] = date('YmdHi', $_REQUEST['timeperiods'][$edit_timeperiodid]['start_date']); } } if ($_REQUEST['go'] != 'none' && !empty($go_result)) { $url = new CUrl(); $path = $url->getPath(); insert_js('cookie.eraseArray("'.$path.'")'); } $options = array( 'groups' => array('editable' => 1), 'groupid' => get_request('groupid', null) ); $pageFilter = new CPageFilter($options); $_REQUEST['groupid'] = $pageFilter->groupid; /* * Display */ $data = array('form' => get_request('form')); if (!empty($data['form'])) { $data['maintenanceid'] = get_request('maintenanceid'); $data['form_refresh'] = get_request('form_refresh', 0); if (!empty($data['maintenanceid']) && !isset($_REQUEST['form_refresh'])) { // get maintenance $options = array( 'editable' => true, 'maintenanceids' => $data['maintenanceid'], 'output' => API_OUTPUT_EXTEND ); $maintenance = API::Maintenance()->get($options); $maintenance = reset($maintenance); $data['mname'] = $maintenance['name']; $data['maintenance_type'] = $maintenance['maintenance_type']; $data['active_since'] = $maintenance['active_since']; $data['active_till'] = $maintenance['active_till']; $data['description'] = $maintenance['description']; // get time periods $data['timeperiods'] = array(); $sql = 'SELECT DISTINCT mw.maintenanceid,tp.*'. ' FROM timeperiods tp,maintenances_windows mw'. ' WHERE mw.maintenanceid='.$data['maintenanceid']. ' AND tp.timeperiodid=mw.timeperiodid'. ' ORDER BY tp.timeperiod_type,tp.start_date'; $db_timeperiods = DBselect($sql); while ($timeperiod = DBfetch($db_timeperiods)) { $data['timeperiods'][] = $timeperiod; } // get hosts $options = array( 'maintenanceids' => $data['maintenanceid'], 'real_hosts' => true, 'output' => API_OUTPUT_SHORTEN, 'editable' => true ); $data['hostids'] = API::Host()->get($options); $data['hostids'] = zbx_objectValues($data['hostids'], 'hostid'); // get groupids $options = array( 'maintenanceids' => $data['maintenanceid'], 'real_hosts' => true, 'output' => API_OUTPUT_SHORTEN, 'editable' => true ); $data['groupids'] = API::HostGroup()->get($options); $data['groupids'] = zbx_objectValues($data['groupids'], 'groupid'); } else { $data['mname'] = get_request('mname', ''); $data['maintenance_type'] = get_request('maintenance_type', 0); $data['active_since'] = zbxDateToTime(get_request('active_since', date('YmdHi'))); $data['active_till'] = zbxDateToTime(get_request('active_till', date('YmdHi', time() + SEC_PER_DAY))); $data['description'] = get_request('description', ''); $data['timeperiods'] = get_request('timeperiods', array()); $data['hostids'] = get_request('hostids', array()); $data['groupids'] = get_request('groupids', array()); } // get groups $options = array( 'editable' => true, 'output' => array('groupid', 'name'), 'real_hosts' => true, 'preservekeys' => true ); $data['all_groups'] = API::HostGroup()->get($options); order_result($data['all_groups'], 'name'); $data['twb_groupid'] = get_request('twb_groupid', 0); if (!isset($data['all_groups'][$data['twb_groupid']])) { $twb_groupid = reset($data['all_groups']); $data['twb_groupid'] = $twb_groupid['groupid']; } // get hosts from selected twb group $options = array( 'output' => array('hostid', 'name'), 'real_hosts' => 1, 'editable' => 1, 'groupids' => $data['twb_groupid'] ); $data['hosts'] = API::Host()->get($options); // selected hosts $options = array( 'output' => array('hostid', 'name'), 'real_hosts' => 1, 'editable' => 1, 'hostids' => $data['hostids'] ); $hosts_selected = API::Host()->get($options); $data['hosts'] = array_merge($data['hosts'], $hosts_selected); $data['hosts'] = zbx_toHash($data['hosts'], 'hostid'); order_result($data['hosts'], 'name'); // render view $maintenanceView = new CView('configuration.maintenance.edit', $data); $maintenanceView->render(); $maintenanceView->show(); } else { // get maintenances $sortfield = getPageSortField('name'); $sortorder = getPageSortOrder(); $options = array( 'output' => API_OUTPUT_EXTEND, 'editable' => 1, 'sortfield' => $sortfield, 'sortorder' => $sortorder, 'limit' => $config['search_limit'] + 1 ); if ($pageFilter->groupsSelected) { if ($pageFilter->groupid > 0) { $options['groupids'] = $pageFilter->groupid; } else { $options['groupids'] = array_keys($pageFilter->groups); } } else { $options['groupids'] = array(); } $data['maintenances'] = API::Maintenance()->get($options); foreach ($data['maintenances'] as $number => $maintenance) { if ($maintenance['active_till'] < time()) { $data['maintenances'][$number]['status'] = MAINTENANCE_STATUS_EXPIRED; } elseif ($maintenance['active_since'] > time()) { $data['maintenances'][$number]['status'] = MAINTENANCE_STATUS_APPROACH; } else { $data['maintenances'][$number]['status'] = MAINTENANCE_STATUS_ACTIVE; } } order_result($data['maintenances'], $sortfield, $sortorder); $data['paging'] = getPagingLine($data['maintenances']); $data['pageFilter'] = $pageFilter; // render view $maintenanceView = new CView('configuration.maintenance.list', $data); $maintenanceView->render(); $maintenanceView->show(); } require_once dirname(__FILE__).'/include/page_footer.php'; ?>
gheja/zabbix-ext
frontends/php/maintenance.php
PHP
gpl-2.0
16,900
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace Cake\Auth; use Cake\Controller\ComponentRegistry; use Cake\Core\InstanceConfigTrait; use Cake\Event\EventListenerInterface; use Cake\Network\Request; use Cake\Network\Response; use Cake\ORM\TableRegistry; /** * Base Authentication class with common methods and properties. * */ abstract class BaseAuthenticate implements EventListenerInterface { use InstanceConfigTrait; /** * Default config for this object. * * - `fields` The fields to use to identify a user by. * - `userModel` The alias for users table, defaults to Users. * - `finder` The finder method to use to fetch user record. Defaults to 'all'. * You can set finder name as string or an array where key is finder name and value * is an array passed to `Table::find()` options. * E.g. ['finderName' => ['some_finder_option' => 'some_value']] * - `passwordHasher` Password hasher class. Can be a string specifying class name * or an array containing `className` key, any other keys will be passed as * config to the class. Defaults to 'Default'. * - Options `scope` and `contain` have been deprecated since 3.1. Use custom * finder instead to modify the query to fetch user record. * * @var array */ protected $_defaultConfig = [ 'fields' => [ 'username' => 'username', 'password' => 'password' ], 'userModel' => 'Users', 'scope' => [], 'finder' => 'all', 'contain' => null, 'passwordHasher' => 'Default' ]; /** * A Component registry, used to get more components. * * @var \Cake\Controller\ComponentRegistry */ protected $_registry; /** * Password hasher instance. * * @var \Cake\Auth\AbstractPasswordHasher */ protected $_passwordHasher; /** * Whether or not the user authenticated by this class * requires their password to be rehashed with another algorithm. * * @var bool */ protected $_needsPasswordRehash = false; /** * Constructor * * @param \Cake\Controller\ComponentRegistry $registry The Component registry used on this request. * @param array $config Array of config to use. */ public function __construct(ComponentRegistry $registry, array $config = []) { $this->_registry = $registry; $this->config($config); } /** * Find a user record using the username and password provided. * * Input passwords will be hashed even when a user doesn't exist. This * helps mitigate timing attacks that are attempting to find valid usernames. * * @param string $username The username/identifier. * @param string|null $password The password, if not provided password checking is skipped * and result of find is returned. * @return bool|array Either false on failure, or an array of user data. */ protected function _findUser($username, $password = null) { $result = $this->_query($username)->first(); if (empty($result)) { return false; } if ($password !== null) { $hasher = $this->passwordHasher(); $hashedPassword = $result->get($this->_config['fields']['password']); if (!$hasher->check($password, $hashedPassword)) { return false; } $this->_needsPasswordRehash = $hasher->needsRehash($hashedPassword); $result->unsetProperty($this->_config['fields']['password']); } return $result->toArray(); } /** * Get query object for fetching user from database. * * @param string $username The username/identifier. * @return \Cake\ORM\Query */ protected function _query($username) { $config = $this->_config; $table = TableRegistry::get($config['userModel']); $options = [ 'conditions' => [$table->aliasField($config['fields']['username']) => $username] ]; if (!empty($config['scope'])) { $options['conditions'] = array_merge($options['conditions'], $config['scope']); } if (!empty($config['contain'])) { $options['contain'] = $config['contain']; } $finder = $config['finder']; if (is_array($finder)) { $options += current($finder); $finder = key($finder); } $query = $table->find($finder, $options); return $query; } /** * Return password hasher object * * @return \Cake\Auth\AbstractPasswordHasher Password hasher instance * @throws \RuntimeException If password hasher class not found or * it does not extend AbstractPasswordHasher */ public function passwordHasher() { if ($this->_passwordHasher) { return $this->_passwordHasher; } $passwordHasher = $this->_config['passwordHasher']; return $this->_passwordHasher = PasswordHasherFactory::build($passwordHasher); } /** * Returns whether or not the password stored in the repository for the logged in user * requires to be rehashed with another algorithm * * @return bool */ public function needsPasswordRehash() { return $this->_needsPasswordRehash; } /** * Authenticate a user based on the request information. * * @param \Cake\Network\Request $request Request to get authentication information from. * @param \Cake\Network\Response $response A response object that can have headers added. * @return mixed Either false on failure, or an array of user data on success. */ abstract public function authenticate(Request $request, Response $response); /** * Get a user based on information in the request. Primarily used by stateless authentication * systems like basic and digest auth. * * @param \Cake\Network\Request $request Request object. * @return mixed Either false or an array of user information */ public function getUser(Request $request) { return false; } /** * Handle unauthenticated access attempt. In implementation valid return values * can be: * * - Null - No action taken, AuthComponent should return appropriate response. * - Cake\Network\Response - A response object, which will cause AuthComponent to * simply return that response. * * @param \Cake\Network\Request $request A request object. * @param \Cake\Network\Response $response A response object. * @return void */ public function unauthenticated(Request $request, Response $response) { } /** * Returns a list of all events that this authenticate class will listen to. * * An authenticate class can listen to following events fired by AuthComponent: * * - `Auth.afterIdentify` - Fired after a user has been identified using one of * configured authenticate class. The callback function should have signature * like `afterIdentify(Event $event, array $user)` when `$user` is the * identified user record. * * - `Auth.logout` - Fired when AuthComponent::logout() is called. The callback * function should have signature like `logout(Event $event, array $user)` * where `$user` is the user about to be logged out. * * @return array List of events this class listens to. Defaults to `[]`. */ public function implementedEvents() { return []; } }
WildTurtles/wildturtles
vendor/cakephp/cakephp/src/Auth/BaseAuthenticate.php
PHP
gpl-2.0
8,197
/////////////////////////////////////////////////////////////////////////////// // For information as to what this class does, see the Javadoc, below. // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, // // 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph // // Ramsey, and Clark Glymour. // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation; either version 2 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program; if not, write to the Free Software // // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /////////////////////////////////////////////////////////////////////////////// package edu.cmu.tetradapp.editor; import edu.cmu.tetrad.session.SessionModel; import edu.cmu.tetrad.util.Parameters; import edu.cmu.tetradapp.model.DataWrapper; import edu.cmu.tetradapp.model.GeneralAlgorithmRunner; import edu.cmu.tetradapp.model.GraphSource; import edu.cmu.tetradapp.model.Simulation; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.LinkedList; import java.util.List; /** * Edits the parameters for generating random graphs. * * @author Joseph Ramsey */ public class EdgewiseComparisonParamsEditor extends JPanel implements ParameterEditor { /** * The parameters object being edited. */ private Parameters params = null; /** * The first graph source. */ private SessionModel model1; /** * The second graph source. */ private SessionModel model2; /** * The parent models. These should be graph sources. */ private Object[] parentModels; public void setParams(Parameters params) { if (params == null) { throw new NullPointerException(); } this.params = params; } public void setParentModels(Object[] parentModels) { this.parentModels = parentModels; } public boolean mustBeShown() { return false; } public void setup() { List<GraphSource> graphSources = new LinkedList<>(); for (Object parentModel : parentModels) { if (parentModel instanceof GraphSource) { graphSources.add((GraphSource) parentModel); } } if (graphSources.size() == 1 && graphSources.get(0) instanceof GeneralAlgorithmRunner) { model1 = (GeneralAlgorithmRunner) graphSources.get(0); model2 = ((GeneralAlgorithmRunner) model1).getDataWrapper(); } else if (graphSources.size() == 2) { model1 = (SessionModel) graphSources.get(0); model2 = (SessionModel) graphSources.get(1); } else { throw new IllegalArgumentException("Expecting 2 graph source."); } setLayout(new BorderLayout()); // Reset? JRadioButton resetOnExecute = new JRadioButton("Reset"); JRadioButton dontResetOnExecute = new JRadioButton("Appended to"); ButtonGroup group1 = new ButtonGroup(); group1.add(resetOnExecute); group1.add(dontResetOnExecute); resetOnExecute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getParams().set("resetTableOnExecute", true); } }); dontResetOnExecute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getParams().set("resetTableOnExecute", false); } }); if (getParams().getBoolean("resetTableOnExecute", false)) { resetOnExecute.setSelected(true); } else { dontResetOnExecute.setSelected(true); } // Latents? JRadioButton latents = new JRadioButton("Yes"); JRadioButton noLatents = new JRadioButton("No"); ButtonGroup group2 = new ButtonGroup(); group2.add(latents); group2.add(noLatents); latents.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getParams().set("keepLatents", true); } }); if (getParams().getBoolean("keepLatents", false)) { latents.setSelected(true); } else { noLatents.setSelected(true); } // True graph? JRadioButton graph1 = new JRadioButton(model1.getName()); JRadioButton graph2 = new JRadioButton(model2.getName()); graph1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getParams().set("referenceGraphName", model1.getName()); getParams().set("targetGraphName", model2.getName()); } }); graph2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { getParams().set("referenceGraphName", model2.getName()); getParams().set("targetGraphName", model1.getName()); } }); ButtonGroup group = new ButtonGroup(); group.add(graph1); group.add(graph2); boolean alreadySet = false; if (model1 instanceof GeneralAlgorithmRunner) { graph1.setSelected(true); } if (model2 instanceof GeneralAlgorithmRunner) { graph2.setSelected(true); alreadySet = true; } if (model2 instanceof Simulation) { graph2.setSelected(true); alreadySet = true; } if (!alreadySet) { graph1.setSelected(true); } if (graph1.isSelected()) { getParams().set("referenceGraphName", model1.getName()); getParams().set("targetGraphName", model2.getName()); } else if (graph2.isSelected()) { getParams().set("referenceGraphName", model2.getName()); getParams().set("targetGraphName", model1.getName()); } Box b1 = Box.createVerticalBox(); Box b8 = Box.createHorizontalBox(); b8.add(new JLabel("Which of the two input graphs is the true graph?")); b8.add(Box.createHorizontalGlue()); b1.add(b8); Box b9 = Box.createHorizontalBox(); b9.add(graph1); b9.add(Box.createHorizontalGlue()); b1.add(b9); Box b10 = Box.createHorizontalBox(); b10.add(graph2); b10.add(Box.createHorizontalGlue()); b1.add(b10); b1.add(Box.createHorizontalGlue()); add(b1, BorderLayout.CENTER); } /** * @return the getMappings object being edited. (This probably should not be * public, but it is needed so that the textfields can edit the model.) */ private synchronized Parameters getParams() { return this.params; } }
ekummerfeld/tetrad
tetrad-gui/src/main/java/edu/cmu/tetradapp/editor/EdgewiseComparisonParamsEditor.java
Java
gpl-2.0
7,810
/* * Copyright 2007 Yusuke Yamamoto * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package twitter4j; import java.util.Date; /** * A data interface representing one single status of a user. * * @author Yusuke Yamamoto - yusuke at mac.com */ public interface Status extends Comparable<Status>, TwitterResponse, EntitySupport, java.io.Serializable { /** * Return the created_at * * @return created_at * @since Twitter4J 1.1.0 */ Date getCreatedAt(); /** * Returns the id of the status * * @return the id */ long getId(); /** * Returns the text of the status * * @return the text */ String getText(); /** * Returns the source * * @return the source * @since Twitter4J 1.0.4 */ String getSource(); /** * Test if the status is truncated * * @return true if truncated * @since Twitter4J 1.0.4 */ boolean isTruncated(); /** * Returns the in_reply_tostatus_id * * @return the in_reply_tostatus_id * @since Twitter4J 1.0.4 */ long getInReplyToStatusId(); /** * Returns the in_reply_user_id * * @return the in_reply_tostatus_id * @since Twitter4J 1.0.4 */ long getInReplyToUserId(); /** * Returns the in_reply_to_screen_name * * @return the in_in_reply_to_screen_name * @since Twitter4J 2.0.4 */ String getInReplyToScreenName(); /** * Returns The location that this tweet refers to if available. * * @return returns The location that this tweet refers to if available (can be null) * @since Twitter4J 2.1.0 */ GeoLocation getGeoLocation(); /** * Returns the place attached to this status * * @return The place attached to this status * @since Twitter4J 2.1.1 */ Place getPlace(); /** * Test if the status is favorited * * @return true if favorited * @since Twitter4J 1.0.4 */ boolean isFavorited(); /** * Test if the status is retweeted * * @return true if retweeted * @since Twitter4J 3.0.4 */ boolean isRetweeted(); /** * Indicates approximately how many times this Tweet has been "favorited" by Twitter users. * * @return the favorite count * @since Twitter4J 3.0.4 */ int getFavoriteCount(); /** * Return the user associated with the status.<br> * This can be null if the instance if from User.getStatus(). * * @return the user */ User getUser(); /** * @since Twitter4J 2.0.10 */ boolean isRetweet(); /** * @since Twitter4J 2.1.0 */ Status getRetweetedStatus(); /** * Returns an array of contributors, or null if no contributor is associated with this status. * * @since Twitter4J 2.2.3 */ long[] getContributors(); /** * Returns the number of times this tweet has been retweeted, or -1 when the tweet was * created before this feature was enabled. * * @return the retweet count. */ int getRetweetCount(); /** * Returns true if the authenticating user has retweeted this tweet, or false when the tweet was * created before this feature was enabled. * * @return whether the authenticating user has retweeted this tweet. * @since Twitter4J 2.1.4 */ boolean isRetweetedByMe(); /** * Returns the authenticating user's retweet's id of this tweet, or -1L when the tweet was created * before this feature was enabled. * * @return the authenticating user's retweet's id of this tweet * @since Twitter4J 3.0.1 */ long getCurrentUserRetweetId(); /** * Returns true if the status contains a link that is identified as sensitive. * * @return whether the status contains sensitive links * @since Twitter4J 3.0.0 */ boolean isPossiblySensitive(); /** * Returns the lang of the status text if available. * * @return two-letter iso language code * @since Twitter4J 3.0.6 */ String getLang(); /** * Returns the targeting scopes applied to a status. * * @return the targeting scopes applied to a status. * @since Twitter4J 3.0.6 */ Scopes getScopes(); }
jonathanmcelroy/DataCommunicationsProgram456
twitter4j/twitter4j-core/src/main/java/twitter4j/Status.java
Java
gpl-2.0
4,909
/* Copyright (C) 2006 - 2012 ScriptDev2 <http://www.scriptdev2.com/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Instance_Uldaman SD%Complete: 60 SDComment: SDCategory: Uldaman EndScriptData */ #include "precompiled.h" #include "uldaman.h" instance_uldaman::instance_uldaman(Map* pMap) : ScriptedInstance(pMap), m_uiStoneKeepersFallen(0), m_uiKeeperCooldown(5000) { Initialize(); } void instance_uldaman::Initialize() { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); } void instance_uldaman::OnObjectCreate(GameObject* pGo) { switch(pGo->GetEntry()) { case GO_TEMPLE_DOOR_UPPER: if (m_auiEncounter[0] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_TEMPLE_DOOR_LOWER: if (m_auiEncounter[0] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_ANCIENT_VAULT: if (m_auiEncounter[1] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; default: return; } m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid(); } void instance_uldaman::OnCreatureCreate(Creature* pCreature) { switch(pCreature->GetEntry()) { case NPC_HALLSHAPER: case NPC_CUSTODIAN: case NPC_GUARDIAN: case NPC_VAULT_WARDER: m_lWardens.push_back(pCreature->GetObjectGuid()); pCreature->SetNoCallAssistance(true); // no assistance break; case NPC_STONE_KEEPER: // FIXME - This isAlive check is currently useless m_mKeeperMap[pCreature->GetObjectGuid()] = pCreature->isAlive(); pCreature->SetNoCallAssistance(true); // no assistance break; default: break; } } void instance_uldaman::SetData(uint32 uiType, uint32 uiData) { switch(uiType) { case TYPE_ALTAR_EVENT: if (uiData == DONE) { DoUseDoorOrButton(GO_TEMPLE_DOOR_UPPER); DoUseDoorOrButton(GO_TEMPLE_DOOR_LOWER); m_auiEncounter[0] = uiData; } break; case TYPE_ARCHAEDAS: if (uiData == FAIL) { for (GuidList::const_iterator itr = m_lWardens.begin(); itr != m_lWardens.end(); ++itr) { if (Creature* pWarden = instance->GetCreature(*itr)) { pWarden->SetDeathState(JUST_DIED); pWarden->Respawn(); pWarden->SetNoCallAssistance(true); } } } else if (uiData == DONE) { for (GuidList::const_iterator itr = m_lWardens.begin(); itr != m_lWardens.end(); ++itr) { Creature* pWarden = instance->GetCreature(*itr); if (pWarden && pWarden->isAlive()) pWarden->ForcedDespawn(); } DoUseDoorOrButton(GO_ANCIENT_VAULT); } m_auiEncounter[1] = uiData; break; } if (uiData == DONE) { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << m_auiEncounter[0] << " " << m_auiEncounter[1]; m_strInstData = saveStream.str(); SaveToDB(); OUT_SAVE_INST_DATA_COMPLETE; } } void instance_uldaman::Load(const char* chrIn) { if (!chrIn) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(chrIn); std::istringstream loadStream(chrIn); loadStream >> m_auiEncounter[0] >> m_auiEncounter[1]; for(uint8 i = 0; i < MAX_ENCOUNTER; ++i) { if (m_auiEncounter[i] == IN_PROGRESS) m_auiEncounter[i] = NOT_STARTED; } OUT_LOAD_INST_DATA_COMPLETE; } void instance_uldaman::SetData64(uint32 uiData, uint64 uiGuid) { switch(uiData) { case DATA_EVENT_STARTER: m_playerGuid = ObjectGuid(uiGuid); break; } } uint32 instance_uldaman::GetData(uint32 uiType) { switch(uiType) { case TYPE_ARCHAEDAS: return m_auiEncounter[1]; } return 0; } uint64 instance_uldaman::GetData64(uint32 uiData) { switch(uiData) { case DATA_EVENT_STARTER: return m_playerGuid.GetRawValue(); } return 0; } void instance_uldaman::StartEvent(uint32 uiEventId, Player* pPlayer) { m_playerGuid = pPlayer->GetObjectGuid(); if (uiEventId == EVENT_ID_ALTAR_KEEPER) { if (m_auiEncounter[0] == NOT_STARTED) m_auiEncounter[0] = IN_PROGRESS; } else if (m_auiEncounter[1] == NOT_STARTED || m_auiEncounter[1] == FAIL) m_auiEncounter[1] = SPECIAL; } void instance_uldaman::DoResetKeeperEvent() { m_auiEncounter[0] = NOT_STARTED; m_uiStoneKeepersFallen = 0; for (std::map<ObjectGuid, bool>::iterator itr = m_mKeeperMap.begin(); itr != m_mKeeperMap.end(); ++itr) { if (Creature* pKeeper = instance->GetCreature(itr->first)) { pKeeper->SetDeathState(JUST_DIED); pKeeper->Respawn(); pKeeper->SetNoCallAssistance(true); itr->second = true; } } } Creature* instance_uldaman::GetClosestDwarfNotInCombat(Creature* pSearcher, uint32 uiPhase) { std::list<Creature*> lTemp; for (GuidList::const_iterator itr = m_lWardens.begin(); itr != m_lWardens.end(); ++itr) { Creature* pTemp = instance->GetCreature(*itr); if (pTemp && pTemp->isAlive() && !pTemp->getVictim()) { switch(uiPhase) { case PHASE_ARCHA_1: if (pTemp->GetEntry() != NPC_CUSTODIAN && pTemp->GetEntry() != NPC_HALLSHAPER) continue; break; case PHASE_ARCHA_2: if (pTemp->GetEntry() != NPC_GUARDIAN) continue; break; case PHASE_ARCHA_3: if (pTemp->GetEntry() != NPC_VAULT_WARDER) continue; break; } lTemp.push_back(pTemp); } } if (lTemp.empty()) return NULL; lTemp.sort(ObjectDistanceOrder(pSearcher)); return lTemp.front(); } void instance_uldaman::Update(uint32 uiDiff) { if (m_auiEncounter[0] == IN_PROGRESS) { if (m_uiKeeperCooldown >= uiDiff) m_uiKeeperCooldown -= uiDiff; else { m_uiKeeperCooldown = 5000; if (!m_mKeeperMap.empty()) { for(std::map<ObjectGuid, bool>::iterator itr = m_mKeeperMap.begin(); itr != m_mKeeperMap.end(); ++itr) { // died earlier if (!itr->second) continue; if (Creature* pKeeper = instance->GetCreature(itr->first)) { if (pKeeper->isAlive() && !pKeeper->getVictim()) { if (Player* pPlayer = pKeeper->GetMap()->GetPlayer(m_playerGuid)) { // we should use group instead, event starter can be dead while group is still fighting if (pPlayer->isAlive() && !pPlayer->isInCombat()) { pKeeper->RemoveAurasDueToSpell(SPELL_STONED); pKeeper->SetInCombatWith(pPlayer); pKeeper->AddThreat(pPlayer); } else { if (!pPlayer->isAlive()) DoResetKeeperEvent(); } } break; } else if (!pKeeper->isAlive()) { itr->second = pKeeper->isAlive(); ++m_uiStoneKeepersFallen; } } } if (m_uiStoneKeepersFallen == m_mKeeperMap.size()) SetData(TYPE_ALTAR_EVENT, DONE); } } } } InstanceData* GetInstanceData_instance_uldaman(Map* pMap) { return new instance_uldaman(pMap); } bool ProcessEventId_event_spell_altar_boss_aggro(uint32 uiEventId, Object* pSource, Object* pTarget, bool bIsStart) { if (bIsStart && pSource->GetTypeId() == TYPEID_PLAYER) { if (instance_uldaman* pInstance = (instance_uldaman*)((Player*)pSource)->GetInstanceData()) { pInstance->StartEvent(uiEventId, (Player*)pSource); return true; } } return false; } void AddSC_instance_uldaman() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "instance_uldaman"; pNewScript->GetInstanceData = &GetInstanceData_instance_uldaman; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "event_spell_altar_boss_aggro"; pNewScript->pProcessEventId = &ProcessEventId_event_spell_altar_boss_aggro; pNewScript->RegisterSelf(); }
Remix99/MaNGOS
src/bindings/scriptdev2/scripts/eastern_kingdoms/uldaman/instance_uldaman.cpp
C++
gpl-2.0
10,144
// This file is part of par2cmdline (a PAR 2.0 compatible file verification and // repair tool). See http://parchive.sourceforge.net for details of PAR 2.0. // // Copyright (c) 2003 Peter Brian Clements // // par2cmdline 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. // // par2cmdline 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 "par2cmdline.h" #ifdef _MSC_VER #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #endif Par2Creator::Par2Creator(void) : noiselevel(CommandLine::nlUnknown) , blocksize(0) , chunksize(0) , inputbuffer(0) , outputbuffer(0) , sourcefilecount(0) , sourceblockcount(0) , largestfilesize(0) , recoveryfilescheme(CommandLine::scUnknown) , recoveryfilecount(0) , recoveryblockcount(0) , firstrecoveryblock(0) , mainpacket(0) , creatorpacket(0) , deferhashcomputation(false) { } Par2Creator::~Par2Creator(void) { delete mainpacket; delete creatorpacket; delete [] (u8*)inputbuffer; delete [] (u8*)outputbuffer; vector<Par2CreatorSourceFile*>::iterator sourcefile = sourcefiles.begin(); while (sourcefile != sourcefiles.end()) { delete *sourcefile; ++sourcefile; } } Result Par2Creator::Process(const CommandLine &commandline) { // Get information from commandline noiselevel = commandline.GetNoiseLevel(); blocksize = commandline.GetBlockSize(); sourceblockcount = commandline.GetBlockCount(); const list<CommandLine::ExtraFile> extrafiles = commandline.GetExtraFiles(); sourcefilecount = (u32)extrafiles.size(); u32 redundancy = commandline.GetRedundancy(); recoveryblockcount = commandline.GetRecoveryBlockCount(); recoveryfilecount = commandline.GetRecoveryFileCount(); firstrecoveryblock = commandline.GetFirstRecoveryBlock(); recoveryfilescheme = commandline.GetRecoveryFileScheme(); string par2filename = commandline.GetParFilename(); size_t memorylimit = commandline.GetMemoryLimit(); largestfilesize = commandline.GetLargestSourceSize(); // Compute block size from block count or vice versa depending on which was // specified on the command line if (!ComputeBlockSizeAndBlockCount(extrafiles)) return eInvalidCommandLineArguments; // Determine how many recovery blocks to create based on the source block // count and the requested level of redundancy. if (redundancy > 0 && !ComputeRecoveryBlockCount(redundancy)) return eInvalidCommandLineArguments; // Determine how much recovery data can be computed on one pass if (!CalculateProcessBlockSize(memorylimit)) return eLogicError; // Determine how many recovery files to create. if (!ComputeRecoveryFileCount()) return eInvalidCommandLineArguments; if (noiselevel > CommandLine::nlQuiet) { // Display information. cout << "Block size: " << blocksize << endl; cout << "Source file count: " << sourcefilecount << endl; cout << "Source block count: " << sourceblockcount << endl; if (redundancy>0 || recoveryblockcount==0) cout << "Redundancy: " << redundancy << '%' << endl; cout << "Recovery block count: " << recoveryblockcount << endl; cout << "Recovery file count: " << recoveryfilecount << endl; cout << endl; } // Open all of the source files, compute the Hashes and CRC values, and store // the results in the file verification and file description packets. if (!OpenSourceFiles(extrafiles)) return eFileIOError; // Create the main packet and determine the setid to use with all packets if (!CreateMainPacket()) return eLogicError; // Create the creator packet. if (!CreateCreatorPacket()) return eLogicError; // Initialise all of the source blocks ready to start reading data from the source files. if (!CreateSourceBlocks()) return eLogicError; // Create all of the output files and allocate all packets to appropriate file offets. if (!InitialiseOutputFiles(par2filename)) return eFileIOError; if (recoveryblockcount > 0) { // Allocate memory buffers for reading and writing data to disk. if (!AllocateBuffers()) return eMemoryError; // Compute the Reed Solomon matrix if (!ComputeRSMatrix()) return eLogicError; // Set the total amount of data to be processed. progress = 0; totaldata = blocksize * sourceblockcount * recoveryblockcount; // Start at an offset of 0 within a block. u64 blockoffset = 0; while (blockoffset < blocksize) // Continue until the end of the block. { // Work out how much data to process this time. size_t blocklength = (size_t)min((u64)chunksize, blocksize-blockoffset); // Read source data, process it through the RS matrix and write it to disk. if (!ProcessData(blockoffset, blocklength)) return eFileIOError; blockoffset += blocklength; } if (noiselevel > CommandLine::nlQuiet) cout << "Writing recovery packets" << endl; // Finish computation of the recovery packets and write the headers to disk. if (!WriteRecoveryPacketHeaders()) return eFileIOError; // Finish computing the full file hash values of the source files if (!FinishFileHashComputation()) return eLogicError; } // Fill in all remaining details in the critical packets. if (!FinishCriticalPackets()) return eLogicError; if (noiselevel > CommandLine::nlQuiet) cout << "Writing verification packets" << endl; // Write all other critical packets to disk. if (!WriteCriticalPackets()) return eFileIOError; // Close all files. if (!CloseFiles()) return eFileIOError; if (noiselevel > CommandLine::nlSilent) cout << "Done" << endl; return eSuccess; } // Compute block size from block count or vice versa depending on which was // specified on the command line bool Par2Creator::ComputeBlockSizeAndBlockCount(const list<CommandLine::ExtraFile> &extrafiles) { // Determine blocksize from sourceblockcount or vice-versa if (blocksize > 0) { u64 count = 0; for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++) { count += (i->FileSize() + blocksize-1) / blocksize; } if (count > 32768) { cerr << "Block size is too small. It would require " << count << "blocks." << endl; return false; } sourceblockcount = (u32)count; } else if (sourceblockcount > 0) { if (sourceblockcount < extrafiles.size()) { // The block count cannot be less that the number of files. cerr << "Block count is too small." << endl; return false; } else if (sourceblockcount == extrafiles.size()) { // If the block count is the same as the number of files, then the block // size is the size of the largest file (rounded up to a multiple of 4). u64 largestsourcesize = 0; for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++) { if (largestsourcesize < i->FileSize()) { largestsourcesize = i->FileSize(); } } blocksize = (largestsourcesize + 3) & ~3; } else { u64 totalsize = 0; for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++) { totalsize += (i->FileSize() + 3) / 4; } if (sourceblockcount > totalsize) { sourceblockcount = (u32)totalsize; blocksize = 4; } else { // Absolute lower bound and upper bound on the source block size that will // result in the requested source block count. u64 lowerBound = totalsize / sourceblockcount; u64 upperBound = (totalsize + sourceblockcount - extrafiles.size() - 1) / (sourceblockcount - extrafiles.size()); u64 bestsize = lowerBound; u64 bestdistance = 1000000; u64 bestcount = 0; u64 count; u64 size; // Work out how many blocks you get for the lower bound block size { size = lowerBound; count = 0; for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++) { count += ((i->FileSize()+3)/4 + size-1) / size; } if (bestdistance > (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count)) { bestdistance = (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count); bestcount = count; bestsize = size; } } // Work out how many blocks you get for the upper bound block size { size = upperBound; count = 0; for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++) { count += ((i->FileSize()+3)/4 + size-1) / size; } if (bestdistance > (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count)) { bestdistance = (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count); bestcount = count; bestsize = size; } } // Use binary search to find best block size while (lowerBound+1 < upperBound) { size = (lowerBound + upperBound)/2; count = 0; for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++) { count += ((i->FileSize()+3)/4 + size-1) / size; } if (bestdistance > (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count)) { bestdistance = (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count); bestcount = count; bestsize = size; } if (count < sourceblockcount) { upperBound = size; } else if (count > sourceblockcount) { lowerBound = size; } else { upperBound = size; } } size = bestsize; count = bestcount; if (count > 32768) { cerr << "Error calculating block size." << endl; return false; } sourceblockcount = (u32)count; blocksize = size*4; } } } return true; } // Determine how many recovery blocks to create based on the source block // count and the requested level of redundancy. bool Par2Creator::ComputeRecoveryBlockCount(u32 redundancy) { // Determine recoveryblockcount recoveryblockcount = (sourceblockcount * redundancy + 50) / 100; // Force valid values if necessary if (recoveryblockcount == 0 && redundancy > 0) recoveryblockcount = 1; if (recoveryblockcount > 65536) { cerr << "Too many recovery blocks requested." << endl; return false; } // Check that the last recovery block number would not be too large if (firstrecoveryblock + recoveryblockcount >= 65536) { cerr << "First recovery block number is too high." << endl; return false; } return true; } // Determine how much recovery data can be computed on one pass bool Par2Creator::CalculateProcessBlockSize(size_t memorylimit) { // Are we computing any recovery blocks if (recoveryblockcount == 0) { deferhashcomputation = false; } else { // Would single pass processing use too much memory if (blocksize * recoveryblockcount > memorylimit) { // Pick a size that is small enough chunksize = ~3 & (memorylimit / recoveryblockcount); deferhashcomputation = false; } else { chunksize = (size_t)blocksize; deferhashcomputation = true; } } return true; } // Determine how many recovery files to create. bool Par2Creator::ComputeRecoveryFileCount(void) { // Are we computing any recovery blocks if (recoveryblockcount == 0) { recoveryfilecount = 0; return true; } switch (recoveryfilescheme) { case CommandLine::scUnknown: { assert(false); return false; } break; case CommandLine::scVariable: case CommandLine::scUniform: { if (recoveryfilecount == 0) { // If none specified then then filecount is roughly log2(blockcount) // This prevents you getting excessively large numbers of files // when the block count is high and also allows the files to have // sizes which vary exponentially. for (u32 blocks=recoveryblockcount; blocks>0; blocks>>=1) { recoveryfilecount++; } } if (recoveryfilecount > recoveryblockcount) { // You cannot have move recovery files that there are recovery blocks // to put in them. cerr << "Too many recovery files specified." << endl; return false; } } break; case CommandLine::scLimited: { // No recovery file will contain more recovery blocks than would // be required to reconstruct the largest source file if it // were missing. Other recovery files will have recovery blocks // distributed in an exponential scheme. u32 largest = (u32)((largestfilesize + blocksize-1) / blocksize); u32 whole = recoveryblockcount / largest; whole = (whole >= 1) ? whole-1 : 0; u32 extra = recoveryblockcount - whole * largest; recoveryfilecount = whole; for (u32 blocks=extra; blocks>0; blocks>>=1) { recoveryfilecount++; } } break; } return true; } // Open all of the source files, compute the Hashes and CRC values, and store // the results in the file verification and file description packets. bool Par2Creator::OpenSourceFiles(const list<CommandLine::ExtraFile> &extrafiles) { ExtraFileIterator extrafile = extrafiles.begin(); while (extrafile != extrafiles.end()) { Par2CreatorSourceFile *sourcefile = new Par2CreatorSourceFile; string path; string name; DiskFile::SplitFilename(extrafile->FileName(), path, name); if (noiselevel > CommandLine::nlSilent) cout << "Opening: " << name << endl; // Open the source file and compute its Hashes and CRCs. if (!sourcefile->Open(noiselevel, *extrafile, blocksize, deferhashcomputation)) { delete sourcefile; return false; } // Record the file verification and file description packets // in the critical packet list. sourcefile->RecordCriticalPackets(criticalpackets); // Add the source file to the sourcefiles array. sourcefiles.push_back(sourcefile); // Close the source file until its needed sourcefile->Close(); ++extrafile; } return true; } // Create the main packet and determine the setid to use with all packets bool Par2Creator::CreateMainPacket(void) { // Construct the main packet from the list of source files and the block size. mainpacket = new MainPacket; // Add the main packet to the list of critical packets. criticalpackets.push_back(mainpacket); // Create the packet (sourcefiles will get sorted into FileId order). return mainpacket->Create(sourcefiles, blocksize); } // Create the creator packet. bool Par2Creator::CreateCreatorPacket(void) { // Construct the creator packet creatorpacket = new CreatorPacket; // Create the packet return creatorpacket->Create(mainpacket->SetId()); } // Initialise all of the source blocks ready to start reading data from the source files. bool Par2Creator::CreateSourceBlocks(void) { // Allocate the array of source blocks sourceblocks.resize(sourceblockcount); vector<DataBlock>::iterator sourceblock = sourceblocks.begin(); for (vector<Par2CreatorSourceFile*>::iterator sourcefile = sourcefiles.begin(); sourcefile!= sourcefiles.end(); sourcefile++) { // Allocate the appopriate number of source blocks to each source file. // sourceblock will be advanced. (*sourcefile)->InitialiseSourceBlocks(sourceblock, blocksize); } return true; } class FileAllocation { public: FileAllocation(void) { filename = ""; exponent = 0; count = 0; } string filename; u32 exponent; u32 count; }; // Create all of the output files and allocate all packets to appropriate file offets. bool Par2Creator::InitialiseOutputFiles(string par2filename) { // Allocate the recovery packets recoverypackets.resize(recoveryblockcount); // Choose filenames and decide which recovery blocks to place in each file vector<FileAllocation> fileallocations; fileallocations.resize(recoveryfilecount+1); // One extra file with no recovery blocks { // Decide how many recovery blocks to place in each file u32 exponent = firstrecoveryblock; if (recoveryfilecount > 0) { switch (recoveryfilescheme) { case CommandLine::scUnknown: { assert(false); return false; } break; case CommandLine::scUniform: { // Files will have roughly the same number of recovery blocks each. u32 base = recoveryblockcount / recoveryfilecount; u32 remainder = recoveryblockcount % recoveryfilecount; for (u32 filenumber=0; filenumber<recoveryfilecount; filenumber++) { fileallocations[filenumber].exponent = exponent; fileallocations[filenumber].count = (filenumber<remainder) ? base+1 : base; exponent += fileallocations[filenumber].count; } } break; case CommandLine::scVariable: { // Files will have recovery blocks allocated in an exponential fashion. // Work out how many blocks to place in the smallest file u32 lowblockcount = 1; u32 maxrecoveryblocks = (1 << recoveryfilecount) - 1; while (maxrecoveryblocks < recoveryblockcount) { lowblockcount <<= 1; maxrecoveryblocks <<= 1; } // Allocate the blocks. u32 blocks = recoveryblockcount; for (u32 filenumber=0; filenumber<recoveryfilecount; filenumber++) { u32 number = min(lowblockcount, blocks); fileallocations[filenumber].exponent = exponent; fileallocations[filenumber].count = number; exponent += number; blocks -= number; lowblockcount <<= 1; } } break; case CommandLine::scLimited: { // Files will be allocated in an exponential fashion but the // Maximum file size will be limited. u32 largest = (u32)((largestfilesize + blocksize-1) / blocksize); u32 filenumber = recoveryfilecount; u32 blocks = recoveryblockcount; exponent = firstrecoveryblock + recoveryblockcount; // Allocate uniformly at the top while (blocks >= 2*largest && filenumber > 0) { filenumber--; exponent -= largest; blocks -= largest; fileallocations[filenumber].exponent = exponent; fileallocations[filenumber].count = largest; } assert(blocks > 0 && filenumber > 0); exponent = firstrecoveryblock; u32 count = 1; u32 files = filenumber; // Allocate exponentially at the bottom for (filenumber=0; filenumber<files; filenumber++) { u32 number = min(count, blocks); fileallocations[filenumber].exponent = exponent; fileallocations[filenumber].count = number; exponent += number; blocks -= number; count <<= 1; } } break; } } // There will be an extra file with no recovery blocks. fileallocations[recoveryfilecount].exponent = exponent; fileallocations[recoveryfilecount].count = 0; // Determine the format to use for filenames of recovery files char filenameformat[300]; { u32 limitLow = 0; u32 limitCount = 0; for (u32 filenumber=0; filenumber<=recoveryfilecount; filenumber++) { if (limitLow < fileallocations[filenumber].exponent) { limitLow = fileallocations[filenumber].exponent; } if (limitCount < fileallocations[filenumber].count) { limitCount = fileallocations[filenumber].count; } } u32 digitsLow = 1; for (u32 t=limitLow; t>=10; t/=10) { digitsLow++; } u32 digitsCount = 1; for (u32 t=limitCount; t>=10; t/=10) { digitsCount++; } sprintf(filenameformat, "%%s.vol%%0%dd+%%0%dd.par2", digitsLow, digitsCount); } // Set the filenames for (u32 filenumber=0; filenumber<recoveryfilecount; filenumber++) { char filename[300]; snprintf(filename, sizeof(filename), filenameformat, par2filename.c_str(), fileallocations[filenumber].exponent, fileallocations[filenumber].count); fileallocations[filenumber].filename = filename; } fileallocations[recoveryfilecount].filename = par2filename + ".par2"; } // Allocate the recovery files { recoveryfiles.resize(recoveryfilecount+1); // Allocate packets to the output files { const MD5Hash &setid = mainpacket->SetId(); vector<RecoveryPacket>::iterator recoverypacket = recoverypackets.begin(); vector<DiskFile>::iterator recoveryfile = recoveryfiles.begin(); vector<FileAllocation>::iterator fileallocation = fileallocations.begin(); // For each recovery file: while (recoveryfile != recoveryfiles.end()) { // How many recovery blocks in this file u32 count = fileallocation->count; // start at the beginning of the recovery file u64 offset = 0; if (count == 0) { // Write one set of critical packets list<CriticalPacket*>::const_iterator nextCriticalPacket = criticalpackets.begin(); while (nextCriticalPacket != criticalpackets.end()) { criticalpacketentries.push_back(CriticalPacketEntry(&*recoveryfile, offset, *nextCriticalPacket)); offset += (*nextCriticalPacket)->PacketLength(); ++nextCriticalPacket; } } else { // How many copies of each critical packet u32 copies = 0; for (u32 t=count; t>0; t>>=1) { copies++; } // Get ready to iterate through the critical packets u32 packetCount = 0; list<CriticalPacket*>::const_iterator nextCriticalPacket = criticalpackets.end(); // What is the first exponent u32 exponent = fileallocation->exponent; // Start allocating the recovery packets u32 limit = exponent + count; while (exponent < limit) { // Add the next recovery packet recoverypacket->Create(&*recoveryfile, offset, blocksize, exponent, setid); offset += recoverypacket->PacketLength(); ++recoverypacket; ++exponent; // Add some critical packets packetCount += copies * criticalpackets.size(); while (packetCount >= count) { if (nextCriticalPacket == criticalpackets.end()) nextCriticalPacket = criticalpackets.begin(); criticalpacketentries.push_back(CriticalPacketEntry(&*recoveryfile, offset, *nextCriticalPacket)); offset += (*nextCriticalPacket)->PacketLength(); ++nextCriticalPacket; packetCount -= count; } } } // Add one copy of the creator packet criticalpacketentries.push_back(CriticalPacketEntry(&*recoveryfile, offset, creatorpacket)); offset += creatorpacket->PacketLength(); // Create the file on disk and make it the required size if (!recoveryfile->Create(fileallocation->filename, offset)) return false; ++recoveryfile; ++fileallocation; } } } return true; } // Allocate memory buffers for reading and writing data to disk. bool Par2Creator::AllocateBuffers(void) { inputbuffer = new u8[chunksize]; outputbuffer = new u8[chunksize * recoveryblockcount]; if (inputbuffer == NULL || outputbuffer == NULL) { cerr << "Could not allocate buffer memory." << endl; return false; } return true; } // Compute the Reed Solomon matrix bool Par2Creator::ComputeRSMatrix(void) { // Set the number of input blocks if (!rs.SetInput(sourceblockcount)) return false; // Set the number of output blocks to be created if (!rs.SetOutput(false, (u16)firstrecoveryblock, (u16)firstrecoveryblock + (u16)(recoveryblockcount-1))) return false; // Compute the RS matrix if (!rs.Compute(noiselevel)) return false; return true; } // Read source data, process it through the RS matrix and write it to disk. bool Par2Creator::ProcessData(u64 blockoffset, size_t blocklength) { // Clear the output buffer memset(outputbuffer, 0, chunksize * recoveryblockcount); // If we have defered computation of the file hash and block crc and hashes // sourcefile and sourceindex will be used to update them during // the main recovery block computation vector<Par2CreatorSourceFile*>::iterator sourcefile = sourcefiles.begin(); u32 sourceindex = 0; vector<DataBlock>::iterator sourceblock; u32 inputblock; DiskFile *lastopenfile = NULL; // For each input block for ((sourceblock=sourceblocks.begin()),(inputblock=0); sourceblock != sourceblocks.end(); ++sourceblock, ++inputblock) { // Are we reading from a new file? if (lastopenfile != (*sourceblock).GetDiskFile()) { // Close the last file if (lastopenfile != NULL) { lastopenfile->Close(); } // Open the new file lastopenfile = (*sourceblock).GetDiskFile(); if (!lastopenfile->Open()) { return false; } } // Read data from the current input block if (!sourceblock->ReadData(blockoffset, blocklength, inputbuffer)) return false; if (deferhashcomputation) { assert(blockoffset == 0 && blocklength == blocksize); assert(sourcefile != sourcefiles.end()); (*sourcefile)->UpdateHashes(sourceindex, inputbuffer, blocklength); } // For each output block for (u32 outputblock=0; outputblock<recoveryblockcount; outputblock++) { // Select the appropriate part of the output buffer void *outbuf = &((u8*)outputbuffer)[chunksize * outputblock]; // Process the data through the RS matrix rs.Process(blocklength, inputblock, inputbuffer, outputblock, outbuf); if (noiselevel > CommandLine::nlQuiet) { // Update a progress indicator u32 oldfraction = (u32)(1000 * progress / totaldata); progress += blocklength; u32 newfraction = (u32)(1000 * progress / totaldata); if (oldfraction != newfraction) { cout << "Processing: " << newfraction/10 << '.' << newfraction%10 << "%\r" << flush; } } } // Work out which source file the next block belongs to if (++sourceindex >= (*sourcefile)->BlockCount()) { sourceindex = 0; ++sourcefile; } } // Close the last file if (lastopenfile != NULL) { lastopenfile->Close(); } if (noiselevel > CommandLine::nlQuiet) cout << "Writing recovery packets\r"; // For each output block for (u32 outputblock=0; outputblock<recoveryblockcount;outputblock++) { // Select the appropriate part of the output buffer char *outbuf = &((char*)outputbuffer)[chunksize * outputblock]; // Write the data to the recovery packet if (!recoverypackets[outputblock].WriteData(blockoffset, blocklength, outbuf)) return false; } if (noiselevel > CommandLine::nlQuiet) cout << "Wrote " << recoveryblockcount * blocklength << " bytes to disk" << endl; return true; } // Finish computation of the recovery packets and write the headers to disk. bool Par2Creator::WriteRecoveryPacketHeaders(void) { // For each recovery packet for (vector<RecoveryPacket>::iterator recoverypacket = recoverypackets.begin(); recoverypacket != recoverypackets.end(); ++recoverypacket) { // Finish the packet header and write it to disk if (!recoverypacket->WriteHeader()) return false; } return true; } bool Par2Creator::FinishFileHashComputation(void) { // If we defered the computation of the full file hash, then we finish it now if (deferhashcomputation) { // For each source file vector<Par2CreatorSourceFile*>::iterator sourcefile = sourcefiles.begin(); while (sourcefile != sourcefiles.end()) { (*sourcefile)->FinishHashes(); ++sourcefile; } } return true; } // Fill in all remaining details in the critical packets. bool Par2Creator::FinishCriticalPackets(void) { // Get the setid from the main packet const MD5Hash &setid = mainpacket->SetId(); for (list<CriticalPacket*>::iterator criticalpacket=criticalpackets.begin(); criticalpacket!=criticalpackets.end(); criticalpacket++) { // Store the setid in each of the critical packets // and compute the packet_hash of each one. (*criticalpacket)->FinishPacket(setid); } return true; } // Write all other critical packets to disk. bool Par2Creator::WriteCriticalPackets(void) { list<CriticalPacketEntry>::const_iterator packetentry = criticalpacketentries.begin(); // For each critical packet while (packetentry != criticalpacketentries.end()) { // Write it to disk if (!packetentry->WritePacket()) return false; ++packetentry; } return true; } // Close all files. bool Par2Creator::CloseFiles(void) { // // Close each source file. // for (vector<Par2CreatorSourceFile*>::iterator sourcefile = sourcefiles.begin(); // sourcefile != sourcefiles.end(); // ++sourcefile) // { // (*sourcefile)->Close(); // } // Close each recovery file. for (vector<DiskFile>::iterator recoveryfile = recoveryfiles.begin(); recoveryfile != recoveryfiles.end(); ++recoveryfile) { recoveryfile->Close(); } return true; }
jojje/par2cmdline-dir
par2creator.cpp
C++
gpl-2.0
31,351
<?php /** * english language file * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Christopher Smith <chris@jalakai.co.uk> * @author Matthias Schulte <dokuwiki@lupo49.de> * @author Schplurtz le Déboulonné <Schplurtz@laposte.net> */ // for admin plugins, the menu prompt to be displayed in the admin menu // if set here, the plugin doesn't need to override the getMenuText() method $lang['menu'] = 'Configuration Settings'; $lang['error'] = 'Settings not updated due to an invalid value, please review your changes and resubmit. <br />The incorrect value(s) will be shown surrounded by a red border.'; $lang['updated'] = 'Settings updated successfully.'; $lang['nochoice'] = '(no other choices available)'; $lang['locked'] = 'The settings file can not be updated, if this is unintentional, <br /> ensure the local settings file name and permissions are correct.'; $lang['danger'] = 'Danger: Changing this option could make your wiki and the configuration menu inaccessible.'; $lang['warning'] = 'Warning: Changing this option could cause unintended behaviour.'; $lang['security'] = 'Security Warning: Changing this option could present a security risk.'; /* --- Config Setting Headers --- */ $lang['_configuration_manager'] = 'Configuration Manager'; //same as heading in intro.txt $lang['_header_dokuwiki'] = 'DokuWiki'; $lang['_header_plugin'] = 'Plugin'; $lang['_header_template'] = 'Template'; $lang['_header_undefined'] = 'Undefined Settings'; /* --- Config Setting Groups --- */ $lang['_basic'] = 'Basic'; $lang['_display'] = 'Display'; $lang['_authentication'] = 'Authentication'; $lang['_anti_spam'] = 'Anti-Spam'; $lang['_editing'] = 'Editing'; $lang['_links'] = 'Links'; $lang['_media'] = 'Media'; $lang['_notifications'] = 'Notification'; $lang['_syndication'] = 'Syndication (RSS)'; $lang['_advanced'] = 'Advanced'; $lang['_network'] = 'Network'; /* --- Undefined Setting Messages --- */ $lang['_msg_setting_undefined'] = 'No setting metadata.'; $lang['_msg_setting_no_class'] = 'No setting class.'; $lang['_msg_setting_no_default'] = 'No default value.'; /* -------------------- Config Options --------------------------- */ /* Basic Settings */ $lang['title'] = 'Wiki title aka. your wiki\'s name'; $lang['start'] = 'Page name to use as the starting point for each namespace'; $lang['lang'] = 'Interface language'; $lang['template'] = 'Template aka. the design of the wiki.'; $lang['tagline'] = 'Tagline (if template supports it)'; $lang['sidebar'] = 'Sidebar page name (if template supports it), empty field disables the sidebar'; $lang['license'] = 'Under which license should your content be released?'; $lang['savedir'] = 'Directory for saving data'; $lang['basedir'] = 'Server path (eg. <code>/dokuwiki/</code>). Leave blank for autodetection.'; $lang['baseurl'] = 'Server URL (eg. <code>http://www.yourserver.com</code>). Leave blank for autodetection.'; $lang['cookiedir'] = 'Cookie path. Leave blank for using baseurl.'; $lang['dmode'] = 'Directory creation mode'; $lang['fmode'] = 'File creation mode'; $lang['allowdebug'] = 'Allow debug. <b>Disable if not needed!</b>'; /* Display Settings */ $lang['recent'] = 'Number of entries per page in the recent changes'; $lang['recent_days'] = 'How many recent changes to keep (days)'; $lang['breadcrumbs'] = 'Number of "trace" breadcrumbs. Set to 0 to disable.'; $lang['youarehere'] = 'Use hierarchical breadcrumbs (you probably want to disable the above option then)'; $lang['fullpath'] = 'Reveal full path of pages in the footer'; $lang['typography'] = 'Do typographical replacements'; $lang['dformat'] = 'Date format (see PHP\'s <a href="http://php.net/strftime">strftime</a> function)'; $lang['signature'] = 'What to insert with the signature button in the editor'; $lang['showuseras'] = 'What to display when showing the user that last edited a page'; $lang['toptoclevel'] = 'Top level for table of contents'; $lang['tocminheads'] = 'Minimum amount of headlines that determines whether the TOC is built'; $lang['maxtoclevel'] = 'Maximum level for table of contents'; $lang['maxseclevel'] = 'Maximum section edit level'; $lang['camelcase'] = 'Use CamelCase for links'; $lang['deaccent'] = 'How to clean pagenames'; $lang['useheading'] = 'Use first heading for pagenames'; $lang['sneaky_index'] = 'By default, DokuWiki will show all namespaces in the sitemap. Enabling this option will hide those where the user doesn\'t have read permissions. This might result in hiding of accessable subnamespaces which may make the index unusable with certain ACL setups.'; $lang['hidepages'] = 'Hide pages matching this regular expression from search, the sitemap and other automatic indexes'; /* Authentication Settings */ $lang['useacl'] = 'Use access control lists'; $lang['autopasswd'] = 'Autogenerate passwords'; $lang['authtype'] = 'Authentication backend'; $lang['passcrypt'] = 'Password encryption method'; $lang['defaultgroup']= 'Default group, all new users will be placed in this group'; $lang['superuser'] = 'Superuser - group, user or comma separated list user1,@group1,user2 with full access to all pages and functions regardless of the ACL settings'; $lang['manager'] = 'Manager - group, user or comma separated list user1,@group1,user2 with access to certain management functions'; $lang['profileconfirm'] = 'Confirm profile changes with password'; $lang['rememberme'] = 'Allow permanent login cookies (remember me)'; $lang['disableactions'] = 'Disable DokuWiki actions'; $lang['disableactions_check'] = 'Check'; $lang['disableactions_subscription'] = 'Subscribe/Unsubscribe'; $lang['disableactions_wikicode'] = 'View source/Export Raw'; $lang['disableactions_profile_delete'] = 'Delete Own Account'; $lang['disableactions_other'] = 'Other actions (comma separated)'; $lang['disableactions_rss'] = 'XML Syndication (RSS)'; $lang['auth_security_timeout'] = 'Authentication Security Timeout (seconds)'; $lang['securecookie'] = 'Should cookies set via HTTPS only be sent via HTTPS by the browser? Disable this option when only the login of your wiki is secured with SSL but browsing the wiki is done unsecured.'; $lang['remote'] = 'Enable the remote API system. This allows other applications to access the wiki via XML-RPC or other mechanisms.'; $lang['remoteuser'] = 'Restrict remote API access to the comma separated groups or users given here. Leave empty to give access to everyone.'; /* Anti-Spam Settings */ $lang['usewordblock']= 'Block spam based on wordlist'; $lang['relnofollow'] = 'Use rel="nofollow" on external links'; $lang['indexdelay'] = 'Time delay before indexing (sec)'; $lang['mailguard'] = 'Obfuscate email addresses'; $lang['iexssprotect']= 'Check uploaded files for possibly malicious JavaScript or HTML code'; /* Editing Settings */ $lang['usedraft'] = 'Automatically save a draft while editing'; $lang['htmlok'] = 'Allow embedded HTML'; $lang['phpok'] = 'Allow embedded PHP'; $lang['locktime'] = 'Maximum age for lock files (sec)'; $lang['cachetime'] = 'Maximum age for cache (sec)'; /* Link settings */ $lang['target____wiki'] = 'Target window for internal links'; $lang['target____interwiki'] = 'Target window for interwiki links'; $lang['target____extern'] = 'Target window for external links'; $lang['target____media'] = 'Target window for media links'; $lang['target____windows'] = 'Target window for windows links'; /* Media Settings */ $lang['mediarevisions'] = 'Enable Mediarevisions?'; $lang['refcheck'] = 'Check if a media file is still in use before deleting it'; $lang['gdlib'] = 'GD Lib version'; $lang['im_convert'] = 'Path to ImageMagick\'s convert tool'; $lang['jpg_quality'] = 'JPG compression quality (0-100)'; $lang['fetchsize'] = 'Maximum size (bytes) fetch.php may download from external URLs, eg. to cache and resize external images.'; /* Notification Settings */ $lang['subscribers'] = 'Allow users to subscribe to page changes by email'; $lang['subscribe_time'] = 'Time after which subscription lists and digests are sent (sec); This should be smaller than the time specified in recent_days.'; $lang['notify'] = 'Always send change notifications to this email address'; $lang['registernotify'] = 'Always send info on newly registered users to this email address'; $lang['mailfrom'] = 'Sender email address to use for automatic mails'; $lang['mailreturnpath'] = 'Recipient email address for non delivery notifications'; $lang['mailprefix'] = 'Email subject prefix to use for automatic mails. Leave blank to use the wiki title'; $lang['htmlmail'] = 'Send better looking, but larger in size HTML multipart emails. Disable for plain text only mails.'; /* Syndication Settings */ $lang['sitemap'] = 'Generate Google sitemap this often (in days). 0 to disable'; $lang['rss_type'] = 'XML feed type'; $lang['rss_linkto'] = 'XML feed links to'; $lang['rss_content'] = 'What to display in the XML feed items?'; $lang['rss_update'] = 'XML feed update interval (sec)'; $lang['rss_show_summary'] = 'XML feed show summary in title'; $lang['rss_media'] = 'What kind of changes should be listed in the XML feed?'; $lang['rss_media_o_both'] = 'both'; $lang['rss_media_o_pages'] = 'pages'; $lang['rss_media_o_media'] = 'media'; /* Advanced Options */ $lang['updatecheck'] = 'Check for updates and security warnings? DokuWiki needs to contact update.dokuwiki.org for this feature.'; $lang['userewrite'] = 'Use nice URLs'; $lang['useslash'] = 'Use slash as namespace separator in URLs'; $lang['sepchar'] = 'Page name word separator'; $lang['canonical'] = 'Use fully canonical URLs'; $lang['fnencode'] = 'Method for encoding non-ASCII filenames.'; $lang['autoplural'] = 'Check for plural forms in links'; $lang['compression'] = 'Compression method for attic files'; $lang['gzip_output'] = 'Use gzip Content-Encoding for xhtml'; $lang['compress'] = 'Compact CSS and javascript output'; $lang['cssdatauri'] = 'Size in bytes up to which images referenced in CSS files should be embedded right into the stylesheet to reduce HTTP request header overhead. <code>400</code> to <code>600</code> bytes is a good value. Set <code>0</code> to disable.'; $lang['send404'] = 'Send "HTTP 404/Page Not Found" for non existing pages'; $lang['broken_iua'] = 'Is the ignore_user_abort function broken on your system? This could cause a non working search index. IIS+PHP/CGI is known to be broken. See <a href="http://bugs.dokuwiki.org/?do=details&amp;task_id=852">Bug 852</a> for more info.'; $lang['xsendfile'] = 'Use the X-Sendfile header to let the webserver deliver static files? Your webserver needs to support this.'; $lang['renderer_xhtml'] = 'Renderer to use for main (xhtml) wiki output'; $lang['renderer__core'] = '%s (dokuwiki core)'; $lang['renderer__plugin'] = '%s (plugin)'; $lang['search_nslimit'] = 'Limit the search to the current X namespaces. When a search is executed from a page within a deeper namespace, the first X namespaces will be added as filter'; $lang['search_fragment'] = 'Specify the default fragment search behavior'; $lang['search_fragment_o_exact'] = 'exact'; $lang['search_fragment_o_starts_with'] = 'starts with'; $lang['search_fragment_o_ends_with'] = 'ends with'; $lang['search_fragment_o_contains'] = 'contains'; /* Network Options */ $lang['dnslookups'] = 'DokuWiki will lookup hostnames for remote IP addresses of users editing pages. If you have a slow or non working DNS server or don\'t want this feature, disable this option'; $lang['jquerycdn'] = 'Should the jQuery and jQuery UI script files be loaded from a CDN? This adds additional HTTP requests, but files may load faster and users may have them cached already.'; /* jQuery CDN options */ $lang['jquerycdn_o_0'] = 'No CDN, local delivery only'; $lang['jquerycdn_o_jquery'] = 'CDN at code.jquery.com'; $lang['jquerycdn_o_cdnjs'] = 'CDN at cdnjs.com'; /* Proxy Options */ $lang['proxy____host'] = 'Proxy servername'; $lang['proxy____port'] = 'Proxy port'; $lang['proxy____user'] = 'Proxy user name'; $lang['proxy____pass'] = 'Proxy password'; $lang['proxy____ssl'] = 'Use SSL to connect to proxy'; $lang['proxy____except'] = 'Regular expression to match URLs for which the proxy should be skipped.'; /* Safemode Hack */ $lang['safemodehack'] = 'Enable safemode hack'; $lang['ftp____host'] = 'FTP server for safemode hack'; $lang['ftp____port'] = 'FTP port for safemode hack'; $lang['ftp____user'] = 'FTP user name for safemode hack'; $lang['ftp____pass'] = 'FTP password for safemode hack'; $lang['ftp____root'] = 'FTP root directory for safemode hack'; /* License Options */ $lang['license_o_'] = 'None chosen'; /* typography options */ $lang['typography_o_0'] = 'none'; $lang['typography_o_1'] = 'excluding single quotes'; $lang['typography_o_2'] = 'including single quotes (might not always work)'; /* userewrite options */ $lang['userewrite_o_0'] = 'none'; $lang['userewrite_o_1'] = '.htaccess'; $lang['userewrite_o_2'] = 'DokuWiki internal'; /* deaccent options */ $lang['deaccent_o_0'] = 'off'; $lang['deaccent_o_1'] = 'remove accents'; $lang['deaccent_o_2'] = 'romanize'; /* gdlib options */ $lang['gdlib_o_0'] = 'GD Lib not available'; $lang['gdlib_o_1'] = 'Version 1.x'; $lang['gdlib_o_2'] = 'Autodetection'; /* rss_type options */ $lang['rss_type_o_rss'] = 'RSS 0.91'; $lang['rss_type_o_rss1'] = 'RSS 1.0'; $lang['rss_type_o_rss2'] = 'RSS 2.0'; $lang['rss_type_o_atom'] = 'Atom 0.3'; $lang['rss_type_o_atom1'] = 'Atom 1.0'; /* rss_content options */ $lang['rss_content_o_abstract'] = 'Abstract'; $lang['rss_content_o_diff'] = 'Unified Diff'; $lang['rss_content_o_htmldiff'] = 'HTML formatted diff table'; $lang['rss_content_o_html'] = 'Full HTML page content'; /* rss_linkto options */ $lang['rss_linkto_o_diff'] = 'difference view'; $lang['rss_linkto_o_page'] = 'the revised page'; $lang['rss_linkto_o_rev'] = 'list of revisions'; $lang['rss_linkto_o_current'] = 'the current page'; /* compression options */ $lang['compression_o_0'] = 'none'; $lang['compression_o_gz'] = 'gzip'; $lang['compression_o_bz2'] = 'bz2'; /* xsendfile header */ $lang['xsendfile_o_0'] = "don't use"; $lang['xsendfile_o_1'] = 'Proprietary lighttpd header (before release 1.5)'; $lang['xsendfile_o_2'] = 'Standard X-Sendfile header'; $lang['xsendfile_o_3'] = 'Proprietary Nginx X-Accel-Redirect header'; /* Display user info */ $lang['showuseras_o_loginname'] = 'Login name'; $lang['showuseras_o_username'] = "User's full name"; $lang['showuseras_o_username_link'] = "User's full name as interwiki user link"; $lang['showuseras_o_email'] = "User's e-mail addresss (obfuscated according to mailguard setting)"; $lang['showuseras_o_email_link'] = "User's e-mail addresss as a mailto: link"; /* useheading options */ $lang['useheading_o_0'] = 'Never'; $lang['useheading_o_navigation'] = 'Navigation Only'; $lang['useheading_o_content'] = 'Wiki Content Only'; $lang['useheading_o_1'] = 'Always'; $lang['readdircache'] = 'Maximum age for readdir cache (sec)';
randonnerleger/wiki_new
lib/plugins/config/lang/en/lang.php
PHP
gpl-2.0
15,290
<div class="weather"> <p><strong><?php print $weather->real_name; ?></strong></p> <div style="text-align:center;"> <img src="<?php print $weather->image_filename; ?>" <?php print $weather->image_size; ?> alt="<?php print $weather->condition; ?>" title="<?php print $weather->condition; ?>" /> </div> <ul> <li><?php print $weather->condition; ?></li> <?php if (isset($weather->temperature)): ?> <?php if (isset($weather->windchill)): ?> <li><?php print t("Temperature: !temperature1, feels like !temperature2", array( '!temperature1' => $weather->temperature, '!temperature2' => $weather->windchill )); ?></li> <?php else: ?> <li><?php print t("Temperature: !temperature", array('!temperature' => $weather->temperature)); ?></li> <?php endif ?> <?php endif ?> <?php if (isset($weather->wind)): ?> <li><?php print t('Wind: !wind', array('!wind' => $weather->wind)); ?></li> <?php endif ?> <?php if (isset($weather->pressure)): ?> <li><?php print t('Pressure: !pressure', array('!pressure' => $weather->pressure)); ?></li> <?php endif ?> <?php if (isset($weather->rel_humidity)): ?> <li><?php print t('Rel. Humidity: !rel_humidity', array('!rel_humidity' => $weather->rel_humidity)); ?></li> <?php endif ?> <?php if (isset($weather->visibility)): ?> <li><?php print t('Visibility: !visibility', array('!visibility' => $weather->visibility)); ?></li> <?php endif ?> <?php if (isset($weather->sunrise)): ?> <li><?php print $weather->sunrise; ?></li> <?php endif ?> <?php if (isset($weather->sunset)): ?> <li><?php print $weather->sunset; ?></li> <?php endif ?> <?php if (isset($weather->metar)): ?> <li><?php print t('METAR data: !metar', array('!metar' => '<pre>'. wordwrap($weather->metar, 20) .'</pre>')); ?></li> <?php endif ?> </ul> <?php if (isset($weather->station)): ?> <small> <?php print t('Location of this weather station:'); ?><br /> <?php print $weather->station; ?> </small> <br /> <?php endif ?> <?php if (isset($weather->legal)): ?> <small> <?php print $weather->legal; ?> </small> <br /> <?php endif ?> <?php if (isset($weather->reported_on)): ?> <small> <?php print t('Reported on:'); ?><br /> <?php print $weather->reported_on; ?> </small> <?php endif ?> </div>
shieldsdesignstudio/lefkowitz
sites/all/modules/weather/weather.tpl.php
PHP
gpl-2.0
2,487
# # Karaka Skype-XMPP Gateway: Python package metadata # <http://www.vipadia.com/products/karaka.html> # # Copyright (C) 2008-2009 Vipadia Limited # Richard Mortier <mort@vipadia.com> # Neil Stratford <neils@vipadia.com> # ## This program is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License version ## 2 as published by the Free Software Foundation. ## This program is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License version 2 for more details. ## You should have received a copy of the GNU General Public License ## version 2 along with this program; if not, write to the Free ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ## MA 02110-1301, USA.
gaka13/karaka
karaka/api/__init__.py
Python
gpl-2.0
896
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using STSdb4.General.Extensions; namespace STSdb4.Data { public class DataToObjects : IToObjects<IData> { public readonly Func<IData, object[]> to; public readonly Func<object[], IData> from; public readonly Type Type; public readonly Func<Type, MemberInfo, int> MembersOrder; public DataToObjects(Type type, Func<Type, MemberInfo, int> membersOrder = null) { if (!DataType.IsPrimitiveType(type) && !type.HasDefaultConstructor()) throw new NotSupportedException("No default constructor."); bool isSupported = DataTypeUtils.IsAllPrimitive(type); if (!isSupported) throw new NotSupportedException("Not all types are primitive."); Type = type; MembersOrder = membersOrder; to = CreateToMethod().Compile(); from = CreateFromMethod().Compile(); } public Expression<Func<IData, object[]>> CreateToMethod() { var data = Expression.Parameter(typeof(IData), "data"); var d = Expression.Variable(typeof(Data<>).MakeGenericType(Type), "d"); var body = Expression.Block(new ParameterExpression[] { d }, Expression.Assign(d, Expression.Convert(data, d.Type)), ValueToObjectsHelper.ToObjects(d.Value(), MembersOrder)); return Expression.Lambda<Func<IData, object[]>>(body, data); } public Expression<Func<object[], IData>> CreateFromMethod() { var objectArray = Expression.Parameter(typeof(object[]), "item"); var data = Expression.Variable(typeof(Data<>).MakeGenericType(Type)); List<Expression> list = new List<Expression>(); list.Add(Expression.Assign(data, Expression.New(data.Type.GetConstructor(new Type[] { })))); if (!DataType.IsPrimitiveType(Type)) list.Add(Expression.Assign(data.Value(), Expression.New(data.Value().Type.GetConstructor(new Type[] { })))); list.Add(ValueToObjectsHelper.FromObjects(data.Value(), objectArray, MembersOrder)); list.Add(Expression.Label(Expression.Label(typeof(IData)), data)); var body = Expression.Block(typeof(IData), new ParameterExpression[] { data }, list); return Expression.Lambda<Func<object[], IData>>(body, objectArray); } public object[] To(IData value1) { return to(value1); } public IData From(object[] value2) { return from(value2); } } }
Injac/STSdb4
STSdb4/Data/DataToObjects.cs
C#
gpl-2.0
2,719
/** * @copyright 2010-2015, The Titon Project * @license http://opensource.org/licenses/BSD-3-Clause * @link http://titon.io */ define([ 'jquery', './toolkit' ], function($, Toolkit) { // Empty class to extend from var Class = Toolkit.Class = function() {}; // Flag to determine if a constructor is initializing var constructing = false; /** * Very basic method for allowing functions to inherit functionality through the prototype. * * @param {Object} properties * @param {Object} options * @returns {Function} */ Class.extend = function(properties, options) { constructing = true; var prototype = new this(); constructing = false; // Inherit the prototype and merge properties $.extend(prototype, properties); // Fetch the constructor function before setting the prototype var constructor = prototype.constructor; // Class interface function Class() { // Exit constructing if being applied as prototype if (constructing) { return; } // Reset (clone) the array and object properties else they will be referenced between instances for (var key in this) { var value = this[key], type = $.type(value); if (type === 'array') { this[key] = value.slice(0); // Clone array } else if (type === 'object') { this[key] = $.extend(true, {}, value); // Clone object } } // Set the UID and increase global count this.uid = Class.count += 1; // Generate the CSS class name and attribute/event name based off the plugin name var name = this.name; if (name) { this.cssClass = name.replace(/[A-Z]/g, function(match) { return ('-' + match.charAt(0).toLowerCase()); }).slice(1); // Generate an attribute and event key name based off the plugin name this.keyName = name.charAt(0).toLowerCase() + name.slice(1); } // Trigger constructor if (constructor) { constructor.apply(this, arguments); } } // Inherit the prototype Class.prototype = prototype; Class.prototype.constructor = constructor || Class; // Inherit and set default options Class.options = $.extend(true, {}, this.options || {}, options || {}); // Inherit the extend method Class.extend = this.extend; // Count of total instances Class.count = 0; return Class; }; return Class; });
localymine/multisite
wp-content/themes/kodomo/html/toolkit-3.0/js/class.js
JavaScript
gpl-2.0
2,561
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "nstencil_half_bin_3d_newtoff.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ NStencilHalfBin3dNewtoff::NStencilHalfBin3dNewtoff(LAMMPS *lmp) : NStencil(lmp) {} /* ---------------------------------------------------------------------- create stencil based on bin geometry and cutoff ------------------------------------------------------------------------- */ void NStencilHalfBin3dNewtoff::create() { int i,j,k; nstencil = 0; for (k = -sz; k <= sz; k++) for (j = -sy; j <= sy; j++) for (i = -sx; i <= sx; i++) if (bin_distance(i,j,k) < cutneighmaxsq) stencil[nstencil++] = k*mbiny*mbinx + j*mbinx + i; }
Pakketeretet2/lammps
src/nstencil_half_bin_3d_newtoff.cpp
C++
gpl-2.0
1,347
/* This file is part of the KDE project Copyright (C) 2008 David Faure <faure@kde.org> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <konqmisc.h> #include <khtml_part.h> #include <khtmlview.h> #include <ktemporaryfile.h> #include <kstandarddirs.h> #include <ktoolbar.h> #include <kdebug.h> #include <ksycoca.h> #include <QScrollArea> #include <qtest_kde.h> #include <qtest_gui.h> #include <konqmainwindow.h> #include <konqviewmanager.h> #include <konqview.h> #include <konqsessionmanager.h> #include <QObject> class KonqHtmlTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase() { KonqSessionManager::self()->disableAutosave(); //qRegisterMetaType<KonqView *>("KonqView*"); // Ensure the tests use KHTML, not kwebkitpart // This code is inspired by settings/konqhtml/generalopts.cpp KSharedConfig::Ptr profile = KSharedConfig::openConfig("mimeapps.list", KConfig::NoGlobals, "xdgdata-apps"); KConfigGroup addedServices(profile, "Added KDE Service Associations"); Q_FOREACH(const QString& mimeType, QStringList() << "text/html" << "application/xhtml+xml" << "application/xml") { QStringList services = addedServices.readXdgListEntry(mimeType); services.removeAll("khtml.desktop"); services.prepend("khtml.desktop"); // make it the preferred one addedServices.writeXdgListEntry(mimeType, services); } profile->sync(); // kbuildsycoca is the one reading mimeapps.list, so we need to run it now QProcess::execute(KGlobal::dirs()->findExe(KBUILDSYCOCA_EXENAME)); } void cleanupTestCase() { // in case some test broke, don't assert in khtmlglobal... deleteAllMainWindows(); } void loadSimpleHtml() { KonqMainWindow mainWindow; // we specify the mimetype so that we don't have to wait for a KonqRun mainWindow.openUrl(0, KUrl("data:text/html, <p>Hello World</p>"), "text/html"); KonqView* view = mainWindow.currentView(); QVERIFY(view); QVERIFY(view->part()); QVERIFY(QTest::kWaitForSignal(view, SIGNAL(viewCompleted(KonqView*)), 20000)); QCOMPARE(view->serviceType(), QString("text/html")); //KHTMLPart* part = qobject_cast<KHTMLPart *>(view->part()); //QVERIFY(part); } void loadDirectory() // #164495 { KonqMainWindow mainWindow; mainWindow.openUrl(0, KUrl(QDir::homePath()), "text/html"); KonqView* view = mainWindow.currentView(); kDebug() << "Waiting for first completed signal"; QVERIFY(QTest::kWaitForSignal(view, SIGNAL(viewCompleted(KonqView*)), 20000)); // error calls openUrlRequest kDebug() << "Waiting for first second signal"; QVERIFY(QTest::kWaitForSignal(view, SIGNAL(viewCompleted(KonqView*)), 20000)); // which then opens the right part QCOMPARE(view->serviceType(), QString("inode/directory")); } void rightClickClose() // #149736 { QPointer<KonqMainWindow> mainWindow = new KonqMainWindow; // we specify the mimetype so that we don't have to wait for a KonqRun mainWindow->openUrl(0, KUrl( "data:text/html, <script type=\"text/javascript\">" "function closeMe() { window.close(); } " "document.onmousedown = closeMe; " "</script>"), QString("text/html")); QPointer<KonqView> view = mainWindow->currentView(); QVERIFY(view); QVERIFY(QTest::kWaitForSignal(view, SIGNAL(viewCompleted(KonqView*)), 10000)); QWidget* widget = partWidget(view); qDebug() << "Clicking on" << widget; QTest::mousePress(widget, Qt::RightButton); qApp->processEvents(); QVERIFY(!view); // deleted QVERIFY(!mainWindow); // the whole window gets deleted, in fact } void windowOpen() { // Simple test for window.open in a onmousedown handler. // We have to use the same protocol for both the orig and dest urls. // KAuthorized would forbid a data: URL to redirect to a file: URL for instance. KTemporaryFile tempFile; QVERIFY(tempFile.open()); tempFile.write("<script>document.write(\"Opener=\" + window.opener);</script>"); KTemporaryFile origTempFile; QVERIFY(origTempFile.open()); origTempFile.write( "<html><script>" "function openWindow() { window.open('" + KUrl(tempFile.fileName()).url().toUtf8() + "'); } " "document.onmousedown = openWindow; " "</script>" ); tempFile.close(); const QString origFile = origTempFile.fileName(); origTempFile.close(); KonqMainWindow* mainWindow = new KonqMainWindow; const QString profile = KStandardDirs::locate("data", "konqueror/profiles/webbrowsing"); mainWindow->viewManager()->loadViewProfileFromFile(profile, "webbrowsing", KUrl(origFile)); QCOMPARE(KMainWindow::memberList().count(), 1); KonqView* view = mainWindow->currentView(); QVERIFY(view); QVERIFY(QTest::kWaitForSignal(view, SIGNAL(viewCompleted(KonqView*)), 10000)); qApp->processEvents(); QWidget* widget = partWidget(view); kDebug() << "Clicking on the khtmlview"; QTest::mousePress(widget, Qt::LeftButton); qApp->processEvents(); // openurlrequestdelayed qApp->processEvents(); // browserrun hideAllMainWindows(); // TODO: why does it appear nonetheless? hiding too early? hiding too late? QTest::qWait(100); // just in case there's more delayed calls :) // Did it open a window? QCOMPARE(KMainWindow::memberList().count(), 2); KMainWindow* newWindow = KMainWindow::memberList().last(); QVERIFY(newWindow != mainWindow); compareToolbarSettings(mainWindow, newWindow); // Does the window contain exactly one tab? QTabWidget* tab = newWindow->findChild<QTabWidget*>(); QVERIFY(tab); QCOMPARE(tab->count(), 1); KonqFrame* frame = qobject_cast<KonqFrame *>(tab->widget(0)); QVERIFY(frame); QVERIFY(!frame->childView()->isLoading()); KHTMLPart* part = qobject_cast<KHTMLPart *>(frame->part()); QVERIFY(part); part->selectAll(); const QString text = part->selectedText(); QCOMPARE(text, QString("Opener=[object Window]")); deleteAllMainWindows(); } void testJSError() { // JS errors appear in a statusbar label, and deleting the frame first // would lead to double deletion (#228255) KonqMainWindow mainWindow; // we specify the mimetype so that we don't have to wait for a KonqRun mainWindow.openUrl(0, KUrl("data:text/html, <script>window.foo=bar</script><p>Hello World</p>"), "text/html"); KonqView* view = mainWindow.currentView(); QVERIFY(view); QVERIFY(view->part()); QVERIFY(QTest::kWaitForSignal(view, SIGNAL(viewCompleted(KonqView*)), 20000)); QCOMPARE(view->serviceType(), QString("text/html")); delete view->part(); } private: // Return the main widget for the given KonqView; used for clicking onto it static QWidget* partWidget(KonqView* view) { QWidget* widget = view->part()->widget(); KHTMLPart* htmlPart = qobject_cast<KHTMLPart *>(view->part()); if (htmlPart) widget = htmlPart->view(); // khtmlview != widget() nowadays, due to find bar if (QScrollArea* scrollArea = qobject_cast<QScrollArea*>(widget)) widget = scrollArea->widget(); return widget; } // Delete all KonqMainWindows static void deleteAllMainWindows() { const QList<KMainWindow*> windows = KMainWindow::memberList(); qDeleteAll(windows); } void compareToolbarSettings(KMainWindow* mainWindow, KMainWindow* newWindow) { QVERIFY(mainWindow != newWindow); KToolBar* firstToolBar = mainWindow->toolBars().first(); QVERIFY(firstToolBar); KToolBar* newFirstToolBar = newWindow->toolBars().first(); QVERIFY(newFirstToolBar); QCOMPARE(firstToolBar->toolButtonStyle(), newFirstToolBar->toolButtonStyle()); } static void hideAllMainWindows() { const QList<KMainWindow*> windows = KMainWindow::memberList(); kDebug() << "hiding" << windows.count() << "windows"; Q_FOREACH(KMainWindow* window, windows) window->hide(); } }; QTEST_KDEMAIN_WITH_COMPONENTNAME( KonqHtmlTest, GUI, "konqueror" ) #include "konqhtmltest.moc"
blue-shell/folderview
konqueror/src/tests/konqhtmltest.cpp
C++
gpl-2.0
9,297
<?php /** * @version $Id: layout.php 15522 2013-11-13 21:47:07Z kevin $ * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2015 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only * * Gantry uses the Joomla Framework (http://www.joomla.org), a GNU/GPLv2 content management system * */ // no direct access defined('_JEXEC') or die('Restricted access'); class GantrySplitmenuLayout extends AbstractRokMenuLayout { protected $theme_path; protected $params; static $jsLoaded = false; private $activeid; public function __construct(&$args) { parent::__construct($args); global $gantry; $theme_rel_path = "/html/mod_roknavmenu/themes/gantry-splitmenu"; $this->theme_path = $gantry->templatePath . $theme_rel_path; $this->args['theme_path'] = $this->theme_path; $this->args['theme_rel_path'] = $gantry->templateUrl. $theme_rel_path; $this->args['theme_url'] = $this->args['theme_rel_path']; $this->args['responsive-menu'] = $args['responsive-menu']; } public function stageHeader() { global $gantry; //don't include class_sfx on 3rd level menu $this->args['class_sfx'] = (array_key_exists('startlevel', $this->args) && $this->args['startLevel']==1) ? '' : $this->args['class_sfx']; $this->activeid = (array_key_exists('splitmenu_enable_current_id', $this->args) && $this->args['splitmenu_enable_current_id']== 0) ? false : true; JHtml::_('behavior.framework', true); if (!self::$jsLoaded && $gantry->get('layout-mode', 'responsive') == 'responsive'){ if (!($gantry->browser->name == 'ie' && $gantry->browser->shortver < 9)){ $gantry->addScript($gantry->baseUrl . 'modules/mod_roknavmenu/themes/default/js/rokmediaqueries.js'); if ($this->args['responsive-menu'] == 'selectbox') { $gantry->addScript($gantry->baseUrl . 'modules/mod_roknavmenu/themes/default/js/responsive.js'); $gantry->addScript($gantry->baseUrl . 'modules/mod_roknavmenu/themes/default/js/responsive-selectbox.js'); } else if (file_exists($gantry->basePath . '/modules/mod_roknavmenu/themes/default/js/sidemenu.js') && ($this->args['responsive-menu'] == 'panel')) { $gantry->addScript($gantry->baseUrl . 'modules/mod_roknavmenu/themes/default/js/sidemenu.js'); } } self::$jsLoaded = true; } $gantry->addLess('menu.less', 'menu.css', 1, array('headerstyle'=>$gantry->get('headerstyle','dark'), 'menuHoverColor'=>$gantry->get('linkcolor'))); // no media queries for IE8 so we compile and load the hovers if ($gantry->browser->name == 'ie' && $gantry->browser->shortver < 9){ $gantry->addLess('menu-hovers.less', 'menu-hovers.css', 1, array('headerstyle'=>$gantry->get('headerstyle','dark'), 'menuHoverColor'=>$gantry->get('linkcolor'))); } } protected function renderItem(JoomlaRokMenuNode &$item, RokMenuNodeTree &$menu) { global $gantry; $item_params = $item->getParams(); //not so elegant solution to add subtext $item_subtext = $item_params->get('splitmenu_item_subtext',''); if ($item_subtext=='') $item_subtext = false; else $item->addLinkClass('subtext'); //get custom image $custom_image = $item_params->get('splitmenu_customimage'); //get the custom icon $custom_icon = $item_params->get('splitmenu_customicon'); //get the custom class $custom_class = $item_params->get('splitmenu_customclass'); //add default link class $item->addLinkClass('item'); if ($custom_image && $custom_image != -1) $item->addLinkClass('image'); if ($custom_icon && $custom_icon != -1) $item->addLinkClass('icon'); if ($custom_class != '') $item->addListItemClass($custom_class); if ($item_params->get('splitmenu_menu_entry_type','normal') == 'normal'): if ($item->getType() != 'menuitem') { $item->setLink('javascript:void(0);'); } ?> <li <?php if($item->hasListItemClasses()) : ?>class="<?php echo $item->getListItemClasses()?>"<?php endif;?> <?php if($item->hasCssId() && $this->activeid):?>id="<?php echo $item->getCssId();?>"<?php endif;?>> <a <?php if($item->hasLinkClasses()):?>class="<?php echo $item->getLinkClasses();?>"<?php endif;?> <?php if($item->hasLink()):?>href="<?php echo $item->getLink();?>"<?php endif;?> <?php if($item->hasTarget()):?>target="<?php echo $item->getTarget();?>"<?php endif;?> <?php if ($item->hasAttribute('onclick')): ?>onclick="<?php echo $item->getAttribute('onclick'); ?>"<?php endif; ?><?php if ($item->hasLinkAttribs()): ?> <?php echo $item->getLinkAttribs(); ?><?php endif; ?>> <?php if ($custom_image && $custom_image != -1) :?> <img class="menu-image" src="<?php echo $gantry->templateUrl."/images/icons/".$custom_image; ?>" alt="<?php echo $custom_image; ?>" /> <?php endif; ?> <?php if ($custom_icon && $custom_icon != -1) { echo '<i class="' . $custom_icon . '">' . $item->getTitle() . '</i>'; } else { echo $item->getTitle(); } if (!empty($item_subtext)) { echo '<em>'. $item_subtext . '</em>'; } ?> </a> <?php if ($item->hasChildren()): ?> <ul class="level<?php echo intval($item->getLevel())+2; ?>"> <?php foreach ($item->getChildren() as $child) : ?> <?php $this->renderItem($child, $menu); ?> <?php endforeach; ?> </ul> <?php endif; ?> </li> <?php else: $item->addListItemClass('menu-module'); $module_id = $item_params->get('splitmenu_menu_module'); $menu_module = $this->getModule($module_id); $document = JFactory::getDocument(); $renderer = $document->loadRenderer('module'); $params = array('style'=> 'splitmenu'); $module_content = $renderer->render($menu_module, $params); ?> <li <?php if ($item->hasListItemClasses()) : ?>class="<?php echo $item->getListItemClasses()?>"<?php endif;?> <?php if ($item->hasCssId() && $this->activeid): ?>id="<?php echo $item->getCssId();?>"<?php endif;?>> <?php echo $module_content; ?> </li> <?php endif; } function getModule ($id=0, $name='') { $modules =& RokNavMenu::loadModules(); $total = count($modules); for ($i = 0; $i < $total; $i++) { // Match the name of the module if ($modules[$i]->id == $id || $modules[$i]->name == $name) { return $modules[$i]; } } return null; } public function curPageURL($link) { $pageURL = 'http'; if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {$pageURL .= "s";} $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; } $replace = str_replace('&', '&amp;', (preg_match("/^http/", $link) ? $pageURL : $_SERVER["REQUEST_URI"])); return $replace == $link || $replace == $link . 'index.php'; } public function renderMenu(&$menu) { ob_start(); $menuname = (isset($this->args['style']) && $this->args['style'] == 'mainmenu') ? 'gf-menu gf-splitmenu' : 'menu'; ?> <?php if ($menu->getChildren()) : ?> <?php if (isset($this->args['style']) && $this->args['style'] == 'mainmenu'): ?> <div class="gf-menu-device-container"></div> <?php endif; ?> <ul class="<?php echo $menuname; ?> l1 <?php echo $this->args['class_sfx']; ?>" <?php if(array_key_exists('tag_id',$this->args)):?>id="<?php echo $this->args['tag_id'];?>"<?php endif;?>> <?php foreach ($menu->getChildren() as $item) : ?> <?php $this->renderItem($item, $menu); ?> <?php endforeach; ?> </ul> <?php endif; ?> <?php return ob_get_clean(); } }
bobozhangshao/HeartCare
templates/heartcare_gantry4/html/mod_roknavmenu/themes/gantry-splitmenu/layout.php
PHP
gpl-2.0
8,317
/**************************************************************************** ** ** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the QtGui module 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 "qwininputcontext_p.h" #include "qinputcontext_p.h" #include "qfont.h" #include "qwidget.h" #include "qapplication.h" #include "qlibrary.h" #include "qevent.h" #include "qtextformat.h" //#define Q_IME_DEBUG /* Active Input method support on Win95/98/NT */ #include <objbase.h> #include <initguid.h> #ifdef Q_IME_DEBUG #include "qdebug.h" #endif QT_BEGIN_NAMESPACE DEFINE_GUID(IID_IActiveIMMApp, 0x08c0e040, 0x62d1, 0x11d1, 0x93, 0x26, 0x0, 0x60, 0xb0, 0x67, 0xb8, 0x6e); DEFINE_GUID(CLSID_CActiveIMM, 0x4955DD33, 0xB159, 0x11d0, 0x8F, 0xCF, 0x0, 0xAA, 0x00, 0x6B, 0xCC, 0x59); DEFINE_GUID(IID_IActiveIMMMessagePumpOwner, 0xb5cf2cfa, 0x8aeb, 0x11d1, 0x93, 0x64, 0x0, 0x60, 0xb0, 0x67, 0xb8, 0x6e); interface IEnumRegisterWordW; interface IEnumInputContext; #define IFMETHOD HRESULT STDMETHODCALLTYPE interface IActiveIMMApp : public IUnknown { public: virtual IFMETHOD AssociateContext(HWND hWnd, HIMC hIME, HIMC __RPC_FAR *phPrev) = 0; virtual IFMETHOD dummy_ConfigureIMEA() = 0; virtual IFMETHOD ConfigureIMEW(HKL hKL, HWND hWnd, DWORD dwMode, REGISTERWORDW __RPC_FAR *pData) = 0; virtual IFMETHOD CreateContext(HIMC __RPC_FAR *phIMC) = 0; virtual IFMETHOD DestroyContext(HIMC hIME) = 0; virtual IFMETHOD dummy_EnumRegisterWordA() = 0; virtual IFMETHOD EnumRegisterWordW(HKL hKL, LPWSTR szReading, DWORD dwStyle, LPWSTR szRegister, LPVOID pData, IEnumRegisterWordW __RPC_FAR *__RPC_FAR *pEnum) = 0; virtual IFMETHOD dummy_EscapeA() = 0; virtual IFMETHOD EscapeW(HKL hKL, HIMC hIMC, UINT uEscape, LPVOID pData, LRESULT __RPC_FAR *plResult) = 0; virtual IFMETHOD dummy_GetCandidateListA() = 0; virtual IFMETHOD GetCandidateListW(HIMC hIMC, DWORD dwIndex, UINT uBufLen, CANDIDATELIST __RPC_FAR *pCandList, UINT __RPC_FAR *puCopied) = 0; virtual IFMETHOD dummy_GetCandidateListCountA() = 0; virtual IFMETHOD GetCandidateListCountW(HIMC hIMC, DWORD __RPC_FAR *pdwListSize, DWORD __RPC_FAR *pdwBufLen) = 0; virtual IFMETHOD GetCandidateWindow(HIMC hIMC, DWORD dwIndex, CANDIDATEFORM __RPC_FAR *pCandidate) = 0; virtual IFMETHOD dummy_GetCompositionFontA() = 0; virtual IFMETHOD GetCompositionFontW(HIMC hIMC, LOGFONTW __RPC_FAR *plf) = 0; virtual IFMETHOD dummy_GetCompositionStringA() = 0; virtual IFMETHOD GetCompositionStringW(HIMC hIMC, DWORD dwIndex, DWORD dwBufLen, LONG __RPC_FAR *plCopied, LPVOID pBuf) = 0; virtual IFMETHOD GetCompositionWindow(HIMC hIMC, COMPOSITIONFORM __RPC_FAR *pCompForm) = 0; virtual IFMETHOD GetContext(HWND hWnd, HIMC __RPC_FAR *phIMC) = 0; virtual IFMETHOD dummy_GetConversionListA() = 0; virtual IFMETHOD GetConversionListW(HKL hKL, HIMC hIMC, LPWSTR pSrc, UINT uBufLen, UINT uFlag, CANDIDATELIST __RPC_FAR *pDst, UINT __RPC_FAR *puCopied) = 0; virtual IFMETHOD GetConversionStatus(HIMC hIMC, DWORD __RPC_FAR *pfdwConversion, DWORD __RPC_FAR *pfdwSentence) = 0; virtual IFMETHOD GetDefaultIMEWnd(HWND hWnd, HWND __RPC_FAR *phDefWnd) = 0; virtual IFMETHOD dummy_GetDescriptionA() = 0; virtual IFMETHOD GetDescriptionW(HKL hKL, UINT uBufLen, LPWSTR szDescription, UINT __RPC_FAR *puCopied) = 0; virtual IFMETHOD dummy_GetGuideLineA() = 0; virtual IFMETHOD GetGuideLineW(HIMC hIMC, DWORD dwIndex, DWORD dwBufLen, LPWSTR pBuf, DWORD __RPC_FAR *pdwResult) = 0; virtual IFMETHOD dummy_GetIMEFileNameA() = 0; virtual IFMETHOD GetIMEFileNameW(HKL hKL, UINT uBufLen, LPWSTR szFileName, UINT __RPC_FAR *puCopied) = 0; virtual IFMETHOD GetOpenStatus(HIMC hIMC) = 0; virtual IFMETHOD GetProperty(HKL hKL, DWORD fdwIndex, DWORD __RPC_FAR *pdwProperty) = 0; virtual IFMETHOD dummy_GetRegisterWordStyleA() = 0; virtual IFMETHOD GetRegisterWordStyleW(HKL hKL, UINT nItem, STYLEBUFW __RPC_FAR *pStyleBuf, UINT __RPC_FAR *puCopied) = 0; virtual IFMETHOD GetStatusWindowPos(HIMC hIMC, POINT __RPC_FAR *pptPos) = 0; virtual IFMETHOD GetVirtualKey(HWND hWnd, UINT __RPC_FAR *puVirtualKey) = 0; virtual IFMETHOD dummy_InstallIMEA() = 0; virtual IFMETHOD InstallIMEW(LPWSTR szIMEFileName, LPWSTR szLayoutText, HKL __RPC_FAR *phKL) = 0; virtual IFMETHOD IsIME(HKL hKL) = 0; virtual IFMETHOD dummy_IsUIMessageA() = 0; virtual IFMETHOD IsUIMessageW(HWND hWndIME, UINT msg, WPARAM wParam, LPARAM lParam) = 0; virtual IFMETHOD NotifyIME(HIMC hIMC, DWORD dwAction, DWORD dwIndex, DWORD dwValue) = 0; virtual IFMETHOD dummy_RegisterWordA() = 0; virtual IFMETHOD RegisterWordW(HKL hKL, LPWSTR szReading, DWORD dwStyle, LPWSTR szRegister) = 0; virtual IFMETHOD ReleaseContext(HWND hWnd, HIMC hIMC) = 0; virtual IFMETHOD SetCandidateWindow(HIMC hIMC, CANDIDATEFORM __RPC_FAR *pCandidate) = 0; virtual IFMETHOD SetCompositionFontA(HIMC hIMC, LOGFONTA __RPC_FAR *plf) = 0; virtual IFMETHOD SetCompositionFontW(HIMC hIMC, LOGFONTW __RPC_FAR *plf) = 0; virtual IFMETHOD dummy_SetCompositionStringA() = 0; virtual IFMETHOD SetCompositionStringW(HIMC hIMC, DWORD dwIndex, LPVOID pComp, DWORD dwCompLen, LPVOID pRead, DWORD dwReadLen) = 0; virtual IFMETHOD SetCompositionWindow(HIMC hIMC, COMPOSITIONFORM __RPC_FAR *pCompForm) = 0; virtual IFMETHOD SetConversionStatus(HIMC hIMC, DWORD fdwConversion, DWORD fdwSentence) = 0; virtual IFMETHOD SetOpenStatus(HIMC hIMC, BOOL fOpen) = 0; virtual IFMETHOD SetStatusWindowPos(HIMC hIMC, POINT __RPC_FAR *pptPos) = 0; virtual IFMETHOD SimulateHotKey(HWND hWnd, DWORD dwHotKeyID) = 0; virtual IFMETHOD dummy_UnregisterWordA() = 0; virtual IFMETHOD UnregisterWordW(HKL hKL, LPWSTR szReading, DWORD dwStyle, LPWSTR szUnregister) = 0; virtual IFMETHOD Activate(BOOL fRestoreLayout) = 0; virtual IFMETHOD Deactivate(void) = 0; virtual IFMETHOD OnDefWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam, LRESULT __RPC_FAR *plResult) = 0; virtual IFMETHOD FilterClientWindows(ATOM __RPC_FAR *aaClassList, UINT uSize) = 0; virtual IFMETHOD dummy_GetCodePageA() = 0; virtual IFMETHOD GetLangId(HKL hKL, LANGID __RPC_FAR *plid) = 0; virtual IFMETHOD AssociateContextEx(HWND hWnd, HIMC hIMC, DWORD dwFlags) = 0; virtual IFMETHOD DisableIME(DWORD idThread) = 0; virtual IFMETHOD dummy_GetImeMenuItemsA() = 0; virtual IFMETHOD GetImeMenuItemsW(HIMC hIMC, DWORD dwFlags, DWORD dwType, /*IMEMENUITEMINFOW*/ void __RPC_FAR *pImeParentMenu, /*IMEMENUITEMINFOW*/ void __RPC_FAR *pImeMenu, DWORD dwSize, DWORD __RPC_FAR *pdwResult) = 0; virtual IFMETHOD EnumInputContext(DWORD idThread, IEnumInputContext __RPC_FAR *__RPC_FAR *ppEnum) = 0; }; interface IActiveIMMMessagePumpOwner : public IUnknown { public: virtual IFMETHOD Start(void) = 0; virtual IFMETHOD End(void) = 0; virtual IFMETHOD OnTranslateMessage(const MSG __RPC_FAR *pMsg) = 0; virtual IFMETHOD Pause(DWORD __RPC_FAR *pdwCookie) = 0; virtual IFMETHOD Resume(DWORD dwCookie) = 0; }; static IActiveIMMApp *aimm = 0; static IActiveIMMMessagePumpOwner *aimmpump = 0; static QString *imeComposition = 0; static int imePosition = -1; bool qt_use_rtl_extensions = false; static bool haveCaret = false; #ifndef LGRPID_INSTALLED #define LGRPID_INSTALLED 0x00000001 // installed language group ids #define LGRPID_SUPPORTED 0x00000002 // supported language group ids #endif #ifndef LGRPID_ARABIC #define LGRPID_WESTERN_EUROPE 0x0001 // Western Europe & U.S. #define LGRPID_CENTRAL_EUROPE 0x0002 // Central Europe #define LGRPID_BALTIC 0x0003 // Baltic #define LGRPID_GREEK 0x0004 // Greek #define LGRPID_CYRILLIC 0x0005 // Cyrillic #define LGRPID_TURKISH 0x0006 // Turkish #define LGRPID_JAPANESE 0x0007 // Japanese #define LGRPID_KOREAN 0x0008 // Korean #define LGRPID_TRADITIONAL_CHINESE 0x0009 // Traditional Chinese #define LGRPID_SIMPLIFIED_CHINESE 0x000a // Simplified Chinese #define LGRPID_THAI 0x000b // Thai #define LGRPID_HEBREW 0x000c // Hebrew #define LGRPID_ARABIC 0x000d // Arabic #define LGRPID_VIETNAMESE 0x000e // Vietnamese #define LGRPID_INDIC 0x000f // Indic #define LGRPID_GEORGIAN 0x0010 // Georgian #define LGRPID_ARMENIAN 0x0011 // Armenian #endif static DWORD WM_MSIME_MOUSE = 0; QWinInputContext::QWinInputContext(QObject *parent) : QInputContext(parent), recursionGuard(false) { if (QSysInfo::WindowsVersion < QSysInfo::WV_2000) { // try to get the Active IMM COM object on Win95/98/NT, where english versions don't // support the regular Windows input methods. if (CoCreateInstance(CLSID_CActiveIMM, NULL, CLSCTX_INPROC_SERVER, IID_IActiveIMMApp, (LPVOID *)&aimm) != S_OK) { aimm = 0; } if (aimm && (aimm->QueryInterface(IID_IActiveIMMMessagePumpOwner, (LPVOID *)&aimmpump) != S_OK || aimm->Activate(true) != S_OK)) { aimm->Release(); aimm = 0; if (aimmpump) aimmpump->Release(); aimmpump = 0; } if (aimmpump) aimmpump->Start(); } #ifndef Q_OS_WINCE QSysInfo::WinVersion ver = QSysInfo::windowsVersion(); if (ver & QSysInfo::WV_NT_based && ver >= QSysInfo::WV_VISTA) { // Since the IsValidLanguageGroup/IsValidLocale functions always return true on // Vista, check the Keyboard Layouts for enabling RTL. UINT nLayouts = GetKeyboardLayoutList(0, 0); if (nLayouts) { HKL *lpList = new HKL[nLayouts]; GetKeyboardLayoutList(nLayouts, lpList); for (int i = 0; i<(int)nLayouts; i++) { WORD plangid = PRIMARYLANGID((quintptr)lpList[i]); if (plangid == LANG_ARABIC || plangid == LANG_HEBREW || plangid == LANG_FARSI #ifdef LANG_SYRIAC || plangid == LANG_SYRIAC #endif ) { qt_use_rtl_extensions = true; break; } } delete []lpList; } } else { // figure out whether a RTL language is installed typedef BOOL(WINAPI *PtrIsValidLanguageGroup)(DWORD,DWORD); PtrIsValidLanguageGroup isValidLanguageGroup = (PtrIsValidLanguageGroup)QLibrary::resolve(QLatin1String("kernel32"), "IsValidLanguageGroup"); if (isValidLanguageGroup) { qt_use_rtl_extensions = isValidLanguageGroup(LGRPID_ARABIC, LGRPID_INSTALLED) || isValidLanguageGroup(LGRPID_HEBREW, LGRPID_INSTALLED); } qt_use_rtl_extensions |= IsValidLocale(MAKELCID(MAKELANGID(LANG_ARABIC, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED) || IsValidLocale(MAKELCID(MAKELANGID(LANG_HEBREW, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED) #ifdef LANG_SYRIAC || IsValidLocale(MAKELCID(MAKELANGID(LANG_SYRIAC, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED) #endif || IsValidLocale(MAKELCID(MAKELANGID(LANG_FARSI, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED); } #else qt_use_rtl_extensions = false; #endif WM_MSIME_MOUSE = QT_WA_INLINE(RegisterWindowMessage(L"MSIMEMouseOperation"), RegisterWindowMessageA("MSIMEMouseOperation")); } QWinInputContext::~QWinInputContext() { // release active input method if we have one if (aimm) { aimmpump->End(); aimmpump->Release(); aimm->Deactivate(); aimm->Release(); aimm = 0; aimmpump = 0; } delete imeComposition; imeComposition = 0; } static HWND getDefaultIMEWnd(HWND wnd) { HWND ime_wnd; if(aimm) aimm->GetDefaultIMEWnd(wnd, &ime_wnd); else ime_wnd = ImmGetDefaultIMEWnd(wnd); return ime_wnd; } static HIMC getContext(HWND wnd) { HIMC imc; if (aimm) aimm->GetContext(wnd, &imc); else imc = ImmGetContext(wnd); return imc; } static void releaseContext(HWND wnd, HIMC imc) { if (aimm) aimm->ReleaseContext(wnd, imc); else ImmReleaseContext(wnd, imc); } static void notifyIME(HIMC imc, DWORD dwAction, DWORD dwIndex, DWORD dwValue) { if (!imc) return; if (aimm) aimm->NotifyIME(imc, dwAction, dwIndex, dwValue); else ImmNotifyIME(imc, dwAction, dwIndex, dwValue); } static LONG getCompositionString(HIMC himc, DWORD dwIndex, LPVOID lpbuf, DWORD dBufLen, bool *unicode = 0) { LONG len = 0; if (unicode) *unicode = true; if (aimm) aimm->GetCompositionStringW(himc, dwIndex, dBufLen, &len, lpbuf); else { if(QSysInfo::WindowsVersion != QSysInfo::WV_95) { len = ImmGetCompositionStringW(himc, dwIndex, lpbuf, dBufLen); } #if !defined(Q_OS_WINCE) else { len = ImmGetCompositionStringA(himc, dwIndex, lpbuf, dBufLen); if (unicode) *unicode = false; } #endif } return len; } static int getCursorPosition(HIMC himc) { return getCompositionString(himc, GCS_CURSORPOS, 0, 0); } static QString getString(HIMC himc, DWORD dwindex, int *selStart = 0, int *selLength = 0) { static char *buffer = 0; static int buflen = 0; int len = getCompositionString(himc, dwindex, 0, 0) + 1; if (!buffer || len > buflen) { delete [] buffer; buflen = qMin(len, 256); buffer = new char[buflen]; } bool unicode = true; len = getCompositionString(himc, dwindex, buffer, buflen, &unicode); if (selStart) { static char *attrbuffer = 0; static int attrbuflen = 0; int attrlen = getCompositionString(himc, dwindex, 0, 0) + 1; if (!attrbuffer || attrlen> attrbuflen) { delete [] attrbuffer; attrbuflen = qMin(attrlen, 256); attrbuffer = new char[attrbuflen]; } attrlen = getCompositionString(himc, GCS_COMPATTR, attrbuffer, attrbuflen); *selStart = attrlen+1; *selLength = -1; for (int i = 0; i < attrlen; i++) { if (attrbuffer[i] & ATTR_TARGET_CONVERTED) { *selStart = qMin(*selStart, i); *selLength = qMax(*selLength, i); } } *selLength = qMax(0, *selLength - *selStart + 1); } if (len <= 0) return QString(); if (unicode) { return QString((QChar *)buffer, len/sizeof(QChar)); } else { buffer[len] = 0; WCHAR *wc = new WCHAR[len+1]; int l = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, buffer, len, wc, len+1); QString res = QString((QChar *)wc, l); delete [] wc; return res; } } void QWinInputContext::TranslateMessage(const MSG *msg) { if (!aimmpump || aimmpump->OnTranslateMessage(msg) != S_OK) ::TranslateMessage(msg); } LRESULT QWinInputContext::DefWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { LRESULT retval; if (!aimm || aimm->OnDefWindowProc(hwnd, msg, wParam, lParam, &retval) != S_OK) { QT_WA({ retval = ::DefWindowProc(hwnd, msg, wParam, lParam); } , { retval = ::DefWindowProcA(hwnd,msg, wParam, lParam); }); } return retval; } void QWinInputContext::update() { QWidget *w = focusWidget(); if(!w) return; Q_ASSERT(w->testAttribute(Qt::WA_WState_Created)); HIMC imc = getContext(w->effectiveWinId()); if (!imc) return; QFont f = qvariant_cast<QFont>(w->inputMethodQuery(Qt::ImFont)); HFONT hf; hf = f.handle(); QT_WA({ LOGFONT lf; if (GetObject(hf, sizeof(lf), &lf)) if (aimm) aimm->SetCompositionFontW(imc, &lf); else ImmSetCompositionFont(imc, &lf); } , { LOGFONTA lf; if (GetObjectA(hf, sizeof(lf), &lf)) if (aimm) aimm->SetCompositionFontA(imc, &lf); else ImmSetCompositionFontA(imc, &lf); }); QRect r = w->inputMethodQuery(Qt::ImMicroFocus).toRect(); // The ime window positions are based on the WinId with active focus. QWidget *imeWnd = QWidget::find(::GetFocus()); if (imeWnd && !aimm) { QPoint pt (r.topLeft()); pt = w->mapToGlobal(pt); pt = imeWnd->mapFromGlobal(pt); r.moveTo(pt); } COMPOSITIONFORM cf; // ### need X-like inputStyle config settings cf.dwStyle = CFS_FORCE_POSITION; cf.ptCurrentPos.x = r.x(); cf.ptCurrentPos.y = r.y(); CANDIDATEFORM candf; candf.dwIndex = 0; candf.dwStyle = CFS_EXCLUDE; candf.ptCurrentPos.x = r.x(); candf.ptCurrentPos.y = r.y() + r.height(); candf.rcArea.left = r.x(); candf.rcArea.top = r.y(); candf.rcArea.right = r.x() + r.width(); candf.rcArea.bottom = r.y() + r.height(); if(haveCaret) SetCaretPos(r.x(), r.y()); if (aimm) { aimm->SetCompositionWindow(imc, &cf); aimm->SetCandidateWindow(imc, &candf); } else { ImmSetCompositionWindow(imc, &cf); ImmSetCandidateWindow(imc, &candf); } releaseContext(w->effectiveWinId(), imc); } bool QWinInputContext::endComposition() { QWidget *fw = focusWidget(); #ifdef Q_IME_DEBUG qDebug("endComposition! fw = %s", fw ? fw->className() : "(null)"); #endif bool result = true; if(imePosition == -1 || recursionGuard) return result; // Googles Pinyin Input Method likes to call endComposition again // when we call notifyIME with CPS_CANCEL, so protect ourselves // against that. recursionGuard = true; if (fw) { Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created)); HIMC imc = getContext(fw->effectiveWinId()); notifyIME(imc, NI_COMPOSITIONSTR, CPS_CANCEL, 0); releaseContext(fw->effectiveWinId(), imc); if(haveCaret) { DestroyCaret(); haveCaret = false; } } if (!fw) fw = qApp->focusWidget(); if (fw) { QInputMethodEvent e; result = qt_sendSpontaneousEvent(fw, &e); } if (imeComposition) imeComposition->clear(); imePosition = -1; recursionGuard = false; return result; } void QWinInputContext::reset() { QWidget *fw = focusWidget(); #ifdef Q_IME_DEBUG qDebug("sending accept to focus widget %s", fw ? fw->className() : "(null)"); #endif if (fw && imePosition != -1) { QInputMethodEvent e; if (imeComposition) e.setCommitString(*imeComposition); qt_sendSpontaneousEvent(fw, &e); } if (imeComposition) imeComposition->clear(); imePosition = -1; if (fw) { Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created)); HIMC imc = getContext(fw->effectiveWinId()); notifyIME(imc, NI_COMPOSITIONSTR, CPS_CANCEL, 0); releaseContext(fw->effectiveWinId(), imc); } } bool QWinInputContext::startComposition() { #ifdef Q_IME_DEBUG qDebug("startComposition"); #endif if (!imeComposition) imeComposition = new QString(); QWidget *fw = focusWidget(); if (fw) { Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created)); imePosition = 0; haveCaret = CreateCaret(fw->effectiveWinId(), 0, 1, 1); HideCaret(fw->effectiveWinId()); update(); } return fw != 0; } enum StandardFormat { PreeditFormat, SelectionFormat }; bool QWinInputContext::composition(LPARAM lParam) { #ifdef Q_IME_DEBUG QString str; if (lParam & GCS_RESULTSTR) str += "RESULTSTR "; if (lParam & GCS_COMPSTR) str += "COMPSTR "; if (lParam & GCS_COMPATTR) str += "COMPATTR "; if (lParam & GCS_CURSORPOS) str += "CURSORPOS "; if (lParam & GCS_COMPCLAUSE) str += "COMPCLAUSE "; if (lParam & CS_INSERTCHAR) str += "INSERTCHAR "; if (lParam & CS_NOMOVECARET) str += "NOMOVECARET "; qDebug("composition, lParam=(%x) %s imePosition=%d", lParam, str.latin1(), imePosition); #endif bool result = true; if(!lParam) // bogus event return true; QWidget *fw = qApp->focusWidget(); if (fw) { Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created)); HIMC imc = getContext(fw->effectiveWinId()); QInputMethodEvent e; if (lParam & (GCS_COMPSTR | GCS_COMPATTR | GCS_CURSORPOS)) { if (imePosition == -1) // need to send a start event startComposition(); // some intermediate composition result int selStart, selLength; *imeComposition = getString(imc, GCS_COMPSTR, &selStart, &selLength); imePosition = getCursorPosition(imc); if (lParam & CS_INSERTCHAR && lParam & CS_NOMOVECARET) { // make korean work correctly. Hope this is correct for all IMEs selStart = 0; selLength = imeComposition->length(); } if(selLength == 0) selStart = 0; QList<QInputMethodEvent::Attribute> attrs; if (selStart > 0) attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, 0, selStart, standardFormat(PreeditFormat)); if (selLength) attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, selStart, selLength, standardFormat(SelectionFormat)); if (selStart + selLength < imeComposition->length()) attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, selStart + selLength, imeComposition->length() - selStart - selLength, standardFormat(PreeditFormat)); if(imePosition >= 0) attrs << QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, imePosition, selLength ? 0 : 1, QVariant()); e = QInputMethodEvent(*imeComposition, attrs); } if (lParam & GCS_RESULTSTR) { if(imePosition == -1) startComposition(); // a fixed result, return the converted string *imeComposition = getString(imc, GCS_RESULTSTR); imePosition = -1; e.setCommitString(*imeComposition); imeComposition->clear(); } result = qt_sendSpontaneousEvent(fw, &e); update(); releaseContext(fw->effectiveWinId(), imc); } #ifdef Q_IME_DEBUG qDebug("imecomposition: cursor pos at %d, str=%x", imePosition, str[0].unicode()); #endif return result; } static HIMC defaultContext = 0; // checks whether widget is a popup inline bool isPopup(QWidget *w) { if (w && (w->windowFlags() & Qt::Popup) == Qt::Popup) return true; else return false; } // checks whether widget is in a popup inline bool isInPopup(QWidget *w) { if (w && (isPopup(w) || isPopup(w->window()))) return true; else return false; } // find the parent widget, which is a non popup toplevel // this is valid only if the widget is/in a popup inline QWidget *findParentforPopup(QWidget *w) { QWidget *e = QWidget::find(w->effectiveWinId()); // check if this or its parent is a popup while (isInPopup(e)) { e = e->window()->parentWidget(); if (!e) break; e = QWidget::find(e->effectiveWinId()); } if (e) return e->window(); else return 0; } // enables or disables the ime inline void enableIme(QWidget *w, bool value) { if (value) { // enable ime if (defaultContext) ImmAssociateContext(w->effectiveWinId(), defaultContext); } else { // disable ime HIMC oldimc = ImmAssociateContext(w->effectiveWinId(), 0); if (!defaultContext) defaultContext = oldimc; } } void QInputContextPrivate::updateImeStatus(QWidget *w, bool hasFocus) { if (!w) return; bool e = w->testAttribute(Qt::WA_InputMethodEnabled) && w->isEnabled(); bool hasIme = e && hasFocus; #ifdef Q_IME_DEBUG qDebug("%s HasFocus = %d hasIme = %d e = %d ", w->className(), hasFocus, hasIme, e); #endif if (hasFocus || e) { if (isInPopup(w)) QWinInputContext::enablePopupChild(w, hasIme); else QWinInputContext::enable(w, hasIme); } } void QWinInputContext::enablePopupChild(QWidget *w, bool e) { if (aimm) { enable(w, e); return; } if (!w || !isInPopup(w)) return; #ifdef Q_IME_DEBUG qDebug("enablePopupChild: w=%s, enable = %s", w ? w->className() : "(null)" , e ? "true" : "false"); #endif QWidget *parent = findParentforPopup(w); if (parent) { // update ime status of the normal toplevel parent of the popup enableIme(parent, e); } QWidget *toplevel = w->window(); if (toplevel) { // update ime status of the toplevel popup enableIme(toplevel, e); } } void QWinInputContext::enable(QWidget *w, bool e) { if(w) { #ifdef Q_IME_DEBUG qDebug("enable: w=%s, enable = %s", w ? w->className() : "(null)" , e ? "true" : "false"); #endif if (!w->testAttribute(Qt::WA_WState_Created)) return; if(aimm) { HIMC oldimc; if (!e) { aimm->AssociateContext(w->effectiveWinId(), 0, &oldimc); if (!defaultContext) defaultContext = oldimc; } else if (defaultContext) { aimm->AssociateContext(w->effectiveWinId(), defaultContext, &oldimc); } } else { // update ime status on the widget QWidget *p = QWidget::find(w->effectiveWinId()); if (p) enableIme(p, e); } } } void QWinInputContext::setFocusWidget(QWidget *w) { QInputContext::setFocusWidget(w); update(); } bool QWinInputContext::isComposing() const { return imeComposition && !imeComposition->isEmpty(); } void QWinInputContext::mouseHandler(int pos, QMouseEvent *e) { if(e->type() != QEvent::MouseButtonPress) return; if (pos < 0 || pos > imeComposition->length()) reset(); // Probably should pass the correct button, but it seems to work fine like this. DWORD button = MK_LBUTTON; QWidget *fw = focusWidget(); if (fw) { Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created)); HIMC himc = getContext(fw->effectiveWinId()); HWND ime_wnd = getDefaultIMEWnd(fw->effectiveWinId()); SendMessage(ime_wnd, WM_MSIME_MOUSE, MAKELONG(MAKEWORD(button, pos == 0 ? 2 : 1), pos), (LPARAM)himc); releaseContext(fw->effectiveWinId(), himc); } //qDebug("mouseHandler: got value %d pos=%d", ret,pos); } QString QWinInputContext::language() { return QString(); } QT_END_NAMESPACE
FilipBE/qtextended
qtopiacore/qt/src/gui/inputmethod/qwininputcontext_win.cpp
C++
gpl-2.0
28,969